A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
[Pages][ALM] Site-referenced table discovery + dependency-aware solution splitting (#193)
T-Nid5dfbbd415efc
diff --git a/marketplace.json b/marketplace.jsonindex 7b836dd72..119399ebc 100644--- a/marketplace.json+++ b/marketplace.json@@ -13,7 +13,7 @@"source": "./plugins/power-pages","description": "Power Pages development and management plugin for Claude Code and GitHub Copilot","category": "development",- "version": "2.2.0",+ "version": "2.4.0","license": "MIT","tags": ["power platform",diff --git a/plugins/power-pages/.plugin/plugin.json b/plugins/power-pages/.plugin/plugin.jsonindex 3021445a0..13763c7f2 100644--- a/plugins/power-pages/.plugin/plugin.json+++ b/plugins/power-pages/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.2.0",+ "version": "2.4.0","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex 1dc654169..5d7ce90c9 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -204,8 +204,12 @@ Shared lib modules live at `scripts/lib/` and are imported by other scripts via#### Solution Splitting Decision Tree (v1.3.0+)- `scripts/lib/alm-thresholds.js`: Central default threshold constants for the split decision tree. Loads optional `.alm-config.json` from project root and merges over defaults. Exports `DEFAULTS`, `DEFAULT_CONFIG`, `loadConfig(projectRoot)`, `classifyTier(value, greenUpperExclusive, yellowUpperExclusive)`, `deepMerge(target, source)`. Used by `estimate-solution-size.js` and `compute-split-plan.js`.-- `scripts/lib/estimate-solution-size.js`: Estimates solution size + component counts by querying Dataverse. Args: `--envUrl`, `--websiteRecordId`, `--token` (opt), `--publisherPrefix` (opt), `--siteName` (opt), `--solutionId` (opt — scopes env var count to the target solution; without it falls back to a publisher-prefix tenant-wide query that overcounts when prefix is shared), `--datamodelManifest` (opt), `--projectRoot` (opt — enables disk cross-check: walks the local build-output directory (`dist/`, `public-output/`, `build/`, `.output/`) and surfaces the byte total). Output: `{ totalSizeMB, componentCountSiteTotal, componentCountSiteActionable, componentCountInSolution, orphansOnSite, tableCount, schemaAttrCount, webFilesAggregateMB, webFilesIndividual[], webFileCount, webFileSampleSize, webFilesDiskMeasuredMB, webFilesDiskMeasuredPath, webFilesDiskFileCount, cloudFlowCount, botCount, envVarCount, envVarCountScope, envVarCountTenantWide, mediaRatio, siteType, tables[], breakdown, estimationMethod, estimationAccuracyPct, truncationSuspected, truncationWarnings, ppcGroundTruthCount }`. Metadata-based estimation with ±15% caveat. Web-file size is measured via stratified sample (first 50 + middle 50 + last 50, cap 150) scaled to full count. Disk fields are null unless `--projectRoot` was passed AND a build-output directory was found. Truncation canaries fire when Dataverse pagination disagrees with `@odata.count`, when ppcs land on a page-size boundary, when sampled average bytes/file < 1 KB at scale, or when the disk total exceeds the Dataverse total by >2× — any signal flips `truncationSuspected: true` with a per-cause `truncationWarnings[]` entry. Used by `plan-alm` Phase 1 Step 10.-- `scripts/lib/compute-split-plan.js`: Runs the split decision tree against a size-estimate blob. Args: `--estimate <path>`, `--projectRoot` (opt — for `.alm-config.json` overrides), `--siteName` (opt), `--publisherPrefix` (opt). Output: `{ sizeAnalysis, assetAdvisory, splitStrategy, appliedStrategies, compositeSubPartitioned, proposedSolutions[], recommendations[], truncationSuspected, truncationWarnings }`. Evaluates strategies in priority order: Strategy 3 (Schema Segmentation) → Strategy 1 (Layer Split) → Strategy 2 (Change-Frequency) → Strategy 4 (Config Isolation). Strategy 4 stacks additively. Strategy 1 also runs a composite sub-partition pass: when Core still exceeds the size OR component-count cap after Web Assets are peeled off, Core is replaced with change-frequency-shaped sub-children (`_Foundation`/`_Config`/`_Content`, plus `_Integration` whenever the parent had any flows or bots — coverage takes priority over the `changeFreqMinFlows` heuristic, which governs only the TOP-LEVEL strategy choice). When additive Strategy 4 is firing concurrently (a top-level `_EnvVars` solution), `_Config` drops `Environment Variable` from its componentTypes to avoid double-claim; when it isn't, `_Config` absorbs env vars so they have an owner. Sub-partitioning sets `compositeSubPartitioned: true` and appends `composite-sub-partition` to `appliedStrategies`. `validateSplits` checks BOTH the size AND component-count cap per split (skipping `isFutureBuffer` solutions). Supports `.alm-config.json` overrides including `strategyOverride` to bypass the tree. See `solution-splitting-logic.md` spec in design docs for full logic.+- `scripts/lib/estimate-solution-size.js`: Estimates solution size + component counts by querying Dataverse. Args: `--envUrl`, `--websiteRecordId`, `--token` (opt), `--publisherPrefix` (opt), `--siteName` (opt), `--solutionId` (opt — scopes env var count to the target solution; without it falls back to a publisher-prefix tenant-wide query that overcounts when prefix is shared), `--datamodelManifest` (opt), `--projectRoot` (opt — enables disk cross-check: walks the local build-output directory (`dist/`, `public-output/`, `build/`, `.output/`) and surfaces the byte total). Output: `{ totalSizeMB, componentCountSiteTotal, componentCountSiteActionable, componentCountInSolution, orphansOnSite, tableCount, tableCountScope, schemaAttrCount, webFilesAggregateMB, webFilesIndividual[], webFileCount, webFileSampleSize, webFilesDiskMeasuredMB, webFilesDiskMeasuredPath, webFilesDiskFileCount, cloudFlowCount, botCount, envVarCount, envVarCountScope, envVarCountTenantWide, mediaRatio, siteType, tables[], tableRelationships[], breakdown, estimationMethod, estimationAccuracyPct, truncationSuspected, truncationWarnings, ppcGroundTruthCount }`. **Table discovery is site-referenced, NOT publisher-prefix:** `tableCount`/`tables[]` are scoped to the custom tables the site actually references — its `.powerpages-site/table-permissions/` (+ datamodel manifest) intersected with the env's custom-unmanaged tables (via `resolve-site-tables.js` + `query-metadata.js`). `tableCountScope` ∈ `"site-referenced" | "manifest-only" | "unavailable"` (the last → 0 tables, never an env-wide prefix dump). `--publisherPrefix` now scopes ONLY the env var count, not tables. `tableRelationships[]` are `[a,b]` dependency edges (lookups + N:N, via `query-table-relationships.js`) among the scoped tables, consumed by `compute-split-plan.js` to cluster related tables into the same solution. Metadata-based estimation with ±15% caveat. Web-file size is measured via stratified sample (first 50 + middle 50 + last 50, cap 150) scaled to full count. Disk fields are null unless `--projectRoot` was passed AND a build-output directory was found. Truncation canaries fire when Dataverse pagination disagrees with `@odata.count`, when ppcs land on a page-size boundary, when sampled average bytes/file < 1 KB at scale, or when the disk total exceeds the Dataverse total by >2× — any signal flips `truncationSuspected: true` with a per-cause `truncationWarnings[]` entry. Used by `plan-alm` Phase 1 Step 10.+- `scripts/lib/compute-split-plan.js`: Runs the split decision tree against a size-estimate blob. Args: `--estimate <path>`, `--projectRoot` (opt — for `.alm-config.json` overrides), `--siteName` (opt), `--publisherPrefix` (opt). Output: `{ sizeAnalysis, assetAdvisory, splitStrategy, appliedStrategies, compositeSubPartitioned, proposedSolutions[], recommendations[], truncationSuspected, truncationWarnings }`. Evaluates strategies in priority order: Strategy 3 (Schema Segmentation) → Strategy 1 (Layer Split) → Strategy 2 (Change-Frequency) → Strategy 4 (Config Isolation). **Schema Segmentation is dependency-aware + capacity-bounded:** it builds connected-component clusters from `estimate.tableRelationships` (union-find), then bin-packs whole clusters (never splitting a relationship) into the fewest solutions that keep each under `maxTableCount`/`maxSchemaAttrs` **where possible** — capped at `maxSchemaSplitSolutions` (default 8). This replaced the old one-solution-per-table-name-stem heuristic that produced ~one solution per table. Two cases CAN exceed a per-solution cap, and BOTH raise an `recommendations[]` warning rather than failing silently: (a) an indivisible dependency cluster larger than `maxTableCount` stays whole (oversized-cluster table-count warning); (b) when MORE than `maxSchemaSplitSolutions` independent attr-heavy clusters must share the capped solution count, the FFD least-loaded fallback co-locates clusters and a solution's summed columns exceed `maxSchemaAttrs` (oversized-schema attr-cap warning). The split trigger + thresholds are unchanged — only the packing. Strategy 4 stacks additively. Strategy 1 also runs a composite sub-partition pass: when Core still exceeds the size OR component-count cap after Web Assets are peeled off, Core is replaced with change-frequency-shaped sub-children (`_Foundation`/`_Config`/`_Content`, plus `_Integration` whenever the parent had any flows or bots — coverage takes priority over the `changeFreqMinFlows` heuristic, which governs only the TOP-LEVEL strategy choice). When additive Strategy 4 is firing concurrently (a top-level `_EnvVars` solution), `_Config` drops `Environment Variable` from its componentTypes to avoid double-claim; when it isn't, `_Config` absorbs env vars so they have an owner. Sub-partitioning sets `compositeSubPartitioned: true` and appends `composite-sub-partition` to `appliedStrategies`. `validateSplits` checks BOTH the size AND component-count cap per split (skipping `isFutureBuffer` solutions). Supports `.alm-config.json` overrides including `strategyOverride` to bypass the tree. See `solution-splitting-logic.md` spec in design docs for full logic.+- `scripts/lib/resolve-site-tables.js`: Single source of truth for "which custom tables does this site actually use." `collectReferencedEntityNames({ projectRoot, datamodelManifestPath })` reads `.powerpages-site/table-permissions/*.tablepermission.yml` (`entitylogicalname`, via `powerpages-config.js → loadTablePermissions`) + the datamodel manifest → `{ names:Set, available, sources }`. `scopeCustomTables(referencedNames, customUnmanagedTables)` intersects that set with the env's custom-unmanaged tables. SME-confirmed: table permissions are the complete signal ("if a table is used in the site there will be permissions for it"), so forms/lists are NOT scanned. Used by `estimate-solution-size.js` and `discover-site-components.js` to replace the publisher-prefix table dump.+- `scripts/lib/query-metadata.js`: `queryCustomUnmanagedTables(envUrl, token, makeRequest?)` → `[{ logicalName, metadataId, schemaName, displayName }]` (the single `EntityDefinitions?$filter=IsCustomEntity` query, `IsManaged===false` filtered). Consolidates the formerly-triplicated custom-table query (estimator, discover-site-components, setup-solution). Reuses `odataGetAll` from `validation-helpers.js`.+- `scripts/lib/query-table-relationships.js`: `fetchTableRelationships(envUrl, table, token, makeRequest?)` → `{ oneToMany[], manyToMany[] }`. Extracted from `skills/audit-permissions/scripts/query-table-relationships.js` (now a thin CLI wrapper over this lib) and extended with ManyToMany. OneToMany errors propagate; ManyToMany is best-effort. Used by the estimator to build `tableRelationships[]` and by audit-permissions for relationship-scope validation.+- `scripts/lib/validation-helpers.js` also exports `odataGet(url, token, makeRequest?)` + `odataGetAll(url, token, makeRequest?, maxPages?)` — the shared, injectable OData GET + `@odata.nextLink` pagination used by the new metadata/relationship helpers (avoids each lib rolling its own paginator).#### Solution Managementdiff --git a/plugins/power-pages/scripts/lib/alm-thresholds.js b/plugins/power-pages/scripts/lib/alm-thresholds.jsindex 3b57f030c..4df94e50b 100644--- a/plugins/power-pages/scripts/lib/alm-thresholds.js+++ b/plugins/power-pages/scripts/lib/alm-thresholds.js@@ -21,6 +21,12 @@ const DEFAULTS = Object.freeze({hardFlagComponentCount: 10000,maxSchemaAttrs: 15000,maxTableCount: 20,+ // Safety ceiling on the number of auto-derived schema-split solutions. The+ // schema-segmentation packing keeps each solution under maxTableCount /+ // maxSchemaAttrs, but caps the COUNT here so a pathological schema can't+ // explode into dozens of solutions — beyond this, the hardFlagComponentCount+ // recommendation tells the user to archive/consolidate instead.+ maxSchemaSplitSolutions: 8,maxAggregateWebFilesMB: 40,maxSingleFileMB: 2,maxEnvVarCount: 500,diff --git a/plugins/power-pages/scripts/lib/compute-split-plan.js b/plugins/power-pages/scripts/lib/compute-split-plan.jsindex e4291b371..41b7155c3 100644--- a/plugins/power-pages/scripts/lib/compute-split-plan.js+++ b/plugins/power-pages/scripts/lib/compute-split-plan.js@@ -299,7 +299,7 @@ function partitionByChangeFrequency(estimate, meta) {function partitionBySchema(estimate, meta, config) {const explicitDomains = Array.isArray(config.domains) && config.domains.length > 0? config.domains- : deriveDomainsFromPrefix(estimate);+ : deriveDomainsByCapacity(estimate, config.thresholds);// Derive domain vs site size shares from the estimator's breakdown when available,// falling back to a 50/50 heuristic only if breakdown is absent.@@ -312,6 +312,22 @@ function partitionBySchema(estimate, meta, config) {const breakdownAvailable = estimate.breakdown && Number.isFinite(Number(estimate.breakdown.tables));const domainDescSuffix = breakdownAvailable ? '' : ' (rough estimate — breakdown unavailable)';+ // Per-table attribute counts → a schema-component PROXY. A table contributes far+ // more than one solution component (the entity + every column/relationship), so+ // counting 1-per-table severely undercounts and lets an over-cap Table solution+ // slip past validateSplits' maxComponentCount check (and distorts the Site+ // solution's count, which subtracts the domain counts). Proxy = sum(attributeCount)+ // + 1 per table (the entity component). attributeCount comes from estimate.tables[].+ // Keys/lookups are LOWERCASED — table logical names are case-insensitive and are+ // lowercased everywhere else (table permissions, relationship edges); user-authored+ // .alm-config.json domain names may not match Dataverse casing exactly.+ const attrByTable = new Map(+ (Array.isArray(estimate.tables) ? estimate.tables : [])+ .map((t) => [t && t.logicalName && t.logicalName.toLowerCase(), (t && t.attributeCount) || 0]),+ );+ const schemaComponentProxy = (names) =>+ (names || []).reduce((sum, n) => sum + (attrByTable.get(String(n).toLowerCase()) || 0), 0) + (names ? names.length : 0);+const domainSolutions = explicitDomains.map((dom, i) => ({uniqueName: `${meta.baseName}_${sanitizeDomainName(dom.name)}`,displayName: `${meta.siteName} — ${dom.name}`,@@ -319,9 +335,12 @@ function partitionBySchema(estimate, meta, config) {componentTypes: ['Table'],description: `Schema domain: ${dom.name}. Tables: ${(dom.tableLogicalNames || []).join(', ') || '(derived)'}${domainDescSuffix}`,sizeMB: round(sizePerDomain),- componentCount: Math.ceil(- (estimate.schemaAttrCount || 0) / domainCount,- ),+ // Schema-component proxy when the domain's tables are known (sum of columns ++ // 1/table); falls back to an even attr-share split only for explicit domains+ // that didn't list their tables.+ componentCount: (dom.tableLogicalNames && dom.tableLogicalNames.length > 0)+ ? schemaComponentProxy(dom.tableLogicalNames)+ : Math.ceil((estimate.schemaAttrCount || 0) / domainCount),components: [],tableLogicalNames: dom.tableLogicalNames || [],}));@@ -345,23 +364,101 @@ function partitionBySchema(estimate, meta, config) {return [...domainSolutions, siteSolution];}-function deriveDomainsFromPrefix(estimate) {- const tables = estimate.tables || [];- if (tables.length === 0) return [{ name: 'All', tableLogicalNames: [] }];+// --- Dependency-aware schema packing ---------------------------------------+//+// Replaces the old "one solution per table-name stem" heuristic (which produced+// ~one solution per table for any distinctly-named schema). Tables connected by+// a relationship MUST ship together, so we:+// 1. Group tables into connected components (union-find over the estimator's+// `tableRelationships` edges). Because components have no edges between+// them, packing whole components into separate solutions never cuts a+// relationship — so there are no cross-/circular-solution table deps and+// import order among the table solutions is irrelevant.+// 2. Bin-pack the components into the FEWEST solutions that keep each under the+// per-solution caps (maxTableCount tables AND maxSchemaAttrs columns),+// capped at maxSchemaSplitSolutions.++function normalizeTables(estimate) {+ return (estimate.tables || [])+ .map((t) => ({+ logicalName: (t && (t.logicalName || t)).toString(),+ attributeCount: (t && t.attributeCount) || 0,+ }))+ .filter((t) => t.logicalName);+}+// Union-find over tables + relationship edges -> array of clusters (each a list+// of table objects). A table with no edges is its own singleton cluster.+function buildTableClusters(tables, edges) {+ const idx = new Map();+ tables.forEach((t, i) => idx.set(t.logicalName.toLowerCase(), i));+ const parent = tables.map((_, i) => i);+ const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };+ const union = (a, b) => { const ra = find(a), rb = find(b); if (ra !== rb) parent[ra] = rb; };+ for (const e of edges || []) {+ if (!Array.isArray(e) || e.length < 2) continue;+ const ia = idx.get(String(e[0]).toLowerCase());+ const ib = idx.get(String(e[1]).toLowerCase());+ if (ia != null && ib != null) union(ia, ib);+ }const groups = new Map();- for (const t of tables) {- const name = (t.logicalName || t).toString();- const afterPrefix = name.includes('_') ? name.split('_').slice(1).join('_') : name;- const stem = afterPrefix.split(/[_]/)[0] || 'misc';- const key = stem.charAt(0).toUpperCase() + stem.slice(1);- if (!groups.has(key)) groups.set(key, []);- groups.get(key).push(name);+ tables.forEach((t, i) => {+ const r = find(i);+ if (!groups.has(r)) groups.set(r, []);+ groups.get(r).push(t);+ });+ return [...groups.values()];+}++function clusterAttrs(cluster) {+ return cluster.reduce((s, t) => s + (t.attributeCount || 0), 0);+}++// First-fit-decreasing pack of whole clusters into `n` buckets, respecting the+// per-solution table + attribute caps. A cluster that fits nowhere under the+// caps (oversized, or n too small) goes to the least-loaded bucket — that bucket+// then exceeds a cap and is surfaced by the oversized-cluster recommendation.+function packClusters(clusters, n, thresholds) {+ const sorted = [...clusters].sort((a, b) => (clusterAttrs(b) - clusterAttrs(a)) || (b.length - a.length));+ const buckets = Array.from({ length: Math.max(n, 1) }, () => ({ tables: [], attrs: 0 }));+ for (const cluster of sorted) {+ const cAttrs = clusterAttrs(cluster);+ let target = buckets.findIndex(+ (b) => b.tables.length + cluster.length <= thresholds.maxTableCount &&+ b.attrs + cAttrs <= thresholds.maxSchemaAttrs,+ );+ if (target === -1) {+ target = buckets.reduce((best, b, i) => (b.attrs < buckets[best].attrs ? i : best), 0);+ }+ buckets[target].tables.push(...cluster);+ buckets[target].attrs += cAttrs;}+ return buckets.filter((b) => b.tables.length > 0);+}- return Array.from(groups.entries()).map(([name, tableLogicalNames]) => ({- name,- tableLogicalNames,+// Returns capacity-bounded "domains" (one per packed bucket) in the same shape+// the schema partitioner consumes: { name, tableLogicalNames }.+function deriveDomainsByCapacity(estimate, thresholds) {+ const tables = normalizeTables(estimate);+ if (tables.length === 0) return [{ name: 'Tables', tableLogicalNames: [] }];++ const clusters = buildTableClusters(tables, estimate.tableRelationships || []);+ const ceiling = (thresholds && thresholds.maxSchemaSplitSolutions) || 8;+ // Seed the packer with the maximum permitted bins (one per cluster, capped at+ // maxSchemaSplitSolutions). First-fit-decreasing still consolidates — clusters+ // that fit together share a bin and the empty bins are dropped, so the final+ // count stays minimal — but a cluster that fits nowhere lands in a NEW bin+ // instead of overflowing an existing one. Seeding from a lower bound+ // (ceil(tables/maxTable), ceil(attrs/maxAttr)) under-allocated bins and let+ // independent attr-heavy clusters bust maxSchemaAttrs in the least-loaded+ // bucket, unwarned (the oversized guard only catches per-cluster table count).+ const n = Math.min(clusters.length, ceiling);++ const buckets = packClusters(clusters, n, thresholds);+ const multi = buckets.length > 1;+ return buckets.map((b, i) => ({+ name: multi ? `Tables ${i + 1}` : 'Tables',+ tableLogicalNames: b.tables.map((t) => t.logicalName),}));}@@ -704,6 +801,38 @@ function computeSplitPlan({ estimate, config, meta }) {proposedSolutions = appendFutureBuffer(proposedSolutions, meta);const splitWarnings = validateSplits(proposedSolutions, config.thresholds);+ // Oversized-cluster guard: a Table solution holding more tables than the+ // per-solution cap means a single connected dependency cluster couldn't be+ // split without cutting a relationship. Name it so the user can decide whether+ // to denormalize the schema or raise the cap — we never silently split a cluster.+ const oversizedClusterWarnings = proposedSolutions+ .filter((s) => Array.isArray(s.tableLogicalNames) &&+ s.tableLogicalNames.length > config.thresholds.maxTableCount)+ .map((s) => ({+ type: 'warning',+ message: `Solution ${s.uniqueName} holds ${s.tableLogicalNames.length} related tables — above the ${config.thresholds.maxTableCount}-per-solution cap — because they form one dependency cluster that cannot be split without breaking a relationship. Consider denormalizing the schema or raising maxTableCount in .alm-config.json.`,+ }));+ // Oversized-SCHEMA guard (companion to the table-count guard above): a Table+ // solution whose summed column count exceeds maxSchemaAttrs. This fires at the+ // `maxSchemaSplitSolutions` ceiling — when MORE than that many independent+ // attr-heavy table clusters must share the capped number of split solutions, the+ // FFD packer's least-loaded fallback co-locates clusters and a bucket busts the+ // column cap. Without this, the overflow is silent (the table-count guard alone+ // misses it). attributeCount comes from estimate.tables[]; keys/lookups lowercased+ // (case-insensitive table names — see partitionBySchema).+ const attrByTable = new Map(+ (Array.isArray(estimate.tables) ? estimate.tables : [])+ .map((t) => [t && t.logicalName && t.logicalName.toLowerCase(), (t && t.attributeCount) || 0]),+ );+ const solutionSchemaAttrs = (s) =>+ (s.tableLogicalNames || []).reduce((sum, n) => sum + (attrByTable.get(String(n).toLowerCase()) || 0), 0);+ const oversizedAttrWarnings = proposedSolutions+ .filter((s) => Array.isArray(s.tableLogicalNames) && s.tableLogicalNames.length > 0 &&+ solutionSchemaAttrs(s) > config.thresholds.maxSchemaAttrs)+ .map((s) => ({+ type: 'warning',+ message: `Solution ${s.uniqueName} holds tables totaling ${solutionSchemaAttrs(s)} columns — above the ${config.thresholds.maxSchemaAttrs}-column per-solution cap. This happens when more than ${config.thresholds.maxSchemaSplitSolutions} independent attr-heavy table clusters must share the capped number of schema-split solutions. Consider raising maxSchemaSplitSolutions (or maxSchemaAttrs) in .alm-config.json, or denormalizing the widest tables.`,+ }));// Surface estimator-side truncation warnings as `recommendations[]` entries// so the rendered plan shows them inline. These get the `error` type because// a truncated input is more dangerous than a normal split-decision warning@@ -715,7 +844,9 @@ function computeSplitPlan({ estimate, config, meta }) {}));const recommendations = truncationRecs.concat(buildRecommendations(estimate, strategy, config))- .concat(splitWarnings);+ .concat(splitWarnings)+ .concat(oversizedClusterWarnings)+ .concat(oversizedAttrWarnings);const appliedStrategies = [strategy.primary];if (strategy.additive) appliedStrategies.push('strategy-4-config-isolation');diff --git a/plugins/power-pages/scripts/lib/discover-site-components.js b/plugins/power-pages/scripts/lib/discover-site-components.jsindex fdd1cf421..c774e14b5 100644--- a/plugins/power-pages/scripts/lib/discover-site-components.js+++ b/plugins/power-pages/scripts/lib/discover-site-components.js@@ -53,6 +53,8 @@'use strict';const helpers = require('./validation-helpers');+const { queryCustomUnmanagedTables } = require('./query-metadata');+const { collectReferencedEntityNames, scopeCustomTables } = require('./resolve-site-tables');/** Authoritative picklist labels for powerpagecomponenttype. */const PPC_TYPE_LABELS = Object.freeze({@@ -107,6 +109,8 @@ function parseArgs(argv) {siteId: null,publisherPrefix: null,solutionId: null,+ projectRoot: null,+ datamodelManifestPath: null,};for (let i = 0; i < args.length; i++) {if (args[i] === '--envUrl' && args[i + 1]) out.envUrl = args[++i];@@ -114,6 +118,8 @@ function parseArgs(argv) {else if (args[i] === '--siteId' && args[i + 1]) out.siteId = args[++i];else if (args[i] === '--publisherPrefix' && args[i + 1]) out.publisherPrefix = args[++i];else if (args[i] === '--solutionId' && args[i + 1]) out.solutionId = args[++i];+ else if (args[i] === '--projectRoot' && args[i + 1]) out.projectRoot = args[++i];+ else if (args[i] === '--datamodelManifest' && args[i + 1]) out.datamodelManifestPath = args[++i];}return out;}@@ -166,6 +172,8 @@ async function discoverSiteComponents({siteId,publisherPrefix = null,solutionId = null,+ projectRoot = null,+ datamodelManifestPath = null,makeRequest = helpers.makeRequest,} = {}) {if (!envUrl) throw new Error('--envUrl is required');@@ -232,10 +240,13 @@ async function discoverSiteComponents({? await discoverEnvVars({ baseUrl, token, publisherPrefix, makeRequest }): [];- // 5) Custom tables filtered by publisher prefix (optional)- const customTables = publisherPrefix- ? await discoverCustomTables({ baseUrl, token, publisherPrefix, makeRequest })- : [];+ // 5) Custom tables the SITE references (table permissions + datamodel manifest),+ // intersected with the env's custom-unmanaged tables. NOT a publisher-prefix+ // dump — that over-counted unrelated tables sharing the prefix (the+ // new_/default-publisher bug). Empty when no local signal is available.+ const customTables = await discoverCustomTables({+ baseUrl, token, projectRoot, datamodelManifestPath, makeRequest,+ });const result = {siteId,@@ -382,28 +393,27 @@ async function discoverEnvVars({ baseUrl, token, publisherPrefix, makeRequest })}));}-async function discoverCustomTables({ baseUrl, token, publisherPrefix, makeRequest }) {- // The $metadata/EntityDefinitions endpoint doesn't support `startswith` (0x8006088a),- // so we fetch all custom tables and filter client-side. Custom-entity sets are small- // enough that a single request is fine. MetadataId is included so callers can diff- // against solutioncomponents.objectid (componenttype 1 = Entity).- // publisherPrefix validated at the entry point of discoverSiteComponents.- const prefixLower = String(publisherPrefix).trim().toLowerCase();- const url =- `${baseUrl}/api/data/v9.2/EntityDefinitions` +- `?$filter=IsCustomEntity eq true` +- `&$select=LogicalName,SchemaName,DisplayName,MetadataId`;- const rows = await odataGetAll(url, token, makeRequest);- return rows- .filter((r) => (r.LogicalName || '').toLowerCase().startsWith(`${prefixLower}_`))- .map((r) => ({- id: r.MetadataId,- logicalName: r.LogicalName,- schemaName: r.SchemaName,- displayName:- (r.DisplayName && r.DisplayName.UserLocalizedLabel && r.DisplayName.UserLocalizedLabel.Label) ||- r.SchemaName,- }));+async function discoverCustomTables({ baseUrl, token, projectRoot, datamodelManifestPath, makeRequest }) {+ // Scope to the tables the SITE references (its table permissions + datamodel+ // manifest — SME-confirmed complete), intersected with the env's custom-unmanaged+ // tables. Replaces the old publisher-prefix dump that returned every table+ // sharing the prefix (catastrophic with `new_`/default publishers). MetadataId+ // is returned as `id` so callers can diff against solutioncomponents.objectid+ // (componenttype 1 = Entity).+ const { names, available } = collectReferencedEntityNames({ projectRoot, datamodelManifestPath });+ if (!available) return []; // no local signal — empty, NEVER a prefix dump+ let customUnmanaged = [];+ try {+ customUnmanaged = await queryCustomUnmanagedTables(baseUrl, token, makeRequest);+ } catch {+ customUnmanaged = [];+ }+ return scopeCustomTables(names, customUnmanaged).map((t) => ({+ id: t.metadataId,+ logicalName: t.logicalName,+ schemaName: t.schemaName,+ displayName: t.displayName,+ }));}if (require.main === module) {diff --git a/plugins/power-pages/scripts/lib/estimate-solution-size.js b/plugins/power-pages/scripts/lib/estimate-solution-size.jsindex f38a6e844..4a29b7cfe 100644--- a/plugins/power-pages/scripts/lib/estimate-solution-size.js+++ b/plugins/power-pages/scripts/lib/estimate-solution-size.js@@ -27,6 +27,9 @@const helpers = require('./validation-helpers');const { getAuthToken } = helpers;+const { queryCustomUnmanagedTables } = require('./query-metadata');+const { fetchTableRelationships } = require('./query-table-relationships');+const { collectReferencedEntityNames, scopeCustomTables } = require('./resolve-site-tables');// `makeRequest` is accessed via `helpers.makeRequest` (not destructured) so// tests can inject a mock by mutating `helpers.makeRequest` before calling// the top-level `estimateSolutionSize`. See estimate-solution-size.test.js for@@ -88,7 +91,11 @@ const ODATA_MAX_PAGE_SIZE = 5000;// not a normal-case truncation.const PAGINATION_SAFETY_CAP = 100;-async function odataGet(envUrl, path, token) {+// NB: this is the local path-based helper `odataGetPath(envUrl, path, token)` — it+// builds the v9.2 URL from a relative path. Distinct from validation-helpers.js's+// shared `odataGet(url, token, request)` (absolute URL, different arg order); the+// rename avoids a silent breakage if a future edit destructures the shared one here.+async function odataGetPath(envUrl, path, token) {const url = path.startsWith('http') ? path : `${envUrl}/api/data/v9.2/${path.replace(/^\//, '')}`;const res = await helpers.makeRequest({url,@@ -126,7 +133,7 @@ async function collectPaginated(envUrl, path, token, maxPages = PAGINATION_SAFETconst items = [];let pagesFetched = 0;for (let p = 0; p < maxPages && next; p++) {- const page = await odataGet(envUrl, next, token);+ const page = await odataGetPath(envUrl, next, token);if (Array.isArray(page.value)) items.push(...page.value);next = page['@odata.nextLink'] || null;pagesFetched += 1;@@ -256,7 +263,7 @@ async function countOData(envUrl, entity, filter, token) {try {const filterPart = filter ? `&$filter=${filter}` : '';const countPath = `${entity}?$count=true&$top=1${filterPart}`;- const page = await odataGet(envUrl, countPath, token);+ const page = await odataGetPath(envUrl, countPath, token);const n = page['@odata.count'];return typeof n === 'number' ? n : null;} catch {@@ -285,51 +292,99 @@ async function discoverPowerPageSiteLanguages(envUrl, websiteRecordId, token) {}}-async function discoverTables(envUrl, publisherPrefix, token, manifestPath) {- // Try manifest first- const fs = require('fs');- let manifestTables = [];- if (manifestPath && fs.existsSync(manifestPath)) {- try {- const man = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));- const entries = man.entities || man.tables || [];- manifestTables = entries.map((e) => ({- logicalName: e.logicalName || e.LogicalName || e.name,- metadataId: e.metadataId || e.MetadataId,- }));- } catch {}+// Discovers the custom tables the SITE actually references — NOT every table+// sharing the publisher prefix. The old prefix-wide enumeration over-counted+// catastrophically with a shared/default publisher (`new_`, env default): a+// 6-table site reported 22 tables, which cascaded into absurd schema splits.+//+// Source of truth = the site's table permissions (+ datamodel manifest), per+// SME: "If a table is used in the site there will be permissions for it."+// We intersect those referenced names with the env's custom-unmanaged tables so+// standard tables (contact/annotation) and managed template tables drop out.+//+// Returns `{ tables, tableCountScope }` where scope ∈+// "site-referenced" | "manifest-only" | "unavailable".+// On no local signal we return zero tables (NEVER a prefix dump) so a missing+// `.powerpages-site/` degrades safe instead of inflating the plan.+async function discoverTables(envUrl, token, { projectRoot, datamodelManifestPath } = {}) {+ let customUnmanaged = [];+ try {+ customUnmanaged = await queryCustomUnmanagedTables(envUrl, token);+ } catch {+ customUnmanaged = [];}- // Query EntityDefinitions for custom unmanaged tables.- // Verified 2026-04-22 against org1e98cc97 (v9.2): EntityDefinitions does NOT- // support `$top` (returns 400 "The query parameter $top is not supported").- // We filter server-side to IsCustomEntity=true to keep the payload bounded —- // there's still no client-side pagination needed for typical tenants.- const path =- `EntityDefinitions` +- `?$filter=IsCustomEntity eq true` +- `&$select=LogicalName,MetadataId,IsManaged,IsCustomEntity`;- const all = await collectPaginated(envUrl, path, token, 10);- const custom = all.filter((e) => e.IsCustomEntity === true && e.IsManaged === false);- const matchingPrefix = publisherPrefix- ? custom.filter((e) => (e.LogicalName || '').toLowerCase().startsWith(`${publisherPrefix.toLowerCase()}_`))- : custom;+ const { names, available, sources } = collectReferencedEntityNames({ projectRoot, datamodelManifestPath });++ let scope;+ let scoped = [];+ if (!available) {+ scope = 'unavailable';+ } else {+ scoped = scopeCustomTables(names, customUnmanaged);+ scope = sources.tablePermissions > 0 ? 'site-referenced' : 'manifest-only';+ }const byName = new Map();- for (const t of [...manifestTables, ...matchingPrefix.map((e) => ({- logicalName: e.LogicalName,- metadataId: e.MetadataId,- }))]) {- if (t.logicalName && !byName.has(t.logicalName)) byName.set(t.logicalName, t);+ for (const t of scoped) {+ if (t.logicalName && !byName.has(t.logicalName)) {+ byName.set(t.logicalName, { logicalName: t.logicalName, metadataId: t.metadataId });+ }}- return Array.from(byName.values());+ return { tables: Array.from(byName.values()), tableCountScope: scope };+}++// Build the deduped, scoped dependency-edge list among the site's tables.+// Each edge `[a, b]` (lowercased logical names, a<b) means tables a and b are+// connected by a lookup (OneToMany) or N:N (ManyToMany) — so the schema-split+// clustering keeps them in the same solution. Only edges where BOTH ends are in+// the scoped table set are kept. Per-table fetch errors are non-fatal.+async function discoverTableRelationships(envUrl, tables, token) {+ if (!Array.isArray(tables) || tables.length < 2) return [];+ const inSet = new Set(tables.map((t) => (t.logicalName || '').toLowerCase()).filter(Boolean));+ const seen = new Set();+ const edges = [];+ const addEdge = (x, y) => {+ const a = String(x || '').toLowerCase();+ const b = String(y || '').toLowerCase();+ if (!a || !b || a === b || !inSet.has(a) || !inSet.has(b)) return;+ const key = a < b ? `${a}|${b}` : `${b}|${a}`;+ if (seen.has(key)) return;+ seen.add(key);+ edges.push(a < b ? [a, b] : [b, a]);+ };+ // Fetch each table's relationships with BOUNDED CONCURRENCY (~2 OData calls per+ // table; a 34-table site is 68 round-trips — serial is slow at plan time). Edge+ // assembly stays sequential, in table order, so dedup is deterministic.+ const CONCURRENCY = 5;+ const results = new Array(tables.length).fill(null);+ let nextIdx = 0;+ async function worker() {+ while (nextIdx < tables.length) {+ const i = nextIdx++;+ try {+ results[i] = await fetchTableRelationships(envUrl, tables[i].logicalName, token);+ } catch {+ results[i] = null; // inaccessible table — skip its edges+ }+ }+ }+ await Promise.all(+ Array.from({ length: Math.min(CONCURRENCY, tables.length) }, () => worker()),+ );+ for (const rel of results) {+ if (!rel) continue;+ for (const e of rel.oneToMany) addEdge(e.referencedEntity, e.referencingEntity);+ for (const e of rel.manyToMany) addEdge(e.entity1, e.entity2);+ }+ return edges;}async function countAttributesForTables(envUrl, tables, token) {let total = 0;for (const t of tables) {try {- const page = await odataGet(+ const page = await odataGetPath(envUrl,`EntityDefinitions(LogicalName='${t.logicalName}')/Attributes?$select=LogicalName&$top=1000`,token,@@ -436,7 +491,7 @@ function classifyPPCs(ppcs) {}async function measureWebFiles(envUrl, webFiles, token) {- // Uses odataGet directly (single-row fetch each, no pagination needed).+ // Uses odataGetPath directly (single-row fetch each, no pagination needed).const individual = [];let aggregateBytes = 0;let imgOrFontBytes = 0;@@ -444,7 +499,7 @@ async function measureWebFiles(envUrl, webFiles, token) {for (const wf of webFiles) {const id = wf.powerpagecomponentid;try {- const rec = await odataGet(+ const rec = await odataGetPath(envUrl,`powerpagecomponents(${id})?$select=name,powerpagecomponentid,content`,token,@@ -712,8 +767,14 @@ async function estimateSolutionSize({ envUrl, websiteRecordId, token, publisherP// (which includes them under componenttype 10428).const siteLanguages = await discoverPowerPageSiteLanguages(envUrl, websiteRecordId, resolved);- const tables = await discoverTables(envUrl, publisherPrefix, resolved, datamodelManifest);+ const { tables, tableCountScope } = await discoverTables(envUrl, resolved, {+ projectRoot,+ datamodelManifestPath: datamodelManifest,+ });const schemaAttrCount = await countAttributesForTables(envUrl, tables, resolved);+ // Dependency edges among the scoped tables — drives the schema-split clustering+ // so related tables ship in the same solution (never split a relationship).+ const tableRelationships = await discoverTableRelationships(envUrl, tables, resolved);// Tenant-wide env var defs matching the publisher prefix. This is the// fallback used when no solution is set up yet (fresh project); for sites@@ -935,7 +996,7 @@ async function estimateSolutionSize({ envUrl, websiteRecordId, token, publisherPconst LEGACY_BOUNDARIES = [500, 1000, 2000];if (LEGACY_BOUNDARIES.includes(ppcs.length)) {truncationWarnings.push(- `ppcs.length is exactly ${ppcs.length} — a historical paging boundary from an older $top value. Suggests the \`Prefer: odata.maxpagesize\` header has regressed; verify odataGet still sends it.`,+ `ppcs.length is exactly ${ppcs.length} — a historical paging boundary from an older $top value. Suggests the \`Prefer: odata.maxpagesize\` header has regressed; verify odataGetPath still sends it.`,);}@@ -1024,6 +1085,10 @@ async function estimateSolutionSize({ envUrl, websiteRecordId, token, publisherP}: null,tableCount: tables.length,+ // How the table set was scoped: "site-referenced" (table permissions),+ // "manifest-only" (datamodel manifest, no permissions), or "unavailable"+ // (no local signal — tableCount reflects 0, NOT a publisher-prefix dump).+ tableCountScope,schemaAttrCount,webFilesAggregateMB: round1(webFilesAggregateBytes / (1024 * 1024)),webFilesIndividual: webMeasure.individual,@@ -1059,6 +1124,9 @@ async function estimateSolutionSize({ envUrl, websiteRecordId, token, publisherPmediaRatio: Math.round(webMeasure.mediaRatio * 100) / 100,siteType: 'code-site',tables: tables.map((t) => ({ logicalName: t.logicalName, attributeCount: t.attributeCount || 0 })),+ // Dependency edges among the scoped tables ([a,b], lowercased, a<b) — consumed+ // by compute-split-plan.js to cluster related tables into the same solution.+ tableRelationships,breakdown: {tables: round1((tables.length * BYTES_PER.table + schemaAttrCount * BYTES_PER.attribute) / (1024 * 1024)),webFiles: round1(webFilesAggregateBytes / (1024 * 1024)),diff --git a/plugins/power-pages/scripts/lib/query-metadata.js b/plugins/power-pages/scripts/lib/query-metadata.jsnew file mode 100644index 000000000..9dc01e224--- /dev/null+++ b/plugins/power-pages/scripts/lib/query-metadata.js@@ -0,0 +1,44 @@+#!/usr/bin/env node++// Shared Dataverse metadata queries (EntityDefinitions). Single source of truth+// for "list the environment's custom unmanaged tables" — previously duplicated+// in estimate-solution-size.js, discover-site-components.js, and inline in the+// setup-solution skill prose. All three now go through this helper.++'use strict';++const helpers = require('./validation-helpers');++/**+ * Lists every CUSTOM, UNMANAGED table in the environment.+ *+ * Note: `EntityDefinitions` does not support `$top`, but it does paginate via+ * `@odata.nextLink`, so we use the shared `odataGetAll`. `IsCustomEntity` is+ * filtered server-side; `IsManaged` is filtered client-side (the metadata+ * `$filter` grammar is limited).+ *+ * @param {string} envUrl - environment base URL+ * @param {string} token - bearer token+ * @param {Function} [request=helpers.makeRequest] - injectable for tests+ * @returns {Promise<{ logicalName: string, metadataId: string, schemaName: string, displayName: string }[]>}+ */+async function queryCustomUnmanagedTables(envUrl, token, request = helpers.makeRequest) {+ const base = String(envUrl).replace(/\/+$/, '');+ const url =+ `${base}/api/data/v9.2/EntityDefinitions` ++ `?$filter=IsCustomEntity eq true` ++ `&$select=LogicalName,MetadataId,SchemaName,DisplayName,IsManaged,IsCustomEntity`;+ const rows = await helpers.odataGetAll(url, token, request);+ return rows+ .filter((e) => e && e.IsCustomEntity === true && e.IsManaged === false)+ .map((e) => ({+ logicalName: e.LogicalName,+ metadataId: e.MetadataId,+ schemaName: e.SchemaName,+ displayName:+ (e.DisplayName && e.DisplayName.UserLocalizedLabel && e.DisplayName.UserLocalizedLabel.Label) ||+ e.SchemaName,+ }));+}++module.exports = { queryCustomUnmanagedTables };diff --git a/plugins/power-pages/scripts/lib/query-table-relationships.js b/plugins/power-pages/scripts/lib/query-table-relationships.jsnew file mode 100644index 000000000..11850f171--- /dev/null+++ b/plugins/power-pages/scripts/lib/query-table-relationships.js@@ -0,0 +1,65 @@+#!/usr/bin/env node++// Shared Dataverse relationship queries for a table: lookups (OneToMany) + N:N+// (ManyToMany). Extracted from skills/audit-permissions/scripts/query-table-relationships.js+// so it can be require()d (that file is a self-executing CLI). The CLI is now a+// thin wrapper over this module. Used by:+// - estimate-solution-size.js — to build the dependency graph for the+// schema-split clustering (so related tables ship in the same solution).+// - audit-permissions — to validate contact/account/parent relationship scopes.++'use strict';++const helpers = require('./validation-helpers');++/**+ * Fetches OneToMany (lookup-backed) and ManyToMany relationships for a table.+ *+ * OneToMany errors propagate (a genuinely missing/inaccessible table is a real+ * error the CLI surfaces via exit 1; the estimator wraps the call per-table for+ * resilience). ManyToMany is best-effort — many tables/envs have no N:N and the+ * navigation property can be finicky — so its errors are swallowed to `[]`.+ *+ * @param {string} envUrl - environment base URL+ * @param {string} table - table logical name+ * @param {string} token - bearer token+ * @param {Function} [request=helpers.makeRequest] - injectable for tests+ * @returns {Promise<{+ * oneToMany: { schemaName, referencedEntity, referencingEntity, referencingAttribute }[],+ * manyToMany: { schemaName, entity1, entity2 }[]+ * }>}+ */+async function fetchTableRelationships(envUrl, table, token, request = helpers.makeRequest) {+ const base = String(envUrl).replace(/\/+$/, '');+ const safe = String(table).replace(/'/g, "''");++ const o2mUrl =+ `${base}/api/data/v9.2/EntityDefinitions(LogicalName='${safe}')/OneToManyRelationships` ++ `?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute`;+ const o2mRows = await helpers.odataGetAll(o2mUrl, token, request);+ const oneToMany = o2mRows.map((r) => ({+ schemaName: r.SchemaName,+ referencedEntity: r.ReferencedEntity,+ referencingEntity: r.ReferencingEntity,+ referencingAttribute: r.ReferencingAttribute,+ }));++ let manyToMany = [];+ try {+ const m2mUrl =+ `${base}/api/data/v9.2/EntityDefinitions(LogicalName='${safe}')/ManyToManyRelationships` ++ `?$select=SchemaName,Entity1LogicalName,Entity2LogicalName`;+ const m2mRows = await helpers.odataGetAll(m2mUrl, token, request);+ manyToMany = m2mRows.map((r) => ({+ schemaName: r.SchemaName,+ entity1: r.Entity1LogicalName,+ entity2: r.Entity2LogicalName,+ }));+ } catch {+ // N:N unavailable for this table/env — best-effort, leave empty.+ }++ return { oneToMany, manyToMany };+}++module.exports = { fetchTableRelationships };diff --git a/plugins/power-pages/scripts/lib/resolve-site-tables.js b/plugins/power-pages/scripts/lib/resolve-site-tables.jsnew file mode 100644index 000000000..e58ce46ec--- /dev/null+++ b/plugins/power-pages/scripts/lib/resolve-site-tables.js@@ -0,0 +1,110 @@+#!/usr/bin/env node++// Resolves the custom Dataverse tables a Power Pages site ACTUALLY references,+// so ALM table discovery stops scooping up every table that merely shares the+// publisher prefix (the `new_` / default-publisher over-count bug).+//+// SME-confirmed source of truth: "We rely on Table permissions from the site.+// If a table is used in the site that means there will be permissions for it."+// So the site's table permissions (+ the datamodel manifest) are the complete+// list of tables the site uses — no need to also scan forms/lists.+//+// Two steps, kept separate so the Dataverse query (custom-unmanaged tables) can+// be supplied by the caller (estimate-solution-size.js / discover-site-components.js):+// 1. collectReferencedEntityNames({ projectRoot, datamodelManifestPath })+// -> the set of entity logical names the site references (local read).+// 2. scopeCustomTables(referencedNames, customUnmanagedTables)+// -> the caller's custom-unmanaged table list, intersected with that set.+//+// Intersecting with custom-UNMANAGED tables drops standard tables (contact,+// annotation) and managed template tables — leaving exactly the tables the+// user's solution would own.++'use strict';++const fs = require('fs');+const path = require('path');+const { loadTablePermissions } = require('./powerpages-config');++/**+ * Collects the entity logical names referenced by the site's table permissions+ * and its datamodel manifest (both local reads; no Dataverse).+ *+ * @param {object} opts+ * @param {string} [opts.projectRoot] - site project root (contains .powerpages-site/)+ * @param {string} [opts.datamodelManifestPath] - explicit manifest path (defaults to+ * `<projectRoot>/.datamodel-manifest.json`)+ * @returns {{ names: Set<string>, available: boolean, sources: { tablePermissions: number, manifest: number } }}+ * `names` are lowercased. `available` is false only when neither a+ * `.powerpages-site/table-permissions/` directory nor a manifest was found.+ */+function collectReferencedEntityNames({ projectRoot, datamodelManifestPath } = {}) {+ const names = new Set();+ const sources = { tablePermissions: 0, manifest: 0 };+ let sawTablePermissionsDir = false;+ let sawManifest = false;++ // 1. Table permissions — `entitylogicalname` per `*.tablepermission.yml`.+ if (projectRoot) {+ const dir = path.join(projectRoot, '.powerpages-site', 'table-permissions');+ if (fs.existsSync(dir)) {+ sawTablePermissionsDir = true;+ // Count the permission FILES present — `sources.tablePermissions` must mean+ // "the site has table-permission files" (a reliable site-referenced signal,+ // consumed by `tableCountScope`), NOT "we parsed at least one record". A+ // temporarily-malformed file must not make a real site look manifest-only.+ try {+ sources.tablePermissions = fs.readdirSync(dir)+ .filter((f) => /\.tablepermission\.yml$/i.test(f)).length;+ } catch { /* keep 0 */ }+ let records = [];+ try { records = loadTablePermissions(dir); } catch { records = []; }+ for (const r of records) {+ const name = r && r.entitylogicalname; // NOT entityname (that's the display label)+ if (typeof name === 'string' && name.trim()) {+ names.add(name.trim().toLowerCase());+ }+ }+ }+ }++ // 2. Datamodel manifest — tables created for this site by setup-datamodel.+ const manifestPath = datamodelManifestPath ||+ (projectRoot ? path.join(projectRoot, '.datamodel-manifest.json') : null);+ if (manifestPath && fs.existsSync(manifestPath)) {+ sawManifest = true;+ try {+ const man = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ const entries = man.entities || man.tables || [];+ for (const e of entries) {+ const name = e && (e.logicalName || e.LogicalName || e.name);+ if (typeof name === 'string' && name.trim()) {+ names.add(name.trim().toLowerCase());+ sources.manifest += 1;+ }+ }+ } catch {+ // Malformed manifest — ignore its contents but still count it as a signal.+ }+ }++ return { names, available: sawTablePermissionsDir || sawManifest, sources };+}++/**+ * Intersects the caller's custom-unmanaged table list with the referenced-name+ * set. Returns the tables the site actually uses (and that the user's solution+ * would own).+ *+ * @param {Set<string>} referencedNames - lowercased logical names (from collectReferencedEntityNames)+ * @param {{ logicalName: string }[]} customUnmanagedTables+ * @returns {{ logicalName: string }[]}+ */+function scopeCustomTables(referencedNames, customUnmanagedTables) {+ if (!referencedNames || referencedNames.size === 0) return [];+ return (customUnmanagedTables || []).filter(+ (t) => t && typeof t.logicalName === 'string' && referencedNames.has(t.logicalName.toLowerCase()),+ );+}++module.exports = { collectReferencedEntityNames, scopeCustomTables };diff --git a/plugins/power-pages/scripts/lib/validation-helpers.js b/plugins/power-pages/scripts/lib/validation-helpers.jsindex 28037792e..b9a097ee5 100644--- a/plugins/power-pages/scripts/lib/validation-helpers.js+++ b/plugins/power-pages/scripts/lib/validation-helpers.js@@ -236,6 +236,64 @@ function makeRequest({ url, method = 'GET', headers = {}, body = null, includeHe});}+/**+ * Single Dataverse OData GET (v9.2 headers, `Prefer: odata.maxpagesize=5000`),+ * throws on non-2xx. `url` is absolute — pass an `@odata.nextLink` straight back in.+ * @param {string} url - absolute URL+ * @param {string} token - bearer token+ * @param {Function} [request=makeRequest] - injectable for tests+ * @returns {Promise<object>} parsed JSON body+ */+async function odataGet(url, token, request = makeRequest) {+ const res = await request({+ url,+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: 'application/json',+ 'OData-MaxVersion': '4.0',+ 'OData-Version': '4.0',+ Prefer: 'odata.maxpagesize=5000',+ },+ timeout: 30000,+ });+ if (res.error) throw new Error(`OData request failed: ${res.error}`);+ if (res.statusCode < 200 || res.statusCode >= 300) {+ throw new Error(`HTTP ${res.statusCode} from ${url}: ${(res.body || '').slice(0, 400)}`);+ }+ return JSON.parse(res.body);+}++/**+ * Follows `@odata.nextLink`, aggregating every page's `value[]` into one array.+ * `maxPages` is a runaway-loop safety cap (100 × 5000 ≈ 500K rows). FAILS CLOSED:+ * if the cap is reached while `@odata.nextLink` is still present, throws rather than+ * silently returning a truncated set — a partial result would produce wrong+ * table/env-var counts for ALM sizing/splitting with no signal. Callers that want+ * partial results must catch and downgrade accuracy intentionally.+ * @param {string} url - absolute starting URL+ * @param {string} token - bearer token+ * @param {Function} [request=makeRequest] - injectable for tests+ * @param {number} [maxPages=100]+ * @returns {Promise<object[]>}+ */+async function odataGetAll(url, token, request = makeRequest, maxPages = 100) {+ const out = [];+ let next = url;+ let p = 0;+ for (; p < maxPages && next; p++) {+ const page = await odataGet(next, token, request);+ if (Array.isArray(page.value)) out.push(...page.value);+ next = page['@odata.nextLink'] || null;+ }+ if (next) {+ throw new Error(+ `odataGetAll hit the ${maxPages}-page cap with @odata.nextLink still present ` ++ `(${out.length} rows so far) — result would be truncated. Raise maxPages or narrow the query.`,+ );+ }+ return out;+}+/** Cloud → Power Platform API base URL mapping */const CLOUD_TO_API = {'Public': 'https://api.powerplatform.com',@@ -265,6 +323,8 @@ module.exports = {UUID_REGEX,getAuthToken,makeRequest,+ odataGet,+ odataGetAll,getEnvironmentUrl,getPacAuthInfo,CLOUD_TO_API,diff --git a/plugins/power-pages/scripts/tests/compute-split-plan.test.js b/plugins/power-pages/scripts/tests/compute-split-plan.test.jsindex 8fda1569b..635b93d32 100644--- a/plugins/power-pages/scripts/tests/compute-split-plan.test.js+++ b/plugins/power-pages/scripts/tests/compute-split-plan.test.js@@ -183,23 +183,121 @@ test('computeSplitPlan Strategy 3 uses explicit config.domains when present', ()assert.equal(result.proposedSolutions[3].isFutureBuffer, true);});-test('computeSplitPlan Strategy 3 falls back to prefix heuristic when no domains configured', () => {+test('computeSplitPlan Strategy 3 packs tables by capacity (no domains configured) — bounded, not per-table', () => {const result = computeSplitPlan({estimate: baseEstimate({tableCount: 22,- schemaAttrCount: 16000,+ schemaAttrCount: 16000, // > maxSchemaAttrs(15000) -> 2 buckets by attrstables: [- { logicalName: 'tst_product' },- { logicalName: 'tst_productVariant' },- { logicalName: 'tst_order' },- { logicalName: 'tst_orderLine' },+ { logicalName: 'tst_product', attributeCount: 4000 },+ { logicalName: 'tst_productVariant', attributeCount: 4000 },+ { logicalName: 'tst_order', attributeCount: 4000 },+ { logicalName: 'tst_orderLine', attributeCount: 4000 },],}),config: baseConfig(),meta: { baseName: 'Test', siteName: 'Test Site' },});assert.equal(result.splitStrategy, 'strategy-3-schema-segmentation');- assert.ok(result.proposedSolutions.length >= 2);+ const tableSolutions = result.proposedSolutions.filter(+ (s) => Array.isArray(s.componentTypes) && s.componentTypes.length === 1 && s.componentTypes[0] === 'Table',+ );+ assert.equal(tableSolutions.length, 2, '16000 attrs / 15000 cap -> 2 Table solutions, not one-per-table');+});++test('computeSplitPlan Strategy 3 never overflows the attr cap when independent clusters fragment', () => {+ // Regression for the FFD under-allocation bug: 4 INDEPENDENT (no-edge) tables of+ // 8000 attrs each = 32000 total. Seeding the packer from the lower bound+ // ceil(32000/15000)=3 gave only 3 bins, so the 4th cluster fell into the+ // least-loaded bucket -> 16000 attrs (> 15000 cap), unwarned. The packer must+ // instead open a 4th bin (clusters.length permits it) so no bucket busts the cap.+ const result = computeSplitPlan({+ estimate: baseEstimate({+ tableCount: 4,+ schemaAttrCount: 32000,+ tables: [+ { logicalName: 'tst_alpha', attributeCount: 8000 },+ { logicalName: 'tst_beta', attributeCount: 8000 },+ { logicalName: 'tst_gamma', attributeCount: 8000 },+ { logicalName: 'tst_delta', attributeCount: 8000 },+ ],+ tableRelationships: [], // no edges -> 4 singleton clusters+ }),+ config: baseConfig(),+ meta: { baseName: 'Test', siteName: 'Test Site' },+ });+ assert.equal(result.splitStrategy, 'strategy-3-schema-segmentation');+ const tableSolutions = result.proposedSolutions.filter(+ (s) => Array.isArray(s.componentTypes) && s.componentTypes.length === 1 && s.componentTypes[0] === 'Table',+ );+ // 4 independent 8000-attr tables -> 4 single-table solutions (each 8000 < 15000),+ // NOT 3 with one 16000-attr overflow bucket.+ assert.equal(tableSolutions.length, 4, '4 independent 8000-attr tables -> 4 Table solutions (no attr-cap overflow)');+ for (const s of tableSolutions) {+ assert.equal(s.tableLogicalNames.length, 1, `${s.uniqueName} must hold exactly one table — no bucket over the attr cap`);+ }+});++test('computeSplitPlan WARNS when >maxSchemaSplitSolutions independent attr-heavy clusters bust the attr cap (ceiling boundary)', () => {+ // 9 INDEPENDENT (no-edge) 14000-attr tables, ceiling=8: the packer can open at+ // most 8 buckets, so FFD's least-loaded fallback co-locates 2 tables in one+ // solution -> 28000 attrs > maxSchemaAttrs(15000). The table-count guard misses+ // it (each solution has <=2 tables, well under maxTableCount). The attr guard+ // must surface it. (Regression for the ceiling-boundary silent overflow.)+ const tables = Array.from({ length: 9 }, (_, i) => ({ logicalName: `tst_t${i}`, attributeCount: 14000 }));+ const result = computeSplitPlan({+ estimate: baseEstimate({ tableCount: 9, schemaAttrCount: 9 * 14000, tables, tableRelationships: [] }),+ config: baseConfig(),+ meta: { baseName: 'Test', siteName: 'Test Site' },+ });+ assert.equal(result.splitStrategy, 'strategy-3-schema-segmentation');+ const attrWarn = (result.recommendations || []).find((r) => /columns — above the .* per-solution cap/i.test(r.message || ''));+ assert.ok(attrWarn, 'expected an oversized-schema (attr-cap) warning when a Table solution exceeds maxSchemaAttrs at the ceiling');+});++test('computeSplitPlan: a Table domain componentCount is a schema-component proxy (sum attrs + 1/table), not the table count', () => {+ // Counting 1-per-table severely undercounts solution components and can let an+ // over-cap solution slip past validateSplits. Proxy = sum(attributeCount) + 1/table.+ const result = computeSplitPlan({+ // tableCount:34 makes the schema "red" so Strategy 3 fires; the proxy reads the+ // per-table attributeCount from tables[] (500 + 300), independent of the global count.+ estimate: baseEstimate({+ tableCount: 34,+ schemaAttrCount: 32000,+ tables: [+ { logicalName: 'tst_product', attributeCount: 500 },+ { logicalName: 'tst_category', attributeCount: 300 },+ ],+ }),+ config: baseConfig({ domains: [{ name: 'Catalog', tableLogicalNames: ['tst_product', 'tst_category'] }] }),+ meta: { baseName: 'Test', siteName: 'Test Site' },+ });+ assert.equal(result.splitStrategy, 'strategy-3-schema-segmentation');+ const catalog = result.proposedSolutions.find((s) => s.uniqueName === 'Test_Catalog');+ assert.ok(catalog, 'Catalog Table domain solution exists');+ assert.equal(catalog.componentCount, 802, 'sum(500+300) + 2 tables = 802 (proxy), not 2 (table count)');+});++test('computeSplitPlan: schema-component proxy + attr-cap guard are CASE-INSENSITIVE on table names', () => {+ // estimate.tables carry Dataverse LogicalName casing (e.g. bp_Inspection), but a+ // user-authored .alm-config.json domain may list them in another case. The proxy+ // (and the attr-cap guard) must match case-insensitively — otherwise the lookups+ // miss, attrs read as 0, and the count collapses to the bare table count.+ const result = computeSplitPlan({+ estimate: baseEstimate({+ tableCount: 34,+ schemaAttrCount: 32000,+ tables: [+ { logicalName: 'bp_Inspection', attributeCount: 500 }, // Dataverse casing+ { logicalName: 'bp_Permit', attributeCount: 300 },+ ],+ }),+ config: baseConfig({ domains: [{ name: 'Core', tableLogicalNames: ['bp_inspection', 'bp_permit'] }] }), // lower-case+ meta: { baseName: 'Test', siteName: 'Test Site' },+ });+ const core = result.proposedSolutions.find((s) => s.uniqueName === 'Test_Core');+ assert.ok(core, 'Core domain solution exists');+ assert.equal(core.componentCount, 802, 'case-insensitive proxy: 500+300+2 = 802, not 2 (missed lookups)');});test('computeSplitPlan additive Strategy 4 prepends EnvVars solution', () => {@@ -601,3 +699,87 @@ test('partitionBySchema uses breakdown.tables to size domain solutions', () => {// Site solution absorbs the remainderassert.equal(solutions[2].sizeMB, 60);});++// --- dependency-aware capacity packing (the "21 solutions" fix) --------------++function makeTables(n, attrsEach, prefix = 'tbl') {+ return Array.from({ length: n }, (_, i) => ({ logicalName: `${prefix}_${i}`, attributeCount: attrsEach }));+}++test('Strategy 3: 34 distinct tables / 32.3k cols -> a HANDFUL of solutions, never ~34', () => {+ const tables = makeTables(34, 950); // 34 * 950 = 32300+ const result = computeSplitPlan({+ estimate: baseEstimate({ totalSizeMB: 68, tableCount: 34, schemaAttrCount: 32300, componentCountSiteTotal: 3000, tables, tableRelationships: [] }),+ config: baseConfig(),+ meta: { baseName: 'Big', siteName: 'Big Site' },+ });+ assert.equal(result.splitStrategy, 'strategy-3-schema-segmentation');+ const tableSolutions = result.proposedSolutions.filter((s) => s.componentTypes && s.componentTypes[0] === 'Table' && s.componentTypes.length === 1);+ assert.ok(tableSolutions.length >= 2 && tableSolutions.length <= 8, `expected a handful of Table solutions, got ${tableSolutions.length}`);+ // Every Table solution stays under the per-solution table cap.+ for (const s of tableSolutions) {+ assert.ok(s.tableLogicalNames.length <= 20, `Table solution ${s.uniqueName} has ${s.tableLogicalNames.length} tables (> cap)`);+ }+ // All 34 tables are placed exactly once across the Table solutions.+ const placed = tableSolutions.flatMap((s) => s.tableLogicalNames);+ assert.equal(placed.length, 34);+ assert.equal(new Set(placed).size, 34);+});++test('Strategy 3: 22 tables with low cols -> 2 Table solutions (count-driven), not 22', () => {+ const tables = makeTables(22, 50);+ const result = computeSplitPlan({+ estimate: baseEstimate({ tableCount: 22, schemaAttrCount: 1100, tables, tableRelationships: [] }),+ config: baseConfig(),+ meta: { baseName: 'M', siteName: 'M' },+ });+ assert.equal(result.splitStrategy, 'strategy-3-schema-segmentation');+ const tableSolutions = result.proposedSolutions.filter((s) => s.componentTypes && s.componentTypes[0] === 'Table' && s.componentTypes.length === 1);+ assert.equal(tableSolutions.length, 2, '22 tables / 20-per-solution -> 2 Table solutions');+});++test('Strategy 3 does NOT trigger for <=20 tables with low cols -> single', () => {+ const tables = makeTables(18, 50);+ const { primary } = selectStrategy(baseEstimate({ tableCount: 18, schemaAttrCount: 900, tables }), baseConfig());+ assert.equal(primary, 'single');+});++test('Strategy 3: dependency clusters are never split across solutions', () => {+ // Cluster A (4 tables) + Cluster B (2 tables) + 20 standalone = 26 tables, low cols.+ const clusterA = ['rel_a0', 'rel_a1', 'rel_a2', 'rel_a3'];+ const clusterB = ['rel_b0', 'rel_b1'];+ const standalone = makeTables(20, 50, 'solo').map((t) => t.logicalName);+ const tables = [...clusterA, ...clusterB, ...standalone].map((n) => ({ logicalName: n, attributeCount: 50 }));+ const edges = [+ ['rel_a0', 'rel_a1'], ['rel_a1', 'rel_a2'], ['rel_a2', 'rel_a3'], // A connected+ ['rel_b0', 'rel_b1'], // B connected+ ];+ const result = computeSplitPlan({+ estimate: baseEstimate({ tableCount: 26, schemaAttrCount: 1300, tables, tableRelationships: edges }),+ config: baseConfig(),+ meta: { baseName: 'Dep', siteName: 'Dep' },+ });+ assert.equal(result.splitStrategy, 'strategy-3-schema-segmentation');+ const tableSolutions = result.proposedSolutions.filter((s) => s.componentTypes && s.componentTypes[0] === 'Table' && s.componentTypes.length === 1);+ const home = (name) => tableSolutions.findIndex((s) => s.tableLogicalNames.includes(name));+ // Every table in cluster A shares one solution; same for B.+ assert.ok(home('rel_a0') !== -1);+ assert.ok(clusterA.every((n) => home(n) === home('rel_a0')), 'cluster A must not be split across solutions');+ assert.ok(clusterB.every((n) => home(n) === home('rel_b0')), 'cluster B must not be split across solutions');+});++test('Strategy 3: an oversized single cluster (>cap) stays whole + raises a warning', () => {+ // 25 tables all chained into ONE connected cluster -> cannot be split.+ const names = makeTables(25, 50, 'big').map((t) => t.logicalName);+ const tables = names.map((n) => ({ logicalName: n, attributeCount: 50 }));+ const edges = names.slice(1).map((n, i) => [names[i], n]); // chain a0-a1-a2-...-a24+ const result = computeSplitPlan({+ estimate: baseEstimate({ tableCount: 25, schemaAttrCount: 1250, tables, tableRelationships: edges }),+ config: baseConfig(),+ meta: { baseName: 'Mega', siteName: 'Mega' },+ });+ const tableSolutions = result.proposedSolutions.filter((s) => s.componentTypes && s.componentTypes[0] === 'Table' && s.componentTypes.length === 1);+ assert.equal(tableSolutions.length, 1, 'one indivisible cluster -> one Table solution');+ assert.equal(tableSolutions[0].tableLogicalNames.length, 25);+ assert.ok(result.recommendations.some((r) => /dependency cluster that cannot be split/.test(r.message)), 'oversized-cluster warning must fire');+});diff --git a/plugins/power-pages/scripts/tests/discover-site-components.test.js b/plugins/power-pages/scripts/tests/discover-site-components.test.jsindex 320c89289..47ea7328e 100644--- a/plugins/power-pages/scripts/tests/discover-site-components.test.js+++ b/plugins/power-pages/scripts/tests/discover-site-components.test.js@@ -2,6 +2,9 @@const test = require('node:test');const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');const {discoverSiteComponents,@@ -9,6 +12,21 @@ const {PPC_DEFAULT_INCLUDE,} = require('../lib/discover-site-components');+// Creates a temp site root whose `.powerpages-site/table-permissions/` references+// the given entity logical names — the SME-confirmed signal for "tables the site+// uses" that now scopes custom-table discovery (replacing the publisher-prefix dump).+function tempSiteWithTablePermissions(t, entityLogicalNames) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dsc-site-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const dir = path.join(root, '.powerpages-site', 'table-permissions');+ fs.mkdirSync(dir, { recursive: true });+ entityLogicalNames.forEach((entity, i) => {+ fs.writeFileSync(path.join(dir, `perm-${i}.tablepermission.yml`),+ `adx_entitypermission_webrole:\n- ad89f5ee-8665-f111-a826-6045bd00fdda\nentitylogicalname: ${entity}\nentityname: Perm ${i}\nid: f03fefed-8665-f111-a826-000d3a597e6a\nscope: 756150000\n`);+ });+ return root;+}+/*** Creates a fake `makeRequest` that matches URL fragments to response bodies.* Each entry is `[urlFragment, responseObject]`; the first matching entry wins.@@ -169,7 +187,7 @@ test('computes missing[] diff against an existing solution', async () => {);});-test('diffs custom tables by MetadataId against solutioncomponents.objectid', async () => {+test('diffs custom tables by MetadataId against solutioncomponents.objectid', async (t) => {const makeRequest = fakeRequest([['/powerpagecomponents?', { value: [] }],['/workflows?', { value: [] }],@@ -183,12 +201,16 @@ test('diffs custom tables by MetadataId against solutioncomponents.objectid', asLogicalName: 'crd50_already',SchemaName: 'crd50_Already',DisplayName: { UserLocalizedLabel: { Label: 'Already' } },+ IsCustomEntity: true,+ IsManaged: false,},{MetadataId: 'meta-missing',LogicalName: 'crd50_missing',SchemaName: 'crd50_Missing',DisplayName: { UserLocalizedLabel: { Label: 'Missing' } },+ IsCustomEntity: true,+ IsManaged: false,},],},@@ -199,12 +221,14 @@ test('diffs custom tables by MetadataId against solutioncomponents.objectid', as],]);+ const projectRoot = tempSiteWithTablePermissions(t, ['crd50_already', 'crd50_missing']);const result = await discoverSiteComponents({envUrl: 'https://example.crm.dynamics.com',token: 'tok',siteId: 'site-guid',publisherPrefix: 'crd50',solutionId: 'sol-guid',+ projectRoot,makeRequest,});@@ -258,7 +282,7 @@ test('matching is case-insensitive on solution object IDs', async () => {assert.equal(result.missing.powerpagecomponents.length, 0);});-test('discovers env vars and custom tables when publisherPrefix is passed', async () => {+test('discovers env vars and scopes custom tables to site references (not publisher prefix)', async (t) => {const makeRequest = fakeRequest([['/powerpagecomponents?', { value: [] }],['/workflows?', { value: [] }],@@ -288,24 +312,34 @@ test('discovers env vars and custom tables when publisherPrefix is passed', asynLogicalName: 'crd50_invoice',SchemaName: 'crd50_Invoice',DisplayName: { UserLocalizedLabel: { Label: 'Invoice' } },+ IsCustomEntity: true,+ IsManaged: false,},{MetadataId: 'meta-other-widget',- // A custom table from a different publisher — must be filtered out client-side.+ // A custom table the site does NOT reference — dropped by the site-reference+ // scoping (not by prefix). Even shares no prefix concern: it's simply unused.LogicalName: 'other_widget',SchemaName: 'other_Widget',DisplayName: { UserLocalizedLabel: { Label: 'Widget' } },+ IsCustomEntity: true,+ IsManaged: false,},],},],]);+ // Site references ONLY crd50_invoice (not other_widget). The scoping must keep+ // crd50_invoice and drop other_widget — because it isn't referenced, NOT because+ // of its prefix (the whole point of the fix).+ const projectRoot = tempSiteWithTablePermissions(t, ['crd50_invoice']);const result = await discoverSiteComponents({envUrl: 'https://example.crm.dynamics.com',token: 'tok',siteId: 'site-guid',publisherPrefix: 'crd50',+ projectRoot,makeRequest,});diff --git a/plugins/power-pages/scripts/tests/estimate-solution-size.test.js b/plugins/power-pages/scripts/tests/estimate-solution-size.test.jsindex 8432c5240..78055b750 100644--- a/plugins/power-pages/scripts/tests/estimate-solution-size.test.js+++ b/plugins/power-pages/scripts/tests/estimate-solution-size.test.js@@ -705,3 +705,87 @@ test('disk-measurement gracefully no-ops when projectRoot has no build-output di'disk-vs-dataverse canary must not fire when no build dir found',);});++// --- site-referenced table scoping + dependency edges (the prefix-overcount fix) ---++test('estimateSolutionSize scopes tables to site references (not publisher prefix) + emits relationships', async (t) => {+ const fs = require('fs');+ const os = require('os');+ const path = require('path');++ // Temp site root with table permissions referencing only bp_permit + bp_permitstep.+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'est-scope-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const tpDir = path.join(root, '.powerpages-site', 'table-permissions');+ fs.mkdirSync(tpDir, { recursive: true });+ for (const [base, entity] of [['Permit', 'bp_permit'], ['Step', 'bp_permitstep'], ['Notes', 'annotation']]) {+ fs.writeFileSync(path.join(tpDir, `${base}.tablepermission.yml`),+ `adx_entitypermission_webrole:\n- ad89f5ee-8665-f111-a826-6045bd00fdda\nentitylogicalname: ${entity}\nentityname: ${base}\nid: f03fefed-8665-f111-a826-000d3a597e6a\nscope: 756150000\n`);+ }++ withMockedMakeRequest(t, async ({ url }) => {+ if (url.includes('OneToManyRelationships')) {+ // bp_permit has a lookup to bp_permitstep (both in scope) + one to contact (out of scope).+ if (url.includes("LogicalName='bp_permit'")) {+ return { statusCode: 200, body: JSON.stringify({ value: [+ { SchemaName: 'bp_permit_step', ReferencedEntity: 'bp_permit', ReferencingEntity: 'bp_permitstep', ReferencingAttribute: 'bp_permitid' },+ { SchemaName: 'contact_permit', ReferencedEntity: 'contact', ReferencingEntity: 'bp_permit', ReferencingAttribute: 'bp_contactid' },+ ] }) };+ }+ return { statusCode: 200, body: JSON.stringify({ value: [] }) };+ }+ if (url.includes('ManyToManyRelationships')) return { statusCode: 200, body: JSON.stringify({ value: [] }) };+ if (url.includes('/Attributes')) return { statusCode: 200, body: JSON.stringify({ value: [{ LogicalName: 'c1' }, { LogicalName: 'c2' }] }) };+ if (url.includes('EntityDefinitions') && url.includes('IsCustomEntity')) {+ // Env has 4 custom tables; only bp_* are referenced. new_* are the prefix-noise.+ return { statusCode: 200, body: JSON.stringify({ value: [+ { LogicalName: 'bp_permit', MetadataId: 'm1', IsCustomEntity: true, IsManaged: false },+ { LogicalName: 'bp_permitstep', MetadataId: 'm2', IsCustomEntity: true, IsManaged: false },+ { LogicalName: 'new_unrelated1', MetadataId: 'm3', IsCustomEntity: true, IsManaged: false },+ { LogicalName: 'new_unrelated2', MetadataId: 'm4', IsCustomEntity: true, IsManaged: false },+ ] }) };+ }+ if (url.includes('powerpagecomponents') && url.includes('$count')) {+ return { statusCode: 200, body: JSON.stringify({ '@odata.count': 0, value: [] }) };+ }+ return { statusCode: 200, body: JSON.stringify({ value: [] }) };+ });++ const result = await estimateSolutionSize({+ envUrl: 'https://test.crm.dynamics.com',+ websiteRecordId: '00000000-0000-0000-0000-000000000001',+ publisherPrefix: 'new', // the (now-irrelevant for tables) shared prefix+ projectRoot: root,+ token: 'fake-token',+ });++ assert.equal(result.tableCount, 2, 'only the 2 site-referenced bp_* tables — NOT the 2 new_* prefix matches');+ assert.equal(result.tableCountScope, 'site-referenced');+ assert.deepEqual(result.tables.map((x) => x.logicalName).sort(), ['bp_permit', 'bp_permitstep']);+ // Edge between the two scoped tables; the contact edge is dropped (out of scope).+ assert.deepEqual(result.tableRelationships, [['bp_permit', 'bp_permitstep']]);+});++test('estimateSolutionSize tableCountScope is "unavailable" with no local signal (never a prefix dump)', async (t) => {+ withMockedMakeRequest(t, async ({ url }) => {+ if (url.includes('EntityDefinitions') && url.includes('IsCustomEntity')) {+ return { statusCode: 200, body: JSON.stringify({ value: [+ { LogicalName: 'new_a', MetadataId: 'm1', IsCustomEntity: true, IsManaged: false },+ { LogicalName: 'new_b', MetadataId: 'm2', IsCustomEntity: true, IsManaged: false },+ ] }) };+ }+ if (url.includes('powerpagecomponents') && url.includes('$count')) {+ return { statusCode: 200, body: JSON.stringify({ '@odata.count': 0, value: [] }) };+ }+ return { statusCode: 200, body: JSON.stringify({ value: [] }) };+ });+ const result = await estimateSolutionSize({+ envUrl: 'https://test.crm.dynamics.com',+ websiteRecordId: '00000000-0000-0000-0000-000000000001',+ publisherPrefix: 'new',+ token: 'fake-token', // no projectRoot+ });+ assert.equal(result.tableCount, 0, 'no .powerpages-site signal -> zero tables, NOT the env-wide prefix dump');+ assert.equal(result.tableCountScope, 'unavailable');+ assert.deepEqual(result.tableRelationships, []);+});diff --git a/plugins/power-pages/scripts/tests/integration/discover-integration.test.js b/plugins/power-pages/scripts/tests/integration/discover-integration.test.jsindex 57e925265..e7a317663 100644--- a/plugins/power-pages/scripts/tests/integration/discover-integration.test.js+++ b/plugins/power-pages/scripts/tests/integration/discover-integration.test.js@@ -6,11 +6,27 @@const test = require('node:test');const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');const { startMock } = require('./mock-dataverse');const {discoverSiteComponents,} = require('../../lib/discover-site-components');+// Temp site root whose table permissions reference the given entities — the+// site-referenced scoping signal that replaced the publisher-prefix table dump.+function makeSiteRoot(entityLogicalNames) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dsc-int-'));+ const dir = path.join(root, '.powerpages-site', 'table-permissions');+ fs.mkdirSync(dir, { recursive: true });+ entityLogicalNames.forEach((entity, i) => {+ fs.writeFileSync(path.join(dir, `perm-${i}.tablepermission.yml`),+ `adx_entitypermission_webrole:\n- ad89f5ee-8665-f111-a826-6045bd00fdda\nentitylogicalname: ${entity}\nentityname: Perm ${i}\nid: f03fefed-8665-f111-a826-000d3a597e6a\nscope: 756150000\n`);+ });+ return root;+}+test('integration: discover follows @odata.nextLink pagination against a real HTTP server', async () => {let mockBase = null;@@ -217,23 +233,30 @@ test('integration: discover with publisherPrefix queries env vars + tables endpoLogicalName: 'contoso_account',SchemaName: 'contoso_Account',DisplayName: { UserLocalizedLabel: { Label: 'Account' } },+ IsCustomEntity: true,+ IsManaged: false,},{MetadataId: 'meta-2',LogicalName: 'other_widget',SchemaName: 'other_Widget',DisplayName: { UserLocalizedLabel: { Label: 'Widget' } },+ IsCustomEntity: true,+ IsManaged: false,},],},},]);+ // Site references contoso_account only -> other_widget is dropped (unreferenced).+ const projectRoot = makeSiteRoot(['contoso_account']);try {const result = await discoverSiteComponents({envUrl: mock.baseUrl,token: 'x',siteId: 'site-42',publisherPrefix: 'contoso',+ projectRoot,});assert.equal(result.envVars.length, 1);assert.equal(result.envVars[0].schemaName, 'contoso_FeatureFlag');@@ -246,5 +269,6 @@ test('integration: discover with publisherPrefix queries env vars + tables endpoassert.equal(edCalls.length, 1);} finally {await mock.close();+ fs.rmSync(projectRoot, { recursive: true, force: true });}});diff --git a/plugins/power-pages/scripts/tests/query-metadata.test.js b/plugins/power-pages/scripts/tests/query-metadata.test.jsnew file mode 100644index 000000000..9433a9f3c--- /dev/null+++ b/plugins/power-pages/scripts/tests/query-metadata.test.js@@ -0,0 +1,44 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');++const { queryCustomUnmanagedTables } = require('../lib/query-metadata');++function fakeRequestReturning(rows, { paginate = false } = {}) {+ let served = false;+ return async ({ url }) => {+ if (paginate && !served && !/page2/.test(url)) {+ served = true;+ return {+ statusCode: 200,+ body: JSON.stringify({ value: rows.slice(0, 1), '@odata.nextLink': 'https://x/page2' }),+ };+ }+ const body = paginate ? { value: rows.slice(1) } : { value: rows };+ return { statusCode: 200, body: JSON.stringify(body) };+ };+}++test('queryCustomUnmanagedTables keeps only custom + unmanaged tables (with schema/display)', async () => {+ const req = fakeRequestReturning([+ { LogicalName: 'bp_permit', MetadataId: 'm1', SchemaName: 'bp_Permit', DisplayName: { UserLocalizedLabel: { Label: 'Permit' } }, IsCustomEntity: true, IsManaged: false },+ { LogicalName: 'bp_managed', MetadataId: 'm2', IsCustomEntity: true, IsManaged: true }, // managed -> dropped+ { LogicalName: 'account', MetadataId: 'm3', IsCustomEntity: false, IsManaged: false }, // system -> dropped (not custom)+ { LogicalName: 'bp_inspection', MetadataId: 'm4', SchemaName: 'bp_Inspection', IsCustomEntity: true, IsManaged: false }, // no DisplayName -> falls back to SchemaName+ ]);+ const out = await queryCustomUnmanagedTables('https://org.crm.dynamics.com/', 'tok', req);+ assert.deepEqual(out, [+ { logicalName: 'bp_permit', metadataId: 'm1', schemaName: 'bp_Permit', displayName: 'Permit' },+ { logicalName: 'bp_inspection', metadataId: 'm4', schemaName: 'bp_Inspection', displayName: 'bp_Inspection' },+ ]);+});++test('queryCustomUnmanagedTables paginates via @odata.nextLink', async () => {+ const req = fakeRequestReturning([+ { LogicalName: 'a_one', MetadataId: 'm1', IsCustomEntity: true, IsManaged: false },+ { LogicalName: 'a_two', MetadataId: 'm2', IsCustomEntity: true, IsManaged: false },+ ], { paginate: true });+ const out = await queryCustomUnmanagedTables('https://org.crm.dynamics.com', 'tok', req);+ assert.deepEqual(out.map((t) => t.logicalName), ['a_one', 'a_two']);+});diff --git a/plugins/power-pages/scripts/tests/query-table-relationships.test.js b/plugins/power-pages/scripts/tests/query-table-relationships.test.jsnew file mode 100644index 000000000..7c5bd446f--- /dev/null+++ b/plugins/power-pages/scripts/tests/query-table-relationships.test.js@@ -0,0 +1,52 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');++const { fetchTableRelationships } = require('../lib/query-table-relationships');++function router(map) {+ // map: substring -> { statusCode, value } | throws if error:true+ return async ({ url }) => {+ for (const [needle, resp] of Object.entries(map)) {+ if (url.includes(needle)) {+ if (resp.error) return { error: resp.error };+ return { statusCode: resp.statusCode || 200, body: JSON.stringify({ value: resp.value || [] }) };+ }+ }+ return { statusCode: 200, body: JSON.stringify({ value: [] }) };+ };+}++test('fetchTableRelationships maps OneToMany + ManyToMany shapes', async () => {+ const req = router({+ 'OneToManyRelationships': {+ value: [{ SchemaName: 'bp_permit_step', ReferencedEntity: 'bp_permit', ReferencingEntity: 'bp_step', ReferencingAttribute: 'bp_permitid' }],+ },+ 'ManyToManyRelationships': {+ value: [{ SchemaName: 'bp_permit_tag', Entity1LogicalName: 'bp_permit', Entity2LogicalName: 'bp_tag' }],+ },+ });+ const out = await fetchTableRelationships('https://org.crm.dynamics.com/', 'bp_permit', 'tok', req);+ assert.deepEqual(out.oneToMany, [+ { schemaName: 'bp_permit_step', referencedEntity: 'bp_permit', referencingEntity: 'bp_step', referencingAttribute: 'bp_permitid' },+ ]);+ assert.deepEqual(out.manyToMany, [+ { schemaName: 'bp_permit_tag', entity1: 'bp_permit', entity2: 'bp_tag' },+ ]);+});++test('fetchTableRelationships swallows ManyToMany errors (best-effort)', async () => {+ const req = router({+ 'OneToManyRelationships': { value: [] },+ 'ManyToManyRelationships': { statusCode: 404, value: [] },+ });+ const out = await fetchTableRelationships('https://org.crm.dynamics.com', 'x_t', 'tok', req);+ assert.deepEqual(out.manyToMany, []);+ assert.deepEqual(out.oneToMany, []);+});++test('fetchTableRelationships propagates OneToMany errors', async () => {+ const req = router({ 'OneToManyRelationships': { statusCode: 404, value: [] } });+ await assert.rejects(() => fetchTableRelationships('https://org.crm.dynamics.com', 'missing', 'tok', req), /HTTP 404/);+});diff --git a/plugins/power-pages/scripts/tests/resolve-site-tables.test.js b/plugins/power-pages/scripts/tests/resolve-site-tables.test.jsnew file mode 100644index 000000000..f806f5b29--- /dev/null+++ b/plugins/power-pages/scripts/tests/resolve-site-tables.test.js@@ -0,0 +1,113 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');++const { collectReferencedEntityNames, scopeCustomTables } = require('../lib/resolve-site-tables');++function makeProject(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'resolve-site-tables-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ return root;+}++function writeTablePermission(root, fileBase, entityLogicalName, displayName) {+ const dir = path.join(root, '.powerpages-site', 'table-permissions');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, `${fileBase}.tablepermission.yml`),+ [+ 'adx_entitypermission_webrole:',+ '- ad89f5ee-8665-f111-a826-6045bd00fdda',+ 'append: true',+ 'appendto: true',+ 'create: true',+ 'delete: true',+ `entitylogicalname: ${entityLogicalName}`,+ `entityname: ${displayName}`,+ 'id: f03fefed-8665-f111-a826-000d3a597e6a',+ 'read: true',+ 'scope: 756150000',+ 'write: true',+ '',+ ].join('\n'),+ );+}++test('collectReferencedEntityNames: extracts entitylogicalname from table permissions (EDM bp_* fixture)', (t) => {+ const root = makeProject(t);+ writeTablePermission(root, 'Admin-to-Permits', 'bp_defaultapplication', 'Admin to Permits');+ writeTablePermission(root, 'Permit-Steps', 'bp_permitstep', 'Permit Steps');+ writeTablePermission(root, 'Notes-Global', 'annotation', 'Notes Global'); // standard table++ const { names, available, sources } = collectReferencedEntityNames({ projectRoot: root });+ assert.equal(available, true);+ assert.equal(sources.tablePermissions, 3);+ assert.ok(names.has('bp_defaultapplication'));+ assert.ok(names.has('bp_permitstep'));+ assert.ok(names.has('annotation'));+ // entityname (display label) must NOT be added.+ assert.ok(!names.has('admin to permits'));+});++test('collectReferencedEntityNames: unions datamodel manifest entities', (t) => {+ const root = makeProject(t);+ writeTablePermission(root, 'Permit', 'bp_permit', 'Permit');+ fs.writeFileSync(+ path.join(root, '.datamodel-manifest.json'),+ JSON.stringify({ entities: [{ logicalName: 'new_extra' }, { logicalName: 'bp_permit' }] }),+ );+ const { names, sources } = collectReferencedEntityNames({ projectRoot: root });+ assert.ok(names.has('bp_permit'));+ assert.ok(names.has('new_extra'));+ assert.ok(sources.manifest >= 1);+});++test('collectReferencedEntityNames: available=false when no .powerpages-site and no manifest', (t) => {+ const root = makeProject(t);+ const { names, available } = collectReferencedEntityNames({ projectRoot: root });+ assert.equal(available, false);+ assert.equal(names.size, 0);+});++test('scopeCustomTables: keeps only referenced custom tables; drops unreferenced + standard', (t) => {+ const root = makeProject(t);+ writeTablePermission(root, 'Permit', 'bp_permit', 'Permit');+ writeTablePermission(root, 'Inspection', 'BP_Inspection', 'Inspection'); // mixed case+ writeTablePermission(root, 'Notes', 'annotation', 'Notes'); // standard++ const { names } = collectReferencedEntityNames({ projectRoot: root });++ // Simulate the env's custom-unmanaged tables (the old prefix dump would return all of these).+ const customUnmanaged = [+ { logicalName: 'bp_permit', metadataId: 'm1' },+ { logicalName: 'bp_inspection', metadataId: 'm2' },+ { logicalName: 'new_unrelated1', metadataId: 'm3' }, // not referenced -> dropped+ { logicalName: 'new_unrelated2', metadataId: 'm4' }, // not referenced -> dropped+ ];+ const scoped = scopeCustomTables(names, customUnmanaged).map((t2) => t2.logicalName).sort();+ assert.deepEqual(scoped, ['bp_inspection', 'bp_permit']);+ // 'annotation' is referenced but not in the custom-unmanaged list -> naturally excluded.+});++test('scopeCustomTables: empty referenced set -> empty (never a prefix dump)', () => {+ assert.deepEqual(scopeCustomTables(new Set(), [{ logicalName: 'new_x' }]), []);+});++test('collectReferencedEntityNames: sources.tablePermissions reflects FILE existence even when files are unparseable', (t) => {+ const root = makeProject(t);+ const dir = path.join(root, '.powerpages-site', 'table-permissions');+ fs.mkdirSync(dir, { recursive: true });+ // A malformed permission file — present, but yields no entitylogicalname. Without+ // counting files up-front, sources.tablePermissions would be 0 and a real site+ // would be misclassified manifest-only/unavailable by tableCountScope.+ fs.writeFileSync(path.join(dir, 'broken.tablepermission.yml'), ':\n not: [valid yaml }}}\n');++ const { names, available, sources } = collectReferencedEntityNames({ projectRoot: root });+ assert.equal(available, true, 'the table-permissions dir exists → available');+ assert.equal(sources.tablePermissions, 1, 'counts the permission FILE, not parsed records (0 parsed here)');+ assert.equal(names.size, 0, 'no entity names parsed from the malformed file');+});diff --git a/plugins/power-pages/scripts/tests/validation-helpers.test.js b/plugins/power-pages/scripts/tests/validation-helpers.test.jsindex 9b7e2dc87..0e739fe9a 100644--- a/plugins/power-pages/scripts/tests/validation-helpers.test.js+++ b/plugins/power-pages/scripts/tests/validation-helpers.test.js@@ -73,3 +73,42 @@ test('findProjectRoot: returns null when neither marker is present', (t) => {assert.equal(findProjectRoot(root), null);});+// --- odataGet / odataGetAll (shared pagination) ------------------------------++test('odataGetAll follows @odata.nextLink and aggregates all pages', async () => {+ const { odataGetAll } = require(helpersPath);+ const pages = {+ 'https://x/api/data/v9.2/things': { value: [{ id: 1 }, { id: 2 }], '@odata.nextLink': 'https://x/page2' },+ 'https://x/page2': { value: [{ id: 3 }] },+ };+ const fakeRequest = async ({ url }) => ({ statusCode: 200, body: JSON.stringify(pages[url]) });+ const rows = await odataGetAll('https://x/api/data/v9.2/things', 'tok', fakeRequest);+ assert.deepEqual(rows.map((r) => r.id), [1, 2, 3]);+});++test('odataGetAll FAILS CLOSED: throws when it hits maxPages with @odata.nextLink still present', async () => {+ const { odataGetAll } = require(helpersPath);+ // Every page advertises a nextLink → never terminates → hits the page cap.+ // Must throw rather than silently return a truncated set (wrong ALM counts).+ const fakeRequest = async () => ({+ statusCode: 200,+ body: JSON.stringify({ value: [{ id: 1 }], '@odata.nextLink': 'https://x/next' }),+ });+ await assert.rejects(+ () => odataGetAll('https://x/start', 'tok', fakeRequest, 3),+ /page cap.*nextLink|truncated/i,+ );+});++test('odataGet throws on non-2xx', async () => {+ const { odataGet } = require(helpersPath);+ const fakeRequest = async () => ({ statusCode: 404, body: 'not found' });+ await assert.rejects(() => odataGet('https://x/y', 'tok', fakeRequest), /HTTP 404/);+});++test('odataGet throws on transport error', async () => {+ const { odataGet } = require(helpersPath);+ const fakeRequest = async () => ({ error: 'ECONNRESET' });+ await assert.rejects(() => odataGet('https://x/y', 'tok', fakeRequest), /OData request failed/);+});+diff --git a/plugins/power-pages/skills/audit-permissions/scripts/query-table-relationships.js b/plugins/power-pages/skills/audit-permissions/scripts/query-table-relationships.jsindex a5bdf93f3..ca98582dc 100644--- a/plugins/power-pages/skills/audit-permissions/scripts/query-table-relationships.js+++ b/plugins/power-pages/skills/audit-permissions/scripts/query-table-relationships.js@@ -1,19 +1,21 @@#!/usr/bin/env node+// Thin CLI wrapper over scripts/lib/query-table-relationships.js.// Queries Dataverse for one-to-many relationships on a given table.// Returns JSON array of { schemaName, referencedEntity, referencingEntity, referencingAttribute }.//// Usage:// node query-table-relationships.js --envUrl <url> --table <logical_name>//-// Output (stdout): JSON array-// [{ "schemaName": "cr4fc_order_orderitem", "referencedEntity": "cr4fc_order", "referencingEntity": "cr4fc_orderitem", "referencingAttribute": "cr4fc_orderid" }]+// Output (stdout): JSON array (OneToMany relationships only — the audit-permissions+// relationship-scope validation consumes schemaName + referencedEntity).//// Exit codes:// 0 = success (JSON on stdout)// 1 = error (message on stderr)-const { getAuthToken, makeRequest } = require('../../../scripts/lib/validation-helpers');+const { getAuthToken } = require('../../../scripts/lib/validation-helpers');+const { fetchTableRelationships } = require('../../../scripts/lib/query-table-relationships');const args = process.argv.slice(2);function getArg(name) {@@ -37,29 +39,10 @@ if (!envUrl || !table) {}try {- const result = await makeRequest({- url: `${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${table}')/OneToManyRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute`,- headers: {- Authorization: `Bearer ${token}`,- Accept: 'application/json',- },- timeout: 15000,- });-- if (result.error || result.statusCode !== 200) {- process.stderr.write(`API error (${result.statusCode}): ${result.error || result.body}\n`);- process.exit(1);- }-- const parsed = JSON.parse(result.body);- const rels = (parsed.value || []).map(r => ({- schemaName: r.SchemaName,- referencedEntity: r.ReferencedEntity,- referencingEntity: r.ReferencingEntity,- referencingAttribute: r.ReferencingAttribute,- }));-- process.stdout.write(JSON.stringify(rels, null, 2) + '\n');+ // OneToMany errors propagate here (preserves the original exit-1-on-API-error+ // behavior); ManyToMany is best-effort inside the lib and unused by this CLI.+ const { oneToMany } = await fetchTableRelationships(envUrl, table, token);+ process.stdout.write(JSON.stringify(oneToMany, null, 2) + '\n');} catch (err) {process.stderr.write(`Request failed: ${err.message}\n`);process.exit(1);diff --git a/plugins/power-pages/skills/deploy-pipeline/SKILL.md b/plugins/power-pages/skills/deploy-pipeline/SKILL.mdindex cff495c76..ba80f76a8 100644--- a/plugins/power-pages/skills/deploy-pipeline/SKILL.md+++ b/plugins/power-pages/skills/deploy-pipeline/SKILL.md@@ -300,7 +300,8 @@ node "${PLUGIN_ROOT}/scripts/lib/discover-site-components.js" \--envUrl "{devEnvUrl}" --token "{DEV_TOKEN}" \--siteId "{websiteRecordId from .solution-manifest.json}" \--publisherPrefix "{publisherPrefix from .solution-manifest.json}" \- --solutionId "{solutionId from .solution-manifest.json}"+ --solutionId "{solutionId from .solution-manifest.json}" \+ --projectRoot "."```Parse stdout and evaluate `missing.*`. **Before doing anything else**, capture the **pre-sync state** so a post-sync re-confirmation gate can show what changed:diff --git a/plugins/power-pages/skills/export-solution/SKILL.md b/plugins/power-pages/skills/export-solution/SKILL.mdindex 91fe12fa8..71d131ef3 100644--- a/plugins/power-pages/skills/export-solution/SKILL.md+++ b/plugins/power-pages/skills/export-solution/SKILL.md@@ -158,7 +158,8 @@ node "${PLUGIN_ROOT}/scripts/lib/discover-site-components.js" \--envUrl "{envUrl}" --token "{token}" \--siteId "{websiteRecordId}" \--publisherPrefix "{publisherPrefix from .solution-manifest.json}" \- --solutionId "{solutionId}"+ --solutionId "{solutionId}" \+ --projectRoot "."```Parse stdout and evaluate `missing`. **Before doing anything else**, capture the **pre-sync state** so a post-sync re-confirmation gate can show what changed:diff --git a/plugins/power-pages/skills/plan-alm/SKILL.md b/plugins/power-pages/skills/plan-alm/SKILL.mdindex 83460a332..652b28a1f 100644--- a/plugins/power-pages/skills/plan-alm/SKILL.md+++ b/plugins/power-pages/skills/plan-alm/SKILL.md@@ -242,7 +242,8 @@ Steps:--envUrl "{envUrl}" --token "{token}" \--siteId "{websiteRecordId from powerpages.config.json}" \--publisherPrefix "{solutionManifest.publisher.prefix}" \- --solutionId "{solutionManifest.solution.solutionId}"+ --solutionId "{solutionManifest.solution.solutionId}" \+ --projectRoot "."```Parse stdout and evaluate `missing.*`:diff --git a/plugins/power-pages/skills/setup-solution/SKILL.md b/plugins/power-pages/skills/setup-solution/SKILL.mdindex be4538f8a..0e95c978d 100644--- a/plugins/power-pages/skills/setup-solution/SKILL.md+++ b/plugins/power-pages/skills/setup-solution/SKILL.md@@ -304,14 +304,18 @@ GET {envUrl}/api/data/v9.2/powerpagesitelanguages?$filter=_powerpagesiteid_value```Store all language IDs.-**D. Dataverse tables** — always discover from the environment, don't rely on a manifest file alone:+**D. Dataverse tables** — discover the tables the **site actually references**, NOT every table sharing the publisher prefix.-1. Read `.datamodel-manifest.json` if present (for the known list of tables created by `setup-datamodel`)-2. **Also** query the environment directly for all custom unmanaged tables, filtering by the publisher prefix:-```-GET {envUrl}/api/data/v9.2/EntityDefinitions?$select=LogicalName,MetadataId,IsManaged,IsCustomEntity+> **Why not publisher prefix:** prefix-matching over-counts catastrophically with a shared/default publisher (`new_`, env default) — a 6-table site can match 22 unrelated tables — and it also *misses* the site's real tables when they come from a different prefix (e.g. a `bp_*` template under an `edm` publisher). The authoritative signal (SME-confirmed) is the site's **table permissions**: "If a table is used in the site there will be permissions for it."++Run the shared discovery helper, which scopes custom tables to the site's table permissions (+ datamodel manifest) intersected with the env's custom-unmanaged tables:+```bash+node "${PLUGIN_ROOT}/scripts/lib/discover-site-components.js" \+ --envUrl "{envUrl}" --token "{token}" --siteId "{websiteRecordId}" \+ --projectRoot "." \+ {if .datamodel-manifest.json elsewhere: --datamodelManifest "<path>"}```-Filter client-side: `IsCustomEntity === true && IsManaged === false`. Group by publisher prefix (characters before first `_`). Present only tables whose prefix matches the site publisher — or if no prefix match, present all custom unmanaged tables and let the user decide.+Use the returned `customTables[]` (each `{ id, logicalName, schemaName, displayName }` — `id` is the MetadataId for the `AddSolutionComponent` call). This is already the correct, site-scoped list — do **not** re-filter by prefix.> **Important note on tables**: Dataverse solutions carry **schema only** — entity definitions, columns, relationships, forms, and views. Table **data/records** do NOT travel with the solution. If the target environment needs seed/reference data, that requires a separate data migration step.@@ -628,11 +632,13 @@ If both `missing.powerpagecomponents` (after filtering) and `missing.siteLanguag**This is the key decision point.** Build a full manifest of everything that will be added and present it to the user before writing anything.-If custom tables were discovered, ask via `AskUserQuestion` with `multiSelect: true` **before** showing the final manifest:-- First option: **"Include all N tables (Recommended)"** — pre-selected default+If custom tables were discovered (the site-referenced set from step D), ask via `AskUserQuestion` with `multiSelect: true` **before** showing the final manifest:+- First option: **"Include all N referenced tables (Recommended)"** — pre-selected default. N is the count of tables the site actually references (not an env-wide prefix list).- Then one option per table: `{logicalName} ({DisplayName})`- Last option: **"Exclude all tables"**+> The default list is already scoped to the site's real tables (step D). If the user knows of an additional table the site needs that has no permission yet, they can add it manually — but the default must never be a publisher-prefix dump.+Present as a structured summary:```