Skip to content

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

Added Migrate SDM to EDM skill for migration (#109)

Ashwani Kumar42a94220bad3
diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.md
index 5e9bf350c..e5e3376f3 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -25,6 +25,84 @@ Keep this precedence in `scripts/lib/template-catalog.js`; create-site caches th
The read-only browser shows each framework's effective previews in a labeled group within the family tab.
The non-SPA experience-preview disclosure in `references/non-spa-preview.md` is separate and unchanged.
+## Data-model migration reliability
+
+Keep `migrate-datamodel`'s four phases, track selection, and approval gates unchanged
+when maintaining its scripts. Snapshot comparisons must not pass incomplete parses
+or ambiguous duplicate identities. Reuse the strict aggregate parser and site-root
+resolver; retain inactive navigation links, target/order/state, and both site-setting
+layouts, and both aggregate and per-record web-role layouts. Capture canonical
+`web-link-sets` (plus legacy layout compatibility),
+prefixed/unprefixed states, nested advanced-form steps and per-record page-access
+rules. Wire new inventories through diff identities, meaningful values and report
+grouping. The live comparison must use record-level diff semantics, not just counts.
+Template inspection must read aggregate and per-record web roles, and localized
+page snapshots must traverse locale subdirectories. Use `site.migrationMode`
+when deciding whether mode `all` already covered transactional references.
+Template detection, snapshot and source-remediation commands require a real `website.yml` file in the
+resolved metadata root before scanning or replacing saved evidence/proposals.
+Snapshot lists and cloud-flow consumers in their flat downloaded layouts while
+retaining legacy per-slug layouts. Only missing optional inputs may be empty;
+permission and I/O failures must surface without claiming a clean comparison.
+Do not treat an arbitrary directory or an empty managed metadata folder as a
+successful zero-record scan; retain report-only CSV generation without a site path.
+Initialization must verify the website and
+environment identity before resuming or resetting an existing folder. Remediation
+reruns rebuild the selected FetchXML/Liquid passes from current source, preserving
+both passes without modifying live files before the approved apply step.
+Treat PAC customization counts as scan references, not severity or required-fix
+counts. Preserve the CSV and per-finding informational/actionable/context-review
+assessment; inspect full source for uncertain findings and record evidence in the
+live report. Do not blanket-allow templates or unmapped tables. Only real staged
+proposals trigger apply/upload approval; only named unresolved actionable work
+requires risk acknowledgment. Expected references alone are not an ALM gap.
+Validate saved state and snapshot/remediation records before dereferencing them;
+invalid input must produce a clear error without replacing usable state or partially
+applying a proposal with missing staged files.
+Bind remediation apply to the manifest's canonical site root, reject linked
+descendants and restore originals after caught copy failures. Report rollback
+failures explicitly and preserve recovery inputs. Do not mutate either tree
+concurrently. Report links need scheme validation, and copyable terminal commands
+must identify their shell and quote paths accordingly. DME data copy requires
+verified metadata migration and complete source-to-component mappings.
+DME checklists apply
+only to mapped metadata tables; unsupported findings remain explicit manual review.
+Completion telemetry uses existing approved fields and shared regional dispatch;
+do not transmit migration-specific phase/template data through `eventInfo`.
+Keep migration instructions shell-independent: use `migration-runtime.js` for
+discovery, UTF-8 solution capture, delays, and bounded read-only polling, not
+PowerShell/Bash loops. PAC runs through the shared argument-array runner; retain
+complete verbose responses for agent-owned history/chunk report updates.
+Retain the guarded missing-customization-report fallback and its before/after
+tracker evidence. Exit 0 without a valid CSV is not success. Distinguish a refused
+references start from an active operation; reset requires separate explicit
+approval and verified status before one references-only retry. Never reset from
+a polling timeout alone or automatically edit Dataverse tracker fields.
+An explicit `Unknown` tracker status is a failed check, not running or accepted;
+retain the raw response and stop for recovery rather than polling it as progress.
+A top-level `Completed` also completes metadata-only polling even when PAC omits
+the current step or returns a different final step.
+After report initialization, every skill-owned input/manual-action pause must
+show the report-wide required-action notice. Reuse approval gates for existing
+approvals; use `--set-input` for other questions and clear it when resolved.
+Never treat a notification as approval or advance migration progress for it.
+Approved package installs reuse the indeterminate now-running bar and elapsed
+timer through installed-version verification; never invent an install percentage
+or advance migration phases for a package's progress display.
+Restart remains after activation in Phase 3, before Phase 4 runtime validation.
+Use `scripts/restart-site.js` only with explicit restart consent; verify the saved
+environment, Portal ID (not the Dataverse record ID), and site origin. Never
+automatically repeat an uncertain POST. Read-only readiness checks and manual
+fallback must not be reported as proof of a restart without prior submission
+or explicit user confirmation.
+Phase 4.1 offers Run now to invoke the existing test-site skill in the migration
+conversation, only after the user chooses it. Preserve its read-only scope and
+user-controlled login. Keep input notices/progress synchronized and record only
+the current matching-site result; warnings, skipped scope, cancellation and
+unavailable tools are not an unconditional pass. Preserve earlier-result,
+defer/skip and final-status/rollback choices.
+Regression coverage lives in `scripts/tests/{diff-snapshots,snapshot-site,update-state,generate-migration-reports,apply-remediation,render-live-report,detect-template,migration-telemetry,migration-runtime}.test.js`.
+
## Non-SPA creation and shared design quality
`scripts/telemetry-config.js` delegates preference changes to the bundled shared CLI and adds the non-SPA creation disclosure.
diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.md
index b9d3fbef1..f16a03aa0 100644
--- a/plugins/power-pages/README.md
+++ b/plugins/power-pages/README.md
@@ -40,9 +40,19 @@ This keeps hook behavior in one place and avoids relying on skill-frontmatter ho
| [PAC CLI](https://learn.microsoft.com/power-platform/developer/cli/introduction) | Deploy, activate, data model | `dotnet tool install -g Microsoft.PowerApps.CLI.Tool` |
| [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) | Data model, sample data, activation | `winget install Microsoft.AzureCLI` |
+The data-model migration skill does not require PowerShell. Its Node.js helper
+handles site discovery, UTF-8 output capture, and bounded status polling on
+Windows, macOS, and Linux. Ensure PAC is available on the agent process's `PATH`;
+use the linked installation guidance for your operating system.
+
+After EDM activation, migration can restart the site through the Power Platform
+API with explicit user approval, using the existing PAC/Azure CLI sign-ins and
+the caller's permissions. It verifies site readiness before Phase 4 runtime
+validation and retains a manual restart fallback when automation is unavailable.
+
## Skills
-The plugin provides 40 skills: 39 user-invocable skills and one model-only worker.
+The plugin provides 41 skills: 40 user-invocable skills and one model-only worker.
They cover the full lifecycle of a Power Pages site - scaffolding,
non-SPA authoring, deployment, data modeling, backend integration, authentication, localization,
ALM and CI/CD, security review, performance analysis, testing, auditing, and platform migrations. Each user-invocable
@@ -197,6 +207,20 @@ Generative AI Search components, Flex Containers, and spacers.
### Data modeling
+#### `/migrate-datamodel`
+
+> "Migrate my existing site from the Standard to the Enhanced data model"
+
+Guides an existing site through discovery, track-aware configuration setup,
+migration and validation with explicit approval gates and a live progress report.
+Stages FetchXML rewrites and Liquid review suggestions without changing live
+source until approved. Data Model Extensions and plugins receive manual
+remediation prompts, not direct schema or plugin-code changes.
+
+Snapshot comparison checks identities, states, navigation targets/order, setting
+values and optional content hashes; incomplete parses cannot be reported as a
+clean comparison. Test this preview migration on a non-production environment first.
+
#### `/setup-datamodel`
> "Create Dataverse tables for my site"
diff --git a/plugins/power-pages/references/skill-tracking-reference.md b/plugins/power-pages/references/skill-tracking-reference.md
index 22ba06d52..d85ede6db 100644
--- a/plugins/power-pages/references/skill-tracking-reference.md
+++ b/plugins/power-pages/references/skill-tracking-reference.md
@@ -61,6 +61,7 @@ Changing an input to count the comparison would alter the evidence being compare
| add-cloud-flow | AddCloudFlow | Site/AI/Skills/AddCloudFlow |
| add-ai-webapi | AddAiWebapi | Site/AI/Skills/AddAiWebapi |
| integrate-backend | IntegrateBackend | Site/AI/Skills/IntegrateBackend |
+| migrate-datamodel | MigrateDatamodel | Site/AI/Skills/MigrateDatamodel |
| scan-site | ScanSite | Site/AI/Skills/ScanSite |
| analyze-performance | AnalyzePerformance | Site/AI/Skills/AnalyzePerformance |
| manage-headers | ManageHeaders | Site/AI/Skills/ManageHeaders |
diff --git a/plugins/power-pages/scripts/lib/pac-command.js b/plugins/power-pages/scripts/lib/pac-command.js
index 7473cb1e9..fe67457af 100644
--- a/plugins/power-pages/scripts/lib/pac-command.js
+++ b/plugins/power-pages/scripts/lib/pac-command.js
@@ -82,7 +82,11 @@ function runPac(args, deps = {}) {
}
try {
- output = readFileTail(logPath, PAC_LOG_TAIL_BYTES, fsImpl);
+ // Migration discovery/polling must retain leading solution anchors and all
+ // chunk details. Existing mutation callers still receive a bounded log tail.
+ output = deps.captureAll
+ ? fsImpl.readFileSync(logPath, 'utf8')
+ : readFileTail(logPath, PAC_LOG_TAIL_BYTES, fsImpl);
if (!output && commandOutput !== undefined && commandOutput !== null) {
output = String(commandOutput);
}
diff --git a/plugins/power-pages/scripts/lib/validation-helpers.js b/plugins/power-pages/scripts/lib/validation-helpers.js
index 9d891951e..5edf0ddd0 100644
--- a/plugins/power-pages/scripts/lib/validation-helpers.js
+++ b/plugins/power-pages/scripts/lib/validation-helpers.js
@@ -173,6 +173,28 @@ function resolvePowerPagesSiteRoot(projectRoot) {
return null;
}
+function requirePowerPagesSiteRoot(projectRoot) {
+ if (typeof projectRoot !== 'string' || !projectRoot.trim()) {
+ throw new Error('A downloaded Power Pages site path containing website.yml is required.');
+ }
+ const root = path.resolve(projectRoot);
+ // The permissive resolver also supports projects whose metadata is not
+ // downloaded yet. Migration scans require the actual website.yml file.
+ const candidates = new Set([resolvePowerPagesSiteRoot(root), root]);
+ for (const candidate of candidates) {
+ if (!candidate) continue;
+ const marker = path.join(candidate, 'website.yml');
+ try {
+ if (fs.statSync(marker).isFile()) return candidate;
+ } catch (error) {
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') {
+ throw new Error(`Could not inspect Power Pages site marker ${marker}: ${error.message}`);
+ }
+ }
+ }
+ throw new Error(`Expected a downloaded Power Pages site containing website.yml at ${root} or its .powerpages-site folder. Select the site root explicitly.`);
+}
+
/**
* Finds a subdirectory inside .powerpages-site/.
* @param {string} dir - Starting directory
@@ -596,6 +618,7 @@ module.exports = {
findProjectRoot,
isNonSpaSiteRoot,
resolvePowerPagesSiteRoot,
+ requirePowerPagesSiteRoot,
findPowerPagesSiteDir,
UUID_REGEX,
validateDataverseEnvironmentUrl,
diff --git a/plugins/power-pages/scripts/restart-site.js b/plugins/power-pages/scripts/restart-site.js
new file mode 100644
index 000000000..cc18f866d
--- /dev/null
+++ b/plugins/power-pages/scripts/restart-site.js
@@ -0,0 +1,164 @@
+#!/usr/bin/env node
+'use strict';
+
+const { resolveContext, request, parseCliArgs, emitJson, runCli } = require('./lib/power-platform-api');
+const {
+ getEnvironmentUrl, validateDataverseEnvironmentUrl, makeRequest, CLOUD_TO_API, UUID_REGEX,
+} = require('./lib/validation-helpers');
+
+const API_VERSION = '2024-10-01';
+const MAX_ATTEMPTS = 20;
+const INTERVAL_MS = 15000;
+
+function siteOrigin(value) {
+ const url = new URL(value);
+ if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443')) {
+ throw new Error('Website URL must be HTTPS without credentials or a nonstandard port.');
+ }
+ return url.origin;
+}
+
+function validateWebsite(body, portalId, websiteUrl) {
+ // The documented WebsiteDto uses camelCase; older API clients also receive
+ // PascalCase. The API id is the Portal ID, NOT the Dataverse website record ID.
+ // https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites/get-website-by-id
+ if (!body || typeof body !== 'object' || Array.isArray(body) ||
+ typeof (body.id || body.Id) !== 'string' ||
+ (body.id || body.Id).toLowerCase() !== portalId.toLowerCase()) {
+ throw new Error('Website API response does not match the approved Portal ID.');
+ }
+ if (siteOrigin(body.websiteUrl || body.WebsiteUrl) !== websiteUrl) {
+ throw new Error('Website API URL does not match the approved site URL. Verify site identity before restarting.');
+ }
+ const status = body.status || body.Status;
+ if (!['OperationComplete', 'OperationFailed', 'OperationInProgress', 'OperationNotStarted'].includes(status)) {
+ throw new Error('Website API response has no recognized operation status.');
+ }
+ return status;
+}
+
+function apiError(label, response) {
+ return `${label} failed (HTTP ${response.statusCode}): ${response.error?.message || response.error?.code || 'unexpected response'}`;
+}
+
+async function restartSite({ portalId, environmentUrl, websiteUrl, approved = false, verifyOnly = false }, deps = {}) {
+ if (typeof portalId !== 'string' || !UUID_REGEX.test(portalId)) throw new Error('--portal-id must be a valid Portal ID GUID.');
+ if (typeof environmentUrl !== 'string' || !environmentUrl.trim()) throw new Error('--env-url is required.');
+ if (typeof websiteUrl !== 'string' || !websiteUrl.trim()) throw new Error('--website-url is required.');
+ if (typeof approved !== 'boolean' || typeof verifyOnly !== 'boolean') throw new Error('Restart approval and verification flags must be booleans.');
+ if (approved !== true && verifyOnly !== true) throw new Error('Explicit user approval (--approved) is required before restarting.');
+ if (approved === true && verifyOnly === true) throw new Error('Use either --approved or --verify-only, not both.');
+ const expectedEnvironment = validateDataverseEnvironmentUrl(environmentUrl);
+ const expectedSite = siteOrigin(websiteUrl);
+ const activeEnvironment = (deps.getEnvironmentUrl || getEnvironmentUrl)();
+ if (!activeEnvironment || validateDataverseEnvironmentUrl(activeEnvironment) !== expectedEnvironment) {
+ throw new Error('Active PAC environment does not match the migration environment. No restart was requested.');
+ }
+ const context = (deps.resolveContext || resolveContext)();
+ if (!context || context.error) throw new Error(context?.error || 'Power Platform API context is unavailable.');
+ if (typeof context.token !== 'string' || !context.token ||
+ !UUID_REGEX.test(context.environmentId || '') || !Object.values(CLOUD_TO_API).includes(context.apiHost) ||
+ context.baseUrl !== `${context.apiHost}/powerpages/environments/${context.environmentId}`) {
+ throw new Error('Invalid Power Platform API environment context.');
+ }
+ const callApi = deps.request || request;
+ const checkHttp = deps.makeRequest || makeRequest;
+ const sleep = deps.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
+ const progress = deps.onProgress || ((record) => console.error(JSON.stringify(record)));
+ const path = `/websites/${portalId}`;
+ const getWebsite = () => callApi({
+ context, method: 'GET', path, query: { 'api-version': API_VERSION }, timeout: 15000,
+ });
+ const identity = { portalId, environmentId: context.environmentId, websiteUrl: expectedSite };
+ const failure = (outcome, error, restartSubmitted, extra = {}) => ({
+ success: false, outcome, error, restartSubmitted, verificationOnly: verifyOnly,
+ manualFallbackRequired: true, ...identity, ...extra,
+ });
+ const initial = await getWebsite();
+ if (!initial.ok) return failure('PreflightFailed', apiError('Get website', initial), false);
+ const initialStatus = validateWebsite(initial.body, portalId, expectedSite);
+
+ let restartSubmitted = false;
+ if (!verifyOnly) {
+ if (initialStatus !== 'OperationComplete') {
+ return failure('PreflightFailed', `Website operation is ${initialStatus}; resolve it before requesting a restart.`, false);
+ }
+ // Exactly one approved POST. Network failures/5xx can be ambiguous: do not
+ // retry a mutation that might already have reached the service.
+ // https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites/restart-website
+ const restarted = await callApi({
+ context, method: 'POST', path: `${path}/restart`,
+ query: { 'api-version': API_VERSION }, timeout: 30000,
+ });
+ if (!restarted.ok) {
+ const submitted = restarted.statusCode >= 400 && restarted.statusCode < 500 && restarted.statusCode !== 408
+ ? false : null;
+ return failure('RestartFailed', apiError('Restart website', restarted), submitted);
+ }
+ restartSubmitted = true;
+ progress({ event: 'restart-submitted', ...identity });
+ // Only 200 is documented as restart success. An unexpected accepted/async
+ // response must not be interpreted as a completed restart.
+ if (restarted.statusCode !== 200) {
+ return failure('RestartUnconfirmed', `Restart returned HTTP ${restarted.statusCode}; confirm completion before continuing.`, true);
+ }
+ await sleep(INTERVAL_MS);
+ }
+
+ let consecutiveReady = 0;
+ let lastError = null;
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
+ const statusResult = await getWebsite();
+ if (!statusResult.ok) return failure('VerificationFailed', apiError('Check website status', statusResult), restartSubmitted, { attempts: attempt });
+ const status = validateWebsite(statusResult.body, portalId, expectedSite);
+ if (status === 'OperationFailed') return failure('VerificationFailed', 'Website API reports OperationFailed.', restartSubmitted, { attempts: attempt });
+ let reachable = false;
+ let httpStatus = null;
+ if (status === 'OperationComplete') {
+ // Only probe the API-verified, approved origin. Never send management
+ // tokens/cookies or follow redirects to a site or an external sign-in page.
+ const health = await checkHttp({
+ url: `${expectedSite}/`, method: 'GET',
+ headers: { Accept: 'text/html', 'Cache-Control': 'no-cache' }, timeout: 15000,
+ });
+ httpStatus = health.statusCode || null;
+ reachable = !health.error && httpStatus >= 200 && httpStatus < 400;
+ lastError = reachable ? null : health.error || `Website returned HTTP ${httpStatus}`;
+ } else {
+ lastError = `Website operation is ${status}`;
+ }
+ consecutiveReady = reachable ? consecutiveReady + 1 : 0;
+ progress({ event: 'readiness-check', attempt, maxAttempts: MAX_ATTEMPTS, status, httpStatus, reachable });
+ // Two consecutive checks avoid treating one transient response as readiness.
+ // Reachability is not proof of EDM functionality; Phase 4 owns runtime testing.
+ if (consecutiveReady >= 2) {
+ return {
+ success: true, outcome: 'Ready', restartSubmitted, verificationOnly: verifyOnly,
+ websiteReachable: true, attempts: attempt, ...identity,
+ };
+ }
+ if (attempt < MAX_ATTEMPTS) await sleep(INTERVAL_MS);
+ }
+ return failure('VerificationTimedOut', `Site readiness was not confirmed after ${MAX_ATTEMPTS} checks. ${lastError || 'Two consecutive healthy responses are required.'}`,
+ restartSubmitted, { attempts: MAX_ATTEMPTS });
+}
+
+async function main() {
+ const args = parseCliArgs(process.argv);
+ try {
+ const result = await restartSite({
+ portalId: args['portal-id'], environmentUrl: args['env-url'], websiteUrl: args['website-url'],
+ approved: args.approved === true, verifyOnly: args['verify-only'] === true,
+ });
+ emitJson(result);
+ process.exitCode = result.success ? 0 : 1;
+ } catch (error) {
+ // An unexpected exception can happen after the request was sent. Preserve
+ // that uncertainty rather than encouraging an unsafe automatic POST retry.
+ emitJson({ success: false, outcome: 'Error', restartSubmitted: null, manualFallbackRequired: true, error: error.message });
+ process.exitCode = 1;
+ }
+}
+
+module.exports = { restartSite };
+runCli(module, main);
diff --git a/plugins/power-pages/scripts/tests/apply-remediation.test.js b/plugins/power-pages/scripts/tests/apply-remediation.test.js
new file mode 100644
index 000000000..022f6db18
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/apply-remediation.test.js
@@ -0,0 +1,323 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const script = path.join(__dirname, '../../skills/migrate-datamodel/scripts/apply-remediation.js');
+
+function setup(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-apply-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const site = path.join(root, 'site');
+ const output = path.join(root, 'reports');
+ const staged = path.join(output, 'remediation-staged');
+ fs.mkdirSync(site);
+ fs.writeFileSync(path.join(site, 'website.yml'), 'adx_name: Contoso\n');
+ fs.mkdirSync(staged, { recursive: true });
+ const manifestPath = path.join(output, 'remediation-diff.json');
+ const writeManifest = (value) => fs.writeFileSync(manifestPath,
+ JSON.stringify(value && typeof value === 'object' ? { siteRoot: site, ...value } : value));
+ const run = (...args) => spawnSync(process.execPath, [
+ script, '--site-root', site, '--output-dir', output, ...args,
+ ], { encoding: 'utf8' });
+ const injectFailure = (body) => spawnSync(process.execPath, ['-e', `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ ${body}
+ process.argv = [process.execPath, ${JSON.stringify(script)}, '--site-root',
+ ${JSON.stringify(site)}, '--output-dir', ${JSON.stringify(output)}];
+ require(${JSON.stringify(script)});
+ `], { encoding: 'utf8' });
+ return { site, output, staged, manifestPath, writeManifest, run, injectFailure };
+}
+
+for (const marker of ['missing', 'directory']) {
+ test(`apply and dry-run reject a ${marker} website marker without changing source or proposals`, (t) => {
+ const fixture = setup(t);
+ const website = path.join(fixture.site, 'website.yml');
+ fs.unlinkSync(website);
+ if (marker === 'directory') fs.mkdirSync(website);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }] });
+ const manifest = fs.readFileSync(fixture.manifestPath, 'utf8');
+ for (const args of [[], ['--dry-run']]) {
+ const result = fixture.run(...args);
+ assert.equal(result.status, 4, result.stderr);
+ assert.match(result.stderr, /downloaded Power Pages site containing website\.yml/);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'original');
+ assert.equal(fs.readFileSync(path.join(fixture.staged, 'page.html'), 'utf8'), 'proposal');
+ assert.equal(fs.readFileSync(fixture.manifestPath, 'utf8'), manifest);
+ assert.deepEqual(fs.readdirSync(fixture.output).sort(), ['remediation-diff.json', 'remediation-staged']);
+ }
+ assert.equal(fixture.run('--discard').status, 0);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'original');
+ });
+}
+
+test('editing both selected root and manifest cannot apply to a non-site directory', (t) => {
+ const fixture = setup(t);
+ const other = path.join(path.dirname(fixture.site), 'not-a-site');
+ fs.mkdirSync(other);
+ fs.writeFileSync(path.join(other, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fixture.writeManifest({ siteRoot: other, files: [{ relativePath: 'page.html' }] });
+ const result = fixture.run('--site-root', other);
+ assert.equal(result.status, 4, result.stderr);
+ assert.match(result.stderr, /downloaded Power Pages site containing website\.yml/);
+ assert.equal(fs.readFileSync(path.join(other, 'page.html'), 'utf8'), 'original');
+ assert.equal(fs.readFileSync(path.join(fixture.staged, 'page.html'), 'utf8'), 'proposal');
+ assert.equal(fs.existsSync(fixture.manifestPath), true);
+});
+
+test('apply resolves a managed project to the downloaded root recorded by the generator', (t) => {
+ const fixture = setup(t);
+ const metadata = path.join(fixture.site, '.powerpages-site');
+ fs.mkdirSync(metadata);
+ fs.renameSync(path.join(fixture.site, 'website.yml'), path.join(metadata, 'website.yml'));
+ fs.writeFileSync(path.join(metadata, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fixture.writeManifest({ siteRoot: metadata, files: [{ relativePath: 'page.html' }] });
+ const result = fixture.run();
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(fs.readFileSync(path.join(metadata, 'page.html'), 'utf8'), 'proposal');
+ assert.equal(fs.existsSync(path.join(fixture.site, 'page.html')), false);
+});
+
+test('successful apply removes both staged files and their diff manifest, but dry-run preserves both', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'approved proposal');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }] });
+ assert.equal(fixture.run('--dry-run').status, 0);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'original');
+ assert.equal(fs.existsSync(fixture.manifestPath), true);
+ assert.equal(fs.readFileSync(path.join(fixture.staged, 'page.html'), 'utf8'), 'approved proposal');
+ assert.equal(fixture.run().status, 0);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'approved proposal');
+ assert.equal(fs.existsSync(fixture.staged), false);
+ assert.equal(fs.existsSync(fixture.manifestPath), false);
+ assert.deepEqual(fs.readdirSync(fixture.output).filter((name) => name.startsWith('remediation-backup-')), []);
+ const repeat = fixture.run();
+ assert.equal(repeat.status, 3);
+ assert.match(repeat.stdout, /nothing to apply/);
+ assert.doesNotMatch(repeat.stderr, /Staged file missing/);
+});
+
+test('keep-staged retains a usable manifest and staged files after successful apply', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'approved proposal');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }] });
+ const before = fs.readFileSync(fixture.manifestPath, 'utf8');
+ const preview = fixture.run('--dry-run', '--keep-staged');
+ assert.equal(preview.status, 0);
+ assert.match(preview.stdout, /staged tree and diff manifest retained/);
+ assert.equal(fixture.run('--keep-staged').status, 0);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'approved proposal');
+ assert.equal(fs.readFileSync(path.join(fixture.staged, 'page.html'), 'utf8'), 'approved proposal');
+ assert.equal(fs.readFileSync(fixture.manifestPath, 'utf8'), before);
+ assert.equal(fixture.run('--keep-staged').status, 0);
+});
+
+test('discard removes both proposals and manifest without applying, while dry-run preserves both', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }] });
+ assert.equal(fixture.run('--discard', '--dry-run').status, 0);
+ assert.equal(fs.existsSync(fixture.manifestPath), true);
+ assert.equal(fs.existsSync(fixture.staged), true);
+ assert.equal(fixture.run('--discard').status, 0);
+ assert.equal(fs.existsSync(fixture.manifestPath), false);
+ assert.equal(fs.existsSync(fixture.staged), false);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'original');
+});
+
+test('hard-linked files cannot bypass apply containment', (t) => {
+ const fixture = setup(t);
+ const outside = path.join(path.dirname(fixture.site), 'outside.html');
+ fs.writeFileSync(outside, 'outside original');
+ fs.linkSync(outside, path.join(fixture.site, 'page.html'));
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }] });
+ const result = fixture.run();
+ assert.equal(result.status, 4);
+ assert.match(result.stderr, /hard-linked file/);
+ assert.equal(fs.readFileSync(outside, 'utf8'), 'outside original');
+});
+
+for (const linkedRoot of ['site', 'staged']) {
+ test(`apply rejects ${linkedRoot} descendant junctions without changing outside files`, (t) => {
+ const fixture = setup(t);
+ const outside = path.join(path.dirname(fixture.site), 'outside');
+ fs.mkdirSync(outside);
+ fs.writeFileSync(path.join(outside, 'page.html'), 'outside original');
+ const otherRoot = linkedRoot === 'site' ? fixture.staged : fixture.site;
+ fs.mkdirSync(path.join(otherRoot, 'link'));
+ fs.writeFileSync(path.join(otherRoot, 'link', 'page.html'), 'inside original');
+ fs.symlinkSync(outside, path.join(fixture[linkedRoot], 'link'),
+ process.platform === 'win32' ? 'junction' : 'dir');
+ fixture.writeManifest({ files: [{ relativePath: path.join('link', 'page.html') }] });
+ const result = fixture.run();
+ assert.equal(result.status, 4);
+ assert.match(result.stderr, /symbolic link or junction/);
+ assert.equal(fs.readFileSync(path.join(outside, 'page.html'), 'utf8'), 'outside original');
+ assert.equal(fs.readFileSync(path.join(otherRoot, 'link', 'page.html'), 'utf8'), 'inside original');
+ assert.ok(fs.existsSync(fixture.manifestPath));
+ });
+}
+
+test('a linked staged root is rejected before copying or cleanup', (t) => {
+ const fixture = setup(t);
+ const outside = path.join(path.dirname(fixture.site), 'outside');
+ fs.mkdirSync(outside);
+ fs.writeFileSync(path.join(outside, 'page.html'), 'proposal');
+ fs.rmdirSync(fixture.staged);
+ fs.symlinkSync(outside, fixture.staged, process.platform === 'win32' ? 'junction' : 'dir');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }] });
+ assert.equal(fixture.run().status, 4);
+ assert.equal(fs.readFileSync(path.join(outside, 'page.html'), 'utf8'), 'proposal');
+});
+
+test('late copy failure restores overwritten files, removes new files and directories, and retains proposals', (t) => {
+ const fixture = setup(t);
+ const paths = ['existing.html', path.join('new-folder', 'new.html'), 'failure.html'];
+ fs.writeFileSync(path.join(fixture.site, paths[0]), 'original');
+ for (const relativePath of paths) {
+ const stagedPath = path.join(fixture.staged, relativePath);
+ fs.mkdirSync(path.dirname(stagedPath), { recursive: true });
+ fs.writeFileSync(stagedPath, 'proposal');
+ }
+ fixture.writeManifest({ files: paths.map((relativePath) => ({ relativePath })) });
+ const result = fixture.injectFailure(`
+ const copy = fs.copyFileSync;
+ fs.copyFileSync = (from, to) => {
+ if (path.basename(to) === 'failure.html') {
+ fs.writeFileSync(to, 'partially copied');
+ throw new Error('injected disk failure');
+ }
+ return copy(from, to);
+ };
+ `);
+ assert.equal(result.status, 4);
+ assert.match(result.stderr, /injected disk failure.*Original files restored/s);
+ assert.equal(fs.readFileSync(path.join(fixture.site, paths[0]), 'utf8'), 'original');
+ assert.equal(fs.existsSync(path.join(fixture.site, 'new-folder')), false);
+ assert.equal(fs.existsSync(path.join(fixture.site, 'failure.html')), false);
+ assert.ok(fs.existsSync(fixture.staged));
+ assert.ok(fs.existsSync(fixture.manifestPath));
+});
+
+test('a failed copy that truncates an existing destination restores that destination too', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }] });
+ const result = fixture.injectFailure(`
+ fs.copyFileSync = (from, to) => {
+ fs.writeFileSync(to, '');
+ throw new Error('injected truncation');
+ };
+ `);
+ assert.equal(result.status, 4);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'original');
+});
+
+test('rollback errors are explicit and retain recovery inputs', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }] });
+ const result = fixture.injectFailure(`
+ fs.copyFileSync = () => { throw new Error('injected copy failure'); };
+ const write = fs.writeFileSync;
+ fs.writeFileSync = (file, ...args) => {
+ if (path.basename(file) === 'page.html') throw new Error('injected restore failure');
+ return write(file, ...args);
+ };
+ `);
+ assert.equal(result.status, 4);
+ assert.match(result.stderr, /Rollback incomplete; manual recovery required/);
+ assert.match(result.stderr, /injected restore failure/);
+ assert.ok(fs.existsSync(fixture.staged));
+ assert.ok(fs.existsSync(fixture.manifestPath));
+ const backups = fs.readdirSync(fixture.output).filter((name) => name.startsWith('remediation-backup-'));
+ assert.equal(backups.length, 1);
+ assert.equal(fs.readFileSync(path.join(fixture.output, backups[0], '0.bin'), 'utf8'), 'original');
+ const recovery = JSON.parse(fs.readFileSync(path.join(fixture.output, backups[0], 'manifest.json'), 'utf8'));
+ assert.equal(recovery.files[0].relativePath, 'page.html');
+});
+
+test('backup failure aborts before any live write', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }] });
+ const result = fixture.injectFailure(`
+ fs.writeFileSync = () => { throw new Error('injected backup failure'); };
+ `);
+ assert.equal(result.status, 4);
+ assert.match(result.stderr, /Could not prepare backup.*No live files changed/s);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'original');
+});
+
+test('missing manifest and empty file list remain explicit nothing-to-apply results', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 3);
+ fixture.writeManifest({ files: [] });
+ assert.equal(fixture.run().status, 3);
+});
+
+test('null or malformed remediation entries produce validation errors without touching source', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ for (const payload of [null, {}, { files: null }, { files: [null] },
+ { files: [{}] }, { files: [{ relativePath: {} }] }, { files: [{ relativePath: '' }] }]) {
+ fixture.writeManifest(payload);
+ const result = fixture.run();
+ assert.equal(result.status, 4);
+ assert.match(result.stderr, /must contain/);
+ assert.doesNotMatch(result.stderr, /TypeError|Cannot read properties/);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'original');
+ }
+});
+
+test('all staged files are checked before any live file is overwritten', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fixture.writeManifest({ files: [{ relativePath: 'page.html' }, { relativePath: 'missing.html' }] });
+ const result = fixture.run();
+ assert.equal(result.status, 4);
+ assert.match(result.stderr, /Staged file missing or not a file/);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'original');
+ assert.ok(fs.existsSync(fixture.staged));
+});
+
+test('traversal paths are rejected without copying or deleting files', (t) => {
+ const fixture = setup(t);
+ fixture.writeManifest({ files: [{ relativePath: path.join('..', 'outside.html') }] });
+ const result = fixture.run();
+ assert.equal(result.status, 4);
+ assert.match(result.stderr, /must stay inside/);
+ assert.ok(fs.existsSync(fixture.staged));
+});
+
+test('a different or missing manifest site identity cannot receive staged files', (t) => {
+ const fixture = setup(t);
+ const otherSite = path.join(path.dirname(fixture.site), 'other-site');
+ fs.mkdirSync(otherSite);
+ fs.writeFileSync(path.join(fixture.staged, 'page.html'), 'proposal');
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), 'original');
+ for (const siteRoot of [otherSite, null, 'relative-site']) {
+ fixture.writeManifest({ siteRoot, files: [{ relativePath: 'page.html' }] });
+ const result = fixture.run();
+ assert.equal(result.status, 4);
+ assert.match(result.stderr, /siteRoot|does not match/);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), 'original');
+ assert.ok(fs.existsSync(fixture.staged));
+ }
+});
diff --git a/plugins/power-pages/scripts/tests/detect-template.test.js b/plugins/power-pages/scripts/tests/detect-template.test.js
new file mode 100644
index 000000000..c057e6581
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/detect-template.test.js
@@ -0,0 +1,127 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const {
+ resolve, loadInstalledSolutions, inspectSite,
+} = require('../../skills/migrate-datamodel/scripts/detect-template');
+
+for (const [label, inspection, anchors, decision, templateKey] of [
+ ['agree', 'Partner', ['PartnerPortal'], 'install-v2', 'Partner'],
+ ['anchor overrides inspection', 'Partner', ['CommunityPortal'], 'install-v2', 'Community'],
+ ['inspection breaks tie', 'Partner', ['PartnerPortal', 'CommunityPortal'], 'install-v2', 'Partner'],
+ ['ambiguous unmatched anchors', 'Partner', ['CommunityPortal', 'ESSPortal'], 'prompt-pick'],
+ ['inspection without anchor', 'Partner', [], 'prompt-confirm'],
+ ['single medium anchor', null, ['PowerPages_FAQ'], 'install-v2', 'FAQ'],
+ ['customer self service', null, ['customerportal'], 'install-v2', 'CustomerSelfService'],
+ ['multiple medium anchors', null, ['PowerPages_FAQ', 'PowerPages_BuildingPermit'], 'prompt-pick-or-install-all'],
+ ['no evidence', null, [], 'low-complexity-skip'],
+]) {
+ test(`template resolution: ${label}`, () => {
+ const result = resolve({ match: inspection, signals: [] }, anchors);
+ assert.equal(result.decision, decision);
+ if (templateKey) assert.equal(result.templateKey, templateKey);
+ assert.equal(result.needsPrompt, decision.startsWith('prompt'));
+ });
+}
+
+test('solution list BOMs are decoded and missing requested input fails explicitly', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-template-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const file = path.join(root, 'solutions.txt');
+ for (const bytes of [
+ Buffer.from('\uFEFFUnique Name PowerPages_FAQ\r\n', 'utf8'),
+ Buffer.from('\uFEFFUnique Name PowerPages_FAQ\r\n', 'utf16le'),
+ Buffer.from('\uFEFFUnique Name PowerPages_FAQ\r\n', 'utf16le').swap16(),
+ ]) {
+ fs.writeFileSync(file, bytes);
+ assert.deepEqual(loadInstalledSolutions({ solutions: [], solutionsFile: file }), ['PowerPages_FAQ']);
+ }
+ assert.throws(() => loadInstalledSolutions({ solutions: [], solutionsFile: path.join(root, 'missing.txt') }),
+ /Could not read template detection input/);
+});
+
+test('template inspection accepts the nested downloaded configuration root', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-template-site-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const config = path.join(root, '.powerpages-site');
+ fs.mkdirSync(config);
+ fs.writeFileSync(path.join(config, 'website.yml'), 'adx_name: Contoso');
+ fs.writeFileSync(path.join(config, 'webrole.yml'), '- adx_key: partneradmin');
+ const result = spawnSync(process.execPath, [
+ path.join(__dirname, '../../skills/migrate-datamodel/scripts/detect-template.js'),
+ '--site-root', root, '--solutions', 'PartnerPortal',
+ ], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(result.stdout).resolution.templateKey, 'Partner');
+});
+
+test('template detection rejects arbitrary or incomplete roots rather than skipping V2 installation', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-template-invalid-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const run = () => spawnSync(process.execPath, [
+ path.join(__dirname, '../../skills/migrate-datamodel/scripts/detect-template.js'),
+ '--site-root', root, '--solutions', 'PartnerPortal',
+ ], { encoding: 'utf8' });
+ fs.mkdirSync(path.join(root, '.powerpages-site'));
+ for (const marker of ['missing', 'directory']) {
+ if (marker === 'directory') fs.mkdirSync(path.join(root, '.powerpages-site', 'website.yml'));
+ const result = run();
+ assert.equal(result.status, 1, result.stdout);
+ assert.match(result.stderr, /downloaded Power Pages site containing website\.yml/);
+ assert.equal(result.stdout, '');
+ }
+});
+
+test('valid low-complexity downloaded sites still skip template installation', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-template-blank-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(root, 'website.yml'), 'adx_name: Contoso');
+ const result = spawnSync(process.execPath, [
+ path.join(__dirname, '../../skills/migrate-datamodel/scripts/detect-template.js'),
+ '--site-root', root,
+ ], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(result.stdout).resolution.decision, 'low-complexity-skip');
+});
+
+for (const [layout, files] of [
+ ['aggregate', { 'webrole.yml': '- adx_key: partneradmin' }],
+ ['per-record', { 'web-roles\\Partner.webrole.yml': 'key: "partneradmin"' }],
+ ['mixed', {
+ 'webrole.yml': '- adx_name: Members',
+ 'web-roles\\Partner.webrole.yml': "adx_key: 'partnermanager'",
+ }],
+]) {
+ test(`Partner V2 detection includes ${layout} web roles`, (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-partner-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ for (const [relative, content] of Object.entries({ 'website.yml': 'adx_name: Contoso', ...files })) {
+ const filename = path.join(root, ...relative.split('\\'));
+ fs.mkdirSync(path.dirname(filename), { recursive: true });
+ fs.writeFileSync(filename, content);
+ }
+ const result = spawnSync(process.execPath, [
+ path.join(__dirname, '../../skills/migrate-datamodel/scripts/detect-template.js'),
+ '--site-root', root, '--solutions', 'PartnerPortal',
+ ], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ const { resolution } = JSON.parse(result.stdout);
+ assert.equal(resolution.decision, 'install-v2');
+ assert.equal(resolution.v2Package, 'PowerPages_PartnerPortal_V2');
+ });
+}
+
+test('Community inspection reads normalized per-record role names and surfaces malformed roles', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-community-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ fs.mkdirSync(path.join(root, 'web-pages', 'blogs'), { recursive: true });
+ fs.mkdirSync(path.join(root, 'web-roles'));
+ const role = path.join(root, 'web-roles', 'Authors.webrole.yml');
+ fs.writeFileSync(role, 'name: "Blog Authors"');
+ assert.equal(inspectSite(root).match, 'Community');
+ fs.writeFileSync(role, 'name: Authors\nmalformed field');
+ assert.throws(() => inspectSite(root), /Invalid YAML line.*Authors\.webrole\.yml/);
+});
diff --git a/plugins/power-pages/scripts/tests/diff-snapshots.test.js b/plugins/power-pages/scripts/tests/diff-snapshots.test.js
new file mode 100644
index 000000000..107ed1bf7
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/diff-snapshots.test.js
@@ -0,0 +1,148 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const script = path.join(__dirname, '../../skills/migrate-datamodel/scripts/diff-snapshots.js');
+
+function compare(t, sdmInventory, edmInventory, options = {}) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-diff-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ for (const [label, inventory] of [['sdm', sdmInventory], ['edm', edmInventory]]) {
+ const snapshot = Object.hasOwn(options, `${label}Snapshot`) ? options[`${label}Snapshot`] : {
+ label, inventory, parseErrors: options[label] || {},
+ };
+ fs.writeFileSync(path.join(root, `${label}.json`), JSON.stringify(snapshot));
+ }
+ const result = spawnSync(process.execPath, [
+ script, '--sdm', path.join(root, 'sdm.json'), '--edm', path.join(root, 'edm.json'),
+ '--output-dir', root,
+ ], { encoding: 'utf8' });
+ const output = path.join(root, 'migration-data-diff.json');
+ return { ...result, diff: fs.existsSync(output) ? JSON.parse(fs.readFileSync(output, 'utf8')) : null };
+}
+
+test('equivalent identities and active state normalization still pass', (t) => {
+ const result = compare(t, { webTemplates: [{ name: 'Home', stateCode: null }] },
+ { webTemplates: [{ name: 'Home', stateCode: 0 }] });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.diff.overallStatus, 'pass');
+});
+
+test('state, setting value and content changes remain reviewable warnings', (t) => {
+ const result = compare(t, {
+ webTemplates: [{ name: 'Home', stateCode: 0, contentHash: 'before' }],
+ siteSettings: [{ name: 'Search/Enabled', value: 'true' }],
+ }, {
+ webTemplates: [{ name: 'Home', stateCode: 1, contentHash: 'after' }],
+ siteSettings: [{ name: 'Search/Enabled', value: 'false' }],
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.diff.overallStatus, 'warn');
+ assert.equal(result.diff.categories.webTemplates.stateChanged.length, 1);
+ assert.equal(result.diff.categories.webTemplates.contentChanged.length, 1);
+ assert.equal(result.diff.categories.siteSettings.valueChanged.length, 1);
+});
+
+test('missing metadata still fails while SDM-only download categories warn', (t) => {
+ const result = compare(t, {
+ webTemplates: [{ name: 'Home' }], ads: [{ name: 'Ad' }], tags: [{ name: 'Tag' }],
+ }, { webTemplates: [], ads: [], tags: [] });
+ assert.equal(result.status, 1);
+ assert.equal(result.diff.categories.webTemplates.status, 'fail');
+ // Ads are nonconfiguration data and remain intentionally excluded.
+ assert.equal(result.diff.categories.ads.status, 'excluded');
+ assert.equal(result.diff.categories.tags.status, 'warn');
+});
+
+test('parse errors in either or both snapshots prevent a passing comparison', async (t) => {
+ for (const side of ['sdm', 'edm', 'both']) {
+ await t.test(side, (t) => {
+ const errors = { webPages: [{ filePath: 'Home.webpage.yml', message: 'invalid YAML' }] };
+ const result = compare(t, {}, {}, {
+ sdm: side !== 'edm' ? errors : {},
+ edm: side !== 'sdm' ? errors : {},
+ });
+ assert.equal(result.status, 1);
+ assert.equal(result.diff.overallStatus, 'fail');
+ assert.deepEqual(result.diff.parseErrors[side === 'edm' ? 'edm' : 'sdm'], errors);
+ assert.match(result.stderr, /snapshot parse error/);
+ });
+ }
+});
+
+test('one-sided companion content hash warns in either direction', async (t) => {
+ for (const [sdmHash, edmHash] of [['hash', null], [null, 'hash']]) {
+ await t.test(`${sdmHash} to ${edmHash}`, (t) => {
+ const result = compare(t, { webTemplates: [{ name: 'Home', contentHash: sdmHash }] },
+ { webTemplates: [{ name: 'Home', contentHash: edmHash }] });
+ assert.equal(result.diff.overallStatus, 'warn');
+ assert.equal(result.diff.categories.webTemplates.contentChanged.length, 1);
+ });
+ }
+});
+
+test('two absent hashes remain equal', (t) => {
+ const result = compare(t, { webTemplates: [{ name: 'Home', contentHash: null }] },
+ { webTemplates: [{ name: 'Home' }] });
+ assert.equal(result.diff.overallStatus, 'pass');
+});
+
+test('pipe characters cannot collide across identity fields', (t) => {
+ const result = compare(t, { contentSnippets: [{ name: 'a|b', language: 'c' }] },
+ { contentSnippets: [{ name: 'a', language: 'b|c' }] });
+ assert.equal(result.status, 1);
+ assert.equal(result.diff.categories.contentSnippets.missingInEdm.length, 1);
+ assert.equal(result.diff.categories.contentSnippets.extraInEdm.length, 1);
+});
+
+test('navigation identities include parent set and language', (t) => {
+ const result = compare(t, { webLinks: [
+ { name: 'Home', parentSet: 'Main', language: 'en-US' },
+ { name: 'Home', parentSet: 'Footer', language: 'en-US' },
+ ] }, { webLinks: [
+ { name: 'Home', parentSet: 'Main', language: 'fr-FR' },
+ { name: 'Home', parentSet: 'Footer', language: 'en-US' },
+ ] });
+ assert.equal(result.status, 1);
+ assert.equal(result.diff.categories.webLinks.missingInEdm.length, 1);
+});
+
+test('duplicate identities cannot silently overwrite one another', (t) => {
+ const records = [{ name: 'Repeated', slug: 'first' }, { name: 'Repeated', slug: 'second' }];
+ const result = compare(t, { basicForms: records }, { basicForms: records });
+ assert.equal(result.status, 1);
+ assert.equal(result.diff.categories.basicForms.duplicateKeys.sdm.length, 1);
+ assert.match(result.stdout, /duplicate identities/);
+});
+
+test('missing inventory is rejected rather than treated as empty', (t) => {
+ const result = compare(t, undefined, {});
+ assert.equal(result.status, 1);
+ assert.equal(result.diff, null);
+ assert.match(result.stderr, /inventory object/);
+});
+
+test('null snapshots and null inventory records produce descriptive validation errors', (t) => {
+ const missing = compare(t, {}, {}, { sdmSnapshot: null });
+ assert.equal(missing.status, 1);
+ assert.match(missing.stderr, /sdm snapshot must contain an inventory object/);
+ assert.doesNotMatch(missing.stderr, /TypeError|Cannot read properties/);
+ const record = compare(t, { webTemplates: [null] }, {});
+ assert.equal(record.status, 1);
+ assert.match(record.stderr, /inventory records must be objects/);
+ assert.doesNotMatch(record.stderr, /TypeError|Cannot read properties/);
+});
+
+test('navigation order and target changes warn even with identical names and counts', (t) => {
+ const link = { name: 'Home', parentSet: 'Main', language: 'en-US',
+ pageId: 'original-page', externalUrl: null, displayOrder: 1, stateCode: 0 };
+ const result = compare(t, { webLinks: [link] }, {
+ webLinks: [{ ...link, pageId: 'other-page', externalUrl: 'https://contoso.com', displayOrder: 2 }],
+ });
+ assert.equal(result.diff.overallStatus, 'warn');
+ assert.deepEqual(result.diff.categories.webLinks.valueChanged.map((change) => change.field),
+ ['pageId', 'externalUrl', 'displayOrder']);
+});
diff --git a/plugins/power-pages/scripts/tests/edm-table-classification.test.js b/plugins/power-pages/scripts/tests/edm-table-classification.test.js
new file mode 100644
index 000000000..fb45d7d0e
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/edm-table-classification.test.js
@@ -0,0 +1,85 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const classification = require('../../skills/migrate-datamodel/scripts/lib/edm-table-classification');
+const { diffCategory } = require('../../skills/migrate-datamodel/scripts/diff-snapshots');
+
+test('nonconfiguration Settings do not exclude migrated site settings from metadata validation', () => {
+ assert.equal(classification.isNonconfigurationCategory('settings'), true);
+ assert.equal(classification.isNonconfigurationCategory('siteSettings'), false);
+ assert.equal(classification.isReportExcludedCategory('siteSettings'), false);
+ const before = [{ name: 'Search/Enabled', value: 'true' }];
+ const missing = diffCategory('siteSettings', before, []);
+ assert.equal(missing.status, 'fail');
+ assert.equal(missing.missingInEdm.length, 1);
+ const changed = diffCategory('siteSettings', before, [{ name: 'Search/Enabled', value: 'false' }]);
+ assert.equal(changed.valueChanged.length, 1);
+});
+
+test('nonconfiguration categories are excluded while poll placements remain comparable', () => {
+ assert.deepEqual(classification.NONCONFIGURATION_TABLES.map(({ table }) => table), [
+ 'Ad',
+ 'Poll',
+ 'Poll Submission',
+ 'External Identity',
+ 'Portal comment',
+ 'Invitation',
+ 'Invitation Redemption',
+ 'Setting',
+ 'WebFormSession',
+ ]);
+ assert.equal(classification.isNonconfigurationCategory('polls'), true);
+ assert.equal(classification.isNonconfigurationCategory('ads'), true);
+ assert.equal(classification.isNonconfigurationCategory('pollPlacements'), false);
+ assert.equal(classification.isReportExcludedCategory('polls'), true);
+ assert.equal(classification.isReportExcludedCategory('pollPlacements'), false);
+});
+
+test('poll metadata describes the separate compatibility warning', () => {
+ assert.deepEqual(classification.getCategoryMetadata('polls'), {
+ label: 'Polls',
+ reason: 'Polls are nonconfiguration data and are removed from the enhanced data model.',
+ });
+});
+
+test('snapshot diff excludes polls from failure totals but compares poll placements', () => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'edm-diff-'));
+ const sdmPath = path.join(tempDir, 'sdm.json');
+ const edmPath = path.join(tempDir, 'edm.json');
+ const sdm = {
+ label: 'sdm',
+ inventory: {
+ polls: [{ name: 'Yes or No Question' }],
+ pollPlacements: [{ name: 'Home' }],
+ webPages: [{ name: 'Home', kind: 'parent', partialUrl: '/', language: '' }],
+ },
+ };
+ const edm = {
+ label: 'edm',
+ inventory: {
+ polls: [],
+ pollPlacements: [{ name: 'Home' }],
+ webPages: [{ name: 'Home', kind: 'parent', partialUrl: '/', language: '' }],
+ },
+ };
+ fs.writeFileSync(sdmPath, JSON.stringify(sdm));
+ fs.writeFileSync(edmPath, JSON.stringify(edm));
+
+ const result = spawnSync(process.execPath, [
+ path.join(__dirname, '../../skills/migrate-datamodel/scripts/diff-snapshots.js'),
+ '--sdm', sdmPath,
+ '--edm', edmPath,
+ '--output-dir', tempDir,
+ ], { encoding: 'utf8' });
+
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+ const diff = JSON.parse(fs.readFileSync(path.join(tempDir, 'migration-data-diff.json'), 'utf8'));
+ assert.equal(diff.overallStatus, 'pass');
+ assert.equal(diff.categories.polls.status, 'excluded');
+ assert.equal(diff.categories.polls.sdmCount, 1);
+ assert.equal(diff.categories.pollPlacements.status, 'pass');
+ assert.equal(diff.summary.totalMissing, 0);
+});
diff --git a/plugins/power-pages/scripts/tests/generate-migration-reports.test.js b/plugins/power-pages/scripts/tests/generate-migration-reports.test.js
new file mode 100644
index 000000000..dd49b9503
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/generate-migration-reports.test.js
@@ -0,0 +1,479 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { pathToFileURL } = require('node:url');
+const {
+ parseCSV, normalizeLocationPath, fillPlaceholders, generateCustomizationSection,
+ rewriteFetchXmlInContent, annotateLiquidEntitiesInContent,
+ buildDataModelExtensionChecklists, categorizePlugin,
+ classifyCustomizationFinding, assessCustomizations, executeAutomatedRemediation,
+} = require('../../skills/migrate-datamodel/scripts/generate-migration-reports');
+
+const script = path.join(__dirname, '../../skills/migrate-datamodel/scripts/generate-migration-reports.js');
+const fetchXml = '<fetch><entity name="adx_webpage"><attribute name="adx_name" /></entity></fetch>';
+const liquid = "{{ entities['adx_contentsnippet'] }}";
+
+function setup(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-remediation-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const site = path.join(root, 'site');
+ const output = path.join(root, 'reports');
+ fs.mkdirSync(site);
+ fs.writeFileSync(path.join(site, 'website.yml'), 'adx_websiteid: 00000000-0000-0000-0000-000000000001\n');
+ const run = (...flags) => spawnSync(process.execPath, [
+ script, '--site-name', 'Contoso', '--website-id', '00000000-0000-0000-0000-000000000001',
+ '--site-path', site, '--output-dir', output, ...flags,
+ ], { encoding: 'utf8', timeout: 10000 });
+ const manifestPath = path.join(output, 'remediation-diff.json');
+ const manifest = () => JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
+ return { site, output, run, manifestPath, manifest };
+}
+
+test('both diff formats terminate on reordered/repeated lines and preserve the inputs', () => {
+ // Run in a bounded child: a regression in the cursor loop must fail this test
+ // rather than hang the entire test runner.
+ const worker = `
+ const assert = require('node:assert/strict');
+ const {diffLines, unifiedDiff, structuredDiff} = require(${JSON.stringify(script)});
+ for (const [before, after] of [
+ ['A\\nB', 'B\\nA'], ['A\\nB\\nA', 'B\\nA\\nB'],
+ ['A', 'A\\nB'], ['A\\nB', 'A'], ['', 'A'], ['A', ''], ['A', 'A'],
+ ]) {
+ const lines = diffLines(before, after);
+ assert.equal(lines.filter(l => l.type !== 'added').map(l => l.text).join('\\n'), before);
+ assert.equal(lines.filter(l => l.type !== 'removed').map(l => l.text).join('\\n'), after);
+ const structured = structuredDiff(before, after);
+ assert.equal(structured.linesAdded, lines.filter(l => l.type === 'added').length);
+ assert.equal(structured.linesRemoved, lines.filter(l => l.type === 'removed').length);
+ assert.equal(unifiedDiff(before, after, 'sample').length > 0, before !== after);
+ }
+ `;
+ const result = spawnSync(process.execPath, ['-e', worker], { encoding: 'utf8', timeout: 5000 });
+ assert.equal(result.error, undefined, result.error?.message);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test('separate remediation passes retain every file without changing live source', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'fetch.html'), fetchXml);
+ fs.writeFileSync(path.join(fixture.site, 'liquid.html'), liquid);
+ assert.equal(fixture.run('--automate-fetchxml').status, 0);
+ assert.deepEqual(fixture.manifest().files.map((entry) => entry.relativePath), ['fetch.html']);
+ const second = fixture.run('--automate-liquid');
+ assert.equal(second.status, 0, second.stderr);
+ assert.deepEqual(fixture.manifest().files.map((entry) => entry.relativePath), ['fetch.html', 'liquid.html']);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'fetch.html'), 'utf8'), fetchXml);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'liquid.html'), 'utf8'), liquid);
+});
+
+test('both passes on one file preserve FetchXML and Liquid changes and reruns are idempotent', (t) => {
+ const fixture = setup(t);
+ const original = `${fetchXml}\n${liquid}`;
+ fs.writeFileSync(path.join(fixture.site, 'combined.html'), original);
+ assert.equal(fixture.run('--automate-fetchxml').status, 0);
+ assert.equal(fixture.run('--automate-liquid').status, 0);
+ const stagedPath = path.join(fixture.output, 'remediation-staged', 'combined.html');
+ const staged = fs.readFileSync(stagedPath, 'utf8');
+ assert.match(staged, /name="powerpagecomponent"/);
+ assert.match(staged, /SDM\u2192EDM SUGGESTION/);
+ assert.equal(fixture.manifest().files[0].kind, 'fetchxml+liquid');
+ const repeated = fixture.run('--automate-liquid');
+ assert.equal(repeated.status, 0, repeated.stderr);
+ assert.equal(fs.readFileSync(stagedPath, 'utf8'), staged);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'combined.html'), 'utf8'), original);
+});
+
+test('zero-rewrite rerun removes obsolete manifest and staged proposals', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), fetchXml);
+ assert.equal(fixture.run('--automate-fetchxml').status, 0);
+ assert.ok(fs.existsSync(fixture.manifestPath));
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), '<p>Already remediated</p>');
+ const rerun = fixture.run('--automate-fetchxml');
+ assert.equal(rerun.status, 0, rerun.stderr);
+ assert.equal(fs.existsSync(fixture.manifestPath), false);
+ assert.equal(fs.existsSync(path.join(fixture.output, 'remediation-staged', 'page.html')), false);
+});
+
+test('a different site cannot reuse an existing remediation manifest', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), fetchXml);
+ assert.equal(fixture.run('--automate-fetchxml').status, 0);
+ const original = fs.readFileSync(fixture.manifestPath, 'utf8');
+ const otherSite = path.join(fixture.site, 'other');
+ fs.mkdirSync(otherSite);
+ fs.writeFileSync(path.join(otherSite, 'website.yml'), 'adx_websiteid: 00000000-0000-0000-0000-000000000002\n');
+ const result = fixture.run('--automate-liquid', '--site-path', otherSite);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /does not match the selected site root/);
+ assert.equal(fs.readFileSync(fixture.manifestPath, 'utf8'), original);
+});
+
+test('null saved remediation inputs produce clear errors before proposals are removed', (t) => {
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), fetchXml);
+ assert.equal(fixture.run('--automate-fetchxml').status, 0);
+ const stagedPath = path.join(fixture.output, 'remediation-staged', 'page.html');
+ const staged = fs.readFileSync(stagedPath, 'utf8');
+ for (const payload of [null, { siteRoot: fixture.site, files: [null] }]) {
+ fs.writeFileSync(fixture.manifestPath, JSON.stringify(payload));
+ const result = fixture.run('--automate-fetchxml');
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /does not match|Unknown remediation kind/);
+ assert.doesNotMatch(result.stderr, /TypeError|Cannot read properties/);
+ assert.equal(fs.readFileSync(stagedPath, 'utf8'), staged);
+ }
+});
+
+test('remediation rejects arbitrary roots before creating reports or altering existing proposals', (t) => {
+ const fixture = setup(t);
+ const empty = path.join(fixture.site, 'not-a-site');
+ fs.mkdirSync(empty);
+ for (const flag of ['--automate-fetchxml', '--automate-liquid']) {
+ const result = fixture.run(flag, '--site-path', empty);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /downloaded Power Pages site containing website\.yml/);
+ assert.equal(fs.existsSync(fixture.output), false);
+ }
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), fetchXml);
+ assert.equal(fixture.run('--automate-fetchxml').status, 0);
+ const manifest = fs.readFileSync(fixture.manifestPath, 'utf8');
+ const stagedPath = path.join(fixture.output, 'remediation-staged', 'page.html');
+ const staged = fs.readFileSync(stagedPath, 'utf8');
+ const result = fixture.run('--automate-liquid', '--site-path', empty);
+ assert.equal(result.status, 1);
+ assert.equal(fs.readFileSync(fixture.manifestPath, 'utf8'), manifest);
+ assert.equal(fs.readFileSync(stagedPath, 'utf8'), staged);
+});
+
+test('remediation resolves managed metadata roots before scanning and binding the manifest', (t) => {
+ const fixture = setup(t);
+ const metadata = path.join(fixture.site, '.powerpages-site');
+ fs.mkdirSync(metadata);
+ fs.writeFileSync(path.join(metadata, 'website.yml'), 'adx_websiteid: 00000000-0000-0000-0000-000000000001\n');
+ fs.writeFileSync(path.join(metadata, 'page.html'), `${fetchXml}\n${liquid}`);
+ fs.writeFileSync(path.join(fixture.site, 'outside.html'), fetchXml);
+ const result = fixture.run('--automate-fetchxml', '--automate-liquid');
+ assert.equal(result.status, 0, result.stderr);
+ const manifest = fixture.manifest();
+ assert.equal(manifest.siteRoot, metadata);
+ assert.deepEqual(manifest.files.map((file) => file.relativePath), ['page.html']);
+ const staged = fs.readFileSync(path.join(fixture.output, 'remediation-staged', 'page.html'), 'utf8');
+ assert.match(staged, /name="powerpagecomponent"/);
+ assert.match(staged, /SDM\u2192EDM SUGGESTION/);
+});
+
+test('CSV parser preserves quoted commas, escaped quotes, multiline fields and CRLF', () => {
+ assert.deepEqual(parseCSV('type,snippet,location\r\nLiquid,"say ""hi"",\nthen go",header.html\r\n'), [
+ ['type', 'snippet', 'location'], ['Liquid', 'say "hi",\nthen go', 'header.html'],
+ ]);
+});
+
+test('expected Liquid references are informational, but mixed or unknown usage is not suppressed', () => {
+ const liquidType = 'Liquid contains adx references';
+ for (const snippet of [
+ '{{ page.adx_copy }}', '{{ website.adx_partialurl }}',
+ "{% editable page 'adx_copy' %}", "{{ snippets['adx_name'] }}",
+ '{{ botconsumer.adx_configjson }} {{ botconsumer.adx_botschemaname }}',
+ '{{ incident.adx_resolutiondate }} {{ forums_sm.adx_name }}',
+ ]) {
+ assert.equal(classifyCustomizationFinding(liquidType, { snippet }).status, 'informational', snippet);
+ }
+ for (const snippet of [
+ '', '{{ page.adx_copy }} adx_unknown',
+ '{{ page.adx_copy }} <entity name="adx_webpage">',
+ '{{ page.adx_copy }} {{ entities[adx_webpage] }}',
+ '{{ entities.adx_webpage }}', '{{ page.adx_copy }} {{ entities[tableName] }}',
+ "{{#label entityLogicalName 'adx_event'}}",
+ "{{ entities['adx_communityforumthread'] }}",
+ ]) {
+ assert.equal(classifyCustomizationFinding(liquidType, { snippet }).status, 'needsReview', snippet);
+ }
+ for (const snippet of [
+ liquid, `{{ page.adx_copy }} ${liquid}`,
+ `{% fetchxml query %}${fetchXml}{% endfetchxml %}`,
+ '{% fetchxml query %}<fetch><entity name="category"><link-entity name="adx_webpage"/></entity></fetch>{% endfetchxml %}',
+ ]) {
+ assert.equal(classifyCustomizationFinding(liquidType, { snippet }).status, 'actionable', snippet);
+ }
+ assert.equal(classifyCustomizationFinding(liquidType, {
+ snippet: '{% fetchxml query %}<fetch><entity name="adx_communityforumthread"/></fetch>{% endfetchxml %}',
+ }).status, 'needsReview');
+});
+
+test('FetchXML category variants share conservative target-aware assessment', () => {
+ for (const type of ['Fetch Xml contains adx references', 'FetchXml contains adx references',
+ 'FetchXML contains adx references']) {
+ assert.equal(classifyCustomizationFinding(type, { snippet: fetchXml }).status, 'actionable');
+ assert.equal(classifyCustomizationFinding(type, {
+ snippet: '<fetch><entity name="category"><link-entity name="knowledgearticle"/></entity></fetch>',
+ }).status, 'informational');
+ for (const snippet of [
+ '<fetch><entity name="category">',
+ '<fetch><entity name="adx_communityforumthread"><attribute name="adx_postcount"/></entity></fetch>',
+ '<fetch><entity name="knowledgearticle"><attribute name="adx_custom"/></entity></fetch>',
+ ]) {
+ assert.equal(classifyCustomizationFinding(type, { snippet }).status, 'needsReview', snippet);
+ }
+ }
+});
+
+test('analysis and report counts separate expected references, actual manual work and investigation', async () => {
+ const customizations = {
+ 'Liquid contains adx references': [
+ { snippet: '{{ page.adx_copy }}', location: 'page.html' },
+ { snippet: liquid, location: 'snippet.html' },
+ { snippet: 'adx_unknown', location: 'unknown.html' },
+ ],
+ 'Data Model Extension': [
+ { snippet: 'Table name : adx_webpage Column name : contoso_value' },
+ { snippet: 'Table name : adx_invitation Column name : contoso_value' },
+ ],
+ 'Plugins registered on adx entities': [
+ { snippet: 'Plugin name : Contoso.Plugin Step name : Update Entity Name : adx_webpage' },
+ { snippet: 'Plugin name : Microsoft.Plugin Step name : Update Entity Name : adx_webpage' },
+ ],
+ };
+ const assessment = assessCustomizations(customizations);
+ assert.deepEqual(assessment.summary, { informational: 1, actionable: 3, needsReview: 3 });
+ assert.equal(assessment.findings.length, 7);
+ assert.equal(assessment.findings[0].location, 'page.html');
+ assert.ok(assessment.findings.every((finding) => finding.reason.length > 0));
+ const results = await executeAutomatedRemediation(customizations);
+ assert.equal(results.informational.length, 1);
+ assert.equal(results.manual.length, 3);
+ assert.equal(results.needsReview.length, 3);
+ assert.equal(results.automated.length, 0);
+ assert.ok(results.manual.every((finding) => finding.assessment.status === 'actionable'));
+});
+
+test('CLI retains assessments with no proposals and does not report unknown work as completed', (t) => {
+ const fixture = setup(t);
+ const csv = path.join(fixture.site, 'SiteCustomization.csv');
+ const assessmentPath = path.join(fixture.output, 'customization-assessment.json');
+ const htmlPath = path.join(fixture.output, 'customization-report.html');
+ const writeFinding = (snippet) => fs.writeFileSync(csv,
+ 'Type of customization,Snippet,Location,Guidance\n' +
+ ['Liquid contains adx references', snippet, 'page.html', ''].map(
+ (field) => `"${field.replace(/"/g, '""')}"`,
+ ).join(',') + '\n');
+ const expected = '{{ page.adx_copy }}';
+ fs.writeFileSync(path.join(fixture.site, 'page.html'), expected);
+ writeFinding(expected);
+ let result = fixture.run('--customization-report', csv, '--automate-fetchxml', '--automate-liquid');
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stdout, /1 informational, 0 actionable, 0 need context review/);
+ assert.deepEqual(JSON.parse(fs.readFileSync(assessmentPath, 'utf8')).summary,
+ { informational: 1, actionable: 0, needsReview: 0 });
+ assert.equal(fs.existsSync(fixture.manifestPath), false);
+ let html = fs.readFileSync(htmlPath, 'utf8');
+ assert.match(html, /1 informational \(no rewrite identified\), 0 actionable, 0 need context review/);
+ assert.match(html, /Informational - no rewrite identified/);
+ assert.doesNotMatch(html, /Each customization will need|without post-migration remediation|Migration should proceed/);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'page.html'), 'utf8'), expected);
+
+ writeFinding('{{ page.adx_copy }} adx_unknown');
+ result = fixture.run('--customization-report', csv, '--automate-fetchxml', '--automate-liquid');
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(JSON.parse(fs.readFileSync(assessmentPath, 'utf8')).summary,
+ { informational: 0, actionable: 0, needsReview: 1 });
+ html = fs.readFileSync(htmlPath, 'utf8');
+ assert.match(html, /Context review needed - not a confirmed defect/);
+ assert.match(html, /0 informational \(no rewrite identified\), 0 actionable, 1 need context review/);
+ assert.equal(fs.existsSync(fixture.manifestPath), false);
+});
+
+test('workflow gates only real proposals and distinguishes expected review from named-risk deferral on both tracks', () => {
+ const skill = fs.readFileSync(path.join(path.dirname(script), '..', 'SKILL.md'), 'utf8');
+ const authoring = skill.slice(skill.indexOf('### 2.4 Remediate Customizations'),
+ skill.indexOf('## Phase 2 — Downstream Track'));
+ const downstream = skill.slice(skill.indexOf('### 3.4 Remediate Customizations'),
+ skill.indexOf('### 3.5 Activate EDM'));
+ assert.match(authoring, /Configuration metadata has migrated\./);
+ assert.match(authoring, /Only show this checkpoint and approval question when `files\[\]` is nonempty/);
+ assert.match(authoring, /missing\/empty manifest means skip steps 6–7/);
+ assert.match(authoring, /Review expected references \(optional\)/);
+ assert.match(authoring, /Defer these named items and proceed \(acknowledge their risk\)/);
+ assert.match(authoring, /--add-decision/);
+ assert.match(authoring, /No unresolved actionable items and no unresolved context review/);
+ assert.match(downstream, /Raw references on Prod\/Test\/UAT do not by themselves establish an ALM gap/);
+ assert.match(downstream, /only a valid nonempty manifest with existing staged files triggers/);
+ assert.doesNotMatch(authoring, /Configuration is migrated|One or more findings.*proceed with auto-rewriters/);
+ assert.doesNotMatch(downstream, /finding them here indicates an ALM gap/);
+});
+
+test('retry requests request headers so Retry-After is available', () => {
+ const helper = path.join(__dirname, '../lib/validation-helpers.js');
+ const worker = `
+ const assert = require('node:assert/strict');
+ let attempts = 0;
+ require(${JSON.stringify(helper)}).makeRequest = async (options) => {
+ assert.equal(options.includeHeaders, true);
+ assert.deepEqual(options.headers, { Accept: 'application/json' });
+ return ++attempts === 1 ? { statusCode: 429, headers: { 'retry-after': '0' } } : { statusCode: 200 };
+ };
+ require(${JSON.stringify(script)}).makeRequestWithRetry({ headers: { Accept: 'application/json' } }, 1)
+ .then(result => { assert.equal(result.statusCode, 200); assert.equal(attempts, 2); });
+ `;
+ const result = spawnSync(process.execPath, ['-e', worker], { encoding: 'utf8', timeout: 5000 });
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test('location cleanup handles PAC temp paths and UNC extended paths', () => {
+ assert.equal(normalizeLocationPath('\\\\?\\C:\\Temp\\portal\\web-templates\\Header.html'),
+ 'web-templates\\Header.html');
+ assert.equal(normalizeLocationPath('\\\\?\\UNC\\server\\share\\Header.html'),
+ '\\\\server\\share\\Header.html');
+});
+
+test('all repeated placeholders are filled and replacement dollar sequences stay literal', () => {
+ assert.equal(fillPlaceholders('{{REPORT_DATE}} {{REPORT_DATE}} {{SITE_NAME}}', {
+ '{{REPORT_DATE}}': '2026-01-01', '{{SITE_NAME}}': '$& $$ $1',
+ }), '2026-01-01 2026-01-01 $& $$ $1');
+});
+
+test('CSV-derived report text is escaped and only HTTP(S) guidance becomes a link', () => {
+ const html = generateCustomizationSection('<img src=x onerror=alert(1)>', [
+ { location: '<script>location</script>', snippet: '<svg/onload=alert(2)>', guidance: 'javascript:alert(3)' },
+ { location: 'safe', snippet: 'x'.repeat(250), guidance: 'https://learn.microsoft.com/?a=1&b=2' },
+ { location: 'safe', guidance: 'not a URL <img src=x>' },
+ ]);
+ assert.doesNotMatch(html, /<img|<script>|<svg|href="javascript:/);
+ assert.match(html, /&lt;script&gt;location&lt;\/script&gt;/);
+ assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/);
+ assert.match(html, /href="https:\/\/learn\.microsoft\.com\/\?a=1&amp;b=2"/);
+ assert.match(html, /target="_blank" rel="noopener noreferrer"/);
+ assert.ok(html.includes('x'.repeat(200) + '...'));
+ assert.ok(!html.includes('x'.repeat(201)));
+});
+
+test('link-entity-only FetchXML is staged, including Cloud Flow consumers', (t) => {
+ const fixture = setup(t);
+ const original = '<fetch><entity name="contoso_record"><link-entity name="adx_cloudflowconsumer"><attribute name="adx_name" /></link-entity></entity></fetch>';
+ fs.writeFileSync(path.join(fixture.site, 'flow.html'), original);
+ const result = fixture.run('--automate-fetchxml');
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(fs.readFileSync(path.join(fixture.output, 'remediation-staged', 'flow.html'), 'utf8'),
+ /powerpagecomponenttype" operator="eq" value="33"/);
+ assert.equal(fs.readFileSync(path.join(fixture.site, 'flow.html'), 'utf8'), original);
+ assert.ok(result.stdout.includes(pathToFileURL(path.join(fixture.output, 'customization-report.html')).href));
+});
+
+test('review regression: skipped FetchXML containers never retain partial nested rewrites', () => {
+ const nested = '<link-entity name="adx_webtemplate"><attribute name="adx_name" /></link-entity>';
+ for (const original of [
+ `<fetch><entity name="adx_webpage"><filter type="or"><condition attribute="adx_name" operator="eq" value="Home" /></filter>${nested}</entity></fetch>`,
+ `<fetch><entity name="adx_unmapped">${nested}</entity></fetch>`,
+ '<fetch><entity name="adx_webpage"><link-entity name="adx_webtemplate"><filter type="or"><condition attribute="adx_name" operator="eq" value="Header" /></filter></link-entity></entity></fetch>',
+ ]) {
+ const result = rewriteFetchXmlInContent(original);
+ assert.equal(result.newContent, original);
+ assert.deepEqual(result.changes, []);
+ assert.equal(result.skipped.length, 1);
+ assert.match(result.skipped[0].reason, /manual review|No powerpagecomponenttype mapping/);
+ }
+});
+
+test('review regression: a skipped FetchXML query does not prevent independent supported queries', () => {
+ const skipped = '<fetch><entity name="adx_webpage"><filter type="or"></filter><link-entity name="adx_webtemplate"></link-entity></entity></fetch>';
+ const result = rewriteFetchXmlInContent(`${skipped}\n${fetchXml}`);
+ assert.ok(result.newContent.startsWith(skipped + '\n'));
+ assert.match(result.newContent.slice(skipped.length), /name="powerpagecomponent"/);
+ assert.deepEqual(result.changes, [{ tag: 'entity', entity: 'adx_webpage', typeValue: 2 }]);
+ assert.equal(result.skipped.length, 1);
+ const standalone = rewriteFetchXmlInContent('<link-entity name="adx_webtemplate"></link-entity>');
+ assert.equal(standalone.changes.length, 1);
+ assert.match(standalone.newContent, /name="powerpagecomponent"/);
+});
+
+test('review regression: skipped FetchXML removes obsolete proposals without changing live source', (t) => {
+ const fixture = setup(t);
+ const livePath = path.join(fixture.site, 'page.html');
+ fs.writeFileSync(livePath, fetchXml);
+ assert.equal(fixture.run('--automate-fetchxml').status, 0);
+ assert.ok(fs.existsSync(fixture.manifestPath));
+ const original = '<fetch><entity name="adx_webpage"><filter type="or"></filter><link-entity name="adx_webtemplate"></link-entity></entity></fetch>';
+ fs.writeFileSync(livePath, original);
+ const result = fixture.run('--automate-fetchxml');
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(fs.readFileSync(livePath, 'utf8'), original);
+ assert.equal(fs.existsSync(fixture.manifestPath), false);
+ assert.equal(fs.existsSync(path.join(fixture.output, 'remediation-staged', 'page.html')), false);
+});
+
+test('review regression: plugin actions and generated prompts restrict rewrites to mapped metadata', (t) => {
+ const fixture = setup(t);
+ const targets = ['adx_webpage', 'adx_invitation', 'adx_externalidentity', 'adx_portalcomment',
+ 'adx_unmapped', 'contoso_record', 'constructor', ''];
+ const findings = targets.map((entity) => ({
+ snippet: `Plugin name : Contoso.Plugin Step name : Update Entity Name : ${entity}`,
+ }));
+ const mapped = categorizePlugin(findings[0].snippet);
+ assert.equal(mapped.componentType, 2);
+ assert.match(mapped.action, /refactor the plugin code to target/);
+ for (const item of findings.slice(1)) {
+ const plugin = categorizePlugin(item.snippet);
+ assert.equal(plugin.componentType, null);
+ assert.match(plugin.action, /manual review/i);
+ assert.match(plugin.action, /unchanged/);
+ assert.doesNotMatch(plugin.action, /refactor the plugin code to target|re-register/);
+ assert.equal(classifyCustomizationFinding('Plugins registered on adx entities', item).status, 'needsReview');
+ }
+ const csv = path.join(fixture.site, 'SiteCustomization.csv');
+ fs.writeFileSync(csv, 'Type of customization,Snippet\n' + findings.map(({ snippet }) =>
+ ['Plugins registered on adx entities', snippet]
+ .map((field) => `"${field.replace(/"/g, '""')}"`).join(',')).join('\n') + '\n');
+ const result = fixture.run('--customization-report', csv);
+ assert.equal(result.status, 0, result.stderr);
+ const prompt = fs.readFileSync(path.join(fixture.output, 'plugin-remediation-prompt.txt'), 'utf8');
+ assert.match(prompt, /Supported metadata targets only/);
+ assert.match(prompt, /\| `adx_webpage` \| 2 \|/);
+ assert.match(prompt, /adx_invitation.*manual review/i);
+ assert.match(prompt, /adx_portalcomment.*manual review/i);
+ assert.doesNotMatch(prompt, /Custom plugins \(everything else\) need code-level\s+refactoring/);
+ assert.doesNotMatch(prompt, /\{\{PLUGIN_METADATA_MAPPING_BLOCK\}\}/);
+});
+
+test('printable rewrite sentinels do not collide with literal source or leak into output', () => {
+ const original = '<fetch><entity name="adx_webpage">__MIGRATION_LINK_ENTITY_0__<link-entity name="adx_webtemplate"><attribute name="adx_name" /></link-entity></entity></fetch>';
+ const result = rewriteFetchXmlInContent(original);
+ assert.equal(result.changes.length, 2);
+ assert.ok(result.newContent.includes('__MIGRATION_LINK_ENTITY_0__'));
+ assert.match(result.newContent, /<link-entity name="powerpagecomponent">/);
+ assert.equal(result.newContent.includes('\0'), false);
+ assert.equal(fs.readFileSync(script).includes(0), false);
+});
+
+test('Liquid singular weblink receives guidance and summaries include the source entity', (t) => {
+ const annotated = annotateLiquidEntitiesInContent("{{ entities['adx_weblink'] }}");
+ assert.match(annotated.suggestions[0].suggestion, /weblinks/);
+ const fixture = setup(t);
+ fs.writeFileSync(path.join(fixture.site, 'link.html'), "{{ entities['adx_weblink'] }}");
+ assert.equal(fixture.run('--automate-liquid').status, 0);
+ assert.match(fixture.manifest().files[0].changeSummary[0], /^adx_weblink /);
+});
+
+test('DME transformation is limited to mapped metadata, and plugin guidance preserves logical attributes', () => {
+ const items = ['adx_webpage', 'annotation', 'adx_invitation'].map((table) => ({
+ snippet: `Table name : ${table} Column name : contoso_value`,
+ }));
+ const checklists = buildDataModelExtensionChecklists(items);
+ assert.deepEqual(checklists.map((item) => item.sourceTable), ['adx_webpage']);
+ const plugin = categorizePlugin('Plugin name : Contoso.Plugin Step name : Update Entity Name : adx_webpage');
+ assert.match(plugin.action, /preserve existing `adx_\*` logical attribute names/);
+ const prompt = fs.readFileSync(path.join(path.dirname(script), 'prompts', 'dme-remediation.template.txt'), 'utf8');
+ assert.match(prompt, /PageInfo = new PagingInfo \{ Count = 5000, PageNumber = 1 \}/);
+ assert.match(prompt, /sourceQuery\.AddOrder/);
+ assert.match(prompt, /if \(!sourceRows\.MoreRecords\) break/);
+ assert.match(prompt, /sourceQuery\.PageInfo\.PagingCookie = sourceRows\.PagingCookie/);
+ assert.match(prompt, /response\.IsFaulted/);
+ assert.match(prompt, /confirm the approved metadata\s+migration has completed/);
+ assert.match(prompt, /read-only preflight across ALL source rows/);
+ assert.match(prompt, /verifiedComponentIds\.TryGetValue\(src\.Id, out var componentId\)/);
+ assert.match(prompt, /"powerpagecomponent", componentId/);
+ assert.doesNotMatch(prompt, /Then run the actual SDM.to.EDM migration/);
+ assert.doesNotMatch(prompt, /"powerpagecomponent", src\.Id/);
+});
diff --git a/plugins/power-pages/scripts/tests/migration-runtime.test.js b/plugins/power-pages/scripts/tests/migration-runtime.test.js
new file mode 100644
index 000000000..aa2e750a1
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/migration-runtime.test.js
@@ -0,0 +1,625 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const {
+ discoverSite, captureSolutions, parseTracker, pollMigration, parseArgs,
+ generateCustomizationReport, startReferences,
+} = require('../../skills/migrate-datamodel/scripts/migration-runtime');
+const { buildInitialState } = require('../../skills/migrate-datamodel/scripts/lib/migration-state-schema');
+
+const script = path.join(__dirname, '../../skills/migrate-datamodel/scripts/migration-runtime.js');
+const websiteId = '00000000-0000-0000-0000-000000000001';
+
+function fixture(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-runtime-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ return root;
+}
+
+function makeSite(root, child = '') {
+ const directory = path.join(root, child);
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(path.join(directory, 'website.yml'), `adx_websiteid: ${websiteId}\n`);
+ return directory;
+}
+
+function response(status, step = 'ConfigurationDataReferencesStarted') {
+ return { status: 0, stdout: `Current migration status is : ${status}\nCurrent Step: ${step}\n` };
+}
+
+function polling(t, responses, mode = 'configurationDataReferences') {
+ const outputDir = fixture(t);
+ const calls = [];
+ const records = [];
+ const sleeps = [];
+ let index = 0;
+ const deps = {
+ runPac(args, options) {
+ calls.push({ args, options });
+ return responses[Math.min(index++, responses.length - 1)];
+ },
+ emit(record) { records.push(record); },
+ sleep: async (ms) => { sleeps.push(ms); },
+ };
+ return { outputDir, calls, records, sleeps, deps, args: { websiteId, mode, outputDir } };
+}
+
+test('site discovery supports direct and nested configuration trees', (t) => {
+ const root = fixture(t);
+ const project = path.join(root, 'site $name & (literal)');
+ const site = makeSite(project, '.powerpages-site');
+ const result = discoverSite(project, true);
+ assert.equal(result.siteRoot, site);
+ assert.equal(result.parentOutputDir, path.join(root, 'migration-reports'));
+ assert.equal(discoverSite(root, true).siteRoot, site);
+});
+
+test('site discovery does not pick the first of multiple sites', (t) => {
+ const root = fixture(t);
+ assert.equal(discoverSite(root).siteRoot, null);
+ makeSite(root, 'first');
+ assert.equal(discoverSite(root, true).siteRoot, path.join(root, 'first'));
+ makeSite(root, 'second');
+ assert.equal(discoverSite(root).siteRoot, null);
+ assert.throws(() => discoverSite(root, true), /found 2/);
+});
+
+test('discovery CLI accepts paths with spaces and reports missing paths explicitly', (t) => {
+ const root = fixture(t);
+ const site = makeSite(root, 'site with spaces');
+ const result = spawnSync(process.execPath, [script, 'discover', '--path', site, '--require-site'], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(result.stdout).siteRoot, site);
+ const missing = spawnSync(process.execPath, [script, 'discover', '--path', path.join(root, 'missing')], { encoding: 'utf8' });
+ assert.equal(missing.status, 1);
+ assert.match(missing.stderr, /ENOENT/);
+});
+
+test('solution capture writes the complete UTF-8 output without a BOM', (t) => {
+ const root = fixture(t);
+ const output = path.join(root, 'reports with spaces', 'solutions.txt');
+ const text = 'PowerPages_FAQ Fran\u00e7ais\n' + 'x'.repeat(40000);
+ captureSolutions(output, {
+ runPac(args, options) {
+ assert.deepEqual(args, ['solution', 'list', '--includeSystemSolutions']);
+ assert.equal(options.captureAll, true);
+ return { status: 0, stdout: text };
+ },
+ });
+ assert.deepEqual(fs.readFileSync(output), Buffer.from(text, 'utf8'));
+});
+
+test('failed or empty solution capture cannot masquerade as an empty template list', (t) => {
+ const root = fixture(t);
+ const output = path.join(root, 'solutions.txt');
+ for (const result of [
+ { status: 1, stderr: 'not authenticated' },
+ { status: 0, stdout: '' },
+ { status: 1, error: Object.assign(new Error('pac not found'), { code: 'ENOENT' }) },
+ ]) {
+ assert.throws(() => captureSolutions(output, { runPac: () => result }), /failed|empty solution list/);
+ assert.equal(fs.existsSync(output), false);
+ }
+});
+
+test('tracker parsing uses labels rather than incidental Completed history', () => {
+ const output = '\u001b[32mCurrent migration status is : Running\u001b[0m\r\n' +
+ ' Current Step: ConfigurationDataCompleted\r\nStep History: Completed\r\n';
+ assert.deepEqual(parseTracker(output), { status: 'Running', currentStep: 'ConfigurationDataCompleted' });
+ assert.throws(() => parseTracker('Step History: Completed'), /no recognized/);
+});
+
+test('metadata-only polling stops at the expected Running handoff', async (t) => {
+ const f = polling(t, [response('Running', 'ConfigurationDataCompleted')], 'configurationData');
+ const result = await pollMigration(f.args, f.deps);
+ assert.equal(result.outcome, 'ConfigurationDataCompleted');
+ assert.equal(f.calls.length, 1);
+ assert.equal(f.sleeps.length, 0);
+ assert.deepEqual(result.operation.poll, { attempt: 1, max: 30 });
+});
+
+test('milestone matching retains the original case-insensitive behavior', async (t) => {
+ const f = polling(t, [response('running', 'configurationdatacompleted')], 'configurationData');
+ assert.equal((await pollMigration(f.args, f.deps)).outcome, 'ConfigurationDataCompleted');
+});
+
+for (const step of [null, 'StatusUpdated', 'configurationdatacompleted']) {
+ test(`metadata polling accepts top-level Completed with step ${step}`, async (t) => {
+ const terminal = step === null
+ ? { status: 0, stdout: 'Current migration status is : Completed\n' }
+ : response('Completed', step);
+ const f = polling(t, [terminal], 'configurationData');
+ const result = await pollMigration(f.args, f.deps);
+ assert.equal(result.outcome, 'ConfigurationDataCompleted');
+ assert.equal(result.status, 'Completed');
+ assert.equal(result.currentStep, step);
+ assert.equal(f.calls.length, 1);
+ assert.equal(f.sleeps.length, 0);
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.outputDir, 'migration-status.json'), 'utf8')).rawOutput, terminal.stdout);
+ });
+}
+
+test('all mode waits past the metadata handoff for top-level Completed', async (t) => {
+ const f = polling(t, [response('Running', 'ConfigurationDataCompleted'), response('Completed')], 'all');
+ const result = await pollMigration(f.args, f.deps);
+ assert.equal(result.outcome, 'Completed');
+ assert.deepEqual(f.sleeps, [60000]);
+ assert.equal(f.calls.length, 2);
+});
+
+test('refs polling preserves complete responses and final snapshots for report interpretation', async (t) => {
+ const terminal = response('Completed');
+ terminal.stdout += 'Chunk Details\n' + 'x'.repeat(40000) + '\nlast chunk\n';
+ const f = polling(t, [response('Running'), terminal]);
+ const result = await pollMigration(f.args, f.deps);
+ assert.equal(result.outcome, 'Completed');
+ assert.deepEqual(f.sleeps, [60000]);
+ assert.equal(f.records.length, 2);
+ assert.equal(f.records.at(-1).rawOutput, terminal.stdout);
+ assert.equal(fs.readFileSync(path.join(f.outputDir, 'migration-status.txt'), 'utf8'), terminal.stdout);
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.outputDir, 'migration-status.json'), 'utf8')).outcome, 'Completed');
+ for (const call of f.calls) {
+ assert.deepEqual(call.args, ['pages', 'migrate-datamodel', '--webSiteId', websiteId, '--checkMigrationStatus', '--verbose']);
+ assert.equal(call.options.captureAll, true);
+ assert.equal(call.options.timeoutMs, 60000);
+ }
+});
+
+test('polling stops after exactly 30 attempts with no final unnecessary sleep', async (t) => {
+ const f = polling(t, [response('Running')]);
+ const result = await pollMigration(f.args, f.deps);
+ assert.equal(result.outcome, 'TimedOut');
+ assert.equal(f.calls.length, 30);
+ assert.equal(f.sleeps.length, 29);
+ assert.ok(f.sleeps.every((ms) => ms === 60000));
+});
+
+for (const mode of ['configurationData', 'all', 'configurationDataReferences']) {
+ test(`${mode} polling stops immediately on Unknown and preserves the raw tracker`, async (t) => {
+ const unknown = response('Unknown', 'ConfigurationDataCompleted');
+ const f = polling(t, [unknown], mode);
+ const result = await pollMigration(f.args, f.deps);
+ assert.equal(result.outcome, 'CheckFailed');
+ assert.equal(result.status, 'Unknown');
+ assert.match(result.error, /Unknown/);
+ assert.equal(f.calls.length, 1);
+ assert.equal(f.sleeps.length, 0);
+ assert.equal(f.records.length, 1);
+ assert.equal(result.rawOutput, unknown.stdout);
+ assert.equal(fs.readFileSync(path.join(f.outputDir, 'migration-status.txt'), 'utf8'), unknown.stdout);
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.outputDir, 'migration-status.json'), 'utf8')).outcome, 'CheckFailed');
+ });
+}
+
+for (const status of ['Failed', 'Reverted']) {
+ test(`${status} takes precedence over a metadata-completed step`, async (t) => {
+ const f = polling(t, [response(status, 'ConfigurationDataCompleted')], 'configurationData');
+ assert.equal((await pollMigration(f.args, f.deps)).outcome, status);
+ assert.equal(f.sleeps.length, 0);
+ });
+}
+
+test('missing executable, timeout, nonzero exit and malformed responses stop rather than spin', async (t) => {
+ for (const response of [
+ { status: 1, error: Object.assign(new Error('pac not found'), { code: 'ENOENT' }) },
+ { status: 1, error: Object.assign(new Error('PAC timed out'), { code: 'ETIMEDOUT' }) },
+ { status: 1, stderr: 'authentication failed' },
+ { status: 0, stdout: 'Completed in step history only' },
+ { status: 1, stdout: 'Current migration status is : Completed\n' },
+ ]) {
+ const f = polling(t, [response]);
+ const result = await pollMigration(f.args, f.deps);
+ assert.equal(result.outcome, 'CheckFailed');
+ assert.ok(result.error);
+ assert.equal(f.calls.length, 1);
+ assert.equal(f.sleeps.length, 0);
+ }
+});
+
+test('only an explicit unsupported verbose flag permits non-verbose fallback', async (t) => {
+ const f = polling(t, [
+ { status: 1, stderr: 'An unknown argument --verbose was passed.' },
+ response('Running'),
+ response('Completed'),
+ ]);
+ const result = await pollMigration(f.args, f.deps);
+ assert.equal(result.outcome, 'Completed');
+ assert.equal(result.verboseSupported, false);
+ assert.ok(f.calls[0].args.includes('--verbose'));
+ assert.ok(f.calls.slice(1).every((call) => !call.args.includes('--verbose')));
+});
+
+test('incidental unknown-verbose text in successful output cannot trigger fallback', async (t) => {
+ const terminal = response('Completed');
+ terminal.stdout += 'History: An unknown argument --verbose was passed.\n';
+ const f = polling(t, [terminal]);
+ assert.equal((await pollMigration(f.args, f.deps)).verboseSupported, true);
+ assert.equal(f.calls.length, 1);
+});
+
+test('metadata-only fallback cannot infer a milestone from Running alone', async (t) => {
+ const f = polling(t, [
+ { status: 1, stderr: 'An unknown argument --verbose was passed.' },
+ { status: 0, stdout: 'Current migration status is : Running\n' },
+ ], 'configurationData');
+ const result = await pollMigration(f.args, f.deps);
+ assert.equal(result.outcome, 'CheckFailed');
+ assert.match(result.error, /requires Current Step/);
+});
+
+const csvHeader = 'Type of customization,Guidance,Snippet,Location\n';
+
+function handoff(t, run) {
+ const root = fixture(t);
+ const outputDir = path.join(root, 'reports with spaces');
+ const cwd = path.join(root, 'working directory');
+ fs.mkdirSync(outputDir);
+ fs.mkdirSync(cwd);
+ const calls = [];
+ return {
+ root, outputDir, cwd, calls, args: { websiteId, outputDir },
+ deps: {
+ cwd,
+ runPac(args, options) {
+ calls.push({ args, options });
+ return run(args, options);
+ },
+ },
+ };
+}
+
+test('incident: report exits 0 without CSV, tracker regresses, and refs start is refused', async (t) => {
+ let step = 'ConfigurationDataCompleted';
+ const f = handoff(t, (args) => {
+ if (args.includes('--checkMigrationStatus')) return response('Running', step);
+ if (args.includes('--siteCustomizationReportPath')) {
+ // Assert that the known milestone was persisted before the report command.
+ const saved = JSON.parse(fs.readFileSync(path.join(f.outputDir, 'customization-report-attempt.json')));
+ assert.equal(saved.before.currentStep, 'ConfigurationDataCompleted');
+ step = 'PrecheckCompleted';
+ return { status: 0, stdout: 'Prechecks completed successfully.\n' };
+ }
+ return { status: 1, stderr: 'The website is already under migration.' };
+ });
+ const metadata = await pollMigration({ ...f.args, mode: 'configurationData' }, { ...f.deps, emit() {} });
+ assert.equal(metadata.outcome, 'ConfigurationDataCompleted');
+ const milestone = fs.readFileSync(path.join(f.outputDir, 'migration-status.json'), 'utf8');
+ const report = generateCustomizationReport(f.args, f.deps);
+ assert.equal(report.outcome, 'TrackerChanged');
+ assert.equal(report.command.status, 0);
+ assert.equal(report.before.currentStep, 'ConfigurationDataCompleted');
+ assert.equal(report.after.currentStep, 'PrecheckCompleted');
+ assert.deepEqual(report.csvPaths, []);
+ assert.equal(report.trackerChanged, true);
+ assert.equal(fs.readFileSync(path.join(f.outputDir, 'migration-status.json'), 'utf8'), milestone);
+ const refs = startReferences(f.args, f.deps);
+ assert.equal(refs.outcome, 'StartRefused');
+ assert.equal(refs.tracker.currentStep, 'PrecheckCompleted');
+ assert.match(refs.error, /already under migration/);
+ assert.ok(f.calls.every(({ args }) => !args.includes('--resetMigration')));
+ assert.equal(f.calls.filter(({ args }) => args.includes('--mode')).length, 1);
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.outputDir, 'references-start.json'))).outcome, 'StartRefused');
+});
+
+for (const location of ['output', 'parent', 'cwd']) {
+ test(`report fallback validates a fresh CSV in ${location} without requiring any shell`, (t) => {
+ const f = handoff(t, (args, options) => {
+ assert.equal(options.captureAll, true);
+ if (args.includes('--checkMigrationStatus')) return response('Running', 'ConfigurationDataCompleted');
+ assert.deepEqual(args, [
+ 'pages', 'migrate-datamodel', '--webSiteId', websiteId, '--siteCustomizationReportPath', f.outputDir,
+ ]);
+ assert.equal(options.cwd, f.cwd);
+ const directory = { output: f.outputDir, parent: f.root, cwd: f.cwd }[location];
+ // A header-only CSV is a valid zero-findings report, unlike an absent CSV.
+ fs.writeFileSync(path.join(directory, 'SiteCustomization1.csv'), '\uFEFF' + csvHeader);
+ return { status: 0, stdout: 'Report generated.' };
+ });
+ const result = generateCustomizationReport(f.args, f.deps);
+ assert.equal(result.outcome, 'ReportGenerated');
+ assert.equal(result.csvPaths.length, 1);
+ assert.equal(result.trackerChanged, false);
+ assert.equal(f.calls.length, 3);
+ });
+}
+
+test('report fallback cannot reuse a stale CSV or claim success from precheck output', (t) => {
+ const f = handoff(t, (args) => args.includes('--checkMigrationStatus')
+ ? response('Running', 'ConfigurationDataCompleted')
+ : { status: 0, stdout: 'Prechecks completed successfully.' });
+ fs.writeFileSync(path.join(f.cwd, 'SiteCustomization999.csv'), csvHeader);
+ const result = generateCustomizationReport(f.args, f.deps);
+ assert.equal(result.outcome, 'ReportMissingOrInvalid');
+ assert.match(result.error, /exit code 0 is not/);
+ assert.deepEqual(result.csvPaths, []);
+ assert.equal(f.calls.length, 3);
+});
+
+test('report fallback accepts a rewritten CSV but rejects empty or malformed artifacts', (t) => {
+ for (const [content, outcome] of [
+ [csvHeader + 'Liquid,Review,adx_name,web-templates/test.html\n', 'ReportGenerated'],
+ ['', 'ReportMissingOrInvalid'],
+ ['not,a,customization,report\n', 'ReportMissingOrInvalid'],
+ [csvHeader + 'Liquid,missing columns\n', 'ReportMissingOrInvalid'],
+ [csvHeader + 'Liquid,Review,adx_name,"unterminated', 'ReportMissingOrInvalid'],
+ ]) {
+ const f = handoff(t, (args) => {
+ if (args.includes('--checkMigrationStatus')) return response('Completed', 'StatusUpdated');
+ fs.writeFileSync(path.join(f.outputDir, 'SiteCustomization.csv'), content);
+ return { status: 0, stdout: 'Done' };
+ });
+ fs.writeFileSync(path.join(f.outputDir, 'SiteCustomization.csv'), csvHeader + 'old,old,old,old\n');
+ const result = generateCustomizationReport(f.args, f.deps);
+ assert.equal(result.outcome, outcome);
+ assert.equal(result.invalidCsvPaths.length, outcome === 'ReportGenerated' ? 0 : 1);
+ }
+});
+
+test('multiple fresh report candidates require selection instead of choosing the highest number', (t) => {
+ const f = handoff(t, (args) => {
+ if (args.includes('--checkMigrationStatus')) return response('Completed', 'StatusUpdated');
+ for (const name of ['SiteCustomization.csv', 'SiteCustomization99.csv']) {
+ fs.writeFileSync(path.join(f.outputDir, name), csvHeader);
+ }
+ return { status: 0, stdout: 'Done' };
+ });
+ assert.equal(generateCustomizationReport(f.args, f.deps).outcome, 'ReportSelectionRequired');
+});
+
+test('report fallback stops before mutation for active, failed or unverifiable trackers', (t) => {
+ for (const tracker of [
+ response('Running', 'ConfigurationDataReferencesStarted'),
+ response('Failed', 'ConfigurationDataCompleted'),
+ { status: 0, stdout: 'Current migration status is : Running\n' },
+ { status: 1, stderr: 'authentication failed' },
+ ]) {
+ const f = handoff(t, () => tracker);
+ assert.equal(generateCustomizationReport(f.args, f.deps).outcome, 'CheckFailed');
+ assert.equal(f.calls.length, 1);
+ assert.ok(f.calls[0].args.includes('--checkMigrationStatus'));
+ }
+});
+
+test('report command and post-report status failures remain explicit with both snapshots', (t) => {
+ for (const failure of ['command', 'status']) {
+ let checks = 0;
+ const f = handoff(t, (args) => {
+ if (args.includes('--checkMigrationStatus')) {
+ if (++checks === 2 && failure === 'status') return { status: 1, stderr: 'network unavailable' };
+ return response('Running', 'ConfigurationDataCompleted');
+ }
+ return failure === 'command' ? { status: 1, stderr: 'report generation failed' } : { status: 0, stdout: '' };
+ });
+ const result = generateCustomizationReport(f.args, f.deps);
+ assert.equal(result.outcome, failure === 'command' ? 'CommandFailed' : 'CheckFailed');
+ assert.ok(result.before.rawOutput);
+ assert.ok(result.after.rawOutput);
+ assert.ok(result.error);
+ assert.equal(f.calls.length, 3);
+ }
+});
+
+test('older PAC report fallback still works without verbose when status includes the current step', (t) => {
+ const f = handoff(t, (args) => {
+ if (args.includes('--verbose')) return { status: 1, stderr: 'An unknown argument --verbose was passed.' };
+ if (args.includes('--checkMigrationStatus')) return response('Running', 'ConfigurationDataCompleted');
+ fs.writeFileSync(path.join(f.outputDir, 'SiteCustomization.csv'), csvHeader);
+ return { status: 0, stdout: 'Done' };
+ });
+ const result = generateCustomizationReport(f.args, f.deps);
+ assert.equal(result.outcome, 'ReportGenerated');
+ assert.equal(result.after.verboseSupported, false);
+ assert.equal(f.calls.filter(({ args }) => args.includes('--verbose')).length, 1);
+});
+
+test('refused, failed and unverifiable reference starts do not retry or report migration success', (t) => {
+ for (const [command, tracker, outcome] of [
+ [{ status: 0, stdout: 'This website is already under migration.' }, response('Running', 'PrecheckCompleted'), 'StartRefused'],
+ [{ status: 1, stderr: 'This website is already under migration.' }, response('Running', 'ConfigurationDataReferencesStarted'), 'StartRefused'],
+ [{ status: 1, stderr: 'authentication failed' }, response('Running'), 'StartFailed'],
+ [{ status: 0, stdout: 'Submitted' }, { status: 1, stderr: 'status check failed' }, 'CheckFailed'],
+ [{ status: 0, stdout: 'Submitted' }, response('Unknown'), 'CheckFailed'],
+ ]) {
+ const f = handoff(t, (args) => args.includes('--checkMigrationStatus') ? tracker : command);
+ const result = startReferences(f.args, f.deps);
+ assert.equal(result.outcome, outcome);
+ assert.ok(result.error);
+ assert.equal(f.calls.length, 2);
+ assert.deepEqual(f.calls[0].args, [
+ 'pages', 'migrate-datamodel', '--webSiteId', websiteId, '--mode', 'configurationDataReferences',
+ ]);
+ assert.ok(f.calls[1].args.includes('--checkMigrationStatus'));
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(f.outputDir, 'references-start.json'), 'utf8')).tracker.rawOutput,
+ tracker.stdout || tracker.stderr);
+ }
+});
+
+test('accepted references start is not completion; polling still waits for top-level Completed', async (t) => {
+ const f = handoff(t, (args) => args.includes('--checkMigrationStatus')
+ ? response('Running', 'PrecheckCompleted') : { status: 0, stdout: 'Submitted' });
+ assert.equal(startReferences(f.args, f.deps).outcome, 'StartAccepted');
+ const poll = polling(t, [
+ response('Running', 'PrecheckCompleted'),
+ response('Running', 'ConfigurationDataReferencesCompleted'),
+ response('Completed', 'StatusUpdated'),
+ ]);
+ assert.equal((await pollMigration(poll.args, poll.deps)).outcome, 'Completed');
+ assert.equal(poll.calls.length, 3);
+ assert.equal(poll.sleeps.length, 2);
+});
+
+test('30 unchanged precheck observations never trigger a reset or another references start', async (t) => {
+ const f = polling(t, [response('Running', 'PrecheckCompleted')]);
+ assert.equal((await pollMigration(f.args, f.deps)).outcome, 'TimedOut');
+ assert.equal(f.calls.length, 30);
+ assert.ok(f.calls.every(({ args }) => args.includes('--checkMigrationStatus') &&
+ !args.includes('--resetMigration') && !args.includes('--mode')));
+});
+
+test('post-references report tracker change preserves Completed evidence and live state', async (t) => {
+ let step = 'StatusUpdated';
+ let status = 'Completed';
+ const f = handoff(t, (args) => {
+ if (args.includes('--checkMigrationStatus')) return response(status, step);
+ fs.writeFileSync(path.join(f.outputDir, 'SiteCustomization.csv'), csvHeader);
+ step = 'PrecheckCompleted';
+ status = 'Running';
+ return { status: 0, stdout: 'Prechecks completed.' };
+ });
+ const statePath = path.join(f.outputDir, 'migration-state.json');
+ fs.writeFileSync(statePath, 'state is owned by update-state.js');
+ assert.equal((await pollMigration({ ...f.args, mode: 'configurationDataReferences' }, { ...f.deps, emit() {} })).outcome, 'Completed');
+ const milestone = fs.readFileSync(path.join(f.outputDir, 'migration-status.json'), 'utf8');
+ const result = generateCustomizationReport(f.args, f.deps);
+ assert.equal(result.outcome, 'TrackerChanged');
+ assert.equal(result.csvPaths.length, 1);
+ assert.equal(result.before.status, 'Completed');
+ assert.equal(result.after.status, 'Running');
+ assert.equal(fs.readFileSync(path.join(f.outputDir, 'migration-status.json'), 'utf8'), milestone);
+ assert.equal(fs.readFileSync(statePath, 'utf8'), 'state is owned by update-state.js');
+});
+
+test('progress can update the existing report through Node without concurrent state writers', async (t) => {
+ const f = polling(t, [response('Completed')]);
+ const statePath = path.join(f.outputDir, 'migration-state.json');
+ fs.writeFileSync(statePath, JSON.stringify(buildInitialState({ webSiteId: websiteId, outputDir: f.outputDir })));
+ const updateScript = path.join(__dirname, '../../skills/migrate-datamodel/scripts/update-state.js');
+ f.deps.emit = (record) => {
+ const result = spawnSync(process.execPath, [
+ updateScript, '--output-dir', f.outputDir, '--set-operation', JSON.stringify(record.operation),
+ ], { encoding: 'utf8', shell: false });
+ assert.equal(result.status, 0, result.stderr);
+ };
+ assert.equal((await pollMigration(f.args, f.deps)).outcome, 'Completed');
+ const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
+ assert.deepEqual(state.currentOperation.poll, { attempt: 1, max: 30 });
+ assert.ok(fs.existsSync(path.join(f.outputDir, 'datamodel-migration-report.html')));
+});
+
+test('the background poller never replaces migration state', async (t) => {
+ const f = polling(t, [response('Completed')]);
+ const statePath = path.join(f.outputDir, 'migration-state.json');
+ fs.writeFileSync(statePath, 'existing state belongs to the report updater');
+ assert.equal((await pollMigration(f.args, f.deps)).outcome, 'Completed');
+ assert.equal(fs.readFileSync(statePath, 'utf8'), 'existing state belongs to the report updater');
+});
+
+test('invalid helper arguments fail before PAC is invoked', async (t) => {
+ assert.throws(() => parseArgs(['poll', '--mode']), /requires a value/);
+ assert.throws(() => parseArgs(['solutions', '--unexpected']), /Unknown argument/);
+ assert.throws(() => parseArgs(['unknown']), /Usage/);
+ assert.deepEqual(parseArgs(['delay', '--seconds', '60']), { action: 'delay', seconds: '60' });
+ const f = polling(t, [response('Completed')]);
+ await assert.rejects(pollMigration({ ...f.args, mode: 'invalid' }, f.deps), /--mode/);
+ await assert.rejects(pollMigration({ ...f.args, websiteId: null }, f.deps), /--website-id/);
+ assert.equal(f.calls.length, 0);
+});
+
+test('polling CLI returns distinct success, migration-failure and elapsed-window exit codes', (t) => {
+ const root = fixture(t);
+ const preload = path.join(root, 'fake-pac.cjs');
+ // Only this child process is mocked. No real PAC executable or environment
+ // is used, and immediate timers exercise the real 30-attempt CLI boundary.
+ fs.writeFileSync(preload, `
+ const fs = require('node:fs');
+ const assert = require('node:assert/strict');
+ require('node:child_process').execFileSync = (command, args, options) => {
+ assert.equal(command, process.platform === 'win32' ? 'pac.exe' : 'pac');
+ assert.equal(options.shell, false);
+ fs.writeSync(options.stdio[1], 'Current migration status is : ' + process.env.TEST_TRACKER_STATUS + '\\n');
+ };
+ global.setTimeout = (callback) => { callback(); };
+ `);
+ for (const [status, exitCode, outcome, attempts] of [
+ ['Completed', 0, 'Completed', 1], ['Failed', 1, 'Failed', 1], ['Running', 2, 'TimedOut', 30],
+ ['Unknown', 1, 'CheckFailed', 1],
+ ]) {
+ const output = path.join(root, status);
+ const result = spawnSync(process.execPath, [
+ '--require', preload, script, 'poll', '--website-id', websiteId,
+ '--mode', 'configurationDataReferences', '--output-dir', output,
+ ], { encoding: 'utf8', env: { ...process.env, TEST_TRACKER_STATUS: status } });
+ assert.equal(result.status, exitCode, result.stderr);
+ const records = result.stdout.trim().split(/\r?\n/).map((line) => JSON.parse(line));
+ assert.equal(records.length, attempts);
+ assert.equal(records.at(-1).outcome, outcome);
+ }
+});
+
+test('report and references-start CLI return nonzero for missing artifacts, tracker changes and refusals', (t) => {
+ const root = fixture(t);
+ const preload = path.join(root, 'fake-handoff-pac.cjs');
+ fs.writeFileSync(preload, `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const assert = require('node:assert/strict');
+ let reported = false;
+ require('node:child_process').execFileSync = (command, args, options) => {
+ assert.equal(command, process.platform === 'win32' ? 'pac.exe' : 'pac');
+ assert.equal(options.shell, false);
+ let output;
+ if (args.includes('--checkMigrationStatus')) {
+ const step = reported && process.env.TEST_CASE === 'changed' ? 'PrecheckCompleted' : 'ConfigurationDataCompleted';
+ const status = process.env.TEST_CASE === 'unknown' ? 'Unknown' : 'Running';
+ output = 'Current migration status is : ' + status + '\\nCurrent Step: ' + step + '\\n';
+ } else if (args.includes('--siteCustomizationReportPath')) {
+ const directory = args[args.indexOf('--siteCustomizationReportPath') + 1];
+ if (process.env.TEST_CASE === 'generated') {
+ fs.writeFileSync(path.join(directory, 'SiteCustomization.csv'), 'Type of customization,Guidance,Snippet,Location\\n');
+ }
+ reported = true;
+ output = 'Prechecks completed.';
+ } else {
+ output = process.env.TEST_CASE === 'refused' ? 'The website is already under migration.' : 'Submitted.';
+ }
+ fs.writeSync(options.stdio[1], output);
+ };
+ `);
+ for (const [action, scenario, outcome, code] of [
+ ['report', 'generated', 'ReportGenerated', 0],
+ ['report', 'missing', 'ReportMissingOrInvalid', 1],
+ ['report', 'changed', 'TrackerChanged', 1],
+ ['start-references', 'refused', 'StartRefused', 1],
+ ['start-references', 'accepted', 'StartAccepted', 0],
+ ['start-references', 'unknown', 'CheckFailed', 1],
+ ]) {
+ const output = path.join(root, scenario);
+ fs.mkdirSync(output);
+ const result = spawnSync(process.execPath, [
+ '--require', preload, script, action, '--website-id', websiteId, '--output-dir', output,
+ ], { encoding: 'utf8', env: { ...process.env, TEST_CASE: scenario }, cwd: root });
+ assert.equal(result.status, code, result.stderr);
+ assert.equal(JSON.parse(result.stdout).outcome, outcome);
+ }
+});
+
+test('migration instructions use portable commands for both tracks', () => {
+ const skillRoot = path.join(__dirname, '../../skills/migrate-datamodel');
+ for (const filename of ['SKILL.md']) {
+ const content = fs.readFileSync(path.join(skillRoot, filename), 'utf8');
+ assert.doesNotMatch(content, /```(?:powershell|bash)\b/i, filename);
+ assert.doesNotMatch(content, /\b(?:Test-Path|Get-ChildItem|Out-File|Out-String|Start-Sleep|ConvertTo-Json|Write-Host|Where-Object)\b/, filename);
+ assert.doesNotMatch(content, / [`\\]\r?$/m, `${filename} must not require shell line-continuation syntax`);
+ }
+ const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');
+ assert.match(skill, /state\.site\.migrationMode === 'all'/);
+ assert.doesNotMatch(skill, /\bstate\.mode\b/);
+ assert.equal((skill.match(/migration-runtime\.js" poll /g) || []).length, 3);
+ assert.match(skill, /agent is the sole report-state writer/);
+ assert.match(skill, /PowerShell is not a prerequisite/);
+ assert.match(skill, /Always refresh the card once more from the final saved response/);
+ assert.equal((skill.match(/migration-runtime\.js" start-references /g) || []).length, 2);
+ assert.match(skill, /migration-runtime\.js" report /);
+ const recovery = skill.split('#### References start refusal recovery')[1].split('### 3.3 Activate EDM')[0];
+ assert.match(recovery, /both tracks/);
+ assert.match(recovery, /Earlier approval to migrate references is \*\*not\*\* reset approval/);
+ assert.match(recovery, /Only after reset approval/);
+ assert.match(recovery, /verify the tracker is no longer `Running`/);
+ assert.match(recovery, /Retry \*\*only\*\* `start-references` once/);
+ assert.match(recovery, /Do not rerun metadata/);
+ assert.match(recovery, /Require overall references `Completed` before activation/);
+ assert.doesNotMatch(skill, /set \*\*`adx_migrationstatus`\*\*|manual `adx_migrationstatus`/);
+});
diff --git a/plugins/power-pages/scripts/tests/migration-telemetry.test.js b/plugins/power-pages/scripts/tests/migration-telemetry.test.js
new file mode 100644
index 000000000..2f29983eb
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/migration-telemetry.test.js
@@ -0,0 +1,66 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const emitter = require('../../skills/migrate-datamodel/scripts/emit-telemetry');
+const telemetry = path.join(__dirname, '../lib/telemetry');
+
+test('completion metrics exclude migration details and do not claim pending work succeeded', () => {
+ const state = {
+ phases: [{ status: 'completed', title: 'Private phase title' }],
+ skillStartedAt: '2026-01-01T00:00:00Z', lastUpdatedAt: '2026-01-01T00:00:05Z',
+ site: { template: 'Private template' }, track: 'A',
+ };
+ assert.deepEqual(emitter.buildPhaseRollup(state), { outcome: 'success', durationMs: 5000 });
+ assert.equal(emitter.buildPhaseRollup({ ...state, phases: [{ status: 'in-progress' }] }), null);
+ assert.equal(emitter.buildPhaseRollup(null), null);
+ assert.equal(emitter.buildPhaseRollup({ phases: [null] }), null);
+ assert.deepEqual(emitter.buildPhaseRollup({ ...state, phases: [{ status: 'blocked' }] }),
+ { outcome: 'failure', durationMs: 5000 });
+});
+
+test('regional config reaches the shared dispatcher without migration-specific eventInfo', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-telemetry-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const ikeyPath = path.join(root, 'ikey.json');
+ const config = { disabled: false, event_stream_name: 'test-stream', default_region: 'us',
+ regions: { us: { instrumentation_key: 'test-only-key' } } };
+ fs.writeFileSync(ikeyPath, JSON.stringify(config));
+ // Use the plugin's real provisioning gate, but never invoke its network resolver.
+ fs.writeFileSync(path.join(root, 'resolver.js'),
+ `module.exports = require(${JSON.stringify(path.join(telemetry, 'resolver.js'))});`);
+ fs.writeFileSync(path.join(root, 'migration-state.json'), JSON.stringify({
+ phases: [{ status: 'completed', title: 'Private phase title' }],
+ site: { template: 'Private template' }, track: 'A',
+ }));
+ const oldArgs = process.argv;
+ const oldKey = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;
+ process.argv = [process.execPath, 'emit-telemetry.js', '--output-dir', root];
+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON = ikeyPath;
+ t.after(() => {
+ process.argv = oldArgs;
+ if (oldKey === undefined) delete process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;
+ else process.env.POWER_PLATFORM_SKILLS_IKEY_JSON = oldKey;
+ });
+ const calls = [];
+ t.mock.method(require(path.join(telemetry, 'lib', 'emit-spawn')), 'fireAndForget',
+ (event, options) => calls.push({ event, options }));
+ t.mock.method(require(path.join(telemetry, 'lib', 'pac-auth')), 'readPacAuth', () => ({ cloud: 'Public' }));
+ const agent = require(path.join(telemetry, 'lib', 'agent-info'));
+ t.mock.method(agent, 'readAiAgent', () => ({}));
+ t.mock.method(agent, 'readPacCliVersion', () => null);
+ t.mock.method(require(path.join(telemetry, 'lib', 'session')), 'getSessionId', () => 'test-session');
+ emitter.main();
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].options.ikeyJsonPath, ikeyPath);
+ assert.equal(calls[0].options.cloud, 'Public');
+ assert.deepEqual(calls[0].event.data.eventInfo, {});
+ assert.doesNotMatch(JSON.stringify(calls[0]), /Private phase title|Private template/);
+ fs.writeFileSync(ikeyPath, JSON.stringify({ ...config, disabled: true }));
+ emitter.main();
+ assert.equal(calls.length, 1);
+ fs.unlinkSync(ikeyPath);
+ emitter.main();
+ assert.equal(calls.length, 1);
+});
diff --git a/plugins/power-pages/scripts/tests/non-spa-customization-workflows.test.js b/plugins/power-pages/scripts/tests/non-spa-customization-workflows.test.js
index 8faec9e0c..a5907fec5 100644
--- a/plugins/power-pages/scripts/tests/non-spa-customization-workflows.test.js
+++ b/plugins/power-pages/scripts/tests/non-spa-customization-workflows.test.js
@@ -71,7 +71,7 @@ test('localized content authoring remains model-invocable without a direct user
assert.match(customization, /^user-invocable: true$/m);
assert.match(customization, /Invoke only `author-webpage-content` through the `Skill` tool/);
assert.match(integration, /Invoke `author-webpage-content` with the exact existing localized body target/);
- assert.match(readme, /39 user-invocable skills and one model-only worker/);
+ assert.match(readme, /40 user-invocable skills and one model-only worker/);
assert.doesNotMatch(readme, /^#### `\/author-webpage-content`/m);
});
diff --git a/plugins/power-pages/scripts/tests/pac-command.test.js b/plugins/power-pages/scripts/tests/pac-command.test.js
new file mode 100644
index 000000000..bfe6a6bd0
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/pac-command.test.js
@@ -0,0 +1,62 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { runPac, PAC_LOG_TAIL_BYTES } = require('../lib/pac-command');
+
+function options(t, output, extra = {}) {
+ const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'pac-capture-test-'));
+ t.after(() => fs.rmSync(tmpRoot, { recursive: true, force: true }));
+ return {
+ tmpRoot,
+ runCommand(command, args, opts) {
+ assert.equal(opts.shell, false);
+ fs.writeSync(opts.stdio[1], output);
+ },
+ ...extra,
+ };
+}
+
+test('default PAC capture retains the existing bounded-tail behavior', (t) => {
+ const output = 'first anchor\n' + 'x'.repeat(PAC_LOG_TAIL_BYTES) + '\nlast anchor';
+ const result = runPac(['solution', 'list'], options(t, output));
+ assert.equal(result.status, 0);
+ assert.equal(result.stdout, output.slice(-PAC_LOG_TAIL_BYTES));
+});
+
+test('opt-in full capture retains leading anchors and every verbose record', (t) => {
+ const output = 'first anchor\n' + 'x'.repeat(PAC_LOG_TAIL_BYTES) + '\nlast anchor';
+ const result = runPac(['solution', 'list'], options(t, output, { captureAll: true }));
+ assert.equal(result.status, 0);
+ assert.equal(result.stdout, output);
+});
+
+test('full capture retains failed command output without hiding the failure', (t) => {
+ const output = 'details\n' + 'x'.repeat(PAC_LOG_TAIL_BYTES);
+ const deps = options(t, output, { captureAll: true });
+ const writeOutput = deps.runCommand;
+ deps.runCommand = (...args) => {
+ writeOutput(...args);
+ throw Object.assign(new Error('PAC failed'), { status: 3 });
+ };
+ const result = runPac(['solution', 'list'], deps);
+ assert.equal(result.status, 3);
+ assert.equal(result.stderr, output);
+ assert.equal(result.stdout, '');
+});
+
+for (const platform of ['win32', 'darwin', 'linux']) {
+ test(`PAC uses direct argument arrays on ${platform}`, (t) => {
+ const args = ['pages', 'migrate-datamodel', '--webSiteId', 'site $name & (literal)'];
+ const deps = options(t, 'result', { captureAll: true, platform });
+ const writeOutput = deps.runCommand;
+ deps.runCommand = (command, actual, opts) => {
+ assert.equal(command, platform === 'win32' ? 'pac.exe' : 'pac');
+ assert.deepEqual(actual, args);
+ assert.equal(opts.shell, false);
+ writeOutput(command, actual, opts);
+ };
+ assert.equal(runPac(args, deps).status, 0);
+ });
+}
diff --git a/plugins/power-pages/scripts/tests/render-live-report.test.js b/plugins/power-pages/scripts/tests/render-live-report.test.js
new file mode 100644
index 000000000..a21b31720
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/render-live-report.test.js
@@ -0,0 +1,434 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { buildInitialState } = require('../../skills/migrate-datamodel/scripts/lib/migration-state-schema');
+const { renderLiveReport } = require('../../skills/migrate-datamodel/scripts/lib/render-live-report');
+
+test('live report refreshes at 40 seconds without changing PAC polling', async () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ const html = renderLiveReport(state);
+ assert.match(html, /Auto-refreshing every 40s/);
+ const script = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)]
+ .map((match) => match[1]).find((content) => content.includes('var POLL_MS'));
+ assert.ok(script, 'generated HTML must include its refresh script');
+
+ for (const protocol of ['file:', 'https:']) {
+ let tick;
+ let reloads = 0;
+ let fetches = 0;
+ let latest = state.lastUpdatedAt;
+ const stored = new Map();
+ const document = {
+ visibilityState: 'visible',
+ getElementById: () => null,
+ querySelector: () => null,
+ querySelectorAll: () => [],
+ };
+ vm.runInNewContext(script, {
+ document,
+ window: { scrollY: 123 },
+ location: { protocol, pathname: '/report.html', reload() { reloads++; } },
+ sessionStorage: {
+ getItem: (key) => stored.get(key) ?? null,
+ setItem: (key, value) => stored.set(key, value),
+ removeItem: (key) => stored.delete(key),
+ },
+ setInterval(callback, interval) {
+ assert.equal(interval, 40000);
+ tick = callback;
+ },
+ fetch: async () => {
+ fetches++;
+ return { ok: true, text: async () => `data-live-updated-at-token="${latest}"` };
+ },
+ });
+ assert.equal(typeof tick, 'function');
+ assert.equal(reloads, 0, 'must wait for the timer');
+ tick();
+ await new Promise(setImmediate);
+ assert.equal(reloads, protocol === 'file:' ? 1 : 0);
+ latest = 'changed-token';
+ tick();
+ await new Promise(setImmediate);
+ assert.equal(reloads, protocol === 'file:' ? 2 : 1);
+ assert.equal(stored.get('sdmEdmReport:scrollY'), '123');
+ document.visibilityState = 'hidden';
+ const before = { reloads, fetches };
+ tick();
+ await new Promise(setImmediate);
+ assert.deepEqual({ reloads, fetches }, before, 'hidden tabs must not refresh');
+ assert.equal(fetches, protocol === 'file:' ? 0 : 2);
+ }
+});
+
+function components(sdm, edm, sdmErrors = {}) {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ const snapshot = (inventory, parseErrors = {}) => ({
+ counts: Object.fromEntries(Object.entries(inventory).map(([category, records]) => [category, records.length])),
+ inventory, parseErrors,
+ });
+ const html = renderLiveReport(state, { sdmSnapshot: snapshot(sdm, sdmErrors), edmSnapshot: snapshot(edm) });
+ return html.slice(html.indexOf('id="tab-pages"'), html.indexOf('id="tab-migration"') > 0
+ ? html.indexOf('id="tab-migration"') : undefined);
+}
+
+test('equal inventory counts show count matches independently of identity or value differences', () => {
+ const replaced = components({ webTemplates: [{ name: 'Before' }] }, { webTemplates: [{ name: 'After' }] });
+ assert.match(replaced, /comp-pill match"/);
+ assert.match(replaced, /Counts match/);
+ assert.match(replaced, /Missing in EDM: 1 · Extra in EDM: 1/);
+ assert.doesNotMatch(replaced, /comp-pill (?:mismatch|warn)/);
+ const changed = components({ siteSettings: [{ name: 'Search', value: 'true' }] },
+ { siteSettings: [{ name: 'Search', value: 'false' }] });
+ assert.match(changed, /comp-pill match"/);
+ assert.match(changed, /Changed values: 1/);
+ assert.match(changed, /1 of 1 category counts match/);
+ assert.doesNotMatch(changed, /comp-pill (?:mismatch|warn)/);
+});
+
+test('count status rejects incomplete evidence but separates duplicate identities and content changes', () => {
+ const records = { webTemplates: [{ name: 'Header', contentHash: 'hash' }] };
+ assert.match(components(records, records, { webTemplates: [{ message: 'invalid YAML' }] }),
+ /Incomplete snapshot/);
+ const duplicate = { basicForms: [{ name: 'Same', slug: 'one' }, { name: 'Same', slug: 'two' }] };
+ const ambiguous = components(duplicate, duplicate);
+ assert.match(ambiguous, /comp-pill match"/);
+ assert.match(ambiguous, /Duplicate SDM identities: 1 · Duplicate EDM identities: 1/);
+ assert.match(ambiguous, /separate migration safety gate still uses the full comparison/);
+ const changed = components(records, { webTemplates: [{ name: 'Header', contentHash: null }] });
+ assert.match(changed, /comp-pill match"/);
+ assert.match(changed, /Changed content hashes: 1/);
+ assert.match(components(records, records), /1 of 1 category counts match/);
+});
+
+test('matching webpage-rule and snippet counts have no warning or error count indicators', () => {
+ const snippets = [
+ { name: 'Forum Post Create Heading', language: 'en-US', slug: 'first' },
+ { name: 'Forum Post Create Heading', language: 'en-US', slug: 'second' },
+ ];
+ const html = components({
+ contentSnippets: snippets,
+ webpageRules: [{ name: 'Grant Change to Content', webRoleIds: '[]' }],
+ }, {
+ contentSnippets: snippets,
+ webpageRules: [{ name: 'Grant Change to Content', webRoleIds: null }],
+ });
+ assert.equal((html.match(/class="comp-pill match"/g) || []).length, 2);
+ assert.match(html, /2 of 2 category counts match/);
+ assert.doesNotMatch(html, /comp-pill (?:warn|mismatch)|Changed records|Different records|⚠|✗/);
+ assert.match(html, /Record-level comparison \(separate from count status\)/);
+});
+
+test('overview equal totals claim count equality rather than verified migration', () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ const html = renderLiveReport(state, {
+ sdmSnapshot: { counts: { webTemplates: 1 }, inventory: { webTemplates: [{ name: 'Before' }] } },
+ edmSnapshot: { counts: { webTemplates: 1 }, inventory: { webTemplates: [{ name: 'After' }] } },
+ });
+ assert.match(html, /Counts match: 1 components on each side/);
+ assert.match(html, /Equal totals do not verify individual records/);
+ assert.doesNotMatch(html, /All 1 components migrated/);
+});
+
+test('prompt links allow local files but never executable URI schemes', () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ for (const promptPath of ['javascript:alert(1)', 'data:text/html,test', '\tjavascript:alert(1)', '//contoso.com/x', 'file://contoso.com/share/prompt.txt']) {
+ state.augmentedPrompts.plugin = { status: 'ready', path: promptPath };
+ const html = renderLiveReport(state);
+ assert.ok(!html.includes(`href="${promptPath}"`));
+ assert.match(html, /unsupported link/);
+ }
+ for (const promptPath of ['plugin-remediation-prompt.txt', 'file:///tmp/plugin-prompt.txt']) {
+ state.augmentedPrompts.plugin.path = promptPath;
+ assert.ok(renderLiveReport(state).includes(`href="${promptPath}"`));
+ }
+});
+
+test('customization report links reuse local-file validation and visibly reject unsupported links', () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ state.customizationReport = { totalFindings: 1, breakdown: { liquid: 1 } };
+ for (const value of ['javascript:alert(1)', 'data:text/html,test', '//contoso.com/x',
+ 'file://contoso.com/share/report.html', 'java\nscript:alert(1)']) {
+ state.customizationReport.path = value;
+ const html = renderLiveReport(state);
+ assert.doesNotMatch(html, /class="cust-open-btn"/);
+ assert.match(html, /Customization report unavailable: unsupported link/);
+ }
+ for (const value of ['customization-report.html', 'file:///tmp/report.html']) {
+ state.customizationReport.path = value;
+ assert.ok(renderLiveReport(state).includes(`class="cust-open-btn" href="${value}"`));
+ }
+});
+
+test('customization catalog uses neutral raw counts without implying fixes or runtime compatibility', () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ let html = renderLiveReport(state);
+ assert.match(html, /scan presence alone does not establish a defect/);
+ state.customizationReport = { totalFindings: 30, breakdown: { liquid: 25, fetchxml: 5 },
+ path: 'customization-report.html' };
+ html = renderLiveReport(state);
+ assert.match(html, /scan references, not confirmed defects/);
+ assert.match(html, /Expected references do not require a risk acknowledgment/);
+ assert.match(html, /Zero proposals does not mean all findings have been reviewed/);
+ assert.match(html, /cust-card\.has-findings \{ border-left:3px solid var\(--info\)/);
+ assert.match(html, /Per-finding informational \/ actionable \/ context-review assessments and reasons/);
+ state.customizationReport = { totalFindings: 0 };
+ html = renderLiveReport(state);
+ assert.match(html, /This does not prove complete coverage or runtime compatibility/);
+ assert.doesNotMatch(html, /Clean scan — nothing to remediate/);
+});
+
+test('portal links allow HTTPS without credentials and otherwise render inert text with an explanation', () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ for (const value of ['javascript:alert(1)', 'data:text/html,test', '//contoso.com',
+ 'http://contoso.com', 'https://[email protected]', 'https://contoso.com/\npath']) {
+ state.site.portalUrl = value;
+ const html = renderLiveReport(state);
+ assert.doesNotMatch(html, /<a class="context-value"/);
+ assert.match(html, /Unsupported portal link; HTTPS URL required/);
+ }
+ state.site.portalUrl = 'https://contoso.powerappsportals.com/';
+ assert.match(renderLiveReport(state), /<a class="context-value" href="https:\/\/contoso\.powerappsportals\.com\/"/);
+});
+
+test('diff commands encode apostrophes separately for PowerShell and Bash and preserve other shell characters', () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ const livePath = "C:\\O'Brien\\$(literal); & page.html";
+ const stagedPath = "C:\\O'Brien\\staged `file`.html";
+ const html = renderLiveReport(state, { remediationDiff: { files: [{
+ relativePath: 'page.html', livePath, stagedPath, hunks: [],
+ }] } });
+ const commands = Object.fromEntries([...html.matchAll(
+ /data-label="Copy (PowerShell|Bash) diff command" data-copy="([^"]*)"/g,
+ )].map((match) => [match[1], match[2].replace(/&#39;/g, "'").replace(/&quot;/g, '"')
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')]));
+ assert.deepEqual(commands, {
+ PowerShell: `code --diff '${livePath.replace(/'/g, "''")}' '${stagedPath.replace(/'/g, "''")}'`,
+ Bash: `code --diff '${livePath.replace(/'/g, "'\\''")}' '${stagedPath.replace(/'/g, "'\\''")}'`,
+ });
+ const invalid = renderLiveReport(state, { remediationDiff: { files: [{
+ relativePath: 'page.html', livePath: 'bad\npath', stagedPath,
+ }] } });
+ assert.doesNotMatch(invalid, /data-label="Copy (PowerShell|Bash) diff command"/);
+ assert.match(invalid, /Diff command unavailable: missing or unsupported file path/);
+});
+
+test('form steps and access-rule changes participate in the live comparison', () => {
+ const step = { name: 'Details', parentForm: 'Order', targetEntity: 'account' };
+ const missing = components({ advancedFormSteps: [step] }, { advancedFormSteps: [] });
+ assert.match(missing, /Forms &amp; Lists/);
+ assert.match(missing, /comp-pill mismatch/);
+ assert.match(missing, /Details in Order/);
+ const changed = components({ webpageRules: [{ name: 'Restrict', right: 2 }] },
+ { webpageRules: [{ name: 'Restrict', right: 0 }] });
+ assert.match(changed, /comp-pill match"/);
+ assert.match(changed, /Changed values: 1/);
+});
+
+for (const track of ['A', 'B']) {
+ test(`track ${track} labels the existing percentage as workflow completion`, () => {
+ const state = buildInitialState({
+ webSiteId: '00000000-0000-0000-0000-000000000001',
+ outputDir: 'migration-reports',
+ track,
+ });
+ const steps = state.phases.flatMap((phase) => phase.subSteps);
+ for (const completed of [0, 1, steps.length]) {
+ for (const [index, step] of steps.entries()) {
+ step.status = index < completed ? 'completed' : 'pending';
+ }
+ const percent = Math.round(completed / steps.length * 100);
+ const html = renderLiveReport(state);
+ assert.ok(html.includes(
+ `<div class="stat-num">${percent}%</div><div class="stat-label">Workflow completion</div>`,
+ ));
+ assert.ok(html.includes(
+ `<div class="stat-num">${completed} / ${steps.length}</div><div class="stat-label">Sub-steps</div>`,
+ ));
+ }
+ });
+
+ test(`track ${track} shows input pauses above every tab without implying active processing`, () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports', track });
+ state.approvalGate = null;
+ state.phases[2].status = 'in-progress';
+ state.currentOperation = { label: 'Migrating references', startedAt: state.skillStartedAt };
+ state.pendingInput = { requiredAction: 'Restart the site, then confirm completion.' };
+ const html = renderLiveReport(state);
+ const notice = html.indexOf('<section class="approval-banner"');
+ assert.ok(notice > 0 && notice < html.indexOf('<div class="layout">'));
+ assert.equal((html.match(/id="user-action-notice"/g) || []).length, 1);
+ assert.match(html, /role="alert" aria-labelledby="user-action-title"/);
+ assert.match(html, /Your input is needed/);
+ assert.match(html, /Restart the site, then confirm completion\./);
+ assert.match(html, /Return to the migration conversation and provide your response\./);
+ assert.match(html, /class="status-pill pending" href="#user-action-notice">Input needed/);
+ assert.match(html, /inputNotice\.style\.scrollMarginTop = \(topbar\.offsetHeight \+ 16\)/);
+ assert.doesNotMatch(html, /data-now-running data-op-started-at=/);
+
+ state.pendingInput = null;
+ const resumed = renderLiveReport(state);
+ assert.doesNotMatch(resumed, /id="user-action-notice"/);
+ assert.match(resumed, /data-now-running data-op-started-at=/);
+ assert.match(resumed, /In Progress · Phase 3/);
+ });
+
+ test(`track ${track} preserves existing approval instructions in the report-wide notice`, () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports', track });
+ delete state.pendingInput;
+ state.approvalGate = { phaseId: 2, kind: 'phase-start' };
+ state.phases[0].status = 'in-progress';
+ state.currentOperation = { label: 'Old operation', startedAt: state.skillStartedAt };
+ const html = renderLiveReport(state);
+ assert.ok(html.indexOf('id="user-action-notice"') < html.indexOf('<div class="layout">'));
+ assert.match(html, /Awaiting Approval — Phase 2/);
+ assert.match(html, /To approve and continue/);
+ assert.match(html, /To cancel/);
+ assert.doesNotMatch(html, /data-now-running data-op-started-at=/);
+ assert.match(html, track === 'A' ? /Approve to start Phase 2: Configuration/ : /Approve to start Phase 2: Setting Up Metadata/);
+ });
+}
+
+test('required actions and response locations render as text, not executable HTML', () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ state.pendingInput = {
+ requiredAction: '<img src=x onerror="alert(1)"> & review',
+ responseLocation: '<script>alert(2)</script>',
+ };
+ const html = renderLiveReport(state);
+ assert.match(html, /&lt;img src=x onerror=&quot;alert\(1\)&quot;&gt; &amp; review/);
+ assert.match(html, /&lt;script&gt;alert\(2\)&lt;\/script&gt;/);
+ assert.doesNotMatch(html, /<img src=x|<script>alert\(2\)/);
+});
+
+for (const track of ['A', 'B']) {
+ test(`track ${track} offers in-session runtime testing and distinguishes waiting from running`, () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports', track });
+ state.approvalGate = { phaseId: 4, kind: 'phase-start' };
+ const approval = renderLiveReport(state);
+ assert.match(approval, /offers <strong>Run now<\/strong> in the migration conversation/);
+ assert.match(approval, /report an earlier run, defer, or skip/);
+ assert.match(approval, /Optional rollback remains a separate choice/);
+ assert.doesNotMatch(approval, /recommended via separate/);
+
+ state.approvalGate = null;
+ state.phases[3].status = 'in-progress';
+ const runtimeStep = state.phases[3].subSteps.find((step) => step.id === '4.1');
+ runtimeStep.status = 'in-progress';
+ state.currentOperation = { label: 'Testing migrated site', startedAt: state.skillStartedAt };
+ const phasesBefore = JSON.stringify(state.phases);
+ const running = renderLiveReport(state);
+ assert.match(running, /Now running: Testing migrated site/);
+ assert.match(running, /class="now-running-bar-fill now-running-bar-indeterminate"/);
+ assert.doesNotMatch(running, /data-op-expected-sec="/);
+ assert.equal(JSON.stringify(state.phases), phasesBefore);
+ assert.equal(state.phases[3].subSteps.find((step) => step.id === '4.2').status, 'pending');
+
+ state.pendingInput = { requiredAction: 'Log in through the browser, then confirm here.' };
+ const waiting = renderLiveReport(state);
+ assert.match(waiting, /Log in through the browser, then confirm here\./);
+ assert.doesNotMatch(waiting, /data-now-running data-op-started-at=/);
+ assert.equal(JSON.stringify(state.phases), phasesBefore);
+ });
+}
+
+test('runtime-test instructions wire Run now to the existing skill and preserve consent and report lifecycle', () => {
+ const skill = fs.readFileSync(path.join(__dirname, '../../skills/migrate-datamodel/SKILL.md'), 'utf8');
+ const runtime = skill.slice(skill.indexOf('### 4.1 Runtime Smoke Test'), skill.indexOf('### 4.2 Final Status'));
+ assert.match(skill, /^allowed-tools:.*\bSkill\b/m);
+ assert.match(runtime, /\| Run now, I've already run it, Defer until later, Skip entirely \|/);
+ assert.match(runtime, /Use the \*\*Skill tool\*\* to invoke `power-pages:test-site` with `<SITE_URL>`/);
+ assert.match(runtime, /do not launch a separate agent\/session or duplicate its browser workflow/);
+ assert.match(runtime, /Phase 4 approval alone does not start the test/);
+ assert.match(runtime, /--set-input '\{"requiredAction":"Choose Run now/);
+ assert.match(runtime, /--set-step 4\.1 --status in-progress/);
+ assert.match(runtime, /--set-operation '\{"label":"Testing migrated site"/);
+ assert.match(runtime, /Before any test-owned login, permission, or continue\/stop question, show `--set-input`/);
+ assert.match(runtime, /--clear-operation`, including on cancellation, tool failure, or early stop/);
+ assert.match(runtime, /Never ask for passwords or tokens/);
+ assert.match(runtime, /Do not submit forms or change site data/);
+ assert.doesNotMatch(runtime, /Open a SEPARATE|Why we don't auto-invoke/);
+});
+
+test('runtime-test outcomes require fresh evidence and retain warnings, incomplete runs and user choices', () => {
+ const skill = fs.readFileSync(path.join(__dirname, '../../skills/migrate-datamodel/SKILL.md'), 'utf8');
+ const runtime = skill.slice(skill.indexOf('### 4.1 Runtime Smoke Test'), skill.indexOf('### 4.2 Final Status'));
+ assert.match(runtime, /`docs\/alm\/last-test-site\.json`/);
+ assert.match(runtime, /its `url` matches the confirmed site/);
+ assert.match(runtime, /its `runAt` belongs to this invocation/);
+ assert.match(runtime, /Never reuse a stale report or a report for another site/);
+ assert.match(runtime, /`runOutcome: passed-with-warnings`/);
+ assert.match(runtime, /actual tested\/failed\/skipped counts and any untested scope/);
+ assert.match(runtime, /Not completed, with the explicit reason; never report passed/);
+ assert.match(runtime, /Record this as \*\*user-reported\*\*/);
+ assert.match(runtime, /Do not automatically retry/);
+ assert.match(runtime, /"id":"runtime-smoke-test"/);
+ assert.match(runtime, /records the resolved choice, not proof that all runtime checks passed/);
+});
+
+test('malformed saved pending input produces an explicit render error', () => {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports' });
+ for (const value of [false, [], 'question', {}, { requiredAction: null }, { requiredAction: 'Continue?', responseLocation: 1 }]) {
+ state.pendingInput = value;
+ assert.throws(() => renderLiveReport(state), /Pending input/);
+ }
+});
+
+test('workflow instructions cover input notice lifecycle and both tracks manual-action pauses', () => {
+ const skill = fs.readFileSync(path.join(__dirname, '../../skills/migrate-datamodel/SKILL.md'), 'utf8');
+ assert.match(skill, /Show every user-input pause \(both tracks\)/);
+ assert.match(skill, /before every skill-owned question, choice, confirmation, or manual-action wait/);
+ assert.match(skill, /Before initialization there is no HTML report/);
+ for (const action of ['Provide the Portal ID', 'Confirm in the migration conversation whether to activate',
+ 'Restart the site in Power Platform admin center', 'Review the SDM-to-EDM metadata diff',
+ 'Import the site configuration metadata']) {
+ assert.ok(skill.includes(`--set-input '{"requiredAction":"${action}`), action);
+ }
+ assert.match(skill, /`--clear-input` \*\*before\*\* continuing or stopping/);
+ assert.match(skill, /If the user says "Not yet".*keep the notice/);
+});
+
+test('approved package installation shows an indeterminate bar without advancing migration', () => {
+ for (const track of ['A', 'B']) {
+ const state = buildInitialState({ webSiteId: 'site-id', outputDir: 'migration-reports', track });
+ state.approvalGate = null;
+ state.phases[0].status = 'completed';
+ state.phases[1].status = 'in-progress';
+ state.phases[1].subSteps.find((step) => step.id === '2.2').status = 'completed';
+ state.currentOperation = {
+ label: 'Installing PowerPages_ProgramRegistration_V2',
+ detail: 'Installation accepted; verifying installed version.',
+ startedAt: '2026-01-01T12:00:00Z',
+ };
+ state.lastUpdatedAt = '2026-01-01T12:02:05Z';
+ const phasesBefore = JSON.stringify(state.phases);
+ const html = renderLiveReport(state);
+ assert.match(html, /Now running: Installing PowerPages_ProgramRegistration_V2/);
+ assert.match(html, /Installation accepted; verifying installed version\./);
+ assert.match(html, /class="now-running-bar-fill now-running-bar-indeterminate"/);
+ assert.match(html, /data-now-running-elapsed>2m 05s/);
+ assert.doesNotMatch(html, /data-op-expected-sec="|<span class="now-running-poll">/);
+ assert.ok(html.indexOf('data-now-running data-op-started-at=') < html.indexOf('<div class="layout">'));
+ assert.equal(JSON.stringify(state.phases), phasesBefore);
+ assert.ok(state.phases[2].subSteps.every((step) => step.status === 'pending'));
+
+ state.currentOperation = null;
+ assert.doesNotMatch(renderLiveReport(state), /data-now-running data-op-started-at=/);
+ }
+});
+
+test('package progress instructions cover all installation paths and asynchronous verification', () => {
+ const skill = fs.readFileSync(path.join(__dirname, '../../skills/migrate-datamodel/SKILL.md'), 'utf8');
+ assert.equal((skill.match(/\[Package installation progress\]\(#package-installation-progress\)/g) || []).length, 3);
+ assert.match(skill, /--set-operation '\{"label":"Installing <PACKAGE_NAME>","detail":/);
+ assert.match(skill, /Keep the banner active through asynchronous installation and verification/);
+ assert.match(skill, /Do not invent an installation percentage or ETA/);
+ assert.match(skill, /keep the same `Installing <PACKAGE_NAME>` label/);
+ assert.match(skill, /Do not start a second install just because the first one is slow/);
+ assert.match(skill, /On verified completion, `--clear-operation`/);
+ assert.match(skill, /Fresh report only:.*Phase 1 is already running/);
+ assert.match(skill, /`--approve-and-start 1`.*existing work/);
+ assert.match(skill, /On resume, preserve the saved phase, pending input, and approval gate/);
+});
diff --git a/plugins/power-pages/scripts/tests/restart-site.test.js b/plugins/power-pages/scripts/tests/restart-site.test.js
new file mode 100644
index 000000000..6012d6721
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/restart-site.test.js
@@ -0,0 +1,289 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const fs = require('node:fs');
+const os = require('node:os');
+const { spawnSync } = require('node:child_process');
+const { restartSite } = require('../restart-site');
+const { buildInitialState } = require('../../skills/migrate-datamodel/scripts/lib/migration-state-schema');
+const { renderLiveReport } = require('../../skills/migrate-datamodel/scripts/lib/render-live-report');
+
+const portalId = '00000000-0000-0000-0000-000000000001';
+const environmentId = '00000000-0000-0000-0000-000000000002';
+const environmentUrl = 'https://contoso.crm.dynamics.com';
+const websiteUrl = 'https://contoso.powerappsportals.com';
+
+function fixture({ statuses = [], health = [], post = { ok: true, statusCode: 200 } } = {}) {
+ const calls = [];
+ const probes = [];
+ const sleeps = [];
+ const progress = [];
+ let index = 0;
+ const site = (status = 'OperationComplete') => ({
+ id: portalId, websiteUrl, status,
+ // The activated EDM record need not be the original SDM record.
+ websiteRecordId: '00000000-0000-0000-0000-000000000003',
+ });
+ const deps = {
+ getEnvironmentUrl: () => environmentUrl,
+ resolveContext: () => ({
+ environmentId, apiHost: 'https://api.powerplatform.com',
+ baseUrl: `https://api.powerplatform.com/powerpages/environments/${environmentId}`, token: 'test-token',
+ }),
+ async request(options) {
+ calls.push(options);
+ if (options.method === 'POST') return post;
+ const current = index++;
+ const selected = statuses[current] || 'OperationComplete';
+ if (typeof selected === 'object') return selected;
+ return { ok: true, statusCode: 200, body: site(selected) };
+ },
+ async makeRequest(options) {
+ probes.push(options);
+ return health[probes.length - 1] || { statusCode: 200 };
+ },
+ async sleep(ms) { sleeps.push(ms); },
+ onProgress(record) { progress.push(record); },
+ };
+ return { deps, calls, probes, sleeps, progress, options: { portalId, environmentUrl, websiteUrl, approved: true } };
+}
+
+test('approved restart uses the API Portal ID and verifies operation status and anonymous reachability', async () => {
+ const f = fixture();
+ const result = await restartSite(f.options, f.deps);
+ assert.equal(result.success, true);
+ assert.equal(result.restartSubmitted, true);
+ assert.equal(result.websiteReachable, true);
+ assert.equal(result.attempts, 2);
+ const posts = f.calls.filter((call) => call.method === 'POST');
+ assert.equal(posts.length, 1);
+ assert.equal(posts[0].path, `/websites/${portalId}/restart`);
+ assert.equal(posts[0].query['api-version'], '2024-10-01');
+ assert.equal(posts[0].timeout, 30000);
+ assert.ok(f.probes.every((probe) => probe.url === `${websiteUrl}/` &&
+ !Object.keys(probe.headers).some((key) => /authorization|cookie/i.test(key))));
+ assert.deepEqual(f.sleeps, [15000, 15000]);
+ assert.equal(f.progress[0].event, 'restart-submitted');
+});
+
+test('missing approval, malformed identifiers and unsafe URLs cannot invoke auth or HTTP', async () => {
+ for (const patch of [
+ { approved: false }, { approved: 'true' }, { approved: true, verifyOnly: true },
+ { portalId: null }, { portalId: '../other-site' }, { environmentUrl: null },
+ { environmentUrl: 'https://example.com' }, { websiteUrl: null },
+ { websiteUrl: 'http://contoso.powerappsportals.com' },
+ { websiteUrl: 'https://user:[email protected]' },
+ { websiteUrl: 'https://contoso.powerappsportals.com:8443' },
+ ]) {
+ const f = fixture();
+ let authCalled = false;
+ f.deps.getEnvironmentUrl = () => { authCalled = true; return environmentUrl; };
+ await assert.rejects(restartSite({ ...f.options, ...patch }, f.deps));
+ assert.equal(authCalled, false);
+ assert.equal(f.calls.length, 0);
+ }
+});
+
+test('environment mismatch and sign-in failures stop before any API mutation', async () => {
+ for (const active of [null, 'https://fabrikam.crm.dynamics.com']) {
+ const f = fixture();
+ f.deps.getEnvironmentUrl = () => active;
+ await assert.rejects(restartSite(f.options, f.deps), /does not match/);
+ assert.equal(f.calls.length, 0);
+ }
+ const f = fixture();
+ f.deps.resolveContext = () => ({ error: 'Azure CLI is not signed in. Run: az login' });
+ await assert.rejects(restartSite(f.options, f.deps), /Azure CLI/);
+ assert.equal(f.calls.length, 0);
+});
+
+test('invalid API context cannot send management credentials to another host', async () => {
+ const f = fixture();
+ f.deps.resolveContext = () => ({ environmentId, apiHost: 'https://example.com', baseUrl: 'https://example.com', token: 'test-token' });
+ await assert.rejects(restartSite(f.options, f.deps), /Invalid Power Platform/);
+ assert.equal(f.calls.length, 0);
+});
+
+test('missing API context produces an actionable error rather than a null dereference', async () => {
+ const f = fixture();
+ f.deps.resolveContext = () => null;
+ await assert.rejects(restartSite(f.options, f.deps), /context is unavailable/);
+ assert.equal(f.calls.length, 0);
+});
+
+test('null, malformed or mismatched API identities cannot be restarted', async () => {
+ for (const body of [null, [], {}, { id: environmentId, websiteUrl, status: 'OperationComplete' },
+ { id: portalId, websiteUrl: 'https://another.powerappsportals.com', status: 'OperationComplete' },
+ { id: portalId, websiteUrl, status: 'Unknown' }]) {
+ const f = fixture({ statuses: [{ ok: true, statusCode: 200, body }] });
+ await assert.rejects(restartSite(f.options, f.deps));
+ assert.equal(f.calls.filter((call) => call.method === 'POST').length, 0);
+ }
+});
+
+test('PascalCase API properties remain supported', async () => {
+ const f = fixture({
+ statuses: Array(3).fill({ ok: true, statusCode: 200, body: { Id: portalId.toUpperCase(), WebsiteUrl: websiteUrl, Status: 'OperationComplete' } }),
+ });
+ assert.equal((await restartSite(f.options, f.deps)).success, true);
+});
+
+test('preflight API failure or an outstanding operation does not restart the site', async () => {
+ for (const initial of [
+ { ok: false, statusCode: 403, error: { message: 'Not authorized' } },
+ 'OperationInProgress', 'OperationNotStarted', 'OperationFailed',
+ ]) {
+ const f = fixture({ statuses: [initial] });
+ const result = await restartSite(f.options, f.deps);
+ assert.equal(result.success, false);
+ assert.equal(result.restartSubmitted, false);
+ assert.equal(result.outcome, 'PreflightFailed');
+ assert.equal(f.calls.length, 1);
+ }
+});
+
+test('restart errors are explicit and ambiguous requests are never retried', async () => {
+ for (const [statusCode, submitted] of [[401, false], [403, false], [404, false], [408, null], [500, null], [0, null]]) {
+ const f = fixture({ post: { ok: false, statusCode, error: { message: 'Restart failed' } } });
+ const result = await restartSite(f.options, f.deps);
+ assert.equal(result.success, false);
+ assert.equal(result.restartSubmitted, submitted);
+ assert.match(result.error, /Restart failed/);
+ assert.equal(f.calls.filter((call) => call.method === 'POST').length, 1);
+ assert.equal(f.probes.length, 0);
+ }
+});
+
+test('an undocumented async response cannot masquerade as a completed restart', async () => {
+ const f = fixture({ post: { ok: true, statusCode: 202 } });
+ const result = await restartSite(f.options, f.deps);
+ assert.equal(result.success, false);
+ assert.equal(result.restartSubmitted, true);
+ assert.equal(result.outcome, 'RestartUnconfirmed');
+ assert.equal(f.probes.length, 0);
+});
+
+test('verification waits for completion and requires two consecutive reachable responses', async () => {
+ const f = fixture({
+ statuses: ['OperationComplete', 'OperationInProgress', 'OperationComplete', 'OperationComplete', 'OperationComplete', 'OperationComplete'],
+ health: [{ statusCode: 200 }, { statusCode: 503 }, { statusCode: 302 }, { statusCode: 200 }],
+ });
+ const result = await restartSite(f.options, f.deps);
+ assert.equal(result.success, true);
+ assert.equal(result.attempts, 5);
+ assert.equal(f.probes.length, 4);
+});
+
+test('website operation failure and API verification errors remain failures after submission', async () => {
+ for (const response of ['OperationFailed', { ok: false, statusCode: 401, error: { message: 'Token expired' } }]) {
+ const f = fixture({ statuses: ['OperationComplete', response] });
+ const result = await restartSite(f.options, f.deps);
+ assert.equal(result.success, false);
+ assert.equal(result.restartSubmitted, true);
+ assert.equal(result.outcome, 'VerificationFailed');
+ assert.equal(f.calls.filter((call) => call.method === 'POST').length, 1);
+ }
+});
+
+test('unreachable or protected sites time out at exactly 20 checks without another restart', async () => {
+ for (const health of [{ error: 'Request timed out' }, { statusCode: 503 }, { statusCode: 403 }]) {
+ const f = fixture({ health: Array(20).fill(health) });
+ const result = await restartSite(f.options, f.deps);
+ assert.equal(result.success, false);
+ assert.equal(result.outcome, 'VerificationTimedOut');
+ assert.equal(result.attempts, 20);
+ assert.equal(f.sleeps.length, 20);
+ assert.equal(f.probes.length, 20);
+ assert.equal(f.calls.filter((call) => call.method === 'POST').length, 1);
+ }
+});
+
+test('read-only verification never sends a POST or needs fresh mutation consent', async () => {
+ const f = fixture();
+ const result = await restartSite({ ...f.options, approved: false, verifyOnly: true }, f.deps);
+ assert.equal(result.success, true);
+ assert.equal(result.verificationOnly, true);
+ assert.equal(result.restartSubmitted, false);
+ assert.equal(f.calls.filter((call) => call.method === 'POST').length, 0);
+ assert.deepEqual(f.sleeps, [15000]);
+});
+
+test('CLI reports invalid or unapproved invocations as JSON failures without accessing live CLIs', () => {
+ const script = path.join(__dirname, '../restart-site.js');
+ const result = spawnSync(process.execPath, [
+ script, '--portal-id', portalId, '--env-url', environmentUrl, '--website-url', websiteUrl,
+ ], { encoding: 'utf8', env: { ...process.env, PATH: '' } });
+ assert.equal(result.status, 1);
+ const output = JSON.parse(result.stdout);
+ assert.equal(output.success, false);
+ assert.match(output.error, /approval/);
+});
+
+test('restart remains after activation in both Phase 3 tracks and before Phase 4 runtime validation', () => {
+ for (const track of ['A', 'B']) {
+ const state = buildInitialState({ webSiteId: portalId, outputDir: 'migration-reports', track });
+ const phase3 = state.phases.find((phase) => phase.id === 3);
+ assert.match(phase3.subSteps.at(-2).label, /Activate EDM/);
+ assert.equal(phase3.subSteps.at(-1).label, 'Restart Site');
+ assert.match(state.phases.find((phase) => phase.id === 4).subSteps[0].label, /Runtime Smoke Test/);
+ assert.match(renderLiveReport(state), /approved API restart and readiness verification \(manual fallback\)/);
+ }
+ const skill = fs.readFileSync(path.join(__dirname, '../../skills/migrate-datamodel/SKILL.md'), 'utf8');
+ assert.match(skill, /### 3\.4 Restart Site \(API first, manual fallback\)/);
+ assert.match(skill, /### 3\.6 Restart Site \(API first, manual fallback\)/);
+ assert.match(skill, /Phase 3, after activation and before Phase 4 runtime validation/);
+ assert.match(skill, /restart-site\.js".*--portal-id "<PORTAL_ID>".*--approved/);
+ assert.match(skill, /restart-site\.js".*--verify-only/);
+ assert.match(skill, /do not automatically repeat the POST/i);
+ assert.match(skill, /A healthy site alone does not prove a restart happened/);
+ assert.match(skill, /Restart the site in Power Platform admin center/);
+});
+
+test('CLI success, read-only verification and readiness timeout preserve the JSON/exit-code contract', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'restart-cli-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const preload = path.join(root, 'stub-api.cjs');
+ const apiPath = path.join(__dirname, '../lib/power-platform-api.js');
+ const helpersPath = path.join(__dirname, '../lib/validation-helpers.js');
+ // Only the spawned child is stubbed; no test can reach real CLI accounts,
+ // management endpoints or websites.
+ fs.writeFileSync(preload, `
+ const api = require(${JSON.stringify(apiPath)});
+ const helpers = require(${JSON.stringify(helpersPath)});
+ // Preloading occurs before Node assigns require.main. Supply the same
+ // entry-point gate here so the CLI main still runs with stubbed services.
+ api.runCli = (caller, main) => {
+ if (caller.filename === process.argv[1]) Promise.resolve().then(main).catch(error => {
+ console.error(error.message);
+ process.exitCode = 1;
+ });
+ };
+ api.resolveContext = () => ({
+ environmentId: ${JSON.stringify(environmentId)}, token: 'test-token',
+ apiHost: 'https://api.powerplatform.com',
+ baseUrl: 'https://api.powerplatform.com/powerpages/environments/${environmentId}'
+ });
+ api.request = async ({method}) => {
+ if (method === 'POST' && process.env.TEST_RESTART_MODE === 'readonly') throw new Error('Read-only command sent a POST');
+ return {ok:true,statusCode:200,body:{id:${JSON.stringify(portalId)},websiteUrl:${JSON.stringify(websiteUrl)},status:'OperationComplete'}};
+ };
+ helpers.getEnvironmentUrl = () => ${JSON.stringify(environmentUrl)};
+ helpers.makeRequest = async () => ({statusCode:process.env.TEST_RESTART_MODE === 'timeout' ? 503 : 200});
+ global.setTimeout = callback => { callback(); };
+ `);
+ for (const [mode, exitCode, submitted, attempts] of [
+ ['ready', 0, true, 2], ['readonly', 0, false, 2], ['timeout', 1, true, 20],
+ ]) {
+ const result = spawnSync(process.execPath, [
+ '--require', preload, path.join(__dirname, '../restart-site.js'),
+ '--portal-id', portalId, '--env-url', environmentUrl, '--website-url', websiteUrl,
+ mode === 'readonly' ? '--verify-only' : '--approved',
+ ], { encoding: 'utf8', env: { ...process.env, TEST_RESTART_MODE: mode } });
+ assert.equal(result.status, exitCode, result.stderr);
+ const output = JSON.parse(result.stdout);
+ assert.equal(output.success, exitCode === 0);
+ assert.equal(output.restartSubmitted, submitted);
+ assert.equal(output.attempts, attempts);
+ assert.doesNotMatch(result.stdout + result.stderr, /test-token/);
+ }
+});
diff --git a/plugins/power-pages/scripts/tests/snapshot-site.test.js b/plugins/power-pages/scripts/tests/snapshot-site.test.js
new file mode 100644
index 000000000..cad6e7753
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/snapshot-site.test.js
@@ -0,0 +1,372 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { safeReaddir } = require('../../skills/migrate-datamodel/scripts/snapshot-site');
+const { diffCategory } = require('../../skills/migrate-datamodel/scripts/diff-snapshots');
+const script = path.join(__dirname, '../../skills/migrate-datamodel/scripts/snapshot-site.js');
+
+function fixture(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-snapshot-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const site = path.join(root, 'site');
+ const output = path.join(root, 'reports');
+ fs.mkdirSync(site);
+ fs.writeFileSync(path.join(site, 'website.yml'), 'adx_websiteid: 00000000-0000-0000-0000-000000000001\n');
+ function write(relative, text) {
+ const file = path.join(site, ...relative.split(/[\\/]/));
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, text);
+ }
+ function run() {
+ const result = spawnSync(process.execPath, [script, '--site-root', site,
+ '--output-dir', output, '--label', 'sdm', '--with-content-hash'], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(fs.readFileSync(path.join(output, 'sdm-snapshot.json'), 'utf8'));
+ }
+ return { write, run, site, output };
+}
+
+test('missing optional snapshot directories remain empty', (t) => {
+ t.mock.method(fs, 'readdirSync', () => {
+ throw Object.assign(new Error('missing directory'), { code: 'ENOENT' });
+ });
+ assert.deepEqual(safeReaddir('missing'), []);
+});
+
+test('unreadable snapshot directories report errors rather than empty inventories', (t) => {
+ t.mock.method(fs, 'readdirSync', () => {
+ throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ });
+ assert.throws(() => safeReaddir('restricted'), /Could not read snapshot directory restricted: permission denied/);
+});
+
+for (const relative of ['web-pages', 'site-settings', 'web-templates\\header']) {
+ test(`inaccessible ${relative} cannot replace a saved snapshot with an empty inventory`, (t) => {
+ const { write, run, site, output } = fixture(t);
+ write('web-templates\\header\\Header.webtemplate.yml', 'adx_name: Header');
+ run();
+ const saved = fs.readFileSync(path.join(output, 'sdm-snapshot.json'), 'utf8');
+ const target = path.join(site, ...relative.split('\\'));
+ const preload = path.join(path.dirname(site), 'unreadable.cjs');
+ fs.writeFileSync(preload, `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const target = ${JSON.stringify(target)};
+ const exists = fs.existsSync;
+ const readdir = fs.readdirSync;
+ fs.existsSync = (p) => path.resolve(p) === target ? false : exists(p);
+ fs.readdirSync = (p, ...args) => {
+ if (path.resolve(p) === target) throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ return readdir(p, ...args);
+ };
+ `);
+ const result = spawnSync(process.execPath, ['--require', preload, script, '--site-root', site,
+ '--output-dir', output, '--label', 'sdm'], { encoding: 'utf8' });
+ assert.equal(result.status, 1, result.stdout);
+ assert.match(result.stderr, /Could not read snapshot directory.*permission denied/);
+ assert.equal(fs.readFileSync(path.join(output, 'sdm-snapshot.json'), 'utf8'), saved);
+ });
+}
+
+test('unreadable companion content cannot silently lose its hash or replace saved evidence', (t) => {
+ const { write, run, site, output } = fixture(t);
+ write('web-templates\\header\\Header.webtemplate.yml', 'adx_name: Header');
+ write('web-templates\\header\\Header.webtemplate.source.html', '<header>Before</header>');
+ run();
+ const saved = fs.readFileSync(path.join(output, 'sdm-snapshot.json'), 'utf8');
+ const target = path.join(site, 'web-templates', 'header', 'Header.webtemplate.source.html');
+ const preload = path.join(path.dirname(site), 'unreadable-content.cjs');
+ fs.writeFileSync(preload, `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const target = ${JSON.stringify(target)};
+ const exists = fs.existsSync;
+ const read = fs.readFileSync;
+ fs.existsSync = (p) => path.resolve(p) === target ? false : exists(p);
+ fs.readFileSync = (p, ...args) => {
+ if (path.resolve(p) === target) throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ return read(p, ...args);
+ };
+ `);
+ const result = spawnSync(process.execPath, ['--require', preload, script, '--site-root', site,
+ '--output-dir', output, '--label', 'sdm', '--with-content-hash'], { encoding: 'utf8' });
+ assert.equal(result.status, 1, result.stdout);
+ assert.match(result.stderr, /Could not hash snapshot content.*permission denied/);
+ assert.equal(fs.readFileSync(path.join(output, 'sdm-snapshot.json'), 'utf8'), saved);
+});
+
+for (const [relative, category] of [
+ ['sitesetting.yml', 'siteSettings'],
+ ['web-link-sets\\primary\\Primary.weblinkset.weblink.yml', 'webLinkSets'],
+]) {
+ test(`unreadable ${relative} retains explicit category errors instead of claiming no records`, (t) => {
+ const { write, site, output } = fixture(t);
+ write('web-link-sets\\primary\\Primary.weblinkset.yml', 'adx_name: Primary');
+ const target = path.join(site, ...relative.split('\\'));
+ const preload = path.join(path.dirname(site), 'unreadable-file.cjs');
+ fs.writeFileSync(preload, `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const target = ${JSON.stringify(target)};
+ const exists = fs.existsSync;
+ const read = fs.readFileSync;
+ fs.existsSync = (p) => path.resolve(p) === target ? false : exists(p);
+ fs.readFileSync = (p, ...args) => {
+ if (path.resolve(p) === target) throw Object.assign(new Error('I/O failure'), { code: 'EIO' });
+ return read(p, ...args);
+ };
+ `);
+ const result = spawnSync(process.execPath, ['--require', preload, script, '--site-root', site,
+ '--output-dir', output, '--label', 'sdm'], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ const snapshot = JSON.parse(fs.readFileSync(path.join(output, 'sdm-snapshot.json'), 'utf8'));
+ assert.equal(snapshot.parseErrors[category]?.length, 1);
+ assert.match(snapshot.parseErrors[category][0].message, /I\/O failure/);
+ });
+}
+
+for (const [category, flat, legacy] of [
+ ['lists', 'lists\\Current.list.yml', 'lists\\legacy\\Legacy.entitylist.yml'],
+ ['cloudFlowConsumers', 'cloud-flow-consumer\\Current.cloudflowconsumer.yml',
+ 'cloud-flow-consumer\\legacy\\Legacy.cloudflowconsumer.yml'],
+]) {
+ test(`${category} snapshots include flat and legacy layouts and detect missing records`, (t) => {
+ const { write, run, site } = fixture(t);
+ write(flat, 'name: Current\nstatecode: 1');
+ write(legacy, 'adx_name: Legacy\nadx_statecode: 0');
+ const before = run();
+ assert.equal(before.counts[category], 2);
+ assert.deepEqual(before.inventory[category].map(({ name }) => name).sort(), ['Current', 'Legacy']);
+ assert.equal(before.inventory[category].find(({ name }) => name === 'Current').stateCode, 1);
+ fs.unlinkSync(path.join(site, ...flat.split('\\')));
+ const after = run();
+ const diff = diffCategory(category, before.inventory[category], after.inventory[category]);
+ assert.equal(diff.status, 'fail');
+ assert.equal(diff.missingInEdm[0].name, 'Current');
+ write(flat, 'name: Current\nmalformed field');
+ const broken = run();
+ assert.match(broken.parseErrors[category][0].message, /Invalid YAML line/);
+ });
+}
+
+test('snapshot rejects arbitrary roots without creating or replacing saved evidence', (t) => {
+ const { write, run, site, output } = fixture(t);
+ const empty = path.join(site, 'not-a-site');
+ fs.mkdirSync(empty);
+ const attempt = () => spawnSync(process.execPath, [script, '--site-root', empty,
+ '--output-dir', output, '--label', 'sdm'], { encoding: 'utf8' });
+ let result = attempt();
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /downloaded Power Pages site containing website\.yml/);
+ assert.equal(fs.existsSync(output), false);
+ write('webrole.yml', '- adx_name: Members');
+ run();
+ const snapshot = path.join(output, 'sdm-snapshot.json');
+ const original = fs.readFileSync(snapshot, 'utf8');
+ result = attempt();
+ assert.equal(result.status, 1);
+ assert.equal(fs.readFileSync(snapshot, 'utf8'), original);
+});
+
+test('nested configuration and both setting layouts are captured with content hashes', (t) => {
+ const { write, run } = fixture(t);
+ write('.powerpages-site\\website.yml', 'adx_name: Contoso');
+ write('.powerpages-site\\sitesetting.yml', '- adx_name: Aggregate\n adx_value: "true"');
+ write('.powerpages-site\\site-settings\\Individual.sitesetting.yml', 'adx_name: Individual\nadx_value: "false"');
+ write('.powerpages-site\\web-templates\\header\\Header.webtemplate.yml', 'adx_name: Header');
+ write('.powerpages-site\\web-templates\\header\\Header.webtemplate.source.html', '<header>Before</header>');
+ const before = run();
+ assert.equal(before.counts.siteSettings, 2);
+ assert.deepEqual(before.inventory.siteSettings.map((record) => record.value), ['true', 'false']);
+ assert.equal(before.counts.webTemplates, 1);
+ assert.match(before.inventory.webTemplates[0].contentHash, /^[a-f0-9]{16}$/);
+ write('.powerpages-site\\web-templates\\header\\Header.webtemplate.source.html', '<header>After</header>');
+ assert.notEqual(run().inventory.webTemplates[0].contentHash, before.inventory.webTemplates[0].contentHash);
+ });
+
+test('malformed aggregate fields are reported instead of silently dropped', (t) => {
+ const { write, run } = fixture(t);
+ write('sitesetting.yml', '- adx_name: Example\n malformed field without a colon');
+ const snapshot = run();
+ assert.equal(snapshot.counts.siteSettings, 0);
+ assert.match(snapshot.parseErrors.siteSettings[0].message, /Invalid YAML line/);
+ });
+
+test('localized page snapshots include flat and locale-subdirectory layouts and detect missing translations', (t) => {
+ const { write, run, site } = fixture(t);
+ write('web-pages\\home\\Home.webpage.yml', 'adx_name: Home\nadx_partialurl: home');
+ write('web-pages\\home\\content-pages\\Home.en-US.webpage.yml', 'adx_name: Home\nadx_partialurl: home');
+ const french = 'web-pages\\home\\content-pages\\fr-FR\\Home.fr-FR.webpage.yml';
+ write(french, 'name: Home\npartialurl: home\nstatecode: 1');
+ write(french.replace('.webpage.yml', '.webpage.copy.html'), '<p>Bonjour</p>');
+ const before = run();
+ assert.equal(before.counts.webPages, 3);
+ const translations = before.inventory.webPages.filter((record) => record.kind === 'content');
+ assert.deepEqual(translations.map((record) => record.language).sort(), ['en-US', 'fr-FR']);
+ const nested = translations.find((record) => record.language === 'fr-FR');
+ assert.equal(nested.stateCode, 1);
+ assert.match(nested.contentHash, /^[a-f0-9]{16}$/);
+ fs.unlinkSync(path.join(site, ...french.split('\\')));
+ const after = run();
+ assert.equal(after.counts.webPages, 2);
+ const diff = diffCategory('webPages', before.inventory.webPages, after.inventory.webPages);
+ assert.equal(diff.status, 'fail');
+ assert.equal(diff.missingInEdm[0].language, 'fr-FR');
+});
+
+test('malformed localized pages in locale subdirectories retain parse errors', (t) => {
+ const { write, run } = fixture(t);
+ write('web-pages\\home\\content-pages\\fr-FR\\Home.fr-FR.webpage.yml', 'adx_name: Home\nmalformed field');
+ const snapshot = run();
+ assert.equal(snapshot.counts.webPages, 0);
+ assert.match(snapshot.parseErrors.webPages[0].filePath, /Home\.fr-FR\.webpage\.yml$/);
+ assert.match(snapshot.parseErrors.webPages[0].message, /Invalid YAML line/);
+});
+
+test('review regression: web roles merge aggregate and per-record layouts with prefixed and unprefixed states', (t) => {
+ const { write, run } = fixture(t);
+ write('webrole.yml', '- adx_name: Aggregate\n adx_statecode: 1');
+ write('web-roles\\Individual.webrole.yml', 'name: Individual\nstatecode: 0');
+ const snapshot = run();
+ assert.equal(snapshot.counts.webRoles, 2);
+ assert.deepEqual(snapshot.inventory.webRoles, [
+ { name: 'Aggregate', stateCode: 1 },
+ { name: 'Individual', stateCode: 0 },
+ ]);
+ assert.equal(Object.hasOwn(snapshot.parseErrors, 'webRoles'), false);
+});
+
+test('review regression: per-record web-role loss is detected instead of comparing empty inventories', (t) => {
+ const { write, run, site } = fixture(t);
+ write('web-roles\\Administrators.webrole.yml', 'adx_name: Administrators');
+ write('web-roles\\Members.webrole.yml', 'adx_name: Members');
+ const before = run();
+ assert.equal(before.counts.webRoles, 2);
+ fs.unlinkSync(path.join(site, 'web-roles', 'Members.webrole.yml'));
+ const after = run();
+ assert.equal(after.counts.webRoles, 1);
+ const diff = diffCategory('webRoles', before.inventory.webRoles, after.inventory.webRoles);
+ assert.equal(diff.status, 'fail');
+ assert.equal(diff.missingInEdm[0].name, 'Members');
+});
+
+test('review regression: malformed per-record web roles retain explicit parse errors', (t) => {
+ const { write, run } = fixture(t);
+ write('web-roles\\Broken.webrole.yml', 'adx_name: Broken\nmalformed field without a colon');
+ const snapshot = run();
+ assert.equal(snapshot.counts.webRoles, 0);
+ assert.equal(snapshot.parseErrors.webRoles.length, 1);
+ assert.match(snapshot.parseErrors.webRoles[0].filePath, /Broken\.webrole\.yml$/);
+ assert.match(snapshot.parseErrors.webRoles[0].message, /Invalid YAML line/);
+});
+
+test('navigation retains inactive links, target, order and state while counting active links', (t) => {
+ const { write, run } = fixture(t);
+ write('web-link-sets\\main\\Main.en-US.weblinkset.yml', 'adx_name: Main\nadx_statecode: 0');
+ write('web-link-sets\\main\\Main.en-US.weblinkset.weblink.yml',
+ '- adx_name: Home\n adx_displayorder: 2\n adx_pageid: page-id\n adx_statecode: 0\n' +
+ '- adx_name: Hidden\n adx_displayorder: 1\n adx_externalurl: https://contoso.com\n adx_statecode: 1');
+ const snapshot = run();
+ assert.equal(snapshot.counts.webLinks, 2);
+ assert.equal(snapshot.inventory.webLinkSets[0].linkCount, 1);
+ assert.deepEqual(snapshot.inventory.webLinkSets[0].linkNames, ['Home']);
+ const hidden = snapshot.inventory.webLinks.find((link) => link.name === 'Hidden');
+ assert.equal(hidden.stateCode, 1);
+ assert.equal(hidden.displayOrder, 1);
+ assert.equal(hidden.externalUrl, 'https://contoso.com');
+ assert.equal(snapshot.inventory.webLinks.find((link) => link.name === 'Home').pageId, 'page-id');
+ });
+
+test('legacy navigation layouts remain supported alongside canonical menus', (t) => {
+ const { write, run } = fixture(t);
+ for (const [folder, name] of [['web-link-sets', 'Main'], ['weblink-sets', 'Footer']]) {
+ write(`${folder}\\menu\\${name}.en-US.weblinkset.yml`, `adx_name: ${name}`);
+ write(`${folder}\\menu\\${name}.en-US.weblinkset.weblink.yml`, '- adx_name: Home\n statecode: 0');
+ }
+ const snapshot = run();
+ assert.equal(snapshot.counts.webLinkSets, 2);
+ assert.equal(snapshot.counts.webLinks, 2);
+ assert.deepEqual(snapshot.inventory.webLinks.map((link) => link.parentSet).sort(), ['Footer', 'Main']);
+});
+
+test('prefixed inactive states survive every scanner shape and produce diff warnings', (t) => {
+ const { write, run } = fixture(t);
+ const records = [
+ ['webrole.yml', '- adx_name: Role\n adx_statecode: 1', 'webRoles'],
+ ['web-pages\\home\\Home.webpage.yml', 'adx_name: Home\nadx_statecode: 1', 'webPages'],
+ ['content-snippets\\title\\Title.en-US.contentsnippet.yml', 'adx_name: Title\nadx_statecode: 1', 'contentSnippets'],
+ ['web-templates\\main\\Main.webtemplate.yml', 'adx_name: Main\nadx_statecode: 1', 'webTemplates'],
+ ['page-templates\\Main.pagetemplate.yml', 'adx_name: Main\nadx_statecode: 1', 'pageTemplates'],
+ ['basic-forms\\main\\Main.basicform.yml', 'adx_name: Main\nadx_statecode: 1', 'basicForms'],
+ ];
+ for (const [file, text] of records) write(file, text);
+ const before = run();
+ for (const [file, text, category] of records) {
+ assert.equal(before.inventory[category][0].stateCode, 1, category);
+ write(file, text.replace('adx_statecode: 1', 'statecode: 0'));
+ }
+ const after = run();
+ for (const [, , category] of records) {
+ const diff = diffCategory(category, before.inventory[category], after.inventory[category]);
+ assert.equal(diff.status, 'warn', category);
+ assert.equal(diff.stateChanged.length, 1, category);
+ }
+});
+
+test('nested form steps retain parent identities, state and routing and cannot silently disappear', (t) => {
+ const { write, run } = fixture(t);
+ for (const form of ['Order', 'Contact']) {
+ write(`advanced-forms\\${form}\\${form}.advancedform.yml`, `adx_name: ${form}`);
+ write(`advanced-forms\\${form}\\advanced-form-steps\\nested\\details\\Details.advancedformstep.yml`,
+ `adx_name: Details\nadx_webform: ${form}-id\nadx_targetentitylogicalname: account\nadx_type: 0\nadx_statecode: 1\nadx_nextstep: next-id`);
+ }
+ const before = run();
+ const steps = before.inventory.advancedFormSteps;
+ assert.equal(before.counts.advancedFormSteps, 2);
+ assert.equal(steps[0].stateCode, 1);
+ assert.equal(steps[0].type, 0);
+ assert.equal(steps[0].nextStepId, 'next-id');
+ assert.equal(diffCategory('advancedFormSteps', steps, steps).status, 'pass');
+ assert.equal(diffCategory('advancedFormSteps', steps, steps.slice(1)).status, 'fail');
+ write('advanced-forms\\Order\\advanced-form-steps\\nested\\details\\Details.advancedformstep.yml',
+ 'name: Details\nwebform: Order-id\ntargetentitylogicalname: contact\ntype: 0\nstatecode: 1\nnextstep: different-id');
+ const diff = diffCategory('advancedFormSteps', steps, run().inventory.advancedFormSteps);
+ assert.equal(diff.status, 'warn');
+ assert.deepEqual(diff.valueChanged.map((change) => change.field).sort(), ['nextStepId', 'targetEntity']);
+});
+
+test('aggregate and per-record access rules retain policy values and normalize role order', (t) => {
+ const { write, run } = fixture(t);
+ write('webpagerule.yml',
+ '- adx_name: Aggregate\n adx_right: 2\n adx_webpageid: home-id\n adx_statecode: 1');
+ write('webpage-rules\\Orders.webpagerule.yml',
+ 'name: Orders\nright: 0\nwebpageid: orders-id\nscope: 1\nstatecode: 0\n' +
+ 'adx_webpageaccesscontrolrule_webrole:\n- role-b\n- role-a');
+ const before = run();
+ const rules = before.inventory.webpageRules;
+ assert.equal(before.counts.webpageRules, 2);
+ assert.equal(rules[0].stateCode, 1);
+ assert.equal(rules[1].right, 0);
+ assert.equal(rules[1].pageId, 'orders-id');
+ assert.deepEqual(rules[1].webRoleIds, ['role-a', 'role-b']);
+ assert.equal(diffCategory('webpageRules', rules, rules.slice(1)).status, 'fail');
+ write('webpage-rules\\Orders.webpagerule.yml',
+ 'name: Orders\nright: 2\nwebpageid: orders-id\nscope: 1\nstatecode: 0\n' +
+ 'adx_webpageaccesscontrolrule_webrole:\n- role-a\n- role-b');
+ const diff = diffCategory('webpageRules', rules, run().inventory.webpageRules);
+ assert.equal(diff.status, 'warn');
+ assert.deepEqual(diff.valueChanged.map((change) => change.field), ['right']);
+});
+
+test('malformed nested steps and per-record access rules surface category parse errors', (t) => {
+ const { write, run } = fixture(t);
+ write('advanced-forms\\order\\Order.advancedform.yml', 'adx_name: Order');
+ write('advanced-forms\\order\\advanced-form-steps\\details\\Details.advancedformstep.yml', 'not valid YAML');
+ write('webpage-rules\\Broken.webpagerule.yml', 'not valid YAML');
+ const snapshot = run();
+ assert.equal(snapshot.parseErrors.advancedFormSteps.length, 1);
+ assert.equal(snapshot.parseErrors.webpageRules.length, 1);
+});
diff --git a/plugins/power-pages/scripts/tests/update-state.test.js b/plugins/power-pages/scripts/tests/update-state.test.js
new file mode 100644
index 000000000..a09d88567
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/update-state.test.js
@@ -0,0 +1,336 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { buildInitialState, rebuildPhasesForTrack } = require('../../skills/migrate-datamodel/scripts/lib/migration-state-schema');
+
+const script = path.join(__dirname, '../../skills/migrate-datamodel/scripts/update-state.js');
+const websiteId = '00000000-0000-0000-0000-000000000001';
+const envUrl = 'https://contoso.crm.dynamics.com';
+
+function setup(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-state-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const output = path.join(root, 'demo-env--portal');
+ const args = ['--init', '--output-dir', root, '--website-id', websiteId,
+ '--env-name', 'Demo Env', '--slug', 'portal', '--env-url', envUrl];
+ const run = (extra = [], base = args) => spawnSync(process.execPath, [script, ...base, ...extra], {
+ encoding: 'utf8',
+ });
+ const statePath = path.join(output, 'migration-state.json');
+ return { root, output, args, run, statePath };
+}
+
+test('initial state retains the four-phase authoring workflow', () => {
+ const state = buildInitialState({ webSiteId: websiteId, outputDir: 'migration-reports' });
+ assert.equal(state.track, 'A');
+ assert.deepEqual(state.phases.map((phase) => phase.id), [1, 2, 3, 4]);
+ assert.equal(state.site.environmentUrl, null);
+});
+
+test('switching tracks preserves shared phase progress and rebuilds track-specific phases', () => {
+ const state = buildInitialState({ webSiteId: websiteId, outputDir: 'migration-reports' });
+ const shared = [state.phases[0], state.phases[3]];
+ state.phases[0].subSteps[0].status = 'completed';
+ state.phases[3].subSteps[0].output = 'Existing result';
+ state.phases[1].subSteps[0].status = 'completed';
+ rebuildPhasesForTrack(state, 'B');
+ assert.equal(state.phases[0], shared[0]);
+ assert.equal(state.phases[3], shared[1]);
+ assert.equal(state.phases[1].subSteps.length, 3);
+ assert.equal(state.phases[2].subSteps.length, 6);
+ assert.equal(state.phases[1].subSteps[0].status, 'pending');
+ rebuildPhasesForTrack(state, 'A');
+ assert.equal(state.phases[1].subSteps.length, 4);
+ assert.equal(state.phases[2].subSteps.length, 4);
+ assert.throws(() => rebuildPhasesForTrack(state, 'invalid'), /unknown track/);
+});
+
+test('init records identity and matching resume preserves progress and prints its output directory', (t) => {
+ const fixture = setup(t);
+ const init = fixture.run();
+ assert.equal(init.status, 0, init.stderr);
+ const state = JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ assert.equal(state.site.environmentUrl, envUrl);
+ assert.equal(state.site.slug, 'portal');
+ state.phases[0].subSteps[0].status = 'completed';
+ fs.writeFileSync(fixture.statePath, JSON.stringify(state));
+ const before = fs.readFileSync(fixture.statePath, 'utf8');
+ const resumed = fixture.run();
+ assert.equal(resumed.status, 0, resumed.stderr);
+ assert.match(resumed.stdout, /resume mode/);
+ assert.ok(resumed.stdout.includes(`--output-dir "${fixture.output}"`));
+ assert.equal(fs.readFileSync(fixture.statePath, 'utf8'), before);
+});
+
+test('identity collisions refuse both resume and force reset without changing state', async (t) => {
+ for (const [label, flag, value] of [
+ ['website ID', '--website-id', '00000000-0000-0000-0000-000000000002'],
+ ['environment URL', '--env-url', 'https://fabrikam.crm.dynamics.com'],
+ ['sanitized environment name', '--env-name', 'Demo-Env'],
+ ['sanitized slug', '--slug', 'Portal'],
+ ]) {
+ await t.test(label, (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const before = fs.readFileSync(fixture.statePath, 'utf8');
+ for (const force of [[], ['--force']]) {
+ const result = fixture.run([flag, value, ...force]);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /identity mismatch/);
+ assert.equal(fs.readFileSync(fixture.statePath, 'utf8'), before);
+ }
+ });
+ }
+});
+
+test('unverified legacy environment is not silently resumed', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const state = JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ delete state.site.environmentUrl;
+ fs.writeFileSync(fixture.statePath, JSON.stringify(state));
+ const result = fixture.run();
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /older state without environmentUrl/);
+ const verified = fixture.run([], ['--output-dir', fixture.output, '--set-site',
+ JSON.stringify({ environmentUrl: `${envUrl}/` })]);
+ assert.equal(verified.status, 0, verified.stderr);
+ assert.equal(fixture.run().status, 0);
+});
+
+test('switching tracks preserves shared progress and approval gates', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const before = JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ before.phases[0].subSteps[0].status = 'completed';
+ fs.writeFileSync(fixture.statePath, JSON.stringify(before));
+ const result = fixture.run([], ['--output-dir', fixture.output, '--set-track', 'B']);
+ assert.equal(result.status, 0, result.stderr);
+ const after = JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ assert.equal(after.track, 'B');
+ assert.deepEqual(after.phases.map((phase) => phase.id), [1, 2, 3, 4]);
+ assert.deepEqual(after.phases[0], before.phases[0]);
+ assert.deepEqual(after.phases[3], before.phases[3]);
+ assert.deepEqual(after.approvalGate, before.approvalGate);
+ assert.deepEqual(after.site, before.site);
+});
+
+test('input notices preserve migration gates/progress and clear when the pause resolves', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const run = (args) => {
+ const result = fixture.run([], ['--output-dir', fixture.output, ...args]);
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ };
+ run(['--approve-and-start', '1']);
+ const before = run(['--set-operation', '{"label":"Checking metadata"}']);
+ const waiting = run(['--set-input', JSON.stringify({ requiredAction: ' Provide the Portal ID. ' })]);
+ assert.equal(waiting.pendingInput.requiredAction, 'Provide the Portal ID.');
+ assert.match(waiting.pendingInput.responseLocation, /migration conversation/);
+ assert.equal(waiting.currentOperation, null);
+ assert.deepEqual(waiting.phases, before.phases);
+ assert.deepEqual(waiting.approvalGate, before.approvalGate);
+ assert.deepEqual(waiting.site, before.site);
+ assert.equal(run(['--set-track', 'B']).pendingInput.requiredAction, waiting.pendingInput.requiredAction);
+ assert.equal(run(['--clear-input']).pendingInput, null);
+ assert.equal(run(['--clear-input']).pendingInput, null);
+
+ const pause = () => run(['--set-input', '{"requiredAction":"Confirm restart.","responseLocation":"Migration chat"}']);
+ assert.equal(pause().pendingInput.responseLocation, 'Migration chat');
+ assert.equal(run(['--set-operation', '{"label":"Verifying restart"}']).pendingInput, null);
+ pause();
+ const approval = run(['--set-approval', '2', 'phase-start']);
+ assert.equal(approval.pendingInput, null);
+ assert.equal(approval.currentOperation, null);
+ pause();
+ assert.deepEqual(run(['--clear-input']).approvalGate, approval.approvalGate);
+ pause();
+ assert.equal(run(['--clear-approval']).pendingInput, null);
+ pause();
+ assert.equal(run(['--approve-and-start', '2']).pendingInput, null);
+});
+
+test('invalid input notices cannot replace usable state or report files', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const stateBefore = fs.readFileSync(fixture.statePath, 'utf8');
+ const reportPath = path.join(fixture.output, 'datamodel-migration-report.html');
+ const reportBefore = fs.readFileSync(reportPath, 'utf8');
+ for (const raw of ['{', 'null', '[]', '1', 'true', '""', '{}',
+ '{"requiredAction":null}', '{"requiredAction":" "}', '{"requiredAction":1}',
+ '{"requiredAction":"Confirm.","responseLocation":null}',
+ '{"requiredAction":"Confirm.","responseLocation":" "}']) {
+ const result = fixture.run([], ['--output-dir', fixture.output, '--set-input', raw]);
+ assert.equal(result.status, 1, raw);
+ assert.match(result.stderr, /--set-input|Pending input/);
+ assert.equal(fs.readFileSync(fixture.statePath, 'utf8'), stateBefore);
+ assert.equal(fs.readFileSync(reportPath, 'utf8'), reportBefore);
+ }
+});
+
+test('legacy saved states without pendingInput render and accept new input notices', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const state = JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ delete state.pendingInput;
+ fs.writeFileSync(fixture.statePath, JSON.stringify(state));
+ const result = fixture.run([], ['--output-dir', fixture.output, '--render-only']);
+ assert.equal(result.status, 0, result.stderr);
+ const paused = fixture.run([], ['--output-dir', fixture.output, '--set-input', '{"requiredAction":"Confirm restart."}']);
+ assert.equal(paused.status, 0, paused.stderr);
+});
+
+test('package progress preserves elapsed time and completed metadata while references remain pending', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const run = (args) => {
+ const result = fixture.run([], ['--output-dir', fixture.output, ...args]);
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ };
+ run(['--approve-and-start', '1']);
+ run(['--set-phase', '1', '--status', 'completed']);
+ run(['--set-phase', '2', '--status', 'in-progress']);
+ const before = run(['--set-step', '2.2', '--status', 'completed']);
+ run(['--set-input', '{"requiredAction":"Approve the additional V2 package installation."}']);
+ const label = 'Installing PowerPages_ProgramRegistration_V2';
+ const installing = run(['--set-operation', JSON.stringify({ label, detail: 'Installation in progress.' })]);
+ assert.equal(installing.pendingInput, null);
+ assert.equal(installing.currentOperation.expectedDurationSec, null);
+ assert.equal(installing.currentOperation.poll, null);
+ assert.deepEqual(installing.phases, before.phases);
+ assert.ok(installing.phases[2].subSteps.every((step) => step.status === 'pending'));
+
+ const startedAt = '2026-01-01T12:00:00Z';
+ installing.currentOperation.startedAt = startedAt;
+ fs.writeFileSync(fixture.statePath, JSON.stringify(installing));
+ const verifying = run(['--set-operation', JSON.stringify({ label, detail: 'Installation accepted; verifying installed version.' })]);
+ assert.equal(verifying.currentOperation.startedAt, startedAt);
+ assert.deepEqual(verifying.phases, before.phases);
+ const reportPath = path.join(fixture.output, 'datamodel-migration-report.html');
+ assert.match(fs.readFileSync(reportPath, 'utf8'), /class="now-running-bar-fill now-running-bar-indeterminate"/);
+ assert.equal(run(['--clear-operation']).currentOperation, null);
+ assert.doesNotMatch(fs.readFileSync(reportPath, 'utf8'), /data-now-running data-op-started-at=/);
+});
+
+test('force reset clears generated artifacts but keeps downloaded source and inputs', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const artifacts = [
+ 'sdm-snapshot.json', 'edm-snapshot.json', 'migration-data-diff.json',
+ 'remediation-diff.json', 'customization-report.html', 'customization-assessment.json',
+ 'plugin-remediation-prompt.txt', 'dme-remediation-prompt.txt',
+ 'migration-status.json', 'migration-status.txt',
+ ];
+ for (const name of artifacts) fs.writeFileSync(path.join(fixture.output, name), '{}');
+ fs.mkdirSync(path.join(fixture.output, 'remediation-staged'));
+ fs.writeFileSync(path.join(fixture.output, 'remediation-staged', 'old.html'), 'old proposal');
+ fs.mkdirSync(path.join(fixture.output, 'site'));
+ fs.writeFileSync(path.join(fixture.output, 'site', 'website.yml'), 'source');
+ fs.writeFileSync(path.join(fixture.output, 'SiteCustomization.csv'), 'input');
+ const result = fixture.run(['--force']);
+ assert.equal(result.status, 0, result.stderr);
+ for (const name of [...artifacts, 'remediation-staged']) {
+ assert.equal(fs.existsSync(path.join(fixture.output, name)), false, name);
+ }
+ assert.equal(fs.readFileSync(path.join(fixture.output, 'site', 'website.yml'), 'utf8'), 'source');
+ assert.equal(fs.readFileSync(path.join(fixture.output, 'SiteCustomization.csv'), 'utf8'), 'input');
+ assert.ok(fs.existsSync(path.join(fixture.output, 'datamodel-migration-report.html')));
+});
+
+test('init rejects missing or invalid environment origins before creating artifacts', (t) => {
+ const fixture = setup(t);
+ const missing = fixture.run([], fixture.args.slice(0, -2));
+ assert.equal(missing.status, 1);
+ assert.match(missing.stderr, /requires --env-url/);
+ for (const value of ['http://contoso.crm.dynamics.com', `${envUrl}/api/data`]) {
+ const invalid = fixture.run(['--env-url', value]);
+ assert.equal(invalid.status, 1);
+ assert.match(invalid.stderr, /HTTPS environment origin/);
+ }
+ assert.equal(fs.existsSync(fixture.output), false);
+});
+
+test('missing state reports the correct initialization command', (t) => {
+ const fixture = setup(t);
+ const result = fixture.run([], ['--output-dir', fixture.output, '--render-only']);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /migration-state.json not found/);
+ assert.match(result.stderr, /--env-url <ENV_URL>/);
+ assert.doesNotMatch(result.stderr, /TypeError|Cannot read properties/);
+});
+
+test('malformed state is rejected without replacing the state or report', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const valid = JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ const reportPath = path.join(fixture.output, 'datamodel-migration-report.html');
+ const report = fs.readFileSync(reportPath, 'utf8');
+ for (const invalid of [
+ null, {}, { ...valid, site: null }, { ...valid, phases: null },
+ { ...valid, phases: [null] },
+ { ...valid, phases: [{ id: 1, subSteps: [null] }] },
+ { ...valid, augmentedPrompts: null },
+ ]) {
+ const raw = JSON.stringify(invalid);
+ fs.writeFileSync(fixture.statePath, raw);
+ const result = fixture.run([], ['--output-dir', fixture.output, '--render-only']);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /Invalid migration state/);
+ assert.doesNotMatch(result.stderr, /TypeError|Cannot read properties/);
+ assert.equal(fs.readFileSync(fixture.statePath, 'utf8'), raw);
+ assert.equal(fs.readFileSync(reportPath, 'utf8'), report);
+ }
+});
+
+test('null site patches and null reference tracker entries are rejected before persisting', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const before = fs.readFileSync(fixture.statePath, 'utf8');
+ for (const [flag, payload, expected] of [
+ ['--set-site', null, /expects a JSON object/],
+ ['--set-site', { name: {} }, /name must be a string or null/],
+ ['--set-refs-migration', { runs: [null] }, /runs and chunks entries must be objects/],
+ ['--set-refs-migration', { runs: [{ chunks: [null] }] }, /runs and chunks entries must be objects/],
+ ['--set-refs-migration', { stepHistory: [null] }, /stepHistory entries must be objects/],
+ ]) {
+ const result = fixture.run([], ['--output-dir', fixture.output, flag, JSON.stringify(payload)]);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, expected);
+ assert.doesNotMatch(result.stderr, /TypeError|Cannot read properties/);
+ assert.equal(fs.readFileSync(fixture.statePath, 'utf8'), before);
+ }
+});
+
+test('valid nullable site fields and pending reference runs still render successfully', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const site = fixture.run([], ['--output-dir', fixture.output, '--set-site', '{"name":null,"template":null}']);
+ assert.equal(site.status, 0, site.stderr);
+ const refs = fixture.run([], ['--output-dir', fixture.output, '--set-refs-migration',
+ JSON.stringify({ status: 'Running', runs: [{ name: 'Pending run', chunks: null }], stepHistory: [] })]);
+ assert.equal(refs.status, 0, refs.stderr);
+ const state = JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ assert.equal(state.site.name, null);
+ assert.equal(state.refsMigration.status, 'Running');
+});
+
+test('environment URL can be cleared without bypassing resume identity checks', (t) => {
+ const fixture = setup(t);
+ assert.equal(fixture.run().status, 0);
+ const cleared = fixture.run([], ['--output-dir', fixture.output, '--set-site', '{"environmentUrl":null}']);
+ assert.equal(cleared.status, 0, cleared.stderr);
+ const state = JSON.parse(fs.readFileSync(fixture.statePath, 'utf8'));
+ assert.equal(state.site.environmentUrl, null);
+ const resumed = fixture.run();
+ assert.equal(resumed.status, 1);
+ assert.match(resumed.stderr, /identity mismatch/);
+ const restored = fixture.run([], ['--output-dir', fixture.output, '--set-site',
+ JSON.stringify({ environmentUrl: `${envUrl}/` })]);
+ assert.equal(restored.status, 0, restored.stderr);
+ assert.equal(fixture.run().status, 0);
+});
diff --git a/plugins/power-pages/scripts/tests/validation-helpers.test.js b/plugins/power-pages/scripts/tests/validation-helpers.test.js
index 5ac1adb4b..0f5aec574 100644
--- a/plugins/power-pages/scripts/tests/validation-helpers.test.js
+++ b/plugins/power-pages/scripts/tests/validation-helpers.test.js
@@ -237,6 +237,43 @@ test('findProjectRoot recognizes a direct PAC declarative-site root', (t) => {
assert.equal(resolvePowerPagesSiteRoot(root), path.resolve(root));
});
+test('required metadata roots reject arbitrary paths and accept direct or managed downloads with website.yml', (t) => {
+ const fs = require('fs');
+ const os = require('os');
+ const { requirePowerPagesSiteRoot } = require(helpersPath);
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'required-site-root-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ for (const input of [null, undefined, true, {}, '', ' ']) {
+ assert.throws(() => requirePowerPagesSiteRoot(input), /site path containing website\.yml is required/);
+ }
+ assert.throws(() => requirePowerPagesSiteRoot(root), /Expected a downloaded Power Pages site/);
+ assert.throws(() => requirePowerPagesSiteRoot(path.join(root, 'missing')), /Expected a downloaded Power Pages site/);
+ fs.mkdirSync(path.join(root, '.powerpages-site'));
+ assert.throws(() => requirePowerPagesSiteRoot(root), /Expected a downloaded Power Pages site/);
+ fs.mkdirSync(path.join(root, 'website.yml'));
+ assert.throws(() => requirePowerPagesSiteRoot(root), /Expected a downloaded Power Pages site/);
+ fs.rmdirSync(path.join(root, 'website.yml'));
+ fs.writeFileSync(path.join(root, 'website.yml'), 'adx_name: Direct');
+ assert.equal(requirePowerPagesSiteRoot(root), root);
+ assert.throws(() => requirePowerPagesSiteRoot(path.join(root, 'website.yml')), /Expected a downloaded Power Pages site/);
+ const nested = path.join(root, '.powerpages-site');
+ fs.writeFileSync(path.join(nested, 'website.yml'), 'adx_name: Managed');
+ assert.equal(requirePowerPagesSiteRoot(root), nested);
+ assert.equal(requirePowerPagesSiteRoot(nested), nested);
+});
+
+test('required metadata root validation surfaces inspection errors instead of treating them as empty sites', (t) => {
+ const fs = require('fs');
+ const os = require('os');
+ const { requirePowerPagesSiteRoot } = require(helpersPath);
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'required-site-permission-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ t.mock.method(fs, 'statSync', () => {
+ throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ });
+ assert.throws(() => requirePowerPagesSiteRoot(root), /Could not inspect Power Pages site marker.*permission denied/);
+});
+
test('findProjectRoot: still recognizes powerpages.config.json (SPA sites)', (t) => {
const fs = require('fs');
const os = require('os');
diff --git a/plugins/power-pages/skills/migrate-datamodel/SKILL.md b/plugins/power-pages/skills/migrate-datamodel/SKILL.md
new file mode 100644
index 000000000..d6a797027
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/SKILL.md
@@ -0,0 +1,2012 @@
+---
+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.
diff --git a/plugins/power-pages/skills/migrate-datamodel/assets/customization-report.html b/plugins/power-pages/skills/migrate-datamodel/assets/customization-report.html
new file mode 100644
index 000000000..00dd3abbb
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/assets/customization-report.html
@@ -0,0 +1,153 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Power Pages Migration — Customization Report</title>
+ <style>
+ :root {
+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --surface3:#edebe9;
+ --border:#e1dfdd; --border-light:#c8c6c4;
+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e;
+ --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;
+ --critical:#d13438; --critical-bg:#d134380a; --critical-border:#d1343825;
+ --warning:#ca5010; --warning-bg:#ca50100a; --warning-border:#ca501025;
+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1025;
+ --info:#0078d4; --info-bg:#0078d40a; --info-border:#0078d425;
+ --purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b825;
+ --mono:'Cascadia Code','Consolas',monospace;
+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;
+ --radius:8px; --radius-sm:4px;
+ --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);
+ --shadow-8:0 3.2px 7.2px 0 rgba(0,0,0,0.132),0 0.6px 1.8px 0 rgba(0,0,0,0.108);
+ }
+ * { margin:0; padding:0; box-sizing:border-box; }
+ html { scroll-behavior:smooth; }
+ body { font-family:var(--sans); background:var(--bg); color:var(--text); font-size:14px; line-height:1.6; }
+
+ /* Topbar */
+ .topbar { background:var(--surface); box-shadow:var(--shadow-4); padding:14px 28px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; position:sticky; top:0; z-index:100; }
+ .topbar-title { font-size:16px; font-weight:700; color:var(--text-bright); }
+ .topbar-sub { font-size:11px; color:var(--text-dim); margin-top:1px; }
+ .topbar-right { font-size:12px; color:var(--text-dim); }
+ .topbar-right strong { color:var(--text-bright); font-family:var(--mono); }
+
+ /* Page header */
+ .page-header { background:var(--surface); border-bottom:1px solid var(--border); padding:24px 40px 20px; }
+ .page-header h1 { font-size:24px; font-weight:800; color:var(--text-bright); letter-spacing:-0.3px; margin-bottom:6px; }
+ .page-header .subtitle { font-size:13px; color:var(--text-dim); }
+
+ /* Metadata grid */
+ .metadata { display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:10px; margin-top:18px; }
+ .metadata-item { background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius); padding:12px 14px; }
+ .metadata-label { font-size:10px; font-weight:600; color:var(--text-dim); text-transform:uppercase; letter-spacing:0.6px; margin-bottom:4px; }
+ .metadata-value { color:var(--text-bright); font-size:13px; font-family:var(--mono); word-break:break-all; }
+ .metadata-value.accent { color:var(--accent); font-weight:700; font-size:16px; }
+
+ /* Content container */
+ .content { padding:24px 40px 40px; max-width:1200px; }
+
+ /* Summary card */
+ .summary { background:var(--accent-bg); border:1px solid var(--accent-border); border-left:4px solid var(--accent); border-radius:var(--radius); padding:16px 20px; margin-bottom:24px; }
+ .summary-title { font-weight:700; color:var(--accent); margin-bottom:6px; font-size:14px; }
+ .summary-content { color:var(--text); font-size:13px; line-height:1.65; }
+
+ /* Section card */
+ .customization-section { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); margin-bottom:16px; box-shadow:var(--shadow-4); overflow:hidden; }
+ .section-header { padding:16px 22px; border-bottom:1px solid var(--surface2); display:flex; align-items:center; gap:10px; }
+ .customization-section h2 { color:var(--text-bright); font-size:15px; font-weight:700; flex:1; }
+ .customization-count { display:inline-block; background:var(--accent-bg); color:var(--accent); border:1px solid var(--accent-border); border-radius:3px; padding:2px 9px; font-size:11px; font-weight:700; font-family:var(--mono); }
+
+ /* Table */
+ .customization-table { width:100%; border-collapse:collapse; font-size:13px; }
+ .customization-table thead { background:var(--surface2); }
+ .customization-table th { padding:11px 18px; text-align:left; font-weight:700; color:var(--text-dim); font-size:11px; text-transform:uppercase; letter-spacing:0.5px; border-bottom:1px solid var(--border); }
+ .customization-table td { padding:11px 18px; border-bottom:1px solid var(--surface2); color:var(--text); font-size:13px; vertical-align:top; }
+ .customization-table tbody tr:last-child td { border-bottom:none; }
+ .customization-table tbody tr:hover { background:var(--surface2); }
+
+ /* Snippet (code block) */
+ .snippet { background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius-sm); padding:8px 12px; font-family:var(--mono); font-size:12px; overflow-x:auto; color:var(--text-bright); max-height:140px; overflow-y:auto; white-space:pre-wrap; }
+
+ /* No-data state */
+ .no-data { padding:48px 32px; text-align:center; color:var(--text-dim); background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:var(--shadow-4); }
+ .no-data-icon { font-size:40px; margin-bottom:16px; color:var(--pass); }
+ .no-data h3 { color:var(--text-bright); font-size:18px; font-weight:700; margin-bottom:8px; }
+ .no-data p { color:var(--text-dim); font-size:13px; margin:4px 0; }
+
+ /* Footer */
+ .footer { color:var(--text-dim); font-size:12px; text-align:center; margin-top:32px; padding:18px; border-top:1px solid var(--border); }
+
+ /* Categories identify scan sources, not severity or compatibility. */
+ .badge { display:inline-block; padding:3px 8px; border-radius:3px; font-size:10px; font-weight:700; margin-right:8px; font-family:var(--mono); text-transform:uppercase; letter-spacing:0.5px; }
+ .badge-liquid { color:var(--info); background:var(--info-bg); border:1px solid var(--info-border); }
+ .badge-workflow { color:var(--info); background:var(--info-bg); border:1px solid var(--info-border); }
+ .badge-data-model { color:var(--info); background:var(--info-bg); border:1px solid var(--info-border); }
+ .badge-plugin { color:var(--purple); background:var(--purple-bg); border:1px solid var(--purple-border); }
+ .badge-fetchxml { color:var(--info); background:var(--info-bg); border:1px solid var(--info-border); }
+
+ /* Status badges (deprecated; legacy callers) */
+ .status-badge { padding:5px 10px; border-radius:var(--radius-sm); font-size:11px; font-weight:700; display:inline-block; font-family:var(--mono); text-transform:uppercase; }
+ .status-completed { color:var(--pass); background:var(--pass-bg); border:1px solid var(--pass-border); }
+ .status-warning { color:var(--warning); background:var(--warning-bg); border:1px solid var(--warning-border); }
+ .status-error { color:var(--critical); background:var(--critical-bg); border:1px solid var(--critical-border); }
+ </style>
+</head>
+<body>
+ <div class="topbar">
+ <div>
+ <div class="topbar-title">SDM → EDM Migration</div>
+ <div class="topbar-sub">Customization Report</div>
+ </div>
+ <div class="topbar-right">Generated <strong>{{REPORT_DATE}}</strong></div>
+ </div>
+
+ <div class="page-header">
+ <h1>Site Customization Report</h1>
+ <div class="subtitle">SDM to EDM migration analysis · {{SITE_NAME}}</div>
+
+ <div class="metadata">
+ <div class="metadata-item">
+ <div class="metadata-label">Site Name</div>
+ <div class="metadata-value">{{SITE_NAME}}</div>
+ </div>
+ <div class="metadata-item">
+ <div class="metadata-label">Website ID</div>
+ <div class="metadata-value">{{WEBSITE_ID}}</div>
+ </div>
+ <div class="metadata-item">
+ <div class="metadata-label">Template</div>
+ <div class="metadata-value">{{TEMPLATE_NAME}}</div>
+ </div>
+ <div class="metadata-item">
+ <div class="metadata-label">Current Model</div>
+ <div class="metadata-value">Standard Data Model (SDM)</div>
+ </div>
+ <div class="metadata-item">
+ <div class="metadata-label">Report Generated</div>
+ <div class="metadata-value">{{REPORT_DATE}}</div>
+ </div>
+ <div class="metadata-item">
+ <div class="metadata-label">Total Customizations Found</div>
+ <div class="metadata-value accent">{{TOTAL_CUSTOMIZATIONS}}</div>
+ </div>
+ </div>
+ </div>
+
+ <div class="content">
+ <div class="summary">
+ <div class="summary-title">What does this report mean?</div>
+ <div class="summary-content">
+ {{SUMMARY_TEXT}}
+ </div>
+ </div>
+
+ {{CUSTOMIZATIONS_SECTIONS}}
+
+ <div class="footer">
+ <p>Generated by Power Pages Migration Tool · Report created on {{REPORT_DATE}}</p>
+ <p>AI-generated content may be incorrect</p>
+ </div>
+ </div>
+</body>
+</html>
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/apply-remediation.js b/plugins/power-pages/skills/migrate-datamodel/scripts/apply-remediation.js
new file mode 100644
index 000000000..19118bcf9
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/apply-remediation.js
@@ -0,0 +1,251 @@
+#!/usr/bin/env node
+
+/**
+ * apply-remediation.js
+ *
+ * Applies the staged remediation produced by `generate-migration-reports.js`
+ * (with `--automate-fetchxml` and/or `--automate-liquid`) to the live site
+ * source. The skill calls this AFTER the user has reviewed the Remediation
+ * Diff card in the live execution report and explicitly approved the upload.
+ *
+ * Usage:
+ * node apply-remediation.js --output-dir "./migration-reports" --site-root "./mysite/contoso/"
+ * node apply-remediation.js --output-dir "./migration-reports" --site-root "./mysite/contoso/" --discard
+ * node apply-remediation.js --output-dir "./migration-reports" --dry-run
+ *
+ * Behavior:
+ * - Reads `<output-dir>/remediation-diff.json` (errors if absent).
+ * - For each entry, copies `<output-dir>/remediation-staged/<relativePath>`
+ * over `<site-root>/<relativePath>`. mkdir -p any missing parents.
+ * - Rejects linked descendants; restores originals on caught copy failures.
+ * Do not edit either tree concurrently. This is not crash-safe recovery.
+ * - On success, deletes the staged tree and diff manifest (unless --keep-staged).
+ * - --discard: skip the copy, just delete the staged dir (used on cancel).
+ * - --dry-run: print what would happen, touch nothing.
+ *
+ * Exit codes: 0 = ok, 2 = bad usage, 3 = nothing-to-apply,
+ * 4 = invalid manifest, missing staged file, or copy error.
+ */
+
+const fs = require('fs');
+const path = require('path');
+const { requirePowerPagesSiteRoot } = require('../../../scripts/lib/validation-helpers');
+
+function parseArgs(argv) {
+ const out = {};
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (!a.startsWith('--')) continue;
+ const key = a.slice(2);
+ const next = argv[i + 1];
+ if (next == null || next.startsWith('--')) {
+ out[key] = true;
+ } else {
+ out[key] = next;
+ i++;
+ }
+ }
+ return out;
+}
+
+function rmRecursive(p) {
+ if (!fs.existsSync(p)) return;
+ fs.rmSync(p, { recursive: true, force: true });
+}
+
+function validatePath(root, relativePath) {
+ const relative = path.relative(root, path.resolve(root, relativePath));
+ if (path.isAbsolute(relativePath) || !relative || path.isAbsolute(relative) ||
+ relative === '..' || relative.startsWith(`..${path.sep}`)) {
+ throw new Error(`Remediation path must stay inside the staged and site roots: ${relativePath}`);
+ }
+ // Lexical containment alone permits "link/page.html" to traverse a junction.
+ // Reject linked roots/descendants, including dangling links, without following them.
+ let current = root;
+ for (const part of ['', ...relative.split(path.sep)]) {
+ current = path.join(current, part);
+ let stat;
+ try {
+ stat = fs.lstatSync(current);
+ } catch (error) {
+ if (error.code === 'ENOENT') break;
+ throw error;
+ }
+ if (stat.isSymbolicLink()) {
+ throw new Error(`Remediation path contains a symbolic link or junction: ${current}`);
+ }
+ if (stat.isFile() && stat.nlink > 1) {
+ throw new Error(`Remediation path contains a hard-linked file: ${current}`);
+ }
+ if (current !== path.join(root, relative) && !stat.isDirectory()) {
+ throw new Error(`Remediation parent is not a directory: ${current}`);
+ }
+ }
+ return path.join(root, relative);
+}
+
+function main() {
+ const args = parseArgs(process.argv.slice(2));
+ const outputDir = args['output-dir'];
+ const siteRoot = args['site-root'];
+ const discard = !!args['discard'];
+ const dryRun = !!args['dry-run'];
+ const keepStaged = !!args['keep-staged'];
+
+ if (!outputDir) {
+ console.error('Error: --output-dir is required');
+ process.exit(2);
+ }
+ if (!discard && !siteRoot) {
+ console.error('Error: --site-root is required (omit only when --discard is set)');
+ process.exit(2);
+ }
+
+ const diffPath = path.join(outputDir, 'remediation-diff.json');
+ const stagedDir = path.join(outputDir, 'remediation-staged');
+
+ if (!fs.existsSync(diffPath)) {
+ console.log(`No remediation-diff.json at ${diffPath} — nothing to apply.`);
+ process.exit(3);
+ }
+
+ if (discard) {
+ if (dryRun) {
+ console.log(`[dry-run] Would delete staged tree: ${stagedDir}`);
+ console.log(`[dry-run] Would delete diff manifest: ${diffPath}`);
+ return;
+ }
+ rmRecursive(stagedDir);
+ fs.unlinkSync(diffPath);
+ console.log('✓ Discarded staged remediation. Live source was never touched.');
+ return;
+ }
+
+ const payload = JSON.parse(fs.readFileSync(diffPath, 'utf-8'));
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload) || !Array.isArray(payload.files)) {
+ throw new Error('remediation-diff.json must contain an object with a files array');
+ }
+ const files = payload.files;
+ if (typeof payload.siteRoot !== 'string' || !path.isAbsolute(payload.siteRoot)) {
+ throw new Error('remediation-diff.json must contain an absolute siteRoot');
+ }
+ const liveRoot = fs.realpathSync(requirePowerPagesSiteRoot(siteRoot));
+ if (liveRoot !== fs.realpathSync(payload.siteRoot)) {
+ throw new Error('Selected site root does not match the remediation manifest siteRoot');
+ }
+ const targets = new Set();
+ const plan = files.map((entry) => {
+ if (!entry || typeof entry !== 'object' || typeof entry.relativePath !== 'string' ||
+ entry.relativePath.trim() === '') {
+ throw new Error('Every remediation file entry must contain a non-empty relativePath string');
+ }
+ const stagedPath = validatePath(path.resolve(stagedDir), entry.relativePath);
+ const livePath = validatePath(liveRoot, entry.relativePath);
+ const identity = process.platform === 'win32' ? livePath.toLowerCase() : livePath;
+ if (targets.has(identity)) {
+ throw new Error(`Duplicate remediation destination: ${entry.relativePath}`);
+ }
+ targets.add(identity);
+ if (!fs.existsSync(stagedPath) || !fs.statSync(stagedPath).isFile()) {
+ throw new Error(`Staged file missing or not a file: ${stagedPath}`);
+ }
+ if (fs.existsSync(livePath) && !fs.statSync(livePath).isFile()) {
+ throw new Error(`Live destination is not a file: ${livePath}`);
+ }
+ return { relativePath: entry.relativePath, from: stagedPath, to: livePath };
+ });
+
+ if (files.length === 0) {
+ console.log('Remediation diff manifest contains zero files — nothing to apply.');
+ if (!keepStaged) rmRecursive(stagedDir);
+ process.exit(3);
+ }
+
+ if (dryRun) {
+ for (const { from, to } of plan) {
+ console.log(`[dry-run] ${from} → ${to}`);
+ }
+ console.log(`\n[dry-run] Would apply ${plan.length}/${files.length} file(s)` +
+ (keepStaged ? '; staged tree and diff manifest retained.' : ` and delete ${stagedDir} and ${diffPath}.`));
+ return;
+ }
+
+ // Read every original before the first write. Include a failed copy in rollback:
+ // copyFileSync can truncate its destination before reporting a disk/I/O failure.
+ for (const entry of plan) {
+ entry.original = fs.existsSync(entry.to) ? fs.readFileSync(entry.to) : null;
+ entry.mode = entry.original !== null ? fs.statSync(entry.to).mode : null;
+ }
+ // Keep a disk copy too: if restoration itself fails, exiting must not destroy
+ // the only remaining original bytes. The index records files that were absent.
+ const backupDir = fs.mkdtempSync(path.join(path.resolve(outputDir), 'remediation-backup-'));
+ try {
+ for (const [index, entry] of plan.entries()) {
+ entry.backupFile = entry.original === null ? null : `${index}.bin`;
+ if (entry.backupFile) fs.writeFileSync(path.join(backupDir, entry.backupFile), entry.original);
+ }
+ fs.writeFileSync(path.join(backupDir, 'manifest.json'), JSON.stringify({
+ siteRoot: liveRoot,
+ files: plan.map(({ relativePath, mode, backupFile }) => ({ relativePath, mode, backupFile })),
+ }, null, 2));
+ } catch (error) {
+ throw new Error(`Could not prepare backup at ${backupDir}: ${error.message}. No live files changed.`);
+ }
+ const touched = [];
+ const createdDirectories = new Set();
+ try {
+ for (const entry of plan) {
+ validatePath(path.resolve(stagedDir), entry.relativePath);
+ validatePath(liveRoot, entry.relativePath);
+ for (let dir = path.dirname(entry.to); !fs.existsSync(dir); dir = path.dirname(dir)) {
+ createdDirectories.add(dir);
+ }
+ fs.mkdirSync(path.dirname(entry.to), { recursive: true });
+ validatePath(liveRoot, entry.relativePath);
+ touched.push(entry);
+ fs.copyFileSync(entry.from, entry.to);
+ }
+ } catch (error) {
+ const rollbackErrors = [];
+ for (const entry of touched.reverse()) {
+ try {
+ validatePath(liveRoot, entry.relativePath);
+ if (entry.original === null) {
+ if (fs.existsSync(entry.to)) fs.unlinkSync(entry.to);
+ } else {
+ fs.writeFileSync(entry.to, entry.original);
+ fs.chmodSync(entry.to, entry.mode);
+ }
+ } catch (rollbackError) {
+ rollbackErrors.push(`${entry.relativePath}: ${rollbackError.message}`);
+ }
+ }
+ for (const dir of [...createdDirectories].sort((a, b) => b.length - a.length)) {
+ try {
+ validatePath(liveRoot, path.relative(liveRoot, dir));
+ fs.rmdirSync(dir);
+ } catch (rollbackError) {
+ if (rollbackError.code !== 'ENOENT') rollbackErrors.push(`${dir}: ${rollbackError.message}`);
+ }
+ }
+ throw new Error(`Apply failed: ${error.message}. ` +
+ (rollbackErrors.length
+ ? `Rollback incomplete; manual recovery required:\n${rollbackErrors.join('\n')}`
+ : 'Original files restored.') +
+ `\nRecovery backup retained at ${backupDir}.\nStaged remediation and manifest retained.`);
+ }
+
+ rmRecursive(backupDir);
+ if (!keepStaged) {
+ rmRecursive(stagedDir);
+ fs.unlinkSync(diffPath);
+ }
+ console.log(`\n✓ Applied ${plan.length}/${files.length} remediation file(s) to ${siteRoot}.`);
+}
+
+try {
+ main();
+} catch (error) {
+ console.error(`Error: ${error.message}`);
+ process.exit(4);
+}
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/detect-template.js b/plugins/power-pages/skills/migrate-datamodel/scripts/detect-template.js
new file mode 100644
index 000000000..6dde6402a
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/detect-template.js
@@ -0,0 +1,283 @@
+#!/usr/bin/env node
+'use strict';
+
+// Detects the Power Pages template a downloaded SDM site was created from, so the
+// migration can ensure the matching Enhanced (V2) solution is installed.
+//
+// Two indicators, resolved in order:
+// 1. Site inspection — identifies the three D365 portals that ship distinctive
+// built-in components (Community, Employee Self-Service, Partner)
+// directly from the downloaded site source.
+// 2. Installed anchor solution — the template ("anchor") solution present in the
+// environment is the source of truth. Covers Customer
+// Self-Service + the medium templates (FAQ, Building Permit,
+// Program Registration, Book Meeting), and confirms/overrides
+// the site-inspection result for the D365 portals.
+//
+// If neither indicator resolves a template, the site is treated as low-complexity
+// (Blank / Starter Layout) and no template package is installed.
+//
+// Usage:
+// node detect-template.js --site-root <path-to-downloaded-sdm-site>
+// [--solutions "<comma,separated,uniquenames>"]
+// [--solutions-file <path-to-pac-solution-list-output>]
+// [--pretty]
+//
+// Output: JSON resolution to stdout. Exit 0 on success, 1 on failure.
+
+const fs = require('fs');
+const path = require('path');
+const { requirePowerPagesSiteRoot } = require('../../../scripts/lib/validation-helpers');
+const { parseTopLevelSequence } = require('../../../scripts/lib/non-spa-metadata');
+const { loadYamlRecordsWithErrors, WEB_ROLE_FILE_SUFFIX } = require('../../../scripts/lib/powerpages-config');
+
+// D365 portals — have a site-inspection signal (except CSS) AND an anchor solution.
+const D365 = {
+ Community: { anchor: 'CommunityPortal', v2: 'PowerPages_CommunityPortal_V2', label: 'Community Portal' },
+ CustomerSelfService: { anchor: 'CustomerPortal', v2: 'PowerPages_CustomerPortal_V2', label: 'Customer Self-Service Portal' },
+ EmployeeSelfService: { anchor: 'ESSPortal', v2: 'PowerPages_ESSPortal_V2', label: 'Employee Self-Service Portal' },
+ Partner: { anchor: 'PartnerPortal', v2: 'PowerPages_PartnerPortal_V2', label: 'Partner Portal' },
+};
+
+// Medium templates — no reliable site-inspection signal; detected by anchor solution only.
+const MEDIUM = {
+ FAQ: { anchor: 'PowerPages_FAQ', v2: 'PowerPages_FAQ_V2', label: 'FAQ' },
+ ScheduleManageMeetings: { anchor: 'PowerPortals_BookMeeting', v2: 'PowerPages_BookMeeting_V2', label: 'Schedule and Manage Meetings' },
+ ApplicationProcessing: { anchor: 'PowerPages_BuildingPermit', v2: 'PowerPages_BuildingPermit_V2', label: 'Application Processing (Building Permit)' },
+ ProgramRegistration: { anchor: 'PowerPortals_ProgramRegistrationCore', v2: 'PowerPages_ProgramRegistration_V2', label: 'Program Registration' },
+};
+
+// D365 anchor solutions (for the anchor-primary resolution of Community/ESS/Partner).
+const D365_ANCHORS = Object.values(D365).map((t) => t.anchor);
+
+// "Group B" anchors — detected purely by installed solution: CSS + all medium templates.
+const GROUP_B_ANCHORS = [
+ D365.CustomerSelfService.anchor,
+ ...Object.values(MEDIUM).map((t) => t.anchor),
+];
+
+function parseArgs(argv) {
+ const out = { siteRoot: null, solutions: [], solutionsFile: null, pretty: false };
+ const args = argv.slice(2);
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--site-root' && args[i + 1]) out.siteRoot = args[++i];
+ else if (args[i] === '--solutions' && args[i + 1]) {
+ out.solutions = args[++i].split(',').map((s) => s.trim()).filter(Boolean);
+ } else if (args[i] === '--solutions-file' && args[i + 1]) out.solutionsFile = args[++i];
+ else if (args[i] === '--pretty') out.pretty = true;
+ }
+ return out;
+}
+
+function readText(file, required = false) {
+ try {
+ const bytes = fs.readFileSync(file);
+ // Windows PowerShell Out-File writes FF FE + UTF-16LE by default; PAC's
+ // Node capture writes UTF-8. Honor the BOM instead of matching NUL-separated names.
+ if (bytes[0] === 0xff && bytes[1] === 0xfe) return bytes.subarray(2).toString('utf16le');
+ if (bytes[0] === 0xfe && bytes[1] === 0xff) return bytes.subarray(2).swap16().toString('utf16le');
+ return bytes.toString('utf8').replace(/^\uFEFF/, '');
+ } catch (error) {
+ if (!required && error.code === 'ENOENT') return '';
+ throw new Error(`Could not read template detection input ${file}: ${error.message}`);
+ }
+}
+
+function dirExists(p) {
+ try {
+ return fs.statSync(p).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Site inspection — returns the D365 portal recognizable from distinctive built-in
+ * components, or null. Order matters: Partner (keyed roles) is the most specific.
+ */
+function inspectSite(siteRoot) {
+ const signals = [];
+
+ // PAC exports webrole.yml sequences and web-roles/*.webrole.yml mappings.
+ // Merge both so a per-record or mixed export cannot hide template signals.
+ const webRoleFile = path.join(siteRoot, 'webrole.yml');
+ const { records, errors } = loadYamlRecordsWithErrors(path.join(siteRoot, 'web-roles'), WEB_ROLE_FILE_SUFFIX);
+ if (errors.length) {
+ throw new Error(`Could not read template detection web roles: ${errors.map(({ message }) => message).join('\n')}`);
+ }
+ const webRoles = [...parseTopLevelSequence(readText(webRoleFile), webRoleFile), ...records];
+
+ // Partner — dedicated partner web roles with fixed keys (stable across installs).
+ if (webRoles.some((role) => /^(partneradmin|partnermanager|partnerseller|nonpartneruser)$/i.test(role.adx_key ?? role.key ?? ''))) {
+ signals.push('partner web roles (partneradmin / partnermanager / partnerseller / nonpartneruser)');
+ return { match: 'Partner', signals };
+ }
+
+ // Community — blog AND idea web pages (use web-pages/ nodes, NOT the root blogs/
+ // folder, which every exported site has as record scaffolding).
+ const webPages = path.join(siteRoot, 'web-pages');
+ if (dirExists(path.join(webPages, 'blogs')) && dirExists(path.join(webPages, 'ideas'))) {
+ signals.push('web-pages/blogs and web-pages/ideas present');
+ return { match: 'Community', signals };
+ }
+ if (webRoles.some((role) => /^Blog Authors$/i.test(role.adx_name ?? role.name ?? '')) && dirExists(path.join(webPages, 'blogs'))) {
+ signals.push('"Blog Authors" web role with blog pages');
+ return { match: 'Community', signals };
+ }
+
+ // Employee Self-Service — license-specific access-denied page/marker.
+ const sitemarker = readText(path.join(siteRoot, 'sitemarker.yml'));
+ if (
+ /adx_name:\s*Access Denied - Missing License\b/i.test(sitemarker) ||
+ dirExists(path.join(webPages, 'access-denied---missing-license'))
+ ) {
+ signals.push('"Access Denied - Missing License" site marker / page');
+ return { match: 'EmployeeSelfService', signals };
+ }
+
+ return { match: null, signals };
+}
+
+function loadInstalledSolutions(opts) {
+ const found = new Set(opts.solutions.map((s) => s));
+ if (opts.solutionsFile) {
+ const text = readText(opts.solutionsFile, true);
+ // Scan for each known anchor uniquename regardless of pac output formatting.
+ const known = [...D365_ANCHORS, ...GROUP_B_ANCHORS];
+ for (const name of known) {
+ const re = new RegExp(`(^|[^A-Za-z0-9_])${name}([^A-Za-z0-9_]|$)`, 'm');
+ if (re.test(text)) found.add(name);
+ }
+ }
+ return [...found];
+}
+
+function anchorToTemplate(anchor) {
+ const all = { ...D365, ...MEDIUM };
+ for (const [key, val] of Object.entries(all)) {
+ if (val.anchor.toLowerCase() === String(anchor).toLowerCase()) return { key, ...val };
+ }
+ return null;
+}
+
+function resolve(inspection, installed) {
+ const installedLc = new Set(installed.map((s) => s.toLowerCase()));
+ const has = (u) => installedLc.has(String(u).toLowerCase());
+
+ const d365Present = D365_ANCHORS.filter(has);
+ const groupBPresent = GROUP_B_ANCHORS.filter(has);
+
+ if (inspection.match) {
+ const pos = D365[inspection.match];
+
+ // Exactly one D365 anchor present — anchor wins even if it disagrees with inspection.
+ if (d365Present.length === 1) {
+ const t = anchorToTemplate(d365Present[0]);
+ const agrees = d365Present[0].toLowerCase() === pos.anchor.toLowerCase();
+ return {
+ decision: 'install-v2',
+ template: t.label,
+ templateKey: t.key,
+ v1Anchor: t.anchor,
+ v2Package: t.v2,
+ method: 'site-inspection + single installed anchor (anchor authoritative)',
+ agreement: agrees ? 'inspection and anchor agree' : `anchor overrides inspection (inspection suggested ${pos.label})`,
+ needsPrompt: false,
+ };
+ }
+
+ // Multiple D365 anchors present — site inspection breaks the tie.
+ if (d365Present.length >= 2) {
+ if (d365Present.some((a) => a.toLowerCase() === pos.anchor.toLowerCase())) {
+ return {
+ decision: 'install-v2',
+ template: pos.label,
+ templateKey: inspection.match,
+ v1Anchor: pos.anchor,
+ v2Package: pos.v2,
+ method: 'multiple anchors present; site inspection broke the tie',
+ needsPrompt: false,
+ };
+ }
+ return {
+ decision: 'prompt-pick',
+ needsPrompt: true,
+ promptReason: 'multiple template solutions installed and none match the site',
+ candidates: d365Present.map(anchorToTemplate),
+ };
+ }
+
+ // No D365 anchor installed — confirm with the user before installing.
+ return {
+ decision: 'prompt-confirm',
+ needsPrompt: true,
+ promptReason: `the site looks like ${pos.label}, but its template solution is not installed in this environment`,
+ confirmTemplate: pos.label,
+ confirmTemplateKey: inspection.match,
+ v1Anchor: pos.anchor,
+ v2Package: pos.v2,
+ onConfirm: { decision: 'install-v2', v2Package: pos.v2 },
+ onDecline: { decision: 'low-complexity-skip' },
+ };
+ }
+
+ // No positive site inspection — decide purely by installed anchor solution.
+ if (groupBPresent.length === 1) {
+ const t = anchorToTemplate(groupBPresent[0]);
+ return {
+ decision: 'install-v2',
+ template: t.label,
+ templateKey: t.key,
+ v1Anchor: t.anchor,
+ v2Package: t.v2,
+ method: 'installed anchor solution (single)',
+ needsPrompt: false,
+ };
+ }
+ if (groupBPresent.length >= 2) {
+ return {
+ decision: 'prompt-pick-or-install-all',
+ needsPrompt: true,
+ promptReason: 'multiple template solutions are installed and the site is not distinctive',
+ candidates: groupBPresent.map(anchorToTemplate),
+ };
+ }
+
+ return {
+ decision: 'low-complexity-skip',
+ needsPrompt: false,
+ template: 'Low-complexity (Blank Page / Starter Layout)',
+ v2Package: null,
+ method: 'no template anchor solution present',
+ };
+}
+
+function main() {
+ const opts = parseArgs(process.argv);
+ if (!opts.siteRoot) {
+ process.stderr.write('ERROR: --site-root is required\n');
+ process.exit(1);
+ }
+ opts.siteRoot = requirePowerPagesSiteRoot(opts.siteRoot);
+ const inspection = inspectSite(opts.siteRoot);
+ const installed = loadInstalledSolutions(opts);
+ const resolution = resolve(inspection, installed);
+
+ const result = {
+ siteRoot: opts.siteRoot,
+ inspection,
+ installedAnchors: installed,
+ resolution,
+ };
+
+ process.stdout.write(JSON.stringify(result, null, opts.pretty ? 2 : 0) + '\n');
+}
+
+if (require.main === module) {
+ try { main(); } catch (error) {
+ process.stderr.write(`ERROR: ${error.message}\n`);
+ process.exitCode = 1;
+ }
+}
+
+module.exports = { resolve, inspectSite, loadInstalledSolutions };
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/diff-snapshots.js b/plugins/power-pages/skills/migrate-datamodel/scripts/diff-snapshots.js
new file mode 100644
index 000000000..5b435f3db
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/diff-snapshots.js
@@ -0,0 +1,375 @@
+#!/usr/bin/env node
+/**
+ * diff-snapshots.js
+ *
+ * Compares an SDM snapshot and an EDM snapshot (produced by snapshot-site.js)
+ * and classifies the differences per category. Output is purely informational
+ * — the skill never auto-rolls-back based on this diff. The user reviews and
+ * decides.
+ *
+ * USAGE
+ * node 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
+ *
+ * Per-category classification:
+ * pass — same identity set, same statecode normalization, same content hash
+ * (if applicable)
+ * warn — identity set matches, but some records changed statecode or content
+ * fail — at least one record present in SDM is missing from EDM, or extra
+ * records appeared in EDM, or counts differ
+ */
+
+const fs = require('fs');
+const path = require('path');
+const {
+ NONCONFIGURATION_CATEGORIES,
+ SDM_ONLY_CATEGORIES,
+ getCategoryMetadata,
+} = require('./lib/edm-table-classification');
+
+function parseArgs(argv) {
+ const out = {};
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a.startsWith('--')) {
+ const k = a.slice(2);
+ const next = argv[i + 1];
+ if (next === undefined || next.startsWith('--')) out[k] = true;
+ else { out[k] = next; i += 1; }
+ }
+ }
+ return out;
+}
+
+// Identity key fields per category. The diff pairs SDM and EDM records by
+// constructing a string from these fields. Choose Dataverse-side fields
+// (adx_name, partialUrl, language) — never the PAC-derived `slug`, which is
+// only a folder name and could theoretically drift between PAC versions.
+const KEY_FIELDS = {
+ webPages: ['kind', 'name', 'partialUrl', 'language'],
+ contentSnippets: ['name', 'language'],
+ webLinkSets: ['name', 'language'],
+ webLinks: ['parentSet', 'name', 'language'],
+ webTemplates: ['name'],
+ webFiles: ['name', 'partialUrl'],
+ pageTemplates: ['name'],
+ tablePermissions: ['name', 'permissionName'],
+ basicForms: ['name'],
+ advancedForms: ['name'],
+ advancedFormSteps: ['parentForm', 'name'],
+ lists: ['name'],
+ polls: ['name'],
+ pollPlacements: ['name'],
+ cloudFlowConsumers: ['name'],
+ columnPermissionProfiles: ['name'],
+ siteSettings: ['name'],
+ webRoles: ['name'],
+ siteMarkers: ['name'],
+ websiteAccesses: ['name'],
+ publishingStates: ['name'],
+ webpageRules: ['name'],
+ websiteBindings: ['name'],
+ websiteLanguages: ['name'],
+ ads: ['name'],
+ adPlacements: ['name'],
+ tags: ['name'],
+ urlHistory: ['name'],
+};
+
+// Categories where the diff should also compare a value field (in addition to
+// identity), because the value carries operational meaning. siteSettings is
+// the classic case: same setting key, but the value changed, is interesting.
+const VALUE_FIELDS = {
+ siteSettings: ['value'],
+ webLinks: ['pageId', 'externalUrl', 'displayOrder'],
+ advancedFormSteps: ['formId', 'type', 'targetEntity', 'nextStepId'],
+ webpageRules: ['pageId', 'right', 'scope', 'webRoleIds'],
+};
+
+function makeKey(rec, fields) {
+ return JSON.stringify(fields.map((f) => String(rec[f] ?? '')));
+}
+
+// Treat null and 0 as equivalent: PAC only writes statecode for inactive
+// records, so an active record can show up as either null (omitted) or 0
+// depending on the data model version's serialization.
+function normalizeStateCode(v) {
+ if (v == null) return 0;
+ return v;
+}
+
+function diffCategory(category, sdmInventory, edmInventory) {
+ if (NONCONFIGURATION_CATEGORIES.has(category)) {
+ const metadata = getCategoryMetadata(category);
+ return {
+ status: 'excluded',
+ scope: 'nonconfiguration',
+ reason: metadata.reason,
+ sdmCount: sdmInventory.length,
+ edmCount: edmInventory.length,
+ missingInEdm: [],
+ extraInEdm: [],
+ stateChanged: [],
+ contentChanged: [],
+ valueChanged: [],
+ sdmOnlyCategory: false,
+ };
+ }
+
+ const keyFields = KEY_FIELDS[category] || ['name'];
+ const valueFields = VALUE_FIELDS[category] || [];
+
+ // Duplicate logical identities cannot be paired reliably. Do not silently
+ // overwrite them, even when both downloads contain the same record count.
+ const duplicateKeys = { sdm: [], edm: [] };
+ function index(records, duplicates) {
+ const map = new Map();
+ for (const rec of records) {
+ const key = makeKey(rec, keyFields);
+ if (map.has(key)) duplicates.push(key);
+ else map.set(key, rec);
+ }
+ return map;
+ }
+ const sdmMap = index(sdmInventory, duplicateKeys.sdm);
+ const edmMap = index(edmInventory, duplicateKeys.edm);
+
+ const missingInEdm = []; // present in SDM, not in EDM
+ const extraInEdm = []; // present in EDM, not in SDM
+ const stateChanged = []; // present in both, but statecode differs
+ const contentChanged = []; // includes a companion file/hash missing on only one side
+ const valueChanged = []; // present in both, but value field differs (siteSettings)
+
+ for (const [key, sdmRec] of sdmMap) {
+ const edmRec = edmMap.get(key);
+ if (!edmRec) {
+ missingInEdm.push(sdmRec);
+ continue;
+ }
+ if (normalizeStateCode(sdmRec.stateCode) !== normalizeStateCode(edmRec.stateCode)) {
+ stateChanged.push({ key, sdmStateCode: sdmRec.stateCode, edmStateCode: edmRec.stateCode, record: sdmRec });
+ }
+ if ((sdmRec.contentHash ?? null) !== (edmRec.contentHash ?? null)) {
+ contentChanged.push({ key, sdmHash: sdmRec.contentHash, edmHash: edmRec.contentHash, record: sdmRec });
+ }
+ for (const valueField of valueFields) {
+ const sdmVal = sdmRec[valueField];
+ const edmVal = edmRec[valueField];
+ if (String(sdmVal ?? '') !== String(edmVal ?? '')) {
+ valueChanged.push({ key, field: valueField, sdmValue: sdmVal, edmValue: edmVal });
+ }
+ }
+ }
+ for (const [key, edmRec] of edmMap) {
+ if (!sdmMap.has(key)) extraInEdm.push(edmRec);
+ }
+
+ const sdmCount = sdmInventory.length;
+ const edmCount = edmInventory.length;
+
+ // SDM-only categories: when EDM count is 0 but SDM had records, treat as
+ // `warn` (expected-difference) rather than `fail`. The records still exist
+ // as `powerpagecomponent` rows in Dataverse — they're just not surfaced by
+ // the EDM YAML download format. Real failures (count mismatches that aren't
+ // "everything missing") still classify as `fail`.
+ const isSdmOnlyDifference = (
+ SDM_ONLY_CATEGORIES.has(category) &&
+ edmCount === 0 &&
+ sdmCount > 0 &&
+ extraInEdm.length === 0
+ );
+
+ let status = 'pass';
+ if (duplicateKeys.sdm.length > 0 || duplicateKeys.edm.length > 0) {
+ status = 'fail';
+ } else if (isSdmOnlyDifference) {
+ status = 'warn';
+ } else if (missingInEdm.length > 0 || extraInEdm.length > 0 || sdmCount !== edmCount) {
+ status = 'fail';
+ } else if (stateChanged.length > 0 || contentChanged.length > 0 || valueChanged.length > 0) {
+ status = 'warn';
+ }
+
+ return {
+ status,
+ scope: SDM_ONLY_CATEGORIES.has(category) ? 'sdm-only-download' : 'metadata',
+ sdmCount,
+ edmCount,
+ missingInEdm,
+ extraInEdm,
+ stateChanged,
+ contentChanged,
+ valueChanged,
+ duplicateKeys,
+ sdmOnlyCategory: SDM_ONLY_CATEGORIES.has(category),
+ };
+}
+
+function summarize(diff) {
+ let totalSdm = 0, totalEdm = 0, totalMissing = 0, totalExtra = 0, totalStateChanged = 0, totalContentChanged = 0, totalValueChanged = 0;
+ for (const c of Object.values(diff.categories)) {
+ if (c.status === 'excluded') continue;
+ totalSdm += c.sdmCount;
+ totalEdm += c.edmCount;
+ totalMissing += c.missingInEdm.length;
+ totalExtra += c.extraInEdm.length;
+ totalStateChanged += c.stateChanged.length;
+ totalContentChanged += c.contentChanged.length;
+ totalValueChanged += c.valueChanged.length;
+ }
+ return { totalSdm, totalEdm, totalMissing, totalExtra, totalStateChanged, totalContentChanged, totalValueChanged };
+}
+
+function describeRecord(rec, keyFields) {
+ const parts = keyFields.map((f) => rec[f] != null ? `${f}=${rec[f]}` : null).filter(Boolean);
+ return parts.join(', ') || JSON.stringify(rec);
+}
+
+function statusGlyph(status) {
+ if (status === 'pass') return '✓';
+ if (status === 'warn') return '⚠';
+ if (status === 'excluded') return '–';
+ return '✗';
+}
+
+function main() {
+ const args = parseArgs(process.argv.slice(2));
+ const sdmPath = args['sdm'];
+ const edmPath = args['edm'];
+ const outputDir = args['output-dir'];
+ if (!sdmPath || !edmPath || !outputDir) {
+ console.error('Usage: diff-snapshots.js --sdm <file> --edm <file> --output-dir <dir>');
+ process.exit(1);
+ }
+ if (!fs.existsSync(sdmPath)) { console.error(`Not found: ${sdmPath}`); process.exit(1); }
+ if (!fs.existsSync(edmPath)) { console.error(`Not found: ${edmPath}`); process.exit(1); }
+
+ const sdm = JSON.parse(fs.readFileSync(sdmPath, 'utf8'));
+ const edm = JSON.parse(fs.readFileSync(edmPath, 'utf8'));
+
+ for (const [label, snapshot] of [['sdm', sdm], ['edm', edm]]) {
+ if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot) ||
+ !snapshot.inventory || typeof snapshot.inventory !== 'object' || Array.isArray(snapshot.inventory)) {
+ throw new Error(`${label} snapshot must contain an inventory object`);
+ }
+ if (Object.values(snapshot.inventory).some((records) => !Array.isArray(records))) {
+ throw new Error(`${label} snapshot inventory categories must be arrays`);
+ }
+ if (Object.values(snapshot.inventory).some((records) =>
+ records.some((record) => !record || typeof record !== 'object' || Array.isArray(record)))) {
+ throw new Error(`${label} snapshot inventory records must be objects`);
+ }
+ if (snapshot.parseErrors != null && (
+ typeof snapshot.parseErrors !== 'object' || Array.isArray(snapshot.parseErrors) ||
+ Object.values(snapshot.parseErrors).some((errors) => !Array.isArray(errors))
+ )) {
+ throw new Error(`${label} snapshot parseErrors must contain arrays of errors`);
+ }
+ }
+
+ if (sdm.label !== 'sdm') console.warn(`Warning: --sdm file has label '${sdm.label}', expected 'sdm'`);
+ if (edm.label !== 'edm') console.warn(`Warning: --edm file has label '${edm.label}', expected 'edm'`);
+
+ const allCategories = new Set([...Object.keys(sdm.inventory || {}), ...Object.keys(edm.inventory || {})]);
+
+ const diff = {
+ schemaVersion: 1,
+ sdmSnapshotPath: path.resolve(sdmPath),
+ edmSnapshotPath: path.resolve(edmPath),
+ sdmCapturedAt: sdm.capturedAt,
+ edmCapturedAt: edm.capturedAt,
+ comparedAt: new Date().toISOString(),
+ overallStatus: Object.values(sdm.parseErrors || {}).some((errors) => errors.length > 0) ||
+ Object.values(edm.parseErrors || {}).some((errors) => errors.length > 0) ? 'fail' : 'pass',
+ parseErrors: { sdm: sdm.parseErrors || {}, edm: edm.parseErrors || {} },
+ categories: {},
+ summary: null,
+ };
+
+ for (const cat of [...allCategories].sort()) {
+ const sdmInv = sdm.inventory?.[cat] || [];
+ const edmInv = edm.inventory?.[cat] || [];
+ diff.categories[cat] = diffCategory(cat, sdmInv, edmInv);
+ if (diff.categories[cat].status === 'fail') diff.overallStatus = 'fail';
+ else if (diff.categories[cat].status === 'warn' && diff.overallStatus !== 'fail') diff.overallStatus = 'warn';
+ }
+
+ diff.summary = summarize(diff);
+
+ fs.mkdirSync(outputDir, { recursive: true });
+ const outPath = path.join(outputDir, 'migration-data-diff.json');
+ fs.writeFileSync(outPath, JSON.stringify(diff, null, 2) + '\n', 'utf8');
+
+ // Console summary
+ console.log(`✓ Wrote ${outPath}\n`);
+ console.log(` Overall status: ${statusGlyph(diff.overallStatus)} ${diff.overallStatus.toUpperCase()}\n`);
+ for (const [label, categories] of Object.entries(diff.parseErrors)) {
+ for (const [category, errors] of Object.entries(categories)) {
+ if (errors.length > 0) console.error(`${label} ${category}: ${errors.length} snapshot parse error(s); comparison is incomplete.`);
+ }
+ }
+ console.log(` Category SDM EDM Status Notes`);
+ console.log(` ────────────────────────── ───── ───── ─────── ─────────────────────────────`);
+ for (const [cat, c] of Object.entries(diff.categories)) {
+ if (c.sdmCount === 0 && c.edmCount === 0) continue;
+ const notes = [];
+ if (c.status === 'excluded') {
+ notes.push(c.reason);
+ }
+ // SDM-only categories: when the whole category is "missing", phrase it as
+ // an expected-format-difference instead of a failure.
+ const isSdmOnlyDifference = c.sdmOnlyCategory && c.edmCount === 0 && c.sdmCount > 0 && c.extraInEdm.length === 0;
+ if (c.status === 'excluded') {
+ // Excluded nonconfiguration categories are intentionally outside the
+ // metadata diff; retain their counts for auditability but not totals.
+ } else if (isSdmOnlyDifference) {
+ notes.push(`SDM-only category (not in EDM YAML format; records still in Dataverse)`);
+ } else {
+ if (c.missingInEdm.length) notes.push(`${c.missingInEdm.length} missing in EDM`);
+ if (c.extraInEdm.length) notes.push(`${c.extraInEdm.length} extra in EDM`);
+ }
+ if (c.stateChanged.length) notes.push(`${c.stateChanged.length} state changed`);
+ if (c.contentChanged.length) notes.push(`${c.contentChanged.length} content changed`);
+ if (c.valueChanged.length) notes.push(`${c.valueChanged.length} value changed`);
+ if (c.duplicateKeys?.sdm.length || c.duplicateKeys?.edm.length) {
+ notes.push('duplicate identities; records cannot be paired reliably');
+ }
+ console.log(
+ ` ${cat.padEnd(26)} ${String(c.sdmCount).padStart(5)} ${String(c.edmCount).padStart(5)} ${statusGlyph(c.status)} ${c.status.padEnd(5)} ${notes.join(', ')}`,
+ );
+ }
+ console.log('');
+ const s = diff.summary;
+ console.log(` Totals: SDM=${s.totalSdm}, EDM=${s.totalEdm}, missing=${s.totalMissing}, extra=${s.totalExtra}, stateChanged=${s.totalStateChanged}, valueChanged=${s.totalValueChanged}`);
+
+ // First-N example mismatches per category for quick eyeballing.
+ // Skip SDM-only categories — listing "every record is missing" isn't
+ // actionable when the whole category is an expected format difference.
+ let printedExamples = false;
+ for (const [cat, c] of Object.entries(diff.categories)) {
+ const fields = KEY_FIELDS[cat] || ['name'];
+ const isSdmOnlyDifference = c.sdmOnlyCategory && c.edmCount === 0 && c.sdmCount > 0 && c.extraInEdm.length === 0;
+ if (c.missingInEdm.length > 0 && !isSdmOnlyDifference) {
+ if (!printedExamples) { console.log(''); printedExamples = true; }
+ console.log(` Missing from EDM in '${cat}' (showing up to 5):`);
+ for (const r of c.missingInEdm.slice(0, 5)) console.log(` - ${describeRecord(r, fields)}`);
+ }
+ if (c.extraInEdm.length > 0) {
+ if (!printedExamples) { console.log(''); printedExamples = true; }
+ console.log(` Extra in EDM in '${cat}' (showing up to 5):`);
+ for (const r of c.extraInEdm.slice(0, 5)) console.log(` + ${describeRecord(r, fields)}`);
+ }
+ }
+
+ // Exit code: 0 for pass/warn, 1 for fail. SKILL.md treats warn as user-decision.
+ process.exit(diff.overallStatus === 'fail' ? 1 : 0);
+}
+
+if (require.main === module) main();
+
+module.exports = { diffCategory };
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/emit-telemetry.js b/plugins/power-pages/skills/migrate-datamodel/scripts/emit-telemetry.js
new file mode 100644
index 000000000..39739c295
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/emit-telemetry.js
@@ -0,0 +1,208 @@
+#!/usr/bin/env node
+"use strict";
+
+/**
+ * emit-telemetry.js
+ *
+ * Fires a single `skill_completed` 1DS event for the migrate-datamodel skill,
+ * deriving only terminal outcome and elapsed duration from migration-state.json.
+ * Migration details stay local; no new eventInfo fields are transmitted.
+ *
+ * Design contract:
+ * - READ-ONLY against the shared telemetry library (reached via the plugin's
+ * bundled `scripts/lib/telemetry` library). Touches nothing shared.
+ * - Fails CLOSED: any error → exit 0, nothing thrown, migration unaffected.
+ * - Honors the same kill switch (ikey.json `disabled` / missing iKey) and the
+ * per-plugin user opt-out that the emit dispatcher enforces.
+ * - `eventInfo` carries only the existing approved aadObjectId when available.
+ * No template names, phase text, site URLs or filesystem paths are emitted.
+ *
+ * USAGE
+ * node emit-telemetry.js --output-dir "<MIGRATION_SUBDIR>"
+ *
+ * The <MIGRATION_SUBDIR> is the per-migration folder printed by
+ * `update-state.js --init` (the one holding migration-state.json).
+ */
+
+const path = require("node:path");
+const fs = require("node:fs");
+const os = require("node:os");
+const crypto = require("node:crypto");
+
+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..", "..");
+const TELEMETRY_DIR = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry");
+
+const SKILL_NAME = "migrate-datamodel";
+
+function main() {
+ let emitSpawn, eventsLib, sessionLib, pacAuthLib, agentInfoLib;
+ try {
+ emitSpawn = require(path.join(TELEMETRY_DIR, "lib", "emit-spawn"));
+ eventsLib = require(path.join(TELEMETRY_DIR, "lib", "events"));
+ sessionLib = require(path.join(TELEMETRY_DIR, "lib", "session"));
+ pacAuthLib = require(path.join(TELEMETRY_DIR, "lib", "pac-auth"));
+ agentInfoLib = require(path.join(TELEMETRY_DIR, "lib", "agent-info"));
+ } catch {
+ return; // telemetry library unavailable → no-op
+ }
+
+ const { cfg, ikeyPath, eventStreamName, disabled } = readIkey();
+ // Repo-side hard-off / unconfigured: gate before any work so a disabled or
+ // unconfigured plugin costs effectively nothing. (The per-plugin user opt-out
+ // is enforced later by the detached dispatcher, which still writes the local
+ // diagnostic mirror but skips the POST.)
+ if (disabled) return;
+ const { loadResolver } = require(path.join(TELEMETRY_DIR, "lib", "resolver-loader"));
+ const resolver = loadResolver(path.dirname(ikeyPath));
+ if (!(resolver ? resolver.isProvisioned(cfg) : cfg.instrumentationKey)) return;
+
+ const outputDir = parseOutputDir(process.argv.slice(2));
+ const state = loadState(outputDir);
+ if (!state) return; // no state → nothing meaningful to report
+
+ const rollup = buildPhaseRollup(state);
+ if (!rollup) return; // Pending/in-progress state is not a successful completion.
+
+ const fields = {
+ pluginName: "power-pages",
+ pluginVersion: readPluginVersion(),
+ sessionId: safeCall(() => sessionLib.getSessionId(), crypto.randomUUID()),
+ correlationId: crypto.randomUUID(),
+ osName: osFriendlyName(process.platform),
+ osVersion: os.release(),
+ nodeVersion: "v" + String(process.versions.node).split(".")[0],
+ skillName: SKILL_NAME,
+ outcome: rollup.outcome,
+ durationMs: rollup.durationMs,
+ eventInfo: {},
+ };
+
+ if (rollup.outcome === "failure") {
+ fields.errorClass = "phaseBlocked";
+ fields.errorDescription = "phaseBlocked";
+ }
+
+ const pacAuth = safeCall(() => pacAuthLib.readPacAuth(), null);
+ if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;
+ if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;
+ if (pacAuth && pacAuth.objectId) fields.eventInfo.aadObjectId = pacAuth.objectId;
+
+ const agentInfo = safeCall(
+ () => ({
+ ...agentInfoLib.readAiAgent(),
+ pacCliVersion: agentInfoLib.readPacCliVersion(),
+ }),
+ {}
+ );
+ if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;
+ if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;
+ if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;
+
+ try {
+ emitSpawn.fireAndForget(eventsLib.buildSkillCompleted(eventStreamName, fields), {
+ cloud: (pacAuth && pacAuth.cloud) || "",
+ configDir: process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "",
+ fakeProbe: process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "",
+ // lib/ is shared, so the dispatcher's __dirname default would hit shared/'s
+ // placeholder ikey.json — point it at this plugin's real config.
+ ikeyJsonPath: ikeyPath,
+ });
+ } catch {
+ // fail closed
+ }
+}
+
+// ── helpers ─────────────────────────────────────────────────────────────────
+
+function parseOutputDir(argv) {
+ for (let i = 0; i < argv.length; i++) {
+ if (argv[i] === "--output-dir" && argv[i + 1]) return argv[i + 1];
+ }
+ return "";
+}
+
+function loadState(outputDir) {
+ if (!outputDir) return null;
+ try {
+ const p = path.join(outputDir, "migration-state.json");
+ return JSON.parse(fs.readFileSync(p, "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+// Only derive approved top-level metrics; user-editable migration fields stay local.
+function buildPhaseRollup(state) {
+ if (!state || !Array.isArray(state.phases) || state.phases.length === 0 ||
+ state.phases.some((phase) => !phase || typeof phase !== "object")) return null;
+ const blocked = state.phases.find((p) => p.status === "blocked");
+ if (!blocked && !state.phases.every((p) => p.status === "completed")) return null;
+ const outcome = blocked ? "failure" : "success";
+ return {
+ outcome,
+ durationMs: skillDurationMs(state),
+ };
+}
+
+function skillDurationMs(state) {
+ const start = Date.parse(state && state.skillStartedAt);
+ const end = Date.parse(state && state.lastUpdatedAt);
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return 0;
+ return end - start;
+}
+
+function readPluginVersion() {
+ try {
+ const manifest = JSON.parse(
+ fs.readFileSync(path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"), "utf8")
+ );
+ return manifest.version || "unknown";
+ } catch {
+ return "unknown";
+ }
+}
+
+function readIkey() {
+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;
+ const ikeyPath =
+ override && override.trim() ? override : path.join(TELEMETRY_DIR, "ikey.json");
+ try {
+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));
+ return {
+ cfg,
+ ikeyPath,
+ eventStreamName: cfg.event_stream_name || "",
+ disabled: cfg.disabled === true,
+ };
+ } catch {
+ // Missing/unreadable → fail CLOSED (disabled), matching the dispatcher's
+ // kill-switch semantics so a missing config can't bypass the off-switch.
+ return { cfg: null, ikeyPath, eventStreamName: "", disabled: true };
+ }
+}
+
+function osFriendlyName(platform) {
+ if (platform === "win32") return "Windows";
+ if (platform === "darwin") return "Mac";
+ if (platform === "linux") return "Linux";
+ return platform;
+}
+
+function safeCall(fn, fallback) {
+ try {
+ const v = fn();
+ return v === undefined || v === null ? fallback : v;
+ } catch {
+ return fallback;
+ }
+}
+
+if (require.main === module) {
+ try {
+ main();
+ } catch {
+ // Telemetry must never interrupt migration.
+ }
+}
+
+module.exports = { main, buildPhaseRollup, readIkey };
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/generate-migration-reports.js b/plugins/power-pages/skills/migrate-datamodel/scripts/generate-migration-reports.js
new file mode 100644
index 000000000..0d18b4d96
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/generate-migration-reports.js
@@ -0,0 +1,1608 @@
+#!/usr/bin/env node
+
+/**
+ * generate-migration-reports.js
+ *
+ * Builds the customization report from the PAC customization CSV, stages the
+ * FetchXML/Liquid remediation rewrites, and writes the augmented remediation
+ * prompts (plugin + DME).
+ *
+ * It does NOT write the execution/progress report (datamodel-migration-report.html) —
+ * that is the live report, owned by update-state.js + lib/render-live-report.js, which
+ * re-render it from migration-state.json after every step.
+ *
+ * Usage:
+ * # Customization report
+ * node generate-migration-reports.js \
+ * --customization-report "path/to/SiteCustomization.csv" \
+ * --site-name "Contoso Portal" \
+ * --website-id "076bf556-9ae6-ee11-a203-6045bdf0328e" \
+ * --template-name "Starter layout 1" \
+ * --output-dir "./migration-reports"
+ *
+ * # Stage remediation rewrites (proposed files land under <output-dir>/remediation-staged/)
+ * node generate-migration-reports.js \
+ * --customization-report "path/to/SiteCustomization.csv" \
+ * --site-name "Contoso Portal" --website-id "<GUID>" \
+ * --site-path "path/to/downloaded/site" \
+ * --automate-fetchxml --automate-liquid \
+ * --output-dir "./migration-reports"
+ */
+
+const fs = require('fs');
+const path = require('path');
+const { pathToFileURL } = require('node:url');
+const { getAuthToken, makeRequest, requirePowerPagesSiteRoot } = require('../../../scripts/lib/validation-helpers');
+
+// Map of adx_* entity logical names to their powerpagecomponenttype value.
+// Source: https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model#site-component-type-and-values
+const COMPONENT_TYPE_MAP = {
+ 'adx_publishingstate': 1,
+ 'adx_webpage': 2,
+ 'adx_webfile': 3,
+ 'adx_weblinkset': 4,
+ 'adx_weblink': 5,
+ 'adx_pagetemplate': 6,
+ 'adx_contentsnippet': 7,
+ 'adx_webtemplate': 8,
+ 'adx_sitesetting': 9,
+ 'adx_webpageaccesscontrolrule': 10,
+ 'adx_webrole': 11,
+ 'adx_websiteaccess': 12,
+ 'adx_sitemarker': 13,
+ 'adx_entityform': 15,
+ 'adx_entityformmetadata': 16,
+ 'adx_entitylist': 17,
+ 'adx_entitypermission': 18,
+ 'adx_webform': 19,
+ 'adx_webformstep': 20,
+ 'adx_webformmetadata': 21,
+ 'adx_pollplacement': 24,
+ 'adx_adplacement': 26,
+ 'adx_botconsumer': 27,
+ 'adx_columnpermissionprofile': 28,
+ 'adx_columnpermission': 29,
+ 'adx_redirect': 30,
+ 'adx_publishingstatetransitionrule': 31,
+ 'adx_shortcut': 32,
+ 'adx_cloudflowconsumer': 33,
+};
+
+// Map of adx_* tables to the dedicated Liquid object suggested by the migration doc.
+// Source: https://learn.microsoft.com/en-us/power-pages/configure/liquid/liquid-objects
+const LIQUID_OBJECT_MAP = {
+ 'adx_weblinkset': { object: 'weblinks', usage: "weblinks['<Web Link Set name>']" },
+ 'adx_weblink': { object: 'weblinks', usage: "weblinks['<Web Link Set name>'].weblinks" },
+ 'adx_contentsnippet': { object: 'snippets', usage: "snippets['<snippet name>']" },
+ 'adx_sitesetting': { object: 'settings', usage: "settings['<setting name>']" },
+ 'adx_sitemarker': { object: 'sitemarkers', usage: "sitemarkers['<marker name>']" },
+ 'adx_ad': { object: 'ads', usage: "ads['<ad name>']" },
+ 'adx_poll': { object: 'polls', usage: "polls['<poll name>']" },
+ 'adx_event': { object: 'events', usage: "events['<event name>']" },
+ 'adx_communityforum': { object: 'forums', usage: "forums['<forum name>']" },
+ 'adx_blog': { object: 'blogs', usage: "blogs['<blog name>']" },
+ 'adx_webpage': { object: 'page', usage: 'page (current page only — for other pages use powerpagecomponent FetchXML)' },
+ 'adx_website': { object: 'website', usage: 'website (singleton)' },
+};
+
+// Parse command line arguments
+function parseArgs(args) {
+ const result = {};
+ for (let i = 0; i < args.length; i++) {
+ if (args[i].startsWith('--')) {
+ const key = args[i].replace('--', '');
+ const nextValue = args[i + 1];
+ if (nextValue && !nextValue.startsWith('--')) {
+ result[key] = nextValue === 'true' ? true : nextValue === 'false' ? false : nextValue;
+ i++;
+ } else {
+ result[key] = true;
+ }
+ }
+ }
+ return result;
+}
+
+/**
+ * Simple CSV parser for the customization report
+ */
+function parseCSV(content, { strict = false } = {}) {
+ const rows = [];
+ let current = '';
+ let row = [];
+ let inQuotes = false;
+
+ for (let i = 0; i < content.length; i++) {
+ const char = content[i];
+ const nextChar = content[i + 1];
+
+ if (char === '"') {
+ if (inQuotes && nextChar === '"') {
+ current += '"';
+ i++;
+ } else {
+ inQuotes = !inQuotes;
+ }
+ } else if (char === ',' && !inQuotes) {
+ row.push(current);
+ current = '';
+ } else if ((char === '\n' || char === '\r') && !inQuotes) {
+ if (char === '\r' && nextChar === '\n') {
+ i++;
+ }
+ row.push(current);
+ rows.push(row);
+ row = [];
+ current = '';
+ } else {
+ current += char;
+ }
+ }
+
+ if (strict && inQuotes) throw new SyntaxError('Customization CSV contains an unterminated quoted field.');
+ if (current !== '' || row.length > 0) {
+ row.push(current);
+ rows.push(row);
+ }
+
+ return rows.map(columns => columns.map(value => {
+ const trimmed = value.trim();
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
+ return trimmed.slice(1, -1).replace(/""/g, '"');
+ }
+ return trimmed;
+ }));
+}
+
+/**
+ * Parse CSV customization report into structured data
+ */
+function parseCustomizationReport(csvPath) {
+ if (!fs.existsSync(csvPath)) {
+ throw new Error(`Customization report not found: ${csvPath}`);
+ }
+
+ const content = fs.readFileSync(csvPath, 'utf-8');
+ const rows = parseCSV(content);
+ const headers = rows[0] || [];
+ const records = rows.slice(1).map(columns => {
+ const record = {};
+ headers.forEach((header, index) => {
+ record[header.trim()] = columns[index] || '';
+ });
+ return record;
+ });
+
+ // Group by customization type
+ const grouped = {};
+ records.forEach(record => {
+ const type = record['Type of customization'] || record['type'] || 'Unknown';
+ if (!grouped[type]) {
+ grouped[type] = [];
+ }
+ grouped[type].push({
+ type: type,
+ guidance: record['Guidance'] || record['guidance'] || '',
+ snippet: record['Snippet'] || record['snippet'] || '',
+ location: normalizeLocationPath(record['Location'] || record['location'] || ''),
+ });
+ });
+
+ return grouped;
+}
+
+/**
+ * Normalize a Location path from PAC's customization-report CSV.
+ *
+ * PAC writes paths to its internal scan temp directory in the Location column, prefixed with
+ * the Windows extended-path marker (`\\?\` or `\\?\UNC\`). Two problems:
+ * 1. The `\\?\` prefix breaks Node's URL parser (the `?` becomes `%3F` in pathToFileURL),
+ * which crashes any agent flow that tries to render the path as a markdown file:// link.
+ * 2. The temp-dir part is meaningless to the user — they never operate on PAC's scratch dir.
+ *
+ * This function strips both:
+ * - Extended-path prefix (`\\?\` / `\\?\UNC\`)
+ * - The leading temp-folder portion (`...\Temp\<site-slug>\`) when present, returning only
+ * the relative path within the site (e.g., `web-templates\X\Y.html`)
+ *
+ * If no temp-dir segment is present, returns the cleaned absolute path as-is.
+ */
+function normalizeLocationPath(loc) {
+ if (!loc) return '';
+ // 1. Strip the Windows extended-path prefix.
+ let cleaned = loc.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '');
+ // 2. If the path passes through a `*\Temp\<single-segment>\<rest>` pattern (PAC's temp
+ // scratch dir + per-run site-slug folder), keep only `<rest>` — that's the relative
+ // path within the site source tree that the user can map to their downloaded site.
+ const tempMatch = cleaned.match(/[\\/]Temp[\\/][^\\/]+[\\/](.+)$/i);
+ return tempMatch ? tempMatch[1] : cleaned;
+}
+
+/**
+ * Generate customization section HTML
+ */
+function generateCustomizationSection(type, items) {
+ const badgeMap = {
+ 'Liquid contains adx references': 'badge-liquid',
+ 'FetchXML contains adx references': 'badge-fetchxml',
+ 'Fetch Xml contains adx references': 'badge-fetchxml',
+ 'FetchXml contains adx references': 'badge-fetchxml',
+ 'Custom workflow': 'badge-workflow',
+ 'Data Model Extension': 'badge-data-model',
+ 'Plugins registered on adx entities': 'badge-plugin'
+ };
+
+ const badge = badgeMap[type] || 'badge-liquid';
+ const typeLabel = type.replace('Liquid contains ', '').replace('Custom ', '');
+
+ let html = `
+ <div class="customization-section">
+ <div class="section-header">
+ <span class="badge ${badge}">${escapeHtml(typeLabel)}</span>
+ <h2>${escapeHtml(type)}</h2>
+ <span class="customization-count">${items.length}</span>
+ </div>
+ <table class="customization-table">
+ <thead>
+ <tr>
+ <th>Location</th>
+ <th>Snippet</th>
+ <th>Assessment</th>
+ <th>Guidance</th>
+ </tr>
+ </thead>
+ <tbody>
+ `;
+
+ items.forEach(item => {
+ const assessment = classifyCustomizationFinding(type, item);
+ const snippet = item.snippet ? item.snippet.substring(0, 200) + (item.snippet.length > 200 ? '...' : '') : '';
+ let guidance = escapeHtml(item.guidance || 'No guidance provided');
+ try {
+ const url = new URL(item.guidance);
+ if (url.protocol === 'https:' || url.protocol === 'http:') {
+ guidance = `<a href="${escapeHtml(url.href)}" target="_blank" rel="noopener noreferrer">View Guidance</a>`;
+ }
+ } catch {
+ // PAC normally supplies an absolute guidance URL; malformed values remain plain text.
+ }
+ html += `
+ <tr>
+ <td>${escapeHtml(item.location || 'N/A')}</td>
+ <td><div class="snippet">${escapeHtml(snippet)}</div></td>
+ <td><strong>${escapeHtml(ASSESSMENT_LABELS[assessment.status])}</strong><br>${escapeHtml(assessment.reason)}</td>
+ <td>${guidance}</td>
+ </tr>
+ `;
+ });
+
+ html += `
+ </tbody>
+ </table>
+ </div>
+ `;
+
+ return html;
+}
+
+/**
+ * Fill every {{PLACEHOLDER}} token in an HTML report template.
+ *
+ * Why this exists instead of chained `template.replace('{{X}}', value)`:
+ * `String.prototype.replace` with a *string* first argument only swaps the FIRST
+ * match. The report templates intentionally repeat some tokens — `{{SITE_NAME}}`
+ * appears in both the subtitle and the metadata card, and `{{REPORT_DATE}}` appears
+ * in the topbar, the metadata card, AND the footer — so the chained-string approach
+ * left the 2nd/3rd occurrences as literal `{{SITE_NAME}}` / `{{REPORT_DATE}}` text in
+ * the rendered report. A global regex replaces every occurrence.
+ *
+ * The value is inserted via a function replacer so `$` sequences in user-derived
+ * content (Liquid snippets, FetchXML, plugin names) are treated literally instead of
+ * as String.replace special patterns ($&, $1, $$).
+ *
+ * Tokens are applied in object order; callers pass scalar values before large HTML
+ * blocks so a block's content is never re-scanned for a later token.
+ */
+function fillPlaceholders(template, replacements) {
+ return Object.entries(replacements).reduce((html, [token, value]) => {
+ // `token` is a literal like '{{SITE_NAME}}'. Escape regex metacharacters so the
+ // braces (and any future punctuation a token might contain) match literally.
+ const pattern = new RegExp(token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
+ return html.replace(pattern, () => String(value));
+ }, template);
+}
+
+/**
+ * Generate customization report HTML
+ */
+function generateCustomizationReportHtml(args, customizations, assessment = assessCustomizations(customizations)) {
+ const templatePath = path.join(__dirname, '../assets/customization-report.html');
+ let template = fs.readFileSync(templatePath, 'utf-8');
+
+ // Generate customization sections
+ let customizationSections = '';
+ if (Object.keys(customizations).length === 0) {
+ customizationSections = `
+ <div class="no-data">
+ <div class="no-data-icon">✓</div>
+ <h3>No Scan Findings</h3>
+ <p>PAC reported no customization references in this scan. This is not proof of complete coverage or runtime compatibility; runtime validation is still required.</p>
+ </div>
+ `;
+ } else {
+ Object.entries(customizations).forEach(([type, items]) => {
+ customizationSections += generateCustomizationSection(type, items);
+ });
+ }
+
+ // Generate summary text
+ const totalCustomizations = Object.values(customizations).reduce((sum, items) => sum + items.length, 0);
+ const summaryText = totalCustomizations === 0
+ ? 'No scan findings. Retain the normal migration approval gates and runtime validation.'
+ : `${totalCustomizations} scan references across ${Object.keys(customizations).length} categories: ` +
+ `${assessment.summary.informational} informational (no rewrite identified), ` +
+ `${assessment.summary.actionable} actionable, ${assessment.summary.needsReview} need context review. ` +
+ 'A scan reference is not automatically a defect or a critical customization. ' +
+ 'Context review is not a confirmed risk; investigate before deciding whether a change is necessary. ' +
+ 'Proposed changes require separate review and approval; runtime validation remains required.';
+
+ // Fill placeholders. Scalars first, large HTML blocks last so block content is
+ // never re-scanned for a later token. fillPlaceholders replaces EVERY occurrence
+ // (the template repeats {{SITE_NAME}} and {{REPORT_DATE}}), which the previous
+ // chained String.replace(string, …) did not — it only swapped the first match,
+ // leaving the metadata card's Site Name / Report Generated (and the footer date)
+ // as literal {{…}} text.
+ template = fillPlaceholders(template, {
+ '{{SITE_NAME}}': escapeHtml(args['site-name'] || 'Unknown'),
+ '{{WEBSITE_ID}}': escapeHtml(args['website-id'] || 'N/A'),
+ '{{TEMPLATE_NAME}}': escapeHtml(args['template-name'] || 'Unknown'),
+ '{{REPORT_DATE}}': new Date().toISOString().split('T')[0],
+ '{{TOTAL_CUSTOMIZATIONS}}': totalCustomizations.toString(),
+ '{{SUMMARY_TEXT}}': summaryText,
+ '{{CUSTOMIZATIONS_SECTIONS}}': customizationSections,
+ });
+
+ return template;
+}
+
+/**
+ * Wraps makeRequest with retry logic for 429 (rate limit) responses.
+ * Retries up to maxRetries times, waiting retryAfter ms between attempts.
+ */
+async function makeRequestWithRetry(options, maxRetries = 3, retryAfterMs = 10000) {
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
+ const result = await makeRequest({ ...options, includeHeaders: true });
+ if (result.statusCode !== 429) return result;
+ if (attempt < maxRetries) {
+ const retryAfterHeader = result.headers && result.headers['retry-after'];
+ const waitMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1000 : retryAfterMs;
+ console.warn(`Rate limited (429). Waiting ${waitMs / 1000}s before retry ${attempt + 1}/${maxRetries}...`);
+ await new Promise(resolve => setTimeout(resolve, waitMs));
+ }
+ }
+ return { statusCode: 429, body: 'Rate limit exceeded after retries' };
+}
+
+/**
+ * Escape HTML special characters
+ */
+function escapeHtml(text) {
+ const map = {
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#039;'
+ };
+ return text.replace(/[&<>"']/g, m => map[m]);
+}
+
+/**
+ * Check if a column exists on a Dataverse table
+ */
+async function checkColumnExists(envUrl, tableLogicalName, columnLogicalName) {
+ const token = getAuthToken(envUrl);
+ if (!token) {
+ throw new Error('Failed to get auth token. Run: az login');
+ }
+
+ const result = await makeRequestWithRetry({
+ url: `${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${tableLogicalName}')/Attributes?$filter=LogicalName eq '${columnLogicalName}'&$select=LogicalName`,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/json',
+ },
+ timeout: 15000,
+ });
+
+ if (result.error || result.statusCode !== 200) {
+ throw new Error(`API error checking column: ${result.error || result.body}`);
+ }
+
+ const parsed = JSON.parse(result.body);
+ return (parsed.value || []).length > 0;
+}
+
+/**
+ * Create a string attribute on a Dataverse table
+ */
+async function createStringAttribute(envUrl, tableLogicalName, columnLogicalName, displayName) {
+ const token = getAuthToken(envUrl);
+ if (!token) {
+ throw new Error('Failed to get auth token. Run: az login');
+ }
+
+ const attributeMetadata = {
+ '@odata.type': 'Microsoft.Dynamics.CRM.StringAttributeMetadata',
+ LogicalName: columnLogicalName,
+ DisplayName: {
+ '@odata.type': 'Microsoft.Dynamics.CRM.Label',
+ LocalizedLabels: [{
+ '@odata.type': 'Microsoft.Dynamics.CRM.LocalizedLabel',
+ Label: displayName,
+ LanguageCode: 1033
+ }]
+ },
+ MaxLength: 100,
+ IsNullable: true,
+ IsRetrievable: true,
+ IsSearchable: true
+ };
+
+ const result = await makeRequestWithRetry({
+ url: `${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${tableLogicalName}')/Attributes`,
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ body: JSON.stringify(attributeMetadata),
+ timeout: 30000,
+ });
+
+ if (result.error || (result.statusCode !== 201 && result.statusCode !== 204)) {
+ throw new Error(`API error creating attribute: ${result.error || result.body}`);
+ }
+
+ return true;
+}
+
+/**
+ * Categorize a Liquid customization-report finding by the patterns it contains.
+ *
+ * The PAC customization report flags files containing `adx_*` in Liquid context, but many
+ * patterns work as-is on EDM via the documented `[logical_name]` accessor. Only a small subset
+ * requires actual rewriting. This categorizer scans the snippet for known patterns and emits
+ * the highest-priority signal:
+ *
+ * needs-rewrite — entities['adx_*'] collection access (rewrite to dedicated Liquid object)
+ * auto-fetchxml — contains {% fetchxml %} block with adx_* entity (handled by --automate-fetchxml)
+ * false-positive — only property access, editable tag, or lookup keys (no action needed)
+ * unknown — unrecognized adx_* usage; flag for manual review
+ */
+function categorizeLiquidFinding(snippet) {
+ if (!snippet) return { category: 'unknown', action: 'Empty snippet — review manually.' };
+
+ const patterns = {
+ entitiesCollection: /entities\s*\[\s*['"]?adx_\w+['"]?\s*\]/,
+ fetchxmlBlock: /\{%\s*fetchxml\b[\s\S]*?<(?:link-)?entity\b[^>]*\bname\s*=\s*['"]adx_/i,
+ editableTag: /\{%\s*editable\s+\w+\s+['"]adx_\w+['"]/,
+ lookupKey: /\b(?:snippets|weblinks|sitemarkers|settings|ads|polls|events|forums|blogs)\s*\[\s*['"]adx_\w+['"]\s*\]/,
+ propertyAccess: /\.\s*adx_\w+\b/,
+ };
+
+ // Priority order: actionable patterns first.
+ if (patterns.entitiesCollection.test(snippet)) {
+ return {
+ category: 'needs-rewrite',
+ pattern: 'entities[\'adx_*\']',
+ action: "Rewrite needed: replace `entities['adx_*']` with the dedicated Liquid object (e.g., `weblinks['<name>']`, `snippets['<name>']`). Run `--automate-liquid` to surface annotated suggestions.",
+ };
+ }
+ if (patterns.fetchxmlBlock.test(snippet)) {
+ return {
+ category: 'auto-fetchxml',
+ pattern: '{% fetchxml %} with adx_* entity',
+ action: 'Embedded FetchXML inside Liquid — automatically rewritten by `--automate-fetchxml` (renames `adx_*` entity to `powerpagecomponent` + injects type filter).',
+ };
+ }
+ if (/\bentities\s*(?:\[|\.)/.test(snippet)) {
+ return {
+ category: 'unknown',
+ action: 'Inspect the entity collection target and consumers; dynamic or unsupported collection access must not be treated as ordinary logical-property access.',
+ };
+ }
+
+ // A safe property accessor must not hide another, unclassified reference:
+ // "{{ page.adx_copy }} ... <entity name='adx_webpage'>" still needs review.
+ const remaining = snippet
+ .replace(/\b[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*\.\s*adx_\w+\b/g, '')
+ .replace(/\{%\s*editable\s+\w+\s+['"]adx_\w+['"]/g, '')
+ .replace(/\b(?:snippets|weblinks|sitemarkers|settings|ads|polls|events|forums|blogs)\s*\[\s*['"]adx_\w+['"]\s*\]/g, '');
+ const onlyFalsePositive = !/adx_/i.test(remaining);
+
+ if (onlyFalsePositive) {
+ const reasons = [];
+ if (patterns.propertyAccess.test(snippet)) {
+ reasons.push("`object.adx_X` — documented `[logical_name]` accessor on Liquid objects (page, website, entity, etc.); resolves on EDM via runtime virtualization");
+ }
+ if (patterns.editableTag.test(snippet)) {
+ reasons.push("`{% editable obj 'adx_X' %}` — the attribute parameter uses the logical name and works on EDM");
+ }
+ if (patterns.lookupKey.test(snippet)) {
+ reasons.push("`snippets['adx_X']` / `weblinks['adx_X']` / similar — the index is a user-defined snippet/link/setting name, not an attribute");
+ }
+ if (reasons.length === 0) {
+ // Some adx_ reference we didn't classify — be honest.
+ return {
+ category: 'unknown',
+ pattern: 'unrecognized adx_ usage',
+ action: 'Pattern not recognized as auto-fixable or known-safe. Review manually against the Liquid Objects doc: https://learn.microsoft.com/en-us/power-pages/configure/liquid/liquid-objects',
+ };
+ }
+ return {
+ category: 'false-positive',
+ pattern: 'documented runtime-safe access',
+ action: `Likely no action needed. Reason: ${reasons.join('; ')}.`,
+ };
+ }
+
+ return { category: 'unknown', pattern: 'mixed', action: 'Review manually.' };
+}
+
+const ASSESSMENT_LABELS = {
+ informational: 'Informational - no rewrite identified',
+ actionable: 'Action required - review proposed or manual changes',
+ needsReview: 'Context review needed - not a confirmed defect',
+};
+
+function classifyCustomizationFinding(type, item) {
+ const snippet = item.snippet || '';
+ if (type === 'Liquid contains adx references') {
+ const result = categorizeLiquidFinding(snippet);
+ if (result.category === 'auto-fetchxml') {
+ return classifyCustomizationFinding('FetchXML contains adx references', item);
+ }
+ if (result.category === 'needs-rewrite' &&
+ ![...snippet.matchAll(/entities\s*\[\s*['"](adx_\w+)['"]\s*\]/g)]
+ .some((match) => Object.hasOwn(LIQUID_OBJECT_MAP, match[1]))) {
+ return { status: 'needsReview', reason: 'Inspect the collection target and consumers; no supported Liquid replacement is known for this table. Do not infer a metadata rewrite from the adx_ prefix alone.' };
+ }
+ return {
+ status: result.category === 'false-positive' ? 'informational'
+ : result.category === 'needs-rewrite' ? 'actionable' : 'needsReview',
+ reason: result.action,
+ };
+ }
+ // PAC has emitted "Fetch Xml", "FetchXml" and "FetchXML". Do not use the
+ // category's spelling, filename or template ownership as a severity signal.
+ if (/^fetch\s*xml contains adx references$/i.test(type)) {
+ const names = [...snippet.matchAll(/<(?:link-)?entity\b[^>]*\bname\s*=\s*['"]([\w]+)['"]/gi)]
+ .map((match) => match[1].toLowerCase());
+ if (names.some((name) => Object.hasOwn(COMPONENT_TYPE_MAP, name))) {
+ return { status: 'actionable', reason: 'FetchXML targets migrated metadata. Review supported staged rewrites and any skipped blocks before applying changes.' };
+ }
+ if (/<fetch\b[^>]*>[\s\S]*<\/fetch>/i.test(snippet) && names.length && !/adx_/i.test(snippet)) {
+ return { status: 'informational', reason: 'The complete supplied FetchXML contains no adx_ reference; no SDM metadata rewrite is identified in this snippet.' };
+ }
+ return { status: 'needsReview', reason: 'Inspect the full local query and referenced tables. A truncated snippet or unmapped transactional table is not automatically a migration defect; do not guess a component mapping.' };
+ }
+ if (type === 'Data Model Extension') {
+ const { table, column } = parseDataModelExtension(snippet);
+ if (table && column && Object.hasOwn(COMPONENT_TYPE_MAP, table.toLowerCase())) {
+ return { status: 'actionable', reason: 'A custom column targets migrated metadata; review the schema/data-copy checklist. No schema or data changes are automated.' };
+ }
+ }
+ if (type === 'Plugins registered on adx entities') {
+ const plugin = categorizePlugin(snippet);
+ if (plugin.category === 'custom' && plugin.pluginName !== 'unknown' && plugin.componentType !== null) {
+ return { status: 'actionable', reason: plugin.action };
+ }
+ }
+ return { status: 'needsReview', reason: 'Verify the full component, target table and installed version in this customer environment. Scan presence or a built-in-looking name alone does not establish a defect, safety, or a required rewrite.' };
+}
+
+function assessCustomizations(customizations) {
+ const summary = { informational: 0, actionable: 0, needsReview: 0 };
+ const findings = Object.entries(customizations).flatMap(([type, items]) => items.map((item) => {
+ const assessment = classifyCustomizationFinding(type, item);
+ summary[assessment.status]++;
+ return { type, ...item, ...assessment };
+ }));
+ return { schemaVersion: 1, summary, findings };
+}
+
+/**
+ * Categorize a plugin finding by class-name prefix.
+ *
+ * Microsoft.* → system plugin, no user action needed (auto-handled by Power Pages Core)
+ * Adxstudio.* → legacy framework plugin; verify V2 EDM solution is installed (step 1.6)
+ * (anything else) → custom plugin; only mapped metadata targets get refactor guidance
+ */
+function categorizePlugin(snippet) {
+ // CSV snippet format from PAC:
+ // "Plugin name : <name> Step name : <step> Entity Name : <entity>"
+ // Fields are separated by 2+ whitespace characters. Split-based parsing is more
+ // robust than overlapping regex alternations (which mis-handle the empty-step
+ // case where input is "Step name : Entity Name : <entity>").
+ const parts = (snippet || '').split(/\s{2,}/);
+ const pickField = (label) => {
+ const part = parts.find((p) => p.startsWith(label));
+ if (!part) return null;
+ return part.slice(label.length).replace(/^\s*:\s*/, '').trim() || null;
+ };
+ const pluginName = pickField('Plugin name') || 'unknown';
+ const entity = pickField('Entity Name');
+ const stepName = pickField('Step name');
+ const target = (entity || '').toLowerCase();
+ const componentType = Object.hasOwn(COMPONENT_TYPE_MAP, target) ? COMPONENT_TYPE_MAP[target] : null;
+
+ let category;
+ let action;
+ if (/^Microsoft\./i.test(pluginName)) {
+ category = 'system';
+ action = `System plugin (\`${pluginName}\`) — no user action needed. Power Pages Core handles this on EDM.`;
+ } else if (/^Adxstudio\./i.test(pluginName)) {
+ category = 'adxstudio';
+ action = `Legacy Adxstudio framework plugin (\`${pluginName}\`) — verify the V2 EDM-compatible version of Power Pages Core / template solution is installed (covered by step 1.6). No code changes typically needed.`;
+ } else {
+ category = 'custom';
+ action = componentType === null
+ ? `Custom plugin (\`${pluginName}\`) — manual review required for target \`${entity || 'unknown'}\`: no supported metadata mapping. Keep its target, queries and registration unchanged until the schema and consumers are verified; an \`adx_*\` prefix alone does not justify a rewrite.`
+ : `Custom plugin (\`${pluginName}\`) — refactor the plugin code to target \`powerpagecomponent\` (was \`${entity}\`), preserve existing \`adx_*\` logical attribute names exposed by EDM, and re-register the plugin step${
+ stepName ? ` (was: ${stepName})` : ''
+ }.`;
+ }
+
+ return { pluginName, entity, stepName, category, componentType, action };
+}
+
+/**
+ * Parse a Data Model Extension snippet into {table, column}.
+ * CSV snippet format: "Table name : adx_webpage Column name : contoso_redirecturl"
+ */
+function parseDataModelExtension(snippet) {
+ const tableMatch = snippet.match(/Table name\s*:\s*(\w+)/i);
+ const columnMatch = snippet.match(/Column name\s*:\s*(\w+)/i);
+ return {
+ table: tableMatch ? tableMatch[1] : null,
+ column: columnMatch ? columnMatch[1] : null,
+ };
+}
+
+/**
+ * Group Data Model Extension findings by source adx_* table and produce a
+ * per-table remediation checklist (no Dataverse API calls — pure guidance).
+ *
+ * Per the migration doc, the correct fix for a custom column on an adx_* table is:
+ * 1. Create a NEW custom table (e.g., contoso_<original-suffix>)
+ * 2. Add the custom column on the new table
+ * 3. Add a lookup column on the new table that points to powerpagecomponent
+ * 4. Migrate data from the original adx_* column to the new table
+ * 5. Update Liquid/FetchXML to reference the new table
+ *
+ * https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model#custom-columns-on-adx-metadata-tables
+ */
+function buildDataModelExtensionChecklists(items) {
+ const groups = {};
+ for (const item of items) {
+ const { table, column } = parseDataModelExtension(item.snippet || '');
+ if (!table || !column || !Object.hasOwn(COMPONENT_TYPE_MAP, table.toLowerCase())) continue;
+ if (!groups[table]) {
+ groups[table] = { sourceTable: table, columns: [], snippets: [] };
+ }
+ // De-duplicate column names per table (the CSV sometimes lists a column twice if its
+ // lookup display name is also flagged — e.g., `mspp_websiteid` and `mspp_websiteidName`).
+ if (!groups[table].columns.includes(column)) {
+ groups[table].columns.push(column);
+ }
+ groups[table].snippets.push(item.snippet);
+ }
+
+ // Build per-table checklists.
+ return Object.values(groups).map((group) => {
+ const suffix = group.sourceTable.replace(/^adx_/i, '');
+ // Suggested new table name uses a placeholder prefix — the user picks the actual publisher prefix.
+ const suggestedNewTable = `<your_prefix>_${suffix}`;
+ return {
+ sourceTable: group.sourceTable,
+ suggestedNewTable,
+ columns: group.columns,
+ checklist: [
+ `Create a new custom table \`${suggestedNewTable}\` in the Data workspace. Use your publisher's prefix in place of \`<your_prefix>\`.`,
+ `On the new table, add a lookup column (e.g., \`${suggestedNewTable}_powerpagecomponentid\`) targeting the \`powerpagecomponent\` table.`,
+ `Add each custom column from the original \`${group.sourceTable}\` table to the new table:\n${group.columns
+ .map((c) => ` - \`${c}\``)
+ .join('\n')}`,
+ `Migrate data: for each row in the source \`${group.sourceTable}\`, create a row in \`${suggestedNewTable}\` with the lookup column set to the matching \`powerpagecomponent\` record (joined via the same id) and copy the custom column values.`,
+ `Update any Liquid/FetchXML/plugin references that previously read \`${group.sourceTable}.<custom_column>\` to query the new \`${suggestedNewTable}\` table via the lookup.`,
+ ],
+ };
+ });
+}
+
+/**
+ * Categorize customization findings into manual-remediation buckets with per-finding guidance.
+ *
+ * NOTE: Earlier versions of this function attempted to "auto-create" missing string columns on
+ * adx_* tables for Data Model Extension findings. That implementation was incorrect — per the
+ * official migration doc, the correct fix is to create a NEW custom table with a lookup to
+ * powerpagecomponent and migrate data. That's a multi-step schema operation we don't automate.
+ *
+ * This function reports all five customization categories with category-specific richer guidance:
+ * - Data Model Extension: grouped by source table with full per-table checklist
+ * - Plugins: categorized by name prefix (Microsoft / Adxstudio / custom)
+ * - Custom workflow: doc's generic guidance (no per-workflow info available without Dataverse queries)
+ * - Liquid / FetchXML: pointer to the automate-* flags
+ *
+ * See: https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model#considerations-for-site-customization-when-migrating-sites-from-standard-to-enhanced-data-model
+ */
+async function executeAutomatedRemediation(customizations, envUrl) {
+ // envUrl is preserved for future use (e.g., querying Dataverse for workflow details).
+ void envUrl;
+
+ const remediationResults = {
+ automated: [],
+ manual: [],
+ informational: [],
+ needsReview: [],
+ errors: [],
+ dataModelChecklists: [],
+ pluginCategorySummary: { system: 0, adxstudio: 0, custom: 0 },
+ liquidCategorySummary: { 'needs-rewrite': 0, 'auto-fetchxml': 0, 'false-positive': 0, unknown: 0 },
+ };
+
+ const genericGuidance = {
+ 'Custom workflow':
+ 'Refactor the workflow to target `powerpagecomponent` and re-register on the new table; update attribute references. Workflow-specific guidance requires reviewing each workflow definition in Dataverse.',
+ 'FetchXml contains adx references':
+ "Use `--automate-fetchxml` to rewrite `<entity name='adx_*'>` and `<link-entity name='adx_*'>` to `powerpagecomponent` + `powerpagecomponenttype` filter automatically.",
+ };
+
+ Object.entries(customizations).forEach(([type, items]) => {
+ if (type === 'Data Model Extension') {
+ // Per-table checklist — replaces row-by-row manual entries.
+ remediationResults.dataModelChecklists = buildDataModelExtensionChecklists(items);
+ // Still record each finding in the manual list for traceability, but with the table-level
+ // reason pointing at the checklist.
+ items.forEach((item) => {
+ const { table, column } = parseDataModelExtension(item.snippet || '');
+ remediationResults.manual.push({
+ type,
+ snippet: item.snippet,
+ location: item.location,
+ reason: table && column
+ ? Object.hasOwn(COMPONENT_TYPE_MAP, table.toLowerCase())
+ ? `Custom column \`${column}\` on \`${table}\` — see per-table remediation checklist below.`
+ : `Finding on \`${table}\` is outside the supported metadata-table mapping. Review manually; do not apply the EDM custom-table transformation.`
+ : 'Could not parse table/column; review manually.',
+ parsed: { table, column },
+ });
+ });
+ return;
+ }
+
+ if (type === 'Plugins registered on adx entities') {
+ items.forEach((item) => {
+ const categorization = categorizePlugin(item.snippet || '');
+ remediationResults.pluginCategorySummary[categorization.category]++;
+ remediationResults.manual.push({
+ type,
+ snippet: item.snippet,
+ location: item.location,
+ reason: categorization.action,
+ parsed: categorization,
+ });
+ });
+ return;
+ }
+
+ if (type === 'Liquid contains adx references') {
+ items.forEach((item) => {
+ const categorization = categorizeLiquidFinding(item.snippet || '');
+ remediationResults.liquidCategorySummary[categorization.category]++;
+ remediationResults.manual.push({
+ type,
+ snippet: item.snippet,
+ location: item.location,
+ reason: categorization.action,
+ parsed: categorization,
+ });
+ });
+ return;
+ }
+
+ items.forEach((item) => {
+ remediationResults.manual.push({
+ type,
+ snippet: item.snippet,
+ location: item.location,
+ reason: genericGuidance[type] || 'Requires manual remediation.',
+ });
+ });
+ });
+
+ const records = remediationResults.manual;
+ remediationResults.manual = [];
+ for (const record of records) {
+ const assessment = classifyCustomizationFinding(record.type, record);
+ record.assessment = assessment;
+ const bucket = assessment.status === 'actionable' ? 'manual' : assessment.status;
+ remediationResults[bucket].push(record);
+ }
+ return remediationResults;
+}
+
+// ---------------------------------------------------------------------------
+// FetchXML and Liquid file rewriters (Phase 9 customization remediation)
+// ---------------------------------------------------------------------------
+
+/**
+ * Walk a directory recursively and return all files matching the given extensions.
+ */
+function walkSiteDirectory(rootPath, extensions) {
+ const results = [];
+ const entries = fs.readdirSync(rootPath, { withFileTypes: true });
+ for (const entry of entries) {
+ const fullPath = path.join(rootPath, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
+ results.push(...walkSiteDirectory(fullPath, extensions));
+ } else if (entry.isFile()) {
+ const ext = path.extname(entry.name).toLowerCase();
+ if (extensions.includes(ext)) {
+ results.push(fullPath);
+ }
+ }
+ }
+ return results;
+}
+
+/**
+ * Rewrite FetchXML in a string. Handles BOTH <entity> and <link-entity> blocks:
+ * renames `name="adx_X"` to `name="powerpagecomponent"` and injects a
+ * `powerpagecomponenttype` filter.
+ *
+ * Returns { newContent, changes: [{ tag, entity, typeValue }], skipped: [...] }.
+ * Unrecognized adx_* entities (e.g., custom tables) are flagged but not modified.
+ */
+function rewriteFetchXmlInContent(content) {
+ const changes = [];
+ const skipped = [];
+
+ // Accept a complete entity block before committing any nested link changes.
+ // Otherwise <entity name="adx_webpage"><filter type="or">...</filter>
+ // <link-entity name="adx_webtemplate">...</link-entity></entity> can retain
+ // a rewritten child even though its containing query requires manual review.
+ const result = content.replace(
+ /<entity\b[^>]*>[\s\S]*?<\/entity>|<link-entity\b[^>]*>[\s\S]*?<\/link-entity>/g,
+ (block) => {
+ const blockChanges = [];
+ const blockSkipped = [];
+ let candidate = rewriteTagBlocks(block, 'entity', blockChanges, blockSkipped);
+ if (blockSkipped.length === 0) {
+ candidate = rewriteTagBlocks(candidate, 'link-entity', blockChanges, blockSkipped);
+ }
+ skipped.push(...blockSkipped);
+ if (blockSkipped.length > 0) return block;
+ changes.push(...blockChanges);
+ return candidate;
+ },
+ );
+
+ return { newContent: result, changes, skipped };
+}
+
+/**
+ * Rewrite all <tagName ... name='adx_X' ...> ... </tagName> blocks in `content`.
+ * Used for both <entity> and <link-entity> — same rename + filter-injection logic.
+ *
+ * When tagName === 'entity', any nested <link-entity> blocks in the body are temporarily
+ * replaced with placeholders before searching for the entity's own <filter>, then restored.
+ * This prevents the outer entity from accidentally injecting its type filter into a nested
+ * link-entity's filter.
+ */
+function rewriteTagBlocks(content, tagName, changes, skipped) {
+ const blockRegex = new RegExp(
+ `<${tagName}\\b([^>]*?)\\bname\\s*=\\s*(['"])(adx_[\\w]+)\\2([^>]*)>([\\s\\S]*?)<\\/${tagName}>`,
+ 'g',
+ );
+
+ return content.replace(blockRegex, (match, beforeName, quote, entityName, afterName, body) => {
+ const typeValue = COMPONENT_TYPE_MAP[entityName.toLowerCase()];
+ if (typeValue === undefined) {
+ skipped.push({
+ tag: tagName,
+ entity: entityName,
+ reason: 'No powerpagecomponenttype mapping (custom or non-portal entity)',
+ });
+ return match;
+ }
+
+ const newOpenTag = `<${tagName}${beforeName}name=${quote}powerpagecomponent${quote}${afterName}>`;
+ const condition = `<condition attribute="powerpagecomponenttype" operator="eq" value="${typeValue}" />`;
+
+ // For outer <entity> tags, hide nested <link-entity>...</link-entity> behind placeholders
+ // so the filter regex only matches the entity's own (direct-child) filter.
+ const linkEntityBlocks = [];
+ // Keep sentinels printable and distinct from literal source text.
+ let linkPlaceholder = '__MIGRATION_LINK_ENTITY_';
+ while (body.includes(linkPlaceholder)) linkPlaceholder = `_${linkPlaceholder}`;
+ let scanBody = body;
+ if (tagName === 'entity') {
+ scanBody = body.replace(/<link-entity\b[\s\S]*?<\/link-entity>/g, (linkBlock) => {
+ const placeholder = `${linkPlaceholder}${linkEntityBlocks.length}__`;
+ linkEntityBlocks.push(linkBlock);
+ return placeholder;
+ });
+ }
+
+ const filterRegex = /<filter\b([^>]*)>([\s\S]*?)<\/filter>/;
+ let newScanBody;
+ const filterMatch = scanBody.match(filterRegex);
+ if (filterMatch) {
+ const filterAttrs = filterMatch[1] || '';
+ if (/type\s*=\s*(['"])or\1/i.test(filterAttrs)) {
+ skipped.push({
+ tag: tagName,
+ entity: entityName,
+ reason: "Existing <filter type='or'> — auto-injection would change semantics; manual review needed",
+ });
+ return match;
+ }
+ newScanBody = scanBody.replace(filterRegex, (_, attrs, inner) => {
+ const safeAttrs = attrs.trim() ? attrs : ' type="and"';
+ return `<filter${safeAttrs}>${inner}${condition}</filter>`;
+ });
+ } else {
+ newScanBody = scanBody.replace(/(\s*)$/, `\n <filter type="and">${condition}</filter>$1`);
+ }
+
+ // Restore link-entity blocks from placeholders.
+ let newBody = newScanBody;
+ if (linkEntityBlocks.length > 0) {
+ newBody = newBody.replace(new RegExp(`${linkPlaceholder}(\\d+)__`, 'g'), (_, idx) => linkEntityBlocks[parseInt(idx, 10)]);
+ }
+
+ changes.push({ tag: tagName, entity: entityName, typeValue });
+ return `${newOpenTag}${newBody}</${tagName}>`;
+ });
+}
+
+/**
+ * Add Liquid-comment suggestions next to entities['adx_*'] / entities["adx_*"] patterns.
+ * Does NOT overwrite the original — only inserts a `{# SUGGESTION: ... #}` (or `{%- comment -%}`) hint.
+ */
+function annotateLiquidEntitiesInContent(content) {
+ const suggestions = [];
+
+ // Match entities['adx_X'] and entities["adx_X"] (also handles entities[adx_X] without quotes)
+ const entitiesRegex = /entities\s*\[\s*(['"]?)(adx_\w+)\1\s*\]/g;
+
+ // Use a Set to keep one suggestion-comment per distinct line (avoid duplicates if same line has multiple matches).
+ const annotatedLines = new Set();
+ const lines = content.split('\n');
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ let m;
+ entitiesRegex.lastIndex = 0;
+ while ((m = entitiesRegex.exec(line)) !== null) {
+ const entityName = m[2].toLowerCase();
+ const mapping = LIQUID_OBJECT_MAP[entityName];
+ const suggestion = mapping
+ ? `Replace entities['${entityName}'] with: ${mapping.usage}`
+ : `entities['${entityName}'] — no dedicated Liquid object found; use powerpagecomponent FetchXML with powerpagecomponenttype filter`;
+ suggestions.push({ line: i + 1, entity: entityName, suggestion });
+ annotatedLines.add(i);
+ }
+ }
+
+ // Insert a comment line ABOVE each annotated line.
+ // Walk lines in reverse so insertion indices stay stable.
+ const sortedLineIndices = [...annotatedLines].sort((a, b) => b - a);
+ for (const idx of sortedLineIndices) {
+ const matchesOnThisLine = suggestions.filter((s) => s.line === idx + 1);
+ const commentText = matchesOnThisLine.map((s) => s.suggestion).join(' | ');
+ // Detect leading whitespace of the target line so the comment lines up.
+ const leadingWhitespace = (lines[idx].match(/^\s*/) || [''])[0];
+ const commentLine = `${leadingWhitespace}{%- comment -%} SDM→EDM SUGGESTION: ${commentText} {%- endcomment -%}`;
+ lines.splice(idx, 0, commentLine);
+ }
+
+ return { newContent: lines.join('\n'), suggestions };
+}
+
+/**
+ * Generate a unified-diff-style string for two file contents.
+ * Minimal implementation — line-level only, no context smarts.
+ */
+function unifiedDiff(oldContent, newContent, filePath) {
+ if (oldContent === newContent) return '';
+ const header = `--- ${filePath}\n+++ ${filePath}\n`;
+ const prefixes = { context: ' ', removed: '- ', added: '+ ' };
+ const out = diffLines(oldContent, newContent).map((line) => prefixes[line.type] + line.text);
+ return header + out.join('\n') + '\n';
+}
+
+function diffLines(oldContent, newContent) {
+ const oldLines = oldContent.split('\n');
+ const newLines = newContent.split('\n');
+ const stream = [];
+ let i = 0;
+ let j = 0;
+ while (i < oldLines.length || j < newLines.length) {
+ if (i < oldLines.length && j < newLines.length && oldLines[i] === newLines[j]) {
+ stream.push({ type: 'context', text: oldLines[i], oldLine: i + 1, newLine: j + 1 });
+ i++;
+ j++;
+ } else {
+ let oi = i;
+ let nj = j;
+ while (oi < oldLines.length && newLines.indexOf(oldLines[oi], j) === -1) oi++;
+ while (nj < newLines.length && oldLines.indexOf(newLines[nj], i) === -1) nj++;
+ // Reordered lines (old A,B; new B,A) otherwise leave both cursors
+ // stationary. Represent this pair as a replacement to guarantee progress.
+ if (oi === i && nj === j) {
+ oi = Math.min(i + 1, oldLines.length);
+ nj = Math.min(j + 1, newLines.length);
+ }
+ for (let k = i; k < oi; k++) stream.push({ type: 'removed', text: oldLines[k], oldLine: k + 1 });
+ for (let k = j; k < nj; k++) stream.push({ type: 'added', text: newLines[k], newLine: k + 1 });
+ i = oi;
+ j = nj;
+ }
+ }
+ return stream;
+}
+
+/**
+ * Structured diff used by `remediation-diff.json`. Walks the two line arrays
+ * in parallel (same algorithm as unifiedDiff) and groups adjacent changes
+ * into hunks with `CONTEXT_LINES` of surrounding context. Returns
+ * { linesAdded, linesRemoved, hunks: [...] } — hunks have the shape:
+ * {
+ * oldStart, oldCount, newStart, newCount,
+ * lines: [ { type: 'context'|'added'|'removed', text, oldLine?, newLine? } ]
+ * }
+ */
+const CONTEXT_LINES = 3;
+function structuredDiff(oldContent, newContent) {
+ const stream = diffLines(oldContent, newContent);
+
+ // Slice into hunks: a hunk is a run of non-context lines bracketed by
+ // up to CONTEXT_LINES of context on either side. Adjacent change runs
+ // within 2*CONTEXT_LINES of each other are merged.
+ let linesAdded = 0;
+ let linesRemoved = 0;
+ for (const line of stream) {
+ if (line.type === 'added') linesAdded++;
+ else if (line.type === 'removed') linesRemoved++;
+ }
+
+ const hunks = [];
+ let k = 0;
+ while (k < stream.length) {
+ if (stream[k].type === 'context') {
+ k++;
+ continue;
+ }
+ // Found a change. Walk back for context.
+ const hunkStart = Math.max(0, k - CONTEXT_LINES);
+ let hunkEnd = k;
+ while (hunkEnd < stream.length) {
+ if (stream[hunkEnd].type !== 'context') {
+ hunkEnd++;
+ continue;
+ }
+ // Look ahead — if another change is within 2*CONTEXT_LINES, keep going.
+ let nextChange = -1;
+ for (let p = hunkEnd; p < Math.min(stream.length, hunkEnd + 2 * CONTEXT_LINES); p++) {
+ if (stream[p].type !== 'context') {
+ nextChange = p;
+ break;
+ }
+ }
+ if (nextChange === -1) break;
+ hunkEnd = nextChange;
+ }
+ const trailingEnd = Math.min(stream.length, hunkEnd + CONTEXT_LINES);
+ const slice = stream.slice(hunkStart, trailingEnd);
+
+ // Compute oldStart/newStart from first context-or-change line.
+ let oldStart = null;
+ let newStart = null;
+ let oldCount = 0;
+ let newCount = 0;
+ for (const line of slice) {
+ if (line.oldLine != null && oldStart == null) oldStart = line.oldLine;
+ if (line.newLine != null && newStart == null) newStart = line.newLine;
+ if (line.type === 'context') { oldCount++; newCount++; }
+ else if (line.type === 'removed') oldCount++;
+ else if (line.type === 'added') newCount++;
+ }
+
+ hunks.push({
+ oldStart: oldStart || 1,
+ oldCount,
+ newStart: newStart || 1,
+ newCount,
+ lines: slice,
+ });
+
+ k = trailingEnd;
+ }
+
+ return { linesAdded, linesRemoved, hunks };
+}
+
+/**
+ * Materialize a staged copy of `live` at `stagedPath` (mkdir -p its parent).
+ */
+function writeStaged(stagedPath, content) {
+ fs.mkdirSync(path.dirname(stagedPath), { recursive: true });
+ fs.writeFileSync(stagedPath, content, 'utf-8');
+}
+
+/**
+ * Run the FetchXML auto-rewriter. Writes proposed files to
+ * `<outputDir>/remediation-staged/<relPath>`. Does NOT modify live files.
+ * Live source remains untouched until the apply-remediation step copies
+ * staged → live after explicit user approval.
+ */
+function executeFetchXmlRewrites(sitePath, outputDir) {
+ if (!fs.existsSync(sitePath)) {
+ throw new Error(`Site path not found: ${sitePath}`);
+ }
+
+ const stagedDir = path.join(outputDir, 'remediation-staged');
+ const files = walkSiteDirectory(sitePath, ['.html', '.yml']);
+ const results = { filesScanned: 0, filesModified: 0, rewrites: [], skipped: [], diffEntries: [] };
+
+ for (const file of files) {
+ results.filesScanned++;
+ const content = fs.readFileSync(file, 'utf-8');
+ if (!/<(?:link-)?entity\b[^>]*\bname\s*=\s*['"]adx_/.test(content)) continue;
+
+ const { newContent, changes, skipped } = rewriteFetchXmlInContent(content);
+ if (changes.length > 0 && newContent !== content) {
+ const relativePath = path.relative(sitePath, file);
+ const stagedPath = path.join(stagedDir, relativePath);
+ writeStaged(stagedPath, newContent);
+ const diff = structuredDiff(content, newContent);
+ results.filesModified++;
+ results.rewrites.push({ file, stagedPath, changes });
+ results.diffEntries.push({
+ relativePath,
+ kind: 'fetchxml',
+ status: 'modified',
+ linesAdded: diff.linesAdded,
+ linesRemoved: diff.linesRemoved,
+ hunks: diff.hunks,
+ changeSummary: changes.map((c) => `${c.tag}: ${c.entity} → powerpagecomponent (type=${c.typeValue})`),
+ livePath: file,
+ stagedPath,
+ });
+ }
+ if (skipped.length > 0) {
+ results.skipped.push({ file, skipped });
+ }
+ }
+
+ results.stagedDir = stagedDir;
+ return results;
+}
+
+/**
+ * Run the Liquid entities['adx_*'] semi-auto rewriter. Writes annotated files
+ * to `<outputDir>/remediation-staged/<relPath>` — does NOT modify live files.
+ */
+function executeLiquidRewrites(sitePath, outputDir) {
+ if (!fs.existsSync(sitePath)) {
+ throw new Error(`Site path not found: ${sitePath}`);
+ }
+
+ const stagedDir = path.join(outputDir, 'remediation-staged');
+ const files = walkSiteDirectory(sitePath, ['.html']);
+ const results = { filesScanned: 0, filesAnnotated: 0, suggestions: [], diffEntries: [] };
+
+ for (const file of files) {
+ results.filesScanned++;
+ const content = fs.readFileSync(file, 'utf-8');
+ if (!/entities\s*\[/.test(content)) continue;
+
+ const { newContent, suggestions } = annotateLiquidEntitiesInContent(content);
+ if (suggestions.length > 0 && newContent !== content) {
+ const relativePath = path.relative(sitePath, file);
+ const stagedPath = path.join(stagedDir, relativePath);
+ // FetchXML rewriter may already have staged this file — if so, diff the
+ // staged version against the Liquid output to preserve both passes.
+ const baseContent = fs.existsSync(stagedPath) ? fs.readFileSync(stagedPath, 'utf-8') : content;
+ const liquidOnly = annotateLiquidEntitiesInContent(baseContent);
+ const finalContent = liquidOnly.newContent !== baseContent ? liquidOnly.newContent : newContent;
+ writeStaged(stagedPath, finalContent);
+ const diff = structuredDiff(content, finalContent);
+ results.filesAnnotated++;
+ results.suggestions.push({ file, stagedPath, suggestions });
+ results.diffEntries.push({
+ relativePath,
+ kind: 'liquid',
+ status: 'modified',
+ linesAdded: diff.linesAdded,
+ linesRemoved: diff.linesRemoved,
+ hunks: diff.hunks,
+ changeSummary: suggestions.map((s) => `${s.entity} → ${s.suggestion}`),
+ livePath: file,
+ stagedPath,
+ });
+ }
+ }
+
+ results.stagedDir = stagedDir;
+ return results;
+}
+
+/**
+ * Merge per-rewriter diff entries by relativePath and emit `remediation-diff.json`.
+ *
+ * The emitted JSON is a lean, skill-owned manifest consumed only by the live
+ * report's Remediation Diff card: `generatedAt`, `siteRoot`, `stagedDir`, and
+ * `files[]` (each with `relativePath`, `kind`, `status`, `linesAdded`,
+ * `linesRemoved`, `hunks[]`, `changeSummary[]`, and ABSOLUTE `livePath` /
+ * `stagedPath`). The report turns each file into a `code --diff "<live>"
+ * "<staged>"` command the user runs in any terminal — VS Code's built-in diff
+ * editor, no extension required.
+ */
+function writeRemediationDiff(sitePath, outputDir, fetchXmlResults, liquidResults) {
+ const fxEntries = (fetchXmlResults && fetchXmlResults.diffEntries) || [];
+ const lqEntries = (liquidResults && liquidResults.diffEntries) || [];
+
+ const byPath = new Map();
+ for (const e of fxEntries) byPath.set(e.relativePath, { ...e });
+ for (const e of lqEntries) {
+ const existing = byPath.get(e.relativePath);
+ if (existing) {
+ existing.kind = 'fetchxml+liquid';
+ existing.linesAdded = e.linesAdded;
+ existing.linesRemoved = e.linesRemoved;
+ existing.hunks = e.hunks;
+ existing.changeSummary = (existing.changeSummary || []).concat(e.changeSummary || []);
+ } else {
+ byPath.set(e.relativePath, { ...e });
+ }
+ }
+
+ const files = [...byPath.values()].sort((a, b) => a.relativePath.localeCompare(b.relativePath));
+ if (files.length === 0) return null;
+
+ // Normalize livePath/stagedPath to ABSOLUTE so the report's per-file
+ // `code --diff "<live>" "<staged>"` commands work when pasted into a fresh
+ // terminal whose working directory is unrelated to the site root or output
+ // dir. Resolved here — the same process/cwd that just wrote the staged files —
+ // so any relative inputs resolve correctly.
+ for (const entry of files) {
+ if (entry.livePath) entry.livePath = path.resolve(entry.livePath);
+ if (entry.stagedPath) entry.stagedPath = path.resolve(entry.stagedPath);
+ }
+
+ const payload = {
+ generatedAt: new Date().toISOString(),
+ siteRoot: path.resolve(sitePath),
+ stagedDir: path.resolve(path.join(outputDir, 'remediation-staged')),
+ files,
+ };
+
+ const outPath = path.join(outputDir, 'remediation-diff.json');
+ fs.writeFileSync(outPath, JSON.stringify(payload, null, 2) + '\n', 'utf-8');
+ return { outPath, fileCount: files.length };
+}
+
+function prepareRemediation(sitePath, outputDir, requestedKinds) {
+ const kinds = new Set(requestedKinds);
+ const manifestPath = path.join(outputDir, 'remediation-diff.json');
+ if (fs.existsSync(manifestPath)) {
+ const previous = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
+ if (!previous || typeof previous.siteRoot !== 'string' ||
+ path.resolve(previous.siteRoot) !== path.resolve(sitePath) || !Array.isArray(previous.files)) {
+ throw new Error('Existing remediation manifest does not match the selected site root');
+ }
+ for (const entry of previous.files) {
+ if (!entry || !['fetchxml', 'liquid', 'fetchxml+liquid'].includes(entry.kind)) {
+ throw new Error(`Unknown remediation kind: ${entry?.kind}`);
+ }
+ for (const kind of entry.kind.split('+')) kinds.add(kind);
+ }
+ }
+ // Rebuild all previously selected passes from current live source. This
+ // preserves separate FetchXML/Liquid invocations without trusting stale staged
+ // content or carrying forward a manifest after a zero-change rerun.
+ fs.rmSync(manifestPath, { force: true });
+ fs.rmSync(path.join(outputDir, 'remediation-staged'), { recursive: true, force: true });
+ return kinds;
+}
+
+// ---------------------------------------------------------------------------
+// Augmented prompts for customer-owned code (Plugin + DME remediation)
+// ---------------------------------------------------------------------------
+
+/**
+ * Load a prompt template from scripts/prompts/.
+ * Templates contain `{{TOKEN}}` placeholders that are filled in at runtime.
+ */
+function loadPromptTemplate(templateName) {
+ const templatePath = path.join(__dirname, 'prompts', templateName);
+ if (!fs.existsSync(templatePath)) {
+ throw new Error(`Prompt template not found: ${templatePath}`);
+ }
+ return fs.readFileSync(templatePath, 'utf-8');
+}
+
+/**
+ * Format the plugin findings as a markdown table block for the prompt.
+ * Categorizes each finding using the same logic as categorizePlugin().
+ */
+function formatPluginFindingsBlock(pluginFindings) {
+ if (!pluginFindings || pluginFindings.length === 0) {
+ return '*(No plugin findings — this prompt was generated empty. Skip plugin remediation.)*';
+ }
+
+ const rows = pluginFindings.map((item) => {
+ const cat = categorizePlugin(item.snippet || '');
+ const category = cat.category === 'system'
+ ? 'Microsoft (no action)'
+ : cat.category === 'adxstudio'
+ ? 'Adxstudio (verify V2)'
+ : cat.componentType === null || cat.pluginName === 'unknown'
+ ? 'Custom (manual review; keep target unchanged)'
+ : `Custom (mapped metadata; type ${cat.componentType}; review refactor)`;
+ return `| \`${cat.pluginName}\` | \`${cat.entity || '?'}\` | ${cat.stepName || '?'} | ${category} |`;
+ });
+
+ return [
+ '| Plugin name | Target entity | Step name | Category |',
+ '| --- | --- | --- | --- |',
+ ...rows,
+ ].join('\n');
+}
+
+/**
+ * Format the DME findings as a markdown table block grouped by source table.
+ */
+function formatDmeTableGroupsBlock(dmeChecklists) {
+ if (!dmeChecklists || dmeChecklists.length === 0) {
+ return '*(No Data Model Extension findings — this prompt was generated empty. Skip DME remediation.)*';
+ }
+
+ const sections = dmeChecklists.map((group) => {
+ const columnList = group.columns.map((c) => `- \`${c}\``).join('\n');
+ return [
+ `### Source: \`${group.sourceTable}\` → suggested target: \`${group.suggestedNewTable}\``,
+ '',
+ 'Custom columns to move:',
+ '',
+ columnList,
+ ].join('\n');
+ });
+
+ return sections.join('\n\n');
+}
+
+/**
+ * Generate the plugin remediation prompt by filling the template with findings.
+ * Returns the full prompt text. Caller is responsible for writing it to disk.
+ */
+function generatePluginRemediationPrompt(pluginFindings) {
+ const template = loadPromptTemplate('plugin-remediation.template.txt');
+ const findingsBlock = formatPluginFindingsBlock(pluginFindings);
+ const mappingBlock = [
+ '| Source logical name | powerpagecomponenttype |',
+ '| --- | --- |',
+ ...Object.entries(COMPONENT_TYPE_MAP).map(([name, value]) => `| \`${name}\` | ${value} |`),
+ ].join('\n');
+ return fillPlaceholders(template, {
+ '{{PLUGIN_FINDINGS_BLOCK}}': findingsBlock,
+ '{{PLUGIN_METADATA_MAPPING_BLOCK}}': mappingBlock,
+ });
+}
+
+/**
+ * Generate the DME remediation prompt by filling the template with checklists.
+ */
+function generateDmeRemediationPrompt(dmeChecklists) {
+ const template = loadPromptTemplate('dme-remediation.template.txt');
+ const tableGroupsBlock = formatDmeTableGroupsBlock(dmeChecklists);
+ return template.replace('{{DME_TABLE_GROUPS_BLOCK}}', tableGroupsBlock);
+}
+
+/**
+ * Write augmented prompts to .txt files in <output-dir> and return paths +
+ * the prompt strings (so the caller can also embed them in the HTML report).
+ */
+function writeAugmentedPrompts(customizations, remediationResults, outputDir) {
+ const pluginFindings = customizations['Plugins registered on adx entities'] || [];
+ const dmeChecklists = (remediationResults && remediationResults.dataModelChecklists) || [];
+
+ const result = { pluginPath: null, dmePath: null, pluginPrompt: '', dmePrompt: '' };
+
+ if (pluginFindings.length > 0) {
+ result.pluginPrompt = generatePluginRemediationPrompt(pluginFindings);
+ result.pluginPath = path.join(outputDir, 'plugin-remediation-prompt.txt');
+ fs.writeFileSync(result.pluginPath, result.pluginPrompt, 'utf-8');
+ }
+
+ if (dmeChecklists.length > 0) {
+ result.dmePrompt = generateDmeRemediationPrompt(dmeChecklists);
+ result.dmePath = path.join(outputDir, 'dme-remediation-prompt.txt');
+ fs.writeFileSync(result.dmePath, result.dmePrompt, 'utf-8');
+ }
+
+ return result;
+}
+
+/**
+ * Print the augmented prompts to the console with clear visual separators
+ * so the user knows where to copy from.
+ */
+function printAugmentedPromptsToConsole(promptResults) {
+ if (!promptResults.pluginPrompt && !promptResults.dmePrompt) return;
+
+ const banner = '═'.repeat(75);
+ console.log('');
+ console.log(banner);
+ console.log(' MANUAL REMEDIATION — augmented prompts ready');
+ console.log(banner);
+ console.log('');
+ console.log('The customization scan flagged manual remediation in two categories that');
+ console.log('this skill does NOT modify directly (your code stays yours):');
+ console.log('');
+ if (promptResults.pluginPath) {
+ console.log(` → Plugin remediation prompt: ${promptResults.pluginPath}`);
+ }
+ if (promptResults.dmePath) {
+ console.log(` → DME remediation prompt: ${promptResults.dmePath}`);
+ }
+ console.log('');
+ console.log('Paste each into a new Claude Code session pointed at the relevant');
+ console.log('working directory (your plugin source repo, or any empty dir for DME).');
+ console.log('');
+ console.log(banner);
+ console.log('');
+}
+
+/**
+ * Main function
+ */
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+
+ // Validate required arguments
+ const required = ['site-name', 'website-id', 'output-dir'];
+ for (const arg of required) {
+ if (!args[arg]) {
+ console.error(`Error: --${arg} is required`);
+ process.exit(1);
+ }
+ }
+
+ try {
+ const sitePath = args['automate-fetchxml'] || args['automate-liquid']
+ ? requirePowerPagesSiteRoot(args['site-path'] || args['sitePath'])
+ : null;
+ if (!fs.existsSync(args['output-dir'])) {
+ fs.mkdirSync(args['output-dir'], { recursive: true });
+ }
+ // Parse customization report if provided
+ let customizations = {};
+ const customizationReportPath =
+ args['customization-report'] ||
+ args['siteCustomizationReportPath'] ||
+ args['siteCustomizationReport'] ||
+ args['report-path'] ||
+ args['reportPath'];
+
+ if (customizationReportPath) {
+ customizations = parseCustomizationReport(customizationReportPath);
+ }
+
+ // Always categorize findings if we have a customization report — this is local-only
+ // analysis (no Dataverse calls) that enriches the execution report with per-finding
+ // guidance (Liquid categorization, plugin categorization, Data Model Extension
+ // per-table checklists). The legacy --automate flag is retained for back-compat but
+ // is now a no-op marker.
+ let remediationResults = null;
+ if (Object.keys(customizations).length > 0) {
+ const envUrl = args['env-url'] || args['envUrl'] || null;
+ remediationResults = await executeAutomatedRemediation(customizations, envUrl);
+ const total = Object.values(customizations).reduce((sum, items) => sum + items.length, 0);
+ console.log(
+ `Categorized ${total} scan references: ${remediationResults.informational.length} informational, ` +
+ `${remediationResults.manual.length} actionable, ${remediationResults.needsReview.length} need context review`,
+ );
+ }
+
+ let remediationKinds = new Set();
+ if (sitePath) {
+ remediationKinds = prepareRemediation(sitePath, args['output-dir'], [
+ ...(args['automate-fetchxml'] ? ['fetchxml'] : []),
+ ...(args['automate-liquid'] ? ['liquid'] : []),
+ ]);
+ }
+
+ // Run FetchXML auto-rewriter if requested
+ let fetchXmlRewriteResults = null;
+ let sitePathUsed = null;
+ if (remediationKinds.has('fetchxml')) {
+ sitePathUsed = sitePath;
+ console.log(`Rewriting FetchXML in: ${sitePath} → staging to remediation-staged/`);
+ fetchXmlRewriteResults = executeFetchXmlRewrites(sitePath, args['output-dir']);
+ console.log(`✓ FetchXML: scanned ${fetchXmlRewriteResults.filesScanned} files, staged ${fetchXmlRewriteResults.filesModified}, skipped ${fetchXmlRewriteResults.skipped.length}`);
+ }
+
+ // Run Liquid entities[''] semi-auto rewriter if requested
+ let liquidRewriteResults = null;
+ if (remediationKinds.has('liquid')) {
+ sitePathUsed = sitePathUsed || sitePath;
+ console.log(`Annotating Liquid entities[adx_*] usages in: ${sitePath} → staging to remediation-staged/`);
+ liquidRewriteResults = executeLiquidRewrites(sitePath, args['output-dir']);
+ console.log(`✓ Liquid: scanned ${liquidRewriteResults.filesScanned} files, staged ${liquidRewriteResults.filesAnnotated}`);
+ }
+
+ // Emit remediation-diff.json combining FetchXML + Liquid passes.
+ if (sitePathUsed && (fetchXmlRewriteResults || liquidRewriteResults)) {
+ const diffOutcome = writeRemediationDiff(sitePathUsed, args['output-dir'], fetchXmlRewriteResults, liquidRewriteResults);
+ if (diffOutcome) {
+ console.log(`✓ Remediation diff: ${diffOutcome.outPath} (${diffOutcome.fileCount} file${diffOutcome.fileCount === 1 ? '' : 's'})`);
+ } else {
+ console.log('✓ No remediation diff to emit — auto-rewriters made zero modifications.');
+ }
+ }
+
+ // Generate augmented prompts for plugin and DME findings (customer-owned code
+ // is not modified by this skill — instead, paste-ready prompts are produced for
+ // the user to take to a fresh Claude session that can act on their plugin source
+ // or build a Dataverse solution package).
+ const promptResults = writeAugmentedPrompts(customizations, remediationResults, args['output-dir']);
+ if (promptResults.pluginPath) {
+ console.log(`✓ Plugin remediation prompt: ${promptResults.pluginPath}`);
+ }
+ if (promptResults.dmePath) {
+ console.log(`✓ DME remediation prompt: ${promptResults.dmePath}`);
+ }
+
+ // Generate customization report
+ const assessment = assessCustomizations(customizations);
+ fs.writeFileSync(path.join(args['output-dir'], 'customization-assessment.json'),
+ JSON.stringify(assessment, null, 2) + '\n', 'utf8');
+ const customizationHtml = generateCustomizationReportHtml(args, customizations, assessment);
+ const customizationPath = path.join(args['output-dir'], 'customization-report.html');
+ fs.writeFileSync(customizationPath, customizationHtml, 'utf-8');
+ console.log(`✓ Customization report generated: ${customizationPath}`);
+
+ // This script intentionally does NOT write datamodel-migration-report.html.
+ // That file is the LIVE execution report, owned exclusively by update-state.js +
+ // lib/render-live-report.js, which re-render it from migration-state.json after every
+ // step. Writing it here (from a static template with generic/hardcoded content) would
+ // clobber the live report every time this script runs for the customization pass.
+
+ console.log('\nReports generated successfully!');
+ console.log(`Open in browser: ${pathToFileURL(path.resolve(customizationPath)).href}`);
+
+ // Print the augmented-prompt handoff to the terminal with clear visual separators.
+ printAugmentedPromptsToConsole(promptResults);
+ } catch (error) {
+ console.error(`Error: ${error.message}`);
+ process.exit(1);
+ }
+}
+
+if (require.main === module) main();
+
+module.exports = {
+ diffLines, structuredDiff, unifiedDiff, parseCSV, normalizeLocationPath,
+ fillPlaceholders, generateCustomizationSection, rewriteFetchXmlInContent,
+ annotateLiquidEntitiesInContent, buildDataModelExtensionChecklists, categorizePlugin,
+ makeRequestWithRetry,
+ categorizeLiquidFinding, classifyCustomizationFinding, assessCustomizations,
+ executeAutomatedRemediation,
+};
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/lib/edm-table-classification.js b/plugins/power-pages/skills/migrate-datamodel/scripts/lib/edm-table-classification.js
new file mode 100644
index 000000000..11e427c08
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/lib/edm-table-classification.js
@@ -0,0 +1,106 @@
+'use strict';
+
+// Microsoft EDM categories are intentionally kept separate from the local
+// snapshot scanner names. Nonconfiguration data is not part of the SDM -> EDM
+// metadata comparison, while virtual configuration such as poll placements is.
+const NONCONFIGURATION_TABLES = [
+ { category: 'ads', label: 'Ads', table: 'Ad' },
+ { category: 'polls', label: 'Polls', table: 'Poll' },
+ { category: 'pollSubmissions', label: 'Poll submissions', table: 'Poll Submission' },
+ { category: 'externalIdentities', label: 'External identities', table: 'External Identity' },
+ { category: 'portalComments', label: 'Portal comments', table: 'Portal comment' },
+ { category: 'invitations', label: 'Invitations', table: 'Invitation' },
+ { category: 'invitationRedemptions', label: 'Invitation redemptions', table: 'Invitation Redemption' },
+ // "Setting" is not adx_sitesetting: siteSettings contains migrated metadata
+ // and must retain count/value validation.
+ // https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model
+ { category: 'settings', label: 'Settings', table: 'Setting' },
+ { category: 'webFormSessions', label: 'Web form sessions', table: 'WebFormSession' },
+];
+
+const NONCONFIGURATION_CATEGORIES = new Set(NONCONFIGURATION_TABLES.map(({ category }) => category));
+
+const SDM_ONLY_CATEGORIES = new Set([
+ 'tags',
+ 'websiteBindings',
+]);
+
+// These categories are retained in raw snapshots but are not shown in the
+// metadata component comparison. websiteBindings is an expected SDM-only
+// download difference; forums/blogs/ideas are reserved for future scanners.
+const REPORT_EXCLUDED_CATEGORIES = new Set([
+ ...NONCONFIGURATION_CATEGORIES,
+ 'forums',
+ 'blogs',
+ 'ideas',
+ 'websiteBindings',
+]);
+
+const CATEGORY_METADATA = {
+ ads: {
+ label: 'Ads',
+ reason: 'Ads are nonconfiguration data and are removed from the enhanced data model.',
+ },
+ polls: {
+ label: 'Polls',
+ reason: 'Polls are nonconfiguration data and are removed from the enhanced data model.',
+ },
+ pollSubmissions: {
+ label: 'Poll submissions',
+ reason: 'Poll submissions are nonconfiguration runtime data and are not part of the metadata migration.',
+ },
+ externalIdentities: {
+ label: 'External identities',
+ reason: 'External identities are nonconfiguration runtime data and are not part of the metadata migration.',
+ },
+ portalComments: {
+ label: 'Portal comments',
+ reason: 'Portal comments are nonconfiguration runtime data and are not part of the metadata migration.',
+ },
+ invitations: {
+ label: 'Invitations',
+ reason: 'Invitations are nonconfiguration runtime data and are not part of the metadata migration.',
+ },
+ invitationRedemptions: {
+ label: 'Invitation redemptions',
+ reason: 'Invitation redemptions are nonconfiguration runtime data and are not part of the metadata migration.',
+ },
+ settings: {
+ label: 'Settings',
+ reason: 'Settings are listed as nonconfiguration data in the enhanced data model.',
+ },
+ webFormSessions: {
+ label: 'Web form sessions',
+ reason: 'Web form sessions are nonconfiguration runtime data and are not part of the metadata migration.',
+ },
+};
+
+function isNonconfigurationCategory(category) {
+ return NONCONFIGURATION_CATEGORIES.has(category);
+}
+
+function isSdmOnlyCategory(category) {
+ return SDM_ONLY_CATEGORIES.has(category);
+}
+
+function isReportExcludedCategory(category) {
+ return REPORT_EXCLUDED_CATEGORIES.has(category);
+}
+
+function getCategoryMetadata(category) {
+ return CATEGORY_METADATA[category] || {
+ label: category,
+ reason: 'This category is outside the SDM to EDM metadata comparison scope.',
+ };
+}
+
+module.exports = {
+ NONCONFIGURATION_TABLES,
+ NONCONFIGURATION_CATEGORIES,
+ SDM_ONLY_CATEGORIES,
+ REPORT_EXCLUDED_CATEGORIES,
+ isNonconfigurationCategory,
+ isSdmOnlyCategory,
+ isReportExcludedCategory,
+ getCategoryMetadata,
+};
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/lib/migration-state-schema.js b/plugins/power-pages/skills/migrate-datamodel/scripts/lib/migration-state-schema.js
new file mode 100644
index 000000000..d01637478
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/lib/migration-state-schema.js
@@ -0,0 +1,274 @@
+/**
+ * migration-state-schema.js
+ *
+ * Source of truth for migration-state.json. Three responsibilities:
+ * 1. `buildInitialState()` — the skeleton the skill writes at startup, before any
+ * sub-step has run. Defaults to the Authoring Track (more common). Matches stage0-initialized.html.
+ * 2. Constants for status / kind / track values used by phases, sub-steps, the
+ * approval gate, and the augmented-prompt cards.
+ * 3. Canonical phase blueprints per track. Phase 1 and Phase 4 are shared across
+ * tracks; Phase 2 and Phase 3 differ.
+ *
+ * Authoring Track (CLI value `A`) — mode is `configurationData` or `all`
+ * For Dev / Test / UAT / Single env. Migrates metadata locally, allows a
+ * customization-remediation pass, then activates EDM.
+ *
+ * Downstream Track (CLI value `B`) — mode is `configurationDataReferences`
+ * For Prod (ALM assumed). Verifies metadata is already in EDM, then migrates
+ * transactional references and activates.
+ *
+ * Kept deliberately small: no I/O, no rendering, no CLI concerns. Pure data.
+ */
+
+const SCHEMA_VERSION = 1;
+
+const PHASE_STATUS = Object.freeze({
+ PENDING: 'pending',
+ PENDING_APPROVAL: 'pending-approval',
+ IN_PROGRESS: 'in-progress',
+ COMPLETED: 'completed',
+ BLOCKED: 'blocked',
+});
+
+const SUB_STEP_STATUS = Object.freeze({
+ PENDING: 'pending',
+ IN_PROGRESS: 'in-progress',
+ COMPLETED: 'completed',
+ BLOCKED: 'blocked',
+});
+
+const APPROVAL_KIND = Object.freeze({
+ PHASE_START: 'phase-start',
+ IN_PHASE: 'in-phase',
+});
+
+const PROMPT_STATUS = Object.freeze({
+ PENDING: 'pending',
+ READY: 'ready',
+});
+
+const TRACK = Object.freeze({
+ A: 'A',
+ B: 'B',
+});
+
+// The Authoring Track defaults to Dev/Test/UAT/Single-env (the most common). Until step 1.7
+// runs --set-track, the live report renders against this default.
+const DEFAULT_TRACK = TRACK.A;
+
+// ── Phase blueprints ───────────────────────────────────────────────────────
+// Phase 1 and Phase 4 are shared across tracks.
+
+const PHASE_1 = {
+ id: 1,
+ title: 'Site Discovery & Pre-checks',
+ subSteps: [
+ { id: '1.1', label: 'Establish CLI Context' },
+ { id: '1.2', label: 'Identify Site Context' },
+ { id: '1.3', label: 'Site Discovery and Validate Data Model' },
+ { id: '1.4', label: 'Check Existing Migration Status' },
+ { id: '1.5', label: 'Validate Required Dependencies' },
+ { id: '1.6', label: 'Validate Site Template and V2 Package' },
+ { id: '1.7', label: 'Determine Environment Type and Migration Mode' },
+ ],
+};
+
+const PHASE_4 = {
+ id: 4,
+ title: 'Post-Migration Validation',
+ subSteps: [
+ { id: '4.1', label: 'Runtime Smoke Test Recommendation (/test-site)' },
+ { id: '4.2', label: 'Final Status, Optional Rollback, Summary' },
+ ],
+};
+
+const PHASE_2_TRACK_A = {
+ id: 2,
+ title: 'Configuration Migration & Customization Remediation',
+ subSteps: [
+ { id: '2.1', label: 'Capture SDM Snapshot' },
+ { id: '2.2', label: 'Migrate Metadata' },
+ { id: '2.3', label: 'Locate Customization Report' },
+ { id: '2.4', label: 'Remediate Customizations' },
+ ],
+};
+
+const PHASE_2_TRACK_B = {
+ id: 2,
+ title: 'Setting Up Metadata',
+ subSteps: [
+ { id: '2.1', label: 'Verify Site in Target Environment' },
+ { id: '2.2', label: 'Import Metadata if Missing' },
+ { id: '2.3', label: 'Confirm Metadata Ready' },
+ ],
+};
+
+// Phase 3 differs by track. The Authoring Track already cleaned up customizations in Phase 2.3,
+// so Phase 3 only needs verify metadata → migrate refs → activate → restart. The Downstream Track
+// never ran the customization remediation in Phase 2, so Phase 3 includes locate + remediate
+// after refs migrate.
+const PHASE_3_TRACK_A = {
+ id: 3,
+ title: 'Migration Execution',
+ subSteps: [
+ { id: '3.1', label: 'Data Diff Validation (SDM ↔ EDM Metadata)' },
+ // When mode=`all`, SKILL.md instructs the agent to mark 3.2 completed with
+ // output "Skipped — refs already migrated in Phase 2.1 (mode=all)".
+ { id: '3.2', label: 'Migrate Transactional References' },
+ { id: '3.3', label: 'Activate EDM (Update Data Model Version)' },
+ { id: '3.4', label: 'Restart Site' },
+ ],
+};
+
+const PHASE_3_TRACK_B = {
+ id: 3,
+ title: 'Migration Execution',
+ subSteps: [
+ { id: '3.1', label: 'Data Diff Validation (SDM ↔ EDM Metadata)' },
+ { id: '3.2', label: 'Migrate Transactional References' },
+ { id: '3.3', label: 'Locate Customization Report' },
+ { id: '3.4', label: 'Remediate Customizations' },
+ { id: '3.5', label: 'Activate EDM (Update Data Model Version)' },
+ { id: '3.6', label: 'Restart Site' },
+ ],
+};
+
+const PHASE_BLUEPRINTS_BY_TRACK = Object.freeze({
+ A: [PHASE_1, PHASE_2_TRACK_A, PHASE_3_TRACK_A, PHASE_4],
+ B: [PHASE_1, PHASE_2_TRACK_B, PHASE_3_TRACK_B, PHASE_4],
+});
+
+function makePhasesFromBlueprint(blueprints) {
+ return blueprints.map((p) => ({
+ id: p.id,
+ title: p.title,
+ status: PHASE_STATUS.PENDING,
+ startedAt: null,
+ completedAt: null,
+ subSteps: p.subSteps.map((s) => ({
+ id: s.id,
+ label: s.label,
+ status: SUB_STEP_STATUS.PENDING,
+ output: null,
+ })),
+ }));
+}
+
+function normalizePendingInput(value) {
+ if (value == null) return null;
+ if (typeof value !== 'object' || Array.isArray(value) ||
+ typeof value.requiredAction !== 'string' || !value.requiredAction.trim()) {
+ throw new Error('Pending input must be an object with a non-empty "requiredAction" string.');
+ }
+ if (value.responseLocation !== undefined &&
+ (typeof value.responseLocation !== 'string' || !value.responseLocation.trim())) {
+ throw new Error('Pending input "responseLocation" must be a non-empty string when supplied.');
+ }
+ return {
+ requiredAction: value.requiredAction.trim(),
+ responseLocation: value.responseLocation?.trim() || 'Return to the migration conversation and provide your response.',
+ };
+}
+
+/**
+ * Build a fresh migration-state.json skeleton. Defaults to the Authoring Track; the skill
+ * calls `--set-track A|B` at the end of step 1.7 once env type and migration
+ * mode are known (`A` = Authoring Track, `B` = Downstream Track).
+ */
+function buildInitialState({ webSiteId, outputDir, track = DEFAULT_TRACK, startedAt = new Date().toISOString() } = {}) {
+ if (!webSiteId) throw new Error('buildInitialState: webSiteId is required');
+ if (!outputDir) throw new Error('buildInitialState: outputDir is required');
+ if (!PHASE_BLUEPRINTS_BY_TRACK[track]) throw new Error(`buildInitialState: unknown track '${track}'`);
+
+ return {
+ schemaVersion: SCHEMA_VERSION,
+ skillStartedAt: startedAt,
+ lastUpdatedAt: startedAt,
+ track,
+ site: {
+ name: null,
+ webSiteId,
+ portalId: null,
+ portalUrl: null,
+ slug: null,
+ currentDataModel: null,
+ template: null,
+ environment: null,
+ environmentName: null,
+ environmentUrl: null,
+ migrationMode: null,
+ siteRoot: null,
+ outputDir,
+ },
+ phases: makePhasesFromBlueprint(PHASE_BLUEPRINTS_BY_TRACK[track]),
+ approvalGate: {
+ phaseId: 1,
+ kind: APPROVAL_KIND.PHASE_START,
+ },
+ // Informational pauses must not replace or approve a migration gate.
+ pendingInput: null,
+ augmentedPrompts: {
+ plugin: null,
+ dme: null,
+ },
+ customizationReport: null,
+ refsMigration: null,
+ // Append-only log of the major migration CHOICES the user makes (env type, mode,
+ // track, package install/skip, remediation, reset, rollback, restart). Rendered in
+ // the Migration & Review tab for later review. Entries upsert by `id` so re-running
+ // a decision point updates in place instead of duplicating. Permission / file
+ // create-update-read prompts are intentionally NOT recorded here.
+ decisions: [],
+ // Structured "now running" pointer for long-running steps (package installs,
+ // metadata/refs migration polling). null when idle. When set:
+ // { label, detail, startedAt, expectedDurationSec, poll: { attempt, max } }
+ // The report renders this as an always-visible banner whose elapsed clock and
+ // estimate bar are advanced client-side every second — so progress stays visible
+ // even while a blocking `pac` call prevents the agent from writing new state.
+ currentOperation: null,
+ };
+}
+
+/**
+ * Switch the state's track in place. Preserves Phase 1 and Phase 4 (which are
+ * shared between tracks and may contain completed sub-steps). Replaces Phase 2
+ * and Phase 3 with the new track's blueprints (pristine).
+ *
+ * Called by update-state.js --set-track A|B (`A` = Authoring Track, `B` = Downstream Track),
+ * typically at the end of step 1.7 when the user confirms env type + migration mode.
+ */
+function rebuildPhasesForTrack(state, newTrack) {
+ if (!PHASE_BLUEPRINTS_BY_TRACK[newTrack]) {
+ throw new Error(`rebuildPhasesForTrack: unknown track '${newTrack}'`);
+ }
+
+ const blueprints = PHASE_BLUEPRINTS_BY_TRACK[newTrack];
+ state.phases = blueprints.map((blueprint) => {
+ // Phase 1 and Phase 4 are shared across tracks — preserve any existing
+ // sub-step status / output. Phase 2 and Phase 3 are track-specific —
+ // rebuild from blueprint (pristine).
+ if (blueprint.id === 1 || blueprint.id === 4) {
+ const existing = state.phases?.find((p) => p.id === blueprint.id);
+ if (existing) return existing;
+ }
+ return makePhasesFromBlueprint([blueprint])[0];
+ });
+ state.track = newTrack;
+}
+
+module.exports = {
+ SCHEMA_VERSION,
+ PHASE_STATUS,
+ SUB_STEP_STATUS,
+ APPROVAL_KIND,
+ PROMPT_STATUS,
+ TRACK,
+ normalizePendingInput,
+ DEFAULT_TRACK,
+ PHASE_BLUEPRINTS_BY_TRACK,
+ // Back-compat exports — `PHASE_BLUEPRINT` was the pre-track flat list. We
+ // alias it to the Authoring Track (CLI value `A`) so any external caller that imported it keeps working.
+ PHASE_BLUEPRINT: PHASE_BLUEPRINTS_BY_TRACK.A,
+ buildInitialState,
+ rebuildPhasesForTrack,
+};
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/lib/render-live-report.js b/plugins/power-pages/skills/migrate-datamodel/scripts/lib/render-live-report.js
new file mode 100644
index 000000000..211613a44
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/lib/render-live-report.js
@@ -0,0 +1,2235 @@
+/**
+ * render-live-report.js
+ *
+ * Pure render function: migration-state.json (+ optional snapshots) -> HTML string.
+ *
+ * The output is a sidebar+sections layout modelled on create-site/assets/create-site-plan.html,
+ * with five sections reachable from the sidebar:
+ *
+ * - Overview summary, site card, confidence stat, current status
+ * - Plan env type + chosen mode + 4-phase flow + approval gates
+ * - SDM Components counts and sample records from sdm-snapshot.json
+ * - EDM Components same shape as SDM, with side-by-side tally
+ * - Migration & Review per-phase sub-step list, approvals, augmented prompts
+ *
+ * Callers can pass `sdmSnapshot` and `edmSnapshot` (parsed JSON objects) — if absent,
+ * those sections render empty states.
+ */
+
+const {
+ PHASE_STATUS,
+ SUB_STEP_STATUS,
+ APPROVAL_KIND,
+ PROMPT_STATUS,
+ normalizePendingInput,
+} = require('./migration-state-schema');
+const {
+ NONCONFIGURATION_CATEGORIES,
+ isReportExcludedCategory,
+ getCategoryMetadata,
+} = require('./edm-table-classification');
+const path = require('node:path');
+const { pathToFileURL } = require('node:url');
+const { diffCategory } = require('../diff-snapshots');
+
+// ── HTML escaping ──────────────────────────────────────────────────────────
+
+function escapeHtml(s) {
+ if (s == null) return '';
+ return String(s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
+function escapeHtmlAllowingInline(s) {
+ if (s == null) return '';
+ const escaped = escapeHtml(s);
+ return escaped
+ .replace(/&lt;(\/?(?:code|strong|em|br))&gt;/g, '<$1>')
+ .replace(/&lt;br\s*\/&gt;/g, '<br/>');
+}
+
+function localReportLink(value) {
+ if (typeof value !== 'string' || !value) return null;
+ const link = value.trim();
+ if (!link || /[\u0000-\u001f\u007f]/.test(link)) return null;
+ if (/^[\\/]{2}/.test(link)) return null;
+ if (path.isAbsolute(link)) return pathToFileURL(link).href;
+ if (/^file:/i.test(link)) {
+ try {
+ const url = new URL(link);
+ return url.hostname ? null : url.href;
+ } catch { return null; }
+ }
+ if (/^[a-z][a-z0-9+.-]*:/i.test(link) || /^[\\/]{2}/.test(link)) return null;
+ return link;
+}
+
+function portalLink(value) {
+ if (typeof value !== 'string' || /[\u0000-\u001f\u007f]/.test(value)) return null;
+ try {
+ const url = new URL(value);
+ return url.protocol === 'https:' && !url.username && !url.password ? url.href : null;
+ } catch { return null; }
+}
+
+// ── Formatting helpers ─────────────────────────────────────────────────────
+
+function formatElapsed(fromIso, toIso) {
+ if (!fromIso) return '0m 00s';
+ const from = new Date(fromIso).getTime();
+ const to = new Date(toIso || new Date().toISOString()).getTime();
+ const seconds = Math.max(0, Math.floor((to - from) / 1000));
+ const m = Math.floor(seconds / 60);
+ const s = seconds % 60;
+ return `${m}m ${String(s).padStart(2, '0')}s`;
+}
+
+function formatClock(iso) {
+ if (!iso) return '';
+ const d = new Date(iso);
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
+}
+
+function formatTimestamp(iso) {
+ if (!iso) return '';
+ const d = new Date(iso);
+ const pad = (n) => String(n).padStart(2, '0');
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+}
+
+function countCompleted(state) {
+ let n = 0;
+ for (const p of state.phases) {
+ for (const s of p.subSteps) {
+ if (s.status === SUB_STEP_STATUS.COMPLETED) n += 1;
+ }
+ }
+ return n;
+}
+
+function totalSubSteps(state) {
+ return state.phases.reduce((n, p) => n + p.subSteps.length, 0);
+}
+
+function overallPercent(state) {
+ const total = totalSubSteps(state);
+ if (total === 0) return 0;
+ return Math.round((countCompleted(state) / total) * 100);
+}
+
+function statusPillFor(state) {
+ if (state.pendingInput) return 'Input needed';
+ // A pending question/gate takes precedence over recorded phase progress.
+ const gate = state.approvalGate;
+ if (gate) {
+ return `Awaiting Approval — Phase ${gate.phaseId}${gate.kind === APPROVAL_KIND.IN_PHASE ? ' (in-phase)' : ''}`;
+ }
+
+ const inProgress = state.phases.find((p) => p.status === PHASE_STATUS.IN_PROGRESS);
+ if (inProgress) return `In Progress · Phase ${inProgress.id} of ${state.phases.length}`;
+
+ const allDone = state.phases.every((p) => p.status === PHASE_STATUS.COMPLETED);
+ if (allDone) return 'Migration Complete';
+
+ // Nothing running, no gate, not done → transitional. Surface the next phase
+ // so the user sees forward motion rather than a stale "Awaiting Approval"
+ // pill while the agent runs the next --set-phase call.
+ const nextPending = state.phases.find((p) => p.status !== PHASE_STATUS.COMPLETED);
+ if (nextPending) return `Ready · Phase ${nextPending.id} of ${state.phases.length}`;
+
+ return 'Migration Complete';
+}
+
+function pillSeverityClass(state) {
+ if (state.pendingInput || state.approvalGate) return 'pending';
+ const inProgress = state.phases.find((p) => p.status === PHASE_STATUS.IN_PROGRESS);
+ if (inProgress) return 'in-progress';
+ const allDone = state.phases.every((p) => p.status === PHASE_STATUS.COMPLETED);
+ if (allDone) return 'done';
+ return 'in-progress';
+}
+
+// ── Approval-banner copy (track-aware: keyed by phase + kind + Authoring/Downstream track) ────────
+
+const APPROVAL_COPY = {
+ '1:phase-start': {
+ heading: 'Approve to start Phase 1: Site Discovery & Pre-checks',
+ body: [
+ 'Phase 1 is mostly read-only context-gathering: PAC version check, auth profile, site discovery, dependency verification, migration mode selection.',
+ '<strong>The one potential write</strong> is in step 1.6 — if your site\'s template needs a V2 EDM solution that isn\'t installed, the skill will ask for your explicit consent before running <code>pac application install</code>.',
+ ],
+ approve: '› Yes, start Phase 1',
+ cancel: '› Cancel — stop the skill',
+ },
+ '2:phase-start:A': {
+ heading: 'Approve to start Phase 2: Configuration Migration & Customization Remediation',
+ body: [
+ 'Phase 1 captured site context, dependencies, and the chosen mode (<code>configurationData</code> or <code>all</code>).',
+ 'In <strong>Phase 2</strong>, the skill will first download the SDM site source and capture a baseline snapshot (so the live report reflects pre-migration state), then run <code>pac pages migrate-datamodel</code> to move metadata into EDM tables, locate the auto-emitted customization report, and — if any <code>adx_*</code> customizations are flagged — run FetchXML/Liquid rewriters, generate augmented prompts, and ask for your explicit approval before <code>pac pages upload</code>.',
+ ],
+ approve: '› Yes, proceed with Phase 2',
+ cancel: '› Cancel — I want to review more first',
+ },
+ '2:phase-start:B': {
+ heading: 'Approve to start Phase 2: Setting Up Metadata',
+ body: [
+ 'Phase 1 captured site context and confirmed mode <code>configurationDataReferences</code> — which assumes configuration metadata is already in EDM (typically via ALM solution import).',
+ 'In <strong>Phase 2</strong>, the skill will list sites in the target environment to verify yours is present, and — if metadata is missing — offer three import paths (ALM skill / Solution Import / PAC CLI). No data is migrated until you confirm metadata is ready.',
+ ],
+ approve: '› Yes, proceed with Phase 2',
+ cancel: '› Cancel — I want to review more first',
+ },
+ '3:phase-start:A': {
+ heading: 'Approve to start Phase 3: Migration Execution',
+ body: [
+ 'Phase 2 has finished: metadata migrated to EDM tables, customizations remediated and uploaded.',
+ '<strong>Phase 3</strong> starts with a pre-flight <strong>SDM ↔ EDM metadata diff</strong> so you can confirm the metadata migration landed cleanly before refs are migrated. Then it migrates transactional references via <code>pac pages migrate-datamodel --mode configurationDataReferences</code> (auto-skipped if you chose <code>--mode all</code> in Phase 2), activates EDM via <code>--updateDataModelVersion</code>, and asks you to approve an API restart with readiness verification (manual fallback if unavailable).',
+ ],
+ approve: '› Yes, start migration execution',
+ cancel: '› Cancel — stop before migration',
+ },
+ '3:phase-start:B': {
+ heading: 'Approve to start Phase 3: Migration Execution',
+ body: [
+ 'Phase 2 confirmed configuration metadata is present in the target environment.',
+ '<strong>Phase 3</strong> starts with a pre-flight <strong>SDM ↔ EDM metadata diff</strong> so you can confirm the upstream-imported metadata landed cleanly before refs are migrated. Then it migrates transactional references, locates the auto-generated customization report, remediates any customizations that surface (stronger warning — Prod findings usually indicate an ALM gap), activates EDM, and asks you to approve an API restart with readiness verification (manual fallback if unavailable).',
+ ],
+ approve: '› Yes, start migration execution',
+ cancel: '› Cancel — stop before migration',
+ },
+ '4:phase-start': {
+ heading: 'Approve to start Phase 4: Post-Migration Validation',
+ body: [
+ 'Migration execution is complete. The site is now on Enhanced Data Model. The pre-flight SDM ↔ EDM metadata diff in Phase 3.1 already confirmed every metadata record made it across.',
+ '<strong>Phase 4</strong> offers <strong>Run now</strong> in the migration conversation to launch <code>/power-pages:test-site</code> for browser-based runtime smoke testing. You can also report an earlier run, defer, or skip. Optional rollback remains a separate choice if validation surfaces problems.',
+ ],
+ approve: '› Yes, start validation',
+ cancel: '› Cancel — I\'ll validate manually',
+ },
+ '2:in-phase': {
+ heading: 'Approve upload to continue Phase 2',
+ body: [
+ 'Auto-rewriters have finished modifying FetchXML and Liquid in your site source. Before <code>pac pages upload</code> writes changes back to Dataverse, please review the diff and rewritten files.',
+ 'See the augmented prompts in the Migration & Review section for plugin and DME work that must run in fresh Claude sessions before Phase 3.',
+ ],
+ approve: '› Approve upload',
+ cancel: '› Cancel — stop before upload',
+ },
+};
+
+// ── Per-section renderers ──────────────────────────────────────────────────
+
+function renderSiteRow(label, value, isKnown = false) {
+ const isPlaceholder = value == null || value === '';
+ const displayValue = isPlaceholder
+ ? `<em>(not yet captured)</em>`
+ : escapeHtmlAllowingInline(value);
+ const cls = isPlaceholder ? '' : (isKnown ? ' class="known"' : '');
+ return ` <tr><td>${escapeHtml(label)}</td><td${cls}>${displayValue}</td></tr>`;
+}
+
+function renderSiteCard(state) {
+ const s = state.site;
+ return `<div class="card site-card">
+ <div class="card-title">Site &amp; Migration Details</div>
+ <table>
+${renderSiteRow('Site name', s.name)}
+${renderSiteRow('Website Id', s.webSiteId, true)}
+${renderSiteRow('Portal Id', s.portalId)}
+${renderSiteRow('Portal URL', s.portalUrl)}
+${renderSiteRow('URL slug', s.slug)}
+${renderSiteRow('Current data model', s.currentDataModel)}
+${renderSiteRow('Template', s.template)}
+${renderSiteRow('Environment name', s.environmentName)}
+${renderSiteRow('Environment type', s.environment)}
+${renderSiteRow('Migration mode', s.migrationMode)}
+${renderSiteRow('Site root', s.siteRoot)}
+${renderSiteRow('Output directory', s.outputDir, true)}
+ <tr><td>Skill started</td><td class="known">${escapeHtml(formatTimestamp(state.skillStartedAt))}</td></tr>
+ </table>
+</div>`;
+}
+
+// Categories that snapshot-site.js scans but are NOT part of the SDM→EDM
+// metadata migration scope. They're surfaced in `*-snapshot.json` for
+// completeness but excluded from the live report's Overview totals and the
+// Pages & Components groups so users don't see misleading "missing record"
+// flags for content that legitimately doesn't migrate.
+function sumMetadataCounts(counts) {
+ if (!counts) return 0;
+ let total = 0;
+ for (const [cat, n] of Object.entries(counts)) {
+ if (isReportExcludedCategory(cat)) continue;
+ total += n || 0;
+ }
+ return total;
+}
+
+function renderConfidenceStat(sdmSnapshot, edmSnapshot) {
+ if (!sdmSnapshot) {
+ return `<div class="card confidence-card empty">
+ <div class="card-title">Migration totals</div>
+ <div class="empty-note">This card appears once the SDM snapshot is captured during configuration setup (after <code>pac pages download --modelVersion 1</code>). After Phase 4.1 runs, it shows <code>SDM total → EDM total</code> with a check mark when the totals match. This is a count comparison, not record-level verification. Per-category breakdown lives in the Pages &amp; Components tab.</div>
+</div>`;
+ }
+
+ const sdmTotal = sumMetadataCounts(sdmSnapshot.counts);
+
+ if (!edmSnapshot) {
+ return `<div class="card confidence-card waiting">
+ <div class="card-title">Migration totals</div>
+ <div class="confidence-numbers">
+ <div class="confidence-num">${sdmTotal}</div>
+ <div class="confidence-arrow">→</div>
+ <div class="confidence-num pending">?</div>
+ </div>
+ <div class="confidence-label">SDM components captured. EDM count appears after Phase 4.1. For the per-category view, open the Pages &amp; Components tab.</div>
+</div>`;
+ }
+
+ const edmTotal = sumMetadataCounts(edmSnapshot.counts);
+ const diff = sdmTotal - edmTotal;
+ const isMatch = diff === 0;
+ const statusIcon = isMatch ? '✓' : '⚠';
+ const statusClass = isMatch ? 'match' : 'mismatch';
+ return `<div class="card confidence-card ${statusClass}">
+ <div class="card-title">Migration totals</div>
+ <div class="confidence-numbers">
+ <div class="confidence-num">${sdmTotal}</div>
+ <div class="confidence-arrow">→</div>
+ <div class="confidence-num">${edmTotal}</div>
+ <div class="confidence-icon">${statusIcon}</div>
+ </div>
+ <div class="confidence-label">${
+ isMatch
+ ? 'Counts match: ' + sdmTotal + ' components on each side. Equal totals do not verify individual records. Open <strong>Pages &amp; Components</strong> for the per-category breakdown.'
+ : Math.abs(diff) + ' component difference — open <strong>Pages &amp; Components</strong> for the per-category breakdown.'
+ }</div>
+</div>`;
+}
+
+function renderOverviewSection(state, snapshots) {
+ const pct = overallPercent(state);
+ const completed = countCompleted(state);
+ const total = totalSubSteps(state);
+ const phasesDone = state.phases.filter((p) => p.status === PHASE_STATUS.COMPLETED).length;
+ const elapsed = formatElapsed(state.skillStartedAt, state.lastUpdatedAt);
+
+ return `<div class="section active" id="tab-overview">
+ <h2>Overview</h2>
+ <p class="section-desc">SDM → EDM migration for <code>${escapeHtml(state.site.name || state.site.webSiteId)}</code>. Open this report alongside the skill to track progress as each sub-step completes.</p>
+
+ <div class="summary-box">
+ <p>The <strong>Enhanced Data Model (EDM)</strong> is the next-generation storage model for Power Pages sites. Instead of spreading site configuration across many bespoke <code>adx_*</code> Dataverse tables (the legacy <strong>Standard Data Model</strong>, or <strong>SDM</strong>), EDM consolidates site metadata into a small set of unified tables — most notably <code>powerpagecomponent</code> — where component-specific properties are stored as JSON in a <code>content</code> column.</p>
+
+ <h4>Why EDM</h4>
+ <ul>
+ <li>Simpler, future-proof schema with fewer tables to reason about.</li>
+ <li>Cleaner ALM — fewer tables to package into solutions.</li>
+ <li>Faster runtime resolution — no joins across many <code>adx_*</code> tables.</li>
+ <li>A consistent surface for new Power Pages features that are built EDM-first.</li>
+ </ul>
+
+ <h4>What migrates into <code>powerpagecomponent</code></h4>
+ <ul>
+ <li>Only the <strong>metadata</strong> <code>adx_*</code> tables — the ones describing the site's structure and authoring surface.</li>
+ <li>Examples: <code>adx_webpage</code>, <code>adx_webtemplate</code>, <code>adx_contentsnippet</code>, <code>adx_sitesetting</code>, <code>adx_pagetemplate</code>, <code>adx_weblink</code>, <code>adx_entityform</code>, <code>adx_entitylist</code>.</li>
+ <li>Their per-row properties move into the <code>content</code> JSON column of <code>powerpagecomponent</code>.</li>
+ </ul>
+
+ <h4>What stays put</h4>
+ <ul>
+ <li>The <strong>transactional / runtime</strong> <code>adx_*</code> tables that capture end-user activity — e.g. <code>adx_invitation</code>, <code>adx_inviteredemption</code>, <code>adx_portalcomment</code>, <code>adx_externalidentity</code>, and the entity-form / advanced-form submission and log tables.</li>
+ <li>These keep their existing schemas and keep storing runtime data as before.</li>
+ <li>Only their lookups get <strong>rewired</strong> during the references migration to point at the new <code>powerpagecomponent</code> rows instead of the legacy metadata <code>adx_*</code> rows.</li>
+ </ul>
+
+ <h4>What migration does</h4>
+ <ul>
+ <li>Existing sites were authored on SDM and still run on <code>adx_*</code>, so each site must be migrated to benefit from EDM.</li>
+ <li>Moves configuration metadata into the EDM <code>powerpagecomponent</code> shape, rewires transactional references onto the new records, and flips the site to serve from EDM.</li>
+ <li>Surfaces and remediates <strong>customizations</strong> — custom <code>adx_*</code> columns, Liquid reading <code>adx_*</code> attributes, FetchXML over <code>adx_*</code> tables, plugins, and workflows — since these don't carry over automatically and must be rewritten to work against EDM.</li>
+ </ul>
+
+ <h4>How this skill runs</h4>
+ <ul>
+ <li><strong>Four high-level phases.</strong> Phase 1 (Site Discovery &amp; Pre-checks) and Phase 4 (Post-Migration Validation) run the same for every site.</li>
+ <li>Phase 2 and Phase 3 are <strong>track-branched</strong> — their shape depends on the migration mode chosen in step 1.7, which derives the track from the environment type.</li>
+ <li><strong>Authoring Track</strong> (mode <code>configurationData</code> or <code>all</code>) — for Dev / Single-environment setups: metadata is migrated locally and customizations are fixed against SDM source before transactional references move.</li>
+ <li><strong>Downstream Track</strong> (mode <code>configurationDataReferences</code>) — for Test / UAT / Production, where metadata is assumed to have arrived via ALM solution import from Dev: only transactional references migrate, and any customization findings signal an upstream ALM gap rather than local work.</li>
+ </ul>
+
+ <h4>Authoring Track — phase detail</h4>
+ <ul>
+ <li><strong>Phase 2:</strong> capture an SDM baseline snapshot → migrate metadata with <code>pac pages migrate-datamodel</code> → locate the auto-emitted customization report → remediate by staging FetchXML/Liquid auto-rewrites plus augmented prompts for plugins &amp; Data Model Extensions → apply the staged diff and upload back with <code>pac pages upload --modelVersion 1</code>.</li>
+ <li><strong>Phase 3:</strong> SDM↔EDM data-diff validation (pre-refs safety gate) → transactional references migration (auto-skipped when mode was <code>all</code>) → EDM activation via <code>--updateDataModelVersion --portalId</code> → approved API restart and readiness verification (manual fallback).</li>
+ </ul>
+
+ <h4>Downstream Track — phase detail</h4>
+ <ul>
+ <li><strong>Phase 2 (shorter):</strong> verify metadata is present in the target environment → capture snapshots → confirm readiness via a user-facing gate before Phase 3 moves transactional data.</li>
+ <li><strong>Phase 3 (longer):</strong> data-diff validation → migrate refs with <code>--mode configurationDataReferences</code> → locate the customization report → remediate with the same staged-rewrite / augmented-prompt flow (stronger warning, since Prod/Test/UAT findings usually signal an upstream ALM gap) → activate EDM → approved API restart and readiness verification (manual fallback).</li>
+ <li><strong>Phase 4</strong> (both tracks): choose <strong>Run now</strong> in the migration conversation for the recommended runtime smoke test, report an earlier run, or defer/skip; then record final status.</li>
+ </ul>
+ </div>
+
+ <div class="stats-grid">
+ <div class="stat-card"><div class="stat-num">${pct}%</div><div class="stat-label">Workflow completion</div></div>
+ <div class="stat-card"><div class="stat-num">${completed} / ${total}</div><div class="stat-label">Sub-steps</div></div>
+ <div class="stat-card"><div class="stat-num">${escapeHtml(elapsed)}</div><div class="stat-label">Elapsed</div></div>
+ <div class="stat-card"><div class="stat-num">${phasesDone} / ${state.phases.length}</div><div class="stat-label">Phases done</div></div>
+ </div>
+
+${renderSiteCard(state)}
+
+${renderConfidenceStat(snapshots.sdmSnapshot, snapshots.edmSnapshot)}
+
+</div>`;
+}
+
+function renderPlanSection(state) {
+ const track = state.track;
+ const mode = state.site.migrationMode;
+ const env = state.site.environment;
+
+ let approachDescription;
+ if (!track || !mode) {
+ approachDescription = `<em>Will be determined in step 1.7 once env type and migration mode are confirmed.</em>`;
+ } else if (track === 'A') {
+ approachDescription = `<strong>Authoring Track — local-migration approach.</strong> Used for Dev / Test/UAT / Single environments. The skill runs <code>pac pages migrate-datamodel --mode ${escapeHtml(mode)}</code> locally to move metadata into EDM tables, then handles customization remediation in Phase 2 itself. Phase 3 migrates transactional references and activates EDM.`;
+ } else {
+ approachDescription = `<strong>Downstream Track — ALM-aware approach.</strong> Used for Prod (configuration metadata is assumed to be pre-imported via solution). Phase 2 verifies metadata is present without re-migrating it. Phase 3 runs the transactional reference migration with <code>--mode configurationDataReferences</code>, handles any customization findings (which would indicate an ALM gap), then activates EDM.`;
+ }
+
+ const phaseRows = state.phases.map((p) => {
+ const labelClass = p.status === PHASE_STATUS.COMPLETED ? 'completed' : (p.status === PHASE_STATUS.IN_PROGRESS ? 'in-progress' : 'pending');
+ return ` <div class="plan-phase-row">
+ <div class="plan-phase-num">Phase ${p.id}</div>
+ <div class="plan-phase-body">
+ <div class="plan-phase-title">${escapeHtml(p.title)}</div>
+ <div class="plan-phase-meta">${p.subSteps.length} sub-step${p.subSteps.length === 1 ? '' : 's'}</div>
+ </div>
+ <div class="plan-phase-status ${labelClass}">${escapeHtml(p.status)}</div>
+ </div>`;
+ }).join('\n');
+
+ const approvalGates = [
+ 'Before Phase 1 (skill startup — light read-only checks)',
+ 'Before Phase 2 (after env type + migration mode are confirmed in step 1.7)',
+ 'In-phase Phase 2 (review FetchXML/Liquid rewrites before pac pages upload)',
+ 'Before Phase 3 (after Phase 2 readiness gate)',
+ 'Before Phase 4 (after site is live on EDM)',
+ 'Phase 4 internal gates (diff decision, runtime check status, final validation status, optional rollback)',
+ ];
+
+ return `<div class="section" id="tab-plan">
+ <h2>Plan</h2>
+ <p class="section-desc">Migration approach, sub-step shape, and approval gates derived from your env type and migration mode.</p>
+
+ <h3>Migration approach</h3>
+ <div class="summary-box">${approachDescription}</div>
+
+ <div class="kv-grid">
+ <div class="kv-item"><div class="kv-label">Environment type</div><div class="kv-value">${escapeHtml(env || '(set in step 1.7)')}</div></div>
+ <div class="kv-item"><div class="kv-label">Migration mode</div><div class="kv-value">${escapeHtml(mode || '(set in step 1.7)')}</div></div>
+ <div class="kv-item"><div class="kv-label">Total sub-steps</div><div class="kv-value">${totalSubSteps(state)}</div></div>
+ </div>
+
+ <h3>Phase flow</h3>
+ <div class="plan-phase-list">
+${phaseRows}
+ </div>
+
+ <h3>Approval gates</h3>
+ <ul class="bullet-list">
+${approvalGates.map((g) => ` <li>${escapeHtml(g)}</li>`).join('\n')}
+ </ul>
+
+ <h3>Expected outcomes</h3>
+ <ul class="bullet-list">
+ <li>Site flipped to EDM in Dataverse, with the SDM record deactivated</li>
+ <li>Customization remediation diff and augmented prompts produced (if findings)</li>
+ <li>SDM and EDM snapshots captured for verifiable post-migration data diff</li>
+ <li>Optional rollback path available via Portal Id + <code>--revertToStandardDataModel</code></li>
+ <li>Runtime smoke test via <strong>Run now</strong> in the migration conversation using <code>/power-pages:test-site &lt;URL&gt;</code>, or an explicit earlier result, deferral, or decline</li>
+ </ul>
+</div>`;
+}
+
+/**
+ * Render the merged Pages & Components tab — single comparison view of SDM vs EDM.
+ * Three states for the inventory:
+ * - No SDM yet → empty card with guidance.
+ * - SDM present, no EDM yet → "EDM pending" banner + per-row `SDM → ?` placeholder.
+ * - Both present → "X of Y matched" header + per-row `SDM → EDM ✓/⚠/✗` pills.
+ *
+ * Each row expands to a two-column records preview (SDM | EDM) showing the first
+ * 5 records per side.
+ */
+function renderPagesComponentsSection({ sdmSnapshot, edmSnapshot }) {
+ if (!sdmSnapshot) {
+ return `<div class="section" id="tab-pages">
+ <h2>Pages &amp; Components</h2>
+ <p class="section-desc">Side-by-side component counts before migration (SDM) and after (EDM). Count status does not verify individual records; record-level comparison and migration safety checks are separate.</p>
+
+ <div class="card empty-card">
+ <div class="empty-icon">○</div>
+ <div class="empty-title">SDM snapshot not yet captured</div>
+ <div class="empty-body">This section populates after the SDM snapshot is captured during configuration setup (right after <code>pac pages download --modelVersion 1</code>). Each Power Pages component category then appears as a row with its SDM count and a placeholder for the EDM count that fills in after Phase 4.1.</div>
+ </div>
+</div>`;
+ }
+
+ const sdmCounts = sdmSnapshot.counts || {};
+ const edmCounts = (edmSnapshot && edmSnapshot.counts) || {};
+ const sdmInventory = sdmSnapshot.inventory || {};
+ const edmInventory = (edmSnapshot && edmSnapshot.inventory) || {};
+ const excludedDifferences = [...NONCONFIGURATION_CATEGORIES]
+ .filter((category) => (sdmCounts[category] || 0) > 0 && (edmCounts[category] || 0) === 0)
+ .map((category) => {
+ const metadata = getCategoryMetadata(category);
+ return `${metadata.label} (${sdmCounts[category]})`;
+ });
+
+ // Union of categories from both sides — covers SDM-only (tags) and any new
+ // categories on EDM. Non-metadata categories (polls, ads, forums, blogs,
+ // ideas, their placement variants, and websiteBindings) are excluded here
+ // so the grouped view stays focused on what's actually migrating.
+ const allCats = new Set();
+ for (const k of Object.keys(sdmCounts)) {
+ if (sdmCounts[k] > 0 && !isReportExcludedCategory(k)) allCats.add(k);
+ }
+ for (const k of Object.keys(edmCounts)) {
+ if (edmCounts[k] > 0 && !isReportExcludedCategory(k)) allCats.add(k);
+ }
+ for (const snapshot of [sdmSnapshot, edmSnapshot]) {
+ for (const [category, errors] of Object.entries(snapshot?.parseErrors || {})) {
+ if (errors.length > 0 && !isReportExcludedCategory(category)) allCats.add(category);
+ }
+ }
+ const categories = [...allCats].sort();
+
+ const isPending = !edmSnapshot;
+ const sdmTotal = sumMetadataCounts(sdmCounts);
+ const edmTotal = sumMetadataCounts(edmCounts);
+
+ // Per-category render produces { cat, group, sdmN, edmN, statusCls, isMatch, html }.
+ let matchedCount = 0;
+ const perCategory = categories.map((cat) => {
+ const sdmN = sdmCounts[cat] || 0;
+ const edmN = edmCounts[cat] || 0;
+ const sdmRecords = sdmInventory[cat] || [];
+ const edmRecords = edmInventory[cat] || [];
+ const hasParseErrors = (sdmSnapshot.parseErrors?.[cat]?.length || 0) +
+ (edmSnapshot?.parseErrors?.[cat]?.length || 0) > 0;
+ const comparison = diffCategory(cat, sdmRecords, edmRecords);
+ const incomplete = hasParseErrors || sdmRecords.length !== sdmN || edmRecords.length !== edmN;
+ const isSdmOnlyExpected = comparison.sdmOnlyCategory && edmN === 0 && sdmN > 0 && !incomplete;
+
+ let pillCls, icon, meta;
+ let isMatchForGroup = false;
+ if (isPending) {
+ pillCls = 'pending';
+ icon = '';
+ meta = '';
+ } else if (isSdmOnlyExpected) {
+ pillCls = 'warn';
+ icon = '⚠';
+ meta = 'SDM-only';
+ } else if (!incomplete && sdmN === edmN) {
+ pillCls = 'match';
+ icon = '✓';
+ meta = 'Counts match';
+ isMatchForGroup = true;
+ matchedCount++;
+ } else {
+ pillCls = 'mismatch';
+ icon = '✗';
+ const delta = edmN - sdmN;
+ meta = incomplete ? 'Incomplete snapshot' : (delta > 0 ? '+' : '') + delta;
+ }
+
+ const pillRight = isPending
+ ? `<span class="comp-num placeholder">?</span>`
+ : `<span class="comp-num edm">${edmN}</span><span class="comp-icon">${icon}</span>${meta ? `<span class="comp-meta">${escapeHtml(meta)}</span>` : ''}`;
+
+ const pill = `<div class="comp-pill ${pillCls}">
+ <span class="comp-num sdm">${sdmN}</span>
+ <span class="comp-arrow">→</span>
+ ${pillRight}
+ </div>`;
+
+ // Two-column records preview (SDM | EDM), first 5 of each side.
+ const hasRecords = sdmRecords.length > 0 || edmRecords.length > 0;
+ const renderColUl = (records, kind) => {
+ if (isPending && kind === 'edm') {
+ return '<li class="record-empty">— pending Phase 4.1 —</li>';
+ }
+ if (records.length === 0) {
+ return '<li class="record-empty">— no records —</li>';
+ }
+ return records.slice(0, 5).map((r) => `<li>${escapeHtml(describeRecord(r, cat))}</li>`).join('');
+ };
+ const recordsBlock = hasRecords
+ ? `
+ <details class="cat-records">
+ <summary>Show records (first 5 of each side)</summary>
+ <div class="records-two-col">
+ <div class="records-col">
+ <div class="records-col-label">SDM</div>
+ <ul class="cat-record-list">${renderColUl(sdmRecords, 'sdm')}</ul>
+ </div>
+ <div class="records-col">
+ <div class="records-col-label">EDM</div>
+ <ul class="cat-record-list">${renderColUl(edmRecords, 'edm')}</ul>
+ </div>
+ </div>
+ </details>`
+ : '';
+
+ // Count badges deliberately ignore record differences, but retain the full
+ // comparison separately so equal counts cannot approve an ambiguous migration.
+ const recordIssues = [
+ ['Missing in EDM', comparison.missingInEdm.length],
+ ['Extra in EDM', comparison.extraInEdm.length],
+ ['Changed states', comparison.stateChanged.length],
+ ['Changed content hashes', comparison.contentChanged.length],
+ ['Changed values', comparison.valueChanged.length],
+ ['Duplicate SDM identities', comparison.duplicateKeys?.sdm.length || 0],
+ ['Duplicate EDM identities', comparison.duplicateKeys?.edm.length || 0],
+ ].filter(([, count]) => count > 0);
+ const recordComparison = !isPending && !incomplete && !isSdmOnlyExpected && recordIssues.length > 0
+ ? `
+ <details class="cat-records">
+ <summary>Record-level comparison (separate from count status)</summary>
+ <p>${recordIssues.map(([label, count]) => `${label}: ${count}`).join(' · ')}. These findings do not change the count badge; the separate migration safety gate still uses the full comparison.</p>
+ </details>`
+ : '';
+ const desc = categoryDescription(cat);
+ const descHtml = desc ? `<div class="cat-desc">${escapeHtml(desc)}</div>` : '';
+ const html = ` <div class="cat-row">
+ <div class="cat-head">
+ <div class="cat-meta">
+ <div class="cat-name">${escapeHtml(formatCategoryName(cat))}</div>
+ ${descHtml}
+ </div>
+ ${pill}
+ </div>${recordsBlock}${recordComparison}
+ </div>`;
+
+ return { cat, group: groupForCategory(cat), sdmN, edmN, isMatch: isMatchForGroup, html };
+ });
+
+ // Group the per-category results into the 5-bucket taxonomy.
+ const grouped = new Map();
+ for (const c of perCategory) {
+ if (!grouped.has(c.group)) grouped.set(c.group, []);
+ grouped.get(c.group).push(c);
+ }
+
+ const groupRows = CATEGORY_GROUP_ORDER
+ .filter((g) => grouped.has(g))
+ .map((g) => {
+ const items = grouped.get(g);
+ const groupSdmTotal = items.reduce((a, i) => a + i.sdmN, 0);
+ const groupEdmTotal = items.reduce((a, i) => a + i.edmN, 0);
+ const groupHasMismatch = items.some((i) => !i.isMatch);
+ // Default state: open if pending (so user sees full inventory), open if any
+ // mismatch in this group (problem-focused), otherwise closed (clean groups
+ // start collapsed so user lands on problems first).
+ const openByDefault = isPending || groupHasMismatch;
+ const groupStatusHtml = isPending
+ ? `<span class="cat-group-stats">${items.length} categor${items.length === 1 ? 'y' : 'ies'} · ${groupSdmTotal} SDM record${groupSdmTotal === 1 ? '' : 's'}</span>`
+ : groupHasMismatch
+ ? `<span class="cat-group-stats warn">${items.length} categor${items.length === 1 ? 'y' : 'ies'} · ${groupSdmTotal} \u2192 ${groupEdmTotal} records · needs attention <span class="cat-group-icon mismatch">⚠</span></span>`
+ : `<span class="cat-group-stats ok">${items.length} categor${items.length === 1 ? 'y' : 'ies'} · ${groupSdmTotal} \u2192 ${groupEdmTotal} records · counts match <span class="cat-group-icon match">✓</span></span>`;
+
+ return ` <details class="cat-group" ${openByDefault ? 'open' : ''}>
+ <summary class="cat-group-summary">
+ <span class="cat-group-name">${escapeHtml(g)}</span>
+ ${groupStatusHtml}
+ </summary>
+ <div class="cat-group-body">
+${items.map((i) => i.html).join('\n')}
+ </div>
+ </details>`;
+ })
+ .join('\n');
+
+ const categoryRows = groupRows;
+
+ // Summary banner — pending vs final state.
+ const totalCats = categories.length;
+ let summary;
+ if (isPending) {
+ summary = `<div class="comp-summary pending">
+ <strong>EDM snapshot pending — appears after Phase 4.1.</strong> Showing your site's SDM inventory now (${totalCats} ${totalCats === 1 ? 'category' : 'categories'}, ${sdmTotal} total ${sdmTotal === 1 ? 'record' : 'records'}). Each row fills in its EDM count after the migration completes and step 4.1 captures the EDM snapshot.
+ </div>`;
+ } else {
+ const allMatched = matchedCount === totalCats;
+ const unmatched = totalCats - matchedCount;
+ summary = `<div class="comp-summary ${allMatched ? 'match' : 'partial'}">
+ <strong>${matchedCount} of ${totalCats} category counts match ${allMatched ? '✓' : '⚠'}</strong>
+ ${allMatched
+ ? '— count comparison only, not verification of identities, values or content. Record-level migration safety checks and runtime validation remain separate.'
+ : `— ${unmatched} ${unmatched === 1 ? 'category has' : 'categories have'} a count difference or incomplete snapshot. SDM-only download categories are labeled separately. Record-level findings do not affect count status.`}
+ </div>`;
+ }
+
+ const excludedDifferenceNote = excludedDifferences.length === 0
+ ? ''
+ : `<div class="comp-summary pending"><strong>Expected excluded differences:</strong> ${escapeHtml(excludedDifferences.join(', '))} are nonconfiguration tables and are not included in the SDM to EDM metadata comparison. See <a href="https://learn.microsoft.com/en-us/power-pages/admin/enhanced-data-model#nonconfiguration-tables" target="_blank" rel="noopener noreferrer">Enhanced data model nonconfiguration tables</a>.</div>`;
+
+ const sdmCap = formatTimestamp(sdmSnapshot.capturedAt);
+ const edmCap = edmSnapshot ? formatTimestamp(edmSnapshot.capturedAt) : '— pending —';
+ const totalEdmDisplay = edmSnapshot ? edmTotal : '?';
+
+ return `<div class="section" id="tab-pages">
+ <h2>Pages &amp; Components</h2>
+ <p class="section-desc">Side-by-side component counts before migration (SDM) and after (EDM). Count status does not verify individual records; record-level comparison and migration safety checks are separate.</p>
+
+ ${summary}
+
+ ${excludedDifferenceNote}
+
+ <div class="snapshot-meta">
+ <div class="kv-item"><div class="kv-label">SDM captured</div><div class="kv-value">${escapeHtml(sdmCap)}</div></div>
+ <div class="kv-item"><div class="kv-label">EDM captured</div><div class="kv-value">${escapeHtml(edmCap)}</div></div>
+ <div class="kv-item"><div class="kv-label">SDM total</div><div class="kv-value">${sdmTotal}</div></div>
+ <div class="kv-item"><div class="kv-label">EDM total</div><div class="kv-value">${totalEdmDisplay}</div></div>
+ </div>
+
+ <div class="cat-list">
+${categoryRows}
+ </div>
+</div>`;
+}
+
+function formatCategoryName(cat) {
+ // Convert camelCase to readable: "webPages" → "Web Pages"
+ return cat
+ .replace(/([A-Z])/g, ' $1')
+ .replace(/^./, (c) => c.toUpperCase())
+ .trim();
+}
+
+// 5-bucket taxonomy for Pages & Components. Order here drives the render order.
+const CATEGORY_GROUP_ORDER = [
+ 'Pages & Content',
+ 'Forms & Lists',
+ 'Navigation',
+ 'Security & Access',
+ 'Site Configuration',
+ 'Other',
+];
+
+// Which group each Power Pages component category belongs to.
+// Categories not in this map fall into 'Other' (defensive fallback for new
+// component types that PAC may add in future releases).
+const CATEGORY_TO_GROUP = {
+ // Pages & Content — routes, files, and the text/templates that render them
+ webPages: 'Pages & Content',
+ webFiles: 'Pages & Content',
+ webTemplates: 'Pages & Content',
+ contentSnippets: 'Pages & Content',
+ pageTemplates: 'Pages & Content',
+ tags: 'Pages & Content',
+ siteMarkers: 'Pages & Content',
+ urlHistory: 'Pages & Content',
+ redirects: 'Pages & Content',
+ shortcuts: 'Pages & Content',
+
+ // Forms & Lists — data-entry surfaces backed by Dataverse tables
+ basicForms: 'Forms & Lists',
+ advancedForms: 'Forms & Lists',
+ advancedFormSteps: 'Forms & Lists',
+ lists: 'Forms & Lists',
+
+ // Navigation — discovery / link-out widgets
+ webLinkSets: 'Navigation',
+ webLinks: 'Navigation',
+
+ // Security & Access — authorization layer
+ webRoles: 'Security & Access',
+ webpageRules: 'Security & Access',
+ websiteAccesses: 'Security & Access',
+ tablePermissions: 'Security & Access',
+ columnPermissionProfiles: 'Security & Access',
+
+ // Site Configuration — site-wide config, channel bindings
+ siteSettings: 'Site Configuration',
+ websiteLanguages: 'Site Configuration',
+ publishingStates: 'Site Configuration',
+ cloudFlowConsumers: 'Site Configuration',
+};
+
+function groupForCategory(cat) {
+ return CATEGORY_TO_GROUP[cat] || 'Other';
+}
+
+// Short, customer-facing descriptions for the Power Pages component categories
+// that surface in SDM/EDM site snapshots. Used as the cat-desc subtitle.
+const CATEGORY_DESC = {
+ webPages: 'Site pages — each one is a route in your portal with a parent template, language, and partial URL.',
+ webTemplates: 'Liquid templates that pages and components reuse to render dynamic content.',
+ webFiles: 'Static assets uploaded into the site — images, CSS, JS, PDFs surfaced via notes attachments.',
+ webLinkSets: 'Named navigation menus referenced from Liquid (header, footer, sidebar links).',
+ webLinks: 'Individual navigation links within web link sets — each is one entry that renders inside its parent menu.',
+ webRoles: 'Authorization roles used by Web Page Access Rules and Table Permissions.',
+ webpageRules: 'Web Page Access Rules — who can read/edit each page based on Web Roles.',
+ websiteAccesses: 'Website-level access permissions controlling preview-mode and admin operations.',
+ websiteLanguages: 'Languages enabled on the site, each with its own published localized content.',
+ pageTemplates: 'Page layout definitions that webPages select from when rendering.',
+ contentSnippets: 'Reusable inline text blobs referenced by Liquid as {{ snippets["name"] }}.',
+ basicForms: 'Entity Forms — single-record create/edit/read forms backed by a Dataverse table.',
+ advancedFormSteps: 'Individual steps within multistep forms, including target tables and next-step routing.',
+ siteSettings: 'Key/value configuration toggles for the site (cache, authentication, telemetry, etc.).',
+ siteMarkers: 'Named anchors used by Liquid to reference specific pages by purpose (e.g. "Home", "404").',
+ publishingStates: 'Editorial states (Draft, Published, Inactive) attached to webPages and webFiles.',
+ tags: 'Editorial tags used to classify webPages — surfaced via SDM YAML only.',
+ ads: 'Banner ad records that surface via ad placements.',
+ adPlacements: 'Page slots where ads can render.',
+ polls: 'Inline poll/voting widgets surfaced on webPages.',
+ tablePermissions: 'Row-level table permissions controlling Dataverse access from the portal.',
+ urlHistory: 'Tracked URL renames so old URLs continue to 301 redirect to new ones.',
+ // Less-common but possible
+ redirects: 'Configured URL redirects (source URL → destination URL).',
+ shortcuts: 'Page shortcuts — alternate URLs that resolve to an existing webPage.',
+ forums: 'Community forums (D365 Customer / Community / Partner portal feature).',
+ blogs: 'Blog containers and posts (D365 Customer / Partner portal feature).',
+ ideas: 'Idea/forum submission containers (D365 Customer portal feature).',
+};
+
+function categoryDescription(cat) {
+ return CATEGORY_DESC[cat] || '';
+}
+
+function describeRecord(rec, category) {
+ // Pick a sensible label per category. Use the most identifying field available.
+ if (category === 'webPages') {
+ const parts = [rec.name, rec.partialUrl ? `url=${rec.partialUrl}` : null, rec.language ? `lang=${rec.language}` : null, rec.kind ? `(${rec.kind})` : null].filter(Boolean);
+ return parts.join(' · ');
+ }
+ if (category === 'webLinks') {
+ const parts = [rec.name, rec.parentSet ? `in '${rec.parentSet}'` : null, rec.language ? `lang=${rec.language}` : null].filter(Boolean);
+ return parts.join(' · ');
+ }
+ if (category === 'advancedFormSteps') return `${rec.name || '(unnamed)'} in ${rec.parentForm || '(unknown form)'}`;
+ if (rec.name && rec.language) return `${rec.name} · lang=${rec.language}`;
+ if (rec.name && rec.partialUrl) return `${rec.name} · url=${rec.partialUrl}`;
+ if (rec.name) return rec.name;
+ if (rec.slug) return rec.slug;
+ return JSON.stringify(rec).slice(0, 120);
+}
+
+// Decisions & Rationale: the major migration CHOICES the user made, recorded live via
+// update-state.js --add-decision. Lives in the Migration & Review tab (after the phase
+// cards) so it reads as a durable, after-the-fact review of every consequential choice.
+function renderDecisionRow(d) {
+ const label = escapeHtml(d.label || d.id || 'Decision');
+ const choice = escapeHtml(d.choice || '');
+ const rationale = d.rationale
+ ? `\n <div class="decision-rationale">${escapeHtmlAllowingInline(d.rationale)}</div>`
+ : '';
+ const at = d.at ? `<span class="decision-at">${escapeHtml(formatTimestamp(d.at))}</span>` : '';
+ return ` <div class="decision-row">
+ <div class="decision-head">
+ <span class="decision-label">${label}</span>
+ <span class="decision-choice">${choice}</span>
+ ${at}
+ </div>${rationale}
+ </div>`;
+}
+
+function renderDecisionsSection(state) {
+ const decisions = Array.isArray(state.decisions) ? state.decisions : [];
+ const body = decisions.length === 0
+ ? `<p class="decisions-empty">No migration decisions recorded yet. Major choices you make in the terminal — environment type, migration mode, package installs, remediation, reset, rollback, restart — appear here as you make them.</p>`
+ : `<div class="decisions-list">
+${decisions.map(renderDecisionRow).join('\n')}
+ </div>`;
+ return `<div class="card decisions-card" id="decisions">
+ <div class="card-title">Decisions &amp; Rationale</div>
+ <p class="decisions-desc">The major migration choices made during this run, for later review. Updates live as you respond in the terminal.</p>
+ ${body}
+</div>`;
+}
+
+function renderMigrationReviewSection(state, snapshots) {
+ const hasLaterActive = (idx) =>
+ state.phases.slice(idx + 1).some(
+ (p) => p.status === PHASE_STATUS.IN_PROGRESS || p.status === PHASE_STATUS.COMPLETED,
+ );
+
+ const phaseCards = state.phases
+ .map((p, i) =>
+ renderPhaseCard(p, {
+ collapse: p.status === PHASE_STATUS.COMPLETED && hasLaterActive(i),
+ }),
+ )
+ .join('\n');
+
+ return `<div class="section" id="tab-review">
+ <h2>Migration &amp; Review</h2>
+ <p class="section-desc">Per-phase sub-step progress, approval gates, and augmented prompts. This is the live view of what's happening.</p>
+
+${renderRemediationDiffCard(snapshots && snapshots.remediationDiff)}
+
+${phaseCards}
+
+${renderDecisionsSection(state)}
+
+${renderPromptsSection(state)}
+</div>`;
+}
+
+// ── Remediation Diff card ──────────────────────────────────────────────────
+
+function renderDiffLine(line) {
+ const t = line.type;
+ const oldNum = line.oldLine != null ? String(line.oldLine).padStart(4, ' ') : ' ';
+ const newNum = line.newLine != null ? String(line.newLine).padStart(4, ' ') : ' ';
+ const sym = t === 'added' ? '+' : t === 'removed' ? '-' : ' ';
+ return `<div class="diff-line ${t}"><span class="diff-gutter">${oldNum}</span><span class="diff-gutter">${newNum}</span><span class="diff-sym">${sym}</span><span class="diff-text">${escapeHtml(line.text || '')}</span></div>`;
+}
+
+function renderDiffHunk(hunk) {
+ const header = `@@ -${hunk.oldStart},${hunk.oldCount} +${hunk.newStart},${hunk.newCount} @@`;
+ const lines = (hunk.lines || []).map(renderDiffLine).join('');
+ return `<div class="diff-hunk"><div class="diff-hunk-header">${escapeHtml(header)}</div>${lines}</div>`;
+}
+
+function kindBadge(kind) {
+ if (kind === 'fetchxml+liquid') return '<span class="kind-badge fetchxml">FetchXML</span><span class="kind-badge liquid">Liquid</span>';
+ if (kind === 'fetchxml') return '<span class="kind-badge fetchxml">FetchXML</span>';
+ if (kind === 'liquid') return '<span class="kind-badge liquid">Liquid</span>';
+ return '';
+}
+
+function renderRemediationFileRow(entry, idx) {
+ const id = `rem-file-${idx}`;
+ const hunks = (entry.hunks || []).map(renderDiffHunk).join('');
+ const summary = (entry.changeSummary && entry.changeSummary.length > 0)
+ ? `<ul class="rem-summary">${entry.changeSummary.map((s) => `<li>${escapeHtml(s)}</li>`).join('')}</ul>`
+ : '';
+ // PowerShell escapes O'Brien as 'O''Brien'; Bash requires 'O'\''Brien'.
+ // These encodings are not interchangeable. Label each copied command's shell.
+ const paths = [entry.livePath, entry.stagedPath];
+ const validPaths = paths.every((value) => typeof value === 'string' && value &&
+ !/[\u0000-\u001f\u007f]/.test(value));
+ const diffCommands = validPaths ? [
+ { shell: 'PowerShell', quote: (value) => `'${value.replace(/'/g, "''")}'` },
+ { shell: 'Bash', quote: (value) => `'${value.replace(/'/g, "'\\''")}'` },
+ ].map(({ shell, quote }) => ({ shell, command: `code --diff ${paths.map(quote).join(' ')}` })) : [];
+ // Per-file Copy button in the always-visible summary row so the user can see
+ // exactly which file each command targets without expanding the row.
+ const copyBtn = diffCommands.map(({ shell, command }) =>
+ `<button type="button" class="rem-copy-btn" data-label="Copy ${shell} diff command" data-copy="${escapeHtml(command)}">Copy ${shell} diff command</button>`).join('');
+ const diffCmdBlock = diffCommands.length
+ ? diffCommands.map(({ shell, command }) => `<div class="rem-open">
+ <div class="rem-open-label">Open this file's side-by-side diff in VS Code using ${shell}:</div>
+ <code class="rem-open-cmd">${escapeHtml(command)}</code>
+ </div>`).join('')
+ : '<div class="rem-open">Diff command unavailable: missing or unsupported file path.</div>';
+ return `<details class="rem-file" id="${id}">
+ <summary>
+ <span class="rem-file-path">${escapeHtml(entry.relativePath)}</span>
+ ${kindBadge(entry.kind)}
+ <span class="rem-stats"><span class="rem-added">+${entry.linesAdded || 0}</span> <span class="rem-removed">−${entry.linesRemoved || 0}</span></span>
+ ${copyBtn}
+ </summary>
+ ${summary}
+ ${diffCmdBlock}
+ <div class="diff-body">${hunks}</div>
+</details>`;
+}
+
+function renderRemediationDiffCard(diff) {
+ if (!diff || !diff.files || diff.files.length === 0) return '';
+
+ const files = diff.files;
+ const fxCount = files.filter((f) => f.kind === 'fetchxml' || f.kind === 'fetchxml+liquid').length;
+ const lqCount = files.filter((f) => f.kind === 'liquid' || f.kind === 'fetchxml+liquid').length;
+ const totalAdded = files.reduce((a, f) => a + (f.linesAdded || 0), 0);
+ const totalRemoved = files.reduce((a, f) => a + (f.linesRemoved || 0), 0);
+ const fileRows = files.map(renderRemediationFileRow).join('\n');
+
+ const generatedAt = diff.generatedAt ? formatTimestamp(diff.generatedAt) : '';
+
+ return `<div class="card remediation-card">
+ <div class="card-title">Remediation Diff <span class="rem-card-subtitle">— review before approving upload</span></div>
+ <p class="rem-blurb">Auto-rewriters proposed changes to <strong>${files.length} file${files.length === 1 ? '' : 's'}</strong> (${fxCount} FetchXML${lqCount ? ` · ${lqCount} Liquid` : ''}, <span class="rem-added">+${totalAdded}</span> <span class="rem-removed">−${totalRemoved}</span> lines). Files are written to <code>remediation-staged/</code> — your live site source is untouched until you approve.</p>
+ <div class="rem-meta">Staged at ${escapeHtml(generatedAt)}</div>
+
+ <div class="rem-howto">
+ <div class="rem-howto-title">Review each change in VS Code's built-in diff editor</div>
+ <p>Each file below has a <strong>Copy diff command</strong> button. Paste the copied command into any terminal to open that file's side-by-side diff (current vs proposed) in VS Code — no extension required. Requires the <code>code</code> command on PATH (in VS Code: Command Palette → <em>Shell Command: Install 'code' command in PATH</em>). The commands use absolute paths, so they work from any working directory.</p>
+ </div>
+
+ <h4 class="rem-files-heading">Per-file diffs &amp; inline preview</h4>
+ <div class="rem-file-list">
+${fileRows}
+ </div>
+</div>`;
+}
+
+// ── Customization Findings card ─────────────────────────────────
+
+function renderCustomizationSection(state) {
+ return `<div class="section" id="tab-customization">
+ <h2>Customization Findings</h2>
+ <p class="section-desc">Catalog of <code>adx_*</code> scan references detected by <code>pac pages migrate-datamodel</code>. Raw counts are not defect counts or severity ratings.</p>
+
+${renderCustomizationCard(state)}
+</div>`;
+}
+
+const CATEGORY_LABELS = {
+ fetchxml: 'FetchXML',
+ liquid: 'Liquid',
+ dme: 'Data Model Extensions',
+ plugins: 'Plugins',
+ workflows: 'Workflows',
+ relationships: 'Relationships',
+};
+
+function renderCustomizationCard(state) {
+ const report = state.customizationReport;
+
+ // State 1: not yet scanned
+ if (!report) {
+ return `<div class="card cust-card pending">
+ <div class="card-title">Customization Findings <span class="cust-card-subtitle">— catalog of <code>adx_*</code> usage detected in your site</span></div>
+ <p class="cust-blurb">Customization report will appear here after the metadata migration scans your site (Authoring Track step 2.3 / Downstream Track step 3.2). The catalog distinguishes informational references, actionable changes, and items needing context review; scan presence alone does not establish a defect.</p>
+</div>`;
+ }
+
+ const total = Number.isFinite(report.totalFindings) ? report.totalFindings : 0;
+ const scannedAt = report.scannedAt ? formatTimestamp(report.scannedAt) : '';
+
+ // State 2: zero findings (clean)
+ if (total === 0) {
+ return `<div class="card cust-card clean">
+ <div class="card-title">Customization Findings <span class="cust-card-subtitle">— no <code>adx_*</code> customizations detected</span></div>
+ <div class="cust-clean-row">
+ <div class="cust-clean-icon">✓</div>
+ <div class="cust-clean-text">
+ <div class="cust-clean-title">No scan findings.</div>
+ <div class="cust-clean-sub">PAC reported no references in this scan. This does not prove complete coverage or runtime compatibility; runtime validation remains required.</div>
+ </div>
+ </div>
+ ${scannedAt ? `<div class="cust-meta">Scanned at ${escapeHtml(scannedAt)}</div>` : ''}
+</div>`;
+ }
+
+ // State 3: has findings
+ const breakdown = report.breakdown || {};
+ const chips = Object.keys(breakdown)
+ .filter((k) => Number.isFinite(breakdown[k]) && breakdown[k] > 0)
+ .map((k) => {
+ const label = CATEGORY_LABELS[k] || k;
+ return `<span class="cust-chip cust-chip-${escapeHtml(k)}"><span class="cust-chip-label">${escapeHtml(label)}</span><span class="cust-chip-count">${breakdown[k]}</span></span>`;
+ })
+ .join('');
+
+ const reportHref = localReportLink(report.path);
+ const reportLink = reportHref
+ ? `<a class="cust-open-btn" href="${escapeHtml(reportHref)}">
+ <span class="cust-open-icon">📄</span>
+ <span class="cust-open-text">
+ <span class="cust-open-title">Open customization-report.html</span>
+ <span class="cust-open-sub">Per-finding informational / actionable / context-review assessments and reasons</span>
+ </span>
+ </a>`
+ : report.path ? '<div class="cust-meta">Customization report unavailable: unsupported link.</div>' : '';
+
+ const csvLine = report.csvPath
+ ? `<div class="cust-meta">Source CSV: <code>${escapeHtml(report.csvPath)}</code></div>`
+ : '';
+
+ return `<div class="card cust-card has-findings">
+ <div class="card-title">Customization Findings <span class="cust-card-subtitle">— scan references, not confirmed defects</span></div>
+ <p class="cust-blurb">Expected references do not require a risk acknowledgment. Open the catalog for assessments; use the Remediation Diff card only for actual staged proposals. Zero proposals does not mean all findings have been reviewed.</p>
+ <div class="cust-summary-row">
+ <div class="cust-total">
+ <div class="cust-total-num">${total}</div>
+ <div class="cust-total-label">finding${total === 1 ? '' : 's'} across ${Object.keys(breakdown).filter((k) => breakdown[k] > 0).length} categor${Object.keys(breakdown).filter((k) => breakdown[k] > 0).length === 1 ? 'y' : 'ies'}</div>
+ </div>
+ <div class="cust-chips">${chips}</div>
+ </div>
+ ${reportLink}
+ ${csvLine}
+ ${scannedAt ? `<div class="cust-meta">Scanned at ${escapeHtml(scannedAt)}</div>` : ''}
+</div>`;
+}
+
+// ── Transactional References Migration card ───────────────────────
+
+function renderRefsMigrationSection(state) {
+ return `<div class="section" id="tab-refs">
+ <h2>Transactional References Migration</h2>
+ <p class="section-desc">Chunk-level tracker from <code>pac pages migrate-datamodel --webSiteId &lt;ID&gt; -s -v</code> — step history, per-run totals, and any chunk-level errors.</p>
+
+${renderRefsMigrationCard(state)}
+</div>`;
+}
+
+const REFS_STATUS_META = {
+ NotStarted: { cls: 'pending', label: 'Not started' },
+ Running: { cls: 'running', label: 'Running' },
+ Completed: { cls: 'completed', label: 'Completed' },
+ Failed: { cls: 'failed', label: 'Failed' },
+ Reverted: { cls: 'warn', label: 'Reverted' },
+ Unknown: { cls: 'warn', label: 'Unknown' },
+};
+
+function formatDuration(fromIso, toIso) {
+ if (!fromIso || !toIso) return '';
+ const from = new Date(fromIso).getTime();
+ const to = new Date(toIso).getTime();
+ if (Number.isNaN(from) || Number.isNaN(to) || to < from) return '';
+ const sec = Math.floor((to - from) / 1000);
+ if (sec < 60) return `${sec}s`;
+ const min = Math.floor(sec / 60);
+ const remSec = sec % 60;
+ if (min < 60) return `${min}m ${remSec}s`;
+ const hr = Math.floor(min / 60);
+ const remMin = min % 60;
+ return `${hr}h ${remMin}m`;
+}
+
+function renderRefsMigrationCard(state) {
+ const r = state.refsMigration;
+
+ // State 1: not yet captured
+ if (!r) {
+ return `<div class="card refs-card pending">
+ <div class="card-title">Transactional References Migration <span class="refs-card-subtitle">— chunk-level tracker from <code>pac pages migrate-datamodel -s -v</code></span></div>
+ <p class="refs-blurb">Migration progress will appear here once the transactional references migration starts (Phase 3.1). You'll see step history, per-run chunk totals, and any chunk-level errors.</p>
+</div>`;
+ }
+
+ const meta = REFS_STATUS_META[r.status] || REFS_STATUS_META.Unknown;
+ const totalChunks = (r.runs || []).reduce((a, run) => a + (Number.isFinite(run.chunkTotal) ? run.chunkTotal : 0), 0);
+ const totalSucceeded = (r.runs || []).reduce((a, run) => a + (Number.isFinite(run.succeeded) ? run.succeeded : 0), 0);
+ const totalCompleted = (r.runs || []).reduce((a, run) => a + (Number.isFinite(run.completed) ? run.completed : 0), 0);
+ const totalFailed = totalCompleted - totalSucceeded;
+ const duration = formatDuration(r.createdAt, r.modifiedAt);
+ // Determinate progress bar from succeeded / total chunks. Only meaningful once the
+ // tracker reports at least one run with a chunkTotal; before that it stays hidden.
+ const chunkPct = totalChunks > 0 ? Math.round((totalSucceeded / totalChunks) * 100) : 0;
+ const progressBar = totalChunks > 0
+ ? `\n <div class="refs-progress" title="${totalSucceeded} of ${totalChunks} chunks succeeded"><div class="refs-progress-fill${totalFailed > 0 ? ' has-fail' : ''}" style="width:${chunkPct}%"></div></div>`
+ : '';
+
+ const stepHistoryRows = (r.stepHistory || []).map((s) => {
+ const stepName = escapeHtml(s.step || '');
+ const ts = s.at ? formatTimestamp(s.at) : '';
+ return ` <div class="refs-step-row"><div class="refs-step-name">${stepName}</div><div class="refs-step-ts">${escapeHtml(ts)}</div></div>`;
+ }).join('\n');
+
+ const renderRunRows = (run, idx) => {
+ const runHeader = `<div class="refs-run-header">
+ <div class="refs-run-name">${escapeHtml(run.name || `Run ${idx + 1}`)}</div>
+ <div class="refs-run-stats"><span class="refs-run-stat">${run.chunkTotal || 0} chunks</span> <span class="refs-run-stat ok">${run.succeeded || 0} succeeded</span>${(run.completed || 0) - (run.succeeded || 0) > 0 ? ` <span class="refs-run-stat fail">${(run.completed || 0) - (run.succeeded || 0)} failed</span>` : ''}</div>
+ </div>`;
+ const chunks = Array.isArray(run.chunks) ? run.chunks : [];
+ if (chunks.length === 0) return ` <div class="refs-run">${runHeader}</div>`;
+ const chunkRows = chunks.map((c) => {
+ const hasErr = c.errorType && c.errorType !== 'N/A' && c.errorType !== null;
+ const rowCls = hasErr ? ' refs-chunk-error' : '';
+ const outcomeIcon = hasErr ? '✗' : '✓';
+ const errCol = hasErr
+ ? `<div class="refs-chunk-err"><span class="refs-chunk-err-type">${escapeHtml(c.errorType)}</span>${c.errorDetails && c.errorDetails !== 'N/A' ? `<span class="refs-chunk-err-detail">${escapeHtml(c.errorDetails)}</span>` : ''}</div>`
+ : '';
+ return ` <div class="refs-chunk-row${rowCls}"><div class="refs-chunk-icon">${outcomeIcon}</div><div class="refs-chunk-name" title="${escapeHtml(c.name || '')}">${escapeHtml(c.name || '')}</div>${errCol}</div>`;
+ }).join('\n');
+ const collapse = chunks.length > 5;
+ const chunksBlock = collapse
+ ? `<details class="refs-chunks"><summary>Show ${chunks.length} chunks</summary><div class="refs-chunk-list">\n${chunkRows}\n </div></details>`
+ : `<div class="refs-chunk-list">\n${chunkRows}\n </div>`;
+ return ` <div class="refs-run">${runHeader}${chunksBlock}</div>`;
+ };
+
+ const runRows = (r.runs || []).map(renderRunRows).join('\n');
+ const capturedAt = r.capturedAt ? formatTimestamp(r.capturedAt) : '';
+ // Step-level failure detail (refsMigration.error) — distinct from the per-chunk errors on
+ // runs[].chunks[]. Shown when the migration step/command itself failed (command aborted,
+ // auth/network failure, or the tracker reported Failed with a top-level message).
+ const errorBlock = r.error
+ ? `\n <div class="refs-error">
+ <div class="refs-error-title">Migration step error</div>
+ <div class="refs-error-detail">${escapeHtml(r.error)}</div>
+ </div>`
+ : '';
+
+ return `<div class="card refs-card ${meta.cls}">
+ <div class="card-title">Transactional References Migration <span class="refs-card-subtitle">— chunk-level tracker from <code>pac pages migrate-datamodel -s -v</code></span></div>
+ <div class="refs-summary">
+ <div class="refs-status-pill refs-${meta.cls}">${escapeHtml(meta.label)}</div>
+ <div class="refs-kvs">
+ ${r.currentStep ? `<div class="refs-kv"><div class="refs-kv-label">Current step</div><div class="refs-kv-value">${escapeHtml(r.currentStep)}</div></div>` : ''}
+ ${totalChunks > 0 ? `<div class="refs-kv"><div class="refs-kv-label">Chunks</div><div class="refs-kv-value"><span class="refs-chunks-ok">${totalSucceeded}</span> / ${totalChunks}${totalFailed > 0 ? ` <span class="refs-chunks-fail">(${totalFailed} failed)</span>` : ''}</div></div>` : ''}
+ ${duration ? `<div class="refs-kv"><div class="refs-kv-label">Duration</div><div class="refs-kv-value">${escapeHtml(duration)}</div></div>` : ''}
+ </div>
+ </div>${progressBar}${errorBlock}
+
+ ${stepHistoryRows ? `<details class="refs-steps">
+ <summary>Step history (${(r.stepHistory || []).length})</summary>
+ <div class="refs-step-list">
+${stepHistoryRows}
+ </div>
+ </details>` : ''}
+
+ ${runRows ? `<div class="refs-runs-heading">Migration runs</div>
+ <div class="refs-runs-list">
+${runRows}
+ </div>` : ''}
+
+ ${capturedAt ? `<div class="refs-meta">Captured at ${escapeHtml(capturedAt)}</div>` : ''}
+</div>`;
+}
+
+// ── Phase card / sub-step rendering ────────────────────────────
+
+function phaseStatusLabel(status) {
+ switch (status) {
+ case PHASE_STATUS.COMPLETED:
+ return { cls: 'label-done', text: 'Completed' };
+ case PHASE_STATUS.IN_PROGRESS:
+ return { cls: 'label-progress', text: 'In Progress' };
+ case PHASE_STATUS.PENDING_APPROVAL:
+ return { cls: 'label-blocked', text: 'Pending Approval' };
+ case PHASE_STATUS.BLOCKED:
+ return { cls: 'label-blocked', text: 'Blocked' };
+ default:
+ return { cls: 'label-pending', text: 'Pending' };
+ }
+}
+
+function phaseIcon(status, id) {
+ switch (status) {
+ case PHASE_STATUS.COMPLETED:
+ return { cls: 'status-done', glyph: '✓' };
+ case PHASE_STATUS.IN_PROGRESS:
+ return { cls: 'status-progress', glyph: '⏳' };
+ case PHASE_STATUS.PENDING_APPROVAL:
+ return { cls: 'status-pending', glyph: String(id) };
+ case PHASE_STATUS.BLOCKED:
+ return { cls: 'status-blocked', glyph: '!' };
+ default:
+ return { cls: 'status-pending', glyph: String(id) };
+ }
+}
+
+function subStepIcon(status) {
+ switch (status) {
+ case SUB_STEP_STATUS.COMPLETED:
+ return { cls: '', glyph: '✓' };
+ case SUB_STEP_STATUS.IN_PROGRESS:
+ return { cls: 'progress', glyph: '●' };
+ case SUB_STEP_STATUS.BLOCKED:
+ return { cls: 'blocked', glyph: '⏸' };
+ default:
+ return { cls: 'pending', glyph: '○' };
+ }
+}
+
+function renderSubStep(sub) {
+ const icon = subStepIcon(sub.status);
+ const labelCls = sub.status === SUB_STEP_STATUS.PENDING ? ' pending' : '';
+ const output = sub.output
+ ? `\n <div class="sub-step-output">${escapeHtmlAllowingInline(sub.output)}</div>`
+ : '';
+ return ` <div class="sub-step">
+ <div class="sub-step-icon${icon.cls ? ' ' + icon.cls : ''}">${icon.glyph}</div>
+ <div class="sub-step-text">
+ <div class="sub-step-label${labelCls}">${escapeHtml(sub.id)} ${escapeHtml(sub.label)}</div>${output}
+ </div>
+ </div>`;
+}
+
+function renderPhaseCard(phase, { collapse }) {
+ const icon = phaseIcon(phase.status, phase.id);
+ const label = phaseStatusLabel(phase.status);
+ const subStepsCount = phase.subSteps.length;
+ const noun = subStepsCount === 1 ? 'sub-step' : 'sub-steps';
+
+ let meta;
+ if (phase.status === PHASE_STATUS.COMPLETED && phase.startedAt && phase.completedAt) {
+ meta = `${subStepsCount} ${noun} · completed in ${formatElapsed(phase.startedAt, phase.completedAt)}`;
+ } else if (phase.status === PHASE_STATUS.IN_PROGRESS) {
+ const done = phase.subSteps.filter((s) => s.status === SUB_STEP_STATUS.COMPLETED).length;
+ meta = `${done} of ${subStepsCount} ${noun} complete${phase.startedAt ? ` · started ${formatElapsed(phase.startedAt, null)} ago` : ''}`;
+ } else if (phase.status === PHASE_STATUS.PENDING_APPROVAL) {
+ meta = `${subStepsCount} ${noun} · awaiting your approval to start`;
+ } else {
+ meta = `${subStepsCount} ${noun}`;
+ }
+
+ const subStepsHtml = phase.subSteps.map(renderSubStep).join('\n');
+ const subStepsBlock = collapse
+ ? ` <details>
+ <summary>Show ${subStepsCount} completed ${noun}</summary>
+${subStepsHtml}
+ </details>`
+ : subStepsHtml;
+
+ return `<div class="phase-card">
+ <div class="phase-header">
+ <div class="phase-status-icon ${icon.cls}">${icon.glyph}</div>
+ <div class="phase-title">
+ <h3>Phase ${phase.id}: ${escapeHtml(phase.title)}</h3>
+ <div class="phase-meta">${escapeHtml(meta)}</div>
+ </div>
+ <div class="phase-status-label ${label.cls}">${escapeHtml(label.text)}</div>
+ </div>
+ <div class="sub-steps">
+${subStepsBlock}
+ </div>
+ </div>`;
+}
+
+// ── Approval banner ────────────────────────────────────────────────────────
+
+function renderUserActionBanner(state) {
+ const input = normalizePendingInput(state.pendingInput);
+ if (input) {
+ return `<section class="approval-banner" id="user-action-notice" role="alert" aria-labelledby="user-action-title">
+ <h3 id="user-action-title">Your input is needed</h3>
+ <p>${escapeHtml(input.requiredAction)}</p>
+ <p class="approval-instr"><strong>Where to respond:</strong> ${escapeHtml(input.responseLocation)}</p>
+</section>`;
+ }
+ const gate = state.approvalGate;
+ if (!gate) return '';
+ const track = state.track;
+ const key = track ? `${gate.phaseId}:${gate.kind}:${track}` : null;
+ const fallbackKey = `${gate.phaseId}:${gate.kind}`;
+ const copy = (key && APPROVAL_COPY[key]) || APPROVAL_COPY[fallbackKey] || {
+ heading: gate.title || `Approval required`,
+ body: [gate.body || 'Respond in your Claude Code chat to continue.'],
+ approve: '› Yes, proceed',
+ cancel: '› Cancel',
+ };
+ const bodyHtml = copy.body
+ .map((p) => ` <p>${escapeHtmlAllowingInline(p)}</p>`)
+ .join('\n');
+ return `<section class="approval-banner" id="user-action-notice" role="alert" aria-labelledby="user-action-title">
+ <h3 id="user-action-title">${escapeHtml(copy.heading)}</h3>
+${bodyHtml}
+ <p class="approval-instr"><strong>To approve and continue</strong>, respond in your Claude Code chat with:</p>
+ <div class="action-cmd">${escapeHtml(copy.approve)}</div>
+ <p class="approval-instr"><strong>To cancel</strong>:</p>
+ <div class="action-cmd">${escapeHtml(copy.cancel)}</div>
+</section>`;
+}
+
+// ── Augmented prompts ──────────────────────────────────────────────────────
+
+function renderPromptCard(kind, prompt) {
+ const titleMap = {
+ plugin: { icon: '🔌', label: 'Plugin Remediation Prompt' },
+ dme: { icon: '🗂️', label: 'Data Model Extension Remediation Prompt' },
+ };
+ const t = titleMap[kind];
+ if (!prompt) {
+ const pendingDesc =
+ kind === 'plugin'
+ ? 'Not yet generated. Will appear after the customization report is parsed if any custom plugins are detected on adx_* entities.'
+ : 'Not yet generated. Will appear after the customization report is parsed if any custom columns are detected on adx_* tables.';
+ return `<div class="prompt-card pending">
+ <h4>${t.icon} ${escapeHtml(t.label)}</h4>
+ <div class="prompt-state">${escapeHtml(pendingDesc)}</div>
+ </div>`;
+ }
+ if (prompt.status !== PROMPT_STATUS.READY) {
+ return `<div class="prompt-card pending">
+ <h4>${t.icon} ${escapeHtml(t.label)}</h4>
+ <div class="prompt-state">${escapeHtmlAllowingInline(prompt.summary || 'Pending.')}</div>
+ </div>`;
+ }
+ const href = localReportLink(prompt.path);
+ const link = href
+ ? `<div class="links"><a href="${escapeHtml(href)}">📄 ${escapeHtml(prompt.path.replace(/^.*[\\/]/, ''))}</a></div>`
+ : prompt.path ? `<div class="links">${escapeHtml(prompt.path)} (unsupported link)</div>` : '';
+ return `<div class="prompt-card ready">
+ <h4>${t.icon} ${escapeHtml(t.label)}</h4>
+ <p>${escapeHtmlAllowingInline(prompt.summary || '')}</p>
+ ${link}
+ </div>`;
+}
+
+function renderPromptsSection(state) {
+ const p = state.augmentedPrompts || {};
+ const anyReady =
+ (p.plugin && p.plugin.status === PROMPT_STATUS.READY) ||
+ (p.dme && p.dme.status === PROMPT_STATUS.READY);
+ const blurb = anyReady
+ ? 'Generated from the customization report. The skill does not modify customer-owned plugin source or Dataverse schema directly — paste these prompts into fresh Claude Code sessions to drive that work.'
+ : 'The skill does not modify customer-owned plugin source or Dataverse schema directly. Instead, after the customization report has been parsed, paste-ready prompts will appear here for you to take to fresh Claude Code sessions.';
+ return `<div class="card prompts-section">
+ <h3>Augmented Prompts for Customer-Owned Code</h3>
+ <p class="prompts-blurb">${escapeHtml(blurb)}</p>
+${renderPromptCard('plugin', p.plugin)}
+${renderPromptCard('dme', p.dme)}
+</div>`;
+}
+
+// ── CSS ────────────────────────────────────────────────────────────────────
+
+const CSS = `:root {
+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --surface3:#edebe9;
+ --border:#e1dfdd; --border-light:#c8c6c4;
+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e;
+ --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;
+ --critical:#d13438; --critical-bg:#d134380a; --critical-border:#d1343825;
+ --warning:#ca5010; --warning-bg:#ca50100a; --warning-border:#ca501025;
+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1025;
+ --info:#0078d4; --info-bg:#0078d40a; --info-border:#0078d425;
+ --purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b825;
+ --mono:'Cascadia Code','Consolas',monospace;
+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;
+ --radius:8px; --radius-sm:4px;
+ --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);
+ --shadow-8:0 3.2px 7.2px 0 rgba(0,0,0,0.132),0 0.6px 1.8px 0 rgba(0,0,0,0.108);
+}
+* { margin:0; padding:0; box-sizing:border-box; }
+html { scroll-behavior:smooth; }
+body { font-family:var(--sans); background:var(--bg); color:var(--text); font-size:14px; line-height:1.6; }
+
+/* Now running banner — always-visible pointer for the active long-running step.
+ Elapsed clock + estimate bar are advanced client-side every second so they keep
+ moving between the 40s auto-refreshes, even while a blocking pac call stops the
+ agent from writing new state. */
+.now-running { background:var(--accent-bg); border-bottom:1px solid var(--accent-border); padding:12px 28px; display:flex; flex-direction:column; gap:8px; }
+.now-running-row { display:flex; align-items:center; gap:12px; flex-wrap:wrap; }
+.now-running-spinner { width:14px; height:14px; border-radius:50%; border:2px solid var(--accent-border); border-top-color:var(--accent); animation:now-running-spin 0.9s linear infinite; flex-shrink:0; }
+@keyframes now-running-spin { to { transform:rotate(360deg); } }
+.now-running-label { font-weight:700; color:var(--text-bright); font-size:13.5px; }
+.now-running-poll { font-family:var(--mono); font-size:11px; color:var(--accent); background:var(--surface); border:1px solid var(--accent-border); border-radius:10px; padding:1px 8px; }
+.now-running-time { margin-left:auto; font-size:12px; color:var(--text-dim); font-variant-numeric:tabular-nums; }
+.now-running-time [data-now-running-elapsed] { font-weight:700; color:var(--text-bright); font-family:var(--mono); }
+.now-running-est { color:var(--text-dim); }
+.now-running-detail { font-size:12px; color:var(--text-dim); font-family:var(--mono); }
+.now-running-bar { height:6px; background:var(--surface3); border-radius:3px; overflow:hidden; }
+.now-running-bar-fill { height:100%; width:0; background:var(--accent); border-radius:3px; transition:width 0.9s linear; }
+.now-running-bar-indeterminate { width:35% !important; background:linear-gradient(90deg,var(--accent-border),var(--accent),var(--accent-border)); animation:now-running-indet 1.4s ease-in-out infinite; }
+@keyframes now-running-indet { 0% { margin-left:-35%; } 100% { margin-left:100%; } }
+/* Chunk progress bar on the Transactional References card. */
+.refs-progress { height:6px; background:var(--surface3); border-radius:3px; overflow:hidden; margin-top:4px; }
+.refs-progress-fill { height:100%; background:var(--pass); border-radius:3px; transition:width 0.4s ease; }
+.refs-progress-fill.has-fail { background:linear-gradient(90deg,var(--pass),var(--warning)); }
+/* Decisions & Rationale (Migration & Review tab) */
+.decisions-desc { font-size:12.5px; color:var(--text-dim); margin-bottom:12px; }
+.decisions-empty { font-size:13px; color:var(--text-dim); font-style:italic; }
+.decisions-list { display:flex; flex-direction:column; gap:8px; }
+.decision-row { border:1px solid var(--border); border-left:3px solid var(--accent); border-radius:var(--radius-sm); padding:10px 12px; background:var(--surface); }
+.decision-head { display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; }
+.decision-label { font-weight:700; color:var(--text-bright); font-size:13px; }
+.decision-choice { font-family:var(--mono); font-size:12.5px; color:var(--accent); font-weight:600; }
+.decision-at { margin-left:auto; font-size:11px; color:var(--text-dim); font-variant-numeric:tabular-nums; }
+.decision-rationale { font-size:12px; color:var(--text-dim); margin-top:4px; }
+
+/* Topbar */
+.topbar { z-index:100; background:var(--surface); box-shadow:var(--shadow-4); padding:14px 28px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; position:sticky; top:0; }
+.topbar-left { display:flex; align-items:center; gap:14px; }
+.topbar-title { font-size:16px; font-weight:700; color:var(--text-bright); }
+.topbar-sub { font-size:11px; color:var(--text-dim); margin-top:1px; }
+.topbar-right { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--text-dim); flex-wrap:wrap; }
+.context-pill { display:inline-flex; align-items:center; gap:6px; padding:3px 9px 3px 7px; border-radius:14px; border:1px solid var(--border); background:var(--surface); font-size:11.5px; line-height:1.4; max-width:280px; }
+.context-pill .context-label { font-size:10px; font-weight:700; color:var(--text-dim); text-transform:uppercase; letter-spacing:0.5px; }
+.context-pill .context-value { color:var(--text-bright); font-weight:600; font-family:var(--mono); font-size:11.5px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:220px; text-decoration:none; }
+.context-pill a.context-value:hover { text-decoration:underline; }
+.context-pill.ctx-info { background:var(--info-bg); border-color:var(--info-border); }
+.context-pill.ctx-info .context-value { color:var(--info); }
+.context-pill.ctx-accent { background:var(--accent-bg); border-color:var(--accent-border); }
+.context-pill.ctx-accent .context-value { color:var(--accent); }
+.context-pill.ctx-pass { background:var(--pass-bg); border-color:var(--pass-border); }
+.context-pill.ctx-pass .context-value { color:var(--pass); }
+.context-pill.ctx-warning { background:var(--warning-bg); border-color:var(--warning-border); }
+.context-pill.ctx-warning .context-value { color:var(--warning); }
+.context-pill.ctx-critical { background:var(--critical-bg); border-color:var(--critical-border); }
+.context-pill.ctx-critical .context-value { color:var(--critical); }
+.status-pill { display:inline-block; font-size:11px; font-weight:700; padding:3px 10px; border-radius:3px; font-family:var(--mono); text-transform:uppercase; letter-spacing:0.5px; }
+.status-pill.in-progress { color:var(--info); background:var(--info-bg); border:1px solid var(--info-border); }
+.status-pill.pending { color:var(--warning); background:var(--warning-bg); border:1px solid var(--warning-border); }
+.status-pill.done { color:var(--pass); background:var(--pass-bg); border:1px solid var(--pass-border); }
+
+/* Layout */
+.layout { display:flex; min-height:calc(100vh - 65px); }
+.sidebar { width:240px; background:var(--surface); border-right:1px solid var(--border); padding:20px 0; flex-shrink:0; position:sticky; top:65px; align-self:flex-start; max-height:calc(100vh - 65px); overflow-y:auto; }
+.nav-group-label { font-size:10px; font-weight:700; color:var(--text-dim); text-transform:uppercase; letter-spacing:1.2px; padding:16px 22px 6px; }
+.nav-btn { display:flex; align-items:center; gap:10px; width:100%; padding:11px 22px; background:none; border:none; border-left:2px solid transparent; color:var(--text-dim); font-size:13px; font-weight:500; cursor:pointer; font-family:var(--sans); text-align:left; transition:all 0.15s; }
+.nav-btn:hover { color:var(--text); background:var(--surface2); }
+.nav-btn.active { color:var(--accent); font-weight:600; border-left-color:var(--accent); background:var(--accent-bg); }
+.nav-btn .nav-icon { font-size:15px; opacity:0.5; width:18px; text-align:center; flex-shrink:0; }
+.nav-btn.active .nav-icon { opacity:0.9; }
+.nav-btn .nav-label { display:flex; flex-direction:column; line-height:1.25; }
+.nav-btn .nav-sub { font-size:10.5px; font-weight:500; color:var(--text-dim); margin-top:1px; letter-spacing:0.2px; }
+.nav-btn.active .nav-sub { color:var(--accent); opacity:0.85; }
+.content { flex:1; padding:32px 40px 72px; max-width:1100px; }
+.section { display:none; }
+.section.active { display:block; animation:fadeIn 0.3s ease; }
+@keyframes fadeIn { from { opacity:0; transform:translateY(8px); } to { opacity:1; transform:translateY(0); } }
+@keyframes pulse { 0%, 100% { opacity:1; } 50% { opacity:0.55; } }
+
+/* Headings */
+h2 { font-size:22px; font-weight:800; color:var(--text-bright); letter-spacing:-0.3px; margin-bottom:6px; }
+.section-desc { font-size:13px; color:var(--text-dim); margin-bottom:22px; }
+.section-desc code { color:var(--accent); background:var(--accent-bg); padding:1px 6px; border-radius:3px; font-family:var(--mono); font-size:12px; }
+h3 { font-size:15px; font-weight:700; color:var(--text-bright); margin-top:24px; margin-bottom:12px; }
+
+/* Summary / cards */
+.summary-box { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:20px 22px; margin-bottom:22px; font-size:14px; color:var(--text); line-height:1.7; }
+.summary-box p { margin:0 0 12px; }
+.summary-box p:last-child { margin-bottom:0; }
+.summary-box code { color:var(--accent); background:var(--accent-bg); padding:1px 6px; border-radius:3px; font-family:var(--mono); font-size:12.5px; }
+.summary-box strong { color:var(--text-bright); }
+.summary-box h4 { margin:18px 0 8px; font-size:12px; font-weight:700; letter-spacing:.05em; text-transform:uppercase; color:var(--accent); }
+.summary-box h4:first-child { margin-top:0; }
+.summary-box h4 code { text-transform:none; letter-spacing:normal; }
+.summary-box ul { margin:0 0 4px; padding-left:20px; }
+.summary-box li { margin:0 0 7px; line-height:1.6; }
+.summary-box li:last-child { margin-bottom:0; }
+
+.card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:18px 20px; margin-bottom:16px; box-shadow:var(--shadow-4); }
+.card-title { font-size:14px; font-weight:700; color:var(--text-bright); margin-bottom:12px; }
+
+/* Stats grid */
+.stats-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin-bottom:20px; }
+.stat-card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:16px; text-align:center; box-shadow:var(--shadow-4); position:relative; overflow:hidden; }
+.stat-card::after { content:''; position:absolute; top:0; left:50%; transform:translateX(-50%); width:40px; height:2px; background:var(--accent); border-radius:0 0 2px 2px; }
+.stat-num { font-size:22px; font-weight:800; font-family:var(--mono); line-height:1; color:var(--text-bright); }
+.stat-label { font-size:10px; color:var(--text-dim); text-transform:uppercase; letter-spacing:1px; margin-top:6px; }
+
+/* Site card */
+.site-card table { width:100%; border-collapse:collapse; font-size:13px; }
+.site-card td { padding:7px 0; border-bottom:1px solid var(--surface2); }
+.site-card tr:last-child td { border-bottom:none; }
+.site-card td:first-child { color:var(--text-dim); width:200px; font-weight:600; font-size:12px; text-transform:uppercase; letter-spacing:0.3px; }
+.site-card td:last-child { color:var(--text-bright); font-family:var(--mono); font-size:12.5px; }
+.site-card td:last-child em { color:var(--text-dim); font-style:italic; font-family:var(--sans); font-size:12.5px; }
+.site-card td.known { color:var(--text-bright); font-family:var(--mono); }
+
+/* Confidence card */
+.confidence-card .confidence-numbers { display:flex; align-items:center; gap:14px; padding:8px 0; }
+.confidence-num { font-size:32px; font-weight:800; font-family:var(--mono); color:var(--text-bright); line-height:1; }
+.confidence-num.pending { color:var(--text-dim); }
+.confidence-arrow { font-size:20px; color:var(--text-dim); }
+.confidence-icon { font-size:24px; font-weight:700; margin-left:8px; }
+.confidence-card.match .confidence-icon { color:var(--pass); }
+.confidence-card.mismatch .confidence-icon { color:var(--warning); }
+.confidence-label { font-size:12px; color:var(--text-dim); line-height:1.55; margin-top:6px; }
+.confidence-card.empty .empty-note { font-size:13px; color:var(--text-dim); line-height:1.65; }
+.confidence-card.empty .empty-note code { color:var(--accent); background:var(--accent-bg); padding:1px 6px; border-radius:3px; font-family:var(--mono); font-size:12px; }
+
+/* Plan section */
+.kv-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(220px, 1fr)); gap:10px; margin-bottom:12px; }
+.kv-item { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:10px 14px; }
+.kv-label { font-size:10px; font-weight:600; color:var(--text-dim); text-transform:uppercase; letter-spacing:0.5px; margin-bottom:3px; }
+.kv-value { font-size:13px; color:var(--text-bright); font-family:var(--mono); }
+.plan-phase-list { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); }
+.plan-phase-row { display:flex; align-items:center; gap:18px; padding:14px 20px; border-bottom:1px solid var(--surface2); }
+.plan-phase-row:last-child { border-bottom:none; }
+.plan-phase-num { font-size:11px; font-weight:700; color:var(--accent); background:var(--accent-bg); padding:4px 10px; border-radius:3px; font-family:var(--mono); flex-shrink:0; }
+.plan-phase-body { flex:1; }
+.plan-phase-title { font-size:14px; font-weight:600; color:var(--text-bright); }
+.plan-phase-meta { font-size:12px; color:var(--text-dim); margin-top:2px; }
+.plan-phase-status { font-size:11px; font-weight:700; padding:3px 10px; border-radius:3px; font-family:var(--mono); text-transform:uppercase; letter-spacing:0.5px; }
+.plan-phase-status.completed { color:var(--pass); background:var(--pass-bg); border:1px solid var(--pass-border); }
+.plan-phase-status.in-progress { color:var(--info); background:var(--info-bg); border:1px solid var(--info-border); }
+.plan-phase-status.pending { color:var(--text-dim); background:var(--surface2); border:1px solid var(--border); }
+.bullet-list { list-style:none; padding:0; background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); }
+.bullet-list li { padding:11px 18px 11px 36px; position:relative; font-size:13px; color:var(--text); border-bottom:1px solid var(--surface2); }
+.bullet-list li:last-child { border-bottom:none; }
+.bullet-list li::before { content:''; position:absolute; left:18px; top:18px; width:6px; height:6px; border-radius:50%; background:var(--accent); }
+
+/* Components sections */
+.snapshot-meta { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin-bottom:18px; }
+.cat-list { display:flex; flex-direction:column; gap:8px; }
+.cat-group { background:transparent; border:none; padding:0; margin-bottom:14px; }
+.cat-group > summary { cursor:pointer; padding:10px 16px; display:flex; align-items:center; justify-content:space-between; gap:14px; flex-wrap:wrap; list-style:none; background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius); font-size:13.5px; user-select:none; transition:background 0.15s; }
+.cat-group > summary::-webkit-details-marker { display:none; }
+.cat-group > summary:hover { background:var(--surface3); }
+.cat-group > summary::before { content:'▸ '; color:var(--text-dim); font-family:var(--mono); font-size:12px; margin-right:4px; display:inline-block; transition:transform 0.15s; }
+.cat-group[open] > summary::before { content:'▾ '; }
+.cat-group-name { font-weight:700; color:var(--text-bright); flex:1; min-width:0; }
+.cat-group-stats { font-size:12px; color:var(--text-dim); font-family:var(--mono); display:inline-flex; align-items:center; gap:6px; flex-wrap:wrap; }
+.cat-group-stats.ok { color:var(--pass); }
+.cat-group-stats.warn { color:var(--warning); }
+.cat-group-icon { font-weight:700; font-size:13px; }
+.cat-group-icon.match { color:var(--pass); }
+.cat-group-icon.mismatch { color:var(--warning); }
+.cat-group-body { padding:10px 4px 4px; display:flex; flex-direction:column; gap:8px; }
+.cat-row { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:14px 20px; box-shadow:var(--shadow-4); }
+.cat-head { display:flex; align-items:flex-start; gap:16px; }
+.cat-meta { flex:1; min-width:0; }
+.cat-name { font-size:14px; font-weight:700; color:var(--text-bright); }
+.cat-desc { font-size:12.5px; color:var(--text-dim); margin-top:4px; line-height:1.55; }
+
+/* Comparison pill — SDM → EDM with status icon */
+.comp-pill { display:flex; align-items:center; gap:8px; padding:7px 12px; border-radius:var(--radius-sm); border:1px solid var(--border); font-family:var(--mono); font-weight:700; white-space:nowrap; flex-shrink:0; }
+.comp-pill.match { background:var(--pass-bg); border-color:var(--pass-border); }
+.comp-pill.warn { background:var(--warning-bg); border-color:var(--warning-border); }
+.comp-pill.mismatch { background:var(--critical-bg); border-color:var(--critical-border); }
+.comp-pill.pending { background:var(--surface2); border-color:var(--border); }
+.comp-num { font-size:15px; color:var(--text-bright); min-width:28px; text-align:right; }
+.comp-num.sdm, .comp-num.edm { font-family:var(--mono); }
+.comp-num.placeholder { color:var(--text-dim); }
+.comp-arrow { color:var(--text-dim); font-size:13px; font-weight:400; }
+.comp-icon { font-size:14px; }
+.comp-pill.match .comp-icon { color:var(--pass); }
+.comp-pill.warn .comp-icon { color:var(--warning); }
+.comp-pill.mismatch .comp-icon { color:var(--critical); }
+.comp-meta { font-size:11px; font-weight:600; padding-left:6px; margin-left:2px; color:var(--text-dim); border-left:1px solid var(--border); }
+.comp-pill.warn .comp-meta { color:var(--warning); border-left-color:var(--warning-border); }
+.comp-pill.mismatch .comp-meta { color:var(--critical); border-left-color:var(--critical-border); }
+
+/* Pages & Components summary banner */
+.comp-summary { padding:14px 18px; border-radius:var(--radius); margin-bottom:18px; font-size:13px; line-height:1.65; border:1px solid var(--border); }
+.comp-summary.match { background:var(--pass-bg); border-color:var(--pass-border); color:var(--text); }
+.comp-summary.partial { background:var(--warning-bg); border-color:var(--warning-border); color:var(--text); }
+.comp-summary.pending { background:var(--info-bg); border-color:var(--info-border); color:var(--text); }
+.comp-summary strong { color:var(--text-bright); }
+.comp-summary .status-x { color:var(--critical); font-weight:700; font-family:var(--mono); }
+.comp-summary .status-warn { color:var(--warning); font-weight:700; font-family:var(--mono); }
+
+/* Two-column records preview (SDM | EDM) */
+.cat-records { margin-top:12px; padding-top:10px; border-top:1px solid var(--surface2); }
+.cat-records > summary { color:var(--accent); font-size:12px; font-weight:600; cursor:pointer; padding:2px 0; }
+.cat-records > summary::-webkit-details-marker { color:var(--text-dim); }
+.cat-records[open] > summary { margin-bottom:8px; }
+.records-two-col { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
+.records-col-label { font-size:10px; font-weight:700; color:var(--text-dim); text-transform:uppercase; letter-spacing:1px; margin-bottom:6px; }
+.cat-record-list { list-style:none; padding:6px 10px; background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius-sm); margin:0; }
+.cat-record-list li { font-size:12px; font-family:var(--mono); color:var(--text); padding:3px 0; border-bottom:1px dashed var(--border); }
+.cat-record-list li.record-empty { color:var(--text-dim); font-style:italic; font-family:var(--sans); }
+.cat-record-list li:last-child { border-bottom:none; }
+@media (max-width:700px) {
+ .records-two-col { grid-template-columns:1fr; }
+}
+.cat-record-list li:last-child { border-bottom:none; }
+
+/* Empty state */
+.empty-card { text-align:center; padding:36px 32px; }
+.empty-icon { font-size:38px; color:var(--text-dim); margin-bottom:10px; }
+.empty-title { font-size:15px; font-weight:700; color:var(--text-bright); margin-bottom:8px; }
+.empty-body { font-size:13px; color:var(--text-dim); line-height:1.65; max-width:680px; margin:0 auto; }
+.empty-body code { color:var(--accent); background:var(--accent-bg); padding:1px 6px; border-radius:3px; font-family:var(--mono); font-size:12px; }
+
+/* Phase cards */
+.phase-card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); margin-bottom:12px; overflow:hidden; box-shadow:var(--shadow-4); transition:box-shadow 0.2s; }
+.phase-card:hover { box-shadow:var(--shadow-8); }
+.phase-header { padding:16px 22px; display:flex; align-items:center; gap:14px; }
+.phase-status-icon { width:30px; height:30px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:14px; font-weight:700; flex-shrink:0; font-family:var(--mono); }
+.status-done { background:var(--pass-bg); color:var(--pass); border:1px solid var(--pass-border); }
+.status-progress { background:var(--info-bg); color:var(--info); border:1px solid var(--info-border); animation:pulse 2s infinite; }
+.status-pending { background:var(--surface2); color:var(--text-dim); border:1px solid var(--border); }
+.status-blocked { background:var(--warning-bg); color:var(--warning); border:1px solid var(--warning-border); }
+.phase-title { flex:1; }
+.phase-title h3 { margin:0; font-size:14px; font-weight:700; color:var(--text-bright); }
+.phase-title .phase-meta { font-size:12px; color:var(--text-dim); margin-top:2px; }
+.phase-status-label { font-size:10px; font-weight:700; padding:3px 8px; border-radius:3px; font-family:var(--mono); text-transform:uppercase; letter-spacing:0.5px; }
+.label-done { color:var(--pass); background:var(--pass-bg); border:1px solid var(--pass-border); }
+.label-progress { color:var(--info); background:var(--info-bg); border:1px solid var(--info-border); }
+.label-pending { color:var(--text-dim); background:var(--surface2); border:1px solid var(--border); }
+.label-blocked { color:var(--warning); background:var(--warning-bg); border:1px solid var(--warning-border); }
+.sub-steps { padding:4px 22px 14px 66px; font-size:13px; border-top:1px solid var(--surface2); }
+.sub-step { padding:8px 0; display:flex; align-items:flex-start; gap:10px; border-bottom:1px dashed var(--surface2); }
+.sub-step:last-child { border-bottom:none; }
+.sub-step-icon { color:var(--pass); font-size:13px; font-weight:700; min-width:14px; font-family:var(--mono); }
+.sub-step-icon.pending { color:var(--text-dim); }
+.sub-step-icon.progress { color:var(--info); animation:pulse 2s infinite; }
+.sub-step-icon.blocked { color:var(--warning); }
+.sub-step-text { flex:1; }
+.sub-step-label { color:var(--text-bright); font-weight:600; }
+.sub-step-label.pending { color:var(--text-dim); font-weight:500; }
+.sub-step-output { color:var(--text); font-size:12.5px; margin-top:3px; font-family:var(--mono); background:var(--surface2); padding:6px 10px; border-radius:var(--radius-sm); border-left:2px solid var(--accent); }
+details > summary { cursor:pointer; color:var(--accent); font-size:12px; padding:4px 0; font-weight:600; }
+details[open] > summary { margin-bottom:6px; }
+
+/* Approval banner */
+.approval-banner { background:var(--warning-bg); border:1px solid var(--warning-border); border-left:4px solid var(--warning); border-radius:var(--radius); padding:20px 24px; margin:20px 28px; scroll-margin-top:100px; box-shadow:var(--shadow-4); }
+.approval-banner h3 { margin:0 0 10px; color:var(--warning); font-size:15px; font-weight:700; }
+.approval-banner p { margin:8px 0; color:var(--text); font-size:13px; line-height:1.65; }
+.approval-banner .approval-instr { margin-top:14px; }
+.approval-banner .action-cmd { background:var(--text-bright); color:#f9f8f7; padding:10px 14px; border-radius:var(--radius-sm); font-family:var(--mono); font-size:12.5px; margin-top:6px; }
+
+/* Augmented prompts */
+.prompts-section h3 { margin-top:0; }
+.prompts-blurb { font-size:13px; color:var(--text-dim); margin-bottom:14px; }
+.prompt-card { padding:14px 16px; background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius); margin-top:10px; border-left:3px solid var(--border-light); }
+.prompt-card.pending { opacity:0.7; }
+.prompt-card.ready { border-left-color:var(--accent); background:var(--accent-bg); }
+.prompt-card h4 { margin:0 0 5px; font-size:13px; font-weight:700; color:var(--text-bright); }
+.prompt-card p { margin:5px 0; font-size:12.5px; color:var(--text); }
+.prompt-card .prompt-state { font-size:12px; color:var(--text-dim); }
+.prompt-card .links { margin-top:6px; font-size:12px; font-family:var(--mono); }
+.prompt-card .links a { color:var(--accent); text-decoration:underline; display:block; padding:2px 0; }
+
+/* Remediation diff card */
+.remediation-card { border-left:3px solid var(--warning); }
+.remediation-card .card-title { display:flex; align-items:baseline; gap:8px; flex-wrap:wrap; }
+.rem-card-subtitle { font-size:12px; font-weight:500; color:var(--text-dim); }
+.rem-blurb { font-size:13px; color:var(--text); line-height:1.65; margin-bottom:8px; }
+.rem-blurb code { font-family:var(--mono); font-size:12px; background:var(--surface2); padding:1px 6px; border-radius:3px; color:var(--text-bright); }
+.rem-blurb strong { color:var(--text-bright); }
+.rem-meta { font-size:11px; color:var(--text-dim); font-family:var(--mono); margin-bottom:14px; }
+.rem-added { color:var(--pass); font-weight:700; font-family:var(--mono); }
+.rem-removed { color:var(--critical); font-weight:700; font-family:var(--mono); }
+.rem-file-list { display:flex; flex-direction:column; gap:6px; }
+.rem-file { background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius-sm); overflow:hidden; }
+.rem-file > summary { cursor:pointer; padding:10px 14px; display:flex; align-items:center; gap:10px; font-size:12.5px; flex-wrap:wrap; list-style:none; user-select:none; }
+.rem-file > summary::-webkit-details-marker { display:none; }
+.rem-file > summary:hover { background:var(--surface3); }
+.rem-file[open] > summary { border-bottom:1px solid var(--border); }
+.rem-file-path { flex:1; font-family:var(--mono); font-weight:600; color:var(--text-bright); min-width:0; word-break:break-all; }
+.kind-badge { font-size:10px; font-weight:700; padding:2px 7px; border-radius:3px; font-family:var(--mono); text-transform:uppercase; letter-spacing:0.5px; }
+.kind-badge.fetchxml { color:var(--info); background:var(--info-bg); border:1px solid var(--info-border); }
+.kind-badge.liquid { color:var(--purple); background:var(--purple-bg); border:1px solid var(--purple-border); }
+.rem-stats { font-family:var(--mono); font-size:12px; padding:0 4px; }
+.rem-copy-btn { margin-left:auto; font-family:inherit; font-size:11px; font-weight:600; color:var(--accent); background:var(--accent-bg); border:1px solid var(--accent); padding:3px 10px; border-radius:4px; cursor:pointer; white-space:nowrap; }
+.rem-copy-btn:hover { background:var(--accent); color:#ffffff; }
+.rem-copy-btn.copied { color:#ffffff; background:#107c10; border-color:#107c10; }
+.rem-summary { margin:8px 14px; padding-left:18px; font-size:12px; color:var(--text-dim); line-height:1.6; }
+.rem-summary li { margin-bottom:2px; }
+.rem-howto { margin:10px 0 14px; padding:12px 16px; background:var(--info-bg); border:1px solid var(--info-border); border-radius:var(--radius-sm); font-size:12.5px; line-height:1.6; }
+.rem-howto-title { font-weight:700; color:var(--text-bright); margin-bottom:4px; font-size:12px; }
+.rem-howto p { margin:0; }
+.rem-howto code { font-family:var(--mono); background:var(--surface); padding:1px 5px; border-radius:3px; color:var(--text-bright); }
+.rem-files-heading { font-size:12px; font-weight:700; color:var(--text-dim); text-transform:uppercase; letter-spacing:1px; margin:18px 0 8px; }
+.rem-open { margin:8px 14px 4px; padding:8px 12px; background:var(--surface); border:1px dashed var(--border); border-radius:var(--radius-sm); }
+.rem-open-label { font-size:11px; color:var(--text-dim); margin-bottom:4px; }
+.rem-open-cmd { display:block; font-family:var(--mono); font-size:11.5px; color:var(--text-bright); background:var(--surface3); padding:6px 10px; border-radius:3px; user-select:all; cursor:text; word-break:break-all; }
+.diff-body { background:var(--surface); padding:10px 0; max-height:420px; overflow-y:auto; border-top:1px solid var(--border); font-family:var(--mono); font-size:11.5px; }
+.diff-hunk { margin-bottom:8px; }
+.diff-hunk-header { color:var(--text-dim); background:var(--surface2); padding:3px 14px; font-size:11px; }
+.diff-line { display:flex; gap:6px; padding:1px 12px; line-height:1.45; white-space:pre; }
+.diff-line.added { background:var(--pass-bg); }
+.diff-line.removed { background:var(--critical-bg); }
+.diff-gutter { color:var(--text-dim); min-width:34px; text-align:right; font-size:10.5px; user-select:none; flex-shrink:0; }
+.diff-sym { width:12px; flex-shrink:0; color:var(--text-dim); }
+.diff-line.added .diff-sym { color:var(--pass); }
+.diff-line.removed .diff-sym { color:var(--critical); }
+.diff-text { flex:1; color:var(--text-bright); white-space:pre-wrap; word-break:break-all; }
+
+/* Customization Findings card */
+.cust-card .card-title { display:flex; align-items:baseline; gap:8px; flex-wrap:wrap; }
+.cust-card-subtitle { font-size:12px; font-weight:500; color:var(--text-dim); }
+.cust-card-subtitle code { font-family:var(--mono); font-size:11.5px; background:var(--surface2); padding:1px 5px; border-radius:3px; color:var(--text-bright); }
+.cust-card.pending { border-left:3px solid var(--border-light); opacity:0.85; }
+.cust-card.clean { border-left:3px solid var(--pass); }
+.cust-card.has-findings { border-left:3px solid var(--info); }
+.cust-blurb { font-size:13px; color:var(--text-dim); line-height:1.65; margin:0; }
+.cust-clean-row { display:flex; align-items:center; gap:14px; padding:6px 0; }
+.cust-clean-icon { font-size:28px; color:var(--pass); font-weight:700; min-width:30px; text-align:center; }
+.cust-clean-text { flex:1; }
+.cust-clean-title { font-size:14px; font-weight:700; color:var(--text-bright); margin-bottom:3px; }
+.cust-clean-sub { font-size:12.5px; color:var(--text); line-height:1.55; }
+.cust-clean-sub code { font-family:var(--mono); font-size:11.5px; background:var(--surface2); padding:1px 5px; border-radius:3px; color:var(--text-bright); }
+.cust-summary-row { display:flex; align-items:center; gap:18px; flex-wrap:wrap; padding:6px 0 12px; }
+.cust-total { display:flex; flex-direction:column; align-items:flex-start; padding-right:18px; border-right:1px solid var(--border); }
+.cust-total-num { font-size:32px; font-weight:700; color:var(--info); line-height:1; font-family:var(--mono); }
+.cust-total-label { font-size:11px; color:var(--text-dim); text-transform:uppercase; letter-spacing:0.5px; margin-top:4px; font-weight:600; }
+.cust-chips { display:flex; flex-wrap:wrap; gap:6px; flex:1; }
+.cust-chip { display:inline-flex; align-items:center; gap:6px; padding:4px 10px; background:var(--surface2); border:1px solid var(--border); border-radius:14px; font-size:11.5px; }
+.cust-chip-label { color:var(--text); font-weight:600; }
+.cust-chip-count { color:var(--info); font-weight:700; font-family:var(--mono); background:var(--surface); padding:1px 7px; border-radius:10px; min-width:18px; text-align:center; }
+.cust-open-btn { display:inline-flex; align-items:center; gap:12px; padding:12px 18px; margin-top:4px; background:var(--accent); color:#ffffff; text-decoration:none; border-radius:var(--radius-sm); box-shadow:var(--shadow-4); transition:background 0.15s; }
+.cust-open-btn:hover { background:#106ebe; box-shadow:var(--shadow-8); }
+.cust-open-icon { font-size:22px; line-height:1; opacity:0.95; }
+.cust-open-text { display:flex; flex-direction:column; }
+.cust-open-title { font-size:13.5px; font-weight:700; }
+.cust-open-sub { font-size:11px; opacity:0.85; margin-top:2px; }
+.cust-meta { font-size:11px; color:var(--text-dim); font-family:var(--mono); margin-top:10px; }
+.cust-meta code { font-family:var(--mono); background:var(--surface2); padding:1px 5px; border-radius:3px; color:var(--text-bright); }
+
+/* Transactional References Migration card */
+.refs-card .card-title { display:flex; align-items:baseline; gap:8px; flex-wrap:wrap; }
+.refs-card-subtitle { font-size:12px; font-weight:500; color:var(--text-dim); }
+.refs-card-subtitle code { font-family:var(--mono); font-size:11.5px; background:var(--surface2); padding:1px 5px; border-radius:3px; color:var(--text-bright); }
+.refs-card.pending { border-left:3px solid var(--border-light); opacity:0.85; }
+.refs-card.running { border-left:3px solid var(--info); }
+.refs-card.completed { border-left:3px solid var(--pass); }
+.refs-card.failed { border-left:3px solid var(--critical); }
+.refs-card.warn { border-left:3px solid var(--warning); }
+.refs-blurb { font-size:13px; color:var(--text-dim); line-height:1.65; margin:0; }
+.refs-summary { display:flex; align-items:center; gap:18px; flex-wrap:wrap; padding:6px 0 12px; }
+.refs-status-pill { font-size:11px; font-weight:700; padding:5px 12px; border-radius:14px; text-transform:uppercase; letter-spacing:0.5px; }
+.refs-status-pill.refs-pending { color:var(--text-dim); background:var(--surface2); border:1px solid var(--border); }
+.refs-status-pill.refs-running { color:var(--info); background:var(--info-bg); border:1px solid var(--info-border); }
+.refs-status-pill.refs-completed { color:var(--pass); background:var(--pass-bg); border:1px solid var(--pass-border, var(--border)); }
+.refs-status-pill.refs-failed { color:var(--critical); background:var(--critical-bg); border:1px solid var(--border); }
+.refs-status-pill.refs-warn { color:var(--warning); background:var(--surface2); border:1px solid var(--border); }
+.refs-kvs { display:flex; flex-wrap:wrap; gap:18px; flex:1; }
+.refs-kv { display:flex; flex-direction:column; min-width:120px; }
+.refs-kv-label { font-size:10px; font-weight:600; color:var(--text-dim); text-transform:uppercase; letter-spacing:0.5px; margin-bottom:3px; }
+.refs-kv-value { font-size:13px; color:var(--text-bright); font-family:var(--mono); }
+.refs-chunks-ok { color:var(--pass); font-weight:700; }
+.refs-chunks-fail { color:var(--critical); font-weight:700; }
+.refs-steps { margin-bottom:12px; }
+.refs-steps > summary { cursor:pointer; padding:8px 0; font-size:12px; font-weight:600; color:var(--text-dim); text-transform:uppercase; letter-spacing:0.5px; list-style:none; }
+.refs-steps > summary::-webkit-details-marker { display:none; }
+.refs-steps > summary:hover { color:var(--text-bright); }
+.refs-steps > summary::before { content:'▸ '; display:inline-block; transition:transform 0.15s; }
+.refs-steps[open] > summary::before { content:'▾ '; }
+.refs-step-list { display:flex; flex-direction:column; gap:2px; padding:6px 0 0; border-top:1px dashed var(--border); }
+.refs-step-row { display:flex; align-items:center; gap:14px; padding:4px 0; font-size:12px; font-family:var(--mono); }
+.refs-step-name { color:var(--text-bright); flex:1; font-weight:600; }
+.refs-step-ts { color:var(--text-dim); font-size:11px; }
+.refs-runs-heading { font-size:11px; font-weight:700; color:var(--text-dim); text-transform:uppercase; letter-spacing:0.5px; margin:14px 0 6px; }
+.refs-runs-list { display:flex; flex-direction:column; gap:8px; }
+.refs-run { background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius-sm); padding:10px 14px; }
+.refs-run-header { display:flex; align-items:center; gap:12px; margin-bottom:8px; flex-wrap:wrap; }
+.refs-run-name { font-size:12.5px; font-weight:700; color:var(--text-bright); flex:1; min-width:0; }
+.refs-run-stats { display:flex; gap:8px; font-size:11px; font-family:var(--mono); flex-wrap:wrap; }
+.refs-run-stat { color:var(--text-dim); padding:2px 7px; background:var(--surface); border:1px solid var(--border); border-radius:10px; }
+.refs-run-stat.ok { color:var(--pass); border-color:var(--pass); }
+.refs-run-stat.fail { color:var(--critical); border-color:var(--critical); }
+.refs-chunks > summary { cursor:pointer; padding:6px 0; font-size:11.5px; color:var(--text-dim); list-style:none; }
+.refs-chunks > summary::-webkit-details-marker { display:none; }
+.refs-chunks > summary::before { content:'▸ '; display:inline-block; }
+.refs-chunks[open] > summary::before { content:'▾ '; }
+.refs-chunk-list { display:flex; flex-direction:column; gap:3px; padding-top:6px; border-top:1px dashed var(--border); }
+.refs-chunk-row { display:flex; align-items:center; gap:10px; padding:3px 0; font-size:11.5px; font-family:var(--mono); }
+.refs-chunk-row.refs-chunk-error { background:var(--critical-bg); padding:6px 8px; border-radius:3px; }
+.refs-chunk-icon { color:var(--pass); font-weight:700; min-width:14px; text-align:center; }
+.refs-chunk-row.refs-chunk-error .refs-chunk-icon { color:var(--critical); }
+.refs-chunk-name { flex:1; color:var(--text-bright); min-width:0; word-break:break-all; }
+.refs-chunk-err { display:flex; flex-direction:column; gap:2px; font-size:11px; min-width:0; }
+.refs-chunk-err-type { color:var(--critical); font-weight:700; }
+.refs-chunk-err-detail { color:var(--text-dim); }
+.refs-error { margin:2px 0 12px; padding:10px 12px; background:var(--critical-bg); border:1px solid var(--border); border-left:3px solid var(--critical); border-radius:4px; }
+.refs-error-title { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:0.5px; color:var(--critical); margin-bottom:4px; }
+.refs-error-detail { font-size:12px; color:var(--text-bright); white-space:pre-wrap; word-break:break-word; }
+.refs-meta { font-size:11px; color:var(--text-dim); font-family:var(--mono); margin-top:10px; }
+
+/* Footer */
+.footer { position:fixed; bottom:0; left:0; right:0; text-align:center; padding:10px; font-size:11px; color:var(--text-dim); border-top:1px solid var(--border); background:var(--surface); z-index:50; }
+
+/* Responsive */
+@media (max-width:900px) {
+ .layout { flex-direction:column; }
+ .sidebar { width:100%; border-right:none; border-bottom:1px solid var(--border); display:flex; flex-wrap:wrap; padding:8px; position:relative; top:0; max-height:none; }
+ .nav-group-label { width:100%; }
+ .nav-btn { width:auto; border-left:none; border-bottom:2px solid transparent; padding:10px 14px; }
+ .nav-btn.active { border-left:none; border-bottom-color:var(--accent); }
+ .content { padding:20px; }
+ .stats-grid { grid-template-columns:repeat(2,1fr); }
+ .snapshot-meta { grid-template-columns:1fr; }
+}`;
+
+// ── JS for tab switching ───────────────────────────────────────────────────
+
+const TAB_JS = `document.querySelectorAll('.nav-btn').forEach(btn => {
+ btn.addEventListener('click', () => {
+ document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
+ btn.classList.add('active');
+ document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
+ document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
+ });
+});`;
+
+// ── Topbar ─────────────────────────────────────────────────────────────────
+
+function renderTopbar(state) {
+ const site = state.site;
+ const pill = statusPillFor(state);
+ const pillClass = pillSeverityClass(state);
+
+ // Each context entry: { label, value, cls, href? }. `cls` drives the pill
+ // background color so the user can scan the top bar at a glance.
+ // Order: Env → Site → Portal URL → Env type → Template → (status pill is rendered separately, last).
+ // - env name: accent (blue) Dataverse environment display name
+ // - site: accent (blue) primary identity
+ // - portal: accent (blue) hyperlinked when URL is present
+ // - env type: severity-colored Dev/Single → info, Test/UAT → warning, Prod → critical
+ // - template: pass (green) site-defined fact
+ const contextItems = [];
+
+ if (site.environmentName) {
+ contextItems.push({ label: 'Env', value: site.environmentName, cls: 'ctx-accent' });
+ }
+
+ if (site.name) {
+ contextItems.push({ label: 'Site', value: site.name, cls: 'ctx-accent' });
+ }
+
+ if (site.portalUrl) {
+ const href = portalLink(site.portalUrl);
+ contextItems.push({ label: 'Portal', value: site.portalUrl, cls: 'ctx-accent', href,
+ invalidLink: !href });
+ }
+
+ if (site.environment) {
+ // env type drives severity: Prod is highest-attention
+ const envType = String(site.environment).toLowerCase();
+ let envTypeCls = 'ctx-info';
+ if (envType === 'prod' || envType === 'production') envTypeCls = 'ctx-critical';
+ else if (envType === 'test' || envType === 'uat' || envType === 'test/uat') envTypeCls = 'ctx-warning';
+ contextItems.push({ label: 'Env type', value: site.environment, cls: envTypeCls });
+ }
+
+ if (site.template) {
+ contextItems.push({ label: 'Template', value: site.template, cls: 'ctx-pass' });
+ }
+
+ const contextHtml = contextItems.map((c) => {
+ const valueHtml = c.href
+ ? `<a class="context-value" href="${escapeHtml(c.href)}" target="_blank" rel="noopener">${escapeHtml(c.value)}</a>`
+ : `<span class="context-value"${c.invalidLink ? ' title="Unsupported portal link; HTTPS URL required"' : ''}>${escapeHtml(c.value)}</span>`;
+ return `<span class="context-pill ${c.cls}"><span class="context-label">${escapeHtml(c.label)}</span>${valueHtml}</span>`;
+ }).join('');
+
+ return `<div class="topbar">
+ <div class="topbar-left">
+ <div>
+ <div class="topbar-title">SDM → EDM Migration</div>
+ <div class="topbar-sub">Power Pages site data-model migration</div>
+ </div>
+ </div>
+ <div class="topbar-right">
+ ${contextHtml}
+ ${state.pendingInput || state.approvalGate
+ ? `<a class="status-pill ${pillClass}" href="#user-action-notice">${escapeHtml(pill)}</a>`
+ : `<span class="status-pill ${pillClass}">${escapeHtml(pill)}</span>`}
+ </div>
+</div>`;
+}
+
+// ── Sidebar ────────────────────────────────────────────────────────────────
+
+// Now-running banner: always-visible pointer for the active long-running step
+// (package install, metadata / refs migration polling). Rendered only when
+// state.currentOperation is set. The elapsed figure and estimate-bar width are
+// seeded here from server time but then advanced every second by the inline
+// now-running ticker script — so the clock keeps moving between the 60s
+// auto-refreshes, even while a blocking `pac` call stops the agent from writing new
+// state. data-op-expected-sec, when present, drives a determinate bar that eases
+// toward the estimate; without it the bar is indeterminate.
+function renderNowRunningBanner(state) {
+ if (state.pendingInput || state.approvalGate) return '';
+ const op = state.currentOperation;
+ if (!op || !op.label) return '';
+ const startedAt = op.startedAt || state.lastUpdatedAt;
+ const expected = Number.isFinite(op.expectedDurationSec) && op.expectedDurationSec > 0
+ ? Math.floor(op.expectedDurationSec)
+ : null;
+ const pollHtml = op.poll && Number.isFinite(op.poll.attempt) && Number.isFinite(op.poll.max)
+ ? `<span class="now-running-poll">attempt ${escapeHtml(String(op.poll.attempt))}/${escapeHtml(String(op.poll.max))}</span>`
+ : '';
+ const detailHtml = op.detail
+ ? `<div class="now-running-detail">${escapeHtmlAllowingInline(op.detail)}</div>`
+ : '';
+ const estHtml = expected
+ ? ` · <span class="now-running-est">est ~${Math.max(1, Math.round(expected / 60))} min</span>`
+ : '';
+ const barClass = expected
+ ? 'now-running-bar-fill'
+ : 'now-running-bar-fill now-running-bar-indeterminate';
+ return `<div class="now-running" data-now-running data-op-started-at="${escapeHtml(startedAt)}"${expected ? ` data-op-expected-sec="${expected}"` : ''}>
+ <div class="now-running-row">
+ <span class="now-running-spinner" aria-hidden="true"></span>
+ <span class="now-running-label">Now running: ${escapeHtml(op.label)}</span>
+ ${pollHtml}
+ <span class="now-running-time"><span data-now-running-elapsed>${escapeHtml(formatElapsed(startedAt, state.lastUpdatedAt))}</span> elapsed${estHtml}</span>
+ </div>
+ ${detailHtml}
+ <div class="now-running-bar"><div class="${barClass}" data-now-running-bar></div></div>
+</div>`;
+}
+
+function renderSidebar() {
+ return `<div class="sidebar">
+ <div class="nav-group-label">Report</div>
+ <button class="nav-btn active" data-tab="overview"><span class="nav-icon">◉</span><span class="nav-label">Overview</span></button>
+ <button class="nav-btn" data-tab="plan"><span class="nav-icon">☰</span><span class="nav-label">Plan</span></button>
+ <button class="nav-btn" data-tab="pages"><span class="nav-icon">▤</span><span class="nav-label">Pages &amp; Components</span></button>
+ <button class="nav-btn" data-tab="customization"><span class="nav-icon">⚠</span><span class="nav-label">Customization Findings</span></button>
+ <button class="nav-btn" data-tab="refs"><span class="nav-icon">⇆</span><span class="nav-label">Transactional Refs</span></button>
+ <button class="nav-btn" data-tab="review"><span class="nav-icon">✓</span><span class="nav-label">Migration &amp; Review</span></button>
+</div>`;
+}
+
+// ── Main render entry ──────────────────────────────────────────────────────
+
+/**
+ * Render the full HTML report from migration state and optional snapshots.
+ *
+ * @param {object} state - Parsed migration-state.json
+ * @param {object} [opts]
+ * @param {object|null} [opts.sdmSnapshot] - Parsed sdm-snapshot.json if present
+ * @param {object|null} [opts.edmSnapshot] - Parsed edm-snapshot.json if present
+ */
+function renderLiveReport(state, opts = {}) {
+ const sdmSnapshot = opts.sdmSnapshot || null;
+ const edmSnapshot = opts.edmSnapshot || null;
+ const remediationDiff = opts.remediationDiff || null;
+ const snapshots = { sdmSnapshot, edmSnapshot, remediationDiff };
+ const pill = statusPillFor(state);
+
+ return `<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width,initial-scale=1.0">
+<title>SDM→EDM Migration — ${escapeHtml(pill)}</title>
+<style>
+${CSS}
+</style>
+</head>
+<body>
+
+${renderTopbar(state)}
+${renderUserActionBanner(state)}
+${renderNowRunningBanner(state)}
+
+<div class="layout">
+ ${renderSidebar()}
+
+ <div class="content">
+${renderOverviewSection(state, snapshots)}
+
+${renderPlanSection(state)}
+
+${renderPagesComponentsSection({ sdmSnapshot, edmSnapshot })}
+
+${renderCustomizationSection(state)}
+
+${renderRefsMigrationSection(state)}
+
+${renderMigrationReviewSection(state, snapshots)}
+ </div>
+</div>
+
+<div class="footer">
+ Generated by <strong>migrate-datamodel</strong> skill · Last updated <span data-live-updated-at>${escapeHtml(formatTimestamp(state.lastUpdatedAt))}</span> · <span id="live-refresh-status">Auto-refreshing every 40s</span> · AI-generated content may be incorrect
+</div>
+
+<script>
+${TAB_JS}
+</script>
+<script>
+// Now-running live ticker: advance the elapsed clock and estimate bar every second
+// from data attributes on the banner, independent of the 40s auto-refresh — so
+// progress stays visibly moving even while a blocking pac call prevents the agent
+// from writing new state.
+(function () {
+ var el = document.querySelector('[data-now-running]');
+ if (!el) return;
+ var startedAt = Date.parse(el.getAttribute('data-op-started-at'));
+ if (isNaN(startedAt)) return;
+ var expectedSec = parseInt(el.getAttribute('data-op-expected-sec'), 10);
+ var hasExpected = !isNaN(expectedSec) && expectedSec > 0;
+ var elapsedEl = el.querySelector('[data-now-running-elapsed]');
+ var barEl = el.querySelector('[data-now-running-bar]');
+ function fmt(sec) {
+ var m = Math.floor(sec / 60);
+ var s = sec % 60;
+ return m + 'm ' + (s < 10 ? '0' : '') + s + 's';
+ }
+ function tick() {
+ var sec = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
+ if (elapsedEl) elapsedEl.textContent = fmt(sec);
+ // Determinate bar only when an estimate was provided. Ease toward the estimate
+ // but cap below 100% — the operation clears (banner removed) only when the agent
+ // writes --clear-operation, so a full bar must never show while still running.
+ if (hasExpected && barEl) {
+ var pct = Math.min(97, (sec / expectedSec) * 100);
+ barEl.style.width = pct.toFixed(1) + '%';
+ }
+ }
+ tick();
+ setInterval(tick, 1000);
+})();
+</script>
+<script>
+// ── Copy-to-clipboard for per-file "code --diff" buttons ─────────────────────
+// Works even when the report is opened as a local file:// URL — tries the async
+// Clipboard API first, then falls back to a hidden-textarea execCommand('copy').
+(function () {
+ function fallbackCopy(text) {
+ try {
+ var ta = document.createElement('textarea');
+ ta.value = text;
+ ta.setAttribute('readonly', '');
+ ta.style.position = 'absolute';
+ ta.style.left = '-9999px';
+ document.body.appendChild(ta);
+ ta.select();
+ var ok = document.execCommand('copy');
+ document.body.removeChild(ta);
+ return ok;
+ } catch (_) { return false; }
+ }
+ function flash(btn) {
+ var label = btn.getAttribute('data-label') || 'Copy';
+ btn.textContent = 'Copied!';
+ btn.classList.add('copied');
+ setTimeout(function () {
+ btn.textContent = label;
+ btn.classList.remove('copied');
+ }, 1500);
+ }
+ document.addEventListener('click', function (e) {
+ var btn = e.target && e.target.closest ? e.target.closest('.rem-copy-btn') : null;
+ if (!btn) return;
+ // Prevent the surrounding <summary> from toggling the <details> open/closed.
+ e.preventDefault();
+ e.stopPropagation();
+ var text = btn.getAttribute('data-copy') || '';
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ navigator.clipboard.writeText(text).then(function () { flash(btn); }, function () {
+ if (fallbackCopy(text)) flash(btn);
+ });
+ } else if (fallbackCopy(text)) {
+ flash(btn);
+ }
+ });
+})();
+</script>
+<script>
+// ── Live auto-refresh ────────────────────────────────────────────────────────
+// Polls this same HTML file, compares the embedded lastUpdatedAt token, and
+// reloads the page only when the agent has written new state. Preserves the
+// scroll position and the active tab across reloads so the user doesn't lose
+// their place when the skill updates a sub-step or clears an approval gate.
+(function () {
+ var CURRENT_UPDATED_AT = ${JSON.stringify(state.lastUpdatedAt || '')};
+ var TOKEN = 'data-live-updated-at-token="';
+ var POLL_MS = 40000;
+ var SCROLL_KEY = 'sdmEdmReport:scrollY';
+ var TAB_KEY = 'sdmEdmReport:activeTab';
+ var DETAILS_KEY = 'sdmEdmReport:openDetails';
+ var statusEl = document.getElementById('live-refresh-status');
+ var inputNotice = document.getElementById('user-action-notice');
+ var topbar = document.querySelector('.topbar');
+ if (inputNotice && topbar) {
+ // Context pills wrap on small screens; a fixed anchor offset hides the
+ // notice heading behind the sticky header.
+ function updateNoticeOffset() {
+ inputNotice.style.scrollMarginTop = (topbar.offsetHeight + 16) + 'px';
+ }
+ updateNoticeOffset();
+ window.addEventListener('resize', updateNoticeOffset);
+ }
+
+ // Stable key for a <details> card so its open/closed state survives a reload even
+ // when a count in the summary ticks up ("Show 7 chunks" -> "Show 9 chunks"). Key on
+ // id, else class + digit-normalized summary text + an ordinal among identical
+ // siblings — not raw DOM index, so small structural changes don't misalign it.
+ function detailsSignature(d, seen) {
+ var key;
+ if (d.id) {
+ key = '#' + d.id;
+ } else {
+ var cls = (d.className || '').trim();
+ var sum = d.querySelector(':scope > summary');
+ var sumText = sum ? (sum.textContent || '').trim().replace(/\\d+/g, '#').slice(0, 80) : '';
+ key = cls + '|' + sumText;
+ }
+ var n = seen[key] = (seen[key] || 0) + 1;
+ return key + '~' + n;
+ }
+
+ // Restore scroll + active tab + expanded cards from the previous reload (if any).
+ try {
+ var savedScroll = sessionStorage.getItem(SCROLL_KEY);
+ if (savedScroll !== null) {
+ window.scrollTo(0, parseInt(savedScroll, 10) || 0);
+ sessionStorage.removeItem(SCROLL_KEY);
+ }
+ var savedTab = sessionStorage.getItem(TAB_KEY);
+ if (savedTab) {
+ var btn = document.querySelector('[data-tab="' + savedTab + '"]');
+ if (btn && typeof btn.click === 'function') btn.click();
+ sessionStorage.removeItem(TAB_KEY);
+ }
+ var savedOpen = JSON.parse(sessionStorage.getItem(DETAILS_KEY) || '[]');
+ if (savedOpen && savedOpen.length) {
+ var seenR = {};
+ document.querySelectorAll('details').forEach(function (d) {
+ if (savedOpen.indexOf(detailsSignature(d, seenR)) !== -1) d.open = true;
+ });
+ sessionStorage.removeItem(DETAILS_KEY);
+ }
+ } catch (_) { /* sessionStorage may be blocked — best-effort only */ }
+
+ // Capture active tab whenever the user clicks one so we can restore it.
+ document.querySelectorAll('[data-tab]').forEach(function (el) {
+ el.addEventListener('click', function () {
+ try { sessionStorage.setItem(TAB_KEY, el.getAttribute('data-tab') || ''); } catch (_) {}
+ });
+ });
+
+ function reloadPreservingScroll() {
+ try { sessionStorage.setItem(SCROLL_KEY, String(window.scrollY || 0)); } catch (_) {}
+ try {
+ var seenS = {};
+ var open = [];
+ document.querySelectorAll('details').forEach(function (d) {
+ var sig = detailsSignature(d, seenS);
+ if (d.open) open.push(sig);
+ });
+ sessionStorage.setItem(DETAILS_KEY, JSON.stringify(open));
+ } catch (_) {}
+ if (statusEl) statusEl.textContent = 'Updating…';
+ location.reload();
+ }
+
+ // When the report is opened as a local file:// URL (the common case — the skill
+ // tells the user to open the HTML file directly), browsers BLOCK fetch() of that
+ // file, so the change-detecting poll can never read it to compare tokens and the
+ // page would never auto-update. Detect that and fall back to a plain timed reload
+ // (scroll + active tab are preserved across reloads via the sessionStorage handling
+ // above). Over http(s):// we keep the smarter poll that only reloads when the
+ // embedded token actually changed, so an idle served report doesn't flash.
+ var isFile = location.protocol === 'file:';
+
+ function poll() {
+ // Don't reload a backgrounded tab — wait until the user is looking at it again.
+ if (document.visibilityState === 'hidden') return;
+ if (isFile) { reloadPreservingScroll(); return; }
+ fetch(location.pathname + '?_=' + Date.now(), { cache: 'no-store' })
+ .then(function (r) { return r.ok ? r.text() : null; })
+ .then(function (html) {
+ if (!html) return;
+ var idx = html.indexOf(TOKEN);
+ if (idx === -1) return;
+ var end = html.indexOf('"', idx + TOKEN.length);
+ if (end === -1) return;
+ var latest = html.slice(idx + TOKEN.length, end);
+ if (latest && latest !== CURRENT_UPDATED_AT) {
+ reloadPreservingScroll();
+ }
+ })
+ .catch(function () {
+ // fetch blocked/unavailable even though protocol wasn't file: (some sandboxed
+ // contexts) — degrade to a timed reload so updates still surface.
+ reloadPreservingScroll();
+ });
+ }
+ setInterval(poll, POLL_MS);
+})();
+</script>
+<!-- data-live-updated-at-token="${escapeHtml(state.lastUpdatedAt || '')}" -->
+</body>
+</html>
+`;
+}
+
+module.exports = {
+ renderLiveReport,
+ _internals: {
+ escapeHtml,
+ escapeHtmlAllowingInline,
+ countCompleted,
+ overallPercent,
+ formatElapsed,
+ },
+};
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/migration-runtime.js b/plugins/power-pages/skills/migrate-datamodel/scripts/migration-runtime.js
new file mode 100644
index 000000000..812b819ed
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/migration-runtime.js
@@ -0,0 +1,323 @@
+#!/usr/bin/env node
+'use strict';
+
+// Shell-independent migration commands and diagnostics. Approval gates and
+// reset/retry decisions remain owned by the skill; no helper resets a tracker.
+const fs = require('node:fs');
+const path = require('node:path');
+const { createHash } = require('node:crypto');
+const { runPac, commandError } = require('../../../scripts/lib/pac-command');
+const { resolvePowerPagesSiteRoot } = require('../../../scripts/lib/validation-helpers');
+const { parseCSV } = require('./generate-migration-reports');
+
+const MODES = new Set(['configurationData', 'all', 'configurationDataReferences']);
+const STATUSES = ['NotStarted', 'Running', 'Completed', 'Failed', 'Reverted', 'Unknown'];
+
+function isFile(filename) {
+ try {
+ return fs.statSync(filename).isFile();
+ } catch (error) {
+ if (error.code === 'ENOENT') return false;
+ throw error;
+ }
+}
+
+function siteRootIn(directory) {
+ const nested = resolvePowerPagesSiteRoot(directory);
+ if (nested && isFile(path.join(nested, 'website.yml'))) return nested;
+ return isFile(path.join(directory, 'website.yml')) ? directory : null;
+}
+
+function discoverSite(directory = process.cwd(), requireSite = false) {
+ const root = path.resolve(directory);
+ const direct = siteRootIn(root);
+ const candidates = direct ? [direct] : fs.readdirSync(root, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => siteRootIn(path.join(root, entry.name)))
+ .filter(Boolean);
+ if (requireSite && candidates.length !== 1) {
+ throw new Error(`Expected exactly one site with website.yml under ${root}; found ${candidates.length}. Select the correct site explicitly.`);
+ }
+ return {
+ siteRoot: candidates.length === 1 ? candidates[0] : null,
+ candidates,
+ parentOutputDir: path.join(direct ? path.dirname(root) : root, 'migration-reports'),
+ };
+}
+
+function captureSolutions(filename, deps = {}) {
+ const result = (deps.runPac || runPac)(['solution', 'list', '--includeSystemSolutions'], {
+ captureAll: true,
+ timeoutMs: 60000,
+ });
+ if (result.status !== 0 || result.error) throw new Error(commandError('Listing installed solutions', result));
+ if (!result.stdout.trim()) throw new Error('PAC returned an empty solution list; template detection cannot continue.');
+ const output = path.resolve(filename);
+ fs.mkdirSync(path.dirname(output), { recursive: true });
+ // Avoid shell redirection/Out-File defaults: detection reads UTF-8 on every OS.
+ fs.writeFileSync(output, result.stdout, 'utf8');
+ return { output };
+}
+
+function parseTracker(output) {
+ // PAC's documented skill contract is a label/value block, for example:
+ // Current migration status is : Running
+ // Current Step: ConfigurationDataCompleted
+ // Step history and chunk details can also contain "Completed"; never infer
+ // the top-level result from those incidental occurrences.
+ const text = output.replace(/\x1b\[[0-9;]*m/g, '');
+ const statusMatch = /^\s*Current migration status is\s*:\s*(\w+)\s*$/im.exec(text);
+ const status = STATUSES.find((candidate) => candidate.toLowerCase() === statusMatch?.[1].toLowerCase());
+ if (!status) throw new Error('PAC output has no recognized "Current migration status is:" field; review migration-status.txt.');
+ const currentStep = /^\s*Current Step\s*:\s*(\w+)\s*$/im.exec(text)?.[1] || null;
+ return { status, currentStep };
+}
+
+function validateTarget(websiteId, outputDir) {
+ if (typeof websiteId !== 'string' || !websiteId.trim()) throw new Error('--website-id is required');
+ if (typeof outputDir !== 'string' || !outputDir.trim()) throw new Error('--output-dir is required');
+}
+
+function checkMigrationStatus(websiteId, deps = {}, verboseSupported = true) {
+ const run = deps.runPac || runPac;
+ const command = ['pages', 'migrate-datamodel', '--webSiteId', websiteId, '--checkMigrationStatus'];
+ let result = run([...command, ...(verboseSupported ? ['--verbose'] : [])], { captureAll: true, timeoutMs: 60000 });
+ // Only an explicit unsupported-flag error permits a non-verbose retry;
+ // authentication, network and executable errors must remain visible.
+ if (verboseSupported && (result.status !== 0 || result.error) &&
+ /unknown argument\s+['"]?--verbose\b/i.test(result.stderr || result.stdout || '')) {
+ verboseSupported = false;
+ result = run(command, { captureAll: true, timeoutMs: 60000 });
+ }
+ const rawOutput = result.stdout || result.stderr || '';
+ let tracker = { status: 'Unknown', currentStep: null };
+ let error = null;
+ try {
+ tracker = parseTracker(rawOutput);
+ if (tracker.status === 'Unknown') {
+ error = 'PAC reported an Unknown migration status; review the saved tracker response before continuing.';
+ }
+ } catch (parseError) {
+ error = parseError.message;
+ }
+ if (result.status !== 0 || result.error) error = commandError('Checking migration status', result);
+ return { ...tracker, verboseSupported, rawOutput, error, capturedAt: new Date().toISOString() };
+}
+
+function saveDiagnostic(outputDir, name, record) {
+ fs.mkdirSync(outputDir, { recursive: true });
+ fs.writeFileSync(path.join(outputDir, `${name}.json`), JSON.stringify(record, null, 2) + '\n', 'utf8');
+ return record;
+}
+
+function customizationFiles(directories) {
+ const files = new Map();
+ for (const directory of new Set(directories.map((entry) => path.resolve(entry)))) {
+ if (!fs.existsSync(directory)) continue;
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
+ if (!entry.isFile() || !/^SiteCustomization.*\.csv$/i.test(entry.name)) continue;
+ const filename = path.join(directory, entry.name);
+ const content = fs.readFileSync(filename, 'utf8');
+ const stat = fs.statSync(filename);
+ files.set(filename, {
+ content,
+ fingerprint: `${stat.mtimeMs}:${stat.ctimeMs}:${createHash('sha256').update(content).digest('hex')}`,
+ });
+ }
+ }
+ return files;
+}
+
+function generateCustomizationReport({ websiteId, outputDir }, deps = {}) {
+ validateTarget(websiteId, outputDir);
+ const directories = [outputDir, path.dirname(path.resolve(outputDir)), deps.cwd || process.cwd()];
+ const previousFiles = customizationFiles(directories);
+ const before = checkMigrationStatus(websiteId, deps);
+ const ready = before.status === 'Completed' ||
+ (before.status === 'Running' && before.currentStep?.toLowerCase() === 'configurationdatacompleted');
+ if (before.error || !before.currentStep || !ready) {
+ return saveDiagnostic(outputDir, 'customization-report-attempt', {
+ outcome: 'CheckFailed', before,
+ error: before.error || 'Verify the tracker and completed migration milestone before generating a report.',
+ });
+ }
+ // A report request may update tracker metadata even though it does not migrate
+ // site data. Preserve both snapshots, separate from migration-status.json.
+ // https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model
+ saveDiagnostic(outputDir, 'customization-report-attempt', { outcome: 'Generating', before });
+ const command = (deps.runPac || runPac)([
+ 'pages', 'migrate-datamodel', '--webSiteId', websiteId, '--siteCustomizationReportPath', outputDir,
+ ], { captureAll: true, ...(deps.cwd ? { cwd: deps.cwd } : {}) });
+ const after = checkMigrationStatus(websiteId, deps, before.verboseSupported);
+ const trackerChanged = before.status !== after.status || before.currentStep !== after.currentStep;
+ const csvPaths = [];
+ const invalidCsvPaths = [];
+ for (const [filename, file] of customizationFiles(directories)) {
+ if (previousFiles.get(filename)?.fingerprint === file.fingerprint) continue;
+ let rows;
+ try {
+ rows = parseCSV(file.content.replace(/^\uFEFF/, ''), { strict: true });
+ } catch (error) {
+ if (!(error instanceof SyntaxError)) throw error;
+ invalidCsvPaths.push(filename);
+ continue;
+ }
+ const required = ['Type of customization', 'Guidance', 'Snippet', 'Location'];
+ const headers = rows[0] || [];
+ if (required.every((header) => headers.includes(header)) &&
+ rows.slice(1).every((row) => row.length === headers.length)) csvPaths.push(filename);
+ else invalidCsvPaths.push(filename);
+ }
+ let outcome = 'ReportGenerated';
+ let error = null;
+ if (command.status !== 0 || command.error) {
+ outcome = 'CommandFailed';
+ error = commandError('Generating customization report', command);
+ } else if (after.error || !after.currentStep) {
+ outcome = 'CheckFailed';
+ error = after.error || 'Report generated without a verifiable current migration step.';
+ } else if (trackerChanged) {
+ outcome = 'TrackerChanged';
+ error = 'Report request changed the migration status/current step; review both snapshots before continuing.';
+ } else if (invalidCsvPaths.length || csvPaths.length === 0) {
+ outcome = 'ReportMissingOrInvalid';
+ error = 'PAC did not produce a new or updated valid customization CSV; exit code 0 is not report-generation success.';
+ } else if (csvPaths.length > 1) {
+ outcome = 'ReportSelectionRequired';
+ error = 'Multiple customization CSVs changed; verify the selected site and report provenance before choosing one.';
+ }
+ return saveDiagnostic(outputDir, 'customization-report-attempt', {
+ outcome, error, before, command, after, trackerChanged, csvPaths, invalidCsvPaths,
+ });
+}
+
+function startReferences({ websiteId, outputDir }, deps = {}) {
+ validateTarget(websiteId, outputDir);
+ fs.mkdirSync(outputDir, { recursive: true });
+ const command = (deps.runPac || runPac)([
+ 'pages', 'migrate-datamodel', '--webSiteId', websiteId, '--mode', 'configurationDataReferences',
+ ], { captureAll: true });
+ const failed = command.status !== 0 || Boolean(command.error);
+ // Observed refusal: "The website is already under migration." Check this
+ // even on exit 0; a refused command must not enter the normal polling loop.
+ const refused = /\b(?:web\s*site|site)\b[^\r\n]*\balready\s+under\s+migration\b/i
+ .test(`${command.stdout || ''}\n${command.stderr || ''}`);
+ const tracker = checkMigrationStatus(websiteId, deps);
+ return saveDiagnostic(outputDir, 'references-start', {
+ outcome: refused ? 'StartRefused' : failed ? 'StartFailed' : tracker.error ? 'CheckFailed' : 'StartAccepted',
+ error: failed || refused ? commandError('Starting references migration', command) : tracker.error,
+ command, tracker,
+ });
+}
+
+async function pollMigration({ websiteId, mode, outputDir }, deps = {}) {
+ validateTarget(websiteId, outputDir);
+ if (!MODES.has(mode)) throw new Error('--mode must be configurationData, all, or configurationDataReferences');
+ const maxAttempts = 30;
+ const intervalMs = 60000;
+ const sleep = deps.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
+ const emit = deps.emit || ((record) => console.log(JSON.stringify(record)));
+ const isReferences = mode === 'configurationDataReferences';
+ fs.mkdirSync(outputDir, { recursive: true });
+
+ let finalRecord;
+ let verboseSupported = true;
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ const operation = {
+ label: isReferences ? 'Migrating transactional references' : 'Migrating configuration metadata to EDM',
+ detail: `mode=${mode}`,
+ poll: { attempt, max: maxAttempts },
+ };
+ const check = checkMigrationStatus(websiteId, deps, verboseSupported);
+ verboseSupported = check.verboseSupported;
+ const { rawOutput, status, currentStep } = check;
+ const tracker = { status, currentStep };
+ fs.writeFileSync(path.join(outputDir, 'migration-status.txt'), rawOutput, 'utf8');
+ let error = check.error;
+ if (!error && mode === 'configurationData' && tracker.status === 'Running' && !tracker.currentStep) {
+ error = 'Metadata-only polling requires Current Step; verify the tracker directly in Dataverse before continuing or resetting.';
+ }
+
+ let outcome = 'Running';
+ if (error) outcome = 'CheckFailed';
+ else if (['Failed', 'Reverted'].includes(tracker.status)) outcome = tracker.status;
+ else if (mode === 'configurationData' && (tracker.status === 'Completed' ||
+ tracker.currentStep?.toLowerCase() === 'configurationdatacompleted')) {
+ outcome = 'ConfigurationDataCompleted';
+ } else if (mode !== 'configurationData' && tracker.status === 'Completed') outcome = 'Completed';
+ else if (attempt === maxAttempts) outcome = 'TimedOut';
+
+ finalRecord = {
+ attempt, maxAttempts, mode, verboseSupported, ...tracker, outcome, error, operation,
+ capturedAt: new Date().toISOString(),
+ // Full verbose output is retained for the agent's existing step-history
+ // and chunk interpretation. Do not truncate it to a process log tail.
+ rawOutput,
+ };
+ fs.writeFileSync(path.join(outputDir, 'migration-status.json'), JSON.stringify(finalRecord, null, 2) + '\n', 'utf8');
+ emit(finalRecord);
+ if (outcome !== 'Running') break;
+ await sleep(intervalMs);
+ }
+ return finalRecord;
+}
+
+function parseArgs(argv) {
+ const [action, ...rest] = argv;
+ const allowed = {
+ discover: new Set(['path', 'require-site']),
+ solutions: new Set(['output']),
+ poll: new Set(['website-id', 'mode', 'output-dir']),
+ report: new Set(['website-id', 'output-dir']),
+ 'start-references': new Set(['website-id', 'output-dir']),
+ delay: new Set(['seconds']),
+ }[action];
+ if (!allowed) throw new Error('Usage: migration-runtime.js discover|solutions|poll|report|start-references|delay [options]');
+ const args = { action };
+ for (let index = 0; index < rest.length; index++) {
+ const option = rest[index].replace(/^--/, '');
+ if (!rest[index].startsWith('--') || !allowed.has(option)) throw new Error(`Unknown argument: ${rest[index]}`);
+ if (option === 'require-site') args[option] = true;
+ else {
+ const value = rest[++index];
+ if (!value || value.startsWith('--')) throw new Error(`--${option} requires a value`);
+ args[option] = value;
+ }
+ }
+ return args;
+}
+
+async function main(argv) {
+ const args = parseArgs(argv);
+ if (args.action === 'discover') {
+ console.log(JSON.stringify(discoverSite(args.path, args['require-site']), null, 2));
+ } else if (args.action === 'solutions') {
+ if (!args.output) throw new Error('--output is required');
+ console.log(JSON.stringify(captureSolutions(args.output)));
+ } else if (args.action === 'report' || args.action === 'start-references') {
+ const action = args.action === 'report' ? generateCustomizationReport : startReferences;
+ const result = action({ websiteId: args['website-id'], outputDir: args['output-dir'] });
+ console.log(JSON.stringify(result));
+ process.exitCode = ['ReportGenerated', 'StartAccepted'].includes(result.outcome) ? 0 : 1;
+ } else if (args.action === 'delay') {
+ const seconds = Number(args.seconds);
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > 60) throw new Error('--seconds must be an integer from 1 to 60');
+ await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
+ } else {
+ const result = await pollMigration({ websiteId: args['website-id'], mode: args.mode, outputDir: args['output-dir'] });
+ process.exitCode = ['Completed', 'ConfigurationDataCompleted'].includes(result.outcome)
+ ? 0 : result.outcome === 'TimedOut' ? 2 : 1;
+ }
+}
+
+if (require.main === module) {
+ main(process.argv.slice(2)).catch((error) => {
+ console.error(`Error: ${error.message}`);
+ process.exitCode = 1;
+ });
+}
+
+module.exports = {
+ discoverSite, captureSolutions, parseTracker, pollMigration, parseArgs,
+ generateCustomizationReport, startReferences,
+};
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/prompts/dme-remediation.template.txt b/plugins/power-pages/skills/migrate-datamodel/scripts/prompts/dme-remediation.template.txt
new file mode 100644
index 000000000..fbe134770
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/prompts/dme-remediation.template.txt
@@ -0,0 +1,217 @@
+You are an expert in Power Platform solution packaging. The user has a Power
+Pages site being migrated from SDM to EDM. A customization scan identified
+custom columns on `adx_*` metadata tables that need to be moved into new
+custom tables (per Microsoft's migration guidance — `adx_*` tables become
+`powerpagecomponent` in EDM, so custom columns can't stay where they are).
+
+The correct fix is to deliver a Dataverse solution package containing:
+- One new custom table per affected `adx_*` table
+- Each custom column moved to the corresponding new table
+- A lookup column on each new table pointing to `powerpagecomponent` (so each
+ new-table row is associated with its EDM component)
+
+The user will import this solution into their environment and run a separate
+data-migration step (covered at the end of this prompt).
+
+## Metadata prerequisite and execution order
+
+Solution schema preparation and packing can happen before metadata migration.
+Data copy cannot: before any extension-row writes, confirm the approved metadata
+migration has completed for this site and environment, or that the downstream
+metadata solution import has completed. The outer migration skill normally
+performs that metadata step before generating this handoff; verify it rather
+than assuming a standalone invocation has done so.
+
+Run a separate read-only preflight across ALL source rows to verify their target
+`powerpagecomponent` rows and expected component types. Build an explicit
+source-ID to component-ID mapping (`verifiedComponentIds` in the C# skeleton).
+Migration normally preserves the source GUID, but a GUID alone is not evidence
+that a matching component exists in the intended environment.
+If metadata or any mapping is missing, STOP and return to the migration
+conversation. Do not copy data, activate EDM, or start another PAC migration
+from this prompt. Resume data copy only after the prerequisite is verified.
+
+## Findings (per-table groupings from the customization report)
+
+{{DME_TABLE_GROUPS_BLOCK}}
+
+## Your task
+
+1. **Ask the user for their publisher prefix** (e.g., `contoso`, `acme`).
+ This prefix is applied to all new table and column names. If they have an
+ existing publisher in Dataverse, use it; otherwise help them pick one.
+
+2. **Ask the user for the solution unique name** (e.g.,
+ `<prefix>_PowerPagesEdmMigration`). This is the solution package name.
+
+3. **Confirm the plan** with the user BEFORE building anything. Show the
+ list of new tables and the columns/lookups each contains. Wait for
+ approval.
+
+4. **Initialize a new solution project:**
+
+ pac solution init --publisher-name "<Publisher Display Name>" `
+ --publisher-prefix "<prefix>" `
+ --outputDirectory "./edm-migration-solution"
+
+5. **For each grouping in the findings, create:**
+
+ a. **A new custom table.** Naming: `<prefix>_<original-suffix>` (e.g.,
+ `adx_webpage` → `contoso_webpage`). Conventions:
+ - Display name: title-cased original suffix (e.g., "Webpage")
+ - Primary name column: `<prefix>_name`, string, MaxLength 100
+
+ b. **Each custom column from the finding** added to the new table.
+ Use the SAME column logical name as the original (just on the new
+ table — `contoso_redirecturl` stays `contoso_redirecturl`, not
+ renamed).
+
+ For column data types, infer from the column logical name (heuristic
+ only — confirm with user when ambiguous):
+ - Ends in `name`, contains `text|description|title|code|url|mimetype`:
+ String, MaxLength 100
+ - Starts with `is`, `has`, contains `enabled|compressed`: TwoOption
+ - Contains `count|number` (and not an id): Integer
+ - Ends in `id` and refers to a Dataverse entity: Lookup (ask user for
+ the target entity)
+ - Contains `date|time`: DateTime
+ - Ambiguous: ASK the user
+
+ c. **A lookup column** on the new table pointing to `powerpagecomponent`:
+ - Logical name: `<prefix>_powerpagecomponentid`
+ - Display name: "Power Pages Component"
+ - Required: Yes (each row belongs to exactly one component)
+ - On-delete behavior: ASK the user (Cascade cleans up extension rows
+ when the component is deleted; Remove Link sets to null and leaves
+ orphan rows. Default suggestion: Cascade for tighter coupling.)
+
+6. **Show the user the solution structure** before packing. Show the
+ directory tree and the entity XML for at least one new table.
+
+7. **Pack the solution:**
+
+ pac solution pack --zipfile "./edm-migration-solution.zip" `
+ --folder "./edm-migration-solution" `
+ --packagetype Unmanaged
+
+ Default to Unmanaged so the user can inspect/modify after import. If the
+ user plans to deploy to a production environment, ASK whether they want
+ Managed instead (cleaner uninstall, prevents post-import editing).
+
+8. **Document the import + data migration steps** (print, do NOT run):
+
+ a. Import the solution:
+
+ pac solution import --path "./edm-migration-solution.zip"
+
+ b. **Post-metadata-migration data copy:** after solution import AND the
+ metadata prerequisite and complete read-only mapping preflight above,
+ migrate row data from the old `adx_*` tables into the new custom tables.
+ For each finding:
+ - Read rows from the source `adx_*` table
+ - For each row, find the corresponding `powerpagecomponent` row
+ (joined by primary key — `powerpagecomponent` rows preserve the
+ original adx_* row ID in EDM)
+ - Create a row in the new custom table with:
+ - The lookup column set to the matching `powerpagecomponent`
+ - The custom column values copied verbatim
+
+ Provide TWO sample data-migration approaches:
+
+ **Approach 1 — Power Automate flow (low volumes, < 1000 rows):**
+
+ Skeleton:
+ Trigger: Manual / Recurrence
+ Step 1: List rows from <adx_source_table> via Dataverse connector
+ Step 2: Resolve the component ID using the verified mapping; stop if absent.
+ Step 3: For each row → Create a new row in <new_custom_table> with
+ <prefix>_powerpagecomponentid = verified component ID and
+ <custom_columns> copied verbatim
+
+ **Approach 2 — C# console app (higher volumes, batched):**
+
+ Skeleton (supply `verifiedComponentIds` from the complete read-only
+ preflight before running this write phase):
+
+ using Microsoft.Xrm.Sdk;
+ using Microsoft.Xrm.Sdk.Messages;
+ using Microsoft.Xrm.Sdk.Query;
+ // ... auth setup omitted ...
+
+ var sourceQuery = new QueryExpression("adx_<source>") {
+ ColumnSet = new ColumnSet("<custom_column1>", "<custom_column2>", "<source>id"),
+ PageInfo = new PagingInfo { Count = 5000, PageNumber = 1 }
+ };
+ sourceQuery.AddOrder("<source>id", OrderType.Ascending);
+
+ var batch = new ExecuteMultipleRequest {
+ Requests = new OrganizationRequestCollection(),
+ Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = false }
+ };
+
+ while (true) {
+ var sourceRows = service.RetrieveMultiple(sourceQuery);
+ foreach (var src in sourceRows.Entities) {
+ if (!verifiedComponentIds.TryGetValue(src.Id, out var componentId)) {
+ throw new InvalidOperationException("Missing verified component mapping; stop and return to the migration conversation.");
+ }
+ var newRow = new Entity("<prefix>_<target>");
+ newRow["<prefix>_powerpagecomponentid"] = new EntityReference(
+ "powerpagecomponent", componentId);
+ newRow["<custom_column1>"] = src.GetAttributeValue<object>("<custom_column1>");
+ // ... copy remaining custom columns ...
+ batch.Requests.Add(new CreateRequest { Target = newRow });
+
+ if (batch.Requests.Count == 1000) {
+ var response = (ExecuteMultipleResponse)service.Execute(batch);
+ if (response.IsFaulted) throw new InvalidOperationException("Data migration batch failed; inspect response.Responses before resuming.");
+ batch.Requests.Clear();
+ }
+ }
+ if (!sourceRows.MoreRecords) break;
+ sourceQuery.PageInfo.PageNumber++;
+ sourceQuery.PageInfo.PagingCookie = sourceRows.PagingCookie;
+ }
+ if (batch.Requests.Count > 0) {
+ var response = (ExecuteMultipleResponse)service.Execute(batch);
+ if (response.IsFaulted) throw new InvalidOperationException("Data migration batch failed; inspect response.Responses before resuming.");
+ }
+
+ Adapt the placeholders to the user's actual table/column names.
+ Retrieve every page before declaring completion. Review batch faults and
+ reconcile already-created rows before retrying; this create-only skeleton
+ is not safe to rerun blindly.
+ Paging reference: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/org-service/queryexpression/page-results
+
+ c. After data migration, the user must:
+ - Update any Liquid/FetchXML references to the old adx_* custom
+ columns to instead query the new custom table via its lookup.
+ (The SDM-to-EDM skill's FetchXML rewriter handles entity-level
+ changes; custom-column references need this manual update.)
+ - Reconcile source and target row counts, mappings, custom values and
+ consumer changes, then return the results to the migration conversation.
+ Continue only through its existing reference-migration, validation and
+ activation approval gates; do not rerun metadata migration after data copy.
+
+## References
+
+- SDM to EDM migration: https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model
+- pac solution commands: https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/solution
+- Solution / ALM concepts: https://learn.microsoft.com/en-us/power-platform/alm/solution-concepts-alm
+- Power Pages component types (for understanding the EDM model):
+ https://learn.microsoft.com/en-us/power-pages/configure/enhanced-data-model
+
+## Constraints
+
+- DO NOT make any direct Dataverse API calls. Generate the solution package
+ only — the user imports it themselves
+- ALL schema decisions (table names, column types, display names, on-delete
+ behavior) must be reviewed by the user before pack
+- Default to Unmanaged solutions for iteration; offer Managed for production
+- DO NOT pack until the user has approved the structure
+- If the user already has a publisher in their Dataverse environment, prefer
+ using it rather than creating a new one — ask first
+- Generate the solution as a separate directory (`./edm-migration-solution/`)
+ so it doesn't pollute cwd
+- The data-migration step is OUTSIDE the solution import scope — the user
+ runs it separately. Do NOT include data migration in the solution package
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/prompts/plugin-remediation.template.txt b/plugins/power-pages/skills/migrate-datamodel/scripts/prompts/plugin-remediation.template.txt
new file mode 100644
index 000000000..9a21e43f5
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/prompts/plugin-remediation.template.txt
@@ -0,0 +1,99 @@
+You are an expert in Power Apps plugin development for Power Pages. The user has
+a Power Pages site being migrated from the Standard Data Model (SDM) to the
+Enhanced Data Model (EDM). A customization scan identified plugin registrations
+against `adx_*` entities. Only customer-owned plugins targeting the supported
+metadata tables below are candidates for a `powerpagecomponent` refactor.
+
+## Findings (verbatim from the customization report)
+
+{{PLUGIN_FINDINGS_BLOCK}}
+
+Plugins prefixed with `Microsoft.*` are platform plugins — no action needed.
+Plugins prefixed with `Adxstudio.*` are legacy framework plugins typically
+handled by the V2 EDM solution upgrade; verify the V2 solution is installed
+in the target environment. Custom plugins require target-specific review, not
+automatic refactoring based on the `adx_*` prefix.
+
+## Supported metadata targets only
+
+The following mapping is generated from the same supported metadata map used by
+the migration report generator:
+
+{{PLUGIN_METADATA_MAPPING_BLOCK}}
+
+Transactional/runtime tables such as `adx_invitation`, `adx_externalidentity`
+and `adx_portalcomment` retain their own schemas. For these, every target absent
+from the mapping, or an unknown registration target: keep the target, queries and
+registration unchanged, report manual review required, and verify the actual
+schema and consumers. Do not invent a component type or move them to
+`powerpagecomponent`. A different EDM target requires separately verified guidance.
+
+## Your task
+
+1. **Locate the plugin source.** Look in the current working directory for:
+ - A C# class library project (`*.csproj`) whose assembly name matches
+ the plugin assembly name from the findings, OR
+ - A `Plugins/`, `src/Plugins/`, or similar folder containing one
+ If not found, ASK the user where their plugin source repo lives. Do not
+ guess.
+
+2. **For each customer-owned finding whose target is explicitly in the mapping,
+ review the proposed plugin refactor. Route all other targets to manual review:**
+
+ a. Find the plugin class. Identify the entity reference. Common patterns:
+ - Set in constructor: `this.EntityName = "adx_webpage";`
+ - In a `[CrmPluginRegistration(...)]` attribute: target entity is one
+ of the parameters
+ - In a separate registration XML (`*.crmregister`, `RegisterFile.xml`):
+ `PrimaryEntityName="adx_webpage"`
+
+ b. For the verified mapped metadata target only, propose changing its target
+ entity name to `powerpagecomponent`. Do not broadly replace `adx_*` strings
+ or unrelated table references.
+
+ c. If the plugin queries the entity via `RetrieveMultiple` / FetchXML /
+ QueryExpression, add a filter on the `powerpagecomponenttype` attribute.
+ Use the exact source-table/component-type pair in the mapping above.
+ Apply this only to queries of the verified mapped table; leave queries
+ against transactional and unmapped tables unchanged for manual review.
+
+ d. Attribute references (`adx_name`, `adx_partialurl`, etc.) STAY AS-IS.
+ PAC's EDM `powerpagecomponent` table exposes the legacy adx_* names as
+ logical attribute names. You do NOT need to rename
+ `GetAttributeValue<T>("adx_name")` calls.
+
+ e. For the verified mapped target only, update plugin step registration metadata (`*.crmregister`,
+ `RegisterFile.xml`, or solution-embedded `SdkMessageProcessingStep`)
+ to reference `powerpagecomponent` for `PrimaryEntityName`.
+
+3. **Generate a diff for user review** BEFORE saving any changes. Show what
+ you're changing and why for each plugin.
+
+4. **Get explicit user approval** before writing changes to disk.
+
+5. **After changes are approved:**
+ - Build: `dotnet build` (or `msbuild` for old-style projects)
+ - Run existing tests: `dotnet test`
+ - Surface any build/test failures — do NOT proceed with broken code
+
+6. **Deployment guidance** (print, do not run):
+ - `pac plugin push --pluginAssemblyPath <build-output>/<Assembly>.dll`
+ - Or, if plugins are part of a solution: re-pack and re-import the solution
+
+## References
+
+- SDM to EDM migration: https://learn.microsoft.com/en-us/power-pages/admin/migrate-enhanced-data-model
+- Plugin development: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/plug-ins
+- pac plugin commands: https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/plugin
+
+## Constraints
+
+- DO NOT modify code without showing the user a diff first
+- DO NOT push to a deployed environment — only build locally
+- DO NOT guess at file locations — ask the user
+- DO NOT change attribute references like `GetAttributeValue<T>("adx_name")`
+- DO NOT move transactional, unmapped, or unknown targets to `powerpagecomponent`
+- If the source is in Git, suggest the user commit current state first so
+ they can revert easily
+- Leave `Microsoft.*` and `Adxstudio.*` plugins alone — they are not the
+ customer's code
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/snapshot-site.js b/plugins/power-pages/skills/migrate-datamodel/scripts/snapshot-site.js
new file mode 100644
index 000000000..9aa6ff743
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/snapshot-site.js
@@ -0,0 +1,536 @@
+#!/usr/bin/env node
+/**
+ * snapshot-site.js
+ *
+ * Walks a `pac pages download` site tree and builds a JSON snapshot of every
+ * artifact it knows about. Pre-migration (modelVersion 1) and post-migration
+ * (modelVersion 2) snapshots have the same shape, so they can be diffed by
+ * diff-snapshots.js.
+ *
+ * USAGE
+ * node snapshot-site.js --site-root <path> --output-dir <path> --label sdm|edm
+ *
+ * OUTPUT
+ * <output-dir>/<label>-snapshot.json
+ *
+ * Identity fields per artifact are deliberately narrow (name + language +
+ * statecode) so the diff is robust against harmless YAML reordering and
+ * whitespace differences. Pass --with-content-hash to also include SHA-256 of
+ * the companion content file (webpage copy HTML, snippet value HTML, web
+ * template source, …) when one exists — stricter but can false-positive on
+ * encoding/line-ending shifts.
+ */
+
+const fs = require('fs');
+const path = require('path');
+const crypto = require('crypto');
+const { parseSimpleYaml } = require('../../../scripts/lib/powerpages-config');
+const { parseTopLevelSequence } = require('../../../scripts/lib/non-spa-metadata');
+const { requirePowerPagesSiteRoot } = require('../../../scripts/lib/validation-helpers');
+
+function parseArgs(argv) {
+ const out = {};
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a.startsWith('--')) {
+ const k = a.slice(2);
+ const next = argv[i + 1];
+ if (next === undefined || next.startsWith('--')) {
+ out[k] = true;
+ } else {
+ out[k] = next;
+ i += 1;
+ }
+ }
+ }
+ return out;
+}
+
+function safeReaddir(p) {
+ try {
+ return fs.readdirSync(p, { withFileTypes: true });
+ } catch (e) {
+ if (e.code === 'ENOENT') return [];
+ throw new Error(`Could not read snapshot directory ${p}: ${e.message}`);
+ }
+}
+
+function findFilesBySuffix(dir, suffix, recursive = false) {
+ return safeReaddir(dir)
+ .flatMap((e) => {
+ const file = path.join(dir, e.name);
+ if (recursive && e.isDirectory()) return findFilesBySuffix(file, suffix, true);
+ return e.isFile() && e.name.endsWith(suffix) ? [file] : [];
+ });
+}
+
+// Aggregate PAC records use "adx_statecode: 1"; per-record exports can use
+// "statecode: 1" (and "name" instead of "adx_name"). Keep explicit zero/false.
+function recordField(record, key) {
+ const alternate = key.startsWith('adx_') ? key.slice(4) : `adx_${key}`;
+ const value = record[key] ?? record[alternate] ?? null;
+ return Array.isArray(value) ? value.slice().sort() : value;
+}
+
+function stateCode(record) {
+ const value = recordField(record, 'statecode');
+ return typeof value === 'number' ? value : null;
+}
+
+function mergeScans(...scans) {
+ const inventory = scans.flatMap((scan) => scan.inventory);
+ return { count: inventory.length, inventory, parseErrors: scans.flatMap((scan) => scan.parseErrors) };
+}
+
+function safeParseYaml(filePath, errors) {
+ try {
+ return parseSimpleYaml(fs.readFileSync(filePath, 'utf8'), filePath);
+ } catch (e) {
+ errors.push({ filePath, message: e.message });
+ return null;
+ }
+}
+
+function sha256OfFileIfExists(p) {
+ if (!p) return null;
+ try {
+ return crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex').slice(0, 16);
+ } catch (error) {
+ if (error.code === 'ENOENT') return null;
+ throw new Error(`Could not hash snapshot content ${p}: ${error.message}`);
+ }
+}
+
+// Extract a language tag from a filename like "About-Footer.en-US.contentsnippet.yml".
+// Returns null if the segment doesn't match a BCP-47-ish pattern.
+function extractLanguageTag(filename, suffix) {
+ const base = filename.slice(0, -suffix.length);
+ const segments = base.split('.');
+ if (segments.length < 2) return null;
+ const last = segments[segments.length - 1];
+ return /^[a-z]{2,3}(-[A-Z]{2,4})?$/i.test(last) ? last : null;
+}
+
+// Reuse strict aggregate parsing so malformed fields cannot silently disappear
+// from a migration baseline. It also handles quoted and multiline YAML scalars.
+function parseCollectionFile(filePath, errors) {
+ try {
+ // Read directly: existsSync can report false for inaccessible files too,
+ // but only ENOENT is an optional missing collection, not incomplete evidence.
+ return parseTopLevelSequence(fs.readFileSync(filePath, 'utf8'), filePath);
+ } catch (e) {
+ if (e.code === 'ENOENT') return [];
+ errors.push({ filePath, message: e.message });
+ return [];
+ }
+}
+
+// ── Per-artifact scanners ──────────────────────────────────────────────────
+
+function scanWebPages(siteRoot, withContentHash) {
+ const errors = [];
+ const inventory = [];
+ const root = path.join(siteRoot, 'web-pages');
+
+ for (const slug of safeReaddir(root)) {
+ if (!slug.isDirectory()) continue;
+ const slugDir = path.join(root, slug.name);
+
+ // Parent page: <Name>.webpage.yml at <slug>/ (not in content-pages/)
+ for (const f of findFilesBySuffix(slugDir, '.webpage.yml')) {
+ const rec = safeParseYaml(f, errors);
+ if (!rec) continue;
+ inventory.push({
+ kind: 'parent',
+ slug: slug.name,
+ name: recordField(rec, 'adx_name'),
+ partialUrl: recordField(rec, 'adx_partialurl'),
+ isRoot: [true, 'true'].includes(recordField(rec, 'adx_isroot')),
+ stateCode: stateCode(rec),
+ contentHash: withContentHash ? sha256OfFileIfExists(f.replace('.webpage.yml', '.webpage.copy.html')) : undefined,
+ });
+ }
+
+ // PAC layouts include content-pages/<Name>.<lang>.webpage.yml and
+ // content-pages/<locale>/<Name>.<lang>.webpage.yml.
+ const contentPagesDir = path.join(slugDir, 'content-pages');
+ for (const f of findFilesBySuffix(contentPagesDir, '.webpage.yml', true)) {
+ const rec = safeParseYaml(f, errors);
+ if (!rec) continue;
+ inventory.push({
+ kind: 'content',
+ slug: slug.name,
+ name: recordField(rec, 'adx_name'),
+ partialUrl: recordField(rec, 'adx_partialurl'),
+ language: extractLanguageTag(path.basename(f), '.webpage.yml'),
+ stateCode: stateCode(rec),
+ contentHash: withContentHash ? sha256OfFileIfExists(f.replace('.webpage.yml', '.webpage.copy.html')) : undefined,
+ });
+ }
+ }
+ return { count: inventory.length, inventory, parseErrors: errors };
+}
+
+function scanContentSnippets(siteRoot, withContentHash) {
+ const errors = [];
+ const inventory = [];
+ const root = path.join(siteRoot, 'content-snippets');
+ for (const slug of safeReaddir(root)) {
+ if (!slug.isDirectory()) continue;
+ const dir = path.join(root, slug.name);
+ for (const f of findFilesBySuffix(dir, '.contentsnippet.yml')) {
+ const rec = safeParseYaml(f, errors);
+ if (!rec) continue;
+ inventory.push({
+ slug: slug.name,
+ name: recordField(rec, 'adx_name'),
+ displayName: recordField(rec, 'adx_display_name'),
+ language: extractLanguageTag(path.basename(f), '.contentsnippet.yml'),
+ stateCode: stateCode(rec),
+ contentHash: withContentHash ? sha256OfFileIfExists(f.replace('.contentsnippet.yml', '.contentsnippet.value.html')) : undefined,
+ });
+ }
+ }
+ return { count: inventory.length, inventory, parseErrors: errors };
+}
+
+function scanWebLinkSets(siteRoot, folder) {
+ const errors = [];
+ const inventory = [];
+ const root = path.join(siteRoot, folder);
+ for (const slug of safeReaddir(root)) {
+ if (!slug.isDirectory()) continue;
+ const dir = path.join(root, slug.name);
+ for (const f of findFilesBySuffix(dir, '.weblinkset.yml')) {
+ // Skip the sibling weblink-collection file (ends with .weblinkset.weblink.yml)
+ if (f.endsWith('.weblinkset.weblink.yml')) continue;
+ const rec = safeParseYaml(f, errors);
+ if (!rec) continue;
+ const language = extractLanguageTag(path.basename(f), '.weblinkset.yml');
+
+ // Read sibling weblinks file (collection format)
+ const linksFile = f.replace('.weblinkset.yml', '.weblinkset.weblink.yml');
+ const linkRecs = parseCollectionFile(linksFile, errors);
+ const links = linkRecs
+ .map((r) => ({
+ name: recordField(r, 'adx_name'),
+ displayOrder: recordField(r, 'adx_displayorder'),
+ pageId: recordField(r, 'adx_pageid'),
+ externalUrl: recordField(r, 'adx_externalurl'),
+ stateCode: stateCode(r),
+ }))
+ .sort((a, b) => (a.displayOrder ?? 999) - (b.displayOrder ?? 999) || String(a.name).localeCompare(String(b.name)));
+
+ inventory.push({
+ slug: slug.name,
+ name: recordField(rec, 'adx_name'),
+ language,
+ stateCode: stateCode(rec),
+ linkCount: links.filter((link) => (link.stateCode ?? 0) === 0).length,
+ linkNames: links.filter((link) => (link.stateCode ?? 0) === 0).map((l) => l.name),
+ links,
+ });
+ }
+ }
+ return { count: inventory.length, inventory, parseErrors: errors };
+}
+
+// Derive a flat per-link inventory from the per-set link data captured by
+// scanWebLinkSets. Each record represents a single navigation link with its
+// parent set's slug for context.
+function deriveWebLinks(linkSetsResult) {
+ const inventory = [];
+ for (const set of linkSetsResult.inventory || []) {
+ for (const link of set.links || []) {
+ inventory.push({
+ ...link,
+ slug: set.slug,
+ parentSet: set.name,
+ language: set.language,
+ });
+ }
+ }
+ return { count: inventory.length, inventory, parseErrors: [] };
+}
+
+function scanWebTemplates(siteRoot, withContentHash) {
+ const errors = [];
+ const inventory = [];
+ const root = path.join(siteRoot, 'web-templates');
+ for (const slug of safeReaddir(root)) {
+ if (!slug.isDirectory()) continue;
+ const dir = path.join(root, slug.name);
+ for (const f of findFilesBySuffix(dir, '.webtemplate.yml')) {
+ const rec = safeParseYaml(f, errors);
+ if (!rec) continue;
+ inventory.push({
+ slug: slug.name,
+ name: recordField(rec, 'adx_name'),
+ stateCode: stateCode(rec),
+ contentHash: withContentHash ? sha256OfFileIfExists(f.replace('.webtemplate.yml', '.webtemplate.source.html')) : undefined,
+ });
+ }
+ }
+ return { count: inventory.length, inventory, parseErrors: errors };
+}
+
+// Flat folder: <root>/<Name>.<artifactKind>.yml (no per-name subfolder)
+function scanFlatFolder(siteRoot, folder, suffix, identity) {
+ const errors = [];
+ const inventory = [];
+ const dir = path.join(siteRoot, folder);
+ for (const f of findFilesBySuffix(dir, suffix)) {
+ const rec = safeParseYaml(f, errors);
+ if (!rec) continue;
+ const item = {};
+ for (const [outKey, ymlKey] of Object.entries(identity)) {
+ item[outKey] = recordField(rec, ymlKey);
+ }
+ item.stateCode = stateCode(rec);
+ inventory.push(item);
+ }
+ return { count: inventory.length, inventory, parseErrors: errors };
+}
+
+// Per-slug subfolder: <root>/<slug>/<slug>.<artifactKind>.yml
+function scanPerSlugFolder(siteRoot, folder, suffix, identity) {
+ const errors = [];
+ const inventory = [];
+ const root = path.join(siteRoot, folder);
+ for (const slug of safeReaddir(root)) {
+ if (!slug.isDirectory()) continue;
+ const dir = path.join(root, slug.name);
+ for (const f of findFilesBySuffix(dir, suffix)) {
+ const rec = safeParseYaml(f, errors);
+ if (!rec) continue;
+ const item = { slug: slug.name };
+ for (const [outKey, ymlKey] of Object.entries(identity)) {
+ item[outKey] = recordField(rec, ymlKey);
+ }
+ item.stateCode = stateCode(rec);
+ inventory.push(item);
+ }
+ }
+ return { count: inventory.length, inventory, parseErrors: errors };
+}
+
+// Top-level collection file (an array of records). PAC names: sitesetting.yml,
+// webrole.yml, sitemarker.yml, websiteaccess.yml, publishingstate.yml, etc.
+function scanTopLevelCollection(siteRoot, file, identity) {
+ const errors = [];
+ const inventory = [];
+ const full = path.join(siteRoot, file);
+ for (const rec of parseCollectionFile(full, errors)) {
+ const item = {};
+ for (const [outKey, ymlKey] of Object.entries(identity)) {
+ item[outKey] = recordField(rec, ymlKey);
+ }
+ item.stateCode = stateCode(rec);
+ inventory.push(item);
+ }
+ return { count: inventory.length, inventory, parseErrors: errors };
+}
+
+function scanAdvancedFormSteps(siteRoot, forms) {
+ const errors = [];
+ const inventory = [];
+ for (const form of forms.inventory) {
+ const root = path.join(siteRoot, 'advanced-forms', form.slug, 'advanced-form-steps');
+ for (const file of findFilesBySuffix(root, '.advancedformstep.yml', true)) {
+ const rec = safeParseYaml(file, errors);
+ if (!rec) continue;
+ inventory.push({
+ name: recordField(rec, 'adx_name'),
+ parentForm: form.name,
+ formId: recordField(rec, 'adx_webform'),
+ type: recordField(rec, 'adx_type'),
+ targetEntity: recordField(rec, 'adx_targetentitylogicalname'),
+ nextStepId: recordField(rec, 'adx_nextstep'),
+ stateCode: stateCode(rec),
+ });
+ }
+ }
+ return { count: inventory.length, inventory, parseErrors: errors };
+}
+
+// ── Canonicalize inventory for stable diffs ────────────────────────────────
+
+function sortInventory(arr, ...keys) {
+ return arr.slice().sort((a, b) => {
+ for (const k of keys) {
+ const av = String(a[k] ?? '');
+ const bv = String(b[k] ?? '');
+ if (av < bv) return -1;
+ if (av > bv) return 1;
+ }
+ return 0;
+ });
+}
+
+// ── Main ───────────────────────────────────────────────────────────────────
+
+function main() {
+ const args = parseArgs(process.argv.slice(2));
+ let siteRoot = args['site-root'];
+ const outputDir = args['output-dir'];
+ const label = args['label'];
+ const withContentHash = !!args['with-content-hash'];
+
+ if (!siteRoot) { console.error('--site-root is required'); process.exit(1); }
+ if (!outputDir) { console.error('--output-dir is required'); process.exit(1); }
+ if (!label || !['sdm', 'edm'].includes(label)) {
+ console.error('--label must be "sdm" or "edm"'); process.exit(1);
+ }
+ siteRoot = requirePowerPagesSiteRoot(siteRoot);
+ const webLinkSets = mergeScans(
+ scanWebLinkSets(siteRoot, 'web-link-sets'),
+ scanWebLinkSets(siteRoot, 'weblink-sets'));
+ const siteSettings = mergeScans(
+ scanTopLevelCollection(siteRoot, 'sitesetting.yml', { name: 'adx_name', value: 'adx_value' }),
+ scanFlatFolder(siteRoot, 'site-settings', '.sitesetting.yml', { name: 'adx_name', value: 'adx_value' }));
+ const ruleFields = {
+ name: 'adx_name', pageId: 'adx_webpageid', right: 'adx_right', scope: 'adx_scope',
+ webRoleIds: 'adx_webpageaccesscontrolrule_webrole',
+ };
+ const webpageRules = mergeScans(
+ scanTopLevelCollection(siteRoot, 'webpagerule.yml', ruleFields),
+ scanFlatFolder(siteRoot, 'webpage-rules', '.webpagerule.yml', ruleFields));
+ const advancedForms = scanPerSlugFolder(siteRoot, 'advanced-forms', '.advancedform.yml',
+ { name: 'adx_name' });
+
+ const categories = {
+ webPages: scanWebPages(siteRoot, withContentHash),
+ contentSnippets: scanContentSnippets(siteRoot, withContentHash),
+ webLinkSets,
+ // webLinks is derived from the per-set link inventory captured by
+ // scanWebLinkSets above. It exposes each individual link as its own
+ // record so the Navigation group in the live report shows the actual
+ // navigation items, not just the menu containers.
+ webLinks: deriveWebLinks(webLinkSets),
+ webTemplates: scanWebTemplates(siteRoot, withContentHash),
+ webFiles: scanFlatFolder(siteRoot, 'web-files', '.webfile.yml',
+ { name: 'adx_name', partialUrl: 'adx_partialurl' }),
+ pageTemplates: scanFlatFolder(siteRoot, 'page-templates', '.pagetemplate.yml',
+ { name: 'adx_name' }),
+ tablePermissions: scanFlatFolder(siteRoot, 'table-permissions', '.tablepermission.yml',
+ { name: 'adx_entityname', permissionName: 'adx_name' }),
+ basicForms: scanPerSlugFolder(siteRoot, 'basic-forms', '.basicform.yml',
+ { name: 'adx_name' }),
+ advancedForms,
+ advancedFormSteps: scanAdvancedFormSteps(siteRoot, advancedForms),
+ lists: mergeScans(
+ scanFlatFolder(siteRoot, 'lists', '.list.yml', { name: 'adx_name' }),
+ scanPerSlugFolder(siteRoot, 'lists', '.entitylist.yml', { name: 'adx_name' })),
+ polls: scanPerSlugFolder(siteRoot, 'polls', '.poll.yml',
+ { name: 'adx_name' }),
+ pollPlacements: scanPerSlugFolder(siteRoot, 'poll-placements', '.pollplacement.yml',
+ { name: 'adx_name' }),
+ cloudFlowConsumers: mergeScans(
+ scanFlatFolder(siteRoot, 'cloud-flow-consumer', '.cloudflowconsumer.yml', { name: 'adx_name' }),
+ scanPerSlugFolder(siteRoot, 'cloud-flow-consumer', '.cloudflowconsumer.yml', { name: 'adx_name' })),
+ columnPermissionProfiles: scanPerSlugFolder(siteRoot, 'column-permission-profiles', '.columnpermissionprofile.yml',
+ { name: 'adx_name' }),
+ siteSettings,
+ webRoles: mergeScans(
+ scanTopLevelCollection(siteRoot, 'webrole.yml', { name: 'adx_name' }),
+ scanFlatFolder(siteRoot, 'web-roles', '.webrole.yml', { name: 'adx_name' })),
+ siteMarkers: scanTopLevelCollection(siteRoot, 'sitemarker.yml',
+ { name: 'adx_name' }),
+ websiteAccesses: scanTopLevelCollection(siteRoot, 'websiteaccess.yml',
+ { name: 'adx_name' }),
+ publishingStates: scanTopLevelCollection(siteRoot, 'publishingstate.yml',
+ { name: 'adx_name' }),
+ webpageRules,
+ websiteBindings: scanTopLevelCollection(siteRoot, 'websitebinding.yml',
+ { name: 'adx_name' }),
+ websiteLanguages: scanTopLevelCollection(siteRoot, 'websitelanguage.yml',
+ { name: 'adx_name' }),
+ ads: scanTopLevelCollection(siteRoot, 'ad.yml',
+ { name: 'adx_name' }),
+ adPlacements: scanTopLevelCollection(siteRoot, 'adplacement.yml',
+ { name: 'adx_name' }),
+ tags: scanTopLevelCollection(siteRoot, 'tag.yml',
+ { name: 'adx_name' }),
+ urlHistory: scanTopLevelCollection(siteRoot, 'urlhistory.yml',
+ { name: 'adx_url_logicalname' }),
+ };
+
+ // Canonical sort keys per category.
+ const sortKeys = {
+ webPages: ['kind', 'slug', 'partialUrl', 'language'],
+ contentSnippets: ['slug', 'language', 'name'],
+ webLinkSets: ['slug', 'language', 'name'],
+ webLinks: ['slug', 'language', 'name'],
+ webTemplates: ['slug', 'name'],
+ webFiles: ['name', 'partialUrl'],
+ pageTemplates: ['name'],
+ tablePermissions: ['name', 'permissionName'],
+ basicForms: ['slug', 'name'],
+ advancedForms: ['slug', 'name'],
+ advancedFormSteps: ['parentForm', 'name'],
+ lists: ['slug', 'name'],
+ polls: ['slug', 'name'],
+ pollPlacements: ['slug', 'name'],
+ cloudFlowConsumers: ['slug', 'name'],
+ columnPermissionProfiles: ['slug', 'name'],
+ siteSettings: ['name'],
+ webRoles: ['name'],
+ siteMarkers: ['name'],
+ websiteAccesses: ['name'],
+ publishingStates: ['name'],
+ webpageRules: ['name'],
+ websiteBindings: ['name'],
+ websiteLanguages: ['name'],
+ ads: ['name'],
+ adPlacements: ['name'],
+ tags: ['name'],
+ urlHistory: ['name'],
+ };
+ for (const [cat, keys] of Object.entries(sortKeys)) {
+ if (categories[cat]) {
+ categories[cat].inventory = sortInventory(categories[cat].inventory, ...keys);
+ }
+ }
+
+ const counts = {};
+ for (const [cat, data] of Object.entries(categories)) counts[cat] = data.count;
+
+ const snapshot = {
+ schemaVersion: 1,
+ label,
+ siteRoot: path.resolve(siteRoot),
+ capturedAt: new Date().toISOString(),
+ withContentHash,
+ counts,
+ inventory: Object.fromEntries(
+ Object.entries(categories).map(([cat, data]) => [cat, data.inventory]),
+ ),
+ parseErrors: Object.fromEntries(
+ Object.entries(categories)
+ .map(([cat, data]) => [cat, data.parseErrors])
+ .filter(([, errs]) => errs.length > 0),
+ ),
+ };
+
+ fs.mkdirSync(outputDir, { recursive: true });
+ const outPath = path.join(outputDir, `${label}-snapshot.json`);
+ fs.writeFileSync(outPath, JSON.stringify(snapshot, null, 2) + '\n', 'utf8');
+
+ console.log(`✓ Wrote ${outPath}`);
+ const totalErrors = Object.values(snapshot.parseErrors).reduce((n, errs) => n + errs.length, 0);
+ console.log('');
+ console.log(` Category Count`);
+ console.log(` ────────────────────────── ─────`);
+ for (const [cat, n] of Object.entries(counts)) {
+ if (n === 0) continue; // hide noisy zeros for sites that don't use every artifact
+ console.log(` ${cat.padEnd(26)} ${String(n).padStart(5)}`);
+ }
+ if (totalErrors > 0) {
+ console.log('');
+ console.log(` ⚠ ${totalErrors} YAML parse errors (see parseErrors in snapshot file)`);
+ }
+}
+
+if (require.main === module) main();
+
+module.exports = { safeReaddir };
diff --git a/plugins/power-pages/skills/migrate-datamodel/scripts/update-state.js b/plugins/power-pages/skills/migrate-datamodel/scripts/update-state.js
new file mode 100644
index 000000000..4ab2fad5c
--- /dev/null
+++ b/plugins/power-pages/skills/migrate-datamodel/scripts/update-state.js
@@ -0,0 +1,741 @@
+#!/usr/bin/env node
+/**
+ * update-state.js
+ *
+ * CLI for managing migration-state.json and re-rendering datamodel-migration-report.html.
+ * Every mutating command (a) loads migration-state.json, (b) applies the change,
+ * (c) bumps lastUpdatedAt, (d) writes migration-state.json back, and (e) re-renders the HTML report.
+ *
+ * USAGE
+ * # initialize a fresh state inside a per-migration subfolder
+ * # (writes migration-state.json + datamodel-migration-report.html into
+ * # <PARENT_DIR>/<sanitized-env>--<sanitized-slug>/)
+ * node update-state.js --init --output-dir <PARENT_DIR> \
+ * --website-id <GUID> --env-name "<NAME>" --slug "<SLUG>" --env-url "<ENV_URL>"
+ * # add --force to overwrite an existing migration in the same subfolder.
+ * # Without --force, --init re-uses the existing state (resume mode).
+ * # The command prints the resolved subfolder path on success \u2014 use that
+ * # subfolder as --output-dir for every subsequent command below.
+ *
+ * # update site card fields (any subset of name, portalId, slug, currentDataModel,
+ * # template, environment, migrationMode, siteRoot)
+ * node update-state.js --output-dir <DIR> --set-site '{"name":"Contoso","slug":"contoso"}'
+ *
+ * # mark a sub-step's status / output
+ * node update-state.js --output-dir <DIR> --set-step 1.1 --status completed \
+ * --output "PAC CLI v1.47.1 · environment Contoso"
+ *
+ * # mark a phase's status (in-progress / completed / blocked)
+ * node update-state.js --output-dir <DIR> --set-phase 1 --status completed
+ *
+ * # set / clear approval gate
+ * node update-state.js --output-dir <DIR> --set-approval 2 phase-start
+ * node update-state.js --output-dir <DIR> --set-approval 2 in-phase
+ * node update-state.js --output-dir <DIR> --clear-approval
+ *
+ * # notify the user of a non-phase-approval input or manual-action pause
+ * node update-state.js --output-dir <DIR> --set-input '{"requiredAction":"Restart the site, then confirm completion in chat."}'
+ * node update-state.js --output-dir <DIR> --clear-input
+ *
+ * # atomically clear an approval gate and mark a phase in-progress (use this
+ * # after the user answers an AskUserQuestion approval gate — avoids the
+ * # transient "Awaiting Approval" pill that would otherwise appear between
+ * # --clear-approval and --set-phase)
+ * node update-state.js --output-dir <DIR> --approve-and-start 2
+ *
+ * # set augmented-prompt card (kind: plugin | dme)
+ * node update-state.js --output-dir <DIR> --set-prompt plugin --status ready \
+ * --path "./migration-reports/plugin-remediation-prompt.txt" \
+ * --summary "4 custom plugins on adx_* entities..."
+ *
+ * # set customization-report findings card (call once after the CSV is parsed)
+ * node update-state.js --output-dir <DIR> --set-customization-report \
+ * '{"path":"./migration-reports/customization-report.html","csvPath":"./migration-reports/SiteCustomization.csv","totalFindings":14,"breakdown":{"fetchxml":3,"liquid":8,"dme":2,"plugins":1}}'
+ *
+ * # set transactional refs migration tracker card (call once after `pac pages migrate-datamodel -s -v` returns)
+ * node update-state.js --output-dir <DIR> --set-refs-migration \
+ * '{"status":"Completed","currentStep":"StatusUpdated","createdAt":"2026-06-22T07:20:16Z","modifiedAt":"2026-06-22T07:29:19Z","stepHistory":[{"step":"ConfigurationDataReferencesStarted","at":"2026-06-22T07:27:21Z"},{"step":"ConfigurationDataReferencesCompleted","at":"2026-06-22T07:29:17Z"}],"runs":[{"name":"Run on 6/22/2026 7:27:27 AM","chunkTotal":3,"completed":3,"succeeded":3,"chunks":[{"name":"adx_blog_webrole...","runStatus":1,"outcome":1,"errorType":null,"errorDetails":null}]}]}'
+ * # On a step-level failure (the command aborted, or the tracker reports Failed with a
+ * # top-level reason not tied to a specific chunk), include an "error" field — it renders
+ * # as an error banner on the card. Chunk-level errors still go on runs[].chunks[].
+ * node update-state.js --output-dir <DIR> --set-refs-migration \
+ * '{"status":"Failed","currentStep":"ConfigurationDataReferencesStarted","error":"pac pages migrate-datamodel exited 1: migration could not be started ..."}'
+ *
+ * # structured "now running" operation card (used during long-running steps:
+ * # package installs, metadata/refs migration polling). Drives the always-visible
+ * # banner + client-side live elapsed ticker + estimate bar in the report. Re-issue
+ * # each poll iteration with a bumped poll.attempt; startedAt is preserved across
+ * # updates that keep the same label so the elapsed clock stays monotonic.
+ * node update-state.js --output-dir <DIR> --set-operation \
+ * '{"label":"Migrating configuration metadata to EDM","detail":"mode=configurationData","expectedDurationSec":600,"poll":{"attempt":3,"max":30}}'
+ * node update-state.js --output-dir <DIR> --clear-operation
+ *
+ * # record a major migration DECISION for later review (Migration & Review tab).
+ * # Upserts by `id` so re-running a decision point updates in place. Record only
+ * # migration-substance choices (env type, mode, track, package install/skip,
+ * # remediation, reset, rollback, restart) — NOT file create/update/read prompts.
+ * node update-state.js --output-dir <DIR> --add-decision \
+ * '{"id":"migration-mode","label":"Migration mode","choice":"configurationData → Authoring Track","rationale":"Dev env — migrate metadata locally; allows remediation before refs"}'
+ *
+ * # set migration track (called at end of step 1.7 once env type + mode known)
+ * # A = Authoring Track (mode configurationData|all — Dev/Single env)
+ * # B = Downstream Track (mode configurationDataReferences — Test/UAT/Prod, ALM assumed)
+ * node update-state.js --output-dir <DIR> --set-track A
+ * node update-state.js --output-dir <DIR> --set-track B
+ *
+ * # re-render without state change (useful after manual edits)
+ * node update-state.js --output-dir <DIR> --render-only
+ */
+
+const fs = require('fs');
+const path = require('path');
+
+const {
+ PHASE_STATUS,
+ SUB_STEP_STATUS,
+ APPROVAL_KIND,
+ PROMPT_STATUS,
+ TRACK,
+ normalizePendingInput,
+ buildInitialState,
+ rebuildPhasesForTrack,
+} = require('./lib/migration-state-schema');
+const { renderLiveReport } = require('./lib/render-live-report');
+
+function parseArgs(argv) {
+ const result = { _: [] };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a.startsWith('--')) {
+ const key = a.slice(2);
+ const next = argv[i + 1];
+ if (next === undefined || next.startsWith('--')) {
+ result[key] = true;
+ } else {
+ result[key] = next;
+ i += 1;
+ }
+ } else {
+ result._.push(a);
+ }
+ }
+ return result;
+}
+
+function statePathFor(outputDir) {
+ return path.join(outputDir, 'migration-state.json');
+}
+
+function reportPathFor(outputDir) {
+ return path.join(outputDir, 'datamodel-migration-report.html');
+}
+
+// Sanitize a free-text segment (env name or website slug) into a safe path component.
+// Lowercase, replace non-[a-z0-9] runs with '-', trim leading/trailing '-', cap at 60 chars.
+function sanitizeForPath(raw) {
+ if (typeof raw !== 'string') return '';
+ return raw
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 60);
+}
+
+// Build the per-migration subdirectory name from env name + slug.
+// Falls back to the first 8 chars of websiteId if both sanitized segments are empty.
+function buildMigrationSubdir({ envName, slug, webSiteId }) {
+ const envPart = sanitizeForPath(envName);
+ const slugPart = sanitizeForPath(slug);
+ if (envPart && slugPart) return `${envPart}--${slugPart}`;
+ if (envPart) return envPart;
+ if (slugPart) return slugPart;
+ // Both sanitized away — fall back to a short site id so we never produce an empty subdir.
+ const idFallback = typeof webSiteId === 'string' ? webSiteId.replace(/[^a-zA-Z0-9]/g, '').slice(0, 8).toLowerCase() : '';
+ return idFallback || 'migration';
+}
+
+function trackName(track) {
+ if (track === TRACK.A) return 'Authoring Track';
+ if (track === TRACK.B) return 'Downstream Track';
+ return `Unknown (${track})`;
+}
+
+function environmentOrigin(raw) {
+ const url = new URL(raw);
+ if (url.protocol !== 'https:' || url.username || url.password ||
+ url.search || url.hash || url.pathname !== '/') {
+ throw new Error('--env-url / environmentUrl must be an HTTPS environment origin, for example https://contoso.crm.dynamics.com');
+ }
+ return url.origin;
+}
+
+function isRecord(value) {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function loadState(outputDir) {
+ const p = statePathFor(outputDir);
+ if (!fs.existsSync(p)) {
+ throw new Error(
+ `migration-state.json not found at ${p}. Run \`update-state.js --init --output-dir <PARENT_DIR> --website-id <GUID> --env-name <NAME> --env-url <ENV_URL> --slug <SLUG>\` first (the init command creates a per-migration subfolder and prints its path — use that subfolder as --output-dir for all subsequent commands).`,
+ );
+ }
+ const state = JSON.parse(fs.readFileSync(p, 'utf-8'));
+ if (!isRecord(state) || !isRecord(state.site) || typeof state.site.webSiteId !== 'string' ||
+ !Array.isArray(state.phases) || state.phases.length === 0 ||
+ state.phases.some((phase) => !isRecord(phase) || !Array.isArray(phase.subSteps) ||
+ phase.subSteps.some((step) => !isRecord(step))) ||
+ !isRecord(state.augmentedPrompts)) {
+ throw new Error(`Invalid migration state at ${p}: expected site identity, phases with subSteps, and augmentedPrompts objects. Restore a valid migration-state.json before continuing.`);
+ }
+ return state;
+}
+
+function loadSnapshotIfExists(outputDir, label) {
+ const p = path.join(outputDir, `${label}-snapshot.json`);
+ if (!fs.existsSync(p)) return null;
+ try {
+ return JSON.parse(fs.readFileSync(p, 'utf-8'));
+ } catch (e) {
+ // Don't fail the report write if a snapshot is malformed — just skip it.
+ console.warn(`Warning: could not parse ${label} snapshot at ${p}: ${e.message}`);
+ return null;
+ }
+}
+
+function loadRemediationDiffIfExists(outputDir) {
+ const p = path.join(outputDir, 'remediation-diff.json');
+ if (!fs.existsSync(p)) return null;
+ try {
+ const data = JSON.parse(fs.readFileSync(p, 'utf-8'));
+ // Inject the manifest's own absolute path for reference by the renderer.
+ data.manifestPath = path.resolve(p);
+ return data;
+ } catch (e) {
+ console.warn(`Warning: could not parse remediation-diff.json at ${p}: ${e.message}`);
+ return null;
+ }
+}
+
+function loadRenderOpts(outputDir) {
+ return {
+ sdmSnapshot: loadSnapshotIfExists(outputDir, 'sdm'),
+ edmSnapshot: loadSnapshotIfExists(outputDir, 'edm'),
+ remediationDiff: loadRemediationDiffIfExists(outputDir),
+ };
+}
+
+function persist(state, outputDir) {
+ state.lastUpdatedAt = new Date().toISOString();
+ // Rendering validates nested report inputs too. Never replace usable state
+ // with an update that cannot be rendered.
+ const html = renderLiveReport(state, loadRenderOpts(outputDir));
+ fs.mkdirSync(outputDir, { recursive: true });
+ fs.writeFileSync(statePathFor(outputDir), JSON.stringify(state, null, 2) + '\n', 'utf-8');
+ fs.writeFileSync(reportPathFor(outputDir), html, 'utf-8');
+}
+
+function cmdInit(args) {
+ const parentDir = args['output-dir'];
+ const webSiteId = args['website-id'];
+ const envName = args['env-name'];
+ const slug = args['slug'];
+ const envUrl = args['env-url'];
+ const force = !!args['force'];
+ if (!parentDir) throw new Error('--init requires --output-dir (the parent directory; a per-migration subfolder is created inside it)');
+ if (!webSiteId) throw new Error('--init requires --website-id');
+ if (typeof envName !== 'string' || envName.trim() === '') {
+ throw new Error('--init requires --env-name "<NAME>" (the Dataverse environment display name, used to namespace the migration subfolder)');
+ }
+ if (typeof slug !== 'string' || slug.trim() === '') {
+ throw new Error('--init requires --slug "<SLUG>" (the website slug from `pac pages list -v`, used to namespace the migration subfolder)');
+ }
+ if (typeof envUrl !== 'string' || envUrl.trim() === '') {
+ throw new Error('--init requires --env-url "<ENV_URL>" to verify the migration environment on resume');
+ }
+ const environmentUrl = environmentOrigin(envUrl);
+
+ const subdirName = buildMigrationSubdir({ envName, slug, webSiteId });
+ const outputDir = path.join(parentDir, subdirName);
+ const statePath = statePathFor(outputDir);
+
+ if (fs.existsSync(statePath)) {
+ const existing = loadState(outputDir);
+ // Display names and sanitized slugs are not unique. Check the original
+ // identity before either resuming or force-resetting this directory.
+ if (String(existing.site.webSiteId).toLowerCase() !== String(webSiteId).toLowerCase() ||
+ existing.site.environmentName !== envName || existing.site.slug !== slug ||
+ existing.site.environmentUrl !== environmentUrl) {
+ throw new Error(`Migration identity mismatch at ${statePath}; refusing to resume or overwrite it. ` +
+ 'Verify the site and environment. For older state without environmentUrl, verify its origin before recording it with --set-site.');
+ }
+ if (!force) {
+ console.log(`⚠ Existing migration found at ${statePath}`);
+ console.log(' Re-using existing state (resume mode). Pass --force to reset and start fresh.');
+ console.log(`Use --output-dir "${outputDir}" for every subsequent update-state.js call.`);
+ return;
+ }
+ }
+
+ if (force) {
+ // Reset only generated migration artifacts, never the downloaded site tree.
+ for (const filename of [
+ 'sdm-snapshot.json', 'edm-snapshot.json', 'migration-data-diff.json',
+ 'remediation-diff.json', 'customization-report.html', 'customization-assessment.json',
+ 'plugin-remediation-prompt.txt', 'dme-remediation-prompt.txt',
+ 'migration-status.json', 'migration-status.txt',
+ ]) {
+ fs.rmSync(path.join(outputDir, filename), { force: true });
+ }
+ fs.rmSync(path.join(outputDir, 'remediation-staged'), { recursive: true, force: true });
+ }
+
+ const state = buildInitialState({ webSiteId, outputDir });
+ state.site.environmentName = envName;
+ state.site.environmentUrl = environmentUrl;
+ state.site.slug = slug;
+ fs.mkdirSync(outputDir, { recursive: true });
+ fs.writeFileSync(statePath, JSON.stringify(state, null, 2) + '\n', 'utf-8');
+ fs.writeFileSync(reportPathFor(outputDir), renderLiveReport(state, loadRenderOpts(outputDir)), 'utf-8');
+ console.log(`✓ Migration subfolder: ${outputDir}`);
+ console.log(`✓ Initialized ${statePath}`);
+ console.log(`✓ Rendered ${reportPathFor(outputDir)}`);
+ console.log('');
+ console.log(`Use --output-dir "${outputDir}" for every subsequent update-state.js call.`);
+}
+
+function cmdSetSite(args) {
+ const outputDir = args['output-dir'];
+ const raw = args['set-site'];
+ if (!outputDir) throw new Error('--set-site requires --output-dir');
+ if (typeof raw !== 'string') throw new Error('--set-site expects a JSON string');
+ let patch;
+ try {
+ patch = JSON.parse(raw);
+ } catch (e) {
+ throw new Error(`--set-site: could not parse JSON: ${e.message}`);
+ }
+ if (!isRecord(patch)) throw new Error('--set-site expects a JSON object');
+ const state = loadState(outputDir);
+ const allowed = [
+ 'name',
+ 'portalId',
+ 'portalUrl',
+ 'slug',
+ 'currentDataModel',
+ 'template',
+ 'environment',
+ 'environmentName',
+ 'environmentUrl',
+ 'migrationMode',
+ 'siteRoot',
+ ];
+ for (const k of Object.keys(patch)) {
+ if (!allowed.includes(k)) {
+ throw new Error(`--set-site: unknown field '${k}'. Allowed: ${allowed.join(', ')}`);
+ }
+ if (patch[k] !== null && typeof patch[k] !== 'string') {
+ throw new Error(`--set-site: ${k} must be a string or null`);
+ }
+ state.site[k] = k === 'environmentUrl' && patch[k] !== null ? environmentOrigin(patch[k]) : patch[k];
+ }
+ persist(state, outputDir);
+ console.log(`✓ Site updated: ${Object.keys(patch).join(', ')}`);
+}
+
+function cmdSetStep(args) {
+ const outputDir = args['output-dir'];
+ const stepId = args['set-step'];
+ const status = args['status'];
+ const output = args['output'];
+ if (!outputDir) throw new Error('--set-step requires --output-dir');
+ if (typeof stepId !== 'string') throw new Error('--set-step requires a sub-step id like 1.1');
+ if (!status) throw new Error('--set-step requires --status <pending|in-progress|completed|blocked>');
+ if (!Object.values(SUB_STEP_STATUS).includes(status)) {
+ throw new Error(`Invalid sub-step status '${status}'. Allowed: ${Object.values(SUB_STEP_STATUS).join(', ')}`);
+ }
+ const state = loadState(outputDir);
+ let sub = null;
+ for (const p of state.phases) {
+ sub = p.subSteps.find((s) => s.id === stepId);
+ if (sub) break;
+ }
+ if (!sub) throw new Error(`Unknown sub-step id '${stepId}'`);
+ sub.status = status;
+ if (output !== undefined) sub.output = typeof output === 'string' ? output : null;
+ persist(state, outputDir);
+ console.log(`✓ Step ${stepId} → ${status}${output ? ` · ${String(output).slice(0, 60)}${String(output).length > 60 ? '…' : ''}` : ''}`);
+}
+
+function cmdSetPhase(args) {
+ const outputDir = args['output-dir'];
+ const phaseId = Number(args['set-phase']);
+ const status = args['status'];
+ if (!outputDir) throw new Error('--set-phase requires --output-dir');
+ if (!Number.isFinite(phaseId)) throw new Error('--set-phase requires a phase number');
+ if (!status) throw new Error('--set-phase requires --status');
+ if (!Object.values(PHASE_STATUS).includes(status)) {
+ throw new Error(`Invalid phase status '${status}'. Allowed: ${Object.values(PHASE_STATUS).join(', ')}`);
+ }
+ const state = loadState(outputDir);
+ const phase = state.phases.find((p) => p.id === phaseId);
+ if (!phase) throw new Error(`Unknown phase id '${phaseId}'`);
+ const now = new Date().toISOString();
+ if (status === PHASE_STATUS.IN_PROGRESS && !phase.startedAt) phase.startedAt = now;
+ if (status === PHASE_STATUS.COMPLETED) {
+ if (!phase.startedAt) phase.startedAt = now;
+ phase.completedAt = now;
+ }
+ phase.status = status;
+ persist(state, outputDir);
+ console.log(`✓ Phase ${phaseId} → ${status}`);
+}
+
+function cmdSetApproval(args) {
+ const outputDir = args['output-dir'];
+ const value = args['set-approval'];
+ if (!outputDir) throw new Error('--set-approval requires --output-dir');
+ // --set-approval <phaseId> <kind> (kind is in positional _ array)
+ const phaseId = Number(value);
+ const kind = args._[0];
+ if (!Number.isFinite(phaseId)) {
+ throw new Error('--set-approval requires a phase id (e.g. --set-approval 2 phase-start)');
+ }
+ if (!kind || !Object.values(APPROVAL_KIND).includes(kind)) {
+ throw new Error(`--set-approval requires kind: ${Object.values(APPROVAL_KIND).join(' | ')}`);
+ }
+ const state = loadState(outputDir);
+ state.approvalGate = { phaseId, kind };
+ state.pendingInput = null;
+ state.currentOperation = null;
+ persist(state, outputDir);
+ console.log(`✓ Approval gate → phase ${phaseId} (${kind})`);
+}
+
+function cmdClearApproval(args) {
+ const outputDir = args['output-dir'];
+ if (!outputDir) throw new Error('--clear-approval requires --output-dir');
+ const state = loadState(outputDir);
+ state.approvalGate = null;
+ state.pendingInput = null;
+ persist(state, outputDir);
+ console.log('✓ Approval gate cleared');
+}
+
+// Atomic helper: clear the approval gate and mark the given phase in-progress
+// in a single persist() / render. Use this whenever the user answers an
+// AskUserQuestion approval gate; calling --clear-approval followed by
+// --set-phase would leave the live report in a transitional state between the
+// two writes (the topbar pill would briefly say "Ready · Phase N" or worse).
+function cmdApproveAndStart(args) {
+ const outputDir = args['output-dir'];
+ const phaseId = Number(args['approve-and-start']);
+ if (!outputDir) throw new Error('--approve-and-start requires --output-dir');
+ if (!Number.isFinite(phaseId)) {
+ throw new Error('--approve-and-start requires a phase id (e.g. --approve-and-start 2)');
+ }
+ const state = loadState(outputDir);
+ const phase = state.phases.find((p) => p.id === phaseId);
+ if (!phase) throw new Error(`--approve-and-start: phase ${phaseId} not found in state`);
+ state.approvalGate = null;
+ state.pendingInput = null;
+ phase.status = PHASE_STATUS.IN_PROGRESS;
+ if (!phase.startedAt) phase.startedAt = new Date().toISOString();
+ persist(state, outputDir);
+ console.log(`✓ Approval cleared and phase ${phaseId} → in-progress`);
+}
+
+function cmdSetInput(args) {
+ const outputDir = args['output-dir'];
+ if (!outputDir) throw new Error('--set-input requires --output-dir');
+ const raw = args['set-input'];
+ if (typeof raw !== 'string') throw new Error('--set-input requires a JSON string value');
+ let payload;
+ try {
+ payload = JSON.parse(raw);
+ } catch (error) {
+ throw new Error(`--set-input requires valid JSON: ${error.message}`);
+ }
+ const pendingInput = normalizePendingInput(payload);
+ if (!pendingInput) throw new Error('--set-input requires an object with a non-empty "requiredAction" string');
+ const state = loadState(outputDir);
+ state.pendingInput = pendingInput;
+ state.currentOperation = null;
+ persist(state, outputDir);
+ console.log(`✓ Input needed: ${pendingInput.requiredAction}`);
+}
+
+function cmdClearInput(args) {
+ const outputDir = args['output-dir'];
+ if (!outputDir) throw new Error('--clear-input requires --output-dir');
+ const state = loadState(outputDir);
+ state.pendingInput = null;
+ persist(state, outputDir);
+ console.log('✓ Input notification cleared');
+}
+
+function cmdSetPrompt(args) {
+ const outputDir = args['output-dir'];
+ const kind = args['set-prompt'];
+ if (!outputDir) throw new Error('--set-prompt requires --output-dir');
+ if (kind !== 'plugin' && kind !== 'dme') {
+ throw new Error(`--set-prompt requires kind 'plugin' or 'dme', got '${kind}'`);
+ }
+ const status = args['status'] || PROMPT_STATUS.READY;
+ if (!Object.values(PROMPT_STATUS).includes(status)) {
+ throw new Error(`Invalid prompt status '${status}'`);
+ }
+ const state = loadState(outputDir);
+ state.augmentedPrompts[kind] = {
+ status,
+ path: typeof args['path'] === 'string' ? args['path'] : null,
+ summary: typeof args['summary'] === 'string' ? args['summary'] : null,
+ };
+ persist(state, outputDir);
+ console.log(`✓ Prompt '${kind}' → ${status}`);
+}
+
+function cmdSetCustomizationReport(args) {
+ const outputDir = args['output-dir'];
+ const raw = args['set-customization-report'];
+ if (!outputDir) throw new Error('--set-customization-report requires --output-dir');
+ if (typeof raw !== 'string') throw new Error('--set-customization-report expects a JSON string');
+ let payload;
+ try {
+ payload = JSON.parse(raw);
+ } catch (e) {
+ throw new Error(`--set-customization-report: could not parse JSON: ${e.message}`);
+ }
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
+ throw new Error('--set-customization-report expects a JSON object');
+ }
+ const allowed = ['path', 'csvPath', 'totalFindings', 'breakdown', 'scannedAt'];
+ for (const k of Object.keys(payload)) {
+ if (!allowed.includes(k)) {
+ throw new Error(`--set-customization-report: unknown field '${k}'. Allowed: ${allowed.join(', ')}`);
+ }
+ }
+ if (payload.totalFindings !== undefined && !Number.isFinite(payload.totalFindings)) {
+ throw new Error('--set-customization-report: totalFindings must be a number');
+ }
+ if (payload.breakdown !== undefined && (payload.breakdown === null || typeof payload.breakdown !== 'object' || Array.isArray(payload.breakdown))) {
+ throw new Error('--set-customization-report: breakdown must be an object of { category: count }');
+ }
+ const state = loadState(outputDir);
+ state.customizationReport = {
+ path: typeof payload.path === 'string' ? payload.path : null,
+ csvPath: typeof payload.csvPath === 'string' ? payload.csvPath : null,
+ totalFindings: Number.isFinite(payload.totalFindings) ? payload.totalFindings : 0,
+ breakdown: payload.breakdown || {},
+ scannedAt: typeof payload.scannedAt === 'string' ? payload.scannedAt : new Date().toISOString(),
+ };
+ persist(state, outputDir);
+ console.log(`✓ Customization report → ${state.customizationReport.totalFindings} finding${state.customizationReport.totalFindings === 1 ? '' : 's'}`);
+}
+
+const REFS_MIGRATION_STATUSES = new Set(['NotStarted', 'Running', 'Completed', 'Failed', 'Reverted', 'Unknown']);
+
+function cmdSetRefsMigration(args) {
+ const outputDir = args['output-dir'];
+ const raw = args['set-refs-migration'];
+ if (!outputDir) throw new Error('--set-refs-migration requires --output-dir');
+ if (typeof raw !== 'string') throw new Error('--set-refs-migration expects a JSON string');
+ let payload;
+ try {
+ payload = JSON.parse(raw);
+ } catch (e) {
+ throw new Error(`--set-refs-migration: could not parse JSON: ${e.message}`);
+ }
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
+ throw new Error('--set-refs-migration expects a JSON object');
+ }
+ const allowed = ['status', 'currentStep', 'createdAt', 'modifiedAt', 'stepHistory', 'runs', 'capturedAt', 'error'];
+ for (const k of Object.keys(payload)) {
+ if (!allowed.includes(k)) {
+ throw new Error(`--set-refs-migration: unknown field '${k}'. Allowed: ${allowed.join(', ')}`);
+ }
+ }
+ if (payload.status !== undefined && !REFS_MIGRATION_STATUSES.has(payload.status)) {
+ throw new Error(`--set-refs-migration: status must be one of ${[...REFS_MIGRATION_STATUSES].join(', ')}`);
+ }
+ if (payload.stepHistory !== undefined && !Array.isArray(payload.stepHistory)) {
+ throw new Error('--set-refs-migration: stepHistory must be an array');
+ }
+ if (payload.runs !== undefined && !Array.isArray(payload.runs)) {
+ throw new Error('--set-refs-migration: runs must be an array');
+ }
+ if (payload.stepHistory?.some((step) => !isRecord(step))) {
+ throw new Error('--set-refs-migration: stepHistory entries must be objects');
+ }
+ if (payload.runs?.some((run) => !isRecord(run) || (run.chunks != null &&
+ (!Array.isArray(run.chunks) || run.chunks.some((chunk) => !isRecord(chunk)))))) {
+ throw new Error('--set-refs-migration: runs and chunks entries must be objects, and chunks must be an array');
+ }
+ if (payload.error !== undefined && payload.error !== null && typeof payload.error !== 'string') {
+ throw new Error('--set-refs-migration: error must be a string');
+ }
+ const state = loadState(outputDir);
+ state.refsMigration = {
+ status: typeof payload.status === 'string' ? payload.status : 'Unknown',
+ currentStep: typeof payload.currentStep === 'string' ? payload.currentStep : null,
+ createdAt: typeof payload.createdAt === 'string' ? payload.createdAt : null,
+ modifiedAt: typeof payload.modifiedAt === 'string' ? payload.modifiedAt : null,
+ stepHistory: Array.isArray(payload.stepHistory) ? payload.stepHistory : [],
+ runs: Array.isArray(payload.runs) ? payload.runs : [],
+ // Step-level (non-chunk) failure detail — the pac command's error text or the tracker's
+ // top-level failure reason. Chunk-level errors live on runs[].chunks[]; this captures a
+ // failure not tied to a specific chunk (command aborted, auth/network failure, or the
+ // tracker reporting Failed with a message). Rendered as an error banner in the report.
+ error: typeof payload.error === 'string' ? payload.error : null,
+ capturedAt: typeof payload.capturedAt === 'string' ? payload.capturedAt : new Date().toISOString(),
+ };
+ persist(state, outputDir);
+ const r = state.refsMigration;
+ const totalChunks = r.runs.reduce((a, run) => a + (Number.isFinite(run.chunkTotal) ? run.chunkTotal : 0), 0);
+ const totalSucceeded = r.runs.reduce((a, run) => a + (Number.isFinite(run.succeeded) ? run.succeeded : 0), 0);
+ console.log(`✓ Refs migration → status=${r.status} · step=${r.currentStep || '?'} · chunks ${totalSucceeded}/${totalChunks}${r.error ? ` · error: ${r.error.slice(0, 120)}` : ''}`);
+}
+
+function cmdSetOperation(args) {
+ const outputDir = args['output-dir'];
+ if (!outputDir) throw new Error('--set-operation requires --output-dir');
+ const raw = args['set-operation'];
+ if (typeof raw !== 'string') throw new Error('--set-operation requires a JSON string value');
+ let payload;
+ try {
+ payload = JSON.parse(raw);
+ } catch (e) {
+ throw new Error(`--set-operation requires valid JSON: ${e.message}`);
+ }
+ if (!payload || typeof payload.label !== 'string' || payload.label.trim() === '') {
+ throw new Error('--set-operation JSON must include a non-empty "label" string');
+ }
+ const state = loadState(outputDir);
+ // Preserve startedAt across repeated updates for the SAME operation label so the
+ // live elapsed ticker stays monotonic across poll iterations — each poll re-issues
+ // --set-operation with a bumped attempt count, not a brand-new operation.
+ const prev = state.currentOperation;
+ const startedAt = (prev && prev.label === payload.label && prev.startedAt)
+ ? prev.startedAt
+ : new Date().toISOString();
+ const expectedDurationSec = Number.isFinite(payload.expectedDurationSec) && payload.expectedDurationSec > 0
+ ? Math.floor(payload.expectedDurationSec)
+ : null;
+ let poll = null;
+ if (payload.poll && Number.isFinite(payload.poll.attempt) && Number.isFinite(payload.poll.max)) {
+ poll = { attempt: Math.floor(payload.poll.attempt), max: Math.floor(payload.poll.max) };
+ }
+ state.currentOperation = {
+ label: payload.label,
+ detail: typeof payload.detail === 'string' ? payload.detail : null,
+ startedAt,
+ expectedDurationSec,
+ poll,
+ };
+ state.pendingInput = null;
+ persist(state, outputDir);
+ console.log(`✓ Operation: ${payload.label}${poll ? ` (attempt ${poll.attempt}/${poll.max})` : ''}`);
+}
+
+function cmdClearOperation(args) {
+ const outputDir = args['output-dir'];
+ if (!outputDir) throw new Error('--clear-operation requires --output-dir');
+ const state = loadState(outputDir);
+ state.currentOperation = null;
+ persist(state, outputDir);
+ console.log('✓ Operation cleared');
+}
+
+function cmdAddDecision(args) {
+ const outputDir = args['output-dir'];
+ if (!outputDir) throw new Error('--add-decision requires --output-dir');
+ const raw = args['add-decision'];
+ if (typeof raw !== 'string') throw new Error('--add-decision requires a JSON string value');
+ let payload;
+ try {
+ payload = JSON.parse(raw);
+ } catch (e) {
+ throw new Error(`--add-decision requires valid JSON: ${e.message}`);
+ }
+ if (!payload || typeof payload.label !== 'string' || payload.label.trim() === '') {
+ throw new Error('--add-decision JSON must include a non-empty "label" string');
+ }
+ if (typeof payload.choice !== 'string' || payload.choice.trim() === '') {
+ throw new Error('--add-decision JSON must include a non-empty "choice" string');
+ }
+ const state = loadState(outputDir);
+ if (!Array.isArray(state.decisions)) state.decisions = [];
+ const entry = {
+ id: typeof payload.id === 'string' && payload.id.trim() ? payload.id.trim() : null,
+ label: payload.label,
+ choice: payload.choice,
+ rationale: typeof payload.rationale === 'string' ? payload.rationale : null,
+ at: new Date().toISOString(),
+ };
+ // Upsert by id when provided, so re-running the same decision point (e.g. the user
+ // changes the migration mode, or a package install is retried) updates the existing
+ // entry instead of appending a duplicate. Without an id, always append.
+ const existingIdx = entry.id ? state.decisions.findIndex((d) => d.id === entry.id) : -1;
+ if (existingIdx >= 0) {
+ state.decisions[existingIdx] = entry;
+ } else {
+ state.decisions.push(entry);
+ }
+ persist(state, outputDir);
+ console.log(`✓ Decision: ${entry.label} → ${entry.choice}`);
+}
+
+function cmdSetTrack(args) {
+ const outputDir = args['output-dir'];
+ const track = args['set-track'];
+ if (!outputDir) throw new Error('--set-track requires --output-dir');
+ if (!Object.values(TRACK).includes(track)) {
+ throw new Error(`--set-track requires one of: ${Object.values(TRACK).join(', ')}`);
+ }
+ const state = loadState(outputDir);
+ if (state.track === track) {
+ console.log(`✓ Track already set to ${track} (${trackName(track)}); no change`);
+ return;
+ }
+ rebuildPhasesForTrack(state, track);
+ persist(state, outputDir);
+ console.log(`✓ Track set to ${track} (${trackName(track)}); Phase 2 + Phase 3 rebuilt from blueprint`);
+}
+
+function cmdRenderOnly(args) {
+ const outputDir = args['output-dir'];
+ if (!outputDir) throw new Error('--render-only requires --output-dir');
+ const state = loadState(outputDir);
+ fs.writeFileSync(reportPathFor(outputDir), renderLiveReport(state, loadRenderOpts(outputDir)), 'utf-8');
+ console.log(`✓ Re-rendered ${reportPathFor(outputDir)}`);
+}
+
+function main() {
+ const args = parseArgs(process.argv.slice(2));
+ try {
+ if (args.init) return cmdInit(args);
+ if (args['set-site'] !== undefined) return cmdSetSite(args);
+ if (args['set-step'] !== undefined) return cmdSetStep(args);
+ if (args['set-phase'] !== undefined) return cmdSetPhase(args);
+ if (args['set-approval'] !== undefined) return cmdSetApproval(args);
+ if (args['clear-approval']) return cmdClearApproval(args);
+ if (args['approve-and-start'] !== undefined) return cmdApproveAndStart(args);
+ if (args['set-input'] !== undefined) return cmdSetInput(args);
+ if (args['clear-input']) return cmdClearInput(args);
+ if (args['set-prompt'] !== undefined) return cmdSetPrompt(args);
+ if (args['set-customization-report'] !== undefined) return cmdSetCustomizationReport(args);
+ if (args['set-refs-migration'] !== undefined) return cmdSetRefsMigration(args);
+ if (args['set-operation'] !== undefined) return cmdSetOperation(args);
+ if (args['clear-operation']) return cmdClearOperation(args);
+ if (args['add-decision'] !== undefined) return cmdAddDecision(args);
+ if (args['set-track'] !== undefined) return cmdSetTrack(args);
+ if (args['render-only']) return cmdRenderOnly(args);
+ console.error('No command given. Run with --help-ish docs at top of update-state.js');
+ process.exit(2);
+ } catch (e) {
+ console.error(`Error: ${e.message}`);
+ process.exit(1);
+ }
+}
+
+main();