Skip to content

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

refresh-alm-plan-data: merge live Dataverse environment variable values (`--live`) (#703)

Copilotea1e2e7518e2
diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.md
index 342fc9817..77214d956 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -466,7 +466,7 @@ Shared lib modules live at `scripts/lib/` and are imported by other scripts via
- `scripts/lib/link-site-setting-to-env-var.js`: Links an `mspp_sitesetting` record to an `environmentvariabledefinition` via OData PATCH on the v9.0 API (not v9.2). HAR-confirmed: navigation property is `[email protected]`; headers `if-match: *` and `clienthost: Browser` are required (omitting causes 400). Args: `--envUrl`, `--token`, `--siteSettingId`, `--definitionId`, `--schemaName`. Output: `{ ok, verified, siteSettingId, definitionId }`.
- `scripts/lib/install-pipelines-app.js`: Installs the Power Platform Pipelines application package on an existing Dataverse env (replaces ensure-pipelines-host Phase 4.B's manual PPAC click-through). Resolution: BAP `applicationPackages` LIST + `/install` POST → 200 sync / 202 + Location poll, with PAC CLI fallback (`pac application install --environment-id ... --application-list msdyn_AppDeploymentAnchor`) on 401/403/5xx. 409 on install POST treated as idempotent (already-installed). Args: `--bapToken`, `--envId`, `--instanceApiUrl` (opt — for verification probe), `--hostToken` (opt), `--no-pac-fallback` (opt), `--correlationId`, `--timeoutSec`, `--apiVersion`, `--bapBase`. Output: `{ status, alreadyInstalled, installPath: 'bap'\|'pac'\|'cached', packageUniqueName, pipelinesSolutionVersion, durationSec, correlationId, pollAttempts, locationHeader, pacFallbackReason }`.
- `scripts/lib/discover-env-var-definitions.js`: Enumerates env var definitions matching a publisher prefix and joins each with its bound `mspp_sitesetting` (if any). Used by `plan-alm` Phase 1 Step 10b to populate `planData.envVars[]` with row-level metadata so the rendered plan's Env Variables tab shows schema name, type, default value, and bound site setting per definition (instead of just a count). Args: `--envUrl`, `--publisherPrefix`, `--websiteRecordId`, `--token` (opt). Output: `{ envVars: [{ schemaName, type, defaultValue, siteSetting }], count }`. Degrades gracefully (empty array, exit 0) on auth failure or query errors so the renderer's count-summary fallback can take over.
-- `scripts/lib/refresh-alm-plan-data.js`: Updates `docs/.alm-plan-data.json` with post-run state from the marker files written by setup-pipeline / deploy-pipeline / ensure-pipelines-host / test-site / import-solution / activate-site / configure-env-variables / setup-solution / export-solution, then optionally re-renders `docs/alm-plan.html`. Driven by the execution skills' final-phase refresh (and the PostToolUse `--reconcile` backstop) — NOT by plan-alm, which is now a plan-only 4-phase planner that only renders the initial plan in Phase 3 — so the rendered Pipelines tab, Validation tab, hostResolution card, env var values matrix, checklist, and risks list reflect actual run state instead of frozen pre-run intent. Args: `--projectRoot`, `--phase` (`setup-solution`/`setup-pipeline`/`configure-env-variables`/`deploy-pipeline`/`export-solution`/`import-solution`/`activate-site`/`test-site`/`ensure-pipelines-host`/`finalize`) **OR `--reconcile`** (mutually exclusive with `--phase`), `--render` (also invoke renderer), `--stageName` (required for `test-site`; preferred for `import-solution`/`activate-site` though both can resolve via marker URL match). Output: `{ ok, phase, dataPath, htmlPath, rendered }`. Returns `ok:false` (soft no-op) when `docs/.alm-plan-data.json` is missing — caller should preserve that file across phases for the helper to work. Plan-alm Phase 3 must NOT delete the file after the initial render — it's read by `check-alm-plan.js` for downstream Phase 0 ALM-plan gates and by this helper for post-run refreshes. **Cross-cutting behaviors**: (a) `setStepStatus` flips the matching entry in `planData.steps[]` to `completed` (or `failed` when the phase's marker indicates failure) — case-insensitive keyword match + stage filter, respects `skip: true`, never regresses completed→pending; (b) `deploy-pipeline` AND `configure-env-variables` both backfill `planData.envVars[i].values{}` from the project root's `deployment-settings.json` so the rendered plan's "Values by Environment" matrix auto-populates (accepts both top-level-stage and nested-`stages` shapes; `SchemaName`/`Value` and camelCase variants; never overwrites a populated cell — manual override wins); (c) `configure-env-variables` and `setup-solution` both re-ingest `docs/alm/last-env-vars.json` (when present) so freshly-created definitions appear in `planData.envVars[]` and `plannedEnvVarCount` zeros out; (d) `export-solution` ingests `docs/alm/last-export.json` into `planData.manualMeta.lastExport` (all 10 marker fields: solutionUniqueName/solutionId/previousVersion/version/managed/sourceEnvironmentUrl/zipPath/fileSizeBytes/asyncOperationId/exportedAt) so the Manual-path tab can show the most recent export. Marker absence is a silent step-sync-only no-op (no `manualMeta.lastExport: null` row in the rendered plan); (e) `deploy-pipeline` ingests the `batchValidation` block from `last-deploy.json` into `planData.pipelineMeta.lastDeploy.batchValidation` (totalSolutions/succeeded/failed/pendingApproval/timedOut/elapsedSeconds/perSolutionStageRunIds) so the rendered plan can show the Phase 3.6 parallel-validation outcome distinct from the serial deploy outcome. Explicitly set to `null` for single-solution / legacy v2 deploys so renderers can branch on it; legacy `elapsedSecondsApprox` field name is accepted and normalized to `elapsedSeconds` on ingest. **`ensure-pipelines-host` phase**: host-only update of `planData.hostResolution` from `last-host-check.json` (drops NoHost risks) WITHOUT touching `pipelineMeta` or the `Setup pipeline` step — for when the host was resolved but the pipeline doesn't exist yet. **`--reconcile` mode**: the enforcement backstop — scans the `last-*.json` markers and, for each one newer than `docs/.alm-plan-data.json` (a skipped refresh), applies the mapped phase (`MARKER_TO_PHASE`; `lastPipeline`→setup-pipeline supersedes the host-only phase; `lastEnvVars`→configure-env-variables if `deployment-settings.json` exists else setup-solution) against a single loaded planData, writes once, renders once. Honors `.alm-deferred`, soft no-op when no plan, idempotent. Output `{ ok, reconciled:[phases healed], failed:[{phase,error}], rendered }` — a phase whose refresh throws (e.g. a marker schema it can't parse) is captured in `failed` (and written to stderr) instead of being silently swallowed, while the remaining phases still heal. Invoked by the PostToolUse hook after every ALM skill (see Hooks). **Completion evaluator (`In Execution` → `Completed`):** after every phase's step-sync (both `refresh()` and `reconcile()`), `evaluatePlanCompletion` flips `PLAN_STATUS` to `Completed` + stamps `COMPLETED_AT` once every non-`skip` step is `completed` and none is `failed`. This is what makes the LAST execution skill terminate the plan automatically — no skill calls `--phase finalize` (the explicit `finalize` phase / `refreshFinalize` exists but nothing invoked it, so the lifecycle previously never reached `Completed`). Only advances from `In Execution` (the normal post-promotion state — see `check-alm-plan.js`) or `Approved` (defensive fallback); never regresses a `Draft` or already-`Completed` plan, and a `failed` step blocks completion so a failed deploy can't look "done".
+- `scripts/lib/refresh-alm-plan-data.js`: Updates `docs/.alm-plan-data.json` with post-run state from the marker files written by setup-pipeline / deploy-pipeline / ensure-pipelines-host / test-site / import-solution / activate-site / configure-env-variables / setup-solution / export-solution, then optionally re-renders `docs/alm-plan.html`. Driven by the execution skills' final-phase refresh (and the PostToolUse `--reconcile` backstop) — NOT by plan-alm, which is now a plan-only 4-phase planner that only renders the initial plan in Phase 3 — so the rendered Pipelines tab, Validation tab, hostResolution card, env var values matrix, checklist, and risks list reflect actual run state instead of frozen pre-run intent. Args: `--projectRoot`, `--phase` (`setup-solution`/`setup-pipeline`/`configure-env-variables`/`deploy-pipeline`/`export-solution`/`import-solution`/`activate-site`/`test-site`/`ensure-pipelines-host`/`finalize`) **OR `--reconcile`** (mutually exclusive with `--phase`), `--render` (also invoke renderer), `--live` (opt — merge live Dataverse env var values, see (b)), `--stageName` (required for `test-site`; preferred for `import-solution`/`activate-site` though both can resolve via marker URL match). Output: `{ ok, phase, dataPath, htmlPath, rendered }`. Returns `ok:false` (soft no-op) when `docs/.alm-plan-data.json` is missing — caller should preserve that file across phases for the helper to work. Plan-alm Phase 3 must NOT delete the file after the initial render — it's read by `check-alm-plan.js` for downstream Phase 0 ALM-plan gates and by this helper for post-run refreshes. **Cross-cutting behaviors**: (a) `setStepStatus` flips the matching entry in `planData.steps[]` to `completed` (or `failed` when the phase's marker indicates failure) — case-insensitive keyword match + stage filter, respects `skip: true`, never regresses completed→pending; (b) `deploy-pipeline` AND `configure-env-variables` both backfill `planData.envVars[i].values{}` from the project root's `deployment-settings.json` so the rendered plan's "Values by Environment" matrix auto-populates (accepts both top-level-stage and nested-`stages` shapes; `SchemaName`/`Value` and camelCase variants; never overwrites a populated untagged cell — manual override wins; cells it writes are tagged `envVars[i].valueSources[stage] = "settings"` so a later change to the file replaces them; schema names match case-insensitively); with **`--live`** (`--phase` mode only) the CLI first queries every `planData.stages[]` entry's `envUrl` (Azure CLI token per env; `environmentvariabledefinitions` + `environmentvariablevalues`, Secret-type definitions skipped) and merges those values for cells with no local value, tagging them `envVars[i].valueSources[stage] = "live"` so later live refreshes update/clear them and a `deployment-settings.json` value replaces them — values set in PPAC reach the plan. Per-stage query failures are fail-soft and reported in the output's `liveEnvVars: { filled, updated, cleared, queriedStages, errors }`, and both calling skills tell the user about each `errors[]` entry (a 401/403 or token failure usually means `az` is signed in to a different tenant than the environment); (c) `configure-env-variables` and `setup-solution` both re-ingest `docs/alm/last-env-vars.json` (when present) so freshly-created definitions appear in `planData.envVars[]` and `plannedEnvVarCount` zeros out; (d) `export-solution` ingests `docs/alm/last-export.json` into `planData.manualMeta.lastExport` (all 10 marker fields: solutionUniqueName/solutionId/previousVersion/version/managed/sourceEnvironmentUrl/zipPath/fileSizeBytes/asyncOperationId/exportedAt) so the Manual-path tab can show the most recent export. Marker absence is a silent step-sync-only no-op (no `manualMeta.lastExport: null` row in the rendered plan); (e) `deploy-pipeline` ingests the `batchValidation` block from `last-deploy.json` into `planData.pipelineMeta.lastDeploy.batchValidation` (totalSolutions/succeeded/failed/pendingApproval/timedOut/elapsedSeconds/perSolutionStageRunIds) so the rendered plan can show the Phase 3.6 parallel-validation outcome distinct from the serial deploy outcome. Explicitly set to `null` for single-solution / legacy v2 deploys so renderers can branch on it; legacy `elapsedSecondsApprox` field name is accepted and normalized to `elapsedSeconds` on ingest. **`ensure-pipelines-host` phase**: host-only update of `planData.hostResolution` from `last-host-check.json` (drops NoHost risks) WITHOUT touching `pipelineMeta` or the `Setup pipeline` step — for when the host was resolved but the pipeline doesn't exist yet. **`--reconcile` mode**: the enforcement backstop — scans the `last-*.json` markers and, for each one newer than `docs/.alm-plan-data.json` (a skipped refresh), applies the mapped phase (`MARKER_TO_PHASE`; `lastPipeline`→setup-pipeline supersedes the host-only phase; `lastEnvVars`→configure-env-variables if `deployment-settings.json` exists else setup-solution) against a single loaded planData, writes once, renders once. Honors `.alm-deferred`, soft no-op when no plan, idempotent. Output `{ ok, reconciled:[phases healed], failed:[{phase,error}], rendered }` — a phase whose refresh throws (e.g. a marker schema it can't parse) is captured in `failed` (and written to stderr) instead of being silently swallowed, while the remaining phases still heal. Invoked by the PostToolUse hook after every ALM skill (see Hooks). **Completion evaluator (`In Execution` → `Completed`):** after every phase's step-sync (both `refresh()` and `reconcile()`), `evaluatePlanCompletion` flips `PLAN_STATUS` to `Completed` + stamps `COMPLETED_AT` once every non-`skip` step is `completed` and none is `failed`. This is what makes the LAST execution skill terminate the plan automatically — no skill calls `--phase finalize` (the explicit `finalize` phase / `refreshFinalize` exists but nothing invoked it, so the lifecycle previously never reached `Completed`). Only advances from `In Execution` (the normal post-promotion state — see `check-alm-plan.js`) or `Approved` (defensive fallback); never regresses a `Draft` or already-`Completed` plan, and a `failed` step blocks completion so a failed deploy can't look "done".
#### PP Pipelines
diff --git a/plugins/power-pages/scripts/lib/refresh-alm-plan-data.js b/plugins/power-pages/scripts/lib/refresh-alm-plan-data.js
index 49fdf36b0..5034f61f4 100644
--- a/plugins/power-pages/scripts/lib/refresh-alm-plan-data.js
+++ b/plugins/power-pages/scripts/lib/refresh-alm-plan-data.js
@@ -20,6 +20,11 @@
// [--render] also invoke render-alm-plan.js after writing
// [--rendererPath <path>] defaults to skills/plan-alm/scripts/render-alm-plan.js
// relative to plugin root
+// [--live] also query each plan stage's live Dataverse
+// `environmentvariablevalues` (Azure CLI token per
+// stage envUrl) and merge them into the "Values by
+// Environment" matrix; deployment-settings.json and
+// manual values win. --phase mode only.
//
// What gets refreshed per phase:
// setup-solution:
@@ -95,6 +100,7 @@ function parseArgs(argv) {
rendererPath: null,
stageName: null,
reconcile: false,
+ live: false,
};
for (let i = 0; i < args.length; i++) {
if (args[i] === '--projectRoot' && args[i + 1]) out.projectRoot = args[++i];
@@ -103,6 +109,7 @@ function parseArgs(argv) {
else if (args[i] === '--rendererPath' && args[i + 1]) out.rendererPath = args[++i];
else if (args[i] === '--stageName' && args[i + 1]) out.stageName = args[++i];
else if (args[i] === '--reconcile') out.reconcile = true;
+ else if (args[i] === '--live') out.live = true;
}
return out;
}
@@ -197,41 +204,338 @@ function extractPerStageValues(deploymentSettings) {
return bySchema;
}
+// Provenance marker for cells written from the live `environmentvariablevalues`
+// table (see mergeLiveEnvVarValues). A cell is "live-sourced" when
+// `ev.valueSources[stageKey] === 'live'`. Live-sourced cells are NOT manual
+// overrides: they must be updated (or cleared) on the next live query and
+// replaced by a deployment-settings.json value, otherwise the first value ever
+// observed in PPAC would freeze into the plan and the audit trail would drift.
+function isLiveSourced(ev, stageKey) {
+ return !!(ev && ev.valueSources && typeof ev.valueSources === 'object' &&
+ ev.valueSources[stageKey] === 'live');
+}
+
+// Provenance marker for cells written by backfillEnvVarValuesFromSettings
+// (`ev.valueSources[stageKey] === 'settings'`). Like live cells these are NOT
+// manual overrides: when deployment-settings.json changes, the next backfill
+// must replace them. Without the tag a cell carried forward from an earlier
+// run (carryForwardEnvVarValues) looks identical to a hand edit and the old
+// file value would freeze. Untagged cells remain manual overrides.
+function isSettingsSourced(ev, stageKey) {
+ return !!(ev && ev.valueSources && typeof ev.valueSources === 'object' &&
+ ev.valueSources[stageKey] === 'settings');
+}
+
+function setValueSource(ev, stageKey, source) {
+ if (source) {
+ ev.valueSources = (ev.valueSources && typeof ev.valueSources === 'object') ? ev.valueSources : {};
+ ev.valueSources[stageKey] = source;
+ return;
+ }
+ if (!ev.valueSources || typeof ev.valueSources !== 'object') return;
+ delete ev.valueSources[stageKey];
+ if (Object.keys(ev.valueSources).length === 0) delete ev.valueSources;
+}
+
+// Replace planData.envVars with a freshly discovered definition list (the
+// last-env-vars.json sidecar) WITHOUT losing per-stage values{} / valueSources{}
+// already in the plan. Discovery rows carry only
+// { schemaName, displayName, type, defaultValue, description, siteSetting }
+// so a plain replace would drop every matrix cell. That is unrecoverable when
+// the same run's live query for a stage fails (the stage is absent from
+// liveEnvVarValues.byStage, so the merge can't refill it) or for manual cells
+// that only ever lived in the plan.
+// - Matched by schemaName, case-insensitively (Dataverse schema names are
+// case-insensitive and discovery may return different casing).
+// - A definition missing from `incoming` is dropped on purpose — it was
+// removed from the solution, so its values go with it.
+// - Values/valueSources on the incoming row win per stage key; prior
+// provenance is kept only for keys the incoming row doesn't set.
+function carryForwardEnvVarValues(previous, incoming) {
+ if (!Array.isArray(incoming)) return incoming;
+ const isObj = (o) => !!o && typeof o === 'object' && !Array.isArray(o);
+ const priorBySchema = new Map();
+ for (const ev of (Array.isArray(previous) ? previous : [])) {
+ if (ev && typeof ev.schemaName === 'string') priorBySchema.set(ev.schemaName.toLowerCase(), ev);
+ }
+ return incoming.map((row) => {
+ if (!row || typeof row.schemaName !== 'string') return row;
+ const prior = priorBySchema.get(row.schemaName.toLowerCase());
+ if (!prior || !isObj(prior.values) || Object.keys(prior.values).length === 0) return row;
+ const rowValues = isObj(row.values) ? row.values : {};
+ const rowSources = isObj(row.valueSources) ? row.valueSources : {};
+ const priorSources = isObj(prior.valueSources) ? prior.valueSources : {};
+ const values = {};
+ const sources = {};
+ for (const [key, value] of Object.entries(prior.values)) {
+ if (Object.prototype.hasOwnProperty.call(rowValues, key)) continue;
+ values[key] = value;
+ if (priorSources[key]) sources[key] = priorSources[key];
+ }
+ Object.assign(values, rowValues);
+ Object.assign(sources, rowSources);
+ const out = { ...row, values };
+ if (Object.keys(sources).length > 0) out.valueSources = sources;
+ else delete out.valueSources;
+ return out;
+ });
+}
+
// Backfill planData.envVars[i].values{} from deployment-settings.json so
// the rendered plan's "Values by Environment" matrix auto-populates after
// deploy-pipeline runs. Idempotent: an existing non-empty value on
-// ev.values[stageName] is preserved (manual overrides win). Returns the
-// number of cells filled in this call.
+// ev.values[stageName] is preserved (manual overrides win) unless that value
+// was written by a previous live query or a previous backfill (tagged
+// valueSources[stage] = 'live' | 'settings') — the current file wins over both.
+// Cells it writes are tagged 'settings'. Schema names match case-insensitively
+// (Dataverse schema names are case-insensitive; files and discovery can differ
+// in casing). Returns the number of cells filled or changed in this call.
//
-// TODO(follow-up): also query the live `environmentvariablevalues` table
-// per target env so values set in Power Platform Admin Center (bypassing
-// the file) show up. Needs per-stage tokens + env var definition GUIDs,
-// neither of which the helper currently has — deferring until those
-// inputs are wired through the refresh contract.
+// Values set in Power Platform Admin Center (bypassing the file) are merged in
+// by mergeLiveEnvVarValues when the caller passes `--live`.
function backfillEnvVarValuesFromSettings(planData, projectRoot) {
if (!Array.isArray(planData.envVars) || planData.envVars.length === 0) return 0;
const settings = readDeploymentSettings(projectRoot);
if (!settings) return 0;
const bySchema = extractPerStageValues(settings);
if (!bySchema || Object.keys(bySchema).length === 0) return 0;
+ const bySchemaLower = new Map();
+ for (const [schemaName, stages] of Object.entries(bySchema)) {
+ // extractPerStageValues groups by exact spelling, so `cr5fe_x` (Staging)
+ // and `CR5FE_X` (Production) arrive as separate entries. Merge their stage
+ // maps rather than letting the second spelling replace the first.
+ const key = schemaName.toLowerCase();
+ bySchemaLower.set(key, { ...(bySchemaLower.get(key) || {}), ...stages });
+ }
let filled = 0;
for (const ev of planData.envVars) {
if (!ev || typeof ev.schemaName !== 'string') continue;
- const matches = bySchema[ev.schemaName];
+ const matches = bySchemaLower.get(ev.schemaName.toLowerCase());
if (!matches) continue;
ev.values = (ev.values && typeof ev.values === 'object') ? ev.values : {};
for (const [stageName, value] of Object.entries(matches)) {
- // Manual override / prior call wins — never overwrite a populated cell.
+ // Manual override wins — never overwrite a populated untagged cell. A
+ // live-queried or previously backfilled cell is replaced by the file.
const existing = ev.values[stageName];
- if (existing != null && existing !== '') continue;
+ const populated = existing != null && existing !== '';
+ const settingsCell = isSettingsSourced(ev, stageName);
+ if (populated && !isLiveSourced(ev, stageName) && !settingsCell) continue;
+ if (populated && settingsCell && existing === value) continue;
ev.values[stageName] = value;
+ setValueSource(ev, stageName, 'settings');
filled += 1;
}
}
return filled;
}
+// Dataverse environment variable definition `type` for Secret (Azure Key Vault
+// reference). The value row holds a Key Vault reference, not a usable value —
+// keep it out of the rendered plan.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/environmentvariabledefinition#BKMK_Type
+const ENV_VAR_TYPE_SECRET = 100000005;
+
+// Query the live `environmentvariablevalues` table of every plan stage that has
+// an envUrl (planData.stages[] = [{ label, envUrl, type }]) so values set in
+// Power Platform Admin Center — which never touch deployment-settings.json —
+// still reach the ALM plan. Async + network-bound, so it is NOT run by
+// refresh()/reconcile() themselves; the CLI calls it only under `--live` and
+// passes the result into refresh() as `liveEnvVarValues`.
+//
+// Two reads per env, both with fields already relied on by
+// verify-env-var-values.js:
+// GET {envUrl}/api/data/v9.2/environmentvariabledefinitions?$select=environmentvariabledefinitionid,schemaname,type
+// → { value: [{ environmentvariabledefinitionid, schemaname, type }], @odata.nextLink? }
+// GET {envUrl}/api/data/v9.2/environmentvariablevalues?$select=value,_environmentvariabledefinitionid_value
+// → { value: [{ value, _environmentvariabledefinitionid_value }], @odata.nextLink? }
+// Every definition is read (not just planData.envVars[]) because the phase
+// refresh may replace planData.envVars from last-env-vars.json AFTER this runs.
+//
+// Fail-soft per stage: a missing token / unreachable env / HTTP error is
+// recorded in `errors[]` and that stage is simply absent from `byStage`, so
+// the merge leaves its cells untouched rather than clearing them.
+//
+// Returns { byStage: { [stageLabel]: { [schemaName]: value } }, queriedStages: [label], errors: [{ stage, error }] }.
+async function fetchLiveEnvVarValues(planData, deps = {}) {
+ const helpers = require('./validation-helpers');
+ const getToken = deps.getToken || helpers.getAuthToken;
+ const request = deps.request || helpers.makeRequest;
+ const byStage = {};
+ const queriedStages = [];
+ const errors = [];
+ const stages = planData && Array.isArray(planData.stages) ? planData.stages : [];
+
+ for (const stage of stages) {
+ if (!stage || typeof stage !== 'object') continue;
+ const label = typeof stage.label === 'string' ? stage.label.trim() : '';
+ const rawUrl = typeof stage.envUrl === 'string' ? stage.envUrl.trim() : '';
+ if (!label || !rawUrl) continue;
+
+ let base;
+ try {
+ // Rejects non-Dataverse hosts so the bearer token is never sent elsewhere.
+ base = helpers.validateDataverseEnvironmentUrl(rawUrl);
+ } catch (e) {
+ errors.push({ stage: label, error: e.message });
+ continue;
+ }
+
+ const token = getToken(base);
+ if (!token) {
+ errors.push({ stage: label, error: `could not acquire a token for ${base}` });
+ continue;
+ }
+
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const defs = await helpers.odataGetAll(
+ `${base}/api/data/v9.2/environmentvariabledefinitions` +
+ '?$select=environmentvariabledefinitionid,schemaname,type',
+ token,
+ request,
+ );
+ // eslint-disable-next-line no-await-in-loop
+ const vals = await helpers.odataGetAll(
+ `${base}/api/data/v9.2/environmentvariablevalues` +
+ '?$select=value,_environmentvariabledefinitionid_value',
+ token,
+ request,
+ );
+ const schemaById = new Map();
+ for (const d of defs) {
+ if (!d || !d.environmentvariabledefinitionid || !d.schemaname) continue;
+ if (Number(d.type) === ENV_VAR_TYPE_SECRET) continue;
+ schemaById.set(String(d.environmentvariabledefinitionid).toLowerCase(), d.schemaname);
+ }
+ const values = {};
+ for (const v of vals) {
+ if (!v || v.value == null || v.value === '') continue;
+ const defId = v._environmentvariabledefinitionid_value;
+ if (!defId) continue;
+ const schemaName = schemaById.get(String(defId).toLowerCase());
+ if (!schemaName) continue;
+ values[schemaName] = String(v.value);
+ }
+ byStage[label] = values;
+ queriedStages.push(label);
+ } catch (e) {
+ errors.push({ stage: label, error: e.message });
+ }
+ }
+ return { byStage, queriedStages, errors };
+}
+
+// True when a values{} key is an alias the renderer collapses onto `label`'s
+// column. Must stay in step with buildEnvVarValuesMatrix() in
+// skills/plan-alm/scripts/render-alm-plan.js, which maps all of these onto the
+// same column:
+// "Staging" bare label
+// "Deploy to Staging" pipeline stage name
+// "Staging (Deploy to Staging)" composite label used by some settings files
+// "CitizenServicesStaging" stage.envName
+// "https://contoso.crm.dynamics.com/" stage.envUrl
+// Label-derived aliases are compared case-insensitively (hand-edited settings
+// files drift in casing); envName / envUrl are exact, like the renderer.
+function isStageAlias(key, stage, label) {
+ if (typeof key !== 'string') return false;
+ const lowerLabel = label.toLowerCase();
+ const lowerKey = key.trim().toLowerCase();
+ if (normalizeStageLabel(key).toLowerCase() === lowerLabel) return true;
+ if (lowerKey === `${lowerLabel} (deploy to ${lowerLabel})`) return true;
+ if (stage && stage.envName && key === String(stage.envName)) return true;
+ if (stage && stage.envUrl && key === String(stage.envUrl)) return true;
+ return false;
+}
+
+// True when ev.values carries a local (non-live) value for `stage` under any
+// alias the renderer collapses onto the same column (see isStageAlias).
+function hasLocalStageValue(ev, stage, label) {
+ for (const [key, value] of Object.entries(ev.values || {})) {
+ if (value == null || value === '') continue;
+ if (isLiveSourced(ev, key)) continue;
+ if (isStageAlias(key, stage, label)) return true;
+ }
+ return false;
+}
+
+// Merge live per-stage values (from fetchLiveEnvVarValues) into
+// planData.envVars[i].values{}. Precedence, highest first:
+// 1. a manual / deployment-settings.json value for that stage (any alias)
+// 2. the live value from the stage's environment
+// deployment-settings.json is backfilled FIRST so the local file always wins.
+// Live-sourced cells are tagged in ev.valueSources so a later query can update
+// them, and they are cleared when the live record has since been deleted (only
+// for stages whose query succeeded). Returns { filled, updated, cleared }.
+//
+// Local precedence is enforced for EVERY plan stage, not just the ones queried
+// successfully: if an earlier refresh left a live `Staging` cell and the user
+// has since added `Deploy to Staging` to deployment-settings.json, that stale
+// live cell must go even when this run's Staging query failed — otherwise the
+// renderer (which prefers the exact-label key) keeps showing the stale live
+// value over the local override. Live fills/updates and deleted-record cleanup
+// stay restricted to stages present in `live.byStage`.
+function mergeLiveEnvVarValues(planData, projectRoot, live) {
+ const counts = { filled: 0, updated: 0, cleared: 0 };
+ backfillEnvVarValuesFromSettings(planData, projectRoot);
+ if (!Array.isArray(planData.envVars) || planData.envVars.length === 0) return counts;
+ if (!live || !live.byStage || typeof live.byStage !== 'object') return counts;
+
+ const stageByLabel = new Map();
+ for (const stage of (Array.isArray(planData.stages) ? planData.stages : [])) {
+ if (stage && typeof stage.label === 'string' && stage.label.trim()) {
+ stageByLabel.set(stage.label.trim(), stage);
+ }
+ }
+ const labels = new Set([...stageByLabel.keys(), ...Object.keys(live.byStage)]);
+ const liveLowerByStage = new Map();
+ for (const [label, valuesBySchema] of Object.entries(live.byStage)) {
+ const lower = new Map();
+ for (const [schemaName, value] of Object.entries(valuesBySchema || {})) {
+ lower.set(schemaName.toLowerCase(), value);
+ }
+ liveLowerByStage.set(label, lower);
+ }
+
+ for (const ev of planData.envVars) {
+ if (!ev || typeof ev.schemaName !== 'string') continue;
+ ev.values = (ev.values && typeof ev.values === 'object') ? ev.values : {};
+ for (const label of labels) {
+ const stage = stageByLabel.get(label) || null;
+ const currentIsLive = isLiveSourced(ev, label);
+ if (hasLocalStageValue(ev, stage, label)) {
+ // Local value wins; drop a stale live cell so the renderer (which
+ // prefers the exact label key) can't show it over the local alias.
+ if (currentIsLive) {
+ delete ev.values[label];
+ setValueSource(ev, label, null);
+ counts.cleared += 1;
+ }
+ continue;
+ }
+ // Query failed or stage not queried: leave its cells exactly as they are.
+ if (!liveLowerByStage.has(label)) continue;
+ // Case-insensitive: the plan's schemaName can come from a discovery
+ // sidecar whose casing differs from what this env's query returned.
+ const liveValue = liveLowerByStage.get(label).get(ev.schemaName.toLowerCase());
+ if (liveValue == null || liveValue === '') {
+ if (currentIsLive) {
+ delete ev.values[label];
+ setValueSource(ev, label, null);
+ counts.cleared += 1;
+ }
+ continue;
+ }
+ if (currentIsLive && ev.values[label] === liveValue) continue;
+ if (currentIsLive) counts.updated += 1;
+ else counts.filled += 1;
+ ev.values[label] = liveValue;
+ setValueSource(ev, label, 'live');
+ }
+ }
+ return counts;
+}
+
// Flip a matching entry in planData.steps[] to the given status. Each phase
// owns a "what step does this complete?" rule, captured at the bottom of the
// per-phase refresh function. The agent used to flip steps[i].status by hand
@@ -691,7 +995,8 @@ function refreshSetupSolution(planData, projectRoot) {
// valid post-state: setup-solution may have skipped all env vars (Tier 1
// Skip-all + no Tier 2 promotions), in which case the tab should reflect
// the empty existing state instead of carrying stale planned counts.
- planData.envVars = envVarsMarker.envVars;
+ // Per-stage values/valueSources are carried forward by schema name.
+ planData.envVars = carryForwardEnvVarValues(planData.envVars, envVarsMarker.envVars);
}
// Refresh sizeAnalysis.envVarCount so the Overview stat card + Size Analysis
// signal reflect the post-setup-solution count (after OAuth promotions,
@@ -922,7 +1227,8 @@ function refreshConfigureEnvVariables(planData, projectRoot) {
}
const envVarsMarker = projectRoot ? readJson(almPath(projectRoot, 'lastEnvVars')) : null;
if (envVarsMarker && Array.isArray(envVarsMarker.envVars)) {
- planData.envVars = envVarsMarker.envVars;
+ // Keep per-stage values/valueSources by schema name — discovery rows have none.
+ planData.envVars = carryForwardEnvVarValues(planData.envVars, envVarsMarker.envVars);
}
// Backfill is the major payoff for this phase — the user just authored
// per-stage values in deployment-settings.json and the rendered plan should
@@ -1144,7 +1450,7 @@ function invokeRenderer(rendererPath, dataPath, outputPath) {
});
}
-function refresh({ projectRoot, phase, render, rendererPath, stageName }) {
+function refresh({ projectRoot, phase, render, rendererPath, stageName, liveEnvVarValues }) {
if (!projectRoot) throw new Error('--projectRoot is required');
if (!phase) throw new Error('--phase is required');
if (!PHASES.has(phase)) {
@@ -1170,6 +1476,17 @@ function refresh({ projectRoot, phase, render, rendererPath, stageName }) {
}
applyRefresh(planData, phase, projectRoot, stageName);
+ // `liveEnvVarValues` is the pre-fetched result of fetchLiveEnvVarValues (CLI
+ // `--live`). Merged after the phase handler so it sees the phase's final
+ // planData.envVars[] (configure-env-variables / setup-solution may replace it).
+ let liveEnvVars;
+ if (liveEnvVarValues) {
+ liveEnvVars = {
+ ...mergeLiveEnvVarValues(planData, projectRoot, liveEnvVarValues),
+ queriedStages: liveEnvVarValues.queriedStages || [],
+ errors: liveEnvVarValues.errors || [],
+ };
+ }
evaluatePlanCompletion(planData);
fs.writeFileSync(dataPath, JSON.stringify(planData, null, 2), 'utf8');
@@ -1184,19 +1501,35 @@ function refresh({ projectRoot, phase, render, rendererPath, stageName }) {
// sequencing — never auto-fired). null when the plan is fully executed.
const nextStep = computeNextStep(planData);
- return { ok: true, phase, dataPath, htmlPath, rendered, nextStep };
+ const result = { ok: true, phase, dataPath, htmlPath, rendered, nextStep };
+ if (liveEnvVars) result.liveEnvVars = liveEnvVars;
+ return result;
+}
+
+// CLI entry. `--live` pre-fetches live env var values (async, network) before
+// the synchronous refresh so refresh() stays sync for its in-process callers.
+// The fetch is skipped when there is no plan to refresh — refresh() then
+// returns its usual ok:false soft no-op without any az / Dataverse calls.
+async function runCli(args, deps = {}) {
+ if (args.reconcile) return reconcile(args);
+ if (args.live && args.projectRoot) {
+ const planData = readJson(planDataPath(args.projectRoot));
+ if (planData) {
+ args = { ...args, liveEnvVarValues: await fetchLiveEnvVarValues(planData, deps) };
+ }
+ }
+ return refresh(args);
}
if (require.main === module) {
const args = parseArgs(process.argv);
- try {
- const result = args.reconcile ? reconcile(args) : refresh(args);
+ runCli(args).then((result) => {
process.stdout.write(JSON.stringify(result) + '\n');
process.exit(0); // ok:false (missing planData / deferred) is a soft no-op
- } catch (err) {
+ }, (err) => {
process.stderr.write('refresh-alm-plan-data: ' + err.message + '\n');
process.exit(1);
- }
+ });
}
module.exports = {
@@ -1206,6 +1539,9 @@ module.exports = {
dropResolvedRisks,
setStepStatus,
backfillEnvVarValuesFromSettings,
+ fetchLiveEnvVarValues,
+ mergeLiveEnvVarValues,
+ runCli,
extractPerStageValues,
computeNextStep,
mapStepToSkill,
diff --git a/plugins/power-pages/scripts/tests/refresh-alm-plan-data.test.js b/plugins/power-pages/scripts/tests/refresh-alm-plan-data.test.js
index d538fff2c..692a99ff3 100644
--- a/plugins/power-pages/scripts/tests/refresh-alm-plan-data.test.js
+++ b/plugins/power-pages/scripts/tests/refresh-alm-plan-data.test.js
@@ -2020,3 +2020,361 @@ test('reconcile: soft no-op when there is no plan', (t) => {
assert.equal(result.ok, false);
assert.equal(result.reason, 'no-plan');
});
+
+// ── Live env var values (--live) ─────────────────────────────────────────
+//
+// Values set in Power Platform Admin Center never touch deployment-settings.json,
+// so `--live` queries each stage's `environmentvariablevalues` table and merges
+// the result in. Local values (deployment-settings.json / manual edits) win.
+// Token + HTTP are injected — these tests never shell out to az or hit a network.
+
+const {
+ fetchLiveEnvVarValues,
+ mergeLiveEnvVarValues,
+ runCli,
+} = require('../lib/refresh-alm-plan-data');
+
+const LIVE_STAGING = 'https://contoso-staging.crm.dynamics.com';
+const LIVE_PROD = 'https://contoso-prod.crm.dynamics.com';
+
+// Fake makeRequest: routes by host + entity set to canned OData bodies.
+function fakeLiveRequest(tables, calls = []) {
+ return async ({ url, headers }) => {
+ calls.push({ url, auth: headers.Authorization });
+ const u = new URL(url);
+ const entity = u.pathname.split('/').pop();
+ const body = tables[u.origin] && tables[u.origin][entity];
+ if (body === undefined) return { statusCode: 500, body: 'boom' };
+ return { statusCode: 200, body: JSON.stringify({ value: body }) };
+ };
+}
+
+const LIVE_TABLES = {
+ [LIVE_STAGING]: {
+ environmentvariabledefinitions: [
+ { environmentvariabledefinitionid: 'AAAA0000-0000-0000-0000-000000000001', schemaname: 'cr5fe_apiBaseUrl', type: 100000000 },
+ { environmentvariabledefinitionid: 'aaaa0000-0000-0000-0000-000000000002', schemaname: 'cr5fe_localLoginEnabled', type: 100000002 },
+ { environmentvariabledefinitionid: 'aaaa0000-0000-0000-0000-000000000003', schemaname: 'cr5fe_clientSecret', type: 100000005 },
+ ],
+ environmentvariablevalues: [
+ { value: 'https://ppac-staging.example.com', _environmentvariabledefinitionid_value: 'aaaa0000-0000-0000-0000-000000000001' },
+ { value: 'false', _environmentvariabledefinitionid_value: 'aaaa0000-0000-0000-0000-000000000002' },
+ { value: 'https://vault.vault.azure.net/secrets/x', _environmentvariabledefinitionid_value: 'aaaa0000-0000-0000-0000-000000000003' },
+ ],
+ },
+ [LIVE_PROD]: {
+ environmentvariabledefinitions: [
+ { environmentvariabledefinitionid: 'bbbb0000-0000-0000-0000-000000000001', schemaname: 'cr5fe_apiBaseUrl', type: 100000000 },
+ ],
+ environmentvariablevalues: [
+ { value: 'https://ppac-prod.example.com', _environmentvariabledefinitionid_value: 'bbbb0000-0000-0000-0000-000000000001' },
+ ],
+ },
+};
+
+test('live: fetchLiveEnvVarValues maps value rows to schema names per stage and skips Secret definitions', async () => {
+ const calls = [];
+ const live = await fetchLiveEnvVarValues({
+ stages: [
+ { label: 'Staging', envUrl: LIVE_STAGING + '/', type: 'target' },
+ { label: 'Production', envUrl: LIVE_PROD, type: 'target' },
+ { label: 'NoUrl', type: 'target' },
+ ],
+ }, { getToken: (url) => 'tok-' + url, request: fakeLiveRequest(LIVE_TABLES, calls) });
+
+ assert.deepEqual(live.queriedStages, ['Staging', 'Production']);
+ assert.deepEqual(live.errors, []);
+ assert.deepEqual(live.byStage, {
+ Staging: { cr5fe_apiBaseUrl: 'https://ppac-staging.example.com', cr5fe_localLoginEnabled: 'false' },
+ Production: { cr5fe_apiBaseUrl: 'https://ppac-prod.example.com' },
+ });
+ assert.equal(calls.length, 4);
+ assert.ok(calls.every((c) => c.auth.endsWith(' tok-' + new URL(c.url).origin)), 'per-stage token must be used');
+});
+
+test('live: fetchLiveEnvVarValues records per-stage failures without throwing', async () => {
+ const live = await fetchLiveEnvVarValues({
+ stages: [
+ { label: 'Staging', envUrl: LIVE_STAGING },
+ { label: 'Production', envUrl: LIVE_PROD },
+ { label: 'Evil', envUrl: 'https://attacker.example.com' },
+ ],
+ }, {
+ getToken: (url) => (url.includes('prod') ? null : 'tok'),
+ request: fakeLiveRequest({}),
+ });
+ assert.deepEqual(live.byStage, {});
+ assert.deepEqual(live.queriedStages, []);
+ assert.deepEqual(live.errors.map((e) => e.stage), ['Staging', 'Production', 'Evil']);
+});
+
+test('live: merge fills empty cells, prefers deployment-settings.json and manual values', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'deployment-settings.json'), {
+ stages: { 'Deploy to Staging': { EnvironmentVariables: [{ SchemaName: 'cr5fe_apiBaseUrl', Value: 'https://file-staging.example.com' }] } },
+ });
+ const planData = {
+ stages: [{ label: 'Staging', envUrl: LIVE_STAGING }, { label: 'Production', envUrl: LIVE_PROD }],
+ envVars: [
+ { schemaName: 'cr5fe_apiBaseUrl', values: { Production: 'manual-prod' } },
+ { schemaName: 'cr5fe_localLoginEnabled' },
+ ],
+ };
+ const counts = mergeLiveEnvVarValues(planData, root, {
+ byStage: {
+ Staging: { cr5fe_apiBaseUrl: 'https://ppac-staging.example.com', cr5fe_localLoginEnabled: 'false' },
+ Production: { cr5fe_apiBaseUrl: 'https://ppac-prod.example.com' },
+ },
+ });
+ assert.deepEqual(planData.envVars[0].values, {
+ Production: 'manual-prod',
+ 'Deploy to Staging': 'https://file-staging.example.com',
+ }, 'local file (any stage alias) and manual values must win over live');
+ assert.deepEqual(planData.envVars[0].valueSources, { 'Deploy to Staging': 'settings' });
+ assert.deepEqual(planData.envVars[1].values, { Staging: 'false' });
+ assert.deepEqual(planData.envVars[1].valueSources, { Staging: 'live' });
+ assert.deepEqual(counts, { filled: 1, updated: 0, cleared: 0 });
+});
+
+test('live: live-sourced cells are updated, cleared, and superseded by the local file on later refreshes', (t) => {
+ const root = makeProject(t);
+ const planData = {
+ stages: [{ label: 'Staging', envUrl: LIVE_STAGING }, { label: 'Production', envUrl: LIVE_PROD }],
+ envVars: [{
+ schemaName: 'cr5fe_apiBaseUrl',
+ values: { Staging: 'old-live', Production: 'old-live-prod' },
+ valueSources: { Staging: 'live', Production: 'live' },
+ }],
+ };
+ // Staging value changed in PPAC; Production value record deleted.
+ let counts = mergeLiveEnvVarValues(planData, root, {
+ byStage: { Staging: { cr5fe_apiBaseUrl: 'new-live' }, Production: {} },
+ });
+ assert.deepEqual(planData.envVars[0].values, { Staging: 'new-live' });
+ assert.deepEqual(planData.envVars[0].valueSources, { Staging: 'live' });
+ assert.deepEqual(counts, { filled: 0, updated: 1, cleared: 1 });
+
+ // A stage whose query failed (absent from byStage) leaves its cells untouched.
+ counts = mergeLiveEnvVarValues(planData, root, { byStage: {} });
+ assert.deepEqual(planData.envVars[0].values, { Staging: 'new-live' });
+
+ // The user then writes the value into deployment-settings.json — local wins.
+ writeJson(path.join(root, 'deployment-settings.json'), {
+ Staging: { EnvironmentVariables: [{ SchemaName: 'cr5fe_apiBaseUrl', Value: 'file-value' }] },
+ });
+ mergeLiveEnvVarValues(planData, root, { byStage: { Staging: { cr5fe_apiBaseUrl: 'new-live' } } });
+ assert.deepEqual(planData.envVars[0].values, { Staging: 'file-value' });
+ assert.deepEqual(planData.envVars[0].valueSources, { Staging: 'settings' });
+});
+
+test('live: runCli --live merges live values into the refreshed plan and reports a summary', async (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ stages: [{ label: 'Dev', envUrl: 'https://contoso-dev.crm.dynamics.com', type: 'source' }, { label: 'Staging', envUrl: LIVE_STAGING, type: 'target' }],
+ envVars: [{ schemaName: 'cr5fe_apiBaseUrl' }],
+ steps: [{ name: 'Configure environment variables', status: 'pending' }],
+ });
+ const result = await runCli(
+ { projectRoot: root, phase: 'configure-env-variables', render: false, live: true },
+ { getToken: () => 'tok', request: fakeLiveRequest(LIVE_TABLES) },
+ );
+ assert.equal(result.ok, true);
+ assert.deepEqual(result.liveEnvVars.queriedStages, ['Staging']);
+ assert.deepEqual(result.liveEnvVars.errors.map((e) => e.stage), ['Dev']);
+ assert.equal(result.liveEnvVars.filled, 1);
+ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));
+ assert.deepEqual(planData.envVars[0].values, { Staging: 'https://ppac-staging.example.com' });
+});
+
+test('live: runCli without --live never queries Dataverse', async (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ stages: [{ label: 'Staging', envUrl: LIVE_STAGING }],
+ envVars: [{ schemaName: 'cr5fe_apiBaseUrl' }],
+ steps: [],
+ });
+ const result = await runCli(
+ { projectRoot: root, phase: 'deploy-pipeline', render: false, live: false },
+ { getToken: () => { throw new Error('must not be called'); } },
+ );
+ assert.equal(result.ok, true);
+ assert.equal(result.liveEnvVars, undefined);
+});
+
+test('live: runCli --live is a soft no-op (no token request) when the plan is missing', async (t) => {
+ const root = makeProject(t);
+ const result = await runCli(
+ { projectRoot: root, phase: 'deploy-pipeline', render: false, live: true },
+ { getToken: () => { throw new Error('must not be called'); } },
+ );
+ assert.equal(result.ok, false);
+});
+
+test('live: a local value under the composite "{label} (Deploy to {label})" alias beats the live value', (t) => {
+ // render-alm-plan.js folds "Staging (Deploy to Staging)" onto the Staging
+ // column, so a settings value under that key is the local override for Staging.
+ const root = makeProject(t);
+ writeJson(path.join(root, 'deployment-settings.json'), {
+ 'Staging (Deploy to Staging)': { EnvironmentVariables: [{ SchemaName: 'cr5fe_apiBaseUrl', Value: 'file-composite' }] },
+ });
+ const planData = {
+ stages: [{ label: 'Staging', envUrl: LIVE_STAGING }],
+ envVars: [{ schemaName: 'cr5fe_apiBaseUrl' }],
+ };
+ const counts = mergeLiveEnvVarValues(planData, root, {
+ byStage: { Staging: { cr5fe_apiBaseUrl: 'https://ppac-staging.example.com' } },
+ });
+ assert.deepEqual(planData.envVars[0].values, { 'Staging (Deploy to Staging)': 'file-composite' });
+ assert.deepEqual(planData.envVars[0].valueSources, { 'Staging (Deploy to Staging)': 'settings' });
+ assert.deepEqual(counts, { filled: 0, updated: 0, cleared: 0 });
+
+ // A pre-existing live cell under the bare label is dropped once the composite local value exists.
+ planData.envVars[0].values.Staging = 'stale-live';
+ planData.envVars[0].valueSources = { ...planData.envVars[0].valueSources, Staging: 'live' };
+ mergeLiveEnvVarValues(planData, root, {
+ byStage: { Staging: { cr5fe_apiBaseUrl: 'https://ppac-staging.example.com' } },
+ });
+ assert.deepEqual(planData.envVars[0].values, { 'Staging (Deploy to Staging)': 'file-composite' });
+ assert.deepEqual(planData.envVars[0].valueSources, { 'Staging (Deploy to Staging)': 'settings' });
+});
+
+test('live: a new local alias replaces a stale live cell even when that stage query failed', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'deployment-settings.json'), {
+ stages: { 'Deploy to Staging': { EnvironmentVariables: [{ SchemaName: 'cr5fe_apiBaseUrl', Value: 'file-staging' }] } },
+ });
+ const planData = {
+ stages: [{ label: 'Staging', envUrl: LIVE_STAGING }, { label: 'Production', envUrl: LIVE_PROD }],
+ envVars: [{
+ schemaName: 'cr5fe_apiBaseUrl',
+ values: { Staging: 'old-live', Production: 'live-prod' },
+ valueSources: { Staging: 'live', Production: 'live' },
+ }],
+ };
+ // Staging's query failed (absent from byStage); Production succeeded unchanged.
+ const counts = mergeLiveEnvVarValues(planData, root, {
+ byStage: { Production: { cr5fe_apiBaseUrl: 'live-prod' } },
+ });
+ assert.deepEqual(planData.envVars[0].values, { Production: 'live-prod', 'Deploy to Staging': 'file-staging' });
+ assert.deepEqual(planData.envVars[0].valueSources, { Production: 'live', 'Deploy to Staging': 'settings' });
+ assert.deepEqual(counts, { filled: 0, updated: 0, cleared: 1 });
+});
+
+test('live: re-ingesting last-env-vars.json keeps values/provenance when a stage query fails', async (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ stages: [{ label: 'Staging', envUrl: LIVE_STAGING, type: 'target' }],
+ envVars: [
+ { schemaName: 'cr5fe_apiBaseUrl', values: { Staging: 'live-staging', Production: 'manual-prod' }, valueSources: { Staging: 'live' } },
+ { schemaName: 'cr5fe_featureFlag', values: { Staging: 'manual-flag' } },
+ { schemaName: 'cr5fe_removed', values: { Staging: 'gone' }, valueSources: { Staging: 'live' } },
+ ],
+ steps: [{ name: 'Configure environment variables', status: 'pending' }],
+ });
+ // Discovery sidecar: no values, different casing, one definition removed, and
+ // one row that carries its own value (which must win for that key).
+ writeJson(path.join(root, 'docs', 'alm', 'last-env-vars.json'), {
+ envVars: [
+ { schemaName: 'CR5FE_APIBASEURL', type: 'String' },
+ { schemaName: 'cr5fe_featureFlag', type: 'Boolean', values: { Staging: 'marker-flag' } },
+ { schemaName: 'cr5fe_brandNew', type: 'String' },
+ ],
+ });
+ const result = await runCli(
+ { projectRoot: root, phase: 'configure-env-variables', render: false, live: true },
+ { getToken: () => 'tok', request: fakeLiveRequest({}) },
+ );
+ assert.deepEqual(result.liveEnvVars.errors.map((e) => e.stage), ['Staging']);
+ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));
+ assert.deepEqual(planData.envVars.map((e) => e.schemaName), ['CR5FE_APIBASEURL', 'cr5fe_featureFlag', 'cr5fe_brandNew']);
+ assert.deepEqual(planData.envVars[0].values, { Staging: 'live-staging', Production: 'manual-prod' });
+ assert.deepEqual(planData.envVars[0].valueSources, { Staging: 'live' });
+ assert.equal(planData.envVars[0].type, 'String', 'definition metadata comes from the sidecar');
+ assert.deepEqual(planData.envVars[1].values, { Staging: 'marker-flag' });
+ assert.equal(planData.envVars[1].valueSources, undefined);
+ assert.deepEqual(planData.envVars[2].values || {}, {});
+});
+
+test('live: a changed deployment-settings.json value replaces the earlier file value across configure runs', async (t) => {
+ const root = makeProject(t);
+ const settingsPath = path.join(root, 'deployment-settings.json');
+ const writeSettings = (value) => writeJson(settingsPath, {
+ Staging: { EnvironmentVariables: [{ SchemaName: 'cr5fe_apiBaseUrl', Value: value }] },
+ });
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ stages: [{ label: 'Staging', envUrl: LIVE_STAGING, type: 'target' }],
+ envVars: [{ schemaName: 'cr5fe_apiBaseUrl', values: { Production: 'manual-prod' } }],
+ steps: [{ name: 'Configure environment variables', status: 'pending' }],
+ });
+ // The discovery sidecar is present on every run, so values are carried forward.
+ writeJson(path.join(root, 'docs', 'alm', 'last-env-vars.json'), {
+ envVars: [{ schemaName: 'cr5fe_apiBaseUrl', type: 'String' }],
+ });
+ const deps = { getToken: () => 'tok', request: fakeLiveRequest(LIVE_TABLES) };
+ const run = () => runCli({ projectRoot: root, phase: 'configure-env-variables', render: false, live: true }, deps);
+ const read = () => readJson(path.join(root, 'docs', '.alm-plan-data.json')).envVars[0];
+
+ writeSettings('file-v1');
+ await run();
+ assert.deepEqual(read().values, { Production: 'manual-prod', Staging: 'file-v1' });
+ assert.deepEqual(read().valueSources, { Staging: 'settings' });
+
+ writeSettings('file-v2');
+ await run();
+ assert.deepEqual(read().values, { Production: 'manual-prod', Staging: 'file-v2' },
+ 'the updated file value must replace the earlier backfilled one; the manual cell is untouched');
+ assert.deepEqual(read().valueSources, { Staging: 'settings' });
+});
+
+test('live: schema names match case-insensitively when a stage query succeeds', async (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ stages: [{ label: 'Staging', envUrl: LIVE_STAGING, type: 'target' }],
+ envVars: [
+ { schemaName: 'cr5fe_apiBaseUrl', values: { Staging: 'old-live' }, valueSources: { Staging: 'live' } },
+ { schemaName: 'cr5fe_localLoginEnabled' },
+ ],
+ steps: [{ name: 'Configure environment variables', status: 'pending' }],
+ });
+ // Sidecar casing differs from what the env returns (cr5fe_apiBaseUrl / cr5fe_localLoginEnabled).
+ writeJson(path.join(root, 'docs', 'alm', 'last-env-vars.json'), {
+ envVars: [
+ { schemaName: 'CR5FE_APIBASEURL', type: 'String' },
+ { schemaName: 'CR5FE_LOCALLOGINENABLED', type: 'Boolean' },
+ ],
+ });
+ const result = await runCli(
+ { projectRoot: root, phase: 'configure-env-variables', render: false, live: true },
+ { getToken: () => 'tok', request: fakeLiveRequest(LIVE_TABLES) },
+ );
+ assert.deepEqual(result.liveEnvVars.queriedStages, ['Staging']);
+ assert.deepEqual({ filled: result.liveEnvVars.filled, updated: result.liveEnvVars.updated, cleared: result.liveEnvVars.cleared },
+ { filled: 1, updated: 1, cleared: 0 });
+ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));
+ assert.deepEqual(planData.envVars[0].values, { Staging: 'https://ppac-staging.example.com' });
+ assert.deepEqual(planData.envVars[0].valueSources, { Staging: 'live' });
+ assert.deepEqual(planData.envVars[1].values, { Staging: 'false' });
+ assert.deepEqual(planData.envVars[1].valueSources, { Staging: 'live' });
+});
+
+test('live: settings entries whose schema names differ only by case are merged across stages', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'deployment-settings.json'), {
+ Staging: { EnvironmentVariables: [{ SchemaName: 'cr5fe_apiBaseUrl', Value: 'file-staging' }] },
+ Production: { EnvironmentVariables: [{ SchemaName: 'CR5FE_APIBASEURL', Value: 'file-prod' }] },
+ });
+ const planData = {
+ stages: [{ label: 'Staging', envUrl: LIVE_STAGING }, { label: 'Production', envUrl: LIVE_PROD }],
+ envVars: [{ schemaName: 'cr5fe_apiBaseUrl' }],
+ };
+ const counts = mergeLiveEnvVarValues(planData, root, {
+ byStage: {
+ Staging: { cr5fe_apiBaseUrl: 'https://ppac-staging.example.com' },
+ Production: { cr5fe_apiBaseUrl: 'https://ppac-prod.example.com' },
+ },
+ });
+ assert.deepEqual(planData.envVars[0].values, { Staging: 'file-staging', Production: 'file-prod' },
+ 'both stages keep their local value; neither spelling may drop the other');
+ assert.deepEqual(planData.envVars[0].valueSources, { Staging: 'settings', Production: 'settings' });
+ assert.deepEqual(counts, { filled: 0, updated: 0, cleared: 0 });
+});
\ No newline at end of file
diff --git a/plugins/power-pages/skills/configure-env-variables/SKILL.md b/plugins/power-pages/skills/configure-env-variables/SKILL.md
index c1a2d5c61..98f815cfb 100644
--- a/plugins/power-pages/skills/configure-env-variables/SKILL.md
+++ b/plugins/power-pages/skills/configure-env-variables/SKILL.md
@@ -488,10 +488,13 @@ Follow the skill tracking instructions in the reference to record this skill's u
node "${PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
--projectRoot "." \
--phase configure-env-variables \
+ --live \
--render
```
-The helper re-reads `docs/alm/last-env-vars.json` so newly-created definitions appear in `planData.envVars[]`, backfills per-stage values from `deployment-settings.json` into the "Values by Environment" matrix, zeroes `plannedEnvVarCount`, stamps `LAST_SYNC_AT`, and re-renders `docs/alm-plan.html`. When `docs/.alm-plan-data.json` is absent (standalone invocation, not part of an ALM plan), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+The helper re-reads `docs/alm/last-env-vars.json` so newly-created definitions appear in `planData.envVars[]`, backfills per-stage values from `deployment-settings.json` into the "Values by Environment" matrix (`--live` also merges values read from each plan stage's live `environmentvariablevalues` table, so values set in Power Platform Admin Center show up; `deployment-settings.json` values win, and a stage whose query fails is listed in the output's `liveEnvVars.errors` and left unchanged), zeroes `plannedEnvVarCount`, stamps `LAST_SYNC_AT`, and re-renders `docs/alm-plan.html`. When `docs/.alm-plan-data.json` is absent (standalone invocation, not part of an ALM plan), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+
+**Surface live-query failures.** When the helper's stdout JSON has a non-empty `liveEnvVars.errors[]`, tell the user which stages could not be read, one line each: *"Could not read live environment variable values for **{stage}**: {error}. That column of the Values by Environment matrix was left unchanged, so values set in Power Platform Admin Center for it may be missing or stale."* When an error is an HTTP 401/403 or says a token could not be acquired, the Azure CLI is most likely signed in to a different tenant than that environment (`az` issues tokens for its default subscription's tenant, which can differ from the PAC CLI profile), so suggest `az login --tenant <environment tenant id>` (or `az account set --subscription <a subscription in that tenant>`) and re-running the refresh command above. This is informational — do not fail the skill or block the summary. Say nothing when `liveEnvVars` is absent or `errors` is empty.
**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. When non-null, branch on `skill`: when `skill` is non-null, tell the user *"Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."*; when `skill` is `null` (an internal step such as Finalize, no user command), name the step only — *"Plan updated. Next in your plan: **{nextStep.name}**."* — and never print `run null`. When `null` or the helper returned `ok:false`, say nothing about a next step. **Never auto-invoke the next skill** — the user drives execution.
diff --git a/plugins/power-pages/skills/deploy-pipeline/SKILL.md b/plugins/power-pages/skills/deploy-pipeline/SKILL.md
index 247e9de30..87010ba6f 100644
--- a/plugins/power-pages/skills/deploy-pipeline/SKILL.md
+++ b/plugins/power-pages/skills/deploy-pipeline/SKILL.md
@@ -952,13 +952,16 @@ Follow the skill tracking instructions in the reference to record this skill's u
node "${PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
--projectRoot "." \
--phase deploy-pipeline \
+ --live \
--render
```
-The helper reads the `docs/alm/last-deploy.json` you just wrote, ingests it into `planData.pipelineMeta.lastDeploy`, drops any pre-deploy "host not yet provisioned" risks, and re-renders `docs/alm-plan.html` so the Pipelines tab shows the actual run state (status, version, component count, activation, site URL). When `docs/.alm-plan-data.json` is absent (the skill was invoked standalone, not part of an ALM plan), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+The helper reads the `docs/alm/last-deploy.json` you just wrote, ingests it into `planData.pipelineMeta.lastDeploy`, merges per-stage env var values (from `deployment-settings.json`, plus — via `--live` — each plan stage's live `environmentvariablevalues` table, with the file winning), drops any pre-deploy "host not yet provisioned" risks, and re-renders `docs/alm-plan.html` so the Pipelines tab shows the actual run state (status, version, component count, activation, site URL). When `docs/.alm-plan-data.json` is absent (the skill was invoked standalone, not part of an ALM plan), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
This step is what keeps the rendered plan current — `plan-alm` is a planner and does not refresh the plan itself, so each execution skill owns its own post-run refresh. Running it more than once is idempotent (same input → same output).
+**Surface live-query failures.** When the helper's stdout JSON has a non-empty `liveEnvVars.errors[]`, tell the user which stages could not be read, one line each: *"Could not read live environment variable values for **{stage}**: {error}. That column of the Values by Environment matrix was left unchanged, so values set in Power Platform Admin Center for it may be missing or stale."* When an error is an HTTP 401/403 or says a token could not be acquired, the Azure CLI is most likely signed in to a different tenant than that environment (`az` issues tokens for its default subscription's tenant, which can differ from the PAC CLI profile), so suggest `az login --tenant <environment tenant id>` (or `az account set --subscription <a subscription in that tenant>`) and re-running the refresh command above. This is informational — do not fail the deploy or block the 7.6 summary. Say nothing when `liveEnvVars` is absent or `errors` is empty.
+
**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. When non-null, branch on `skill`: when `skill` is non-null, tell the user *"Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."*; when `skill` is `null` (an internal step such as Finalize, no user command), name the step only — *"Plan updated. Next in your plan: **{nextStep.name}**."* — and never print `run null`. (For a multi-stage pipeline this is typically the next stage's deploy, or the next stage's activate/test if those are separate steps.) When `null` (all steps done) or the helper returned `ok:false` (no plan), say nothing about a next step. **Never auto-invoke the next skill** — the user drives execution.
**7.6 Present summary:**