Skip to content

microsoft/power-platform-skills / plugins/power-pages/skills/migrate-datamodel

migrate-datamodel

Verified

This skill should be used when the user asks to "migrate to enhanced data model", "migrate from standard to enhanced", "switch to EDM", "migrate SDM to EDM", "upgrade data model", "migrate site data model", or wants to migrate an existing Power Pages site from the Standard Data Model (SDM) to the Enhanced Data Model (EDM) using PAC CLI.

---
name: migrate-datamodel
description: >-
  This skill should be used when the user asks to "migrate to enhanced data model",
  "migrate from standard to enhanced", "switch to EDM", "migrate SDM to EDM",
  "upgrade data model", "migrate site data model", or wants to migrate an existing
  Power Pages site from the Standard Data Model (SDM) to the Enhanced Data Model (EDM)
  using PAC CLI.
user-invocable: true
argument-hint: Optional site name or WebSiteId GUID
allowed-tools: Read, Bash, Glob, Grep, AskUserQuestion, Skill, TaskCreate, TaskUpdate, TaskList
model: sonnet
---

> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.

> **Plugin check**: Run `node "${CLAUDE_PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.

# Migrate Power Pages Site from Standard to Enhanced Data Model

Guide the user through a comprehensive migration of an existing Power Pages site from the Standard Data Model (SDM) to the Enhanced Data Model (EDM). The skill is organized into **four high-level phases** — Site Discovery & Pre-checks, Customization Remediation, Migration Execution, and Post-Migration Validation. Each phase contains numbered sub-steps for granular execution and progress tracking.

> **Important:** This is a preview feature. EDM migration behavior may change before GA.

## Core Principles

- **Environment-aware**: Capture environment type (Dev/Test/UAT/Prod) for context and future ALM integration
- **Remediate before migrate**: Identify and fix customizations before executing the data model migration
- **Validate comprehensively**: Check CLI context, site discovery, dependencies, and templates before any execution
- **Confirm before executing**: Present all migration parameters and customization findings to user before proceeding
- **Track all operations**: Generate comprehensive reports documenting all commands, results, and fixes applied
- **Graceful failure**: Halt on blocking issues; guide user to support when needed

**Supported templates:** All Power Pages and D365 portal templates can be migrated, provided the corresponding V2 EDM solution is installed in the environment (see step 1.6). This includes Starter Layouts 1–5, Application Processing, Blank Page, Program Registration, Schedule and Manage Meetings, FAQ, Event Registration, and the D365 portal templates (Community, Customer Self-Service, Employee Self-Service, Partner).

> **PAC CLI version note:** Migration of D365 portal templates requires a recent PAC CLI build. Older builds may still reject these templates.

**Initial request:** $ARGUMENTS

---

## Live Execution Report

Throughout this skill, progress is mirrored to two files inside `<OUTPUT_DIR>`:

- `migration-state.json` — single source of truth for current state
- `datamodel-migration-report.html` — auto-regenerated from state after every update; user opens in browser to watch progress

**Init point.** At the end of step 1.3, when the parent output directory, WebSiteId, environment name/URL, and website slug are known, run once:

```text
node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/update-state.js" --init --output-dir "<PARENT_OUTPUT_DIR>" --website-id "<WEBSITE_ID>" --env-name "<ENV_NAME>" --env-url "<ENV_URL>" --slug "<URL_SLUG>"
```

Capture the printed migration subfolder as `<MIGRATION_OUTPUT_DIR>` (also called `<OUTPUT_DIR>` below); the init argument is its **parent**, not the migration subfolder itself. After init, each sub-step below ends with a **→ Update report** callout. Execute each as a `node update-state.js --output-dir "<OUTPUT_DIR>" <args>` call. The CLI accepts:

| Command | Use |
|---|---|
| `--set-step <id> --status <s> --output "<text>"` | Mark sub-step status + write its output line (status: `pending`/`in-progress`/`completed`/`blocked`) |
| `--set-phase <n> --status <s>` | Mark phase status (`pending`/`in-progress`/`completed`/`blocked`) |
| `--set-site '<json>'` | Update site card fields. Allowed keys: `name`, `portalId`, `slug`, `currentDataModel`, `template`, `environment`, `migrationMode`, `siteRoot` |
| `--set-approval <phaseId> <kind>` | Show approval banner; `kind` ∈ {`phase-start`, `in-phase`} |
| `--clear-approval` | Hide approval banner once user has approved (use only for in-phase gates that don't advance to a new phase) |
| `--approve-and-start <phaseId>` | Atomic: clear approval gate + mark phase in-progress in one render. Use this whenever the user answers a `phase-start` AskUserQuestion approval — avoids the transient "Awaiting Approval" pill that would otherwise flash between `--clear-approval` and `--set-phase`. |
| `--set-input '<json>'` / `--clear-input` | Show/clear a report-wide **Your input is needed** notification. JSON requires `requiredAction`; optional `responseLocation` explains where to respond (defaults to the migration conversation). Does not approve or replace a migration gate. |
| `--set-prompt <plugin\|dme> --status ready --path "<file>" --summary "<text>"` | Show augmented-prompt card |
| `--set-operation '<json>'` / `--clear-operation` | Structured "now running" card (`label`, `detail`, `expectedDurationSec`, `poll`) for long-running ops — drives the always-visible banner + live elapsed ticker + estimate bar |
| `--add-decision '<json>'` | Record a major migration decision (`id`, `label`, `choice`, `rationale`) in the **Decisions & Rationale** review (Migration & Review tab). Upserts by `id`. |
| `--render-only` | Re-render HTML from existing state (rare) |

> **Best-effort:** if any `update-state.js` call fails (e.g., node missing), log a warning and continue — the live report is informational, never a blocker for migration work.

> **Record major decisions.** Whenever the user makes a consequential **migration** choice — environment type, migration mode, derived track, a package install/skip, a customization-remediation approach, a reset, a rollback, or the EDM activation/restart — also record it with `--add-decision` so it lands in the **Decisions & Rationale** review (Migration & Review tab). Concrete calls are wired into the steps below; follow the same pattern for any other consequential migration choice. **Do not** record file create/update/read permission prompts or other tool-consent prompts — only migration-substance choices.

> **Show what's running.** Wrap every notable **agent-run** operation with the now-running banner so the user always sees what's executing: call `--set-operation '{"label":"<present-tense description>"}'` immediately **before** the operation and `--clear-operation` immediately **after** (and before any user prompt/gate). For these single-shot operations **omit** `poll` and `expectedDurationSec` — the animated indeterminate bar and live elapsed clock convey activity, not measured completion (the `attempt N/30` counter is only for the two polled migrations, 2.2 and 3.2). Wrap: approved package installs (keep the banner through installed-version verification; see below); SDM & EDM downloads; remediated upload; customization-report generation; EDM activation; approved API restart and readiness verification; rollback. **Caveat:** the banner needs the initialized report, so it only works from the **end of step 1.3 onward** — the pre-init discovery steps (1.1 CLI context, 1.3 site listing) can't show it, so don't wrap those. User-run metadata **solution import** and the manual **site restart fallback** use input notices instead of a running bar. Explicit calls are wired at the steps below.

> **Show every user-input pause (both tracks).** After report initialization, immediately **before every skill-owned question, choice, confirmation, or manual-action wait**, call `--set-input` with the specific action the user needs to take. This includes migration-status/reset choices, package consent/manual installs, environment/mode selection, metadata import, customization choices, error/retry decisions, pre-refs review, Portal ID entry, activation, and restart confirmation. Existing phase-start and remediation approvals already use `--set-approval`; keep those gates and their approval/clearing commands unchanged rather than adding a second notification. Both kinds of notice appear above every report tab; the sticky status pill links to the notice. Setting a notice stops the now-running display without altering phase/step progress.
>
> Once a valid answer resolves the question, call `--clear-input` **before** continuing or stopping. If the user says "Not yet" and the skill is still waiting for that same action, keep the notice; if the answer is invalid, keep it while re-prompting. On resume, resolve any saved pending input before executing the next operation. `--set-operation` clears a resolved input notice when work starts; approval commands also clear stale input notices. Do not mark a step complete or treat a notice as consent. File/tool permission prompts and automatic read-only polling do not need input notices. Before initialization there is no HTML report to update: use chat only, never create a second report or guess an output directory.
>
> Example (serialize JSON as one argument; replace the action with the actual question):
> ```text
> node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/update-state.js" --output-dir "<OUTPUT_DIR>" --set-input '{"requiredAction":"Review the metadata diff, then choose whether to continue in the migration conversation."}'
> ```
> After the response resolves the pause:
> ```text
> node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/update-state.js" --output-dir "<OUTPUT_DIR>" --clear-input
> ```

> **Cross-platform execution:** This skill runs on Windows, macOS, and Linux with Node.js and PAC CLI; the API restart also uses Azure CLI authentication. PowerShell is not a prerequisite. Use the host's available terminal/process tool. Resolve `${CLAUDE_PLUGIN_ROOT}` to the installed plugin's absolute path before executing examples; it is a host-provided path, not a required shell expansion. Command examples are single-line invocations. Pass JSON as one argument, using the active shell's quoting rules or a direct argument-array API; do not evaluate JSON as shell code or remove punctuation from its values. PAC must be on the agent process's `PATH` (`pac.exe` on Windows, `pac` elsewhere); if it is missing, fix that process's PATH or restart the host after installation rather than installing another shell.
>
> Use `scripts/migration-runtime.js` (under this skill) for site discovery, UTF-8 solution-list capture, portable delays, and bounded migration-status polling. It invokes PAC without a shell. The polling action emits a JSON progress record on every attempt and saves the latest full response in `<OUTPUT_DIR>/migration-status.json` and `migration-status.txt`. Never substitute an unbounded shell loop.

### Package installation progress

Use the existing now-running banner for every **approved, agent-run** `pac application install`, including foundation dependencies (1.5), template packages (1.6), and additional V2 packages flagged by a later PAC precheck (2.2). Do not run an install or clear an unapproved gate merely to display progress. Resolve the user's existing approval/input prompt using its normal handler first.

Immediately before launching the approved install, execute:

```text
node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/update-state.js" --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Installing <PACKAGE_NAME>","detail":"Package installation in progress; waiting for PAC completion and installed-version verification."}'
pac application install --application-name "<PACKAGE_NAME>"
```

- The report shows the package name, an **animated indeterminate progress bar**, and elapsed time on every tab. **Do not invent an installation percentage or ETA:** omit `expectedDurationSec` and `poll`. The bar indicates activity only; it is not the workflow-completion percentage.
- Use the host's supported background-process tool when available so the conversation remains responsive. The report's animation/timer continues even while the command is blocking or no new PAC output is arriving.
- **Keep the banner active through asynchronous installation and verification.** A successful PAC exit or "accepted" response alone does not establish that the package is installed. Follow the existing `pac solution list --includeSystemSolutions` re-checks to confirm package presence and, for foundation packages, the minimum version. During the existing wait/re-check flow, use `migration-runtime.js delay --seconds 60` instead of a shell-specific sleep. Do not start a second install just because the first one is slow.
- When updating the banner detail (for example, "Installation accepted; verifying installed version"), keep the same `Installing <PACKAGE_NAME>` label so the elapsed clock is preserved. For multiple packages, include the current package's position in `detail` (for example, "Package 2 of 3"); do not translate package counts into a fabricated installation percentage.
- On verified completion, `--clear-operation` before moving to the next package or step. On an error, a command timeout, or a pause requiring a user decision, clear the running banner, surface the actual result, and show the existing input notice. A timeout does not prove that the server-side install failed. Keep the existing retry, manual-install, skip, and cancellation choices unchanged.
- If installation is user-run and the user has not confirmed completion, show the manual-action input notice rather than claiming the agent is actively installing. On resume, inspect/verify a previously running installation before deciding whether another install is needed.
- Do not advance migration phases/sub-steps merely to show this bar. If metadata migration is already complete, preserve that result; references migration and activation must remain unstarted until their existing gates and commands run.

### Pointing the user at the report

The skill **opens the live report in the user's default browser exactly once** — right after `--init` succeeds at Checkpoint 1 (see step 1.2). On every subsequent state change, the file is rewritten in place. The visible browser tab checks every **40 seconds**: local files reload, while HTTP(S) reports reload only when the saved update token changes. Background tabs skip refreshes. This browser timer does not query PAC; migration-status polling remains every **60 seconds**. After each major state change, **explicitly tell the user where the report is and prompt them to refresh** if they want to see it immediately before approving the next phase. The user shouldn't have to guess where files live. Use this pattern in the chat:

```
📄 Live execution report updated:
   <ABSOLUTE_PATH_TO>/datamodel-migration-report.html

Refresh the browser tab opened in Checkpoint 1 to review the plan/results before approving the next phase. (If you closed it, re-open the path above in your browser.)
```

Surface that callout at these **7 checkpoints**:

| # | Checkpoint | Files to point at |
|---|---|---|
| 1 | After `--init` runs (end of step 1.3) | `datamodel-migration-report.html` (initialized state) |
| 2 | End of Phase 1, before Phase 2 approval | `datamodel-migration-report.html` (shows full Phase 1 outcomes + plan for next phase) |
| 3 | After step 2.3 (Authoring Track) — customization CSV parsed | `customization-report.html` (findings catalog) |
| 4 | Mid-step 2.4 (Authoring Track) — after auto-rewrites are staged, before apply+upload approval | `remediation-diff.json` + `remediation-staged/` tree, augmented prompt files (review the **Remediation Diff** card in the live report) |
| 5 | End of Phase 2, before Phase 3 approval | `datamodel-migration-report.html` (shows Phase 2 outcomes) |
| 6 | End of Phase 3, before Phase 4 approval | `datamodel-migration-report.html` (shows EDM activation status) |
| 7 | Phase 3.1 (Data Diff Validation — pre-refs gate) | `migration-data-diff.json` + `datamodel-migration-report.html` (Pages & Components card now shows SDM↔EDM per-category pills) |

The skill-level approval prompt that follows (via AskUserQuestion) is for the **user's substantive approval to proceed** — not Claude Code's standard command-execution permission prompt. Always print the file paths in chat first so the user knows where to look.

---

## Phase 1: Site Discovery & Pre-checks

**Goal**: Gather all context needed to plan and execute migration safely. Establish CLI context, identify the target site, detect any prior migration state, verify dependencies and template packages, and select migration mode.

**Output**: Site identified and confirmed SDM, prior migration state known, dependencies verified, migration mode chosen. Durable values captured: `<SITE_ROOT>`, `<OUTPUT_DIR>`, WebSiteId, Portal Id (if available), template name, migration mode.

---

### 1.1 Establish CLI Context

**Goal**: Set up PAC CLI with correct version and establish authenticated connection to Dataverse

**Actions**:

1. **Create todo list** with the 4 high-level phases (see [Progress Tracking](#progress-tracking) table). Sub-steps within each phase are internal execution detail — agent doesn't need to surface them as separate todos.

2. **Check PAC CLI Installation**

   ```text
   pac --version
   ```

   - **If version >= 1.31.6**: Proceed to step 3.
   - **If not installed or version < 1.31.6**: Ask user:

     | Question | Header | Options |
     |----------|--------|---------|
     | PAC CLI is not installed or below v1.31.6. Would you like guidance on installation? | Install PAC CLI | Yes, guide me, I'll install manually |

     If "Yes, guide me": Provide OS-specific installation steps from <https://aka.ms/PowerPlatformCLI>

3. **Check Existing Authentication**

   ```text
   pac auth list
   pac auth who
   ```

   - **If authenticated**: Extract environment URL and ask user:

     | Question | Header | Options |
     |----------|--------|---------|
     | Current environment: `<ENV_URL>`. Is this correct for migration? | Confirm Env | Yes, correct, No, switch environment |

     - If "No": Run `pac auth select` to switch
     - If "Yes": Proceed

   - **If not authenticated**: Ask for environment URL and run:

     ```text
     pac auth create -u "<ENV_URL>"
     ```

4. **Inform About Requirements** (user must verify manually):
   - Role: System Administrator, Dynamics 365 Admin, or Power Platform Admin
   - Dataverse base portal package: 9.3.2307.x+
   - Power Pages Core package: 1.1.2602.230+
   - Environment mode: If admin mode, background operations must be enabled (warning only)

**Output**: PAC CLI installed/verified, authenticated to correct environment

---

### 1.2 Identify Site Context

**Goal**: Determine target site from local `website.yml` or user input, AND resolve where to place migration outputs

**Actions**:

1. **Resolve site location**

   Run these checks in order to determine `<SITE_ROOT>` (where the site source lives or will be downloaded to) and `<PARENT_OUTPUT_DIR>` (the parent directory under which step 1.3 will create a per-migration subfolder named `<env>--<slug>/` for all migration artifacts):

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" discover --path "."
   ```

   The JSON result includes `siteRoot`, `candidates`, and `parentOutputDir`. It recognizes a direct `website.yml` and the nested `.powerpages-site/website.yml` layout. An ambiguous directory is never silently selected. Resolve based on results:

   | Result of check A | Result of check B | `<SITE_ROOT>` | `<PARENT_OUTPUT_DIR>` |
   |---|---|---|---|
   | True (cwd is the site) | — | returned `siteRoot` | returned sibling `parentOutputDir` (site source stays clean) |
   | False | Exactly one subdir | returned `siteRoot` | returned `parentOutputDir` in cwd alongside the site folder |
   | False | Zero or multiple subdirs | (will download to `<MIGRATION_OUTPUT_DIR>/site-sdm/<auto-slug>` in step 2.1) | returned `parentOutputDir` in cwd |

   Capture both `<SITE_ROOT>` and `<PARENT_OUTPUT_DIR>` as durable values. The actual per-migration subfolder `<MIGRATION_OUTPUT_DIR>` is computed in step 1.3 and is used throughout the rest of the skill. Create `<PARENT_OUTPUT_DIR>` if it doesn't exist yet.

   > **`<PARENT_OUTPUT_DIR>` is always exactly `migration-reports` (or the sibling `../migration-reports` when cwd is the site) — never a timestamped or `fresh-*` variant.** Re-runs must resume in the **same** folder: step 1.3's `update-state.js --init` already reuses an existing `<env>--<slug>` subfolder unless `--force` is passed. Do **not** invent a new parent (e.g., `migration-reports/fresh-<timestamp>/`) to "keep prior files" — doing so silently re-downloads the site and strands the user's working copy. If the user wants a clean slate, pass `--force` to `--init` in the **same** folder rather than creating a new tree.

2. **Use website.yml if present**

   If a `website.yml` exists at `<SITE_ROOT>`, parse it and extract:
   - `adx_name` (site name)
   - `adx_websiteid` (site GUID)

   Ask user confirmation:

   | Question | Header | Options |
   |----------|--------|---------|
   | Found local website.yml for site: `<SITE_NAME>` (ID: `<WEBSITEID>`) at `<SITE_ROOT>`. Use this site? | Use Local Context | Yes, use this site, No, specify different site |

   - If "Yes": use extracted values. Then make the **reuse-vs-fresh source decision** below, and continue to step 1.3.
   - If "No": treat as if no website.yml; proceed to step 3.

   **Reuse-vs-fresh source decision (only when the user confirmed a local site above).** The user may be sitting in their own working copy. Ask once — reusing it is faster and avoids a second download, but it has real consequences:

   | Question | Header | Options |
   |----------|--------|---------|
   | Use your local copy at `<SITE_ROOT>` as the migration source, or download a fresh SDM copy? **Reuse** is faster and keeps your folder, but any local edits you've made will be included when the skill uploads remediated source in Phase 2.4, and server-side changes made since you downloaded won't be reflected. **Fresh** is a pristine copy matching the current server state and leaves your working copy untouched. | Site Source | Reuse my local copy, Download a fresh SDM copy |

   - **Reuse my local copy**: set `<SITE_SOURCE_MODE> = reuse-local`; keep `<SITE_ROOT>` as resolved; step 2.1 **skips** the download.
   - **Download a fresh SDM copy**: set `<SITE_SOURCE_MODE> = fresh-download`; step 2.1 downloads to `<MIGRATION_OUTPUT_DIR>/site-sdm/<auto-slug>`; the user's working copy is left untouched.

   Record the choice once the live report is initialized (end of step 1.3): `--add-decision '{"id":"site-source","label":"Site source","choice":"<Reuse local copy | Fresh SDM download>","rationale":"<reused local working copy | downloaded a pristine copy to match server state>"}'`.

   When **no** local site was found (the step 3 path, where the user supplies a site ID), there is nothing to reuse: `<SITE_SOURCE_MODE>` is `fresh-download` and step 2.1 downloads the SDM source — no prompt needed.

3. **Get site identification from user**

   If no `website.yml` resolved or user declined, ask:

   | Question | Header | Options |
   |----------|--------|---------|
   | Provide the site name or WebSiteId (GUID) for migration | Site ID | I'll paste the site name, I'll paste the WebSiteId |

   Then prompt for the actual value in the chat (do not create a single-option AskUserQuestion — that errors with "expected array to have >=2 items"; ask in plain text or use 2+ options).

   In this path, `<SITE_ROOT>` will be set to the path step 2.1 downloads to (typically `<MIGRATION_OUTPUT_DIR>/site-sdm/<auto-slug>` once `pac pages download` runs). Downloading into the per-migration subfolder keeps every artifact for this site contained — multiple migrations sharing the same parent dir won't collide on the `site-sdm` / `site-edm` folder names.

**Output**: WebSiteId captured; `<SITE_ROOT>` and `<PARENT_OUTPUT_DIR>` resolved (or marked "download in step 2.2" for `<SITE_ROOT>`)

> **Live report init is deferred to the end of step 1.3.** The init command needs the environment name and the website slug to compute a per-migration subfolder; both are captured by `pac auth list` (step 1.1) and `pac pages list -v` (step 1.3) respectively. We don't write `migration-state.json` here in 1.2.

---

### 1.3 Site Discovery and Validate Data Model

<!-- not-a-gate: The `AskUserQuestion` references in this section are the automatic template-detection confirm/pick prompts (pure data-gathering that only shapes the step 1.6 package install — no side effect to undo). Per approval-gates.md §2, data-gathering prompts are not approval gates. -->

**Goal**: Find the site in the environment and verify it's on SDM (not already EDM)

**Actions**:

1. **List All Sites**

   ```text
   pac pages list -v
   ```

   Verbose output columns: `Index | Website Id | Portal Id | Friendly Name | Portal Url | Data Model Version | Single Page Application | Is Site Active`.

   Parse output to extract all available sites with:
   - WebSiteId
   - Portal Id (may render as `Unknown` if the Power Platform active-websites API failed, or `N/A` if the site is inactive — treat both as "missing" for the activation step in Phase 3, which prompts the user when Portal Id is needed)
   - Portal Url (full site URL from the `Portal Url` column; may be empty for inactive sites — store as `null` if so)
   - Site Name (display name from Friendly Name, the part before " - ")
   - URL slug (from Friendly Name, the part after " - ")
   - Current ModelVersion (`Standard` or `Enhanced`)

   > **Note:** Template name is not included in `pac pages list` output. Template is auto-detected separately in step 4.
   >
   > **PAC CLI version note:** The Portal Id column was added on 2026-02-24. If your installed PAC build predates that and the column is missing entirely, treat Portal Id as missing — the activation step in Phase 3 will prompt the user before the data-model update.

2. **Locate Target Site**

   Search the list for site matching user input (name or GUID):
   - If found: Extract WebSiteId, Portal Id, ModelVersion, and URL slug. Store all four for later phases. If Portal Id parsed as a valid GUID, mark it as "captured"; if `Unknown`/`N/A`/missing, mark as "needs prompt".
   - If not found: Show list and ask user to confirm site name/ID. If still not found, stop and ask user to verify in Power Platform admin center.

3. **Validate Data Model**

   Check `ModelVersion` from output:
   - **If EDM**: Stop with message: "This site is already on Enhanced Data Model. Migration not needed."
   - **If SDM**: Continue to step 1.4

4. **Identify Site Template (automatic)**

   Template name is not available from `pac pages list`, and the migration tracker's `adx_templatename` is not reliably populated — so the template is detected automatically from two indicators, combined by [detect-template.js](scripts/detect-template.js):

   - **Site inspection** — recognizes the D365 portals that ship distinctive built-in components (Community, Employee Self-Service, Partner) from the downloaded site source.
   - **Installed template "anchor" solution** — the authoritative source of truth. Covers Customer Self-Service and the medium templates (FAQ, Application Processing, Program Registration, Schedule & Manage Meetings), and confirms/overrides the site-inspection result.

   **4a. Ensure a local SDM copy of the site (reuse or download).**

   - **If step 1.2 already resolved a local `<SITE_ROOT>`** (cwd is the site, or a single site subfolder): **reuse it — do not download again.** A stale local copy only affects site inspection (Community/ESS/Partner recognition), never the authoritative anchor check, so this is safe; if you want certainty, note any local edits to the user. The site's data model was already confirmed Standard in step 1.3.3.

   - **If no local site was resolved**, download the SDM source once (Phase 2's snapshot step reuses it, so it isn't downloaded twice):

     ```text
     pac pages download --webSiteId "<WEBSITE_ID>" --modelVersion 1 --path "<PARENT_OUTPUT_DIR>/site-sdm"
     node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" discover --path "<PARENT_OUTPUT_DIR>/site-sdm" --require-site
     ```

     Capture the returned `siteRoot` as `<SITE_ROOT>` (the download path can be a wrapper, including a nested `.powerpages-site` layout). Stop and select the correct site if discovery reports zero or multiple candidates.

   **4b. Capture installed solutions (reused by steps 1.5 and 1.6).**

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" solutions --output "<PARENT_OUTPUT_DIR>/solution-list.txt"
   ```

   The helper runs `pac solution list --includeSystemSolutions` and writes the complete output as UTF-8 on every OS. `--includeSystemSolutions` is required — the anchor solutions are first-party and hidden without it. A missing PAC executable, nonzero exit, or empty response is an error, not evidence that no template is installed.

   **4c. Run detection.**

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/detect-template.js" --site-root "<SITE_ROOT>" --solutions-file "<PARENT_OUTPUT_DIR>/solution-list.txt" --pretty
   ```

   The script returns JSON with `inspection`, `installedAnchors`, and a `resolution`. Act on `resolution.decision`:

   | `decision` | Meaning | Action |
   |---|---|---|
   | `install-v2` | Template resolved (site inspection + anchor, or anchor alone; anchor is authoritative on any disagreement). | Store `template`, `v1Anchor`, `v2Package`. No prompt. |
   | `prompt-confirm` | Site looks like a D365 portal but its anchor solution isn't installed. | Ask the user to confirm (below). |
   | `prompt-pick` | Multiple D365 anchors installed, none match the site. | Ask the user to pick among `candidates`. |
   | `prompt-pick-or-install-all` | Multiple template solutions installed, site not distinctive. | Ask the user to pick one, or install all `candidates`. |
   | `low-complexity-skip` | No template anchor present. | Treat as low-complexity (Blank / Starter Layout). No template package — step 1.6 is skipped. |

   **Prompt — `prompt-confirm`:**

   | Question | Header | Options |
   |----------|--------|---------|
   | This site appears to be `<confirmTemplate>`, but its template solution isn't installed here. Is that the correct template? | Confirm Template | Yes — it's `<confirmTemplate>`, No — treat as basic (no template package) |

   - **Yes** → store `template` / `v2Package` from the resolution; step 1.6 installs it.
   - **No** → treat as low-complexity; step 1.6 skips the install.

   **Prompt — `prompt-pick` / `prompt-pick-or-install-all`:** present `candidates[].label` (max 4 per `AskUserQuestion`). For `prompt-pick-or-install-all`, add an **Install all** option that installs every candidate's `v2Package` in step 1.6.

   Store `<TEMPLATE_NAME>` (resolution `template` or the user's choice), `<TEMPLATE_V2_PACKAGE>` (resolution `v2Package`, or the list when "Install all"), `<TEMPLATE_DECISION>` (the `decision`), and `<SITE_ROOT>` — these drive step 1.6 and are reused by Phase 2.

**Output**: Target site confirmed as SDM; template auto-detected (or user-confirmed / low-complexity); `<SITE_ROOT>`, `<TEMPLATE_NAME>`, `<TEMPLATE_V2_PACKAGE>` captured; WebSiteId/ModelVersion/URL slug/Portal Id captured (Portal Id marked "captured" or "needs prompt")

> **→ Initialize live report (per-migration subfolder).** Now that env name (from step 1.1's `pac auth list`) and website slug (from `pac pages list -v` above) are both known, initialize state. Run:
>
> ```
> node update-state.js --init --output-dir "<PARENT_OUTPUT_DIR>" --website-id "<WEBSITE_ID>" --env-name "<ENV_NAME>" --env-url "<ENV_URL>" --slug "<URL_SLUG>"
> ```
>
> The command creates a per-migration subfolder `<PARENT_OUTPUT_DIR>/<sanitized-env>--<sanitized-slug>/` and writes `migration-state.json` + `datamodel-migration-report.html` inside it. It prints the resolved subfolder path on stdout — **capture that path as `<MIGRATION_OUTPUT_DIR>` and use it as `--output-dir` for every subsequent `update-state.js` call and as the artifacts directory throughout the rest of the skill.** Pass `--force` only if you intentionally want to wipe an existing migration in the same subfolder.
>
> Resume and reset verify the website ID, environment URL/name, and original slug before reusing a folder; a sanitized-name collision stops with an error rather than opening another migration. Older state without `site.environmentUrl` must be checked against its original environment before recording the verified URL with `--set-site '{"environmentUrl":"<ENV_URL>"}'`. A force reset clears generated snapshots, comparisons, reports, prompts, and staged remediation, but preserves downloaded site source.
>
> **Fresh report only:** Phase 1 is already running when this initialization happens. After a new initialization (including an explicitly approved force reset), run `--approve-and-start 1` to align the report with that existing work and clear the skeleton's initial Phase 1 display gate. This is not package-install consent. On resume, preserve the saved phase, pending input, and approval gate; do not blindly restart Phase 1 or clear an unresolved gate.
>
> Then batch-update the steps that ran before init:
>
> ```
> --set-step 1.1 --status completed --output "PAC CLI v<X> · auth <profile> · env <ENV_NAME>"
> --set-step 1.2 --status completed --output "<SITE_ROOT> resolved; parent <PARENT_OUTPUT_DIR>"
> --set-site '{"name":"<SITE_NAME>","slug":"<URL_SLUG>","portalId":"<PORTAL_ID_OR_NULL>","portalUrl":"<PORTAL_URL_OR_NULL>","currentDataModel":"Standard SDM","template":"<TEMPLATE_NAME>","siteRoot":"<SITE_ROOT>"}'
> --set-step 1.3 --status completed --output "Site <NAME> · ModelVersion=Standard · template <TEMPLATE>"
> ```
>
> **📄 Checkpoint 1 — Open the live report in the user's default browser, then tell them.** After `--init` succeeds, use the host's browser/file-opening tool to open `<MIGRATION_OUTPUT_DIR>/datamodel-migration-report.html` once. If no opener is available (for example, in a headless session), show a clickable absolute file link and tell the user to open it. Do not install a shell or block migration because automatic browser opening is unavailable.
>
> Then print this in chat so the user knows where the tab they just saw came from and what to do next:
>
> ```
> 📄 SDM → EDM migration report initialized and opened in your default browser:
>    <MIGRATION_OUTPUT_DIR>/datamodel-migration-report.html
>
> Keep this tab open and refresh it as the migration progresses — the file is
> regenerated in place after every sub-step. (If the tab didn't open, paste the
> path above into your browser.)
> ```

---

### 1.4 Check Existing Migration Status

**Goal**: Detect whether a migration is already in flight, previously completed, or previously failed for this site — and recover or short-circuit accordingly before doing any new work

**Actions**:

1. **Query Current Status**

   ```text
   pac pages migrate-datamodel --webSiteId "<WEBSITE_ID>" --checkMigrationStatus --verbose
   ```

   > **PAC CLI build note:** Verbose output (`-v` / `--verbose`) is required here when supported because the top-level `Running` status alone cannot distinguish active metadata work from the expected `ConfigurationDataCompleted` handoff. On some older builds the flag errors with `An unknown argument --verbose was passed.`; only then fall back to the non-verbose command. If the fallback reports `Running`, query the migration tracker record directly in Dataverse for `currentStep` before presenting any in-flight choices. Never offer reset based only on the non-verbose `Running` status.

2. **Parse Status**

   Extract from the output:
   - **Status**: one of `NotStarted`, `Running`, `Completed`, `Failed`, `Reverted`, `Unknown`
   - On older PAC builds where `--verbose` worked, also: **createdOn** / **modifiedOn** (for elapsed-time), **currentStep** / **stepHistory** (granular progress)

3. **Branch Based on Status**

   - **NotStarted / no tracker record**: No prior migration. Proceed to step 1.5.

   - **Reverted**: Site was previously rolled back to SDM. Treat as fresh start. Proceed to step 1.5.

   - **Completed**: A prior migration finished but the data model version was not yet flipped to EDM (otherwise step 1.3 would have stopped earlier). Skip ahead to the activation step in Phase 3 (Authoring Track 3.3 or Downstream Track 3.5 — track is derived in step 1.7, so complete 1.7 first to know which).

   - **Failed**: A prior migration failed. Show the last step and error details (from chunk records in the verbose output), then ask:

     | Question | Header | Options |
     |----------|--------|---------|
     | Previous migration failed at step `<currentStep>`. Retry from the migration phase, or stop and investigate? | Failed Migration | Retry migration, Stop and investigate |

     - **Retry**: Proceed to step 1.5 (full pre-checks still run). Reuse the `<SITE_ROOT>`, `<SITE_SOURCE_MODE>`, and output folder already resolved in step 1.2 — honor the reuse-vs-fresh decision; do **not** re-download the site or create a new `migration-reports` tree.
     - **Stop**: Halt. Direct user to verbose status output and Microsoft Learn for diagnostics.

    - **Running with `currentStep = ConfigurationDataCompleted`**: Configuration metadata finished, but the tracker remains `Running` until the references phase finishes. This is an expected handoff, not evidence that metadata migration is stuck. **Do not show the generic in-flight prompt, do not ask whether to proceed, and do not offer reset.** Proceed through steps 1.5–1.7 to recover the intended mode:
       - If the confirmed mode is `configurationData`, automatically mark Authoring Track step 2.2 completed and immediately resume at step 2.3. Do not reset or rerun metadata migration.
       - If the confirmed mode is `all`, the same current step is only an intermediate milestone; resume the step 2.2 polling loop and wait for top-level `Completed`.

    - **Running with any other `currentStep`**: Migration is in progress. Compute and present elapsed time:

     > Migration started **`<createdOn → now>`**, last activity **`<modifiedOn → now>`** ago. Current step: **`<currentStep>`**. Migration processes records in batches of 5K — large sites can take hours.
     > Reference: <https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model>

     Ask:

     | Question | Header | Options |
     |----------|--------|---------|
     | A migration is already running for this site. How to proceed? | In-Flight Migration | Wait and poll until complete, Reset and start over, Exit and check back later |

     - **Wait**: Skip the rest of Phase 1 and Phase 2 setup work; jump directly to the migration-status polling loop (Authoring Track 2.2 step 2 for an in-flight metadata migration, or Authoring Track 3.2 step 3 / Downstream Track 3.2 step 2 for an in-flight refs migration — depends on which mode the in-flight migration was started with; complete 1.7 first to determine track). After polling reports Completed, continue to the activation step (Authoring Track 3.3 / Downstream Track 3.5).
     - **Reset and start over**: Show the reset warning (see step 4), confirm, run reset, then proceed to step 1.5.
     - **Exit**: Halt the skill cleanly. User can re-invoke later — step 1.4 will re-detect the in-flight migration.

   - **Unknown**: Print warning. Ask user to verify in Power Platform admin center, then choose to proceed or stop.

4. **Reset Warning (only shown if user picks "Reset")**

   > **Reset** flips the migration tracker status from `Running` → `Failed` so a new migration can be triggered. It does **not** undo any data already migrated — records already moved to the target tables stay there. PAC's own behavior: see <https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model>.

   Confirm:

   | Question | Header | Options |
   |----------|--------|---------|
   | Reset will mark the in-flight migration as Failed but will NOT undo migrated records. Continue? | Confirm Reset | Yes, reset, No, cancel |

   If "Yes":

   ```text
   pac pages migrate-datamodel --webSiteId "<WEBSITE_ID>" --resetMigration
   ```

   Then proceed to step 1.5.

**Output**: Migration history known; skill either short-circuits to the appropriate phase or proceeds normally with a clean tracker state

> **→ Update report:** `--set-step 1.4 --status completed --output "Status: <STATUS> · <NOTES>"`. If the skill is short-circuiting (in-flight or previously-completed migration), also `--set-phase 1 --status completed`, `--set-phase 2 --status completed` (Phase 2 setup work is skipped), and skip the Phase 2 approval gate — the user has effectively already approved this path by responding to the in-flight prompt.
>
> If the user confirmed a **reset** at this step, also record it: `--add-decision '{"id":"reset-migration","label":"Reset in-flight migration","choice":"Yes, reset","rationale":"Marked the prior tracker Failed to start fresh; does not undo already-migrated records"}'`.

---

### 1.5 Validate Required Dependencies

**Goal**: Verify required first-party packages are installed at the minimum required version, and install/upgrade them via `pac application install` with explicit user confirmation when they're not.

**Actions**:

1. **Check Installed Solutions**

   Run the following to list **all** solutions in the environment, including first-party Microsoft solutions:

   ```text
   pac solution list --includeSystemSolutions
   ```

   > **Important:** The `--includeSystemSolutions` flag is required. Without it, `pac solution list` returns only user/managed-by-customer solutions and omits the first-party packages we need to verify (`CDSBasePortal`, `PowerPages_Core`, and the V2 template solutions checked in step 1.6).

   Search the output for:
   - `CDSBasePortal` — Dataverse base portal package (required: **9.3.2307.x+**)
   - `PowerPages_Core` — Power Pages Core package (required: **1.1.2602.230+**)

   Capture both the **installed version** (or `not found`) and present them to the user.

2. **Evaluate and Install/Upgrade as Needed**

   For **each** of `CDSBasePortal` and `PowerPages_Core`, evaluate independently:

   - **Found and version meets minimum**: log "OK · v<X>" and move on to the next package.
   - **Not found OR installed version is below the minimum**: surface the gap and ask the user before running any install:

     | Question | Header | Options |
     |----------|--------|---------|
     | `<PACKAGE_NAME>` is `<not installed OR v<X> · needs v<MIN>+>`. Install/upgrade via `pac application install` (pulls the latest from the Microsoft application catalog)? | Install Package | Yes — install/upgrade now, Skip — I'll install manually, Cancel — stop the skill |

     - **Yes**: follow [Package installation progress](#package-installation-progress), then run

       ```text
       pac application install --application-name "<PACKAGE_NAME>"
       ```

       Wait for completion. On some clouds the install is asynchronous, so re-run `pac solution list --includeSystemSolutions` afterwards to confirm the package now meets the minimum version. If the re-check still shows the old version, ask the user to wait a minute and re-check, or proceed knowing the install is in flight.

     - **Skip**: log the user's choice and proceed to step 1.6. The migration command in Phase 2/3 will surface a clearer error if the package version is genuinely too low; the user has acknowledged the risk.

     - **Cancel**: halt the skill cleanly.

   - **`pac application install` errors** (rare for these first-party packages — they're always in the Microsoft application catalog, but the call can fail on older PAC builds, missing tenant roles, or transient catalog issues): fall back to manual install.

     | Question | Header | Options |
     |----------|--------|---------|
     | `pac application install --application-name "<PACKAGE_NAME>"` failed: `<error message>`. Install manually via Power Platform admin center → Resources → Dynamics 365 apps → find `<PACKAGE_NAME>` → Install? | Manual Install | I'll install manually now (then continue), Skip — I'll install later, Cancel — stop the skill |

     - **I'll install manually**: pause until user confirms install is complete, then re-run step 1 above to verify.
     - **Skip / Cancel**: same as above.

3. **Fallback if Automatic Check Fails Entirely**

   If `pac solution list --includeSystemSolutions` itself errors out (older PAC build, missing role, transient error), fall back to asking the user:

   | Question | Header | Options |
   |----------|--------|---------|
   | Unable to verify packages automatically. Can you confirm both Dataverse base portal package (9.3.2307.x+) and Power Pages Core (1.1.2602.230+) are installed? | Deps Confirmed | Yes, confirmed, Not sure — help me check |

   - If "Not sure": guide user to Power Platform admin center → Resources → Dynamics 365 apps to verify package versions.
   - If "Yes": proceed to step 1.6.

**Output**: Both required first-party packages verified at or above the minimum version, installed/upgraded via `pac application install`, or explicitly acknowledged as skipped by the user.

> **→ Update report:** `--set-step 1.5 --status completed --output "CDSBasePortal <state> · PowerPages_Core <state>"` where `<state>` is one of `v<X> OK`, `installed via pac application install (v<X> → v<Y>)`, `upgraded via pac application install (v<X> → v<Y>)`, or `user skipped — proceeding at user's risk`. Capturing the install method explicitly so the user can audit afterwards.
>
> Record each package decision: `--add-decision '{"id":"pkg-CDSBasePortal","label":"Package: CDSBasePortal","choice":"<state>","rationale":"Base portal components the migration utility depends on"}'` and the same for `PowerPages_Core` (id `pkg-PowerPages_Core`, rationale "EDM / Power Pages runtime components the migrated site runs on").

---

### 1.6 Ensure the Template's V2 Package Is Installed

**Goal**: Make sure the Enhanced (V2) solution for the template detected in step 1.3 is installed, installing it via `pac application install` when it isn't.

**Actions**:

1. **Honor the step 1.3 decision.**

   - If `<TEMPLATE_DECISION>` from step 1.3 is **`low-complexity-skip`** (Blank Page / Starter Layout, or the user declined the `prompt-confirm`): **skip this step entirely** — these templates need no template package. Migration proceeds on the foundation packages (`CDSBasePortal`, `PowerPages_Core`) verified in step 1.5.
   - Otherwise continue with `<TEMPLATE_V2_PACKAGE>` — a single package, or the list captured when the user chose "Install all".

2. **Check whether the V2 package is already installed.**

   Reuse the `pac solution list --includeSystemSolutions` output captured in step 1.3 (`<PARENT_OUTPUT_DIR>/solution-list.txt`). For each `<TEMPLATE_V2_PACKAGE>`:
   - **Present** → nothing to do; log `OK · already installed`.
   - **Not present** → install it in step 3.

3. **Install via `pac application install`.**

   Follow [Package installation progress](#package-installation-progress) for each approved install, including keeping the bar active until verification.

   ```text
   pac application install --application-name "<TEMPLATE_V2_PACKAGE>"
   ```

   Run once per package when installing multiple (the "Install all" case). The install is asynchronous on some clouds, so afterwards re-run `pac solution list --includeSystemSolutions` and confirm each package now appears; if it doesn't yet, wait a minute and re-check.

   **If `pac application install` errors** (missing tenant role, transient catalog issue, older PAC build): surface the exact error and ask the user to install the package manually from Power Platform admin center → Resources → Dynamics 365 apps, then re-run the verification in step 2.

   | Question | Header | Options |
   |----------|--------|---------|
   | `pac application install --application-name "<TEMPLATE_V2_PACKAGE>"` failed: `<error>`. Install it manually via Power Platform admin center → Resources → Dynamics 365 apps, then continue? | Manual Install | I've installed it — re-verify, Cancel — stop the skill |

   The V2 package is required for the detected template, so there is no "skip" option — either it gets installed, or the user stops to resolve the install.

**Output**: The detected template's V2 package is installed (or confirmed already present), or the site was low-complexity and no template package was needed. `PowerPages_Core` was already verified in step 1.5.

> **→ Update report:** `--set-step 1.6 --status completed --output "<TEMPLATE_V2_PACKAGE> <state>"` where `<state>` is one of `already installed`, `installed via pac application install`, or `low-complexity — no template package needed`.
>
> Record the decision: `--add-decision '{"id":"pkg-template-v2","label":"Package: <TEMPLATE_V2_PACKAGE>","choice":"<state>","rationale":"EDM version of the template-specific schema; for D365 templates it carries the EDM relationship changes the migrate precheck requires"}'`.

---

### 1.7 Determine Environment Type and Migration Mode

**Goal**: Capture env type, select migration mode, and derive the **migration track** (Authoring Track vs Downstream Track) that controls the shape of Phase 2 and Phase 3.

**Actions**:

1. **Identify Environment Type**

   | Question | Header | Options |
   |----------|--------|---------|
   | Which type of environment is this? | Environment Type | Development (Dev), Test/UAT, Production (Prod), Single environment (no ALM) |

   Store the choice.

2. **Recommend Migration Mode Based on Environment**

   | Env Type | Recommended Mode | Rationale |
   |---|---|---|
   | Dev | `configurationData` | Migrate metadata here; allows a customization remediation pass before refs |
   | Test / UAT | `configurationDataReferences` | Assumes config metadata came from Dev via ALM solution import |
   | Prod | `configurationDataReferences` | Assumes config metadata came from Dev via ALM solution import |
   | Single env (no ALM) | `configurationData` | Same as Dev — no upstream env to ALM from; we migrate metadata locally |

3. **Confirm Migration Mode**

   | Question | Header | Options |
   |----------|--------|---------|
   | Recommended mode for `<ENV_TYPE>`: `<RECOMMENDED_MODE>`. Confirm or override? | Migration Mode | Use recommended (`<RECOMMENDED_MODE>`), Use `configurationData`, Use `configurationDataReferences`, Use `all` |

   Mode descriptions:
   - `configurationData`: Migrate metadata (web pages, snippets, settings, etc.) only. **Recommended default** — auto-generates a customization report, allows remediation before refs migrate in Phase 3.
   - `configurationDataReferences`: Migrate transactional data references only. Assumes config metadata is already in EDM (typically via ALM solution import on Test/UAT/Prod).
   - `all`: Migrate metadata AND refs in one shot. **Advanced override.** Only safe if no `adx_*` customizations exist. When chosen, Phase 3.2 (Migrate Transactional References) is skipped automatically because refs are already done in Phase 2.2 — but Phase 3.1 (Data Diff Validation), Phase 3.3 (Activate EDM), and Phase 3.4 (Restart Site) still run.

   If user picks an override for their env, show a warning:
   - **`all` on any env**: "Recommended only when you know there are no `adx_*` customizations. Once refs migrate, customization fixes become much harder. Proceed?"
   - **`configurationDataReferences` on Dev/Single env**: "Only safe if metadata is already in EDM (from a prior `configurationData` run or solution import). Proceed?"

   Store final selected `<MODE>`.

4. **Derive Migration Track**

   | Final Mode | Track | CLI Value |
   |---|---|---|
   | `configurationData` | **Authoring** | `A` |
   | `all` | **Authoring** | `A` |
   | `configurationDataReferences` | **Downstream** | `B` |

   Persist track to state. The Authoring Track and Downstream Track have **different Phase 2 structures**; **both Phase 3 tracks start with the same Data Diff Validation (3.1)** but the Downstream Track has additional customization steps after refs migrate. Step 3.2 (Migrate Transactional References) auto-skipped when mode = `all`.

**Output**: Environment type captured, migration mode confirmed, track derived

> **→ Update report (end of Phase 1):**
>
> ```
> --set-site '{"environment":"<DEV|TEST|UAT|PROD|SINGLE>","migrationMode":"<MODE>"}'
> --set-step 1.7 --status completed --output "Env: <ENV_TYPE> · mode=<MODE> · Track <A|B>"
> --set-track <A|B>
> --add-decision '{"id":"env-type","label":"Environment type","choice":"<ENV_TYPE>","rationale":"<why this environment was selected>"}'
> --add-decision '{"id":"migration-mode","label":"Migration mode","choice":"<MODE>","rationale":"<env rationale; if mode=all, note the no-adx_* customizations risk was acknowledged>"}'
> --set-phase 1 --status completed
> --set-approval 2 phase-start
> ```
>
> `--set-track` rebuilds the Phase 2 and Phase 3 cards in the live report from the chosen track's blueprint. Phase 1 sub-step status is preserved across the swap.
>
> **📄 Checkpoint 2 — Tell the user about the report before asking for approval.** Print this in chat *before* the AskUserQuestion approval gate:
>
> ```
> 📄 Phase 1 complete. Review the plan in your browser before approving Phase 2:
>    <ABSOLUTE_PATH_TO_OUTPUT_DIR>/datamodel-migration-report.html
>
> The report now shows: site context, env type, migration mode, derived track, and
> the Phase 2 sub-steps that will run if you approve.
> ```
>
> Then proceed to ask the user to approve Phase 2 via AskUserQuestion. On approval, run `node update-state.js --output-dir "<OUTPUT_DIR>" --approve-and-start 2` to atomically clear the approval gate and mark Phase 2 in-progress.

---

## Phase 2: Configuration Setup (track-branched)

This phase has **two completely different shapes** depending on the migration track derived in step 1.7. Pick the matching section below; ignore the other one.

- [**Phase 2 — Authoring Track**](#phase-2--authoring-track) — mode is `configurationData` or `all` (Dev / Test/UAT / Single env)
- [**Phase 2 — Downstream Track**](#phase-2--downstream-track) — mode is `configurationDataReferences` (Prod, ALM assumed)

---

## Phase 2 — Authoring Track

**Applies when**: state.track === 'A' (mode = `configurationData` or `all`)

**Goal**: Capture an SDM baseline snapshot first (so the live report shows pre-migration state and Phase 4 has something to diff against), then migrate configuration metadata to EDM tables. Newer PAC versions auto-generate a customization report as a side effect of the migrate command. If any `adx_*` customizations are flagged, remediate the site source (FetchXML / Liquid auto-rewrites + augmented prompts for plugins / DME) and upload back to Dataverse before activation.

**Output**: SDM baseline captured and reflected in the live report, metadata migrated to EDM tables, customization report parsed, any flagged customizations remediated and uploaded, final readiness gate confirmed.

---

### 2.1 Capture SDM Snapshot

**Goal**: Ensure the SDM source is available — downloaded fresh, or reused from the user's local copy per the step 1.2 decision — and snapshot it **before** the migration runs, so the live report's "Migration totals" and "Pages & Components" cards reflect the pre-migration baseline from the start of Phase 2. This also provides `<SITE_ROOT>` for the FetchXML/Liquid rewriters in step 2.4.

**Actions**:

1. **Provide SDM source (honor the step 1.2 reuse-vs-fresh decision)**

   Branch on `<SITE_SOURCE_MODE>` resolved in step 1.2:

   - **`reuse-local`** (user chose to reuse their local copy and `<SITE_ROOT>` is still present): **skip the download entirely** — `<SITE_ROOT>` already points at the source. Do not run `pac pages download`.
   - **`fresh-download`** (user chose fresh, or no local copy existed): download the SDM source now (then capture the nested inner folder as `<SITE_ROOT>`):

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Downloading SDM site source"}'
   pac pages download --webSiteId "<WEBSITE_ID>" --modelVersion 1 --path "<MIGRATION_OUTPUT_DIR>/site-sdm"
   node update-state.js --output-dir "<OUTPUT_DIR>" --clear-operation
   ```

   > **Important — nested folder quirk:** After download, run `node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" discover --path "<MIGRATION_OUTPUT_DIR>/site-sdm" --require-site` and capture the returned `siteRoot` as `<SITE_ROOT>`. This finds `website.yml` in a direct or nested `.powerpages-site` tree without guessing the first child folder. Subsequent migrate, rewrite, and upload steps must use `<SITE_ROOT>`, not the `site-sdm` wrapper.
   >
   > **`--modelVersion 1`** explicitly requests SDM data. The site's activation is still SDM at this point (step 3.3 hasn't run yet), so this is the live source of truth for the baseline.

2. **Snapshot the SDM source**

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/snapshot-site.js" --site-root "<SITE_ROOT>" --output-dir "<OUTPUT_DIR>" --label sdm
   ```

   Output: `<OUTPUT_DIR>/sdm-snapshot.json` — Phase 4 will diff this against an EDM snapshot to confirm every record migrated. The live report's Pages & Components tab also reads this file to populate per-category counts.

**Output**: SDM baseline captured to `sdm-snapshot.json`; `<SITE_ROOT>` ready for step 2.2's migrate command and step 2.4's rewriters.

> **→ Update report:**
>
> ```
> --set-site '{"siteRoot":"<SITE_ROOT>"}'
> --set-step 2.1 --status completed --output "SDM snapshot captured · <N> components"
> ```

---

### 2.2 Migrate Metadata

**Goal**: Run the PAC migrate command for the chosen mode. Auto-generates the customization report.

**Actions**:

1. **Execute Migration Command**

   ```text
   pac pages migrate-datamodel --webSiteId "<WEBSITE_ID>" --mode <MODE>
   ```

   Where `<MODE>` is the value confirmed in step 1.7 (either `configurationData` or `all` for the Authoring Track).

   > **If PAC's precheck flags a missing V2 template package here**, it is PAC's **environment-wide** prerequisite (`checkAllV1PackagesHasV2Packages`) — **not** a re-detection of this site's template. It fires for **any** V1 template solution installed in the environment that lacks its V2, even ones unrelated to the site being migrated (e.g. a Community site can be blocked because `PowerPortals_ProgramRegistrationCore` is installed env-wide). Install the flagged V2 via `pac application install --application-name "<V2>"` (or uninstall the stray V1 solution), then re-run. **Do not** relabel this site's template — the template was determined in step 1.3.

   Follow [Package installation progress](#package-installation-progress) for any approved precheck-triggered install, even if metadata migration is already complete. Show the actual flagged package in the banner, preserve migration progress, and clear the bar only after installed-package verification or when handing control back to the user.

2. **Monitor & Poll**

   Poll every 1 minute, up to 30 attempts (approximately 30 minutes plus command runtime), using the portable helper. It checks immediately, waits 60 seconds between attempts, and never sleeps after the final check. Run it in the background using the host's supported process/task tool so the main conversation remains responsive. Do not request approval for these read-only status checks.

   PAC keeps the top-level tracker `Running` after a metadata-only `configurationData` run because Phase 3 still needs to migrate configuration-data references. For that mode, `Current Step: ConfigurationDataCompleted` means **metadata migration is finished**. A top-level `Completed` also confirms metadata completion, even without that current step. For `all`, wait until the top-level tracker reaches `Completed`. Always match the labeled fields instead of searching the whole response for `Completed`, because step names and step history also contain that word. When naming this check in the terminal, use the plain-language heading **"Check metadata migration status"**.

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" poll --website-id "<WEBSITE_ID>" --mode "<MODE>" --output-dir "<OUTPUT_DIR>"
   ```

   Before launching, set the now-running banner to "Migrating configuration metadata to EDM". While the helper runs, consume its JSON progress records and pass each record's serialized `operation` object to `update-state.js --set-operation`. Clear the banner after the helper exits and before any approval prompt. **The agent is the sole report-state writer:** the background helper only writes status artifacts, avoiding concurrent state/report overwrites.

   Read `outcome` from the last JSON progress record (also saved in `migration-status.json`). Exit codes: `0` = successful milestone, `2` = poll window elapsed without a terminal result, `1` = Failed/Reverted or a status-check error. A missing executable, failed PAC command, or unrecognized status response is **not** a successful migration.

   - **`outcome` is `ConfigurationDataCompleted` or `Completed`**: mark step 2.2 completed and immediately execute step 2.3. **This transition has no approval gate: do not ask the user whether to proceed and do not describe the migration as stuck.**
   - **`outcome` is `TimedOut` with status still `Running`**: this usually just means the migration is still working — large sites process in 5K-record batches and can take a long time. **Recommend the user wait and keep polling** rather than resetting. Re-run the same helper and show elapsed time (from the tracker's `Created On` / `Modified On` in `rawOutput`). Only if it stays `Running` with **no forward progress for an extended period** (`Modified On` not advancing, no newly completed chunks) treat it as genuinely stuck — see **"Unblocking a stuck `Running` tracker"** below.
   - **Failed / Reverted**: surface error, ask user (retry / reset / exit).
   - **`outcome` is `CheckFailed`, or a non-running status exhausts the window**: show the diagnostic and latest `migration-status.txt`. Resolve the command/output issue or verify the tracker directly; do not mark the step completed or reset a migration merely because a status check failed.

   > **Unblocking a stuck `Running` tracker.** A top-level `Running` status with `ConfigurationDataCompleted` is expected after `configurationData`; proceed to customization remediation and Phase 3 rather than resetting it. For `all`, or when the current step has not reached the mode-specific milestone, wait first. If it is genuinely stuck for an extended period:
   > 1. Preserve status/history/chunks and timestamps, show the reset warning from step 1.4, and obtain **explicit reset approval** using the report-wide required-action notice. A polling-window timeout alone never authorizes reset.
   > 2. Only after approval, run the supported reset: `pac pages migrate-datamodel --webSiteId "<WEBSITE_ID>" --resetMigration`. Recheck status and verify that it actually cleared `Running` before retrying.
   > 3. Retry only the interrupted, approved mode and resume polling. If reset fails or its result is uncertain, stop and retain diagnostics for support; do not automatically edit tracker fields in Dataverse.
   >
   > Reset only unblocks a new run — it does **not** undo already-migrated records.

   > **Why this matters:** shell-specific PATH differences and unchecked subprocess failures can turn a failed status query into endless polling. The helper launches PAC directly from the agent process, checks its exit status, matches the labeled tracker fields, and enforces the attempt limit without requiring any particular shell.

**Output**: Metadata moved to EDM tables; site activation still SDM until step 3.3 flips it. Newer PAC builds auto-emit `SiteCustomization*.csv` here; **older builds do not** — step 2.3 will fall back to running the explicit `--siteCustomizationReportPath` command. Don't assume the CSV exists yet.

> **→ Update report:** `--clear-operation` and `--set-step 2.2 --status completed --output "Metadata migration <COMPLETED|FAILED> · mode=<MODE>"`

---

### 2.3 Locate Customization Report

**Goal**: Find the CSV PAC auto-generated in step 2.2; fall back to explicit generation if PAC didn't produce one (older builds).

**Actions**:

1. **Search for the auto-generated CSV**

   Search `<OUTPUT_DIR>`, its parent, and the current working directory for `SiteCustomization*.csv`. Reuse a report only when its originating run and applicability to the selected website are verified. A high filename number or recent timestamp alone is not proof: these locations can contain reports for other sites. If provenance is unclear, show the candidate paths and ask the user to select/confirm the applicable report using `--set-input`; clear it after the decision. Retain the original CSV and record whether it was generated or explicitly reused.

2. **Fallback if no applicable report is available**

   Keep this compatibility fallback for older PAC builds and missing reports; do not rerun configuration migration merely to obtain a CSV. Use the helper so the explicit report request retains the tracker snapshots and verifies the artifact:

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Generating customization report"}'
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" report --website-id "<WEBSITE_ID>" --output-dir "<OUTPUT_DIR>"
   node update-state.js --output-dir "<OUTPUT_DIR>" --clear-operation
   ```

   Clear the banner even if the helper fails. Read `customization-report-attempt.json`: it preserves `before`, the report `command` output/exit status, `after`, `trackerChanged`, and new/updated `csvPaths` / `invalidCsvPaths`. It never replaces `migration-status.json` or the already-verified step 2.2 milestone.

   - **`ReportGenerated`**: verify that the CSV applies to the selected site before parsing. Header-only reports can legitimately contain zero findings; an absent, empty or invalid CSV cannot.
   - **`ReportSelectionRequired`**: show the changed candidate paths and confirm provenance; do not silently take the newest file.
   - **`ReportMissingOrInvalid` / `CommandFailed` / `CheckFailed`**: show the saved diagnostic. Exit `0` from PAC with only precheck output does **not** prove report generation. Offer a verified existing CSV or pause for investigation; do not mark step 2.3 completed, invent zero findings, or repeatedly invoke the fallback.
   - **`TrackerChanged` or `trackerChanged=true`**: show both tracker snapshots, any CSV candidates, and the command result. For example, `Running / ConfigurationDataCompleted` may change to `Running / PrecheckCompleted`. Preserve the earlier metadata-completion evidence, but do not assume the new tracker is ready for references, reset it, or rerun metadata. Pause with `--set-input` for review/recheck or stop. If a references start is subsequently refused, follow [References start refusal recovery](#references-start-refusal-recovery).

   If verbose status is unavailable and the current step cannot be verified, inspect the tracker read-only before proceeding; do not bypass the guard by invoking the report command directly.

   > **Official ordering:** The [Microsoft guide](https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model) places explicit report generation in prechecks, before configuration migration. Keep the existing auto-emitted-report-first flow and this guarded fallback until that reordering is validated against supported PAC builds; do not add another automatic report request.

3. **Parse Report**

   Read the CSV and categorize findings:
   - Liquid contains adx references
   - Data Model Extension (custom columns on adx tables)
   - Plugins registered on adx entities
   - Custom workflows
   - Relationships between custom and adx tables
   - FetchXML with adx references

   > **Important:** The CSV's `Location` column contains paths to PAC's internal scan temp folder (e.g., `\\?\C:\Users\...\Temp\<site-slug>/web-templates\X\Y.html`). **Do NOT** use those paths to locate or modify files. They're informational only — for actual rewrites use the path captured in step 1.2 (`<SITE_ROOT>`).

4. **Generate HTML Customization Report**

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/generate-migration-reports.js" --customization-report "<OUTPUT_DIR>/SiteCustomization.csv" --site-name "<SITE_NAME>" --website-id "<WEBSITE_ID>" --template-name "<TEMPLATE_NAME>" --output-dir "<OUTPUT_DIR>"
   ```

   This creates `<OUTPUT_DIR>/customization-report.html` alongside the CSV.

5. **Present Findings**

   Show summary of customizations found (by category) or "No customizations found" if clean.

**Output**: Customization report located/generated and parsed. Findings summary available.

> **→ Update report:**
>
> ```
> --set-step 2.3 --status completed --output "CSV: <PATH> · <N> findings total · <BREAKDOWN_BY_CATEGORY>"
> --set-customization-report '{"path":"<ABSOLUTE_PATH_TO_OUTPUT_DIR>/customization-report.html","csvPath":"<ABSOLUTE_PATH_TO_OUTPUT_DIR>/SiteCustomization.csv","totalFindings":<N>,"breakdown":{"fetchxml":<N>,"liquid":<N>,"dme":<N>,"plugins":<N>,"workflows":<N>,"relationships":<N>}}'
> ```
>
> Pass absolute paths so the live report's "Open customization-report.html" link works no matter where the user opens the report from. Omit any breakdown keys with zero count.
>
> **📄 Checkpoint 3 — Tell the user about the customization report.** Print in chat:
>
> ```
> 📄 Customization findings catalog:
>    <ABSOLUTE_PATH_TO_OUTPUT_DIR>/customization-report.html
>
> Open this in your browser to review the per-finding details before remediation starts.
> ```

---

### 2.4 Remediate Customizations

**Goal**: Distinguish expected scan references from actual customization work, then stage and approve only necessary changes. SDM source is already downloaded into `<SITE_ROOT>` from step 2.1; this step works against that tree. Configuration **metadata** has migrated; references migration, activation and runtime validation are not complete yet.

> **A scan reference is not automatically a defect or a risk.** PAC can flag expected logical-name access and operational-table usage. Classify each finding from this customer's current source, not conversation memory, template ownership, or a previous customer's successful smoke test. Keep the original CSV for traceability. Zero proposed changes does **not** mean all findings are reviewed.

**Actions**:

### 1. Categorize findings: what to fix vs. leave alone

| Customization category | Action | Reasoning |
|---|---|---|
| FetchXML targeting a mapped metadata entity or link-entity | **Stage supported rewrite** | Use the generator's component type map; inspect skipped blocks and approve the diff before applying |
| Liquid `entities['adx_*']` collection | **Semi-auto fix (user reviews)** | Doc shows replacing with dedicated Liquid object (`weblinks`, `snippets`, etc.). Semantics may shift; user must approve |
| Liquid property access (`page.adx_X`, `website.adx_X`, `botconsumer.adx_X`) | **Leave alone** | Documented `[logical_name]` accessor; works on EDM via virtualization |
| Liquid `{% editable page 'adx_*' %}` tag | **Leave alone** | Uses logical attribute name; same access rule |
| Liquid `snippets['adx_*']`, `weblinks['adx_*']` | **Leave alone** | Index is a user-defined name, not an attribute |
| Data Model Extensions (custom columns on mapped metadata tables) | **Manual only** | Per migration doc, the fix is to create a new custom table with a lookup to `powerpagecomponent` and migrate data — multi-step schema operation, not automatable safely |
| Relationships between custom and `adx_*` tables | **Manual only** | New relationship to `powerpagecomponent`-side; user-driven |
| Custom plugins/workflows on `adx_*` tables | **Manual only** | Code refactor + re-registration — semantic, not mechanical |

Generate/read `customization-assessment.json` alongside `customization-report.html` using the report generator from step 2.3. It separates `informational`, `actionable`, and `needsReview`, with a reason and the original evidence for each finding. These are initial static assessments, **not completed manual fixes** or runtime-test results. Category counts are not severity ratings.

For `needsReview`, inspect the full matching local file and its consumers, not only PAC's possibly truncated snippet. Confirm the file belongs to this run/site before classifying it. Use these reusable context checks:

| Scan pattern | Check before treating as informational / no change required |
|---|---|
| `page.adx_copy`, `website.adx_partialurl`, editable logical attributes, `forums_sm.adx_name` | Confirm logical-property or editable access only; no direct migrated-table query or mixed unclassified reference. Preserve supported legacy logical names. |
| `incident.adx_publishtoweb`, `incident.adx_resolutiondate`, `incident.adx_resolution`, `incident_adx_portalcomments` | Confirm these are business/operational attributes or navigation references, not metadata-table queries. An `adx_` substring alone does not require an EDM rewrite. |
| Client-side labels such as `{{#label entityLogicalName 'adx_event'}}`, `adx_eventschedule`, `adx_issue` | Confirm client-side label/template context and actual consumers. Do not mistake a display-label argument for a Liquid entity collection. |
| FetchXML querying `category` or `knowledgearticle` | Read the entire query, including links, filters and dynamic names. If no migrated metadata target/consumer exists, record the PAC reference as informational. |
| Forum queries such as `adx_communityforumthread` and fields `adx_forumid`, `adx_postcount` | Verify operational-table schema and consumers. Absence from the metadata map is a reason to investigate, **not** proof of a broken customization or permission to invent a rewrite. |
| `botconsumer.adx_configjson`, `botconsumer.adx_botschemaname` | Confirm supported logical-property access and configuration consumers; preserve values rather than rewriting attributes solely because of the prefix. |

Use the [migration metadata-table guidance](https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model) and [Liquid objects documentation](https://learn.microsoft.com/en-us/power-pages/configure/liquid/liquid-objects) to verify context. A comment-only reference can be informational after confirming it is not executable Liquid or consumed elsewhere. Never blanket-allow Microsoft/template code or all `adx_*` references.

Record contextual review outcomes through `update-state.js --add-decision` in the live report: affected file/reference, disposition, evidence/reason, and any remaining action. Use stable decision IDs so a re-review updates rather than duplicates the entry. Keep the generated assessment as the initial scan assessment; recorded source-review decisions explain any reclassification. Summarize raw, informational, actionable, needs-review and actual staged-file counts in the step output. Deduplicate identical required fixes without deleting their raw CSV references.

### 2. Branch on findings

- **Zero findings or reviewed informational-only references**: skip steps 3–7 and jump to step 8. Expected references are not deferred fixes.
- **Needs context review**: investigate the full source now. If evidence/tools are unavailable, name the affected items and offer **Inspect affected files / Provide missing context / Pause**. Do not silently classify them as safe, completed, or critical.
- **Confirmed actionable findings**: run the applicable staging/manual-guidance steps below. Separate proposed source changes from manual work; neither is complete merely because a prompt was generated.

### 3. Stage automated FetchXML rewrites

```text
node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/generate-migration-reports.js" --customization-report "<OUTPUT_DIR>/SiteCustomization.csv" --site-name "<SITE_NAME>" --website-id "<WEBSITE_ID>" --template-name "<TEMPLATE_NAME>" --site-path "<SITE_ROOT>" --automate-fetchxml --output-dir "<OUTPUT_DIR>"
```

Script behavior:

- Walks `.html` and `.yml` files under `--site-path`
- Finds each `<entity name='adx_X'>` block (in `{% fetchxml %}` Liquid tags and YAML `query:` fields)
- Renames entity to `powerpagecomponent` and injects `<condition attribute='powerpagecomponenttype' operator='eq' value='<N>'/>` based on the component type map
- **Writes the proposed file to `<OUTPUT_DIR>/remediation-staged/<relative path>`.** The live `<SITE_ROOT>` is NOT modified — the staged copy is what step 8 applies after user approval.

### 4. Stage semi-automated Liquid `entities['adx_*']` rewrites

```text
node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/generate-migration-reports.js" --customization-report "<OUTPUT_DIR>/SiteCustomization.csv" --site-name "<SITE_NAME>" --website-id "<WEBSITE_ID>" --template-name "<TEMPLATE_NAME>" --site-path "<SITE_ROOT>" --automate-liquid --output-dir "<OUTPUT_DIR>"
```

Script behavior:

- Walks `.html` files for `entities['adx_*']` and `entities["adx_*"]` patterns
- For each match, looks up the suggested dedicated Liquid object (e.g., `entities['adx_weblinkset']` → `weblinks`)
- **Inserts a suggested rewrite as a Liquid comment next to the original** — does NOT overwrite the original line. User decides what to keep.
- **Writes the annotated file to `<OUTPUT_DIR>/remediation-staged/<relative path>`** (merging on top of the FetchXML pass if the same file was touched there).

After both rewriters run, the script emits **`<OUTPUT_DIR>/remediation-diff.json`** — a lean, skill-owned manifest consumed by the live execution report's Remediation Diff card. It carries `generatedAt`, `siteRoot`, `stagedDir`, and `files[]` (each with `relativePath`, `kind: "fetchxml" | "liquid" | "fetchxml+liquid"`, `status: "modified"`, `linesAdded`, `linesRemoved`, `hunks[]`, `changeSummary[]`, and **absolute** `livePath` / `stagedPath`). The report renders one expandable row per touched file with inline hunks plus separate **Copy PowerShell diff command** and **Copy Bash diff command** buttons. Paste the command into the named shell to open VS Code's built-in side-by-side diff editor (current vs proposed); quoting differs between shells, so do not use either command in Command Prompt. No VS Code extension is required.

### 5. Generate augmented prompts for manual categories

The customization report's plugin and DME findings get exported as paste-ready prompts for fresh Claude Code sessions (the skill never modifies customer-owned plugin source or Dataverse schema directly).

DME schema preparation is separate from data copy. Before any extension-row writes,
confirm metadata migration (or the downstream metadata solution import) has completed
for this site/environment and verify every source-to-`powerpagecomponent` mapping.
Missing metadata or mappings require a pause in this conversation, not another
migration command from the standalone prompt. Review data-copy results before
continuing the existing reference-migration and activation approval gates.

The script in step 3/4 also emits:
- `<OUTPUT_DIR>/plugin-remediation-prompt.txt` (if plugin findings exist)
- `<OUTPUT_DIR>/dme-remediation-prompt.txt` (if DME findings exist)

> **→ Update report (only when actual staged proposals exist, before asking for upload approval):**
>
> ```
> --set-step 2.4 --status in-progress --output "Auto-rewrites staged · awaiting diff review"
> --set-prompt plugin --status ready --path "<OUTPUT_DIR>/plugin-remediation-prompt.txt" --summary "<N> custom plugins on adx_* entities"
> --set-prompt dme    --status ready --path "<OUTPUT_DIR>/dme-remediation-prompt.txt"    --summary "<N> custom columns across <T> adx_* tables"
> --set-approval 2 in-phase
> ```
>
> (Skip a category's `--set-prompt` unless its prompt file actually exists. If there are no proposals, report "No source changes proposed" with the classification counts; do not claim auto-rewrites were staged or set an apply/upload approval.)

### 6. Review and approve changes

**Proposal gate:** Read `remediation-diff.json`. Only show this checkpoint and approval question when `files[]` is nonempty and the referenced staged files exist. A missing/empty manifest means skip steps 6–7: no apply, discard/edit prompt, or upload. A malformed manifest or missing referenced file is an explicit error to resolve, not a zero-proposal result. Manual actionable work still goes to step 8.

> **📄 Checkpoint 4 — Tell the user where to review.** Print this in chat before asking for upload approval:
>
> ```
> 📄 Auto-rewriters staged proposed changes. Review them in the live report:
>    <ABSOLUTE_PATH_TO_OUTPUT_DIR>/datamodel-migration-report.html
>
> Open the "Migration & Review" tab — the Remediation Diff card shows one
> expandable row per touched file with inline hunks. Click "Open staged file"
> on any row to view it in VSCode.
>
> Augmented prompts (work in parallel, in separate Claude sessions):
>    <ABSOLUTE_PATH_TO_OUTPUT_DIR>/plugin-remediation-prompt.txt   (if plugin findings)
>    <ABSOLUTE_PATH_TO_OUTPUT_DIR>/dme-remediation-prompt.txt      (if DME findings)
>
> Your live site source under <SITE_ROOT> is UNTOUCHED — staged files live
> under <OUTPUT_DIR>/remediation-staged\ and are only applied when you approve.
> ```

| Question | Header | Options |
|----------|--------|---------|
| Review the Remediation Diff card in the live report. Apply the staged changes to your site source and upload to Dataverse? | Approve Rewrites | Yes — apply and upload, No — discard staged changes, Let me edit the staged files first |

### 7. Apply staged changes and upload to Dataverse

Branch on the user's answer:

**Yes — apply and upload:** copy staged files over the live source, then upload.

```text
node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/apply-remediation.js" --output-dir "<OUTPUT_DIR>" --site-root "<SITE_ROOT>"

node update-state.js --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Uploading remediated site source"}'
pac pages upload --path "<SITE_ROOT>" --modelVersion 1
node update-state.js --output-dir "<OUTPUT_DIR>" --clear-operation
```

`apply-remediation.js` reads `remediation-diff.json`, copies each staged file over its live counterpart, and deletes both the `remediation-staged/` directory and the diff manifest on success so the live report does not retain broken staged-file links. `--keep-staged` retains both artifacts. Pass `--dry-run` first if you want to print the planned copies without executing.

**No — discard staged changes:** delete the staged tree and the diff manifest; live source remains untouched.

```text
node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/apply-remediation.js" --output-dir "<OUTPUT_DIR>" --discard
```

**Let me edit the staged files first:** the user hand-edits files under `<OUTPUT_DIR>/remediation-staged\` (changes preview live in the report on refresh). When done, re-ask the approval question.

> **PAC CLI argument notes:**
>
> - `pac pages upload` does **not** accept `--webSiteId` — the site is inferred from `website.yml` inside `<SITE_ROOT>`. If you pass `--webSiteId`, PAC errors with "An unknown argument --webSiteId was passed."
> - `--modelVersion 1` = SDM (the site's activation is still SDM at this point, since step 3.3 hasn't flipped it yet).
> - `<SITE_ROOT>` must point at the directory containing `website.yml` (not the `<MIGRATION_OUTPUT_DIR>/site-sdm` wrapper).

> **→ Update report (after upload completes):** `--clear-approval`. The in-phase gate is now resolved.

### 8. Final readiness gate

After approved proposals are uploaded (or no source changes were proposed), reconcile every actionable/manual item against actual completion evidence. Handing off a prompt, discarding changes, or producing zero rewrites does not complete an item.

**No unresolved actionable items and no unresolved context review** (including informational-only references):

| Question | Header | Options |
|----------|--------|---------|
| Configuration metadata has migrated. `<N>` expected references require no changes; `<M>` actual changes are verified complete. Continue to Phase 3, or review the expected references once? | Migration Readiness | Continue to Phase 3, Review expected references (optional), Pause |

- **Continue**: continue through the existing Phase 3 approval gate. Do not ask for a risk acknowledgment for expected references.
- **Review expected references**: show file/context/reason, then return to this choice; this is optional verification, not remediation.
- **Pause**: halt cleanly.

**Actual actionable customizations remain unreviewed or unfixed:** list the specific files/components, required actions and concrete possible impact, then ask **Finish/review fixes now / Defer these named items and proceed (acknowledge their risk) / Pause**. Record any explicit deferral and its scope in the execution report; never turn raw scan counts or expected references into a blanket risk warning. Unresolved context-review items follow step 2's investigation choices instead of being silently bundled into deferral.

**Output**: Classification/review evidence recorded; actual proposals applied/uploaded only if approved; manual outcomes or specifically acknowledged deferrals recorded; readiness gate confirmed. Keep the pre-refs metadata comparison and all later approval gates unchanged.

> **→ Update report (end of Phase 2 Authoring Track):**
>
> ```
> --set-step 2.4 --status completed --output "<N informational; M fixes verified; K named items explicitly deferred> · readiness confirmed"
> --set-phase 2 --status completed
> --set-approval 3 phase-start
> ```
>
> **📄 Checkpoint 5 — Tell the user about the report before asking for Phase 3 approval.** Print in chat:
>
> ```
> 📄 Phase 2 complete. Review the outcomes in your browser before approving Phase 3:
>    <ABSOLUTE_PATH_TO_OUTPUT_DIR>/datamodel-migration-report.html
>
> The report shows: scan assessments, actual fixes and any named deferrals, SDM snapshot captured, and the
> Phase 3 sub-steps that will run if you approve.
> ```
>
> Then ask the user to approve Phase 3 via AskUserQuestion. On approval, run `node update-state.js --output-dir "<OUTPUT_DIR>" --approve-and-start 3` to atomically clear the approval gate and mark Phase 3 in-progress.

---

## Phase 2 — Downstream Track

**Applies when**: state.track === 'B' (mode = `configurationDataReferences`)

**Goal**: Verify that configuration metadata is already present in the target environment (typically loaded via ALM solution import). If missing, offer the user three import paths (ALM skill / Solution Import / PAC CLI). No data is migrated yet — Phase 3 does the transactional migration.

**Output**: Configuration metadata confirmed available in target environment, ready for Phase 3.

---

### 2.1 Verify Site in Target Environment

**Goal**: Confirm the site exists in the currently-authenticated environment by listing sites via PAC.

**Actions**:

1. **List sites in target env**

   ```text
   pac pages list -v
   ```

   Parse output and look for a row matching `<WEBSITE_ID>`.

2. **Branch on result**

   - **Site found**: ALM has likely brought the site (and its metadata) into the target env. Ask the user:

     | Question | Header | Options |
     |----------|--------|---------|
     | Site `<SITE_NAME>` (ID `<WEBSITE_ID>`) is present in this environment. Has the configuration metadata been imported (via ALM, solution import, or PAC CLI)? | Metadata Imported | Yes, metadata is imported, No, I still need to import it |

     - **Yes**: skip step 2.2, jump straight to 2.3.
     - **No**: proceed to step 2.2.

   - **Site NOT found**: this is unexpected for a Prod env. Surface the issue:

     | Question | Header | Options |
     |----------|--------|---------|
     | Site is not visible in the target environment via `pac pages list -v`. The site needs to be imported before this skill can proceed. How would you like to import? | Import Path | Use ALM skill (recommended), Solution Import (manual), PAC CLI import (manual), Cancel — investigate first |

     Whatever the user picks routes into step 2.2.

**Output**: Site presence confirmed; user has either verified metadata is imported (→ 2.3) or chosen an import path (→ 2.2).

> **→ Update report:** `--set-step 2.1 --status completed --output "Site <found|not found> in target env · user response: <response>"`

---

### 2.2 Import Metadata if Missing

**Goal**: Guide the user through one of three import paths so configuration metadata lands in the target env's EDM tables.

**Actions**:

Before handing off any manual import work, show `--set-input '{"requiredAction":"Import the site configuration metadata using the chosen method, then return to the migration conversation to confirm completion."}'`. Keep it visible while the user is away; clear it when they return before the existing step 2.1 re-verification.

Based on the user's choice in 2.1, run one of:

**Option (a) — Use ALM skill**

The team's ALM skill handles solution-based ALM workflows including metadata import. Look it up:

Use the host's skill discovery or Glob tool to find installed ALM skills (for a checkout, pattern `plugins/**/skills/*alm*/SKILL.md`). Search the host's installed-plugin locations, not a Windows-specific relative path.

- **If found**: print a hand-off message to the user: "To import configuration metadata, please run **/<alm-skill-name>** in your current Claude Code session. Once it reports successful import, resume this skill by re-confirming Phase 2 readiness."
- **If not found**: print "ALM skill not available in installed plugins. Falling through to manual options." and present (b) and (c) below.

**Option (b) — Solution Import**

Print instructions:

> "Open Power Platform admin center → your target environment → Solutions → Import. Import the site's exported solution package (built from your Dev environment). Once import completes, return here."

**Option (c) — PAC CLI Import**

Print the command for the user to run:

```text
pac solution import --path "<PATH_TO_SOLUTION_ZIP>" --activate-plugins true --publish-changes true
```

> Instruct the user to provide the path to their site's exported solution package.

After whichever option, loop back to **step 2.1** to re-verify the site is now present.

**Output**: Configuration metadata imported via the chosen path; site now visible in the target environment.

> **→ Update report:** `--set-step 2.2 --status completed --output "Imported via <ALM|Solution|PAC>"` (or `--status pending` and re-run 2.1 if the user needs another import attempt).

---

### 2.3 Confirm Metadata Ready

**Goal**: Final user-facing gate before Phase 3 starts moving transactional data.

**Actions**:

| Question | Header | Options |
|----------|--------|---------|
| Configuration metadata is available in the target environment? Phase 3 will run `pac pages migrate-datamodel --mode configurationDataReferences` to migrate transactional references onto the metadata that's already in place. | Metadata Ready | Yes, proceed to Phase 3, No, pause — I need more time, Cancel — stop the skill |

- **Yes**: proceed to Phase 3.
- **No**: halt skill cleanly; user can re-invoke later.
- **Cancel**: halt skill cleanly.

**Output**: User has confirmed configuration metadata is ready; skill proceeds to Phase 3.

> **→ Update report (end of Phase 2 Downstream Track):**
>
> ```
> --set-step 2.3 --status completed --output "Metadata ready · proceeding to Phase 3"
> --set-phase 2 --status completed
> --set-approval 3 phase-start
> ```
>
> **📄 Checkpoint 5 — Tell the user about the report before asking for Phase 3 approval.** Print in chat:
>
> ```
> 📄 Phase 2 complete. Review the outcomes in your browser before approving Phase 3:
>    <ABSOLUTE_PATH_TO_OUTPUT_DIR>/datamodel-migration-report.html
>
> The report shows: customization findings handled, SDM snapshot captured, and the
> Phase 3 sub-steps that will run if you approve.
> ```
>
> Then ask the user to approve Phase 3 via AskUserQuestion. On approval, run `node update-state.js --output-dir "<OUTPUT_DIR>" --approve-and-start 3` to atomically clear the approval gate and mark Phase 3 in-progress.

---

## Phase 3: Migration Execution (track-branched)

Phase 3 has **two different shapes** depending on the migration track. The Authoring Track is shorter (4 sub-steps) because customization remediation already happened in Phase 2.4. The Downstream Track is longer (6 sub-steps) because customizations get scanned and remediated here (Phase 2 for the Downstream Track was just metadata verification). **Both tracks start with the same pre-flight check (3.1):** a metadata-only SDM↔EDM diff that confirms the metadata migration in Phase 2 (Authoring) or the upstream ALM import (Downstream) landed cleanly before the refs migration runs.

- [**Phase 3 — Authoring Track**](#phase-3--authoring-track) — Authoring Track (mode = `configurationData` or `all`). 4 sub-steps: verify metadata diff → migrate refs → activate → restart.
- [**Phase 3 — Downstream Track**](#phase-3--downstream-track) — Downstream Track (mode = `configurationDataReferences`). 6 sub-steps: verify metadata diff → migrate refs → locate customization report → remediate → activate → restart.

---

## Phase 3 — Authoring Track

**Applies when**: state.track === 'A' (mode = `configurationData` or `all`)

**Goal**: Verify the metadata migration succeeded via an SDM↔EDM diff, then migrate transactional references (skipped if mode=all already covered them), activate EDM, and perform an approved API restart with a manual fallback. Customization handling is **not in this phase** — Phase 2.4 already cleaned things up.

**Output**: Metadata diff confirmed, transactional refs migrated (or skip if mode=all), site activated on EDM, API restart verified or manual restart confirmed by the user.

---

### 3.1 Data Diff Validation (SDM ↔ EDM Metadata)

**Goal**: Before running the refs migration, re-download the site as EDM, snapshot it, and diff against the SDM baseline captured in Phase 2.1. Surface the result so the user can decide whether to proceed with refs migration or pause to investigate. The Pages & Components card in the live report visualizes the per-category comparison.

**Why pre-refs:** at this point only metadata has been migrated (Phase 2.2 for Authoring; assumed via ALM solution import for Downstream) — refs haven't run yet. Catching a metadata mismatch here means the user can fix the source and re-run without having to roll back a completed migration.

**Actions**:

1. **Re-download the migrated site as EDM**

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Downloading EDM site source"}'
   pac pages download --webSiteId "<WEBSITE_ID>" --modelVersion 2 --path "<MIGRATION_OUTPUT_DIR>/site-edm"
   node update-state.js --output-dir "<OUTPUT_DIR>" --clear-operation
   ```

   Resolve the downloaded root with `node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" discover --path "<MIGRATION_OUTPUT_DIR>/site-edm" --require-site`. Capture the returned `siteRoot` as `<SITE_ROOT_EDM>`; do not assume the first directory is the site.

2. **Snapshot the EDM site**

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/snapshot-site.js" --site-root "<SITE_ROOT_EDM>" --output-dir "<OUTPUT_DIR>" --label edm
   ```

   Output: `<OUTPUT_DIR>/edm-snapshot.json`. The live report's **Pages & Components** card now shows `SDM → EDM` per-category pills.

3. **Diff SDM vs EDM**

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/diff-snapshots.js" --sdm "<OUTPUT_DIR>/sdm-snapshot.json" --edm "<OUTPUT_DIR>/edm-snapshot.json" --output-dir "<OUTPUT_DIR>"
   ```

   Output: `<OUTPUT_DIR>/migration-data-diff.json` + console table grouped by category. Exit code: `0` for pass or warn, `1` for fail.

   Per-category status:
   - **pass** — same identity set, no differences
   - **warn** — identity match but some records changed statecode/value/content (including a companion content hash present on only one side), OR an SDM-only category (e.g., `tags`, `websiteBindings`) shows 0 records in EDM (expected — EDM YAML format doesn't surface those; records still in `powerpagecomponent`)
   - **fail** — records actually missing/extra (excluding SDM-only categories), ambiguous duplicate identities, or parse errors in either snapshot. Parse errors are retained in the diff output; repair the baseline/download before treating the comparison as complete.

   **Nonconfiguration feature handling:** The Microsoft EDM documentation defines Ad, Poll, Poll Option, Poll Submission, External Identity, Portal comment, Invitation, Invitation Redemption, Setting, and WebFormSession as nonconfiguration tables. These categories are outside the SDM↔EDM metadata comparison and do not affect the diff status or migration totals. File-backed categories remain in the raw snapshots for audit evidence, while the live report lists the complete documented set and distinguishes detected data from categories not represented by the site download. `pollPlacements` remains in the metadata comparison because it is virtual configuration represented by the EDM component model; a missing placement is still a migration finding.

4. **Surface the diff and gate refs migration**

   > **📄 Checkpoint 7 — Tell the user about the diff result.** Print in chat:
   >
   > ```
   > 📄 Metadata diff complete. Review:
   >    <OUTPUT_DIR>/migration-data-diff.json
   >    <MIGRATION_OUTPUT_DIR>/datamodel-migration-report.html
   >
   > Status: <PASS | WARN | FAIL>
   >    <N> records missing in EDM
   >    <M> extra records in EDM
   >    <S> records with state changes
   > ```

   Before the pre-refs question, show `--set-input '{"requiredAction":"Review the SDM-to-EDM metadata diff, then choose whether to proceed with transactional references migration."}'`. Clear it after the user chooses to proceed, pause, or cancel; the notice itself is not approval.

   Then ask:

   | Question | Header | Options |
   |----------|--------|---------|
   | Metadata diff status: `<PASS\|WARN\|FAIL>`. `<N>` missing, `<M>` extra, `<S>` state-changed. Ready to proceed to the transactional references migration? | Pre-Refs Gate | Looks good — proceed to refs migration, Let me review the diff first, Cancel — stop the skill |

   - **Looks good**: proceed to step 3.2.
   - **Let me review the diff first**: halt Phase 3 cleanly. User can review the diff and, if needed, fix the metadata source (re-import solution / re-run Phase 2.2 in Authoring) and re-invoke the skill from this point.
   - **Cancel**: halt cleanly.

**Output**: Metadata SDM↔EDM diff complete, user has decided whether to proceed with refs migration or pause.

> **→ Update report:** `--set-step 3.1 --status completed --output "Metadata diff: <PASS|WARN|FAIL> · <N> missing · <M> extra · <S> state-changed · user chose: <choice>"`

---

### 3.2 Migrate Transactional References

**Goal**: Run `pac pages migrate-datamodel --mode configurationDataReferences` to move transactional data references. Skip if mode was `all` in Phase 2.2.

**Actions**:

1. **Check whether to skip**

   - If `state.site.migrationMode === 'all'`: refs were already migrated in Phase 2.2. Mark this sub-step completed with output `"Skipped — refs already migrated in Phase 2.2 (mode=all)"` and proceed to step 3.3.
   - Otherwise: proceed with the migration command below.

2. **Execute Migration Command**

   After the existing pre-refs approval, use the wrapper to retain the command result and immediately capture status:

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" start-references --website-id "<WEBSITE_ID>" --output-dir "<OUTPUT_DIR>"
   ```

   Read `references-start.json`. Only `outcome=StartAccepted` enters normal polling; this means the command was accepted, **not** that references completed. For `StartRefused`, `StartFailed`, or `CheckFailed`, clear the banner, surface the command output and captured tracker, and follow [References start refusal recovery](#references-start-refusal-recovery). Do not poll an unstarted operation for 30 minutes or silently retry it. Newer PAC versions may auto-emit `SiteCustomization*.csv`.

3. **Poll Status with Verbose Output**

   Use the same portable helper with mode `configurationDataReferences`. It runs the read-only verbose status query every 60 seconds, up to 30 attempts, preserving the complete response for the existing **Transactional References Migration** card.

   > **Run this automatically in the background — do not ask the user to confirm before checking status.** Checking migration status (`-s -v` / `--checkMigrationStatus`) is a read-only, non-destructive query. Poll it silently and only surface a message when the status reaches a terminal state (Completed / Failed / Reverted) or genuinely appears stuck. Apply this to **any** read-only check in this skill: never gate a status/read operation behind a user confirmation.

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" poll --website-id "<WEBSITE_ID>" --mode configurationDataReferences --output-dir "<OUTPUT_DIR>"
   ```

   Before launching, set the now-running banner to "Migrating transactional references". While the helper runs in the background, consume each JSON progress record and interpret its `rawOutput` using the existing tracker schema below. After each captured attempt, serialize the interpreted object and invoke `update-state.js --set-refs-migration` with that JSON as a single argument, then pass the record's serialized `operation` to `--set-operation`. Keep these report updates sequential; the helper does not write report state. If tool output is truncated, read `migration-status.json` / `migration-status.txt` rather than guessing omitted chunks. **Always refresh the card once more from the final saved response and clear the banner when the helper exits**, including on failure or timeout.

   | Report field | Source in the complete response |
   |---|---|
   | `status` | `Current migration status is :` (`NotStarted`, `Running`, `Completed`, `Failed`, `Reverted`, `Unknown`) |
   | `currentStep` | `Current Step:` under Migration Step Details |
   | `createdAt`, `modifiedAt` | Created On / Modified On from Migration Tracker Summary, normalized to ISO 8601 |
   | `stepHistory` | `{ step, at }` entries from ConfigurationDataReferencesStarted onward; exclude earlier metadata steps |
   | `runs` | Every Migration Run block: `{ name, chunkTotal, completed, succeeded, chunks }` |
   | `runs[].chunks` | **Every** Chunk Details row, including successes: `{ name, runStatus, outcome, errorType, errorDetails }`; use the migrated entity/table for `name` and null error fields for successes |
   | `error` | Top-level command/tracker failure details, when present; keep per-chunk errors on their chunk records |

   The helper owns timing, bounded attempts, and tracker terminal-state detection. Report updates and detailed history/chunk interpretation remain the agent's responsibility, just as before; do not replace them with fabricated zero counts or drop successful chunks. Pass real serialized JSON, not the literal text `<PARSED_JSON>`. For retry backoff use `node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" delay --seconds 60`.

   - **Completed**: clear the now-running banner (`--clear-operation`), proceed to step 3.3. The card now shows status=Completed.
   - **Still `Running` (`outcome=TimedOut`, exit `2`)**: recommend the user **wait and keep polling** (refs migration on large sites can take a long time). A polling-window timeout is not a migration failure. Only if genuinely stuck for an extended period (`Modified On` not advancing, no newly completed chunks), follow the explicitly approved, verified supported-reset procedure in step 2.2. The card shows the last captured running state.
   - **Failed / Reverted**: surface error, ask user (retry / reset / exit). Add the top-level failure message to the `--set-refs-migration` payload's `error` field so the card logs it as an error banner (the card also shows chunk-level error details from the last poll).
   - **`CheckFailed` or any other unresolved status**: surface the saved diagnostic; do not continue to activation or treat a status-query failure as a migration failure requiring reset.

   > **Chunk-level generic SQL errors — auto-retry before escalating.** When individual chunks fail with a **Generic SQL error** (e.g., `1205` deadlock victim, `3732` type still referenced), these come from the **Dataverse SQL backend, not PAC/client-side**. Under chunked migration most are transient — `1205` is always a deadlock retry, and `3732` ("type still referenced") is frequently a concurrency side-effect from parallel chunk processing that clears on a fresh pass. **The refs migration is resumable**: re-running `pac pages migrate-datamodel --webSiteId "<WEBSITE_ID>" --mode configurationDataReferences` re-processes only the still-unmigrated chunks, so a retry is cheap and non-destructive. **Automatically retry the command up to 3 times** (30–60s backoff between attempts, re-entering the poll loop each time) whenever the only failures are chunk-level generic SQL errors — **do this even when the tracker labels a chunk `Non Retriable`**, because that label reflects PAC's in-run retry classification, not whether a fresh command invocation can succeed. Only escalate if the **same** chunks still fail with the **same** generic SQL error after the retries: capture the failing chunk IDs, error numbers, `pac --version`, WebSiteId, and environment URL for a Microsoft support ticket. Do **not** proceed to step 3.3 (Activate EDM) until refs migration reports `Completed`.

   > **PAC build compatibility:** The helper falls back to plain `--checkMigrationStatus` only for the explicit unknown-`--verbose` argument error. When `verboseSupported=false`, emit a smaller refs payload with only fields actually returned (`status` and `currentStep` when available). For metadata-only `configurationData`, a non-verbose Running response cannot prove the ConfigurationDataCompleted milestone; verify `currentStep` directly in Dataverse rather than guessing or offering reset.

**Output**: Transactional references migrated (or step skipped because mode=all). Live report's Transactional References Migration card reflected real-time progress during polling and shows the final completed/failed payload.

> **→ Update report:**
>
> ```
> --clear-operation
> --set-step 3.2 --status completed --output "<Refs migrated · status=<STATUS> | Skipped — already covered by mode=all in Phase 2.2>"
> ```
>
> When this step is skipped because mode=all, also emit a minimal `--set-refs-migration '{"status":"Completed","currentStep":"Skipped — covered by mode=all in Phase 2.2"}'` so the card shows a Completed pill instead of staying empty. Otherwise the polling loop above already emitted the final payload — no extra `--set-refs-migration` call needed here.

---

#### References start refusal recovery

This procedure applies to **both tracks**, and is distinct from polling an accepted references operation or retrying failed SQL chunks.

1. Retain `references-start.json`, `customization-report-attempt.json` if present, and the earlier metadata-completion evidence. Use the captured verbose response to update the references card, including the refusal in `error`; preserve real history/chunks, not fabricated zero counts.
2. Recheck status read-only and compare `Current Step`, `Created On` / `Modified On`, reference step history and chunks. `Running / PrecheckCompleted` after a report request, without evidence of references starting, is a **possible tracker gate**, not proof of an active references run or a confirmed PAC root cause. Missing verbose details are unknown, not evidence that no work exists.
3. If references are progressing, continue read-only polling of that operation; do not reset or submit another start. If already `Completed`, verify the references history/result before continuing. For authentication/command/output errors or uncertain activity, investigate or stop rather than treating them as stale-tracker evidence.
4. If the command is refused and repeated observations show no forward progress or active references work, show the evidence and offer **Recheck / Approve supported reset and retry references / Stop**. Set `--set-input` before asking, explain the step 1.4 reset warning, record the explicit decision, and clear the notice afterward. Earlier approval to migrate references is **not** reset approval.
5. Only after reset approval, run `pac pages migrate-datamodel --webSiteId "<WEBSITE_ID>" --resetMigration` **once**. Recheck and verify the tracker is no longer `Running` and no active work remains. If the reset fails, status is uncertain, or the tracker is still `Running`, stop with diagnostics; do not retry mutations blindly or edit Dataverse tracker fields.
6. Retry **only** `start-references` once, then poll only when `StartAccepted`. Do not rerun metadata, discard remediation, or automatically activate/restart the site. If refused again, stop and retain diagnostics for support instead of entering a reset loop. Require overall references `Completed` before activation.

### 3.3 Activate EDM (Update Data Model Version)

**Goal**: Run `--updateDataModelVersion` to flip the site to EDM.

**Actions**:

1. **Retrieve Portal ID**

   Check the Portal Id state captured in step 1.3:

   - **If marked "captured"** (valid GUID from `pac pages list -v`): use directly — proceed to step 2.
   - **If marked "needs prompt"** (`Unknown`/`N/A`, column missing on older PAC builds, or the column was present but the value couldn't be parsed): ask the user to paste it directly. Don't try to construct a URL.

   **Why no URL construction:** the previous design constructed `<URL_SLUG>.<CLOUD_DOMAIN>` from a Public/UsGov/UsGovHigh/UsGovDod/China lookup so the user could fetch `portalId` from `<URL>/_services/about`. In practice this is brittle — it doesn't cover Preprod/TIE cloud rings, custom-domain sites, or the cases where DNS isn't resolvable from the user's network. Far simpler to just ask the user; they have several ways to find it:

   - **Easiest:** open Power Platform admin center → Resources → Power Pages sites → `<SITE_NAME>` → check the Site details panel for "Portal Id".
   - Or browse to the site URL (whatever it actually is) and append `/_services/about` — paste the `portalId` JSON value.
   - Or query `pac data` against the `mspp_website` / `adx_website` table for the `mspp_portalid` field.

   Before asking for Portal ID, show `--set-input '{"requiredAction":"Provide the Portal ID for this site in the migration conversation. Find it in Power Platform admin center under Power Pages site details."}'`.

   Ask via AskUserQuestion:

   | Question | Header | Options |
   |----------|--------|---------|
   | Step 1.3 didn't capture a usable Portal Id from `pac pages list -v`. Please paste the Portal Id for `<SITE_NAME>`. You can find it in Power Platform admin center → Resources → Power Pages sites → <SITE_NAME> → Site details panel, OR by browsing to your site URL + `/_services/about`. | Portal ID | I'll paste the Portal ID |

   Validate the pasted value is a GUID (`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`). Re-prompt if invalid, keeping the input notice visible. Once valid, store it and `--clear-input` — also needed for rollback in Phase 4.

   > **Do not run the update command until Portal Id is available.** Both `--updateDataModelVersion` and `--revertToStandardDataModel` require Portal Id. See the [public PAC CLI reference](https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/pages#pac-pages-migrate-datamodel).

2. **Confirm Activation**

   Activating EDM is a one-way switch from the user's perspective — the site begins serving from EDM tables, the SDM record is deactivated, and recovering requires the explicit `--revertToStandardDataModel` rollback path in Phase 4.2. Ask explicitly before running the command, even though Phase 3 was already approved at its start:

   Show `--set-input '{"requiredAction":"Confirm in the migration conversation whether to activate Enhanced Data Model for this site. No activation runs until you approve."}'` before the question. Clear the notice once the user answers, including pause/cancel; only the existing Yes choice permits execution.

   | Question | Header | Options |
   |----------|--------|---------|
   | Ready to activate Enhanced Data Model for `<SITE_NAME>` using Portal Id `<PORTAL_ID>`? This deactivates the SDM record and the site will serve from EDM after the restart in step 3.4. | Activate EDM | Yes — activate now, No — pause, I want to verify something, Cancel — stop the skill |

   - **Yes**: proceed to step 3 (execute the command).
   - **No, pause**: halt cleanly; user can re-invoke later to resume from this gate.
   - **Cancel**: halt cleanly.

3. **Execute Update Command**

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Activating Enhanced Data Model"}'
   pac pages migrate-datamodel --webSiteId "<WEBSITE_ID>" --updateDataModelVersion --portalId "<PORTAL_ID>"
   node update-state.js --output-dir "<OUTPUT_DIR>" --clear-operation
   ```

4. **Confirm Switch**

   Inform user: "Data model updated. Site now uses Enhanced Data Model. SDM record has been deactivated."

**Output**: Site flipped to EDM in Dataverse; activation done.

> **→ Update report:**
>
> ```
> --set-site '{"portalId":"<PORTAL_ID>","currentDataModel":"Enhanced EDM"}'
> --set-step 3.3 --status completed --output "Data model flipped to EDM · Portal Id <PORTAL_ID>"
> ```

---

### 3.4 Restart Site (API first, manual fallback)

**Goal**: Restart the activated site so the runtime reloads EDM. This remains in **Phase 3, after activation and before Phase 4 runtime validation**. Phase 3.1's metadata-diff check remains earlier and unchanged.

**Actions**:

1. **Confirm restart and identity**

   Use the captured `<PORTAL_ID>`, saved environment URL `<ENV_URL>`, and confirmed site URL `<SITE_URL>` (`state.site.portalUrl`). The Power Platform API uses **Portal ID**, not the SDM/EDM Dataverse website record ID. If an identifier or URL is missing, collect and verify it; do not guess a site by name or construct its URL.

   Show `--set-input '{"requiredAction":"Approve restarting this Power Pages site via the Power Platform API. The restart can briefly interrupt availability."}'` before asking:

   | Question | Header | Options |
   |----------|--------|---------|
   | EDM is activated for `<SITE_NAME>`. Restart the site now so its runtime reloads EDM? This can briefly interrupt availability. | Restart Site | Restart now via API, I'll restart manually, Pause — stop here |

   - **Restart now via API**: clear the input notice and continue below. Only this explicit answer authorizes `--approved`.
   - **I'll restart manually**: go to the manual fallback without sending an API restart.
   - **Pause**: clear the resolved notice and halt. Do not mark the restart or Phase 3 complete.

2. **Execute the approved API restart and verify readiness**

   Record intent before execution: `--add-decision '{"id":"site-restart","label":"Site restart","choice":"API restart approved; attempt starting","rationale":"Reload the activated EDM runtime before Phase 4 validation"}'`. This records approval, **not** proof that a restart succeeded.

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/update-state.js" --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Restarting Power Pages site","detail":"Requesting the approved API restart, then checking website status and reachability."}'
   node "${CLAUDE_PLUGIN_ROOT}/scripts/restart-site.js" --portal-id "<PORTAL_ID>" --env-url "<ENV_URL>" --website-url "<SITE_URL>" --approved
   ```

   Use the host's background-process tool when available. The helper uses shared PAC/Azure CLI authentication, checks the active environment against `<ENV_URL>`, and verifies Portal ID and site origin against the website API before making **one** restart POST. It never uses the original SDM record ID as the API URL segment.

   The documented [Restart Website API](https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites/restart-website) reports success as HTTP 200. The helper then checks the [website operation status](https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites/get-website-by-id) and anonymous site reachability. It requires two consecutive `OperationComplete` + HTTP 2xx/3xx checks, up to 20 checks at 15-second intervals (plus request runtime). No management token or cookie is sent to the site, and redirects are not followed. Progress records go to stderr; the final JSON result goes to stdout.

   **Always `--clear-operation` when the helper exits, before any prompt.** Interpret its actual result:
   - **`success=true`, `outcome=Ready`, `restartSubmitted=true`**: record "API restart verified; site reachable". This is readiness, **not** proof of EDM functionality; Phase 4 still owns runtime validation.
   - **`restartSubmitted=true` with failed/unconfirmed verification**: the request reached the service. Record the pending result in the `site-restart` decision, surface the actual error, and offer read-only verification, manual verification/restart, or pause. Do not send another restart just because readiness was not confirmed.
   - **`restartSubmitted=null`** (including a network timeout or interrupted attempt): the mutation outcome is uncertain. Do not automatically repeat the POST or claim restart success. Ask the user to verify in the admin center, or pause.
   - **`restartSubmitted=false`**: preflight/auth/API rejection prevented a confirmed restart. Surface the error and offer manual restart or pause. Fix any identity/environment mismatch before attempting either API or manual actions.

   For a **prior confirmed submission** whose readiness still needs checking, use this read-only command instead of sending a second restart:

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/scripts/restart-site.js" --portal-id "<PORTAL_ID>" --env-url "<ENV_URL>" --website-url "<SITE_URL>" --verify-only
   ```

   `--verify-only` never restarts the site. Its success finishes this step **only alongside the recorded prior submission or explicit user confirmation of a completed restart**. A healthy site alone does not prove a restart happened.

3. **Manual fallback, only when chosen or API automation cannot complete**

   Explain the actual API/auth/readiness issue. Show `--set-input '{"requiredAction":"Restart the site in Power Platform admin center, then confirm completion in the migration conversation."}'`. For a submitted or uncertain request, first ask the user to check whether the restart completed; do not blindly request a duplicate restart.

   Direct the user to <https://admin.powerplatform.microsoft.com> → the verified environment → **Resources** → **Power Pages sites** → `<SITE_NAME>` → **Restart**. Ask:

   | Question | Header | Options |
   |----------|--------|---------|
   | Has the site restart completed? | Restart Confirmation | Yes, the site has been restarted, Not yet — I'll check or restart it now, Cancel — stop here |

   - **Yes**: clear the notice and record "Manual restart confirmed by user". Use read-only verification when available; if network/access restrictions prevent probing, preserve that limitation rather than claiming automatic verification.
   - **Not yet**: keep the notice and remain at this gate.
   - **Cancel**: clear the notice and halt. EDM is already activated; do not automatically roll back.

**Output**: API restart verified with the site reachable, or manual restart explicitly confirmed by the user. Record the actual method/result with `--add-decision` using id `site-restart`. Only then complete this restart sub-step and Phase 3; do not move the restart to Phase 4.

> **→ Update report (end of Phase 3 Authoring Track):**
>
> ```
> --set-step 3.4 --status completed --output "<API restart verified; site reachable | manual restart confirmed by user>"
> --set-phase 3 --status completed
> --set-approval 4 phase-start
> ```
>
> **📄 Checkpoint 6 — Tell the user about the report before asking for Phase 4 approval.** Print in chat:
>
> ```
> 📄 Phase 3 complete. The site is on EDM and restarted. Review before approving Phase 4:
>    <ABSOLUTE_PATH_TO_OUTPUT_DIR>/datamodel-migration-report.html
>
> Phase 4 recommends a runtime smoke test and records final validation/rollback
> decisions. The SDM-to-EDM metadata diff was already checked in Phase 3.1.
> ```
>
> Then ask the user to approve Phase 4. On approval, run `node update-state.js --output-dir "<OUTPUT_DIR>" --approve-and-start 4` to atomically clear the approval gate and mark Phase 4 in-progress.

---

## Phase 3 — Downstream Track

**Applies when**: state.track === 'B' (mode = `configurationDataReferences`)

**Goal**: Capture an SDM baseline (the Downstream Track has no Phase 2 SDM capture), verify the upstream-imported metadata via SDM↔EDM diff, then migrate transactional references, locate and remediate the auto-emitted customization report (findings here usually indicate an ALM gap), activate EDM, and perform an approved API restart with a manual fallback.

**Output**: Metadata diff confirmed, transactional refs migrated, customizations handled, site activated on EDM, API restart verified or manual restart confirmed by the user.

---

### 3.1 Data Diff Validation (SDM ↔ EDM Metadata)

**Goal**: Before running the refs migration, capture an SDM baseline (Downstream Track has no Phase 2 SDM capture), re-download the site as EDM, and diff the two. Surface the result so the user can decide whether to proceed with refs migration or pause to investigate. The Pages & Components card in the live report visualizes the per-category comparison.

**Why pre-refs:** the Downstream Track assumes metadata arrived via ALM solution import — but until we diff against an SDM baseline, we have no proof that the import landed cleanly. Catching mismatches here lets the user fix the ALM source and re-import without having to roll back a completed refs migration.

**Actions**:

1. **Capture SDM snapshot** (Downstream Track specific — the Authoring Track captures this in 2.1)

   Honor `<SITE_SOURCE_MODE>` from step 1.2: if **`reuse-local`** and `<SITE_ROOT>` is present, **skip this download** and snapshot the existing `<SITE_ROOT>`. Otherwise (**`fresh-download`**) download the SDM source:

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Downloading SDM site source"}'
   pac pages download --webSiteId "<WEBSITE_ID>" --modelVersion 1 --path "<MIGRATION_OUTPUT_DIR>/site-sdm"
   node update-state.js --output-dir "<OUTPUT_DIR>" --clear-operation
   ```

   > **Nested-folder quirk:** run `node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" discover --path "<MIGRATION_OUTPUT_DIR>/site-sdm" --require-site` and capture its returned `siteRoot` as `<SITE_ROOT>`.

   Then snapshot:

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/snapshot-site.js" --site-root "<SITE_ROOT>" --output-dir "<OUTPUT_DIR>" --label sdm
   ```

2. **Re-download the migrated site as EDM**

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Downloading EDM site source"}'
   pac pages download --webSiteId "<WEBSITE_ID>" --modelVersion 2 --path "<MIGRATION_OUTPUT_DIR>/site-edm"
   node update-state.js --output-dir "<OUTPUT_DIR>" --clear-operation
   ```

   Run `node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" discover --path "<MIGRATION_OUTPUT_DIR>/site-edm" --require-site` and capture its returned `siteRoot` as `<SITE_ROOT_EDM>`.

3. **Snapshot the EDM site**

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/snapshot-site.js" --site-root "<SITE_ROOT_EDM>" --output-dir "<OUTPUT_DIR>" --label edm
   ```

   Output: `<OUTPUT_DIR>/edm-snapshot.json`. The live report's **Pages & Components** card now shows `SDM → EDM` per-category pills.

4. **Diff SDM vs EDM**

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/diff-snapshots.js" --sdm "<OUTPUT_DIR>/sdm-snapshot.json" --edm "<OUTPUT_DIR>/edm-snapshot.json" --output-dir "<OUTPUT_DIR>"
   ```

   Output: `<OUTPUT_DIR>/migration-data-diff.json` + console table grouped by category. See Authoring Track 3.1 step 3 for the pass/warn/fail rubric.

5. **Surface the diff and gate refs migration**

   Same Checkpoint 7 chat callout and AskUserQuestion gate as Authoring Track 3.1 step 4. On "Looks fine" proceed to step 3.2; on "Concerning" halt cleanly so the user can fix the upstream ALM source and re-import; on "Cancel" halt.

**Output**: SDM baseline captured, metadata SDM↔EDM diff complete, user has decided whether to proceed with refs migration.

> **→ Update report:** `--set-step 3.1 --status completed --output "Metadata diff: <PASS|WARN|FAIL> · <N> missing · <M> extra · <S> state-changed · user chose: <choice>"`

---

### 3.2 Migrate Transactional References

**Goal**: Run `pac pages migrate-datamodel --mode configurationDataReferences` to move transactional data references.

**Actions**:

1. **Execute Migration Command**

   After the existing pre-refs approval, use the same guarded start as Authoring Track 3.2:

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" start-references --website-id "<WEBSITE_ID>" --output-dir "<OUTPUT_DIR>"
   ```

   Read `references-start.json`. Only `StartAccepted` enters normal polling; it is not proof of migration completion. Handle `StartRefused`, `StartFailed`, and `CheckFailed` using [References start refusal recovery](#references-start-refusal-recovery), including its explicit reset approval and one-retry limit. Newer PAC versions may auto-emit `SiteCustomization*.csv`.

2. **Poll Status with Verbose Output**

   Use the same portable helper and report-update contract as Authoring Track 3.2 step 3: 60 seconds between checks, at most 30 attempts, and complete raw responses for the **Transactional References Migration** card.

   > **Run this automatically in the background — do not ask the user to confirm before checking status.** Checking migration status is a read-only, non-destructive query; poll it silently and only surface a message on a terminal state (Completed / Failed / Reverted) or when genuinely stuck.

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/migration-runtime.js" poll --website-id "<WEBSITE_ID>" --mode configurationDataReferences --output-dir "<OUTPUT_DIR>"
   ```

   Set the now-running banner before launching. While it runs, interpret every progress record's complete `rawOutput` and call `update-state.js --set-refs-migration` using the Authoring Track's field schema, followed by `--set-operation` with the record's serialized `operation`. Include all chunks, not just failures. Keep report updates sequential. Re-emit the final payload from `migration-status.json` and clear the banner after the helper exits. Report writes remain best-effort; status-check failures never imply migration success.

   - **Completed**: clear the now-running banner (`--clear-operation`), proceed to step 3.3. The card now shows status=Completed.
   - **Still `Running` (`outcome=TimedOut`, exit `2`)**: recommend the user **wait and keep polling** (refs migration on large sites can take a long time). A polling-window timeout is not a migration failure. Only if genuinely stuck for an extended period (`Modified On` not advancing, no newly completed chunks), follow the explicitly approved, verified supported-reset procedure in step 2.2. The card shows the last captured running state.
   - **Failed / Reverted**: surface error, ask user; card shows the failed status and chunk-level errors from the last poll.
   - **`CheckFailed` or any other unresolved status**: show the saved diagnostic and resolve the status-query issue; do not activate EDM or reset based on a failed check.

   > **Chunk-level generic SQL errors — auto-retry before escalating.** Same handling as Authoring Track 3.2: chunk-level **Generic SQL error** failures (e.g., `1205` deadlock victim, `3732` type still referenced) are **Dataverse SQL-backend errors, not PAC/client-side**, and are usually transient under chunked migration. Because the refs migration is resumable (re-running re-processes only the still-unmigrated chunks), **automatically retry the command up to 3 times** (30–60s backoff, re-entering the poll loop) whenever the only failures are chunk-level generic SQL errors — **even when a chunk is labeled `Non Retriable`**, since that label is PAC's in-run classification, not a verdict on a fresh invocation. Only escalate to a Microsoft support ticket (chunk IDs, error numbers, `pac --version`, WebSiteId, env URL) if the **same** chunks fail with the **same** error after the retries. Do **not** proceed until refs migration reports `Completed`.

   > **PAC build compatibility:** Follow Authoring Track 3.2's helper fallback contract: when `verboseSupported=false`, populate the card only with fields actually returned. Missing verbose details are not zero counts or evidence of successful migration.

**Output**: Transactional references migrated, customization CSV auto-emitted. Live report's Transactional References Migration card reflected real-time progress during polling.

> **→ Update report:**
>
> ```
> --clear-operation
> --set-step 3.2 --status completed --output "Refs migrated · status=<STATUS>"
> ```
>
> The polling loop above already emitted the final payload; no extra `--set-refs-migration` call needed here.

---

### 3.3 Locate Customization Report

**Goal**: Find the CSV PAC auto-generated in step 3.2; fall back to explicit generation if missing.

**Actions**:

Follow **all** of Authoring Track Phase 2.3: verify CSV provenance, reuse an applicable report, and retain the guarded `migration-runtime.js report` fallback if missing. Honor every missing/invalid-report and changed-tracker pause; a post-references report request must not erase the verified references-completion evidence or silently proceed to activation after a tracker change.

**Output**: Customization report located and parsed.

> **→ Update report:**
>
> ```
> --set-step 3.3 --status completed --output "CSV: <PATH> · <N> findings total"
> --set-customization-report '{"path":"<ABSOLUTE_PATH_TO_OUTPUT_DIR>/customization-report.html","csvPath":"<ABSOLUTE_PATH_TO_OUTPUT_DIR>/SiteCustomization.csv","totalFindings":<N>,"breakdown":{"fetchxml":<N>,"liquid":<N>,"dme":<N>,"plugins":<N>,"workflows":<N>,"relationships":<N>}}'
> ```
>
> Pass absolute paths so the live report's "Open customization-report.html" link works no matter where the user opens the report from. Omit any breakdown keys with zero count.

---

### 3.4 Remediate Customizations

**Goal**: Apply the same evidence-based classification and proposal gates as Authoring Track step 2.4. Raw references on Prod/Test/UAT do not by themselves establish an ALM gap.

**Actions**:

1. **Branch on findings**

   - **Zero findings or reviewed informational-only references**: record the assessment and proceed through the existing activation approval in step 3.5. Offer optional review of expected references without a risk acknowledgment.
   - **Needs context review**: investigate full local source using step 2.4's context checks. Offer targeted inspection/missing-context/pause choices if blocked; do not assume an ALM gap.
   - **Confirmed unresolved actionable customizations**: list the actual files/components and evidence before asking how to proceed.

2. **Discuss confirmed downstream work**

   | Question | Header | Options |
   |----------|--------|---------|
   | These verified customizations still need changes: `<named items and impact>`. They may indicate an upstream ALM gap. How do you want to address them? | Downstream Customizations | Review/remediate the named items here, Pause — fix at source in Dev and re-import, Cancel |

   - **Remediate now**: proceed with the auto-rewriter steps below.
   - **Pause skill**: halt cleanly; user fixes upstream and re-runs.
   - **Cancel**: halt cleanly.

3. **Stage FetchXML rewrites** — same script as Authoring Track Phase 2.4 step 3 (writes proposed files to `remediation-staged/`).

4. **Stage Liquid annotations** — same script as Authoring Track Phase 2.4 step 4 (writes annotated files to `remediation-staged/`).

5. **Generate augmented prompts** — same as Authoring Track Phase 2.4 step 5 (plugin + DME prompts surfaced for separate Claude sessions).

6. **Review and approve** — same proposal gate as Authoring Track Phase 2.4 step 6: only a valid nonempty manifest with existing staged files triggers `--set-approval 3 in-phase` and the apply/upload question. Zero proposals skips steps 6–7; manual work remains unresolved until verified or explicitly deferred.

7. **Apply staged changes and upload** — same as Authoring Track Phase 2.4 step 7 (`apply-remediation.js` copies staged → live, then `pac pages upload`). On "No — discard staged changes", run `apply-remediation.js --discard` and skip upload.

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/apply-remediation.js" --output-dir "<OUTPUT_DIR>" --site-root "<SITE_ROOT>"

   pac pages upload --path "<SITE_ROOT>" --modelVersion 1
   ```

   > **→ Update report (after upload):** `--clear-approval`.

Before activation, reconcile manual work using step 2.4's readiness rules: expected references get optional verification only; actual unreviewed/unfixed items require specific impact and explicit named-risk deferral if the user chooses to proceed. Preserve the existing activation/restart approvals.

**Output**: Assessments and source-review evidence recorded; only actual approved changes applied/uploaded; manual outcomes or specifically acknowledged deferrals recorded.

> **→ Update report:** `--set-step 3.4 --status completed --output "<N informational; M fixes verified; K named items explicitly deferred>"`

---

### 3.5 Activate EDM (Update Data Model Version)

Identical to the Authoring Track's step 3.3 — retrieve Portal ID, ask the user to confirm activation via AskUserQuestion, run `--updateDataModelVersion`, confirm switch.

> **→ Update report:**
>
> ```
> --set-site '{"portalId":"<PORTAL_ID>","currentDataModel":"Enhanced EDM"}'
> --set-step 3.5 --status completed --output "Data model flipped to EDM · Portal Id <PORTAL_ID>"
> ```

---

### 3.6 Restart Site (API first, manual fallback)

Identical to the Authoring Track's step 3.4: ask for explicit restart approval, run the API helper, and verify readiness; use the same manual fallback and uncertain-request safeguards. This is still Phase 3, after activation in 3.5 and before Phase 4 runtime validation.

> **→ Update report (end of Phase 3 Downstream Track):**
>
> ```
> --set-step 3.6 --status completed --output "<API restart verified; site reachable | manual restart confirmed by user>"
> --set-phase 3 --status completed
> --set-approval 4 phase-start
> ```
>
> **📄 Checkpoint 6 — Tell the user about the report before asking for Phase 4 approval.** Print in chat:
>
> ```
> 📄 Phase 3 complete. The site is on EDM and restarted. Review before approving Phase 4:
>    <ABSOLUTE_PATH_TO_OUTPUT_DIR>/datamodel-migration-report.html
>
> Phase 4 recommends a runtime smoke test and records final validation/rollback
> decisions. The SDM-to-EDM metadata diff was already checked in Phase 3.1.
> ```
>
> Then ask the user to approve Phase 4. On approval, run `node update-state.js --output-dir "<OUTPUT_DIR>" --approve-and-start 4` to atomically clear the approval gate and mark Phase 4 in-progress.


## Phase 4: Post-Migration Validation

**Goal**: Validate the migrated site, optionally rollback if issues are found, and produce the final execution report.

**Output**: Runtime validation outcome (including warnings, incomplete checks, deferral, or decline) recorded, any approved rollback handled, and final execution report produced.

---

### 4.1 Runtime Smoke Test Recommendation (/test-site)

**Goal**: Offer the recommended browser-based smoke check with **Run now** in the current migration conversation. Reuse `/power-pages:test-site` rather than implementing a second crawler. Testing is optional; the user can also report an earlier run, defer, or decline.

> **Skip this sub-step if Phase 3.1 (Data Diff Validation) user chose "Concerning"** — we never reached this point because Phase 3 halted. This guard is here defensively in case the agent reaches 4.1 with a degraded migration; in normal flow, only `PASS`/`WARN` diffs let execution continue past the Phase 3.1 gate.

**Actions**:

1. **Explain the runtime check**:

   ```
   Runtime smoke test — run here now, or defer.

   The migrated site is live at:
      <SITE_URL>

   Choose "Run now" to run /power-pages:test-site in this conversation.
   It uses Playwright to crawl up to 25 pages, capture API calls,
   check console errors, and report pass/fail per page and per endpoint.
   You control any browser login; the agent will not sign in for you.
   It needs only the live URL — no re-download required. The site URL
   is unchanged from before migration; only the data model underneath
   has changed.

   What /test-site catches that the data diff cannot:
   • Pages whose records all migrated but render empty because a
     FetchXML rewrite has the wrong powerpagecomponenttype filter
   • Table permissions that worked on SDM but block on EDM (401/403)
   • Liquid runtime errors visible only in browser console
   ```

2. **Offer the choice in this conversation**. First show the input notice:

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-input '{"requiredAction":"Choose Run now to test the migrated site in this conversation, report an earlier test, defer, or skip."}'
   ```

   | Question | Header | Options |
   |----------|--------|---------|
   | Run the recommended runtime smoke test against `<SITE_URL>` now? The Phase 3.1 metadata diff cannot verify browser behavior. | Runtime Check | Run now, I've already run it, Defer until later, Skip entirely |

   Clear the input notice after a valid answer. Selecting **Run now** is consent for this read-only test only, not for fixes, uploads, restarts, or rollback. Phase 4 approval alone does not start the test.

3. **Run now — invoke the existing skill, then return here**:

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-step 4.1 --status in-progress --output "Runtime smoke test requested"
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Testing migrated site","detail":"Browser-based runtime smoke test; up to 25 pages, API responses, and console errors."}'
   ```

   - Save the current migration context: `<OUTPUT_DIR>`, track, Phase 4 task, confirmed `<SITE_URL>`, test start time, and the project root used for test reports. Use the confirmed HTTPS live URL from activation/restart, not an inferred URL or a different project's config.
   - Use the **Skill tool** to invoke `power-pages:test-site` with `<SITE_URL>` as its argument **in the current conversation**. Follow `${CLAUDE_PLUGIN_ROOT}/skills/test-site/SKILL.md`; do not launch a separate agent/session or duplicate its browser workflow.
   - Pass along the migration context and report lifecycle instructions: the migration agent remains the sole writer of `migration-state.json`; keep Phase 4 and step 4.1 in progress during testing. Before any test-owned login, permission, or continue/stop question, show `--set-input` with the required action (for example, log in through the browser and confirm here). Never ask for passwords or tokens. Clear the notice on a valid response; if testing resumes, restore the same `Testing migrated site` operation without inventing a percentage or ETA. Do not mark the migration complete from inside `test-site`.
   - Preserve `test-site`'s read-only behavior, user-controlled authentication, and 25-page limit. Do not submit forms or change site data as part of this consent.
   - When the skill returns, clear any resolved input notice and `--clear-operation`, including on cancellation, tool failure, or early stop. Restore the migration task/context before continuing to 4.2.
   - Read the current run's `docs/alm/last-test-site.json` from the saved test project root and link the test report. Before accepting it, verify its `url` matches the confirmed site (allowing a trailing slash), its `runAt` belongs to this invocation, and its outcome/counts agree with the observed run. Never reuse a stale report or a report for another site.

   | Observed result | Record in migration report |
   |-----------------|----------------------------|
   | `runOutcome: passed` | Passed, with actual tested/failed/skipped counts and any untested scope |
   | `runOutcome: passed-with-warnings` | Passed with warnings; include findings and any skipped authenticated checks |
   | `runOutcome: failed` | Issues found; include findings/report path and retain the user's final-status/rollback choice in 4.2 |
   | Cancelled, unavailable Skill/browser tools, missing/invalid/stale report, or interrupted run | Not completed, with the explicit reason; never report passed |

   If the host cannot invoke the skill here, explain the limitation and show an input notice offering the user `/power-pages:test-site <SITE_URL>` to run themselves, defer, or skip. Do not silently fall back to a metadata diff or HTTP reachability as a runtime-test result.

4. **Other choices**:

   - **I've already run it**: show an input notice and ask whether all checks passed or issues were found; collect issue details/report location as needed. Record this as **user-reported**, not as a test executed by this migration run.
   - **Defer until later**: record "deferred runtime check"; show `/power-pages:test-site <SITE_URL>` for later.
   - **Skip entirely**: record "user declined runtime check".
   - For an incomplete run, ask whether to retry, report an external result, defer, or skip before closing this step. Do not automatically retry or treat a request to test as a completed test.

5. **Record the actual decision and outcome**, then proceed to 4.2:

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --add-decision '{"id":"runtime-smoke-test","label":"Runtime smoke test","choice":"<Run now | Already run | Deferred | Declined>","rationale":"<actual outcome, counts, skipped scope, and report path or reason testing was not completed>"}'
   ```

**Output**: Actual runtime outcome or explicit deferral/decline captured for step 4.2. Completing this workflow sub-step records the resolved choice, not proof that all runtime checks passed.

> **→ Update report (end of 4.1, after the choice/run is resolved):** `--set-step 4.1 --status completed --output "Runtime check: <passed | passed with warnings | issues found: details | user-reported result | not completed: reason; deferred/declined | deferred | declined>"`

---

### 4.2 Final Status, Optional Rollback, Summary

**Goal**: Capture the user's final validation status, perform rollback if requested, and print the success/rollback summary.

**Actions**:

1. **Ask for final validation status**

   | Question | Header | Options |
   |----------|--------|---------|
   | Final validation status for this migration? | Final Status | Validated — all good, Rollback to SDM, Deferred — I'll validate later |

   - **Validated — all good**: proceed to step 3 (success summary).
   - **Rollback to SDM**: proceed to step 2 (rollback).
   - **Deferred**: skip to step 3 with a note that final validation was deferred.

2. **Rollback (if user opted for it)**

   Confirm the Portal ID collected during activation (Authoring Track step 3.3 or Downstream Track step 3.5) is still correct:

   | Question | Header | Options |
   |----------|--------|---------|
   | Confirm Portal ID for rollback: `<PORTAL_ID>`. Is this correct? | Confirm Portal ID | Yes, proceed with rollback, No, let me re-enter it |

   If "No": ask user to paste the correct Portal ID directly (don't try to construct the site URL — same reasoning as Authoring Track step 3.3 / Downstream Track step 3.5).

   ```text
   node update-state.js --output-dir "<OUTPUT_DIR>" --set-operation '{"label":"Rolling back to Standard Data Model"}'
   pac pages migrate-datamodel --webSiteId "<WEBSITE_ID>" --revertToStandardDataModel --portalId "<PORTAL_ID>"
   node update-state.js --output-dir "<OUTPUT_DIR>" --clear-operation
   ```

   Inform user: "Site reverted to SDM. EDM record deactivated, SDM record reactivated."

3. **Success Summary**

   Print to chat:

   ```
   ✅ Migration Complete

   Site:                <SITE_NAME> (ID: <WEBSITE_ID>)
   Previous model:      Standard (SDM)
   Current model:       Enhanced (EDM) | Reverted to Standard (SDM)
   Data diff:           <PASS | WARN | FAIL> — <summary>
   Runtime check:       <passed | passed with warnings | issues found | user-reported result | not completed: reason | deferred | declined>
   Customizations:      <count> (or "None") — see customization-report.html
   Environment:         <ENV_TYPE>
   Track:               <Authoring | Downstream>

   Reports in <OUTPUT_DIR>:
     migration-state.json          — single source of truth for state
     datamodel-migration-report.html   — live execution timeline (this run)
     customization-report.html     — findings catalog (if any)
     sdm-snapshot.json             — SDM baseline
     edm-snapshot.json             — EDM result
     migration-data-diff.json      — full diff report
     plugin-remediation-prompt.txt — augmented prompt (if findings)
     dme-remediation-prompt.txt    — augmented prompt (if findings)
   ```

4. **Record Skill Usage**

   Follow instructions in `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`.

5. **Emit Completion Telemetry**

   After the end-of-Phase-4 report update below, emit the `skill_completed` 1DS
   event with terminal outcome and elapsed duration from `migration-state.json`.
   Pending/in-progress state is not emitted as success. This is best-effort and fails closed — never
   block or surface errors from it:

   ```text
   node "${CLAUDE_PLUGIN_ROOT}/skills/migrate-datamodel/scripts/emit-telemetry.js" --output-dir "<OUTPUT_DIR>"
   ```

   `<OUTPUT_DIR>` is the per-migration subfolder holding `migration-state.json`.
   The script honors the plugin telemetry kill switch / opt-out and sends only
   the existing shared completion fields, including outcome and duration.
   `eventInfo` contains only the approved Entra object ID when available.
   Track, template, phase summaries, site names, URLs, environment names and paths
   stay local. The shared dispatcher owns regional routing and opt-out enforcement.

**Output**: Migration complete (or rolled back), final summary printed, skill usage recorded.

> **→ Update report (end of Phase 4):**
>
> ```
> --set-step 4.2 --status completed --output "<Migration complete | Rolled back | Deferred>"
> --set-phase 4 --status completed
> ```
>
> No further approval gates. Live report header pill switches to "✅ Migration Complete".

---

## Progress Tracking

| Phase | Task Subject | Active Form |
|-------|-------------|-------------|
| Phase 1 | Site Discovery & Pre-checks | Setting up for migration |
| Phase 2 | Configuration Setup | Setting up configuration (track-aware) |
| Phase 3 | Migration Execution | Executing migration and activating EDM |
| Phase 4 | Post-Migration Validation | Validating and completing migration |

> **Track-aware naming for Phase 2 and Phase 3:** Both phases have different structures depending on the track derived in step 1.7. The live execution report shows the track-specific phase title and sub-step list:
>
> - **Authoring Track** (mode = `configurationData` or `all`):
>   - Phase 2 renders as "Configuration Migration & Customization Remediation" (**4 sub-steps**: Capture SDM Snapshot → Migrate Metadata → Locate Customization Report → Remediate Customizations)
>   - Phase 3 renders as "Migration Execution" (**4 sub-steps**: Data Diff Validation → Migrate Refs → Activate EDM → Restart)
> - **Downstream Track** (mode = `configurationDataReferences`):
>   - Phase 2 renders as "Setting Up Metadata" (3 sub-steps)
>   - Phase 3 renders as "Migration Execution" (**6 sub-steps**: Data Diff Validation → Migrate Refs → Locate Report → Remediate → Activate EDM → Restart)
>
> **Phase 4 has 2 sub-steps in both tracks**: Runtime Smoke Test Recommendation (`/test-site`, Run now or defer/decline) → Final Status & Summary. The SDM↔EDM data diff that used to live in Phase 4.1 was promoted to Phase 3.1 as a pre-refs safety gate.
>
> **Authoring Track total = 17 sub-steps. Downstream Track total = 18 sub-steps.** The `--set-track A|B` command at end of 1.7 (where `A` = Authoring Track and `B` = Downstream Track) rebuilds Phase 2 and Phase 3 cards in the live report from the chosen blueprint.

---

## Component Type Reference

Use this for FetchXML and Liquid customization mapping:

| Component | Type Value |
|-----------|------------|
| Publishing State | 1 |
| Web Page | 2 |
| Web File | 3 |
| Web Link Set | 4 |
| Web Link | 5 |
| Page Template | 6 |
| Content Snippet | 7 |
| Web Template | 8 |
| Site Setting | 9 |
| Web Page Access Control Rule | 10 |
| Web Role | 11 |
| Website Access | 12 |
| Site Marker | 13 |
| Basic Form | 15 |
| Basic Form Metadata | 16 |
| List | 17 |
| Table Permission | 18 |
| Advanced Form | 19 |
| Advanced Form Step | 20 |
| Advanced Form Metadata | 21 |
| Poll Placement | 24 |
| Ad Placement | 26 |
| Bot Consumer | 27 |
| Column Permission Profile | 28 |
| Column Permission | 29 |
| Redirect | 30 |
| Publishing State Transition Rule | 31 |
| Shortcut | 32 |
| Cloud Flow | 33 |
| UX Component | 34 |

This table lists platform types. Automatic FetchXML rewriting supports only
the explicit legacy-table mappings in the generator, including
`adx_cloudflowconsumer` (33). UX Component (34) has no supported legacy-table
mapping here; unmapped entities remain unchanged and require manual review.
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall