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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
[Pages] Add permissions architects, audit skill, test-site skill, and Dataverse script refactors (#40)
Priyanshu Agrawal31651c473b38
diff --git a/.gitignore b/.gitignoreindex 6768d62fd..a548ac875 100644--- a/.gitignore+++ b/.gitignore@@ -4,6 +4,7 @@ evals/temp/# Eval reports (aggregated results)evals/reports/+evals/**/*-workspace/# Python__pycache__/@@ -44,3 +45,5 @@ ENV/# OS.DS_StoreThumbs.db++.playwright-mcp/diff --git a/evals/README.md b/evals/README.mddeleted file mode 100644index 1da473bd9..000000000--- a/evals/README.md+++ /dev/null@@ -1,183 +0,0 @@-# 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.pydeleted file mode 100644index ce03a49fe..000000000--- a/evals/grade_eval.py+++ /dev/null@@ -1,107 +0,0 @@-#!/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/activate-site/evals.json b/evals/power-pages/activate-site/evals.jsonnew file mode 100644index 000000000..673507ab1--- /dev/null+++ b/evals/power-pages/activate-site/evals.json@@ -0,0 +1,77 @@+{+ "skill_name": "activate-site",+ "evals": [+ {+ "id": 1,+ "prompt": "I just created my Power Pages code site and now I need to activate it so I can actually see it in the browser. Can you provision it for me?",+ "expected_output": "The skill verifies PAC CLI auth and Azure CLI login, checks that the site is not already activated via check-activation-status.js, reads the site name from powerpages.config.json, runs generate-subdomain.js to produce a random subdomain suggestion, asks the user whether to use the generated subdomain or enter a custom one, presents the full activation parameters (site name, subdomain, environment ID) for user approval, runs activate-site.js to POST to the websites API and poll for completion, and presents a summary with the provisioned site URL and next steps.",+ "files": [],+ "expectations": [+ "PAC CLI is verified via 'pac help'",+ "Authentication is checked via 'pac auth who' and Environment ID, Organization ID, and Cloud are extracted",+ "Azure CLI login is verified via 'az account show'",+ "Activation status is checked by running check-activation-status.js before gathering parameters",+ "Site name is read from powerpages.config.json",+ "generate-subdomain.js script is run to produce a subdomain suggestion",+ "User is asked via AskUserQuestion whether to use the generated subdomain or enter a custom one",+ "User is presented with full activation parameters and asked to confirm before proceeding",+ "activate-site.js is run with --siteName, --subdomain, --organizationId, --environmentId, --cloud, and --websiteRecordId",+ "Bash timeout for the activation script is at least 360 seconds",+ "A summary is presented showing site name, site URL, environment, and status",+ "Skill usage is recorded with --skillName 'ActivateSite'",+ "Next steps are suggested including test-site, setup-datamodel, and add-sample-data",+ "Progress is tracked using TaskCreate/TaskUpdate for each phase"+ ]+ },+ {+ "id": 2,+ "prompt": "activate my power pages site please. i want to use my own subdomain though -- 'contoso-hr-portal' instead of whatever random one you come up with",+ "expected_output": "The skill completes all prerequisite checks, reads the site name from config, runs the subdomain generator but the user declines the suggestion and provides 'contoso-hr-portal' as their custom subdomain. The custom subdomain is validated (lowercase, alphanumeric with hyphens, 3-50 chars). The user confirms activation parameters with the custom subdomain, the activation script runs, and a summary is presented with the site URL using the custom subdomain.",+ "files": [],+ "expectations": [+ "PAC CLI auth and Azure CLI login are verified",+ "Activation status is checked before gathering parameters",+ "Site name is read from powerpages.config.json",+ "generate-subdomain.js is still run to produce a suggestion",+ "User is asked via AskUserQuestion and selects the custom subdomain option",+ "Custom subdomain 'contoso-hr-portal' is validated (lowercase, alphanumeric with hyphens, 3-50 characters)",+ "Confirmation prompt shows the custom subdomain in the full URL (e.g., contoso-hr-portal.powerappsportals.com)",+ "activate-site.js is called with --subdomain 'contoso-hr-portal'",+ "Summary shows the site URL using the custom subdomain",+ "Progress is tracked using TaskCreate/TaskUpdate for each phase"+ ]+ },+ {+ "id": 3,+ "prompt": "hey can you provision my power pages website? i think it might already be set up but i'm not sure",+ "expected_output": "The skill verifies PAC CLI auth and Azure CLI login, then runs check-activation-status.js which returns activated: true. The skill informs the user that the site is already activated, shows the existing site URL, suggests next steps, and stops early without proceeding to parameter gathering or activation.",+ "files": [],+ "expectations": [+ "PAC CLI auth is verified via 'pac auth who'",+ "Azure CLI login is verified via 'az account show'",+ "check-activation-status.js is run to check current activation status",+ "When the script returns activated: true, the skill stops early",+ "User is informed the site is already activated with the existing site URL",+ "The skill does NOT proceed to Phase 2 (subdomain generation or parameter gathering)",+ "The skill does NOT run activate-site.js",+ "Next steps are still suggested (test-site, setup-datamodel, add-sample-data)",+ "Progress is tracked using TaskCreate/TaskUpdate"+ ]+ },+ {+ "id": 4,+ "prompt": "turn on my power pages site so i can start building on it",+ "expected_output": "The skill attempts to verify PAC CLI authentication via 'pac auth who' and discovers the user is not authenticated. It prompts the user to authenticate by providing their environment URL and runs 'pac auth create'. It does not proceed with activation until authentication is established.",+ "files": [],+ "expectations": [+ "PAC CLI is verified via 'pac help'",+ "'pac auth who' is run and the unauthenticated status is detected",+ "User is informed they need to authenticate with PAC CLI",+ "User is asked for their environment URL to run 'pac auth create --environment'",+ "The skill does NOT proceed to activation without valid PAC CLI authentication",+ "If Azure CLI is also not logged in, the user is instructed to run 'az login'",+ "The skill blocks on authentication and does not skip to parameter gathering or activation"+ ]+ }+ ]+}diff --git a/evals/power-pages/add-sample-data/evals.json b/evals/power-pages/add-sample-data/evals.jsonnew file mode 100644index 000000000..9e56b7d7f--- /dev/null+++ b/evals/power-pages/add-sample-data/evals.json@@ -0,0 +1,78 @@+{+ "skill_name": "add-sample-data",+ "evals": [+ {+ "id": 1,+ "prompt": "I just set up my datamodel with a few tables -- Projects, Tasks, and Team Members. Tasks have a lookup to Projects and Team Members. Can you add some sample data so I can test my site? Maybe like 10 records per table would be good.",+ "expected_output": "The skill discovers the 3 tables (Projects, Tasks, Team Members) from .datamodel-manifest.json or OData API, determines the correct insertion order (Projects and Team Members first, then Tasks), asks the user to confirm table selection and record count, generates contextually appropriate sample data with realistic names/descriptions, inserts records via OData API respecting lookup relationships, and presents a verification summary with record counts per table.",+ "files": [],+ "expectations": [+ "Prerequisites are verified (PAC CLI auth, Azure CLI token, API access)",+ "Tables are discovered from .datamodel-manifest.json or OData API",+ "User is asked to confirm which tables to populate",+ "User is asked to select record count (with 10 as the chosen option)",+ "Insertion order respects parent-child relationships (Projects and Team Members before Tasks)",+ "Sample data uses contextually appropriate values (realistic project names, task descriptions, team member names)",+ "Lookup columns in Tasks use @odata.bind syntax referencing parent record IDs",+ "OData POST calls are made to insert records",+ "A verification summary with record counts per table is presented",+ "Token is refreshed if more than 20 records are being inserted"+ ]+ },+ {+ "id": 2,+ "prompt": "add sample data to my power pages site. i have tables for Courses, Students, and Enrollments. just 5 records each is fine, i just want to see if my lists and forms work",+ "expected_output": "The skill discovers Courses, Students, and Enrollments tables, determines Courses and Students must be inserted before Enrollments (which references both), generates 5 records per table with realistic course names, student names, and enrollment dates, inserts them via OData API, and shows a summary.",+ "files": [],+ "expectations": [+ "Prerequisites are verified before any data operations",+ "All 3 tables (Courses, Students, Enrollments) are discovered",+ "Insertion order: Courses and Students first, then Enrollments",+ "Picklist/choice columns are queried for valid option values before generating data",+ "Sample courses have realistic names (not generic 'Course 1', 'Course 2')",+ "Sample students have realistic names",+ "Enrollments reference actual inserted Course and Student record IDs via @odata.bind",+ "Exactly 5 records per table are requested for insertion",+ "A markdown preview of sample data is shown before insertion",+ "Final summary includes record counts and any failures"+ ]+ },+ {+ "id": 3,+ "prompt": "I need to populate my Dataverse tables with demo data for a presentation tomorrow. I have a Property Listings table, an Agents table, and a Showings table. Showings has lookups to both Properties and Agents. Can you add 25 records to each table? I want it to look realistic for the demo.",+ "expected_output": "The skill handles the larger dataset (25 records x 3 tables = 75 total), discovers the tables and relationships, generates highly realistic real estate data (property addresses, agent names, showing dates/times), inserts parent tables first, refreshes the token during insertion since >20 records, and provides a detailed verification summary.",+ "files": [],+ "expectations": [+ "Prerequisites are verified including API access confirmation",+ "All 3 tables are discovered with their columns and relationships",+ "User is presented with table list and confirms selection",+ "25 records per table is confirmed as the record count",+ "Insertion order: Property Listings and Agents first, then Showings",+ "Property data includes realistic addresses, prices, and descriptions",+ "Agent data includes realistic names, phone numbers, and email addresses",+ "Showings reference actual Property and Agent record IDs",+ "Azure CLI token is refreshed during insertion (75 records exceeds 20-record threshold)",+ "Progress is tracked using TaskCreate/TaskUpdate throughout all phases",+ "Verification queries confirm record counts match expected 25 per table",+ "Summary table shows Records Requested vs Records Created vs Failures for each table"+ ]+ },+ {+ "id": 4,+ "prompt": "seed some test data into my tables. I only have one table -- a simple FAQ table with question, answer, and category columns. throw in about 10 records",+ "expected_output": "The skill handles the simple single-table case with no relationships. Discovers the FAQ table, generates 10 realistic FAQ entries with varied categories, inserts them via OData, and verifies.",+ "files": [],+ "expectations": [+ "Prerequisites are verified",+ "FAQ table is discovered with its columns (question, answer, category)",+ "No insertion order complexity since there's only one table with no lookups",+ "If category is a picklist/choice column, valid option values are queried first",+ "Generated FAQs cover diverse topics relevant to the site context",+ "Questions and answers are realistic and substantive (not placeholder text)",+ "All 10 records are inserted via OData POST calls",+ "Verification confirms 10 records were created",+ "Summary is presented even for this simple single-table case"+ ]+ }+ ]+}diff --git a/evals/power-pages/add-sample-data/prompts.csv b/evals/power-pages/add-sample-data/prompts.csvdeleted file mode 100644index f398f5a03..000000000--- a/evals/power-pages/add-sample-data/prompts.csv+++ /dev/null@@ -1,11 +0,0 @@-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 questiondiff --git a/evals/power-pages/add-sample-data/rubric.json b/evals/power-pages/add-sample-data/rubric.jsondeleted file mode 100644index 7fdee3f94..000000000--- a/evals/power-pages/add-sample-data/rubric.json+++ /dev/null@@ -1,31 +0,0 @@-{- "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/evals.json b/evals/power-pages/add-seo/evals.jsonnew file mode 100644index 000000000..793d4f879--- /dev/null+++ b/evals/power-pages/add-seo/evals.json@@ -0,0 +1,78 @@+{+ "skill_name": "add-seo",+ "evals": [+ {+ "id": 1,+ "prompt": "I have a React-based Power Pages code site in c:\\repos\\ghe\\contoso-portal. I want the full SEO treatment: robots.txt, sitemap.xml, meta tags with Open Graph and Twitter Card tags, and a favicon. The site URL is https://contoso.powerappsportals.com and it has routes for /, /about, /contact, /products, and /products/:id. Use the favicon at public/favicon.ico that already exists.",+ "expected_output": "The skill detects a React framework, discovers all routes, generates robots.txt and sitemap.xml in the public directory, adds meta tags (title, description, viewport, OG, Twitter Card, favicon link) to index.html, confirms the plan with the user, verifies with Playwright, and commits to git.",+ "files": [],+ "expectations": [+ "Detects the project as a React-based Power Pages code site by examining package.json or project structure",+ "Discovers routes including /, /about, /contact, /products, and /products/:id",+ "Creates public/robots.txt with User-agent: *, Allow: /, and a Sitemap directive pointing to https://contoso.powerappsportals.com/sitemap.xml",+ "Creates public/sitemap.xml containing <url> entries for https://contoso.powerappsportals.com/, /about, /contact, and /products",+ "Adds <meta name=\"description\"> and <meta name=\"viewport\"> tags to public/index.html or the root HTML template",+ "Adds Open Graph meta tags (og:title, og:description, og:url, og:type) to the root HTML template",+ "Adds Twitter Card meta tags (twitter:card, twitter:title, twitter:description) to the root HTML template",+ "Adds a <link rel=\"icon\" href=\"/favicon.ico\"> reference in the HTML head",+ "Presents an SEO plan to the user and waits for approval before making changes",+ "Runs a Playwright-based verification to confirm SEO elements are present on the rendered site",+ "Creates a git commit with the SEO changes"+ ]+ },+ {+ "id": 2,+ "prompt": "Add SEO to my Astro Power Pages code site at c:\\repos\\ghe\\northwind-portal. The site URL is https://northwind.powerappsportals.com. It has pages at src/pages/index.astro, src/pages/services.astro, and src/pages/blog/[slug].astro. I want robots.txt, sitemap, meta tags with OG tags, and a favicon.",+ "expected_output": "The skill detects an Astro framework, places meta tags in the Layout.astro component rather than a standalone index.html, generates robots.txt and sitemap.xml in the public directory, and follows the standard verification and commit workflow.",+ "files": [],+ "expectations": [+ "Detects the project as an Astro-based Power Pages code site by examining astro.config.mjs or package.json",+ "Discovers routes /, /services, and /blog/[slug] from the src/pages directory structure",+ "Creates public/robots.txt with User-agent: *, Allow: /, and a Sitemap directive pointing to https://northwind.powerappsportals.com/sitemap.xml",+ "Creates public/sitemap.xml containing <url> entries for https://northwind.powerappsportals.com/, /services, and /blog",+ "Adds meta tags (description, viewport, OG tags, Twitter Card tags) inside the <head> of the Astro layout file (e.g., src/layouts/Layout.astro) rather than a plain index.html",+ "Adds a <link rel=\"icon\"> reference in the Astro layout head",+ "Presents an SEO plan to the user and waits for approval before making changes",+ "Runs a Playwright-based verification to confirm SEO elements render correctly",+ "Creates a git commit with the SEO changes"+ ]+ },+ {+ "id": 3,+ "prompt": "I need SEO for my React Power Pages code site at c:\\repos\\ghe\\fabrikam-portal. Site URL is https://fabrikam.powerappsportals.com. The site has routes /, /dashboard, /admin, /admin/settings, /auth/login, /auth/register, /pricing, and /docs. Exclude all /admin and /auth routes from the sitemap and block them in robots.txt. I want full SEO with OG tags and favicon.",+ "expected_output": "The skill generates robots.txt with Disallow rules for /admin and /auth paths, creates sitemap.xml that excludes those routes, adds all meta tags, and follows the approval, verification, and commit workflow.",+ "files": [],+ "expectations": [+ "Detects the project as a React-based Power Pages code site",+ "Discovers all routes including /, /dashboard, /admin, /admin/settings, /auth/login, /auth/register, /pricing, and /docs",+ "Creates robots.txt with Disallow: /admin and Disallow: /auth directives to block crawlers from those paths",+ "Creates sitemap.xml that includes /, /dashboard, /pricing, and /docs but excludes /admin, /admin/settings, /auth/login, and /auth/register",+ "Adds meta tags (title, description, viewport) to the root HTML template",+ "Adds Open Graph and Twitter Card meta tags to the root HTML template",+ "Adds a favicon link in the HTML head",+ "Presents the SEO plan showing excluded routes and waits for user approval",+ "Runs Playwright verification to confirm SEO elements and that excluded routes are properly handled",+ "Creates a git commit with the SEO changes"+ ]+ },+ {+ "id": 4,+ "prompt": "Add minimal SEO to my React Power Pages site at c:\\repos\\ghe\\litware-portal. Site URL is https://litware.powerappsportals.com. It only has / and /about pages. I just need a basic robots.txt and sitemap.xml. No Open Graph tags, no Twitter Card tags, no favicon. Keep it simple.",+ "expected_output": "The skill generates only robots.txt and sitemap.xml with the two routes, adds basic meta tags (title, description, viewport) without OG or Twitter Card tags, skips favicon setup, and follows the approval, verification, and commit workflow.",+ "files": [],+ "expectations": [+ "Detects the project as a React-based Power Pages code site",+ "Discovers routes / and /about",+ "Creates public/robots.txt with User-agent: * and Allow: / along with a Sitemap directive",+ "Creates public/sitemap.xml containing <url> entries for https://litware.powerappsportals.com/ and /about only",+ "Adds basic meta tags (title, description, viewport) to the root HTML template",+ "Does NOT add Open Graph meta tags (og:title, og:description, og:url, og:type)",+ "Does NOT add Twitter Card meta tags (twitter:card, twitter:title, twitter:description)",+ "Does NOT add a favicon link element",+ "Presents the minimal SEO plan to the user and waits for approval",+ "Runs Playwright verification to confirm the basic SEO elements are present",+ "Creates a git commit with the SEO changes"+ ]+ }+ ]+}diff --git a/evals/power-pages/add-seo/prompts.csv b/evals/power-pages/add-seo/prompts.csvdeleted file mode 100644index fd04909c8..000000000--- a/evals/power-pages/add-seo/prompts.csv+++ /dev/null@@ -1,11 +0,0 @@-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 questiondiff --git a/evals/power-pages/add-seo/rubric.json b/evals/power-pages/add-seo/rubric.jsondeleted file mode 100644index 8397fded1..000000000--- a/evals/power-pages/add-seo/rubric.json+++ /dev/null@@ -1,31 +0,0 @@-{- "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.csvdeleted file mode 100644index 985a34a9e..000000000--- a/evals/power-pages/add-tests/prompts.csv+++ /dev/null@@ -1,11 +0,0 @@-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 questiondiff --git a/evals/power-pages/add-tests/rubric.json b/evals/power-pages/add-tests/rubric.jsondeleted file mode 100644index 43ef59bc3..000000000--- a/evals/power-pages/add-tests/rubric.json+++ /dev/null@@ -1,31 +0,0 @@-{- "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/audit-permissions/evals.json b/evals/power-pages/audit-permissions/evals.jsonnew file mode 100644index 000000000..0aea0ff89--- /dev/null+++ b/evals/power-pages/audit-permissions/evals.json@@ -0,0 +1,97 @@+{+ "skill_name": "audit-permissions",+ "evals": [+ {+ "id": 1,+ "prompt": "I just set up table permissions for my e-commerce site but I'm not sure if I got everything right. Can you audit the permissions and let me know if there are any issues? I have tables for Products, Orders, Order Items, and Customers.",+ "expected_output": "The skill reads existing web roles and table permissions from .powerpages-site/, analyzes the site code for /_api/ patterns, @odata.bind lookups, and file upload patterns, checks .datamodel-manifest.json for the authoritative table list, queries Dataverse for lookup columns using query-table-lookups.js, runs all audit checks, generates an HTML audit report using the template with findings sorted by severity, displays it in the browser, records skill usage, and presents a summary asking if the user wants to fix issues.",+ "files": [],+ "expectations": [+ "Task tracking is set up at Step 1 with TaskCreate for all 6 tasks (Verify site deployment, Gather configuration, Discover relationships, Run audit checks, Generate audit report, Present findings)",+ "Site deployment is verified by checking .powerpages-site folder and table permissions exist",+ "All existing web roles are read from .powerpages-site/web-roles/",+ "All existing table permissions are read from .powerpages-site/table-permissions/",+ "Site source code is searched for /_api/ patterns to identify tables used in code",+ "Site source code is searched for @odata.bind patterns to identify lookup relationships",+ "Site source code is searched for file upload patterns (uploadFileColumn, uploadFile, etc.)",+ ".datamodel-manifest.json is checked for the authoritative table list",+ "pac env who is run to get the environment URL for Dataverse API calls",+ "query-table-lookups.js script is used to query Dataverse for lookup columns on tables with create/write permissions",+ "Missing permissions are flagged as critical for tables referenced in code but lacking permissions",+ "Missing append/appendto flags are checked for tables with lookup relationships",+ "Overly broad Global scope with write/delete is flagged as warning",+ "HTML audit report is generated using the template from assets/audit-report.html with placeholder replacement",+ "Health score is calculated based on findings (critical: -15, warning: -5, info: -1)",+ "Report is saved to docs/permissions-audit.html in the project directory",+ "Report is opened in browser via Playwright with 1920x1080 resize and full-page screenshot taken",+ "Skill usage is recorded via skill tracking reference",+ "Summary is presented with health score, critical/warning counts, and offer to fix issues",+ "Each task is marked in_progress when starting and completed when done"+ ]+ },+ {+ "id": 2,+ "prompt": "audit my power pages permissions. i think something is wrong because users are getting 403 errors when trying to create orders. the site has products, orders, and order items tables",+ "expected_output": "The skill should identify likely causes of 403 errors — most commonly missing append/appendto for lookup relationships or missing create permissions. The audit uses query-table-lookups.js to discover lookup columns and flags missing append/appendto as critical findings with reasoning about why they cause 403 errors and specific fix suggestions.",+ "files": [],+ "expectations": [+ "Task tracking is used throughout all 6 tasks",+ "Existing permissions are discovered from .powerpages-site/table-permissions/",+ "Code analysis identifies which CRUD operations are performed on each table",+ "pac env who is run to get the environment URL",+ "query-table-lookups.js is used to discover lookup columns on tables with create/write permissions",+ "Missing append flag is detected if orders have lookups to products without append: true",+ "Missing appendto flag is detected if products are referenced by order lookups without appendto: true",+ "Missing create permission is flagged if no permission grants create on the orders table",+ "Findings specifically reference the association/disassociation error message in reasoning",+ "HTML report includes critical findings at the top of the findings list",+ "Suggested fixes include exact permission changes needed (enable append, appendto, or create)",+ "Report health score reflects the severity of found issues",+ "Skill usage is recorded via skill tracking reference",+ "User is asked if they want the issues fixed after presenting the report"+ ]+ },+ {+ "id": 3,+ "prompt": "can you do a security review of my table permissions? I want to make sure we're following least-privilege principles. we have a portal with case management -- cases, notes, attachments, contacts, and knowledge articles",+ "expected_output": "The skill should focus on scope analysis — checking for overly permissive Global scope where Contact or Parent would be safer, validating parent-child chains for notes/attachments inheriting from cases using query-table-relationships.js, and flagging any Global write/delete permissions. Knowledge articles with Global read-only should pass as appropriate for public content.",+ "files": [],+ "expectations": [+ "Task tracking is used with TaskCreate at the start for all 6 tasks",+ "All table permissions are inventoried",+ "Parent chain integrity is verified for notes and attachments inheriting from cases",+ "query-table-relationships.js is used to validate parentrelationshipname values for parent-scope permissions",+ "Contact scope is validated as appropriate for case records (users see only own cases)",+ "Global scope with read-only for knowledge articles is marked as pass (appropriate for public content)",+ "Global scope with write or delete is flagged as warning with reasoning about least-privilege",+ "Write-without-read is flagged if any permission has write: true but read: false",+ "Orphaned permissions are detected for tables not referenced in site code",+ "Missing web role associations are flagged as warning",+ "HTML report is generated with correct health score",+ "Inventory data is included in the report with all permissions in a clean table",+ "Findings include both issues and passed checks to show thoroughness",+ "If Dataverse API scripts fail, those checks are skipped and noted in the report rather than stopping the audit"+ ]+ },+ {+ "id": 4,+ "prompt": "check my permissions setup. this is a brand new site and I haven't configured any table permissions yet, but I already have web roles and my site code references several tables via the Web API",+ "expected_output": "The skill should detect that no table permissions exist at all but tables are used in code, flagging each missing permission as critical. The report should have a low health score and multiple critical findings, one for each table referenced in code.",+ "files": [],+ "expectations": [+ "Site deployment is verified (.powerpages-site exists)",+ "The absence of any table permissions is detected and noted as a critical finding",+ "Web roles are still read and noted as existing",+ "Site code is analyzed to identify which tables need permissions via /_api/ and @odata.bind patterns",+ "Each table referenced in code gets a critical finding for missing permission",+ "Findings include reasoning about which code files reference each table",+ "Suggested fixes recommend appropriate scope and CRUD flags based on code analysis",+ "Health score is very low (near 0) due to multiple critical findings",+ "No passed checks for permission configuration (since none exist)",+ "HTML report is generated using the template and displayed via Playwright",+ "Skill usage is recorded via skill tracking reference",+ "User is offered to fix all issues, potentially suggesting /power-pages:setup-permissions for a complete permissions plan"+ ]+ }+ ]+}diff --git a/evals/power-pages/create-site/evals.json b/evals/power-pages/create-site/evals.jsonnew file mode 100644index 000000000..d7ee5a0de--- /dev/null+++ b/evals/power-pages/create-site/evals.json@@ -0,0 +1,127 @@+{+ "skill_name": "create-site",+ "evals": [+ {+ "id": 1,+ "prompt": "Create a Power Pages site for our company called 'Contoso Solutions Portal'. It should be a public-facing company portal built with React. We want to showcase our services, share company news, and let customers reach out to us.",+ "expected_output": "The skill discovers the site requirements (name: Contoso Solutions Portal, framework: React, purpose: Company Portal, audience: External, location: new folder in current directory), scaffolds the React template with placeholders replaced (__SITE_NAME__ = Contoso Solutions Portal, __SITE_SLUG__ = contoso-solutions-portal), runs npm install, initializes git, starts the dev server, and shares the URL. During component planning, the user selects Bold & Vibrant aesthetic with features like Services Catalog, News/Blog, Contact Form, and Team/About section. The plan is presented and approved. Implementation applies distinctive Google Fonts, a vibrant color palette via CSS variables, motion/animations, and builds all pages with real Unsplash images. Each page and component gets its own git commit. Accessibility is verified with axe-core on every route, all critical/serious violations are fixed and re-verified. The user reviews the site via the dev server URL and is asked about deployment.",+ "files": [],+ "expectations": [+ "Discovery phase asks for site name, framework, purpose, audience, and project location via AskUserQuestion",+ "Site naming values are derived: __SITE_NAME__ = 'Contoso Solutions Portal', __SITE_SLUG__ = 'contoso-solutions-portal'",+ "React template is copied from the assets/react/ directory and all __PLACEHOLDER__ tokens are replaced",+ "gitignore file is renamed to .gitignore in the project root",+ "npm install is run before git init so package-lock.json is included in the initial commit",+ "Git repository is initialized with an initial scaffold commit",+ "Dev server is started in background via 'npm run dev' and the localhost URL is shared with the user",+ "Playwright browser_navigate and browser_snapshot are used to verify the scaffold loads (no screenshots taken)",+ "Component planning asks for features (context-aware options for an external company portal), aesthetic direction (Bold & Vibrant selected), and mood",+ "Design aesthetics reference is read from ${CLAUDE_PLUGIN_ROOT}/skills/create-site/references/design-aesthetics.md",+ "A component plan table is presented showing pages, shared components, design elements, and routes",+ "Color palette is determined with 6 CSS variables (--color-primary, --color-secondary, --color-bg, --color-surface, --color-text, --color-text-muted)",+ "Implementation plan is presented with Section A (Design & Pages) and Section B (Review & Deployment) and user approval is requested",+ "Design foundations are applied first: distinctive Google Fonts (not Inter/Roboto/Arial), CSS variables for colors, motion/animation utilities, and background treatments",+ "The scaffold loading screen is completely replaced — no trace of Power Pages branded animation remains",+ "Real Unsplash images are sourced via WebSearch and used in hero sections, feature cards, and content areas",+ "Each individual page gets its own dedicated git commit (not batched together)",+ "Each shared component gets its own dedicated git commit",+ "Playwright browser_snapshot is used to verify each page after creation (no screenshots)",+ "axe-core audit script is run on every route passing --url, --routes, and --project-root flags",+ "All critical and serious accessibility violations are fixed and committed",+ "axe-core is re-run after fixes to confirm zero critical/serious violations",+ "An accessibility summary table is presented showing violations found vs fixed per page",+ "User is asked to review the site at the dev server URL via AskUserQuestion",+ "Deployment is offered via AskUserQuestion with 'Deploy now (Recommended)' and 'Skip for now' options",+ "TaskCreate is used to create todos for all 8 phases before starting work"+ ]+ },+ {+ "id": 2,+ "prompt": "I need an internal employee dashboard for our HR team. Call it 'PeopleHub Dashboard'. Use Vue. The team needs to see employee info, track leave requests, and post announcements. It's only for internal staff.",+ "expected_output": "The skill identifies this as an internal dashboard (prioritizing data tables, functional design over flashy) with Vue framework. It scaffolds the Vue template, replaces placeholders (__SITE_NAME__ = PeopleHub Dashboard, __SITE_SLUG__ = peoplehub-dashboard), installs dependencies, initializes git, and starts the Vite dev server. During planning, Minimal & Clean aesthetic is selected with features like Employee Directory, Leave Tracker, Announcements Board, and Quick Links. Implementation applies clean typography via Google Fonts, a muted professional color palette via CSS variables, subtle motion, and builds dashboard-oriented pages with data tables and card layouts. Every page and component is individually committed. Accessibility is audited and all violations fixed. The user reviews and is asked about deployment.",+ "files": [],+ "expectations": [+ "Discovery identifies the site as internal-audience, which influences generation toward data tables, dashboards, and functional design",+ "Vue template is copied from assets/vue/ directory with all placeholders replaced",+ "Site values derived: __SITE_NAME__ = 'PeopleHub Dashboard', __SITE_SLUG__ = 'peoplehub-dashboard'",+ "npm install runs before git init, dev server starts via 'npm run dev' in background",+ "Dev server URL (typically localhost:5173 for Vite) is shared with the user",+ "Scaffold is verified via Playwright browser_navigate and browser_snapshot before proceeding",+ "Feature options are context-aware for an internal HR dashboard (e.g., Employee Directory, Leave Requests, Announcements) — not a hardcoded list",+ "Minimal & Clean aesthetic is selected with appropriate mood pairing",+ "Google Fonts are chosen that are distinctive (not generic Inter/Roboto/Arial) and match Minimal & Clean direction",+ "CSS variables define a muted, professional color palette appropriate for an internal dashboard",+ "Motion/animation plan includes subtle transitions appropriate for Minimal & Clean aesthetic",+ "The scaffold loading screen is completely replaced with the actual dashboard UI",+ "Dashboard-oriented pages are built with functional UI elements (tables, cards, lists) — not placeholder 'coming soon' pages",+ "Router is updated with all new routes beyond the scaffold's default / and /about",+ "Navigation/header component is updated with links to all pages",+ "Individual git commits are made for each page and each shared component separately",+ "Playwright browser_snapshot verifies each page after implementation",+ "axe-core audit runs on every route; all critical/serious violations are fixed",+ "Re-verification confirms zero critical/serious violations across all pages",+ "User review is requested with the dev server URL and list of all available routes",+ "Deployment prompt is presented — session does not end without asking about deployment"+ ]+ },+ {+ "id": 3,+ "prompt": "Build me a landing page site called 'Aurelia Jewels' using Astro. It's for a luxury jewelry brand — we want it to feel high-end and exclusive. Target audience is external customers browsing our collections.",+ "expected_output": "The skill recognizes this as an external-facing landing page for a luxury brand. It scaffolds the Astro template (dev server at localhost:4321), replaces placeholders (__SITE_NAME__ = Aurelia Jewels, __SITE_SLUG__ = aurelia-jewels), and launches the dev server. During planning, the user selects Elegant & Premium mood with features like Collections Showcase, Brand Story, Craftsmanship section, and Contact/Boutique Locator. Implementation applies premium typography via Google Fonts (e.g., serif display fonts), a refined color palette with gold/dark tones via CSS variables, elegant animations, and builds visually rich pages with high-quality Unsplash jewelry/luxury images. Astro-specific conventions are followed (Layout.astro for fonts, separate Header/Footer components). Each page is individually committed. Accessibility is verified and the user reviews before deployment is offered.",+ "files": [],+ "expectations": [+ "Discovery identifies external audience, influencing site toward landing page appeal, SEO-friendly structure, and marketing-oriented layout",+ "Astro template is copied from assets/astro/ directory with all placeholders replaced",+ "Site values: __SITE_NAME__ = 'Aurelia Jewels', __SITE_SLUG__ = 'aurelia-jewels'",+ "Dev server starts at localhost:4321 (Astro default) and URL is shared with the user",+ "Scaffold verified via Playwright before proceeding to planning",+ "Feature options are context-aware for a luxury jewelry brand (e.g., Collections, Brand Story, Craftsmanship, Boutique Locator)",+ "Elegant & Premium mood is selected, and design-aesthetics.md reference is consulted for the aesthetic x mood mapping",+ "Google Fonts chosen are distinctive and appropriate for luxury branding (e.g., serif or display fonts — not Inter/Roboto/Arial)",+ "Color palette reflects luxury/premium feel (e.g., gold, deep tones, refined neutrals) defined via CSS variables",+ "Motion includes elegant, sophisticated animations (smooth transitions, subtle reveals) matching premium mood",+ "Astro-specific: Layout.astro is updated to load chosen Google Fonts instead of scaffold's DM Sans + Outfit",+ "Astro-specific: Header and Footer are separate components rewritten with proper navigation",+ "Real Unsplash images are sourced matching luxury/jewelry aesthetic with cohesive style and lighting",+ "Images use appropriate sizing (w=1600 for heroes, w=800 for cards) with descriptive alt text",+ "Each page gets its own dedicated git commit; each component gets its own commit",+ "Playwright browser_snapshot verifies each page (no screenshots taken)",+ "axe-core audit script runs with --routes flag covering all site routes",+ "All critical/serious accessibility violations are fixed, committed, and re-verified",+ "Accessibility summary table shows per-page violations found vs fixed",+ "User reviews the site and is asked for feedback via AskUserQuestion",+ "Deployment is offered as the final step — session does not end without this prompt"+ ]+ },+ {+ "id": 4,+ "prompt": "Create a partner hub site called 'Nexus Partner Hub' using Angular. This is for our business partners to access resources, track deals, and find partner contacts. It should feel professional and trustworthy. Put it in C:\\projects\\nexus-hub.",+ "expected_output": "The skill identifies this as an internal partner hub with Angular framework at a specific directory. It scaffolds the Angular template (dev server at localhost:4200), replaces placeholders (__SITE_NAME__ = Nexus Partner Hub, __SITE_SLUG__ = nexus-partner-hub), and launches the dev server. During planning, Professional & Trustworthy mood is selected with features like Resource Library, Deal Tracker, Partner Directory, and Notifications/Updates. Implementation applies authoritative typography via Google Fonts, a corporate color palette via CSS variables, confident animations, and builds functional partner-oriented pages. Angular conventions are followed (styles.css for theme, Angular router). Each page and component is individually committed. Accessibility is verified on all routes and the user reviews before deployment is offered.",+ "files": [],+ "expectations": [+ "Discovery resolves project location to the user-specified path C:\\projects\\nexus-hub instead of defaulting to current directory",+ "Angular template is copied from assets/angular/ directory with all placeholders replaced",+ "Site values: __SITE_NAME__ = 'Nexus Partner Hub', __SITE_SLUG__ = 'nexus-partner-hub'",+ "Dev server starts at localhost:4200 (Angular default) and URL is shared with the user",+ "Scaffold verified via Playwright browser_navigate and browser_snapshot",+ "Internal audience is identified, prioritizing functional navigation depth and data-oriented layouts",+ "Feature options are context-aware for a partner hub (e.g., Resource Library, Deal Tracker, Partner Directory, Notifications)",+ "Professional & Trustworthy mood is selected and mapped to design choices via the aesthetics reference",+ "Google Fonts chosen convey authority and professionalism (not generic Inter/Roboto/Arial)",+ "Angular-specific: styles.css (not theme.css) is used for design tokens and CSS variables",+ "Angular-specific: Angular router is configured with all new routes",+ "Color palette uses corporate, trustworthy tones defined via 6 CSS variables",+ "Motion/animations are confident and restrained, matching Professional & Trustworthy mood",+ "TodoList is created upfront with all 8 phases tracked via TaskCreate before any work begins",+ "Each individual page and component gets its own dedicated git commit",+ "Playwright browser_snapshot verifies each page after creation",+ "axe-core audit runs on every route; violations are fixed and re-verified until zero critical/serious issues",+ "Review phase presents a summary table of pages, components, design elements, and git commits",+ "Dev server URL and all available routes are shared with user for review",+ "User is asked for feedback via AskUserQuestion during review phase",+ "Deployment is offered with 'Deploy now (Recommended)' and 'Skip for now' options",+ "Skill usage is recorded via skill tracking reference before deployment prompt"+ ]+ }+ ]+}diff --git a/evals/power-pages/create-site/prompts.csv b/evals/power-pages/create-site/prompts.csvdeleted file mode 100644index b7bf926a5..000000000--- a/evals/power-pages/create-site/prompts.csv+++ /dev/null@@ -1,11 +0,0 @@-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 onlydiff --git a/evals/power-pages/create-site/rubric.json b/evals/power-pages/create-site/rubric.jsondeleted file mode 100644index 3bfe1758d..000000000--- a/evals/power-pages/create-site/rubric.json+++ /dev/null@@ -1,26 +0,0 @@-{- "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/create-webroles/evals.json b/evals/power-pages/create-webroles/evals.jsonnew file mode 100644index 000000000..29032d376--- /dev/null+++ b/evals/power-pages/create-webroles/evals.json@@ -0,0 +1,81 @@+{+ "skill_name": "create-webroles",+ "evals": [+ {+ "id": 1,+ "prompt": "I just deployed my Power Pages site for the first time and I need to set up the basic web roles. Can you create the standard roles -- Administrators, Authenticated Users, and Anonymous Users?",+ "expected_output": "The skill verifies the .powerpages-site/web-roles/ directory exists, finds no existing roles, suggests the three standard roles (Administrators, Authenticated Users, Anonymous Users), asks the user to confirm, generates a unique UUID for each role via generate-uuid.js, creates three YAML files with correct flags (anonymoususersrole: true only on Anonymous Users, authenticatedusersrole: true only on Authenticated Users), validates all files, and offers deployment.",+ "files": [],+ "expectations": [+ "The .powerpages-site/web-roles/ directory is checked for existence",+ "Existing web role YAML files are read to discover current roles (none found)",+ "The three standard roles (Administrators, Authenticated Users, Anonymous Users) are suggested",+ "User is asked to confirm which roles to create",+ "generate-uuid.js script is called once per role to produce 3 unique UUIDs",+ "administrators.yml is created with anonymoususersrole: false and authenticatedusersrole: false",+ "authenticated-users.yml is created with authenticatedusersrole: true and anonymoususersrole: false",+ "anonymous-users.yml is created with anonymoususersrole: true and authenticatedusersrole: false",+ "Each YAML file contains exactly 4 fields: anonymoususersrole, authenticatedusersrole, id, name",+ "All created files are verified for valid UUID v4 format and correct boolean flags",+ "Uniqueness constraints are validated: only one role has anonymoususersrole: true and only one has authenticatedusersrole: true",+ "A summary table of created roles is presented to the user",+ "User is asked whether to deploy the site to apply the new roles"+ ]+ },+ {+ "id": 2,+ "prompt": "I already have Administrators, Authenticated Users, and Anonymous Users roles set up. I need to add a Content Editors role and a Moderators role for my community site.",+ "expected_output": "The skill finds the existing three roles in .powerpages-site/web-roles/, lists them for the user, suggests Content Editors and Moderators as new roles without duplicating any existing roles, generates UUIDs for the two new roles, creates YAML files with both anonymoususersrole and authenticatedusersrole set to false (since those flags are already assigned to existing roles), validates all files including existing ones for constraint compliance, and offers deployment.",+ "files": [],+ "expectations": [+ "The .powerpages-site/web-roles/ directory is checked and found to exist",+ "Existing YAML files are read and 3 roles are discovered (Administrators, Authenticated Users, Anonymous Users)",+ "Existing roles are presented to the user before suggesting new ones",+ "Suggestions do not include any already-existing role names",+ "User is asked to confirm creation of Content Editors and Moderators",+ "generate-uuid.js script is called once per new role to produce 2 unique UUIDs",+ "content-editors.yml is created with anonymoususersrole: false and authenticatedusersrole: false",+ "moderators.yml is created with anonymoususersrole: false and authenticatedusersrole: false",+ "Neither new role sets anonymoususersrole or authenticatedusersrole to true since those flags are already assigned to existing roles",+ "Uniqueness constraints are validated across all 5 roles (existing + new): no duplicate IDs, at most one anonymous flag, at most one authenticated flag",+ "Summary table includes only the newly created roles",+ "User is asked whether to deploy the site to apply the new roles"+ ]+ },+ {+ "id": 3,+ "prompt": "Create web roles for my Power Pages site. I haven't deployed it yet though.",+ "expected_output": "The skill checks for the .powerpages-site directory and does not find it. It informs the user that the site must be deployed first to create the .powerpages-site folder, and asks whether to deploy now. If the user agrees, the deploy-site skill is invoked first. If the user declines, the skill stops and reminds the user to deploy before creating web roles.",+ "files": [],+ "expectations": [+ "Glob search is performed for .powerpages-site/web-roles/ directory",+ "The .powerpages-site folder is determined to be missing",+ "User is informed that .powerpages-site is created during first deployment",+ "User is asked whether to deploy now using AskUserQuestion with options (Yes, deploy now / No, I'll do it later)",+ "If user declines deployment, the skill stops without creating any web role files",+ "If user accepts deployment, the deploy-site skill is invoked before continuing",+ "No UUID generation or YAML file creation occurs before deployment completes",+ "Progress is tracked with TaskCreate/TaskUpdate throughout all phases"+ ]+ },+ {+ "id": 4,+ "prompt": "I need a Content Editors role for my Power Pages site so certain users can manage pages and content. Just that one role please.",+ "expected_output": "The skill verifies the site structure, discovers any existing roles, confirms the user wants only a Content Editors role, generates a single UUID via generate-uuid.js, creates content-editors.yml with both special flags set to false, validates the file, and offers deployment.",+ "files": [],+ "expectations": [+ "The .powerpages-site/web-roles/ directory is checked for existence",+ "Existing web role YAML files are read to discover current roles and their flags",+ "User is asked to confirm creation of the Content Editors role",+ "generate-uuid.js script is called exactly once to produce a UUID for the role",+ "content-editors.yml is created in .powerpages-site/web-roles/ with kebab-case filename",+ "The YAML file has anonymoususersrole: false and authenticatedusersrole: false",+ "The YAML file has the correct name field set to Content Editors",+ "The id field contains a valid UUID v4 generated by the script",+ "Verification confirms the file exists, has valid format, and no uniqueness constraints are violated",+ "A summary table showing the single created role is presented",+ "User is asked whether to deploy the site to apply the new role"+ ]+ }+ ]+}diff --git a/evals/power-pages/deploy-site/evals.json b/evals/power-pages/deploy-site/evals.jsonnew file mode 100644index 000000000..7c06b5ccb--- /dev/null+++ b/evals/power-pages/deploy-site/evals.json@@ -0,0 +1,80 @@+{+ "skill_name": "deploy-site",+ "evals": [+ {+ "id": 1,+ "prompt": "Deploy my Power Pages site. I'm already authenticated and the environment is correct. The project is in the current directory.",+ "expected_output": "The skill verifies PAC CLI installation, confirms authentication via pac auth who, presents the current environment for user confirmation, locates powerpages.config.json, runs npm run build, executes pac pages upload-code-site, verifies the .powerpages-site folder exists, commits deployment artifacts, checks activation status, and offers to activate or suggests next steps.",+ "files": [],+ "expectations": [+ "PAC CLI is verified by running pac help",+ "Authentication is checked via pac auth who",+ "Current environment name and URL are presented to the user for confirmation",+ "Project root is located by finding powerpages.config.json",+ "npm run build is executed before uploading",+ "pac pages upload-code-site is run with the correct --rootPath",+ ".powerpages-site folder is verified to exist after upload",+ "Deployment artifacts are committed via git add -A and git commit",+ "Activation status is checked using the check-activation-status.js script",+ "If site is not activated, user is asked whether to activate now or skip",+ "Next steps are suggested including activate-site, test-site, setup-datamodel, and add-seo",+ "TaskCreate is used to create a task list covering all 6 phases before starting work"+ ]+ },+ {+ "id": 2,+ "prompt": "I want to push my code site to Power Pages. I haven't set up PAC CLI auth yet.",+ "expected_output": "The skill verifies PAC CLI is installed, detects that the user is not authenticated via pac auth who, asks the user for their environment URL, runs pac auth create with the provided URL, verifies authentication succeeded, then proceeds with environment confirmation, build, upload, verification, and post-deployment steps.",+ "files": [],+ "expectations": [+ "PAC CLI is verified by running pac help",+ "pac auth who is run and the unauthenticated status is detected",+ "User is informed they are not authenticated with PAC CLI",+ "AskUserQuestion is used to request the environment URL from the user",+ "pac auth create --environment is run with the user-provided URL",+ "pac auth who is run again to verify authentication succeeded",+ "After successful auth, the environment is presented for confirmation",+ "Project root is located, site is built with npm run build, and uploaded with pac pages upload-code-site",+ "Post-deployment verification is performed including .powerpages-site check and git commit",+ "TaskCreate is used upfront to track all phases"+ ]+ },+ {+ "id": 3,+ "prompt": "Deploy my site to Power Pages. I've been getting errors about JavaScript files being blocked.",+ "expected_output": "The skill completes pre-deployment checks, attempts the upload which fails due to blocked .js attachments, explains the issue to the user, asks for permission to unblock .js, retrieves the current blocked attachments list via pac env list-settings, removes js from the list, updates the setting via pac env update-settings, retries the upload successfully, and proceeds to verify deployment.",+ "files": [],+ "expectations": [+ "PAC CLI and authentication are verified before attempting upload",+ "Environment is confirmed with the user",+ "pac pages upload-code-site is attempted and the blocked JavaScript error is detected",+ "User is informed that .js attachments are blocked in the environment",+ "AskUserQuestion is used to ask permission before modifying the blocked attachments setting",+ "pac env list-settings is run to retrieve the current blockedattachments value",+ "The js extension is removed from the semicolon-separated blocked attachments list",+ "pac env update-settings is run with the updated list (without js)",+ "pac pages upload-code-site is retried after unblocking",+ "Post-deployment verification proceeds normally after successful retry",+ "Git commit is made with deployment artifacts"+ ]+ },+ {+ "id": 4,+ "prompt": "Upload my code site to Power Pages. I previously deployed to a different environment and now I'm getting an error about .html attachments being blocked.",+ "expected_output": "The skill completes pre-deployment checks, attempts the upload which fails with a misleading HTML blocked attachment error, recognizes this is caused by a stale environment manifest in .powerpages-site, locates and deletes the old environment-specific manifest.yml file, retries the upload successfully, and proceeds to verify deployment.",+ "files": [],+ "expectations": [+ "PAC CLI and authentication are verified",+ "Environment is confirmed with the user",+ "pac pages upload-code-site is attempted and the HTML blocked attachment error is detected",+ "The error is recognized as misleading — not an actual .html block issue",+ "The .powerpages-site folder is inspected for stale environment manifest files matching *-manifest.yml",+ "The old environment-specific manifest.yml file is deleted",+ "The skill does NOT attempt to unblock .html in the environment's blocked attachments list",+ "pac pages upload-code-site is retried after deleting the manifest",+ "Post-deployment verification proceeds after successful retry including .powerpages-site check and git commit",+ "Activation status is checked and next steps are suggested"+ ]+ }+ ]+}diff --git a/evals/power-pages/integrate-webapi/evals.json b/evals/power-pages/integrate-webapi/evals.jsonnew file mode 100644index 000000000..72ff9fb1e--- /dev/null+++ b/evals/power-pages/integrate-webapi/evals.json@@ -0,0 +1,112 @@+{+ "skill_name": "integrate-webapi",+ "evals": [+ {+ "id": 1,+ "prompt": "I need to hook up the Web API for my Power Pages site. It's a React app with three tables -- Products, Categories, and Reviews. Reviews has lookups to both Products and Categories. I've got mock data scattered around the components right now. Just let the architects figure out the permissions, I don't have a diagram.",+ "expected_output": "The skill locates the project via powerpages.config.json, detects React from package.json, reads .datamodel-manifest.json to discover Products, Categories, and Reviews tables with their columns and relationships. It presents the three tables to the user for confirmation, then sequentially invokes the webapi-integration agent for each table — creating the shared powerPagesApi.ts client on the first table. After all integrations, it verifies type files, service files, and React hooks exist for each table, runs npm run build to confirm no errors, and commits. It then invokes the table-permissions-architect and webapi-settings-architect agents sequentially (Path B), which propose permissions and site settings with case-sensitive validated column names queried from Dataverse. After user approval of each plan, YAML files are created and committed. Finally, it presents a summary and asks whether to deploy.",+ "files": [],+ "expectations": [+ "Project root is located by finding powerpages.config.json",+ "React framework is detected from package.json dependencies",+ "Tables (Products, Categories, Reviews) are discovered from .datamodel-manifest.json",+ "Mock data and placeholder fetch calls are identified in source files via the Explore agent",+ "User is asked to confirm which tables to integrate",+ "Tables are processed sequentially (not in parallel) via the webapi-integration agent",+ "The shared powerPagesApi.ts API client is created during the first table's integration",+ "Type definition files are created in src/types/ for each table (e.g., product.ts, category.ts, review.ts)",+ "Service files are created in src/shared/services/ for each table (e.g., productService.ts, categoryService.ts, reviewService.ts)",+ "React hooks are created in src/shared/hooks/ for each table (e.g., useProducts.ts, useCategories.ts, useReviews.ts)",+ "Mock data in components is replaced with actual Web API service calls",+ "npm run build is executed to verify no compilation or import errors",+ "A git commit is made after integration code is complete",+ "The table-permissions-architect agent is invoked to propose and create table permission YAML files",+ "The webapi-settings-architect agent is invoked to propose site settings with case-sensitive column names validated against Dataverse",+ "Lookup columns in site settings include both the LogicalName and the _value OData computed form",+ "A git commit is made after permissions and site settings files are created",+ "A summary table of all created files is presented to the user",+ "User is asked whether to deploy the site",+ "TaskCreate/TaskUpdate is used to track progress through all phases"+ ]+ },+ {+ "id": 2,+ "prompt": "integrate web api into my vue power pages site. I have Events and Registrations tables. Here's my permissions diagram -- I'll paste it as Mermaid:\n\n```mermaid\nflowchart TD\n AR[Authenticated Role] --> EP[Events - Read]\n AR --> RP[Registrations - CRUD]\n EP -->|Parent: cr87b_event_registrations| RP\n```\n\nThe fields for Events should be cr87b_name, cr87b_date, cr87b_location and for Registrations cr87b_name, cr87b_email, cr87b_eventid.",+ "expected_output": "The skill detects Vue framework, discovers Events and Registrations from .datamodel-manifest.json, confirms tables with the user, then sequentially integrates both tables via the webapi-integration agent creating Vue composables. After verification and build, it follows Path A for permissions — parsing the user-provided Mermaid diagram to extract the Authenticated Role, two table permissions (Events with Read, Registrations with CRUD and Parent scope), and site settings. It validates the column names against Dataverse (case-sensitive), creates the YAML files using deterministic scripts, commits, and offers deployment.",+ "files": [],+ "expectations": [+ "Vue framework is detected from package.json (vue dependency)",+ "Events and Registrations tables are discovered from .datamodel-manifest.json",+ "User is asked to confirm which tables to integrate",+ "Tables are processed sequentially via the webapi-integration agent",+ "The shared powerPagesApi.ts API client is created during the first table's integration",+ "Vue composables are created (e.g., src/composables/useEvents.ts, src/composables/useRegistrations.ts)",+ "Type definition files are created for each table in src/types/",+ "Service files are created for each table",+ "npm run build is executed to verify the project compiles",+ "A git commit is made after integration code",+ "Path A is followed for permissions since the user provided a Mermaid diagram",+ "The Mermaid diagram is parsed to extract web roles, table permissions, scopes, and CRUD flags",+ "The Authenticated Role is matched to an existing web role in .powerpages-site/web-roles/ to get its UUID",+ "Events table permission is created with Read-only access and Global or appropriate scope",+ "Registrations table permission is created with CRUD access and Parent scope referencing Events via cr87b_event_registrations",+ "Column names (cr87b_name, cr87b_date, cr87b_location, cr87b_email, cr87b_eventid) are validated against Dataverse for exact case-sensitive LogicalNames",+ "Registrations site settings fields include both cr87b_eventid and _cr87b_eventid_value for the lookup column",+ "Site setting YAML files are created using the create-site-setting.js script, not manually written",+ "Table permission YAML files are created using the create-table-permission.js script",+ "A git commit is made after permissions and site settings files",+ "User is asked whether to deploy the site"+ ]+ },+ {+ "id": 3,+ "prompt": "add web api to my power pages site for the Projects and Tasks tables. it's a react site but I haven't deployed it yet so the .powerpages-site folder doesn't exist.",+ "expected_output": "The skill detects React, discovers Projects and Tasks tables, confirms with the user, and proceeds with integration code (Phases 1-5) since those don't require deployment. After integration and build verification, at Phase 6 it detects the missing .powerpages-site folder and warns the user that permissions cannot be configured without deployment. It asks whether to deploy now or skip permissions. If the user chooses to deploy, it invokes deploy-site first then resumes permissions setup. If the user skips, it notes that permissions are pending and presents a partial summary.",+ "files": [],+ "expectations": [+ "Project root is located via powerpages.config.json",+ "React framework is detected from package.json",+ "Projects and Tasks tables are discovered from .datamodel-manifest.json",+ "The absence of .powerpages-site folder is detected during Phase 1",+ "A warning is issued that permissions setup will require deployment first",+ "Integration code phases (2-5) proceed despite missing .powerpages-site",+ "Tables are processed sequentially via the webapi-integration agent",+ "The shared powerPagesApi.ts API client is created",+ "Type files, service files, and React hooks are created for both tables",+ "npm run build is executed to verify the project compiles",+ "A git commit is made after integration code",+ "At Phase 6, user is asked whether to deploy now or skip permissions",+ "If user chooses to skip, the summary notes that table permissions and site settings still need to be configured",+ "If user chooses to deploy, deploy-site is invoked before permissions setup resumes",+ "User is presented with a summary of completed work",+ "TaskCreate/TaskUpdate tracks progress including the deployment prerequisite status"+ ]+ },+ {+ "id": 4,+ "prompt": "I need to add web api integration for just the Contacts table in my react site. I already have a powerPagesApi.ts client set up from a previous integration. Let the architects handle permissions.",+ "expected_output": "The skill detects React, discovers the Contacts table, and during exploration notices that src/shared/powerPagesApi.ts already exists. It confirms the single table with the user, then invokes the webapi-integration agent for Contacts only, which reuses the existing API client rather than creating a new one. After verifying the new type, service, and hook files exist and the build succeeds, it invokes the table-permissions-architect and webapi-settings-architect agents for the single table. After approval and file creation, it commits and offers deployment.",+ "files": [],+ "expectations": [+ "Project root is located via powerpages.config.json",+ "React framework is detected from package.json",+ "Contacts table is discovered from .datamodel-manifest.json",+ "The Explore agent detects that src/shared/powerPagesApi.ts already exists",+ "User is asked to confirm integration for the Contacts table",+ "Only one table is processed via the webapi-integration agent",+ "The existing powerPagesApi.ts API client is reused, not recreated",+ "A type definition file is created for Contacts in src/types/",+ "A service file is created for Contacts (e.g., contactService.ts)",+ "A React hook is created for Contacts (e.g., useContacts.ts)",+ "npm run build is executed to verify no errors",+ "A git commit is made after integration code",+ "The table-permissions-architect agent is invoked for the single Contacts table",+ "The webapi-settings-architect agent is invoked and validates column names against Dataverse (case-sensitive)",+ "Site settings for Contacts use exact Dataverse LogicalNames (all lowercase)",+ "A git commit is made after permissions and site settings",+ "A summary is presented showing the single table integration",+ "User is asked whether to deploy"+ ]+ }+ ]+}diff --git a/evals/power-pages/integrate-webapi/prompts.csv b/evals/power-pages/integrate-webapi/prompts.csvdeleted file mode 100644index 471007e3a..000000000--- a/evals/power-pages/integrate-webapi/prompts.csv+++ /dev/null@@ -1,11 +0,0 @@-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 questiondiff --git a/evals/power-pages/integrate-webapi/rubric.json b/evals/power-pages/integrate-webapi/rubric.jsondeleted file mode 100644index 2436958ab..000000000--- a/evals/power-pages/integrate-webapi/rubric.json+++ /dev/null@@ -1,36 +0,0 @@-{- "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/evals.json b/evals/power-pages/setup-auth/evals.jsonnew file mode 100644index 000000000..076193e86--- /dev/null+++ b/evals/power-pages/setup-auth/evals.json@@ -0,0 +1,85 @@+{+ "skill_name": "setup-auth",+ "evals": [+ {+ "id": 1,+ "prompt": "Set up authentication and role-based access control for my Power Pages React site. I need login/logout with Microsoft Entra ID and want to restrict certain pages to Administrators and Authenticated Users roles.",+ "expected_output": "Full auth setup for a React site including auth service with login/logout, type declarations, role-based authorization utilities, AuthButton component integrated into navigation, and role-based UI patterns for Administrators and Authenticated Users. ProfileRedirectEnabled site setting configured and deployment prompted.",+ "files": [],+ "expectations": [+ "Detects the site as a React framework project",+ "Discovers existing web roles including Administrators and Authenticated Users",+ "Creates a powerPages.d.ts type declarations file for the shell API",+ "Creates an auth service module with login and logout functions using Microsoft Entra ID",+ "Creates a React-specific hook (e.g., useAuth) for consuming auth state in components",+ "Creates mock data or local dev helpers so auth works in local development",+ "Creates authorization utility functions for checking user roles",+ "Creates React-specific authorization components (e.g., RoleGuard or RequireRole)",+ "Creates an AuthButton component that shows login/logout based on auth state",+ "Integrates the AuthButton component into the site navigation",+ "Applies role-based UI patterns to protect content for Administrators and Authenticated Users",+ "Runs a build verification to confirm no compilation errors",+ "Sets the ProfileRedirectEnabled site setting to false",+ "Prompts the user to deploy the updated site"+ ]+ },+ {+ "id": 2,+ "prompt": "Add login and logout functionality to my Vue Power Pages site using Microsoft Entra ID. I don't need any role-based access control, just basic authentication so users can sign in and out.",+ "expected_output": "Auth setup for a Vue site with login/logout only. Auth service, Vue composable, AuthButton component in navigation, type declarations, and mock data for local dev. No role-based authorization utilities or protected content patterns. ProfileRedirectEnabled configured and deployment prompted.",+ "files": [],+ "expectations": [+ "Detects the site as a Vue framework project",+ "Checks for existing web roles but does not require them for login-only setup",+ "Creates a powerPages.d.ts type declarations file for the shell API",+ "Creates an auth service module with login and logout functions using Microsoft Entra ID",+ "Creates a Vue-specific composable (e.g., useAuth) for consuming auth state",+ "Creates mock data or local dev helpers so auth works in local development",+ "Does not create role-checking authorization utility functions",+ "Does not create role-based guard components or directives",+ "Creates an AuthButton component that shows login/logout based on auth state",+ "Integrates the AuthButton component into the site navigation",+ "Runs a build verification to confirm no compilation errors",+ "Sets the ProfileRedirectEnabled site setting to false",+ "Prompts the user to deploy the updated site"+ ]+ },+ {+ "id": 3,+ "prompt": "I have an Angular Power Pages code site. Set up authentication with Microsoft Entra ID and add role-based guards so only users with specific web roles can access certain routes and see certain UI elements.",+ "expected_output": "Full auth setup for an Angular site including auth service with login/logout, type declarations, Angular-specific route guards and structural directives for role-based access, AuthButton component in navigation, and role-based UI patterns. ProfileRedirectEnabled configured and deployment prompted.",+ "files": [],+ "expectations": [+ "Detects the site as an Angular framework project",+ "Discovers existing web roles on the site",+ "Creates a powerPages.d.ts type declarations file for the shell API",+ "Creates an Angular auth service with login and logout functions using Microsoft Entra ID",+ "Creates an Angular-specific injectable service for consuming auth state",+ "Creates mock data or local dev helpers so auth works in local development",+ "Creates authorization utility functions for checking user roles",+ "Creates Angular route guards for protecting routes by role",+ "Creates Angular structural directives or components for role-based UI visibility",+ "Creates an AuthButton component that shows login/logout based on auth state",+ "Integrates the AuthButton component into the site navigation",+ "Applies role-based guards to routes with protected content",+ "Runs a build verification to confirm no compilation errors",+ "Sets the ProfileRedirectEnabled site setting to false",+ "Prompts the user to deploy the updated site"+ ]+ },+ {+ "id": 4,+ "prompt": "Set up authentication and authorization for my Power Pages React site. I want role-based access for different user groups.",+ "expected_output": "The skill detects that no web roles exist on the site and informs the user that web roles must be created in the Power Pages admin center before role-based authorization can be configured. The skill should not proceed with authorization setup until roles are available.",+ "files": [],+ "expectations": [+ "Detects the site as a React framework project",+ "Checks for existing web roles and finds none configured",+ "Informs the user that no web roles exist on the site",+ "Prompts or instructs the user to create web roles in Power Pages admin center before proceeding",+ "Does not create authorization utilities or role-based components without valid web roles",+ "May still offer to set up basic login/logout authentication without role-based access"+ ]+ }+ ]+}diff --git a/evals/power-pages/setup-auth/prompts.csv b/evals/power-pages/setup-auth/prompts.csvdeleted file mode 100644index 63eecc8b7..000000000--- a/evals/power-pages/setup-auth/prompts.csv+++ /dev/null@@ -1,11 +0,0 @@-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 questiondiff --git a/evals/power-pages/setup-auth/rubric.json b/evals/power-pages/setup-auth/rubric.jsondeleted file mode 100644index 3028efd17..000000000--- a/evals/power-pages/setup-auth/rubric.json+++ /dev/null@@ -1,36 +0,0 @@-{- "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-datamodel/evals.json b/evals/power-pages/setup-datamodel/evals.jsonnew file mode 100644index 000000000..0002ee79f--- /dev/null+++ b/evals/power-pages/setup-datamodel/evals.json@@ -0,0 +1,93 @@+{+ "skill_name": "setup-datamodel",+ "evals": [+ {+ "id": 1,+ "prompt": "I'm building an e-commerce Power Pages site. I need tables for Products, Categories, and Orders. Can you set up the data model for me? The site is already created and connected via PAC CLI.",+ "expected_output": "The skill invokes the Data Model Architect agent to analyze the site and propose a data model with Products, Categories, and Orders tables including appropriate columns and relationships. After user approval, it creates the tables via OData deep-insert, sets up 1:N and M:N relationships, publishes customizations, and writes the manifest file.",+ "files": [],+ "expectations": [+ "Verifies PAC CLI authentication and Azure CLI token before proceeding",+ "Chooses Path B (Data Model Architect) since no ER diagram was provided",+ "Spawns the Data Model Architect agent to analyze the site and propose tables, columns, and relationships",+ "Presents a Mermaid ER diagram showing Products, Categories, and Orders with their relationships",+ "Waits for explicit user approval of the proposed data model before creating anything",+ "Refreshes the Azure CLI token before making API calls",+ "Queries existing tables via OData to check for conflicts and builds a creation plan",+ "Creates tables and columns using OData POST to EntityDefinitions with deep-insert pattern",+ "Creates 1:N lookup relationship from Orders to Products",+ "Creates 1:N or M:N relationship between Products and Categories",+ "Calls PublishXml to publish all created customizations",+ "Verifies the created tables are accessible after publishing",+ "Writes a .datamodel-manifest.json file listing all created tables, columns, and relationships",+ "Displays a summary of what was created with suggested next steps"+ ]+ },+ {+ "id": 2,+ "prompt": "I have an ER diagram for a blog data model. Please set up these tables:\n\n```mermaid\nerDiagram\n cr_author {\n string cr_name\n string cr_email\n string cr_bio\n }\n cr_post {\n string cr_title\n string cr_body\n datetime cr_publishedon\n boolean cr_isfeatured\n }\n cr_comment {\n string cr_text\n datetime cr_createdon\n string cr_guestname\n }\n cr_author ||--o{ cr_post : writes\n cr_post ||--o{ cr_comment : has\n```",+ "expected_output": "The skill accepts the uploaded Mermaid ER diagram, parses the three tables (Author, Post, Comment) with their columns and relationships, presents the model for approval, then creates everything via OData and publishes.",+ "files": [],+ "expectations": [+ "Verifies PAC CLI authentication and Azure CLI token before proceeding",+ "Chooses Path A (user-provided ER diagram) since a Mermaid diagram was supplied",+ "Parses the Mermaid ER diagram to extract tables, columns, and relationships",+ "Presents the parsed data model back to the user with a formatted Mermaid ER diagram for confirmation",+ "Waits for explicit user approval before creating any tables",+ "Refreshes the Azure CLI token before making OData API calls",+ "Queries existing tables to check whether cr_author, cr_post, or cr_comment already exist",+ "Creates cr_author table with cr_name, cr_email, and cr_bio columns via OData POST deep-insert",+ "Creates cr_post table with cr_title, cr_body, cr_publishedon, and cr_isfeatured columns via OData POST deep-insert",+ "Creates cr_comment table with cr_text, cr_createdon, and cr_guestname columns via OData POST deep-insert",+ "Creates 1:N lookup relationship from cr_author to cr_post",+ "Creates 1:N lookup relationship from cr_post to cr_comment",+ "Calls PublishXml to publish all customizations",+ "Writes a .datamodel-manifest.json file documenting the created schema",+ "Displays a summary with next steps for configuring the Power Pages site"+ ]+ },+ {+ "id": 3,+ "prompt": "I need to extend my Power Pages site data model. I already have a cr_customer table and a cr_product table. I need to add a cr_review table (with rating and comment columns) linked to both, and add a cr_loyaltypoints column to the existing cr_customer table.",+ "expected_output": "The skill detects that cr_customer and cr_product already exist, plans to reuse them, creates the new cr_review table, adds the cr_loyaltypoints column to cr_customer, sets up relationships, and publishes.",+ "files": [],+ "expectations": [+ "Verifies PAC CLI authentication and Azure CLI token before proceeding",+ "Chooses Path B (Data Model Architect) to analyze requirements since no ER diagram was provided",+ "Presents a Mermaid ER diagram showing cr_customer, cr_product (existing), and cr_review (new) with relationships",+ "Waits for explicit user approval of the proposed changes",+ "Refreshes the Azure CLI token before making API calls",+ "Queries existing tables and discovers cr_customer and cr_product already exist in the environment",+ "Builds a creation plan that distinguishes between new tables, existing tables to modify, and tables to reuse as-is",+ "Creates the new cr_review table with rating and comment columns via OData POST deep-insert",+ "Adds the cr_loyaltypoints column to the existing cr_customer table via OData PATCH or POST to the existing entity",+ "Creates 1:N lookup relationship from cr_customer to cr_review",+ "Creates 1:N lookup relationship from cr_product to cr_review",+ "Calls PublishXml to publish all new and modified customizations",+ "Verifies the created and modified tables are accessible after publishing",+ "Writes a .datamodel-manifest.json file reflecting both new and existing entities",+ "Displays a summary clearly indicating which tables were created, which were modified, and which were reused"+ ]+ },+ {+ "id": 4,+ "prompt": "I just need a simple feedback table for my Power Pages site. It should have a subject field (text, required), a description field (multiline text), a rating field (whole number 1-5), and a submitted on field (date). Nothing else.",+ "expected_output": "The skill creates a single cr_feedback table with the four specified columns, publishes it, and writes the manifest. No relationships are needed.",+ "files": [],+ "expectations": [+ "Verifies PAC CLI authentication and Azure CLI token before proceeding",+ "Recognizes this is a simple single-table request and proposes a straightforward data model",+ "Presents a Mermaid ER diagram showing the cr_feedback table with its four columns",+ "Waits for explicit user approval before creating the table",+ "Refreshes the Azure CLI token before making API calls",+ "Queries existing tables to confirm cr_feedback does not already exist",+ "Creates cr_feedback table with cr_subject (text, required), cr_description (multiline text), cr_rating (whole number), and cr_submittedon (date) columns via OData POST deep-insert",+ "Does not attempt to create any relationships since none are needed",+ "Calls PublishXml to publish the new table",+ "Verifies the cr_feedback table is accessible after publishing",+ "Writes a .datamodel-manifest.json file documenting the single table and its columns",+ "Displays a summary confirming the table was created with suggested next steps"+ ]+ }+ ]+}diff --git a/evals/power-pages/setup-dataverse/prompts.csv b/evals/power-pages/setup-dataverse/prompts.csvdeleted file mode 100644index 0e8e2f868..000000000--- a/evals/power-pages/setup-dataverse/prompts.csv+++ /dev/null@@ -1,11 +0,0 @@-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 setupdiff --git a/evals/power-pages/setup-dataverse/rubric.json b/evals/power-pages/setup-dataverse/rubric.jsondeleted file mode 100644index b70b72410..000000000--- a/evals/power-pages/setup-dataverse/rubric.json+++ /dev/null@@ -1,36 +0,0 @@-{- "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.csvdeleted file mode 100644index 814e582cc..000000000--- a/evals/power-pages/setup-webapi/prompts.csv+++ /dev/null@@ -1,11 +0,0 @@-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 questiondiff --git a/evals/power-pages/setup-webapi/rubric.json b/evals/power-pages/setup-webapi/rubric.jsondeleted file mode 100644index e19345629..000000000--- a/evals/power-pages/setup-webapi/rubric.json+++ /dev/null@@ -1,36 +0,0 @@-{- "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/power-pages/test-site/evals.json b/evals/power-pages/test-site/evals.jsonnew file mode 100644index 000000000..4a3968669--- /dev/null+++ b/evals/power-pages/test-site/evals.json@@ -0,0 +1,87 @@+{+ "skill_name": "test-site",+ "evals": [+ {+ "id": 1,+ "prompt": "Test my Power Pages site at https://contoso-portal.powerappsportals.com and make sure all the pages and APIs are working correctly.",+ "expected_output": "The agent uses the provided URL directly without needing to resolve it from activation status. It launches a Playwright browser, resizes the viewport, navigates to the homepage, and verifies it loads successfully. It captures console errors and network requests during the initial load. Since the site is public (no login wall), it proceeds to crawl discoverable links up to a maximum of 25 pages, checking each for errors. It captures /_api/ requests, analyzes their status codes (all returning 200 OK), and confirms the APIs are healthy. Finally, it generates a test report with pass/fail results per page and per API endpoint, closes the browser, and provides next steps.",+ "files": [],+ "expectations": [+ "Uses the user-provided URL https://contoso-portal.powerappsportals.com directly without prompting or checking activation status",+ "Resizes the browser viewport to an appropriate dimension before navigating",+ "Navigates to the homepage URL and verifies it loads without critical errors",+ "Captures and reports any browser console errors during page loads",+ "Captures network requests during navigation to identify API calls",+ "Detects no login wall and proceeds without asking the user to authenticate",+ "Crawls discoverable links on the site, visiting up to a maximum of 25 pages",+ "Checks each crawled page for load errors, console errors, and failed network requests",+ "Identifies /_api/ requests and analyzes their HTTP status codes",+ "Reports all API endpoints as healthy when status codes are 200",+ "Generates a final test report with per-page pass/fail results and per-API-endpoint results",+ "Closes the browser session after testing is complete",+ "Provides actionable next steps or recommendations based on the test results"+ ]+ },+ {+ "id": 2,+ "prompt": "Run a full test on my Power Pages site. I don't have the URL handy but it should be activated already.",+ "expected_output": "The agent detects that no URL was provided. It attempts to auto-detect the site URL by checking the activation status of the Power Pages site in the current environment. Once the URL is resolved from the activation status, it launches a Playwright browser, resizes the viewport, navigates to the resolved homepage, and verifies it loads. It captures console errors and network requests, confirms no login wall is present, crawls up to 25 pages, tests API endpoints, and generates a comprehensive test report before closing the browser.",+ "files": [],+ "expectations": [+ "Recognizes that the user did not provide a site URL",+ "Attempts to resolve the site URL from the activation status or environment configuration",+ "Falls back to asking the user for the URL if auto-detection fails",+ "Resizes the browser viewport before navigating to the site",+ "Navigates to the resolved homepage and verifies successful load",+ "Captures browser console errors and network requests during navigation",+ "Crawls discoverable links up to a maximum of 25 pages",+ "Identifies and analyzes /_api/ network requests with their status codes",+ "Generates a test report summarizing pass/fail results for each page and API endpoint",+ "Closes the browser after all tests are complete",+ "Provides recommendations or next steps based on test findings"+ ]+ },+ {+ "id": 3,+ "prompt": "Test https://hr-portal.powerappsportals.com to see if all pages load correctly. This site requires employees to log in.",+ "expected_output": "The agent uses the provided URL, launches a Playwright browser, resizes the viewport, and navigates to the homepage. During the initial load, it detects a login wall (redirect to a sign-in page or presence of authentication prompts). It informs the user that authentication is required and asks the user to complete the login process in the browser. After the user logs in, the agent resumes testing by verifying the authenticated homepage, capturing console errors and network requests, crawling up to 25 pages behind the login wall, testing API endpoints, and generating a full test report before closing the browser.",+ "files": [],+ "expectations": [+ "Uses the user-provided URL https://hr-portal.powerappsportals.com directly",+ "Resizes the browser viewport to an appropriate dimension",+ "Navigates to the homepage and detects a login wall or authentication redirect",+ "Informs the user that the site requires authentication and asks them to log in",+ "Waits for the user to complete the login process before continuing",+ "After authentication, verifies the homepage loads correctly in the authenticated state",+ "Captures browser console errors and network requests throughout testing",+ "Crawls discoverable links up to a maximum of 25 pages in the authenticated context",+ "Identifies /_api/ requests and analyzes their HTTP status codes",+ "Generates a test report with per-page and per-API pass/fail results",+ "Closes the browser session after testing is complete",+ "Provides next steps or recommendations based on the test outcomes"+ ]+ },+ {+ "id": 4,+ "prompt": "I need to test https://partner-portal.powerappsportals.com -- some of our API endpoints have been returning errors lately. Please check everything.",+ "expected_output": "The agent uses the provided URL, launches a Playwright browser, resizes the viewport, and navigates to the homepage. It verifies the homepage loads, captures console errors and network requests, and confirms no login wall is present. It crawls up to 25 pages, finding some pages that load correctly and others that may show errors. Critically, it captures /_api/ requests and identifies several returning 403 Forbidden status codes. It provides detailed remediation guidance for the 403 errors, such as checking table permissions, web roles, and site settings. The final test report includes per-page pass/fail results, per-API-endpoint results with status codes, specific remediation steps for failing endpoints, and an overall summary with recommendations.",+ "files": [],+ "expectations": [+ "Uses the user-provided URL https://partner-portal.powerappsportals.com directly",+ "Resizes the browser viewport before navigating to the site",+ "Navigates to the homepage and verifies it loads without critical failure",+ "Captures browser console errors during all page loads",+ "Captures network requests including /_api/ calls during navigation",+ "Detects no login wall and proceeds with testing without authentication prompts",+ "Crawls discoverable links on the site up to a maximum of 25 pages",+ "Checks each crawled page for load errors and console issues",+ "Identifies /_api/ requests that return 403 Forbidden status codes",+ "Provides actionable remediation guidance for 403 errors such as reviewing table permissions, web roles, or site settings",+ "Generates a final test report with per-page pass/fail results and per-API-endpoint results including status codes",+ "Includes an overall summary distinguishing healthy endpoints from failing ones",+ "Closes the browser session after all testing is complete",+ "Provides prioritized next steps focusing on resolving the API failures"+ ]+ }+ ]+}diff --git a/evals/run_eval.py b/evals/run_eval.pydeleted file mode 100644index 7d3e75ee3..000000000--- a/evals/run_eval.py+++ /dev/null@@ -1,208 +0,0 @@-#!/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__.pydeleted file mode 100644index d41b2b59e..000000000--- a/evals/shared/__init__.py+++ /dev/null@@ -1,40 +0,0 @@-"""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.pydeleted file mode 100644index 92ad406a2..000000000--- a/evals/shared/grader.py+++ /dev/null@@ -1,290 +0,0 @@-"""-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.pydeleted file mode 100644index 1465d79dc..000000000--- a/evals/shared/helpers.py+++ /dev/null@@ -1,424 +0,0 @@-"""-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.pydeleted file mode 100644index 07d63f3fe..000000000--- a/evals/shared/runner.py+++ /dev/null@@ -1,270 +0,0 @@-"""-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")diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex 9a4f37974..e814c28d9 100644--- a/plugins/power-pages/.claude-plugin/plugin.json+++ b/plugins/power-pages/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "1.0.3",+ "version": "1.1.0","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro, with more site types coming soon.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex dae362cfb..e35578198 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -1,227 +1,42 @@-# AGENTS.md — Power Pages Plugin--This file provides guidance to AI Agents when working with the **power-pages** plugin.--## What This Plugin Is+# Power Pages PluginA plugin for creating, deploying, and managing Power Pages code sites. Supports static SPA frameworks (React, Vue, Angular, Astro) with Dataverse integration, Web API access, and browser-based previews via Playwright.-## Local Development--Test this plugin locally:--```bash-claude --plugin-dir /path/to/plugins/power-pages-```--Each framework template under `skills/create-site/assets/{react,vue,angular,astro}/` has its own `package.json` with `dev`, `build`, and `preview` scripts (Vite for React/Vue, Angular CLI for Angular, Astro CLI for Astro).--## Architecture--```-.claude-plugin/plugin.json ← Plugin metadata (name, version, keywords)-.mcp.json ← MCP server config (Playwright for browser automation)-agents/- data-model-architect.md ← Agent: proposes Dataverse data models (read-only)- webapi-integration.md ← Agent: implements Web API integration in frontend code- webapi-permissions.md ← Agent: proposes Web API permissions plan (read-only)-scripts/- generate-uuid.js ← Shared UUID v4 generator (used by multiple skills)- check-activation-status.js ← Checks if site is already activated (used by deploy-site, activate-site)-references/ ← Shared reference docs used by multiple skills- odata-common.md ← Auth headers, token refresh, error handling, retry patterns- dataverse-prerequisites.md ← PAC CLI check, Azure CLI token, API access verification- framework-conventions.md ← Framework detection, paths, route discovery- datamodel-manifest-schema.md ← .datamodel-manifest.json format spec-skills/- create-site/- SKILL.md ← Skill definition with frontmatter (model, allowed-tools, hooks)- assets/{react,vue,angular,astro}/ ← Framework templates with __PLACEHOLDER__ tokens- references/design-aesthetics.md ← Design principles, font/color/motion guidance for inline design step- scripts/validate-site.js ← Node script validating generated sites- deploy-site/- SKILL.md ← Deployment skill definition- setup-datamodel/- SKILL.md ← Dataverse data model creation skill definition- references/odata-api-patterns.md ← OData API body templates for table/column/relationship creation- scripts/validate-datamodel.js ← Node script validating Dataverse data model creation- add-sample-data/- SKILL.md ← Sample data insertion skill definition- references/odata-record-patterns.md ← OData API patterns for record creation and lookups- add-seo/- SKILL.md ← SEO essentials skill definition (robots.txt, sitemap.xml, meta tags)- scripts/validate-seo.js ← Node script validating SEO assets (robots.txt, sitemap.xml, meta tags)- activate-site/- SKILL.md ← Site activation/provisioning skill definition- scripts/activate-site.js ← Activates a site via PP API + polls status- scripts/generate-subdomain.js ← Random subdomain suggestion generator- scripts/validate-activation.js ← Validates site was provisioned via PP API- create-webroles/- SKILL.md ← Web roles creation skill definition- scripts/validate-webroles.js ← Node script validating web role YAML files were created- integrate-webapi/- SKILL.md ← Web API integration skill definition- scripts/validate-webapi-integration.js ← Node script validating Web API integration code- setup-auth/- SKILL.md ← Authentication & authorization skill definition- references/authentication-reference.md ← Login/logout flow, auth service, framework patterns- references/authorization-reference.md ← Role-based access control, guards, directives- scripts/validate-auth.js ← Node script validating auth service and authorization code-```--## Plugin Components--### Agents--Auto-triggered by the main conversation when relevant:--- `data-model-architect`: Read-only agent that analyzes site requirements, discovers existing Dataverse tables via OData API, and proposes a data model (new/modified/reused tables + Mermaid ER diagram). Uses `pac env who` + Azure CLI auth to query Dataverse. Renders the ER diagram visually in the browser via Playwright (writes a temp HTML file with Mermaid.js CDN, navigates to it, takes a screenshot) before entering plan mode. Does NOT create, modify, or delete any tables — purely advisory. The main conversation uses its output to create tables.-- `webapi-integration`: Implementation agent that creates production-ready Web API integration code for a single Dataverse table in a Power Pages code site. Detects the frontend framework (React/Vue/Angular/Astro), creates a shared `powerPagesApi.ts` client (token management, retry logic, OData URL builder) if one doesn't exist, then generates TypeScript entity types, a domain mapper, and a CRUD service layer for the target table. Also creates framework-specific hooks (React), composables (Vue), or injectable services (Angular). Follows Power Pages Web API best practices: `/_api/` endpoints, dual token headers, `@odata.bind` for lookups, explicit `$select` (never `*`), formatted value annotations, exponential backoff retry, and 8-minute token TTL. Handles one table per invocation — invoke separately for multiple tables.-- `webapi-permissions`: Read-only agent that analyzes site code, discovers existing web roles and table permissions, queries Dataverse for table columns, and proposes a complete Web API permissions plan (table permissions + site settings). Checks for `.powerpages-site` folder to verify site deployment. Renders a Mermaid flowchart showing web roles → table permissions → tables visually in the browser via Playwright. Never uses `*` for Web API field settings — always lists specific columns. Does NOT create any YAML files — purely advisory. The main conversation uses its output to create table permission and site setting files.--### Skills--User-invocable via `/power-pages:<skill-name>`:--- `create-site`: 6-step workflow — gather requirements (including design direction), plan (with explicit scaffold prerequisites), scaffold from template, build pages/components/routing with design applied from the start using `skills/create-site/references/design-aesthetics.md` and live Playwright preview, review, deploy-- `deploy-site`: 6-step workflow — verify PAC CLI, authenticate, confirm environment, upload via `pac pages upload-code-site`, verify deployment (confirm `.powerpages-site` folder, commit, offer activation), handle blocked JS attachments-- `setup-datamodel`: 7-step workflow — verify prerequisites, invoke data-model-architect agent, review proposal, pre-creation checks, create tables & columns via OData API, create relationships, publish & verify. Writes `.datamodel-manifest.json` for hook validation.-- `add-sample-data`: 6-step workflow — verify prerequisites, discover tables (from `.datamodel-manifest.json` or OData API), select tables & configure record count, generate & review sample data plan, insert records via OData API with relationship handling, verify & summarize.-- `activate-site`: 5-step workflow — verify prerequisites (PAC CLI auth + Azure CLI token + cloud-aware API URL resolution + activation status check via shared script), gather parameters (site name, subdomain, website record ID), confirm with user, activate & poll via `skills/activate-site/scripts/activate-site.js`, present summary with site URL.-- `add-seo`: 7-step workflow — verify site exists, gather SEO config (production URL, exclusions, meta description), plan & approve, create robots.txt, generate sitemap.xml from discovered routes, add meta tags (title, description, viewport, Open Graph, Twitter Card, favicon) to index.html, verify via Playwright & commit.-- `create-webroles`: 6-step workflow — verify `.powerpages-site/web-roles/` exists (redirect to deploy-site if missing), discover existing roles, determine new roles needed, create web role YAML files with UUIDs from shared `scripts/generate-uuid.js`, verify web roles (validate files, UUIDs, uniqueness constraints), review & prompt deployment via deploy-site skill.-- `integrate-webapi`: 7-step workflow — verify site exists, use Explore agent to analyze code and identify tables needing Web API integration, review plan with user, invoke `webapi-integration` agent per table to create API client/types/services/hooks, verify integrations (validate all files exist, project builds), invoke `webapi-permissions` agent to configure table permissions and site settings, review & deploy via `deploy-site` skill.-- `setup-auth`: 8-step workflow — verify prerequisites (site deployed + web roles), gather auth requirements and plan, create auth service with Entra ID login/logout (anti-forgery token + form POST), create authorization utilities (role checking), create auth UI (AuthButton component), apply role-based access control to components, verify auth setup (validate files, build, auth UI renders), create `ProfileRedirectEnabled` site setting and deploy.--Skills are defined in `SKILL.md` files with YAML frontmatter (name, description, allowed-tools, model, hooks).--### Hooks--Defined in each skill's SKILL.md frontmatter:--- Stop hooks run when a skill session ends. Each skill defines its own hooks so validation only runs in the correct context:- - `create-site`: command hook runs `validate-site.js` + prompt hook checks site completeness- - `setup-datamodel`: command hook runs `validate-datamodel.js` + prompt hook checks data model completeness- - `add-sample-data`: prompt hook checks sample data insertion completeness- - `activate-site`: command hook runs `validate-activation.js` + prompt hook checks activation completeness- - `add-seo`: command hook runs `validate-seo.js` + prompt hook checks SEO asset completeness- - `create-webroles`: command hook runs `validate-webroles.js` + prompt hook checks web role creation completeness- - `integrate-webapi`: command hook runs `validate-webapi-integration.js` + prompt hook checks integration completeness- - `setup-auth`: command hook runs `validate-auth.js` + prompt hook checks auth setup completeness-- Hooks are defined in SKILL.md frontmatter (not a global hooks.json) so they only fire for the relevant skill session--### Shared Scripts--Shared utility scripts live at `scripts/` and are referenced by multiple skills and agents via `${CLAUDE_PLUGIN_ROOT}/scripts/`.--- `generate-uuid.js`: Generates a random UUID v4. Self-contained, no dependencies. Used by `create-webroles` and the main agent when creating table permission / site setting files from the `webapi-permissions` agent plan.-- `update-skill-tracking.js`: Updates skill usage tracking site settings. Takes `--projectRoot`, `--skillName`, and `--authoringTool` args. The agent passes its own name as `--authoringTool` (e.g., `ClaudeCode`, `GitHubCopilot`). Creates/increments a per-skill counter (`Site-AI-<SkillName>.sitesetting.yml`) and records the authoring tool (`Site-AI-AuthoringTool.sitesetting.yml`). Exits silently if `.powerpages-site/site-settings/` does not exist. Used by all 9 skills.-- `check-activation-status.js`: Checks whether a Power Pages site is already activated (provisioned) in the environment. Takes `--projectRoot` arg. Reads `siteName` from `powerpages.config.json`, looks up `websiteRecordId` via `pac pages list`, queries the Power Platform GET websites API, and matches by both `websiteRecordId` and `name`. Outputs JSON: `{ activated: true/false, siteName, websiteRecordId, websiteUrl }` or `{ error }`. Used by `deploy-site` and `activate-site`.--### Shared References--Shared reference documents live at `references/` and are referenced by multiple skills via relative paths (e.g., `../../references/odata-common.md`). This avoids duplicating common patterns across skill-specific reference docs and SKILL.md files.--- `odata-common.md`: Auth headers, PowerShell token helper, token refresh cadence, HTTP status codes, Dataverse error codes, retry pattern. Used by `setup-datamodel` and `add-sample-data`.-- `dataverse-prerequisites.md`: PAC CLI auth check (`pac env who`), Azure CLI token acquisition, API access verification (`WhoAmI`). Used by `setup-datamodel` and `add-sample-data`.-- `framework-conventions.md`: Supported frameworks, framework → build tool / router / build output / public dir / index HTML mapping, framework detection via `package.json`, route discovery patterns. Used by `create-site` and `add-seo`.-- `datamodel-manifest-schema.md`: Schema spec for `.datamodel-manifest.json` (fields, types, usage). Written by `setup-datamodel`, read by `add-sample-data`, validated by `validate-datamodel.js`.-- `skill-tracking-reference.md`: Skill usage tracking instructions — script invocation syntax, skill name mapping table, and YAML format. Referenced by all 9 skills to record usage via `update-skill-tracking.js`.--Skill-specific reference docs (e.g., `skills/setup-datamodel/references/odata-api-patterns.md`) contain only patterns unique to that skill and point to the shared docs via `${CLAUDE_PLUGIN_ROOT}/references/` paths for common content.--### MCP Integration--Playwright MCP server for browser automation and live site previews during development.--## Template System--Framework templates use `__PLACEHOLDER__` tokens (e.g., `__SITE_NAME__`, `__PRIMARY_COLOR__`, `__BG_COLOR__`) that get replaced during site scaffolding. The `gitignore` file is stored without the dot prefix to avoid git interference in the plugin repo — it gets renamed to `.gitignore` during scaffolding.--## Validation Scripts--### `create-site/scripts/validate-site.js`--Checks generated sites for: required files (`package.json`, `.gitignore`, `powerpages.config.json`), config schema fields (`$schema`, `compiledPath`, `siteName`, `defaultLandingPage`), build/dev scripts in package.json, unreplaced `__PLACEHOLDER__` tokens, git initialization, and `src/` directory existence.--### `setup-datamodel/scripts/validate-datamodel.js`--Checks created Dataverse data models by reading `.datamodel-manifest.json` (written by the `setup-datamodel` skill during table creation). Queries the Dataverse OData API to verify each table and column in the manifest actually exists in the environment. Gracefully exits 0 on auth errors (doesn't block if token expired) or when no manifest is found (not a data model session).--### `add-seo/scripts/validate-seo.js`--Checks SEO assets added to Power Pages sites: verifies `robots.txt` exists in `public/` with proper `User-agent` and `Sitemap` directives, `sitemap.xml` exists with `<urlset>` and `<loc>` entries (no unreplaced placeholders), and `index.html` has `meta description` and `viewport` tags. Only runs validation when at least one SEO file (robots.txt or sitemap.xml) is detected — gracefully exits 0 otherwise to avoid blocking non-SEO sessions.+**Server-rendered frameworks (Next.js, Nuxt, Remix, SvelteKit) are NOT supported.**-### `create-webroles/scripts/validate-webroles.js`+Read `PLUGIN_DEVELOPMENT_GUIDE.md` for UX and reliability standards when creating new skills and agents.-Checks that web role YAML files were created in `.powerpages-site/web-roles/`. Validates each file has required `id` and `name` fields and that the `id` field contains a valid UUID v4 format. Gracefully exits 0 when no `.powerpages-site/web-roles/` directory is found (not a web roles session).+## Key Conventions-### `integrate-webapi/scripts/validate-webapi-integration.js`+- **DRY** — Never duplicate logic. Shared scripts live in `scripts/` (e.g., `generate-uuid.js`, `scripts/lib/validation-helpers.js`). Shared reference docs live in `references/`. Always check for existing helpers before writing new code.+- **Validation scripts** must import from `scripts/lib/validation-helpers.js` for boilerplate, path finders, auth helpers, and constants.+- **UUID generation** must use the shared `scripts/generate-uuid.js` — never copy it into skill-specific directories.+- **Reference docs** shared across skills live in `references/` — reference via `${CLAUDE_PLUGIN_ROOT}/references/` paths, don't duplicate.+- **Templates** use `__PLACEHOLDER__` tokens (e.g., `__SITE_NAME__`) replaced during scaffolding. The `gitignore` file is stored without the dot prefix and renamed to `.gitignore` during scaffolding.+- **Hooks** are defined per-skill in SKILL.md frontmatter (not a global hooks.json).-Checks that Web API integration code was created for a Power Pages code site: verifies the shared API client (`src/shared/powerPagesApi.ts` or equivalent) exists, at least one service file exists in `src/shared/services/` or `src/services/` with `/_api/` endpoint references, and corresponding type definition files exist in `src/types/`. Gracefully exits 0 when no integration files are detected (not an integration session).+## Skill Development Conventions-### `setup-auth/scripts/validate-auth.js`--Checks that authentication and authorization code was created: verifies auth service (`src/services/authService.ts` or equivalent) exists with login/logout/getCurrentUser functions and anti-forgery token handling, Power Pages type declarations (`src/types/powerPages.d.ts`) exist, authorization utilities (`src/utils/authorization.ts`) exist, and an auth UI component (AuthButton or equivalent) exists. Gracefully exits 0 when no auth files are detected (not an auth session).--## Skill Development Guide--All skills in this plugin follow a consistent set of patterns. When creating a new skill, follow every convention below to maintain consistency across the plugin.+All skills follow these patterns. See existing skills for examples.### Phase-Wise Workflow-Every skill is structured as a sequence of **phases** (typically 5–8). Each phase has a single, clear goal and an explicit output statement describing what it delivers. Phases execute sequentially — never skip or reorder them.--A typical phase sequence looks like:--1. **Prerequisites / Verify** — Confirm tools, auth, project structure exist-2. **Discover / Gather** — Collect user input, analyze existing code/state-3. **Plan / Review** — Present a plan and get user approval before proceeding-4. **Implement / Create** — Do the actual work (create files, call APIs, scaffold)-5. **Verify** (**mandatory**) — Validate the output: confirm files exist, formats are correct, project builds, UI renders-6. **Deploy / Summarize** — Offer deployment and present a summary with next steps--**Every skill must have a dedicated verification phase.** This is not optional. The verification phase must be a standalone phase (not a substep buried inside another phase) and must appear after the implementation work is complete but before the final review/deploy phase. What verification checks depends on the skill:--- **File-creating skills**: Verify files exist, formats are valid, no unreplaced placeholders, project builds-- **API-calling skills**: Verify records/resources were created by querying them back, present success/failure counts-- **Deployment skills**: Verify deployment artifacts exist (e.g., `.powerpages-site` folder), confirm command output reported success-- **UI-creating skills**: Verify the project builds and the new UI renders correctly via Playwright--### Task Tracking (To Do List)--Every skill uses `TaskCreate`, `TaskUpdate`, and `TaskList` to track progress:--1. **Create all tasks upfront** — At the very start of Phase 1, before any work begins, create one task per phase using `TaskCreate`. The user sees the full scope immediately. Never add tasks incrementally mid-workflow.-2. **Task fields** — Each task must include:- - `subject`: Imperative form (e.g., "Verify prerequisites")- - `activeForm`: Present continuous form shown in spinner (e.g., "Verifying prerequisites")- - `description`: Detailed description of what the phase does and its acceptance criteria-3. **Task lifecycle** — Mark each task `in_progress` via `TaskUpdate` when starting the phase, then `completed` when the phase finishes. Progress through tasks sequentially.-4. **Progress tracking table** — Include a table at the end of the SKILL.md listing all tasks with their `subject`, `activeForm`, and `description` fields. This serves as the reference for task creation.+Every skill is a sequence of phases (typically 5-8): Prerequisites, Discover/Gather, Plan/Review, Implement, **Verify** (mandatory standalone phase), Deploy/Summarize. Never skip or reorder phases.-Example:+### Task Tracking-```-| Task subject | activeForm | Description |-|---|---|---|-| Verify prerequisites | Verifying prerequisites | Confirm PAC CLI auth, acquire Azure CLI token, verify API access |-| Gather configuration | Gathering configuration | Collect user input for site name, options, preferences |-| ... | ... | ... |-```+Create all tasks upfront at Phase 1 start using `TaskCreate` (one per phase). Each task needs `subject` (imperative), `activeForm` (present continuous for spinner), and `description`. Mark `in_progress` when starting, `completed` when done. Include a progress tracking table at the end of the SKILL.md.### SKILL.md Frontmatter-Every SKILL.md starts with YAML frontmatter following this structure:-```yaml----name: <skill-name> # kebab-case identifier-description: >- # User-facing description listing trigger phrases- <when to use this skill and synonym phrases>+name: <skill-name>+description: >-+ <when to use this skill>user-invocable: true-argument-hint: <optional hint> # Describes optional argument the user can pass-allowed-tools: Read, Write, Edit, Bash, Glob, Grep, Task, TaskCreate, TaskUpdate, TaskList, AskUserQuestion # Comma-separated list (not JSON array or YAML list)+argument-hint: <optional>+allowed-tools: Read, Write, Edit, Bash, Glob, Grep, Task, TaskCreate, TaskUpdate, TaskList, AskUserQuestionmodel: opushooks:Stop:@@ -230,87 +45,27 @@ hooks:command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/<skill-name>/scripts/validate-<skill>.js"'timeout: 30- type: prompt- prompt: "<completeness checklist — returns { ok: true } or { ok: false, reason }>"+ prompt: "<completeness checklist>"timeout: 30---```-### User Confirmation at Key Decision Points--Every skill must pause and wait for user input at critical junctures using `AskUserQuestion`. Document these decision points explicitly in the SKILL.md under a **"Key Decision Points (Wait for User)"** section. Common points:--- After gathering requirements — confirm understanding before planning-- After presenting a plan — get approval before implementation-- After implementation — accept results or request changes-- Before deployment — deploy now or later--### Deployment Prompt--Skills that create or modify site artifacts should end with a deployment prompt:--1. Announce completion: "The X has been created/configured locally."-2. Ask via `AskUserQuestion`: "Ready to deploy?" with options: "Yes, deploy now (Recommended)" / "No, I'll deploy later"-3. If "Yes" — invoke the `/power-pages:deploy-site` skill-4. If "No" — remind user: "Run `/power-pages:deploy-site` when ready"-5. Present a summary and suggest next steps--### Validation Hooks (Stop Hooks)--Every skill that creates files must define two Stop hooks in its frontmatter:+Note: `allowed-tools` must be a comma-separated list, not JSON array or YAML list syntax.-1. **Command hook** — A Node.js validation script (`scripts/validate-<skill>.js`) that verifies artifacts were created correctly (files exist, valid format, no unreplaced placeholders). Must import shared boilerplate from `scripts/lib/validation-helpers.js`. Must gracefully exit 0 when the session didn't involve this skill (e.g., no relevant files detected).-2. **Prompt hook** — A completeness checklist that returns `{ ok: true }` or `{ ok: false, reason: "..." }`. Lists 4–6 specific conditions that must all be true for the skill to be considered complete.+### Key Patterns-### Shared Resources (DRY)--Before writing any new logic, check for existing shared utilities and references:--- **Shared references** in `references/` at the plugin root — reuse via `${CLAUDE_PLUGIN_ROOT}/references/` paths-- **Shared scripts** in `scripts/` — e.g., `generate-uuid.js`, `scripts/lib/validation-helpers.js`-- **Skill-specific references** go in `skills/<skill-name>/references/` and must point to shared docs for common content rather than duplicating--### Graceful Failure (No Auto-Rollback)--Skills that make API calls must:--- Track each API call result (success/failure/skipped)-- **Never** attempt automated rollback on failure-- Report failures clearly and continue with remaining items-- Present a summary at the end showing what succeeded and what failed--### Token Refresh for Long Operations--Skills that make repeated Dataverse/API calls must refresh the Azure CLI access token periodically — every ~20 records, 3–4 tables, or ~60 seconds — to avoid expiration mid-workflow.--### Git Commits at Milestones--Skills that create or modify source files must commit after every significant milestone:--- After creating each page or component-- After applying design foundations-- After each phase that modifies files completes--Each commit should be focused with a clear message describing what was added or changed.--### Agent Spawning--Skills that delegate work to agents (via the `Task` tool) must:--- Process agent invocations **sequentially, not in parallel** — the first invocation may create shared files that subsequent ones depend on-- Wait for each agent to complete before invoking the next-- Present agent output to the user for approval before proceeding--## Key Constraint--Only static SPA frameworks are supported (React, Vue, Angular, Astro). Server-rendered frameworks (Next.js, Nuxt, Remix, SvelteKit) are **not** supported.--**DRY (Don't Repeat Yourself):** Never duplicate logic across files. Before writing new code, check for existing shared utilities and patterns:--- **Validation scripts** must import from `scripts/lib/validation-helpers.js` for boilerplate (`approve`, `block`, `runValidation`), path finders (`findPath`, `findProjectRoot`, `findPowerPagesSiteDir`), auth helpers (`getAuthToken`, `getEnvironmentUrl`, `getPacAuthInfo`), and constants (`UUID_REGEX`, `CLOUD_TO_API`). Do not re-implement these in individual scripts.-- **UUID generation** must use the shared `scripts/generate-uuid.js`. Do not copy it into skill-specific `scripts/` directories.-- **Reference docs** shared across skills live in `references/` at the plugin root. Do not duplicate OData patterns, prerequisite steps, or framework conventions in skill-specific files — reference the shared docs via `${CLAUDE_PLUGIN_ROOT}/references/`.-- When adding a new validation script, extend `validation-helpers.js` if the new helper would be useful to other scripts. Keep skill-specific logic in the individual script, shared logic in the library.+- **User confirmation** — Pause with `AskUserQuestion` after gathering requirements, after presenting a plan, after implementation, and before deployment.+- **Deployment prompt** — Skills that modify site artifacts should end by asking "Ready to deploy?" and invoke `/power-pages:deploy-site` if yes.+- **Stop hooks** — Every file-creating skill needs a command hook (validation script) and a prompt hook (completeness checklist).+- **Graceful failure** — Track API call results, never auto-rollback, report failures clearly, continue with remaining items.+- **Token refresh** — Refresh Azure CLI token every ~20 records / 3-4 tables / ~60 seconds.+- **Git commits** — Commit after every significant milestone (each page/component, design foundations, phase completion).+- **Agent spawning** — Process sequentially (not parallel), wait for completion, present output for approval.+- **Skill tracking** — Every skill must record usage in its final phase via `> Reference: ${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md` (pointer pattern, not hardcoded command). When adding a new skill, also add its entry to the skill name mapping table in `references/skill-tracking-reference.md`.+- **Dataverse API calls** — Use deterministic Node.js scripts (in the skill's `scripts/` directory) for Dataverse API queries. Scripts should import `getAuthToken` and `makeRequest` from `scripts/lib/validation-helpers.js`. Never use inline PowerShell `Invoke-RestMethod` for API calls — scripts are more reliable, testable, and cross-platform.## Maintaining This File-When you make significant changes to this plugin (new skills, agents, hooks, templates, or architectural shifts), update this file to keep it accurate for future agents.+Update when plugin structure or conventions change or you learn something which can be useful for new skills or agents.++Keep this file concise — detailed docs belong in `PLUGIN_DEVELOPMENT_GUIDE.md` or individual SKILL.md / agent files.diff --git a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.mdnew file mode 100644index 000000000..d84d33e00--- /dev/null+++ b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md@@ -0,0 +1,403 @@+# Plugin UX & Reliability++## Why This Matters++A plugin can have 18 brilliant skills and still feel broken if the user sits staring at a frozen terminal for 90 seconds, has no way to know if the schema actually deployed, or loses their main conversation context because a long deployment blocked the thread.++Here are **five UX and reliability pillars** that as a quality standard every skill and command must meet before it ships.++---++## The Five Pillars++These five engineering principles address the gap between "the plugin works" and "the plugin feels great to use." Each pillar is a non-negotiable requirement embedded into the acceptance criteria for every skill and command.++### 01 — Engaging Loading Experience++**Pillar 1 — Perception of speed**++Long operations must show structured progress — not silence. The user should always know what's happening, what stage they're in, and roughly how long remains.++### 02 — Action Verification++**Pillar 2 — Trust through proof**++Every action the LLM performs must be verifiable. The agent should confirm what it did, show evidence it worked, and give the user a way to validate independently.++### 03 — Sub-Agent Architecture++**Pillar 3 — Context preservation**++Long-running processes (deployments, schema pushes, test suites) should run as sub-agents in isolated contexts, keeping the main conversation responsive and clean.++### 04 — PAC CLI Determinism++**Pillar 4 — Reliability through determinism**++Deterministic operations (upload, download, deploy, list) should be routed through PAC CLI commands — not generated by the LLM. LLMs compose the intent; PAC CLI executes it.++### 05 — Transparency & User Approval++**Pillar 5 — No surprises, ever**++The plugin must show every action it performs in real time and seek explicit user approval before any destructive, irreversible, or environment-altering operation. The user should never be surprised by what the plugin did.++---++## Pillar 1 — Engaging Loading Experience++### The Problem++When a skill generates a Dataverse schema or deploys a site, the terminal goes quiet for 30–120 seconds. The user doesn't know if it's working, stuck, or crashed. Research on perceived wait time shows that unexplained silence beyond 10 seconds causes users to assume failure — and they interrupt the process, making things worse.++### The Solution++Every skill and command must implement a **structured progress protocol** — a standardized way of reporting what stage the operation is in, what it just completed, and what's next.++**❌ Before — Current behavior**++User runs `/deploy-site`. Terminal shows "Running..." for 87 seconds. No output. User types "is it working?" and interrupts the process.++**✅ After — With progress protocol**++```+▸ Building site (step 1/4) ✓+▸ Validating schema (step 2/4) ✓+▸ Uploading to environment (step 3/4) ◌ in progress...+▸ Activating site (step 4/4) pending+```++### Implementation Pattern++Each skill defines its operation as a sequence of named stages. The skill emits stage transitions as structured console output that the agent can relay to the user.++```+# In every skill's SKILL.md — define the progress contract++## Progress Stages+Every long-running operation MUST print stage markers:++Stage format: [STAGE n/N] Stage name... {status}+Status values: STARTED | DONE | FAILED | SKIPPED++# Example: Schema Generator deploying a schema+[STAGE 1/5] Validating schema definition... DONE (0.8s)+[STAGE 2/5] Checking for existing tables... DONE (2.1s)+[STAGE 3/5] Creating 4 tables in Dataverse... DONE (12.3s)+[STAGE 4/5] Configuring relationships... DONE (3.7s)+[STAGE 5/5] Generating table permissions... DONE (1.2s)+✓ Schema deployed: 4 tables, 23 columns, 6 relationships (20.1s total)+```++### What This Means for Each Phase++| Phase | Operations That Need Progress | Typical Duration |+|-------|-------------------------------|-----------------|+| **P1** | Schema push, permission deployment, Web API generation | 15–60s |+| **P2** | Accessibility scan (full site), SEO audit | 20–45s |+| **P3** | Server Logic deployment, Power Automate flow creation | 30–90s |+| **P4** | Power BI embed config, SharePoint connection setup | 20–60s |+| **P5** | Knowledge index build, AI model configuration | 30–120s |+| **P6** | Compliance scan, CI/CD pipeline generation, full site deploy | 45–180s |++> **Acceptance criterion:** No operation that takes longer than 10 seconds may ship without implementing the stage progress protocol. This is enforced in the PR checklist.++---++## Pillar 2 — Action Verification++### The Problem++The LLM says "I've created 4 tables in Dataverse" — but did it? The user has no way to verify without opening the maker portal and checking manually. This erodes trust. In regulated environments (the Sovereign Cloud use case), unverifiable actions are a non-starter.++### The Solution++Every mutating action must follow a **Do → Verify → Report** cycle. The agent performs the action, then runs an independent verification step to confirm it succeeded, then reports the verified result with evidence.++**❌ Before — Trust the LLM**++Agent: "I've created the Contact table with 8 columns and configured Read permissions for the Customer web role."++*User has no way to verify this without opening the maker portal.*++**✅ After — Verify and prove**++Agent: "I've created the Contact table. Let me verify..."++- `pac pages list` → confirms site exists+- `Dataverse query` → confirms 8 columns present+- `Permission check` → confirms Customer role has Read access++**✓ Verified:** Contact table (8 cols), Customer role (Read). [View in maker portal →]++### The Verification Pattern++```python+# Every skill that modifies state must implement this pattern:++## Verification Protocol++# Step 1: Execute the action+execute_action() # e.g., create tables via Dataverse API++# Step 2: Independently verify the result+verify_result() # e.g., query Dataverse to confirm tables exist++# Step 3: Report with evidence+report_with_evidence()+# - What was requested+# - What was done+# - Verification result (pass/fail)+# - Link to view in maker portal / admin center+# - Rollback instructions if something is wrong+```++### Verification Methods by Phase++| Phase | Action | Verification Method |+|-------|--------|-------------------|+| **P1** | Schema creation | Query Dataverse metadata API to confirm tables, columns, and relationships match spec |+| **P1** | Table permissions | Read back permissions via Web API and compare against intended configuration |+| **P2** | Accessibility fixes | Re-run axe-core scan and confirm issue count reduced to zero |+| **P3** | Server Logic deploy | Invoke the endpoint with a test payload and confirm expected response |+| **P3** | Power Automate flow | Trigger a test run and verify flow execution history shows success |+| **P4** | Power BI embed | Fetch embed token and verify report renders (HTTP 200 from embed URL) |+| **P6** | Site deployment | `pac pages list` confirms site is active; HTTP GET to site URL returns 200 |+| **P6** | Compliance config | Scan response headers for CSP, HSTS, cookie flags; compare against template |++> **Acceptance criterion:** No skill that creates, modifies, or deletes Dataverse data, site configuration, or deployment state may ship without an automated verification step. The verification must use a different code path than the action itself (e.g., don't verify a create by reading the create response — query independently).++---++## Pillar 3 — Sub-Agent Architecture++### The Problem++Long-running operations (site deployment, full accessibility scan, schema migration) block the main conversation. The user can't ask questions, adjust parameters, or start a new task while waiting. Additionally, complex operations pollute the main context window with implementation details the user doesn't need to see.++### The Solution++Use Claude Code's native sub-agent system to offload long-running and context-heavy operations to isolated sub-agents. The main conversation stays responsive. The sub-agent runs with its own context, specific tool permissions, and reports back a clean summary when done.++### Sub-Agent Definitions for the Plugin++The plugin should ship with purpose-built sub-agents for each category of long-running work:++| Sub-Agent | Triggers On | Tools Allowed | Model | Reports Back |+|-----------|-------------|---------------|-------|-------------|+| **deploy-agent** | Site upload, code-site push, activation | `Bash(pac *), Read, Write` | sonnet | Deploy status, site URL, any errors |+| **schema-agent** | Dataverse schema creation, migration | `Bash(pac *), Read, Write, WebFetch` | sonnet | Tables created, columns, relationships, verification result |+| **audit-agent** | Accessibility scan, security audit, metadata validation, compliance check | `Read, Grep, Glob, Bash(npx axe-core *)` | sonnet | Issue count, severity breakdown, auto-fix suggestions |+| **integration-agent** | Power BI embed setup, SharePoint connection, Copilot Studio agent creation | `Bash(pac *), Read, Write, WebFetch` | sonnet | Integration status, config summary, verification result |+| **pipeline-agent** | CI/CD pipeline generation, environment migration | `Read, Write, Bash(git *), Bash(az *)` | sonnet | Pipeline file paths, test run results |++### Example Sub-Agent Definition++```markdown+# .claude/agents/deploy-agent.md+---+name: deploy-agent+description: Handles Power Pages site deployments, uploads,+ and activations as a background process.+tools: Bash, Read, Write+model: sonnet+---++# You are a Power Pages deployment specialist.++## Protocol+1. Print [STAGE n/N] markers for every step+2. Use `pac pages upload-code-site` for all uploads+3. After upload, verify with `pac pages list`+4. After activation, HTTP GET the site URL to confirm 200+5. Report back: site URL, deploy time, verification status+6. If any step fails, report the error and suggest recovery steps++## Constraints+- NEVER modify source code — only deploy what exists+- ALWAYS use PAC CLI for deterministic operations+- ALWAYS verify after every mutating action+```++### When to Delegate vs. Inline++| Operation | Expected Duration | Approach | Rationale |+|-----------|------------------|----------|-----------|+| Generate a React component | <5s | Inline (main agent) | Fast, context-relevant, user wants to see output |+| Deploy site to environment | 30–120s | **Sub-agent** | Long, deterministic, blocks conversation |+| Full accessibility audit | 20–60s | **Sub-agent** | Generates large output that pollutes main context |+| Create a single table | 5–15s | Inline with progress | Short enough to inline, but needs progress indicator |+| Schema migration (10+ tables) | 60–180s | **Sub-agent** | Complex, long, lots of intermediate output |+| Generate CI/CD pipeline files | <10s | Inline | File generation is fast; only deploy is long |+| Run CI/CD pipeline | 120–300s | **Sub-agent** | Very long; user should be free to work on other tasks |++> **Acceptance criterion:** Any operation expected to take longer than 30 seconds must be implemented as a sub-agent with its own context. The sub-agent must follow the progress protocol (Pillar 1) and verification protocol (Pillar 2).++---++## Pillar 4 — PAC CLI Determinism++### The Problem++LLMs are probabilistic. They are excellent at generating code, composing configurations, and reasoning about architecture. They are unreliable at executing the same API call identically every time. When an LLM constructs and executes a Dataverse REST API call directly, minor variations in URL encoding, header formatting, or parameter ordering can cause intermittent failures that are extremely hard to debug.++### The Principle++**LLMs compose. PAC CLI executes.** The LLM's job is to determine *what* needs to happen (intent). The PAC CLI's job is to *make it happen* (execution). This separation creates a deterministic execution layer that produces the same result every time, regardless of LLM temperature or token sampling.++**❌ Before — LLM as executor**++LLM constructs a raw HTTP POST to the Dataverse Web API with hand-assembled JSON body, manually constructed URL, and custom auth headers. Works 90% of the time. The other 10% fails silently or produces inconsistent results.++**✅ After — LLM as composer, PAC CLI as executor**++LLM determines: "Need to upload code site from ./build to 'Contoso Portal'."++Emits: `pac pages upload-code-site --rootPath "./src" --compiledPath "./build" --siteName "Contoso Portal"`++PAC CLI handles auth, URL construction, retries, and error formatting deterministically. Works 100% of the time.++### Determinism Classification++Every operation in the plugin should be classified as either **deterministic** (use PAC CLI or scripts) or **generative** (LLM-appropriate). This classification must be documented in the skill's SKILL.md.++| Operation Type | Classification | Execute With | Examples |+|---------------|---------------|-------------|----------|+| Site upload / download | ✅ Deterministic | `pac pages upload-code-site` / `pac pages download-code-site` | Deploy, download site content |+| Site listing / status | ✅ Deterministic | `pac pages list` | Check if site exists, get site ID |+| Auth profile management | ✅ Deterministic | `pac auth create` / `pac auth list` | Environment connection |+| Solution management | ✅ Deterministic | `pac solution export` / `pac solution import` | Environment promotion |+| Bootstrap migration | ✅ Deterministic | `pac pages bootstrap-migrate` | V3 to V5 migration |+| Code generation (React, TS) | 🔵 Generative | LLM | Components, services, config files |+| Schema design (table/column decisions) | 🔵 Generative | LLM | Deciding which tables, columns, relationships to create |+| Architecture recommendations | 🔵 Generative | LLM | Security model design, component architecture |+| Schema execution (creating tables) | 🟡 Hybrid | LLM composes → script executes | LLM generates the schema JSON; a deterministic script pushes it to Dataverse via API |+| Compliance header configuration | 🟡 Hybrid | LLM composes → template applies | LLM selects the template (GDPR, FedRAMP); a deterministic script applies it |++> **Acceptance criterion:** Every skill's SKILL.md must include a "Determinism Classification" section that lists each operation and whether it's deterministic, generative, or hybrid. Deterministic operations must use PAC CLI or pre-tested scripts. No skill may use LLM-generated raw API calls for operations that have a PAC CLI equivalent.++---++## Pillar 5 — Transparency & User Approval++### The Problem++An agent that silently creates 6 Dataverse tables, modifies security roles, and deploys to production — all from a single prompt — is terrifying in an enterprise context. Even if every action succeeds, the user didn't see what happened, didn't consent to each step, and can't explain to their team or compliance officer what the plugin did on their behalf. Opacity destroys trust faster than any bug.++### The Principle++**Show everything. Ask before anything irreversible.** The plugin must operate with radical transparency: every action is logged, every decision is explained, and every destructive or environment-altering operation requires explicit user confirmation before execution.++### The Three Transparency Layers++**Layer 1 — Action Log (always on)**++Every action the plugin performs must be printed to the console in real time. Not just the result — the action itself. The user should be able to read the log and reconstruct exactly what happened, in what order, and why.++**❌ Before — Black box**++```+Agent: "Done! Your Customer Service portal is ready."+```++*The user has no idea what was created, configured, or deployed.*++**✅ After — Full action log**++```+📋 Action Log:+ 1. Created table: Contact (8 columns)+ 2. Created table: Case (12 columns)+ 3. Created table: Knowledge Article (6 columns)+ 4. Set relationship: Contact → Case (1:N)+ 5. Set relationship: Case → Knowledge Article (N:N)+ 6. Created web role: Customer (scope: Contact)+ 7. Created table permission: Contact (Read, Create) → Customer role+ 8. Created table permission: Case (Read, Create) → Customer role+ 9. Generated React components: ContactList, CaseForm, KBSearch+ 10. Deployed to: https://contoso-portal.powerappsportals.com++✓ 10 actions completed. 0 errors.+```++**Layer 2 — Decision Explanation (for non-obvious choices)**++When the plugin makes a design decision that the user didn't explicitly request, it must explain *why*. This is especially important for security-related defaults.++```+ℹ️ Decision: Set Contact table permission to Read + Create only+ (not Update or Delete).+ Reason: Customer-facing portals should follow least-privilege.+ Customers can view their own contacts and create new ones,+ but cannot modify or delete existing records.+ Override: Add --permissions "Read,Create,Update,Delete" to+ grant full CRUD.+```++**Layer 3 — Approval Gates (for irreversible or high-impact actions)**++Certain actions must pause and ask for explicit user confirmation before proceeding. The plugin must never assume consent for destructive operations.++### Actions That Require Approval++| Action Category | Examples | Why Approval Is Needed |+|----------------|----------|----------------------|+| **Destructive operations** | Delete table, drop column, remove web role, clear site data | Data loss is irreversible |+| **Production deployment** | `pac pages upload-code-site` to a production environment | Affects live users immediately |+| **Security configuration** | Create or modify table permissions, change web role scope, modify CSP headers | Misconfiguration = data exposure |+| **Schema migration** | Add/remove columns on tables with existing data, change column types | May cause data truncation or loss |+| **External service connection** | Connect Power BI workspace, link SharePoint site, create Copilot Studio agent | Grants cross-service access |+| **Compliance-critical changes** | Modify GDPR/FedRAMP/HIPAA configuration, change cookie consent settings | Regulatory implications |++### The Approval Protocol++```+# Before any approval-gated action, the plugin must:++## Step 1: Announce intent+⚠️ I'm about to: Deploy site code to PRODUCTION environment+ Target: https://contoso-portal.powerappsportals.com+ Changes: 3 new components, 2 modified pages, 1 new Server Logic handler++## Step 2: Show impact summary+ Impact:+ - 3 new React components will be added (ContactList, CaseForm, KBSearch)+ - 2 existing pages will be overwritten (Home, Support)+ - 1 Server Logic handler will go live (case-validation)+ - Estimated downtime: none (hot deploy)++## Step 3: Request explicit approval+ Proceed? [Y/n]++## Step 4: Log the approval+ ✓ User approved deployment at 2026-03-15T14:32:07Z+```++### Transparency Levels by Context++Not every action needs the same level of transparency. The plugin should scale its transparency to the risk level of the operation:++| Context | Action Log | Decision Explanation | Approval Gate |+|---------|-----------|---------------------|--------------|+| **Local file generation** (components, configs) | ✅ Show files created | ❌ Not needed | ❌ Not needed |+| **Local analysis** (accessibility scan, SEO audit) | ✅ Show scan progress | ✅ Explain flagged issues | ❌ Not needed |+| **Dev environment changes** (schema push, permission config) | ✅ Full action log | ✅ Explain security defaults | ⚠️ Prompt for confirmation |+| **Production deployment** | ✅ Full action log | ✅ Explain all changes | ✅ **Mandatory approval** |+| **Destructive operations** (delete, drop, clear) | ✅ Full action log | ✅ Explain consequences | ✅ **Mandatory approval** |+| **Security / compliance changes** | ✅ Full action log | ✅ Explain regulatory impact | ✅ **Mandatory approval** |++### Undo & Rollback Visibility++When an action supports rollback, the plugin must tell the user how to undo it — immediately after the action completes, not buried in documentation.++```+✓ Deployed 3 components to production.++↩️ To rollback: Run /rollback-deploy --timestamp 2026-03-15T14:32:07Z+ This will restore the previous site state from the auto-backup+ created before deployment.+```++> **Acceptance criterion:** Every skill must implement Layer 1 (action log) for all operations. Skills that modify environment state must implement Layer 2 (decision explanation) for non-obvious defaults. Skills that perform destructive, production, security, or compliance operations must implement Layer 3 (approval gate). No approval-gated action may proceed without explicit user confirmation.++---diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex bf698539a..7f97005d3 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -89,7 +89,7 @@ Populates your Dataverse tables with realistic, contextually appropriate recordsOrchestrates the full Web API integration lifecycle — from analyzing your site's code to identify where data is needed, through generating typed API code for each table, to configuring table permissions and site settings so the APIs work in production.-The skill first scans your codebase to find components using mock data, placeholder fetch calls, or hardcoded arrays, then maps them to your Dataverse tables. It processes each table sequentially, spawning a dedicated **Web API Integration** agent that creates the integration code. After all tables are wired up, a **Web API Permissions Architect** agent analyzes your site and proposes table permissions and site settings — or you can upload your own permissions diagram instead.+The skill first scans your codebase to find components using mock data, placeholder fetch calls, or hardcoded arrays, then maps them to your Dataverse tables. It processes each table sequentially, spawning a dedicated **Web API Integration** agent that creates the integration code. After all tables are wired up, a **Table Permissions** agent proposes CRUD permissions and scopes, and a **Web API Settings** agent proposes site settings with case-sensitive validated column names queried directly from Dataverse — or you can upload your own permissions diagram instead.**What gets created:**@@ -137,15 +137,16 @@ Adds search engine optimization artifacts: `robots.txt`, `sitemap.xml`, and meta## Agents-The plugin includes 3 specialized agents that are spawned automatically by skills when needed:+The plugin includes 4 specialized agents that are spawned automatically by skills when needed:| Agent | Purpose | Triggered by ||---|---|---|| **Data Model Architect** | Analyzes your site and proposes a Dataverse data model with an ER diagram | `/setup-datamodel` || **Web API Integration** | Creates typed API client, services, and hooks for a Dataverse table | `/integrate-webapi` |-| **Web API Permissions** | Proposes table permissions and site settings for Web API access | `/integrate-webapi` |+| **Table Permissions** | Proposes table permissions (web roles, CRUD flags, scopes) with a visual Mermaid diagram | `/integrate-webapi` |+| **Web API Settings** | Proposes Web API site settings with case-sensitive validated column names from Dataverse | `/integrate-webapi` |-The Data Model Architect and Web API Permissions agents are **read-only** — they analyze and propose but never create or modify resources directly. You review and approve their proposals before any changes are made.+The Data Model Architect, Table Permissions, and Web API Settings agents are **read-only** — they analyze and propose but never create or modify resources directly. You review and approve their proposals before any changes are made.## Typical Workflowdiff --git a/plugins/power-pages/agents/assets/data-model-plan.html b/plugins/power-pages/agents/assets/data-model-plan.htmlnew file mode 100644index 000000000..5a99dff59--- /dev/null+++ b/plugins/power-pages/agents/assets/data-model-plan.html@@ -0,0 +1,361 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8"/>+<meta name="viewport" content="width=device-width,initial-scale=1.0"/>+<title>Data Model Plan — __SITE_NAME__</title>+<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>+<style>+:root {+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --surface3:#edebe9;+ --border:#e1dfdd; --border-light:#c8c6c4;+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e;+ --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;+ --critical:#d13438; --critical-bg:#d134380a; --critical-border:#d1343820;+ --high:#ca5010; --high-bg:#ca50100a; --high-border:#ca501020;+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1020;+ --purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b820;+ --mono:'Cascadia Code','Consolas',monospace;+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;+ --radius:8px; --radius-sm:4px;+ --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);+ --shadow-8:0 3.2px 7.2px 0 rgba(0,0,0,0.132),0 0.6px 1.8px 0 rgba(0,0,0,0.108);+ --shadow-16:0 6.4px 14.4px 0 rgba(0,0,0,0.132),0 1.2px 3.6px 0 rgba(0,0,0,0.108);+}+*{margin:0;padding:0;box-sizing:border-box;}+html{scroll-behavior:smooth;}+body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;}+++/* Top Bar */+.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;}+.topbar-left{display:flex;align-items:center;gap:14px;}+.logo{width:36px;height:36px;border-radius:var(--radius);background:linear-gradient(135deg,#0078d4,#5c2d91);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:800;color:#fff;font-family:var(--mono);letter-spacing:-0.5px;}+.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}+.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;}++/* Layout */+.layout{display:flex;min-height:calc(100vh - 65px);}++/* Sidebar */+.sidebar{width:200px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}+.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;}+.nav-btn:hover{color:var(--text);background:var(--surface2);}+.nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}+.nav-btn .nav-icon{font-size:15px;opacity:0.5;width:18px;text-align:center;}+.nav-btn.active .nav-icon{opacity:0.9;}++/* Content */+.content{flex:1;padding:32px 40px;max-width:960px;}+.section{display:none;}+.section.active{display:block;animation:fadeIn 0.3s ease;}+@keyframes fadeIn{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}++h2{font-size:21px;font-weight:800;color:var(--text-bright);letter-spacing:-0.3px;margin-bottom:5px;}+.section-desc{font-size:13px;color:var(--text-dim);margin-bottom:20px;}+.section-desc code{color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;font-family:var(--mono);font-size:12px;}+h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margin-bottom:12px;}++/* Cards */+.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:10px;transition:box-shadow 0.2s,border-color 0.2s;}+.card:hover{box-shadow:var(--shadow-4);}++/* Stats Grid */+.stats-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:24px;}+.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;position:relative;overflow:hidden;box-shadow:var(--shadow-4);}+.stat-card::after{content:'';position:absolute;top:0;left:50%;transform:translateX(-50%);width:40px;height:2px;border-radius:0 0 2px 2px;}+.stat-card:nth-child(1)::after{background:var(--pass);}+.stat-card:nth-child(2)::after{background:var(--high);}+.stat-card:nth-child(3)::after{background:var(--accent);}+.stat-num{font-size:30px;font-weight:800;font-family:var(--mono);line-height:1;}+.stat-label{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-top:6px;}++/* Summary Box */+.summary-box{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:22px;margin-bottom:22px;font-size:14px;color:var(--text);line-height:1.75;}++/* Prefix Box */+.prefix-box{display:inline-flex;align-items:center;gap:8px;background:var(--surface);border:1px solid var(--accent-border);border-radius:var(--radius);padding:8px 16px;margin-bottom:20px;}+.prefix-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;}+.prefix-value{font-size:16px;font-weight:800;font-family:var(--mono);color:var(--accent);}++/* Principles / Rationale */+.principle{display:flex;gap:16px;padding:16px 0;border-bottom:1px solid var(--border);}+.principle:last-child{border-bottom:none;}+.principle-icon{font-size:22px;flex-shrink:0;margin-top:2px;}+.principle-title{font-size:13px;font-weight:700;color:var(--text-bright);margin-bottom:3px;}+.principle-desc{font-size:13px;color:var(--text-dim);line-height:1.65;}++/* Status Tags */+.status-tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:3px;font-family:var(--mono);display:inline-block;text-align:center;min-width:58px;text-transform:uppercase;letter-spacing:0.5px;}+.status-new{color:var(--accent);background:var(--accent-bg);border:1px solid var(--accent-border);}+.status-modified{color:var(--high);background:var(--high-bg);border:1px solid var(--high-border);}+.status-reused{color:var(--pass);background:var(--pass-bg);border:1px solid var(--pass-border);}++/* Key badge */+.key-badge{font-size:9px;font-weight:700;padding:1px 5px;border-radius:3px;font-family:var(--mono);}+.key-PK{color:var(--accent);background:var(--accent-bg);}+.key-FK{color:var(--purple);background:var(--purple-bg);}++/* Column type chip */+.type-chip{font-size:10px;font-family:var(--mono);color:var(--text-dim);background:var(--surface2);padding:1px 6px;border-radius:3px;border:1px solid var(--border);}++/* Required dot */+.req-dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--critical);margin-right:2px;vertical-align:middle;}++/* Field label */+.field-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:2px;}++/* Expandable */+.expandable-header{display:flex;align-items:center;gap:10px;cursor:pointer;-webkit-user-select:none;user-select:none;padding:11px 14px;border-radius:var(--radius-sm);}+.expandable-header:hover{background:var(--surface2);}+.expand-chevron{color:var(--text-dim);font-size:12px;transition:transform 0.2s;flex-shrink:0;}+.expanded .expand-chevron{transform:rotate(90deg);}+.expandable-body{display:none;padding:0 14px 14px;border-top:1px solid var(--border);margin-top:4px;}+.expanded .expandable-body{display:block;animation:fadeIn 0.2s ease;}++/* Columns table */+.col-table{width:100%;border-collapse:collapse;font-size:12px;margin-top:8px;}+.col-table th{text-align:left;font-size:10px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;padding:6px 8px;border-bottom:2px solid var(--border);background:var(--surface2);}+.col-table td{padding:6px 8px;border-bottom:1px solid var(--border);vertical-align:middle;}+.col-table tr:last-child td{border-bottom:none;}+.col-table tr:hover td{background:var(--surface2);}+.col-table .col-logical{font-family:var(--mono);font-size:11px;color:var(--text-bright);}+.col-table .col-display{color:var(--text);font-weight:500;}+.col-table .col-new{background:var(--accent-bg);}++/* Relationship chips */+.rel-chip{display:inline-flex;align-items:center;gap:6px;font-size:11px;padding:4px 10px;border-radius:4px;background:var(--surface2);border:1px solid var(--border);margin-right:6px;margin-bottom:4px;}+.rel-arrow{color:var(--accent);font-weight:700;font-family:var(--mono);}++/* ER Diagram */+.er-container{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:32px;min-height:400px;display:flex;justify-content:center;align-items:flex-start;}+.er-container .mermaid svg{max-width:100%;height:auto !important;}++/* Responsive */+@media(max-width:768px){+ .sidebar{display:none;}+ .content{padding:20px 16px;}+ .stats-grid{grid-template-columns:1fr;}+}+</style>+</head>+<body>++<div id="mainApp">+ <!-- Top Bar -->+ <div class="topbar">+ <div class="topbar-left">+ <div class="logo">PP</div>+ <div>+ <div class="topbar-title">Data Model Plan</div>+ <div class="topbar-sub">__SITE_NAME__</div>+ </div>+ </div>+ </div>++ <div class="layout">+ <!-- Sidebar -->+ <div class="sidebar">+ <button class="nav-btn active" data-tab="overview"><span class="nav-icon">◉</span> Overview</button>+ <button class="nav-btn" data-tab="tables"><span class="nav-icon">▦</span> Tables</button>+ <button class="nav-btn" data-tab="diagram"><span class="nav-icon">◈</span> ER Diagram</button>+ </div>++ <!-- Content -->+ <div class="content">++ <!-- OVERVIEW -->+ <div class="section active" id="tab-overview">+ <h2>Plan Overview</h2>+ <p class="section-desc">Data model architecture for <code>__SITE_NAME__</code></p>++ <div class="summary-box" id="summaryBox">__SUMMARY__</div>++ <div class="prefix-box">+ <span class="prefix-label">Publisher Prefix</span>+ <span class="prefix-value" id="prefixValue"></span>+ </div>++ <div class="stats-grid">+ <div class="stat-card"><div class="stat-num" style="color:var(--pass)" id="statNew">0</div><div class="stat-label">New Tables</div></div>+ <div class="stat-card"><div class="stat-num" style="color:var(--high)" id="statModified">0</div><div class="stat-label">Modified Tables</div></div>+ <div class="stat-card"><div class="stat-num" style="color:var(--accent)" id="statReused">0</div><div class="stat-label">Reused Tables</div></div>+ </div>++ <h3>Design Rationale</h3>+ <div id="rationaleContainer"></div>+ </div>++ <!-- TABLES -->+ <div class="section" id="tab-tables">+ <h2>Tables</h2>+ <p class="section-desc" id="tablesDesc"></p>+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:8px;">+ <div style="display:flex;gap:6px;flex-wrap:wrap;">+ <span class="status-tag status-new">New</span>+ <span class="status-tag status-modified">Modified</span>+ <span class="status-tag status-reused">Reused</span>+ </div>+ <button id="expandAllBtn" onclick="toggleExpandAll()" style="padding:5px 12px;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface);color:var(--text-dim);font-size:12px;font-weight:600;cursor:pointer;font-family:var(--sans);transition:all 0.15s;">Expand All</button>+ </div>+ <div id="tablesContainer"></div>+ </div>++ <!-- ER DIAGRAM -->+ <div class="section" id="tab-diagram">+ <h2>ER Diagram</h2>+ <p class="section-desc">Entity-relationship diagram showing all tables and their relationships</p>+ <div class="er-container" id="erDiagram"></div>+ </div>++ </div>+ </div>+</div>++<script>+// Data is populated by the data-model-architect agent+const SITE_NAME = "__SITE_NAME__";+const PREFIX = "__PREFIX__";++const TABLES = __TABLES_DATA__;+// Each table: { id, logicalName, displayName, status ("new"|"modified"|"reused"), rationale, columns: [{ logicalName, displayName, type, required, key ("PK"|"FK"|null), isNew }], relationships: [{ description, relatedTable, type, foreignKey }] }++const RATIONALE = __RATIONALE_DATA__;+// Array of { icon, title, desc }++const ER_DIAGRAM = __ER_DIAGRAM__;+// Mermaid erDiagram code as a string++// Tab navigation+document.querySelectorAll('.nav-btn').forEach(btn => {+ btn.addEventListener('click', () => {+ document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));+ btn.classList.add('active');+ document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));+ document.getElementById('tab-' + btn.dataset.tab).classList.add('active');+ });+});++const statusColors = {+ new: 'var(--accent)', modified: 'var(--high)', reused: 'var(--pass)'+};+const statusBorderColors = {+ new: 'var(--accent-border)', modified: 'var(--high-border)', reused: 'var(--pass-border)'+};++// Stats+document.getElementById('prefixValue').textContent = PREFIX || '—';+document.getElementById('statNew').textContent = TABLES.filter(t => t.status === 'new').length;+document.getElementById('statModified').textContent = TABLES.filter(t => t.status === 'modified').length;+document.getElementById('statReused').textContent = TABLES.filter(t => t.status === 'reused').length;++const totalColumns = TABLES.reduce((sum, t) => sum + (t.columns ? t.columns.length : 0), 0);+const totalRelationships = TABLES.reduce((sum, t) => sum + (t.relationships ? t.relationships.length : 0), 0);+document.getElementById('tablesDesc').textContent =+ TABLES.length + ' table' + (TABLES.length !== 1 ? 's' : '') ++ ', ' + totalColumns + ' column' + (totalColumns !== 1 ? 's' : '') ++ ', ' + totalRelationships + ' relationship' + (totalRelationships !== 1 ? 's' : '') + '.';++// Render Rationale+function renderRationale() {+ const c = document.getElementById('rationaleContainer');+ let html = '';+ RATIONALE.forEach(r => {+ html += `<div class="principle">+ <div class="principle-icon">${r.icon}</div>+ <div>+ <div class="principle-title">${r.title}</div>+ <div class="principle-desc">${r.desc}</div>+ </div>+ </div>`;+ });+ c.innerHTML = html;+}++// Render Tables+function renderTables() {+ const c = document.getElementById('tablesContainer');+ let html = '';+ const order = { new: 0, modified: 1, reused: 2 };+ const sorted = [...TABLES].sort((a, b) => (order[a.status] ?? 3) - (order[b.status] ?? 3));+ sorted.forEach(t => {+ const statusClass = 'status-' + t.status;+ const bgStyle = t.status === 'new' ? 'background:var(--accent-bg);border-color:var(--accent-border);' : t.status === 'modified' ? 'background:var(--high-bg);border-color:var(--high-border);' : '';++ // Columns table+ let colHtml = '';+ if (t.columns && t.columns.length > 0) {+ colHtml = `<div style="margin-top:12px;"><div class="field-label">Columns</div>+ <table class="col-table">+ <thead><tr><th></th><th>Logical Name</th><th>Display Name</th><th>Type</th><th>Required</th></tr></thead>+ <tbody>${t.columns.map(col => `<tr class="${col.isNew ? 'col-new' : ''}">+ <td>${col.key ? `<span class="key-badge key-${col.key}">${col.key}</span>` : ''}</td>+ <td class="col-logical">${col.logicalName}</td>+ <td class="col-display">${col.displayName}</td>+ <td><span class="type-chip">${col.type}</span></td>+ <td>${col.required ? '<span class="req-dot"></span> Yes' : '<span style="color:var(--text-dim)">No</span>'}</td>+ </tr>`).join('')}</tbody>+ </table></div>`;+ }++ // Relationships+ let relHtml = '';+ if (t.relationships && t.relationships.length > 0) {+ relHtml = `<div style="margin-top:12px;"><div class="field-label">Relationships</div>+ <div style="margin-top:4px;">${t.relationships.map(r =>+ `<div class="rel-chip"><span class="rel-arrow">${r.type || '1:N'}</span> ${r.description}${r.foreignKey ? ` <code style="font-size:10px;color:var(--accent);background:var(--accent-bg);padding:0 4px;border-radius:2px;">${r.foreignKey}</code>` : ''}</div>`+ ).join('')}</div></div>`;+ }++ // Rationale+ let ratHtml = '';+ if (t.rationale) {+ ratHtml = `<div style="margin-top:12px;"><div class="field-label">Rationale</div>+ <div style="font-size:12px;color:var(--text);background:var(--surface2);padding:10px 14px;border-radius:var(--radius-sm);border-left:2px solid ${statusColors[t.status]};line-height:1.7;margin-top:4px;">${t.rationale}</div></div>`;+ }++ html += `<div class="card" style="border-left:3px solid ${statusColors[t.status]};padding:0;${bgStyle}">+ <div class="expandable-header" onclick="this.parentElement.classList.toggle('expanded')">+ <span class="status-tag ${statusClass}">${t.status}</span>+ <span style="font-size:13px;font-weight:600;color:var(--text-bright);flex:1;">${t.displayName}</span>+ <code style="font-size:11px;color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;border:1px solid var(--accent-border);">${t.logicalName}</code>+ <span style="font-size:11px;color:var(--text-dim);">${t.columns ? t.columns.length : 0} cols</span>+ <span class="expand-chevron">▶</span>+ </div>+ <div class="expandable-body">+ ${colHtml}+ ${relHtml}+ ${ratHtml}+ </div>+ </div>`;+ });+ c.innerHTML = html;+}++// Expand All toggle+let allExpanded = false;+function toggleExpandAll() {+ allExpanded = !allExpanded;+ const cards = document.querySelectorAll('#tablesContainer .card');+ cards.forEach(card => {+ if (allExpanded) card.classList.add('expanded');+ else card.classList.remove('expanded');+ });+ document.getElementById('expandAllBtn').textContent = allExpanded ? 'Collapse All' : 'Expand All';+}++// Init+mermaid.initialize({ startOnLoad: false, theme: 'default', er: { fontSize: 16, useMaxWidth: false } });+renderRationale();+renderTables();++// Render ER diagram using mermaid.render() to avoid DOM parsing issues+mermaid.render('erDiagramSvg', ER_DIAGRAM).then(({ svg }) => {+ document.getElementById('erDiagram').innerHTML = svg;+}).catch(() => {+ document.getElementById('erDiagram').innerHTML = '<pre style="color:var(--text-dim);font-family:var(--mono);font-size:12px;white-space:pre-wrap;">' + ER_DIAGRAM.replace(/</g, '<') + '</pre>';+});+</script>+<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;">AI-generated content may be incorrect</footer>+</body>+</html>diff --git a/plugins/power-pages/agents/assets/permissions-plan.html b/plugins/power-pages/agents/assets/permissions-plan.htmlnew file mode 100644index 000000000..bfebe087b--- /dev/null+++ b/plugins/power-pages/agents/assets/permissions-plan.html@@ -0,0 +1,385 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8"/>+<meta name="viewport" content="width=device-width,initial-scale=1.0"/>+<title>Table Permissions Plan — __SITE_NAME__</title>+<style>+:root {+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --surface3:#edebe9;+ --border:#e1dfdd; --border-light:#c8c6c4;+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e;+ --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;+ --critical:#d13438; --critical-bg:#d134380a; --critical-border:#d1343820;+ --high:#ca5010; --high-bg:#ca50100a; --high-border:#ca501020;+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1020;+ --purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b820;+ --mono:'Cascadia Code','Consolas',monospace;+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;+ --radius:8px; --radius-sm:4px;+ --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);+ --shadow-8:0 3.2px 7.2px 0 rgba(0,0,0,0.132),0 0.6px 1.8px 0 rgba(0,0,0,0.108);+ --shadow-16:0 6.4px 14.4px 0 rgba(0,0,0,0.132),0 1.2px 3.6px 0 rgba(0,0,0,0.108);+}+*{margin:0;padding:0;box-sizing:border-box;}+html{scroll-behavior:smooth;}+body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;}+++/* Top Bar */+.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;}+.topbar-left{display:flex;align-items:center;gap:14px;}+.logo{width:36px;height:36px;border-radius:var(--radius);background:linear-gradient(135deg,#0078d4,#5c2d91);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:800;color:#fff;font-family:var(--mono);letter-spacing:-0.5px;}+.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}+.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;}++/* Layout */+.layout{display:flex;min-height:calc(100vh - 65px);}++/* Sidebar */+.sidebar{width:200px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}+.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;}+.nav-btn:hover{color:var(--text);background:var(--surface2);}+.nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}+.nav-btn .nav-icon{font-size:15px;opacity:0.5;width:18px;text-align:center;}+.nav-btn.active .nav-icon{opacity:0.9;}+.nav-badge{position:absolute;right:14px;font-size:10px;font-family:var(--mono);padding:1px 6px;border-radius:8px;font-weight:700;}++/* Content */+.content{flex:1;padding:32px 40px;max-width:900px;}+.section{display:none;}+.section.active{display:block;animation:fadeIn 0.3s ease;}+@keyframes fadeIn{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}++h2{font-size:21px;font-weight:800;color:var(--text-bright);letter-spacing:-0.3px;margin-bottom:5px;}+.section-desc{font-size:13px;color:var(--text-dim);margin-bottom:20px;}+.section-desc code{color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;font-family:var(--mono);font-size:12px;}+h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margin-bottom:12px;}++/* Cards */+.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:10px;transition:box-shadow 0.2s,border-color 0.2s;}+.card:hover{box-shadow:var(--shadow-4);}++/* Stats Grid */+.stats-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;margin-bottom:24px;}+.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;position:relative;overflow:hidden;box-shadow:var(--shadow-4);}+.stat-card::after{content:'';position:absolute;top:0;left:50%;transform:translateX(-50%);width:40px;height:2px;border-radius:0 0 2px 2px;}+.stat-card:nth-child(1)::after{background:var(--accent);}+.stat-card:nth-child(2)::after{background:var(--purple);}+.stat-num{font-size:30px;font-weight:800;font-family:var(--mono);line-height:1;}+.stat-label{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-top:6px;}++/* Summary Box */+.summary-box{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:22px;margin-bottom:22px;font-size:14px;color:var(--text);line-height:1.75;}++/* Principles */+.principle{display:flex;gap:16px;padding:16px 0;border-bottom:1px solid var(--border);}+.principle:last-child{border-bottom:none;}+.principle-icon{font-size:22px;flex-shrink:0;margin-top:2px;}+.principle-title{font-size:13px;font-weight:700;color:var(--text-bright);margin-bottom:3px;}+.principle-desc{font-size:13px;color:var(--text-dim);line-height:1.65;}++/* Scope Tags */+.scope-tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:3px;font-family:var(--mono);display:inline-block;text-align:center;min-width:58px;}+.scope-Global{color:var(--critical);background:var(--critical-bg);border:1px solid var(--critical-border);}+.scope-Contact{color:var(--pass);background:var(--pass-bg);border:1px solid var(--pass-border);}+.scope-Account{color:var(--accent);background:var(--accent-bg);border:1px solid var(--accent-border);}+.scope-Parent{color:var(--purple);background:var(--purple-bg);border:1px solid var(--purple-border);}+.scope-Self{color:var(--text-dim);background:var(--surface2);border:1px solid var(--border);}++/* Privilege Chips */+.priv{font-size:9px;font-weight:700;padding:2px 5px;border-radius:3px;font-family:var(--mono);}+.priv-on{color:var(--pass);background:var(--pass-bg);}+.priv-off{color:var(--text-dim);background:var(--surface2);opacity:0.5;}++/* Role Chips */+.role-chip{font-size:11px;padding:2px 8px;border-radius:4px;font-weight:600;display:inline-block;margin-right:4px;margin-bottom:2px;}++/* Role status badges */+.new-badge{font-size:9px;font-weight:700;padding:2px 6px;border-radius:3px;background:var(--accent-bg);color:var(--accent);border:1px solid var(--accent-border);margin-left:8px;text-transform:uppercase;letter-spacing:0.5px;}+.existing-badge{font-size:9px;font-weight:700;padding:2px 6px;border-radius:3px;background:var(--pass-bg);color:var(--pass);border:1px solid var(--pass-border);margin-left:8px;text-transform:uppercase;letter-spacing:0.5px;}+.builtin-badge{font-size:10px;background:var(--surface2);color:var(--text-dim);padding:2px 6px;border-radius:3px;font-weight:600;border:1px solid var(--border);margin-left:8px;}++/* Field label */+.field-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:2px;}++/* Reasoning list */+.reasoning-list{margin:0;padding-left:18px;list-style:disc;}+.reasoning-list li{margin-bottom:2px;}+.reasoning-list li strong{color:var(--text-bright);}++/* Expandable */+.expandable-header{display:flex;align-items:center;gap:10px;cursor:pointer;-webkit-user-select:none;user-select:none;padding:11px 14px;border-radius:var(--radius-sm);}+.expandable-header:hover{background:var(--surface2);}+.expand-chevron{color:var(--text-dim);font-size:12px;transition:transform 0.2s;flex-shrink:0;}+.expanded .expand-chevron{transform:rotate(90deg);}+.expandable-body{display:none;padding:0 14px 14px;border-top:1px solid var(--border);margin-top:4px;}+.expanded .expandable-body{display:block;animation:fadeIn 0.2s ease;}++/* Responsive */+@media(max-width:768px){+ .sidebar{display:none;}+ .content{padding:20px 16px;}+ .stats-grid{grid-template-columns:1fr;}+}+</style>+</head>+<body>++<div id="mainApp">+ <!-- Top Bar -->+ <div class="topbar">+ <div class="topbar-left">+ <div class="logo">PP</div>+ <div>+ <div class="topbar-title">Table Permissions Plan</div>+ <div class="topbar-sub">__SITE_NAME__</div>+ </div>+ </div>+ </div>++ <div class="layout">+ <!-- Sidebar -->+ <div class="sidebar">+ <button class="nav-btn active" data-tab="overview"><span class="nav-icon">◉</span> Overview</button>+ <button class="nav-btn" data-tab="roles"><span class="nav-icon">◈</span> Roles</button>+ <button class="nav-btn" data-tab="permissions"><span class="nav-icon">▦</span> Table Permissions</button>+ </div>++ <!-- Content -->+ <div class="content">++ <!-- OVERVIEW -->+ <div class="section active" id="tab-overview">+ <h2>Plan Overview</h2>+ <p class="section-desc">Table permissions architecture for <code>__SITE_NAME__</code></p>++ <div class="summary-box" id="summaryBox">__SUMMARY__</div>++ <div class="stats-grid">+ <div class="stat-card"><div class="stat-num" style="color:var(--accent)" id="statRoles">0</div><div class="stat-label">Web Roles</div></div>+ <div class="stat-card"><div class="stat-num" style="color:var(--purple)" id="statPerms">0</div><div class="stat-label">Table Perms</div></div>+ </div>++ <h3>Design Rationale</h3>+ <div id="rationaleContainer"></div>+ </div>++ <!-- ROLES -->+ <div class="section" id="tab-roles">+ <h2>Web Roles</h2>+ <p class="section-desc" id="rolesDesc"></p>+ <div id="rolesContainer"></div>+ </div>++ <!-- PERMISSIONS -->+ <div class="section" id="tab-permissions">+ <h2>Table Permissions</h2>+ <p class="section-desc" id="permsDesc"></p>++ <h3>Legend</h3>+ <div class="card" style="margin-bottom:16px;">+ <div style="display:flex;gap:32px;flex-wrap:wrap;">+ <div>+ <div class="field-label" style="margin-bottom:6px;">Scope</div>+ <div style="display:flex;gap:6px;flex-wrap:wrap;">+ <span class="scope-tag scope-Global">Global</span>+ <span class="scope-tag scope-Contact">Contact</span>+ <span class="scope-tag scope-Account">Account</span>+ <span class="scope-tag scope-Parent">Parent</span>+ <span class="scope-tag scope-Self">Self</span>+ </div>+ <div style="font-size:11px;color:var(--text-dim);margin-top:6px;line-height:1.6;">+ <strong>Global</strong> — all records | + <strong>Contact</strong> — user's contact | + <strong>Account</strong> — user's account | + <strong>Parent</strong> — via parent table | + <strong>Self</strong> — own record only+ </div>+ </div>+ <div>+ <div class="field-label" style="margin-bottom:6px;">Privileges</div>+ <div style="display:flex;flex-direction:column;gap:4px;font-size:12px;">+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">R</span><strong style="color:var(--text-bright);">Read</strong><span style="color:var(--text-dim);">— Retrieve and view records</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">C</span><strong style="color:var(--text-bright);">Create</strong><span style="color:var(--text-dim);">— Add new records</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">W</span><strong style="color:var(--text-bright);">Write</strong><span style="color:var(--text-dim);">— Update existing records (includes file uploads via PATCH)</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">D</span><strong style="color:var(--text-bright);">Delete</strong><span style="color:var(--text-dim);">— Remove records</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">A</span><strong style="color:var(--text-bright);">Append</strong><span style="color:var(--text-dim);">— Attach this record to another via a lookup</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">AT</span><strong style="color:var(--text-bright);">AppendTo</strong><span style="color:var(--text-dim);">— Allow other records to reference this one via a lookup</span></div>+ </div>+ <div style="font-size:11px;color:var(--text-dim);margin-top:8px;">+ <span class="priv priv-on" style="font-size:8px;">R</span> enabled + <span class="priv priv-off" style="font-size:8px;">R</span> disabled+ </div>+ </div>+ </div>+ </div>++ <div style="display:flex;justify-content:flex-end;align-items:center;margin-bottom:16px;">+ <button id="expandAllBtn" onclick="toggleExpandAll()" style="padding:5px 12px;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface);color:var(--text-dim);font-size:12px;font-weight:600;cursor:pointer;font-family:var(--sans);transition:all 0.15s;">Expand All</button>+ </div>+ <div id="permsContainer"></div>+ </div>++ </div>+ </div>+</div>++<script>+// Data is populated by the table-permissions-architect agent+const SITE_NAME = "__SITE_NAME__";++const ROLES = __ROLES_DATA__;+// Each role: { id, name, desc, builtin, isNew, color }+// builtin: true only for "Authenticated Users" and "Anonymous Users"+// isNew: true if proposed by this plan, false if already exists in .powerpages-site/web-roles/++const PERMS = __PERMISSIONS_DATA__;+// Each perm: { id, name, displayName, table, scope, read, create, write, delete, append, appendto, roles (array of role ids), parent (perm id or null), parentRelationship, rationale: { scope, read, create, write, delete, append, appendto }, isNew }++const RATIONALE = __RATIONALE_DATA__;+// Array of { icon, title, desc }++// Tab navigation+document.querySelectorAll('.nav-btn').forEach(btn => {+ btn.addEventListener('click', () => {+ document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));+ btn.classList.add('active');+ document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));+ document.getElementById('tab-' + btn.dataset.tab).classList.add('active');+ });+});++function getRoleName(id) { return ROLES.find(r => r.id === id)?.name || id; }+function getRoleColor(id) { return ROLES.find(r => r.id === id)?.color || "#8890a4"; }++const scopeColors = {+ Global: 'var(--critical)', Contact: 'var(--pass)', Account: 'var(--accent)',+ Parent: 'var(--purple)', Self: 'var(--text-dim)'+};++// Stats+const uniqueTables = [...new Set(PERMS.map(p => p.table))];+document.getElementById('statRoles').textContent = ROLES.length;+document.getElementById('statPerms').textContent = PERMS.length;++const newRoleCount = ROLES.filter(r => r.isNew).length;+const existingRoleCount = ROLES.filter(r => !r.builtin && !r.isNew).length;+const builtinRoleCount = ROLES.filter(r => r.builtin).length;+const totalRoleCount = ROLES.length;+const roleParts = [];+if (builtinRoleCount > 0) roleParts.push(builtinRoleCount + ' built-in');+if (existingRoleCount > 0) roleParts.push(existingRoleCount + ' existing');+if (newRoleCount > 0) roleParts.push(newRoleCount + ' proposed');+document.getElementById('rolesDesc').textContent =+ totalRoleCount + ' role' + (totalRoleCount !== 1 ? 's' : '') ++ (roleParts.length > 0 ? ' \u2014 ' + roleParts.join(', ') : '') ++ '.';++const newPermCount = PERMS.filter(p => p.isNew).length;+const existingPermCount = PERMS.filter(p => !p.isNew).length;+const permParts = [];+if (existingPermCount > 0) permParts.push(existingPermCount + ' existing');+if (newPermCount > 0) permParts.push(newPermCount + ' proposed');+document.getElementById('permsDesc').textContent =+ PERMS.length + ' permission' + (PERMS.length !== 1 ? 's' : '') ++ ' across ' + uniqueTables.length + ' Dataverse table' + (uniqueTables.length !== 1 ? 's' : '') ++ (permParts.length > 0 ? ' \u2014 ' + permParts.join(', ') : '') + '.';++// Render Rationale+function renderRationale() {+ const c = document.getElementById('rationaleContainer');+ let html = '';+ RATIONALE.forEach(r => {+ html += `<div class="principle">+ <div class="principle-icon">${r.icon}</div>+ <div>+ <div class="principle-title">${r.title}</div>+ <div class="principle-desc">${r.desc}</div>+ </div>+ </div>`;+ });+ c.innerHTML = html;+}++// Render Roles+function renderRoles() {+ const c = document.getElementById('rolesContainer');+ let html = '';+ const sortedRoles = [...ROLES].sort((a, b) => (b.isNew ? 1 : 0) - (a.isNew ? 1 : 0));+ sortedRoles.forEach(r => {+ const perms = PERMS.filter(p => p.roles.includes(r.id));+ html += `<div class="card" style="cursor:default;${r.isNew ? 'background:var(--accent-bg);border-color:var(--accent-border);' : ''}">+ <div style="display:flex;justify-content:space-between;align-items:flex-start;">+ <div style="display:flex;align-items:center;gap:10px;">+ <div style="width:10px;height:10px;border-radius:50%;background:${r.color};flex-shrink:0;"></div>+ <div>+ <span style="font-size:14px;font-weight:700;color:var(--text-bright)">${r.name}</span>+ ${r.builtin ? '<span class="builtin-badge">BUILT-IN</span>' : r.isNew ? '<span class="new-badge">PROPOSED</span>' : '<span class="existing-badge">EXISTING</span>'}+ <div style="font-size:12px;color:var(--text-dim);margin-top:2px;">${r.desc}</div>+ </div>+ </div>+ </div>+ <div style="margin-top:10px;padding-top:10px;border-top:1px solid var(--border);display:flex;flex-wrap:wrap;gap:5px;">+ ${perms.length > 0 ? perms.map(p => `<span style="font-size:10px;background:var(--surface2);border:1px solid var(--border);border-radius:4px;padding:3px 8px;color:var(--text);"><span class="scope-tag scope-${p.scope}" style="font-size:9px;padding:1px 5px;min-width:auto;margin-right:4px;">${p.scope}</span>${p.name}</span>`).join('') : '<span style="font-size:11px;color:var(--text-dim);font-style:italic;">No direct table permissions</span>'}+ </div>+ </div>`;+ });+ c.innerHTML = html;+}++// Render Permissions+function renderPerms() {+ const c = document.getElementById('permsContainer');+ let html = '';+ const sortedPerms = [...PERMS].sort((a, b) => (b.isNew ? 1 : 0) - (a.isNew ? 1 : 0));+ sortedPerms.forEach(p => {+ const parentName = p.parent ? PERMS.find(x => x.id === p.parent)?.name : null;+ const privs = ['Read','Create','Write','Delete','Append','AppendTo'];+ const privFlags = { Read: p.read, Create: p.create, Write: p.write, Delete: p.delete, Append: p.append, AppendTo: p.appendto };++ html += `<div class="card" style="border-left:3px solid ${scopeColors[p.scope]};padding:0;${p.isNew ? 'background:var(--accent-bg);border-color:var(--accent-border);' : ''}">+ <div class="expandable-header" onclick="this.parentElement.classList.toggle('expanded')">+ <span class="scope-tag scope-${p.scope}">${p.scope}</span>+ <span style="font-size:13px;font-weight:600;color:var(--text-bright);flex:1;">${p.name}</span>+ ${p.isNew ? '<span class="new-badge">PROPOSED</span>' : '<span class="existing-badge">EXISTING</span>'}+ <code style="font-size:11px;color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;border:1px solid var(--accent-border);">${p.table}</code>+ <span style="display:flex;gap:3px;">${privs.map(pr => `<span class="priv ${privFlags[pr] ? 'priv-on' : 'priv-off'}">${pr[0]}${pr === 'AppendTo' ? 'T' : ''}</span>`).join('')}</span>+ <span class="expand-chevron">▶</span>+ </div>+ <div class="expandable-body">+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:12px;font-size:12px;">+ <div><div class="field-label">Scope</div><span class="scope-tag scope-${p.scope}" style="font-size:10px;padding:1px 6px;min-width:auto;">${p.scope}${p.scope === 'Parent' && parentName ? ' \u2192 ' + parentName : ''}</span></div>+ <div><div class="field-label">Display Name</div><span style="color:var(--text-bright);font-weight:600;">${p.displayName || p.name}</span></div>+ <div><div class="field-label">Table Logical Name</div><span style="color:var(--text);font-family:var(--mono);font-size:11px;">${p.table}</span></div>+ <div><div class="field-label">Roles</div>${p.roles.map(rid => `<span style="color:${getRoleColor(rid)};font-weight:600;margin-right:6px;">${getRoleName(rid)}</span>`).join('')}</div>+ <div style="grid-column:span 2"><div class="field-label">Privileges</div>${privs.map(pr => `<span class="priv ${privFlags[pr] ? 'priv-on' : 'priv-off'}" style="margin-right:4px;">${pr}: ${privFlags[pr] ? '\u2713' : '\u2717'}</span>`).join('')}</div>+ ${p.parentRelationship ? `<div style="grid-column:span 2"><div class="field-label">Relationship</div><span style="color:var(--text);font-family:var(--mono);font-size:11px;">${p.parentRelationship}</span></div>` : ''}+ </div>+ ${p.rationale ? (() => { const labels = {read:'Read',create:'Create',write:'Write',delete:'Delete',append:'Append',appendto:'AppendTo'}; return `<div style="margin-top:12px;"><div class="field-label" style="margin-bottom:6px;">Reasoning</div><div style="font-size:12px;color:var(--text);background:var(--surface2);padding:10px 14px;border-radius:var(--radius-sm);border-left:2px solid var(--accent);line-height:1.8;"><ul class="reasoning-list">${p.rationale.scope ? `<li><strong>Scope:</strong> ${p.rationale.scope}</li>` : ''}${Object.entries(labels).map(([k,l]) => p.rationale[k] ? `<li><strong>${l}:</strong> ${p.rationale[k]}</li>` : '').join('')}</ul></div></div>`; })() : ''}+ </div>+ </div>`;+ });+ c.innerHTML = html;+}++// Expand All toggle+let allExpanded = false;+function toggleExpandAll() {+ allExpanded = !allExpanded;+ const cards = document.querySelectorAll('#permsContainer .card');+ cards.forEach(card => {+ if (allExpanded) card.classList.add('expanded');+ else card.classList.remove('expanded');+ });+ document.getElementById('expandAllBtn').textContent = allExpanded ? 'Collapse All' : 'Expand All';+}++// Init+renderRationale();+renderRoles();+renderPerms();+</script>+<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;">AI-generated content may be incorrect</footer>+</body>+</html>diff --git a/plugins/power-pages/agents/data-model-architect.md b/plugins/power-pages/agents/data-model-architect.mdindex fb395b010..38e78aed1 100644--- a/plugins/power-pages/agents/data-model-architect.md+++ b/plugins/power-pages/agents/data-model-architect.md@@ -17,8 +17,8 @@ tools:- Bash- EnterPlanMode- ExitPlanMode+ - mcp__plugin_power-pages_playwright__browser_resize- mcp__plugin_power-pages_playwright__browser_navigate- - mcp__plugin_power-pages_playwright__browser_take_screenshot- mcp__plugin_power-pages_playwright__browser_wait_for- mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search- mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search@@ -76,7 +76,7 @@ Also factor in context from the user's original request (e.g., "I need a custome## Step 2: Discover Existing Tables-Always query the Dataverse OData API to discover what already exists in the environment. Use Azure CLI authentication.+Always query the Dataverse OData API to discover what already exists in the environment. Use the shared Node.js scripts for authentication and API requests.### 2.1 Get Environment URL@@ -86,62 +86,62 @@ Run `pac env who` and parse the `Environment URL` field:pac env who```-Extract the environment URL (e.g., `https://org12345.crm.dynamics.com`). Store this as `$envUrl`.+Extract the environment URL (e.g., `https://org12345.crm.dynamics.com`). Use this as the `<envUrl>` argument for subsequent script calls.-### 2.2 Get Auth Token+### 2.2 Verify Access-Get an Azure CLI access token for the environment:+Verify Dataverse access and obtain authentication details using the shared script:-```powershell-$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>```-If `az` is not authenticated or not installed, inform the user and ask them to run `az login` first.+This outputs JSON with `token`, `userId`, `organizationId`, and `tenantId`. If it fails, inform the user that Azure CLI login is required (`az login`).### 2.3 Query Existing TablesFetch custom tables from Dataverse:-```powershell-$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }-$tables = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions?`$select=LogicalName,DisplayName,Description&`$filter=IsCustomEntity eq true" -Headers $headers-$tables.value | ForEach-Object { [PSCustomObject]@{ LogicalName = $_.LogicalName; DisplayName = $_.DisplayName.UserLocalizedLabel.Label; Description = $_.Description.UserLocalizedLabel.Label } } | Format-Table -AutoSize```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions?$select=LogicalName,DisplayName,Description&$filter=IsCustomEntity eq true"+```++The script outputs JSON with `status` and `data`. Parse `data.value` to list each table's `LogicalName`, `DisplayName.UserLocalizedLabel.Label`, and `Description.UserLocalizedLabel.Label`.### 2.4 Query Table ColumnsFor each relevant table, fetch its columns:-```powershell-$attrs = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_name>')/Attributes?`$select=LogicalName,DisplayName,AttributeType,RequiredLevel" -Headers $headers-$attrs.value | ForEach-Object { [PSCustomObject]@{ LogicalName = $_.LogicalName; DisplayName = $_.DisplayName.UserLocalizedLabel.Label; Type = $_.AttributeType; Required = $_.RequiredLevel.Value } } | Format-Table -AutoSize+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table_name>')/Attributes?$select=LogicalName,DisplayName,AttributeType,RequiredLevel"```+Parse `data.value` to list each column's `LogicalName`, `DisplayName.UserLocalizedLabel.Label`, `AttributeType`, and `RequiredLevel.Value`.+### 2.5 Query RelationshipsFetch relationships for relevant tables:-```powershell-$rels = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_name>')/OneToManyRelationships?`$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute" -Headers $headers-$rels.value | ForEach-Object { [PSCustomObject]@{ Name = $_.SchemaName; From = $_.ReferencedEntity; To = $_.ReferencingEntity; ForeignKey = $_.ReferencingAttribute } } | Format-Table -AutoSize```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table_name>')/OneToManyRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute"+```++Parse `data.value` to list each relationship's `SchemaName`, `ReferencedEntity`, `ReferencingEntity`, and `ReferencingAttribute`.### 2.6 Look Up Default Publisher PrefixQuery the `CDS Default Publisher` to get the customization prefix used for new tables and columns:-```powershell-$publishers = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/publishers?`$filter=friendlyname eq 'CDS Default Publisher'&`$select=customizationprefix" -Headers $headers-$prefix = $publishers.value[0].customizationprefix+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "publishers?$filter=friendlyname eq 'CDS Default Publisher'&$select=customizationprefix"```-Store the result as `$prefix` (e.g., `cr123`). All new table logical names must be prefixed with `{prefix}_` (e.g., `cr123_project`) and all new custom column logical names must also use this prefix (e.g., `cr123_projectname`). This ensures new entities are created under the environment's default publisher.+Parse `data.value[0].customizationprefix` to get the prefix (e.g., `cr123`). All new table logical names must be prefixed with `{prefix}_` (e.g., `cr123_project`) and all new custom column logical names must also use this prefix (e.g., `cr123_projectname`). This ensures new entities are created under the environment's default publisher.If the query returns no results, try querying all publishers and pick the first non-Microsoft one:-```powershell-$allPubs = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/publishers?`$select=friendlyname,customizationprefix" -Headers $headers-$allPubs.value | ForEach-Object { [PSCustomObject]@{ FriendlyName = $_.friendlyname; Prefix = $_.customizationprefix } } | Format-Table -AutoSize+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "publishers?$select=friendlyname,customizationprefix"```If still unable to determine the prefix, use `cr` as a placeholder and note in the proposal that the user should confirm their publisher prefix.@@ -151,9 +151,9 @@ If still unable to determine the prefix, use `cr` as a placeholder and note in tIf any of the above commands fail, include the error in your plan output so the user can see what went wrong:- If `pac env who` fails: Note that PAC CLI auth is required (`pac auth create`)-- If `az account get-access-token` fails: Note that Azure CLI login is required (`az login`)-- If OData API returns 401/403: Note that the token may have expired or permissions are insufficient-- If OData API returns 404: Note that the environment URL may be incorrect+- If `verify-dataverse-access.js` fails: Note that Azure CLI login is required (`az login`)+- If `dataverse-request.js` returns a non-2xx `status`: Check the status code — 401/403 means permissions are insufficient, 404 means the environment URL or API path may be incorrect+- The `dataverse-request.js` script handles 401 token refresh and 429/5xx retries automaticallyDo NOT stop the entire workflow for auth errors. Proceed with the steps you can complete (e.g., code analysis) and note which discovery steps were skipped and why.@@ -182,7 +182,7 @@ Categorize each table as:## Step 4: Propose Data Model via Plan Mode-Once you have completed Steps 1-3, prepare the data model proposal. Sections 4.1–4.4 describe the plan content to assemble. Section 4.5 renders the ER diagram visually in the browser — do this **before** entering plan mode so the user can see the diagram while reviewing the textual plan. Sections 4.6–4.7 handle the plan mode interaction.+Once you have completed Steps 1-3, prepare the data model proposal. Sections 4.1–4.3 describe the data to assemble. Section 4.4 covers the ER diagram. Section 4.5 renders the interactive HTML plan in the browser. Sections 4.6–4.7 handle plan mode for user approval.### 4.1 Publisher Prefix@@ -194,10 +194,12 @@ Existing/reused standard tables (e.g., `contact`, `account`) keep their original### 4.2 Table Proposals-For each table, always include **both the logical name and display name**:+For each table, always include **both the logical name and display name** and explain **why** it is being proposed:**`<table_logical_name>`** — *<Display Name>* (`new` | `modified` | `reused`)+**Rationale:** Explain why this table is needed — what site functionality or data requirement drives it, why you chose to create it new vs. reuse an existing table, and any key design decisions (e.g., "This table stores customer orders. A new table is needed because no existing table matches the order schema inferred from the `/orders` page and `OrderForm` component. Contact scope is recommended because each order belongs to a specific user.").+| Column (Logical Name) | Display Name | Type | Required | Notes ||------------------------|-------------|------|----------|-------|| `cr123_projectname` | Project Name | SingleLine.Text | Yes | Primary name column |@@ -252,111 +254,121 @@ Follow these conventions:- Show cardinality: `||--o{` (one-to-many), `||--||` (one-to-one), `}o--o{` (many-to-many)- Include all proposed tables (new, modified, and reused)-### 4.5 Render ER Diagram Visually--**Do this BEFORE entering plan mode.** Render the Mermaid ER diagram in the browser so the user can see it while reviewing the plan.--1. Write a temporary HTML file to the **system temp directory** (NOT the project directory — avoid polluting the repo):--```powershell-# Get the temp directory path-$tempDir = [System.IO.Path]::GetTempPath()-# File path: $tempDir/er-diagram.html+### 4.5 Render Data Model Plan in Browser++**Do this BEFORE entering plan mode.** Render the complete data model plan — including tables, columns, rationale, and the ER diagram — as an interactive HTML page in the browser.++The HTML template is at `${CLAUDE_PLUGIN_ROOT}/agents/assets/data-model-plan.html`. It uses placeholder tokens that you replace with actual data.++#### 4.5.1 Prepare the Data++Build these JavaScript data structures from your analysis:++**TABLES array** — one object per table:+```json+[+ {+ "id": "cr123_order",+ "logicalName": "cr123_order",+ "displayName": "Order",+ "status": "new",+ "rationale": "Stores customer orders. A new table is needed because...",+ "columns": [+ { "logicalName": "cr123_orderid", "displayName": "Order ID", "type": "Uniqueidentifier", "required": true, "key": "PK", "isNew": true },+ { "logicalName": "cr123_contactid", "displayName": "Contact", "type": "Lookup", "required": true, "key": "FK", "isNew": true },+ { "logicalName": "cr123_ordernumber", "displayName": "Order Number", "type": "SingleLine.Text", "required": true, "key": null, "isNew": true }+ ],+ "relationships": [+ { "description": "One Contact has many Orders", "relatedTable": "contact", "type": "1:N", "foreignKey": "cr123_contactid" }+ ]+ }+]```-HTML template:--```html-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <title>ER Diagram</title>- <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>- <style>- body {- background: #ffffff;- display: flex;- justify-content: center;- align-items: flex-start;- margin: 0;- padding: 40px;- font-family: system-ui, sans-serif;- }- .mermaid {- width: 100%;- min-width: 1200px;- }- .mermaid svg {- width: 100% !important;- height: auto !important;- }- </style>-</head>-<body>- <pre class="mermaid">- <!-- paste the Mermaid erDiagram code here -->- </pre>- <script>mermaid.initialize({ startOnLoad: true, theme: 'default', er: { fontSize: 16, useMaxWidth: false } });</script>-</body>-</html>+- `status`: `"new"` | `"modified"` | `"reused"` — Classification rules:+ - `"new"` — Table does not exist in Dataverse yet; will be created from scratch+ - `"modified"` — Table already exists in Dataverse but you are proposing new columns, relationship changes, or other schema additions (i.e., any table with `isNew: true` columns must be `"modified"`)+ - `"reused"` — Table already exists in Dataverse and is used as-is with NO schema changes (only existing columns are referenced)+- `key`: `"PK"` | `"FK"` | `null`+- `isNew` on columns: `true` for proposed new columns, `false` for existing ones++**RATIONALE array** — design rationale items:+```json+[+ { "icon": "🏗️", "title": "Why this structure", "desc": "Orders and Order Items are separate tables with a 1:many relationship because..." },+ { "icon": "♻️", "title": "Reuse decisions", "desc": "The standard Contact table is modified (not just reused) because 3 new profile columns are needed beyond the existing Contact fields." },+ { "icon": "⚖️", "title": "Trade-offs", "desc": "Considered using a single Products table but split into Products and Categories for..." }+]```-2. **Resize the browser** to a large viewport for a legible diagram:+Include these rationale categories:+- **Why this structure** — Key architectural decisions, relationship cardinalities, workflow support+- **Reuse decisions** — Why specific existing tables were reused or extended+- **Trade-offs** — Alternatives considered and why they were rejected+- Any notes about skipped discovery steps due to auth errors+- Any suggestions for indexes, alternate keys, or security roles++**ER_DIAGRAM** — the Mermaid ER diagram code (from section 4.4), as a string.-Use `browser_resize` with **width: 1920** and **height: 1080** before navigating.+#### 4.5.2 Determine Output Location-3. Navigate Playwright to the file using a `file:///` URL:- - On Windows: `file:///C:/Users/<user>/AppData/Local/Temp/er-diagram.html`- - Convert backslashes to forward slashes in the path+- **If working in the context of a website** (a project root with `powerpages.config.json` exists): write the file to `<PROJECT_ROOT>/docs/data-model-plan.html`+- **Otherwise**: write to the system temp directory (`[System.IO.Path]::GetTempPath()`)-4. Wait for the diagram to render (wait for the `svg` element to appear, or wait ~3 seconds).+#### 4.5.3 Write the HTML File-5. Take a **full-page screenshot** using `browser_take_screenshot` with `fullPage: true` — this captures the entire diagram regardless of viewport height. The browser window also remains open so the user can view and interact with it directly.+**Do NOT generate HTML manually or read/modify the template yourself.** Use the `render-plan.js` script which mechanically reads the template and replaces placeholder tokens with your data.-If Playwright fails to launch or navigate, fall back to printing an ASCII ER diagram directly in the conversation. Use box-drawing characters to represent tables and arrows for relationships:+1. Write a temporary JSON data file (e.g., `<OUTPUT_DIR>/data-model-data.json`) containing:+```json+{+ "SITE_NAME": "The site name (from powerpages.config.json or folder name)",+ "SUMMARY": "A 2-3 sentence summary of the data model plan",+ "PREFIX": "cr123",+ "TABLES_DATA": [/* array of table objects from section 4.5.1 */],+ "RATIONALE_DATA": [/* array of rationale objects */],+ "ER_DIAGRAM": "erDiagram\n CONTACT[\"contact (Contact)\"] {\n ..."+}```-┌──────────────────────┐ ┌──────────────────────────┐-│ contact (Contact) │ │ cr123_order (Order) │-├──────────────────────┤ ├──────────────────────────┤-│ PK contactid │ │ PK cr123_orderid │-│ fullname │───┐ │ FK cr123_contactid │-│ emailaddress1 │ │ │ cr123_ordernumber │-└──────────────────────┘ │ │ cr123_totalamount │- │ └──────────────────────────┘- │ ▲- └──────────────┘- 1 many++2. Run the render script:++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/render-data-model-plan.js" --output "<OUTPUT_PATH>" --data "<DATA_JSON_PATH>"```-Follow these conventions for the ASCII diagram:-- Use `┌─┐│└─┘` box-drawing characters for table borders-- Show `PK` and `FK` prefixes for key columns-- Use `───` lines and `▲` arrows to show relationships-- Label cardinality (`1`, `many`) near the connection points-- Keep tables aligned horizontally or vertically for readability+3. Delete the temporary data JSON file after the script succeeds.-### 4.6 Recommendations & Next Steps+#### 4.5.4 Open in Browser-End the plan with:-- Any suggestions for indexes, alternate keys, or security roles-- Note which discovery steps were skipped (if any) due to auth errors-- State that the main agent will use this proposal to create the tables in Dataverse+1. **Resize the browser** to a large viewport:+ Use `browser_resize` with **width: 1920** and **height: 1080**.-### 4.7 Enter Plan Mode & Exit+2. Navigate Playwright to the HTML file using `browser_navigate` with the full file path.-Use `EnterPlanMode` to present the complete proposal (sections 4.1–4.4 and 4.6) to the user. Then use `ExitPlanMode` for user review and approval.+3. Wait for the page to render (wait for the `.stat-num` element, or wait ~3 seconds). The browser window remains open so the user can interact with the tabs.----+If Playwright fails, fall back to presenting the plan as text in plan mode (section 4.7).++### 4.6 Design Rationale & Recommendations++The rationale is embedded in the HTML plan (in the RATIONALE data and per-table `rationale` fields). When entering plan mode (section 4.7), include a brief text summary referencing the HTML for full details. Also note:+- That the main agent will use this proposal to create the tables in Dataverse+- Which discovery steps were skipped (if any) due to auth errors++### 4.7 Enter Plan Mode & Exit-## Step 5: Clean Up+Use `EnterPlanMode` to present a brief summary directing the user to the HTML plan open in the browser. Include:+- Total table counts by status (new/modified/reused)+- Publisher prefix+- Note that the interactive HTML has full details (tables, columns, rationale, ER diagram)-After the user approves the plan, delete the temporary `er-diagram.html` file from the system temp directory if it was created.+Then use `ExitPlanMode` for user review and approval.----## Step 6: Return Structured Output+## Step 5: Return Structured OutputAfter the user approves the plan, return the complete proposal back to the calling context. The output **must** include both logical names and display names for every table and column, so the main agent can create them in Dataverse. Structure the return as:diff --git a/plugins/power-pages/agents/table-permissions-architect.md b/plugins/power-pages/agents/table-permissions-architect.mdnew file mode 100644index 000000000..4cbdda8e0--- /dev/null+++ b/plugins/power-pages/agents/table-permissions-architect.md@@ -0,0 +1,529 @@+---+name: table-permissions-architect+description: |+ Use this agent when the user wants to set up table permissions for their Power Pages site,+ configure CRUD access for web roles, or define permission scopes.+ Trigger examples: "set up table permissions", "configure table permissions", "add table permissions",+ "set up CRUD permissions", "configure web role access", "add permissions for my tables".+ This agent analyzes the site, discovers tables and web roles, proposes a table permissions plan+ with a visual HTML plan file, and after user approval creates the table permission YAML files+ using deterministic scripts.+model: opus+color: yellow+tools:+ - Read+ - Grep+ - Glob+ - Bash+ - Write+ - EnterPlanMode+ - ExitPlanMode+ - mcp__plugin_power-pages_playwright__browser_resize+ - mcp__plugin_power-pages_playwright__browser_navigate+ - mcp__plugin_power-pages_playwright__browser_wait_for+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch+---++# Table Permissions Architect++You are a table permissions architect for Power Pages code sites. Your job is to analyze the site, discover existing tables and web roles, propose a complete table permissions plan, and after user approval create the table permission YAML files using deterministic scripts.++## Workflow++1. **Verify Site Deployment** — Check that `.powerpages-site` folder exists+2. **Discover Existing Configuration** — Read web roles and existing table permissions+3. **Analyze Access Patterns** — Determine which tables need permissions and what CRUD operations + scopes are needed+4. **Discover Relationships** — Query Dataverse OData API to get relationship names for parent-scope permissions+5. **Propose Table Permissions Plan** — Generate an HTML plan file and enter plan mode for user approval+6. **Create Files** — After user approval, create web roles (if needed) and table permission YAML files using scripts++**Important:** Do NOT ask the user questions. Autonomously analyze the site code, data model manifest, and Dataverse environment to figure out the permissions plan, then present your findings via plan mode for the user to review and approve.++---++## Step 1: Verify Site Deployment++Check that the site has been deployed at least once by looking for the `.powerpages-site` folder.++### 1.1 Locate the Project++Use `Glob` to find:+- `**/powerpages.config.json` — Power Pages config (identifies the project root)+- `**/.powerpages-site` — Deployment folder++### 1.2 Check Deployment Status++**If `.powerpages-site` folder does NOT exist:**++Enter plan mode and state:++> "The `.powerpages-site` folder was not found. This folder is created when the site is first deployed to Power Pages. You need to deploy your site first using `/power-pages:deploy-site` before table permissions can be configured."++Exit plan mode and stop. Do NOT proceed with the remaining steps.++**If `.powerpages-site` exists:** Proceed to Step 2.++---++## Step 2: Discover Existing Configuration++Read all existing web roles and table permissions to understand the current state.++### 2.1 Discover Web Roles++Read all files in `.powerpages-site/web-roles/`:++```text+**/.powerpages-site/web-roles/*.yml+```++Each web role file has this format:++```yaml+anonymoususersrole: false+authenticatedusersrole: true+id: ce938206-701d-4902-85b2-b46b1dd169b9+name: Authenticated Users+```++Compile a list of all web roles with their `id`, `name`, and flags. You will need the role IDs to associate table permissions with roles.++**If no web roles exist:** Note this in your plan — the main agent will need to create web roles before table permissions can be set up. Suggest at minimum: `Anonymous Users` and `Authenticated Users`.++### 2.2 Discover Existing Table Permissions++Read all files in `.powerpages-site/table-permissions/`:++```text+**/.powerpages-site/table-permissions/*.tablepermission.yml+```++Each table permission file has this format (code site / git format — fields alphabetically sorted, `adx_` prefix stripped except for M2M relationships):++```yaml+adx_entitypermission_webrole:+- ce938206-701d-4902-85b2-b46b1dd169b9+append: true+appendto: true+create: true+delete: false+entitylogicalname: cra5b_order+entityname: Order - Authenticated Access+id: d75934c2-5ea2-4b95-9309-e15637820626+read: true+scope: 756150004+write: false+```++For permissions with parent relationships:++```yaml+adx_entitypermission_webrole:+- ce938206-701d-4902-85b2-b46b1dd169b9+append: false+appendto: true+create: true+delete: false+entitylogicalname: cra5b_orderitem+entityname: Order Item - Authenticated Access+id: a3b4c5d6-7890-4abc-def0-123456789012+parententitypermission: d75934c2-5ea2-4b95-9309-e15637820626+parentrelationshipname: cra5b_order_orderitem+read: true+scope: 756150003+write: false+```++Compile a list of existing table permissions noting which tables already have permissions configured.++---++## Step 3: Analyze Access Patterns++Determine which tables need table permissions and what operations/scopes are required.++### 3.1 Read Data Model Manifest++Check for `.datamodel-manifest.json` in the project root:++```text+**/.datamodel-manifest.json+```++If found, read it to get the list of tables. This is the preferred source for table discovery.++### 3.2 Analyze Site Code++If no manifest exists, analyze the source code to infer which tables need permissions:++- **API calls / fetch requests** — Look for `/_api/` endpoints which indicate Web API usage patterns+- **TypeScript interfaces / types** — Type definitions often map to table schemas+- **Data services / hooks** — Custom hooks or service files that interact with Dataverse+- **Component data bindings** — What data each component displays or modifies++Look for patterns like:+```text+/_api/<table_plural_name>+fetch.*/_api/+```++### 3.3 Determine Access Patterns++For each table that needs permissions, determine:++1. **Which web roles** need access (Anonymous Users for public read, Authenticated Users for CRUD, etc.)+2. **What operations** are needed per role:+ - `read` — Can read records+ - `create` — Can create new records+ - `write` — Can update existing records. **Also required for file/image column uploads** — uploading a file uses `PATCH` which requires write permission even if the role doesn't need to update other fields on the record.+ - `delete` — Can delete records+ - `append` — Can associate records to other records. **Required when this table has lookup columns that are set during create/write operations.** Setting a lookup (e.g., `[email protected]` on a product) is an association operation — Power Pages requires `append` on the source table to allow attaching a relationship to it.+ - `appendto` — Can be associated as a child to other records. **Required when this table is the TARGET of a lookup column on another table.** For example, if `cr87b_product` has a lookup to `cr87b_productcategory`, then `cr87b_productcategory` needs `appendto: true` to allow products to reference it.++ **Lookup column detection (CRITICAL for append/appendto):**+ When a table has `create` or `write` permissions AND has lookup columns to other tables, you MUST set:+ - `append: true` on the **source table** (the one with the lookup column)+ - `appendto: true` on the **target table** (the one being referenced by the lookup)++ Detect lookup columns by searching for `@odata.bind` patterns in service code:+ ```text+ Grep: "@odata\.bind|_value" in src/**/*.ts+ ```++ Also check the data model manifest or Dataverse column metadata for columns with `AttributeType = 'Lookup'`.++ **Example:** If `cr87b_product` has a lookup `cr87b_productcategoryid` → `cr87b_productcategory`:+ - `cr87b_product` permission needs `append: true` (it sets the lookup)+ - `cr87b_productcategory` permission needs `appendto: true` (it is referenced)++ **File/image upload detection:** If the integration code contains `uploadFileColumn`, `uploadFile`, or PATCH requests targeting a column endpoint (pattern: `/_api/<table>(<id>)/<column>`), the table requires `write: true`. Search for these patterns:+ ```text+ Grep: "uploadFileColumn|uploadFile|upload\w+Photo|upload\w+Image|upload\w+File" in src/**/*.ts+ ```+3. **Scope** — What records the role can access:+ - `756150000` — **Global**: Access all records. **Avoid Global scope whenever possible** — it grants unrestricted access to every record in the table. Only use Global for truly public, read-only reference data (e.g., product catalog for anonymous browsing) where no other scope is appropriate.+ - `756150001` — **Contact**: Access records associated with the current user's contact. **Recommend Contact scope for individual self-access** — use when each user should only see/manage their own records (e.g., orders, profiles, addresses).+ - `756150002` — **Account**: Access records associated with the current user's parent account. **Recommend Account scope for organizational collaboration** — use when users within the same organization need shared visibility (e.g., team members viewing company orders, shared projects).+ - `756150003` — **Parent**: Access records through parent table permission relationship (for child tables like order items that inherit access from a parent table).+ - `756150004` — **Self**: Access only the user's own contact record and records directly linked to it.++ **Scope Selection Guidance:**+ - Default to **Contact** (`756150001`) for user-specific data — it is the safest and most common choice+ - Use **Account** (`756150002`) when business logic requires shared access within an organization+ - Use **Parent** (`756150003`) for child tables that should inherit permissions from their parent table+ - Use **Self** (`756150004`) for the contact record itself or records directly owned by the user+ - Use **Global** (`756150000`) only as a last resort for genuinely public reference data, and only with read-only permissions++4. **Parent relationships** — If a table's permission scope is Parent (`756150003`), identify the parent table permission and relationship name++---++## Step 4: Discover Relationships & Lookup Columns++Query the Dataverse OData API to get relationship names for parent-scope permissions AND to identify lookup columns that require append/appendto permissions.++### 4.1 Get Environment URL and Token++```+pac env who+```++Extract the `Environment URL` (e.g., `https://org12345.crm.dynamics.com`).++Verify Dataverse access and obtain auth credentials:++```+node "${CLAUDE_PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>+```++This outputs JSON with `token`, `userId`, `organizationId`, and `tenantId`. The token is used automatically by the `dataverse-request.js` script below.++### 4.2 Query Relationships++For tables that have parent-child relationships (Parent scope permissions), fetch the relationship names:++```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<parent_table>')/OneToManyRelationships?\$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute"+```++The output JSON contains a `data.value` array with each relationship's `SchemaName`, `ReferencedEntity`, `ReferencingEntity`, and `ReferencingAttribute`.++Use the relationship `SchemaName` as the `parentrelationshipname` value in the child table permission.++### 4.3 Query Lookup Columns (for append/appendto)++For each table that has `create` or `write` permissions, query its lookup columns to determine which tables need `appendto`:++```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table_logical_name>')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?\$select=LogicalName,Targets"+```++The output JSON contains a `data.value` array with each lookup column's `LogicalName` and `Targets` array.++This returns each lookup column and its target table(s). Use this to build the append/appendto map:+- The **source table** (with the lookup) needs `append: true`+- Each **target table** in the `Targets` array needs `appendto: true`++**Example output:**+```+Lookup Targets+------ -------+cr87b_productcategoryid cr87b_productcategory+cr87b_contactid contact+```++This means:+- `cr87b_product` needs `append: true` (it has lookup columns)+- `cr87b_productcategory` needs `appendto: true` (it is referenced by the product lookup)+- `contact` — system table, typically already has permissions++### Error Handling++If any API calls fail:+- **`pac env who` fails**: Note that PAC CLI auth is required (`pac auth create`)+- **`verify-dataverse-access.js` fails**: Note that Azure CLI login is required (`az login`)+- **OData 401/403**: The `dataverse-request.js` script handles 401 token refresh automatically; persistent 401/403 indicates insufficient privileges — note in plan+- **OData 404**: Table doesn't exist — exclude from plan++Do NOT stop the entire workflow for auth errors. Use the data model manifest and code analysis as fallback for relationship discovery, and note which API-based steps were skipped and why.++---++## Step 5: Propose Table Permissions Plan via Plan Mode++Once you have completed Steps 1-4, prepare the permissions proposal. Sections 5.1-5.2 describe the plan content. Section 5.3 generates an HTML plan file and opens it in the browser — do this **before** entering plan mode.++### 5.1 Table Permissions Plan++For each table permission to create, specify:++**Permission Name Convention:** `<DisplayName> - <RoleName> <AccessType>` (e.g., `Product - Anonymous Read`, `Order - Authenticated Access`)++For each permission, include:+- Which web role(s) it is associated with (by UUID from Step 2.1, or note that a new web role needs to be created)+- CRUD + append/appendto flags+- Scope (Global, Contact, Account, Parent, or Self)+- Parent permission and relationship name (if Parent scope)+- The table logical name+- **Rationale** — A structured object explaining *why* this permission is configured the way it is. Include:+ - `scope`: Why this scope was chosen (e.g., "Contact scope because each user should only see their own orders, inferred from the `getCurrentContactId()` filter in the order service")+ - One entry per **enabled** privilege explaining why it is necessary (e.g., `read`: "Products must be visible for catalog browsing", `append`: "This table has a lookup to Product Category set during create")+ - Omit keys for disabled privileges — only explain what is turned on++For each permission, prepare the exact `create-table-permission.js` script invocation that will be used in Step 7:++**For Global/Contact/Account/Self scope:**++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "<Global|Contact|Account|Self>" [--read] [--create] [--write] [--delete] [--append] [--appendto]+```++**For Parent scope:**++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1>" --scope "Parent" --parentPermissionId "<parent-uuid>" --parentRelationshipName "<relationship_name>" [--read] [--create] [--write] [--delete] [--append] [--appendto]+```++Note: Parent permissions must be created before child permissions — the child's `--parentPermissionId` uses the UUID from the parent's JSON output.++### 5.2 Design Rationale++Prepare an array of design rationale items that explain the permissions architecture. Each item has an icon, title, and description. Include rationale for:+- **Why this permissions structure** — Explain the overall security model (e.g., "The site uses a two-role model: Anonymous Users for public catalog browsing and Authenticated Users for order management.")+- **Scope decisions** — Summarize why each scope was chosen and any alternatives considered+- **Security trade-offs** — Note any permissions that are more permissive than ideal and why++### 5.3 Generate Permissions Plan HTML++**Do this BEFORE entering plan mode.** Generate an HTML plan file from the template and open it in the browser so the user can see it while reviewing the plan.++**Do NOT generate HTML manually or read/modify the template yourself.** Use the `render-plan.js` script which mechanically reads the template and replaces placeholder tokens with your data.++#### 5.3.1 Determine Output Location++- **If working in the context of a website** (a project root with `powerpages.config.json` exists): write the file to `<PROJECT_ROOT>/docs/permissions-plan.html`+- **Otherwise**: write to the system temp directory (`[System.IO.Path]::GetTempPath()`)++#### 5.3.2 Prepare Data++Write a temporary JSON data file (e.g., `<OUTPUT_DIR>/permissions-plan-data.json`) with these keys:++```json+{+ "SITE_NAME": "The site name (from powerpages.config.json or folder name)",+ "SUMMARY": "A 1-2 sentence summary of the plan",+ "ROLES_DATA": [/* array of role objects */],+ "PERMISSIONS_DATA": [/* array of permission objects */],+ "RATIONALE_DATA": [/* array of rationale objects */]+}+```++**ROLES_DATA format** — JSON array where each element is:++```json+{+ "id": "r1",+ "name": "Authenticated Users",+ "desc": "Built-in role — baseline access for logged-in users",+ "builtin": true,+ "isNew": false,+ "color": "#4a7ce8"+}+```++- `id`: Short identifier (e.g., `"r1"`, `"r2"`) used to link permissions to roles+- `builtin`: `true` **only** for `Authenticated Users` and `Anonymous Users` — these are the only built-in Power Pages roles+- `isNew`: `true` if this role is proposed by the plan and will be newly created, `false` if it already exists in `.powerpages-site/web-roles/`+- The HTML template shows three distinct badges based on these flags:+ - **BUILT-IN** (gray) — `builtin: true` (only Authenticated Users / Anonymous Users)+ - **EXISTING** (green) — `builtin: false, isNew: false` (already created, found in web-roles folder)+ - **PROPOSED** (blue) — `builtin: false, isNew: true` (will be created by this plan)+- `color`: A distinct hex color for visual identification. Use these defaults:+ - `#4a7ce8` (blue) for the first custom role+ - `#7c5edb` (purple) for the second custom role+ - `#d4882e` (orange) for the third custom role+ - `#e07ab8` (pink) for additional custom roles+ - `#8890a4` (gray) for built-in roles++**PERMISSIONS_DATA format** — JSON array where each element is:++```json+{+ "id": "p1",+ "name": "Product - Anonymous Read",+ "displayName": "Product",+ "table": "cra5b_product",+ "scope": "Global",+ "read": true,+ "create": false,+ "write": false,+ "delete": false,+ "append": false,+ "appendto": true,+ "roles": ["r1"],+ "parent": null,+ "parentRelationship": null,+ "rationale": {+ "scope": "Global scope because the product catalog is public reference data with no user ownership.",+ "read": "Products must be visible to anonymous visitors for catalog browsing.",+ "appendto": "Orders reference products via a lookup column, requiring AppendTo on the target table."+ },+ "isNew": true+}+```++- `name`: The permission name (used as `entityname` in the YAML file)+- `displayName`: Human-friendly table display name shown in the UI (e.g., `"Product"`, `"Order Item"`)+- `isNew`: `true` if this permission is proposed by the plan, `false` if it already exists in `.powerpages-site/table-permissions/`. Proposed permissions are highlighted with a blue background and `PROPOSED` badge; existing ones show an `EXISTING` badge.+- `roles`: Array of role `id` values from ROLES_DATA+- `parent`: The `id` of the parent permission (for Parent scope), or `null`+- `parentRelationship`: The Dataverse relationship SchemaName (for Parent scope), or `null`+- `rationale`: An object with per-aspect reasoning, rendered as a bulleted list under the "Reasoning" label. Include a key for `scope` plus one key for each **enabled** privilege explaining why it is necessary. Omit keys for disabled privileges. Available keys:+ - `scope` — Why this scope was chosen (e.g., "Contact scope because each user should only see their own orders")+ - `read` — Why read access is needed+ - `create` — Why create access is needed+ - `write` — Why write access is needed+ - `delete` — Why delete access is needed+ - `append` — Why append is needed (e.g., "This table has a lookup to Product Category set during create")+ - `appendto` — Why appendto is needed (e.g., "Referenced by orders via a lookup column")++**RATIONALE_DATA format** — JSON array where each element is:++```json+{+ "icon": "\uD83D\uDEE1\uFE0F",+ "title": "Least Privilege by Default",+ "desc": "Every permission uses the narrowest scope possible. Global scope is only used for read-only public content."+}+```++Use HTML entity references for icons if needed: `🛡️` (shield), `🔗` (link), `👤` (user), `🔒` (lock).++#### 5.3.3 Render the HTML File++Run the render script (it creates the output directory if needed):++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/render-permissions-plan.js" --output "<OUTPUT_PATH>" --data "<DATA_JSON_PATH>"+```++Delete the temporary data JSON file after the script succeeds.++#### 5.3.4 Open in Browser++1. **Resize the browser** to a large viewport:+ Use `browser_resize` with **width: 1920** and **height: 1080** before navigating.++2. Navigate Playwright to the HTML file using `browser_navigate` with the full file path.++3. Wait for the page to render (~2 seconds).++### 5.4 Summary and Next Steps++Prepare for the plan mode message. Include:+1. **Summary table** of all table permission files to be created:++ | Permission Name | Table | Scope | Web Role | CRUD |+ |----------------|-------|-------|----------|------|+ | `Product - Anonymous Read` | `cra5b_product` | Global | Anonymous Users | R |+ | `Order - Authenticated Access` | `cra5b_order` | Contact | Authenticated Users | RCWD |++2. **New web roles needed** — List any web roles that need to be created (the script will generate UUIDs)+3. **Script invocations** — The exact `create-table-permission.js` commands for each permission (from section 5.1)+4. **HTML plan file location** — Tell the user where the detailed plan file was saved+5. **Any discovery steps skipped** due to auth errors++### 5.5 Enter Plan Mode & Exit++Use `EnterPlanMode` to present the complete proposal (sections 5.1 and 5.4) to the user along with a note that the detailed visual plan is available in the HTML file. Then use `ExitPlanMode` for user review and approval.++---++## Step 6: Clean Up & Create Files++After the user approves the plan:++1. **Create web roles** if the plan identified missing web roles. Use the `create-web-role.js` script from the create-webroles skill:++```powershell+$result = node "${CLAUDE_PLUGIN_ROOT}/skills/create-webroles/scripts/create-web-role.js" --projectRoot "<PROJECT_ROOT>" --name "<Role Name>" [--anonymous] [--authenticated]+```++Capture the JSON output (`{ "id": "<uuid>", "filePath": "<path>" }`) — you need the `id` for `--webRoleIds` in table permissions.++2. **Create table permissions** using `create-table-permission.js`. Process **parent permissions before child permissions** (children need the parent's UUID from JSON output).++Run each script invocation prepared in section 5.1:++```powershell+# Parent permission first+$parentResult = node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Parent Permission Name>" --tableName "<table>" --webRoleIds "<uuid>" --scope "<scope>" [--read] [--create] [--write] [--delete] [--append] [--appendto]++# Then child permissions using parent's UUID+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Child Permission Name>" --tableName "<child_table>" --webRoleIds "<uuid>" --scope "Parent" --parentPermissionId "<parent-uuid-from-above>" --parentRelationshipName "<relationship_name>" [--read] [--create] [--write] [--delete] [--append] [--appendto]+```++The scripts handle UUID generation, alphabetical field ordering, correct YAML formatting (unquoted booleans/numbers/UUIDs, `adx_entitypermission_webrole` array format), and file naming automatically.++---++## Step 7: Return Summary++After creating all files, return a summary to the calling context:++1. **Web Roles Created** — List of new web roles with their UUIDs and file paths+2. **Table Permissions Created** — List of permissions with their UUIDs and file paths+3. **Plan File** — Path to the HTML permissions plan file+4. **Issues** — Any errors encountered during file creation++---++## Critical Constraints++- **No manual YAML writes**: Do NOT use `Write` or `Edit` to create YAML files in `.powerpages-site/`. Always use the deterministic scripts (`create-table-permission.js`, `create-web-role.js`) via `Bash`. The only file you may write directly is the `permissions-plan.html` file (in `docs/` or the system temp directory).+- **LOOKUP COLUMNS REQUIRE APPEND/APPENDTO**: When a table has `create` or `write` permissions AND has lookup columns to other tables, the source table MUST have `append: true` and each target table MUST have `appendto: true`. Missing these causes "You don't have permission to associate or disassociate" errors. Always query Dataverse for lookup columns (Step 4.3) to detect these requirements.+- **No questions**: Do NOT use `AskUserQuestion`. Autonomously analyze the site and environment, then present your findings via plan mode.+- **Security**: Never log or display the full auth token. Use it only in API request headers.+- **Parent before child**: Always create parent table permissions before child permissions that reference them.diff --git a/plugins/power-pages/agents/webapi-integration.md b/plugins/power-pages/agents/webapi-integration.mdindex c24b689ed..c90d65a27 100644--- a/plugins/power-pages/agents/webapi-integration.md+++ b/plugins/power-pages/agents/webapi-integration.md@@ -5,7 +5,7 @@ description: |frontend code. Trigger examples: "integrate web api for products table", "add api calls for orders","connect my site to the blog posts table", "implement crud for categories", "set up web api client","create a service for the products table", "add data fetching for my table", "hook up the products api".- This agent is NOT for configuring permissions or site settings — use the webapi-permissions agent for that.+ This agent is NOT for configuring permissions or site settings — use the table-permissions-architect and webapi-settings-architect agents for that.This agent is NOT for designing data models — use the data-model-architect agent for that.This agent creates production-ready Web API integration code — a centralized API client, TypeScript types,and a CRUD service layer for a single Dataverse table. Called by the user or main agent.@@ -137,39 +137,41 @@ If uncertain, use the name as provided by the user or manifest. The API-verifiedGet the environment URL from the manifest's `environmentUrl` field, or fall back to `pac env who`:-```powershell+```pac env who-# Extract the "Environment URL" value → $envUrl```-Get an Azure CLI access token:+Extract the `Environment URL` value (e.g., `https://org12345.crm.dynamics.com`).++Verify Dataverse access and obtain an auth token:-```powershell-$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv-$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>```+This outputs JSON with `token`, `userId`, `organizationId`, and `tenantId`. The token is used automatically by the `dataverse-request.js` script below.+#### 2.5.2 Query Entity Set NameGet the actual OData entity set name from Dataverse (do not guess from pluralization):-```powershell-$entityDef = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')?`$select=EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute" -Headers $headers-$entitySetName = $entityDef.EntitySetName-$primaryIdAttribute = $entityDef.PrimaryIdAttribute-$primaryNameAttribute = $entityDef.PrimaryNameAttribute+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table_logical_name>')?\$select=EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"```+The script outputs JSON: `{ "status": <code>, "data": { "EntitySetName": "...", "PrimaryIdAttribute": "...", "PrimaryNameAttribute": "..." } }`.+Use the returned `EntitySetName` for all `/_api/` URLs. Use `PrimaryIdAttribute` as the record ID column name.#### 2.5.3 Query Column MetadataFetch actual column logical names, display names, and types:-```powershell-$attrs = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')/Attributes?`$select=LogicalName,DisplayName,AttributeType,IsPrimaryId&`$filter=IsCustomAttribute eq true or IsPrimaryId eq true" -Headers $headers-$attrs.value | ForEach-Object { [PSCustomObject]@{ LogicalName = $_.LogicalName; DisplayName = $_.DisplayName.UserLocalizedLabel.Label; Type = $_.AttributeType } } | Format-Table -AutoSize```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table_logical_name>')/Attributes?\$select=LogicalName,DisplayName,AttributeType,IsPrimaryId&\$filter=IsCustomAttribute eq true or IsPrimaryId eq true"+```++The script outputs JSON: `{ "status": <code>, "data": { "value": [...] } }`. Each entry in `value` contains `LogicalName`, `DisplayName`, `AttributeType`, and `IsPrimaryId`.This returns the **real** column logical names. Cross-reference against the manifest:@@ -181,10 +183,11 @@ This returns the **real** column logical names. Cross-reference against the maniIf the table has lookup columns, fetch relationship metadata to get the correct Navigation Property names (case-sensitive, needed for `$expand` and `@odata.bind`):-```powershell-$rels = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')/ManyToOneRelationships?`$select=SchemaName,ReferencedEntity,ReferencingAttribute,ReferencingEntityNavigationPropertyName" -Headers $headers-$rels.value | ForEach-Object { [PSCustomObject]@{ NavigationProperty = $_.ReferencingEntityNavigationPropertyName; TargetTable = $_.ReferencedEntity; ForeignKey = $_.ReferencingAttribute } } | Format-Table -AutoSize```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table_logical_name>')/ManyToOneRelationships?\$select=SchemaName,ReferencedEntity,ReferencingAttribute,ReferencingEntityNavigationPropertyName"+```++The script outputs JSON: `{ "status": <code>, "data": { "value": [...] } }`. Each entry in `value` contains `ReferencingEntityNavigationPropertyName`, `ReferencedEntity`, `ReferencingAttribute`, and `SchemaName`.Use `ReferencingEntityNavigationPropertyName` as the Navigation Property name in `$expand` and `@odata.bind`. This is the **case-sensitive** name that must be used exactly.@@ -453,7 +456,7 @@ Include this in the core API client file only if the site's code requires user-s## Site Settings Prerequisites-Web API calls will fail unless site settings (`Webapi/<table>/enabled`, `Webapi/<table>/fields`) and table permissions are configured. **This is handled by the `webapi-permissions` agent** — not this agent. After creating the integration code, note that the user should run the `webapi-permissions` agent if permissions are not yet set up.+Web API calls will fail unless site settings (`Webapi/<table>/enabled`, `Webapi/<table>/fields`) and table permissions are configured. **This is handled by the `table-permissions-architect` and `webapi-settings-architect` agents** — not this agent. After creating the integration code, note that the user should run those agents if permissions and site settings are not yet set up.---@@ -546,7 +549,7 @@ Only create this if the site's UI shows/hides controls based on user roles.19. **File upload body is binary** — Send `ArrayBuffer` via `file.arrayBuffer()`, not JSON. Set `Content-Type` to the file's MIME type. Include `If-Match: *` and `x-ms-file-name` headers.20. **File download uses blob response** — Set `Accept: */*` (not `application/json`). Parse response as blob, not JSON. Return `null` on 404 instead of throwing.21. **Lookup GUID vs Navigation Property** — On GET, use `_{logicalname}_value` in `$select` for the raw GUID, and the Navigation Property in `$expand` for related data. On POST/PATCH, use `[email protected]` — never write directly to the `_value` property.-22. **Remind about permissions** — After creating integration code, note that the `webapi-permissions` agent must be run to configure site settings and table permissions if not already done.+22. **Remind about permissions** — After creating integration code, note that the `table-permissions-architect` and `webapi-settings-architect` agents must be run to configure table permissions and site settings if not already done.23. **Disable `innererror` in production** — `Webapi/error/innererror = true` is useful for debugging but exposes internal Dataverse error details. Must be disabled before going live.24. **Always update existing components** — Creating service files is not enough. After generating the API client, types, service, and hooks, you MUST search for and update all existing components that use mock data, hardcoded arrays, or placeholder fetch calls for the target table. Replace their data sources with the new service/hook. This is the most critical step — without it, the integration is incomplete.25. **Supported OData query options** — Power Pages Web API supports exactly these query params: `$select`, `$expand`, `$filter`, `$apply`, `$count`, `$top`, `$orderby`, `$skiptoken`, and `fetchXml`. Any other query params (e.g., `$skip`, `$search`) will be rejected if query param validation is enabled. Use `$apply` for aggregation queries (groupby, aggregate) when the UI needs totals, averages, or grouped counts.@@ -600,5 +603,5 @@ Before confirming that work is done, verify every item below. Do not skip any ch- [ ] File placement follows existing project conventions (or the default layout from the File Placement Summary)### User Guidance-- [ ] Reminded user to run the `webapi-permissions` agent if table permissions and site settings are not yet configured+- [ ] Reminded user to run the `table-permissions-architect` and `webapi-settings-architect` agents if table permissions and site settings are not yet configured- [ ] Noted that `Webapi/error/innererror` should be disabled before going live (if mentioned in context)diff --git a/plugins/power-pages/agents/webapi-permissions.md b/plugins/power-pages/agents/webapi-permissions.mddeleted file mode 100644index 8298a2642..000000000--- a/plugins/power-pages/agents/webapi-permissions.md+++ /dev/null@@ -1,645 +0,0 @@-----name: webapi-permissions-description: |- Use this agent when the user wants to enable Web API access for their Power Pages site, set up table permissions,- or configure site settings for Web API. Trigger examples: "enable web api", "set up web api", "configure table permissions",- "add web api access", "set up api for my tables", "enable api access for products table", "configure web api permissions".- This agent is read-only — it analyzes the site, discovers tables and web roles, and proposes a permissions plan- (table permissions + site settings + Web API config). It does NOT create any files. The main agent uses its output- to create the actual YAML files.-model: opus-color: yellow-tools:- - Read- - Grep- - Glob- - Bash- - Write- - EnterPlanMode- - ExitPlanMode- - mcp__plugin_power-pages_playwright__browser_navigate- - mcp__plugin_power-pages_playwright__browser_take_screenshot- - mcp__plugin_power-pages_playwright__browser_wait_for- - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search- - mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search- - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch------# Web API Permissions Architect--You are a Web API permissions architect for Power Pages code sites. Your job is to analyze the site, discover existing tables and web roles, and propose a complete permissions plan for enabling Web API access — **without creating or modifying any files**. You are strictly read-only and advisory. The main agent will use your output to create the actual table permission and site setting YAML files.--## Workflow--1. **Verify Site Deployment** — Check that `.powerpages-site` folder exists-2. **Discover Existing Configuration** — Read web roles, table permissions, and site settings-3. **Analyze Data Requirements** — Determine which tables need Web API access and what operations are needed-4. **Discover Table Columns** — Query Dataverse OData API to get the exact columns for each table-5. **Propose Permissions Plan** — Render a visual diagram and enter plan mode for user approval--**Important:** Do NOT ask the user questions. Autonomously analyze the site code, data model manifest, and Dataverse environment to figure out the permissions plan, then present your findings via plan mode for the user to review and approve.-------## Step 1: Verify Site Deployment--Check that the site has been deployed at least once by looking for the `.powerpages-site` folder.--### 1.1 Locate the Project--Use `Glob` to find:-- `**/powerpages.config.json` — Power Pages config (identifies the project root)-- `**/.powerpages-site` — Deployment folder--### 1.2 Check Deployment Status--**If `.powerpages-site` folder does NOT exist:**--The site has not been deployed yet. The `.powerpages-site` folder is created when the site is first deployed using `pac pages upload-code-site`. Web API configuration requires this folder.--Enter plan mode and state:--> "The `.powerpages-site` folder was not found. This folder is created when the site is first deployed to Power Pages. You need to deploy your site first using `/power-pages:deploy-site` before Web API permissions can be configured."--Exit plan mode and stop. Do NOT proceed with the remaining steps.--**If `.powerpages-site` exists:** Proceed to Step 2.-------## Step 2: Discover Existing Configuration--Read all existing web roles, table permissions, and site settings to understand the current state.--### 2.1 Discover Web Roles--Read all files in `.powerpages-site/web-roles/`:--```text-**/.powerpages-site/web-roles/*.yml-```--Each web role file has this format:--```yaml-anonymoususersrole: false-authenticatedusersrole: true-id: ce938206-701d-4902-85b2-b46b1dd169b9-name: Authenticated Users-```--Compile a list of all web roles with their `id`, `name`, and flags. You will need the role IDs to associate table permissions with roles.--**If no web roles exist:** Note this in your plan — the main agent will need to create web roles before table permissions can be set up. Suggest at minimum: `Anonymous Users` and `Authenticated Users`.--### 2.2 Discover Existing Table Permissions--Read all files in `.powerpages-site/table-permissions/`:--```text-**/.powerpages-site/table-permissions/*.tablepermission.yml-```--Each table permission file has this format (code site / git format — fields alphabetically sorted, `adx_` prefix stripped except for M2M relationships):--```yaml-adx_entitypermission_webrole:-- ce938206-701d-4902-85b2-b46b1dd169b9-append: true-appendto: true-create: true-delete: false-entitylogicalname: cra5b_order-entityname: Order - Authenticated Access-id: d75934c2-5ea2-4b95-9309-e15637820626-read: true-scope: 756150004-write: false-```--For permissions with parent relationships:--```yaml-adx_entitypermission_webrole:-- ce938206-701d-4902-85b2-b46b1dd169b9-append: false-appendto: true-create: true-delete: false-entitylogicalname: cra5b_orderitem-entityname: Order Item - Authenticated Access-id: a3b4c5d6-7890-4abc-def0-123456789012-parententitypermission: d75934c2-5ea2-4b95-9309-e15637820626-parentrelationshipname: cra5b_order_orderitem-read: true-scope: 756150003-write: false-```--Compile a list of existing table permissions noting which tables already have permissions configured.--### 2.3 Discover Existing Site Settings--Read all Web API-related site settings in `.powerpages-site/site-settings/`:--```text-**/.powerpages-site/site-settings/Webapi-*.sitesetting.yml-```--Each site setting has this format:--```yaml-description: Enable Web API access for cra5b_product table-id: a1b2c3d4-2111-4111-8111-111111111111-name: Webapi/cra5b_product/enabled-value: true-```--Fields setting (lists specific columns — **never** uses `*`):--```yaml-description: Allowed fields for cra5b_product Web API access-id: a1b2c3d4-2112-4111-8111-111111111112-name: Webapi/cra5b_product/fields-value: cra5b_productid,cra5b_name,cra5b_description,cra5b_price,cra5b_imageurl-```--Note which tables already have Web API enabled and which fields are currently exposed.-------## Step 3: Analyze Data Requirements--Determine which tables need Web API access by analyzing the site code and data model.--### 3.1 Read Data Model Manifest--Check for `.datamodel-manifest.json` in the project root:--```text-**/.datamodel-manifest.json-```--If found, read it to get the list of tables and their columns. This is the preferred source for table discovery.--### 3.2 Analyze Site Code--If no manifest exists, analyze the source code to infer which tables need Web API access:--- **API calls / fetch requests** — Look for `/_api/` endpoints which indicate Web API usage patterns-- **TypeScript interfaces / types** — Type definitions often map to table schemas-- **Data services / hooks** — Custom hooks or service files that interact with Dataverse-- **Component data bindings** — What data each component displays or modifies--Look for patterns like:-```text-/_api/<table_plural_name>-fetch.*/_api/-```--### 3.3 Determine Access Patterns--For each table that needs Web API access, determine:--1. **Which web roles** need access (Anonymous Users for public read, Authenticated Users for CRUD, etc.)-2. **What operations** are needed per role:- - `adx_read` — Can read records- - `adx_create` — Can create new records- - `adx_write` — Can update existing records. **Also required for file/image column uploads** — uploading a file uses `PATCH` which requires write permission even if the role doesn't need to update other fields on the record.- - `adx_delete` — Can delete records- - `adx_append` — Can associate records to other records (needed when this table has child relationships)- - `adx_appendto` — Can be associated as a child to other records (needed when this table is referenced by lookups)-- **File/image upload detection:** If the integration code contains `uploadFileColumn`, `uploadFile`, or PATCH requests targeting a column endpoint (pattern: `/_api/<table>(<id>)/<column>`), the table requires `write: true`. Search for these patterns:- ```text- Grep: "uploadFileColumn|uploadFile|upload\w+Photo|upload\w+Image|upload\w+File" in src/**/*.ts- ```-3. **Scope** — What records the role can access:- - `756150000` — **Global**: Access all records. **Avoid Global scope whenever possible** — it grants unrestricted access to every record in the table. Only use Global for truly public, read-only reference data (e.g., product catalog for anonymous browsing) where no other scope is appropriate.- - `756150001` — **Contact**: Access records associated with the current user's contact. **Recommend Contact scope for individual self-access** — use when each user should only see/manage their own records (e.g., orders, profiles, addresses).- - `756150002` — **Account**: Access records associated with the current user's parent account. **Recommend Account scope for organizational collaboration** — use when users within the same organization need shared visibility (e.g., team members viewing company orders, shared projects).- - `756150003` — **Parent**: Access records through parent table permission relationship (for child tables like order items that inherit access from a parent table).- - `756150004` — **Self**: Access only the user's own contact record and records directly linked to it.-- **Scope Selection Guidance:**- - Default to **Contact** (`756150001`) for user-specific data — it is the safest and most common choice- - Use **Account** (`756150002`) when business logic requires shared access within an organization- - Use **Parent** (`756150003`) for child tables that should inherit permissions from their parent table- - Use **Self** (`756150004`) for the contact record itself or records directly owned by the user- - Use **Global** (`756150000`) only as a last resort for genuinely public reference data, and only with read-only permissions--4. **Parent relationships** — If a table's permission scope is Parent (`756150003`), identify the parent table permission and relationship name--### 3.4 Identify Fields for Web API--For each table that needs Web API access, determine the specific columns to expose.--**CRITICAL SECURITY RULE: NEVER use `*` (wildcard) for the fields setting.** Always list specific column logical names. Using `*` exposes all columns including system columns and potentially sensitive data. This is a security risk.--#### Cross-Check with Integration Code--After determining which columns to include, verify that **every column referenced in the Web API integration code** is present in the proposed `Webapi/<table>/fields` setting. Missing columns will cause silent data gaps or API errors at runtime.--Search the source code for columns used in each table's service layer:--1. **`$select` statements** — Find column select arrays in service files:- ```text- Grep: "\$select|_SELECT" in src/**/*.ts- ```--2. **POST/PATCH request bodies** — Find columns written in create/update operations:- ```text- Grep: "cr[a-z0-9]+_\w+" in src/shared/services/*.ts or src/services/*.ts- ```--3. **Type definitions** — Check TypeScript entity interfaces for column names:- ```text- Grep: "cr[a-z0-9]+_\w+" in src/types/*.ts- ```--For each table, compile the complete set of columns used in code and ensure the proposed `Webapi/<table>/fields` value includes **all of them**. If a column appears in the integration code but is missing from the fields setting, add it.--**Common omissions to check for:**-- Primary key column (e.g., `cr4fc_productid`) — always needed for CRUD-- Lookup GUID columns (e.g., `_cr4fc_category_value`) — needed for filtering and references-- File/image columns (e.g., `cr4fc_photo`) — needed in the fields list if the code downloads or uploads files. Also ensure `write: true` is set on the table permission if uploads are used (PATCH method).-- `createdon` / `modifiedon` — if displayed in the UI-- Columns used in `$filter` or `$orderby` — must be in the fields list to be queryable-------## Step 4: Discover Table Columns--Query the Dataverse OData API to get the exact columns for each table, so you can list specific fields in the site settings.--### 4.1 Get Environment URL and Token--Follow the shared prerequisite pattern:--```powershell-# Get environment URL-pac env who-```--Extract the `Environment URL` (e.g., `https://org12345.crm.dynamics.com`). Store as `$envUrl`.--```powershell-# Get auth token-$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv-$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }-```--### 4.2 Query Table Columns--For each table that needs Web API access, fetch its columns:--```powershell-$attrs = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')/Attributes?`$select=LogicalName,DisplayName,AttributeType,IsPrimaryId&`$filter=IsCustomAttribute eq true or IsPrimaryId eq true" -Headers $headers-$attrs.value | ForEach-Object { [PSCustomObject]@{ LogicalName = $_.LogicalName; DisplayName = $_.DisplayName.UserLocalizedLabel.Label; Type = $_.AttributeType; IsPK = $_.IsPrimaryId } } | Format-Table -AutoSize-```--This query returns custom columns plus the primary key — these are the columns that should be included in the Web API fields setting.--**Field selection guidance:**-- Always include the primary key column (e.g., `cra5b_productid`)-- Include all custom columns the site actually uses (referenced in code, types, or API calls)-- Exclude system columns (`createdon`, `modifiedon`, `statecode`, `statuscode`, `versionnumber`, etc.) unless the site explicitly needs them-- Exclude sensitive columns that should not be exposed via client-side API--### 4.3 Query Relationships--For tables that have parent-child relationships (Parent scope permissions), fetch the relationship names:--```powershell-$rels = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<parent_table>')/OneToManyRelationships?`$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute" -Headers $headers-$rels.value | ForEach-Object { [PSCustomObject]@{ Name = $_.SchemaName; From = $_.ReferencedEntity; To = $_.ReferencingEntity; ForeignKey = $_.ReferencingAttribute } } | Format-Table -AutoSize-```--Use the relationship `SchemaName` as the `adx_parentrelationshipname` value in the child table permission.--### Error Handling--If any API calls fail:-- **`pac env who` fails**: Note that PAC CLI auth is required (`pac auth create`)-- **`az account get-access-token` fails**: Note that Azure CLI login is required (`az login`)-- **OData 401/403**: Token expired or insufficient privileges — note in plan-- **OData 404**: Table doesn't exist — exclude from plan--Do NOT stop the entire workflow for auth errors. Use the data model manifest and code analysis as fallback for table/column discovery, and note which API-based steps were skipped and why.-------## Step 5: Propose Permissions Plan via Plan Mode--Once you have completed Steps 1-4, prepare the permissions proposal. Section 5.1-5.4 describe the plan content. Section 5.5 renders the diagram visually in the browser — do this **before** entering plan mode.--### 5.1 Table Permissions Plan--For each table permission to create, specify the complete YAML content:--**Permission Name Convention:** `<DisplayName> - <RoleName> <AccessType>` (e.g., `Product - Anonymous Read`, `Order - Authenticated Access`)--**File Name Convention:** `<PermissionName>.tablepermission.yml` using the permission name with spaces replaced by hyphens (e.g., `Product-Anonymous-Read.tablepermission.yml`)--For each permission, include:-- Which web role(s) it is associated with (by UUID from Step 2.1)-- CRUD + append/appendto flags-- Scope (Global, Contact, Account, Parent, or Self)-- Parent permission and relationship name (if Parent scope)-- The table logical name--**YAML format (Global or Contact scope):**--Code sites use git format — all fields are alphabetically sorted, `adx_` prefix is stripped from regular attributes, but **M2M relationships keep their `adx_` prefix**. Entity-specific ID fields become just `id`. Entity reference lookups store only the GUID (not a nested object).--```yaml-adx_entitypermission_webrole:-- <web-role-uuid>-append: false-appendto: false-create: false-delete: false-entitylogicalname: <table_logical_name>-entityname: <Display Name - Role Access>-id: <uuid-from-generate-uuid.js>-read: true-scope: <scope_code>-write: false-```--**YAML format (Parent scope):**--```yaml-adx_entitypermission_webrole:-- <web-role-uuid>-append: false-appendto: true-create: true-delete: false-entitylogicalname: <child_table_logical_name>-entityname: <Child Table - Role Access>-id: <uuid-from-generate-uuid.js>-parententitypermission: <parent-permission-uuid>-parentrelationshipname: <relationship_schema_name>-read: true-scope: 756150003-write: false-```--Note: `parententitypermission` is the UUID of the parent table permission (create the parent first, then reference its UUID here). It is NOT a nested object — just the GUID value.--**CRITICAL YAML RULES:**-- **Code site git format**: All field names have `adx_` prefix stripped EXCEPT `adx_entitypermission_webrole` (M2M relationship keeps prefix)-- The display name field is `entityname` (from Dataverse `adx_entityname`) — NOT `entitypermissionname`-- Every table permission MUST have an `id` field with a UUID v4 generated by `node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"`-- Booleans MUST be unquoted lowercase: `true` or `false` — NEVER `"true"`, `"false"`, `True`, or `False`-- Numeric scope values MUST be unquoted integers: `756150000` — NEVER `"756150000"`-- UUIDs MUST be unquoted-- Web role UUIDs use array format with `-` prefix-- Fields MUST be alphabetically sorted (as shown in the examples above)-- No extra whitespace or comments--### 5.2 Site Settings Plan--For each table that needs Web API access, two site settings are required:--**1. Enable setting** (`Webapi/<table>/enabled`):--```yaml-description: Enable Web API access for <table_logical_name> table-id: <uuid-from-generate-uuid.js>-name: Webapi/<table_logical_name>/enabled-value: true-```--**2. Fields setting** (`Webapi/<table>/fields`):--```yaml-description: Allowed fields for <table_logical_name> Web API access-id: <uuid-from-generate-uuid.js>-name: Webapi/<table_logical_name>/fields-value: <comma-separated-list-of-column-logical-names>-```--**CRITICAL: The `value` in the fields setting MUST list specific column logical names, comma-separated, with NO spaces after commas. NEVER use `*` (wildcard). Using `*` is a security risk that exposes all columns including system and sensitive data.**--Example:-```yaml-value: cra5b_productid,cra5b_name,cra5b_description,cra5b_price,cra5b_imageurl-```--**Optionally**, if the `Webapi/error/innererror` setting does not already exist, suggest it for development/debugging:--```yaml-description: Enable detailed error messages for debugging-id: <uuid-from-generate-uuid.js>-name: Webapi/error/innererror-value: true-```--**File Name Convention:** `Webapi-<table_logical_name>-enabled.sitesetting.yml` and `Webapi-<table_logical_name>-fields.sitesetting.yml`--**Site Setting YAML RULES:**-- Boolean `value` field MUST be unquoted: `value: true` — NEVER `value: "true"`-- String `value` fields (like CSV field lists) are unquoted-- UUIDs MUST be unquoted-- The `name` field uses forward slashes: `Webapi/cra5b_product/enabled`-- The `id` must be a valid UUID v4 generated by the script--### 5.3 UUID Generation--All new table permissions and site settings need UUIDs for their `id` fields. Note in the plan that UUIDs must be generated using the shared script:--```powershell-node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"-```--The main agent must run this script once per file it creates. **Never generate UUIDs manually.**--### 5.4 Permissions Diagram--Create a Mermaid flowchart diagram that visually shows the permissions structure. The diagram should illustrate:-- Web roles at the top-- Table permissions in the middle (showing scope and CRUD flags)-- Tables at the bottom-- Connections showing which roles have which permissions on which tables--Use this diagram pattern:--~~~markdown-```mermaid-flowchart TD- subgraph Web Roles- AR["Anonymous Users"]- AU["Authenticated Users"]- end-- subgraph Table Permissions- TP1["Product - Anonymous Read<br/>Scope: Global<br/>Read: ✓ | Create: ✗ | Write: ✗ | Delete: ✗"]- TP2["Order - Authenticated Access<br/>Scope: Self<br/>Read: ✓ | Create: ✓ | Write: ✗ | Delete: ✗"]- TP3["Order Item - Authenticated Access<br/>Scope: Parent → Order<br/>Read: ✓ | Create: ✓ | Write: ✗ | Delete: ✗"]- end-- subgraph Tables- T1[("cra5b_product")]- T2[("cra5b_order")]- T3[("cra5b_orderitem")]- end-- AR --> TP1- AU --> TP2- AU --> TP3- TP1 --> T1- TP2 --> T2- TP3 --> T3- TP2 -.->|parent| TP3-```-~~~--Conventions for the diagram:-- Web role nodes: rectangle with role name `["Role Name"]`-- Table permission nodes: rectangle with permission name, scope, and CRUD summary-- Table nodes: cylinder/database shape `[("table_logical_name")]`-- Solid arrows `-->`: role-to-permission and permission-to-table associations-- Dashed arrows `-.->|parent|`: parent-child permission relationships-- Use checkmarks `✓` and crosses `✗` for CRUD flags in the permission nodes-- Group nodes in subgraphs for visual clarity--### 5.5 Render Diagram Visually--**Do this BEFORE entering plan mode.** Render the Mermaid diagram in the browser so the user can see it while reviewing the plan.--1. Write a temporary HTML file to the **system temp directory** (NOT the project directory — avoid polluting the repo):--```powershell-# Get the temp directory path-$tempDir = [System.IO.Path]::GetTempPath()-# File path: $tempDir/permissions-diagram.html-```--HTML template:--```html-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <title>Web API Permissions Diagram</title>- <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>- <style>- body {- background: #ffffff;- display: flex;- justify-content: center;- align-items: flex-start;- margin: 0;- padding: 40px;- font-family: system-ui, sans-serif;- }- .mermaid {- width: 100%;- min-width: 1200px;- }- .mermaid svg {- width: 100% !important;- height: auto !important;- }- </style>-</head>-<body>- <pre class="mermaid">- <!-- paste the Mermaid flowchart code here -->- </pre>- <script>mermaid.initialize({ startOnLoad: true, theme: 'default', flowchart: { useMaxWidth: false }, themeVariables: { fontSize: '16px' } });</script>-</body>-</html>-```--2. **Resize the browser** to a large viewport for a legible diagram:--Use `browser_resize` with **width: 1920** and **height: 1080** before navigating.--3. Navigate Playwright to the file using a `file:///` URL:- - On Windows: `file:///C:/Users/<user>/AppData/Local/Temp/permissions-diagram.html`- - Convert backslashes to forward slashes in the path--4. Wait for the diagram to render (wait ~3 seconds for Mermaid to process).--5. Take a **full-page screenshot** using `browser_take_screenshot` with `fullPage: true` — this captures the entire diagram regardless of viewport height.--If Playwright fails, fall back to an ASCII representation:--```-┌─────────────────────┐ ┌──────────────────────────┐-│ Anonymous Users │ │ Authenticated Users │-└─────────┬───────────┘ └───────────┬──────────────┘- │ │- ▼ ▼-┌─────────────────────┐ ┌──────────────────────────┐-│ Product - Anon Read │ │ Order - Auth Access │-│ Scope: Global │ │ Scope: Self │-│ R:✓ C:✗ W:✗ D:✗ │ │ R:✓ C:✓ W:✗ D:✗ │-└─────────┬───────────┘ └───────────┬──────────────┘- │ │ ┌─ parent- ▼ ▼ ▼-┌─────────────────────┐ ┌──────────────────────────┐-│ cra5b_product │ │ OrderItem - Auth Access │-└─────────────────────┘ │ Scope: Parent │- │ R:✓ C:✓ W:✗ D:✗ │- └───────────┬──────────────┘- ▼- ┌──────────────────────────┐- │ cra5b_orderitem │- └──────────────────────────┘-```--### 5.6 Summary and Next Steps--End the plan with:-1. **Summary table** of all files to be created:-- | File | Type | Location |- |------|------|----------|- | `Product-Anonymous-Read.tablepermission.yml` | Table Permission | `.powerpages-site/table-permissions/` |- | `Webapi-cra5b_product-enabled.sitesetting.yml` | Site Setting | `.powerpages-site/site-settings/` |- | `Webapi-cra5b_product-fields.sitesetting.yml` | Site Setting | `.powerpages-site/site-settings/` |--2. **Missing prerequisites** — Note if web roles need to be created first-3. **Security notes** — Confirm that no wildcard `*` is used for fields-4. **Deployment reminder** — After the main agent creates the files, the site must be deployed using `/power-pages:deploy-site`-5. **Any discovery steps skipped** due to auth errors--### 5.7 Enter Plan Mode & Exit--Use `EnterPlanMode` to present the complete proposal (sections 5.1–5.4 and 5.6) to the user. Then use `ExitPlanMode` for user review and approval.-------## Step 6: Clean Up--After the user approves the plan, delete the temporary `permissions-diagram.html` file from the system temp directory if it was created.-------## Step 7: Return Structured Output--After the user approves the plan, return the complete proposal back to the calling context. The output **must** include enough detail for the main agent to create all files. Structure the return as:--1. **Web Roles Required** — List of web role names and UUIDs (existing ones discovered in Step 2.1, plus any new ones that need to be created first)-2. **Table Permissions** — Array of permission objects, each with: permission name, file name, table logical name, web role UUID(s), scope, CRUD flags, and optional parent permission/relationship-3. **Site Settings** — Array of setting objects, each with: setting name, file name, value (including the specific field list for each table)-4. **Files to Create** — Complete list of files with their full YAML content in **code site git format** (using placeholder `<GENERATE-UUID>` for IDs that need to be generated). Table permissions must use the git format: `adx_` prefix stripped from regular attributes, `adx_entitypermission_webrole` keeps prefix (M2M), display name field is `entityname`, entity references are GUIDs only, fields alphabetically sorted.-5. **Diagram** — The Mermaid diagram markdown-------## Critical Constraints--- **READ-ONLY**: Do NOT create, modify, or delete any YAML files, table permissions, or site settings. You are advisory only. The main agent creates files based on your plan.-- **No file writes**: Do not use `Write` tool for any YAML files in `.powerpages-site/`. The only file you may write is the temporary `permissions-diagram.html` in the system temp directory for visualization.-- **Code site git format**: All YAML files must use the code site git format where `adx_` prefix is stripped from regular attributes but M2M relationships (like `adx_entitypermission_webrole`) keep the prefix. Entity-specific ID fields become just `id`. Entity reference lookups store only the GUID value. The display name field for table permissions is `entityname` (from Dataverse `adx_entityname`), NOT `entitypermissionname`. Fields must be alphabetically sorted.-- **NEVER use `*` for fields**: Always list specific column logical names in `Webapi/<table>/fields` settings. Using `*` is a security risk.-- **No questions**: Do NOT use `AskUserQuestion`. Autonomously analyze the site and environment, then present your findings via plan mode.-- **Boolean formatting**: All YAML booleans must be unquoted lowercase `true` or `false`. Never `"true"`, `"false"`, `True`, or `False`.-- **UUID generation**: Note that the main agent must use `node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"` for all UUIDs. Never hardcode or manually generate UUIDs.-- **Security**: Never log or display the full auth token. Use it only in API request headers.diff --git a/plugins/power-pages/agents/webapi-settings-architect.md b/plugins/power-pages/agents/webapi-settings-architect.mdnew file mode 100644index 000000000..5690c57cc--- /dev/null+++ b/plugins/power-pages/agents/webapi-settings-architect.md@@ -0,0 +1,410 @@+---+name: webapi-settings-architect+description: |+ Use this agent when the user wants to configure Web API site settings for their Power Pages site,+ enable Web API access for tables, or specify which columns to expose via the Web API.+ Trigger examples: "enable web api", "set up web api", "configure web api settings",+ "add web api access", "enable api access for products table", "configure web api fields".+ This agent analyzes the site, discovers tables and columns, queries Dataverse for exact column+ LogicalNames, proposes Web API site settings with case-sensitive validated column names, and+ after user approval creates the site setting YAML files using deterministic scripts.+model: opus+color: blue+tools:+ - Read+ - Grep+ - Glob+ - Bash+ - EnterPlanMode+ - ExitPlanMode+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch+---++# Web API Settings Architect++You are a Web API site settings architect for Power Pages code sites. Your job is to analyze the site, discover which tables need Web API access, query Dataverse for exact column metadata, propose Web API site settings with **case-sensitive validated column names**, and after user approval create the site setting YAML files using deterministic scripts.++## Why Case-Sensitive Column Names Matter++The Power Pages Web API `Webapi/<table>/fields` site setting performs **case-sensitive** matching against Dataverse column LogicalNames. If the fields list contains a column name with incorrect casing (e.g., `Cr4fc_Name` instead of `cr4fc_name`), the Web API returns a **403 Forbidden** error for any request involving that column. This is the most common cause of unexplained 403 errors after configuring Web API access.++Dataverse stores two forms of every column name:+- **LogicalName**: Always all-lowercase (e.g., `cr4fc_productname`) — **this is what the Web API fields setting requires**+- **SchemaName**: PascalCase with publisher prefix (e.g., `Cr4fc_ProductName`) — used in some tools but **NOT valid** in the fields setting++This agent always queries Dataverse to get the exact LogicalName and uses it as the authoritative source. Column names from code, type definitions, or documentation are **never trusted directly** — they are cross-referenced against Dataverse and corrected if they differ.++## Workflow++1. **Verify Site Deployment** — Check that `.powerpages-site` folder exists+2. **Discover Existing Site Settings** — Read existing Web API site settings+3. **Analyze Data Requirements** — Determine which tables need Web API access and which columns are used in code+4. **Query Dataverse for Exact Column LogicalNames** — Get authoritative column names from the OData metadata API+5. **Cross-Validate Column Names** — Compare code references against Dataverse LogicalNames (case-sensitive)+6. **Propose Site Settings Plan** — Enter plan mode for user approval+7. **Create Files** — After user approval, create site setting YAML files using scripts++**Important:** Do NOT ask the user questions. Autonomously analyze the site code, data model manifest, and Dataverse environment to figure out the site settings, then present your findings via plan mode for the user to review and approve.++---++## Step 1: Verify Site Deployment++Check that the site has been deployed at least once by looking for the `.powerpages-site` folder.++### 1.1 Locate the Project++Use `Glob` to find:+- `**/powerpages.config.json` — Power Pages config (identifies the project root)+- `**/.powerpages-site` — Deployment folder++### 1.2 Check Deployment Status++**If `.powerpages-site` folder does NOT exist:**++Enter plan mode and state:++> "The `.powerpages-site` folder was not found. This folder is created when the site is first deployed to Power Pages. You need to deploy your site first using `/power-pages:deploy-site` before Web API site settings can be configured."++Exit plan mode and stop. Do NOT proceed with the remaining steps.++**If `.powerpages-site` exists:** Proceed to Step 2.++---++## Step 2: Discover Existing Site Settings++Read all Web API-related site settings in `.powerpages-site/site-settings/`:++```text+**/.powerpages-site/site-settings/Webapi-*.sitesetting.yml+```++Each site setting has this format:++**Enabled setting:**+```yaml+description: Enable Web API access for cra5b_product table+id: a1b2c3d4-2111-4111-8111-111111111111+name: Webapi/cra5b_product/enabled+value: true+```++**Fields setting (lists specific columns — NEVER uses `*`):**+```yaml+description: Allowed fields for cra5b_product Web API access+id: a1b2c3d4-2112-4111-8111-111111111112+name: Webapi/cra5b_product/fields+value: cra5b_productid,cra5b_name,cra5b_description,cra5b_price,cra5b_imageurl+```++Note which tables already have Web API enabled and which fields are currently exposed.++---++## Step 3: Analyze Data Requirements++Determine which tables need Web API access and which columns are referenced in code.++### 3.1 Read Data Model Manifest++Check for `.datamodel-manifest.json` in the project root:++```text+**/.datamodel-manifest.json+```++If found, read it to get the list of tables and their columns. This is the preferred source for table discovery.++### 3.2 Analyze Site Code++If no manifest exists, analyze the source code to infer which tables need Web API access:++- **API calls / fetch requests** — Look for `/_api/` endpoints which indicate Web API usage patterns+- **TypeScript interfaces / types** — Type definitions often map to table schemas+- **Data services / hooks** — Custom hooks or service files that interact with Dataverse+- **Component data bindings** — What data each component displays or modifies++Look for patterns like:+```text+/_api/<table_plural_name>+fetch.*/_api/+```++### 3.3 Identify Columns Referenced in Code++For each table that needs Web API access, collect **every column name** referenced in the integration code. Search for:++1. **`$select` statements** — Column select arrays in service files:+ ```text+ Grep: "\$select|_SELECT" in src/**/*.ts+ ```++2. **POST/PATCH request bodies** — Columns written in create/update operations:+ ```text+ Grep: "cr[a-z0-9]+_\w+" in src/shared/services/*.ts or src/services/*.ts+ ```++3. **Type definitions** — TypeScript entity interfaces for column names:+ ```text+ Grep: "cr[a-z0-9]+_\w+" in src/types/*.ts+ ```++4. **`$filter` and `$orderby` clauses** — Columns used in queries:+ ```text+ Grep: "\$filter|\$orderby" in src/**/*.ts+ ```++5. **File/image upload code** — Columns used in file operations:+ ```text+ Grep: "uploadFileColumn|uploadFile|upload\w+Photo|upload\w+Image|upload\w+File" in src/**/*.ts+ ```++For each table, compile the complete set of column names found in code. These will be cross-validated against Dataverse in Step 5.++6. **Lookup column references** — OData uses `_<logicalname>_value` format to read lookup GUIDs:+ ```text+ Grep: "_cr[a-z0-9]+_\w+_value" in src/**/*.ts+ ```++**Common columns to check for:**+- Primary key column (e.g., `cr4fc_productid`) — always needed for CRUD+- **Lookup columns** (e.g., `cr4fc_categoryid`) — these have TWO forms that both need to be in the fields list:+ - `cr4fc_categoryid` — the Dataverse LogicalName (used for write operations / setting the lookup)+ - `_cr4fc_categoryid_value` — the OData computed attribute (used for read operations in `$select`, `$filter`)+ - **Both forms MUST be included** — see Step 5.3 for details+- File/image columns (e.g., `cr4fc_photo`) — needed if the code downloads or uploads files+- `createdon` / `modifiedon` — if displayed in the UI+- Columns used in `$filter` or `$orderby` — must be in the fields list to be queryable++---++## Step 4: Query Dataverse for Exact Column LogicalNames++This is the critical step that prevents 403 errors. Query the Dataverse OData API to get the **exact** LogicalName for every column.++### 4.1 Get Environment URL and Token++```+pac env who+```++Extract the `Environment URL` (e.g., `https://org12345.crm.dynamics.com`).++Verify Dataverse access and obtain an auth token:++```+node "${CLAUDE_PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>+```++This outputs JSON with `token`, `userId`, `organizationId`, and `tenantId`. The token is used automatically by the `dataverse-request.js` script below.++### 4.2 Query Table Columns++For each table that needs Web API access, fetch its columns:++```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table_logical_name>')/Attributes?\$select=LogicalName,DisplayName,AttributeType,IsPrimaryId,SchemaName&\$filter=IsCustomAttribute eq true or IsPrimaryId eq true"+```++The script outputs JSON: `{ "status": <code>, "data": { "value": [...] } }`. Each entry in `value` contains `LogicalName`, `SchemaName`, `DisplayName`, `AttributeType`, and `IsPrimaryId`.++**Important:** The query returns both `LogicalName` (all-lowercase, authoritative) and `SchemaName` (PascalCase). Always use `LogicalName` for the site settings fields list.++Store the results as a lookup map for each table:+```+{ LogicalName → { SchemaName, DisplayName, AttributeType, IsPrimaryId } }+```++**Identify lookup columns:** Columns with `AttributeType = 'Lookup'` or `AttributeType = 'Customer'` or `AttributeType = 'Owner'` are lookup columns. These require special handling — see Step 5.3.++### Error Handling++If any API calls fail:+- **`pac env who` fails**: Note that PAC CLI auth is required (`pac auth create`)+- **`verify-dataverse-access.js` fails**: Note that Azure CLI login is required (`az login`)+- **OData 401/403**: Token expired or insufficient privileges — note in plan+- **OData 404**: Table doesn't exist — exclude from plan++Do NOT stop the entire workflow for auth errors. Use the data model manifest and code analysis as fallback for column discovery, and note which API-based steps were skipped and why.++**If Dataverse API is unavailable**, use columns from the data model manifest or code analysis — but add a prominent warning in the plan that column names have NOT been validated against Dataverse and may cause 403 errors if casing is incorrect. Recommend the user verify column names manually using the Power Apps maker portal.++---++## Step 5: Cross-Validate Column Names (Case-Sensitive)++This step catches the casing mismatches that cause 403 errors. For each table, compare every column name found in the integration code against the exact LogicalName from Dataverse.++### 5.1 Build Validation Map++For each table, create a case-insensitive lookup from Dataverse results:++```+lowercase("LogicalName") → exact LogicalName+```++Since Dataverse LogicalNames are already all-lowercase, this map effectively allows matching code references regardless of their casing.++### 5.2 Validate Each Column++For each column referenced in code (from Step 3.3):++1. **Normalize** the code column name to lowercase+2. **Check for OData lookup format**: If the name matches `_<name>_value`, strip the prefix `_` and suffix `_value` to get the base logical name, then look up that base name in the Dataverse map+3. **Look up** in the Dataverse map+4. Classify the result:++| Scenario | Action |+|----------|--------|+| Exact match (code = Dataverse) | Include in fields list as-is |+| Case mismatch (code ≠ Dataverse but lowercase matches) | **Use the Dataverse LogicalName** and log a warning |+| OData lookup format (`_<name>_value`) matched to a Lookup column | Include **both** the LogicalName AND the `_<name>_value` format (see 5.3) |+| Not found in Dataverse | **Exclude** from fields list and flag as a potential error |+| In Dataverse but not in code | Note as available but not currently used |++### 5.3 Lookup Column Handling (CRITICAL)++Lookup columns have **two attribute names** in OData, and the Power Pages Web API fields setting does a **literal match**. Both forms must be included:++| Form | Example | Used For |+|------|---------|----------|+| LogicalName | `cr87b_productcategoryid` | Write operations (setting the lookup value via POST/PATCH) |+| OData computed attribute | `_cr87b_productcategoryid_value` | Read operations (`$select`, `$filter`, response body GUID) |++**Rule:** For every lookup column (AttributeType = `Lookup`, `Customer`, or `Owner`) that is referenced in the code — whether the code uses `cr87b_productcategoryid` or `_cr87b_productcategoryid_value` — **always include BOTH forms** in the fields list.++Example: If the code references `_cr87b_productcategoryid_value` in a `$select`:+- Include `cr87b_productcategoryid` (the LogicalName)+- Include `_cr87b_productcategoryid_value` (the OData read format)++The fields value becomes:+```+_cr87b_productcategoryid_value,cr87b_description,cr87b_name,cr87b_price,cr87b_productcategoryid,cr87b_productid+```++Note: The `_..._value` entries sort alphabetically with the underscore prefix placing them before regular column names.++### 5.4 Present Validation Results++For each table, present a comparison table in the plan:++```text+Column Validation for cra5b_product:++| Column in Code | Dataverse LogicalName | Type | Match | Action |+|------------------------------------|----------------------------|--------|----------------|------------------------------------------------|+| cra5b_productid | cra5b_productid | PK | ✓ Exact | Include |+| cra5b_name | cra5b_name | String | ✓ Exact | Include |+| _cra5b_productcategoryid_value | cra5b_productcategoryid | Lookup | ✓ Lookup | Include BOTH: cra5b_productcategoryid AND _cra5b_productcategoryid_value |+| Cra5b_Description | cra5b_description | String | ✗ CASE MISMATCH | Use `cra5b_description` (Dataverse) |+| cra5b_bogusfield | — | — | ✗ NOT FOUND | Exclude — column does not exist |+```++**If any case mismatches are found**, add a prominent warning:++> **WARNING: Case mismatches detected.** The following columns in code use incorrect casing. The `Webapi/<table>/fields` site setting requires exact Dataverse LogicalNames (all lowercase). Using incorrect casing causes 403 Forbidden errors. The proposed site settings use the corrected Dataverse LogicalNames.++**If any lookup columns are found**, add a note:++> **Lookup columns detected.** The following lookup columns require both the LogicalName and `_<name>_value` OData format in the fields list. Both forms have been included automatically.++---++## Step 6: Propose Site Settings Plan via Plan Mode++Once you have completed Steps 1-5, prepare the site settings proposal.++### 6.1 Site Settings Plan++For each table that needs Web API access, prepare the exact `create-site-setting.js` script invocations:++**1. Enable setting:**++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Webapi/<table_logical_name>/enabled" --value "true" --description "Enable Web API access for <table_logical_name> table" --type "boolean"+```++**2. Fields setting:**++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Webapi/<table_logical_name>/fields" --value "<comma-separated-validated-column-logicalnames>" --description "Allowed fields for <table_logical_name> Web API access"+```++**CRITICAL: The `--value` for fields settings MUST use exact Dataverse LogicalNames (all lowercase), comma-separated, with NO spaces after commas. NEVER use `*` (wildcard). NEVER use SchemaName (PascalCase) or any other casing variant. Every column name must have been validated against Dataverse in Step 5.**++**CRITICAL: Lookup columns MUST include BOTH the LogicalName AND the `_<name>_value` OData format.** See Step 5.3.++Example (with lookup column `cra5b_productcategoryid`):+```powershell+--value "_cra5b_productcategoryid_value,cra5b_description,cra5b_name,cra5b_price,cra5b_productcategoryid,cra5b_productid"+```++**3. Optionally**, if `Webapi/error/innererror` does not already exist, suggest it for debugging:++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Webapi/error/innererror" --value "true" --description "Enable detailed error messages for debugging" --type "boolean"+```++### 6.2 Rationale, Summary, and Next Steps++Start with an explanation of the reasoning behind the proposed settings:+- **Why these tables need Web API access** — For each table, explain what site functionality requires API access (e.g., "The `cr87b_product` table needs Web API access because the product listing page fetches products via `/_api/cr87b_products` and the admin panel creates/updates products through the service layer.")+- **Column inclusion rationale** — Explain why specific columns are included and any that were deliberately excluded (e.g., "The `cr87b_internalnotes` column exists in Dataverse but is excluded from the fields list because no frontend code references it, following the principle of least privilege.")+- **Lookup column decisions** — For lookup columns, explain which relationships they support (e.g., "Both `cr87b_productcategoryid` and `_cr87b_productcategoryid_value` are included because the product service reads the category GUID via `$select` and writes it via `@odata.bind` during product creation.")++Then include:+1. **Summary table** of all site settings to be created:++ | Setting Name | Value | Type |+ |-------------|-------|------|+ | `Webapi/cra5b_product/enabled` | `true` | boolean |+ | `Webapi/cra5b_product/fields` | `_cra5b_categoryid_value,cra5b_categoryid,cra5b_name,...` | string |++2. **Column validation summary** — How many columns were validated, any mismatches found, any columns excluded+3. **Lookup columns** — List which columns are lookups and confirm both forms are included+3. **Security notes** — Confirm that no wildcard `*` is used for fields+4. **Script invocations** — The exact `create-site-setting.js` commands for each setting (from section 6.1)+5. **Any discovery steps skipped** due to auth errors+6. **Dataverse validation status** — Whether column names were validated against Dataverse or only inferred from code/manifest++### 6.3 Enter Plan Mode & Exit++Use `EnterPlanMode` to present the complete proposal (sections 6.1, 6.2, and the validation results from 5.3) to the user. Then use `ExitPlanMode` for user review and approval.++---++## Step 7: Create Files & Return Summary++After the user approves the plan, create the site setting files using the `create-site-setting.js` script. Run each invocation prepared in section 6.1:++```powershell+# Enable setting+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Webapi/<table>/enabled" --value "true" --description "Enable Web API access for <table> table" --type "boolean"++# Fields setting+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Webapi/<table>/fields" --value "<validated-columns>" --description "Allowed fields for <table> Web API access"+```++The script handles UUID generation, alphabetical field ordering, correct YAML formatting (unquoted booleans/strings/UUIDs), and file naming automatically.++After creating all files, return a summary to the calling context:++1. **Site Settings Created** — List of settings with their UUIDs and file paths (from each script's JSON output)+2. **Column Validation Report** — For each table: columns validated, mismatches found and corrected, columns excluded+3. **Warnings** — Any case mismatches, missing columns, or unvalidated column names+4. **Issues** — Any errors encountered during file creation++---++## Critical Constraints++- **No manual YAML writes**: Do NOT use `Write` or `Edit` to create YAML files in `.powerpages-site/`. Always use the `create-site-setting.js` script via `Bash`. The script handles all formatting (unquoted booleans, UUIDs, alphabetical fields) automatically.+- **CASE-SENSITIVE COLUMN NAMES**: The `Webapi/<table>/fields` site setting is case-sensitive. Always use the exact Dataverse LogicalName (all lowercase). Never use SchemaName (PascalCase), DisplayName, or any other variant. Column names from code must be cross-validated against Dataverse before inclusion.+- **LOOKUP COLUMNS NEED BOTH FORMS**: For every lookup column, include both the LogicalName (`cr87b_categoryid`) AND the OData computed attribute (`_cr87b_categoryid_value`) in the fields list. Missing either form causes 403 errors — the LogicalName is needed for writes, the `_..._value` form is needed for reads.+- **NEVER use `*` for fields**: Always list specific column logical names in `Webapi/<table>/fields` settings. Using `*` is a security risk.+- **Dataverse is the authority**: Column names from code, type definitions, or manifests are NOT authoritative. Only the `LogicalName` returned by the Dataverse `EntityDefinitions/Attributes` API is authoritative. If Dataverse is unavailable, warn prominently that column names are unvalidated.+- **No questions**: Do NOT use `AskUserQuestion`. Autonomously analyze the site and environment, then present your findings via plan mode.+- **Security**: Never log or display the full auth token. Use it only in API request headers.diff --git a/plugins/power-pages/references/dataverse-prerequisites.md b/plugins/power-pages/references/dataverse-prerequisites.mdindex e87ffa9da..363b249ce 100644--- a/plugins/power-pages/references/dataverse-prerequisites.md+++ b/plugins/power-pages/references/dataverse-prerequisites.md@@ -8,35 +8,20 @@ Shared prerequisite steps for skills that interact with the Dataverse OData WebRun `pac env who` to get the current environment URL:-```powershell+```bashpac env who```-Extract the `Environment URL` (e.g., `https://org12345.crm.dynamics.com`). Store as `$envUrl`.+Extract the `Environment URL` (e.g., `https://org12345.crm.dynamics.com`). Store as `envUrl`.-**If `pac env who` fails**: Tell the user to authenticate first:+**If `pac env who` fails**: Tell the user to authenticate first with `pac auth create`.-```powershell-pac auth create-```--## 2. Get Azure CLI Token+## 2. Get Azure CLI Token & Verify API Access-Get an access token for the Dataverse environment:+Run the shared script to obtain an Azure CLI token and verify Dataverse API access in one step:-```powershell-$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv```--**If `az` fails**: Tell the user to run `az login` first.--## 3. Verify API Access--Make a lightweight test request to confirm the token works:--```powershell-$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }-Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/WhoAmI" -Headers $headers+node "${CLAUDE_PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>```-If this returns a valid response, proceed. If it returns 401/403, the token is invalid — ask the user to re-authenticate.+On success (exit 0), it outputs JSON to stdout with `token`, `userId`, `organizationId`, and `tenantId`. On failure (exit 1), stderr explains the issue (missing `az login`, expired token, etc.).diff --git a/plugins/power-pages/references/odata-common.md b/plugins/power-pages/references/odata-common.mdindex c477d8320..33e59b80e 100644--- a/plugins/power-pages/references/odata-common.md+++ b/plugins/power-pages/references/odata-common.md@@ -18,24 +18,26 @@ All requests require the following headers:}```-PowerShell helper:--```powershell-$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv-$headers = @{- Authorization = "Bearer $token"- "Content-Type" = "application/json"- Accept = "application/json"-}+To verify access and obtain a token:++```+node "${CLAUDE_PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>+```++This outputs JSON with `token`, `userId`, `organizationId`, and `tenantId`.++For making requests, use `dataverse-request.js` which handles authentication headers automatically:++```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET /api/data/v9.2/entities```### Token Refresh-Azure CLI tokens expire after ~60 minutes. Refresh before each major step or every 20 records:+Azure CLI tokens expire after ~60 minutes. The `dataverse-request.js` script handles 401 token refresh automatically. For long-running operations (many records or multiple tables), re-run `verify-dataverse-access.js` periodically (every ~20 records or 3-4 tables) to confirm access is still valid:-```powershell-$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv-$headers["Authorization"] = "Bearer $token"+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>```---@@ -80,25 +82,15 @@ Parse `error.message` for user-friendly reporting. Common error codes:### Retry Pattern-For transient errors (401, 429, 5xx):--```powershell-$maxRetries = 2-for ($i = 0; $i -le $maxRetries; $i++) {- try {- $result = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $body -ContentType "application/json"- break- } catch {- $statusCode = $_.Exception.Response.StatusCode.value__- if ($statusCode -eq 401) {- # Refresh token and retry- $token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv- $headers["Authorization"] = "Bearer $token"- } elseif ($statusCode -in @(429, 500, 502, 503)) {- Start-Sleep -Seconds 5- } else {- throw- }- }-}+The `dataverse-request.js` script handles retries internally:++- **401** — Automatically refreshes the token and retries+- **429 / 5xx** — Waits and retries automatically++No manual retry logic is needed. Simply call the script and check the returned status code:++```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST /api/data/v9.2/cr123_projects --body "{\"cr123_name\":\"My Project\"}"```++The output is JSON: `{ "status": <code>, "data": {...} }`. If the request fails after retries, inspect `status` and `data.error.message` to determine the appropriate action from the error tables above.diff --git a/plugins/power-pages/references/skill-tracking-reference.md b/plugins/power-pages/references/skill-tracking-reference.mdindex 0d0069289..df1fc9662 100644--- a/plugins/power-pages/references/skill-tracking-reference.md+++ b/plugins/power-pages/references/skill-tracking-reference.md@@ -24,15 +24,17 @@ The script exits silently if `.powerpages-site/site-settings/` does not exist, s| Skill | PascalCase (`--skillName`) | Setting Name ||-------|---------------------------|--------------|-| create-site | CreateSite | Site/AI/CreateSite |-| deploy-site | DeploySite | Site/AI/DeploySite |-| setup-datamodel | SetupDatamodel | Site/AI/SetupDatamodel |-| add-sample-data | AddSampleData | Site/AI/AddSampleData |-| activate-site | ActivateSite | Site/AI/ActivateSite |-| add-seo | AddSeo | Site/AI/AddSeo |-| create-webroles | CreateWebroles | Site/AI/CreateWebroles |-| integrate-webapi | IntegrateWebApi | Site/AI/IntegrateWebApi |-| setup-auth | SetupAuth | Site/AI/SetupAuth |+| create-site | CreateSite | Site/AI/Skills/CreateSite |+| deploy-site | DeploySite | Site/AI/Skills/DeploySite |+| setup-datamodel | SetupDatamodel | Site/AI/Skills/SetupDatamodel |+| add-sample-data | AddSampleData | Site/AI/Skills/AddSampleData |+| activate-site | ActivateSite | Site/AI/Skills/ActivateSite |+| add-seo | AddSeo | Site/AI/Skills/AddSeo |+| create-webroles | CreateWebroles | Site/AI/Skills/CreateWebroles |+| integrate-webapi | IntegrateWebApi | Site/AI/Skills/IntegrateWebApi |+| setup-auth | SetupAuth | Site/AI/Skills/SetupAuth |+| test-site | TestSite | Site/AI/Skills/TestSite |+| audit-permissions | AuditPermissions | Site/AI/Skills/AuditPermissions |## YAML Format@@ -41,9 +43,9 @@ The tracking script produces site setting files in code site git format (alphabe```yamldescription: Tracks usage count of the CreateSite skillid: 778fa3d0-a2ef-4d2b-98b8-e6c7d8ce1444-name: Site/AI/CreateSite+name: Site/AI/Skills/CreateSitevalue: 1```-- **Skill counter** (`Site-AI-<SkillName>.sitesetting.yml`): Incremented each time the skill runs. The `id` is preserved across increments.-- **Authoring tool** (`Site-AI-AuthoringTool.sitesetting.yml`): Created once on first skill invocation. Subsequent runs preserve the original value.+- **Skill counter** (`Site-AI-Skills-<SkillName>.sitesetting.yml`): Incremented each time the skill runs. The `id` is preserved across increments.+- **Authoring tool** (`Site-AI-Tools-AuthoringTool.sitesetting.yml`): Created once on first skill invocation. Subsequent runs preserve the original value.diff --git a/plugins/power-pages/scripts/create-site-setting.js b/plugins/power-pages/scripts/create-site-setting.jsnew file mode 100644index 000000000..96f098453--- /dev/null+++ b/plugins/power-pages/scripts/create-site-setting.js@@ -0,0 +1,84 @@+#!/usr/bin/env node++// Creates a site setting YAML file for Power Pages code sites.+// Generates UUID, validates inputs, writes correctly-formatted YAML.+//+// Usage:+// node create-site-setting.js --projectRoot <path> --name <string> --value <string> --description <string> [--type <boolean|string>]+//+// Output (JSON to stdout):+// { "id": "<uuid>", "filePath": "<path>" }+//+// Exits with code 1 on validation errors (messages to stderr).++const fs = require('fs');+const path = require('path');+const generateUuid = require('./generate-uuid');++// --- CLI arg parsing (same pattern as update-skill-tracking.js) ---++const args = process.argv.slice(2);++function getArg(name) {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;+}++const projectRoot = getArg('projectRoot');+const settingName = getArg('name');+const settingValue = getArg('value');+const description = getArg('description');+const valueType = getArg('type') || 'string';++// --- Validation ---++if (!projectRoot || !settingName || settingValue === null || settingValue === undefined || !description) {+ console.error('Usage: node create-site-setting.js --projectRoot <path> --name <string> --value <string> --description <string> [--type <boolean|string>]');+ process.exit(1);+}++if (valueType !== 'boolean' && valueType !== 'string') {+ console.error(`Error: --type must be "boolean" or "string", got "${valueType}"`);+ process.exit(1);+}++if (valueType === 'boolean' && settingValue !== 'true' && settingValue !== 'false') {+ console.error(`Error: --value must be "true" or "false" when --type is "boolean", got "${settingValue}"`);+ process.exit(1);+}++const siteSettingsDir = path.join(projectRoot, '.powerpages-site', 'site-settings');+if (!fs.existsSync(siteSettingsDir)) {+ console.error(`Error: Site settings directory not found at ${siteSettingsDir}`);+ console.error('The site must be deployed at least once before site settings can be created.');+ process.exit(1);+}++// --- Helpers ---++function writeYaml(fields) {+ const keys = Object.keys(fields).sort();+ return keys.map(k => `${k}: ${fields[k]}`).join('\n') + '\n';+}++// --- Create site setting ---++const uuid = generateUuid();++const fields = {+ description: description,+ id: uuid,+ name: settingName,+ value: valueType === 'boolean' ? (settingValue === 'true') : settingValue,+};++const yamlContent = writeYaml(fields);++// File name: replace / with - (e.g., "Webapi/cra5b_product/enabled" → "Webapi-cra5b_product-enabled.sitesetting.yml")+const fileName = `${settingName.replace(/\//g, '-')}.sitesetting.yml`;+const filePath = path.join(siteSettingsDir, fileName);++fs.writeFileSync(filePath, yamlContent, 'utf8');++const result = { id: uuid, filePath: filePath };+process.stdout.write(JSON.stringify(result));diff --git a/plugins/power-pages/scripts/create-table-permission.js b/plugins/power-pages/scripts/create-table-permission.jsnew file mode 100644index 000000000..fbf2b09de--- /dev/null+++ b/plugins/power-pages/scripts/create-table-permission.js@@ -0,0 +1,167 @@+#!/usr/bin/env node++// Creates a table permission YAML file for Power Pages code sites.+// Generates UUID, validates inputs, writes correctly-formatted YAML in code site git format.+//+// Usage:+// node create-table-permission.js --projectRoot <path> --permissionName <string> --tableName <string>+// --webRoleIds <csv> --scope <string> [--read] [--create] [--write] [--delete] [--append] [--appendto]+// [--parentPermissionId <uuid>] [--parentRelationshipName <string>]+//+// Scope accepts friendly names (Global, Contact, Account, Parent, Self) or numeric codes (756150000-756150004).+//+// Output (JSON to stdout):+// { "id": "<uuid>", "filePath": "<path>" }+//+// Exits with code 1 on validation errors (messages to stderr).++const fs = require('fs');+const path = require('path');+const generateUuid = require('./generate-uuid');++// --- CLI arg parsing ---++const args = process.argv.slice(2);++function getArg(name) {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;+}++function hasFlag(name) {+ return args.includes(`--${name}`);+}++const projectRoot = getArg('projectRoot');+const permissionName = getArg('permissionName');+const tableName = getArg('tableName');+const webRoleIdsRaw = getArg('webRoleIds');+const scopeRaw = getArg('scope');+const parentPermissionId = getArg('parentPermissionId');+const parentRelationshipName = getArg('parentRelationshipName');++// --- Constants ---++const SCOPE_MAP = {+ 'global': 756150000,+ 'contact': 756150001,+ 'account': 756150002,+ 'parent': 756150003,+ 'self': 756150004,+};++const VALID_SCOPE_CODES = new Set(Object.values(SCOPE_MAP));++const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++// --- Validation ---++if (!projectRoot || !permissionName || !tableName || !webRoleIdsRaw || !scopeRaw) {+ console.error('Usage: node create-table-permission.js --projectRoot <path> --permissionName <string> --tableName <string> --webRoleIds <csv> --scope <string> [--read] [--create] [--write] [--delete] [--append] [--appendto] [--parentPermissionId <uuid>] [--parentRelationshipName <string>]');+ process.exit(1);+}++// Parse and validate web role IDs+const webRoleIds = webRoleIdsRaw.split(',').map(id => id.trim()).filter(Boolean);+for (const roleId of webRoleIds) {+ if (!UUID_REGEX.test(roleId)) {+ console.error(`Error: Invalid UUID in --webRoleIds: "${roleId}"`);+ process.exit(1);+ }+}+if (webRoleIds.length === 0) {+ console.error('Error: --webRoleIds must contain at least one UUID');+ process.exit(1);+}++// Parse and validate scope+let scopeCode;+const scopeLower = scopeRaw.toLowerCase();+if (SCOPE_MAP[scopeLower] !== undefined) {+ scopeCode = SCOPE_MAP[scopeLower];+} else {+ const parsed = parseInt(scopeRaw, 10);+ if (isNaN(parsed) || !VALID_SCOPE_CODES.has(parsed)) {+ console.error(`Error: Invalid --scope "${scopeRaw}". Use: Global, Contact, Account, Parent, Self, or numeric code (756150000-756150004)`);+ process.exit(1);+ }+ scopeCode = parsed;+}++// Validate parent scope requirements+if (scopeCode === 756150003) {+ if (!parentPermissionId) {+ console.error('Error: --parentPermissionId is required when scope is Parent (756150003)');+ process.exit(1);+ }+ if (!UUID_REGEX.test(parentPermissionId)) {+ console.error(`Error: Invalid UUID in --parentPermissionId: "${parentPermissionId}"`);+ process.exit(1);+ }+ if (!parentRelationshipName) {+ console.error('Error: --parentRelationshipName is required when scope is Parent (756150003)');+ process.exit(1);+ }+}++// Validate target directory+const tablePermissionsDir = path.join(projectRoot, '.powerpages-site', 'table-permissions');+if (!fs.existsSync(tablePermissionsDir)) {+ console.error(`Error: Table permissions directory not found at ${tablePermissionsDir}`);+ console.error('The site must be deployed at least once before table permissions can be created.');+ process.exit(1);+}++// --- Build YAML ---++const uuid = generateUuid();++// Build fields object (alphabetically sorted keys)+const fields = {};+fields['adx_entitypermission_webrole'] = null; // special array handling+fields['append'] = hasFlag('append');+fields['appendto'] = hasFlag('appendto');+fields['create'] = hasFlag('create');+fields['delete'] = hasFlag('delete');+fields['entitylogicalname'] = tableName;+fields['entityname'] = permissionName;+fields['id'] = uuid;++if (scopeCode === 756150003) {+ fields['parententitypermission'] = parentPermissionId;+ fields['parentrelationshipname'] = parentRelationshipName;+}++fields['read'] = hasFlag('read');+fields['scope'] = scopeCode;+fields['write'] = hasFlag('write');++// Write YAML with alphabetically sorted keys+// Special handling for adx_entitypermission_webrole (array with - prefix items)+function writeTablePermissionYaml(fields, webRoleIds) {+ const lines = [];+ const keys = Object.keys(fields).sort();+ for (const key of keys) {+ if (key === 'adx_entitypermission_webrole') {+ lines.push('adx_entitypermission_webrole:');+ for (const roleId of webRoleIds) {+ lines.push(`- ${roleId}`);+ }+ } else {+ lines.push(`${key}: ${fields[key]}`);+ }+ }+ return lines.join('\n') + '\n';+}++const yamlContent = writeTablePermissionYaml(fields, webRoleIds);++// File name: collapse spaces and hyphens into single hyphens+// "Product - Anonymous Read" → "Product-Anonymous-Read.tablepermission.yml"+const fileName = `${permissionName.replace(/[\s-]+/g, '-')}.tablepermission.yml`;+const filePath = path.join(tablePermissionsDir, fileName);++fs.writeFileSync(filePath, yamlContent, 'utf8');++const result = { id: uuid, filePath: filePath };+process.stdout.write(JSON.stringify(result));diff --git a/plugins/power-pages/scripts/dataverse-request.js b/plugins/power-pages/scripts/dataverse-request.jsnew file mode 100644index 000000000..ef53c3223--- /dev/null+++ b/plugins/power-pages/scripts/dataverse-request.js@@ -0,0 +1,128 @@+#!/usr/bin/env node++// General-purpose Dataverse OData API request script with built-in auth and retry.+// Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json>]+//+// Arguments:+// envUrl - Dataverse environment URL (e.g., https://org123.crm.dynamics.com)+// method - HTTP method: GET, POST, PATCH, DELETE+// apiPath - API path after /api/data/v9.2/ (e.g., "EntityDefinitions?$filter=...")+//+// Options:+// --body <json> Request body as JSON string+// --include-headers Include response headers in output (for OData-EntityId etc.)+//+// Output (JSON to stdout):+// Success: { "status": 200, "data": { ... } }+// With headers: { "status": 200, "data": { ... }, "headers": { ... } }+// Error: { "status": 401, "error": "..." }+//+// Exit codes:+// 0 - Request completed (check status field for HTTP result)+// 1 - Fatal error (no token, invalid args, network failure after retries)++const { getAuthToken, makeRequest } = require('./lib/validation-helpers');++function parseArgs() {+ const args = process.argv.slice(2);+ if (args.length < 3) {+ process.stderr.write(+ 'Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json>] [--include-headers]\n'+ );+ process.exit(1);+ }++ const envUrl = args[0].replace(/\/+$/, '');+ const method = args[1].toUpperCase();+ const apiPath = args[2];+ let body = null;+ let includeHeaders = false;++ for (let i = 3; i < args.length; i++) {+ if (args[i] === '--body' && args[i + 1]) {+ body = args[++i];+ } else if (args[i] === '--include-headers') {+ includeHeaders = true;+ }+ }++ return { envUrl, method, apiPath, body, includeHeaders };+}++async function doRequest(envUrl, method, apiPath, body, token, includeHeaders) {+ const url = `${envUrl}/api/data/v9.2/${apiPath}`;+ const headers = {+ Authorization: `Bearer ${token}`,+ Accept: 'application/json',+ };+ if (body) {+ headers['Content-Type'] = 'application/json';+ }++ const res = await makeRequest({+ url,+ method,+ headers,+ body,+ includeHeaders,+ timeout: 30000,+ });++ return res;+}++async function main() {+ const { envUrl, method, apiPath, body, includeHeaders } = parseArgs();++ let token = getAuthToken(envUrl);+ if (!token) {+ process.stderr.write('Failed to get Azure CLI token. Run `az login` first.\n');+ process.exit(1);+ }++ const maxRetries = 2;+ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ const res = await doRequest(envUrl, method, apiPath, body, token, includeHeaders);++ if (res.error) {+ if (attempt < maxRetries) continue;+ process.stderr.write(`Request failed: ${res.error}\n`);+ process.exit(1);+ }++ // Retry on 401 with token refresh+ if (res.statusCode === 401 && attempt < maxRetries) {+ token = getAuthToken(envUrl);+ if (!token) {+ process.stderr.write('Token refresh failed. Run `az login` again.\n');+ process.exit(1);+ }+ continue;+ }++ // Retry on transient server errors+ if ([429, 500, 502, 503].includes(res.statusCode) && attempt < maxRetries) {+ await new Promise((r) => setTimeout(r, 5000));+ continue;+ }++ // Parse response body+ let data = null;+ if (res.body) {+ try {+ data = JSON.parse(res.body);+ } catch {+ data = res.body;+ }+ }++ const output = { status: res.statusCode, data };+ if (includeHeaders && res.headers) {+ output.headers = res.headers;+ }+ console.log(JSON.stringify(output));+ return;+ }+}++main();diff --git a/plugins/power-pages/scripts/generate-uuid.js b/plugins/power-pages/scripts/generate-uuid.jsindex 883637628..bebf092b7 100644--- a/plugins/power-pages/scripts/generate-uuid.js+++ b/plugins/power-pages/scripts/generate-uuid.js@@ -3,14 +3,26 @@// Generates a random UUID v4.// Output: a UUID string like "778fa3d0-a2ef-4d2b-98b8-e6c7d8ce1444"// Self-contained — no external dependencies required.+//+// Can be used as a CLI tool (node generate-uuid.js) or as a module:+// const generateUuid = require('./generate-uuid');+// const uuid = generateUuid();const { randomBytes } = require('crypto');-const bytes = randomBytes(16);-// Set version (4) and variant (RFC 4122) bits-bytes[6] = (bytes[6] & 0x0f) | 0x40;-bytes[8] = (bytes[8] & 0x3f) | 0x80;+function generateUuid() {+ const bytes = randomBytes(16);+ // Set version (4) and variant (RFC 4122) bits+ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;-const hex = bytes.toString('hex');-const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;-process.stdout.write(uuid);+ const hex = bytes.toString('hex');+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;+}++module.exports = generateUuid;++// When run directly as a CLI tool, output the UUID to stdout+if (require.main === module) {+ process.stdout.write(generateUuid());+}diff --git a/plugins/power-pages/scripts/launch-playwright-mcp.js b/plugins/power-pages/scripts/launch-playwright-mcp.jsindex 435e90282..b921e60ba 100644--- a/plugins/power-pages/scripts/launch-playwright-mcp.js+++ b/plugins/power-pages/scripts/launch-playwright-mcp.js@@ -5,68 +5,8 @@// then falls back to Playwright's bundled Chromium.// Self-contained — no external dependencies required.-const { execSync, spawn } = require('child_process');-const fs = require('fs');-const path = require('path');-const os = require('os');--function exists(filePath) {- try { return fs.existsSync(filePath); } catch { return false; }-}--function whichExists(cmd) {- try {- execSync(`which ${cmd}`, { stdio: 'ignore' });- return true;- } catch {- return false;- }-}--function detectBrowser() {- const platform = os.platform();-- if (platform === 'win32') {- const localAppData = process.env.LOCALAPPDATA || '';- const programFiles = process.env.PROGRAMFILES || '';- const programFilesX86 = process.env['PROGRAMFILES(X86)'] || '';-- // Edge — pre-installed on all Windows 10/11 machines- const edgePaths = [- path.join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),- path.join(programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),- path.join(localAppData, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),- ];- for (const p of edgePaths) {- if (exists(p)) return 'msedge';- }-- // Chrome- const chromePaths = [- path.join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'),- path.join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),- path.join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),- ];- for (const p of chromePaths) {- if (exists(p)) return 'chrome';- }- } else if (platform === 'darwin') {- // macOS- if (exists('/Applications/Google Chrome.app')) return 'chrome';- if (exists('/Applications/Microsoft Edge.app')) return 'msedge';- } else {- // Linux- if (whichExists('google-chrome')) return 'chrome';- if (whichExists('google-chrome-stable')) return 'chrome';- if (whichExists('microsoft-edge')) return 'msedge';- if (whichExists('microsoft-edge-stable')) return 'msedge';- if (whichExists('chromium-browser')) return 'chromium';- if (whichExists('chromium')) return 'chromium';- }-- // Fallback: Playwright's bundled Chromium (requires `npx playwright install chromium`)- return 'chromium';-}+const { spawn } = require('child_process');+const { detectBrowser } = require('./lib/detect-browser');const browser = detectBrowser();const child = spawn('npx', ['@playwright/mcp@latest', '--browser', browser], {diff --git a/plugins/power-pages/scripts/lib/detect-browser.js b/plugins/power-pages/scripts/lib/detect-browser.jsnew file mode 100644index 000000000..266201ccc--- /dev/null+++ b/plugins/power-pages/scripts/lib/detect-browser.js@@ -0,0 +1,70 @@+#!/usr/bin/env node++// Detects the best available Chromium-based browser on the system.+// Returns a Playwright channel name ('msedge', 'chrome', 'chromium').+// Used by the Playwright MCP launcher and the axe-core audit script.++const { execSync } = require('child_process');+const fs = require('fs');+const path = require('path');+const os = require('os');++function exists(filePath) {+ try { return fs.existsSync(filePath); } catch { return false; }+}++function whichExists(cmd) {+ try {+ execSync(`which ${cmd}`, { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+}++function detectBrowser() {+ const platform = os.platform();++ if (platform === 'win32') {+ const localAppData = process.env.LOCALAPPDATA || '';+ const programFiles = process.env.PROGRAMFILES || '';+ const programFilesX86 = process.env['PROGRAMFILES(X86)'] || '';++ // Edge — pre-installed on all Windows 10/11 machines+ const edgePaths = [+ path.join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),+ path.join(programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),+ path.join(localAppData, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),+ ];+ for (const p of edgePaths) {+ if (exists(p)) return 'msedge';+ }++ // Chrome+ const chromePaths = [+ path.join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ path.join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ path.join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ ];+ for (const p of chromePaths) {+ if (exists(p)) return 'chrome';+ }+ } else if (platform === 'darwin') {+ // macOS+ if (exists('/Applications/Google Chrome.app')) return 'chrome';+ if (exists('/Applications/Microsoft Edge.app')) return 'msedge';+ } else {+ // Linux+ if (whichExists('google-chrome')) return 'chrome';+ if (whichExists('google-chrome-stable')) return 'chrome';+ if (whichExists('microsoft-edge')) return 'msedge';+ if (whichExists('microsoft-edge-stable')) return 'msedge';+ if (whichExists('chromium-browser')) return 'chromium';+ if (whichExists('chromium')) return 'chromium';+ }++ // Fallback: Playwright's bundled Chromium (requires `npx playwright install chromium`)+ return 'chromium';+}++module.exports = { detectBrowser };diff --git a/plugins/power-pages/scripts/lib/render-template.js b/plugins/power-pages/scripts/lib/render-template.jsnew file mode 100644index 000000000..b6beaf04b--- /dev/null+++ b/plugins/power-pages/scripts/lib/render-template.js@@ -0,0 +1,77 @@+/**+ * render-template.js — Shared helper for rendering HTML plan templates.+ *+ * Reads an HTML template, replaces __PLACEHOLDER__ tokens with data values,+ * validates all required placeholders are provided, and writes the output.+ *+ * Used by the template-specific render scripts (render-data-model-plan.js, etc.).+ */++const fs = require('fs');+const path = require('path');++/**+ * @param {Object} options+ * @param {string} options.templatePath - Absolute path to the HTML template+ * @param {string} options.outputPath - Absolute path for the rendered output+ * @param {string} options.dataPath - Absolute path to the JSON data file+ * @param {string[]} options.requiredKeys - Keys that must be present in the data file+ */+function renderTemplate({ templatePath, outputPath, dataPath, requiredKeys }) {+ // Validate inputs exist+ if (!fs.existsSync(templatePath)) {+ console.error(`Template not found: ${templatePath}`);+ process.exit(1);+ }+ if (!fs.existsSync(dataPath)) {+ console.error(`Data file not found: ${dataPath}`);+ process.exit(1);+ }++ // Read template and data+ const template = fs.readFileSync(templatePath, 'utf8');+ const data = JSON.parse(fs.readFileSync(dataPath, 'utf8'));++ // Validate required keys+ const missing = requiredKeys.filter((k) => !(k in data));+ if (missing.length > 0) {+ console.error(`Missing required keys in data file: ${missing.join(', ')}`);+ process.exit(1);+ }++ // Replace all __KEY__ placeholders with corresponding values from the data object+ let result = template;+ for (const [key, value] of Object.entries(data)) {+ const placeholder = `__${key}__`;+ const replacement = typeof value === 'string' ? value : JSON.stringify(value);+ result = result.split(placeholder).join(replacement);+ }++ // Warn about any unreplaced placeholders (helps catch typos)+ const remaining = result.match(/__[A-Z][A-Z0-9_]+__/g);+ if (remaining) {+ const unique = [...new Set(remaining)];+ console.error(`Warning: unreplaced placeholders: ${unique.join(', ')}`);+ }++ // Ensure output directory exists+ const outputDir = path.dirname(outputPath);+ if (!fs.existsSync(outputDir)) {+ fs.mkdirSync(outputDir, { recursive: true });+ }++ fs.writeFileSync(outputPath, result, 'utf8');+ console.log(JSON.stringify({ status: 'ok', output: outputPath }));+}++function parseArgs(argv) {+ const args = {};+ for (let i = 2; i < argv.length; i++) {+ if (argv[i].startsWith('--') && i + 1 < argv.length) {+ args[argv[i].slice(2)] = argv[++i];+ }+ }+ return args;+}++module.exports = { renderTemplate, parseArgs };diff --git a/plugins/power-pages/scripts/render-audit-report.js b/plugins/power-pages/scripts/render-audit-report.jsnew file mode 100644index 000000000..99eb39b65--- /dev/null+++ b/plugins/power-pages/scripts/render-audit-report.js@@ -0,0 +1,29 @@+#!/usr/bin/env node+/**+ * render-audit-report.js — Renders the permissions audit report HTML from a JSON data file.+ *+ * Usage:+ * node render-audit-report.js --output <path> --data <json-file>+ *+ * Required keys in the JSON data file:+ * SITE_NAME, AUDIT_DESC, SUMMARY, FINDINGS_DATA, INVENTORY_DATA+ */++const path = require('path');+const { renderTemplate, parseArgs } = require('./lib/render-template');++const args = parseArgs(process.argv);++if (!args.output || !args.data) {+ console.error(+ 'Usage: node render-audit-report.js --output <path> --data <json-file>'+ );+ process.exit(1);+}++renderTemplate({+ templatePath: path.join(__dirname, '..', 'skills', 'audit-permissions', 'assets', 'audit-report.html'),+ outputPath: path.resolve(args.output),+ dataPath: path.resolve(args.data),+ requiredKeys: ['SITE_NAME', 'AUDIT_DESC', 'SUMMARY', 'FINDINGS_DATA', 'INVENTORY_DATA'],+});diff --git a/plugins/power-pages/scripts/render-data-model-plan.js b/plugins/power-pages/scripts/render-data-model-plan.jsnew file mode 100644index 000000000..be4fd6826--- /dev/null+++ b/plugins/power-pages/scripts/render-data-model-plan.js@@ -0,0 +1,29 @@+#!/usr/bin/env node+/**+ * render-data-model-plan.js — Renders the data model plan HTML from a JSON data file.+ *+ * Usage:+ * node render-data-model-plan.js --output <path> --data <json-file>+ *+ * Required keys in the JSON data file:+ * SITE_NAME, SUMMARY, PREFIX, TABLES_DATA, RATIONALE_DATA, ER_DIAGRAM+ */++const path = require('path');+const { renderTemplate, parseArgs } = require('./lib/render-template');++const args = parseArgs(process.argv);++if (!args.output || !args.data) {+ console.error(+ 'Usage: node render-data-model-plan.js --output <path> --data <json-file>'+ );+ process.exit(1);+}++renderTemplate({+ templatePath: path.join(__dirname, '..', 'agents', 'assets', 'data-model-plan.html'),+ outputPath: path.resolve(args.output),+ dataPath: path.resolve(args.data),+ requiredKeys: ['SITE_NAME', 'SUMMARY', 'PREFIX', 'TABLES_DATA', 'RATIONALE_DATA', 'ER_DIAGRAM'],+});diff --git a/plugins/power-pages/scripts/render-permissions-plan.js b/plugins/power-pages/scripts/render-permissions-plan.jsnew file mode 100644index 000000000..58548c732--- /dev/null+++ b/plugins/power-pages/scripts/render-permissions-plan.js@@ -0,0 +1,29 @@+#!/usr/bin/env node+/**+ * render-permissions-plan.js — Renders the permissions plan HTML from a JSON data file.+ *+ * Usage:+ * node render-permissions-plan.js --output <path> --data <json-file>+ *+ * Required keys in the JSON data file:+ * SITE_NAME, SUMMARY, ROLES_DATA, PERMISSIONS_DATA, RATIONALE_DATA+ */++const path = require('path');+const { renderTemplate, parseArgs } = require('./lib/render-template');++const args = parseArgs(process.argv);++if (!args.output || !args.data) {+ console.error(+ 'Usage: node render-permissions-plan.js --output <path> --data <json-file>'+ );+ process.exit(1);+}++renderTemplate({+ templatePath: path.join(__dirname, '..', 'agents', 'assets', 'permissions-plan.html'),+ outputPath: path.resolve(args.output),+ dataPath: path.resolve(args.data),+ requiredKeys: ['SITE_NAME', 'SUMMARY', 'ROLES_DATA', 'PERMISSIONS_DATA', 'RATIONALE_DATA'],+});diff --git a/plugins/power-pages/scripts/update-skill-tracking.js b/plugins/power-pages/scripts/update-skill-tracking.jsindex 336a68aed..a1108ceea 100644--- a/plugins/power-pages/scripts/update-skill-tracking.js+++ b/plugins/power-pages/scripts/update-skill-tracking.js@@ -77,8 +77,8 @@ function writeYaml(fields) {// --- Skill counter setting ----const skillSettingName = `Site/AI/${skillName}`;-const skillFileName = `Site-AI-${skillName}.sitesetting.yml`;+const skillSettingName = `Site/AI/Skills/${skillName}`;+const skillFileName = `Site-AI-Skills-${skillName}.sitesetting.yml`;const skillFilePath = path.join(siteSettingsDir, skillFileName);if (fs.existsSync(skillFilePath)) {@@ -100,18 +100,18 @@ if (fs.existsSync(skillFilePath)) {// --- Authoring tool setting ----const authoringFileName = 'Site-AI-AuthoringTool.sitesetting.yml';+const authoringFileName = 'Site-AI-Tools-AuthoringTool.sitesetting.yml';const authoringFilePath = path.join(siteSettingsDir, authoringFileName);if (!fs.existsSync(authoringFilePath)) {const fields = {description: 'Records which AI authoring tool was used',id: generateUuid(),- name: 'Site/AI/AuthoringTool',+ name: 'Site/AI/Tools/AuthoringTool',value: normalizedAuthoringTool};fs.writeFileSync(authoringFilePath, writeYaml(fields), 'utf8');- console.log(`Created Site/AI/AuthoringTool setting (value: ${normalizedAuthoringTool})`);+ console.log(`Created Site/AI/Tools/AuthoringTool setting (value: ${normalizedAuthoringTool})`);} else {- console.log('Site/AI/AuthoringTool setting already exists — preserved');+ console.log('Site/AI/Tools/AuthoringTool setting already exists — preserved');}diff --git a/plugins/power-pages/scripts/verify-dataverse-access.js b/plugins/power-pages/scripts/verify-dataverse-access.jsnew file mode 100644index 000000000..c8f3ce3ba--- /dev/null+++ b/plugins/power-pages/scripts/verify-dataverse-access.js@@ -0,0 +1,58 @@+#!/usr/bin/env node++// Verifies Dataverse API access by obtaining an Azure CLI token and calling WhoAmI.+// Usage: node verify-dataverse-access.js <environmentUrl>+// Outputs JSON: { "token": "...", "userId": "...", "organizationId": "...", "tenantId": "..." }+// Exit 0 on success, exit 1 on failure (error message on stderr).++const { getAuthToken, makeRequest } = require('./lib/validation-helpers');++async function main() {+ const envUrl = process.argv[2];+ if (!envUrl) {+ process.stderr.write('Usage: node verify-dataverse-access.js <environmentUrl>\n');+ process.exit(1);+ }++ const token = getAuthToken(envUrl);+ if (!token) {+ process.stderr.write('Failed to get Azure CLI token. Run `az login` first.\n');+ process.exit(1);+ }++ const res = await makeRequest({+ url: `${envUrl}/api/data/v9.2/WhoAmI`,+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },+ });++ if (res.error) {+ process.stderr.write(`API request failed: ${res.error}\n`);+ process.exit(1);+ }++ if (res.statusCode === 401 || res.statusCode === 403) {+ process.stderr.write(`Authentication failed (${res.statusCode}). Token may be expired — run \`az login\` again.\n`);+ process.exit(1);+ }++ if (res.statusCode !== 200) {+ process.stderr.write(`Unexpected response (${res.statusCode}): ${res.body}\n`);+ process.exit(1);+ }++ const data = JSON.parse(res.body);+ // Extract tenantId from JWT token payload+ let tenantId = null;+ try {+ const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());+ tenantId = payload.tid || null;+ } catch {}+ console.log(JSON.stringify({+ token,+ userId: data.UserId,+ organizationId: data.OrganizationId,+ tenantId,+ }));+}++main();diff --git a/plugins/power-pages/skills/activate-site/SKILL.md b/plugins/power-pages/skills/activate-site/SKILL.mdindex 6706f7709..780914ec7 100644--- a/plugins/power-pages/skills/activate-site/SKILL.md+++ b/plugins/power-pages/skills/activate-site/SKILL.md@@ -8,7 +8,7 @@ description: >Power Platform environment via the Power Platform REST API.user-invocable: trueallowed-tools: Read, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList-model: opus+model: sonnethooks:Stop:- hooks:@@ -283,6 +283,7 @@ Follow the skill tracking instructions in the reference to record this skill's u#### 5.3 Suggest Next StepsAfter the summary, suggest:+- Test the site: `/power-pages:test-site` — Verify the site loads correctly and API calls are working- Set up the data model: `/power-pages:setup-datamodel`- Add sample data: `/power-pages:add-sample-data`- View the site in the browser at the provisioned URL (note: it may take a few minutes for DNS to propagate)diff --git a/plugins/power-pages/skills/add-sample-data/SKILL.md b/plugins/power-pages/skills/add-sample-data/SKILL.mdindex 6f9f344c6..e7f8b4869 100644--- a/plugins/power-pages/skills/add-sample-data/SKILL.md+++ b/plugins/power-pages/skills/add-sample-data/SKILL.md@@ -8,7 +8,7 @@ description: >so they can test and demo their Power Pages site.user-invocable: trueallowed-tools: Read, Write, Bash, Grep, Glob, AskUserQuestion, Task, TaskCreate, TaskUpdate, TaskList, mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search, mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search, mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch-model: opus+model: sonnethooks:Stop:- hooks:@@ -70,14 +70,14 @@ See `${CLAUDE_PLUGIN_ROOT}/references/datamodel-manifest-schema.md` for the fullIf no manifest exists, discover custom tables via OData:-```powershell-$tables = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions?`$select=LogicalName,DisplayName,EntitySetName&`$filter=IsCustomEntity eq true" -Headers $headers+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions?\$select=LogicalName,DisplayName,EntitySetName&\$filter=IsCustomEntity eq true"```For each discovered table, fetch its custom columns:-```powershell-$columns = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes?`$select=LogicalName,DisplayName,AttributeType,RequiredLevel&`$filter=IsCustomAttribute eq true" -Headers $headers+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table>')/Attributes?\$select=LogicalName,DisplayName,AttributeType,RequiredLevel&\$filter=IsCustomAttribute eq true"```### 2.1 Present Available Tables@@ -172,17 +172,16 @@ Refer to `references/odata-record-patterns.md` for full patterns.For each table, get the entity set name (needed for the API URL):-```powershell-$entityDef = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')?`$select=EntitySetName" -Headers $headers-$entitySetName = $entityDef.EntitySetName+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table>')?\$select=EntitySetName"```### 5.2 Get Picklist OptionsFor any picklist/choice columns, query valid option values before insertion:-```powershell-$picklistMeta = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes(LogicalName='<column>')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?`$expand=OptionSet" -Headers $headers+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table>')/Attributes(LogicalName='<column>')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?\$expand=OptionSet"```Use the actual `Value` integers from the option set in your sample data.@@ -191,35 +190,20 @@ Use the actual `Value` integers from the option set in your sample data.Insert records into parent/referenced tables first to capture their IDs:-```powershell-$body = @{- cr123_name = "Sample Record"- cr123_description = "A sample record for testing"-} | ConvertTo-Json--$response = Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/<EntitySetName>" -Headers $headers -Body $body -ContentType "application/json"```--Capture the returned record ID from the `OData-EntityId` response header or by querying back:--```powershell-# The ID is in the response headers-# Or query: GET {envUrl}/api/data/v9.2/<EntitySetName>?$filter=cr123_name eq 'Sample Record'&$select=cr123_<table>id+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "<EntitySetName>" --body '{"cr123_name":"Sample Record","cr123_description":"A sample record for testing"}' --include-headers```+The `--include-headers` flag includes the `OData-EntityId` response header, which contains the created record ID. Parse the GUID from the response to use in child table lookups.+Store parent record IDs for use in child table lookups.### 5.4 Insert Child Tables with LookupsFor child/referencing tables, use `@odata.bind` syntax to set lookup fields:-```powershell-$body = @{- cr123_name = "Child Record"- "[email protected]" = "/<ParentEntitySetName>(<parent_guid>)"-} | ConvertTo-Json--Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/<ChildEntitySetName>" -Headers $headers -Body $body -ContentType "application/json"+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "<ChildEntitySetName>" --body '{"cr123_name":"Child Record","[email protected]":"/<ParentEntitySetName>(<parent_guid>)"}' --include-headers```### 5.5 Track Progress@@ -231,11 +215,10 @@ Track each insertion attempt:### 5.6 Refresh Token Periodically-Refresh the Azure CLI token every 20 records to avoid expiration:+The `dataverse-request.js` script handles 401 token refresh internally. For long-running operations (many records), periodically re-run `verify-dataverse-access.js` to confirm the session is still valid:-```powershell-$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv-$headers["Authorization"] = "Bearer $token"+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>```**Output**: All approved records inserted with parent-child relationships established@@ -252,8 +235,8 @@ $headers["Authorization"] = "Bearer $token"For each table that was populated, query the record count:-```powershell-$count = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/<EntitySetName>?`$count=true&`$top=0" -Headers $headers+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "<EntitySetName>?\$count=true&\$top=0"```The `@odata.count` field in the response gives the total record count.diff --git a/plugins/power-pages/skills/add-sample-data/references/odata-record-patterns.md b/plugins/power-pages/skills/add-sample-data/references/odata-record-patterns.mdindex 65e0191cc..8f0033f02 100644--- a/plugins/power-pages/skills/add-sample-data/references/odata-record-patterns.md+++ b/plugins/power-pages/skills/add-sample-data/references/odata-record-patterns.md@@ -12,10 +12,11 @@ Entity set names are required for all record operations. They differ from logica**Endpoint:** `GET {envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='<table>')?$select=EntitySetName`-```powershell-$entityDef = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='cr123_project')?`$select=EntitySetName" -Headers $headers-$entitySetName = $entityDef.EntitySetName # e.g., "cr123_projects"```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='cr123_project')?\$select=EntitySetName"+```++The response JSON `data.EntitySetName` contains the entity set name (e.g., `"cr123_projects"`).---@@ -23,37 +24,20 @@ $entitySetName = $entityDef.EntitySetName # e.g., "cr123_projects"**Endpoint:** `POST {envUrl}/api/data/v9.2/<EntitySetName>`-```powershell-$body = @{- cr123_name = "Website Redesign"- cr123_description = "Modernize the corporate website with a fresh design"- cr123_startdate = "2025-06-15T10:30:00Z"- cr123_budget = 15000.00- cr123_isactive = $true- cr123_status = 100000000-} | ConvertTo-Json--$response = Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/cr123_projects" -Headers $headers -Body $body -ContentType "application/json"+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "cr123_projects" --body '{"cr123_name":"Website Redesign","cr123_description":"Modernize the corporate website with a fresh design","cr123_startdate":"2025-06-15T10:30:00Z","cr123_budget":15000.00,"cr123_isactive":true,"cr123_status":100000000}'```### Capturing the Created Record ID-The record ID is returned in the `OData-EntityId` response header. To capture it:+The record ID is returned in the `OData-EntityId` response header. Use `--include-headers` to capture it:-```powershell-$response = Invoke-WebRequest -Method Post -Uri "$envUrl/api/data/v9.2/cr123_projects" -Headers $headers -Body $body -ContentType "application/json"-$entityId = $response.Headers["OData-EntityId"] -replace '.*\(([^)]+)\).*', '$1'```--Alternatively, use the `Prefer: return=representation` header to get the full record back:--```powershell-$headers["Prefer"] = "return=representation"-$response = Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/cr123_projects" -Headers $headers -Body $body -ContentType "application/json"-$recordId = $response.cr123_projectid-$headers.Remove("Prefer")+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "cr123_projects" --body '{"cr123_name":"Website Redesign"}' --include-headers```+The response JSON includes a `headers` object with the `OData-EntityId` value. Parse the GUID from it to use in subsequent lookups.+---## Column Type Values@@ -148,17 +132,12 @@ Before inserting records with picklist/choice columns, query the valid option va**Endpoint:** `GET {envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes(LogicalName='<column>')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$expand=OptionSet`-```powershell-$picklistMeta = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='cr123_project')/Attributes(LogicalName='cr123_status')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?`$expand=OptionSet" -Headers $headers--# Extract options-$options = $picklistMeta.OptionSet.Options-foreach ($opt in $options) {- $value = $opt.Value # e.g., 100000000- $label = $opt.Label.LocalizedLabels[0].Label # e.g., "Active"-}+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='cr123_project')/Attributes(LogicalName='cr123_status')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?\$expand=OptionSet"```+The response `data.OptionSet.Options` array contains objects with `Value` (e.g., `100000000`) and `Label.LocalizedLabels[0].Label` (e.g., `"Active"`).+Use these actual `Value` integers in your sample data — never guess option values.---@@ -169,26 +148,16 @@ Use these actual `Value` integers in your sample data — never guess option valA task referencing a project:-```powershell-$body = @{- cr123_name = "Design mockups"- cr123_duedate = "2025-07-01T00:00:00Z"- "[email protected]" = "/cr123_projects($projectGuid)"-} | ConvertTo-Json--Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/cr123_tasks" -Headers $headers -Body $body -ContentType "application/json"+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "cr123_tasks" --body '{"cr123_name":"Design mockups","cr123_duedate":"2025-07-01T00:00:00Z","[email protected]":"/cr123_projects(<projectGuid>)"}' --include-headers```### Multiple LookupsA record referencing multiple parent tables:-```powershell-$body = @{- cr123_name = "Project Update Meeting"- "[email protected]" = "/cr123_projects($projectGuid)"- "[email protected]" = "/contacts($contactGuid)"-} | ConvertTo-Json+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "<EntitySetName>" --body '{"cr123_name":"Project Update Meeting","[email protected]":"/cr123_projects(<projectGuid>)","[email protected]":"/contacts(<contactGuid>)"}' --include-headers```---@@ -199,10 +168,11 @@ Verify how many records exist in a table after insertion:**Endpoint:** `GET {envUrl}/api/data/v9.2/<EntitySetName>?$count=true&$top=0`-```powershell-$result = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/cr123_projects?`$count=true&`$top=0" -Headers $headers-$recordCount = $result."@odata.count"```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "cr123_projects?\$count=true&\$top=0"+```++The response `data["@odata.count"]` contains the total record count.The `$top=0` ensures no actual records are returned — only the count.@@ -216,13 +186,10 @@ For inserting many records efficiently, use OData batch requests to send multipl**Headers:**-```powershell-$batchId = [guid]::NewGuid().ToString()-$batchHeaders = @{- Authorization = "Bearer $token"- "Content-Type" = "multipart/mixed; boundary=batch_$batchId"- Accept = "application/json"-}+Authentication is handled automatically by `dataverse-request.js`. To send a batch request, use POST to the `$batch` endpoint. The script handles auth headers and token refresh internally:++```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "\$batch" --body '<batch body>'```**Body format:**diff --git a/plugins/power-pages/skills/add-seo/SKILL.md b/plugins/power-pages/skills/add-seo/SKILL.mdindex fa268dad8..b7d6469be 100644--- a/plugins/power-pages/skills/add-seo/SKILL.md+++ b/plugins/power-pages/skills/add-seo/SKILL.md@@ -8,7 +8,7 @@ description: >Power Pages code site after creating it with /power-pages:create-site.user-invocable: trueallowed-tools: Read, Write, Edit, Grep, Glob, Bash, AskUserQuestion, Task, TaskCreate, TaskUpdate, TaskList, mcp__plugin_power-pages_playwright__browser_navigate, mcp__plugin_power-pages_playwright__browser_snapshot, mcp__plugin_power-pages_playwright__browser_click, mcp__plugin_power-pages_playwright__browser_close-model: opus+model: sonnethooks:Stop:- hooks:diff --git a/plugins/power-pages/skills/audit-permissions/SKILL.md b/plugins/power-pages/skills/audit-permissions/SKILL.mdnew file mode 100644index 000000000..0f6ed2338--- /dev/null+++ b/plugins/power-pages/skills/audit-permissions/SKILL.md@@ -0,0 +1,341 @@+---+name: audit-permissions+description: >-+ Use this skill to audit existing table permissions on a Power Pages site.+ Trigger examples: "audit permissions", "check permissions", "review table permissions",+ "are my permissions correct", "permission security audit", "verify permissions setup",+ "check for permission issues", "permission health check".+ This skill analyzes existing table permissions against the site code and Dataverse metadata,+ generates an HTML audit report with findings grouped by severity (critical, warning, info, pass),+ and suggests fixes for any issues found.+user-invocable: true+argument-hint: "[optional: specific table or concern]"+allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, mcp__plugin_power-pages_playwright__browser_resize, mcp__plugin_power-pages_playwright__browser_navigate, mcp__plugin_power-pages_playwright__browser_wait_for+model: opus+hooks:+ Stop:+ - hooks:+ - type: command+ command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/audit-permissions/scripts/validate-audit.js"'+ timeout: 15+ - type: prompt+ prompt: >+ If a permissions audit was being performed in this session (via /power-pages:audit-permissions),+ verify before allowing stop: 1) The site's permissions structure was analyzed (web roles,+ table permissions, code references), 2) An HTML audit report was generated with findings+ and inventory, 3) The report was displayed to the user via Playwright or+ the file path was communicated, 4) A summary with finding counts was presented. If any of+ these are incomplete, return { "ok": false, "reason": "<specific issues>" }. If no audit+ work happened or everything is complete, return { "ok": true }.+ timeout: 30+---++# Audit Permissions++Audit existing table permissions on a Power Pages code site. Analyze permissions against the site code and Dataverse metadata, then generate a visual HTML audit report with findings, reasoning, and suggested fixes.++## Workflow++1. **Verify Site Deployment** — Check that `.powerpages-site` folder and table permissions exist+2. **Gather Configuration** — Read all web roles, table permissions, and site code+3. **Analyze & Discover** — Query Dataverse for relationships and lookup columns using deterministic scripts+4. **Run Audit Checks** — Compare permissions against code usage and best practices+5. **Generate Report** — Create the HTML audit report and display in browser+6. **Present Findings & Track** — Summarize findings, record skill usage, and ask user if they want to fix issues++**Important:** Do NOT ask the user questions during analysis. Autonomously gather all data, then present findings.++## Task Tracking++At the start of Step 1, create all tasks upfront using `TaskCreate`. Mark each task `in_progress` when starting and `completed` when done.++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Verify site deployment | Verifying site deployment | Check .powerpages-site folder and table permissions exist |+| Gather configuration | Gathering configuration | Read web roles, table permissions, and site code |+| Discover relationships | Discovering relationships | Query Dataverse for lookup columns and relationships |+| Run audit checks | Running audit checks | Analyze permissions against code and best practices |+| Generate audit report | Generating audit report | Create HTML report and display in browser |+| Present findings | Presenting findings | Summarize results, record usage, and offer to fix issues |++---++## Step 1: Verify Site Deployment++Use `Glob` to find:+- `**/powerpages.config.json` — identifies the project root+- `**/.powerpages-site/table-permissions/*.tablepermission.yml` — existing permissions++If no `.powerpages-site` folder exists, stop and tell the user to deploy first using `/power-pages:deploy-site`.+If no table permissions exist, note this as a critical finding (the site may have no data access configured) and continue the audit — there may still be code references that need permissions.++---++## Step 2: Gather Configuration++### 2.1 Read Web Roles++Read all files matching `**/.powerpages-site/web-roles/*.yml`. Extract `id`, `name`, `anonymoususersrole`, `authenticatedusersrole` from each.++### 2.2 Read Table Permissions++Read all files matching `**/.powerpages-site/table-permissions/*.tablepermission.yml`. For each permission, extract:+- `entityname` (permission name)+- `entitylogicalname` (table)+- `scope` (numeric code)+- `read`, `create`, `write`, `delete`, `append`, `appendto` (boolean flags)+- `adx_entitypermission_webrole` (array of web role UUIDs)+- `parententitypermission`, `parentrelationshipname` (if parent scope)++### 2.3 Analyze Site Code++Search the source code to understand which tables the site actually uses:++```text+Grep: "/_api/" in src/**/*.ts src/**/*.tsx src/**/*.js src/**/*.jsx+Grep: "@odata\.bind" in src/**/*.ts src/**/*.tsx+Grep: "uploadFileColumn|uploadFile|upload\w+Photo|upload\w+Image" in src/**/*.ts+```++Also check for `.datamodel-manifest.json` in the project root for the authoritative table list.++Build a map of: which tables are referenced in code, which CRUD operations are performed on each, and which lookup relationships are used.++---++## Step 3: Analyze & Discover (Dataverse API)++Use deterministic Node.js scripts for all Dataverse API calls. These scripts handle auth token acquisition, HTTP requests, and JSON parsing consistently.++### 3.1 Get Environment URL++```powershell+pac env who+```++Extract the `Environment URL` (e.g., `https://org12345.crm.dynamics.com`). Store as `$envUrl`.++### 3.2 Query Lookup Columns++For each table that has permissions with `create` or `write` enabled, use the lookup query script:++```powershell+$lookups = node "${CLAUDE_PLUGIN_ROOT}/skills/audit-permissions/scripts/query-table-lookups.js" --envUrl "$envUrl" --table "<table_logical_name>"+```++The script returns a JSON array of `{ logicalName, targets }` for each lookup column. Use this to build the append/appendto map:+- The **source table** (with the lookup) needs `append: true`+- Each **target table** in `targets` needs `appendto: true`++### 3.3 Query Relationships++For tables with parent-scope permissions, verify the relationship names using the relationship query script:++```powershell+$rels = node "${CLAUDE_PLUGIN_ROOT}/skills/audit-permissions/scripts/query-table-relationships.js" --envUrl "$envUrl" --table "<parent_table>"+```++The script returns a JSON array of `{ schemaName, referencedEntity, referencingEntity, referencingAttribute }`. Use `schemaName` to validate the `parentrelationshipname` value in parent-scope permissions.++### Error Handling++If any script exits with code 1, skip the API-dependent checks and note which checks were skipped in the report. Do NOT stop the entire audit for auth errors. Use the data model manifest and code analysis as fallback.++---++## Step 4: Run Audit Checks++Run every applicable check below. Each check produces a finding with severity, title, reasoning, and a suggested fix. Findings can be `critical`, `warning`, `info`, or `pass`.++### Check Categories++#### 4.1 Missing Permissions (Critical)++For each table referenced in site code (from Step 2.3), verify that a table permission exists. If a table is used in code but has no permission:+- **Severity:** `critical`+- **Title:** `Missing permission for <table>`+- **Reasoning:** Explain which code file references this table and what operations it performs+- **Fix:** Suggest creating a permission with the appropriate scope and CRUD flags++#### 4.2 Overly Broad Scope (Warning)++For each permission with Global scope (`756150000`) that has `write` or `delete` enabled:+- **Severity:** `warning`+- **Title:** `Global scope with write/delete on <table>`+- **Reasoning:** Explain why Global write/delete is risky — any user with this role can modify/delete any record+- **Fix:** Suggest narrowing to Contact or Account scope, or removing write/delete if not needed++For Global scope with only `read` enabled, this is acceptable for public reference data — mark as `pass`.++#### 4.3 Missing Append/AppendTo (Critical)++For each permission with `create` or `write` enabled, check if the table has lookup columns (from Step 3.2). If lookups exist:+- The **source table** (with the lookup) needs `append: true`+- The **target table** needs `appendto: true`++If these are missing:+- **Severity:** `critical`+- **Title:** `Missing append on <source_table>` or `Missing appendto on <target_table>`+- **Reasoning:** Explain which lookup column requires this and what error the user will see ("You don't have permission to associate or disassociate")+- **Fix:** Suggest enabling the missing flag++#### 4.4 Orphaned Permissions (Info)++For each permission, check if the table is actually referenced in the site code. If not:+- **Severity:** `info`+- **Title:** `Unused permission for <table>`+- **Reasoning:** The table is not referenced in any source code — the permission may be unnecessary+- **Fix:** Suggest reviewing whether this permission is still needed++#### 4.5 Missing Web Role Association (Warning)++For each permission where `adx_entitypermission_webrole` is empty or missing:+- **Severity:** `warning`+- **Title:** `Permission <name> has no web role association`+- **Reasoning:** A permission without a web role association has no effect — no users will receive this access+- **Fix:** Suggest associating with the appropriate web role++#### 4.6 Parent Chain Integrity (Critical)++For each permission with Parent scope (`756150003`):+- Verify `parententitypermission` references a valid permission ID that exists+- Verify `parentrelationshipname` is a valid Dataverse relationship (if API available, using Step 3.3 results)++If broken:+- **Severity:** `critical`+- **Title:** `Broken parent chain for <permission>`+- **Reasoning:** The parent permission reference is invalid — this permission will not grant any access+- **Fix:** Suggest correcting the parent reference++#### 4.7 Write Without Read (Warning)++For each permission with `write: true` but `read: false`:+- **Severity:** `warning`+- **Title:** `Write enabled without read on <table>`+- **Reasoning:** Users can modify records they cannot see, which is unusual and likely unintended+- **Fix:** Suggest enabling read++#### 4.8 File Upload Without Write (Warning)++If the code contains file upload patterns (detected in Step 2.3) but the table's permission has `write: false`:+- **Severity:** `warning`+- **Title:** `File upload detected but write is disabled on <table>`+- **Reasoning:** File uploads use PATCH which requires write permission+- **Fix:** Suggest enabling write on the permission++#### 4.9 Passed Checks++For each check that passes (e.g., a table has correct permissions, a scope is appropriate), create a `pass` severity finding briefly noting what was verified. This gives the user confidence that the audit was thorough.++---++## Step 5: Generate Report++### 5.1 Determine Output Location++- **If working in context of a website** (project root with `powerpages.config.json` exists): write to `<PROJECT_ROOT>/docs/permissions-audit.html`+- **Otherwise**: write to the system temp directory++### 5.2 Prepare Data++**Do NOT generate HTML manually or read/modify the template yourself.** Use the `render-plan.js` script which mechanically reads the template and replaces placeholder tokens with your data.++Write a temporary JSON data file (e.g., `<OUTPUT_DIR>/audit-data.json`) with these keys:++```json+{+ "SITE_NAME": "The site name (from powerpages.config.json or folder name)",+ "AUDIT_DESC": "Security audit of table permissions for Contoso Portal",+ "SUMMARY": "2-3 sentence summary of the audit results",+ "FINDINGS_DATA": [/* array of finding objects */],+ "INVENTORY_DATA": [/* array of current permission objects */]+}+```++**FINDINGS_DATA format:**++```json+{+ "id": "f1",+ "severity": "critical",+ "title": "Missing permission for cra5b_product",+ "table": "cra5b_product",+ "scope": null,+ "permission": null,+ "reasoning": "The table cra5b_product is referenced in src/services/productService.ts with GET requests to /_api/cra5b_products, but no table permission exists for this table.",+ "fix": "Create a table permission with Global scope and read-only access for the Anonymous Users role.",+ "details": "Referenced in: src/services/productService.ts (line 23), src/components/ProductList.tsx (line 45)"+}+```++- `severity`: One of `critical`, `warning`, `info`, `pass`+- `table`: The table logical name this finding relates to (or `null` for general findings)+- `scope`: The current scope if applicable (numeric code or friendly name), or `null`+- `permission`: The permission name if this finding is about an existing permission, or `null`+- `reasoning`: Detailed explanation of why this is an issue — reference specific code files, line patterns, or Dataverse metadata+- `fix`: Actionable suggestion for how to resolve the issue (or `null` for `pass` findings)+- `details`: Additional context like file references, column names, or relationship details++**INVENTORY_DATA format:**++```json+{+ "name": "Product - Anonymous Read",+ "table": "cra5b_product",+ "scope": "Global",+ "roles": ["Anonymous Users"],+ "read": true,+ "create": false,+ "write": false,+ "delete": false,+ "append": false,+ "appendto": true+}+```++### 5.3 Render the HTML File++Run the render script (it creates the output directory if needed):++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/render-audit-report.js" --output "<OUTPUT_PATH>" --data "<DATA_JSON_PATH>"+```++Delete the temporary data JSON file after the script succeeds.++### 5.4 Open in Browser++1. Use `browser_resize` with **width: 1920** and **height: 1080**+2. Navigate Playwright to the file using `file:///` URL (convert backslashes to forward slashes)+3. Wait ~2 seconds for rendering++---++## Step 6: Present Findings & Track++### 6.1 Record Skill Usage++> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`++Follow the skill tracking instructions in the reference to record this skill's usage. Use `--skillName "AuditPermissions"`.++### 6.2 Present Summary++Present a summary to the user:++1. **Critical findings count** — these need immediate attention+2. **Warning findings count** — should be addressed+3. **Report location** — where the HTML file was saved+5. **Ask the user** using `AskUserQuestion`: "Would you like me to fix any of these issues? I can create or update table permissions to resolve the critical and warning findings."++If the user wants fixes applied, use the `${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js` script for new permissions or explain what manual changes are needed for existing permissions. For complex fixes, suggest running `/power-pages:setup-permissions` to architect a complete permissions plan.++---++## Critical Constraints++- **Read-only analysis**: This skill only reads existing configuration and code. It does NOT modify any files unless the user explicitly asks to fix issues.+- **Deterministic API calls**: Always use the Node.js scripts (`query-table-lookups.js`, `query-table-relationships.js`) for Dataverse API queries — never use inline PowerShell `Invoke-RestMethod` calls.+- **No questions during analysis**: Autonomously gather all data, run checks, and present findings. Only ask the user at the end about fixing issues.+- **Security**: Never log or display auth tokens. The scripts handle token acquisition internally via `getAuthToken()`.+- **Graceful degradation**: If Dataverse API scripts fail (exit code 1), skip API-dependent checks (4.3 append/appendto validation, 4.6 relationship verification) and note in the report which checks were skipped.diff --git a/plugins/power-pages/skills/audit-permissions/assets/audit-report.html b/plugins/power-pages/skills/audit-permissions/assets/audit-report.htmlnew file mode 100644index 000000000..953e5cad2--- /dev/null+++ b/plugins/power-pages/skills/audit-permissions/assets/audit-report.html@@ -0,0 +1,379 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8"/>+<meta name="viewport" content="width=device-width,initial-scale=1.0"/>+<title>Permissions Audit — __SITE_NAME__</title>+<style>+:root {+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --surface3:#edebe9;+ --border:#e1dfdd; --border-light:#c8c6c4;+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e;+ --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;+ --critical:#d13438; --critical-bg:#d134380a; --critical-border:#d1343825;+ --warning:#ca5010; --warning-bg:#ca50100a; --warning-border:#ca501025;+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1025;+ --info:#0078d4; --info-bg:#0078d40a; --info-border:#0078d425;+ --purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b825;+ --mono:'Cascadia Code','Consolas',monospace;+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;+ --radius:8px; --radius-sm:4px;+ --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);+ --shadow-8:0 3.2px 7.2px 0 rgba(0,0,0,0.132),0 0.6px 1.8px 0 rgba(0,0,0,0.108);+}+*{margin:0;padding:0;box-sizing:border-box;}+html{scroll-behavior:smooth;}+body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;}+++/* Top Bar */+.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;}+.topbar-left{display:flex;align-items:center;gap:14px;}+.logo{width:36px;height:36px;border-radius:var(--radius);background:linear-gradient(135deg,#0078d4,#5c2d91);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:800;color:#fff;font-family:var(--mono);letter-spacing:-0.5px;}+.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}+.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;}++/* Layout */+.layout{display:flex;min-height:calc(100vh - 61px);}++/* Sidebar */+.sidebar{width:200px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}+.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;position:relative;}+.nav-btn:hover{color:var(--text);background:var(--surface2);}+.nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}+.nav-btn .nav-icon{font-size:15px;opacity:0.5;width:18px;text-align:center;}+.nav-btn.active .nav-icon{opacity:0.9;}+.nav-badge{position:absolute;right:14px;font-size:10px;font-family:var(--mono);padding:1px 6px;border-radius:8px;font-weight:700;}++/* Content */+.content{flex:1;padding:32px 40px;max-width:960px;}+.section{display:none;}+.section.active{display:block;animation:fadeIn 0.3s ease;}+@keyframes fadeIn{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}++h2{font-size:21px;font-weight:800;color:var(--text-bright);letter-spacing:-0.3px;margin-bottom:5px;}+.section-desc{font-size:13px;color:var(--text-dim);margin-bottom:20px;}+h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margin-bottom:12px;}++/* Cards */+.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:10px;transition:box-shadow 0.2s;}+.card:hover{box-shadow:var(--shadow-4);}++/* Stats Grid */+.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:24px;}+.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;position:relative;overflow:hidden;box-shadow:var(--shadow-4);}+.stat-card::after{content:'';position:absolute;top:0;left:50%;transform:translateX(-50%);width:40px;height:2px;border-radius:0 0 2px 2px;}+.stat-num{font-size:28px;font-weight:800;font-family:var(--mono);line-height:1;}+.stat-label{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-top:6px;}++/* Severity badges */+.severity{font-size:9px;font-weight:700;padding:3px 8px;border-radius:3px;font-family:var(--mono);display:inline-block;text-transform:uppercase;letter-spacing:0.5px;}+.severity-critical{color:var(--critical);background:var(--critical-bg);border:1px solid var(--critical-border);}+.severity-warning{color:var(--warning);background:var(--warning-bg);border:1px solid var(--warning-border);}+.severity-info{color:var(--info);background:var(--info-bg);border:1px solid var(--info-border);}+.severity-pass{color:var(--pass);background:var(--pass-bg);border:1px solid var(--pass-border);}++/* Finding cards */+.finding-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:12px;transition:box-shadow 0.2s;overflow:hidden;}+.finding-card:hover{box-shadow:var(--shadow-4);}+.finding-header{display:flex;align-items:flex-start;gap:12px;padding:16px 20px;cursor:pointer;-webkit-user-select:none;user-select:none;}+.finding-header:hover{background:var(--surface2);}+.finding-title{font-size:14px;font-weight:600;color:var(--text-bright);flex:1;}+.finding-table{font-size:11px;color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;border:1px solid var(--accent-border);font-family:var(--mono);}+.finding-chevron{color:var(--text-dim);font-size:12px;transition:transform 0.2s;flex-shrink:0;margin-top:3px;}+.finding-card.expanded .finding-chevron{transform:rotate(90deg);}+.finding-body{display:none;padding:0 20px 16px;border-top:1px solid var(--border);}+.finding-card.expanded .finding-body{display:block;animation:fadeIn 0.2s ease;}++/* Field label */+.field-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;}++/* Reasoning & fix blocks */+.reasoning-block{background:var(--surface2);border-left:2px solid var(--accent);border-radius:var(--radius-sm);padding:10px 14px;margin-top:10px;font-size:12px;color:var(--text);line-height:1.7;}+.fix-block{background:var(--pass-bg);border-left:2px solid var(--pass);border-radius:var(--radius-sm);padding:10px 14px;margin-top:8px;font-size:12px;color:var(--text);line-height:1.7;}+.fix-block strong{color:var(--pass);}++/* Scope Tags */+.scope-tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:3px;font-family:var(--mono);display:inline-block;text-align:center;min-width:58px;}+.scope-Global{color:var(--critical);background:var(--critical-bg);border:1px solid var(--critical-border);}+.scope-Contact{color:var(--pass);background:var(--pass-bg);border:1px solid var(--pass-border);}+.scope-Account{color:var(--accent);background:var(--accent-bg);border:1px solid var(--accent-border);}+.scope-Parent{color:var(--purple);background:var(--purple-bg);border:1px solid var(--purple-border);}+.scope-Self{color:var(--text-dim);background:var(--surface2);border:1px solid var(--border);}++/* Privilege Chips */+.priv{font-size:9px;font-weight:700;padding:2px 5px;border-radius:3px;font-family:var(--mono);}+.priv-on{color:var(--pass);background:var(--pass-bg);}+.priv-off{color:var(--text-dim);background:var(--surface2);opacity:0.5;}++/* Inventory table */+.inv-table{width:100%;border-collapse:collapse;font-size:13px;margin:10px 0;}+.inv-table th{text-align:left;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.8px;color:var(--text-dim);padding:10px 12px;border-bottom:2px solid var(--border);}+.inv-table td{padding:10px 12px;border-bottom:1px solid var(--border);vertical-align:top;}+.inv-table tr:last-child td{border-bottom:none;}+.inv-table tr:hover td{background:var(--surface2);}++/* Filter buttons */+.filter-bar{display:flex;gap:6px;margin-bottom:16px;flex-wrap:wrap;}+.filter-btn{padding:5px 12px;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface);color:var(--text-dim);font-size:12px;font-weight:600;cursor:pointer;font-family:var(--sans);transition:all 0.15s;}+.filter-btn:hover{border-color:var(--border-light);color:var(--text);}+.filter-btn.active{background:var(--accent-bg);border-color:var(--accent-border);color:var(--accent);}+.filter-count{font-family:var(--mono);font-size:10px;margin-left:4px;opacity:0.7;}++/* Responsive */+@media(max-width:768px){+ .sidebar{display:none;}+ .content{padding:20px 16px;}+ .stats-grid{grid-template-columns:repeat(2,1fr);}+}+</style>+</head>+<body>++<div id="mainApp">+ <div class="topbar">+ <div class="topbar-left">+ <div class="logo">PP</div>+ <div>+ <div class="topbar-title">Permissions Audit Report</div>+ <div class="topbar-sub">__SITE_NAME__</div>+ </div>+ </div>+ </div>++ <div class="layout">+ <div class="sidebar">+ <button class="nav-btn active" data-tab="overview"><span class="nav-icon">◉</span> Overview</button>+ <button class="nav-btn" data-tab="findings"><span class="nav-icon">⚠</span> Findings+ <span class="nav-badge" id="navFindingsCount" style="background:var(--critical-bg);color:var(--critical);"></span>+ </button>+ <button class="nav-btn" data-tab="inventory"><span class="nav-icon">▦</span> Inventory</button>+ </div>++ <div class="content">++ <!-- OVERVIEW -->+ <div class="section active" id="tab-overview">+ <h2>Audit Overview</h2>+ <p class="section-desc">__AUDIT_DESC__</p>++ <div class="stats-grid">+ <div class="stat-card" style="--accent-color:var(--critical)"><div class="stat-num" style="color:var(--critical)" id="statCritical">0</div><div class="stat-label">Critical</div></div>+ <div class="stat-card"><div class="stat-num" style="color:var(--warning)" id="statWarning">0</div><div class="stat-label">Warning</div></div>+ <div class="stat-card"><div class="stat-num" style="color:var(--info)" id="statInfo">0</div><div class="stat-label">Info</div></div>+ <div class="stat-card"><div class="stat-num" style="color:var(--pass)" id="statPassed">0</div><div class="stat-label">Passed</div></div>+ </div>++ <h3>Audit Summary</h3>+ <div class="card" id="summaryBox" style="line-height:1.75;">__SUMMARY__</div>++ </div>++ <!-- FINDINGS -->+ <div class="section" id="tab-findings">+ <h2>Findings</h2>+ <p class="section-desc" id="findingsDesc"></p>+ <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">+ <div class="filter-bar" id="filterBar" style="margin-bottom:0;"></div>+ <button class="filter-btn" id="expandAllBtn" onclick="toggleExpandAll()" style="white-space:nowrap;">Expand All</button>+ </div>+ <div id="findingsContainer" style="margin-top:16px;"></div>+ </div>++ <!-- INVENTORY -->+ <div class="section" id="tab-inventory">+ <h2>Permissions Inventory</h2>+ <p class="section-desc" id="invDesc"></p>++ <h3>Legend</h3>+ <div class="card" style="margin-bottom:16px;">+ <div style="display:flex;gap:32px;flex-wrap:wrap;">+ <div>+ <div class="field-label" style="margin-bottom:6px;">Scope</div>+ <div style="display:flex;gap:6px;flex-wrap:wrap;">+ <span class="scope-tag scope-Global">Global</span>+ <span class="scope-tag scope-Contact">Contact</span>+ <span class="scope-tag scope-Account">Account</span>+ <span class="scope-tag scope-Parent">Parent</span>+ <span class="scope-tag scope-Self">Self</span>+ </div>+ <div style="font-size:11px;color:var(--text-dim);margin-top:6px;line-height:1.6;">+ <strong>Global</strong> — all records | + <strong>Contact</strong> — user's contact | + <strong>Account</strong> — user's account | + <strong>Parent</strong> — via parent table | + <strong>Self</strong> — own record only+ </div>+ </div>+ <div>+ <div class="field-label" style="margin-bottom:6px;">Privileges</div>+ <div style="display:flex;flex-direction:column;gap:4px;font-size:12px;">+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">R</span><strong style="color:var(--text-bright);">Read</strong><span style="color:var(--text-dim);">— Retrieve and view records</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">C</span><strong style="color:var(--text-bright);">Create</strong><span style="color:var(--text-dim);">— Add new records</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">W</span><strong style="color:var(--text-bright);">Write</strong><span style="color:var(--text-dim);">— Update existing records (includes file uploads via PATCH)</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">D</span><strong style="color:var(--text-bright);">Delete</strong><span style="color:var(--text-dim);">— Remove records</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">A</span><strong style="color:var(--text-bright);">Append</strong><span style="color:var(--text-dim);">— Attach this record to another via a lookup</span></div>+ <div style="display:flex;align-items:center;gap:6px;"><span class="priv priv-on">AT</span><strong style="color:var(--text-bright);">AppendTo</strong><span style="color:var(--text-dim);">— Allow other records to reference this one via a lookup</span></div>+ </div>+ <div style="font-size:11px;color:var(--text-dim);margin-top:8px;">+ <span class="priv priv-on" style="font-size:8px;">R</span> enabled + <span class="priv priv-off" style="font-size:8px;">R</span> disabled+ </div>+ </div>+ </div>+ </div>++ <div id="invContainer"></div>+ </div>++ </div>+ </div>+</div>++<script>+// Data populated by the audit-permissions skill+const SITE_NAME = "__SITE_NAME__";++const FINDINGS = __FINDINGS_DATA__;+// Each finding: { id, severity (critical|warning|info|pass), title, table, scope, permission, reasoning, fix, details }++const INVENTORY = __INVENTORY_DATA__;+// Each item: { name, table, scope, roles, read, create, write, delete, append, appendto }++// Tab navigation+document.querySelectorAll('.nav-btn').forEach(btn => {+ btn.addEventListener('click', () => {+ document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));+ btn.classList.add('active');+ document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));+ document.getElementById('tab-' + btn.dataset.tab).classList.add('active');+ });+});++// Severity config+const sevConfig = {+ critical: { color: 'var(--critical)', label: 'CRITICAL', icon: '\u2716' },+ warning: { color: 'var(--warning)', label: 'WARNING', icon: '\u26A0' },+ info: { color: 'var(--info)', label: 'INFO', icon: '\u2139' },+ pass: { color: 'var(--pass)', label: 'PASSED', icon: '\u2714' }+};++const scopeNames = { 756150000:'Global', 756150001:'Contact', 756150002:'Account', 756150003:'Parent', 756150004:'Self' };+function scopeName(s) { return scopeNames[s] || s; }++// Stats+const criticalCount = FINDINGS.filter(f => f.severity === 'critical').length;+const warningCount = FINDINGS.filter(f => f.severity === 'warning').length;+const infoCount = FINDINGS.filter(f => f.severity === 'info').length;+const passCount = FINDINGS.filter(f => f.severity === 'pass').length;+const issueCount = criticalCount + warningCount + infoCount;++document.getElementById('statCritical').textContent = criticalCount;+document.getElementById('statWarning').textContent = warningCount;+document.getElementById('statInfo').textContent = infoCount;+document.getElementById('statPassed').textContent = passCount;+document.getElementById('navFindingsCount').textContent = issueCount > 0 ? issueCount : '';++document.getElementById('findingsDesc').textContent =+ FINDINGS.length + ' check' + (FINDINGS.length !== 1 ? 's' : '') ++ ' \u2014 ' + criticalCount + ' critical, ' + warningCount + ' warning, ' + infoCount + ' info, ' + passCount + ' passed.';++document.getElementById('invDesc').textContent =+ INVENTORY.length + ' table permission' + (INVENTORY.length !== 1 ? 's' : '') + ' currently configured.';++// Filter bar+let activeFilter = 'all';+function renderFilterBar() {+ const c = document.getElementById('filterBar');+ const counts = { all: FINDINGS.length, critical: criticalCount, warning: warningCount, info: infoCount, pass: passCount };+ const labels = { all: 'All', critical: 'Critical', warning: 'Warning', info: 'Info', pass: 'Passed' };+ let html = '';+ Object.entries(labels).forEach(([key, label]) => {+ if (counts[key] === 0 && key !== 'all') return;+ html += `<button class="filter-btn ${activeFilter === key ? 'active' : ''}" onclick="setFilter('${key}')">${label}<span class="filter-count">${counts[key]}</span></button>`;+ });+ c.innerHTML = html;+}+function setFilter(f) {+ activeFilter = f;+ renderFilterBar();+ renderFindings();+}++// Render findings+function renderFindings() {+ const c = document.getElementById('findingsContainer');+ const filtered = activeFilter === 'all' ? FINDINGS : FINDINGS.filter(f => f.severity === activeFilter);++ // Sort: critical first, then warning, info, pass+ const order = { critical: 0, warning: 1, info: 2, pass: 3 };+ const sorted = [...filtered].sort((a, b) => (order[a.severity] ?? 99) - (order[b.severity] ?? 99));++ let html = '';+ sorted.forEach(f => {+ const sev = sevConfig[f.severity] || sevConfig.info;+ html += `<div class="finding-card" id="finding-${f.id}">+ <div class="finding-header" onclick="document.getElementById('finding-${f.id}').classList.toggle('expanded')">+ <span class="severity severity-${f.severity}">${sev.label}</span>+ <span class="finding-title">${f.title}</span>+ ${f.table ? `<span class="finding-table">${f.table}</span>` : ''}+ <span class="finding-chevron">▶</span>+ </div>+ <div class="finding-body">+ ${f.permission ? `<div style="margin-top:10px;font-size:12px;"><span class="field-label">Permission:</span> <span style="font-weight:600;color:var(--text-bright)">${f.permission}</span></div>` : ''}+ ${f.scope ? `<div style="margin-top:6px;font-size:12px;"><span class="field-label">Scope:</span> <span class="scope-tag scope-${scopeName(f.scope)}" style="font-size:10px;padding:1px 6px;min-width:auto;">${scopeName(f.scope)}</span></div>` : ''}+ ${f.details ? `<div style="margin-top:10px;font-size:12px;color:var(--text);line-height:1.7;">${f.details}</div>` : ''}+ ${f.reasoning ? `<div style="margin-top:10px;"><div class="field-label">Reasoning</div><div class="reasoning-block">${f.reasoning}</div></div>` : ''}+ ${f.fix ? `<div style="margin-top:8px;"><div class="field-label">Suggested Fix</div><div class="fix-block"><strong>Fix:</strong> ${f.fix}</div></div>` : ''}+ </div>+ </div>`;+ });++ if (sorted.length === 0) {+ html = '<div style="text-align:center;padding:40px;color:var(--text-dim);font-size:14px;">No findings for this filter.</div>';+ }+ c.innerHTML = html;+}++// Expand/Collapse All+let allExpanded = false;+function toggleExpandAll() {+ allExpanded = !allExpanded;+ document.querySelectorAll('.finding-card').forEach(c => {+ if (allExpanded) c.classList.add('expanded');+ else c.classList.remove('expanded');+ });+ document.getElementById('expandAllBtn').textContent = allExpanded ? 'Collapse All' : 'Expand All';+}++// Render inventory+function renderInventory() {+ const c = document.getElementById('invContainer');+ if (INVENTORY.length === 0) {+ c.innerHTML = '<div style="text-align:center;padding:40px;color:var(--text-dim);font-size:14px;">No table permissions configured.</div>';+ return;+ }+ const privs = ['Read','Create','Write','Delete','Append','AppendTo'];+ let html = '<table class="inv-table"><thead><tr><th>Permission Name</th><th>Table</th><th>Scope</th><th>Roles</th><th>Privileges</th></tr></thead><tbody>';+ INVENTORY.forEach(p => {+ const flags = { Read: p.read, Create: p.create, Write: p.write, Delete: p.delete, Append: p.append, AppendTo: p.appendto };+ html += `<tr>+ <td style="font-weight:600;color:var(--text-bright)">${p.name}</td>+ <td><code style="font-size:11px;color:var(--accent);background:var(--accent-bg);padding:1px 5px;border-radius:3px;border:1px solid var(--accent-border);">${p.table}</code></td>+ <td><span class="scope-tag scope-${scopeName(p.scope)}" style="font-size:9px;padding:1px 6px;min-width:auto;">${scopeName(p.scope)}</span></td>+ <td style="font-size:12px;">${Array.isArray(p.roles) ? p.roles.join(', ') : p.roles}</td>+ <td style="display:flex;gap:3px;flex-wrap:wrap;">${privs.map(pr => `<span class="priv ${flags[pr] ? 'priv-on' : 'priv-off'}">${pr[0]}${pr === 'AppendTo' ? 'T' : ''}</span>`).join('')}</td>+ </tr>`;+ });+ html += '</tbody></table>';+ c.innerHTML = html;+}++// Init+renderFilterBar();+renderFindings();+renderInventory();+</script>+<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;">AI-generated content may be incorrect</footer>+</body>+</html>diff --git a/plugins/power-pages/skills/audit-permissions/scripts/query-table-lookups.js b/plugins/power-pages/skills/audit-permissions/scripts/query-table-lookups.jsnew file mode 100644index 000000000..e015000d0--- /dev/null+++ b/plugins/power-pages/skills/audit-permissions/scripts/query-table-lookups.js@@ -0,0 +1,65 @@+#!/usr/bin/env node++// Queries Dataverse for lookup columns on a given table.+// Returns JSON array of { logicalName, targets } for each lookup column.+//+// Usage:+// node query-table-lookups.js --envUrl <url> --table <logical_name>+//+// Output (stdout): JSON array+// [{ "logicalName": "cr4fc_categoryid", "targets": ["cr4fc_category"] }]+//+// Exit codes:+// 0 = success (JSON on stdout)+// 1 = error (message on stderr)++const { getAuthToken, makeRequest } = require('../../../scripts/lib/validation-helpers');++const args = process.argv.slice(2);+function getArg(name) {+ const idx = args.indexOf('--' + name);+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;+}++const envUrl = getArg('envUrl');+const table = getArg('table');++if (!envUrl || !table) {+ process.stderr.write('Usage: node query-table-lookups.js --envUrl <url> --table <logical_name>\n');+ process.exit(1);+}++(async () => {+ const token = getAuthToken(envUrl);+ if (!token) {+ process.stderr.write('Failed to get auth token. Run: az login\n');+ process.exit(1);+ }++ try {+ const result = await makeRequest({+ url: `${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${table}')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets`,+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: 'application/json',+ },+ timeout: 15000,+ });++ if (result.error || result.statusCode !== 200) {+ process.stderr.write(`API error (${result.statusCode}): ${result.error || result.body}\n`);+ process.exit(1);+ }++ const parsed = JSON.parse(result.body);+ const lookups = (parsed.value || []).map(attr => ({+ logicalName: attr.LogicalName,+ targets: attr.Targets || [],+ }));++ process.stdout.write(JSON.stringify(lookups, null, 2) + '\n');+ } catch (err) {+ process.stderr.write(`Request failed: ${err.message}\n`);+ process.exit(1);+ }+})();diff --git a/plugins/power-pages/skills/audit-permissions/scripts/query-table-relationships.js b/plugins/power-pages/skills/audit-permissions/scripts/query-table-relationships.jsnew file mode 100644index 000000000..12026acc0--- /dev/null+++ b/plugins/power-pages/skills/audit-permissions/scripts/query-table-relationships.js@@ -0,0 +1,67 @@+#!/usr/bin/env node++// Queries Dataverse for one-to-many relationships on a given table.+// Returns JSON array of { schemaName, referencedEntity, referencingEntity, referencingAttribute }.+//+// Usage:+// node query-table-relationships.js --envUrl <url> --table <logical_name>+//+// Output (stdout): JSON array+// [{ "schemaName": "cr4fc_order_orderitem", "referencedEntity": "cr4fc_order", "referencingEntity": "cr4fc_orderitem", "referencingAttribute": "cr4fc_orderid" }]+//+// Exit codes:+// 0 = success (JSON on stdout)+// 1 = error (message on stderr)++const { getAuthToken, makeRequest } = require('../../../scripts/lib/validation-helpers');++const args = process.argv.slice(2);+function getArg(name) {+ const idx = args.indexOf('--' + name);+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;+}++const envUrl = getArg('envUrl');+const table = getArg('table');++if (!envUrl || !table) {+ process.stderr.write('Usage: node query-table-relationships.js --envUrl <url> --table <logical_name>\n');+ process.exit(1);+}++(async () => {+ const token = getAuthToken(envUrl);+ if (!token) {+ process.stderr.write('Failed to get auth token. Run: az login\n');+ process.exit(1);+ }++ try {+ const result = await makeRequest({+ url: `${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${table}')/OneToManyRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute`,+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: 'application/json',+ },+ timeout: 15000,+ });++ if (result.error || result.statusCode !== 200) {+ process.stderr.write(`API error (${result.statusCode}): ${result.error || result.body}\n`);+ process.exit(1);+ }++ const parsed = JSON.parse(result.body);+ const rels = (parsed.value || []).map(r => ({+ schemaName: r.SchemaName,+ referencedEntity: r.ReferencedEntity,+ referencingEntity: r.ReferencingEntity,+ referencingAttribute: r.ReferencingAttribute,+ }));++ process.stdout.write(JSON.stringify(rels, null, 2) + '\n');+ } catch (err) {+ process.stderr.write(`Request failed: ${err.message}\n`);+ process.exit(1);+ }+})();diff --git a/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js b/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.jsnew file mode 100644index 000000000..7d4df22c1--- /dev/null+++ b/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js@@ -0,0 +1,36 @@+#!/usr/bin/env node++// Validates that the permissions audit report was generated.+// Runs as a Stop hook to verify the skill produced output.++const fs = require('fs');+const path = require('path');+const { approve, block, runValidation, findPath, findProjectRoot } = require('../../../scripts/lib/validation-helpers');++runValidation((cwd) => {+ const projectRoot = findProjectRoot(cwd);+ if (!projectRoot) approve(); // Not a Power Pages project — not an audit session++ // Check if audit report was generated in docs/+ const docsReport = path.join(projectRoot, 'docs', 'permissions-audit.html');+ if (fs.existsSync(docsReport)) {+ const content = fs.readFileSync(docsReport, 'utf8');+ if (!content.includes('FINDINGS_DATA') && !content.includes('__FINDINGS_DATA__')) {+ // File exists but still has unreplaced placeholders+ if (content.includes('__FINDINGS_DATA__')) {+ block('Audit report has unreplaced placeholders — data was not populated.');+ }+ }+ approve();+ }++ // Check temp directory as fallback+ const tempDir = process.env.TEMP || process.env.TMP || '/tmp';+ const tempReport = path.join(tempDir, 'permissions-audit.html');+ if (fs.existsSync(tempReport)) {+ approve();+ }++ // No report found — this may not be an audit session, so don't block+ approve();+});diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.mdindex 0cf070262..0cab98dc8 100644--- a/plugins/power-pages/skills/create-site/SKILL.md+++ b/plugins/power-pages/skills/create-site/SKILL.md@@ -12,7 +12,7 @@ hooks:command: "node \"${CLAUDE_PLUGIN_ROOT}/skills/create-site/scripts/validate-site.js\""timeout: 15- type: prompt- prompt: "If a Power Pages code site was being created in this session (via /power-pages:create-site), verify before allowing stop: 1) All user-requested features and pages were implemented — not just the scaffold, 2) Design changes were applied to real files — distinctive typography via Google Fonts (no generic Inter/Roboto/Arial), cohesive color palette via CSS variables, motion/animations, and backgrounds, 3) The user was given the dev server URL and asked to review the site, 4) No build errors remain unresolved, 5) Git commits were made at key milestones, 6) The user was asked about deploying via /power-pages:deploy-site. If any of these are incomplete, return { \"ok\": false, \"reason\": \"<specific issues>\" }. If no site creation happened or everything is complete, return { \"ok\": true }."+ prompt: "If a Power Pages code site was being created in this session (via /power-pages:create-site), verify before allowing stop: 1) All user-requested features and pages were implemented — not just the scaffold, 2) Design changes were applied to real files — distinctive typography via Google Fonts (no generic Inter/Roboto/Arial), cohesive color palette via CSS variables, motion/animations, and backgrounds, 3) Accessibility verification was performed — axe-core was run on every page, all critical and serious violations were fixed, and a re-run confirmed zero critical/serious violations, 4) The user was given the dev server URL and asked to review the site, 5) No build errors remain unresolved, 6) Git commits were made at key milestones, 7) The user was asked about deploying via /power-pages:deploy-site. If any of these are incomplete, return { \"ok\": false, \"reason\": \"<specific issues>\" }. If no site creation happened or everything is complete, return { \"ok\": true }."timeout: 30---@@ -40,7 +40,7 @@ Guide the user through creating a complete, production-quality Power Pages code**Goal**: Understand what site needs to be built and what problem it solves**Actions**:-1. Create todo list with all 7 phases (see [Progress Tracking](#progress-tracking) table)+1. Create todo list with all 8 phases (see [Progress Tracking](#progress-tracking) table)2. If site purpose is clear from arguments:- Summarize understanding- Identify site type (portal, dashboard, landing page, blog, etc.)@@ -344,13 +344,87 @@ After each significant change (new page or component), browse the site via PlaywThe user is previewing in their own browser via the dev server URL shared in Phase 2.7.-> **GATE: Do NOT proceed to Phase 6 until ALL customization is complete with design applied.** The site must have distinctive typography (Google Fonts — no generic Inter/Roboto/Arial), a cohesive color palette (CSS variables), motion/animations, and all requested pages/features before moving to review.+> **GATE: Do NOT proceed to Phase 6 until ALL customization is complete with design applied.** The site must have distinctive typography (Google Fonts — no generic Inter/Roboto/Arial), a cohesive color palette (CSS variables), motion/animations, and all requested pages/features before moving to accessibility verification.**Output**: All pages, components, and design elements implemented and verified----## Phase 6: Review & User Testing+## Phase 6: Accessibility Verification++**Goal**: Verify the site meets WCAG 2.2 AA standards using axe-core automated testing and fix any violations++> **Prerequisite:** All pages and components must be fully implemented (Phase 5 complete). The dev server MUST be running.++**Actions**:++### 6.1 Install Playwright Dependency++Install `playwright` as a dev dependency in the project so the audit script can launch a headless browser. This uses the system-installed browser (Edge/Chrome) — no browser download is needed:++```powershell+cd "<PROJECT_ROOT>"+npm install --save-dev playwright+```++### 6.2 Run axe-core Audit on Every Page++Run the audit script via `Bash`, passing the dev server URL and all site routes:++```powershell+node "${CLAUDE_PLUGIN_ROOT}/skills/create-site/scripts/axe-audit.js" --url <DEV_SERVER_URL> --routes /,/about,/services,/contact --project-root "<PROJECT_ROOT>"+```++The script launches a headless browser, navigates to each route, injects axe-core from CDN, runs the analysis, and outputs a JSON array of per-route results to stdout. Each result contains `violations` (with `id`, `impact`, `description`, `helpUrl`, and affected `nodes`), `passes` count, and `incomplete` count. The script exits with code 1 if any `critical` or `serious` violations are found.++Parse the JSON output and record all violations.++### 6.3 Fix Accessibility Violations++For each violation found, identify the source file and apply the fix:++| Violation | Fix |+|-----------|-----|+| Missing `alt` text on images | Add descriptive `alt` attributes to `<img>` tags |+| Insufficient color contrast | Adjust CSS color variables to meet 4.5:1 (normal text) or 3:1 (large text) ratios |+| Missing form labels | Add `<label>` elements or `aria-label` attributes |+| Missing landmark regions | Wrap content in `<main>`, `<nav>`, `<header>`, `<footer>` |+| Skipped heading levels | Correct heading hierarchy (h1 → h2 → h3, no gaps) |+| Missing link text | Add descriptive text or `aria-label` to links |+| Missing `lang` attribute | Add `lang="en"` to the `<html>` tag |+| Inadequate focus indicators | Add visible `outline` styles to interactive elements |++After fixing each group of related violations, commit:+```powershell+git add -A+git commit -m "Fix accessibility: <violation description>"+```++### 6.4 Re-verify After Fixes++After all fixes are applied, re-run the audit script (same command as 6.2) to confirm violations are resolved:++1. If new violations appear (e.g., a fix introduced a regression), repeat 6.3–6.4+2. Continue until the script exits with code 0 (zero `critical` and `serious` violations)++Present a summary table to the user:++```+| Page | Route | Violations Found | Violations Fixed | Status |+|------|-------|-----------------|-----------------|--------|+| Home | / | 3 | 3 | Pass |+| About | /about | 1 | 1 | Pass |+| Contact | /contact | 2 | 2 | Pass |+| **Total** | | **6** | **6** | **All passing** |+```++> **GATE: Do NOT proceed to Phase 7 until all pages pass axe-core with zero `critical` and `serious` violations.** Minor and moderate violations should also be fixed where possible, but are not blocking.++**Output**: Accessibility-verified site with zero critical/serious axe-core violations++---++## Phase 7: Review & User Testing**Goal**: Ensure the site meets user expectations and all pages work correctly@@ -374,7 +448,7 @@ The user is previewing in their own browser via the dev server URL shared in Pha----## Phase 7: Deployment & Next Steps+## Phase 8: Deployment & Next Steps**Goal**: Deploy the site and suggest enhancements@@ -422,8 +496,8 @@ The user is previewing in their own browser via the dev server URL shared in Pha1. After Phase 1: Confirm site purpose, framework, and project location2. After Phase 4: Approve implementation plan-3. After Phase 6: Accept site or request changes-4. At Phase 7: Deploy or skip+3. After Phase 7: Accept site or request changes+4. At Phase 8: Deploy or skip### Progress Tracking@@ -436,6 +510,7 @@ Before starting Phase 1, create a task list with all phases using `TaskCreate`:| Plan site components | Planning components | Determine pages, components, design direction, and routes while user previews scaffold || Approve implementation plan | Getting plan approval | Present implementation plan covering design and pages, get user approval || Implement pages and components | Building site | Apply chosen design tokens, create all pages, components, routing, navigation |+| Verify accessibility with axe-core | Verifying accessibility | Run axe-core on every page, fix all critical/serious violations, re-verify until passing || Review with user | Reviewing site | Navigate all pages, share URL, get user feedback, apply changes || Deploy and wrap up | Deploying site | Ask about deployment, present summary, suggest next steps |@@ -449,6 +524,7 @@ Every site must meet these standards before completion:- Motion/animations (page transitions, hover states)- All requested pages and features implemented (not placeholders)- All routes working and navigation complete+- Accessibility verified via axe-core — zero critical/serious violations on all pages- Git commits at key milestones- Verified via Playwright- User reviewed and approved@@ -491,12 +567,18 @@ Every site must meet these standards before completion:- Git commits after each major piece- Playwright verified each page-### Phase 6: Review+### Phase 6: Accessibility Verification+- axe-core injected and run on all 4 pages via `browser_evaluate`+- Found 5 violations: 2 missing alt text, 1 insufficient contrast, 1 missing lang attribute, 1 skipped heading level+- All violations fixed in source code and committed+- Re-run confirmed zero critical/serious violations across all pages++### Phase 7: Review- Summary table presented- User reviewed at `http://localhost:5173`, requested minor color adjustment- Adjustment applied, re-verified-### Phase 7: Deploy+### Phase 8: Deploy- User chose to deploy → invoked `/power-pages:deploy-site`- Final summary presented with next step suggestionsdiff --git a/plugins/power-pages/skills/create-site/assets/angular/gitignore b/plugins/power-pages/skills/create-site/assets/angular/gitignoreindex b06ab183b..b1b516614 100644--- a/plugins/power-pages/skills/create-site/assets/angular/gitignore+++ b/plugins/power-pages/skills/create-site/assets/angular/gitignore@@ -43,6 +43,8 @@ coverage.sass-cachetestem.log+.playwright-mcp/+# OS.DS_StoreThumbs.dbdiff --git a/plugins/power-pages/skills/create-site/assets/astro/gitignore b/plugins/power-pages/skills/create-site/assets/astro/gitignoreindex 456349dca..0970bd524 100644--- a/plugins/power-pages/skills/create-site/assets/astro/gitignore+++ b/plugins/power-pages/skills/create-site/assets/astro/gitignore@@ -34,6 +34,8 @@ coverage*.sln*.sw?+.playwright-mcp/+# OS.DS_StoreThumbs.dbdiff --git a/plugins/power-pages/skills/create-site/assets/react/gitignore b/plugins/power-pages/skills/create-site/assets/react/gitignoreindex 98ee4ab93..6b4b3bf45 100644--- a/plugins/power-pages/skills/create-site/assets/react/gitignore+++ b/plugins/power-pages/skills/create-site/assets/react/gitignore@@ -37,6 +37,8 @@ coverage*.sln*.sw?+.playwright-mcp/+# OS.DS_StoreThumbs.dbdiff --git a/plugins/power-pages/skills/create-site/assets/vue/gitignore b/plugins/power-pages/skills/create-site/assets/vue/gitignoreindex 98ee4ab93..6b4b3bf45 100644--- a/plugins/power-pages/skills/create-site/assets/vue/gitignore+++ b/plugins/power-pages/skills/create-site/assets/vue/gitignore@@ -37,6 +37,8 @@ coverage*.sln*.sw?+.playwright-mcp/+# OS.DS_StoreThumbs.dbdiff --git a/plugins/power-pages/skills/create-site/references/design-aesthetics.md b/plugins/power-pages/skills/create-site/references/design-aesthetics.mdindex eda27bb3f..65ad78059 100644--- a/plugins/power-pages/skills/create-site/references/design-aesthetics.md+++ b/plugins/power-pages/skills/create-site/references/design-aesthetics.md@@ -29,7 +29,7 @@ Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant coloUse animations for effects and micro-interactions. Prioritize CSS-only solutions. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (`animation-delay`) creates more delight than scattered micro-interactions.### Accessibility-Accessibility is mandatory (WCAG 2.1 AA). Semantic structure, strong contrast, visible focus states, keyboard navigation, accessible form validation.+Accessibility is mandatory (WCAG 2.2 AA). Semantic structure, strong contrast, visible focus states, keyboard navigation, accessible form validation.- **Semantic HTML**: Use `<header>`, `<nav>`, `<main>`, `<section>`, `<footer>`, `<article>` — never rely on `<div>` soup. Headings (`h1`–`h6`) must follow a logical hierarchy with no skipped levels.- **Color contrast**: Text must meet WCAG AA minimums — 4.5:1 for normal text, 3:1 for large text (18px+ bold or 24px+ regular). Never convey meaning through color alone.diff --git a/plugins/power-pages/skills/create-site/scripts/axe-audit.js b/plugins/power-pages/skills/create-site/scripts/axe-audit.jsnew file mode 100644index 000000000..13182be4d--- /dev/null+++ b/plugins/power-pages/skills/create-site/scripts/axe-audit.js@@ -0,0 +1,114 @@+#!/usr/bin/env node++// Runs axe-core accessibility audit on a Power Pages dev server.+// Navigates to each route, injects axe-core from CDN, and reports violations.+//+// Usage:+// node axe-audit.js --url http://localhost:5173 --routes /,/about,/contact --project-root /path/to/project+//+// Prerequisites:+// npm install --save-dev playwright (in the project directory)+//+// Output: JSON array of per-route audit results to stdout.+// Exit code: 1 if critical/serious violations found, 0 otherwise.++const path = require('path');+const { detectBrowser } = require('../../../scripts/lib/detect-browser');++const AXE_CDN_URL = 'https://cdnjs.cloudflare.com/ajax/libs/axe-core/4.10.3/axe.min.js';++function parseArgs() {+ const args = process.argv.slice(2);+ const parsed = {};+ for (let i = 0; i < args.length; i++) {+ if (args[i] === '--url' && args[i + 1]) parsed.url = args[++i];+ else if (args[i] === '--routes' && args[i + 1]) parsed.routes = args[++i].split(',');+ else if (args[i] === '--project-root' && args[i + 1]) parsed.projectRoot = args[++i];+ }+ if (!parsed.url || !parsed.routes || !parsed.projectRoot) {+ console.error('Usage: node axe-audit.js --url <base-url> --routes <comma-separated> --project-root <path>');+ process.exit(1);+ }+ return parsed;+}++function loadPlaywright(projectRoot) {+ const attempts = [+ () => require('playwright'),+ () => require(path.join(projectRoot, 'node_modules', 'playwright')),+ () => require('playwright-core'),+ () => require(path.join(projectRoot, 'node_modules', 'playwright-core')),+ ];+ for (const attempt of attempts) {+ try { return attempt(); } catch {}+ }+ console.error('playwright not found. Run: npm install --save-dev playwright');+ process.exit(1);+}++async function main() {+ const { url, routes, projectRoot } = parseArgs();+ const { chromium } = loadPlaywright(projectRoot);+ const channel = detectBrowser();++ const browser = await chromium.launch({ channel, headless: true });+ const page = await browser.newPage();+ const results = [];++ for (const route of routes) {+ const pageUrl = `${url.replace(/\/$/, '')}${route}`;+ try {+ await page.goto(pageUrl, { waitUntil: 'networkidle', timeout: 15000 });+ await page.waitForTimeout(2000);++ // Inject axe-core from CDN+ await page.addScriptTag({ url: AXE_CDN_URL });+ await page.waitForFunction(() => typeof window.axe !== 'undefined', { timeout: 10000 });++ // Run axe-core audit against WCAG 2.2 AA (cumulative: includes 2.0 and 2.1)+ const audit = await page.evaluate(async () => {+ const res = await window.axe.run(document, {+ runOnly: {+ type: 'tag',+ values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'],+ },+ });+ return {+ violations: res.violations.map(v => ({+ id: v.id,+ impact: v.impact,+ description: v.description,+ helpUrl: v.helpUrl,+ nodes: v.nodes.map(n => ({+ html: n.html,+ target: n.target,+ failureSummary: n.failureSummary,+ })),+ })),+ passes: res.passes.length,+ incomplete: res.incomplete.length,+ };+ });++ results.push({ route, url: pageUrl, ...audit });+ } catch (err) {+ results.push({ route, url: pageUrl, error: err.message, violations: [], passes: 0, incomplete: 0 });+ }+ }++ await browser.close();++ // Output JSON results+ console.log(JSON.stringify(results, null, 2));++ // Exit with error code if critical/serious violations exist+ const hasCriticalOrSerious = results.some(r =>+ r.violations.some(v => v.impact === 'critical' || v.impact === 'serious')+ );+ process.exit(hasCriticalOrSerious ? 1 : 0);+}++main().catch(err => {+ console.error(err.message);+ process.exit(1);+});diff --git a/plugins/power-pages/skills/create-webroles/scripts/create-web-role.js b/plugins/power-pages/skills/create-webroles/scripts/create-web-role.jsnew file mode 100644index 000000000..02fcd6cdf--- /dev/null+++ b/plugins/power-pages/skills/create-webroles/scripts/create-web-role.js@@ -0,0 +1,77 @@+#!/usr/bin/env node++// Creates a web role YAML file for Power Pages code sites.+// Generates UUID, validates inputs, writes correctly-formatted YAML.+//+// Usage:+// node create-web-role.js --projectRoot <path> --name <string> [--anonymous] [--authenticated]+//+// Output (JSON to stdout):+// { "id": "<uuid>", "filePath": "<path>" }+//+// Exits with code 1 on validation errors (messages to stderr).++const fs = require('fs');+const path = require('path');+const generateUuid = require(path.join(__dirname, '..', '..', '..', 'scripts', 'generate-uuid'));++// --- CLI arg parsing ---++const args = process.argv.slice(2);++function getArg(name) {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;+}++function hasFlag(name) {+ return args.includes(`--${name}`);+}++const projectRoot = getArg('projectRoot');+const roleName = getArg('name');+const isAnonymous = hasFlag('anonymous');+const isAuthenticated = hasFlag('authenticated');++// --- Validation ---++if (!projectRoot || !roleName) {+ console.error('Usage: node create-web-role.js --projectRoot <path> --name <string> [--anonymous] [--authenticated]');+ process.exit(1);+}++const webRolesDir = path.join(projectRoot, '.powerpages-site', 'web-roles');+if (!fs.existsSync(webRolesDir)) {+ console.error(`Error: Web roles directory not found at ${webRolesDir}`);+ console.error('The site must be deployed at least once before web roles can be created.');+ process.exit(1);+}++// --- Helpers ---++function writeYaml(fields) {+ const keys = Object.keys(fields).sort();+ return keys.map(k => `${k}: ${fields[k]}`).join('\n') + '\n';+}++// --- Create web role ---++const uuid = generateUuid();++const fields = {+ anonymoususersrole: isAnonymous,+ authenticatedusersrole: isAuthenticated,+ id: uuid,+ name: roleName,+};++const yamlContent = writeYaml(fields);++// File name: kebab-case with .yml extension (matching create-webroles skill convention)+const fileName = `${roleName.toLowerCase().replace(/\s+/g, '-')}.webrole.yml`;+const filePath = path.join(webRolesDir, fileName);++fs.writeFileSync(filePath, yamlContent, 'utf8');++const result = { id: uuid, filePath: filePath };+process.stdout.write(JSON.stringify(result));diff --git a/plugins/power-pages/skills/deploy-site/SKILL.md b/plugins/power-pages/skills/deploy-site/SKILL.mdindex a0c40c66b..e31f79ab0 100644--- a/plugins/power-pages/skills/deploy-site/SKILL.md+++ b/plugins/power-pages/skills/deploy-site/SKILL.md@@ -3,7 +3,7 @@ name: deploy-sitedescription: This skill should be used when the user asks to "deploy to power pages", "upload site", "publish site", "deploy site", "push to power pages", "upload code site", or wants to deploy/upload an existing Power Pages code site to a Power Pages environment using PAC CLI.user-invocable: trueallowed-tools: Read, Bash, AskUserQuestion, Glob, Grep, TaskCreate, TaskUpdate, TaskList-model: opus+model: sonnet---# Deploy Power Pages Code Site@@ -352,6 +352,7 @@ If the retry succeeds, proceed to Phase 5. If it fails with a different error, pIf the user skips activation (or after activation completes), suggest:- `/power-pages:activate-site` — Provision the site with a subdomain and make it live (if not already activated)+- `/power-pages:test-site` — Test the deployed site in the browser (verify pages load, check API calls)- `/power-pages:setup-datamodel` — Create Dataverse tables for dynamic content- `/power-pages:add-seo` — Add meta tags, robots.txt, sitemap.xml, favicondiff --git a/plugins/power-pages/skills/integrate-webapi/SKILL.md b/plugins/power-pages/skills/integrate-webapi/SKILL.mdindex 451149e02..db47f99eb 100644--- a/plugins/power-pages/skills/integrate-webapi/SKILL.md+++ b/plugins/power-pages/skills/integrate-webapi/SKILL.md@@ -23,9 +23,11 @@ hooks:verify before allowing stop: 1) The site was analyzed and tables requiring Web API integrationwere identified, 2) The webapi-integration agent was invoked to create API client, types, andservice files for each table, 3) All integration files were verified (types, services, hooks exist)- and the project builds successfully, 4) Table permissions and site settings were configured- (either via the webapi-permissions agent or by parsing a user-provided permissions diagram),- 5) The user was asked whether to deploy the site.+ and the project builds successfully, 4) Table permissions were configured (either via the+ table-permissions-architect agent or by parsing a user-provided permissions diagram), 5) Web API site+ settings were configured with case-sensitive validated column names (either via the webapi-settings-architect+ agent or by parsing a user-provided permissions diagram), 6) The user was asked whether to deploy+ the site.If any of these are incomplete, return { "ok": false, "reason": "<specific issues>" }.If no Web API integration work happened or everything is complete, return { "ok": true }.timeout: 30@@ -37,7 +39,8 @@ Integrate Power Pages Web API into a code site's frontend. This skill orchestrat## Core Principles-- **One table at a time**: Process tables sequentially because the first table creates the shared `powerPagesApi.ts` client that subsequent tables reuse, and each agent invocation may modify shared files.+- **First table sequential, then parallel**: The first table must be processed alone because it creates the shared `powerPagesApi.ts` client. Once that exists, remaining tables can be processed in parallel since each creates independent files (types, service, hooks).+- **Parallelize independent agents**: The `table-permissions-architect` and `webapi-settings-architect` agents are independent — invoke them in parallel rather than sequentially.- **Permissions require deployment**: The `.powerpages-site` folder must exist before table permissions and site settings can be configured. Integration code can be written without it, but permissions cannot.- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.@@ -57,7 +60,7 @@ Integrate Power Pages Web API into a code site's frontend. This skill orchestrat3. **Review Integration Plan** — Present findings to the user and confirm which tables to integrate4. **Implement Integrations** — Use the `webapi-integration` agent for each table5. **Verify Integrations** — Validate all expected files exist and the project builds successfully-6. **Setup Permissions** — Choose permissions source (upload diagram or let the Web API Permissions Architect analyze), then configure table permissions and site settings+6. **Setup Permissions & Settings** — Choose permissions source (upload diagram or let the architects analyze), then configure table permissions and Web API site settings with case-sensitive validated column names7. **Review & Deploy** — Ask the user to deploy the site and invoke `/power-pages:deploy-site` if confirmed---@@ -213,15 +216,18 @@ For each table, use the `Task` tool to invoke the `webapi-integration` agent at>> Create the TypeScript types, CRUD service layer, and framework-specific hooks/composables. Replace any mock data or placeholder API calls in the referencing source files with the new service."-### 4.2 Process Tables Sequentially+### 4.2 Process First Table, Then Parallelize Remaining-Process tables **one at a time** (not in parallel), because:-- The first table creates the shared `powerPagesApi.ts` client — subsequent tables reuse it-- Each agent invocation may modify shared files+The **first table** must be processed alone — it creates the shared `powerPagesApi.ts` client that all other tables depend on. After the first table completes and the shared client exists:++- **Verify** the shared API client was created at `src/shared/powerPagesApi.ts`+- **Then invoke all remaining tables in parallel** using multiple `Task` calls — each table creates independent files (its own types in `src/types/`, service in `src/shared/services/`, and hook/composable), so there are no conflicts++If there is only one table, this step is simply sequential.### 4.3 Verify Each Integration-After each agent completes, verify the output:+After each agent completes (or after all parallel agents complete), verify the output:- Check that the expected files were created (types, service, hook/composable)- Confirm the shared API client exists after the first table is processed- Note any issues reported by the agent@@ -285,36 +291,36 @@ Present a table summarizing the verification:----## Phase 6: Setup Permissions+## Phase 6: Setup Permissions & Settings-**Goal**: Configure table permissions and site settings for all integrated tables using the `webapi-permissions` agent+**Goal**: Configure table permissions and Web API site settings for all integrated tables using the `table-permissions-architect` and `webapi-settings-architect` agents**Actions**:-### 5.1 Check Deployment Prerequisite+### 6.1 Check Deployment Prerequisite-The permissions agent requires the `.powerpages-site` folder. If it doesn't exist:+Both agents require the `.powerpages-site` folder. If it doesn't exist:Use `AskUserQuestion`:| Question | Options ||----------|---------|-| The `.powerpages-site` folder was not found. The site needs to be deployed once before permissions can be configured. Would you like to deploy now? | Yes, deploy now (Recommended), Skip permissions for now — I'll set them up later |+| The `.powerpages-site` folder was not found. The site needs to be deployed once before permissions and site settings can be configured. Would you like to deploy now? | Yes, deploy now (Recommended), Skip permissions for now — I'll set them up later |**If "Yes, deploy now"**: Invoke `/power-pages:deploy-site` first, then resume this phase.-**If "Skip"**: Skip to Phase 7 with a note that permissions still need to be configured.+**If "Skip"**: Skip to Phase 7 with a note that permissions and site settings still need to be configured.-### 5.2 Choose Permissions Source+### 6.2 Choose Permissions SourceAsk the user how they want to define the permissions using the `AskUserQuestion` tool:-**Question**: "How would you like to define the Web API permissions for your site?"+**Question**: "How would you like to define the Web API permissions and settings for your site?"| Option | Description ||--------|-------------|| **Upload an existing permissions diagram** | Provide an image (PNG/JPG) or Mermaid diagram of your existing permissions structure |-| **Let the Web API Permissions Architect figure it out** | The Web API Permissions Architect will analyze your site's code, data model, and Dataverse environment, then propose permissions automatically |+| **Let the architects figure it out** | The Table Permissions Architect and Web API Settings Architect will analyze your site's code, data model, and Dataverse environment, then propose permissions and settings automatically |Route to the appropriate path:@@ -327,65 +333,132 @@ If the user chooses to upload an existing diagram:- **Mermaid syntax** — The user can paste a Mermaid flowchart diagram text directly in chat- **Text description** — A structured list of web roles, table permissions, scopes, and site settings-2. Parse the diagram into the same structured format used by the webapi-permissions agent:+2. Parse the diagram into structured format:- **Web roles**: Match with existing roles from `.powerpages-site/web-roles/` by name to get their UUIDs- **Table permissions**: Permission name, table logical name, web role UUID(s), scope, CRUD flags (read/create/write/delete/append/appendto), parent permission and relationship name (if Parent scope)- **Site settings**: `Webapi/<table>/enabled` and `Webapi/<table>/fields` — **CRITICAL: fields must list specific column logical names, NEVER use `*` wildcard**-3. Cross-check with existing configuration in `.powerpages-site/` to identify which permissions and site settings are new vs. already exist.+3. **Validate column names against Dataverse** — Even when using a user-provided diagram, query Dataverse for each table's column LogicalNames and verify that every column in the `Webapi/<table>/fields` values uses the exact Dataverse LogicalName (case-sensitive). Correct any mismatches before creating files.++4. Cross-check with existing configuration in `.powerpages-site/` to identify which permissions and site settings are new vs. already exist.-4. Generate a Mermaid flowchart from the parsed data (if the user provided an image or text) for visual confirmation.+5. Generate a Mermaid flowchart from the parsed data (if the user provided an image or text) for visual confirmation.-5. Present the parsed permissions plan to the user for approval using `AskUserQuestion`:+6. Present the parsed permissions plan to the user for approval using `AskUserQuestion`:| Question | Options ||----------|---------|| Does this permissions plan look correct? | Approve and create files (Recommended), Request changes, Cancel |-6. Proceed directly to **section 5.4: Create Permission Files** with the parsed permissions data.+7. Proceed directly to **section 6.4: Create Permission & Settings Files** with the parsed data.++#### Path B: Let the Architects Figure It Out++If the user chooses to let the architects figure it out, proceed to **section 6.3: Invoke Table Permissions Agent**.++### 6.3 Invoke Table Permissions and Web API Settings Agents (in Parallel)++These two agents are **independent** — invoke them in parallel using two `Task` calls simultaneously:++#### Table Permissions Agent++Use the `Task` tool to invoke the `table-permissions-architect` agent at `${CLAUDE_PLUGIN_ROOT}/agents/table-permissions-architect.md`:++**Prompt:**-#### Path B: Let the Web API Permissions Architect Figure It Out+> "Analyze this Power Pages code site and propose table permissions. The following tables have been integrated with Web API: [list of tables integrated in Phase 4]. Check for existing web roles and table permissions. Propose a complete table permissions plan covering all integrated tables. After I approve the plan, create the web role and table permission YAML files using the deterministic scripts."-If the user chooses to let the Web API Permissions Architect figure it out, proceed to **section 5.3: Invoke Permissions Agent**.+The agent will:+1. Analyze the site and propose a plan (with Mermaid diagram)+2. Present the plan via plan mode for user approval+3. After approval, create any needed web roles using `create-web-role.js`+4. Create all table permission files using `create-table-permission.js`+5. Return a summary of created files-### 5.3 Invoke Permissions Agent+#### Web API Settings Agent-Use the `Task` tool to invoke the `webapi-permissions` agent at `${CLAUDE_PLUGIN_ROOT}/agents/webapi-permissions.md`:+Use the `Task` tool to invoke the `webapi-settings-architect` agent at `${CLAUDE_PLUGIN_ROOT}/agents/webapi-settings-architect.md`:**Prompt:**-> "Analyze this Power Pages code site and set up Web API permissions. The following tables have been integrated with Web API: [list of tables integrated in Phase 4]. Check for existing web roles, table permissions, and site settings. Propose a complete permissions plan covering all integrated tables."+> "Analyze this Power Pages code site and propose Web API site settings. The following tables have been integrated with Web API: [list of tables integrated in Phase 4]. Check for existing site settings and query Dataverse for exact column LogicalNames. Propose site settings with case-sensitive validated column names. After I approve the plan, create the site setting YAML files using the deterministic scripts."++The agent will:+1. Analyze the site, query Dataverse for exact column LogicalNames+2. Cross-validate column names (case-sensitive)+3. Present the plan via plan mode for user approval+4. After approval, create all site setting files using `create-site-setting.js`+5. Return a summary of created files++Wait for **both** agents to complete before proceeding to 6.4.++### 6.4 Create Permission & Settings Files (Path A Only)++**This section applies only to Path A (user-provided permissions diagram).** For Path B, the architect agents create the files directly in section 6.3.++After parsing the user's diagram, create the YAML files using the deterministic scripts below. **Do NOT write YAML files manually** — always use these scripts which handle UUID generation, field ordering, formatting, and file naming automatically.++#### 6.4.1 Create Web Roles (if needed)++If the plan requires new web roles that don't already exist, create them first (their UUIDs are needed for table permissions):++```powershell+node "${CLAUDE_PLUGIN_ROOT}/skills/create-webroles/scripts/create-web-role.js" --projectRoot "<PROJECT_ROOT>" --name "<Role Name>" [--anonymous] [--authenticated]+```-### 5.4 Create Permission Files+Capture the JSON output (`{ "id": "<uuid>", "filePath": "<path>" }`) — use the `id` as the `--webRoleIds` value when creating table permissions.-After the permissions data is available — either from the user's uploaded diagram (Path A) or from the `webapi-permissions` agent's approved plan (Path B) — create the actual YAML files:+#### 6.4.2 Create Table Permissions-- **Table permission files** in `.powerpages-site/table-permissions/`-- **Site setting files** in `.powerpages-site/site-settings/`+For each table permission in the plan. Process **parent permissions before child permissions** — children need the parent's UUID from the JSON output.-For each file that needs a UUID, generate one using the shared script:+**For Global/Contact/Account/Self scope:**```powershell-node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "<Global|Contact|Account|Self>" [--read] [--create] [--write] [--delete] [--append] [--appendto]```-**CRITICAL YAML FORMATTING RULES when writing these files:**-- **Code site git format**: Table permission fields have `adx_` prefix stripped (e.g., `append`, `read`, `scope`) EXCEPT `adx_entitypermission_webrole` (M2M relationship keeps prefix). The display name field is `entityname` (NOT `entitypermissionname`). Entity reference lookups (like `parententitypermission`) store only the GUID, not a nested object.-- Boolean values MUST be unquoted: `value: true` — NEVER `value: "true"` or `value: "false"`-- Numeric values MUST be unquoted: `scope: 756150000` — NEVER `scope: "756150000"`-- UUIDs MUST be unquoted: `id: a1b2c3d4-...` — NEVER `id: "a1b2c3d4-..."`-- String values (like field lists) are also unquoted: `value: cr87b_name,cr87b_email`-- CRUD flags are unquoted booleans: `read: true` — NEVER `read: "true"`-- Fields MUST be alphabetically sorted-- Follow the exact YAML format specified by the permissions plan output+**For Parent scope** (requires parent permission UUID and relationship name):++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1>" --scope "Parent" --parentPermissionId "<parent-uuid>" --parentRelationshipName "<relationship_name>" [--read] [--create] [--write] [--delete] [--append] [--appendto]+```++Each invocation outputs `{ "id": "<uuid>", "filePath": "<path>" }`. Use the `id` as `--parentPermissionId` for child permissions.++#### 6.4.3 Create Site Settings++For each site setting in the plan:++**Enabled setting (boolean):**++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Webapi/<table>/enabled" --value "true" --description "Enable Web API access for <table> table" --type "boolean"+```++**Fields setting (string — use the validated column names from the diagram):**++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Webapi/<table>/fields" --value "<comma-separated-validated-columns>" --description "Allowed fields for <table> Web API access"+```++**Inner error setting (boolean, optional for debugging):**++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Webapi/error/innererror" --value "true" --description "Enable detailed error messages for debugging" --type "boolean"+```++**Important**: The `--value` for fields settings MUST use exact Dataverse LogicalNames (case-sensitive, all lowercase). Using incorrect casing causes 403 Forbidden errors.++**Lookup columns**: For every lookup column, include **both** the LogicalName (`cr87b_categoryid`) AND the OData computed attribute (`_cr87b_categoryid_value`) in the fields value. The Power Pages Web API does a literal match — the LogicalName is needed for write operations, the `_..._value` form is needed for read operations (`$select`, `$filter`). Missing either form causes 403 errors.-### 5.5 Git Commit+### 6.5 Git Commit-Stage and commit the permission files:+Stage and commit the permission and settings files:```powershellgit add -A-git commit -m "Add Web API permissions and site settings for [table names]"+git commit -m "Add table permissions and Web API site settings for [table names]"```**Output**: Table permissions and site settings created, verified, and committed@@ -437,7 +510,7 @@ Use `AskUserQuestion`:After deployment (or if skipped), remind the user:- **Test the API**: Open the deployed site and verify Web API calls work in the browser's Network tab-- **Check permissions**: If any API call returns 403, verify table permissions and site settings are correct+- **Check permissions**: If any API call returns 403, verify table permissions and site settings are correct. The most common cause of 403 errors is column names in `Webapi/<table>/fields` not matching the exact Dataverse LogicalName (case-sensitive — must be all lowercase).- **Disable innererror in production**: If `Webapi/error/innererror` was enabled for debugging, disable it before going live- **Web roles**: Users must be assigned the appropriate web roles to access protected APIs@@ -451,7 +524,7 @@ After deployment (or if skipped), remind the user:- **Use TaskCreate/TaskUpdate** to track progress at every phase- **Ask for user confirmation** at key decision points (see list below)-- **Process tables sequentially** — never in parallel, because the shared API client and shared files create ordering dependencies+- **First table sequential, then parallel** — the first table creates the shared API client; after that, remaining tables can be processed in parallel since each creates independent files- **Commit at milestones** — after integration code and after permission files- **Verify each integration** — confirm expected files exist after each agent invocation@@ -460,9 +533,9 @@ After deployment (or if skipped), remind the user:1. After Phase 2: Confirm which tables to integrate2. After Phase 3: Approve integration plan3. At Phase 6.1: Deploy now or skip permissions (if `.powerpages-site` missing)-4. At Phase 6.2: Choose permissions source (upload diagram or let the Web API Permissions Architect analyze)-5. At Phase 6.3/6.4: Approve permissions plan (via user review for Path A, or plan mode within the agent for Path B)-6. At Phase 7.2: Deploy now or deploy later+4. At Phase 6.2: Choose permissions source (upload diagram or let the architects analyze)+5. At Phase 6.3: Approve table permissions plan and Web API site settings plan (both agents run in parallel for Path B, each presents its own plan for approval)+7. At Phase 7.2: Deploy now or deploy later### Progress Tracking@@ -473,9 +546,9 @@ Before starting Phase 1, create a task list with all phases using `TaskCreate`:| Verify site exists | Verifying site prerequisites | Locate project root, detect framework, check data model and deployment status || Explore integration points | Analyzing code for integration points | Use Explore agent to discover tables, existing services, and compile integration manifest || Review integration plan | Reviewing integration plan with user | Present findings and confirm which tables to integrate |-| Implement integrations | Implementing Web API integrations | Invoke webapi-integration agent per table, verify output, git commit |+| Implement integrations | Implementing Web API integrations | Invoke webapi-integration agent for first table (creates shared client), then remaining tables in parallel, verify output, git commit || Verify integrations | Verifying integrations | Validate all expected files exist, check imports and API references, run project build |-| Setup permissions | Configuring permissions and site settings | Choose permissions source (upload diagram or Web API Permissions Architect), create YAML files, git commit |+| Setup permissions and settings | Configuring permissions and site settings | Choose permissions source (upload diagram or architects), invoke table-permissions-architect and webapi-settings-architect agents in parallel, create YAML files with case-sensitive validated column names, git commit || Review and deploy | Reviewing summary and deploying | Present summary, ask about deployment, provide post-deploy guidance |Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`. This gives the user visibility into progress and keeps the workflow deterministic.diff --git a/plugins/power-pages/skills/setup-datamodel/SKILL.md b/plugins/power-pages/skills/setup-datamodel/SKILL.mdindex 04b8d3f8a..062905e8f 100644--- a/plugins/power-pages/skills/setup-datamodel/SKILL.md+++ b/plugins/power-pages/skills/setup-datamodel/SKILL.md@@ -172,19 +172,18 @@ Only proceed to creation after explicit user approval.### 5.1 Refresh Token-Re-acquire the Azure CLI token (tokens expire after ~60 minutes):+Re-acquire the auth token (tokens expire after ~60 minutes):-```powershell-$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>```### 5.2 Query Existing TablesFor each table in the approved proposal marked as `new`, check whether it already exists:-```powershell-$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }-Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')" -Headers $headers+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')"```- **If 404**: Table does not exist, proceed to create it@@ -219,14 +218,8 @@ Refer to `references/odata-api-patterns.md` for full JSON body templates.For each new table, POST to the EntityDefinitions endpoint:-```powershell-$body = <JSON body from references/odata-api-patterns.md>-$headers = @{- Authorization = "Bearer $token"- "Content-Type" = "application/json"- Accept = "application/json"-}-Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/EntityDefinitions" -Headers $headers -Body $body+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "api/data/v9.2/EntityDefinitions" --body '<JSON body from references/odata-api-patterns.md>'```Use the deep-insert pattern to create the table and its columns in a single POST request. See `references/odata-api-patterns.md` for the complete JSON structure.@@ -235,9 +228,8 @@ Use the deep-insert pattern to create the table and its columns in a single POSTFor tables marked as `modified`, add new columns one at a time:-```powershell-$body = <column JSON from references/odata-api-patterns.md>-Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes" -Headers $headers -Body $body+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes" --body '<column JSON from references/odata-api-patterns.md>'```### 6.3 Track Progress@@ -246,11 +238,7 @@ Track each creation attempt and its result (success/failure/skipped). Do NOT att### 6.4 Refresh Token if Needed-If creating many tables, refresh the token between batches (every 3–4 tables) to avoid expiration:--```powershell-$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv-```+If creating many tables, the `dataverse-request.js` script handles 401 token refresh automatically. No manual refresh is needed between batches.**Output**: All approved tables and columns created (or failures reported)@@ -266,18 +254,16 @@ $token = az account get-access-token --resource "$envUrl" --query accessToken -oCreate lookup columns that establish 1:N relationships:-```powershell-$body = <relationship JSON from references/odata-api-patterns.md>-Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/RelationshipDefinitions" -Headers $headers -Body $body+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "api/data/v9.2/RelationshipDefinitions" --body '<relationship JSON from references/odata-api-patterns.md>'```### 7.2 Many-to-Many RelationshipsCreate M:N relationships (intersect tables are created automatically):-```powershell-$body = <M:N relationship JSON from references/odata-api-patterns.md>-Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/RelationshipDefinitions" -Headers $headers -Body $body+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "api/data/v9.2/RelationshipDefinitions" --body '<M:N relationship JSON from references/odata-api-patterns.md>'```### 7.3 Track Relationship Creation@@ -298,12 +284,8 @@ Track each relationship creation attempt. Report failures without rolling back.Publish all customizations so the new tables and columns become available:-```powershell-$publishBody = @{- ParameterXml = "<importexportxml><entities><entity>$( ($tables | ForEach-Object { $_.logicalName }) -join '</entity><entity>' )</entity></entities></importexportxml>"-} | ConvertTo-Json--Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/PublishXml" -Headers $headers -Body $publishBody -ContentType "application/json"+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "api/data/v9.2/PublishXml" --body '{"ParameterXml":"<importexportxml><entities><entity>cr123_project</entity><entity>cr123_task</entity></entities></importexportxml>"}'```See `references/odata-api-patterns.md` for the full PublishXml pattern.@@ -312,8 +294,8 @@ See `references/odata-api-patterns.md` for the full PublishXml pattern.For each created table, run a verification query:-```powershell-Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')?`$select=LogicalName,DisplayName" -Headers $headers+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "api/data/v9.2/EntityDefinitions(LogicalName='<table>')?$select=LogicalName,DisplayName"```### 8.3 Write Manifest@@ -381,7 +363,7 @@ After the summary, suggest:- **Use TaskCreate/TaskUpdate** to track progress at every phase- **Ask for user confirmation** at key decision points (see list below)-- **Refresh tokens proactively** — re-acquire the Azure CLI token before any batch of API calls, especially if more than a few minutes have passed+- **Token refresh is automatic** — the `dataverse-request.js` script handles 401 token refresh and 429/5xx retry internally- **Report failures without rollback** — track each creation attempt and continue with remaining items on failure### Key Decision Points (Wait for User)diff --git a/plugins/power-pages/skills/setup-datamodel/references/odata-api-patterns.md b/plugins/power-pages/skills/setup-datamodel/references/odata-api-patterns.mdindex dbedbd24d..d549fc9b0 100644--- a/plugins/power-pages/skills/setup-datamodel/references/odata-api-patterns.md+++ b/plugins/power-pages/skills/setup-datamodel/references/odata-api-patterns.md@@ -269,9 +269,8 @@ Lookups are NOT created as standalone columns. They are created as part of a relUse the same column JSON bodies as above. The column is added to the specified table.-```powershell-$body = '<column JSON>' | ConvertFrom-Json | ConvertTo-Json -Depth 20-Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='cr123_project')/Attributes" -Headers $headers -Body $body+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "api/data/v9.2/EntityDefinitions(LogicalName='cr123_project')/Attributes" --body '<column JSON>'```---@@ -370,14 +369,8 @@ After creating tables, columns, and relationships, publish them so they become a}```-```powershell-$tables = @("cr123_project", "cr123_task")-$entityXml = ($tables | ForEach-Object { "<entity>$_</entity>" }) -join ""-$publishBody = @{- ParameterXml = "<importexportxml><entities>$entityXml</entities></importexportxml>"-} | ConvertTo-Json--Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/PublishXml" -Headers $headers -Body $publishBody -ContentType "application/json"+```+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "api/data/v9.2/PublishXml" --body '{"ParameterXml":"<importexportxml><entities><entity>cr123_project</entity><entity>cr123_task</entity></entities></importexportxml>"}'```### Publish All Customizations (Fallback)diff --git a/plugins/power-pages/skills/test-site/SKILL.md b/plugins/power-pages/skills/test-site/SKILL.mdnew file mode 100644index 000000000..0c0cdbd48--- /dev/null+++ b/plugins/power-pages/skills/test-site/SKILL.md@@ -0,0 +1,482 @@+---+name: test-site+description: >+ This skill should be used when the user asks to "test my site", "test the site",+ "run site tests", "check if site is working", "verify site", "smoke test",+ "test pages", "check api calls", "test web api", "verify deployment works",+ or wants to test a deployed, activated Power Pages site at runtime using+ browser-based navigation, page crawling, and API request verification.+user-invocable: true+argument-hint: "<site-url>"+allowed-tools: Read, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, mcp__plugin_power-pages_playwright__browser_navigate, mcp__plugin_power-pages_playwright__browser_snapshot, mcp__plugin_power-pages_playwright__browser_click, mcp__plugin_power-pages_playwright__browser_close, mcp__plugin_power-pages_playwright__browser_network_requests, mcp__plugin_power-pages_playwright__browser_console_messages, mcp__plugin_power-pages_playwright__browser_wait_for, mcp__plugin_power-pages_playwright__browser_take_screenshot, mcp__plugin_power-pages_playwright__browser_resize, mcp__plugin_power-pages_playwright__browser_evaluate+model: opus+hooks:+ Stop:+ - hooks:+ - type: prompt+ prompt: >+ If a Power Pages site was being tested in this session (via /power-pages:test-site),+ verify before allowing stop: 1) A site URL was resolved (from user input, activation+ status check, or .powerpages-site config), 2) The browser navigated to the site and+ the homepage loaded successfully, 3) Authentication was handled — if the site had a+ private site gate (identity provider redirect), the user was asked to log in; if the+ site had site-level authentication (Sign in links), the user was asked to log in or+ chose to skip, 4) Discoverable links were crawled and each page was tested for load+ errors, 5) Network requests were captured and API endpoints (/_api/ or OData) were+ analyzed for errors, 6) A test report summary was presented to the user with pass/fail+ status for pages and API endpoints.+ If any of these are incomplete, return { "ok": false, "reason": "<specific issues>" }.+ If no site testing happened or everything is complete, return { "ok": true }.+ timeout: 30+---++# Test Power Pages Site++Test a deployed, activated Power Pages site at runtime. Navigate the site in a browser, crawl all discoverable links, verify pages load correctly, capture network traffic to test API requests, and generate a comprehensive test report.++> **Prerequisite:** This skill expects a deployed and activated Power Pages site. Run `/power-pages:deploy-site` and `/power-pages:activate-site` first if the site is not yet live.++## Core Principles++- **Non-destructive**: This skill is read-only — it does not create, modify, or delete any files or data. It only observes the site via the browser.+- **API-first testing**: The primary goal beyond page loads is verifying that all `/_api/` (Web API / OData) requests return successful responses.+- **User-controlled authentication**: Never attempt to log in automatically. Always ask the user to log in via the browser window when authentication is required.+- **Bounded crawling**: Cap page crawling at 25 pages to prevent infinite loops on sites with dynamic or paginated URLs.++**Initial request:** $ARGUMENTS++---++## Phase 1: Resolve Site URL++**Goal:** Determine the live URL of the Power Pages site to test.++### Actions++#### 1.1 Create Task List++Create the full task list with all 6 phases before starting any work (see [Progress Tracking](#progress-tracking) table).++#### 1.2 Check User Input++If the user provided a URL in `$ARGUMENTS`:+1. Validate it starts with `https://`.+2. Store it as `SITE_URL` and skip to Phase 2.++#### 1.3 Auto-Detect from Activation Status++If no URL was provided, attempt auto-detection:++1. Locate the project root by searching for `powerpages.config.json`:++ ```+ **/powerpages.config.json+ ```++2. Run the activation status check script:++ ```powershell+ node "${CLAUDE_PLUGIN_ROOT}/scripts/check-activation-status.js" --projectRoot "<PROJECT_ROOT>"+ ```++3. Evaluate the JSON result:+ - **If `activated` is `true` and `websiteUrl` is present**: Use `websiteUrl` as `SITE_URL`. Inform the user: "Detected your site URL: **<websiteUrl>**"+ - **If `activated` is `false`**: Inform the user: "Your site is not yet activated. Please run `/power-pages:activate-site` first, then re-run this skill." Stop the skill.+ - **If `error` is present**: Fall through to step 1.4.++#### 1.4 Ask the User++If auto-detection failed or was inconclusive, use `AskUserQuestion`:++| Question | Header | Options |+|----------|--------|---------|+| What is the URL of the deployed Power Pages site you want to test? (e.g., https://contoso.powerappsportals.com) | Site URL | I'll paste the URL (description: Select "Other" below and paste your site URL), I don't know my URL (description: Run `/power-pages:activate-site` to get your site URL, or check the Power Platform admin center) |++Store the user-provided URL as `SITE_URL`.++### Output++- `SITE_URL` resolved and ready for testing++---++## Phase 2: Launch Browser & Initial Load++**Goal:** Open the site in a browser, verify the homepage loads, and capture baseline errors.++### Actions++#### 2.1 Resize Browser++Set the browser to a standard desktop viewport:++- Use `browser_resize` with **width: 1280, height: 720**.++#### 2.2 Navigate to Site++- Use `browser_navigate` to open `SITE_URL`.++#### 2.3 Wait for Page Load++- Use `browser_wait_for` with **time: 5** seconds to allow the page to fully render (SPAs may need time for client-side routing and API calls).++#### 2.4 Verify Homepage++- Use `browser_snapshot` to take an accessibility snapshot.+- Check the snapshot for signs of a working page:+ - Page has meaningful content (not blank, not a generic error page).+ - Look for common error indicators: "404", "Page not found", "500", "Internal Server Error", "This site can't be reached".+- If the page shows an error, report it to the user and ask whether to continue or stop.++#### 2.5 Capture Console Errors++- Use `browser_console_messages` with **level: "error"** to check for JavaScript errors on initial load.+- Record any errors found — these will be included in the final report.++#### 2.6 Capture Initial Network Requests++- Use `browser_network_requests` with **includeStatic: false** to capture the initial page load API calls.+- Record any `/_api/` or OData requests and their status codes for Phase 5 analysis.++### Output++- Browser launched at correct viewport size+- Homepage loaded and verified via snapshot+- Initial console errors and network requests recorded+- If the homepage shows a login screen, noted for Phase 3++---++## Phase 3: Authentication Check++**Goal:** Detect if the site requires authentication and handle login if needed. Power Pages sites can have **two layers** of authentication:++1. **Private site gate** — The entire site is private. Navigating to the site redirects to an identity provider (Azure AD B2C, etc.) before any site content is visible. The browser URL will typically change to a different domain (e.g., `login.microsoftonline.com`, `*.b2clogin.com`).+2. **Site-level authentication** — The site is publicly accessible (homepage loads), but certain pages or features require a logged-in user with a specific web role. Indicated by "Sign in" / "Log in" links in the navigation, or pages that show restricted-access messages.++### Actions++#### 3.1 Analyze Homepage Snapshot for Private Site Gate++Review the browser snapshot from Phase 2.4 and the current browser URL for signs of a **private site redirect**:+- The page content shows an identity provider login form (Azure AD B2C, Azure AD, etc.)+- The browser URL has changed to a different domain than `SITE_URL` (e.g., `login.microsoftonline.com`, `*.b2clogin.com`, or a custom identity provider domain)+- A 401/403 response was returned before any site content loaded+- The page is blank or shows "Access denied" / "You do not have access" with no site navigation visible++#### 3.2 Handle Private Site Gate++If a private site gate is detected, use `AskUserQuestion`:++| Question | Header | Options |+|----------|--------|---------|+| This site is **private** — it redirected to an identity provider login page before any content could load. A browser window should be open showing the login page. Please log in there using credentials that have access to this site. Once you have successfully logged in and can see the site homepage, select "I have logged in" below. | Private Site Login | I have logged in (Recommended) — I've completed the login and can see the site, Cancel testing — Stop the test |++**If "I have logged in"**:+1. Use `browser_snapshot` to verify the user is now on the actual site (site content visible, navigation present, URL is back on the `SITE_URL` domain).+2. If still on the identity provider login page:+ - Use `AskUserQuestion` again: "It looks like the login hasn't completed yet. The browser should still be open — please complete the login and try again."+ - Repeat until login is confirmed or user cancels.+3. Once confirmed, re-run Phase 2.5 and 2.6 (capture console errors and network requests on the now-loaded homepage).+4. Continue to step 3.3 to check for site-level authentication.++**If "Cancel testing"**:+- Stop the skill and inform the user they can re-run it after resolving access.++#### 3.3 Analyze for Site-Level Authentication++After the homepage is loaded (either directly for public sites, or after passing the private site gate), review the snapshot for signs of **site-level authentication**:+- "Sign in" / "Log in" / "Register" links or buttons in the site navigation+- Pages that show "You must be signed in to view this page" or similar messages+- Content that indicates some areas are restricted to authenticated users++#### 3.4 Handle Public Site (No Authentication Needed)++If neither a private site gate nor site-level authentication indicators are found:+- Inform the user: "Site is publicly accessible. Proceeding with page and API testing."+- Skip to Phase 4.++#### 3.5 Handle Site-Level Authentication++If site-level authentication indicators are detected (login links in navigation, etc.), use `AskUserQuestion`:++| Question | Header | Options |+|----------|--------|---------|+| The site has a **Sign in** option, which means some pages or API calls may require authentication. A browser window should be open — you can click "Sign in" and log in with a user account that has the appropriate web role. Once you have successfully logged in, select "I have logged in" below. | Site Authentication | I have logged in (Recommended) — I've signed in through the site's login flow, Skip authenticated pages — Only test publicly accessible pages and APIs, Cancel testing — Stop the test |++**If "I have logged in"**:+1. Use `browser_snapshot` to verify the user is now logged in (login link replaced with user name/profile, or authenticated content is visible).+2. If the login form is still showing:+ - Use `AskUserQuestion` again: "It looks like the login hasn't completed yet. The browser should still be open — please complete the login and try again."+ - Repeat until login is confirmed or user cancels.++**If "Skip authenticated pages"**:+- Note that only public pages will be tested. Some API calls may return 401/403 — these will be flagged but not treated as failures.+- Continue to Phase 4.++**If "Cancel testing"**:+- Stop the skill and inform the user they can re-run it after resolving authentication.++### Output++- Authentication status resolved for both layers:+ - Private site gate: passed, not needed, or cancelled+ - Site-level auth: logged in, skipped, or not needed++---++## Phase 4: Crawl & Test Pages++**Goal:** Discover all navigable links on the site and verify each page loads correctly.++### Actions++#### 4.1 Discover Links from Current Page++Use `browser_evaluate` to extract all internal links:++```javascript+() => {+ const links = Array.from(document.querySelectorAll('a[href]'));+ return links+ .map(a => a.href)+ .filter(href => href.startsWith(window.location.origin))+ .filter(href => !href.includes('#') || href.split('#')[0] !== window.location.href.split('#')[0])+ .map(href => href.split('#')[0])+ .filter((href, i, arr) => arr.indexOf(href) === i);+}+```++Present the discovered links to the user:+> "Found **X** internal links on the homepage. Testing each page..."++#### 4.2 Test Each Page++For each discovered URL, in sequence:++1. **Navigate**: Use `browser_navigate` to go to the URL.+2. **Wait**: Use `browser_wait_for` with **time: 3** seconds for the page to render.+3. **Snapshot**: Use `browser_snapshot` to verify the page rendered content.+4. **Check for errors**: Look for error indicators in the snapshot (404, 500, blank page, error messages).+5. **Console errors**: Use `browser_console_messages` with **level: "error"** to check for JavaScript errors.+6. **Discover new links**: Use `browser_evaluate` (same script as 4.1) to find any new internal links not already in the queue.+7. **Record result**: URL, status (Pass/Fail), error count, notes.++#### 4.3 Crawl Newly Discovered Links++- Add any newly discovered links from step 4.2.6 to the test queue.+- Continue testing until all links are visited or the **25-page cap** is reached.+- If the cap is hit, inform the user: "Reached the 25-page testing limit. **Y** additional links were discovered but not tested."++#### 4.4 Record Page Test Results++Build a results list tracking:+- URL tested+- Load status (Pass / Fail)+- Number of console errors+- Notes (error messages, blank page, redirect, etc.)++### Output++- All discoverable pages crawled (up to 25)+- Pass/fail status recorded for each page+- New links discovered during crawl added to results++---++## Phase 5: Test API Requests++**Goal:** Capture and analyze all API requests made by the site to verify they are working.++### Actions++#### 5.1 Revisit Data-Driven Pages++Navigate back to pages that are likely to make API calls — pages with dynamic content such as data tables, lists, forms, or dashboards. Prioritize pages where `/_api/` requests were observed in Phase 2.6 or Phase 4.++For each data-driven page:+1. Use `browser_navigate` to go to the page.+2. Use `browser_wait_for` with **time: 5** seconds to allow API calls to complete.++#### 5.2 Capture Network Requests++- Use `browser_network_requests` with **includeStatic: false** to get all network requests.+- Filter for API requests matching these patterns:+ - `/_api/` — Power Pages Web API / OData endpoints+ - `/api/` — Custom API endpoints+ - URLs containing `odata` or `$filter`, `$select`, `$expand` query parameters++#### 5.3 Analyze API Responses++For each captured API request, evaluate:++| Status Code | Category | Action |+|-------------|----------|--------|+| 200, 201, 204 | **Pass** | Valid successful response |+| 304 | **Warning** | Cached response — acceptable but note it |+| 401 | **Fail** | Unauthorized — missing or expired auth token |+| 403 | **Fail** | Forbidden — table permissions or site settings issue |+| 404 | **Fail** | Not found — incorrect entity set name or endpoint |+| 500 | **Fail** | Server error — internal Dataverse or plugin error |+| Other 4xx/5xx | **Fail** | Unexpected error |++#### 5.4 Provide Actionable Guidance for Failures++For each failed API request, provide specific remediation:++- **401 Unauthorized**: "This endpoint requires authentication. If you skipped login in Phase 3, try re-running with authentication. Otherwise, check that the auth token is being passed correctly."+- **403 Forbidden on `/_api/` calls**: "Check the following:\n 1. **Table permissions** — Ensure a table permission exists for this table with the correct scope and privileges (Read, Write, etc.) assigned to the appropriate web role.\n 2. **Site settings** — Verify `Webapi/<tablename>/enabled` is set to `true` and `Webapi/<tablename>/fields` lists the required columns (exact Dataverse LogicalNames, all lowercase, comma-separated).\n 3. **Web role assignment** — Confirm the authenticated user has the correct web role assigned."+- **404 Not Found**: "Verify the entity set name (should be the plural form of the table logical name). Check that the table exists in Dataverse and is published."+- **500 Internal Server Error**: "Enable the `Webapi/error/innererror` site setting (set to `true`) to get detailed error messages. Redeploy and retest to see the inner error details."++#### 5.5 Test Form Submissions (Optional)++If forms are detected on any page (via `browser_snapshot` showing form elements), ask the user before interacting:++| Question | Header | Options |+|----------|--------|---------|+| I found forms on the site that may trigger API calls when submitted. Should I attempt to interact with these forms to test the POST/PATCH API endpoints? Note: this may create or modify data in your Dataverse environment. | Form Testing | Yes, test form submissions — I understand this may create test data, Skip form testing (Recommended) — Only test read-only API calls |++**If "Yes"**:+1. Use `browser_click` to interact with form submit buttons.+2. Use `browser_wait_for` to wait for the form response.+3. Use `browser_network_requests` to capture the resulting POST/PATCH requests.+4. Analyze responses using the same criteria as 5.3.++**If "Skip"**: Continue to Phase 6 with read-only API results only.++### Output++- All API endpoints discovered and tested+- Pass/fail status with HTTP status codes recorded+- Actionable remediation guidance provided for each failure++---++## Phase 6: Generate Test Report++**Goal:** Present a comprehensive summary of all test results and suggest next steps.++### Actions++#### 6.1 Record Skill Usage++> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`++Follow the skill tracking instructions in the reference to record this skill's usage. Use `--skillName "TestSite"`.++#### 6.2 Present Page Test Results++Present results in a clear table:++```+## Page Test Results++| # | URL | Status | Console Errors | Notes |+|---|-----|--------|----------------|-------|+| 1 | / | Pass | 0 | Homepage loaded successfully |+| 2 | /about | Pass | 0 | |+| 3 | /products | Pass | 2 | Minor JS warnings |+| 4 | /admin | Fail | 1 | 403 Forbidden |++Pages tested: 4/4 | Passed: 3 | Failed: 1+```++#### 6.3 Present API Test Results++```+## API Test Results++| # | Endpoint | Method | Status | Notes |+|---|----------|--------|--------|-------|+| 1 | /_api/cr4fc_products | GET | 200 OK | 12 records returned |+| 2 | /_api/cr4fc_categories | GET | 200 OK | 3 records returned |+| 3 | /_api/cr4fc_orders | GET | 403 Forbidden | Missing table permissions |++API endpoints tested: 3 | Passed: 2 | Failed: 1+```++If no API requests were captured, note: "No API requests (`/_api/` or OData) were detected during testing. This site may not use the Web API, or API calls may require specific user interactions to trigger."++#### 6.4 Present Overall Summary++```+## Overall Test Summary++| Category | Tested | Passed | Failed | Warnings |+|-----------------|--------|--------|--------|----------|+| Pages | 4 | 3 | 1 | 0 |+| API Endpoints | 3 | 2 | 1 | 0 |+| Console Errors | — | — | — | 2 |++Overall: X/Y checks passed+```++#### 6.5 Present Recommendations++For each failure, reiterate the specific remediation guidance from Phase 5.4. Group recommendations by category:++- **Table permissions issues** → `/power-pages:create-webroles` or manually configure table permissions+- **Site settings issues** → Check `Webapi/<table>/enabled` and `Webapi/<table>/fields` settings+- **Authentication issues** → `/power-pages:setup-auth`+- **Missing endpoints** → Verify table exists in Dataverse via `/power-pages:setup-datamodel`+- **Server errors** → Enable `Webapi/error/innererror` site setting for diagnostics++#### 6.6 Close Browser++- Use `browser_close` to clean up the browser session.++#### 6.7 Suggest Next Steps++Based on the test results, suggest relevant skills:++- If API failures were found: `/power-pages:integrate-webapi` — Fix Web API site settings and table permissions+- If authentication issues: `/power-pages:setup-auth` — Configure authentication providers+- If pages had errors: Review the site code and redeploy with `/power-pages:deploy-site`+- If all tests passed: Site is working correctly! Consider `/power-pages:add-seo` for search engine optimization++### Output++- Comprehensive test report presented with pass/fail for pages and APIs+- Actionable recommendations for each failure+- Browser session closed+- Next steps suggested++---++## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase+- **This skill is read-only** — it does not modify any files or data+- **Never attempt to log in** on behalf of the user — always ask them to log in via the browser window+- **Present errors clearly** — when a page or API fails, include the specific URL and error details++### Key Decision Points++1. **Phase 1.3**: If the site is not activated, stop and redirect to `/power-pages:activate-site`+2. **Phase 1.4**: If no URL can be auto-detected, must ask the user+3. **Phase 3.2**: If the site is private (redirects to identity provider), must ask the user to log in — cannot bypass+4. **Phase 3.5**: If site-level authentication is available, must ask the user whether to log in or skip — cannot auto-login+5. **Phase 4.3**: Stop crawling at 25 pages to prevent infinite loops+6. **Phase 5.5**: Before interacting with forms (which may create/modify data), must get explicit user permission++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Resolve site URL | Resolving site URL | Get URL from user input, activation status check, or context |+| Launch browser and verify initial load | Loading site in browser | Navigate to site, verify homepage loads, capture baseline errors |+| Check authentication requirements | Checking authentication | Detect if site requires auth, handle login if needed |+| Crawl and test all pages | Crawling site pages | Discover links, navigate each page, verify loads, check console errors |+| Test API requests | Testing API endpoints | Capture network requests, verify API responses, analyze errors |+| Generate test report | Generating test report | Present summary of all pages and APIs tested, suggest next steps |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`.++---++**Begin with Phase 1: Resolve Site URL**