Skip to content

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

[Pages] Add $expand and OneToMany relationship support to Web API skill (#48)

Priyanshu Agrawal7ca5f46c8503
diff --git a/.github/workflows/power-pages-script-tests.yml b/.github/workflows/power-pages-script-tests.yml
new file mode 100644
index 000000000..293b7db39
--- /dev/null
+++ b/.github/workflows/power-pages-script-tests.yml
@@ -0,0 +1,33 @@
+name: power-pages-script-tests
+
+on:
+ pull_request:
+ branches:
+ - main
+ paths:
+ - "plugins/power-pages/**"
+
+jobs:
+ test-power-pages-scripts:
+ name: test-power-pages-scripts (${{ matrix.os }})
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - ubuntu-latest
+ - windows-latest
+ - macos-latest
+ steps:
+ - name: checkout
+ uses: actions/checkout@v4
+
+ - name: setup-node
+ uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - name: run-power-pages-script-tests
+ shell: bash
+ working-directory: plugins/power-pages/scripts/tests
+ run: node --test
diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.json
index 599d505d9..b1b60b616 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.1.1",
+ "version": "1.1.2",
"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.md
index e35578198..c3ce179f7 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -11,9 +11,12 @@ Read `PLUGIN_DEVELOPMENT_GUIDE.md` for UX and reliability standards when creatin
- **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.
+- **Power Pages config loading** must reuse `scripts/lib/powerpages-config.js` anywhere a script reads `.powerpages-site` table-permission or site-setting YAML. Keep that module focused on loading/parsing code-site config only; put validation or business rules in separate validator modules.
+- **Script changes require tests** — Whenever you add a new script or modify an existing script, add or update `node:test` coverage under `scripts/tests/`. Prefer one `*.test.js` file per script/module being tested, and keep the PowerShell test command passing: `$files = Get-ChildItem .\plugins\power-pages\scripts\tests\*.test.js | ForEach-Object { $_.FullName }` followed by `node --test $files`. Validator changes are not an exception; they must always ship with test coverage.
+- **Dataverse-backed validation** must stay opt-in for local runs only. Do not require live Dataverse connectivity in CI workflows or default test runs; gate it behind explicit local flags such as `--validate-dataverse-relationships`.
- **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).
+- **Hooks** are defined centrally in `hooks/hooks.json`, using `PostToolUse` with matcher `Skill` so validation runs when a tracked Power Pages skill completes.
## Skill Development Conventions
@@ -38,15 +41,6 @@ user-invocable: true
argument-hint: <optional>
allowed-tools: Read, Write, Edit, Bash, Glob, Grep, Task, TaskCreate, TaskUpdate, TaskList, AskUserQuestion
model: opus
-hooks:
- Stop:
- - hooks:
- - type: command
- command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/<skill-name>/scripts/validate-<skill>.js"'
- timeout: 30
- - type: prompt
- prompt: "<completeness checklist>"
- timeout: 30
---
```
@@ -55,8 +49,8 @@ Note: `allowed-tools` must be a comma-separated list, not JSON array or YAML lis
### Key Patterns
- **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).
+- **Deployment prompt** — Skills that modify site artifacts should end by asking "Ready to deploy?" and invoke `/deploy-site` if yes.
+- **Lifecycle hooks** — If a skill needs command validation or checklist enforcement, update `hooks/hooks.json` and `scripts/lib/powerpages-hook-utils.js`. Do not define hook registration in individual `SKILL.md` files.
- **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).
diff --git a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md
index d84d33e00..f40fc2014 100644
--- a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md
+++ b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md
@@ -2,45 +2,45 @@
## 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.
+A plugin can have many 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.
+Here are **five UX and reliability pillars** that every skill and agent 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.
+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 agent.
### 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.
+Long operations must show structured progress — not silence. The user should always know what's happening, what phase they're in, and what's next.
### 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.
+Every action the agent 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.
+Complex, multi-table operations should delegate to specialized agents in isolated contexts, keeping the main conversation responsive and clean.
-### 04 — PAC CLI Determinism
+### 04 — Deterministic Execution
**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.
+Deterministic operations (file creation, Dataverse API calls, UUID generation, YAML parsing) must use shared Node.js scripts — not inline LLM-generated commands. LLMs compose the intent; scripts execute 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.
+The plugin must show every action it performs in real time and seek explicit user approval at defined checkpoints. The user should never be surprised by what the plugin did.
---
@@ -48,59 +48,42 @@ The plugin must show every action it performs in real time and seek explicit use
### 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.
+When a skill deploys a site or audits permissions across many tables, the terminal can go quiet. The user doesn't know if it's working, stuck, or crashed. Unexplained silence beyond 10 seconds causes users to assume failure — and they interrupt the process.
### 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
-```
+Every skill must implement **task-based progress tracking** using `TaskCreate` and `TaskUpdate`. Tasks are created upfront at Phase 1, one per phase, and marked `in_progress` / `completed` as the skill progresses.
### 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.
+Every skill creates all phase tasks at the start:
```
-# In every skill's SKILL.md — define the progress contract
-
-## Progress Stages
-Every long-running operation MUST print stage markers:
+Phase 1: TaskCreate → subject: "Verify prerequisites", activeForm: "Verifying prerequisites"
+Phase 2: TaskCreate → subject: "Discover existing config", activeForm: "Discovering config"
+Phase 3: TaskCreate → subject: "Review plan with user", activeForm: "Reviewing plan"
+Phase 4: TaskCreate → subject: "Implement changes", activeForm: "Implementing changes"
+Phase 5: TaskCreate → subject: "Verify results", activeForm: "Verifying results"
+Phase 6: TaskCreate → subject: "Deploy and summarize", activeForm: "Deploying"
+```
-Stage format: [STAGE n/N] Stage name... {status}
-Status values: STARTED | DONE | FAILED | SKIPPED
+Each task has three fields:
+- `subject` — Imperative form (what to do)
+- `activeForm` — Present continuous (shown in the spinner)
+- `description` — Brief explanation of the phase
-# 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)
-```
+For skills that process multiple entities (e.g., audit-permissions auditing many tables), create **per-entity sub-tasks** dynamically within the relevant phase.
-### What This Means for Each Phase
+### What This Means in Practice
-| 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 |
+| Skill | Phases | Dynamic Sub-Tasks |
+|-------|--------|-------------------|
+| `/deploy-site` | 6 phases (prereqs → auth → env → build/upload → verify → summarize) | None |
+| `/integrate-webapi` | 7 phases (prereqs → analyze → plan → implement → verify → permissions → deploy) | Per-table tasks in Phase 4 |
+| `/audit-permissions` | 7 phases (prereqs → discover → analyze → audit → cross-check → report → present) | Per-table tasks in Phase 4 (checklist A-K) |
+| `/create-site` | 8 phases (prereqs → gather → plan → scaffold → implement → validate → deploy → summarize) | None |
-> **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.
+> **Acceptance criterion:** Every skill must create all phase tasks upfront at Phase 1 start. Each task must have `subject`, `activeForm`, and `description`. Tasks must be marked `in_progress` when starting and `completed` when done.
---
@@ -108,64 +91,34 @@ Status values: STARTED | DONE | FAILED | SKIPPED
### 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 agent says "I've created table permissions and site settings" — but did it? The user has no way to verify without manually inspecting YAML files. This erodes trust.
### 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 →]
+Every skill must have a **dedicated Verify phase** (typically Phase 5) — separate from implementation. Verification uses a different code path than the action itself.
### The Verification Pattern
-```python
-# Every skill that modifies state must implement this pattern:
-
-## Verification Protocol
+After implementation, always run a standalone verification phase that:
-# Step 1: Execute the action
-execute_action() # e.g., create tables via Dataverse API
+1. **Checks expected files exist** — Glob for generated files and confirm count matches plan
+2. **Validates schema/content** — Run shared validators (`validate-permissions-schema.js`, `site-settings-validator.js`, `web-roles-validator.js`)
+3. **Runs project build** — Confirm no TypeScript/build errors from generated code
+4. **Reports results** — Present a summary to the user before proceeding
-# 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 in Practice
-### Verification Methods by Phase
+| Skill | Verification Phase | What It Checks |
+|-------|-------------------|----------------|
+| `/deploy-site` | Phase 5 | Upload succeeded, site responds, activation status |
+| `/integrate-webapi` | Phase 5 | File inventory matches plan, all imports resolve, build passes |
+| `/audit-permissions` | Phase 6 | Findings report generated, all tables audited, cross-checks complete |
+| `/create-site` | Phase 6 | All pages render, design foundations applied, build passes |
+| `/create-webroles` | Stop hook | Web role YAML validates (schema, naming conventions, booleans) |
-| 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 |
+**Hook-based validation** — Skills tracked in `hooks/hooks.json` get automatic validation when they complete. The `PostToolUse` hook on `Skill` dispatches to per-skill validator scripts via `run-skill-posttool-validation.js`. Validators use `approve()` / `block(reason)` from `scripts/lib/validation-helpers.js`.
-> **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).
+> **Acceptance criterion:** No skill that creates, modifies, or deletes files may ship without a dedicated verification phase. Verification must use a different code path than creation (e.g., run validators, glob for files, build the project — don't just trust the write succeeded).
---
@@ -173,108 +126,128 @@ report_with_evidence()
### 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.
+Complex operations (multi-table Web API integration, permission analysis, data model design) generate large amounts of intermediate output that pollutes the main context. Additionally, specialized tasks benefit from purpose-built system prompts.
### 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
+Delegate to specialized **architect agents** defined in `agents/`. Skills invoke agents via the `Task` tool. Each agent has its own context, tool permissions, model, and system prompt.
-The plugin should ship with purpose-built sub-agents for each category of long-running work:
+### Current Agents
-| 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 |
+| Agent | Purpose | Mode | Key Tools |
+|-------|---------|------|-----------|
+| `webapi-integration` | Implements Web API code for a single table (client, types, service, hooks) | Generative (writes code) | Read, Write, Edit, Bash, Glob, Grep |
+| `table-permissions-architect` | Analyzes site and proposes table permissions plan | Plan mode (proposes, then creates after approval) | Read, Write, Edit, Bash, Glob, Grep, EnterPlanMode |
+| `webapi-settings-architect` | Analyzes site and proposes Web API site settings | Plan mode (proposes, then creates after approval) | Read, Write, Edit, Bash, Glob, Grep, EnterPlanMode |
+| `data-model-architect` | Analyzes requirements and Dataverse, proposes data model | Plan mode (read-only advisor) | Read, Bash, Glob, Grep, EnterPlanMode |
-### Example Sub-Agent Definition
+### Agent Orchestration Patterns
-```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
----
+**Sequential-then-parallel** — When agents depend on shared output:
-# You are a Power Pages deployment specialist.
+```
+# /integrate-webapi Phase 4:
+# First table creates the shared powerPagesApi.ts client.
+# After the first table completes and the shared client exists,
+# invoke all remaining tables IN PARALLEL via multiple Task calls.
+```
-## 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
+**Independent parallel** — When agents are fully independent:
-## Constraints
-- NEVER modify source code — only deploy what exists
-- ALWAYS use PAC CLI for deterministic operations
-- ALWAYS verify after every mutating action
```
+# /integrate-webapi Phase 6.3:
+# table-permissions-architect and webapi-settings-architect are
+# INDEPENDENT — invoke them IN PARALLEL rather than sequentially.
+# Wait for BOTH agents to complete before proceeding.
+```
+
+### Plan Mode
+
+Architect agents use `EnterPlanMode` / `ExitPlanMode` to propose plans before creating files. The agent renders an HTML visualization (Mermaid diagram, permissions matrix, etc.) for the user to review. If the user rejects, the agent revises. This prevents costly rework.
### 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 |
+| Operation | Approach | Rationale |
+|-----------|----------|-----------|
+| Generate a React component | Inline (main agent) | Fast, context-relevant, user wants to see output |
+| Integrate Web API for one table | **Agent** (`webapi-integration`) | Specialized system prompt, isolated context |
+| Analyze and propose permissions | **Agent** (`table-permissions-architect`) | Plan mode, specialized analysis |
+| Run a deterministic script | Inline (`node script.js`) | Fast, no agent overhead needed |
+| Audit permissions across many tables | Inline with per-table sub-tasks | Skill orchestrates, but tracks per-table progress |
-> **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).
+> **Acceptance criterion:** Skills must delegate specialized work to purpose-built agents. Agent invocations must be documented as sequential or parallel with rationale. Agents that propose changes must use plan mode.
---
-## Pillar 4 — PAC CLI Determinism
+## Pillar 4 — Deterministic Execution
### 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.
+LLMs are probabilistic. When an LLM constructs inline bash commands for Dataverse API calls, file creation, or YAML generation, minor variations cause intermittent failures that are 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"`
+**LLMs compose. Scripts execute.** The LLM determines *what* needs to happen (intent). Shared Node.js scripts *make it happen* (execution). This separation creates a deterministic layer that produces the same result every time.
+
+### Script Categories
+
+**Shared helpers** (`scripts/lib/`):
+
+| Module | Purpose |
+|--------|---------|
+| `validation-helpers.js` | `runValidation()`, `findPath()`, `findProjectRoot()`, `approve()`, `block()` — shared boilerplate for all validators |
+| `powerpages-config.js` | Loads `.powerpages-site` YAML files (table permissions, site settings, web roles) with consistent parsing |
+| `powerpages-hook-utils.js` | Maps skill names to validator scripts for the hook dispatcher |
+| `powerpages-schema-validator.js` | Validates permission/site-setting YAML schema |
+| `table-permissions-validator.js` | Validates table permission YAML |
+| `web-roles-validator.js` | Validates web role YAML |
+| `site-settings-validator.js` | Validates site setting YAML |
+| `render-template.js` | Template rendering with `__PLACEHOLDER__` variable substitution |
+
+**File creation scripts** (`scripts/`):
+
+| Script | Purpose |
+|--------|---------|
+| `create-table-permission.js` | Generates table permission YAML with proper formatting, UUIDs, field ordering |
+| `create-site-setting.js` | Generates site setting YAML |
+| `generate-uuid.js` | Centralized UUID generation — never duplicate this |
+| `update-skill-tracking.js` | Records skill usage in site settings |
+
+**Dataverse API scripts** (`scripts/` and skill-specific `scripts/`):
+
+| Script | Purpose |
+|--------|---------|
+| `dataverse-request.js` | Generic authenticated Dataverse API request helper |
+| `verify-dataverse-access.js` | Verifies Dataverse connectivity and permissions |
+| `check-activation-status.js` | Queries Power Platform API for site activation status |
+| `clear-site-cache.js` | Clears site cache via Power Platform admin API |
+
+### Usage Pattern
+
+Skills invoke scripts via `node` with CLI arguments:
+
+```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" \
+ --read --create
+```
-PAC CLI handles auth, URL construction, retries, and error formatting deterministically. Works 100% of the time.
+Scripts that call Dataverse APIs import `getAuthToken` and `makeRequest` from `scripts/lib/validation-helpers.js`. Never use inline PowerShell `Invoke-RestMethod` for API calls.
-### Determinism Classification
+### Testing Requirement
-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.
+Every script must have test coverage in `scripts/tests/`. Run tests with:
-| 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 |
+```powershell
+$files = Get-ChildItem .\plugins\power-pages\scripts\tests\*.test.js | ForEach-Object { $_.FullName }
+node --test $files
+```
-> **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.
+> **Acceptance criterion:** All file creation, YAML generation, UUID generation, and Dataverse API calls must use shared scripts. No skill may use LLM-generated inline commands for operations that have a shared script. New scripts must ship with test coverage.
---
@@ -282,122 +255,51 @@ Every operation in the plugin should be classified as either **deterministic** (
### 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.
+An agent that silently creates table permissions, modifies site settings, and deploys — all from a single prompt — is dangerous in an enterprise context. The user didn't see what happened, didn't consent to each step, and can't explain to their team what the plugin did.
### 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.
-```
+**Show everything. Ask at defined checkpoints.** The plugin operates with radical transparency: every action is logged, every decision is explained, and user approval is required at specific points in the workflow.
-**Layer 2 — Decision Explanation (for non-obvious choices)**
+### The Three-Point Approval Pattern
-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.
+Every skill pauses for user approval at three junctures:
-```
-ℹ️ 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.
-```
+1. **After discovery** — Present what was found (existing config, code patterns, tables). Ask the user to confirm the scope before planning.
+2. **After planning** — Present the proposed plan (HTML visualization, permissions matrix, integration list). Ask the user to approve before implementing.
+3. **Before deployment** — Present what was created. Ask "Ready to deploy?" and invoke `/deploy-site` if yes.
-**Layer 3 — Approval Gates (for irreversible or high-impact actions)**
+Between checkpoints, skills work **autonomously** — no mid-analysis questions.
-Certain actions must pause and ask for explicit user confirmation before proceeding. The plugin must never assume consent for destructive operations.
+### Approval in Practice
-### Actions That Require Approval
+| Skill | Checkpoint 1 (Discovery) | Checkpoint 2 (Plan) | Checkpoint 3 (Deploy) |
+|-------|--------------------------|---------------------|----------------------|
+| `/deploy-site` | Confirm environment is correct | N/A (no plan phase) | Confirm site activation |
+| `/integrate-webapi` | Confirm tables to integrate | Approve permissions/settings plans (via plan mode agents) | Deploy site |
+| `/audit-permissions` | N/A (autonomous discovery) | N/A (autonomous audit) | "Fix issues?" after report |
+| `/create-site` | Confirm requirements | Approve site plan | Deploy site |
+| `/create-webroles` | Confirm web role requirements | Approve roles and assignments | Deploy site |
-| 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 |
+### Decision Explanation
-### The Approval Protocol
+When the agent makes a non-obvious design choice, it must explain *why*:
```
-# 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
+Decision: Set Contact 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.
```
-### Transparency Levels by Context
+### Actions That Always Require Approval
-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.
-```
+| Action Category | Examples |
+|----------------|----------|
+| **Production deployment** | `pac pages upload-code-site` to any environment |
+| **Security configuration** | Creating/modifying table permissions, web roles |
+| **Environment changes** | Enabling JS attachments, changing site settings |
+| **Destructive operations** | Deleting permissions, removing web roles |
-> **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.
+> **Acceptance criterion:** Every skill must implement the three-point approval pattern. No approval-gated action may proceed without explicit user confirmation via `AskUserQuestion`. Skills must work autonomously between checkpoints — no mid-analysis questions.
---
diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.md
index 7f97005d3..d2eef38e2 100644
--- a/plugins/power-pages/README.md
+++ b/plugins/power-pages/README.md
@@ -19,6 +19,15 @@ Create and deploy Power Pages code sites using modern frontend frameworks. This
claude --plugin-dir /path/to/power-platform-skills/plugins/power-pages
```
+## Hook behavior
+
+The plugin centralizes Claude Code hook registration in `hooks/hooks.json`.
+
+- `PostToolUse` hooks match the `Skill` tool so validation runs when a tracked Power Pages skill completes.
+- Command validators and checklist verification are maintained centrally instead of in per-skill frontmatter.
+
+This keeps hook behavior in one place and avoids relying on skill-frontmatter hook registration.
+
## Prerequisites
| Prerequisite | Required for | Install |
@@ -97,7 +106,7 @@ The skill first scans your codebase to find components using mock data, placehol
- TypeScript entity types and domain mappers per table
- CRUD service layer per table using `/_api/` endpoints with dual token headers and `@odata.bind` for lookups
- Framework-specific patterns: React hooks, Vue composables, Angular injectable services
-- Table permission YAML files and site setting YAML files (with explicit column lists — never `*` wildcards)
+- Table permission YAML files and site setting YAML files (with explicit validated column lists by default; use `*` only for aggregate OData scenarios that otherwise 403)
**What gets updated:**
@@ -202,6 +211,23 @@ claude --dangerously-skip-permissions
- [Power Pages REST API](https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites)
- [Dataverse Web API](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/overview)
+## Testing validator scripts
+
+Run the validator unit tests with Node's built-in test runner:
+
+```powershell
+$files = Get-ChildItem .\plugins\power-pages\scripts\tests\*.test.js | ForEach-Object { $_.FullName }
+node --test $files
+```
+
+To validate table-permission relationship names against live Dataverse metadata during local testing, run:
+
+```powershell
+node .\plugins\power-pages\scripts\validate-permissions-schema.js --projectRoot C:\path\to\site --validate-dataverse-relationships --envUrl https://your-org.crm.dynamics.com
+```
+
+This Dataverse relationship check is intended for local validation only and should not be used in CI.
+
## License
[MIT](../../LICENSE)
diff --git a/plugins/power-pages/agents/assets/permissions-plan.html b/plugins/power-pages/agents/assets/permissions-plan.html
index bfebe087b..33d3ff655 100644
--- a/plugins/power-pages/agents/assets/permissions-plan.html
+++ b/plugins/power-pages/agents/assets/permissions-plan.html
@@ -328,23 +328,39 @@ function renderRoles() {
c.innerHTML = html;
}
-// Render Permissions
+// Render Permissions — hierarchical tree view
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 => {
+
+ // Build parent→children map
+ const childrenOf = {};
+ PERMS.forEach(p => {
+ const key = p.parent || '__root__';
+ if (!childrenOf[key]) childrenOf[key] = [];
+ childrenOf[key].push(p);
+ });
+
+ // Sort each group: proposed first
+ Object.values(childrenOf).forEach(arr => arr.sort((a, b) => (b.isNew ? 1 : 0) - (a.isNew ? 1 : 0)));
+
+ function renderPermCard(p, depth) {
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 };
+ const indent = depth * 32;
+ const children = childrenOf[p.id] || [];
+
+ let html = `<div style="position:relative;">`;
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')">
+ ${depth > 0 ? '<span style="font-size:15px;color:var(--purple);font-weight:700;margin-right:2px;">&#8627;</span>' : ''}
<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>
+ ${children.length > 0 ? `<span style="font-size:10px;color:var(--purple);font-weight:700;font-family:var(--mono);background:var(--purple-bg);border:1px solid var(--purple-border);padding:1px 6px;border-radius:3px;">${children.length} child${children.length > 1 ? 'ren' : ''}</span>` : ''}
<span class="expand-chevron">&#9654;</span>
</div>
<div class="expandable-body">
@@ -354,12 +370,28 @@ function renderPerms() {
<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>` : ''}
+ ${p.parentRelationship ? `<div style="grid-column:span 2"><div class="field-label">Parent Relationship</div><span style="color:var(--text);font-family:var(--mono);font-size:11px;">${p.parentRelationship}</span> <span style="font-size:11px;color:var(--text-dim);">\u2192 ${parentName}</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>`;
- });
+
+ // Render children recursively
+ if (children.length > 0) {
+ html += `<div style="padding-left:4px;border-left:2px solid var(--purple-border);margin-left:6px;margin-top:2px;margin-bottom:6px;">`;
+ children.forEach(child => { html += renderPermCard(child, depth + 1); });
+ html += `</div>`;
+ }
+
+ html += `</div>`;
+ return html;
+ }
+
+ // Render root permissions (those with no parent)
+ const roots = childrenOf['__root__'] || [];
+ let html = '';
+ roots.forEach(p => { html += renderPermCard(p, 0); });
+
c.innerHTML = html;
}
diff --git a/plugins/power-pages/agents/data-model-architect.md b/plugins/power-pages/agents/data-model-architect.md
index 38e78aed1..42fc7ada7 100644
--- a/plugins/power-pages/agents/data-model-architect.md
+++ b/plugins/power-pages/agents/data-model-architect.md
@@ -17,9 +17,6 @@ tools:
- Bash
- 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
@@ -34,7 +31,7 @@ You are a Dataverse data model architect for Power Pages code sites. Your job is
1. **Analyze Site Code** — Read the existing project to infer what data the site needs
2. **Discover Existing Tables** — Query Dataverse OData API to find current tables, columns, and publisher prefix
3. **Analyze Reuse Opportunities** — Identify which existing tables can be reused or extended
-4. **Propose Data Model** — Render the ER diagram in the browser via Playwright, then enter plan mode for user approval
+4. **Propose Data Model** — Render the HTML plan and open it in the default browser, then enter plan mode for user approval
**Important:** Do NOT ask the user questions. Autonomously analyze the site code and Dataverse environment to figure out the data model, then present your findings via plan mode for the user to review and approve.
@@ -342,14 +339,7 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/render-data-model-plan.js" --output "<OUTPUT
#### 4.5.4 Open in Browser
-1. **Resize the browser** to a large viewport:
- Use `browser_resize` with **width: 1920** and **height: 1080**.
-
-2. Navigate Playwright to the HTML file using `browser_navigate` with the full file path.
-
-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).
+Open the generated HTML file in the user's default browser so they can interact with the tabs and ER diagram.
### 4.6 Design Rationale & Recommendations
diff --git a/plugins/power-pages/agents/table-permissions-architect.md b/plugins/power-pages/agents/table-permissions-architect.md
index 6e90e9b65..d0786f8ef 100644
--- a/plugins/power-pages/agents/table-permissions-architect.md
+++ b/plugins/power-pages/agents/table-permissions-architect.md
@@ -18,9 +18,9 @@ tools:
- 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
+ - 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
@@ -34,7 +34,7 @@ You are a table permissions architect for Power Pages code sites. Your job is to
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
+3. **Analyze Access Patterns** — Identify tables needing permissions, then use task tracking to systematically analyze each table's scope and CRUD privileges one at a time with code evidence
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
@@ -50,6 +50,7 @@ Check that the site has been deployed at least once by looking for the `.powerpa
### 1.1 Locate the Project
Use `Glob` to find:
+
- `**/powerpages.config.json` — Power Pages config (identifies the project root)
- `**/.powerpages-site` — Deployment folder
@@ -57,11 +58,11 @@ Use `Glob` to find:
**If `.powerpages-site` folder does NOT exist:**
-Enter plan mode and state:
+Stop and tell the user:
-> "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."
+> "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 `/deploy-site` before table permissions can be configured."
-Exit plan mode and stop. Do NOT proceed with the remaining steps.
+Do NOT proceed with the remaining steps.
**If `.powerpages-site` exists:** Proceed to Step 2.
@@ -90,7 +91,7 @@ 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`.
+**If no web roles exist:** You will need to create them in Step 6 before creating table permissions. At minimum, plan to create `Anonymous Users` (with `anonymoususersrole: true`) and `Authenticated Users` (with `authenticatedusersrole: true`) using the `create-web-role.js` script. Note these as proposed roles in the plan (Step 5).
### 2.2 Discover Existing Table Permissions
@@ -106,7 +107,7 @@ Each table permission file has this format (code site / git format — fields al
adx_entitypermission_webrole:
- ce938206-701d-4902-85b2-b46b1dd169b9
append: true
-appendto: true
+appendto: false
create: true
delete: false
entitylogicalname: cra5b_order
@@ -130,7 +131,7 @@ entitylogicalname: cra5b_orderitem
entityname: Order Item - Authenticated Access
id: a3b4c5d6-7890-4abc-def0-123456789012
parententitypermission: d75934c2-5ea2-4b95-9309-e15637820626
-parentrelationshipname: cra5b_order_orderitem
+parentrelationship: cra5b_order_orderitem
read: true
scope: 756150003
write: false
@@ -138,6 +139,72 @@ write: false
Compile a list of existing table permissions noting which tables already have permissions configured.
+### Understanding Multi-Level Parent Hierarchies
+
+Table permissions support **deep parent-child chains** (not just 2 levels). A common real-world pattern is a 3-level hierarchy like **incident → portal comment → annotation** (attachments):
+
+**Level 1 — Root (Contact scope):** `incident`
+
+```yaml
+adx_entitypermission_webrole:
+- 987f1600-4e7f-f011-b4cc-000d3a5a150a
+append: true
+appendto: true
+create: true
+delete: true
+entitylogicalname: incident
+entityname: Customer Service - Cases where contact is customer
+id: ee1871a4-4d7f-f011-b4cc-000d3a5a150a
+read: true
+scope: 756150001
+write: true
+```
+
+**Level 2 — Child of incident (Parent scope):** `adx_portalcomment`
+
+```yaml
+adx_entitypermission_webrole: []
+append: true
+appendto: true
+create: true
+delete: true
+entitylogicalname: adx_portalcomment
+entityname: Customer Service - Portal Comment where contact is customer
+id: f41871a4-4d7f-f011-b4cc-000d3a5a150a
+parententitypermission: ee1871a4-4d7f-f011-b4cc-000d3a5a150a
+parentrelationship: incident_adx_portalcomments
+read: true
+scope: 756150003
+write: true
+```
+
+**Level 3 — Child of portal comment (Parent scope):** `annotation`
+
+```yaml
+adx_entitypermission_webrole: []
+append: true
+appendto: true
+create: true
+delete: false
+entitylogicalname: annotation
+entityname: Portal Comment - Attachments where contact is customer
+id: 31218baa-4d7f-f011-b4cc-000d3a5a150a
+parententitypermission: f41871a4-4d7f-f011-b4cc-000d3a5a150a
+parentrelationship: adx_portalcomment_Annotations
+read: true
+scope: 756150003
+write: true
+```
+
+Key points:
+- The **root** permission uses Contact/Account/Global scope. All deeper levels use **Parent scope**.
+- Each child's `parententitypermission` references its **immediate** parent's `id` — not the root.
+- The `parentrelationship` is the **one-to-many relationship name** from the parent table to the child table.
+- Child permissions at Level 2+ can have `adx_entitypermission_webrole: []` (empty) — they inherit role association through the parent chain.
+- A table can appear as a child at **multiple points** in the hierarchy (e.g., `annotation` can be a child of both `incident` and `adx_portalcomment` with different relationship names).
+
+When designing permissions, always consider whether the data model has 3+ level chains and create the full parent chain — don't stop at 2 levels.
+
---
## Step 3: Analyze Access Patterns
@@ -162,61 +229,71 @@ If no manifest exists, analyze the source code to infer which tables need permis
- **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
+- **`$expand` usage** — Look for expanded navigation properties that reference related tables. Each expanded related table also needs its own table permission with at least `read: true`.
Look for patterns like:
+
```text
/_api/<table_plural_name>
fetch.*/_api/
+$expand
+buildExpandClause
+ExpandOption
+```
+
+### 3.2.1 Detect `$expand` Related Tables
+
+Search the site source code for `$expand` usage (`$expand`, `buildExpandClause`, `ExpandOption`) to identify related tables that need read permissions.
+
+For each expanded navigation property found:
+
+- **Single-valued (lookup):** The target table needs `read: true` table permission for the same web role
+- **Collection-valued (one-to-many):** The child table needs `read: true` table permission. Prefer **Parent scope** (`756150003`) using the one-to-many relationship name so access is scoped to the parent record's children
+- **Nested expand:** Every table in the expansion chain needs `read: true` table permissions
+
+Cross-reference expanded navigation property names with the relationship metadata from Step 4.2 to determine the exact target table logical names.
+
+### 3.3 Build Table Permission Inventory with Task Tracking
+
+After identifying all tables that need permissions (from Steps 3.1, 3.2, and 3.2.1), use `TaskCreate` to create one task per table. Each task tracks the structured privilege analysis for that table. This forces a systematic, per-table evaluation instead of trying to determine all permissions at once.
+
+#### 3.3.1 Create Tasks
+
+For each table that needs permissions, create a task:
+
+```
+TaskCreate:
+ subject: "Analyze permissions for <table_logical_name>"
+ activeForm: "Analyzing <table_display_name> permissions"
+ description: "Determine scope, CRUD, append/appendto for <table_logical_name>"
+```
+
+Also create a summary task:
+
```
+TaskCreate:
+ subject: "Compile final permissions plan"
+ activeForm: "Compiling permissions plan"
+ description: "Combine all per-table analyses into the final plan"
+```
+
+Use `TaskList` at any point to review progress and see which tables still need analysis.
+
+#### 3.3.2 Per-Table Privilege Analysis
+
+For each table, mark its task `in_progress` and work through the privilege analysis checklist (sections A through K), recording code evidence for every decision.
+
+> Reference: ${CLAUDE_PLUGIN_ROOT}/references/table-permission-analysis-guide.md
+
+Mark the table's task as `completed` via `TaskUpdate`.
+
+#### 3.3.3 Cross-Table Validation & Role Consolidation
-### 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
+After all individual table analyses are complete, perform the cross-table validation pass (append/appendto consistency, `$expand` coverage, parent chain completeness, orphaned permissions, web role coverage, and role consolidation).
+
+> Reference: ${CLAUDE_PLUGIN_ROOT}/references/table-permission-analysis-guide.md — "Cross-Table Validation" section
+
+Use `TaskList` to review all completed analyses, then mark the "Compile final permissions plan" task as `in_progress`.
---
@@ -250,11 +327,19 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDe
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.
+Use the relationship `SchemaName` as the `parentrelationship` value in the child table permission.
+
+For tables that are candidates for **Contact** or **Account** scope, also verify that the table itself has the direct contact/account relationship you plan to use:
+
+```text
+EntityDefinitions(LogicalName='<child_table>')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute
+```
+
+Use this to confirm `contactrelationship` / `accountrelationship` on the secured table itself. Do **not** reuse the parent table's relationship name unless Dataverse shows that exact relationship on the child table too.
### 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`:
+For each table that has `create` or `write` permissions, query its lookup columns to determine append/appendto requirements:
```
node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table_logical_name>')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?\$select=LogicalName,Targets"
@@ -262,11 +347,16 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDe
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`
+This returns each lookup column and its target table(s). After querying **all** tables with create or write permissions, build two maps from the combined results:
+
+1. **Source map** (table → lookup columns): For each queried table, record which lookup columns it has and their targets. Used to determine `appendto` on the source table.
+2. **Reverse target map** (target table → list of source tables): For each target table found in any lookup's `Targets` array, record which source table(s) reference it. Used to determine `append` on the target table.
+
+- The **source table** (with the lookup) needs `appendto: true` — it links TO other records (checked via the source map)
+- Each **target table** in the `Targets` array needs `append: true` — other records link TO it (checked via the reverse target map)
+
+**Example:** Querying `cr87b_product` (which has create permissions) returns:
-**Example output:**
```
Lookup Targets
------ -------
@@ -274,14 +364,19 @@ 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)
+This produces:
+- Source map: `cr87b_product → [{ column: "cr87b_productcategoryid", targets: ["cr87b_productcategory"] }, { column: "cr87b_contactid", targets: ["contact"] }]`
+- Reverse target map: `cr87b_productcategory → [{ sourceTable: "cr87b_product", column: "cr87b_productcategoryid" }]`, `contact → [{ sourceTable: "cr87b_product", column: "cr87b_contactid" }]`
+
+Result:
+- `cr87b_product` needs `appendto: true` (it is the source table with lookup columns — it links to other records)
+- `cr87b_productcategory` needs `append: true` (it is the target table — other records link to it)
- `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
@@ -293,15 +388,16 @@ Do NOT stop the entire workflow for auth errors. Use the data model manifest and
## 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.
+Once you have completed Steps 1-4, prepare the permissions proposal. Section 5.1 describes the plan content. Section 5.2 generates the HTML plan file — 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`)
+**Permission Name Convention:** Use `<DisplayName> - <AccessType>` when multiple roles share the same CRUD+scope (e.g., `Product - Read`, `Order - Full Access`). Only include the role name `<DisplayName> - <RoleName> <AccessType>` when different roles need **different** CRUD or scope configurations for the same table (e.g., `Order - Anonymous Read` with Global/read-only vs `Order - Authenticated Access` with Contact/RCWD).
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)
@@ -309,15 +405,18 @@ For each permission, include:
- 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")
+ - One entry per **enabled** privilege explaining why it is necessary (e.g., `read`: "Products must be visible for catalog browsing", `append`: "Referenced by orders via a lookup column — other records link to this table")
- 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 each permission, prepare the exact `create-table-permission.js` script invocation that will be used in Step 6:
**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]
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "Global" [--read] [--create] [--write] [--delete] [--append] [--appendto]
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "Contact" --contactRelationshipName "<lookup_to_contact>" [--read] [--create] [--write] [--delete] [--append] [--appendto]
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "Account" --accountRelationshipName "<lookup_to_account>" [--read] [--create] [--write] [--delete] [--append] [--appendto]
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "Self" [--read] [--create] [--write] [--delete] [--append] [--appendto]
```
**For Parent scope:**
@@ -327,147 +426,25 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<
```
Note: Parent permissions must be created before child permissions — the child's `--parentPermissionId` uses the UUID from the parent's JSON output.
+For Contact and Account scopes, the relationship argument is mandatory and must use the lookup logical name from the table being secured.
-### 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
+### 5.2 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
+Prepare the JSON data file and run the render script following the data format reference:
-Write a temporary JSON data file (e.g., `<OUTPUT_DIR>/permissions-plan-data.json`) with these keys:
+> Reference: ${CLAUDE_PLUGIN_ROOT}/references/permissions-plan-data-format.md
-```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: `&#x1F6E1;&#xFE0F;` (shield), `&#x1F517;` (link), `&#x1F464;` (user), `&#x1F512;` (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
+### 5.3 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 |
+ | `Product - Read` | `cra5b_product` | Global | Anonymous Users, Authenticated 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)
@@ -475,9 +452,9 @@ Prepare for the plan mode message. Include:
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
+### 5.4 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.
+Use `EnterPlanMode` to present the complete proposal (sections 5.1 and 5.3) 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.
---
@@ -493,13 +470,15 @@ $result = node "${CLAUDE_PLUGIN_ROOT}/skills/create-webroles/scripts/create-web-
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).
+1. **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]
+$parentResult = node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Parent Permission Name>" --tableName "<table>" --webRoleIds "<uuid>" --scope "Global" [--read] [--create] [--write] [--delete] [--append] [--appendto]
+$contactResult = node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Contact Permission Name>" --tableName "<table>" --webRoleIds "<uuid>" --scope "Contact" --contactRelationshipName "<lookup_to_contact>" [--read] [--create] [--write] [--delete] [--append] [--appendto]
+$accountResult = node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Account Permission Name>" --tableName "<table>" --webRoleIds "<uuid>" --scope "Account" --accountRelationshipName "<lookup_to_account>" [--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]
@@ -507,6 +486,14 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<
The scripts handle UUID generation, alphabetical field ordering, correct YAML formatting (unquoted booleans/numbers/UUIDs, `adx_entitypermission_webrole` array format), and file naming automatically.
+**Before finalizing scope changes to existing permissions:** if you are running locally with Dataverse access, validate the resulting files using the shared validator with live relationship checks:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/validate-permissions-schema.js" --projectRoot "<PROJECT_ROOT>" --validate-dataverse-relationships --envUrl "<envUrl>"
+```
+
+If this local validation reports relationship or schema problems, stop and revise the plan instead of proceeding with file creation.
+
---
## Step 7: Return Summary
@@ -522,9 +509,12 @@ After creating all files, return a summary to the calling context:
## Critical Constraints
+- **No Administrators permissions by default**: Do NOT create table permissions for the `Administrators` web role unless the user explicitly asks for them. Administrators already have highly privileged access, so adding CRUD table permissions for them is unnecessary and creates security noise. If the user specifically requests Administrators permissions, include them in the plan — otherwise omit them entirely.
- **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`.
-- **No manual HTML generation**: Do NOT use `Write` or `Edit` to create the `permissions-plan.html` file directly. ALWAYS use `render-permissions-plan.js` with a JSON data file as described in Step 5.3. The only files you may write directly are the temporary JSON data file for the render script.
-- **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 manual HTML generation**: Do NOT use `Write` or `Edit` to create the `permissions-plan.html` file directly. ALWAYS use `render-permissions-plan.js` with a JSON data file as described in Step 5.2. The only files you may write directly are the temporary JSON data file for the render script.
+- **LOOKUP COLUMNS REQUIRE APPENDTO/APPEND**: When a table has `create` or `write` permissions AND has lookup columns to other tables, the source table (with the lookup) MUST have `appendto: true` and each target table (referenced by the lookup) MUST have `append: 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 speculative scope rewrites**: Never convert Parent scope to Contact/Account scope (or vice versa) based only on a runtime Web API failure or a guessed internal Power Pages behavior. Require deterministic code evidence plus Dataverse relationship evidence on the exact table being secured.
+- **Do not compare relationship names across unrelated entities**: Contact/account relationship names can legitimately differ between parent and child tables. Only validate whether each relationship exists on the table where it is used.
- **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.md
index c90d65a27..c8b63b7f1 100644
--- a/plugins/power-pages/agents/webapi-integration.md
+++ b/plugins/power-pages/agents/webapi-integration.md
@@ -191,7 +191,19 @@ The script outputs JSON: `{ "status": <code>, "data": { "value": [...] } }`. Eac
Use `ReferencingEntityNavigationPropertyName` as the Navigation Property name in `$expand` and `@odata.bind`. This is the **case-sensitive** name that must be used exactly.
-#### 2.5.5 Graceful Fallback
+#### 2.5.5 Query OneToMany Relationships (if applicable)
+
+If the table has one-to-many relationships (e.g., order → order lines, account → contacts), fetch the relationship metadata to get the correct collection-valued navigation property names:
+
+```
+node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET "EntityDefinitions(LogicalName='<table_logical_name>')/OneToManyRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute,ReferencedEntityNavigationPropertyName"
+```
+
+The script outputs JSON: `{ "status": <code>, "data": { "value": [...] } }`. Each entry contains `ReferencedEntityNavigationPropertyName` (the collection-valued navigation property on the parent entity), `ReferencingEntity` (the child table), and `ReferencingAttribute` (the foreign key column on the child table).
+
+Use `ReferencedEntityNavigationPropertyName` as the navigation property name in `$expand` for collection-valued expansions. This is the **case-sensitive** name that must be used exactly.
+
+#### 2.5.6 Graceful Fallback
If API calls fail (no PAC auth, no Azure CLI token, network error, 401/403):
@@ -205,7 +217,7 @@ If API calls fail (no PAC auth, no Azure CLI token, network error, 401/403):
**Skip this step entirely if an API client already exists** (detected in Step 1.3). Read the existing client and import from it in subsequent steps.
-Create `src/shared/powerPagesApi.ts` — a centralized fetch wrapper shared by all table services. This file is created once and reused for every future integration. It includes anti-forgery token management (8-min TTL cache, fetched from `/_layout/tokenhtml`), header builder, response parsing, retry logic (exponential backoff, 403 token refresh, 401 session expiry), error code constants, OData URL builder, pagination helpers, lookup binding, and file column helpers.
+Create `src/shared/powerPagesApi.ts` — a centralized fetch wrapper shared by all table services. This file is created once and reused for every future integration. It includes anti-forgery token management (fetch-once-reuse, refresh on 403 error code `90040107`, fetched from `/_layout/tokenhtml`), header builder, response parsing, retry logic (exponential backoff, 403 token refresh, 401 session expiry), error code constants, OData URL builder, pagination helpers, lookup binding, and file column helpers.
Read the complete file template:
@@ -217,7 +229,7 @@ Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-core-client.md`
Create TypeScript type definitions for the target table. Place them following existing project conventions. If no convention exists, use `src/types/<tableName>.ts`. Define the raw OData entity interface, clean domain type, option set constants, create/update input types, and an entity-to-domain mapper function. Follow the lookup property rules for retrieval (`_value` GUID property in `$select`, Navigation Property in `$expand`) vs mutation (`@odata.bind` on Navigation Property).
-Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-service-patterns.md` — see "Entity Types (Step 4)" section.
+Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-service-patterns.md` — see "Entity Types (Step 4)" section. If the table has one-to-many relationships that will be expanded, also define interfaces for the related entity types and include them as properties on the parent entity interface — see "Related Entities ($expand)" section.
---
@@ -225,7 +237,7 @@ Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-service-patterns.md` — see
Create a service module with CRUD operations for the target table. Place it following project conventions. Default: `src/shared/services/<tableName>Service.ts`. Implement list (paginated with `$top` + `@odata.nextLink`), get by ID, create (POST with `Prefer: return=representation` + Location header fallback), update (PATCH with `If-Match: *`), delete, and optionally M:N sync, count, aggregation, and file/image column operations.
-Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-service-patterns.md` — see "Service Layer (Step 5)" section.
+Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-service-patterns.md` — see "Service Layer (Step 5)" section. If the table has lookup or one-to-many relationships, implement `$expand` using the `buildExpandClause` helper from the core API client — see "Related Entities ($expand)" section for expand patterns, nested expand, collection paging, and when to fetch related records separately.
---
@@ -458,6 +470,8 @@ Include this in the core API client file only if the site's code requires user-s
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.
+**Important for `$expand`:** When the service uses `$expand` to fetch related entities, each expanded related table also needs its own site settings AND table permissions with at least `read: true`. Without permissions on the related table, expanded properties return empty results or the query fails. Make sure to mention all expanded related tables when reminding the user about permissions setup.
+
---
## Service Factory Pattern (Optional)
@@ -540,16 +554,16 @@ Only create this if the site's UI shows/hides controls based on user roles.
10. **Formatted values** — Include `Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"` to get display names for lookups and option set labels.
11. **Escape OData strings** — Always use `escapeODataString()` for user-provided values in `$filter` to prevent injection.
12. **Safe `fetchAllPages` iteration limit** — Always cap the pagination loop (default 100 iterations) when following `@odata.nextLink` to prevent infinite loops.
-13. **Cache the anti-forgery token** — Use an 8-minute TTL cache to avoid fetching from `/_layout/tokenhtml` on every request.
-14. **Retry transient errors** — 429 and 5xx with exponential backoff. On 403, invalidate the cached anti-forgery token and retry. On 401, do **not** retry — the session has expired and the user must re-authenticate. Throw a clear "Session expired" error.
+13. **Cache the anti-forgery token** — Fetch the token once from `/_layout/tokenhtml` on first use and reuse it for all subsequent requests. Do NOT use a TTL-based cache. Only invalidate and re-fetch when a 403 response with the anti-forgery error code (`90040107`) indicates the token has expired.
+14. **Retry transient errors** — 429 and 5xx with exponential backoff. On 403, check the error code: if `90040107` (anti-forgery token invalid), invalidate the cached token and retry; otherwise it's a real permission denial — do **not** retry. On 401, do **not** retry — the session has expired and the user must re-authenticate. Throw a clear "Session expired" error.
15. **Type everything** — Raw OData entity interface + clean domain type + mapper function.
16. **Match existing patterns** — If the project has conventions for file locations, naming, or code style, follow them exactly.
17. **One table per invocation** — This agent handles a single table. For multiple tables, the caller invokes it separately for each.
18. **Upload vs download URLs** — File upload uses `/_api/table(id)/column` (PATCH, no `/$value`). File download uses `/_api/table(id)/column/$value` (GET). File delete uses `/_api/table(id)/column` (DELETE). Do not confuse the URL patterns.
-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.
+19. **File upload body is binary** — Send `ArrayBuffer` via `file.arrayBuffer()`, not JSON. Set `Content-Type` to `application/octet-stream` (NOT the file's MIME type — using e.g. `image/png` causes OData to route to the JSON deserializer, resulting in 400 "Stream was not readable"). Include `If-Match: *` and `x-ms-file-name` headers.
+20. **File download uses blob response** — Set `Accept: */*` (not `application/json`) AND `Content-Type: application/octet-stream` (required for OData to route to the binary file handler — without it, downloads return 404). 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 `table-permissions-architect` and `webapi-settings-architect` agents must be run to configure table permissions and site settings 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. If the service uses `$expand`, explicitly list each expanded related table that also needs permissions and site settings configured.
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.
@@ -558,6 +572,11 @@ Only create this if the site's UI shows/hides controls based on user roles.
28. **Web API error codes** — Use the error codes exported from the core API client (`WebApiErrorCode`) for specific error handling in the UI. The server returns distinct hex codes for each permission denial type (read `90040120`, write `90040102`, create `90040103`, delete `90040104`), anti-forgery failures (`90040107`), and resource not found (`9004010c`). Use `isPermissionError()` to show a "contact your administrator" message instead of generic errors.
29. **Column permissions** — Power Pages enforces field-level access control via column permission profiles. If a column permission profile blocks a field, the Web API will silently omit it from the response even if it appears in `$select`. This can cause unexpected `undefined` values in mapped domain types. Design mappers with sensible defaults for all fields.
30. **Verify column names against actual metadata** — Never trust manifest or user-provided column logical names without verification. Dataverse auto-generates logical names that can differ from display names (e.g., display name "Title" on a Posts table → `cr87b_posttitle`, not `cr87b_title`). Always query `EntityDefinitions/Attributes` in Step 2.5 to get the real schema. If the API is unavailable, fall back to manifest data but warn that names may need correction.
+31. **`$expand` limit** — Up to 15 `$expand` options per query. Each `$expand` creates a join that can affect performance. Always include `$select` within each `$expand` to limit returned columns.
+32. **Nested `$expand` paging behavior** — When any nested `$expand` is present in the query, `Prefer: odata.maxpagesize` applies to all expanded collections (not just the root entity set). `$orderby` and `$top` are NOT supported on collection-valued expansions when nested `$expand` is used anywhere in the query.
+33. **Collection-valued expand limits** — Without nested `$expand`, up to 5,000 related records are returned per collection. Always include `$top` or `$filter` to control response size. For large collections (hundreds+ records), fetch related records as a separate paginated query instead of using `$expand`.
+34. **N:N relationships cannot be nested-expanded** — Many-to-many navigation properties do not support nested `$expand`. The API returns error code `0x80060888`. Use FetchXml for nested N:N joins, or expand the N:N without nesting.
+35. **Expanded collection `@odata.nextLink`** — When nested `$expand` is used, each expanded collection-valued navigation property includes its own `@odata.nextLink` for paging through additional related records. Use `parseExpandedCollection` from the core API client to extract both items and nextLink.
---
@@ -578,6 +597,7 @@ Before confirming that work is done, verify every item below. Do not skip any ch
- [ ] Entity set name is from the API's `EntitySetName` (not guessed from pluralization)
- [ ] Column logical names in generated code match the actual Dataverse schema (not just manifest display names)
- [ ] Navigation property names are from the API's `ReferencingEntityNavigationPropertyName` (case-sensitive)
+- [ ] OneToMany relationship navigation properties are from the API's `ReferencedEntityNavigationPropertyName` (case-sensitive) — if expanding collection-valued properties
### Code Correctness
- [ ] All list/query operations include `$top` — no unbounded fetches
@@ -585,11 +605,13 @@ Before confirming that work is done, verify every item below. Do not skip any ch
- [ ] All queries include `$count=true` for total record count
- [ ] Lookups on POST/PATCH use `[email protected]` — not raw GUID writes to `_value` properties
- [ ] Navigation property names are case-sensitive and match the schema (typically PascalCase)
+- [ ] `$expand` on collection-valued navigation properties includes `$top` or `$filter` to limit response size
+- [ ] Related entity types defined for all expanded navigation properties (both single-valued and collection-valued)
- [ ] Update (PATCH) operations include the `If-Match: *` header
- [ ] Domain mappers provide sensible defaults for every field (guards against column permissions silently omitting values)
- [ ] OData string values in `$filter` use `escapeODataString()` to prevent injection
-- [ ] File upload sends `ArrayBuffer` body with correct `Content-Type`, `If-Match: *`, and `x-ms-file-name` headers
-- [ ] File download uses `Accept: */*` and returns `null` on 404 instead of throwing
+- [ ] File upload sends `ArrayBuffer` body with `Content-Type: application/octet-stream` (not file MIME type), `If-Match: *`, and `x-ms-file-name` headers
+- [ ] File download uses `Accept: */*`, `Content-Type: application/octet-stream`, and returns `null` on 404 instead of throwing
### Existing Code Updated
- [ ] Searched for all components referencing the target table's data (mock arrays, hardcoded data, inline `/_api/` fetch calls, TODO/FIXME comments)
diff --git a/plugins/power-pages/agents/webapi-settings-architect.md b/plugins/power-pages/agents/webapi-settings-architect.md
index 5690c57cc..1bd9ecfbc 100644
--- a/plugins/power-pages/agents/webapi-settings-architect.md
+++ b/plugins/power-pages/agents/webapi-settings-architect.md
@@ -31,6 +31,7 @@ You are a Web API site settings architect for Power Pages code sites. Your job i
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
@@ -57,6 +58,7 @@ Check that the site has been deployed at least once by looking for the `.powerpa
### 1.1 Locate the Project
Use `Glob` to find:
+
- `**/powerpages.config.json` — Power Pages config (identifies the project root)
- `**/.powerpages-site` — Deployment folder
@@ -64,11 +66,11 @@ Use `Glob` to find:
**If `.powerpages-site` folder does NOT exist:**
-Enter plan mode and state:
+Stop and tell the user:
-> "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."
+> "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 `/deploy-site` before Web API site settings can be configured."
-Exit plan mode and stop. Do NOT proceed with the remaining steps.
+Do NOT proceed with the remaining steps.
**If `.powerpages-site` exists:** Proceed to Step 2.
@@ -85,6 +87,7 @@ Read all Web API-related site settings in `.powerpages-site/site-settings/`:
Each site setting has this format:
**Enabled setting:**
+
```yaml
description: Enable Web API access for cra5b_product table
id: a1b2c3d4-2111-4111-8111-111111111111
@@ -92,7 +95,8 @@ name: Webapi/cra5b_product/enabled
value: true
```
-**Fields setting (lists specific columns — NEVER uses `*`):**
+**Fields setting (lists specific columns by default; use `*` only for aggregate OData scenarios):**
+
```yaml
description: Allowed fields for cra5b_product Web API access
id: a1b2c3d4-2112-4111-8111-111111111112
@@ -128,6 +132,7 @@ If no manifest exists, analyze the source code to infer which tables need Web AP
- **Component data bindings** — What data each component displays or modifies
Look for patterns like:
+
```text
/_api/<table_plural_name>
fetch.*/_api/
@@ -138,38 +143,45 @@ fetch.*/_api/
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:
+1. **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)
@@ -214,6 +226,7 @@ The script outputs JSON: `{ "status": <code>, "data": { "value": [...] } }`. Eac
**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 } }
```
@@ -223,6 +236,7 @@ Store the results as a lookup map for each table:
### 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
@@ -277,10 +291,12 @@ Lookup columns have **two attribute names** in OData, and the Power Pages Web AP
**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
```
@@ -333,11 +349,12 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJ
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: For normal CRUD/read scenarios, the `--value` for fields settings MUST use exact Dataverse LogicalNames (all lowercase), comma-separated, with NO spaces after commas. NEVER use SchemaName (PascalCase) or any other casing variant. Every column name must have been validated against Dataverse in Step 5. If the table has File or Image columns accessed via the Web API, OR the site uses aggregate OData queries (`$apply`, `aggregate`, grouped totals), use `*` instead — the `/$value` download endpoint internally does `SELECT *`, so an explicit column list causes 403.**
**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"
```
@@ -351,11 +368,13 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJ
### 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 |
@@ -365,10 +384,10 @@ Then include:
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
+4. **Security notes** — Confirm that wildcard `*` is only used for tables with File/Image columns or aggregate OData scenarios; all other tables use explicit column lists
+5. **Script invocations** — The exact `create-site-setting.js` commands for each setting (from section 6.1)
+6. **Any discovery steps skipped** due to auth errors
+7. **Dataverse validation status** — Whether column names were validated against Dataverse or only inferred from code/manifest
### 6.3 Enter Plan Mode & Exit
@@ -404,7 +423,7 @@ After creating all files, return a summary to the calling context:
- **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.
+- **Use `*` for tables with File/Image columns or aggregate OData scenarios**: If a table has **File** or **Image** columns that will be accessed via the Web API, the `Webapi/<table>/fields` setting **must use `*`** (wildcard). The `/$value` download endpoint internally performs `SELECT *`; an explicit column list causes `403 "Attribute * not enabled for Web Api"`. Also use `*` when the site relies on aggregate OData queries (`$apply`, `aggregate`, grouped totals). For all other tables, default to specific validated column logical names.
- **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/hooks/hooks.json b/plugins/power-pages/hooks/hooks.json
new file mode 100644
index 000000000..7084a1aaf
--- /dev/null
+++ b/plugins/power-pages/hooks/hooks.json
@@ -0,0 +1,18 @@
+{
+ "description": "Centralized Power Pages lifecycle hooks",
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Skill",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/run-skill-posttool-validation.js\"",
+ "timeout": 30,
+ "statusMessage": "Running Power Pages validator"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/power-pages/hooks/run-skill-posttool-validation.js b/plugins/power-pages/hooks/run-skill-posttool-validation.js
new file mode 100644
index 000000000..5bc5a8113
--- /dev/null
+++ b/plugins/power-pages/hooks/run-skill-posttool-validation.js
@@ -0,0 +1,48 @@
+#!/usr/bin/env node
+
+const path = require('path');
+const { spawnSync } = require('child_process');
+const {
+ getTrackedSkillFromToolInput,
+ getValidatorScript,
+} = require('../scripts/lib/powerpages-hook-utils');
+
+let inputData = '';
+
+process.stdin.on('data', (chunk) => {
+ inputData += chunk;
+});
+
+process.stdin.on('end', () => {
+ try {
+ const input = JSON.parse(inputData);
+ const skillName = getTrackedSkillFromToolInput(input.tool_input);
+ if (!skillName) {
+ process.exit(0);
+ }
+
+ const validatorScript = getValidatorScript(skillName);
+ if (!validatorScript) {
+ process.exit(0);
+ }
+
+ const validatorPath = path.join(__dirname, '..', validatorScript);
+ const result = spawnSync(process.execPath, [validatorPath], {
+ input: inputData,
+ encoding: 'utf8',
+ cwd: input.cwd || process.cwd(),
+ });
+
+ if (result.stdout) {
+ process.stdout.write(result.stdout);
+ }
+
+ if (result.stderr) {
+ process.stderr.write(result.stderr);
+ }
+
+ process.exit(result.status ?? 0);
+ } catch {
+ process.exit(0);
+ }
+});
diff --git a/plugins/power-pages/references/permissions-plan-data-format.md b/plugins/power-pages/references/permissions-plan-data-format.md
new file mode 100644
index 000000000..3aa01c3f4
--- /dev/null
+++ b/plugins/power-pages/references/permissions-plan-data-format.md
@@ -0,0 +1,135 @@
+# Permissions Plan Data Format
+
+Reference document for generating the HTML permissions plan file using `render-permissions-plan.js`. Covers the JSON data structure, role/permission/rationale formats, and rendering instructions.
+
+## Design Rationale Items
+
+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
+
+## Generating the HTML Plan File
+
+**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.
+
+### 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()`)
+
+### 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 - Read",
+ "displayName": "Product",
+ "table": "cra5b_product",
+ "scope": "Global",
+ "read": true,
+ "create": false,
+ "write": false,
+ "delete": false,
+ "append": true,
+ "appendto": false,
+ "roles": ["r1", "r2"],
+ "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.",
+ "append": "Orders reference products via a lookup column, requiring Append on the target table so records can be linked to it."
+ },
+ "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., "Referenced by orders via a lookup column — other records link to this table")
+ - `appendto` — Why appendto is needed (e.g., "This table has a lookup to Product Category set during create — this table links to other records")
+
+### 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: `&#x1F6E1;&#xFE0F;` (shield), `&#x1F517;` (link), `&#x1F464;` (user), `&#x1F512;` (lock).
+
+### 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.
+
+### Open in Browser
+
+Open the generated HTML file in the user's default browser.
diff --git a/plugins/power-pages/references/table-permission-analysis-guide.md b/plugins/power-pages/references/table-permission-analysis-guide.md
new file mode 100644
index 000000000..7ee8ffc1e
--- /dev/null
+++ b/plugins/power-pages/references/table-permission-analysis-guide.md
@@ -0,0 +1,153 @@
+# Table Permission Analysis Guide
+
+Reference document for systematically analyzing per-table privileges and performing cross-table validation when configuring Power Pages table permissions.
+
+## Per-Table Privilege Analysis Checklist
+
+For each table, work through the following checklist **in order**. For every decision, note the **specific code evidence** (file path, line pattern, or API pattern) that justifies it. Do NOT guess — if no evidence exists for a privilege, leave it `false`.
+
+### A. Determine Source — Why does this table need permissions?
+
+Classify the table into one or more categories:
+
+- **Direct API target** — Code makes `/_api/<entity_set>` calls to this table
+- **`$expand` related** — This table is fetched via `$expand` on another table's query
+- **Lookup target** — This table is referenced by a lookup column on another table (needs `append`)
+- **Data model only** — Table exists in manifest but no code references found (may not need permissions yet)
+
+Record the source files and patterns that reference this table.
+
+### B. Determine Web Role(s)
+
+Which web role(s) need access to this table?
+
+- Search for authentication checks near the API calls (e.g., `getCurrentContactId()`, `getPortalUser()`, role checks)
+- If the table is accessed without auth checks → likely needs Anonymous Users role
+- If the table is accessed behind auth/login → needs Authenticated Users role
+- If role-specific checks exist → map to the specific custom role
+
+**If the required role does not exist** in the discovered web roles, flag it as a new role to create. Record it so it can be included in the plan and created before table permissions. At minimum, every site needs `Authenticated Users` (`authenticatedusersrole: true`). If anonymous/public access is needed, also flag `Anonymous Users` (`anonymoususersrole: true`).
+
+### C. Determine Scope
+
+Evaluate the scope based on code patterns. Check **each scope option** and pick the most restrictive one that fits:
+
+| Scope | Code Pattern to Look For | When to Use |
+|-------|-------------------------|-------------|
+| **Self** (`756150004`) | Queries filter by current contact ID for contact table itself | Only for the contact record itself |
+| **Contact** (`756150001`) | `getCurrentContactId()`, `_contactid_value eq`, filter by current user | User's own records (orders, profiles) — **default choice** |
+| **Account** (`756150002`) | Account-based filters, shared team access patterns | Organizational shared access |
+| **Parent** (`756150003`) | Table is a child accessed via parent (e.g., order lines under orders), `$expand` with one-to-many | Child tables that inherit access from parent |
+| **Global** (`756150000`) | No user/contact filter, public browsing, anonymous access | **Last resort** — only for read-only public reference data |
+
+Search the service code for scope-relevant filter patterns: contact-scoped filters (`getCurrentContactId`, `_contactid_value`, `contactid`) and account-scoped filters (`_accountid_value`, `parentcustomerid`).
+
+**Scope guardrails (critical):**
+
+- Do **not** replace an existing or proposed **Parent** scope permission with **Contact** or **Account** scope unless you have **direct evidence on the child table itself**:
+ - the child table has its own direct lookup to contact/account,
+ - the corresponding Dataverse relationship exists for that child table, and
+ - the business rule truly grants access based on the child record's own owner/contact/account — not inherited parent access.
+- Do **not** assume Power Pages "flattens" a Parent→Contact or Parent→Account chain onto the child table unless Microsoft documentation explicitly states it or deterministic validation proves it.
+- Relationship schema names do **not** need to match across different entities. A parent table's contact relationship name and a child table's contact relationship name may legitimately differ. Never rewrite scope just because the names differ across entities.
+- For **Contact** scope, validate the relationship against the secured table itself. For **Parent** scope, validate only the child→parent `parentrelationship` plus the parent permission chain; do not compare unrelated relationship names across entities.
+
+### D. Determine Read
+
+Is `read: true` needed?
+
+- Search the service code for: GET requests to `/_api/<entity_set>`, list/get functions (`list<TableName>`, `get<TableName>`), `$select` patterns, `$expand` that references this table
+- If this table is only accessed via `$expand` from another table → still needs `read: true`
+- **Decision:** `true` if any read pattern found, `false` otherwise
+
+### E. Determine Create
+
+Is `create: true` needed?
+
+- Search the service code for: POST requests (`method: 'POST'`) to `/_api/<entity_set>`, create functions (`create<TableName>`)
+- **Decision:** `true` only if POST/create pattern found for this specific table, `false` otherwise
+
+### F. Determine Write
+
+Is `write: true` needed?
+
+- Search the service code for: PATCH requests (`method: 'PATCH'`) to `/_api/<entity_set>`, update functions (`update<TableName>`), file upload patterns (`uploadFileColumn`, `uploadFile`, `upload*Photo`, `upload*Image`, `upload*File`)
+- **Important:** File/image uploads use PATCH → require `write: true` even if no other field updates exist
+- **Decision:** `true` if PATCH/update/upload pattern found, `false` otherwise
+
+### G. Determine Delete
+
+Is `delete: true` needed?
+
+- Search the service code for: DELETE requests (`method: 'DELETE'`) to `/_api/<entity_set>`, delete functions (`delete<TableName>`)
+- **Decision:** `true` only if DELETE pattern found for this specific table, `false` otherwise
+
+### H. Determine Append
+
+Is `append: true` needed?
+
+- **Required when:** This table is the TARGET of a lookup column on another table that has create or write permissions — i.e., other records link TO this table
+- Search the service code for `@odata.bind` references to this table's entity set (e.g., `<entity_set>(`)
+- Also check the **reverse target map** from the relationship discovery step — does any other table with create/write have a lookup whose `Targets` include this table?
+- **Decision:** `true` if any other table with create/write has a lookup to this table, `false` otherwise
+- **If `true`:** Record which source table's lookup triggers this (needed for rationale)
+
+### I. Determine AppendTo
+
+Is `appendto: true` needed?
+
+- **Required when:** This table has lookup columns that are set during create or write operations — i.e., this table links TO other records
+- Search the service code for `@odata.bind` patterns in create/update functions for this table
+- Also check the **source map** from the relationship discovery for lookup columns on this table
+- **Decision:** `true` if this table sets lookup columns during create/write, `false` otherwise
+- **If `true`:** Record which lookup columns trigger this (needed for rationale)
+
+### J. Determine Parent Relationship (if Parent scope)
+
+If scope is Parent (`756150003`):
+
+- Identify the parent table and its permission (must be analyzed first)
+- Identify the Dataverse relationship name (from relationship discovery) — use `SchemaName` as `parentrelationship`
+
+### K. Record Decision Summary
+
+After completing all checks, record the final permission configuration for this table:
+
+```
+Table: <table_logical_name>
+Source: <Direct API target / $expand related / Lookup target>
+Web Role: <role name(s)>
+Scope: <scope name> (code evidence: <file:pattern>)
+read: <true/false> (evidence: <reason>)
+create: <true/false> (evidence: <reason>)
+write: <true/false> (evidence: <reason>)
+delete: <true/false> (evidence: <reason>)
+append: <true/false> (evidence: <reason>)
+appendto: <true/false> (evidence: <reason>)
+Parent: <parent permission + relationship if Parent scope>
+```
+
+---
+
+## Cross-Table Validation
+
+After all individual table analyses are complete, do a cross-table validation pass:
+
+1. **Append/AppendTo consistency:** For every table with `appendto: true` (source table with lookups), verify that each lookup target table has `append: true`. For every table with `append: true` (target table), verify that the source table that references it has `appendto: true`.
+2. **`$expand` coverage:** For every `$expand` usage found during code analysis, verify the expanded table has `read: true` in the inventory.
+3. **Parent chain completeness:** For every Parent scope permission, verify the parent permission exists in the inventory and will be created first.
+4. **No orphaned permissions:** If a table is only in the inventory because of `append` (lookup target) but has no direct code references, confirm that read-only + append is sufficient — it does not need create/write/delete.
+5. **Web role coverage:** Collect all web roles referenced across all table analyses. For each role, verify it exists in the discovered roles. If any required role does not exist, add it to a "roles to create" list that will be included in the plan and created before table permissions.
+6. **Role consolidation (critical):** Group all per-table permission entries by `(table, scope, CRUD flags, append, appendto, parent, parentRelationship)`. If two or more roles produce an **identical** permission tuple for the same table, merge them into a **single** permission with multiple `webRoleIds` instead of creating separate per-role permissions. For example, if both Anonymous Users and Authenticated Users need `read-only + Global scope` on the Product table, create one permission `Product - Read` assigned to both roles — not two permissions `Product - Anonymous Read` and `Product - Authenticated Read`. This prevents count inflation and matches how Power Pages actually enforces permissions (one permission record, many role associations).
+
+---
+
+## Scope Reference
+
+Available scopes:
+
+- `756150000` — **Global**: Access all records. **Avoid whenever possible** — grants unrestricted access. Only use for truly public, read-only reference data (e.g., product catalog for anonymous browsing).
+- `756150001` — **Contact**: Access records associated with the current user's contact. **Default and safest choice** for user-specific data (orders, profiles, addresses).
+- `756150002` — **Account**: Access records associated with the current user's parent account. Use when business logic requires shared access within an organization.
+- `756150003` — **Parent**: Access records through parent table permission relationship. Use for child tables (order items, line items) that inherit access from a parent table.
+- `756150004` — **Self**: Access only the user's own contact record and records directly linked to it.
diff --git a/plugins/power-pages/references/webapi-core-client.md b/plugins/power-pages/references/webapi-core-client.md
index c46c86782..02e9681be 100644
--- a/plugins/power-pages/references/webapi-core-client.md
+++ b/plugins/power-pages/references/webapi-core-client.md
@@ -12,18 +12,16 @@ Adapt imports and style to match the project's existing TypeScript conventions (
// ── Anti-Forgery Token ────────────────────────────────────────────────────────
// Power Pages Web API requires a __RequestVerificationToken header on every
-// mutating request. The token is fetched from /_layout/tokenhtml and cached.
+// mutating request. The token is fetched once from /_layout/tokenhtml and
+// reused for all subsequent requests. It is only re-fetched when a 403 response
+// with the anti-forgery error code (90040107) indicates the token has expired.
// No Authorization/Bearer header is needed — authenticated users get cookie-based
// session auth automatically.
-const TOKEN_TTL_MS = 8 * 60 * 1000; // 8 min cache
-
let cachedAntiForgeryToken: string | null = null;
-let cachedAntiForgeryTimestamp = 0;
const fetchAntiForgeryToken = async (): Promise<string> => {
- const now = Date.now();
- if (cachedAntiForgeryToken && now - cachedAntiForgeryTimestamp < TOKEN_TTL_MS) {
+ if (cachedAntiForgeryToken) {
return cachedAntiForgeryToken;
}
@@ -48,7 +46,6 @@ const fetchAntiForgeryToken = async (): Promise<string> => {
);
cachedAntiForgeryToken = token || '';
- cachedAntiForgeryTimestamp = now;
return cachedAntiForgeryToken;
} catch (error) {
console.warn('Failed to fetch anti-forgery token:', error);
@@ -56,6 +53,11 @@ const fetchAntiForgeryToken = async (): Promise<string> => {
}
};
+/** Invalidate the cached token so the next request re-fetches it. */
+const invalidateAntiForgeryToken = (): void => {
+ cachedAntiForgeryToken = null;
+};
+
// ── Header Builder ────────────────────────────────────────────────────────────
export const buildPowerPagesHeaders = async (
@@ -151,10 +153,14 @@ export async function powerPagesFetch<T>(
throw new Error('Session expired. Please sign in again.');
}
- // On 403, the anti-forgery token may have expired — refresh and retry
+ // On 403, check if it's an anti-forgery token error — only retry for that
if (response.status === 403 && attempt < MAX_RETRIES) {
- cachedAntiForgeryToken = null;
- continue;
+ const errorCode = await extractErrorCode(response.clone());
+ if (errorCode === WebApiErrorCode.AntiForgeryTokenInvalid) {
+ invalidateAntiForgeryToken();
+ continue;
+ }
+ // Not a token error — this is a real permission denial, don't retry
}
if (isTransientError(response.status) && attempt < MAX_RETRIES) {
@@ -196,10 +202,14 @@ export async function powerPagesFetchResponse(
throw new Error('Session expired. Please sign in again.');
}
- // On 403, the anti-forgery token may have expired — refresh and retry
+ // On 403, check if it's an anti-forgery token error — only retry for that
if (response.status === 403 && attempt < MAX_RETRIES) {
- cachedAntiForgeryToken = null;
- continue;
+ const errorCode = await extractErrorCode(response.clone());
+ if (errorCode === WebApiErrorCode.AntiForgeryTokenInvalid) {
+ invalidateAntiForgeryToken();
+ continue;
+ }
+ // Not a token error — this is a real permission denial, don't retry
}
if (isTransientError(response.status) && attempt < MAX_RETRIES) {
@@ -240,13 +250,28 @@ export const WebApiErrorCode = {
} as const;
/**
- * Parse the error code from a Web API error response.
+ * Extract the error code from a Web API Response object.
+ * Reads the JSON body: { error: { code: "90040120", message: "..." } }
+ * Returns the hex code string (e.g., '90040120') or undefined.
+ * Use response.clone() before passing if you need to read the body again.
+ */
+const extractErrorCode = async (response: Response): Promise<string | undefined> => {
+ try {
+ const payload = await response.json();
+ const code = payload?.error?.code;
+ return typeof code === 'string' ? code.toLowerCase() : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Parse the error code from a caught Error object.
* Returns the hex code string (e.g., '90040120') or undefined.
*/
export const parseErrorCode = (error: unknown): string | undefined => {
if (error && typeof error === 'object' && 'message' in error) {
const msg = (error as Error).message;
- // The error code appears in the JSON: { error: { code: "90040120", message: "..." } }
const match = msg.match(/[0-9a-f]{8}/i);
return match?.[0]?.toLowerCase();
}
@@ -304,6 +329,35 @@ export interface PaginatedResult<T> {
nextLink?: string;
}
+/**
+ * Response shape for expanded collection-valued navigation properties.
+ * Each expanded collection includes an @odata.nextLink for paging through
+ * additional related records when the query uses nested $expand.
+ */
+export interface ExpandedCollection<T> {
+ items: T[];
+ nextLink?: string;
+}
+
+/**
+ * Parse an expanded collection-valued navigation property from a raw OData entity.
+ * Extracts both the array of related records and the @odata.nextLink for paging.
+ *
+ * @param entity - The parent entity object from the OData response
+ * @param property - The navigation property name (e.g., 'cr4fc_order_lines')
+ * @returns The related records array and optional nextLink for further paging
+ */
+export const parseExpandedCollection = <T>(
+ entity: Record<string, unknown>,
+ property: string
+): ExpandedCollection<T> => {
+ const raw = entity[property];
+ return {
+ items: Array.isArray(raw) ? (raw as T[]) : [],
+ nextLink: entity[`${property}@odata.nextLink`] as string | undefined,
+ };
+};
+
// ── Formatted Value Helper ────────────────────────────────────────────────────
/**
@@ -366,6 +420,90 @@ export const bindLookup = (
}
};
+// ── Expand Builder ────────────────────────────────────────────────────────────
+
+/**
+ * Options for expanding a navigation property.
+ * Single-valued (lookup) navigation properties support: $select, $expand (nested).
+ * Collection-valued (one-to-many) navigation properties support: $select, $filter, $orderby, $top.
+ * Note: $orderby and $top are NOT supported when the query contains any nested $expand.
+ */
+export interface ExpandOption {
+ /** Navigation property name — must match exact Dataverse schema name (case-sensitive) */
+ property: string;
+ /** Columns to select from the related entity */
+ select?: string[];
+ /** Filter expression for collection-valued navigation properties */
+ filter?: string;
+ /** Order expression for collection-valued navigation properties (not supported with nested $expand) */
+ orderBy?: string;
+ /** Max records for collection-valued navigation properties (not supported with nested $expand) */
+ top?: number;
+ /** Nested expand options for single-valued navigation properties */
+ expand?: ExpandOption[];
+}
+
+/**
+ * Build an OData $expand clause from structured options.
+ * Handles nested expand for single-valued navigation properties and
+ * query options ($select, $filter, $orderby, $top) for collection-valued navigation properties.
+ *
+ * @example Single-valued with nested expand (lookup → lookup → lookup):
+ * buildExpandClause([{
+ * property: 'cr4fc_Contact',
+ * select: ['fullname'],
+ * expand: [{
+ * property: 'parentcustomerid_account',
+ * select: ['name'],
+ * expand: [{ property: 'createdby', select: ['fullname'] }]
+ * }]
+ * }])
+ * // → "cr4fc_Contact($select=fullname;$expand=parentcustomerid_account($select=name;$expand=createdby($select=fullname)))"
+ *
+ * @example Collection-valued with filter and ordering:
+ * buildExpandClause([{
+ * property: 'cr4fc_order_lines',
+ * select: ['cr4fc_quantity', 'cr4fc_unitprice'],
+ * filter: 'cr4fc_quantity gt 0',
+ * orderBy: 'cr4fc_unitprice desc',
+ * top: 10,
+ * }])
+ * // → "cr4fc_order_lines($select=cr4fc_quantity,cr4fc_unitprice;$filter=cr4fc_quantity gt 0;$orderby=cr4fc_unitprice desc;$top=10)"
+ *
+ * @example Multiple expands (single + collection):
+ * buildExpandClause([
+ * { property: 'cr4fc_Category', select: ['cr4fc_categoryid', 'cr4fc_name'] },
+ * { property: 'cr4fc_product_reviews', select: ['cr4fc_rating', 'cr4fc_comment'], top: 5 },
+ * ])
+ * // → "cr4fc_Category($select=cr4fc_categoryid,cr4fc_name),cr4fc_product_reviews($select=cr4fc_rating,cr4fc_comment;$top=5)"
+ */
+export const buildExpandClause = (options: ExpandOption[]): string =>
+ options.map(formatExpandOption).join(',');
+
+const formatExpandOption = (opt: ExpandOption): string => {
+ const parts: string[] = [];
+
+ if (opt.select?.length) {
+ parts.push(`$select=${opt.select.join(',')}`);
+ }
+ if (opt.filter) {
+ parts.push(`$filter=${opt.filter}`);
+ }
+ if (opt.orderBy) {
+ parts.push(`$orderby=${opt.orderBy}`);
+ }
+ if (opt.top !== undefined) {
+ parts.push(`$top=${opt.top}`);
+ }
+ if (opt.expand?.length) {
+ parts.push(`$expand=${buildExpandClause(opt.expand)}`);
+ }
+
+ return parts.length > 0
+ ? `${opt.property}(${parts.join(';')})`
+ : opt.property;
+};
+
// ── File Column Helpers ───────────────────────────────────────────────────────
/**
@@ -379,7 +517,7 @@ export const fetchFileColumnUrl = async (
): Promise<string | null> => {
const headers = await buildPowerPagesHeaders(undefined, {
accept: '*/*',
- contentType: null,
+ contentType: 'application/octet-stream',
prefer: null,
});
@@ -410,7 +548,7 @@ export const uploadFileColumn = async (
},
{
accept: 'application/json',
- contentType: file.type || 'application/octet-stream',
+ contentType: 'application/octet-stream',
prefer: null,
}
);
diff --git a/plugins/power-pages/references/webapi-service-patterns.md b/plugins/power-pages/references/webapi-service-patterns.md
index ad36b5d8c..fcd8ee04b 100644
--- a/plugins/power-pages/references/webapi-service-patterns.md
+++ b/plugins/power-pages/references/webapi-service-patterns.md
@@ -499,6 +499,283 @@ Only create these methods if the target table actually has File or Image columns
| Using `$select` on `/$value` URL | `400 Bad Request` | OData query options are not supported on `/$value` |
| Missing `x-ms-file-name` header | File saved without name/extension | Include `x-ms-file-name` header with filename |
| Using `Accept: application/json` for download | Empty or error response | Use `Accept: */*` for blob downloads |
+| Using file MIME type as upload `Content-Type` (e.g. `image/png`) | `400 "Stream was not readable"` — OData routes to JSON deserializer instead of binary handler | Always use `Content-Type: application/octet-stream` for uploads |
+| Missing `Content-Type: application/octet-stream` on download | `404` — OData pipeline can't route to binary file handler | Add `Content-Type: application/octet-stream` to download headers |
+| Explicit column list in `Webapi/<table>/fields` with file columns | `403 "Attribute * not enabled for Web Api"` on `/$value` download — the endpoint internally does `SELECT *` | Set field allowlist to `*` when the table has File or Image columns |
+
+---
+
+## Related Entities ($expand)
+
+Use `$expand` to join related tables in a single API call instead of making separate requests. Power Pages Web API supports expanding both single-valued (lookup/many-to-one) and collection-valued (one-to-many) navigation properties.
+
+### Rules and Limitations
+
+| Rule | Detail |
+|------|--------|
+| Max expand count | Up to **15** `$expand` options per query |
+| Single-valued expand | Supports `$select` and nested `$expand` (multi-level lookup traversal) |
+| Collection-valued expand | Supports `$select`, `$filter`, `$orderby`, `$top` |
+| Nested `$expand` paging impact | When **any** nested `$expand` exists in the query, `Prefer: odata.maxpagesize` applies to **all** expanded collections (not just the root entity set). `$orderby` and `$top` are **NOT** supported on collection-valued expansions in this case. |
+| N:N relationships | **Cannot** be nested-expanded. Use FetchXml for nested N:N joins. |
+| `$skip` | **Not supported** — use `@odata.nextLink` cursors |
+| Cached responses | Expanded collection-valued properties may return cached data. Use `If-None-Match: null` header to bypass browser caching. |
+
+### Expand Types
+
+**Single-valued (lookup / many-to-one):**
+```typescript
+// Expand a lookup to get related record details
+'$expand': 'cr4fc_Category($select=cr4fc_categoryid,cr4fc_name)'
+```
+
+**Collection-valued (one-to-many):**
+```typescript
+// Expand a one-to-many relationship with filter and ordering
+'$expand': 'cr4fc_order_lines($select=cr4fc_quantity,cr4fc_unitprice;$filter=cr4fc_quantity gt 0;$orderby=cr4fc_unitprice desc;$top=10)'
+```
+
+**Multiple expands (mix of single + collection):**
+```typescript
+'$expand': 'cr4fc_Category($select=cr4fc_categoryid,cr4fc_name),cr4fc_order_lines($select=cr4fc_quantity;$top=5)'
+```
+
+### Nested Expand of Single-Valued Navigation Properties
+
+Chain single-valued (lookup) navigation properties to traverse multiple levels in one request. Use semicolons to separate options within each level's parentheses:
+
+```typescript
+// Traverse: Order → Contact (lookup) → Account (lookup) → CreatedBy (lookup)
+const EXPAND_WITH_NESTED = buildExpandClause([{
+ property: 'cr4fc_CustomerContact',
+ select: ['fullname', 'emailaddress1'],
+ expand: [{
+ property: 'parentcustomerid_account',
+ select: ['name', 'telephone1'],
+ expand: [{
+ property: 'createdby',
+ select: ['fullname'],
+ }],
+ }],
+}]);
+
+// Produces: "cr4fc_CustomerContact($select=fullname,emailaddress1;$expand=parentcustomerid_account($select=name,telephone1;$expand=createdby($select=fullname)))"
+```
+
+The response returns nested objects:
+
+```json
+{
+ "cr4fc_orderid": "...",
+ "cr4fc_ordernumber": "ORD-001",
+ "cr4fc_CustomerContact": {
+ "fullname": "Jane Smith",
+ "emailaddress1": "[email protected]",
+ "contactid": "...",
+ "parentcustomerid_account": {
+ "name": "Contoso Ltd",
+ "telephone1": "555-0100",
+ "accountid": "...",
+ "createdby": {
+ "fullname": "System Administrator",
+ "systemuserid": "..."
+ }
+ }
+ }
+}
+```
+
+### Collection-Valued Navigation Property Expand
+
+Expand one-to-many relationships to retrieve child records inline. Always include `$top` or `$filter` to limit the response size — without limits, up to 5,000 related records can be returned per collection.
+
+```typescript
+import { buildExpandClause, type ExpandOption } from '../shared/powerPagesApi';
+
+// Expand order lines (one-to-many) with filter and limit
+const ORDER_EXPAND: ExpandOption[] = [
+ {
+ property: 'cr4fc_Category',
+ select: ['cr4fc_categoryid', 'cr4fc_name'],
+ },
+ {
+ property: 'cr4fc_order_lines',
+ select: ['cr4fc_orderlineid', 'cr4fc_productname', 'cr4fc_quantity', 'cr4fc_unitprice'],
+ filter: 'statecode eq 0',
+ orderBy: 'cr4fc_quantity desc',
+ top: 50,
+ },
+];
+
+const ORDER_EXPAND_CLAUSE = buildExpandClause(ORDER_EXPAND);
+```
+
+### Entity Types for Related Entities
+
+When a table has expanded relationships, define nested interfaces in the OData entity type:
+
+```typescript
+// Related entity interfaces
+export interface OrderLineEntity {
+ cr4fc_orderlineid: string;
+ cr4fc_productname?: string;
+ cr4fc_quantity?: number;
+ cr4fc_unitprice?: number;
+ [key: string]: unknown;
+}
+
+export interface CategoryEntity {
+ cr4fc_categoryid: string;
+ cr4fc_name?: string;
+ [key: string]: unknown;
+}
+
+// Parent entity with expanded navigation properties
+export interface OrderEntity {
+ cr4fc_orderid: string;
+ cr4fc_ordernumber?: string;
+ cr4fc_totalamount?: number;
+ _cr4fc_category_value?: string;
+ // Single-valued navigation property (lookup — returns object or null)
+ cr4fc_Category?: CategoryEntity | null;
+ // Collection-valued navigation property (one-to-many — returns array)
+ cr4fc_order_lines?: OrderLineEntity[];
+ createdon?: string;
+ modifiedon?: string;
+ [key: string]: unknown;
+}
+```
+
+**Key difference:** Single-valued expansions return an **object or null**. Collection-valued expansions return an **array** (empty if no related records).
+
+### Domain Types for Related Entities
+
+```typescript
+export interface OrderLine {
+ id: string;
+ productName: string;
+ quantity: number;
+ unitPrice: number;
+ lineTotal: number;
+}
+
+export interface Order {
+ id: string;
+ orderNumber: string;
+ totalAmount: number;
+ categoryId?: string;
+ categoryName: string;
+ // Expanded related records mapped to domain types
+ orderLines: OrderLine[];
+ createdAt: string;
+ updatedAt: string;
+}
+```
+
+### Mapper for Expanded Entities
+
+```typescript
+const mapOrderLineEntity = (entity: OrderLineEntity): OrderLine => ({
+ id: entity.cr4fc_orderlineid,
+ productName: entity.cr4fc_productname ?? '',
+ quantity: entity.cr4fc_quantity ?? 0,
+ unitPrice: entity.cr4fc_unitprice ?? 0,
+ lineTotal: (entity.cr4fc_quantity ?? 0) * (entity.cr4fc_unitprice ?? 0),
+});
+
+export const mapOrderEntity = (entity: OrderEntity): Order => ({
+ id: entity.cr4fc_orderid,
+ orderNumber: entity.cr4fc_ordernumber ?? '',
+ totalAmount: entity.cr4fc_totalamount ?? 0,
+ categoryId: entity._cr4fc_category_value,
+ categoryName: entity.cr4fc_Category?.cr4fc_name ?? getFormattedValue(entity, '_cr4fc_category_value') ?? 'Uncategorized',
+ orderLines: (entity.cr4fc_order_lines ?? []).map(mapOrderLineEntity),
+ createdAt: entity.createdon ?? new Date().toISOString(),
+ updatedAt: entity.modifiedon ?? entity.createdon ?? new Date().toISOString(),
+});
+```
+
+### Paging Expanded Collections
+
+When the query contains **any** nested `$expand`, the `Prefer: odata.maxpagesize` header applies to expanded collections too. Each expanded collection returns its own `@odata.nextLink` for fetching additional related records.
+
+Use `parseExpandedCollection` from the core API client to extract both the items and nextLink:
+
+```typescript
+import { parseExpandedCollection, powerPagesFetch } from '../shared/powerPagesApi';
+
+// After fetching an order with expanded order lines:
+const entity = await powerPagesFetch<OrderEntity>(url);
+if (entity) {
+ const { items: orderLines, nextLink } = parseExpandedCollection<OrderLineEntity>(
+ entity as Record<string, unknown>,
+ 'cr4fc_order_lines'
+ );
+
+ // Map the first page of order lines
+ const mapped = orderLines.map(mapOrderLineEntity);
+
+ // Fetch additional pages if needed
+ if (nextLink) {
+ const additionalLines = await fetchAllPages<OrderLineEntity>(nextLink);
+ mapped.push(...additionalLines.map(mapOrderLineEntity));
+ }
+}
+```
+
+**Without** nested `$expand`, up to 5,000 related records are returned inline (no paging on the expanded collection). The `@odata.nextLink` on the collection is a URL to the filtered collection itself, not a paged cursor.
+
+### Get Related Records Separately
+
+For large collections or when you need full paging control, fetch related records as a separate query instead of `$expand`:
+
+```typescript
+// Instead of expanding, query the related entity set directly with a filter
+export const listOrderLines = async (orderId: string, params?: ListParams): Promise<PaginatedResult<OrderLine>> => {
+ const pageSize = params?.pageSize ?? 20;
+
+ const url = params?.nextLink ?? buildODataUrl('cr4fc_orderlines', {
+ '$select': 'cr4fc_orderlineid,cr4fc_productname,cr4fc_quantity,cr4fc_unitprice',
+ '$filter': `_cr4fc_order_value eq ${orderId}`,
+ '$orderby': params?.orderBy ?? 'cr4fc_quantity desc',
+ '$count': 'true',
+ '$top': String(pageSize),
+ });
+
+ const response = await powerPagesFetch<ODataCollectionResponse<OrderLineEntity>>(url);
+
+ return {
+ items: (response?.value ?? []).map(mapOrderLineEntity),
+ totalCount: response?.['@odata.count'] ?? response?.value?.length ?? 0,
+ nextLink: response?.['@odata.nextLink'],
+ };
+};
+```
+
+Use this approach when:
+- The related collection can be large (hundreds+ records)
+- You need `$orderby`, `$top`, or full pagination control alongside nested `$expand`
+- The relationship is N:N (many-to-many), which cannot be nested-expanded
+
+### Site Settings for Related Entity Columns
+
+When expanding related entities, the `Webapi/<table>/fields` site setting on the **parent** table must include the lookup column's logical name (e.g., `cr4fc_categoryid`). The **related** table must also have its own `Webapi/<related_table>/enabled` and `Webapi/<related_table>/fields` settings configured with the columns being selected in the `$expand`.
+
+### Table Permissions for Related Entities
+
+When using `$expand` to fetch related entities, the related table **must have its own table permission** with at least `read: true` for the same web role. Power Pages enforces table permissions on every entity accessed in the query — including expanded navigation properties. Without a read permission on the related table, the `$expand` silently returns empty results or the entire query fails with a permission error.
+
+**Rules:**
+- **Single-valued expand (lookup):** The target table of the lookup needs `read: true` table permission for the requesting web role
+- **Collection-valued expand (one-to-many):** The child table needs `read: true` table permission for the requesting web role. Use **Parent scope** (`756150003`) with the one-to-many relationship name to restrict access to only the related child records of the parent
+- **Nested expand:** Every table in the expansion chain needs `read: true` table permissions
+
+**Example:** If `cr4fc_order` expands `cr4fc_Category` (lookup) and `cr4fc_order_lines` (one-to-many):
+- `cr4fc_order` — needs its own table permission (e.g., Contact scope, CRUD as needed)
+- `cr4fc_category` — needs `read: true` table permission (e.g., Global scope for reference data)
+- `cr4fc_orderline` — needs `read: true` table permission with **Parent scope** referencing the order permission via the `cr4fc_order_orderline` relationship
+
+**Important:** This is in addition to the site settings requirements above. Both `Webapi/<table>/enabled` + `Webapi/<table>/fields` AND table permissions must be configured for each expanded related table.
---
diff --git a/plugins/power-pages/scripts/clear-site-cache.js b/plugins/power-pages/scripts/clear-site-cache.js
new file mode 100644
index 000000000..df3fbfd8b
--- /dev/null
+++ b/plugins/power-pages/scripts/clear-site-cache.js
@@ -0,0 +1,122 @@
+#!/usr/bin/env node
+
+// Clears the runtime cache of an activated Power Pages site by restarting it
+// via the Power Platform admin API.
+//
+// Usage:
+// node clear-site-cache.js --projectRoot "<path>"
+//
+// Output (JSON to stdout):
+// { "success": true, "websiteUrl": "..." }
+// { "success": false, "error": "..." }
+
+const fs = require('fs');
+const path = require('path');
+const { execSync } = require('child_process');
+const { findPath, getPacAuthInfo, getAuthToken, makeRequest, CLOUD_TO_API } = require('./lib/validation-helpers');
+
+function output(obj) {
+ process.stdout.write(JSON.stringify(obj));
+ process.exit(obj.success ? 0 : 1);
+}
+
+// --- Parse --projectRoot argument ---
+const args = process.argv.slice(2);
+const rootIdx = args.indexOf('--projectRoot');
+const projectRoot = rootIdx !== -1 ? args[rootIdx + 1] : process.cwd();
+
+// --- Read siteName from powerpages.config.json ---
+const configPath = findPath(projectRoot, 'powerpages.config.json');
+if (!configPath) {
+ output({ success: false, error: 'powerpages.config.json not found' });
+}
+
+let siteName;
+try {
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
+ siteName = config.siteName;
+} catch {
+ output({ success: false, error: 'Failed to parse powerpages.config.json' });
+}
+if (!siteName) {
+ output({ success: false, error: 'siteName not found in powerpages.config.json' });
+}
+
+// --- Get PAC auth info ---
+const pacInfo = getPacAuthInfo();
+if (!pacInfo) {
+ output({ success: false, error: 'PAC CLI not authenticated' });
+}
+
+const ppApiBaseUrl = CLOUD_TO_API[pacInfo.cloud] || CLOUD_TO_API['Public'];
+
+// --- Get Power Platform API token ---
+const token = getAuthToken(ppApiBaseUrl);
+if (!token) {
+ output({ success: false, error: 'Failed to get Azure CLI access token. Ensure you are logged in with: az login' });
+}
+
+// --- Find the website and restart it to clear cache ---
+(async () => {
+ // Get websites for this environment
+ const listResult = await makeRequest({
+ url: `${ppApiBaseUrl}/powerpages/environments/${pacInfo.environmentId}/websites?api-version=2022-03-01-preview`,
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
+ timeout: 15000,
+ });
+
+ if (listResult.error || listResult.statusCode !== 200) {
+ output({ success: false, error: `Failed to list websites: ${listResult.error || `HTTP ${listResult.statusCode}`}` });
+ }
+
+ let websites;
+ try {
+ const parsed = JSON.parse(listResult.body);
+ websites = Array.isArray(parsed.value) ? parsed.value : [];
+ } catch {
+ output({ success: false, error: 'Failed to parse websites API response' });
+ }
+
+ // Match by websiteRecordId (from pac pages list) or by name
+ let websiteRecordId = null;
+ try {
+ const pacOutput = execSync('pac pages list', { encoding: 'utf8', timeout: 15000 });
+ const lines = pacOutput.split(/\r?\n/).filter((l) => l.trim());
+ for (const line of lines) {
+ if (line.includes('----') || line.toLowerCase().includes('website name')) continue;
+ if (line.toLowerCase().includes(siteName.toLowerCase())) {
+ const guidMatch = line.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);
+ if (guidMatch) websiteRecordId = guidMatch[0];
+ break;
+ }
+ }
+ } catch {}
+
+ const match = websites.find((w) => {
+ if (websiteRecordId && w.websiteRecordId && w.websiteRecordId.toLowerCase() === websiteRecordId.toLowerCase()) return true;
+ if (w.name && w.name.toLowerCase() === siteName.toLowerCase()) return true;
+ return false;
+ });
+
+ if (!match || !match.id) {
+ output({ success: false, error: `Website "${siteName}" not found in environment` });
+ }
+
+ // Restart the site to clear its runtime cache
+ const restartResult = await makeRequest({
+ url: `${ppApiBaseUrl}/powerpages/environments/${pacInfo.environmentId}/websites/${match.id}/restart?api-version=2022-03-01-preview`,
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
+ timeout: 30000,
+ });
+
+ if (restartResult.error) {
+ output({ success: false, error: `Restart request failed: ${restartResult.error}` });
+ }
+
+ if (restartResult.statusCode >= 200 && restartResult.statusCode < 300) {
+ output({ success: true, websiteUrl: match.websiteUrl || null });
+ } else {
+ output({ success: false, error: `Restart returned HTTP ${restartResult.statusCode}: ${restartResult.body}` });
+ }
+})();
diff --git a/plugins/power-pages/scripts/create-site-setting.js b/plugins/power-pages/scripts/create-site-setting.js
index 96f098453..3a130d11d 100644
--- a/plugins/power-pages/scripts/create-site-setting.js
+++ b/plugins/power-pages/scripts/create-site-setting.js
@@ -5,6 +5,7 @@
//
// Usage:
// node create-site-setting.js --projectRoot <path> --name <string> --value <string> --description <string> [--type <boolean|string>]
+// node create-site-setting.js --projectRoot <path> --name <string> --envVarSchema <string>
//
// Output (JSON to stdout):
// { "id": "<uuid>", "filePath": "<path>" }
@@ -14,6 +15,7 @@
const fs = require('fs');
const path = require('path');
const generateUuid = require('./generate-uuid');
+const { loadSiteSettings, SITE_SETTING_FILE_SUFFIX } = require('./lib/powerpages-config');
// --- CLI arg parsing (same pattern as update-skill-tracking.js) ---
@@ -29,20 +31,39 @@ const settingName = getArg('name');
const settingValue = getArg('value');
const description = getArg('description');
const valueType = getArg('type') || 'string';
+const envVarSchema = getArg('envVarSchema');
+const usesEnvironmentVariable = envVarSchema !== null;
// --- Validation ---
-if (!projectRoot || !settingName || settingValue === null || settingValue === undefined || !description) {
+if (!projectRoot || !settingName) {
console.error('Usage: node create-site-setting.js --projectRoot <path> --name <string> --value <string> --description <string> [--type <boolean|string>]');
+ console.error(' or: node create-site-setting.js --projectRoot <path> --name <string> --envVarSchema <string>');
process.exit(1);
}
-if (valueType !== 'boolean' && valueType !== 'string') {
+if (usesEnvironmentVariable && (settingValue !== null || description !== null)) {
+ console.error('Error: --envVarSchema cannot be combined with --value or --description.');
+ process.exit(1);
+}
+
+if (usesEnvironmentVariable && String(envVarSchema).trim() === '') {
+ console.error('Error: --envVarSchema must be a non-empty string.');
+ process.exit(1);
+}
+
+if (!usesEnvironmentVariable && (settingValue === null || settingValue === undefined || !description)) {
+ console.error('Usage: node create-site-setting.js --projectRoot <path> --name <string> --value <string> --description <string> [--type <boolean|string>]');
+ console.error(' or: node create-site-setting.js --projectRoot <path> --name <string> --envVarSchema <string>');
+ process.exit(1);
+}
+
+if (!usesEnvironmentVariable && 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') {
+if (!usesEnvironmentVariable && valueType === 'boolean' && settingValue !== 'true' && settingValue !== 'false') {
console.error(`Error: --value must be "true" or "false" when --type is "boolean", got "${settingValue}"`);
process.exit(1);
}
@@ -54,6 +75,14 @@ if (!fs.existsSync(siteSettingsDir)) {
process.exit(1);
}
+let existingSiteSettings;
+try {
+ existingSiteSettings = loadSiteSettings(siteSettingsDir);
+} catch (error) {
+ console.error(`Error: Failed to read existing site settings. ${error.message}`);
+ process.exit(1);
+}
+
// --- Helpers ---
function writeYaml(fields) {
@@ -64,18 +93,41 @@ function writeYaml(fields) {
// --- Create site setting ---
const uuid = generateUuid();
+const fileName = `${settingName.replace(/\//g, '-')}${SITE_SETTING_FILE_SUFFIX}`;
+
+const existingSettingByName = existingSiteSettings.find(
+ setting => typeof setting.name === 'string' && setting.name.toLowerCase() === settingName.toLowerCase()
+);
+if (existingSettingByName) {
+ console.error(`Error: A site setting named "${settingName}" already exists (ID: ${existingSettingByName.id}) in ${existingSettingByName.filePath}.`);
+ process.exit(1);
+}
+
+const existingSettingByFileName = existingSiteSettings.find(
+ setting => path.basename(setting.filePath).toLowerCase() === fileName.toLowerCase()
+);
+if (existingSettingByFileName) {
+ console.error(`Error: Site setting file "${fileName}" would collide with existing setting "${existingSettingByFileName.name}" in ${existingSettingByFileName.filePath}.`);
+ process.exit(1);
+}
-const fields = {
- description: description,
- id: uuid,
- name: settingName,
- value: valueType === 'boolean' ? (settingValue === 'true') : settingValue,
-};
+const fields = usesEnvironmentVariable
+ ? {
+ envvar_schema: envVarSchema,
+ id: uuid,
+ name: settingName,
+ source: 1,
+ }
+ : {
+ 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');
diff --git a/plugins/power-pages/scripts/create-table-permission.js b/plugins/power-pages/scripts/create-table-permission.js
index fbf2b09de..b205923fc 100644
--- a/plugins/power-pages/scripts/create-table-permission.js
+++ b/plugins/power-pages/scripts/create-table-permission.js
@@ -6,6 +6,7 @@
// Usage:
// node create-table-permission.js --projectRoot <path> --permissionName <string> --tableName <string>
// --webRoleIds <csv> --scope <string> [--read] [--create] [--write] [--delete] [--append] [--appendto]
+// [--contactRelationshipName <string>] [--accountRelationshipName <string>]
// [--parentPermissionId <uuid>] [--parentRelationshipName <string>]
//
// Scope accepts friendly names (Global, Contact, Account, Parent, Self) or numeric codes (756150000-756150004).
@@ -18,6 +19,7 @@
const fs = require('fs');
const path = require('path');
const generateUuid = require('./generate-uuid');
+const { loadTablePermissions, TABLE_PERMISSION_FILE_SUFFIX } = require('./lib/powerpages-config');
// --- CLI arg parsing ---
@@ -33,12 +35,14 @@ function hasFlag(name) {
}
const projectRoot = getArg('projectRoot');
-const permissionName = getArg('permissionName');
-const tableName = getArg('tableName');
+const permissionName = getArg('permissionName')?.trim() || null;
+const tableName = getArg('tableName')?.trim() || null;
const webRoleIdsRaw = getArg('webRoleIds');
-const scopeRaw = getArg('scope');
-const parentPermissionId = getArg('parentPermissionId');
-const parentRelationshipName = getArg('parentRelationshipName');
+const scopeRaw = getArg('scope')?.trim() || null;
+const contactRelationshipName = getArg('contactRelationshipName')?.trim() || null;
+const accountRelationshipName = getArg('accountRelationshipName')?.trim() || null;
+const parentPermissionId = getArg('parentPermissionId')?.trim() || null;
+const parentRelationshipName = getArg('parentRelationshipName')?.trim() || null;
// --- Constants ---
@@ -57,7 +61,7 @@ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12
// --- 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>]');
+ console.error('Usage: node create-table-permission.js --projectRoot <path> --permissionName <string> --tableName <string> --webRoleIds <csv> --scope <string> [--read] [--create] [--write] [--delete] [--append] [--appendto] [--contactRelationshipName <string>] [--accountRelationshipName <string>] [--parentPermissionId <uuid>] [--parentRelationshipName <string>]');
process.exit(1);
}
@@ -89,6 +93,35 @@ if (SCOPE_MAP[scopeLower] !== undefined) {
}
// Validate parent scope requirements
+if (scopeCode === 756150001) {
+ if (!contactRelationshipName) {
+ console.error(`Error: --contactRelationshipName is required when scope is Contact (756150001). Provide the lookup field from "${tableName}" to contact.`);
+ if (tableName.toLowerCase() === 'contact') {
+ console.error('For the contact table itself, use Self scope instead of Contact scope.');
+ }
+ process.exit(1);
+ }
+ if (tableName.toLowerCase() === 'contact') {
+ console.error('Error: Contact scope is not valid for the contact table itself. Use Self scope instead.');
+ process.exit(1);
+ }
+ if (accountRelationshipName || parentPermissionId || parentRelationshipName) {
+ console.error('Error: Contact scope only supports --contactRelationshipName. Remove account/parent relationship arguments.');
+ process.exit(1);
+ }
+}
+
+if (scopeCode === 756150002) {
+ if (!accountRelationshipName) {
+ console.error(`Error: --accountRelationshipName is required when scope is Account (756150002). Provide the lookup field from "${tableName}" to account.`);
+ process.exit(1);
+ }
+ if (contactRelationshipName || parentPermissionId || parentRelationshipName) {
+ console.error('Error: Account scope only supports --accountRelationshipName. Remove contact/parent relationship arguments.');
+ process.exit(1);
+ }
+}
+
if (scopeCode === 756150003) {
if (!parentPermissionId) {
console.error('Error: --parentPermissionId is required when scope is Parent (756150003)');
@@ -102,6 +135,16 @@ if (scopeCode === 756150003) {
console.error('Error: --parentRelationshipName is required when scope is Parent (756150003)');
process.exit(1);
}
+ if (contactRelationshipName || accountRelationshipName) {
+ console.error('Error: Parent scope does not support contact/account relationship arguments.');
+ process.exit(1);
+ }
+}
+
+if ((scopeCode === 756150000 || scopeCode === 756150004) &&
+ (contactRelationshipName || accountRelationshipName || parentPermissionId || parentRelationshipName)) {
+ console.error('Error: Global and Self scopes do not use relationship arguments.');
+ process.exit(1);
}
// Validate target directory
@@ -112,6 +155,40 @@ if (!fs.existsSync(tablePermissionsDir)) {
process.exit(1);
}
+let existingPermissions;
+try {
+ existingPermissions = loadTablePermissions(tablePermissionsDir);
+} catch (error) {
+ console.error(`Error: Failed to read existing table permissions. ${error.message}`);
+ process.exit(1);
+}
+
+const existingPermissionByName = existingPermissions.find(
+ permission => typeof permission.entityname === 'string' && permission.entityname.toLowerCase() === permissionName.toLowerCase()
+);
+if (existingPermissionByName) {
+ console.error(`Error: A table permission named "${permissionName}" already exists (ID: ${existingPermissionByName.id}) in ${existingPermissionByName.filePath}.`);
+ console.error('Use a unique permission name instead of overwriting an existing permission file.');
+ process.exit(1);
+}
+
+if (scopeCode === 756150003) {
+ const parentPermission = existingPermissions.find(permission => permission.id === parentPermissionId);
+ if (!parentPermission) {
+ console.error(`Error: Parent permission "${parentPermissionId}" was not found in ${tablePermissionsDir}.`);
+ process.exit(1);
+ }
+
+ const parentRoleIds = new Set(Array.isArray(parentPermission.adx_entitypermission_webrole)
+ ? parentPermission.adx_entitypermission_webrole.map(String)
+ : []);
+ const invalidRoleIds = webRoleIds.filter(roleId => !parentRoleIds.has(roleId));
+ if (invalidRoleIds.length > 0) {
+ console.error(`Error: Child permission roles must be a subset of the parent permission's roles. Invalid role IDs: ${invalidRoleIds.join(', ')}`);
+ process.exit(1);
+ }
+}
+
// --- Build YAML ---
const uuid = generateUuid();
@@ -129,7 +206,15 @@ fields['id'] = uuid;
if (scopeCode === 756150003) {
fields['parententitypermission'] = parentPermissionId;
- fields['parentrelationshipname'] = parentRelationshipName;
+ fields['parentrelationship'] = parentRelationshipName;
+}
+
+if (scopeCode === 756150001) {
+ fields['contactrelationship'] = contactRelationshipName;
+}
+
+if (scopeCode === 756150002) {
+ fields['accountrelationship'] = accountRelationshipName;
}
fields['read'] = hasFlag('read');
@@ -158,7 +243,7 @@ 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 fileName = `${permissionName.replace(/[\s-]+/g, '-')}${TABLE_PERMISSION_FILE_SUFFIX}`;
const filePath = path.join(tablePermissionsDir, fileName);
fs.writeFileSync(filePath, yamlContent, 'utf8');
diff --git a/plugins/power-pages/scripts/launch-playwright-mcp.js b/plugins/power-pages/scripts/launch-playwright-mcp.js
index b921e60ba..4c458c5f3 100644
--- a/plugins/power-pages/scripts/launch-playwright-mcp.js
+++ b/plugins/power-pages/scripts/launch-playwright-mcp.js
@@ -9,7 +9,7 @@ const { spawn } = require('child_process');
const { detectBrowser } = require('./lib/detect-browser');
const browser = detectBrowser();
-const child = spawn('npx', ['@playwright/mcp@latest', '--browser', browser], {
+const child = spawn('npx', ['@playwright/mcp@latest', '--browser', browser, '--window-size', '1024,768'], {
stdio: 'inherit',
shell: true,
});
diff --git a/plugins/power-pages/scripts/lib/powerpages-config.js b/plugins/power-pages/scripts/lib/powerpages-config.js
new file mode 100644
index 000000000..519b802b1
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/powerpages-config.js
@@ -0,0 +1,146 @@
+const fs = require('fs');
+const path = require('path');
+
+const TABLE_PERMISSION_FILE_SUFFIX = '.tablepermission.yml';
+const SITE_SETTING_FILE_SUFFIX = '.sitesetting.yml';
+const WEB_ROLE_FILE_SUFFIX = '.webrole.yml';
+
+function parseYamlScalar(value) {
+ const trimmed = value.trim();
+ if (trimmed === 'true') {
+ return true;
+ }
+ if (trimmed === 'false') {
+ return false;
+ }
+ if (trimmed === 'null') {
+ return null;
+ }
+ if (/^-?\d+$/.test(trimmed)) {
+ return Number(trimmed);
+ }
+ return trimmed;
+}
+
+function parseSimpleYaml(content, filePath) {
+ const parsed = { filePath };
+ let currentArrayKey = null;
+ const lines = content.split(/\r?\n/);
+
+ for (let index = 0; index < lines.length; index += 1) {
+ const rawLine = lines[index];
+ const line = rawLine.trim();
+ if (!line) {
+ continue;
+ }
+
+ if (line.startsWith('- ')) {
+ if (!currentArrayKey || !Array.isArray(parsed[currentArrayKey])) {
+ throw new Error(`Invalid YAML array entry in ${filePath}`);
+ }
+ parsed[currentArrayKey].push(parseYamlScalar(line.slice(2)));
+ continue;
+ }
+
+ const separatorIndex = line.indexOf(':');
+ if (separatorIndex === -1) {
+ throw new Error(`Invalid YAML line "${line}" in ${filePath}`);
+ }
+
+ const key = line.slice(0, separatorIndex).trim();
+ const value = line.slice(separatorIndex + 1).trim();
+
+ if (/^[>|][+-]?$/.test(value)) {
+ const blockLines = [];
+ currentArrayKey = null;
+
+ while (index + 1 < lines.length) {
+ const nextRawLine = lines[index + 1];
+ if (nextRawLine.trim() === '') {
+ blockLines.push('');
+ index += 1;
+ continue;
+ }
+
+ if (/^\s+/.test(nextRawLine)) {
+ blockLines.push(nextRawLine.replace(/^\s+/, ''));
+ index += 1;
+ continue;
+ }
+
+ break;
+ }
+
+ parsed[key] = blockLines.join('\n').trim();
+ continue;
+ }
+
+ if (value === '') {
+ parsed[key] = [];
+ currentArrayKey = key;
+ continue;
+ }
+
+ parsed[key] = parseYamlScalar(value);
+ currentArrayKey = null;
+ }
+
+ return parsed;
+}
+
+function loadYamlRecordsWithErrors(dirPath, suffix) {
+ const records = [];
+ const errors = [];
+
+ if (!dirPath || !fs.existsSync(dirPath)) {
+ return { records, errors };
+ }
+
+ for (const fileName of fs.readdirSync(dirPath).filter(name => name.endsWith(suffix))) {
+ const filePath = path.join(dirPath, fileName);
+ try {
+ records.push(parseSimpleYaml(fs.readFileSync(filePath, 'utf8'), filePath));
+ } catch (error) {
+ errors.push({ filePath, message: error.message });
+ }
+ }
+
+ return { records, errors };
+}
+
+function listYamlFiles(dirPath) {
+ if (!dirPath || !fs.existsSync(dirPath)) {
+ return [];
+ }
+
+ return fs.readdirSync(dirPath)
+ .filter(fileName => fileName.endsWith('.yml') || fileName.endsWith('.yaml'))
+ .map(fileName => path.join(dirPath, fileName));
+}
+
+function loadYamlRecords(dirPath, suffix) {
+ const { records, errors } = loadYamlRecordsWithErrors(dirPath, suffix);
+ if (errors.length > 0) {
+ throw new Error(errors[0].message);
+ }
+ return records;
+}
+
+function loadTablePermissions(tablePermissionsDir) {
+ return loadYamlRecords(tablePermissionsDir, TABLE_PERMISSION_FILE_SUFFIX);
+}
+
+function loadSiteSettings(siteSettingsDir) {
+ return loadYamlRecords(siteSettingsDir, SITE_SETTING_FILE_SUFFIX);
+}
+
+module.exports = {
+ TABLE_PERMISSION_FILE_SUFFIX,
+ SITE_SETTING_FILE_SUFFIX,
+ WEB_ROLE_FILE_SUFFIX,
+ parseSimpleYaml,
+ loadYamlRecordsWithErrors,
+ loadTablePermissions,
+ loadSiteSettings,
+ listYamlFiles,
+};
diff --git a/plugins/power-pages/scripts/lib/powerpages-hook-utils.js b/plugins/power-pages/scripts/lib/powerpages-hook-utils.js
new file mode 100644
index 000000000..1fc16c760
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/powerpages-hook-utils.js
@@ -0,0 +1,84 @@
+const TRACKED_SKILLS = {
+ 'activate-site': {
+ validatorScript: 'skills/activate-site/scripts/validate-activation.js',
+ },
+ 'add-sample-data': {},
+ 'add-seo': {
+ validatorScript: 'skills/add-seo/scripts/validate-seo.js',
+ },
+ 'audit-permissions': {
+ validatorScript: 'skills/audit-permissions/scripts/validate-audit.js',
+ },
+ 'create-site': {
+ validatorScript: 'skills/create-site/scripts/validate-site.js',
+ },
+ 'create-webroles': {
+ validatorScript: 'skills/create-webroles/scripts/validate-webroles.js',
+ },
+ 'integrate-webapi': {
+ validatorScript: 'skills/integrate-webapi/scripts/validate-webapi-integration.js',
+ },
+ 'setup-auth': {
+ validatorScript: 'skills/setup-auth/scripts/validate-auth.js',
+ },
+ 'setup-datamodel': {
+ validatorScript: 'skills/setup-datamodel/scripts/validate-datamodel.js',
+ },
+ 'test-site': {},
+};
+
+function detectTrackedSkill(value) {
+ if (typeof value !== 'string') {
+ return null;
+ }
+
+ const trimmed = value.trim();
+ if (TRACKED_SKILLS[trimmed]) {
+ return trimmed;
+ }
+
+ // Strip leading slash and optional plugin prefix: /create-site, /power-pages:create-site
+ const normalized = trimmed.replace(/^\/?(?:power-pages:)?/, '').toLowerCase();
+ if (TRACKED_SKILLS[normalized]) {
+ return normalized;
+ }
+
+ // Fall back to searching for power-pages:<skill> anywhere in the string
+ const commandMatch = trimmed.match(/power-pages:([a-z0-9-]+)/i);
+ if (!commandMatch) {
+ return null;
+ }
+
+ const skillName = commandMatch[1].toLowerCase();
+ return TRACKED_SKILLS[skillName] ? skillName : null;
+}
+
+function getTrackedSkillFromToolInput(toolInput) {
+ if (!toolInput || typeof toolInput !== 'object') {
+ return null;
+ }
+
+ for (const field of ['skill', 'skill_name', 'skillName', 'name', 'commandName', 'command']) {
+ const skillName = detectTrackedSkill(toolInput[field]);
+ if (skillName) {
+ return skillName;
+ }
+ }
+
+ try {
+ return detectTrackedSkill(JSON.stringify(toolInput));
+ } catch {
+ return null;
+ }
+}
+
+function getValidatorScript(skillName) {
+ return TRACKED_SKILLS[skillName]?.validatorScript ?? null;
+}
+
+module.exports = {
+ TRACKED_SKILLS,
+ detectTrackedSkill,
+ getTrackedSkillFromToolInput,
+ getValidatorScript,
+};
diff --git a/plugins/power-pages/scripts/lib/powerpages-schema-validator.js b/plugins/power-pages/scripts/lib/powerpages-schema-validator.js
new file mode 100644
index 000000000..846a02580
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/powerpages-schema-validator.js
@@ -0,0 +1,28 @@
+const { validateTablePermissionsWithOptions } = require('./table-permissions-validator');
+const { validateSiteSettings } = require('./site-settings-validator');
+const { validateWebRoles } = require('./web-roles-validator');
+const { summarize } = require('./powerpages-validation-utils');
+
+function validatePowerPagesSchema(projectRoot, options = {}) {
+ const tablePermissions = validateTablePermissionsWithOptions(projectRoot, options);
+ const siteSettings = validateSiteSettings(projectRoot);
+ const webRoles = validateWebRoles(projectRoot);
+ const findings = [
+ ...tablePermissions.findings,
+ ...siteSettings.findings,
+ ...webRoles.findings,
+ ];
+
+ return {
+ projectRoot,
+ tablePermissions,
+ siteSettings,
+ webRoles,
+ findings,
+ summary: summarize(findings),
+ };
+}
+
+module.exports = {
+ validatePowerPagesSchema,
+};
diff --git a/plugins/power-pages/scripts/lib/powerpages-validation-utils.js b/plugins/power-pages/scripts/lib/powerpages-validation-utils.js
new file mode 100644
index 000000000..be53e84cd
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/powerpages-validation-utils.js
@@ -0,0 +1,29 @@
+function addFinding(findings, severity, message, details = {}) {
+ findings.push({ severity, message, ...details });
+}
+
+function findUnexpectedKeys(record, allowedKeys) {
+ return Object.keys(record)
+ .filter(key => key !== 'filePath' && !allowedKeys.has(key))
+ .sort();
+}
+
+function findMissingKeys(record, requiredKeys) {
+ return [...requiredKeys]
+ .filter(key => record[key] === undefined)
+ .sort();
+}
+
+function summarize(findings) {
+ return findings.reduce((summary, finding) => {
+ summary[finding.severity] += 1;
+ return summary;
+ }, { error: 0, warning: 0, info: 0 });
+}
+
+module.exports = {
+ addFinding,
+ findUnexpectedKeys,
+ findMissingKeys,
+ summarize,
+};
diff --git a/plugins/power-pages/scripts/lib/site-settings-validator.js b/plugins/power-pages/scripts/lib/site-settings-validator.js
new file mode 100644
index 000000000..1e976867c
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/site-settings-validator.js
@@ -0,0 +1,119 @@
+const path = require('path');
+const { SITE_SETTING_FILE_SUFFIX, loadYamlRecordsWithErrors, listYamlFiles } = require('./powerpages-config');
+const { addFinding, findUnexpectedKeys, findMissingKeys, summarize } = require('./powerpages-validation-utils');
+
+const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+const SITE_SETTING_ALLOWED_KEYS = new Set([
+ 'description',
+ 'envvar_schema',
+ 'id',
+ 'name',
+ 'source',
+ 'value',
+]);
+
+const SITE_SETTING_REQUIRED_KEYS = new Set([
+ 'id',
+ 'name',
+]);
+
+function validateSiteSettings(projectRoot) {
+ const findings = [];
+ const siteSettingsDir = path.join(projectRoot, '.powerpages-site', 'site-settings');
+
+ for (const filePath of listYamlFiles(siteSettingsDir)) {
+ const fileName = path.basename(filePath);
+ if (!fileName.endsWith(SITE_SETTING_FILE_SUFFIX)) {
+ addFinding(findings, 'error', `Site setting file does not follow naming convention "*${SITE_SETTING_FILE_SUFFIX}".`, {
+ filePath,
+ fileName,
+ });
+ }
+ }
+
+ const { records: siteSettings, errors } = loadYamlRecordsWithErrors(siteSettingsDir, SITE_SETTING_FILE_SUFFIX);
+ for (const error of errors) {
+ addFinding(findings, 'error', `Failed to parse site setting YAML: ${error.message}`, {
+ filePath: error.filePath,
+ fileName: path.basename(error.filePath),
+ });
+ }
+
+ for (const setting of siteSettings) {
+ const fileName = path.basename(setting.filePath);
+ const unexpectedKeys = findUnexpectedKeys(setting, SITE_SETTING_ALLOWED_KEYS);
+ if (unexpectedKeys.length > 0) {
+ addFinding(findings, 'error', `Site setting contains unexpected schema keys: ${unexpectedKeys.join(', ')}.`, {
+ filePath: setting.filePath,
+ fileName,
+ });
+ }
+
+ const missingKeys = findMissingKeys(setting, SITE_SETTING_REQUIRED_KEYS);
+ if (missingKeys.length > 0) {
+ addFinding(findings, 'error', `Site setting is missing required schema keys: ${missingKeys.join(', ')}.`, {
+ filePath: setting.filePath,
+ fileName,
+ });
+ }
+
+ if (!UUID_REGEX.test(String(setting.id || ''))) {
+ addFinding(findings, 'error', 'Site setting has an invalid "id" UUID.', {
+ filePath: setting.filePath,
+ fileName,
+ });
+ }
+
+ if (!setting.name || String(setting.name).trim() === '') {
+ addFinding(findings, 'error', 'Site setting has an empty "name" value.', {
+ filePath: setting.filePath,
+ fileName,
+ });
+ }
+
+ const hasEnvironmentVariableSchema = Object.prototype.hasOwnProperty.call(setting, 'envvar_schema');
+ const hasSource = Object.prototype.hasOwnProperty.call(setting, 'source');
+ const hasValue = Object.prototype.hasOwnProperty.call(setting, 'value');
+
+ if (hasEnvironmentVariableSchema) {
+ if (String(setting.envvar_schema || '').trim() === '') {
+ addFinding(findings, 'error', 'Site setting has an empty "envvar_schema" value.', {
+ filePath: setting.filePath,
+ fileName,
+ });
+ }
+
+ if (!hasSource || setting.source !== 1) {
+ addFinding(findings, 'error', 'Environment-variable-backed site setting must set "source" to 1.', {
+ filePath: setting.filePath,
+ fileName,
+ });
+ }
+
+ if (hasValue) {
+ addFinding(findings, 'error', 'Environment-variable-backed site setting must not define "value".', {
+ filePath: setting.filePath,
+ fileName,
+ });
+ }
+ }
+
+ if (hasSource && setting.source === 1 && !hasEnvironmentVariableSchema) {
+ addFinding(findings, 'error', 'Site setting with "source" set to 1 must also define "envvar_schema".', {
+ filePath: setting.filePath,
+ fileName,
+ });
+ }
+ }
+
+ return {
+ projectRoot,
+ findings,
+ summary: summarize(findings),
+ };
+}
+
+module.exports = {
+ validateSiteSettings,
+};
diff --git a/plugins/power-pages/scripts/lib/table-permissions-validator.js b/plugins/power-pages/scripts/lib/table-permissions-validator.js
new file mode 100644
index 000000000..f38f985de
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/table-permissions-validator.js
@@ -0,0 +1,328 @@
+const path = require('path');
+const { TABLE_PERMISSION_FILE_SUFFIX, loadYamlRecordsWithErrors, listYamlFiles } = require('./powerpages-config');
+const { addFinding, findUnexpectedKeys, findMissingKeys, summarize } = require('./powerpages-validation-utils');
+
+const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+const BOOLEAN_FIELDS = ['append', 'appendto', 'create', 'delete', 'read', 'write'];
+
+const SCOPE = {
+ GLOBAL: 756150000,
+ CONTACT: 756150001,
+ ACCOUNT: 756150002,
+ PARENT: 756150003,
+ SELF: 756150004,
+};
+
+const VALID_SCOPES = new Set(Object.values(SCOPE));
+
+const TABLE_PERMISSION_ALLOWED_KEYS = new Set([
+ 'adx_entitypermission_webrole',
+ 'accountrelationship',
+ 'append',
+ 'appendto',
+ 'contactrelationship',
+ 'create',
+ 'delete',
+ 'entitylogicalname',
+ 'entityname',
+ 'id',
+ 'parententitypermission',
+ 'parentrelationship',
+ 'read',
+ 'scope',
+ 'write',
+]);
+
+const TABLE_PERMISSION_REQUIRED_KEYS = new Set([
+ 'adx_entitypermission_webrole',
+ 'append',
+ 'appendto',
+ 'create',
+ 'delete',
+ 'entitylogicalname',
+ 'entityname',
+ 'id',
+ 'read',
+ 'scope',
+ 'write',
+]);
+
+function validateTablePermissions(projectRoot, options = {}) {
+ return validateTablePermissionsWithOptions(projectRoot, options);
+}
+
+function validateTablePermissionsWithOptions(projectRoot, options = {}) {
+ const findings = [];
+ const tablePermissionsDir = path.join(projectRoot, '.powerpages-site', 'table-permissions');
+
+ for (const filePath of listYamlFiles(tablePermissionsDir)) {
+ const fileName = path.basename(filePath);
+ if (!fileName.endsWith(TABLE_PERMISSION_FILE_SUFFIX)) {
+ addFinding(findings, 'error', `Table permission file does not follow naming convention "*${TABLE_PERMISSION_FILE_SUFFIX}".`, {
+ filePath,
+ fileName,
+ });
+ }
+ }
+
+ const { records: permissions, errors } = loadYamlRecordsWithErrors(tablePermissionsDir, TABLE_PERMISSION_FILE_SUFFIX);
+ for (const error of errors) {
+ addFinding(findings, 'error', `Failed to parse table permission YAML: ${error.message}`, {
+ filePath: error.filePath,
+ fileName: path.basename(error.filePath),
+ });
+ }
+
+ const permissionsById = new Map();
+
+ for (const permission of permissions) {
+ if (permission.id) {
+ permissionsById.set(String(permission.id), permission);
+ }
+
+ const fileName = path.basename(permission.filePath);
+ const entityName = typeof permission.entitylogicalname === 'string' ? permission.entitylogicalname.toLowerCase() : '';
+ const scope = permission.scope;
+
+ const unexpectedKeys = findUnexpectedKeys(permission, TABLE_PERMISSION_ALLOWED_KEYS);
+ if (unexpectedKeys.length > 0) {
+ addFinding(findings, 'error', `Table permission contains unexpected schema keys: ${unexpectedKeys.join(', ')}.`, {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+
+ const missingKeys = findMissingKeys(permission, TABLE_PERMISSION_REQUIRED_KEYS);
+ if (missingKeys.length > 0) {
+ addFinding(findings, 'error', `Table permission is missing required schema keys: ${missingKeys.join(', ')}.`, {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+
+ if (!permission.entityname || !entityName || scope === undefined || scope === null) {
+ addFinding(findings, 'error', 'Table permission has empty values for entityname, entitylogicalname, or scope.', {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+
+ if (!UUID_REGEX.test(String(permission.id || ''))) {
+ addFinding(findings, 'error', 'Table permission has an invalid "id" UUID.', {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+
+ if (!VALID_SCOPES.has(scope)) {
+ addFinding(findings, 'error', `Table permission has an invalid "scope" value: ${scope}.`, {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+
+ for (const fieldName of BOOLEAN_FIELDS) {
+ if (typeof permission[fieldName] !== 'boolean') {
+ addFinding(findings, 'error', `Table permission field "${fieldName}" must be a boolean.`, {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+ }
+
+ if (!Array.isArray(permission.adx_entitypermission_webrole) || permission.adx_entitypermission_webrole.length === 0) {
+ addFinding(findings, 'warning', 'Table permission has no associated web roles.', {
+ filePath: permission.filePath,
+ fileName,
+ permissionName: permission.entityname || null,
+ });
+ } else {
+ const invalidRoleIds = permission.adx_entitypermission_webrole.filter(roleId => !UUID_REGEX.test(String(roleId)));
+ if (invalidRoleIds.length > 0) {
+ addFinding(findings, 'error', `Table permission has invalid web role UUIDs: ${invalidRoleIds.join(', ')}.`, {
+ filePath: permission.filePath,
+ fileName,
+ permissionName: permission.entityname || null,
+ });
+ }
+ }
+
+ if (permission.parententitypermission && !UUID_REGEX.test(String(permission.parententitypermission))) {
+ addFinding(findings, 'error', 'Table permission has an invalid "parententitypermission" UUID.', {
+ filePath: permission.filePath,
+ fileName,
+ permissionName: permission.entityname || null,
+ });
+ }
+
+ if (scope === SCOPE.CONTACT) {
+ if (!permission.contactrelationship) {
+ addFinding(findings, 'error', 'Contact-scope table permission is missing "contactrelationship".', {
+ filePath: permission.filePath,
+ fileName,
+ permissionName: permission.entityname || null,
+ });
+ }
+ if (entityName === 'contact') {
+ addFinding(findings, 'error', 'The contact table should use Self scope instead of Contact scope.', {
+ filePath: permission.filePath,
+ fileName,
+ permissionName: permission.entityname || null,
+ });
+ }
+ } else if (permission.contactrelationship) {
+ addFinding(findings, 'warning', 'Table permission includes "contactrelationship" but is not using Contact scope.', {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+
+ if (scope === SCOPE.ACCOUNT) {
+ if (!permission.accountrelationship) {
+ addFinding(findings, 'error', 'Account-scope table permission is missing "accountrelationship".', {
+ filePath: permission.filePath,
+ fileName,
+ permissionName: permission.entityname || null,
+ });
+ }
+ } else if (permission.accountrelationship) {
+ addFinding(findings, 'warning', 'Table permission includes "accountrelationship" but is not using Account scope.', {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+
+ if (scope === SCOPE.PARENT) {
+ if (!permission.parententitypermission) {
+ addFinding(findings, 'error', 'Parent-scope table permission is missing "parententitypermission".', {
+ filePath: permission.filePath,
+ fileName,
+ permissionName: permission.entityname || null,
+ });
+ }
+ if (!permission.parentrelationship) {
+ addFinding(findings, 'error', 'Parent-scope table permission is missing "parentrelationship".', {
+ filePath: permission.filePath,
+ fileName,
+ permissionName: permission.entityname || null,
+ });
+ }
+ } else if (permission.parententitypermission || permission.parentrelationship) {
+ addFinding(findings, 'warning', 'Table permission includes parent-scope fields but is not using Parent scope.', {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+ }
+
+ for (const permission of permissions) {
+ if (permission.scope !== SCOPE.PARENT || !permission.parententitypermission) {
+ continue;
+ }
+
+ const parentPermission = permissionsById.get(String(permission.parententitypermission));
+ if (!parentPermission) {
+ addFinding(findings, 'error', `Parent permission "${permission.parententitypermission}" was not found for this child permission.`, {
+ filePath: permission.filePath,
+ fileName: path.basename(permission.filePath),
+ permissionName: permission.entityname || null,
+ });
+ continue;
+ }
+
+ const childRoles = new Set((permission.adx_entitypermission_webrole || []).map(String));
+ const parentRoles = new Set((parentPermission.adx_entitypermission_webrole || []).map(String));
+ const invalidRoles = [...childRoles].filter(roleId => !parentRoles.has(roleId));
+ if (invalidRoles.length > 0) {
+ addFinding(findings, 'error', 'Child permission roles are not a subset of the parent permission roles.', {
+ filePath: permission.filePath,
+ fileName: path.basename(permission.filePath),
+ permissionName: permission.entityname || null,
+ invalidRoleIds: invalidRoles,
+ });
+ }
+ }
+
+ if (typeof options.resolveRelationships === 'function') {
+ const relationshipCache = new Map();
+
+ function getRelationships(entityLogicalName) {
+ const key = String(entityLogicalName || '').toLowerCase();
+ if (!relationshipCache.has(key)) {
+ relationshipCache.set(key, options.resolveRelationships(key) || []);
+ }
+ return relationshipCache.get(key);
+ }
+
+ for (const permission of permissions) {
+ const fileName = path.basename(permission.filePath);
+ const entityLogicalName = String(permission.entitylogicalname || '').toLowerCase();
+ if (!entityLogicalName) {
+ continue;
+ }
+
+ try {
+ const relationships = getRelationships(entityLogicalName);
+
+ if (permission.scope === SCOPE.CONTACT && permission.contactrelationship) {
+ const match = relationships.some(relationship =>
+ String(relationship.schemaName || '').toLowerCase() === String(permission.contactrelationship).toLowerCase()
+ && String(relationship.referencedEntity || '').toLowerCase() === 'contact'
+ );
+ if (!match) {
+ addFinding(findings, 'error', `Contact relationship "${permission.contactrelationship}" was not found in Dataverse for table "${entityLogicalName}".`, {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+ }
+
+ if (permission.scope === SCOPE.ACCOUNT && permission.accountrelationship) {
+ const match = relationships.some(relationship =>
+ String(relationship.schemaName || '').toLowerCase() === String(permission.accountrelationship).toLowerCase()
+ && String(relationship.referencedEntity || '').toLowerCase() === 'account'
+ );
+ if (!match) {
+ addFinding(findings, 'error', `Account relationship "${permission.accountrelationship}" was not found in Dataverse for table "${entityLogicalName}".`, {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+ }
+
+ if (permission.scope === SCOPE.PARENT && permission.parentrelationship && permission.parententitypermission) {
+ const parentPermission = permissionsById.get(String(permission.parententitypermission));
+ const expectedParentEntity = String(parentPermission?.entitylogicalname || '').toLowerCase();
+ if (expectedParentEntity) {
+ const match = relationships.some(relationship =>
+ String(relationship.schemaName || '').toLowerCase() === String(permission.parentrelationship).toLowerCase()
+ && String(relationship.referencedEntity || '').toLowerCase() === expectedParentEntity
+ );
+ if (!match) {
+ addFinding(findings, 'error', `Parent relationship "${permission.parentrelationship}" was not found in Dataverse for table "${entityLogicalName}".`, {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+ }
+ }
+ } catch (error) {
+ addFinding(findings, 'error', `Dataverse relationship validation failed for table "${entityLogicalName}": ${error.message}`, {
+ filePath: permission.filePath,
+ fileName,
+ });
+ }
+ }
+ }
+
+ return {
+ projectRoot,
+ findings,
+ summary: summarize(findings),
+ };
+}
+
+module.exports = {
+ validateTablePermissions,
+ validateTablePermissionsWithOptions,
+};
diff --git a/plugins/power-pages/scripts/lib/validation-helpers.js b/plugins/power-pages/scripts/lib/validation-helpers.js
index a4501b327..eff59f614 100644
--- a/plugins/power-pages/scripts/lib/validation-helpers.js
+++ b/plugins/power-pages/scripts/lib/validation-helpers.js
@@ -61,8 +61,22 @@ function findPath(dir, target) {
* @returns {string|null} Project root path, or null
*/
function findProjectRoot(dir) {
- const configPath = findPath(dir, 'powerpages.config.json');
- return configPath ? path.dirname(configPath) : null;
+ let current = path.resolve(dir);
+ while (true) {
+ const configPath = path.join(current, 'powerpages.config.json');
+ if (fs.existsSync(configPath)) {
+ return current;
+ }
+
+ const parent = path.dirname(current);
+ if (parent === current) {
+ break;
+ }
+ current = parent;
+ }
+
+ const fallbackConfigPath = findPath(dir, 'powerpages.config.json');
+ return fallbackConfigPath ? path.dirname(fallbackConfigPath) : null;
}
/**
diff --git a/plugins/power-pages/scripts/lib/web-roles-validator.js b/plugins/power-pages/scripts/lib/web-roles-validator.js
new file mode 100644
index 000000000..a38235433
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/web-roles-validator.js
@@ -0,0 +1,135 @@
+const fs = require('fs');
+const path = require('path');
+const { WEB_ROLE_FILE_SUFFIX, listYamlFiles } = require('./powerpages-config');
+const { addFinding, findUnexpectedKeys, findMissingKeys, summarize } = require('./powerpages-validation-utils');
+
+const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+const WEB_ROLE_ALLOWED_KEYS = new Set([
+ 'anonymoususersrole',
+ 'authenticatedusersrole',
+ 'id',
+ 'name',
+]);
+const WEB_ROLE_REQUIRED_KEYS = new Set([
+ 'anonymoususersrole',
+ 'authenticatedusersrole',
+ 'id',
+ 'name',
+]);
+
+function parseWebRoleYaml(content, filePath) {
+ const parsed = { filePath };
+ for (const rawLine of content.split(/\r?\n/)) {
+ const line = rawLine.trim();
+ if (!line) {
+ continue;
+ }
+
+ const separatorIndex = line.indexOf(':');
+ if (separatorIndex === -1) {
+ throw new Error(`Invalid YAML line "${line}" in ${filePath}`);
+ }
+
+ const key = line.slice(0, separatorIndex).trim();
+ const value = line.slice(separatorIndex + 1).trim();
+ if (value === 'true') {
+ parsed[key] = true;
+ } else if (value === 'false') {
+ parsed[key] = false;
+ } else {
+ parsed[key] = value;
+ }
+ }
+
+ return parsed;
+}
+
+function loadWebRoles(webRolesDir) {
+ if (!webRolesDir || !fs.existsSync(webRolesDir)) {
+ return [];
+ }
+
+ return fs.readdirSync(webRolesDir)
+ .filter(fileName => fileName.endsWith('.webrole.yml') || fileName.endsWith('.webrole.yaml'))
+ .map(fileName => {
+ const filePath = path.join(webRolesDir, fileName);
+ return parseWebRoleYaml(fs.readFileSync(filePath, 'utf8'), filePath);
+ });
+}
+
+function validateWebRoles(projectRoot) {
+ const findings = [];
+ const webRolesDir = path.join(projectRoot, '.powerpages-site', 'web-roles');
+
+ for (const filePath of listYamlFiles(webRolesDir)) {
+ const fileName = path.basename(filePath);
+ if (!fileName.endsWith(WEB_ROLE_FILE_SUFFIX)) {
+ addFinding(findings, 'error', `Web role file does not follow naming convention "*${WEB_ROLE_FILE_SUFFIX}".`, {
+ filePath,
+ fileName,
+ });
+ }
+ }
+
+ let webRoles = [];
+ try {
+ webRoles = loadWebRoles(webRolesDir);
+ } catch (error) {
+ addFinding(findings, 'error', `Failed to parse web role YAML: ${error.message}`, {
+ filePath: webRolesDir,
+ });
+ }
+
+ for (const webRole of webRoles) {
+ const fileName = path.basename(webRole.filePath);
+ const unexpectedKeys = findUnexpectedKeys(webRole, WEB_ROLE_ALLOWED_KEYS);
+ if (unexpectedKeys.length > 0) {
+ addFinding(findings, 'error', `Web role contains unexpected schema keys: ${unexpectedKeys.join(', ')}.`, {
+ filePath: webRole.filePath,
+ fileName,
+ });
+ }
+
+ const missingKeys = findMissingKeys(webRole, WEB_ROLE_REQUIRED_KEYS);
+ if (missingKeys.length > 0) {
+ addFinding(findings, 'error', `Web role is missing required schema keys: ${missingKeys.join(', ')}.`, {
+ filePath: webRole.filePath,
+ fileName,
+ });
+ }
+
+ if (!UUID_REGEX.test(String(webRole.id || ''))) {
+ addFinding(findings, 'error', 'Web role has an invalid "id" UUID.', {
+ filePath: webRole.filePath,
+ fileName,
+ });
+ }
+
+ if (!webRole.name || String(webRole.name).trim() === '') {
+ addFinding(findings, 'error', 'Web role has an empty "name" value.', {
+ filePath: webRole.filePath,
+ fileName,
+ });
+ }
+
+ for (const booleanField of ['anonymoususersrole', 'authenticatedusersrole']) {
+ if (typeof webRole[booleanField] !== 'boolean') {
+ addFinding(findings, 'error', `Web role field "${booleanField}" must be a boolean.`, {
+ filePath: webRole.filePath,
+ fileName,
+ });
+ }
+ }
+ }
+
+ return {
+ projectRoot,
+ webRoles,
+ findings,
+ summary: summarize(findings),
+ };
+}
+
+module.exports = {
+ validateWebRoles,
+};
diff --git a/plugins/power-pages/scripts/tests/clear-site-cache.test.js b/plugins/power-pages/scripts/tests/clear-site-cache.test.js
new file mode 100644
index 000000000..1b0d2d427
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/clear-site-cache.test.js
@@ -0,0 +1,59 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const { createTempProject, writeProjectFile } = require('./test-utils');
+
+const scriptPath = path.join(__dirname, '..', 'clear-site-cache.js');
+
+function runClearSiteCache(args) {
+ return spawnSync(process.execPath, [scriptPath, ...args], {
+ encoding: 'utf8',
+ timeout: 30000,
+ });
+}
+
+test('fails when powerpages.config.json is not found', (t) => {
+ const projectRoot = createTempProject(t);
+ const result = runClearSiteCache(['--projectRoot', projectRoot]);
+ assert.equal(result.status, 1);
+ const parsed = JSON.parse(result.stdout);
+ assert.equal(parsed.success, false);
+ assert.match(parsed.error, /powerpages\.config\.json not found/);
+});
+
+test('fails when siteName is missing from config', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', JSON.stringify({}));
+ const result = runClearSiteCache(['--projectRoot', projectRoot]);
+ assert.equal(result.status, 1);
+ const parsed = JSON.parse(result.stdout);
+ assert.equal(parsed.success, false);
+ assert.match(parsed.error, /siteName not found/);
+});
+
+test('fails when powerpages.config.json is invalid JSON', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', 'not json');
+ const result = runClearSiteCache(['--projectRoot', projectRoot]);
+ assert.equal(result.status, 1);
+ const parsed = JSON.parse(result.stdout);
+ assert.equal(parsed.success, false);
+ assert.match(parsed.error, /Failed to parse/);
+});
+
+test('fails gracefully when PAC CLI is not authenticated', (t) => {
+ // This test depends on the PAC CLI auth state.
+ // If PAC is authenticated, it will proceed further and fail at the API call.
+ // If not authenticated, it will fail at the PAC auth check.
+ // Either way, the script should exit 1 with success: false.
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', JSON.stringify({ siteName: 'nonexistent-test-site' }));
+ const result = runClearSiteCache(['--projectRoot', projectRoot]);
+ assert.equal(result.status, 1);
+ const parsed = JSON.parse(result.stdout);
+ assert.equal(parsed.success, false);
+ assert.ok(parsed.error.length > 0, 'error message should be non-empty');
+});
diff --git a/plugins/power-pages/scripts/tests/create-site-setting.test.js b/plugins/power-pages/scripts/tests/create-site-setting.test.js
new file mode 100644
index 000000000..04d29cfe2
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/create-site-setting.test.js
@@ -0,0 +1,68 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const { createTempProject } = require('./test-utils');
+
+function runCreateSiteSetting(args) {
+ const cliPath = path.join(__dirname, '..', 'create-site-setting.js');
+ return spawnSync(process.execPath, [cliPath, ...args], {
+ encoding: 'utf8',
+ });
+}
+
+test('create-site-setting creates a value-backed site setting', (t) => {
+ const projectRoot = createTempProject(t);
+ const result = runCreateSiteSetting([
+ '--projectRoot', projectRoot,
+ '--name', 'Webapi/test/enabled',
+ '--value', 'true',
+ '--description', 'Enable test setting',
+ '--type', 'boolean',
+ ]);
+
+ assert.equal(result.status, 0, result.stderr);
+
+ const parsed = JSON.parse(result.stdout);
+ const yaml = fs.readFileSync(parsed.filePath, 'utf8');
+
+ assert.match(parsed.filePath, /Webapi-test-enabled\.sitesetting\.yml$/);
+ assert.match(yaml, /^description: Enable test setting$/m);
+ assert.match(yaml, /^name: Webapi\/test\/enabled$/m);
+ assert.match(yaml, /^value: true$/m);
+});
+
+test('create-site-setting creates an environment-variable-backed site setting', (t) => {
+ const projectRoot = createTempProject(t);
+ const result = runCreateSiteSetting([
+ '--projectRoot', projectRoot,
+ '--name', 'TestEnvABC',
+ '--envVarSchema', 'ABC',
+ ]);
+
+ assert.equal(result.status, 0, result.stderr);
+
+ const parsed = JSON.parse(result.stdout);
+ const yaml = fs.readFileSync(parsed.filePath, 'utf8');
+
+ assert.match(yaml, /^envvar_schema: ABC$/m);
+ assert.match(yaml, /^name: TestEnvABC$/m);
+ assert.match(yaml, /^source: 1$/m);
+ assert.doesNotMatch(yaml, /^value:/m);
+ assert.doesNotMatch(yaml, /^description:/m);
+});
+
+test('create-site-setting rejects mixing environment-variable and value inputs', (t) => {
+ const projectRoot = createTempProject(t);
+ const result = runCreateSiteSetting([
+ '--projectRoot', projectRoot,
+ '--name', 'TestEnvABC',
+ '--envVarSchema', 'ABC',
+ '--value', 'ignored',
+ ]);
+
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /cannot be combined with --value or --description/);
+});
diff --git a/plugins/power-pages/scripts/tests/powerpages-config.test.js b/plugins/power-pages/scripts/tests/powerpages-config.test.js
new file mode 100644
index 000000000..37e430829
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/powerpages-config.test.js
@@ -0,0 +1,22 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const { parseSimpleYaml } = require('../lib/powerpages-config');
+
+test('parseSimpleYaml handles arrays and block-scalar descriptions', () => {
+ const parsed = parseSimpleYaml(
+ [
+ 'description: >-',
+ ' First line',
+ '',
+ ' Second line',
+ 'id: e7c06211-0cb1-4096-b3f8-9b7f91f3a133',
+ 'adx_entitypermission_webrole:',
+ '- 997e7996-e241-4117-9c09-28e90a1fcdbc',
+ ].join('\n'),
+ 'sample.yml'
+ );
+
+ assert.equal(parsed.description, 'First line\n\nSecond line');
+ assert.deepEqual(parsed.adx_entitypermission_webrole, ['997e7996-e241-4117-9c09-28e90a1fcdbc']);
+});
diff --git a/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js b/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js
new file mode 100644
index 000000000..bd0b014f8
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js
@@ -0,0 +1,39 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const {
+ detectTrackedSkill,
+ getTrackedSkillFromToolInput,
+ getValidatorScript,
+} = require('../lib/powerpages-hook-utils');
+
+test('detectTrackedSkill recognizes tracked skill references', () => {
+ assert.equal(detectTrackedSkill('create-site'), 'create-site');
+ assert.equal(detectTrackedSkill('/power-pages:setup-auth'), 'setup-auth');
+ assert.equal(detectTrackedSkill('power-pages:add-seo'), 'add-seo');
+ assert.equal(detectTrackedSkill('/power-pages:deploy-site'), null);
+});
+
+test('detectTrackedSkill recognizes slash command aliases without plugin prefix', () => {
+ assert.equal(detectTrackedSkill('/create-site'), 'create-site');
+ assert.equal(detectTrackedSkill('/setup-auth'), 'setup-auth');
+ assert.equal(detectTrackedSkill('/integrate-webapi'), 'integrate-webapi');
+ assert.equal(detectTrackedSkill('/audit-permissions'), 'audit-permissions');
+ assert.equal(detectTrackedSkill('/deploy-site'), null);
+});
+
+test('getTrackedSkillFromToolInput finds a tracked skill in common fields', () => {
+ assert.equal(getTrackedSkillFromToolInput({ skill_name: 'create-site' }), 'create-site');
+ assert.equal(getTrackedSkillFromToolInput({ name: '/power-pages:setup-auth' }), 'setup-auth');
+ assert.equal(
+ getTrackedSkillFromToolInput({ command: 'run /power-pages:integrate-webapi for this repo' }),
+ 'integrate-webapi'
+ );
+ assert.equal(getTrackedSkillFromToolInput({ name: 'deploy-site' }), null);
+});
+
+test('getValidatorScript returns validator paths only for command-backed skills', () => {
+ assert.match(getValidatorScript('create-site'), /validate-site\.js$/);
+ assert.equal(getValidatorScript('test-site'), null);
+ assert.equal(getValidatorScript('missing-skill'), null);
+});
diff --git a/plugins/power-pages/scripts/tests/powerpages-schema-validator.test.js b/plugins/power-pages/scripts/tests/powerpages-schema-validator.test.js
new file mode 100644
index 000000000..eac501e04
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/powerpages-schema-validator.test.js
@@ -0,0 +1,18 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const { validatePowerPagesSchema } = require('../lib/powerpages-schema-validator');
+const { createTempProject, writeProjectFile } = require('./test-utils');
+
+test('validatePowerPagesSchema combines findings across validators', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, '.powerpages-site/table-permissions/foo.yml', 'id: x\n');
+ writeProjectFile(projectRoot, '.powerpages-site/site-settings/bar.yml', 'id: x\n');
+ writeProjectFile(projectRoot, '.powerpages-site/web-roles/baz.yml', 'id: x\n');
+
+ const result = validatePowerPagesSchema(projectRoot);
+ assert.ok(result.summary.error >= 3);
+ assert.ok(result.tablePermissions.summary.error >= 1);
+ assert.ok(result.siteSettings.summary.error >= 1);
+ assert.ok(result.webRoles.summary.error >= 1);
+});
diff --git a/plugins/power-pages/scripts/tests/powerpages-validation-utils.test.js b/plugins/power-pages/scripts/tests/powerpages-validation-utils.test.js
new file mode 100644
index 000000000..9d18c443d
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/powerpages-validation-utils.test.js
@@ -0,0 +1,13 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const { addFinding, summarize } = require('../lib/powerpages-validation-utils');
+
+test('addFinding and summarize produce severity counts', () => {
+ const findings = [];
+ addFinding(findings, 'error', 'Bad config');
+ addFinding(findings, 'warning', 'Odd config');
+ addFinding(findings, 'info', 'FYI');
+
+ assert.deepEqual(summarize(findings), { error: 1, warning: 1, info: 1 });
+});
diff --git a/plugins/power-pages/scripts/tests/site-settings-validator.test.js b/plugins/power-pages/scripts/tests/site-settings-validator.test.js
new file mode 100644
index 000000000..8820f2762
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/site-settings-validator.test.js
@@ -0,0 +1,86 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const { validateSiteSettings } = require('../lib/site-settings-validator');
+const { createTempProject, writeProjectFile, findingMessages } = require('./test-utils');
+
+test('validateSiteSettings accepts optional description and value', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ '.powerpages-site/site-settings/search-filters.sitesetting.yml',
+ [
+ 'description: >-',
+ ' A collection of search logical name filter options.',
+ 'id: e7c06211-0cb1-4096-b3f8-9b7f91f3a133',
+ 'name: search/filters',
+ '',
+ ].join('\n')
+ );
+
+ const result = validateSiteSettings(projectRoot);
+ assert.equal(result.summary.error, 0);
+});
+
+test('validateSiteSettings flags naming convention violations', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, '.powerpages-site/site-settings/bar.yml', 'id: x\n');
+
+ const result = validateSiteSettings(projectRoot);
+ assert.ok(findingMessages(result.findings).some(message => message.includes('does not follow naming convention "*.sitesetting.yml"')));
+});
+
+test('validateSiteSettings accepts environment-variable-backed settings', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ '.powerpages-site/site-settings/test-env.sitesetting.yml',
+ [
+ 'envvar_schema: ABC',
+ 'id: e9981fe5-6724-4111-8341-6045bd001091',
+ 'name: TestEnvABC',
+ 'source: 1',
+ '',
+ ].join('\n')
+ );
+
+ const result = validateSiteSettings(projectRoot);
+ assert.equal(result.summary.error, 0);
+});
+
+test('validateSiteSettings accepts source 0 without envvar_schema', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ '.powerpages-site/site-settings/CodeSite-Enabled.sitesetting.yml',
+ [
+ 'id: e7c06211-0cb1-4096-b3f8-9b7f91f3a133',
+ 'name: CodeSite/Enabled',
+ 'source: 0',
+ 'value: true',
+ '',
+ ].join('\n')
+ );
+
+ const result = validateSiteSettings(projectRoot);
+ assert.equal(result.summary.error, 0);
+});
+
+test('validateSiteSettings rejects environment-variable-backed settings with value', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ '.powerpages-site/site-settings/test-env-invalid.sitesetting.yml',
+ [
+ 'envvar_schema: ABC',
+ 'id: e9981fe5-6724-4111-8341-6045bd001091',
+ 'name: TestEnvABC',
+ 'source: 1',
+ 'value: should-not-be-present',
+ '',
+ ].join('\n')
+ );
+
+ const result = validateSiteSettings(projectRoot);
+ assert.ok(findingMessages(result.findings).some(message => message.includes('must not define "value"')));
+});
diff --git a/plugins/power-pages/scripts/tests/table-permissions-validator.test.js b/plugins/power-pages/scripts/tests/table-permissions-validator.test.js
new file mode 100644
index 000000000..4db0936fe
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/table-permissions-validator.test.js
@@ -0,0 +1,127 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const { validateTablePermissions } = require('../lib/table-permissions-validator');
+const { createTempProject, writeProjectFile, findingMessages } = require('./test-utils');
+
+test('validateTablePermissions accepts a valid contact-scope permission', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ '.powerpages-site/table-permissions/Invoice-Supplier-Access.tablepermission.yml',
+ [
+ 'adx_entitypermission_webrole:',
+ '- 997e7996-e241-4117-9c09-28e90a1fcdbc',
+ 'append: true',
+ 'appendto: true',
+ 'contactrelationship: crd50_contact_invoice_submitter',
+ 'create: true',
+ 'delete: true',
+ 'entitylogicalname: crd50_invoice',
+ 'entityname: Invoice - Supplier Access',
+ 'id: cb0c220a-7e81-4056-9dde-666922e9f1a4',
+ 'read: true',
+ 'scope: 756150001',
+ 'write: true',
+ '',
+ ].join('\n')
+ );
+
+ const result = validateTablePermissions(projectRoot);
+ assert.equal(result.summary.error, 0);
+});
+
+test('validateTablePermissions flags wrong relationship key and missing contactrelationship', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ '.powerpages-site/table-permissions/Invoice-Supplier-Access.tablepermission.yml',
+ [
+ 'adx_entitypermission_webrole:',
+ '- 997e7996-e241-4117-9c09-28e90a1fcdbc',
+ 'append: true',
+ 'appendto: true',
+ 'contactaccessrelationshipname: crd50_contact_invoice_submitter',
+ 'create: true',
+ 'delete: true',
+ 'entitylogicalname: crd50_invoice',
+ 'entityname: Invoice - Supplier Access',
+ 'id: cb0c220a-7e81-4056-9dde-666922e9f1a4',
+ 'read: true',
+ 'scope: 756150001',
+ 'write: true',
+ '',
+ ].join('\n')
+ );
+
+ const result = validateTablePermissions(projectRoot);
+ assert.ok(findingMessages(result.findings).some(message => message.includes('unexpected schema keys: contactaccessrelationshipname')));
+ assert.ok(findingMessages(result.findings).some(message => message.includes('missing "contactrelationship"')));
+});
+
+test('validateTablePermissions flags table permission naming convention violations', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, '.powerpages-site/table-permissions/foo.yml', 'id: x\n');
+
+ const result = validateTablePermissions(projectRoot);
+ assert.ok(findingMessages(result.findings).some(message => message.includes('does not follow naming convention "*.tablepermission.yml"')));
+});
+
+test('validateTablePermissions flags missing scope', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ '.powerpages-site/table-permissions/Invoice-Supplier-Access.tablepermission.yml',
+ [
+ 'adx_entitypermission_webrole:',
+ '- 997e7996-e241-4117-9c09-28e90a1fcdbc',
+ 'append: true',
+ 'appendto: true',
+ 'create: true',
+ 'delete: true',
+ 'entitylogicalname: crd50_invoice',
+ 'entityname: Invoice - Supplier Access',
+ 'id: cb0c220a-7e81-4056-9dde-666922e9f1a4',
+ 'read: true',
+ 'write: true',
+ '',
+ ].join('\n')
+ );
+
+ const result = validateTablePermissions(projectRoot);
+ assert.ok(findingMessages(result.findings).some(message => message.includes('missing required schema keys: scope')));
+ assert.ok(findingMessages(result.findings).some(message => message.includes('empty values for entityname, entitylogicalname, or scope')));
+ assert.ok(findingMessages(result.findings).some(message => message.includes('invalid "scope" value')));
+});
+
+test('validateTablePermissions can validate relationship names against a provided Dataverse resolver', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ '.powerpages-site/table-permissions/Invoice-Supplier-Access.tablepermission.yml',
+ [
+ 'adx_entitypermission_webrole:',
+ '- 997e7996-e241-4117-9c09-28e90a1fcdbc',
+ 'append: true',
+ 'appendto: true',
+ 'contactrelationship: crd50_contact_invoice_submitter',
+ 'create: true',
+ 'delete: true',
+ 'entitylogicalname: crd50_invoice',
+ 'entityname: Invoice - Supplier Access',
+ 'id: cb0c220a-7e81-4056-9dde-666922e9f1a4',
+ 'read: true',
+ 'scope: 756150001',
+ 'write: true',
+ '',
+ ].join('\n')
+ );
+
+ const result = validateTablePermissions(projectRoot, {
+ resolveRelationships: () => [
+ { schemaName: 'different_relationship', referencedEntity: 'contact' },
+ ],
+ });
+
+ assert.ok(findingMessages(result.findings).some(message => message.includes('was not found in Dataverse')));
+});
diff --git a/plugins/power-pages/scripts/tests/test-utils.js b/plugins/power-pages/scripts/tests/test-utils.js
new file mode 100644
index 000000000..f7a7ec5a4
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/test-utils.js
@@ -0,0 +1,35 @@
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+
+function createTempProject(t) {
+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'powerpages-validator-'));
+ t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));
+
+ for (const relativeDir of [
+ '.powerpages-site/table-permissions',
+ '.powerpages-site/site-settings',
+ '.powerpages-site/web-roles',
+ ]) {
+ fs.mkdirSync(path.join(projectRoot, relativeDir), { recursive: true });
+ }
+
+ return projectRoot;
+}
+
+function writeProjectFile(projectRoot, relativePath, content) {
+ const filePath = path.join(projectRoot, relativePath);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, content, 'utf8');
+ return filePath;
+}
+
+function findingMessages(findings) {
+ return findings.map(finding => finding.message);
+}
+
+module.exports = {
+ createTempProject,
+ writeProjectFile,
+ findingMessages,
+};
diff --git a/plugins/power-pages/scripts/tests/validate-permissions-schema.test.js b/plugins/power-pages/scripts/tests/validate-permissions-schema.test.js
new file mode 100644
index 000000000..fa50c18a2
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/validate-permissions-schema.test.js
@@ -0,0 +1,20 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const { createTempProject, writeProjectFile } = require('./test-utils');
+
+test('validate-permissions-schema CLI exits with code 2 on --fail-on-error', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, '.powerpages-site/table-permissions/foo.yml', 'id: x\n');
+
+ const cliPath = path.join(__dirname, '..', 'validate-permissions-schema.js');
+ const result = spawnSync(process.execPath, [cliPath, '--projectRoot', projectRoot, '--fail-on-error'], {
+ encoding: 'utf8',
+ });
+
+ assert.equal(result.status, 2);
+ const parsed = JSON.parse(result.stdout);
+ assert.ok(parsed.summary.error >= 1);
+});
diff --git a/plugins/power-pages/scripts/tests/web-roles-validator.test.js b/plugins/power-pages/scripts/tests/web-roles-validator.test.js
new file mode 100644
index 000000000..27be89a9f
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/web-roles-validator.test.js
@@ -0,0 +1,31 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const { validateWebRoles } = require('../lib/web-roles-validator');
+const { createTempProject, writeProjectFile, findingMessages } = require('./test-utils');
+
+test('validateWebRoles flags invalid booleans', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ '.powerpages-site/web-roles/Bad.webrole.yml',
+ [
+ 'anonymoususersrole: maybe',
+ 'authenticatedusersrole: false',
+ 'id: fbd6927d-9902-49e2-96b3-79989482c839',
+ 'name: Bad Role',
+ '',
+ ].join('\n')
+ );
+
+ const result = validateWebRoles(projectRoot);
+ assert.ok(findingMessages(result.findings).some(message => message.includes('anonymoususersrole') && message.includes('must be a boolean')));
+});
+
+test('validateWebRoles flags naming convention violations', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, '.powerpages-site/web-roles/baz.yml', 'id: x\n');
+
+ const result = validateWebRoles(projectRoot);
+ assert.ok(findingMessages(result.findings).some(message => message.includes('does not follow naming convention "*.webrole.yml"')));
+});
diff --git a/plugins/power-pages/scripts/update-skill-tracking.js b/plugins/power-pages/scripts/update-skill-tracking.js
index a1108ceea..363d27ea0 100644
--- a/plugins/power-pages/scripts/update-skill-tracking.js
+++ b/plugins/power-pages/scripts/update-skill-tracking.js
@@ -11,7 +11,8 @@
const fs = require('fs');
const path = require('path');
-const { randomBytes } = require('crypto');
+const generateUuid = require('./generate-uuid');
+const { loadSiteSettings, SITE_SETTING_FILE_SUFFIX } = require('./lib/powerpages-config');
// --- CLI arg parsing ---
@@ -49,26 +50,15 @@ if (!fs.existsSync(siteSettingsDir)) {
process.exit(0);
}
-// --- Helpers ---
-
-function generateUuid() {
- const bytes = randomBytes(16);
- bytes[6] = (bytes[6] & 0x0f) | 0x40;
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
- 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)}`;
+let existingSiteSettings;
+try {
+ existingSiteSettings = loadSiteSettings(siteSettingsDir);
+} catch (error) {
+ console.error(`Error: Failed to read existing site settings. ${error.message}`);
+ process.exit(1);
}
-function parseYaml(content) {
- const fields = {};
- for (const line of content.split('\n')) {
- const sep = line.indexOf(': ');
- if (sep !== -1) {
- fields[line.slice(0, sep)] = line.slice(sep + 2);
- }
- }
- return fields;
-}
+// --- Helpers ---
function writeYaml(fields) {
const keys = Object.keys(fields).sort();
@@ -78,15 +68,16 @@ function writeYaml(fields) {
// --- Skill counter setting ---
const skillSettingName = `Site/AI/Skills/${skillName}`;
-const skillFileName = `Site-AI-Skills-${skillName}.sitesetting.yml`;
+const skillFileName = `Site-AI-Skills-${skillName}${SITE_SETTING_FILE_SUFFIX}`;
const skillFilePath = path.join(siteSettingsDir, skillFileName);
-
-if (fs.existsSync(skillFilePath)) {
- const existing = parseYaml(fs.readFileSync(skillFilePath, 'utf8'));
- const currentValue = parseInt(existing.value, 10) || 0;
- existing.value = String(currentValue + 1);
- fs.writeFileSync(skillFilePath, writeYaml(existing), 'utf8');
- console.log(`Updated ${skillSettingName} counter to ${existing.value}`);
+const existingSkillSetting = existingSiteSettings.find(setting => setting.name === skillSettingName);
+
+if (existingSkillSetting) {
+ const currentValue = parseInt(existingSkillSetting.value, 10) || 0;
+ const { filePath, ...yamlFields } = existingSkillSetting;
+ yamlFields.value = String(currentValue + 1);
+ fs.writeFileSync(filePath, writeYaml(yamlFields), 'utf8');
+ console.log(`Updated ${skillSettingName} counter to ${yamlFields.value}`);
} else {
const fields = {
description: `Tracks usage count of the ${skillName} skill`,
@@ -100,10 +91,11 @@ if (fs.existsSync(skillFilePath)) {
// --- Authoring tool setting ---
-const authoringFileName = 'Site-AI-Tools-AuthoringTool.sitesetting.yml';
+const authoringFileName = `Site-AI-Tools-AuthoringTool${SITE_SETTING_FILE_SUFFIX}`;
const authoringFilePath = path.join(siteSettingsDir, authoringFileName);
+const existingAuthoringSetting = existingSiteSettings.find(setting => setting.name === 'Site/AI/Tools/AuthoringTool');
-if (!fs.existsSync(authoringFilePath)) {
+if (!existingAuthoringSetting) {
const fields = {
description: 'Records which AI authoring tool was used',
id: generateUuid(),
diff --git a/plugins/power-pages/scripts/validate-permissions-schema.js b/plugins/power-pages/scripts/validate-permissions-schema.js
new file mode 100644
index 000000000..63109247f
--- /dev/null
+++ b/plugins/power-pages/scripts/validate-permissions-schema.js
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+
+const { execFileSync } = require('child_process');
+const path = require('path');
+const { validatePowerPagesSchema } = require('./lib/powerpages-schema-validator');
+const { getEnvironmentUrl } = require('./lib/validation-helpers');
+
+const args = process.argv.slice(2);
+
+function getArg(name) {
+ const index = args.indexOf(`--${name}`);
+ return index !== -1 && index + 1 < args.length ? args[index + 1] : null;
+}
+
+const projectRoot = getArg('projectRoot');
+const failOnError = args.includes('--fail-on-error');
+const validateDataverseRelationships = args.includes('--validate-dataverse-relationships');
+const envUrlArg = getArg('envUrl');
+
+if (!projectRoot) {
+ console.error('Usage: node validate-permissions-schema.js --projectRoot <path> [--fail-on-error] [--validate-dataverse-relationships] [--envUrl <url>]');
+ process.exit(1);
+}
+
+function createDataverseRelationshipResolver(envUrl) {
+ const normalizedEnvUrl = envUrl.replace(/\/+$/, '');
+ const cache = new Map();
+ const dataverseRequestScript = path.join(__dirname, 'dataverse-request.js');
+
+ return (entityLogicalName) => {
+ const key = String(entityLogicalName || '').toLowerCase();
+ if (cache.has(key)) {
+ return cache.get(key);
+ }
+
+ const apiPath = `EntityDefinitions(LogicalName='${key}')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute`;
+ const output = execFileSync(process.execPath, [dataverseRequestScript, normalizedEnvUrl, 'GET', apiPath], {
+ encoding: 'utf8',
+ });
+ const parsed = JSON.parse(output);
+ if (parsed.status !== 200) {
+ throw new Error(parsed.error || `Dataverse returned status ${parsed.status}`);
+ }
+
+ const relationships = Array.isArray(parsed.data?.value) ? parsed.data.value.map(relationship => ({
+ schemaName: relationship.SchemaName,
+ referencedEntity: relationship.ReferencedEntity,
+ referencingEntity: relationship.ReferencingEntity,
+ referencingAttribute: relationship.ReferencingAttribute,
+ })) : [];
+
+ cache.set(key, relationships);
+ return relationships;
+ };
+}
+
+const validationOptions = {};
+if (validateDataverseRelationships) {
+ const envUrl = envUrlArg || getEnvironmentUrl();
+ if (!envUrl) {
+ console.error('Failed to determine Dataverse environment URL. Pass --envUrl <url> or run `pac env who` locally.');
+ process.exit(1);
+ }
+
+ validationOptions.resolveRelationships = createDataverseRelationshipResolver(envUrl);
+}
+
+const result = validatePowerPagesSchema(path.resolve(projectRoot), validationOptions);
+process.stdout.write(JSON.stringify(result, null, 2));
+
+if (failOnError && result.summary.error > 0) {
+ process.exit(2);
+}
diff --git a/plugins/power-pages/skills/activate-site/SKILL.md b/plugins/power-pages/skills/activate-site/SKILL.md
index 780914ec7..f66b5d585 100644
--- a/plugins/power-pages/skills/activate-site/SKILL.md
+++ b/plugins/power-pages/skills/activate-site/SKILL.md
@@ -9,28 +9,13 @@ description: >
user-invocable: true
allowed-tools: Read, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList
model: sonnet
-hooks:
- Stop:
- - hooks:
- - type: command
- command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/activate-site/scripts/validate-activation.js"'
- timeout: 30
- - type: prompt
- prompt: >
- If a Power Pages website was being activated in this session (via /power-pages:activate-site),
- verify before allowing stop: 1) Prerequisites were verified (PAC CLI auth + Azure CLI login),
- 2) Site name was read from config or user input, 3) The subdomain generator script was run AND the user was asked (via AskUserQuestion) whether to use the generated subdomain or enter a custom one,
- 4) The user confirmed activation parameters, 5) The POST to the websites API was made,
- 6) Provisioning status was polled to completion, 7) A summary with the site URL was presented.
- If incomplete, return { "ok": false, "reason": "<specific issues>" }. Otherwise return { "ok": true }.
- timeout: 30
---
# Activate Power Pages Site
Provision a new Power Pages website in a Power Platform environment via the Power Platform REST API.
-> **Prerequisite:** This skill expects an existing Power Pages code site created via `/power-pages:create-site`. Run that skill first if the site does not exist yet.
+> **Prerequisite:** This skill expects an existing Power Pages code site created via `/create-site`. Run that skill first if the site does not exist yet.
## Core Principles
@@ -72,7 +57,7 @@ pac help
dotnet tool install --global Microsoft.PowerApps.CLI.Tool
```
-2. If `dotnet` is also not available, direct the user to https://aka.ms/PowerPlatformCLI for full installation instructions.
+2. If `dotnet` is also not available, direct the user to <https://aka.ms/PowerPlatformCLI> for full installation instructions.
3. After installation, verify by running `pac help` again.
#### 1.2 Check Authentication
@@ -84,6 +69,7 @@ pac auth who
```
**If authenticated**: Extract these values from the output:
+
- **Environment ID** — the GUID after `Environment ID:`
- **Organization ID** — the GUID after `Organization ID:` (this is the Dataverse org ID)
- **Cloud** — the value after `Cloud:` (e.g., `Public`, `UsGov`, `UsGovHigh`, `UsGovDod`, `China`)
@@ -108,15 +94,12 @@ Before gathering parameters, check whether the site is already activated by runn
node "${CLAUDE_PLUGIN_ROOT}/scripts/check-activation-status.js" --projectRoot "<PROJECT_ROOT>"
```
-Where `<PROJECT_ROOT>` is the directory containing `powerpages.config.json` (use `Glob` with `**/powerpages.config.json` to locate it if not already known).
-
-The script reads `siteName` from `powerpages.config.json`, looks up the `websiteRecordId` via `pac pages list`, queries the Power Platform GET websites API, and matches the response against **both** the `websiteRecordId` (exact GUID match) and `name` (case-insensitive). It outputs a JSON result to stdout.
+Where `<PROJECT_ROOT>` is the directory containing `powerpages.config.json` or `.powerpages-site` folder.
+Evaluate the JSON result:
-Evaluate the result:
-
-- **If `activated` is `true`**: The site is already provisioned. Inform the user: "Your site **<siteName>** is already activated at **<websiteUrl>**. No further provisioning is needed." Suggest next steps (Phase 5.3) and stop — do NOT proceed to Phase 2.
+- **If `activated` is `true`**: Inform the user their site is already activated at `websiteUrl`. Suggest next steps (Phase 5.3) and stop — do NOT proceed to Phase 2.
- **If `activated` is `false`**: Proceed to Phase 2.
-- **If `error` is present**: The check could not complete. Proceed to Phase 2 (do not block the activation flow due to a failed check).
+- **If `error` is present**: Proceed to Phase 2 (do not block the activation flow).
### Output
@@ -241,7 +224,7 @@ Evaluate the JSON output:
| **`Failed`** | `400` + `SubdomainConflict` (or error message mentions subdomain) | Subdomain already taken. Loop back to Phase 2 action 2.2 for a new subdomain, then re-run the script. |
| **`Failed`** | `401` | Token expired. Ask the user to run `az login` and retry. |
| **`Failed`** | `403` | Insufficient permissions. Inform user they need the "Power Pages site creator" or "System Administrator" role. |
-| **`Failed`** | `409` | Website already exists. Inform user and suggest using `/power-pages:deploy-site` instead. |
+| **`Failed`** | `409` | Website already exists. Inform user and suggest using `/deploy-site` instead. |
| **`Failed`** | `429` or `5xx` | Throttling or server error. Wait 5 seconds and re-run the script once. |
| **`Failed`** | other | Present the error to the user and help troubleshoot. |
| **`Running`** | — | Provisioning still in progress after 5 minutes. Inform the user it may take up to 15 minutes and suggest checking the Power Platform admin center. |
@@ -283,9 +266,10 @@ Follow the skill tracking instructions in the reference to record this skill's u
#### 5.3 Suggest Next Steps
After 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`
+
+- Test the site: `/test-site` — Verify the site loads correctly and API calls are working
+- Set up the data model: `/setup-datamodel`
+- Add sample data: `/add-sample-data`
- View the site in the browser at the provisioned URL (note: it may take a few minutes for DNS to propagate)
### Output
@@ -318,7 +302,7 @@ Mark each task complete with `TaskUpdate` as you finish each phase.
- **Phase 2.2**: User may accept the generated subdomain or provide a custom one — validate custom input.
- **Phase 3**: User must explicitly approve activation. If declined, stop the skill entirely.
- **Phase 4.2**: On 400 (subdomain taken), loop back to Phase 2 action 2.2 and re-run the script — do not abort.
-- **Phase 4.2**: On 409 (site already exists), redirect user to `/power-pages:deploy-site` instead.
+- **Phase 4.2**: On 409 (site already exists), redirect user to `/deploy-site` instead.
- **Phase 4.2**: On timeout (still Running after 5 minutes), do not treat as failure — advise user to check admin center.
**Begin with Phase 1: Verify Prerequisites**
diff --git a/plugins/power-pages/skills/add-sample-data/SKILL.md b/plugins/power-pages/skills/add-sample-data/SKILL.md
index e7f8b4869..9fbd1f8ca 100644
--- a/plugins/power-pages/skills/add-sample-data/SKILL.md
+++ b/plugins/power-pages/skills/add-sample-data/SKILL.md
@@ -9,18 +9,6 @@ description: >
user-invocable: true
allowed-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: sonnet
-hooks:
- Stop:
- - hooks:
- - type: prompt
- prompt: >
- If sample data was being added in this session (via /power-pages:add-sample-data),
- verify before allowing stop: 1) Tables were discovered (from .datamodel-manifest.json or OData API),
- 2) The user selected which tables to populate,
- 3) All records were inserted via OData API, 4) A verification summary was presented
- showing record counts per table. If incomplete, return { "ok": false, "reason": "<specific issues>" }.
- Otherwise return { "ok": true }.
- timeout: 30
---
# Add Sample Data
@@ -42,6 +30,7 @@ Populate Dataverse tables with sample records via OData API so users can test an
**Goal**: Confirm PAC CLI auth, acquire an Azure CLI token, and verify API access
**Actions**:
+
1. Create todo list with all 6 phases (see [Progress Tracking](#progress-tracking) table)
2. Follow the prerequisite steps in `${CLAUDE_PLUGIN_ROOT}/references/dataverse-prerequisites.md` to verify PAC CLI auth, acquire an Azure CLI token, and confirm API access. Store the environment URL as `$envUrl`.
@@ -114,6 +103,7 @@ Use `AskUserQuestion` to ask how many sample records per table:
Analyze relationships between selected tables. Parent/referenced tables must be inserted first so their IDs are available for child/referencing table lookups.
Build the insertion order:
+
1. Tables with no lookup dependencies (parent tables) -- insert first
2. Tables that reference already-inserted tables -- insert next
3. Continue until all tables are ordered
@@ -209,6 +199,7 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST "<ChildE
### 5.5 Track Progress
Track each insertion attempt:
+
- Record table name, record number, success/failure
- On failure, log the error message but continue with remaining records
- Do NOT attempt automated rollback on failure
@@ -257,6 +248,7 @@ Present a summary table:
| `cr123_task` (Task) | 10 | 9 | 1 |
Include:
+
- Total records created across all tables
- Any failures with error details
- Lookup relationships that were established
@@ -264,9 +256,10 @@ Include:
### 6.4 Suggest Next Steps
After the summary, suggest:
+
- Review the data in the Power Pages maker portal or model-driven app
-- If the site is not yet built: `/power-pages:create-site`
-- If the site is ready to deploy: `/power-pages:deploy-site`
+- If the site is not yet built: `/create-site`
+- If the site is ready to deploy: `/deploy-site`
**Output**: Verified record counts and summary presented to the user
diff --git a/plugins/power-pages/skills/add-seo/SKILL.md b/plugins/power-pages/skills/add-seo/SKILL.md
index b7d6469be..ec6c1b480 100644
--- a/plugins/power-pages/skills/add-seo/SKILL.md
+++ b/plugins/power-pages/skills/add-seo/SKILL.md
@@ -5,26 +5,17 @@ description: >
"add robots.txt", "add sitemap", "improve SEO", "search engine optimization",
"add open graph tags", "add favicon", "make site searchable",
or wants to add SEO essentials (robots.txt, sitemap.xml, meta tags) to their
- Power Pages code site after creating it with /power-pages:create-site.
+ Power Pages code site after creating it with /create-site.
user-invocable: true
allowed-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: sonnet
-hooks:
- Stop:
- - hooks:
- - type: command
- command: "node \"${CLAUDE_PLUGIN_ROOT}/skills/add-seo/scripts/validate-seo.js\""
- timeout: 15
- - type: prompt
- prompt: "If SEO assets were being added in this session (via /power-pages:add-seo), verify before allowing stop: 1) robots.txt was created in the public directory, 2) sitemap.xml was created in the public directory with correct site URLs, 3) Meta tags (title, description, viewport, Open Graph) were added to index.html, 4) The user reviewed and approved the SEO additions, 5) A git commit was made with the SEO changes. If any of these are incomplete, return { \"ok\": false, \"reason\": \"<specific issues>\" }. If no SEO work happened or everything is complete, return { \"ok\": true }."
- timeout: 30
---
# Add SEO
Add essential SEO assets to a Power Pages code site: `robots.txt`, `sitemap.xml`, and meta tags.
-> **Prerequisite:** This skill expects an existing Power Pages code site created via `/power-pages:create-site`. Run that skill first if the site does not exist yet.
+> **Prerequisite:** This skill expects an existing Power Pages code site created via `/create-site`. Run that skill first if the site does not exist yet.
## Core Principles
@@ -61,7 +52,7 @@ Look for `powerpages.config.json` in the current directory or immediate subdirec
Get-ChildItem -Path . -Filter "powerpages.config.json" -Recurse -Depth 1
```
-**If not found**: Tell the user to create a site first with `/power-pages:create-site`.
+**If not found**: Tell the user to create a site first with `/create-site`.
#### 1.2 Read Existing Config
@@ -93,14 +84,14 @@ Build a list of all routes (e.g., `/`, `/about`, `/contact`, `/blog`).
Use `AskUserQuestion` to collect SEO preferences:
-#### Call 1:
+#### Call 1
| Question | Header | Options |
|----------|--------|---------|
-| What is the production URL for your site? (e.g., https://contoso.powerappsportals.com) | Site URL | *(free text — use single generic option so user types via "Other")* |
+| What is the production URL for your site? (e.g., <https://contoso.powerappsportals.com>) | Site URL | *(free text — use single generic option so user types via "Other")* |
| Which pages should be excluded from search engine indexing? | Exclusions | None — index all pages (Recommended), Admin/auth pages only, Let me specify |
-#### Call 2:
+#### Call 2
| Question | Header | Options |
|----------|--------|---------|
@@ -205,6 +196,7 @@ Generate entries for each discovered route using the production URL:
```
**Priority rules:**
+
- Home page (`/`): `1.0`
- Top-level pages: `0.8`
- Sub-pages: `0.6`
@@ -297,6 +289,7 @@ For Astro sites, meta tags should be added to the base layout component (e.g., `
#### 7.1 Verify Files Exist
Confirm the following files were created/updated:
+
- `public/robots.txt`
- `public/sitemap.xml`
- `public/favicon.svg` (if created)
@@ -344,8 +337,9 @@ Present a summary of what was added:
#### 7.6 Suggest Next Steps
After the summary, suggest:
-- **Deploy the site** to make SEO changes live: `/power-pages:deploy-site`
-- If data model is needed: `/power-pages:setup-datamodel`
+
+- **Deploy the site** to make SEO changes live: `/deploy-site`
+- If data model is needed: `/setup-datamodel`
- For more advanced SEO: consider structured data (JSON-LD), performance optimization, and accessibility audit
### Output
@@ -376,7 +370,7 @@ Update each task with `TaskUpdate` as it is completed.
### Key Decision Points
-- **Phase 1:** If `powerpages.config.json` is not found, stop and redirect the user to `/power-pages:create-site`.
+- **Phase 1:** If `powerpages.config.json` is not found, stop and redirect the user to `/create-site`.
- **Phase 2:** If the user specifies custom exclusions, confirm the exact paths before proceeding.
- **Phase 3:** Do not proceed to implementation until the user explicitly approves the plan.
- **Phase 6.4:** If the framework is Astro, meta tags go into the layout component, not `index.html`.
diff --git a/plugins/power-pages/skills/audit-permissions/SKILL.md b/plugins/power-pages/skills/audit-permissions/SKILL.md
index 0f6ed2338..ebe995f84 100644
--- a/plugins/power-pages/skills/audit-permissions/SKILL.md
+++ b/plugins/power-pages/skills/audit-permissions/SKILL.md
@@ -10,24 +10,8 @@ description: >-
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
+allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, Agent
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
@@ -38,10 +22,11 @@ Audit existing table permissions on a Power Pages code site. Analyze permissions
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
+3. **Run Local Schema Validation** — Use the shared validator to detect invalid permission/site-setting YAML before deeper analysis
+4. **Analyze & Discover** — Query Dataverse for relationships and lookup columns using deterministic scripts
+5. **Run Audit Checks** — Compare permissions against code usage and best practices
+6. **Generate Report** — Create the HTML audit report and display in browser
+7. **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.
@@ -53,20 +38,24 @@ At the start of Step 1, create all tasks upfront using `TaskCreate`. Mark each t
|-------------|------------|-------------|
| 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 |
+| Run local schema validation | Validating local permissions schema | Run shared validator against existing table permission and site setting YAML |
| Discover relationships | Discovering relationships | Query Dataverse for lookup columns and relationships |
-| Run audit checks | Running audit checks | Analyze permissions against code and best practices |
+| Run audit checks | Running audit checks | Create per-table tasks and run checklist (A–K) for each table, then cross-validate |
| 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 |
+**Note:** The "Run audit checks" phase creates **additional per-table tasks** dynamically in Step 4.2. These per-table tasks track the systematic A–K checklist for each table independently.
+
---
## 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 `.powerpages-site` folder exists, stop and tell the user to deploy first using `/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.
---
@@ -80,26 +69,51 @@ Read all files matching `**/.powerpages-site/web-roles/*.yml`. Extract `id`, `na
### 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)
+- `contactrelationship`, `accountrelationship` (if Contact/Account scope)
+- `parententitypermission`, `parentrelationship` (if parent scope)
### 2.3 Analyze Site Code
-Search the source code to understand which tables the site actually uses:
+Search the site source code for:
-```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
-```
+- Web API calls (`/_api/`)
+- Lookup bindings (`@odata.bind`)
+- File uploads (`uploadFileColumn`, `uploadFile`, `upload*Photo`, `upload*Image`)
+- `$expand` usage (`$expand`, `buildExpandClause`, `ExpandOption`)
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.
+Build a map of: which tables are referenced in code, which CRUD operations are performed on each, which lookup relationships are used, and which related tables are fetched via `$expand` (these need read permissions too).
+
+### 2.4 Run Shared Schema Validator
+
+Run the shared validator against the existing site:
+
+```powershell
+$schemaValidation = node "${CLAUDE_PLUGIN_ROOT}/scripts/validate-permissions-schema.js" --projectRoot "<PROJECT_ROOT>"
+```
+
+Parse the JSON output and carry the findings into the audit. Treat:
+
+- `error` findings as **critical**
+- `warning` findings as **warning**
+- `info` findings as **info**
+
+These findings should be included in the final audit report even if the later code/Dataverse analysis also finds additional issues.
+
+After Step 3.1 determines `$envUrl`, if this audit is running locally with Dataverse access available, rerun the shared validator with live relationship verification enabled and merge any additional findings:
+
+```powershell
+$schemaValidation = node "${CLAUDE_PLUGIN_ROOT}/scripts/validate-permissions-schema.js" --projectRoot "<PROJECT_ROOT>" --validate-dataverse-relationships --envUrl "$envUrl"
+```
+
+Use this Dataverse-backed relationship validation only for local runs. Do **not** require it in CI or other offline contexts.
---
@@ -123,9 +137,20 @@ For each table that has permissions with `create` or `write` enabled, use the lo
$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`
+The script returns a JSON array of `{ logicalName, targets }` for each lookup column.
+
+After querying **all** tables with create or write permissions, build two maps from the combined results:
+
+1. **Source map** (table → lookup columns): For each queried table, record which lookup columns it has and their targets. Used in Section H2 to check `appendto` on the source table.
+2. **Reverse target map** (target table → list of source tables): For each target table found in any lookup's `targets` array, record which source table(s) reference it. Used in Section H to check `append` on the target table.
+
+Example: querying `order_item` returns `[{ logicalName: "cr4fc_orderid", targets: ["cr4fc_order"] }]`
+- Source map: `order_item → [{ column: "cr4fc_orderid", targets: ["cr4fc_order"] }]`
+- Reverse target map: `cr4fc_order → [{ sourceTable: "order_item", column: "cr4fc_orderid" }]`
+
+Both maps are used in Sections H and H2:
+- The **source table** (with the lookup) needs `appendto: true` — it links TO other records (checked via the source map)
+- Each **target table** in `targets` needs `append: true` — other records link TO it (checked via the reverse target map)
### 3.3 Query Relationships
@@ -135,7 +160,7 @@ For tables with parent-scope permissions, verify the relationship names using th
$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.
+The script returns a JSON array of `{ schemaName, referencedEntity, referencingEntity, referencingAttribute }`. Use `schemaName` to validate the `parentrelationship` value in parent-scope permissions.
### Error Handling
@@ -145,87 +170,231 @@ If any script exits with code 1, skip the API-dependent checks and note which ch
## 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)
+Use per-table task tracking to systematically run every audit check. Each check produces a finding with severity, title, reasoning, and a suggested fix. Findings can be `critical`, `warning`, `info`, or `pass`.
-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.1 Build Audit Inventory
-#### 4.2 Overly Broad Scope (Warning)
+First, build a combined list of all tables to audit from two sources:
-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
+1. **Tables referenced in code** (from Step 2.3) — these may or may not have permissions
+2. **Tables with existing permissions** (from Step 2.2) — these may or may not be referenced in code
-For Global scope with only `read` enabled, this is acceptable for public reference data — mark as `pass`.
+The union of these two sets is the complete audit scope. Each table will be audited from both directions: "does the code need a permission that doesn't exist?" and "does the permission match what the code actually does?"
-#### 4.3 Missing Append/AppendTo (Critical)
+### 4.2 Create Per-Table Audit Tasks
-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`
+For each table in the audit inventory, create a task:
-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
+```
+TaskCreate:
+ subject: "Audit <table_logical_name>"
+ activeForm: "Auditing <table_display_name> permissions"
+ description: "Run all audit checks for <table_logical_name>"
+```
-#### 4.4 Orphaned Permissions (Info)
+Also create a summary task:
-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
+```
+TaskCreate:
+ subject: "Compile audit findings"
+ activeForm: "Compiling audit findings"
+ description: "Combine all per-table findings into the final report"
+```
-#### 4.5 Missing Web Role Association (Warning)
+Use `TaskList` at any point to review progress and see which tables still need auditing.
+
+### 4.3 Per-Table Audit Checklist
+
+For each table, mark its task `in_progress` and run through the following checks **in order**. For every finding, note the **specific evidence** (file path, permission name, code pattern) that supports it. Skip checks that don't apply to this table.
+
+**A. Permission Existence**
+
+Does this table have a table permission?
+
+- If the table is referenced in code but has **no permission** → finding:
+ - **Severity:** `critical`
+ - **Title:** `Missing permission for <table>`
+ - **Reasoning:** Which code files reference this table and what operations they perform
+ - **Fix:** Create a permission with the appropriate scope and CRUD flags
+- If a permission exists but the table is **not referenced in code** → finding:
+ - **Severity:** `info`
+ - **Title:** `Unused permission for <table>`
+ - **Reasoning:** The table is not referenced in any source code — the permission may be unnecessary
+ - **Fix:** Review whether this permission is still needed
+- If both exist → `pass`, proceed to remaining checks
+
+**B. Web Role Association**
+
+Does the permission have web role(s) assigned?
+
+- Check `adx_entitypermission_webrole` — if empty or missing → finding:
+ - **Severity:** `warning`
+ - **Title:** `Permission <name> has no web role association`
+ - **Reasoning:** A permission without a web role has no effect — no users will receive this access
+ - **Fix:** Associate with the appropriate web role
+- If roles are assigned → `pass`
+
+**C. Scope Appropriateness**
+
+Is the scope the least-privileged option that fits?
+
+- Search the service code for scope-relevant patterns: contact-scoped filters (`getCurrentContactId`, `_contactid_value`, `contactid`) and account-scoped filters (`_accountid_value`, `parentcustomerid`)
+- If Global scope (`756150000`) with `write` or `delete` enabled → finding:
+ - **Severity:** `warning`
+ - **Title:** `Global scope with write/delete on <table>`
+ - **Reasoning:** Any user with this role can modify/delete any record in this table
+ - **Fix:** Narrow to Contact or Account scope, or remove write/delete if not needed
+- If Global scope with only `read` → `pass` (acceptable for public reference data)
+- If code uses contact-scoped filters but permission uses Global → finding:
+ - **Severity:** `warning`
+ - **Title:** `Scope could be narrower for <table>`
+ - **Reasoning:** Code filters by current contact but permission grants Global access
+ - **Fix:** Narrow to Contact scope
+- Otherwise → `pass`
+
+**D. Read Permission**
+
+Is `read` correctly set?
+
+- Search the service code for GET/list/get patterns for this table: API calls to `/_api/<entity_set>`, list/get functions (`list<TableName>`, `get<TableName>`)
+- If code reads this table but `read: false` → finding:
+ - **Severity:** `critical`
+ - **Title:** `Missing read permission for <table>`
+ - **Reasoning:** Code reads from this table but permission does not grant read access
+ - **Fix:** Enable `read: true`
+- If `read: true` and code reads → `pass`
+
+**E. Create Permission**
+
+Is `create` correctly set?
+
+- Search the service code for POST/create patterns: POST method usage (`method: 'POST'`), create functions (`create<TableName>`)
+- If code creates records but `create: false` → finding:
+ - **Severity:** `critical`
+ - **Title:** `Missing create permission for <table>`
+ - **Reasoning:** Code creates records in this table but permission does not grant create access
+ - **Fix:** Enable `create: true`
+- If `create: true` but no create patterns in code → finding:
+ - **Severity:** `info`
+ - **Title:** `Create enabled but not used for <table>`
+ - **Reasoning:** No create operations found in code — permission may be overly permissive
+ - **Fix:** Consider disabling `create` if not needed
+- If matched → `pass`
+
+**F. Write Permission**
+
+Is `write` correctly set?
+
+- Search the service code for PATCH/update/upload patterns: PATCH method usage (`method: 'PATCH'`), update functions (`update<TableName>`), file upload patterns (`uploadFileColumn`, `uploadFile`, `upload*Photo`, `upload*Image`, `upload*File`)
+- If code updates records but `write: false` → finding:
+ - **Severity:** `critical`
+ - **Title:** `Missing write permission for <table>`
+ - **Reasoning:** Code updates records (or uploads files) in this table but permission does not grant write access
+ - **Fix:** Enable `write: true`
+- If file upload patterns found but `write: false` → finding:
+ - **Severity:** `warning`
+ - **Title:** `File upload detected but write is disabled on <table>`
+ - **Reasoning:** File uploads use PATCH which requires write permission
+ - **Fix:** Enable `write: true`
+- If `write: true` but `read: false` → finding:
+ - **Severity:** `warning`
+ - **Title:** `Write enabled without read on <table>`
+ - **Reasoning:** Users can modify records they cannot see, which is unusual and likely unintended
+ - **Fix:** Enable `read: true`
+- If `write: true` but no write patterns in code → finding:
+ - **Severity:** `info`
+ - **Title:** `Write enabled but not used for <table>`
+ - **Reasoning:** No update operations found in code — permission may be overly permissive
+ - **Fix:** Consider disabling `write` if not needed
+- If matched → `pass`
+
+**G. Delete Permission**
+
+Is `delete` correctly set?
+
+- Search the service code for DELETE patterns: DELETE method usage (`method: 'DELETE'`), delete functions (`delete<TableName>`)
+- If code deletes records but `delete: false` → finding:
+ - **Severity:** `critical`
+ - **Title:** `Missing delete permission for <table>`
+ - **Reasoning:** Code deletes records in this table but permission does not grant delete access
+ - **Fix:** Enable `delete: true`
+- If `delete: true` but no delete patterns in code → finding:
+ - **Severity:** `info`
+ - **Title:** `Delete enabled but not used for <table>`
+ - **Reasoning:** No delete operations found in code — permission may be overly permissive
+ - **Fix:** Consider disabling `delete` if not needed
+- If matched → `pass`
+
+**H. Append (target table check)**
+
+Does this table need `append: true`? Append is required on the **target** table — the table that other records link TO via lookup columns.
+
+- Check the **reverse target map** from Step 3.2: is this table referenced as a lookup target by any other table that has `create` or `write` permissions?
+- Also search the service code for `@odata.bind` references to this table's entity set (e.g., `/<entity_set>(`)
+- If this table appears in the reverse target map (i.e., another table with create/write has a lookup to this table), but `append: false` → finding:
+ - **Severity:** `critical`
+ - **Title:** `Missing append on <table>`
+ - **Reasoning:** Table `<source_table>` has lookup column `<column>` targeting this table and sets it during create/write. The target table needs append permission so records can be linked to it. Users will see "You don't have permission to associate or disassociate"
+ - **Fix:** Enable `append: true`
+- If `append: true` and justified → `pass`
+- If `append: true` but this table does NOT appear in the reverse target map and no code references it as a lookup target → finding:
+ - **Severity:** `info`
+ - **Title:** `Append enabled but not needed on <table>`
+ - **Reasoning:** No other table with create/write has a lookup to this table — append may be unnecessary
+ - **Fix:** Consider disabling `append` if not needed
+
+**H2. AppendTo (source table check)**
+
+Does this table need `appendto: true`? AppendTo is required on the **source** table — the table that has lookup columns linking TO other records.
+
+- Check the **source map** from Step 3.2: does this table have lookup columns?
+- Also search the service code for `@odata.bind` patterns in create/update calls for this table
+- If this table has lookup columns (in source map or code) AND has `create` or `write` enabled, but `appendto: false` → finding:
+ - **Severity:** `critical`
+ - **Title:** `Missing appendto on <table>`
+ - **Reasoning:** This table sets lookup column `<column>` targeting `<target_table>` during create/write, which requires appendto permission. Users will see "You don't have permission to associate or disassociate"
+ - **Fix:** Enable `appendto: true`
+- If `appendto: true` and justified → `pass`
+
+**I. Parent Chain Integrity**
+
+If the permission has Parent scope (`756150003`):
-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
+- Verify `parententitypermission` references a valid permission ID that exists
+- Verify `parentrelationship` is a valid Dataverse relationship (if API available, using Step 3.3 results)
+- If broken → finding:
+ - **Severity:** `critical`
+ - **Title:** `Broken parent chain for <permission>`
+ - **Reasoning:** The parent permission reference is invalid — this permission will not grant any access
+ - **Fix:** Correct the parent permission ID and/or relationship name
+- If valid → `pass`
-#### 4.6 Parent Chain Integrity (Critical)
+**J. $expand Related Table Coverage**
-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)
+Is this table fetched via `$expand` on another table's query?
-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
+- Check the `$expand` analysis from Step 2.3 (search site source code for `$expand`, `buildExpandClause`, `ExpandOption`)
+- If this table is expanded from another table but has no table permission with `read: true` for the same web role → finding:
+ - **Severity:** `critical`
+ - **Title:** `Missing read permission for expanded table <table>`
+ - **Reasoning:** This table is fetched via `$expand` on `<parent_table>` in `<service_file>`, but has no read permission. Power Pages enforces table permissions on every entity in the query.
+ - **Fix:** Create a table permission with `read: true` for the same web role. For collection-valued expansions (one-to-many), use Parent scope with the relationship name. For single-valued expansions (lookups to reference data), use Global scope with read-only access.
+- If properly covered → `pass`
-#### 4.7 Write Without Read (Warning)
+**K. Record Findings & Complete**
-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
+After all checks, mark the table's task as `completed` via `TaskUpdate`.
-#### 4.8 File Upload Without Write (Warning)
+### 4.4 Cross-Table Validation
-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
+After all per-table audits are complete, run these cross-table checks:
-#### 4.9 Passed Checks
+1. **Append/AppendTo consistency:** Using the source map and reverse target map from Step 3.2, verify: (a) every source table (with lookups and create/write) has `appendto: true`, (b) every target table in the reverse map has `append: true`, (c) no table has `appendto: true` without lookup columns in the source map, (d) no table has `append: true` without being in the reverse target map
+2. **$expand coverage:** For every `$expand` usage, verify the expanded table has `read: true`
+3. **Parent chain completeness:** For every Parent scope permission, verify the parent permission exists and is valid
+4. **Web role consistency:** If two related tables (e.g., parent and child) are accessed by the same feature, verify they share the same web role assignment
-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.
+Use `TaskList` to review all completed audits, then mark the "Compile audit findings" task as `in_progress` and proceed to Step 5.
---
@@ -238,7 +407,7 @@ For each check that passes (e.g., a table has correct permissions, a scope is ap
### 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.
+**Do NOT generate HTML manually or read/modify the template yourself.** Use the `render-audit-report.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:
@@ -288,8 +457,8 @@ Write a temporary JSON data file (e.g., `<OUTPUT_DIR>/audit-data.json`) with the
"create": false,
"write": false,
"delete": false,
- "append": false,
- "appendto": true
+ "append": true,
+ "appendto": false
}
```
@@ -305,9 +474,7 @@ 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
+Open the generated HTML file in the user's default browser.
---
@@ -326,9 +493,12 @@ 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."
+4. **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:
-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.
+- **For 403 / Web API access issues** (missing table permissions, missing CRUD flags, incorrect scope, missing append/appendto, missing `$expand` read coverage — any finding that would result in a 403 Forbidden response from the Power Pages Web API): Spawn the **table-permissions-architect** agent using the `Agent` tool. Pass it a prompt that includes the specific tables, the required CRUD flags, scope recommendations, and relationship details from the audit findings. The agent will analyze the site, propose a permissions plan, and create the correct table permission YAML files after user approval. Example prompt: `"Create table permissions for the following tables based on audit findings: <table1> needs Global scope with read:true; <table2> needs Parent scope under <parent_table> with read:true, create:true, append:true; <table3> needs appendto:true for lookups from <source_table>. The site project root is <PROJECT_ROOT>."`
+- **For non-permission issues** (e.g., unused permissions, scope narrowing suggestions, informational findings): explain what manual changes are needed or suggest running `/integrate-webapi` so the Web API settings architect can address site-setting-level issues.
---
@@ -338,4 +508,4 @@ If the user wants fixes applied, use the `${CLAUDE_PLUGIN_ROOT}/scripts/create-t
- **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.
+- **Graceful degradation**: If Dataverse API scripts fail (exit code 1), skip API-dependent checks (H/H2 append/appendto validation, I parent chain integrity) and note in the report which checks were skipped.
diff --git a/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js b/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js
index 7d4df22c1..522ed1148 100644
--- a/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js
+++ b/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js
@@ -15,11 +15,8 @@ runValidation((cwd) => {
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.');
- }
+ if (content.includes('__FINDINGS_DATA__') || content.includes('__INVENTORY_DATA__')) {
+ block('Audit report has unreplaced placeholders — data was not populated.');
}
approve();
}
diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.md
index 0cab98dc8..c1f64ddd1 100644
--- a/plugins/power-pages/skills/create-site/SKILL.md
+++ b/plugins/power-pages/skills/create-site/SKILL.md
@@ -5,15 +5,6 @@ user-invocable: true
argument-hint: Optional site description
allowed-tools: Read, Write, Edit, Grep, Glob, Bash, WebSearch, 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
model: opus
-hooks:
- Stop:
- - hooks:
- - type: command
- 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) 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
---
# Create Power Pages Code Site
@@ -40,6 +31,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 8 phases (see [Progress Tracking](#progress-tracking) table)
2. If site purpose is clear from arguments:
- Summarize understanding
@@ -70,6 +62,7 @@ Guide the user through creating a complete, production-quality Power Pages code
6. Summarize understanding and confirm with user before proceeding
**Audience influences site generation:**
+
- **Internal**: Prioritize data tables, dashboards, authentication, navigation depth, functional over flashy design
- **External**: Prioritize landing page appeal, SEO-friendly structure, contact forms, clean marketing-oriented layout
@@ -156,6 +149,7 @@ Immediately after the dev server starts, verify the scaffold is working:
3. **Share the dev server URL with the user** so they can preview the site in their own browser (e.g., "Your site is running at `http://localhost:5173` — open it in your browser to follow along as I build.")
> **GATE: Do NOT proceed to Phase 3 until ALL of the following are true:**
+>
> 1. Template files copied and placeholders replaced
> 2. Git repo initialized with initial scaffold commit
> 3. `npm install` completed successfully
@@ -174,6 +168,7 @@ Immediately after the dev server starts, verify the scaffold is working:
**Goal**: Determine what pages, components, and design elements the site needs — while the user previews the running scaffold
**Actions**:
+
1. Use `AskUserQuestion` to collect feature and design requirements:
| Question | Header | Options |
@@ -222,6 +217,7 @@ Immediately after the dev server starts, verify the scaffold is working:
**Goal**: Get user approval on the implementation plan
**Actions**:
+
1. Read the design aesthetics reference: `${CLAUDE_PLUGIN_ROOT}/skills/create-site/references/design-aesthetics.md`
2. Present the implementation plan directly to the user as a formatted message. **The plan MUST have ALL of the following sections:**
@@ -295,11 +291,13 @@ The scaffold is a temporary loading screen — it must be **completely replaced*
Use high-quality photos from Unsplash wherever the site needs visual content. Do NOT use placeholder services (e.g., `placeholder.com`, `placehold.co`), broken `<img>` tags, or leave empty image slots.
**How to find images:**
+
1. Use `WebSearch` to search Unsplash for relevant photos (e.g., `site:unsplash.com modern office workspace`)
2. Pick specific photos and use their direct URL with sizing parameters: `https://images.unsplash.com/photo-{id}?w={width}&h={height}&fit=crop`
3. Choose images that match the site's aesthetic and mood
**Where to use images:**
+
- **Hero sections** — Striking, high-resolution photos that set the tone for the site
- **Feature/service cards** — Relevant photos that illustrate each feature or service
- **About/team sections** — Professional or contextual photos matching the site's purpose
@@ -307,6 +305,7 @@ Use high-quality photos from Unsplash wherever the site needs visual content. Do
- **Content sections** — Supporting photos that break up text and add visual interest
**Guidelines:**
+
- Pick images that feel cohesive together — consistent style, lighting, and color tone
- Use appropriate sizing (`w=800` for cards, `w=1600` for heroes/backgrounds) to avoid slow loads
- Add descriptive `alt` text to every `<img>` for accessibility
@@ -322,6 +321,7 @@ git commit -m "<short description of what was added/changed>"
```
**When to commit:**
+
- After applying design foundations (fonts, colors, motion)
- After creating each page (e.g., "Add Home page", "Add Contact page")
- After creating each shared component (e.g., "Add Navbar component", "Add Footer component")
@@ -395,6 +395,7 @@ For each violation found, identify the source file and apply the fix:
| 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>"
@@ -429,8 +430,10 @@ Present a summary table to the user:
**Goal**: Ensure the site meets user expectations and all pages work correctly
**Actions**:
+
1. Browse through each page via Playwright (`browser_navigate` + `browser_snapshot`) to verify all pages load correctly — do NOT take screenshots
2. Present a summary of what was built:
+
```
| Component Type | Count | Details |
|---------------------|-------|---------|
@@ -439,6 +442,7 @@ Present a summary table to the user:
| Design Elements | 4 | Playfair Display + Source Sans Pro, 6 CSS variables, fade-in transitions, gradient backgrounds |
| Git Commits | 7 | scaffold + 6 feature commits |
```
+
3. Share the dev server URL with the user and list all available routes
4. Ask the user to review using `AskUserQuestion`:
> "The site is ready for review at `<dev server URL>`. Please check it out in your browser. Would you like any changes?"
@@ -455,6 +459,7 @@ Present a summary table to the user:
> **This phase is MANDATORY. Do NOT end the session without asking about deployment.**
**Actions**:
+
1. Record skill usage:
> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`
@@ -463,7 +468,7 @@ Present a summary table to the user:
2. Use `AskUserQuestion` with options: **Deploy now (Recommended)**, **Skip for now**:
> "Would you like to deploy your site to Power Pages now?"
-3. If the user chooses to deploy, invoke the `/power-pages:deploy-site` skill.
+3. If the user chooses to deploy, invoke the `/deploy-site` skill.
4. Mark all todos complete
5. Present a final summary:
- Site name and purpose
@@ -472,9 +477,9 @@ Present a summary table to the user:
- Key files and their purposes
- Total file count and git commit count
6. Suggest optional enhancement skills:
- - `/power-pages:setup-datamodel` — Create Dataverse tables for dynamic content
- - `/power-pages:add-seo` — Add meta tags, robots.txt, sitemap.xml, favicon
- - `/power-pages:add-tests` — Add unit tests (Vitest) and E2E tests (Playwright)
+ - `/setup-datamodel` — Create Dataverse tables for dynamic content
+ - `/add-seo` — Add meta tags, robots.txt, sitemap.xml, favicon
+ - `/add-tests` — Add unit tests (Vitest) and E2E tests (Playwright)
**Output**: Deployed (or deployment-ready) site with clear next steps
@@ -519,6 +524,7 @@ Mark each task `in_progress` when starting it and `completed` when done via `Tas
### Quality Standards
Every site must meet these standards before completion:
+
- Distinctive typography via Google Fonts (no generic Inter/Roboto/Arial)
- Cohesive color palette via CSS variables
- Motion/animations (page transitions, hover states)
@@ -535,9 +541,11 @@ Every site must meet these standards before completion:
## Example Workflow
### User Request
+
"Create a partner portal for our consultants"
### Phase 1: Discovery
+
- Name: Partner Portal
- Framework: React
- Purpose: Company Portal
@@ -545,12 +553,14 @@ Every site must meet these standards before completion:
- Location: New folder `partner-portal` in current directory
### Phase 2: Scaffold & Launch
+
- React template copied, default placeholders replaced
- Git initialized, npm installed, dev server running at `http://localhost:5173`
- Playwright verified scaffold loads
- URL shared with user — they can preview immediately
### Phase 3: Component Planning
+
- Features: Consultant Directory, Project Tracker, Document Library, Announcements
- Aesthetic: Minimal & Clean
- Mood: Professional & Trustworthy
@@ -558,28 +568,33 @@ Every site must meet these standards before completion:
- Design choices made: DM Sans + Space Grotesk, `#1e3a5f` primary, blue-gray palette
### Phase 4: Plan Approval
+
- Plan presented inline with design & pages + review & deployment sections
- User approved via AskUserQuestion
### Phase 5: Implementation
+
- Todos created for each page, component, routing, navigation, design foundations
- Built in order: design tokens (replace defaults with chosen palette) → shared components → pages → router → nav
- Git commits after each major piece
- Playwright verified each page
### 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 8: Deploy
-- User chose to deploy → invoked `/power-pages:deploy-site`
+
+- User chose to deploy → invoked `/deploy-site`
- Final summary presented with next step suggestions
---
diff --git a/plugins/power-pages/skills/create-webroles/SKILL.md b/plugins/power-pages/skills/create-webroles/SKILL.md
index da275751e..0336eeff1 100644
--- a/plugins/power-pages/skills/create-webroles/SKILL.md
+++ b/plugins/power-pages/skills/create-webroles/SKILL.md
@@ -8,22 +8,6 @@ description: >
user-invocable: true
allowed-tools: Read, Write, Bash, Grep, Glob, AskUserQuestion, Task, TaskCreate, TaskUpdate, TaskList
model: opus
-hooks:
- Stop:
- - hooks:
- - type: command
- command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/create-webroles/scripts/validate-webroles.js"'
- timeout: 15
- - type: prompt
- prompt: >
- If web roles were being created in this session (via /power-pages:create-webroles),
- verify before allowing stop: 1) The .powerpages-site/web-roles/ directory was checked
- for existing roles, 2) New web role YAML files were created with valid UUIDs generated
- by the generate-uuid.js script, 3) All web role files were verified (valid UUIDs, correct
- format, no duplicate flags), 4) The user was asked to deploy the site to apply the
- new roles. If any of these are incomplete, return { "ok": false, "reason": "<specific issues>" }.
- If no web role work happened or everything is complete, return { "ok": true }.
- timeout: 30
---
# Create Web Roles
@@ -59,47 +43,17 @@ Create web roles for a Power Pages code site. Web roles define the permissions a
**Actions**:
-1. Look for the `.powerpages-site/web-roles/` directory in the project root. Use `Glob` to search:
+1. Locate the project root (`**/powerpages.config.json`) and check for `.powerpages-site/web-roles/`.
- ```text
- **/.powerpages-site/web-roles
- ```
-
-2. Also locate the project root by finding `powerpages.config.json`:
-
- ```text
- **/powerpages.config.json
- ```
-
-3. **If `.powerpages-site` folder does NOT exist:**
+2. **If `.powerpages-site` does NOT exist:** Ask the user to deploy first via `AskUserQuestion` (options: "Yes, deploy now (Recommended)", "No, I'll do it later"). If yes, invoke `/deploy-site` then resume from Phase 2. If no, stop.
- The site has not been deployed yet. The `.powerpages-site` folder is created automatically when the site is deployed for the first time using `pac pages upload-code-site`.
-
- Tell the user:
-
- > "The `.powerpages-site` folder was not found. This folder is created when the site is first deployed to Power Pages. I'll deploy your site first, and then we can create web roles."
-
- Use `AskUserQuestion` to confirm:
-
- | Question | Options |
- |----------|---------|
- | Your site needs to be deployed first so the `.powerpages-site` folder is created. Shall I deploy it now? | Yes, deploy now (Recommended), No, I'll do it later |
-
- **If "Yes, deploy now"**: Invoke the `/power-pages:deploy-site` skill to deploy the site. Once deployment completes and `.powerpages-site` is created, resume this workflow from Phase 2.
-
- **If "No, I'll do it later"**: Stop here — the user must deploy first before web roles can be created.
-
-4. **If `.powerpages-site` exists but `web-roles/` subdirectory does NOT exist:**
-
- Create the `web-roles` directory:
+3. **If `.powerpages-site` exists but `web-roles/` does NOT:** Create it:
```powershell
New-Item -ItemType Directory -Path "<PROJECT_ROOT>/.powerpages-site/web-roles" -Force
```
- Proceed to Phase 2.
-
-5. **If both exist:** Proceed to Phase 2.
+4. **If both exist:** Proceed to Phase 2.
**Output**: Confirmed `.powerpages-site/web-roles/` directory exists and is ready
@@ -196,6 +150,7 @@ name: <Role Name>
```
**Rules:**
+
- Only ONE role can have `anonymoususersrole: true`
- Only ONE role can have `authenticatedusersrole: true`
- If an existing role already has one of these flags set to `true`, do not set it again on a new role
@@ -245,6 +200,7 @@ name: <Role Name>
2. Present a summary of what was created:
> "I've created the following new web roles:"
+>
> | Role Name | ID | Anonymous | Authenticated |
> |-----------|-----|-----------|---------------|
> | Content Editors | `a1b2c3d4-...` | false | false |
@@ -258,11 +214,11 @@ name: <Role Name>
4. **If "Yes, deploy now"**: Tell the user to invoke the deploy skill:
- > "Please run `/power-pages:deploy-site` to deploy your site and apply the new web roles."
+ > "Please run `/deploy-site` to deploy your site and apply the new web roles."
5. **If "No, I'll deploy later"**: Acknowledge and remind them:
- > "No problem! Remember to deploy your site using `/power-pages:deploy-site` when you're ready to apply the new web roles to your Power Pages environment."
+ > "No problem! Remember to deploy your site using `/deploy-site` when you're ready to apply the new web roles to your Power Pages environment."
**Output**: Summary presented and deployment offered
diff --git a/plugins/power-pages/skills/create-webroles/scripts/validate-webroles.js b/plugins/power-pages/skills/create-webroles/scripts/validate-webroles.js
index b45fbe507..8c938fb55 100644
--- a/plugins/power-pages/skills/create-webroles/scripts/validate-webroles.js
+++ b/plugins/power-pages/skills/create-webroles/scripts/validate-webroles.js
@@ -3,35 +3,22 @@
// Validates that new web role YAML files were created in .powerpages-site/web-roles/.
// Runs as a Stop hook to verify the skill produced output.
-const fs = require('fs');
const path = require('path');
-const { approve, block, runValidation, findPowerPagesSiteDir, UUID_REGEX } = require('../../../scripts/lib/validation-helpers');
+const { approve, block, runValidation, findPowerPagesSiteDir } = require('../../../scripts/lib/validation-helpers');
+const { validateWebRoles } = require('../../../scripts/lib/web-roles-validator');
runValidation((cwd) => {
const webRolesDir = findPowerPagesSiteDir(cwd, 'web-roles');
if (!webRolesDir) approve(); // No .powerpages-site found — not a web roles session
- const files = fs.readdirSync(webRolesDir).filter(f => f.endsWith('.yml') || f.endsWith('.yaml'));
- if (files.length === 0) {
+ const validation = validateWebRoles(path.resolve(webRolesDir, '..', '..'));
+ const webRoleFiles = validation.webRoles;
+ if (webRoleFiles && webRoleFiles.length === 0) {
block('Web roles validation failed:\n- No web role YAML files found in .powerpages-site/web-roles/');
}
-
- const errors = [];
-
- for (const file of files) {
- const content = fs.readFileSync(path.join(webRolesDir, file), 'utf8');
-
- if (!content.includes('id:')) errors.push(`${file}: missing "id" field`);
- if (!content.includes('name:')) errors.push(`${file}: missing "name" field`);
-
- const idMatch = content.match(/^id:\s*(.+)$/m);
- if (idMatch) {
- const id = idMatch[1].trim();
- if (!UUID_REGEX.test(id)) {
- errors.push(`${file}: invalid UUID format in "id" field: ${id}`);
- }
- }
- }
+ const errors = validation.findings
+ .filter(finding => finding.severity === 'error')
+ .map(finding => finding.filePath ? `${finding.message} (${path.basename(finding.filePath)})` : finding.message);
if (errors.length > 0) {
block('Web roles validation failed:\n- ' + errors.join('\n- '));
diff --git a/plugins/power-pages/skills/deploy-site/SKILL.md b/plugins/power-pages/skills/deploy-site/SKILL.md
index e31f79ab0..5bcb895a0 100644
--- a/plugins/power-pages/skills/deploy-site/SKILL.md
+++ b/plugins/power-pages/skills/deploy-site/SKILL.md
@@ -25,6 +25,7 @@ Guide the user through deploying an existing Power Pages code site to a Power Pa
**Goal**: Ensure PAC CLI is installed and available on the system PATH
**Actions**:
+
1. Create todo list with all 6 phases (see [Progress Tracking](#progress-tracking) table)
2. Run `pac help` to check if the PAC CLI is installed and available on the system PATH.
@@ -44,7 +45,7 @@ Guide the user through deploying an existing Power Pages code site to a Power Pa
dotnet tool install --global Microsoft.PowerApps.CLI.Tool
```
- - If `dotnet` is also not available, direct the user to https://aka.ms/PowerPlatformCLI for full installation instructions including .NET SDK setup.
+ - If `dotnet` is also not available, direct the user to <https://aka.ms/PowerPlatformCLI> for full installation instructions including .NET SDK setup.
3. After installation, verify by running `pac help` again.
4. If it still fails, stop and ask the user to resolve the installation manually.
@@ -58,6 +59,7 @@ Guide the user through deploying an existing Power Pages code site to a Power Pa
**Goal**: Ensure the user is authenticated with PAC CLI and has a valid session
**Actions**:
+
1. Run `pac auth who` to check the current authentication status.
```powershell
@@ -105,6 +107,7 @@ Guide the user through deploying an existing Power Pages code site to a Power Pa
**Goal**: Ensure the user is deploying to the correct target environment
**Actions**:
+
1. Present the current environment information to the user and ask them to confirm.
Use `AskUserQuestion` with the following structure:
@@ -155,7 +158,22 @@ If found in the current working directory or a subdirectory, use that directory
If not found, ask the user to provide the path to the project root.
-### 4.2 Build the Site
+### 4.2 Offer Permissions Audit (Redeployments Only)
+
+If `.powerpages-site` already exists (i.e., this is not the first deployment), table permissions and site settings may have drifted from the code since the last deployment. Offer to audit before deploying.
+
+Use `AskUserQuestion`:
+
+| Question | Header | Options |
+|----------|--------|---------|
+| This site has been deployed before. Would you like to run a permissions audit to verify table permissions match your current code before deploying? | Audit | Yes, audit permissions (Recommended), Skip — permissions are up to date |
+
+**If "Yes"**: Invoke `/audit-permissions` to run the audit. After the audit completes, resume with Step 4.3.
+**If "Skip"**: Proceed to Step 4.3.
+
+If `.powerpages-site` does **not** exist (first deployment), skip this step — there are no existing permissions to audit.
+
+### 4.3 Build the Site
Before uploading, ensure the site is built:
@@ -166,7 +184,7 @@ npm run build
If the build fails, stop and help the user fix the build errors before retrying.
-### 4.3 Upload to Power Pages
+### 4.4 Upload to Power Pages
Run the upload command:
@@ -177,6 +195,7 @@ pac pages upload-code-site --rootPath "<PROJECT_ROOT>"
**If the upload succeeds**: Proceed to Phase 5 to verify the deployment.
**If the upload fails**: Check the error message:
+
- If the failure is related to **blocked JavaScript** (`.js`) attachments → proceed to **Phase 6**
- If the failure mentions **`.html` type attachments are currently blocked** → this is a **misleading error**. See [Troubleshooting: HTML Blocked Attachment Error](#troubleshooting-html-blocked-attachment-error) below
- For other errors → present the error to the user and help them troubleshoot
@@ -193,13 +212,7 @@ pac pages upload-code-site --rootPath "<PROJECT_ROOT>"
### 5.1 Verify `.powerpages-site` Folder
-Confirm the `.powerpages-site` folder was created (first deploy) or still exists:
-
-```powershell
-Get-ChildItem -Path "<PROJECT_ROOT>/.powerpages-site" -ErrorAction SilentlyContinue
-```
-
-List its contents to confirm site configuration files are present (e.g., `web-roles/`, `site-settings/`, `table-permissions/`).
+Confirm `.powerpages-site` exists and list its contents (`web-roles/`, `site-settings/`, `table-permissions/`).
### 5.2 Record Skill Usage
@@ -222,21 +235,17 @@ git commit -m "Deploy site to Power Pages"
### 5.5 Check Activation Status
-Before asking about activation, check whether the site is already activated by running the shared activation status script. This avoids prompting the user unnecessarily when the site is already live.
-
-Run the check-activation-status script, passing the project root (determined in Phase 4.1):
+Run the activation status check:
```powershell
node "${CLAUDE_PLUGIN_ROOT}/scripts/check-activation-status.js" --projectRoot "<PROJECT_ROOT>"
```
-The script reads `siteName` from `powerpages.config.json`, looks up the `websiteRecordId` via `pac pages list`, queries the Power Platform GET websites API, and matches the response against **both** the `websiteRecordId` (exact GUID match) and `name` (case-insensitive). It outputs a JSON result to stdout.
-
-Evaluate the result:
+Evaluate the JSON result:
-- **If `activated` is `true`**: This site is already activated. Inform the user: "Your site **<siteName>** is already activated — no further provisioning needed." If the result includes a `websiteUrl`, show it to the user. Skip to [Suggest Next Steps](#suggest-next-steps). Do NOT ask about activation.
-- **If `activated` is `false`**: This site is not yet activated. Proceed to step 5.5.1.
-- **If `error` is present**: The check could not complete (e.g., Azure CLI not installed, PAC CLI not authenticated, config not found). Fall back to step 5.5.1. Do not block the deployment flow due to a failed activation check.
+- **If `activated` is `true`**: Inform the user their site is already activated (show `websiteUrl` if present). Proceed to step 5.6, then skip to [Suggest Next Steps](#suggest-next-steps). Do NOT ask about activation.
+- **If `activated` is `false`**: Proceed to step 5.5.1.
+- **If `error` is present**: Fall back to step 5.5.1. Do not block the deployment flow.
#### 5.5.1 Ask About Activation (only if site is NOT already activated)
@@ -246,10 +255,37 @@ Ask the user if they want to activate the site using `AskUserQuestion`:
|----------|--------|---------|
| Site deployed successfully! Would you like to activate (provision) the site now so it gets a live URL? | Activate | Activate now (Recommended) — Provision the site with a subdomain and make it live, Skip for now — I'll activate later |
-**If "Activate now"**: Invoke the `/power-pages:activate-site` skill.
+**If "Activate now"**: Invoke the `/activate-site` skill. After activation completes, proceed to step 5.6 to clear the site cache.
**If "Skip for now"**: Suggest next steps (see [Suggest Next Steps](#suggest-next-steps)).
-**Output**: Deployment verified, changes committed, activation offered
+### 5.6 Clear Site Cache (Only If Activated)
+
+After confirming the site is activated (either it was already activated in step 5.5, or the user just activated it in step 5.5.1), offer to clear the runtime cache so the deployed changes are immediately visible.
+
+**Prerequisites**: The site must be activated and the project root must be known (from Phase 4.1).
+
+Use `AskUserQuestion` to confirm before proceeding:
+
+| Question | Header | Options |
+|----------|--------|---------|
+| Would you like to restart the site so your latest changes are immediately visible? This may cause a brief downtime (a few seconds). | Restart | Yes, restart site (Recommended), Skip — I'll restart later |
+
+**If "Skip"**: Skip to [Suggest Next Steps](#suggest-next-steps).
+
+**If "Yes"**: Run the cache-clearing script, passing the project root:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/clear-site-cache.js" --projectRoot "<PROJECT_ROOT>"
+```
+
+The script reads `siteName` from `powerpages.config.json`, looks up the website via the Power Platform admin API, and restarts it to flush the runtime cache.
+
+Evaluate the result:
+
+- **If `success` is `true`**: Inform the user: "Site cache cleared — your latest changes should now be visible at **<websiteUrl>**."
+- **If `success` is `false`**: Warn the user that cache clearing failed and show the error, but do not block the deployment flow. The deployment itself succeeded; cache will eventually refresh on its own. Suggest the user can manually clear cache from the Power Pages admin center if needed.
+
+**Output**: Deployment verified, changes committed, activation offered, cache cleared
---
@@ -351,15 +387,21 @@ If the retry succeeds, proceed to Phase 5. If it fails with a different error, p
## Suggest Next Steps
If 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, favicon
+
+- `/activate-site` — Provision the site with a subdomain and make it live (if not already activated)
+- `/test-site` — Test the deployed site in the browser (verify pages load, check API calls)
+- `/audit-permissions` — Audit table permissions against current code (recommended after redeployments)
+- `/setup-datamodel` — Create Dataverse tables for dynamic content
+- `/add-seo` — Add meta tags, robots.txt, sitemap.xml, favicon
---
## Important Notes
+### NEVER Use `pac pages upload`
+
+Always use `pac pages upload-code-site` — **never** use `pac pages upload`. The `pac pages upload` command is designed for portal-studio-style sites and will corrupt code site metadata if used on a code site project. This applies to every upload step in this skill (Phase 4.4, Phase 6.4, and troubleshooting retries).
+
### Throughout All Phases
- **Use TaskCreate/TaskUpdate** to track progress at every phase
@@ -370,9 +412,10 @@ If the user skips activation (or after activation completes), suggest:
1. After Phase 2: If not authenticated, get environment URL from user
2. At Phase 3: Confirm or switch the target environment
-3. At Phase 4: If multiple `powerpages.config.json` found, ask which project to deploy
-4. At Phase 5: Activate site now or later
-5. At Phase 6: Get permission before modifying blocked attachments setting
+3. At Phase 4.1: If multiple `powerpages.config.json` found, ask which project to deploy
+4. At Phase 4.2: Audit permissions now or skip (redeployments only)
+5. At Phase 5.5: Activate site now or later
+6. At Phase 6: Get permission before modifying blocked attachments setting
### Progress Tracking
diff --git a/plugins/power-pages/skills/integrate-webapi/SKILL.md b/plugins/power-pages/skills/integrate-webapi/SKILL.md
index db47f99eb..9162103b1 100644
--- a/plugins/power-pages/skills/integrate-webapi/SKILL.md
+++ b/plugins/power-pages/skills/integrate-webapi/SKILL.md
@@ -11,26 +11,6 @@ description: >
user-invocable: true
allowed-tools: Read, Write, Edit, Bash, Grep, Glob, AskUserQuestion, Task, TaskCreate, TaskUpdate, TaskList
model: opus
-hooks:
- Stop:
- - hooks:
- - type: command
- command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/integrate-webapi/scripts/validate-webapi-integration.js"'
- timeout: 15
- - type: prompt
- prompt: >
- If Web API integration was being performed in this session (via /power-pages:integrate-webapi),
- verify before allowing stop: 1) The site was analyzed and tables requiring Web API integration
- were identified, 2) The webapi-integration agent was invoked to create API client, types, and
- service files for each table, 3) All integration files were verified (types, services, hooks exist)
- 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
---
# Integrate Web API
@@ -45,8 +25,9 @@ Integrate Power Pages Web API into a code site's frontend. This skill orchestrat
- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.
> **Prerequisites:**
-> - An existing Power Pages code site created via `/power-pages:create-site`
-> - A Dataverse data model (tables/columns) already set up via `/power-pages:setup-datamodel` or created manually
+>
+> - An existing Power Pages code site created via `/create-site`
+> - A Dataverse data model (tables/columns) already set up via `/setup-datamodel` or created manually
> - The site must be deployed at least once (`.powerpages-site` folder must exist) for permissions setup
**Initial request:** $ARGUMENTS
@@ -61,7 +42,7 @@ Integrate Power Pages Web API into a code site's frontend. This skill orchestrat
4. **Implement Integrations** — Use the `webapi-integration` agent for each table
5. **Verify Integrations** — Validate all expected files exist and the project builds successfully
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 names
-7. **Review & Deploy** — Ask the user to deploy the site and invoke `/power-pages:deploy-site` if confirmed
+7. **Review & Deploy** — Ask the user to deploy the site and invoke `/deploy-site` if confirmed
---
@@ -79,7 +60,7 @@ Look for `powerpages.config.json` in the current directory or immediate subdirec
Get-ChildItem -Path . -Filter "powerpages.config.json" -Recurse -Depth 1
```
-**If not found**: Tell the user to create a site first with `/power-pages:create-site`.
+**If not found**: Tell the user to create a site first with `/create-site`.
### 1.2 Read Existing Config
@@ -174,6 +155,7 @@ From the Explore agent's findings, compile a list of tables needing integration:
### 3.1 Present Findings
Show the user:
+
1. The tables that were identified for Web API integration
2. For each table: which files reference it, what operations are needed
3. Whether a shared API client already exists or needs to be created
@@ -206,6 +188,7 @@ For each table, use the `Task` tool to invoke the `webapi-integration` agent at
**Prompt template for the agent:**
> "Integrate Power Pages Web API for the **[Table Display Name]** table.
+>
> - Table logical name: `[logical_name]`
> - Entity set name: `[entity_set_name]`
> - Operations needed: [read/create/update/delete]
@@ -228,6 +211,7 @@ If there is only one table, this step is simply sequential.
### 4.3 Verify Each Integration
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
@@ -254,11 +238,13 @@ git commit -m "Add Web API integration for [table names]"
### 5.1 Verify File Inventory
For each integrated table, confirm the following files exist:
+
- **Type definition** in `src/types/` (e.g., `src/types/product.ts`)
- **Service file** in `src/shared/services/` or `src/services/` (e.g., `productService.ts`)
- **Framework-specific hook/composable** (e.g., `src/shared/hooks/useProducts.ts` for React, `src/composables/useProducts.ts` for Vue)
Also verify:
+
- **Shared API client** at `src/shared/powerPagesApi.ts` exists
- Each service file references `/_api/` endpoints
- Each service file imports from the shared API client
@@ -272,6 +258,7 @@ npm run build
```
If the build fails, fix the issues before proceeding. Common issues:
+
- Missing imports between generated files
- Type mismatches between service and type definitions
- Framework-specific compilation errors
@@ -307,7 +294,7 @@ Use `AskUserQuestion`:
|----------|---------|
| 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 "Yes, deploy now"**: Invoke `/deploy-site` first, then resume this phase.
**If "Skip"**: Skip to Phase 7 with a note that permissions and site settings still need to be configured.
@@ -336,7 +323,7 @@ If the user chooses to upload an existing diagram:
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**
+ - **Site settings**: `Webapi/<table>/enabled` and `Webapi/<table>/fields` — **CRITICAL: fields normally list specific column logical names; only use `*` when the site relies on aggregate OData queries (`$apply`/aggregate) that otherwise fail with 403**
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.
@@ -369,6 +356,7 @@ Use the `Task` tool to invoke the `table-permissions-architect` agent at `${CLAU
> "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."
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`
@@ -384,6 +372,7 @@ Use the `Task` tool to invoke the `webapi-settings-architect` agent at `${CLAUDE
> "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
@@ -415,7 +404,10 @@ For each table permission in the plan. Process **parent permissions before child
**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]
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "Global" [--read] [--create] [--write] [--delete] [--append] [--appendto]
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "Contact" --contactRelationshipName "<lookup_to_contact>" [--read] [--create] [--write] [--delete] [--append] [--appendto]
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "Account" --accountRelationshipName "<lookup_to_account>" [--read] [--create] [--write] [--delete] [--append] [--appendto]
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" --projectRoot "<PROJECT_ROOT>" --permissionName "<Permission Name>" --tableName "<table_logical_name>" --webRoleIds "<uuid1,uuid2>" --scope "Self" [--read] [--create] [--write] [--delete] [--append] [--appendto]
```
**For Parent scope** (requires parent permission UUID and relationship name):
@@ -448,7 +440,9 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJ
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.
+**Important**: The `--value` for fields settings MUST use exact Dataverse LogicalNames (case-sensitive, all lowercase) for normal CRUD/read scenarios. Using incorrect casing causes 403 Forbidden errors.
+
+**Aggregate exception**: If the site uses aggregate OData queries (`$apply`, `aggregate`, grouped totals, etc.), set `Webapi/<table>/fields` to `*`. Power Pages rejects some aggregate queries with 403 unless wildcard field access is enabled.
**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.
@@ -499,18 +493,18 @@ Use `AskUserQuestion`:
|----------|---------|
| The Web API integration and permissions are ready. To make everything live, the site needs to be deployed. Would you like to deploy now? | Yes, deploy now (Recommended), No, I'll deploy later |
-**If "Yes, deploy now"**: Invoke the `/power-pages:deploy-site` skill to deploy the site.
+**If "Yes, deploy now"**: Invoke the `/deploy-site` skill to deploy the site.
**If "No, I'll deploy later"**: Acknowledge and remind:
-> "No problem! Remember to deploy your site using `/power-pages:deploy-site` when you're ready. The Web API calls will not work until the site is deployed with the new permissions."
+> "No problem! Remember to deploy your site using `/deploy-site` when you're ready. The Web API calls will not work until the site is deployed with the new permissions."
### 7.4 Post-Deploy Notes
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. 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).
+- **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). If the failing request uses aggregate OData (`$apply`, `aggregate`, grouped totals), also verify `Webapi/<table>/fields` is set to `*`.
- **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
@@ -535,7 +529,7 @@ After deployment (or if skipped), remind the user:
3. 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 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
+6. At Phase 7.2: Deploy now or deploy later
### Progress Tracking
diff --git a/plugins/power-pages/skills/integrate-webapi/scripts/validate-webapi-integration.js b/plugins/power-pages/skills/integrate-webapi/scripts/validate-webapi-integration.js
index 354d0bf25..515989fea 100644
--- a/plugins/power-pages/skills/integrate-webapi/scripts/validate-webapi-integration.js
+++ b/plugins/power-pages/skills/integrate-webapi/scripts/validate-webapi-integration.js
@@ -6,6 +6,7 @@
const fs = require('fs');
const path = require('path');
const { approve, block, runValidation, findProjectRoot } = require('../../../scripts/lib/validation-helpers');
+const { validatePowerPagesSchema } = require('../../../scripts/lib/powerpages-schema-validator');
runValidation((cwd) => {
const projectRoot = findProjectRoot(cwd);
@@ -39,6 +40,15 @@ runValidation((cwd) => {
errors.push('No type definition files found in src/types/ — services should have corresponding type definitions');
}
+ const schemaValidation = validatePowerPagesSchema(projectRoot);
+ const schemaErrors = schemaValidation.findings
+ .filter(finding => finding.severity === 'error')
+ .map(finding => finding.filePath ? `${finding.message} (${path.basename(finding.filePath)})` : finding.message);
+
+ if (schemaErrors.length > 0) {
+ errors.push('Invalid Power Pages permissions/site-settings schema:\n - ' + schemaErrors.join('\n - '));
+ }
+
if (errors.length > 0) {
block('Web API integration validation failed:\n- ' + errors.join('\n- '));
}
diff --git a/plugins/power-pages/skills/setup-auth/SKILL.md b/plugins/power-pages/skills/setup-auth/SKILL.md
index 8592bc6be..4ddab5636 100644
--- a/plugins/power-pages/skills/setup-auth/SKILL.md
+++ b/plugins/power-pages/skills/setup-auth/SKILL.md
@@ -11,24 +11,6 @@ description: >
user-invocable: true
allowed-tools: Read, Write, Edit, Bash, Grep, Glob, AskUserQuestion, Task, TaskCreate, TaskUpdate, TaskList, Skill
model: opus
-hooks:
- Stop:
- - hooks:
- - type: command
- command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/scripts/validate-auth.js"'
- timeout: 15
- - type: prompt
- prompt: >
- If authentication/authorization was being set up in this session (via /power-pages:setup-auth),
- verify before allowing stop: 1) The site was found and framework detected, 2) An auth service
- file was created (authService.ts/js) with login/logout functions, 3) PowerPages type declarations
- were created (powerPages.d.ts), 4) Authorization utilities were created (authorization.ts/js)
- with role-checking functions, 5) Auth UI component was created (AuthButton or equivalent),
- 6) All auth files were verified (exist, contain expected exports, project builds successfully),
- 7) The user was asked whether to deploy the site.
- If any of these are incomplete, return { "ok": false, "reason": "<specific issues>" }.
- If no auth setup work happened or everything is complete, return { "ok": true }.
- timeout: 30
---
# Set Up Authentication & Authorization
@@ -44,9 +26,10 @@ Configure authentication (login/logout via Microsoft Entra ID) and role-based au
**Initial request:** $ARGUMENTS
> **Prerequisites:**
-> - An existing Power Pages code site created via `/power-pages:create-site`
+>
+> - An existing Power Pages code site created via `/create-site`
> - The site must be deployed at least once (`.powerpages-site` folder must exist)
-> - Web roles must be created via `/power-pages:create-webroles`
+> - Web roles must be created via `/create-webroles`
## Workflow
@@ -75,7 +58,7 @@ Look for `powerpages.config.json` in the current directory or immediate subdirec
**/powerpages.config.json
```
-**If not found**: Tell the user to create a site first with `/power-pages:create-site`.
+**If not found**: Tell the user to create a site first with `/create-site`.
#### 1.2 Detect Framework
@@ -99,7 +82,7 @@ Use `AskUserQuestion`:
|----------|---------|
| Your site needs to be deployed first. Would you like to deploy now? | Yes, deploy now (Recommended), No, I'll do it later |
-**If "Yes, deploy now"**: Invoke `/power-pages:deploy-site`, then resume.
+**If "Yes, deploy now"**: Invoke `/deploy-site`, then resume.
**If "No"**: Stop — the site must be deployed first.
@@ -119,7 +102,7 @@ Read each file and compile a list of existing web roles (name, id, flags).
|----------|---------|
| No web roles were found. Web roles are required for role-based authorization. Would you like to create them now? | Yes, create web roles first (Recommended), Skip — I'll add roles later |
-**If "Yes"**: Invoke `/power-pages:create-webroles`, then resume.
+**If "Yes"**: Invoke `/create-webroles`, then resume.
**If "Skip"**: Continue — auth service and login/logout will still work, but role-based authorization will need roles created later.
@@ -281,19 +264,23 @@ Create `src/utils/authorization.ts` with:
Based on the detected framework:
**React:**
+
- `src/components/RequireAuth.tsx` — renders children only for authenticated users, optional login prompt fallback
- `src/components/RequireRole.tsx` — renders children only for users with specified roles, supports `requireAll` mode
- `src/hooks/useAuthorization.ts` — hook returning `{ roles, hasRole, hasAnyRole, hasAllRoles, isAuthenticated, isAdmin }`
**Vue:**
+
- `src/composables/useAuthorization.ts` — composable with computed roles and role-checking functions
- `src/directives/vRole.ts` — `v-role` directive for declarative role-based visibility
**Angular:**
+
- `src/app/guards/auth.guard.ts` — `CanActivateFn` with route data for required roles
- `src/app/directives/has-role.directive.ts` — structural directive `*appHasRole="'RoleName'"`
**Astro:**
+
- `src/utils/authorization.ts` only (use directly in component scripts)
#### 4.3 Security Reminder
@@ -303,7 +290,7 @@ Add a comment at the top of the authorization utilities:
```typescript
// IMPORTANT: Client-side authorization is for UX only, not security.
// Server-side table permissions enforce actual access control.
-// Always configure table permissions via /power-pages:integrate-webapi.
+// Always configure table permissions via /integrate-webapi.
```
### Output
@@ -330,6 +317,7 @@ Based on the detected framework, create a login/logout button component:
- **Astro**: `src/components/AuthButton.astro`
The component should:
+
- Show a "Sign In" button when the user is not authenticated
- Show the user's display name, avatar (initials-based), and a "Sign Out" button when authenticated
- Include a loading state while checking auth status
@@ -383,6 +371,7 @@ Present findings to the user and confirm which areas to protect.
Based on the user's choices, wrap the appropriate components:
**React example:**
+
```tsx
<RequireAuth fallback={<p>Please sign in to view this content.</p>}>
<Dashboard />
@@ -394,6 +383,7 @@ Based on the user's choices, wrap the appropriate components:
```
**Vue example:**
+
```vue
<div v-role="'Administrators'">
<AdminPanel />
@@ -401,6 +391,7 @@ Based on the user's choices, wrap the appropriate components:
```
**Angular example:**
+
```typescript
{ path: 'admin', component: AdminComponent, canActivate: [authGuard, roleGuard], data: { roles: ['Administrators'] } }
```
@@ -431,6 +422,7 @@ git commit -m "Add role-based access control to site components"
#### 7.1 Verify File Inventory
Confirm the following files were created:
+
- `src/types/powerPages.d.ts` — Power Pages type declarations
- `src/services/authService.ts` — Auth service with login/logout functions
- Framework-specific auth hook/composable (e.g., `src/hooks/useAuth.ts` for React)
@@ -439,6 +431,7 @@ Confirm the following files were created:
- Auth button component (e.g., `src/components/AuthButton.tsx` for React)
Read each file and verify it contains the expected exports and functions:
+
- Auth service: `login`, `logout`, `getCurrentUser`, `isAuthenticated`, `fetchAntiForgeryToken`
- Authorization utils: `hasRole`, `hasAnyRole`, `hasAllRoles`, `getUserRoles`
@@ -461,6 +454,7 @@ npm run dev
```
Use Playwright to navigate to the site and take a snapshot to confirm the auth button is visible:
+
- Navigate to `http://localhost:<port>`
- Take a browser snapshot
- Verify the auth button (Sign In / mock user) appears in the navigation area
@@ -527,11 +521,11 @@ Use `AskUserQuestion`:
|----------|---------|
| Authentication and authorization are configured. To make login work, the site needs to be deployed. Would you like to deploy now? | Yes, deploy now (Recommended), No, I'll deploy later |
-**If "Yes, deploy now"**: Invoke `/power-pages:deploy-site`.
+**If "Yes, deploy now"**: Invoke `/deploy-site`.
**If "No"**: Remind the user:
-> "Remember to deploy your site using `/power-pages:deploy-site` when you're ready. Authentication will not work until the site is deployed with the new site settings."
+> "Remember to deploy your site using `/deploy-site` when you're ready. Authentication will not work until the site is deployed with the new site settings."
#### 8.5 Post-Deploy Notes
@@ -540,7 +534,7 @@ After deployment (or if skipped), remind the user:
- **Test on deployed site**: Auth only works on the deployed Power Pages site, not on `localhost`
- **Entra ID configuration**: The site's identity provider must be configured in the Power Pages admin center to use Microsoft Entra ID
- **Assign web roles**: Users must be assigned appropriate web roles in the Power Pages admin center
-- **Table permissions**: Client-side auth checks are for UX only — configure server-side table permissions via `/power-pages:integrate-webapi` for actual data security
+- **Table permissions**: Client-side auth checks are for UX only — configure server-side table permissions via `/integrate-webapi` for actual data security
- **Local development**: The auth service includes mock data for testing on localhost — remove or disable before production
### Output
diff --git a/plugins/power-pages/skills/setup-auth/references/authorization-reference.md b/plugins/power-pages/skills/setup-auth/references/authorization-reference.md
index e7e1a0820..2ca9a9948 100644
--- a/plugins/power-pages/skills/setup-auth/references/authorization-reference.md
+++ b/plugins/power-pages/skills/setup-auth/references/authorization-reference.md
@@ -9,7 +9,7 @@ Create `src/utils/authorization.ts`:
```typescript
// IMPORTANT: Client-side authorization is for UX only, not security.
// Server-side table permissions enforce actual access control.
-// Always configure table permissions via /power-pages:integrate-webapi.
+// Always configure table permissions via /integrate-webapi.
import { getCurrentUser, isAuthenticated as checkAuthenticated } from '../services/authService';
@@ -360,5 +360,5 @@ export class HasRoleDirective {
- The `window.Microsoft.Dynamic365.Portal.User.userRoles` array is set by the server and cannot be modified by the client in a way that affects server-side checks.
- However, hiding a UI element does NOT prevent a user from calling the underlying API directly.
-- **Always configure server-side table permissions** to enforce data access control. Use `/power-pages:integrate-webapi` to set up proper table permissions and site settings.
+- **Always configure server-side table permissions** to enforce data access control. Use `/integrate-webapi` to set up proper table permissions and site settings.
- Test both: verify the UI shows/hides correctly AND verify direct API calls respect table permissions.
diff --git a/plugins/power-pages/skills/setup-datamodel/SKILL.md b/plugins/power-pages/skills/setup-datamodel/SKILL.md
index 062905e8f..d3168daaa 100644
--- a/plugins/power-pages/skills/setup-datamodel/SKILL.md
+++ b/plugins/power-pages/skills/setup-datamodel/SKILL.md
@@ -9,20 +9,6 @@ description: >
user-invocable: true
allowed-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
-hooks:
- Stop:
- - hooks:
- - type: command
- command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/setup-datamodel/scripts/validate-datamodel.js"'
- timeout: 30
- - type: prompt
- prompt: >
- If a Dataverse data model was being set up in this session (via /power-pages:setup-datamodel),
- verify before allowing stop: 1) A data model was obtained (either the data-model-architect agent
- was invoked OR the user uploaded an existing ER diagram that was parsed), 2) The user approved
- the proposal, 3) All approved tables were created, 4) A summary was presented.
- If incomplete, return { "ok": false, "reason": "<specific issues>" }. Otherwise return { "ok": true }.
- timeout: 30
---
# Set Up Dataverse Data Model
@@ -44,6 +30,7 @@ Guide the user through creating Dataverse tables, columns, and relationships for
**Goal**: Confirm PAC CLI authentication, acquire an Azure CLI token, and verify API access
**Actions**:
+
1. Create todo list with all 8 phases (see [Progress Tracking](#progress-tracking) table)
2. Follow the prerequisite steps in `${CLAUDE_PLUGIN_ROOT}/references/dataverse-prerequisites.md` to verify PAC CLI auth, acquire an Azure CLI token, and confirm API access. Store the environment URL as `$envUrl`.
@@ -56,6 +43,7 @@ Guide the user through creating Dataverse tables, columns, and relationships for
**Goal**: Determine whether the user will upload an existing ER diagram or let AI analyze the site
**Actions**:
+
1. Ask the user how they want to define the data model using the `AskUserQuestion` tool:
**Question**: "How would you like to define the data model for your site?"
@@ -101,6 +89,7 @@ If the user chooses to let the Data Model Architect figure it out, proceed to **
**Goal**: Spawn the data-model-architect agent to autonomously analyze the site and propose a data model
**Actions**:
+
1. Use the `Task` tool to spawn the `data-model-architect` agent. This agent autonomously:
- Analyzes the site's source code to infer data requirements
- Queries existing Dataverse tables via OData GET requests
@@ -338,6 +327,7 @@ Present a summary to the user:
| `cr123_task` (Task) | Created | 4 columns | 1 relationship |
Include:
+
- Total tables created/modified/reused/failed
- Total columns created/skipped/failed
- Total relationships created/failed
@@ -347,11 +337,12 @@ Include:
### 8.6 Suggest Next Steps
After the summary, suggest:
+
- Review created tables in the Power Pages maker portal
-- Populate tables with sample data for testing: `/power-pages:add-sample-data`
-- Integrate tables with your site's frontend via Web API: `/power-pages:integrate-webapi`
-- If the site is not yet built: `/power-pages:create-site`
-- If the site is ready to deploy: `/power-pages:deploy-site`
+- Populate tables with sample data for testing: `/add-sample-data`
+- Integrate tables with your site's frontend via Web API: `/integrate-webapi`
+- If the site is not yet built: `/create-site`
+- If the site is ready to deploy: `/deploy-site`
**Output**: Published customizations, verified tables, manifest written, summary presented
diff --git a/plugins/power-pages/skills/test-site/SKILL.md b/plugins/power-pages/skills/test-site/SKILL.md
index 0c0cdbd48..2d87d0559 100644
--- a/plugins/power-pages/skills/test-site/SKILL.md
+++ b/plugins/power-pages/skills/test-site/SKILL.md
@@ -10,31 +10,13 @@ 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.
+> **Prerequisite:** This skill expects a deployed and activated Power Pages site. Run `/deploy-site` and `/activate-site` first if the site is not yet live.
## Core Principles
@@ -60,6 +42,7 @@ Create the full task list with all 6 phases before starting any work (see [Progr
#### 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.
@@ -81,7 +64,7 @@ If no URL was provided, attempt auto-detection:
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 `activated` is `false`**: Inform the user: "Your site is not yet activated. Please run `/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
@@ -90,7 +73,7 @@ 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) |
+| 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 `/activate-site` to get your site URL, or check the Power Platform admin center) |
Store the user-provided URL as `SITE_URL`.
@@ -159,6 +142,7 @@ Set the browser to a standard desktop viewport:
#### 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
@@ -173,6 +157,7 @@ If a private site gate is detected, use `AskUserQuestion`:
| 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."
@@ -181,11 +166,13 @@ If a private site gate is detected, use `AskUserQuestion`:
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
@@ -193,6 +180,7 @@ After the homepage is loaded (either directly for public sites, or after passing
#### 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.
@@ -205,16 +193,25 @@ If site-level authentication indicators are detected (login links in navigation,
| 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.
+3. Create an additional task for testing authenticated scenarios using `TaskCreate`:
+
+ | Task subject | activeForm | Description |
+ |-------------|------------|-------------|
+ | Test authenticated pages and APIs | Testing authenticated scenarios | Re-crawl site as logged-in user, verify auth-gated pages load and authenticated API calls succeed |
**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.
+- Do **not** create the authenticated testing task.
- Continue to Phase 4.
**If "Cancel testing"**:
+
- Stop the skill and inform the user they can re-run it after resolving authentication.
### Output
@@ -222,6 +219,7 @@ If site-level authentication indicators are detected (login links in navigation,
- Authentication status resolved for both layers:
- Private site gate: passed, not needed, or cancelled
- Site-level auth: logged in, skipped, or not needed
+- If authenticated: additional task created for authenticated testing in Phase 5.6
---
@@ -271,6 +269,7 @@ For each discovered URL, in sequence:
#### 4.4 Record Page Test Results
Build a results list tracking:
+
- URL tested
- Load status (Pass / Fail)
- Number of console errors
@@ -295,6 +294,7 @@ Build a results list tracking:
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.
@@ -325,7 +325,7 @@ For each captured API request, evaluate:
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."
+- **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). If the failing request uses aggregate OData (`$apply`, `aggregate`, grouped totals), set `Webapi/<tablename>/fields` to `*`.\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."
@@ -338,12 +338,13 @@ If forms are detected on any page (via `browser_snapshot` showing form elements)
| 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.
+**If "Skip"**: Continue to Phase 5.6 (or Phase 6 if no authenticated testing task was created).
### Output
@@ -353,6 +354,59 @@ If forms are detected on any page (via `browser_snapshot` showing form elements)
---
+### 5.6 Test Authenticated Scenarios (Only If User Logged In)
+
+> Skip this step entirely if the user chose "Skip authenticated pages" in Phase 3.5, or if no site-level authentication was detected in Phase 3.3.
+
+**Goal:** Re-crawl the site as an authenticated user to discover and test pages and API calls that are only available after login.
+
+Mark the "Test authenticated pages and APIs" task as `in_progress`.
+
+#### 5.6.1 Discover Authenticated Pages
+
+After login, the site navigation may show additional links that were hidden or restricted for anonymous users (e.g., profile pages, dashboards, admin panels, account management).
+
+1. Navigate back to `SITE_URL` (homepage).
+2. Use `browser_snapshot` to capture the authenticated navigation.
+3. Use `browser_evaluate` (same link extraction script as Phase 4.1) to discover internal links.
+4. Compare against the links already tested in Phase 4. Identify any **new links** that were not visible before authentication.
+
+If new links are found, inform the user:
+> "Found **X** additional pages visible after login that were not accessible anonymously. Testing each page..."
+
+#### 5.6.2 Test Authenticated Pages
+
+For each newly discovered link, follow the same test procedure as Phase 4.2:
+
+1. Navigate, wait, snapshot, check for errors, capture console errors.
+2. Record results separately as **authenticated page tests**.
+3. Respect the same 25-page cap (counting pages already tested in Phase 4).
+
+#### 5.6.3 Test Authenticated API Calls
+
+For each authenticated page that makes `/_api/` requests:
+
+1. Use `browser_network_requests` with **includeStatic: false** to capture API calls.
+2. Compare against API calls captured in Phase 5 — identify any **new endpoints** or endpoints that previously returned 401/403 and now succeed.
+3. Analyze responses using the same criteria as Phase 5.3.
+
+#### 5.6.4 Record Results
+
+Record authenticated test results separately so Phase 6 can report them in a distinct section:
+
+- Authenticated pages discovered and tested (count, pass/fail)
+- Authenticated API calls (count, pass/fail, any endpoints that changed from fail to pass after login)
+
+Mark the "Test authenticated pages and APIs" task as `completed`.
+
+### Output
+
+- Authenticated pages crawled and tested
+- Authenticated API endpoints captured and analyzed
+- Results recorded separately for the test report
+
+---
+
## Phase 6: Generate Test Report
**Goal:** Present a comprehensive summary of all test results and suggest next steps.
@@ -398,42 +452,75 @@ 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
+#### 6.4 Present Authenticated Test Results (If Applicable)
+
+If Phase 5.6 was executed, present results in separate tables:
+
+```
+## Authenticated Page Test Results
+
+| # | URL | Status | Console Errors | Notes |
+|---|-----|--------|----------------|-------|
+| 1 | /profile | Pass | 0 | User profile loaded |
+| 2 | /dashboard | Pass | 1 | Minor JS warning |
+| 3 | /admin/settings | Fail | 0 | 403 Forbidden — insufficient web role |
+
+Authenticated pages tested: 3 | Passed: 2 | Failed: 1
+```
+
+```
+## Authenticated API Test Results
+
+| # | Endpoint | Method | Status | Notes |
+|---|----------|--------|--------|-------|
+| 1 | /_api/cr4fc_orders | GET | 200 OK | Previously 403 — now accessible after login |
+| 2 | /_api/cr4fc_userprofiles | GET | 200 OK | Only visible after auth |
+
+Authenticated API endpoints tested: 2 | Passed: 2 | Failed: 0
+```
+
+If no additional pages or APIs were discovered after login, note: "No additional pages or API endpoints were found after authentication. The authenticated user sees the same content as an anonymous visitor."
+
+#### 6.5 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 |
+| Category | Tested | Passed | Failed | Warnings |
+|--------------------------|--------|--------|--------|----------|
+| Pages (public) | 4 | 3 | 1 | 0 |
+| Pages (authenticated) | 3 | 2 | 1 | 0 |
+| API Endpoints (public) | 3 | 2 | 1 | 0 |
+| API Endpoints (auth) | 2 | 2 | 0 | 0 |
+| Console Errors | — | — | — | 2 |
Overall: X/Y checks passed
```
-#### 6.5 Present Recommendations
+If authenticated testing was skipped, omit the authenticated rows from the table.
+
+#### 6.6 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
+- **Table permissions issues** → `/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`
+- **Authentication issues** → `/setup-auth`
+- **Missing endpoints** → Verify table exists in Dataverse via `/setup-datamodel`
- **Server errors** → Enable `Webapi/error/innererror` site setting for diagnostics
-#### 6.6 Close Browser
+#### 6.7 Close Browser
- Use `browser_close` to clean up the browser session.
-#### 6.7 Suggest Next Steps
+#### 6.8 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
+- If API failures were found: `/integrate-webapi` — Fix Web API site settings and table permissions
+- If authentication issues: `/setup-auth` — Configure authentication providers
+- If pages had errors: Review the site code and redeploy with `/deploy-site`
+- If all tests passed: Site is working correctly! Consider `/add-seo` for search engine optimization
### Output
@@ -455,7 +542,7 @@ Based on the test results, suggest relevant skills:
### Key Decision Points
-1. **Phase 1.3**: If the site is not activated, stop and redirect to `/power-pages:activate-site`
+1. **Phase 1.3**: If the site is not activated, stop and redirect to `/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