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.

Add manage-governance Power Pages skill (#309)

kumarsach07fc1625b74dd8
diff --git a/evals/power-pages/manage-governance/evals.json b/evals/power-pages/manage-governance/evals.json
new file mode 100644
index 000000000..f11f92e16
--- /dev/null
+++ b/evals/power-pages/manage-governance/evals.json
@@ -0,0 +1,181 @@
+{
+ "skill_name": "manage-governance",
+ "evals": [
+ {
+ "id": 1,
+ "prompt": "What is the status of the External Authentication providers governance setting in the Sachin-preprod-July environment?",
+ "expected_output": "A Fetch Env read of EnableExternalAuthProviders for the named environment. External Auth is a leaf policy (no gating parents), so get-effective-status.js fires exactly two API calls (getEnv + getDetails) in one batch with an empty dependency list. The reply is the bold one-line env-level summary leading with the correct state icon, followed by the mandated 5-column Unicode status box (# | Name | URL | Site ID | State) with a green/red icon per site.",
+ "files": [],
+ "expectations": [
+ "Confirms PAC CLI and Azure CLI are signed in before running any governance read",
+ "Renders the full environment list and lets the user keep/switch before reading (env only pre-flagged as the default)",
+ "Recognizes 'External Authentication providers' as the EnableExternalAuthProviders policy",
+ "Reads state via get-effective-status.js as a single parallel batch (env value + per-site details); because External Auth has no parents the dependency list is empty and only two API calls are made",
+ "Renders a bold one-line plain-language summary that leads with the state icon (green when on for some/all sites, red when off everywhere)",
+ "Always also renders the full per-site status as the fixed-width Unicode box inside a fenced code block, with a rule between every row",
+ "The status box shows EXACTLY the five columns # | Name | URL | Site ID | State — never adds, drops, reorders, or renames a column",
+ "Each State cell shows the green Enabled / red Disabled icon",
+ "Uses plain language and does not surface internal terms (policyValue, InclusionList, ExclusionList, Include, Exclude) to the user"
+ ]
+ },
+ {
+ "id": 2,
+ "prompt": "What is the status of the OpenID Connect (OIDC) setting in the Sachin-preprod-July environment?",
+ "expected_output": "A parent-aware effective-status read of EnableProtocolOpenIdConnect. OIDC is a gated child of External Auth, so get-effective-status.js reads OIDC and its External Auth parent in ONE parallel batch (four API calls: getEnv + getDetails for each policy) and computes each site's effective state as its own OIDC setting AND the External Auth parent. The result is rendered as the same 5-column Unicode box with a single effective State column — the parent chain is computed inside the script and never shown as an extra column.",
+ "files": [],
+ "expectations": [
+ "Recognizes 'OIDC' / 'OpenID Connect' as the EnableProtocolOpenIdConnect policy",
+ "Treats OpenID Connect as a gated child whose availability depends on the External Auth parent (EnableExternalAuthProviders)",
+ "Uses get-effective-status.js to read OIDC and External Auth together in one parallel Promise.all batch (getEnv + getDetails per policy), not one portal at a time",
+ "Resolves the governance context once and shares it across all calls in the batch (does not re-mint the auth token per call)",
+ "Marks a site as effectively Enabled only when its own OIDC state AND the External Auth parent are both Enabled",
+ "Renders the result as the fixed-width 5-column Unicode box (# | Name | URL | Site ID | State) — no External Auth parent column, no separate Effective column, no paraphrase column",
+ "Each State cell shows the green Enabled / red Disabled icon",
+ "Explains in prose why any disabled site is off (own setting off vs blocked by the External Auth parent)"
+ ]
+ },
+ {
+ "id": 3,
+ "prompt": "What is the status of Google sign-in in the Sachin-preprod-July environment?",
+ "expected_output": "A two-parent effective-status read of EnableIdpOAuthGoogle. Google is a social IdP gated by External Auth then OAuth 2.0, so get-effective-status.js fires all six API calls (getEnv + getDetails for Google, External Auth, and OAuth 2.0) in ONE parallel Promise.all wave and computes each site's effective state as Google's own setting AND both parents. The result is rendered as the same 5-column Unicode box with a single effective State column — both parents are computed inside the script and never shown as extra columns.",
+ "files": [],
+ "expectations": [
+ "Recognizes 'Google' / 'Google sign-in' as the EnableIdpOAuthGoogle policy",
+ "Treats Google as a social IdP with two parents: External Auth and OAuth 2.0 (OpenAuth)",
+ "Uses get-effective-status.js to read Google and both parents together in one parallel batch of six API calls, not per-portal reads and not three sequential env+details round-trips",
+ "Resolves the governance context once and shares it across all six calls with a longer batch timeout so the concurrent slow-gateway calls do not time out",
+ "Marks a site effectively Enabled only when Google's own state AND both parents (External Auth AND OAuth 2.0) are all Enabled",
+ "Renders the result as the fixed-width 5-column Unicode box (# | Name | URL | Site ID | State) — no parent columns, no Effective column, no paraphrase column",
+ "Shows green / red icons in every State cell",
+ "Explains per-site why a site is disabled (own setting off, OAuth 2.0 parent off, or External Auth parent off)"
+ ]
+ },
+ {
+ "id": 4,
+ "prompt": "Disable OAuth 2.0 in Sachin-preprod-July, only on Portal_5.",
+ "expected_output": "A Set (disable) of EnableProtocolOpenAuth scoped to a single site via an Exclude policy value. The skill lists the sites, resolves Portal_5, reads current state to build the impact summary (including the cascade of OAuth-based social providers), gets explicit consent, applies asynchronously, and verifies the result rendered as the 5-column Unicode box.",
+ "files": [],
+ "expectations": [
+ "Recognizes 'OAuth 2.0' / 'OAuth2' as the EnableProtocolOpenAuth policy and the direction as disable",
+ "Resolves the environment named in the request and lists the environment's sites so the user can pick the scope",
+ "Resolves Portal_5 to its portal ID and sets the scope to Exclude (disable on the named site, others stay as-is)",
+ "Reads the current OAuth 2.0 state (env value + details) before rendering the impact summary to show the Current State -> New State transition",
+ "Renders the impact summary via render-impact-summary.js starting at the Action: row with no lead-in label",
+ "Marks Portal_5's row as CHANGED (Enabled -> Disabled) and shows the other sites are unaffected",
+ "Includes the cascade block listing the OAuth-based social identity providers (Facebook, Google, Microsoft) that get disabled as a side effect",
+ "Surfaces the sign-out side effect for users currently authenticated via OAuth 2.0 on Portal_5",
+ "Requires explicit free-text 'Apply now' consent before POSTing and does not proceed on cancel",
+ "Applies via set-governance.js with --policyValue Exclude and --portalIds for Portal_5, polling until a terminal state",
+ "Verifies after rollout by re-reading state via get-effective-status.js and rendering the 5-column Unicode box confirming Portal_5 is red Disabled"
+ ]
+ },
+ {
+ "id": 5,
+ "prompt": "Enable the OAuth 2.0 protocol governance setting for all sites in Sachin-preprod-July.",
+ "expected_output": "A Set (enable) of EnableProtocolOpenAuth env-wide using the All policy value. Because OAuth 2.0 depends on External Auth, only sites where External Auth is enabled are eligible; the skill shows the impact summary, takes consent, applies, and verifies with the 5-column Unicode box.",
+ "files": [],
+ "expectations": [
+ "Recognizes the enable direction and All (env-wide) scope from 'all sites'",
+ "Maps enable + all to policyValue = All with no portal list",
+ "For this gated child, only offers/affects sites where the External Auth parent is enabled and surfaces any sites hidden because External Auth is off on them",
+ "Renders the impact summary with a green Action: row (enable) before the consent gate",
+ "For an enable of a parent-dependent policy, the cascade block is informational (children become available but are not auto-enabled; each provider still controlled by its own setting)",
+ "Requires explicit 'Apply now' consent before POSTing",
+ "Applies via set-governance.js with --policyValue All (no --portalIds) and polls to terminal",
+ "Verifies via get-effective-status.js after rollout and renders the env-wide state as the 5-column Unicode box"
+ ]
+ },
+ {
+ "id": 6,
+ "prompt": "Enable Google sign-in on Portal_3, Portal_4, and Portal_5 in Sachin-preprod-July.",
+ "expected_output": "A Set (enable) of EnableIdpOAuthGoogle scoped to specific sites via an Include policy value with the three portal IDs. The skill resolves the named sites, checks that each is eligible (both parents on), shows the impact summary, takes consent, applies, and verifies with the 5-column Unicode box.",
+ "files": [],
+ "expectations": [
+ "Recognizes 'Google' as EnableIdpOAuthGoogle and the direction as enable",
+ "Resolves Portal_3, Portal_4, Portal_5 to their portal IDs via parse-portal-input.js against the site list",
+ "Sets the scope to Include with the three resolved IDs as ToBeAdded",
+ "As a social IdP, only treats sites where External Auth AND OAuth 2.0 are enabled as eligible, and surfaces any named site that can't take effect because a parent is off",
+ "Renders the impact summary (Include scope) showing only the covered sites plus a note about what is not covered",
+ "Requires explicit 'Apply now' consent before POSTing",
+ "Applies via set-governance.js with --policyValue Include --portalIds for the three sites and polls to terminal",
+ "Verifies after rollout via get-effective-status.js and renders the targeted-site status as the 5-column Unicode box"
+ ]
+ },
+ {
+ "id": 7,
+ "prompt": "Disable OAuth 2.0 across Sachin-preprod-July.",
+ "expected_output": "When OAuth 2.0 is already disabled everywhere in the environment, the env-wide disable is a no-op. The redundant-operation guard fires BEFORE the impact summary and asks the admin to Keep (no change) or Enforce only on specific sites, rather than silently POSTing.",
+ "files": [],
+ "expectations": [
+ "Reads the current OAuth 2.0 state before rendering any impact summary",
+ "Detects that the requested disable is a no-op because the setting is already disabled for the in-scope sites",
+ "Fires the redundant-operation guard BEFORE rendering the impact summary and BEFORE any POST",
+ "Presents the Keep vs Enforce-only-on-<sites> choice as a free-text prompt naming the sites and both options",
+ "On Keep, makes no API call and reports 'no change made', then returns to the loop prompt",
+ "On Enforce only, switches to Exclude on the named site(s), then renders the impact summary that surfaces the collateral flip on the out-of-scope sites before the normal consent gate",
+ "Never silently POSTs a no-op env-wide change"
+ ]
+ },
+ {
+ "id": 8,
+ "prompt": "Show me which portals I can enable OpenID Connect on in this environment.",
+ "expected_output": "For a gated child (OpenID Connect), the site picker lists only the portals where the External Auth parent is enabled; portals where the parent is off are shown separately below as unavailable. If no portal has External Auth enabled, the skill states that External Auth is disabled for the env instead of offering an empty list.",
+ "files": [],
+ "expectations": [
+ "Recognizes OpenID Connect as a gated child of External Auth",
+ "Renders the env list / resolves the env first, then lists sites",
+ "Lists only the portals where the External Auth parent is enabled as eligible for enabling OpenID Connect",
+ "Shows portals where External Auth is off separately below, labeled as unavailable because the parent governance setting is off",
+ "When no portal in the env has External Auth enabled, states that External Auth is disabled for this environment and that OpenID Connect can't apply, instead of offering an empty picker",
+ "Uses the get-effective-status.js parallel read to resolve parent availability across all portals rather than reading each portal individually",
+ "Uses plain language and phrases the parent dependency in terms of governance settings (e.g. 'External Auth governance setting is off on them, so OpenID Connect can't apply')"
+ ]
+ },
+ {
+ "id": 9,
+ "prompt": "What is the status of the Facebook governance setting in Sachin-preprod-July?",
+ "expected_output": "A two-parent effective-status read of EnableIdpOAuthFacebook. Facebook is a social IdP gated by External Auth then OAuth 2.0, so get-effective-status.js fires all six API calls (getEnv + getDetails for Facebook, External Auth, and OAuth 2.0) in ONE parallel Promise.all wave, computes each site's effective state as Facebook's own setting AND both parents, and renders the mandated 5-column Unicode box. On Sachin-preprod-July this resolves to Portal_4 and Portal_5 green Enabled and Portal_1, Portal_2, Portal_3 red Disabled.",
+ "files": [],
+ "expectations": [
+ "Recognizes 'Facebook' / 'Facebook sign-in' as the EnableIdpOAuthFacebook policy",
+ "Treats Facebook as a social IdP with two parents in dependency order: External Auth first, then OAuth 2.0 (OpenAuth)",
+ "Reads Facebook plus both parents in a SINGLE parallel batch of six API calls via get-effective-status.js (getEnv + getDetails per policy) — not three sequential env+details round-trips and not per-portal reads",
+ "Resolves the governance context once up front and shares it across all six calls, and uses a longer per-request timeout so the concurrent slow-gateway calls do not trip the default 15s timeout",
+ "Marks a site effectively Enabled only when Facebook's own state AND both parents (External Auth AND OAuth 2.0) are all Enabled",
+ "Renders the result as the fixed-width 5-column Unicode box (# | Name | URL | Site ID | State) inside a fenced code block, with a rule between every row — no parent columns, no Effective column, no paraphrase column",
+ "Shows green / red icons in every State cell",
+ "Explains per-site why a site is disabled (own setting off, OAuth 2.0 parent off, or External Auth parent off), e.g. Portal_2 is off because both parents are off"
+ ]
+ },
+ {
+ "id": 10,
+ "prompt": "Enable Facebook on Portal_1 in Sachin-preprod-July.",
+ "expected_output": "A Set (enable) of EnableIdpOAuthFacebook targeting a single portal where the parent chain is off. Because Facebook's parents (External Auth and OAuth 2.0) are disabled on Portal_1, the parent-gate hard block prevents enabling the child there: the skill refuses to offer or POST the change for that portal and explains that the parent governance setting is off — it never presents a force/override option.",
+ "files": [],
+ "expectations": [
+ "Recognizes 'Facebook' as EnableIdpOAuthFacebook and the direction as enable, scoped to Portal_1",
+ "Resolves Facebook's parent chain (External Auth, then OAuth 2.0) and reads their state on Portal_1 via the parallel get-effective-status.js read",
+ "Detects that a gating parent is disabled on Portal_1 and applies the parent-gate hard block to the child Set",
+ "Does NOT offer a force / override path and does NOT POST an enable for Portal_1 while a parent is off",
+ "Explains in plain governance language that External Auth / OAuth 2.0 governance setting is off on Portal_1, so Facebook can't be enabled there",
+ "Applies the same hard block on the named-site fast path (when the portal is named directly in the request) and on the scope picker",
+ "If the user asks to disable a child on a portal whose parent is off, treats it the same way — the child is already effectively off, so the block/redundancy is surfaced rather than a silent POST"
+ ]
+ },
+ {
+ "id": 11,
+ "prompt": "Enable Facebook for Sachin-preprod-July.",
+ "expected_output": "A Set (enable) of EnableIdpOAuthFacebook with no scope named. For a social IdP with two parents, the skill offers only the eligible portals (those where both External Auth AND OAuth 2.0 are enabled) and takes a free-text reply (all / comma-separated site names or IDs / cancel). If no portal in the env is eligible, it states that External Auth or OAuth 2.0 is disabled in the environment instead of presenting an empty picker.",
+ "files": [],
+ "expectations": [
+ "Recognizes 'Facebook' as EnableIdpOAuthFacebook and the direction as enable",
+ "Resolves the environment, then uses get-effective-status.js to resolve per-portal eligibility (both External Auth AND OAuth 2.0 enabled) in one parallel batch",
+ "Lists ONLY the eligible portals (both parents on) as choices for enabling Facebook",
+ "Takes a free-text reply — 'all' for every eligible site, a comma-separated list of names/IDs for specific sites, or 'cancel' — and does NOT offer a diagnostic 'check which sites have which parent off' option",
+ "When no portal in the env is eligible, states that External Auth or OAuth 2.0 (OpenAuth) is disabled in this environment and does not present an empty picker",
+ "Proceeds through the normal impact summary and explicit 'Apply now' consent gate before POSTing the eligible sites",
+ "Applies via set-governance.js and verifies with the 5-column Unicode box"
+ ]
+ }
+ ]
+}
diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.md
index 77214d956..c25af9fa5 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -172,6 +172,7 @@ Reference reads do not trigger skill hooks. Coordinator validation of the exact
## Key Conventions
+- **Governance is temporarily disabled pending Product approval.** Keep `skills/manage-governance/SKILL.disabled.md` archived; do not create its discoverable `SKILL.md` or invoke the preserved workflow until explicitly approved. Scripts and consent tests are retained. Follow the re-enablement checklist in `skills/manage-governance/HOW_IT_WORKS.md`; the governance component description below documents implementation, not availability.
- **DRY** — Never duplicate logic. Shared scripts live in `scripts/` (e.g., `generate-uuid.js`, `scripts/lib/validation-helpers.js`, `scripts/lib/discover-site-components.js`). Shared reference docs live in `references/`. Always check for existing helpers before writing new code.
- **Validation scripts** must import from `scripts/lib/validation-helpers.js` for boilerplate, path finders, auth helpers, and constants.
- **UUID generation** must use the shared `scripts/generate-uuid.js` — never copy it into skill-specific directories.
@@ -403,6 +404,10 @@ For small mid-cycle changes (one file, one snippet, one site setting) that previ
Skills are defined in `SKILL.md` files with YAML frontmatter (name, description, allowed-tools, model). Skill-specific `hooks:` blocks are not used — hook registration is centralized.
+### Temporarily disabled skills
+
+- `manage-governance` — **Disabled pending Product approval; not user-invocable or automatically discoverable.** Its preserved tenant-admin workflow applies and inspects 21 governance policies through Apply / Fetch Env / Fetch Site, with environment/site resolution, per-change consent, rollout polling, and verification. The implementation remains in `skills/manage-governance/`, but the entry is `SKILL.disabled.md`, not `SKILL.md`. Do not invoke or re-enable it without explicit approval. See [the preserved workflow and re-enablement checklist](skills/manage-governance/HOW_IT_WORKS.md#temporary-disablement).
+
### Hooks
Hook registration is centralized in `hooks/hooks.json` — a single PostToolUse hook (matcher `Skill`) runs `hooks/run-skill-posttool-validation.js` after every Skill tool call. The runner derives tracked skills directly from `skills/*/SKILL.md` via `scripts/lib/powerpages-hook-utils.js`, looks up an optional `skills/<skill>/scripts/validate*.js` validator for the skill that just completed, and invokes it with the current cwd.
diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.md
index eb6019b48..e3cfbcc29 100644
--- a/plugins/power-pages/README.md
+++ b/plugins/power-pages/README.md
@@ -47,6 +47,7 @@ They cover the full lifecycle of a Power Pages site - scaffolding,
non-SPA authoring, deployment, data modeling, backend integration, authentication, localization,
ALM and CI/CD, security review, performance analysis, testing, auditing, and platform migrations. Each user-invocable
skill is invoked conversationally - just describe what you want to do.
+Governance remains temporarily disabled pending Product approval and is not included in these counts.
### Site scaffolding and deployment
@@ -354,6 +355,20 @@ Runs a guided, end-to-end security review of a Power Pages site and consolidates
- Consolidates findings into a single HTML report
- Suitable for release-readiness or live-site monitoring
+#### `manage-governance` (temporarily disabled)
+
+**Not available for invocation pending Product approval.** The workflow and
+scripts are retained for future enablement, but there is no discoverable
+`SKILL.md` entry point. See [enablement instructions](skills/manage-governance/HOW_IT_WORKS.md#temporary-disablement)
+for restoring it.
+
+Applies and inspects 21 Power Pages tenant governance policies: the Maker Copilot toggle for existing sites (`EnableMakerCopilotForExistingSites`), nine authentication feature toggles, and eleven `PowerPages_*` Copilot / site-control policies. The authentication toggles cover the OpenID Connect / SAML 2.0 / WS-Federation / OAuth 2.0 protocols, Facebook / Google / Microsoft sign-in, local (username & password) login, and all external identity providers. The additional policies govern Maker / pro-developer / site Copilots, search and list summaries, intelligent forms, summarization APIs, non-production public sites, and external service calls from server logic. Tenant-admin skill: it does not require a Power Pages project on disk.
+
+- Picks any environment the signed-in user has admin access to (via `pac admin list`)
+- Applies a policy environment-wide or to multiple selected sites through Include / Exclude scopes, with an explicit consent gate
+- Watches the roll-out by polling `governance/status/{policy}` until terminal, then re-reads state to verify
+- Also reads the current state at environment or portal level on demand
+
### ALM and CI/CD
#### `/plan-alm`
diff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.md
index 7ccde6ab4..deab9d046 100644
--- a/plugins/power-pages/references/approval-gates.md
+++ b/plugins/power-pages/references/approval-gates.md
@@ -800,6 +800,29 @@ The `analyze-performance:4.auto-fix` template fires once per finding with `autoF
---
+### 6.36 `manage-governance` (temporarily disabled)
+
+This skill is not discoverable: its workflow is preserved as
+`skills/manage-governance/SKILL.disabled.md`, not `SKILL.md`. The rows below
+use Kind `disabled` to archive the consent contracts without declaring active
+gates. When Product approves enabling the skill, restore the entry filename
+and change both rows back to Kind `gate` in the same change.
+
+Phase 2.2 documents the NLP-path consent contract; Phase 4.2.3 implements that
+same contract. These are not two consecutive prompts. Fire the applicable
+consent once per policy/environment/scope change, after the Impact Summary and
+before the POST. Each follow-up change and each prerequisite parent-policy
+change needs fresh consent; a previous iteration's approval never carries over.
+`nothing` means this iteration adds no governance change; earlier approved
+changes are not rolled back.
+
+| ID | Kind | Category | Phase | Trigger / question | Cancel leaves |
+|---|---|---|---|---|---|
+| `manage-governance:2.2.consent` | disabled | consent | 2.2 | NLP-path consent after the resolved impact summary: *"Proceed with this change?"* — **Apply now / Cancel**. Fires PER CHANGE; implemented by 4.2.3, not a second approval. | nothing |
+| `manage-governance:4.2.3.consent` | disabled | consent | 4.2.3 | After rendering the live Current State / New State summary: *"Proceed with this change?"* — **Apply now / Cancel**. Fires PER LOOP ITERATION, including prerequisite parent-policy changes. Only a selected **Apply now** authorizes the POST. | nothing |
+
+---
+
### Cross-plugin shared skills — out of catalog scope
`report-issue` — Its prompts are cross-plugin, not power-pages-specific, so they are not catalogued here. If the shared workflow is ever governed by per-plugin approval-gate linting, add a `report-issue:*` section to this catalog.
diff --git a/plugins/power-pages/references/skill-tracking-reference.md b/plugins/power-pages/references/skill-tracking-reference.md
index 7489dff05..dc64a1ffe 100644
--- a/plugins/power-pages/references/skill-tracking-reference.md
+++ b/plugins/power-pages/references/skill-tracking-reference.md
@@ -74,6 +74,7 @@ If the tracking script creates or updates site setting YAML files, include those
| migrate-bootstrap | MigrateBootstrap | Site/AI/Skills/MigrateBootstrap |
| migrate-webapi-selectall | MigrateWebapiSelectall | Site/AI/Skills/MigrateWebapiSelectall |
| author-webpage-content | AuthorWebpageContent | Site/AI/Skills/AuthorWebpageContent |
+| manage-governance (temporarily disabled) | ManageGovernance | Site/AI/Skills/ManageGovernance |
## YAML Format
diff --git a/plugins/power-pages/scripts/tests/governance-route-guards.test.js b/plugins/power-pages/scripts/tests/governance-route-guards.test.js
new file mode 100644
index 000000000..85bff11a8
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance-route-guards.test.js
@@ -0,0 +1,75 @@
+'use strict';
+
+// Tests for the fail-fast guards added to buildRoute() and the newline
+// flattening added to render-env-table's mdCell (PR #309 review comments
+// #1 and #3).
+//
+// #1: getEnv/getStatus/getPortal/getDetails encode `policy` (and getPortal
+// also `portalId`) directly into the gateway path. A missing value used to
+// build `/governance/undefined` and 404 with a confusing URL; buildRoute now
+// throws up front. `apply` is exempt — its policy travels in the POST body.
+//
+// #3: a raw CR/LF in an environment display name would spill the value onto a
+// malformed new row in the single-line Markdown table; mdCell now flattens
+// newline runs to a single space.
+
+const { test } = require('node:test');
+const assert = require('node:assert');
+
+const routeMod = require('../../skills/manage-governance/scripts/governance-route.js');
+const { buildRoute } = routeMod;
+
+const envTableMod = require('../../skills/manage-governance/scripts/render-env-table.js');
+
+test('buildRoute: apply needs no policy in the path', () => {
+ const r = buildRoute({ op: 'apply', envId: 'env-1' });
+ assert.strictEqual(r.method, 'POST');
+ assert.strictEqual(r.path, '/governance');
+});
+
+test('buildRoute: valid getEnv builds the encoded policy path', () => {
+ const r = buildRoute({ op: 'getEnv', envId: 'env-1', policy: 'EnableIdpOAuthGoogle' });
+ assert.strictEqual(r.path, '/governance/EnableIdpOAuthGoogle');
+});
+
+test('buildRoute: getPortal builds the encoded portal + policy path', () => {
+ const r = buildRoute({
+ op: 'getPortal',
+ envId: 'env-1',
+ portalId: 'p-1',
+ policy: 'EnableProtocolSAML20',
+ });
+ assert.strictEqual(r.path, '/websites/p-1/governance/EnableProtocolSAML20');
+});
+
+for (const op of ['getEnv', 'getStatus', 'getPortal', 'getDetails']) {
+ test(`buildRoute: ${op} without policy throws instead of building /governance/undefined`, () => {
+ assert.throws(
+ () => buildRoute({ op, envId: 'env-1', portalId: 'p-1' }),
+ /policy is required/,
+ );
+ });
+}
+
+test('buildRoute: getPortal without portalId throws', () => {
+ assert.throws(
+ () => buildRoute({ op: 'getPortal', envId: 'env-1', policy: 'EnableProtocolSAML20' }),
+ /portalId is required/,
+ );
+});
+
+test('buildRoute: missing op / envId still throw (unchanged)', () => {
+ assert.throws(() => buildRoute({ envId: 'env-1', policy: 'p' }), /op is required/);
+ assert.throws(() => buildRoute({ op: 'getEnv', policy: 'p' }), /envId is required/);
+});
+
+// #3 — mdCell newline flattening, asserted through the public renderEnvMarkdown.
+test('renderEnvMarkdown: a newline in an env name does not break the table row', () => {
+ const md = envTableMod.renderEnvMarkdown([
+ { envId: 'env-1', displayName: 'Contoso\r\nProd', type: 'Default' },
+ ]);
+ // The malformed value must not introduce a stray line break inside the row —
+ // every non-blank line of the table must still be a single pipe-delimited row.
+ assert.ok(!md.includes('Contoso\nProd'), 'newline should be flattened, not preserved');
+ assert.ok(md.includes('Contoso Prod'), 'CR/LF run should collapse to a single space');
+});
diff --git a/plugins/power-pages/scripts/tests/governance/fetch-env-status.test.js b/plugins/power-pages/scripts/tests/governance/fetch-env-status.test.js
new file mode 100644
index 000000000..94b748236
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/fetch-env-status.test.js
@@ -0,0 +1,58 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const {
+ pickHeadline,
+ parseFlags,
+} = require('../../../skills/manage-governance/scripts/fetch-env-status');
+const listPortals = require('../../../skills/manage-governance/scripts/list-portals');
+
+// --- pickHeadline: mirrors SKILL.md Phase 4.3.1 headline rule ---
+// Green when at least one site is effectively Enabled; red when off everywhere
+// (including the zero-site case, where nothing is enabled).
+
+test('pickHeadline is green when at least one site is effectively enabled', () => {
+ const h = pickHeadline(1);
+ assert.match(h, /\u{1F7E2} Enabled for these Sites:$/u);
+});
+
+test('pickHeadline is green for many enabled sites', () => {
+ assert.match(pickHeadline(5), /\u{1F7E2} Enabled for these Sites:$/u);
+});
+
+test('pickHeadline is red when nothing is enabled', () => {
+ const h = pickHeadline(0);
+ assert.match(h, /\u{1F534} Disabled for these Sites:$/u);
+});
+
+test('pickHeadline treats the zero-site env (count 0) as red/off', () => {
+ // An env with no sites has effectiveEnabledCount 0, so the setting is "off
+ // everywhere" — the red headline, not the green one.
+ assert.match(pickHeadline(0), /\u{1F534} Disabled/u);
+});
+
+// --- parseFlags: CLI surface ---
+
+test('parseFlags reads --policy and --envId', () => {
+ const f = parseFlags(['node', 'fetch-env-status.js', '--policy', 'EnableIdpOAuthFacebook', '--envId', 'env-guid']);
+ assert.equal(f.policy, 'EnableIdpOAuthFacebook');
+ assert.equal(f.envId, 'env-guid');
+});
+
+test('parseFlags sets json and help booleans', () => {
+ const f = parseFlags(['node', 'x', '--policy', 'P', '--json', '--help']);
+ assert.equal(f.json, true);
+ assert.equal(f.help, true);
+});
+
+test('parseFlags leaves envId undefined when omitted (falls back to PAC env)', () => {
+ const f = parseFlags(['node', 'x', '--policy', 'P']);
+ assert.equal(f.envId, undefined);
+});
+
+// --- fetchPortalsPaged export: the seam that lets the site-list fetch join the
+// parallel batch instead of being a separate prior step ---
+
+test('list-portals.js exports fetchPortalsPaged for the batched Fetch Env', () => {
+ assert.equal(typeof listPortals.fetchPortalsPaged, 'function');
+});
diff --git a/plugins/power-pages/scripts/tests/governance/get-effective-status.test.js b/plugins/power-pages/scripts/tests/governance/get-effective-status.test.js
new file mode 100644
index 000000000..126249e17
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/get-effective-status.test.js
@@ -0,0 +1,20 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { SUPPORTED_POLICIES } = require('../../../skills/manage-governance/scripts/policies');
+
+test('get-effective-status documents current policy support and default stdin input', () => {
+ const script = path.resolve(
+ __dirname,
+ '../../../skills/manage-governance/scripts/get-effective-status.js'
+ );
+ const result = spawnSync(process.execPath, [script, '--help'], { encoding: 'utf8' });
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.ok(result.stdout.includes(`Governance policy name (${SUPPORTED_POLICIES.length} supported policies)`));
+ assert.doesNotMatch(result.stdout, /any of the ten/);
+ assert.match(result.stdout, /node list-portals\.js/);
+ assert.match(result.stdout, /stdin\s+list-portals\.js output/);
+ assert.match(result.stdout, /--portalsFile\s+Backward-compatible alternative/);
+});
diff --git a/plugins/power-pages/scripts/tests/governance/governance-context.test.js b/plugins/power-pages/scripts/tests/governance/governance-context.test.js
new file mode 100644
index 000000000..f8711e466
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/governance-context.test.js
@@ -0,0 +1,303 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert');
+
+const {
+ applyHostOverride,
+ applyEnvOverride,
+ resolveHostOverride,
+ resolveRing,
+ getRing,
+ loadConfig,
+ resetConfigCache,
+ resolveTargetEnv,
+ resourceForHost,
+ isTruthyFlag,
+ DEFAULT_RINGS,
+ RINGS,
+ TIP_GATEWAY_HOST,
+ PROD_GATEWAY_HOST,
+} = require('../../../skills/manage-governance/scripts/governance-context');
+
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const vm = require('node:vm');
+
+test('TIP auth uses shell-free argv and preserves token and failure behavior', () => {
+ const modulePath = require.resolve('../../../skills/manage-governance/scripts/governance-context');
+ const scriptDir = path.join(os.tmpdir(), 'governance helpers & tools');
+ const env = { PP_GOV_TIP_CLIENT_ID: 'test-client' };
+ for (const scenario of [
+ { output: ' test-token\n', expected: 'test-token' },
+ { output: ' \n', expected: null },
+ { throws: true, expected: null },
+ { configError: true, expected: null },
+ ]) {
+ const calls = [];
+ const sandbox = {
+ module: { exports: {} },
+ __dirname: scriptDir,
+ process: { execPath: process.execPath },
+ require(name) {
+ if (name === 'child_process') {
+ return {
+ execFileSync(executable, args, options) {
+ calls.push({ executable, args, options });
+ if (scenario.throws) throw new Error('device-code helper failed');
+ return scenario.output;
+ },
+ };
+ }
+ if (name === 'fs') return fs;
+ if (name === 'path') return path;
+ if (name === '../../../scripts/lib/power-platform-api') return {};
+ if (name === '../../../scripts/lib/validation-helpers') return {};
+ if (name === './tip-auth') {
+ return { resolveTipConfig: () => scenario.configError ? { error: 'missing config' } : {} };
+ }
+ throw new Error(`Unexpected dependency: ${name}`);
+ },
+ };
+ vm.runInNewContext(fs.readFileSync(modulePath, 'utf8'), sandbox, { filename: modulePath });
+ assert.strictEqual(sandbox.module.exports.getTipTokenSync(env), scenario.expected);
+ assert.equal(calls.length, scenario.configError ? 0 : 1);
+ if (scenario.configError) continue;
+ assert.equal(calls[0].executable, process.execPath);
+ assert.deepEqual(Array.from(calls[0].args), [path.join(scriptDir, 'tip-auth.js')]);
+ assert.equal(calls[0].options.encoding, 'utf8');
+ assert.deepEqual(Array.from(calls[0].options.stdio), ['ignore', 'pipe', 'inherit']);
+ assert.equal(calls[0].options.timeout, 15 * 60 * 1000);
+ assert.strictEqual(calls[0].options.env, env);
+ assert.notEqual(calls[0].options.shell, true);
+ }
+});
+
+function shippedRingKey() {
+ resetConfigCache();
+ return loadConfig().activeRing || 'TIP';
+}
+
+test('RINGS registry: central source of truth for host + token strategy', () => {
+ assert.equal(RINGS.TIP.host, 'https://api.preprod.powerplatform.com');
+ assert.equal(RINGS.TIP.tokenStrategy, 'device-code');
+ assert.equal(RINGS.TIP.hostEnv, 'PP_GOV_TIP_HOST');
+ assert.equal(RINGS.Prod.host, 'https://api.powerplatform.com');
+ assert.equal(RINGS.Prod.tokenStrategy, 'az');
+ // Named host constants must stay in sync with the registry.
+ assert.equal(TIP_GATEWAY_HOST, RINGS.TIP.host);
+ assert.equal(PROD_GATEWAY_HOST, RINGS.Prod.host);
+});
+
+test('TIP_GATEWAY_HOST is the Preprod host, distinct from prod', () => {
+ // api.tip.powerplatform.com does NOT resolve — Preprod is api.preprod...
+ assert.equal(TIP_GATEWAY_HOST, 'https://api.preprod.powerplatform.com');
+ assert.equal(PROD_GATEWAY_HOST, 'https://api.powerplatform.com');
+ assert.notEqual(TIP_GATEWAY_HOST, PROD_GATEWAY_HOST);
+});
+
+test('isTruthyFlag accepts the dotnet-style truthy spellings', () => {
+ for (const v of ['1', 'true', 'TRUE', 'yes', 'on', ' On ']) {
+ assert.equal(isTruthyFlag(v), true, `expected "${v}" truthy`);
+ }
+ for (const v of ['0', 'false', 'no', 'off', '', undefined, null]) {
+ assert.equal(isTruthyFlag(v), false, `expected "${v}" falsy`);
+ }
+});
+
+test('resolveRing: app-settings.json decides the active ring', () => {
+ const expected = shippedRingKey();
+ assert.equal(resolveRing({}), expected);
+ assert.equal(resolveRing({ PP_GOV_PROD: '0' }), expected);
+});
+
+test('resolveRing: ring env vars no longer override app-settings.json', () => {
+ const expected = shippedRingKey();
+ assert.equal(resolveRing({ PP_GOV_PROD: '1' }), expected);
+ assert.equal(resolveRing({ PP_GOV_PROD: 'true' }), expected);
+ assert.equal(resolveRing({ PP_GOV_RING: 'prod' }), expected);
+ assert.equal(resolveRing({ PP_GOV_RING: 'production' }), expected);
+});
+
+test('resolveHostOverride: default host follows the configured ring', () => {
+ const expected =
+ shippedRingKey() === 'Prod' ? 'https://api.powerplatform.com' : TIP_GATEWAY_HOST;
+ assert.equal(resolveHostOverride({}, 'https://api.powerplatform.com'), expected);
+});
+
+test('resolveHostOverride: PP_GOV_TIP_HOST only matters when TIP is the configured ring', () => {
+ const custom = 'https://api.custom-ring.powerplatform.com';
+ const expected = shippedRingKey() === 'Prod' ? 'x' : custom;
+ assert.equal(resolveHostOverride({ PP_GOV_TIP_HOST: custom + '/' }, 'x'), expected);
+});
+
+test('resolveHostOverride: Prod ring uses the signed-in prod host', () => {
+ const expectedWithProdApiHost =
+ shippedRingKey() === 'Prod' ? 'https://api.gov.powerplatform.microsoft.us' : TIP_GATEWAY_HOST;
+ assert.equal(
+ resolveHostOverride({}, 'https://api.gov.powerplatform.microsoft.us'),
+ expectedWithProdApiHost
+ );
+ const expectedWithoutProdApiHost =
+ shippedRingKey() === 'Prod' ? PROD_GATEWAY_HOST : TIP_GATEWAY_HOST;
+ assert.equal(resolveHostOverride({}, undefined), expectedWithoutProdApiHost);
+});
+
+test('resolveHostOverride: explicit PP_GOV_API_HOST outranks the configured ring host', () => {
+ const explicit = 'https://api.example-ring.powerplatform.com';
+ assert.equal(
+ resolveHostOverride({ PP_GOV_API_HOST: explicit + '//' }, 'x'),
+ explicit
+ );
+});
+
+test('resourceForHost appends exactly one trailing slash (the token audience)', () => {
+ assert.equal(resourceForHost('https://api.preprod.powerplatform.com'), 'https://api.preprod.powerplatform.com/');
+ assert.equal(resourceForHost('https://api.preprod.powerplatform.com///'), 'https://api.preprod.powerplatform.com/');
+});
+
+test('applyHostOverride rewrites only scheme+authority, preserving the env path', () => {
+ const ctx = {
+ baseUrl: 'https://api.powerplatform.com/powerpages/environments/env-123',
+ apiHost: 'https://api.powerplatform.com',
+ };
+ applyHostOverride(ctx, TIP_GATEWAY_HOST);
+ assert.equal(
+ ctx.baseUrl,
+ 'https://api.preprod.powerplatform.com/powerpages/environments/env-123'
+ );
+ assert.equal(ctx.apiHost, TIP_GATEWAY_HOST);
+});
+
+test('applyHostOverride strips trailing slashes from the override host', () => {
+ const ctx = {
+ baseUrl: 'https://api.powerplatform.com/powerpages/environments/env-123',
+ apiHost: 'https://api.powerplatform.com',
+ };
+ applyHostOverride(ctx, 'https://api.preprod.powerplatform.com///');
+ assert.equal(
+ ctx.baseUrl,
+ 'https://api.preprod.powerplatform.com/powerpages/environments/env-123'
+ );
+ assert.equal(ctx.apiHost, 'https://api.preprod.powerplatform.com');
+});
+
+test('applyEnvOverride swaps the env id segment and leaves the host intact', () => {
+ const ctx = {
+ baseUrl: 'https://api.preprod.powerplatform.com/powerpages/environments/old-env',
+ environmentId: 'old-env',
+ };
+ applyEnvOverride(ctx, 'new-env');
+ assert.equal(
+ ctx.baseUrl,
+ 'https://api.preprod.powerplatform.com/powerpages/environments/new-env'
+ );
+ assert.equal(ctx.environmentId, 'new-env');
+});
+
+test('configured ring host + env override compose correctly', () => {
+ const ctx = {
+ baseUrl: 'https://api.powerplatform.com/powerpages/environments/env-a',
+ apiHost: 'https://api.powerplatform.com',
+ environmentId: 'env-a',
+ };
+ applyHostOverride(ctx, resolveHostOverride({}, ctx.apiHost));
+ applyEnvOverride(ctx, 'env-b');
+ const expectedHost =
+ shippedRingKey() === 'Prod'
+ ? 'https://api.powerplatform.com'
+ : 'https://api.preprod.powerplatform.com';
+ assert.equal(
+ ctx.baseUrl,
+ `${expectedHost}/powerpages/environments/env-b`
+ );
+});
+
+// --- Single-switch config (app-settings.json) coverage --------------------
+
+test('DEFAULT_RINGS carry both gateway AND bap routing per ring', () => {
+ // TIP: preprod gateway + device-code, TIP BAP via REST.
+ assert.equal(DEFAULT_RINGS.TIP.gatewayHost, 'https://api.preprod.powerplatform.com');
+ assert.equal(DEFAULT_RINGS.TIP.tokenStrategy, 'device-code');
+ assert.equal(DEFAULT_RINGS.TIP.bapStrategy, 'rest');
+ assert.equal(DEFAULT_RINGS.TIP.bapHost, 'https://tip1.api.bap.microsoft.com');
+ // Prod: prod gateway + az, prod BAP via the pac CLI shim.
+ assert.equal(DEFAULT_RINGS.Prod.gatewayHost, 'https://api.powerplatform.com');
+ assert.equal(DEFAULT_RINGS.Prod.tokenStrategy, 'az');
+ assert.equal(DEFAULT_RINGS.Prod.bapStrategy, 'pac');
+ assert.equal(DEFAULT_RINGS.Prod.bapHost, 'https://api.bap.microsoft.com');
+});
+
+test('getRing returns the merged ring object for the config-selected switch', () => {
+ const expected = shippedRingKey();
+ const expectedBapStrategy = expected === 'Prod' ? 'pac' : 'rest';
+ assert.equal(getRing({}).label, expected);
+ assert.equal(getRing({}).bapStrategy, expectedBapStrategy);
+ assert.equal(getRing({}, 'Prod').label, 'Prod');
+ assert.equal(getRing({}, 'Prod').bapStrategy, 'pac');
+});
+
+test('resolveRing: config.activeRing decides the ring even when env vars disagree', () => {
+ const cfg = loadConfig(writeFixture({ activeRing: 'Prod' }));
+ assert.equal(cfg.activeRing, 'Prod');
+ // The shipped app-settings.json remains authoritative; ring env vars are ignored.
+ const expected = shippedRingKey();
+ assert.equal(resolveRing({ PP_GOV_RING: 'tip' }), expected);
+ assert.equal(resolveRing({ PP_GOV_PROD: '1' }), expected);
+});
+
+test('loadConfig normalizes activeRing aliases and merges ring overrides', () => {
+ const p = writeFixture({
+ activeRing: 'test', // alias → TIP
+ targetEnv: ' a5ff24b0-0000 ',
+ rings: {
+ TIP: { bapHost: 'https://tip1.api.bap.microsoft.com/', gatewayHost: 'https://custom.preprod/' },
+ },
+ });
+ const cfg = loadConfig(p);
+ assert.equal(cfg.activeRing, 'TIP');
+ assert.equal(cfg.targetEnv, 'a5ff24b0-0000'); // trimmed
+ // Trailing slashes stripped on hosts.
+ assert.equal(cfg.rings.TIP.bapHost, 'https://tip1.api.bap.microsoft.com');
+ assert.equal(cfg.rings.TIP.gatewayHost, 'https://custom.preprod');
+ // Unspecified fields fall back to defaults.
+ assert.equal(cfg.rings.TIP.tokenStrategy, 'device-code');
+ assert.equal(cfg.rings.Prod.gatewayHost, DEFAULT_RINGS.Prod.gatewayHost);
+});
+
+test('loadConfig fails open to defaults on a missing/invalid file', () => {
+ const missing = path.join(os.tmpdir(), `pp-gov-nope-${Date.now()}.json`);
+ const cfg = loadConfig(missing);
+ assert.equal(cfg.rings.TIP.gatewayHost, DEFAULT_RINGS.TIP.gatewayHost);
+ assert.equal(cfg.activeRing, null); // no file → no explicit ring → default path
+ // Invalid JSON also fails open.
+ const bad = writeFixtureRaw('{ not json');
+ const cfg2 = loadConfig(bad);
+ assert.equal(cfg2.rings.Prod.bapHost, DEFAULT_RINGS.Prod.bapHost);
+});
+
+test('loadConfig accepts legacy `host` as gatewayHost alias', () => {
+ const cfg = loadConfig(writeFixture({ rings: { Prod: { host: 'https://legacy.prod' } } }));
+ assert.equal(cfg.rings.Prod.gatewayHost, 'https://legacy.prod');
+});
+
+test('resolveTargetEnv: PP_GOV_ENV_ID overrides the file targetEnv', () => {
+ assert.equal(resolveTargetEnv({ PP_GOV_ENV_ID: 'env-from-var' }), 'env-from-var');
+ // With neither set, the shipped app-settings.json targetEnv is empty → null.
+ resetConfigCache();
+ assert.equal(resolveTargetEnv({}), null);
+});
+
+// Write a temp app-settings.json fixture and return its path. Kept local to the
+// test so cases can exercise loadConfig's file path without touching the shipped
+// config. Each fixture is uniquely named so parallel runs don't collide.
+let fixtureSeq = 0;
+function writeFixture(obj) {
+ return writeFixtureRaw(JSON.stringify(obj));
+}
+function writeFixtureRaw(text) {
+ const p = path.join(os.tmpdir(), `pp-gov-cfg-${process.pid}-${fixtureSeq++}.json`);
+ fs.writeFileSync(p, text);
+ return p;
+}
diff --git a/plugins/power-pages/scripts/tests/governance/governance-mapping-shorthands.test.js b/plugins/power-pages/scripts/tests/governance/governance-mapping-shorthands.test.js
new file mode 100644
index 000000000..2a64a7acb
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/governance-mapping-shorthands.test.js
@@ -0,0 +1,107 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const mapping = require('../../../skills/manage-governance/references/governance-mapping.json');
+
+// Build a shorthand -> policyName index from the committed mapping data. This is
+// exactly what the orchestrator relies on when resolving a user's phrasing to a
+// policy, so asserting against it proves the DATA (not just parser logic) covers
+// the abbreviations/synonyms used across the 270 governance test cases.
+function shorthandIndex() {
+ const idx = new Map();
+ for (const p of mapping.policies) {
+ for (const s of p.userShorthands || []) {
+ idx.set(String(s).toLowerCase(), p.policyName);
+ }
+ }
+ return idx;
+}
+
+// Abbreviations/synonyms that appear in PowerPages_Policy_TestCases_270.csv and
+// were previously missing from userShorthands (fb, gmail, msa, external idps,
+// third-party providers, oauth2, ws-fed, password login). Each MUST resolve to
+// its expected policy for the skill to handle those rows without asking.
+const REQUIRED_SHORTHANDS = {
+ fb: 'EnableIdpOAuthFacebook',
+ gmail: 'EnableIdpOAuthGoogle',
+ msa: 'EnableIdpOAuthMicrosoft',
+ oauth2: 'EnableProtocolOpenAuth',
+ 'oauth 2.0': 'EnableProtocolOpenAuth',
+ 'ws-fed': 'EnableProtocolWsFederation',
+ 'password login': 'EnableAuthenticationLocalLogin',
+ 'external idps': 'EnableExternalAuthProviders',
+ 'external idp': 'EnableExternalAuthProviders',
+ 'third-party identity providers': 'EnableExternalAuthProviders',
+ 'third-party providers': 'EnableExternalAuthProviders',
+};
+
+test('every 270-case synonym resolves to the expected policy via userShorthands', () => {
+ const idx = shorthandIndex();
+ for (const [phrase, expected] of Object.entries(REQUIRED_SHORTHANDS)) {
+ assert.equal(
+ idx.get(phrase),
+ expected,
+ `shorthand "${phrase}" should map to ${expected} but mapped to ${idx.get(phrase)}`
+ );
+ }
+});
+
+test('additive edit preserved every original committed shorthand', () => {
+ // Guard the additive-only constraint: the pre-existing shorthands must still
+ // be present (we only appended, never removed/restructured).
+ const idx = shorthandIndex();
+ const ORIGINAL = {
+ facebook: 'EnableIdpOAuthFacebook',
+ google: 'EnableIdpOAuthGoogle',
+ microsoft: 'EnableIdpOAuthMicrosoft',
+ 'oauth 2.0 protocol': 'EnableProtocolOpenAuth',
+ wsfed: 'EnableProtocolWsFederation',
+ 'username and password': 'EnableAuthenticationLocalLogin',
+ 'external identity providers': 'EnableExternalAuthProviders',
+ };
+ for (const [phrase, expected] of Object.entries(ORIGINAL)) {
+ assert.equal(idx.get(phrase), expected, `original shorthand "${phrase}" must remain`);
+ }
+});
+
+test('each new PowerPages_* copilot policy resolves via at least one shorthand', () => {
+ const idx = shorthandIndex();
+ // A representative shorthand per new policy must resolve to it, proving the
+ // Phase 2.1 parser can reach every added policy from natural phrasing.
+ const NEW_COPILOT_SHORTHANDS = {
+ 'new sites copilot': 'PowerPages_AllowMakerCopilotsForNewSites',
+ 'maker copilots for existing sites': 'PowerPages_AllowMakerCopilotsForExistingSites',
+ 'pro dev copilot for sites': 'PowerPages_AllowProDevCopilotsForSites',
+ 'site copilot': 'PowerPages_AllowSiteCopilotForSites',
+ 'search summary copilot': 'PowerPages_AllowSearchSummaryCopilotForSites',
+ 'list summary copilot': 'PowerPages_AllowListSummaryCopilotForSites',
+ 'intelligent forms copilot': 'PowerPages_AllowIntelligentFormsCopilotForSites',
+ 'summarization api copilot': 'PowerPages_AllowSummarizationAPICopilotForSites',
+ 'pro dev copilot for environment': 'PowerPages_AllowProDevCopilotsForEnvironment',
+ 'non-prod public sites': 'PowerPages_AllowNonProdPublicSites',
+ 'external service calls from server logic': 'PowerPages_DisableExtSvcCallsFromServerLogic',
+ };
+ for (const [phrase, expected] of Object.entries(NEW_COPILOT_SHORTHANDS)) {
+ assert.equal(
+ idx.get(phrase),
+ expected,
+ `shorthand "${phrase}" should map to ${expected} but mapped to ${idx.get(phrase)}`
+ );
+ }
+});
+
+test('mapping still exposes all 21 policies and its committed top-level keys', () => {
+ assert.equal(mapping.policies.length, 21);
+ for (const key of [
+ 'policyModes',
+ 'policies',
+ 'intentToPolicyValue',
+ 'ambiguousPhrasings',
+ 'effectLineTemplates',
+ 'scopePicker',
+ 'consentGate',
+ 'uiConstants',
+ ]) {
+ assert.ok(key in mapping, `committed top-level key '${key}' must be present`);
+ }
+});
diff --git a/plugins/power-pages/scripts/tests/governance/governance-policies.test.js b/plugins/power-pages/scripts/tests/governance/governance-policies.test.js
new file mode 100644
index 000000000..0725a2014
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/governance-policies.test.js
@@ -0,0 +1,225 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('path');
+
+const policies = require('../../../skills/manage-governance/scripts/policies');
+const mapping = require('../../../skills/manage-governance/references/governance-mapping.json');
+
+const {
+ SUPPORTED_POLICIES,
+ ENV_VALUE_ALIASES,
+ isSupportedPolicy,
+ normalizeEnvValue,
+ classifyStatus,
+} = policies;
+
+const NEW_AUTH_ENABLE_POLICIES = [
+ 'EnableProtocolOpenIdConnect',
+ 'EnableProtocolSAML20',
+ 'EnableProtocolWsFederation',
+ 'EnableProtocolOpenAuth',
+ 'EnableIdpOAuthFacebook',
+ 'EnableIdpOAuthGoogle',
+ 'EnableIdpOAuthMicrosoft',
+ 'EnableAuthenticationLocalLogin',
+ 'EnableExternalAuthProviders',
+];
+
+// Power Pages Copilot / site-control policies added in the 2026-07 enhancement.
+// Same uniformGovernance type as everything else (All/None/Include/Exclude),
+// but INDEPENDENT — no parent/child availability gating, no cascade. They carry
+// the Maker-Copilot-style empty sideEffectCallout (no user sign-out).
+const NEW_COPILOT_POLICIES = [
+ 'PowerPages_AllowMakerCopilotsForNewSites',
+ 'PowerPages_AllowMakerCopilotsForExistingSites',
+ 'PowerPages_AllowProDevCopilotsForSites',
+ 'PowerPages_AllowSiteCopilotForSites',
+ 'PowerPages_AllowSearchSummaryCopilotForSites',
+ 'PowerPages_AllowListSummaryCopilotForSites',
+ 'PowerPages_AllowIntelligentFormsCopilotForSites',
+ 'PowerPages_AllowSummarizationAPICopilotForSites',
+ 'PowerPages_AllowProDevCopilotsForEnvironment',
+ 'PowerPages_AllowNonProdPublicSites',
+ 'PowerPages_DisableExtSvcCallsFromServerLogic',
+];
+
+test('SUPPORTED_POLICIES includes maker copilot, the nine auth Enable* policies, and the eleven PowerPages_* copilot policies', () => {
+ assert.deepEqual([...SUPPORTED_POLICIES], [
+ 'EnableMakerCopilotForExistingSites',
+ ...NEW_AUTH_ENABLE_POLICIES,
+ ...NEW_COPILOT_POLICIES,
+ ]);
+});
+
+test('SUPPORTED_POLICIES is frozen', () => {
+ assert.equal(Object.isFrozen(SUPPORTED_POLICIES), true);
+});
+
+test('isSupportedPolicy recognizes EnableMakerCopilotForExistingSites', () => {
+ assert.equal(isSupportedPolicy('EnableMakerCopilotForExistingSites'), true);
+});
+
+test('isSupportedPolicy recognizes each new auth Enable* policy and rejects mis-casing', () => {
+ for (const name of NEW_AUTH_ENABLE_POLICIES) {
+ assert.equal(isSupportedPolicy(name), true, `should support ${name}`);
+ assert.equal(isSupportedPolicy(name.toLowerCase()), false, `should reject mis-cased ${name}`);
+ }
+});
+
+test('isSupportedPolicy recognizes each new PowerPages_* copilot policy and rejects mis-casing', () => {
+ for (const name of NEW_COPILOT_POLICIES) {
+ assert.equal(isSupportedPolicy(name), true, `should support ${name}`);
+ assert.equal(isSupportedPolicy(name.toLowerCase()), false, `should reject mis-cased ${name}`);
+ }
+});
+
+test('isSupportedPolicy rejects unknown and mis-cased policy names', () => {
+ assert.equal(isSupportedPolicy('EnableMakerCopilotForNewSites'), false);
+ assert.equal(isSupportedPolicy('enablemakercopilotforexistingsites'), false);
+ assert.equal(isSupportedPolicy(''), false);
+ assert.equal(isSupportedPolicy(undefined), false);
+});
+
+test('normalizeEnvValue maps env-level applyTo vocabulary to canonical policyValue', () => {
+ assert.equal(normalizeEnvValue('AllSites'), 'All');
+ assert.equal(normalizeEnvValue('IncludedSites'), 'Include');
+ assert.equal(normalizeEnvValue('AllSitesExceptExcluded'), 'Exclude');
+ assert.equal(normalizeEnvValue('ExcludedSites'), 'Exclude');
+});
+
+test('normalizeEnvValue is case-insensitive on the alias key', () => {
+ assert.equal(normalizeEnvValue('allsites'), 'All');
+ assert.equal(normalizeEnvValue('ALLSITES'), 'All');
+ assert.equal(normalizeEnvValue(' AllSites '), 'All');
+});
+
+test('normalizeEnvValue passes canonical policyValues through unchanged', () => {
+ for (const v of ['All', 'None', 'Include', 'Exclude']) {
+ assert.equal(normalizeEnvValue(v), v);
+ }
+});
+
+test('normalizeEnvValue passes unknown values through and preserves null/undefined', () => {
+ assert.equal(normalizeEnvValue('SomethingElse'), 'SomethingElse');
+ assert.equal(normalizeEnvValue(null), null);
+ assert.equal(normalizeEnvValue(undefined), undefined);
+});
+
+test('ENV_VALUE_ALIASES stays consistent with mapping.readValueAliases', () => {
+ // Every alias declared in the mapping JSON (except the identity None mapping)
+ // must be honored by the code-side normalizer.
+ for (const [raw, canonical] of Object.entries(mapping.readValueAliases)) {
+ assert.equal(normalizeEnvValue(raw), canonical, `alias ${raw} -> ${canonical}`);
+ }
+ // And the code-side alias table keys should be lowercase for the lookup.
+ for (const key of Object.keys(ENV_VALUE_ALIASES)) {
+ assert.equal(key, key.toLowerCase());
+ }
+});
+
+test('governance-mapping declares a policy entry for every supported policy', () => {
+ const mapped = new Set(mapping.policies.map((p) => p.policyName));
+ for (const name of SUPPORTED_POLICIES) {
+ assert.equal(mapped.has(name), true, `mapping missing policy ${name}`);
+ }
+});
+
+test('maker copilot mapping entry has the required render fields', () => {
+ const maker = mapping.policies.find(
+ (p) => p.policyName === 'EnableMakerCopilotForExistingSites'
+ );
+ assert.ok(maker, 'maker copilot policy entry present');
+ assert.equal(maker.policyMode, 'uniformGovernance');
+ assert.ok(maker.displayName);
+ assert.ok(maker.subject);
+ assert.ok(maker.summaryLabel);
+ assert.ok(Array.isArray(maker.userShorthands) && maker.userShorthands.length > 0);
+ assert.ok(maker.stateParaphrase.Enabled);
+ assert.ok(maker.stateParaphrase.Disabled);
+ assert.ok(maker.sideEffectCallout);
+});
+
+test('each new auth Enable* policy is configured like the reference EnableProtocolOpenIdConnect policy', () => {
+ const oidc = mapping.policies.find(
+ (p) => p.policyName === 'EnableProtocolOpenIdConnect'
+ );
+ assert.ok(oidc, 'reference OIDC protocol policy entry present');
+ for (const name of NEW_AUTH_ENABLE_POLICIES) {
+ const entry = mapping.policies.find((p) => p.policyName === name);
+ assert.ok(entry, `mapping missing policy ${name}`);
+ // Same uniformGovernance mode and full field set as the reference policy.
+ assert.equal(entry.policyMode, oidc.policyMode, `${name} policyMode`);
+ assert.ok(entry.displayName, `${name} displayName`);
+ assert.ok(entry.subject, `${name} subject`);
+ assert.ok(entry.summaryLabel, `${name} summaryLabel`);
+ assert.ok(
+ Array.isArray(entry.userShorthands) && entry.userShorthands.length > 0,
+ `${name} userShorthands`
+ );
+ assert.ok(entry.stateParaphrase.Enabled, `${name} stateParaphrase.Enabled`);
+ assert.ok(entry.stateParaphrase.Disabled, `${name} stateParaphrase.Disabled`);
+ assert.ok(entry.sideEffectCallout, `${name} sideEffectCallout`);
+ // These are Enable* auth policies: the sign-out side effect fires when the
+ // auth path is turned OFF (disable = None / Exclude).
+ assert.deepEqual(
+ entry.sideEffectCallout.policyValueTriggers,
+ ['None', 'Exclude'],
+ `${name} sideEffect triggers`
+ );
+ assert.ok(
+ entry.sideEffectCallout.message && entry.sideEffectCallout.message.length > 0,
+ `${name} sideEffect message`
+ );
+ }
+});
+
+test('each new PowerPages_* copilot policy is a uniformGovernance leaf with the required render fields', () => {
+ for (const name of NEW_COPILOT_POLICIES) {
+ const entry = mapping.policies.find((p) => p.policyName === name);
+ assert.ok(entry, `mapping missing policy ${name}`);
+ assert.equal(entry.policyMode, 'uniformGovernance', `${name} policyMode`);
+ assert.ok(entry.displayName, `${name} displayName`);
+ assert.ok(entry.subject, `${name} subject`);
+ assert.ok(entry.summaryLabel, `${name} summaryLabel`);
+ assert.ok(
+ Array.isArray(entry.userShorthands) && entry.userShorthands.length > 0,
+ `${name} userShorthands`
+ );
+ assert.ok(entry.stateParaphrase.Enabled, `${name} stateParaphrase.Enabled`);
+ assert.ok(entry.stateParaphrase.Disabled, `${name} stateParaphrase.Disabled`);
+ assert.ok(entry.sideEffectCallout, `${name} sideEffectCallout`);
+ // Independent policies: no parent/child availability gating, no cascade.
+ assert.equal(entry.availabilityDependsOn, undefined, `${name} must have no availabilityDependsOn`);
+ assert.equal(entry.cascadeOnDisable, undefined, `${name} must have no cascadeOnDisable`);
+ assert.equal(entry.cascadeOnEnable, undefined, `${name} must have no cascadeOnEnable`);
+ // Copilot / site-control policies do not sign users out, so (like Maker
+ // Copilot) their side-effect callout is empty.
+ assert.deepEqual(entry.sideEffectCallout.policyValueTriggers, [], `${name} empty sideEffect triggers`);
+ }
+});
+
+test('new auth Enable* policies use the canonical vocabulary (not the applyTo *Sites contract)', () => {
+ // Only Maker Copilot carries the applyTo read-alias contract; the nine auth
+ // Enable* policies must NOT be listed anywhere that would give them the
+ // *Sites write vocab. There is no applyTo policy list in the mapping.
+ assert.equal(mapping.applyToWriteVocab, undefined);
+ // The nine policies resolve to the canonical policyValues via the uniform
+ // intentToPolicyValue table (shared with every other policy).
+ const values = mapping.intentToPolicyValue.map((r) => r.policyValue).sort();
+ assert.deepEqual(values, ['All', 'Exclude', 'Include', 'None']);
+});
+
+test('classifyStatus unaffected by the new policy plumbing', () => {
+ assert.equal(classifyStatus('Succeeded'), 'success');
+ assert.equal(classifyStatus('Failed'), 'failure');
+ assert.equal(classifyStatus('InProgress'), 'in-progress');
+ assert.equal(classifyStatus(''), 'unknown');
+});
+
+test('policies module path resolves under manage-governance skill', () => {
+ const resolved = require.resolve('../../../skills/manage-governance/scripts/policies');
+ assert.equal(resolved, path.resolve(
+ __dirname,
+ '../../../skills/manage-governance/scripts/policies.js'
+ ));
+});
diff --git a/plugins/power-pages/scripts/tests/governance/governance-transport.test.js b/plugins/power-pages/scripts/tests/governance/governance-transport.test.js
new file mode 100644
index 000000000..f1e6320bc
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/governance-transport.test.js
@@ -0,0 +1,138 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const { createRequire } = require('node:module');
+
+const modulePath = require.resolve('../../../skills/manage-governance/scripts/governance-transport');
+const realRequire = createRequire(modulePath);
+
+// Exercise the real route builder without credentials, authentication subprocesses,
+// or gateway traffic; context and request are the only replaced dependencies.
+function harness(context, response = { ok: true, statusCode: 200, body: 'test-result' }) {
+ const resolutions = [];
+ const requests = [];
+ const sandbox = {
+ module: { exports: {} },
+ require(name) {
+ if (name === './governance-route') return realRequire(name);
+ if (name === './governance-context') {
+ return {
+ resolveGovernanceContext(envId) {
+ resolutions.push(envId);
+ return context;
+ },
+ };
+ }
+ if (name === '../../../scripts/lib/power-platform-api') {
+ return {
+ async request(args) {
+ requests.push(args);
+ return response;
+ },
+ };
+ }
+ throw new Error(`Unexpected dependency: ${name}`);
+ },
+ };
+ vm.runInNewContext(fs.readFileSync(modulePath, 'utf8'), sandbox, { filename: modulePath });
+ return { call: sandbox.module.exports.callGovernance, resolutions, requests };
+}
+
+const operations = [
+ ['apply', 'POST', '/governance'],
+ ['getEnv', 'GET', '/governance/TestPolicy'],
+ ['getStatus', 'GET', '/governance/status/TestPolicy'],
+ ['getDetails', 'GET', '/governance/TestPolicy/details'],
+ ['getPortal', 'GET', '/websites/test-site/governance/TestPolicy'],
+];
+
+for (const [op, method, path] of operations) {
+ for (const reuseContext of [false, true]) {
+ test(`${op} without envId uses ${reuseContext ? 'pre-resolved' : 'current/configured'} context`, async () => {
+ const context = {
+ environmentId: 'resolved-env',
+ baseUrl: 'https://api.powerplatform.com/powerpages/environments/resolved-env',
+ token: 'test-token',
+ };
+ const h = harness(context);
+ const body = { test: 'payload' };
+ const result = await h.call({
+ op, policy: 'TestPolicy', portalId: 'test-site', body, timeout: 60_000,
+ ...(reuseContext ? { context } : {}),
+ });
+ assert.equal(result.ok, true);
+ assert.equal(result.transport, 'gateway');
+ assert.deepEqual(h.resolutions, reuseContext ? [] : [undefined]);
+ assert.equal(h.requests.length, 1);
+ assert.strictEqual(h.requests[0].context, context);
+ assert.equal(h.requests[0].method, method);
+ assert.equal(h.requests[0].path, path);
+ assert.strictEqual(h.requests[0].body, body);
+ assert.equal(h.requests[0].timeout, 60_000);
+ });
+ }
+}
+
+test('explicit envId is passed to context resolution unchanged', async () => {
+ const context = { environmentId: 'explicit-env', baseUrl: 'test-base-url' };
+ const h = harness(context);
+ assert.equal((await h.call({ op: 'getEnv', policy: 'TestPolicy', envId: 'explicit-env' })).ok, true);
+ assert.deepEqual(h.resolutions, ['explicit-env']);
+ assert.strictEqual(h.requests[0].context, context);
+});
+
+test('unresolved environments and authentication errors fail before any gateway request', async () => {
+ for (const context of [{ error: 'Sign-in required' }, {}]) {
+ const h = harness(context);
+ const result = await h.call({ op: 'getEnv', policy: 'TestPolicy' });
+ assert.equal(result.ok, false);
+ assert.equal(result.statusCode, 0);
+ assert.equal(result.error.code, 'ContextError');
+ assert.match(result.error.message, context.error ? /Sign-in required/ : /No environment could be resolved.*--envId/);
+ assert.equal(h.requests.length, 0);
+ }
+});
+
+test('resolving an environment preserves required policy and site validation', async () => {
+ const h = harness({ environmentId: 'resolved-env' });
+ await assert.rejects(h.call({ op: 'getEnv' }), /policy is required/);
+ await assert.rejects(h.call({ op: 'getPortal', policy: 'TestPolicy' }), /portalId is required/);
+ assert.equal(h.requests.length, 0);
+});
+
+test('only an environment-policy 404 becomes an explicit unconfigured disabled scope', async () => {
+ const failure = {
+ ok: false, statusCode: 404, body: { error: { message: 'Not found' } },
+ error: { code: 'HTTP_404', message: 'Not found' },
+ };
+ for (const [op] of operations) {
+ const h = harness({ environmentId: 'test-env' }, failure);
+ const result = await h.call({ op, policy: 'TestPolicy', portalId: 'test-site' });
+ assert.equal(result.statusCode, 404);
+ assert.equal(result.ok, op === 'getEnv');
+ if (op === 'getEnv') {
+ assert.equal(result.body, 'None');
+ assert.equal(result.settingPresent, false);
+ assert.equal(result.error, undefined);
+ } else {
+ assert.strictEqual(result.body, failure.body);
+ assert.strictEqual(result.error, failure.error);
+ assert.equal(result.settingPresent, undefined);
+ }
+ }
+});
+
+test('environment-policy authentication, transport, and server failures remain failures', async () => {
+ for (const statusCode of [0, 400, 401, 403, 429, 500, 503]) {
+ const failure = { ok: false, statusCode, body: null, error: { code: 'Failure', message: 'Rejected' } };
+ const h = harness({ environmentId: 'test-env' }, failure);
+ const result = await h.call({ op: 'getEnv', policy: 'TestPolicy' });
+ assert.equal(result.ok, false);
+ assert.equal(result.statusCode, statusCode);
+ assert.strictEqual(result.error, failure.error);
+ assert.equal(result.settingPresent, undefined);
+ }
+});
diff --git a/plugins/power-pages/scripts/tests/governance/list-envs.test.js b/plugins/power-pages/scripts/tests/governance/list-envs.test.js
new file mode 100644
index 000000000..50cc42af8
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/list-envs.test.js
@@ -0,0 +1,149 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const { EventEmitter } = require('node:events');
+
+// Run the real REST helper/CLI with fake HTTPS and time so deadline tests
+// never contact BAP, read credentials, or wait sixty seconds.
+function harness() {
+ const script = path.resolve(__dirname, '../../../skills/manage-governance/scripts/list-envs.js');
+ const req = new EventEmitter();
+ let onResponse;
+ let main;
+ let clock = 0;
+ let timer;
+ let stdout = '';
+ let timerCleared = false;
+ let destroyed = false;
+ req.destroy = (error) => { destroyed = true; req.emit('error', error); };
+ const sandbox = {
+ module: { exports: {} },
+ process: {
+ argv: ['node', script], env: {},
+ stdout: { write: (text) => { stdout += text; } },
+ },
+ setTimeout(callback, ms) {
+ timer = { callback, deadline: clock + ms };
+ return timer;
+ },
+ clearTimeout(handle) {
+ assert.equal(handle, timer);
+ timerCleared = true;
+ },
+ require(name) {
+ if (name === 'https') return { get(url, options, callback) { onResponse = callback; return req; } };
+ if (name === '../../../scripts/lib/power-platform-api') {
+ return {
+ parseCliArgs: () => ({}),
+ runCli: (mod, callback) => { main = callback; },
+ fail(message, code) { throw Object.assign(new Error(message), { exitCode: code }); },
+ };
+ }
+ if (name === '../../../scripts/lib/validation-helpers') return { getAuthToken: () => 'test-token' };
+ if (name === '../../../scripts/lib/pac-bap-shim') {
+ return { listEnvsViaPac: () => { throw new Error('Unexpected PAC call'); } };
+ }
+ if (name === './governance-context') {
+ return {
+ resolveRing: () => 'TIP',
+ getRing: () => ({ bapStrategy: 'rest', bapHost: 'https://example.invalid', bapResource: 'test' }),
+ };
+ }
+ throw new Error(`Unexpected dependency: ${name}`);
+ },
+ };
+ vm.runInNewContext(fs.readFileSync(script, 'utf8'), sandbox, { filename: script });
+ return {
+ fetch: () => sandbox.module.exports.fetchEnvsViaBapRest('https://example.invalid', 'test-token'),
+ run: () => main(),
+ advance(ms) {
+ clock += ms;
+ if (timer && !timerCleared && clock >= timer.deadline) timer.callback();
+ },
+ respond(statusCode = 200) {
+ const res = new EventEmitter();
+ res.statusCode = statusCode;
+ onResponse(res);
+ return res;
+ },
+ get destroyed() { return destroyed; },
+ get timerCleared() { return timerCleared; },
+ get stdout() { return stdout; },
+ req,
+ };
+}
+
+test('TIP environment request aborts at the 60-second total deadline', async () => {
+ const h = harness();
+ const pending = h.fetch();
+ h.advance(59_999);
+ assert.equal(h.destroyed, false);
+ h.advance(1);
+ await assert.rejects(pending, /timed out after 60 seconds/);
+ assert.equal(h.destroyed, true);
+ assert.equal(h.timerCleared, true);
+});
+
+test('TIP timeout still bounds a response body that keeps receiving data', async () => {
+ const h = harness();
+ const pending = h.fetch();
+ const response = h.respond();
+ response.emit('data', '{"value":[');
+ h.advance(30_000);
+ response.emit('data', ' ');
+ h.advance(30_000);
+ await assert.rejects(pending, /timed out after 60 seconds/);
+ assert.equal(h.destroyed, true);
+});
+
+test('TIP environment request clears its deadline after success', async () => {
+ const h = harness();
+ const pending = h.fetch();
+ const response = h.respond();
+ response.emit('data', '{"value":[{"name":"test-environment"}]}');
+ response.emit('end');
+ assert.equal(JSON.stringify(await pending), '[{"name":"test-environment"}]');
+ assert.equal(h.timerCleared, true);
+ h.advance(60_000);
+ assert.equal(h.destroyed, false);
+});
+
+test('TIP environment request clears its deadline after transport and body errors', async () => {
+ for (const source of ['request', 'response']) {
+ const h = harness();
+ const pending = h.fetch();
+ const emitter = source === 'request' ? h.req : h.respond();
+ emitter.emit('error', new Error('connection reset'));
+ await assert.rejects(pending, /connection reset/);
+ assert.equal(h.timerCleared, true);
+ h.advance(60_000);
+ assert.equal(h.destroyed, false);
+ }
+});
+
+test('TIP environment-list CLI reports timeout as a failure, not an empty inventory', async () => {
+ const h = harness();
+ const pending = h.run();
+ h.advance(60_000);
+ await assert.rejects(pending, (error) => {
+ assert.equal(error.exitCode, 1);
+ assert.match(error.message, /Failed to list environments \(TIP ring\).*timed out after 60 seconds/);
+ return true;
+ });
+ assert.equal(h.stdout, '');
+});
+
+test('list-envs exposes no cache or TTL flags', () => {
+ const script = path.resolve(
+ __dirname,
+ '../../../skills/manage-governance/scripts/list-envs.js'
+ );
+ const result = spawnSync(process.execPath, [script, '--help'], { encoding: 'utf8' });
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.doesNotMatch(result.stdout, /cacheFile|maxAgeHours|refresh|TTL/i);
+ assert.match(result.stdout, /node list-envs\.js/);
+});
diff --git a/plugins/power-pages/scripts/tests/governance/list-portals-display.test.js b/plugins/power-pages/scripts/tests/governance/list-portals-display.test.js
new file mode 100644
index 000000000..cf97225e6
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/list-portals-display.test.js
@@ -0,0 +1,111 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const {
+ normalize,
+ orderPortalsForDisplay,
+ compareForDisplay,
+ DISPLAY_LIMIT,
+} = require('../../../skills/manage-governance/scripts/list-portals');
+
+function portal(over = {}) {
+ return {
+ portalId: over.portalId || 'id',
+ name: over.name || 'n',
+ websiteUrl: over.websiteUrl || 'u',
+ type: over.type ?? null,
+ status: over.status ?? null,
+ createdOn: over.createdOn ?? null,
+ };
+}
+
+test('normalize surfaces status and createdOn (camelCase)', () => {
+ const n = normalize({
+ id: 'a',
+ name: 'Portal_1',
+ websiteUrl: 'https://x',
+ type: 'Trial',
+ status: 'StateConfigured',
+ createdOn: '2026-07-19T07:30:42',
+ });
+ assert.equal(n.portalId, 'a');
+ assert.equal(n.status, 'StateConfigured');
+ assert.equal(n.createdOn, '2026-07-19T07:30:42');
+ assert.equal(n.type, 'Trial');
+});
+
+test('normalize tolerates PascalCase Status/CreatedOn', () => {
+ const n = normalize({ Id: 'a', Name: 'P', Status: 'StateConfigured', CreatedOn: '2026-01-01T00:00:00' });
+ assert.equal(n.status, 'StateConfigured');
+ assert.equal(n.createdOn, '2026-01-01T00:00:00');
+});
+
+test('DISPLAY_LIMIT defaults to 10', () => {
+ assert.equal(DISPLAY_LIMIT, 10);
+});
+
+test('orderPortalsForDisplay preserves order and does not truncate when <= limit', () => {
+ const input = [portal({ name: 'A' }), portal({ name: 'B' }), portal({ name: 'C' })];
+ const res = orderPortalsForDisplay(input, 10);
+ assert.equal(res.truncated, false);
+ assert.equal(res.total, 3);
+ assert.deepEqual(res.shown.map((p) => p.name), ['A', 'B', 'C']);
+});
+
+test('orderPortalsForDisplay caps to limit and prioritizes Production first when > limit', () => {
+ // 12 portals: mix of Production/Trial, Configured/other, varied createdOn.
+ const input = [];
+ for (let i = 0; i < 6; i += 1) {
+ input.push(portal({ name: `trial-${i}`, type: 'Trial', status: 'StateConfigured', createdOn: `2026-01-${10 + i}T00:00:00` }));
+ }
+ for (let i = 0; i < 6; i += 1) {
+ input.push(portal({ name: `prod-${i}`, type: 'Production', status: 'StateConfigured', createdOn: `2026-02-${10 + i}T00:00:00` }));
+ }
+ const res = orderPortalsForDisplay(input, 10);
+ assert.equal(res.truncated, true);
+ assert.equal(res.total, 12);
+ assert.equal(res.shown.length, 10);
+ // First six must be the Production ones (rank 1 beats Trial).
+ const firstSix = res.shown.slice(0, 6);
+ assert.ok(firstSix.every((p) => p.type === 'Production'), 'Production sites lead the list');
+});
+
+test('orderPortalsForDisplay ranks StateConfigured above others within same type', () => {
+ const input = [];
+ // 11 Production portals; some not StateConfigured.
+ input.push(portal({ name: 'prod-unconfigured', type: 'Production', status: 'StateCreating', createdOn: '2020-01-01T00:00:00' }));
+ for (let i = 0; i < 10; i += 1) {
+ input.push(portal({ name: `prod-cfg-${i}`, type: 'Production', status: 'StateConfigured', createdOn: `2026-03-${10 + i}T00:00:00` }));
+ }
+ const res = orderPortalsForDisplay(input, 10);
+ assert.equal(res.truncated, true);
+ // The unconfigured one has the oldest createdOn but must be de-prioritized
+ // below StateConfigured, so it should be dropped from the top 10.
+ assert.ok(!res.shown.some((p) => p.name === 'prod-unconfigured'), 'unconfigured site is de-prioritized out of the top 10');
+});
+
+test('compareForDisplay orders by createdOn ASC when type and status tie', () => {
+ const older = portal({ name: 'older', type: 'Production', status: 'StateConfigured', createdOn: '2026-01-01T00:00:00' });
+ const newer = portal({ name: 'newer', type: 'Production', status: 'StateConfigured', createdOn: '2026-06-01T00:00:00' });
+ assert.ok(compareForDisplay(older, newer) < 0);
+ assert.ok(compareForDisplay(newer, older) > 0);
+});
+
+test('compareForDisplay pushes unparseable/missing createdOn to the end', () => {
+ const good = portal({ type: 'Production', status: 'StateConfigured', createdOn: '2026-01-01T00:00:00' });
+ const noDate = portal({ type: 'Production', status: 'StateConfigured', createdOn: null });
+ assert.ok(compareForDisplay(good, noDate) < 0);
+});
+
+test('orderPortalsForDisplay is case-insensitive on type/status', () => {
+ const input = [];
+ for (let i = 0; i < 6; i += 1) input.push(portal({ name: `t-${i}`, type: 'trial', status: 'stateconfigured', createdOn: `2026-01-${10 + i}T00:00:00` }));
+ for (let i = 0; i < 6; i += 1) input.push(portal({ name: `p-${i}`, type: 'production', status: 'stateconfigured', createdOn: `2026-02-${10 + i}T00:00:00` }));
+ const res = orderPortalsForDisplay(input, 10);
+ assert.ok(res.shown.slice(0, 6).every((p) => String(p.type).toLowerCase() === 'production'));
+});
+
+test('orderPortalsForDisplay handles empty / non-array input', () => {
+ assert.deepEqual(orderPortalsForDisplay([]), { shown: [], total: 0, truncated: false, limit: 10 });
+ assert.deepEqual(orderPortalsForDisplay(undefined), { shown: [], total: 0, truncated: false, limit: 10 });
+});
diff --git a/plugins/power-pages/scripts/tests/governance/parse-portal-input.test.js b/plugins/power-pages/scripts/tests/governance/parse-portal-input.test.js
new file mode 100644
index 000000000..e0d8210fd
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/parse-portal-input.test.js
@@ -0,0 +1,190 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const {
+ parsePortalInput,
+} = require('../../../skills/manage-governance/scripts/parse-portal-input');
+
+const siteId = 'abcdefab-1234-5678-90ab-abcdefabcdef';
+const otherId = '11111111-2222-3333-4444-555555555555';
+
+test('parsePortalInput accepts exact IDs and preserves selection syntax', () => {
+ assert.deepEqual(parsePortalInput('all'), { policyValue: 'All', portalIds: [], errors: [] });
+ assert.deepEqual(parsePortalInput('none'), { policyValue: 'None', portalIds: [], errors: [] });
+ for (const [prefix, policyValue] of [['', 'Include'], ['not ', 'Exclude'], ['except ', 'Exclude']]) {
+ const result = parsePortalInput(` ${prefix}${siteId.toUpperCase()},\r\n ${otherId}, ${siteId} `, {
+ validIds: [siteId, otherId],
+ });
+ assert.deepEqual(result, { policyValue, portalIds: [siteId, otherId], errors: [] });
+ }
+ assert.deepEqual(parsePortalInput(` ${siteId} `), {
+ policyValue: 'Include', portalIds: [siteId], errors: [],
+ });
+});
+
+test('parsePortalInput rejects embedded IDs without returning a partial selection', () => {
+ const invalidTokens = [
+ `please use ${siteId} now`,
+ `prefix${siteId}`,
+ `${siteId}suffix`,
+ `{${siteId}}`,
+ `${siteId}.`,
+ `${siteId} ${otherId}`,
+ ];
+ for (const validIds of [undefined, [siteId, otherId]]) {
+ for (const token of invalidTokens) {
+ for (const prefix of ['', 'not ', 'except ', `${otherId}, `]) {
+ const result = parsePortalInput(prefix + token, { validIds });
+ assert.equal(result.policyValue, null, prefix + token);
+ assert.deepEqual(result.portalIds, [], prefix + token);
+ assert.ok(result.errors.length > 0, prefix + token);
+ }
+ }
+ }
+});
+
+test('an explicitly empty site inventory accepts only all, not unverified IDs or other scope input', () => {
+ assert.deepEqual(parsePortalInput(' ALL ', { validIds: [] }), {
+ policyValue: 'All', portalIds: [], errors: [],
+ });
+ for (const input of [siteId, `not ${siteId}`, `except ${siteId}`, 'Site 1', 'none', '', null]) {
+ const result = parsePortalInput(input, { validIds: [] });
+ assert.equal(result.policyValue, null);
+ assert.deepEqual(result.portalIds, []);
+ assert.equal(result.errors.length, 1);
+ assert.match(result.errors[0], /no sites.*Enter "all".*or cancel/);
+ }
+ assert.deepEqual(parsePortalInput(siteId), {
+ policyValue: 'Include', portalIds: [siteId], errors: [],
+ });
+});
+
+test('parse portal CLI restricts an empty environment to all', () => {
+ const script = path.resolve(__dirname, '../../../skills/manage-governance/scripts/parse-portal-input.js');
+ for (const input of ['all', siteId, 'none']) {
+ const result = spawnSync(process.execPath, [script, '--portalsStdin', '--input', input], {
+ input: JSON.stringify({ portals: [] }), encoding: 'utf8',
+ });
+ const parsed = JSON.parse(result.stdout);
+ assert.equal(result.status, input === 'all' ? 0 : 1, result.stderr);
+ assert.equal(parsed.policyValue, input === 'all' ? 'All' : null);
+ assert.deepEqual(parsed.portalIds, []);
+ if (input !== 'all') assert.match(parsed.errors[0], /no sites.*Enter "all"/);
+ }
+});
+
+test('parsePortalInput resolves exact names containing IDs without extracting the ID', () => {
+ const name = `Preview ${siteId}`;
+ const result = parsePortalInput(name.toUpperCase(), {
+ validIds: [{ portalId: otherId, name }],
+ });
+ assert.deepEqual(result, {
+ policyValue: 'Include', portalIds: [otherId], errors: [], resolvedNames: [name],
+ });
+});
+
+test('parsePortalInput resolves a portal name from an in-memory list', () => {
+ const result = parsePortalInput('Portal_1', {
+ validIds: [{ portalId: 'portal-id-1', name: 'Portal_1' }],
+ });
+ assert.deepEqual(result, {
+ policyValue: 'Include',
+ portalIds: ['portal-id-1'],
+ errors: [],
+ resolvedNames: ['Portal_1'],
+ });
+});
+
+test('duplicate site names require an exact ID regardless of case or inventory order', () => {
+ for (const name of ['Shared Site', 'SHARED SITE']) {
+ const sites = [{ portalId: siteId, name: 'Shared Site' }, { portalId: otherId, name }];
+ for (const validIds of [sites, [...sites].reverse()]) {
+ for (const prefix of ['', 'not ', 'except ', `${siteId}, `]) {
+ const result = parsePortalInput(`${prefix}shared site`, { validIds });
+ assert.equal(result.policyValue, null);
+ assert.deepEqual(result.portalIds, []);
+ assert.equal(result.resolvedNames, undefined);
+ assert.equal(result.errors.length, 1);
+ assert.match(result.errors[0], /ambiguous.*Provide the exact site ID or cancel/);
+ assert.ok(result.errors[0].includes(siteId));
+ assert.ok(result.errors[0].includes(otherId));
+ }
+ for (const [prefix, policyValue] of [['', 'Include'], ['not ', 'Exclude'], ['except ', 'Exclude']]) {
+ const result = parsePortalInput(`${prefix}${siteId.toUpperCase()}`, { validIds });
+ assert.equal(result.policyValue, policyValue);
+ assert.deepEqual(result.portalIds, [siteId]);
+ assert.deepEqual(result.errors, []);
+ }
+ }
+ }
+});
+
+test('repeated records for one site ID do not make its name ambiguous', () => {
+ const result = parsePortalInput(`shared site, ${siteId}`, {
+ validIds: [
+ { portalId: siteId, name: 'Shared Site' },
+ { portalId: siteId.toUpperCase(), name: 'SHARED SITE' },
+ ],
+ });
+ assert.equal(result.policyValue, 'Include');
+ assert.deepEqual(result.portalIds, [siteId.toUpperCase()]);
+ assert.deepEqual(result.errors, []);
+ assert.deepEqual(result.resolvedNames, ['SHARED SITE']);
+});
+
+test('parse portal CLI rejects duplicate names but accepts the selected exact ID', () => {
+ const script = path.resolve(__dirname, '../../../skills/manage-governance/scripts/parse-portal-input.js');
+ const input = JSON.stringify({
+ portals: [{ portalId: siteId, name: 'Same Name' }, { portalId: otherId, name: 'same name' }],
+ });
+ for (const selection of ['Same Name', otherId]) {
+ const result = spawnSync(process.execPath, [script, '--portalsStdin', '--input', selection], {
+ input, encoding: 'utf8',
+ });
+ const parsed = JSON.parse(result.stdout);
+ assert.equal(result.status, selection === otherId ? 0 : 1, result.stderr);
+ assert.deepEqual(parsed.portalIds, selection === otherId ? [otherId] : []);
+ if (selection !== otherId) assert.match(parsed.errors[0], /ambiguous/);
+ }
+});
+
+test('parse portal CLI accepts list-portals JSON on stdin', () => {
+ const script = path.resolve(
+ __dirname,
+ '../../../skills/manage-governance/scripts/parse-portal-input.js'
+ );
+ const result = spawnSync(
+ process.execPath,
+ [script, '--portalsStdin', '--input', 'Portal_1'],
+ {
+ input: JSON.stringify({
+ portals: [{ portalId: 'portal-id-1', name: 'Portal_1' }],
+ }),
+ encoding: 'utf8',
+ }
+ );
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(JSON.parse(result.stdout).portalIds, ['portal-id-1']);
+});
+
+test('parse portal CLI exits with an error for an ID embedded in extra text', () => {
+ const script = path.resolve(
+ __dirname,
+ '../../../skills/manage-governance/scripts/parse-portal-input.js'
+ );
+ const result = spawnSync(
+ process.execPath,
+ [script, '--portalsStdin', '--input', `please use ${siteId} now`],
+ {
+ input: JSON.stringify({ portals: [{ portalId: siteId, name: 'Site 1' }] }),
+ encoding: 'utf8',
+ }
+ );
+ assert.equal(result.status, 1, result.stderr);
+ const parsed = JSON.parse(result.stdout);
+ assert.equal(parsed.policyValue, null);
+ assert.deepEqual(parsed.portalIds, []);
+ assert.ok(parsed.errors.length > 0);
+});
diff --git a/plugins/power-pages/scripts/tests/governance/render-env-table.test.js b/plugins/power-pages/scripts/tests/governance/render-env-table.test.js
new file mode 100644
index 000000000..3758d36d9
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/render-env-table.test.js
@@ -0,0 +1,158 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const {
+ renderEnvTable,
+ renderEnvMarkdown,
+ resolveDefaultEnvId,
+ CURRENT_TAG,
+ CURRENT_MARK,
+} = require('../../../skills/manage-governance/scripts/render-env-table');
+
+const SAMPLE = [
+ { displayName: 'Test environment 1', envId: '00000000-0000-4000-8000-000000000001' },
+ { displayName: 'Test environment 2', envId: '00000000-0000-4000-8000-000000000002' },
+ { displayName: 'Test environment 3', envId: '00000000-0000-4000-8000-000000000003' },
+];
+
+function lines(str) {
+ return str.split('\n');
+}
+
+test('renders a bordered box with header and one row per env', () => {
+ const out = renderEnvTable(SAMPLE);
+ const l = lines(out);
+ // top border + header + header-sep + 3 rows + bottom border = 7 lines
+ assert.equal(l.length, 7);
+ assert.match(l[0], /^\+-+\+-+\+-+\+-+\+$/);
+ assert.match(l[l.length - 1], /^\+-+\+-+\+-+\+-+\+$/);
+ assert.ok(l[1].includes('Environment Name'));
+ assert.ok(l[1].includes('Environment ID'));
+});
+
+test('every rendered line has identical visible width (aligned columns)', () => {
+ const out = renderEnvTable(SAMPLE, { currentEnvId: SAMPLE[2].envId });
+ const widths = new Set(lines(out).map((s) => s.length));
+ assert.equal(widths.size, 1, 'all lines must share one width');
+});
+
+test('output is ASCII-only (no wide glyphs that break alignment)', () => {
+ const out = renderEnvTable(SAMPLE, { currentEnvId: SAMPLE[2].envId });
+ // eslint-disable-next-line no-control-regex
+ assert.ok(/^[\x00-\x7F\n]*$/.test(out), 'table must contain only ASCII characters');
+});
+
+test('flags the current selection row with the marker and tag', () => {
+ const current = SAMPLE[2].envId;
+ const out = renderEnvTable(SAMPLE, { currentEnvId: current });
+ const row = lines(out).find((s) => s.includes(SAMPLE[2].displayName));
+ assert.ok(row.includes(CURRENT_MARK), 'current row shows the marker');
+ assert.ok(row.includes(CURRENT_TAG), 'current row shows the CURRENT SELECTION tag');
+});
+
+test('no current selection → no marker/tag anywhere', () => {
+ const out = renderEnvTable(SAMPLE);
+ assert.ok(!out.includes(CURRENT_TAG));
+});
+
+test('exactly one row is tagged as current', () => {
+ const out = renderEnvTable(SAMPLE, { currentEnvId: SAMPLE[1].envId });
+ const tagged = lines(out).filter((s) => s.includes(CURRENT_TAG));
+ assert.equal(tagged.length, 1);
+ assert.ok(tagged[0].includes(SAMPLE[1].displayName));
+});
+
+test('row numbers are 1-based and sequential', () => {
+ const out = renderEnvTable(SAMPLE);
+ const body = lines(out).slice(3, -1);
+ assert.match(body[0], /^\|\s*1\s*\|/);
+ assert.match(body[1], /^\|\s*2\s*\|/);
+ assert.match(body[2], /^\|\s*3\s*\|/);
+});
+
+test('handles empty env list without throwing', () => {
+ const out = renderEnvTable([]);
+ assert.ok(out.includes('Environment Name'));
+});
+
+test('unknown currentEnvId tags nothing', () => {
+ const out = renderEnvTable(SAMPLE, { currentEnvId: 'does-not-exist' });
+ assert.ok(!out.includes(CURRENT_TAG));
+});
+
+test('missing displayName falls back to (unnamed)', () => {
+ const out = renderEnvTable([{ envId: 'abc' }]);
+ assert.ok(out.includes('(unnamed)'));
+});
+
+// --- renderEnvMarkdown (GitHub-flavored Markdown table for chat surfaces) ---
+
+test('markdown: emits header + separator + one row per env', () => {
+ const out = renderEnvMarkdown(SAMPLE);
+ const l = lines(out);
+ // header + separator + 3 rows = 5 lines
+ assert.equal(l.length, 5);
+ assert.equal(l[0], '| # | Selected | Environment Name | Environment ID |');
+ assert.equal(l[1], '|---|---|---|---|');
+ assert.ok(l[2].includes(SAMPLE[0].displayName));
+});
+
+test('markdown: row numbers are 1-based and sequential', () => {
+ const out = renderEnvMarkdown(SAMPLE);
+ const body = lines(out).slice(2);
+ assert.match(body[0], /^\|\s*1\s*\|/);
+ assert.match(body[1], /^\|\s*2\s*\|/);
+ assert.match(body[2], /^\|\s*3\s*\|/);
+});
+
+test('markdown: flags exactly the current selection row in the Selected column', () => {
+ const out = renderEnvMarkdown(SAMPLE, {
+ currentEnvId: SAMPLE[2].envId,
+ });
+ const tagged = lines(out).filter((s) => s.includes('selected earlier'));
+ assert.equal(tagged.length, 1);
+ assert.ok(tagged[0].includes(SAMPLE[2].displayName));
+});
+
+test('markdown: no current selection → no "selected earlier" marker', () => {
+ const out = renderEnvMarkdown(SAMPLE);
+ assert.ok(!out.includes('selected earlier'));
+});
+
+test('markdown: escapes pipe characters in env display names', () => {
+ // A literal '|' in a name would prematurely close the Markdown cell — it must
+ // be escaped so the table structure survives user-controlled env names.
+ const out = renderEnvMarkdown([{ displayName: 'a|b', envId: 'x' }]);
+ assert.ok(out.includes('a\\|b'), 'pipe must be backslash-escaped');
+});
+
+test('markdown: missing displayName falls back to (unnamed)', () => {
+ const out = renderEnvMarkdown([{ envId: 'abc' }]);
+ assert.ok(out.includes('(unnamed)'));
+});
+
+// --- resolveDefaultEnvId (auto-flag the tenant-default env, no extra lookup) ---
+
+test('resolveDefaultEnvId: returns the env whose type is "Default"', () => {
+ const envs = [
+ { envId: 'a', type: 'Production' },
+ { envId: 'b', type: 'Default' },
+ ];
+ assert.equal(resolveDefaultEnvId(envs), 'b');
+});
+
+test('resolveDefaultEnvId: matches type case-insensitively', () => {
+ // Casing has varied across CLI versions ("Default" vs "default").
+ const envs = [{ envId: 'a', type: 'default' }];
+ assert.equal(resolveDefaultEnvId(envs), 'a');
+});
+
+test('resolveDefaultEnvId: returns null when no default env is present', () => {
+ const envs = [{ envId: 'a', type: 'Production' }];
+ assert.equal(resolveDefaultEnvId(envs), null);
+});
+
+test('resolveDefaultEnvId: tolerates non-array / empty input', () => {
+ assert.equal(resolveDefaultEnvId(null), null);
+ assert.equal(resolveDefaultEnvId([]), null);
+});
diff --git a/plugins/power-pages/scripts/tests/governance/render-impact-summary.test.js b/plugins/power-pages/scripts/tests/governance/render-impact-summary.test.js
new file mode 100644
index 000000000..ca229a4cd
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/render-impact-summary.test.js
@@ -0,0 +1,553 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const {
+ renderImpactSummary,
+ normalizeState,
+ newStateFor,
+ scopeLine,
+ cascadeLines,
+ actionCell,
+ effectLine,
+} = require('../../../skills/manage-governance/scripts/render-impact-summary');
+const { markdownText } = require('../../../skills/manage-governance/scripts/table');
+const mapping = require('../../../skills/manage-governance/references/governance-mapping.json');
+
+function findPolicy(name) {
+ return mapping.policies.find((p) => p.policyName === name);
+}
+
+test('renderImpactSummary emits the required consent-gate rows in order', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenIdConnect',
+ direction: 'disable',
+ scope: 'all',
+ policyValue: 'None',
+ env: { displayName: 'Test environment', envId: 'env-1' },
+ sites: [
+ { name: 'Site 1', url: 'https://a', portalId: '3e13', currentState: 'Enabled' },
+ { name: 'Site 2', url: 'https://b', portalId: 'ea51', currentState: 'Enabled' },
+ ],
+ });
+ const l = out.split('\n');
+ // Must start at Action: with no lead-in (SKILL.md forbids any heading first).
+ // The Action row is direction-colored: red 🔴 for a disable operation.
+ assert.match(l[0], /^\*\*Action:\*\*\s+🔴 Disable OpenID Connect sign-in$/);
+ assert.match(out, /^\*\*Environment:\*\*\s+Test environment\s+\(env-1\)$/m);
+ assert.match(out, /^\*\*Scope:\*\*\s+Every site in this environment$/m);
+ assert.match(out, /^\*\*Sites in environment:\*\*$/m);
+ assert.match(out, /^\*\*Effect:\*\*\s+OpenID Connect sign-in will be disabled on all sites in Test environment\.$/m);
+ // The API-mapping companion line: env-wide disable -> None (no ToBeAdded list).
+ assert.match(out, /^\*\*Policy value:\*\*\s+None$/m);
+});
+
+test('shared Markdown prose helper preserves names as single-line literal text', () => {
+ const cases = [
+ [null, ''],
+ ['Test environment', 'Test environment'],
+ ['*Site*_[link](url)`code`', '\\*Site\\*\\_\\[link\\]\\(url\\)\\`code\\`'],
+ ['A\\|B', 'A\\\\\\|B'],
+ ['A\r\nB\rC\nD\u2028E\u2029F', 'A B C D E F'],
+ ['<b>&#42; &amp;</b>', '\\<b\\>&amp;\\#42; &amp;amp;\\</b\\>'],
+ ['A\tB\u001bC', 'A B C'],
+ ];
+ for (const [input, expected] of cases) {
+ assert.equal(markdownText(input), expected);
+ }
+});
+
+for (const direction of ['enable', 'disable']) {
+ for (const scope of ['all', 'specific']) {
+ test(`impact prose escapes names for ${direction}/${scope} without replacement-string expansion`, () => {
+ const envName = '*Environment*\r\n> [link](url) $&';
+ const siteName = '`Site`\\|A\n# Heading $&';
+ const escapedEnv = '\\*Environment\\* \\> \\[link\\]\\(url\\) $&amp;';
+ const escapedSite = '\\`Site\\`\\\\\\|A \\# Heading $&amp;';
+ const req = {
+ policy: 'EnableProtocolOpenIdConnect',
+ direction,
+ scope,
+ env: { displayName: envName, envId: 'env-1' },
+ sites: [{ name: siteName, portalId: 'site-1', currentState: 'Disabled' }],
+ };
+ const out = renderImpactSummary(req);
+ const envLine = out.split('\n').find((line) => line.startsWith('**Environment:**'));
+ const scopeOutput = out.split('\n').find((line) => line.startsWith('**Scope:**'));
+ const effect = out.split('\n').find((line) => line.startsWith('**Effect:**'));
+ assert.equal(envLine, `**Environment:** ${escapedEnv} (env-1)`);
+ assert.equal(scopeOutput, scope === 'specific'
+ ? `**Scope:** Only ${escapedSite}`
+ : '**Scope:** Every site in this environment');
+ assert.ok(effect.includes(scope === 'specific' ? escapedSite : escapedEnv));
+ assert.doesNotMatch(out, /^> \[link\]|^# Heading/m);
+ assert.doesNotMatch(effect, /\{EnvDisplay\}|\{SiteNameList\}/);
+ assert.equal(req.env.displayName, envName, 'input names are not modified');
+ assert.equal(req.sites[0].name, siteName);
+ });
+ }
+}
+
+test('fallback Effect sentence also escapes the environment name', () => {
+ assert.equal(
+ effectLine({}, findPolicy('EnableProtocolOpenIdConnect'), 'disable', 'all', '*Env*\n<b>', []),
+ 'OpenID Connect sign-in will be disabled in \\*Env\\* \\<b\\>.',
+ );
+});
+
+test('Policy value line derives Include + ToBeAdded ids for a specific-site enable', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenIdConnect',
+ direction: 'enable',
+ scope: 'specific',
+ // policyValue intentionally omitted — must be derived (enable+specific -> Include).
+ env: { displayName: 'Env', envId: 'e1' },
+ sites: [
+ { name: 'P3', url: 'https://c', portalId: 'aaa', currentState: 'Disabled' },
+ { name: 'P4', url: 'https://d', portalId: 'bbb', currentState: 'Disabled' },
+ ],
+ });
+ assert.match(out, /^\*\*Policy value:\*\*\s+Include, ToBeAdded = \[aaa, bbb\]$/m);
+});
+
+test('Policy value line uses the explicit req.policyValue when provided (Exclude for specific disable)', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenIdConnect',
+ direction: 'disable',
+ scope: 'specific',
+ policyValue: 'Exclude',
+ env: { displayName: 'Env', envId: 'e1' },
+ sites: [{ name: 'P1', url: 'https://a', portalId: 'xyz', currentState: 'Enabled' }],
+ });
+ assert.match(out, /^\*\*Policy value:\*\*\s+Exclude, ToBeAdded = \[xyz\]$/m);
+});
+
+test('flips are marked ← CHANGED, already-terminal sites are not', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenIdConnect',
+ direction: 'disable',
+ scope: 'all',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [
+ { name: 'Site 1', currentState: 'Enabled' }, // Enabled -> Disabled = changed
+ { name: 'Site 2', currentState: 'Disabled' }, // already Disabled = no change
+ { name: 'Site 3', currentState: 'garbage' }, // Unknown = never flagged
+ ],
+ });
+ // Exactly one known current state flips; Unknown is not asserted as changed.
+ assert.equal((out.match(/CHANGED/g) || []).length, 1, 'exactly one row must be flagged CHANGED');
+ assert.match(out, /←/, 'the changed marker uses the ← arrow');
+ // All three sites must still appear in the table.
+ for (const name of ['Site 1', 'Site 2', 'Site 3']) {
+ assert.ok(out.includes(name), `${name} must appear in the Sites table`);
+ }
+});
+
+test('the Sites table renders as a GitHub-flavored Markdown table with single-line rows', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenIdConnect',
+ direction: 'disable',
+ scope: 'all',
+ policyValue: 'None',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [
+ {
+ name: 'Portal_1',
+ url: 'https://site-1.example.com',
+ portalId: 'site-1',
+ currentState: 'Enabled',
+ },
+ ],
+ });
+ // Markdown pipe table — a header row, a `---` delimiter row, then data rows.
+ // We deliberately DROPPED the fixed-width Unicode box (it misaligned in chat
+ // because the state emoji are double-width), so the box borders must be gone.
+ assert.ok(!/[┌┬┐└┴┘├┼┤─│]/.test(out), 'must NOT render Unicode box-drawing characters');
+ assert.match(
+ out,
+ /^\| Site Name \| URL \| Site ID \| Current State \| New State \|$/m,
+ 'Markdown header row present'
+ );
+ assert.match(out, /^\| --- \| --- \| --- \| --- \| --- \|$/m, 'Markdown delimiter row present');
+ // The whole site row — including the double-width emoji and the ← CHANGED
+ // marker — renders on ONE physical line as a single pipe row.
+ assert.match(
+ out,
+ /^\| Portal_1 \| https:\/\/site-1\.example\.com \| site-1 \| 🟢 Enabled \| 🔴 Disabled ← CHANGED \|$/m,
+ 'the site row is a single Markdown line with every cell inline'
+ );
+});
+
+test('Markdown table cells escape a literal pipe so columns never shift', () => {
+ // A site name containing '|' must be backslash-escaped, otherwise it would be
+ // read as an extra column separator and break the row's alignment.
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenIdConnect',
+ direction: 'disable',
+ scope: 'all',
+ policyValue: 'None',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'A|B', url: 'https://x', portalId: 'p1', currentState: 'Enabled' }],
+ });
+ assert.match(out, /\| A\\\|B \|/, 'a literal pipe in a cell is escaped as \\|');
+});
+
+test('impact Markdown separates paragraphs, table, warning, and cascade without hard-wrapping cells', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableExternalAuthProviders',
+ direction: 'disable',
+ scope: 'all',
+ env: { displayName: 'Test environment', envId: 'test-env' },
+ sites: [{
+ name: 'Long|Site\r\nPreview',
+ url: `https://${'long-site-'.repeat(8)}.example.com`,
+ portalId: '11111111-2222-3333-4444-555555555555',
+ currentState: 'Enabled',
+ }],
+ });
+ const table = out.split('\n').filter((line) => line.startsWith('|'));
+ assert.equal(table.length, 3, 'one header, separator, and complete data row');
+ assert.match(table[2], /Long\\\|Site Preview/);
+ assert.ok(table[2].includes('11111111-2222-3333-4444-555555555555'));
+ assert.match(out, /\*\*Scope:\*\*[^\n]+\n\n\*\*Sites in environment:\*\*\n\n\|/);
+ assert.match(out, /\| 🔴 Disabled ← CHANGED \|\n\n\*\*Effect:\*\*/);
+ assert.match(out, /\n\n\*\*Policy value:\*\* None\n\n> \*\*Side effect:\*\*/);
+ const heading = findPolicy('EnableExternalAuthProviders').cascadeOnDisable.heading;
+ assert.ok(out.includes(`\n\n**${heading}**\n\n1. `), 'list needs separation from its heading');
+ assert.equal(out.split('\n').filter((line) => /^\d+\. /.test(line)).length, 7);
+ assert.ok(!out.includes('```'), 'render Markdown, not a code block');
+ assert.ok(!out.includes('\u001b['), 'default Markdown must not include ANSI');
+});
+
+test('Side effect line only renders when policyValue is a per-policy trigger', () => {
+ // Enable* toggles trigger the sign-out callout on None/Exclude (disable).
+ const disabled = renderImpactSummary({
+ policy: 'EnableIdpOAuthFacebook',
+ direction: 'disable',
+ scope: 'all',
+ policyValue: 'None',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Enabled' }],
+ });
+ assert.match(disabled, /^> \*\*Side effect:\*\*\s+Disabling this signs out/m);
+
+ // Enabling (All) must NOT surface the sign-out warning.
+ const enabled = renderImpactSummary({
+ policy: 'EnableIdpOAuthFacebook',
+ direction: 'enable',
+ scope: 'all',
+ policyValue: 'All',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Disabled' }],
+ });
+ assert.ok(!/Side effect:/.test(enabled), 'enable must not show a sign-out side effect');
+});
+
+test('specific scope renders the Sites covered label and lists names in the Effect line', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolSAML20',
+ direction: 'enable',
+ scope: 'specific',
+ policyValue: 'Include',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [
+ { name: 'Site 1', currentState: 'Disabled' },
+ { name: 'Site 2', currentState: 'Disabled' },
+ ],
+ });
+ assert.match(out, /^\*\*Sites covered:\*\*$/m);
+ assert.match(out, /^\*\*Scope:\*\*\s+Only Site 1, Site 2$/m);
+ assert.match(out, /Effect:.*listed sites in env: Site 1, Site 2\.$/m);
+});
+
+test('never leaks the internal policyValue terms into the plain-language block', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenIdConnect',
+ direction: 'enable',
+ scope: 'all',
+ policyValue: 'All',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Disabled' }],
+ });
+ // The dedicated `Policy value:` line intentionally shows the technical
+ // All/None/Include/Exclude value the admin approves (the user explicitly asked
+ // to see it). Everything ELSE — Action / Scope / Effect / Sites — is
+ // plain-language and must never leak those internal terms. So scrub only the
+ // Policy value line before scanning the rest.
+ const plain = out
+ .split('\n')
+ .filter((line) => !/^\*\*Policy value:/.test(line))
+ .join('\n');
+ for (const term of ['All', 'Include', 'None', 'Exclude']) {
+ assert.ok(
+ !new RegExp('\\b' + term + '\\b').test(plain),
+ `plain-language block must not leak internal term '${term}'`
+ );
+ }
+});
+
+test('unknown policy throws (guards against a bad caller)', () => {
+ assert.throws(
+ () => renderImpactSummary({ policy: 'NotAPolicy', direction: 'enable', env: {} }),
+ /unknown policy/
+ );
+});
+
+test('normalizeState maps live-read variants, falling back to Unknown', () => {
+ assert.equal(normalizeState('Enabled'), 'Enabled');
+ assert.equal(normalizeState('disabled'), 'Disabled');
+ assert.equal(normalizeState('blocked'), 'Disabled');
+ assert.equal(normalizeState(''), 'Unknown');
+ assert.equal(normalizeState(null), 'Unknown');
+ assert.equal(normalizeState('None'), 'Unknown');
+});
+
+test('newStateFor / scopeLine helpers behave per direction and scope', () => {
+ assert.equal(newStateFor('disable'), 'Disabled');
+ assert.equal(newStateFor('enable'), 'Enabled');
+ assert.equal(scopeLine('all', ['Site 1']), 'Every site in this environment');
+ assert.equal(scopeLine('specific', ['Site 1', 'Site 2']), 'Only Site 1, Site 2');
+});
+
+test('disabling External Auth Providers lists every downstream sign-in method it turns off', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableExternalAuthProviders',
+ direction: 'disable',
+ scope: 'all',
+ policyValue: 'None',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Enabled' }],
+ });
+ // Heading + all 7 downstream methods, numbered, each marked Disabled.
+ assert.ok(out.includes(`**${findPolicy('EnableExternalAuthProviders').cascadeOnDisable.heading}**`));
+ const expected = [
+ 'Authentication Using OpenID Connect (OIDC) Protocol',
+ 'Authentication Using SAML 2.0 Protocol',
+ 'Authentication Using OAuth 2.0 Protocol',
+ 'Facebook Authentication',
+ 'Google Authentication',
+ 'Microsoft Authentication',
+ 'Authentication Using WS-Federation Protocol',
+ ];
+ expected.forEach((name, i) => {
+ const row = out.split('\n').find((line) => line.startsWith(`${i + 1}. `));
+ assert.equal(row, `${i + 1}. ${name} — 🔴 Disabled`);
+ });
+ assert.ok(!out.includes('undefined'));
+ // The cascade block appears after the Side effect line, not before the table.
+ assert.ok(out.indexOf(findPolicy('EnableExternalAuthProviders').cascadeOnDisable.heading) > out.indexOf('Side effect:'));
+});
+
+test('disabling the OAuth 2.0 protocol lists only the OAuth-based social IdPs', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenAuth',
+ direction: 'disable',
+ scope: 'all',
+ policyValue: 'None',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Enabled' }],
+ });
+ assert.ok(out.includes(findPolicy('EnableProtocolOpenAuth').cascadeOnDisable.heading));
+ assert.match(out, /^1\. Facebook — 🔴 Disabled$/m);
+ assert.match(out, /^2\. Google — 🔴 Disabled$/m);
+ assert.match(out, /^3\. Microsoft — 🔴 Disabled$/m);
+ // OAuth's cascade is the social IdPs only — it must NOT list the protocols.
+ assert.ok(!/OpenIdConnect/.test(out), 'OAuth cascade must not list OpenIdConnect');
+ assert.ok(!/WS_Federation/.test(out), 'OAuth cascade must not list WS_Federation');
+});
+
+test('enabling a parent shows the availability cascade, not the disable checklist', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenAuth',
+ direction: 'enable',
+ scope: 'all',
+ policyValue: 'All',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Disabled' }],
+ });
+ // Enable must never claim the children "will get Disable" (they keep their state).
+ assert.ok(!out.includes(findPolicy('EnableProtocolOpenAuth').cascadeOnDisable.heading), 'enable must not show the disable cascade');
+ // It surfaces the informational availability list instead.
+ assert.match(out, /must also be enabled individually through its corresponding governance setting/);
+});
+
+test('policies without a cascade dependency render no cascade block', () => {
+ // Facebook is a leaf provider — disabling it has no downstream cascade.
+ const out = renderImpactSummary({
+ policy: 'EnableIdpOAuthFacebook',
+ direction: 'disable',
+ scope: 'all',
+ policyValue: 'None',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Enabled' }],
+ });
+ assert.ok(!/sign-in methods will be disabled/.test(out), 'leaf policy must not show a cascade');
+});
+
+test('cascadeLines helper is direction-gated and data-driven from the mapping', () => {
+ const parent = findPolicy('EnableExternalAuthProviders');
+ const leaf = findPolicy('EnableIdpOAuthGoogle');
+ // disable + has cascade -> heading + one line per item.
+ const disableLines = cascadeLines(parent, 'disable', { enabled: false });
+ assert.equal(disableLines[0], ''); // leading blank line separates from the summary
+ assert.equal(disableLines[1], `**${parent.cascadeOnDisable.heading}**`);
+ assert.equal(disableLines[2], '');
+ assert.equal(disableLines.length, 3 + 7);
+ // enable + has cascade -> heading + one line per item + blank + footer note.
+ const enableLines = cascadeLines(parent, 'enable', { enabled: false });
+ assert.equal(enableLines[0], '');
+ assert.equal(enableLines[1], `**${parent.cascadeOnEnable.heading}**`);
+ assert.equal(
+ enableLines.length,
+ 3 + 7 + 2, // heading separators, seven expanded entries, and footer
+ );
+ assert.match(enableLines[enableLines.length - 1], /^\*\*Note:\*\* Enabling the External Authentication policy/);
+ // leaf policy -> no cascade in either direction.
+ assert.deepEqual(cascadeLines(leaf, 'disable', { enabled: false }), []);
+ assert.deepEqual(cascadeLines(leaf, 'enable', { enabled: false }), []);
+});
+
+test('enabling External Auth Providers lists the methods that become available + config note', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableExternalAuthProviders',
+ direction: 'enable',
+ scope: 'all',
+ policyValue: 'All',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Disabled' }],
+ });
+ assert.ok(out.includes(findPolicy('EnableExternalAuthProviders').cascadeOnEnable.heading));
+ const rows = out.split('\n').filter((line) => /^\d+\./.test(line));
+ assert.deepEqual(rows, [
+ '1. Authentication Using OpenID Connect (OIDC) Protocol',
+ '2. Authentication Using SAML 2.0 Protocol',
+ '3. Authentication Using OAuth 2.0 Protocol',
+ '4. Facebook Authentication',
+ '5. Google Authentication',
+ '6. Microsoft Authentication',
+ '7. Authentication Using WS-Federation Protocol',
+ ]);
+ assert.ok(!out.includes('undefined'));
+ assert.ok(!rows.some((line) => /Enabled|Disabled/.test(line)), 'availability does not force-enable children');
+ // Footer note about per-provider configuration.
+ assert.match(out, /^\*\*Note:\*\* Enabling the External Authentication policy restores support/m);
+ // Enable path must never render the disable heading.
+ assert.ok(!out.includes(findPolicy('EnableExternalAuthProviders').cascadeOnDisable.heading));
+});
+
+test('enabling the OAuth 2.0 protocol lists the social IdPs it does NOT auto-enable', () => {
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenAuth',
+ direction: 'enable',
+ scope: 'all',
+ policyValue: 'All',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Disabled' }],
+ });
+ assert.match(out, /must also be enabled individually through its corresponding governance setting/);
+ assert.match(out, /^1\. Facebook — Controlled by the Facebook governance setting\.$/m);
+ assert.match(out, /^2\. Google — Controlled by the Google governance setting\.$/m);
+ assert.match(out, /^3\. Microsoft — Controlled by the Microsoft governance setting\.$/m);
+ // OAuth enable is IdP-only — no protocol rows, and no numbered disable-cascade
+ // row (the Sites table legitimately shows a 🔴 Disabled current-state cell, so
+ // scope the check to numbered cascade rows only).
+ assert.ok(!/OpenID Connect/.test(out));
+ assert.ok(!/^\d+\..*🔴 Disabled$/m.test(out));
+});
+
+test('cascade note text does not use the abbreviation "IDP"', () => {
+ // The admin asked to drop "IDP" from the per-provider notes.
+ for (const name of ['EnableExternalAuthProviders', 'EnableProtocolOpenAuth']) {
+ const out = renderImpactSummary({
+ policy: name,
+ direction: 'enable',
+ scope: 'all',
+ policyValue: 'All',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Disabled' }],
+ });
+ assert.ok(!/\bIDP\b/.test(out), `${name} enable cascade must not contain "IDP"`);
+ }
+});
+
+test('disable-cascade rows render the red state marker (🔴) for chat visibility', () => {
+ // The 🔴 emoji is what makes the "red for Disable" cue visible where ANSI is
+ // stripped; assert it is present on each disable-cascade row.
+ const out = renderImpactSummary({
+ policy: 'EnableProtocolOpenAuth',
+ direction: 'disable',
+ scope: 'all',
+ policyValue: 'None',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Enabled' }],
+ });
+ assert.match(out, /^1\. Facebook — 🔴 Disabled$/m);
+});
+
+test('cascadeLines renders a green 🟢 Enabled marker for enable items that declare a state', () => {
+ // Mirror of the disable side: an enable item with { state: 'Enabled' } gets the
+ // green "🟢 Enabled" marker, honoring "green for enable". Color is disabled so we
+ // assert the emoji/label only (ANSI would otherwise wrap the span in a terminal).
+ const policy = {
+ cascadeOnEnable: {
+ heading: 'Now enabled:',
+ items: [{ label: 'OAuth 2.0', state: 'Enabled' }],
+ },
+ };
+ const lines = cascadeLines(policy, 'enable', { enabled: false });
+ assert.equal(lines[1], '**Now enabled:**');
+ assert.equal(lines[2], '');
+ assert.match(lines[3], /^1\. OAuth 2\.0 — 🟢 Enabled$/);
+});
+
+test('cascadeLines preserves notes and states in recursively grouped entries', () => {
+ const policy = {
+ cascadeOnEnable: {
+ items: [{ Protocol: [{ Providers: [{ label: 'Provider', state: 'Enabled', note: 'Configured.' }] }] }],
+ },
+ };
+ const rows = cascadeLines(policy, 'enable', { enabled: false }).slice(3);
+ assert.deepEqual(rows, [
+ '1. Protocol',
+ '2. Providers',
+ '3. Provider — 🟢 Enabled - Configured.',
+ ]);
+});
+
+test('cascadeLines rejects malformed entries instead of rendering undefined or omitting impact', () => {
+ for (const item of [null, '', {}, { note: 'Missing label' }, { Protocol: 'not an array' }]) {
+ assert.throws(
+ () => cascadeLines({ cascadeOnDisable: { items: [item] } }, 'disable', { enabled: false }),
+ /invalid cascade item/,
+ );
+ }
+});
+
+test('the Action line is colored by direction (red 🔴 disable / green 🟢 enable)', () => {
+ // The Action row must reflect the same green=enable / red=disable cue as the
+ // state cells; the emoji is the chat-visible carrier where ANSI is stripped.
+ const disableOut = renderImpactSummary({
+ policy: 'EnableProtocolOpenAuth',
+ direction: 'disable',
+ scope: 'all',
+ policyValue: 'None',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Enabled' }],
+ });
+ assert.match(disableOut, /^\*\*Action:\*\*\s+🔴 Disable OAuth 2\.0 sign-in$/m);
+
+ const enableOut = renderImpactSummary({
+ policy: 'EnableProtocolOpenAuth',
+ direction: 'enable',
+ scope: 'all',
+ policyValue: 'All',
+ env: { displayName: 'env', envId: 'e1' },
+ sites: [{ name: 'Site 1', currentState: 'Disabled' }],
+ });
+ assert.match(enableOut, /^\*\*Action:\*\*\s+🟢 Enable OAuth 2\.0 sign-in$/m);
+
+ // Unit-level: actionCell adds ANSI red/green when color is forced on.
+ const redAnsi = actionCell('disable', 'Disable X', { enabled: true });
+ assert.ok(redAnsi.includes('\u001b[31m') && redAnsi.includes('🔴'));
+ const greenAnsi = actionCell('enable', 'Enable X', { enabled: true });
+ assert.ok(greenAnsi.includes('\u001b[32m') && greenAnsi.includes('🟢'));
+});
diff --git a/plugins/power-pages/scripts/tests/governance/render-portal-table.test.js b/plugins/power-pages/scripts/tests/governance/render-portal-table.test.js
new file mode 100644
index 000000000..aa3045201
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/render-portal-table.test.js
@@ -0,0 +1,227 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const scriptsDir = path.join(
+ __dirname,
+ '..',
+ '..',
+ '..',
+ 'skills',
+ 'manage-governance',
+ 'scripts'
+);
+const { foregroundColor, green, red, shouldColor } = require(path.join(scriptsDir, 'colors.js'));
+const { renderPortalTable, renderPortalTableMarkdown, normalizeState, colorForState } = require(path.join(
+ scriptsDir,
+ 'render-portal-table.js'
+));
+
+const GREEN = '\u001b[32m';
+const RED = '\u001b[31m';
+const RESET = '\u001b[0m';
+
+// --- colors.js ---
+
+test('foregroundColor wraps text when enabled', () => {
+ assert.strictEqual(green('Enabled', { enabled: true }), `${GREEN}Enabled${RESET}`);
+ assert.strictEqual(red('Disabled', { enabled: true }), `${RED}Disabled${RESET}`);
+});
+
+test('foregroundColor returns plain text when disabled', () => {
+ assert.strictEqual(green('Enabled', { enabled: false }), 'Enabled');
+ assert.strictEqual(foregroundColor('x', 'Green', { enabled: false }), 'x');
+});
+
+test('unknown color name is left uncolored even when enabled', () => {
+ assert.strictEqual(foregroundColor('x', 'Chartreuse', { enabled: true }), 'x');
+});
+
+test('shouldColor honors explicit tri-state', () => {
+ assert.strictEqual(shouldColor({ enabled: true }), true);
+ assert.strictEqual(shouldColor({ enabled: false }), false);
+});
+
+test('shouldColor: NO_COLOR forces off, FORCE_COLOR forces on', () => {
+ assert.strictEqual(shouldColor({ env: { NO_COLOR: '1' }, stream: { isTTY: true } }), false);
+ assert.strictEqual(shouldColor({ env: { FORCE_COLOR: '1' }, stream: { isTTY: false } }), true);
+});
+
+test('shouldColor auto-detects TTY when no override', () => {
+ assert.strictEqual(shouldColor({ env: {}, stream: { isTTY: true } }), true);
+ assert.strictEqual(shouldColor({ env: {}, stream: { isTTY: false } }), false);
+});
+
+// --- render-portal-table.js ---
+
+const portals = [
+ { name: 'Portal_1', url: 'https://a.example.com', portalId: 'id-1', state: true },
+ { name: 'Portal_2', url: 'https://b.example.com', portalId: 'id-2', state: false },
+];
+
+test('normalizeState maps booleans and strings', () => {
+ assert.strictEqual(normalizeState(true), 'Enabled');
+ assert.strictEqual(normalizeState(false), 'Disabled');
+ assert.strictEqual(normalizeState('enabled'), 'Enabled');
+ assert.strictEqual(normalizeState('Disabled'), 'Disabled');
+ assert.strictEqual(normalizeState('weird'), 'Unknown');
+});
+
+test('colorForState picks green/red/none', () => {
+ assert.strictEqual(colorForState('Enabled'), 'Green');
+ assert.strictEqual(colorForState('Disabled'), 'Red');
+ assert.strictEqual(colorForState('Unknown'), null);
+});
+
+test('renderPortalTable is plain ASCII when color off', () => {
+ const out = renderPortalTable(portals, { color: false });
+ assert.ok(!out.includes('\u001b['), 'must contain no ANSI escapes');
+ assert.ok(out.includes('Enabled'));
+ assert.ok(out.includes('Disabled'));
+});
+
+test('renderPortalTable colors State green/red when color on', () => {
+ const out = renderPortalTable(portals, { color: true });
+ assert.ok(out.includes(GREEN), 'Enabled row should be green');
+ assert.ok(out.includes(RED), 'Disabled row should be red');
+ assert.ok(out.includes(RESET));
+});
+
+test('coloring does not change visible column alignment', () => {
+ const plain = renderPortalTable(portals, { color: false }).split('\n');
+ const colored = renderPortalTable(portals, { color: true }).split('\n');
+ // Strip ANSI from colored, compare to plain — must be identical.
+ const stripped = colored.map((l) => l.replace(/\u001b\[[0-9;]*m/g, ''));
+ assert.deepStrictEqual(stripped, plain);
+});
+
+test('all rows have equal visible width', () => {
+ const lines = renderPortalTable(portals, { color: false }).split('\n');
+ const widths = new Set(lines.map((l) => l.length));
+ assert.strictEqual(widths.size, 1, 'every row must be the same width');
+});
+
+test('renderPortalTable auto-detect: off when not a TTY', () => {
+ const out = renderPortalTable(portals, { color: null, stream: { isTTY: false }, env: {} });
+ assert.ok(!out.includes('\u001b['), 'non-TTY auto-detect must stay plain');
+});
+
+test('empty portal list still renders header + borders', () => {
+ const out = renderPortalTable([], { color: false });
+ assert.ok(out.includes('State'));
+ assert.strictEqual(out.split('\n').length, 4, 'top border + header + separator + bottom border');
+});
+
+// --- render-portal-table.js optional terminal Unicode box mode ---
+
+test('unicode mode emits box-drawing frame with a rule between every row', () => {
+ const out = renderPortalTable(
+ [
+ { name: 'Portal_3', url: 'https://a', portalId: 'id3', state: true },
+ { name: 'Portal_4', url: 'https://b', portalId: 'id4', state: true },
+ { name: 'Portal_1', url: 'https://c', portalId: 'id1', state: false },
+ ],
+ { color: false, icons: true, unicode: true }
+ );
+ const lines = out.split('\n');
+ // Frame corners/tees + vertical bar are Unicode box-drawing, never ASCII '+'/'|'.
+ assert.ok(lines[0].startsWith('┌') && lines[0].endsWith('┐'), 'top border');
+ assert.ok(out.includes('│'), 'cells use the │ vertical bar');
+ assert.ok(!out.includes('+') && !out.includes('|'), 'no ASCII box glyphs');
+ assert.ok(lines[lines.length - 1].startsWith('└') && lines[lines.length - 1].endsWith('┘'), 'bottom border');
+ // 3 rows → top, header, mid, r1, mid, r2, mid, r3, bottom = 9 lines.
+ assert.strictEqual(lines.length, 9, 'a ├┼┤ rule separates every data row');
+ assert.strictEqual(out.match(/├/g).length, 3, 'exactly 3 inter-row/header rules');
+});
+
+test('unicode mode keeps exactly the five columns with state icons', () => {
+ const out = renderPortalTable([{ name: 'P', url: 'u', portalId: 'i', state: true }], {
+ color: false,
+ icons: true,
+ unicode: true,
+ });
+ const header = out.split('\n')[1];
+ assert.ok(/│ # │ Name .*│ URL .*│ Site ID .*│ State .*│/.test(header), 'five fixed columns');
+ assert.ok(out.includes('🟢 Enabled'), 'State cell carries the icon');
+});
+
+test('unicode option is additive — default ASCII output is unchanged', () => {
+ const ascii = renderPortalTable([{ name: 'P', url: 'u', portalId: 'i', state: true }], { color: false });
+ assert.ok(ascii.includes('+---') && ascii.includes('| # |'), 'default stays ASCII box');
+ assert.ok(!ascii.includes('┌') && !ascii.includes('│'), 'no Unicode glyphs by default');
+});
+
+test('unknown state stays uncolored even with color on', () => {
+ const out = renderPortalTable([{ name: 'X', state: 'weird' }], { color: true });
+ assert.ok(out.includes('Unknown'));
+ assert.ok(!out.includes(GREEN) && !out.includes(RED));
+});
+
+// --- render-portal-table.js Markdown mode (chat-safe) ---
+
+test('renderPortalTableMarkdown emits a GFM table, no box-drawing/ANSI', () => {
+ const out = renderPortalTableMarkdown(portals);
+ // No ASCII box borders and no ANSI escapes — the chat client sizes columns.
+ assert.ok(!out.includes('\u001b['), 'markdown output must contain no ANSI escapes');
+ assert.ok(!/[+\-]{3,}/.test(out.replace(/---/g, '')), 'no ASCII box rule rows');
+ assert.match(out, /^\| # \| Name \| URL \| Site ID \| State \|$/m, 'header row present');
+ assert.match(out, /^\| --- \| --- \| --- \| --- \| --- \|$/m, 'delimiter row present');
+});
+
+test('renderPortalTableMarkdown carries the 🟢/🔴 state icon by default and one row per site', () => {
+ const out = renderPortalTableMarkdown(portals);
+ const lines = out.split('\n');
+ // header + delimiter + 2 data rows = 4 lines, each a single physical line.
+ assert.strictEqual(lines.length, 4, 'exactly one line per header/delimiter/site row');
+ assert.match(out, /^\| 1 \| Portal_1 \| https:\/\/a\.example\.com \| id-1 \| 🟢 Enabled \|$/m);
+ assert.match(out, /^\| 2 \| Portal_2 \| https:\/\/b\.example\.com \| id-2 \| 🔴 Disabled \|$/m);
+});
+
+test('renderPortalTableMarkdown --no-icons drops the emoji', () => {
+ const out = renderPortalTableMarkdown(portals, { icons: false });
+ assert.ok(!out.includes('🟢') && !out.includes('🔴'), 'icons suppressed');
+ assert.match(out, /\| Enabled \|/);
+ assert.match(out, /\| Disabled \|/);
+});
+
+test('renderPortalTableMarkdown escapes a literal pipe in a cell', () => {
+ const out = renderPortalTableMarkdown([{ name: 'A|B', url: 'https://x', portalId: 'p1', state: true }]);
+ assert.match(out, /\| A\\\|B \|/, 'a literal pipe is backslash-escaped');
+});
+
+test('Markdown rows flatten line separators without losing cells or long IDs', () => {
+ const out = renderPortalTableMarkdown([{
+ name: 'A|B\rC\nD\r\nE\u2028F\u2029G',
+ url: `https://${'long-site-'.repeat(8)}.example.com`,
+ portalId: '11111111-2222-3333-4444-555555555555',
+ state: false,
+ }]);
+ const lines = out.split('\n');
+ assert.equal(lines.length, 3);
+ assert.match(lines[2], /\| A\\\|B C D E F G \|/);
+ assert.ok(lines[2].includes('11111111-2222-3333-4444-555555555555'));
+ assert.ok(lines[2].endsWith('| 🔴 Disabled |'));
+});
+
+test('Markdown CLI preserves every status row without fences, boxes, or forced ANSI', () => {
+ const input = Array.from({ length: 13 }, (_, index) => ({
+ name: `Test site ${index + 1}`,
+ url: `https://site-${index + 1}.example.com`,
+ portalId: `site-id-${index + 1}`,
+ state: index % 2 === 0,
+ }));
+ const result = spawnSync(process.execPath, [
+ path.join(scriptsDir, 'render-portal-table.js'), '--markdown', '--no-color',
+ ], {
+ input: JSON.stringify({ portals: input }),
+ encoding: 'utf8',
+ env: { ...process.env, FORCE_COLOR: '1' },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout.trimEnd(), renderPortalTableMarkdown(input));
+ assert.equal(result.stdout.trimEnd().split('\n').length, 15);
+ assert.ok(!/[\u001b┌│]|```/.test(result.stdout));
+});
diff --git a/plugins/power-pages/scripts/tests/governance/resolve-portal-availability.test.js b/plugins/power-pages/scripts/tests/governance/resolve-portal-availability.test.js
new file mode 100644
index 000000000..66dbc05cd
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/resolve-portal-availability.test.js
@@ -0,0 +1,580 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const { createRequire } = require('node:module');
+
+const {
+ dependenciesForPolicy,
+ canonicalizeEnvValue,
+ computeSiteState,
+ extractLists,
+ parsePortalsJson,
+ resolvePortalStates,
+ computeAvailability,
+ renderAvailabilityMarkdown,
+ renderAvailablePortalsMarkdown,
+} = require('../../../skills/manage-governance/scripts/resolve-portal-availability');
+const mapping = require('../../../skills/manage-governance/references/governance-mapping.json');
+
+test('parsePortalsJson accepts list-portals envelopes and bare arrays', () => {
+ assert.deepEqual(parsePortalsJson('{"portals":[{"portalId":"p1"}]}'), [{ portalId: 'p1' }]);
+ assert.deepEqual(parsePortalsJson('[{"portalId":"p2"}]'), [{ portalId: 'p2' }]);
+});
+
+test('availability CLI reads portal JSON from stdin without a temporary file', () => {
+ const script = path.resolve(
+ __dirname,
+ '../../../skills/manage-governance/scripts/resolve-portal-availability.js'
+ );
+ const result = spawnSync(
+ process.execPath,
+ [script, '--policy', 'EnableAuthenticationLocalLogin'],
+ {
+ input: JSON.stringify({ portals: [{ portalId: 'p1', name: 'Site 1' }] }),
+ encoding: 'utf8',
+ }
+ );
+ assert.equal(result.status, 0, result.stderr);
+ const output = JSON.parse(result.stdout);
+ assert.deepEqual(output.available.map((portal) => portal.portalId), ['p1']);
+});
+
+// --- Mapping data invariants: the parent/child tree is the requirement ------
+
+test('mapping declares the External-Auth -> protocols -> OAuth -> social-IdP tree', () => {
+ const deps = mapping.policyAvailabilityDependencies;
+ assert.ok(deps, 'policyAvailabilityDependencies block must exist');
+ assert.deepEqual(deps.parents.EnableExternalAuthProviders, [
+ 'EnableProtocolOpenIdConnect',
+ 'EnableProtocolSAML20',
+ 'EnableProtocolWsFederation',
+ 'EnableProtocolOpenAuth',
+ ]);
+ assert.deepEqual(deps.parents.EnableProtocolOpenAuth, [
+ 'EnableIdpOAuthFacebook',
+ 'EnableIdpOAuthGoogle',
+ 'EnableIdpOAuthMicrosoft',
+ ]);
+});
+
+test('each protocol child depends on External Auth only', () => {
+ for (const child of [
+ 'EnableProtocolOpenIdConnect',
+ 'EnableProtocolSAML20',
+ 'EnableProtocolWsFederation',
+ 'EnableProtocolOpenAuth',
+ ]) {
+ assert.deepEqual(dependenciesForPolicy(child, mapping), ['EnableExternalAuthProviders'], child);
+ }
+});
+
+test('each social IdP depends on both External Auth and OAuth 2.0', () => {
+ for (const child of ['EnableIdpOAuthFacebook', 'EnableIdpOAuthGoogle', 'EnableIdpOAuthMicrosoft']) {
+ assert.deepEqual(
+ dependenciesForPolicy(child, mapping),
+ ['EnableExternalAuthProviders', 'EnableProtocolOpenAuth'],
+ child
+ );
+ }
+});
+
+test('leaf / independent policies have no availability dependencies', () => {
+ assert.deepEqual(dependenciesForPolicy('EnableMakerCopilotForExistingSites', mapping), []);
+ assert.deepEqual(dependenciesForPolicy('EnableAuthenticationLocalLogin', mapping), []);
+ assert.deepEqual(dependenciesForPolicy('EnableExternalAuthProviders', mapping), []);
+});
+
+test('the parent/child overview matches every per-policy availabilityDependsOn field', () => {
+ // The top-level block is only an overview — assert it stays consistent with
+ // the authoritative per-policy fields so the two can't silently drift.
+ const parents = mapping.policyAvailabilityDependencies.parents;
+ for (const [parent, children] of Object.entries(parents)) {
+ for (const child of children) {
+ assert.ok(
+ dependenciesForPolicy(child, mapping).includes(parent),
+ `${child}.availabilityDependsOn must include ${parent}`
+ );
+ }
+ }
+});
+
+// --- canonicalizeEnvValue ---------------------------------------------------
+
+test('canonicalizeEnvValue folds *Sites and casing to canonical, else Unknown', () => {
+ assert.equal(canonicalizeEnvValue('All'), 'All');
+ assert.equal(canonicalizeEnvValue('allsites'), 'All');
+ assert.equal(canonicalizeEnvValue('None'), 'None');
+ assert.equal(canonicalizeEnvValue('IncludeSites'), 'Include');
+ assert.equal(canonicalizeEnvValue('IncludedSites'), 'Include');
+ assert.equal(canonicalizeEnvValue('ExcludeSites'), 'Exclude');
+ assert.equal(canonicalizeEnvValue('AllSitesExceptExcluded'), 'Exclude');
+ assert.equal(canonicalizeEnvValue(''), 'Unknown');
+ assert.equal(canonicalizeEnvValue(null), 'Unknown');
+ assert.equal(canonicalizeEnvValue('garbage'), 'Unknown');
+});
+
+// --- computeSiteState (siteStateRules contract) -----------------------------
+
+test('computeSiteState follows the siteStateRules table', () => {
+ assert.equal(computeSiteState('All', {}), 'Enabled');
+ assert.equal(computeSiteState('None', {}), 'Disabled');
+ assert.equal(computeSiteState('Include', { inInclusion: true }), 'Enabled');
+ assert.equal(computeSiteState('Include', { inInclusion: false }), 'Disabled');
+ assert.equal(computeSiteState('Exclude', { inExclusion: true }), 'Disabled');
+ assert.equal(computeSiteState('Exclude', { inExclusion: false }), 'Enabled');
+ assert.equal(computeSiteState('Unknown', {}), 'Unknown');
+});
+
+// --- extractLists tolerance -------------------------------------------------
+
+test('extractLists reads several field spellings and id shapes, lowercased', () => {
+ const a = extractLists({ InclusionList: ['AAA', { id: 'BBB' }], ExclusionList: [{ portalId: 'CcC' }] });
+ assert.deepEqual([...a.inclusion].sort(), ['aaa', 'bbb']);
+ assert.deepEqual([...a.exclusion], ['ccc']);
+
+ const b = extractLists({ details: { IncludedSites: ['X1'], ExcludedSites: [{ websiteId: 'Y2' }] } });
+ assert.deepEqual([...b.inclusion], ['x1']);
+ assert.deepEqual([...b.exclusion], ['y2']);
+
+ const empty = extractLists(null);
+ assert.equal(empty.inclusion.size, 0);
+ assert.equal(empty.exclusion.size, 0);
+});
+
+// --- computeAvailability core scenarios -------------------------------------
+
+const PORTALS = [
+ { portalId: 'AAA', name: 'Site 1', websiteUrl: 'https://a' },
+ { portalId: 'bbb', name: 'Site 2', websiteUrl: 'https://b' },
+ { portalId: 'ccc', name: 'Site 3', websiteUrl: 'https://c' },
+];
+
+function parentReadHarness(responses) {
+ const filename = require.resolve('../../../skills/manage-governance/scripts/resolve-portal-availability');
+ const realRequire = createRequire(filename);
+ const calls = [];
+ const queue = [...responses];
+ const sandbox = {
+ module: { exports: {} },
+ __dirname: path.dirname(filename),
+ require(name) {
+ if (name === './governance-transport') {
+ return {
+ async callGovernance(args) {
+ calls.push(args);
+ assert.ok(queue.length, `Unexpected parent read: ${args.op}`);
+ return queue.shift();
+ },
+ };
+ }
+ return realRequire(name);
+ },
+ };
+ vm.runInNewContext(fs.readFileSync(filename, 'utf8'), sandbox, { filename });
+ return { resolver: sandbox.module.exports, calls };
+}
+
+for (const envValue of ['Include', 'Exclude']) {
+ for (const statusCode of [0, 404, 429, 503]) {
+ test(`${envValue} parent membership failure ${statusCode} is disclosed, not interpreted as an empty list`, async () => {
+ const h = parentReadHarness([
+ { ok: true, body: envValue },
+ { ok: false, statusCode, error: { message: 'Membership unavailable' } },
+ ]);
+ const parent = 'EnableExternalAuthProviders';
+ const states = await h.resolver.readParentStates([parent], 'test-env');
+ assert.equal(states[parent].envValue, envValue);
+ assert.equal(states[parent].membershipReadError.statusCode, statusCode);
+ assert.equal(states[parent].membershipReadError.message, 'Membership unavailable');
+ const part = h.resolver.computeAvailability({
+ targetPolicy: 'EnableProtocolOpenIdConnect', portals: PORTALS, parentStates: states,
+ });
+ assert.equal(part.available.length, 3);
+ assert.equal(part.unavailable.length, 0);
+ assert.equal(part.remediationChain.length, 0);
+ assert.equal(part.membershipReadErrors[parent].statusCode, statusCode);
+ for (const portal of part.available) assert.deepEqual([...portal.unreadParents], [parent]);
+ for (const render of [h.resolver.renderAvailabilityMarkdown, h.resolver.renderAvailablePortalsMarkdown]) {
+ const markdown = render(part);
+ assert.match(markdown, /^\*\*Warning:\*\*.*EnableExternalAuthProviders.*Eligibility is unverified/);
+ assert.match(markdown, /Site 1/);
+ }
+ assert.match(h.resolver.renderAvailabilityMarkdown(part), /Yes \(unverified\)/);
+ assert.deepEqual(h.calls.map((call) => call.op), ['getEnv', 'getDetails']);
+ });
+ }
+
+ test(`successful empty ${envValue} membership retains its known semantics without a warning`, async () => {
+ const h = parentReadHarness([{ ok: true, body: envValue }, { ok: true, body: {} }]);
+ const states = await h.resolver.readParentStates(['EnableExternalAuthProviders']);
+ const part = h.resolver.computeAvailability({
+ targetPolicy: 'EnableProtocolOpenIdConnect', portals: PORTALS, parentStates: states,
+ });
+ assert.equal(part.available.length, envValue === 'Include' ? 0 : 3);
+ assert.equal(states.EnableExternalAuthProviders.membershipReadError, undefined);
+ assert.equal(part.membershipReadErrors, undefined);
+ assert.doesNotMatch(h.resolver.renderAvailabilityMarkdown(part), /Warning|unverified/);
+ });
+}
+
+test('parent membership authentication failures stop rather than failing open', async () => {
+ for (const failure of [
+ { ok: false, statusCode: 401, error: { message: 'Unauthorized' } },
+ { ok: false, statusCode: 403, error: { message: 'Forbidden' } },
+ { ok: false, statusCode: 0, error: { code: 'ContextError', message: 'Sign-in required' } },
+ ]) {
+ const h = parentReadHarness([{ ok: true, body: 'Exclude' }, failure]);
+ await assert.rejects(
+ h.resolver.readParentStates(['EnableExternalAuthProviders']),
+ (error) => error.exitCode === 2 && /site membership failed/.test(error.message),
+ );
+ }
+});
+
+test('known blocking parents remain blocking while a different membership is unread', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableIdpOAuthGoogle',
+ portals: PORTALS,
+ parentStates: {
+ EnableExternalAuthProviders: { envValue: 'None' },
+ EnableProtocolOpenAuth: {
+ envValue: 'Exclude', membershipReadError: { statusCode: 503, message: 'Unavailable' },
+ },
+ },
+ });
+ assert.equal(part.available.length, 0);
+ for (const portal of part.unavailable) {
+ assert.deepEqual(portal.blockingParents, ['EnableExternalAuthProviders']);
+ assert.deepEqual(portal.unreadParents, ['EnableProtocolOpenAuth']);
+ }
+ assert.deepEqual(part.remediationChain.map((parent) => parent.policyName), ['EnableExternalAuthProviders']);
+ assert.match(renderAvailabilityMarkdown(part), /^\*\*Warning:\*\*/);
+ assert.match(renderAvailablePortalsMarkdown(part), /^\*\*Warning:\*\*/);
+});
+
+test('External Auth disabled env-wide makes every portal unavailable for a protocol child', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableProtocolOpenIdConnect',
+ portals: PORTALS,
+ parentStates: { EnableExternalAuthProviders: { envValue: 'None' } },
+ });
+ assert.equal(part.available.length, 0);
+ assert.equal(part.unavailable.length, 3);
+ for (const p of part.unavailable) {
+ assert.deepEqual(p.blockingParents, ['EnableExternalAuthProviders']);
+ assert.deepEqual(p.blockedBy, ['External authentication providers']);
+ }
+});
+
+test('External Auth Include partitions available vs unavailable by inclusion list', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableProtocolSAML20',
+ portals: PORTALS,
+ parentStates: { EnableExternalAuthProviders: { envValue: 'Include', inclusion: ['aaa'] } },
+ });
+ assert.deepEqual(part.available.map((p) => p.name), ['Site 1']);
+ assert.deepEqual(part.unavailable.map((p) => p.name), ['Site 2', 'Site 3']);
+});
+
+test('social IdP is unavailable when EITHER External Auth OR OAuth is disabled for the portal', () => {
+ // External Auth: All. OAuth: Exclude Site 2 -> Site 2 gets OAuth Disabled.
+ const part = computeAvailability({
+ targetPolicy: 'EnableIdpOAuthGoogle',
+ portals: PORTALS,
+ parentStates: {
+ EnableExternalAuthProviders: { envValue: 'All' },
+ EnableProtocolOpenAuth: { envValue: 'Exclude', exclusion: ['bbb'] },
+ },
+ });
+ assert.deepEqual(part.available.map((p) => p.name), ['Site 1', 'Site 3']);
+ assert.deepEqual(part.unavailable.map((p) => p.name), ['Site 2']);
+ assert.deepEqual(part.unavailable[0].blockingParents, ['EnableProtocolOpenAuth']);
+ assert.deepEqual(part.unavailable[0].blockedBy, ['OAuth 2.0 sign-in']);
+});
+
+test('a social IdP portal blocked by BOTH parents lists both in blockedBy', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableIdpOAuthMicrosoft',
+ portals: [{ portalId: 'zzz', name: 'Blocked Site', websiteUrl: 'https://z' }],
+ parentStates: {
+ EnableExternalAuthProviders: { envValue: 'None' },
+ EnableProtocolOpenAuth: { envValue: 'None' },
+ },
+ });
+ assert.equal(part.available.length, 0);
+ assert.deepEqual(part.unavailable[0].blockingParents, [
+ 'EnableExternalAuthProviders',
+ 'EnableProtocolOpenAuth',
+ ]);
+ assert.deepEqual(part.unavailable[0].blockedBy, [
+ 'External authentication providers',
+ 'OAuth 2.0 sign-in',
+ ]);
+});
+
+test('leaf policy: every portal is available, no parent reads needed', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableAuthenticationLocalLogin',
+ portals: PORTALS,
+ parentStates: {},
+ });
+ assert.deepEqual(part.dependencies, []);
+ assert.equal(part.available.length, 3);
+ assert.equal(part.unavailable.length, 0);
+});
+
+test('unknown/unread parent state is fail-open (portal stays available, parent recorded)', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableProtocolWsFederation',
+ portals: [{ portalId: 'AAA', name: 'Site 1', websiteUrl: 'https://a' }],
+ parentStates: {}, // parent entirely absent -> Unknown
+ });
+ assert.equal(part.available.length, 1, 'a transient read miss must not hide the portal');
+ assert.equal(part.unavailable.length, 0);
+ assert.deepEqual(part.available[0].unreadParents, ['EnableExternalAuthProviders']);
+});
+
+test('parentStates accepts inclusion/exclusion as Set or array, case-insensitively', () => {
+ const withSet = computeAvailability({
+ targetPolicy: 'EnableProtocolOpenIdConnect',
+ portals: PORTALS,
+ parentStates: { EnableExternalAuthProviders: { envValue: 'Include', inclusion: new Set(['AAA']) } },
+ });
+ assert.deepEqual(withSet.available.map((p) => p.name), ['Site 1']);
+});
+
+// --- renderAvailabilityMarkdown (eligibility table: all portals, Yes/No) -----
+
+test('renderAvailabilityMarkdown lists eligible first then ineligible below, with an Eligible column + reason', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableIdpOAuthGoogle',
+ portals: PORTALS,
+ parentStates: {
+ EnableExternalAuthProviders: { envValue: 'Include', inclusion: ['aaa'] },
+ EnableProtocolOpenAuth: { envValue: 'All' },
+ },
+ });
+ const md = renderAvailabilityMarkdown(part);
+ const lines = md.split('\n');
+ assert.match(lines[0], /^\| # \| Portal Name \| Portal URL \| Portal ID \| Eligible \|$/);
+ assert.match(lines[1], /^\| --- \| --- \| --- \| --- \| --- \|$/);
+ // Row 1 is the eligible site; the two ineligible ones come strictly after.
+ assert.match(md, /^\| 1 \| Site 1 \| https:\/\/a \| AAA \| ✅ Yes \|$/m);
+ assert.match(
+ md,
+ /^\| 2 \| Site 2 \| https:\/\/b \| bbb \| 🚫 No — blocked by External authentication providers \(Disabled\) \|$/m
+ );
+ const availIdx = md.indexOf('Site 1');
+ const unavailIdx = md.indexOf('Site 2');
+ assert.ok(availIdx < unavailIdx, 'eligible rows must render above ineligible rows');
+});
+
+test('renderAvailabilityMarkdown escapes pipes and can omit icons', () => {
+ const part = {
+ available: [{ portalId: 'p1', name: 'A|B', websiteUrl: 'https://x' }],
+ unavailable: [],
+ };
+ const md = renderAvailabilityMarkdown(part, { icons: false });
+ assert.match(md, /\| A\\\|B \|/);
+ assert.match(md, /\| Yes \|/);
+ assert.ok(!/✅/.test(md), 'icons:false suppresses the emoji marker');
+});
+
+test('renderAvailabilityMarkdown shows the parent-disabled message (no all-No table) when NO portal is eligible', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableProtocolOpenIdConnect',
+ portals: PORTALS,
+ parentStates: {
+ EnableExternalAuthProviders: { envValue: 'None' },
+ },
+ });
+ const md = renderAvailabilityMarkdown(part);
+ // Empty-state: single message, NOT a Markdown table of ineligible rows.
+ assert.ok(!/\| Eligible \|/.test(md), 'no eligibility table when nothing is eligible');
+ assert.match(md, /off for this environment/i);
+});
+
+// --- renderAvailablePortalsMarkdown (scope picker: available only) -----------
+
+test('renderAvailablePortalsMarkdown lists ONLY the available portals (no unavailable rows)', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableProtocolOpenAuth',
+ portals: PORTALS,
+ parentStates: { EnableExternalAuthProviders: { envValue: 'Include', inclusion: ['aaa'] } },
+ });
+ const md = renderAvailablePortalsMarkdown(part);
+ // Header has NO Availability column — only the actionable set is shown.
+ assert.match(md.split('\n')[0], /^\| # \| Portal Name \| Portal URL \| Portal ID \|$/);
+ assert.match(md, /Site 1/);
+ assert.doesNotMatch(md, /Site 2/); // the unavailable sites are omitted
+ assert.doesNotMatch(md, /Site 3/);
+});
+
+test('renderAvailablePortalsMarkdown shows the parent-disabled message when NO site is available', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableProtocolSAML20',
+ portals: PORTALS,
+ parentStates: { EnableExternalAuthProviders: { envValue: 'None' } },
+ });
+ const md = renderAvailablePortalsMarkdown(part);
+ assert.match(md, /The External authentication providers Governance setting is off for this environment/);
+ assert.match(md, /No sites are available to configure/);
+ // It is a message, NOT a table.
+ assert.doesNotMatch(md, /\| # \| Portal Name/);
+});
+
+test('renderAvailablePortalsMarkdown adds an info line when only a subset is available', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableProtocolWsFederation',
+ portals: PORTALS,
+ parentStates: { EnableExternalAuthProviders: { envValue: 'Include', inclusion: ['aaa'] } },
+ });
+ const md = renderAvailablePortalsMarkdown(part);
+ assert.match(md, /Showing 1 of 3 site\(s\)/);
+ assert.match(md, /2 site\(s\) are hidden because the External authentication providers Governance setting is off/);
+ // The consequence for the child is spelled out in Governance-setting terms.
+ assert.match(md, /the WS-Federation sign-in Governance setting can't apply there/);
+});
+
+test('renderAvailablePortalsMarkdown names BOTH blocking parents for a social IdP when both disabled', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableIdpOAuthGoogle',
+ portals: [{ portalId: 'zzz', name: 'Blocked', websiteUrl: 'https://z' }],
+ parentStates: {
+ EnableExternalAuthProviders: { envValue: 'None' },
+ EnableProtocolOpenAuth: { envValue: 'None' },
+ },
+ });
+ const md = renderAvailablePortalsMarkdown(part);
+ assert.match(md, /The External authentication providers or OAuth 2\.0 sign-in Governance setting is off for this environment/);
+ // Enabling a social IdP needs BOTH parents on, so the enable instruction uses "both … and …".
+ assert.match(md, /turn on both the External authentication providers and OAuth 2\.0 sign-in Governance settings first/);
+});
+
+test('renderAvailablePortalsMarkdown (social IdP subset) requires BOTH parents enabled and phrases them with and/or', () => {
+ // Google depends on External Auth AND OAuth 2.0. A site is eligible only when
+ // BOTH are enabled; blocked when EITHER is off.
+ // External Auth Include [AAA, bbb] -> Site1, Site2 on; Site3 off
+ // OAuth 2.0 Include [AAA, ccc] -> Site1, Site3 on; Site2 off
+ // Intersection = only Site1 (AAA); Site2 blocked by OAuth 2.0, Site3 by External Auth.
+ const part = computeAvailability({
+ targetPolicy: 'EnableIdpOAuthGoogle',
+ portals: PORTALS,
+ parentStates: {
+ EnableExternalAuthProviders: { envValue: 'Include', inclusion: ['AAA', 'bbb'] },
+ EnableProtocolOpenAuth: { envValue: 'Include', inclusion: ['AAA', 'ccc'] },
+ },
+ });
+ const md = renderAvailablePortalsMarkdown(part);
+ assert.match(md, /Site 1/);
+ assert.doesNotMatch(md, /Site 2/);
+ assert.doesNotMatch(md, /Site 3/);
+ assert.match(md, /Showing 1 of 3 site\(s\)/);
+ // "only … where both … Governance settings are on" (AND — every parent must be on).
+ assert.match(md, /only be configured on sites where both .* Governance settings are on/);
+ // "hidden because … or … Governance setting is off on them" (OR — either parent off blocks).
+ assert.match(md, /hidden because .* Governance setting is off on them/);
+ // Both parent subjects are named regardless of order.
+ assert.match(md, /External authentication providers/);
+ assert.match(md, /OAuth 2\.0 sign-in/);
+});
+
+test('renderAvailablePortalsMarkdown shows a clean table (no info line) when ALL sites are available', () => {
+ const part = computeAvailability({
+ targetPolicy: 'EnableProtocolOpenIdConnect',
+ portals: PORTALS,
+ parentStates: { EnableExternalAuthProviders: { envValue: 'All' } },
+ });
+ const md = renderAvailablePortalsMarkdown(part);
+ assert.match(md, /Site 1/);
+ assert.match(md, /Site 2/);
+ assert.match(md, /Site 3/);
+ assert.doesNotMatch(md, /hidden because/);
+});
+
+// --- resolvePortalStates: batch per-portal state from ONE env + details read -
+// This is the getDetails fast path — it must reproduce, locally and with zero
+// per-portal network calls, exactly what a per-portal get-portal.js loop would
+// return. See SKILL.md Phase 4.3.1 / 4.4.4 / 4.2.3 / 4.2.5.
+
+test('resolvePortalStates: Include -> only listed sites Enabled (rest Disabled)', () => {
+ // Keep the API response shape with synthetic site IDs.
+ const details = {
+ IncludedSites: [
+ 'site-3',
+ 'site-4',
+ ],
+ ExcludedSites: null,
+ };
+ const portals = [
+ 'site-3', // listed -> Enabled
+ 'site-1', // not listed -> Disabled
+ ];
+ const states = resolvePortalStates('Include', details, portals);
+ assert.deepEqual(states, [
+ { portalId: 'site-3', state: 'Enabled' },
+ { portalId: 'site-1', state: 'Disabled' },
+ ]);
+});
+
+test('resolvePortalStates: Exclude -> listed sites Disabled, rest Enabled', () => {
+ const details = { ExcludedSites: ['AAA'] };
+ const states = resolvePortalStates('Exclude', details, ['aaa', 'bbb']);
+ // Membership test is case-insensitive: 'AAA' in the list matches portal 'aaa'.
+ assert.deepEqual(states, [
+ { portalId: 'aaa', state: 'Disabled' },
+ { portalId: 'bbb', state: 'Enabled' },
+ ]);
+});
+
+test('resolvePortalStates: All / None ignore the lists entirely', () => {
+ const all = resolvePortalStates('All', { IncludedSites: [] }, ['x', 'y']);
+ assert.deepEqual(all.map((s) => s.state), ['Enabled', 'Enabled']);
+ const none = resolvePortalStates('None', { IncludedSites: ['x'] }, ['x', 'y']);
+ assert.deepEqual(none.map((s) => s.state), ['Disabled', 'Disabled']);
+});
+
+test('resolvePortalStates: accepts portal OBJECTS and passes name/url through', () => {
+ const details = { IncludedSites: ['p1'] };
+ const portals = [
+ { portalId: 'p1', name: 'Portal_1', websiteUrl: 'https://p1.example' },
+ { portalId: 'p2', name: 'Portal_2', url: 'https://p2.example' },
+ ];
+ const states = resolvePortalStates('Include', details, portals);
+ assert.deepEqual(states, [
+ { portalId: 'p1', state: 'Enabled', name: 'Portal_1', url: 'https://p1.example' },
+ { portalId: 'p2', state: 'Disabled', name: 'Portal_2', url: 'https://p2.example' },
+ ]);
+});
+
+test('resolvePortalStates: unknown env value -> Unknown (fail visible, never guess)', () => {
+ const states = resolvePortalStates('Bogus', { IncludedSites: ['p1'] }, ['p1']);
+ assert.deepEqual(states, [{ portalId: 'p1', state: 'Unknown' }]);
+});
+
+test('resolvePortalStates: reproduces a five-site OIDC Include read with synthetic IDs', () => {
+ // Regression guard for the exact case that motivated this path: env=Include,
+ // details.IncludedSites=[Portal_3,4,5]. A per-portal get-portal loop returned
+ // Enabled for 3/4/5 and Disabled for 1/2 — this must match without any
+ // per-portal call.
+ const details = {
+ IncludedSites: [
+ 'site-3',
+ 'site-4',
+ 'site-5',
+ ],
+ ExcludedSites: null,
+ };
+ const portals = [
+ 'site-1',
+ 'site-2',
+ 'site-3',
+ 'site-4',
+ 'site-5',
+ ];
+ const states = resolvePortalStates('Include', details, portals).map((s) => s.state);
+ assert.deepEqual(states, ['Disabled', 'Disabled', 'Enabled', 'Enabled', 'Enabled']);
+});
diff --git a/plugins/power-pages/scripts/tests/governance/set-governance-auth.test.js b/plugins/power-pages/scripts/tests/governance/set-governance-auth.test.js
new file mode 100644
index 000000000..4d75c341d
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/set-governance-auth.test.js
@@ -0,0 +1,224 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const { createRequire } = require('node:module');
+
+const modulePath = require.resolve('../../../skills/manage-governance/scripts/set-governance');
+const apiPath = require.resolve('../../lib/power-platform-api');
+const realRequire = createRequire(modulePath);
+const envId = 'test-environment';
+const ok = (body = 'Succeeded') => ({ ok: true, statusCode: 200, body, transport: 'gateway' });
+const networkError = () => ({
+ ok: false, statusCode: 0, body: null, error: { code: 'NetworkError', message: 'connection lost' },
+});
+
+class CliExit extends Error {
+ constructor(code) {
+ super(`CLI exited ${code}`);
+ this.code = code;
+ }
+}
+
+// Exercise the real CLI main and shared pollUntil with virtual time. All
+// context/network dependencies are replaced; no operator credentials, login
+// subprocesses, or live governance endpoints are accessed.
+function harness(responses, context = { environmentId: envId, token: 'test-only' }, extraArgs = []) {
+ let now = 0;
+ let main;
+ let stdout = '';
+ let stderr = '';
+ const calls = [];
+ const resolutions = [];
+ const waits = [];
+ const queue = [...responses];
+ const processStub = {
+ argv: ['node', modulePath, '--policy', 'EnableProtocolOpenIdConnect', '--envId', envId, ...extraArgs],
+ stdout: { write: (text) => { stdout += text; } },
+ stderr: { write: (text) => { stderr += text; } },
+ exit(code) { throw new CliExit(code); },
+ };
+ const apiSandbox = {
+ module: { exports: {} },
+ require(name) {
+ if (name === 'child_process' || name === './validation-helpers') return {};
+ throw new Error(`Unexpected API dependency: ${name}`);
+ },
+ process: processStub,
+ Date: class extends Date { static now() { return now; } },
+ setTimeout(callback, ms) {
+ waits.push(ms);
+ now += ms;
+ queueMicrotask(callback);
+ },
+ };
+ vm.runInNewContext(fs.readFileSync(apiPath, 'utf8'), apiSandbox, { filename: apiPath });
+ const sandbox = {
+ module: { exports: {} },
+ process: processStub,
+ require(name) {
+ if (name === '../../../scripts/lib/power-platform-api') {
+ return { ...apiSandbox.module.exports, runCli: (mod, callback) => { main = callback; } };
+ }
+ if (name === './governance-context') {
+ return { resolveGovernanceContext: (id) => { resolutions.push(id); return context; } };
+ }
+ if (name === './governance-transport') {
+ return {
+ async callGovernance(args) {
+ assert.strictEqual(args.context, context, 'every call must reuse the resolved context');
+ calls.push(args);
+ assert.ok(queue.length, `Unexpected call: ${args.op}`);
+ return queue.shift();
+ },
+ };
+ }
+ if (name === './policies') return realRequire(name);
+ throw new Error(`Unexpected Apply dependency: ${name}`);
+ },
+ };
+ vm.runInNewContext(fs.readFileSync(modulePath, 'utf8'), sandbox, { filename: modulePath });
+ return {
+ calls, resolutions, waits,
+ async run() {
+ let code = 0;
+ try {
+ await main();
+ } catch (error) {
+ if (!(error instanceof CliExit)) throw error;
+ code = error.code;
+ }
+ return { code, stdout, stderr };
+ },
+ };
+}
+
+test('Apply resolves context once and retains fixed 30-second polling after transient failures', async () => {
+ const h = harness([ok(), ok('InProgress'), networkError(), ok()]);
+ const result = await h.run();
+ assert.equal(result.code, 0);
+ assert.deepEqual(h.resolutions, [envId]);
+ assert.deepEqual(h.calls.map((call) => call.op), ['apply', 'getStatus', 'getStatus', 'getStatus']);
+ assert.deepEqual(h.waits, [30_000, 30_000]);
+ assert.equal(JSON.parse(result.stdout).status, 'applied');
+ assert.equal(JSON.parse(result.stdout).attempts, 3);
+});
+
+test('Apply also reuses its context for existing uncertain-response recovery', async () => {
+ const h = harness([networkError(), ok('All'), ok()]);
+ assert.equal((await h.run()).code, 0);
+ assert.deepEqual(h.resolutions, [envId]);
+ assert.deepEqual(h.calls.map((call) => call.op), ['apply', 'getEnv', 'getStatus']);
+});
+
+for (const scope of ['Include', 'Exclude']) {
+ test(`CLI forwards comma/space-separated removals for a removal-only ${scope} edit`, async () => {
+ const h = harness([ok(), ok()], undefined, [
+ '--policyValue', scope, '--removePortalIds', 'site-a, site-b site-c',
+ ]);
+ const result = await h.run();
+ assert.equal(result.code, 0);
+ assert.deepEqual(h.calls.map((call) => call.op), ['apply', 'getStatus']);
+ const payload = JSON.parse(JSON.stringify(h.calls[0].body));
+ assert.deepEqual(payload, [{
+ policyName: 'EnableProtocolOpenIdConnect',
+ policyValue: scope,
+ ToBeAdded: [],
+ ToBeRemoved: ['site-a', 'site-b', 'site-c'],
+ }]);
+ });
+}
+
+for (const statusCode of [400, 409, 429, 500, 503]) {
+ for (const scope of ['Include', 'Exclude']) {
+ test(`HTTP ${statusCode} rejects a ${scope} membership edit without matching-scope recovery`, async () => {
+ const rejection = {
+ ok: false,
+ statusCode,
+ error: { code: 'Rejected', message: 'governance update rejected' },
+ };
+ // If reached, these reads could falsely confirm a rejected edit using
+ // the existing scope and a previous rollout's success.
+ const h = harness([rejection, ok(scope), ok()], undefined, [
+ '--policyValue', scope, '--portalIds', 'site-b', '--removePortalIds', 'site-a',
+ ]);
+ const result = await h.run();
+ assert.equal(result.code, 1);
+ assert.equal(result.stdout, '');
+ assert.ok(result.stderr.includes(`HTTP ${statusCode}`));
+ assert.match(result.stderr, /governance update rejected/);
+ assert.deepEqual(h.calls.map((call) => call.op), ['apply']);
+ assert.deepEqual(h.waits, []);
+ assert.deepEqual(h.resolutions, [envId]);
+ const payload = h.calls[0].body[0];
+ assert.equal(payload.policyValue, scope);
+ assert.equal(payload.ToBeAdded.join(','), 'site-b');
+ assert.equal(payload.ToBeRemoved.join(','), 'site-a');
+ });
+ }
+}
+
+test('initial context failure exits before any request', async () => {
+ const h = harness([], { error: 'Run: pac auth create' });
+ const result = await h.run();
+ assert.equal(result.code, 2);
+ assert.match(result.stderr, /Failed to resolve governance context.*pac auth create/);
+ assert.equal(result.stdout, '');
+ assert.deepEqual(h.calls, []);
+ assert.deepEqual(h.waits, []);
+ assert.deepEqual(h.resolutions, [envId]);
+});
+
+const authFailures = [
+ {
+ name: '401', code: 2, guidance: /sign in again/,
+ response: { ok: false, statusCode: 401, error: { code: 'Unauthorized', message: 'expired token' } },
+ },
+ {
+ name: '403', code: 1, guidance: /admin role, delegated permissions, and access policies/,
+ response: { ok: false, statusCode: 403, error: { code: 'Forbidden', message: 'missing permission' } },
+ },
+ {
+ name: 'context error', code: 2, guidance: /sign-in required/,
+ response: { ok: false, statusCode: 0, error: { code: 'ContextError', message: 'sign-in required' } },
+ },
+];
+
+const stages = [
+ { name: 'POST', before: [], operations: ['apply'], waits: [] },
+ { name: 'recovery read', before: [networkError()], operations: ['apply', 'getEnv'], waits: [] },
+ { name: 'first status poll', before: [ok()], operations: ['apply', 'getStatus'], waits: [] },
+ {
+ name: 'status poll after healthy polling', before: [ok(), ok('InProgress')],
+ operations: ['apply', 'getStatus', 'getStatus'], waits: [30_000],
+ },
+ {
+ name: 'final check after transient-error exhaustion',
+ before: [ok(), ...Array.from({ length: 5 }, networkError)],
+ operations: ['apply', ...Array(6).fill('getStatus')], waits: Array(4).fill(30_000),
+ },
+ {
+ name: 'final check after timeout', before: [ok(), ok('InProgress')],
+ operations: ['apply', 'getStatus', 'getStatus'], waits: [30_000],
+ extraArgs: ['--timeoutMinutes', '0.5'],
+ },
+];
+
+for (const failure of authFailures) {
+ for (const stage of stages) {
+ test(`${failure.name} at ${stage.name} exits immediately without recovery or stale success`, async () => {
+ const h = harness([...stage.before, failure.response, ok()], undefined, stage.extraArgs);
+ const result = await h.run();
+ assert.equal(result.code, failure.code);
+ assert.equal(result.stdout, '', 'failure must not emit an applied result');
+ assert.match(result.stderr, failure.guidance);
+ assert.ok(result.stderr.includes(failure.response.error.message), 'retain upstream error detail');
+ assert.deepEqual(h.calls.map((call) => call.op), stage.operations);
+ assert.deepEqual(h.waits, stage.waits);
+ assert.deepEqual(h.resolutions, [envId]);
+ assert.equal(h.calls.filter((call) => call.op === 'apply').length, 1, 'never replay the POST');
+ });
+ }
+}
diff --git a/plugins/power-pages/scripts/tests/governance/set-governance-payload.test.js b/plugins/power-pages/scripts/tests/governance/set-governance-payload.test.js
new file mode 100644
index 000000000..b08045014
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/set-governance-payload.test.js
@@ -0,0 +1,105 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const { buildPolicyPayload } = require('../../../skills/manage-governance/scripts/set-governance');
+
+// buildPolicyPayload is the single seam where a canonical policyValue
+// (All / None / Include / Exclude) is forward-mapped to the value that
+// actually goes on the wire. As of the 2026-07 A059 gateway shift the wire
+// vocabulary is the SHORT canonical form itself (All / Include / Exclude /
+// None) — the older applyTo `*Sites` enums ("AllSites" etc.) are now rejected
+// with HTTP 400 A059. So the forward-map is an identity map and each of these
+// tests asserts the short form goes on the wire verbatim.
+
+const ENV_LEVEL_POLICY = 'EnableMakerCopilotForExistingSites';
+
+test('env-level policy env-wide enable posts short canonical "All"', () => {
+ const [entry] = buildPolicyPayload(ENV_LEVEL_POLICY, [], null);
+ assert.equal(entry.policyName, ENV_LEVEL_POLICY);
+ assert.equal(entry.policyValue, 'All');
+ assert.deepEqual(entry.ToBeAdded, []);
+ assert.deepEqual(entry.ToBeRemoved, []);
+});
+
+test('env-level policy env-wide disable posts "None"', () => {
+ const [entry] = buildPolicyPayload(ENV_LEVEL_POLICY, [], 'None');
+ assert.equal(entry.policyValue, 'None');
+ assert.deepEqual(entry.ToBeAdded, []);
+});
+
+test('env-level policy Include posts short canonical "Include" with ids', () => {
+ const [entry] = buildPolicyPayload(ENV_LEVEL_POLICY, ['a', 'b'], 'Include');
+ assert.equal(entry.policyValue, 'Include');
+ assert.deepEqual(entry.ToBeAdded, ['a', 'b']);
+});
+
+test('env-level policy Exclude posts short canonical "Exclude"', () => {
+ const [entry] = buildPolicyPayload(ENV_LEVEL_POLICY, ['a'], 'Exclude');
+ assert.equal(entry.policyValue, 'Exclude');
+ assert.deepEqual(entry.ToBeAdded, ['a']);
+});
+
+test('env-level policy defaults to Include enum when portalIds given and no override', () => {
+ const [entry] = buildPolicyPayload(ENV_LEVEL_POLICY, ['a'], null);
+ assert.equal(entry.policyValue, 'Include');
+ assert.deepEqual(entry.ToBeAdded, ['a']);
+});
+
+test('single portalId string is accepted (legacy call shape)', () => {
+ const [entry] = buildPolicyPayload(ENV_LEVEL_POLICY, 'single-id', 'Include');
+ assert.deepEqual(entry.ToBeAdded, ['single-id']);
+ assert.equal(entry.policyValue, 'Include');
+});
+
+for (const scope of ['Include', 'Exclude']) {
+ test(`removal-only ${scope} edit preserves the mode and sends only the removal delta`, () => {
+ assert.deepEqual(buildPolicyPayload(ENV_LEVEL_POLICY, [], scope, ['old-a', 'old-b']), [{
+ policyName: ENV_LEVEL_POLICY,
+ policyValue: scope,
+ ToBeAdded: [],
+ ToBeRemoved: ['old-a', 'old-b'],
+ }]);
+ });
+
+ test(`${scope} edit keeps independent addition and removal deltas without mutating input arrays`, () => {
+ const additions = Object.freeze(['new-a', '', null, 'new-b']);
+ const removals = Object.freeze(['old-a', null, '', 'old-b']);
+ assert.deepEqual(buildPolicyPayload(ENV_LEVEL_POLICY, additions, scope, removals), [{
+ policyName: ENV_LEVEL_POLICY,
+ policyValue: scope,
+ ToBeAdded: ['new-a', 'new-b'],
+ ToBeRemoved: ['old-a', 'old-b'],
+ }]);
+ assert.deepEqual(additions, ['new-a', '', null, 'new-b']);
+ assert.deepEqual(removals, ['old-a', null, '', 'old-b']);
+ });
+}
+
+test('removals alone default to Include rather than accidentally applying to All sites', () => {
+ assert.deepEqual(buildPolicyPayload(ENV_LEVEL_POLICY, null, null, ['old-site']), [{
+ policyName: ENV_LEVEL_POLICY,
+ policyValue: 'Include',
+ ToBeAdded: [],
+ ToBeRemoved: ['old-site'],
+ }]);
+});
+
+test('a single removal ID is accepted without being split into characters', () => {
+ assert.deepEqual(buildPolicyPayload(ENV_LEVEL_POLICY, '', 'Exclude', 'old-site'), [{
+ policyName: ENV_LEVEL_POLICY,
+ policyValue: 'Exclude',
+ ToBeAdded: [],
+ ToBeRemoved: ['old-site'],
+ }]);
+});
+
+test('omitted, empty, and filtered-empty removals preserve the env-wide default', () => {
+ for (const removals of [undefined, null, '', [], ['', null]]) {
+ assert.deepEqual(buildPolicyPayload(ENV_LEVEL_POLICY, [], null, removals), [{
+ policyName: ENV_LEVEL_POLICY,
+ policyValue: 'All',
+ ToBeAdded: [],
+ ToBeRemoved: [],
+ }]);
+ }
+});
diff --git a/plugins/power-pages/scripts/tests/governance/tip-auth.test.js b/plugins/power-pages/scripts/tests/governance/tip-auth.test.js
new file mode 100644
index 000000000..1c86f4c8f
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/tip-auth.test.js
@@ -0,0 +1,244 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const vm = require('node:vm');
+const { EventEmitter } = require('node:events');
+const { createRequire } = require('node:module');
+
+const modulePath = require.resolve('../../../skills/manage-governance/scripts/tip-auth');
+const {
+ buildScope,
+ resolveTipConfig,
+ decodeJwtExp,
+ isTokenFresh,
+ cachePath,
+ DEFAULT_TIP_HOST,
+ DEFAULT_TIP_CLIENT_ID,
+ DEFAULT_TIP_TENANT,
+} = require(modulePath);
+
+function fakeJwt(exp) {
+ const encode = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
+ return `${encode({ alg: 'none' })}.${encode({ exp })}.sig`;
+}
+
+const now = () => Math.floor(Date.now() / 1000);
+const cfgEnv = { PP_GOV_TIP_CLIENT_ID: 'c', PP_GOV_TIP_TENANT: 't' };
+const cachedToken = (exp = now() + 3600) => ({
+ clientId: 'c',
+ host: DEFAULT_TIP_HOST,
+ accessToken: fakeJwt(exp),
+ refreshToken: 'rt',
+});
+
+// Load the real module with in-memory storage and queued HTTPS responses.
+// No test may read/delete an operator's token cache or contact the real login
+// endpoint, including when a fixture misses the cached-token fast path.
+function authHarness({ cache, responses = [], readError = false, writeError = false } = {}) {
+ const requests = [];
+ const writes = [];
+ const prompts = [];
+ const waits = [];
+ let stored = cache == null ? null : JSON.stringify(cache);
+ const realRequire = createRequire(modulePath);
+ const mockedFs = {
+ readFileSync() {
+ if (readError || stored === null) throw new Error('cache unavailable');
+ return stored;
+ },
+ writeFileSync(file, data, options) {
+ if (writeError) throw new Error('cache not writable');
+ stored = data;
+ writes.push({ file, data: JSON.parse(data), options });
+ },
+ };
+ const mockedHttps = {
+ request(url, options, onResponse) {
+ const response = responses[requests.length];
+ assert.ok(response, `Unexpected HTTPS request: ${url}`);
+ const req = new EventEmitter();
+ let body = '';
+ req.write = (chunk) => { body += chunk; };
+ req.end = () => {
+ requests.push({ url, options, form: Object.fromEntries(new URLSearchParams(body)) });
+ queueMicrotask(() => {
+ if (response.error) {
+ req.emit('error', new Error(response.error));
+ return;
+ }
+ const res = new EventEmitter();
+ res.statusCode = response.statusCode;
+ onResponse(res);
+ res.emit('data', JSON.stringify(response.body));
+ res.emit('end');
+ });
+ };
+ return req;
+ },
+ };
+ const sandbox = {
+ module: { exports: {} },
+ require: (name) => name === 'fs' ? mockedFs : name === 'https' ? mockedHttps : realRequire(name),
+ Buffer,
+ process: { stderr: { write: (text) => prompts.push(text) } },
+ setTimeout(callback, ms) {
+ waits.push(ms);
+ queueMicrotask(callback);
+ },
+ };
+ vm.runInNewContext(fs.readFileSync(modulePath, 'utf8'), sandbox, { filename: modulePath });
+ return { getTipToken: sandbox.module.exports.getTipToken, requests, writes, prompts, waits };
+}
+
+test('buildScope resource-qualifies both PP scopes + offline_access', () => {
+ assert.equal(
+ buildScope(DEFAULT_TIP_HOST),
+ `${DEFAULT_TIP_HOST}/PowerPages.Websites.Read ${DEFAULT_TIP_HOST}/PowerPages.Websites.Write offline_access`,
+ );
+});
+
+test('buildScope strips a trailing slash before qualifying scopes', () => {
+ assert.equal(buildScope(`${DEFAULT_TIP_HOST}/`), buildScope(DEFAULT_TIP_HOST));
+});
+
+test('resolveTipConfig defaults to the shipped app id and organizations tenant', () => {
+ const cfg = resolveTipConfig({});
+ assert.equal(cfg.clientId, DEFAULT_TIP_CLIENT_ID);
+ assert.equal(cfg.tenantId, DEFAULT_TIP_TENANT);
+ assert.equal(cfg.host, DEFAULT_TIP_HOST);
+});
+
+test('resolveTipConfig honors app, tenant, and host overrides', () => {
+ const cfg = resolveTipConfig({
+ PP_GOV_TIP_CLIENT_ID: ' abc ',
+ PP_GOV_TIP_TENANT: ' tid ',
+ PP_GOV_TIP_HOST: 'https://api.custom.powerplatform.com/',
+ });
+ assert.equal(cfg.clientId, 'abc');
+ assert.equal(cfg.tenantId, 'tid');
+ assert.equal(cfg.host, 'https://api.custom.powerplatform.com');
+});
+
+test('decodeJwtExp extracts expiry and rejects malformed tokens', () => {
+ assert.equal(decodeJwtExp(fakeJwt(1790000000)), 1790000000);
+ for (const value of ['not-a-jwt', '', null, 'a.invalid.sig']) {
+ assert.equal(decodeJwtExp(value), null);
+ }
+});
+
+test('isTokenFresh accounts for expiry skew', () => {
+ assert.equal(isTokenFresh(fakeJwt(now() + 3600), 300), true);
+ assert.equal(isTokenFresh(fakeJwt(now() + 100), 300), false);
+ assert.equal(isTokenFresh(fakeJwt(now() - 10), 300), false);
+ assert.equal(isTokenFresh('garbage', 300), false);
+});
+
+test('cachePath lives in the OS temp dir', () => {
+ assert.ok(cachePath().startsWith(os.tmpdir()));
+ assert.ok(cachePath().endsWith('pp-gov-tip-token.json'));
+});
+
+test('getTipToken reuses a fresh matching cached token without HTTPS or writes', async () => {
+ const cache = cachedToken();
+ const h = authHarness({ cache });
+ assert.equal(await h.getTipToken(cfgEnv), cache.accessToken);
+ assert.equal(h.requests.length, 0);
+ assert.equal(h.writes.length, 0);
+});
+
+test('getTipToken refreshes an expired token and persists the rotated refresh token', async () => {
+ const h = authHarness({
+ cache: cachedToken(now() - 10),
+ responses: [{ statusCode: 200, body: { access_token: 'refreshed', refresh_token: 'rt2' } }],
+ });
+ assert.equal(await h.getTipToken(cfgEnv), 'refreshed');
+ assert.equal(h.requests.length, 1);
+ assert.equal(h.requests[0].form.grant_type, 'refresh_token');
+ assert.equal(h.requests[0].form.refresh_token, 'rt');
+ assert.equal(h.requests[0].form.client_id, 'c');
+ assert.equal(h.requests[0].form.scope, buildScope(DEFAULT_TIP_HOST));
+ assert.equal(h.writes[0].data.refreshToken, 'rt2');
+ assert.equal(h.writes[0].options.mode, 0o600);
+});
+
+test('getTipToken preserves the prior refresh token when no replacement is returned', async () => {
+ const h = authHarness({
+ cache: cachedToken(now() - 10),
+ responses: [{ statusCode: 200, body: { access_token: 'refreshed' } }],
+ });
+ assert.equal(await h.getTipToken(cfgEnv), 'refreshed');
+ assert.equal(h.writes[0].data.refreshToken, 'rt');
+});
+
+const deviceResponse = {
+ statusCode: 200,
+ body: { device_code: 'device-code', message: 'Test sign-in prompt', expires_in: 60, interval: 5 },
+};
+const tokenResponse = { statusCode: 200, body: { access_token: 'signed-in', refresh_token: 'newrt' } };
+
+test('getTipToken falls back to mocked device-code sign-in after refresh rejection', async () => {
+ const h = authHarness({
+ cache: cachedToken(now() - 10),
+ responses: [
+ { statusCode: 400, body: { error: 'invalid_grant' } },
+ deviceResponse,
+ tokenResponse,
+ ],
+ });
+ assert.equal(await h.getTipToken(cfgEnv), 'signed-in');
+ assert.equal(h.requests.length, 3);
+ assert.match(h.requests[1].url, /\/t\/oauth2\/v2\.0\/devicecode$/);
+ assert.equal(h.requests[2].form.device_code, 'device-code');
+ assert.equal(h.writes[0].data.refreshToken, 'newrt');
+ assert.match(h.prompts.join(''), /Test sign-in prompt/);
+});
+
+test('getTipToken ignores a fresh cache for a different client or host', async () => {
+ for (const mismatch of [{ clientId: 'other' }, { host: 'https://other.example' }]) {
+ const h = authHarness({
+ cache: { ...cachedToken(), ...mismatch },
+ responses: [deviceResponse, tokenResponse],
+ });
+ assert.equal(await h.getTipToken(cfgEnv), 'signed-in');
+ assert.match(h.requests[0].url, /\/devicecode$/);
+ }
+});
+
+test('getTipToken handles a missing or unreadable cache with mocked sign-in', async () => {
+ const h = authHarness({ readError: true, responses: [deviceResponse, tokenResponse] });
+ assert.equal(await h.getTipToken(cfgEnv), 'signed-in');
+ assert.equal(h.requests.length, 2);
+});
+
+test('device-code polling honors pending and slow_down responses', async () => {
+ const h = authHarness({
+ responses: [
+ deviceResponse,
+ { statusCode: 400, body: { error: 'authorization_pending' } },
+ { statusCode: 400, body: { error: 'slow_down' } },
+ tokenResponse,
+ ],
+ });
+ assert.equal(await h.getTipToken(cfgEnv), 'signed-in');
+ assert.deepEqual(h.waits, [5000, 5000, 10000]);
+});
+
+test('device-code rejection and network errors propagate without cache writes', async () => {
+ for (const responses of [
+ [{ statusCode: 400, body: { error: 'invalid_client' } }],
+ [deviceResponse, { statusCode: 400, body: { error: 'access_denied' } }],
+ [{ error: 'offline' }],
+ ]) {
+ const h = authHarness({ responses });
+ await assert.rejects(() => h.getTipToken(cfgEnv), /invalid_client|access_denied|offline/);
+ assert.equal(h.writes.length, 0);
+ }
+});
+
+test('cache write failure does not discard a successfully acquired token', async () => {
+ const h = authHarness({ writeError: true, responses: [deviceResponse, tokenResponse] });
+ assert.equal(await h.getTipToken(cfgEnv), 'signed-in');
+});
diff --git a/plugins/power-pages/scripts/tests/governance/unset-policy.test.js b/plugins/power-pages/scripts/tests/governance/unset-policy.test.js
new file mode 100644
index 000000000..8b24930b0
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/unset-policy.test.js
@@ -0,0 +1,119 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { createRequire } = require('node:module');
+
+const scripts = path.resolve(__dirname, '../../../skills/manage-governance/scripts');
+const policy = 'EnableIdpOAuthFacebook';
+const portals = [{ portalId: 'test-site', name: 'Test Site', url: 'https://example.invalid' }];
+const availability = require('../../../skills/manage-governance/scripts/resolve-portal-availability');
+const deps = availability.dependenciesForPolicy(policy, availability.loadMapping());
+
+// Run real readers and the shared transport against mocked HTTP responses.
+// No PAC/Azure CLI state, auth subprocess, or live endpoint is accessed.
+function harness(unconfigured, failedStatus) {
+ let stdout = '';
+ let stderr = '';
+ const context = { environmentId: 'test-env', baseUrl: 'https://api.powerplatform.com/powerpages/environments/test-env' };
+ const processStub = {
+ argv: ['node', 'test-script', '--policy', policy],
+ stdout: { write: (text) => { stdout += text; } },
+ stderr: { write: (text) => { stderr += text; } },
+ exit(code) { throw Object.assign(new Error(`CLI exited ${code}`), { exitCode: code }); },
+ };
+ let transport;
+ function load(name) {
+ const filename = path.join(scripts, `${name}.js`);
+ const realRequire = createRequire(filename);
+ const sandbox = {
+ module: { exports: {} },
+ __dirname: scripts,
+ process: processStub,
+ require(dependency) {
+ if (dependency === './governance-transport') return transport;
+ if (dependency === './governance-context') return { resolveGovernanceContext: () => context };
+ if (dependency === './list-portals') return { fetchPortalsPaged: async () => ({ portals }) };
+ if (dependency === './resolve-portal-availability') {
+ return { ...availability, readPortalsInput: async () => portals };
+ }
+ if (dependency === '../../../scripts/lib/power-platform-api') {
+ return {
+ parseCliArgs: () => ({ policy }),
+ runCli() {},
+ fail(message, code) { throw Object.assign(new Error(message), { exitCode: code }); },
+ async request({ path: route }) {
+ const selectedPolicy = decodeURIComponent(route.split('/')[2]);
+ const statusCode = failedStatus || (unconfigured.includes(selectedPolicy) ? 404 : 200);
+ return statusCode === 200
+ ? { ok: true, statusCode, body: route.endsWith('/details') ? {} : 'All' }
+ : { ok: false, statusCode, body: null, error: { code: `HTTP_${statusCode}`, message: 'Read failed' } };
+ },
+ };
+ }
+ return realRequire(dependency);
+ },
+ };
+ vm.runInNewContext(
+ `${fs.readFileSync(filename, 'utf8')}\nmodule.exports.testMain = typeof main === 'function' ? main : undefined;`,
+ sandbox,
+ { filename },
+ );
+ return sandbox.module.exports;
+ }
+ transport = load('governance-transport');
+ return {
+ load,
+ async run(name) {
+ await load(name).testMain();
+ return JSON.parse(stdout);
+ },
+ get stderr() { return stderr; },
+ };
+}
+
+test('get-env reports an unconfigured policy rather than failing its documented 404', async () => {
+ const h = harness([policy]);
+ const result = await h.run('get-env');
+ assert.equal(result.status, 'ok');
+ assert.equal(result.settingPresent, false);
+ assert.equal(result.value, 'None');
+ assert.match(result.message, /No governance setting on record/);
+ assert.equal(h.stderr, '');
+});
+
+for (const script of ['fetch-env-status', 'get-effective-status']) {
+ for (const missing of [policy, deps[0]]) {
+ test(`${script} preserves rows and reports an unconfigured ${missing === policy ? 'policy' : 'parent'}`, async () => {
+ const h = harness([missing]);
+ const result = await h.run(script);
+ assert.equal(result.status, 'ok');
+ assert.equal(result.settingPresent, missing !== policy);
+ assert.deepEqual(result.unconfiguredPolicies, [missing]);
+ assert.equal(result.portals.length, 1);
+ assert.equal(result.portals[0].state, false);
+ assert.equal(result.effectiveEnabledCount, 0);
+ if (script === 'fetch-env-status' && missing === policy) assert.equal(result.envValue, 'None');
+ if (missing !== policy) assert.equal(result.portals[0].parents[missing], false);
+ assert.equal(h.stderr, '');
+ });
+ }
+}
+
+test('an unconfigured prerequisite is a known disabled parent eligible for remediation', async () => {
+ const h = harness([deps[0]]);
+ const resolver = h.load('resolve-portal-availability');
+ const states = await resolver.readParentStates([deps[0]]);
+ assert.equal(states[deps[0]].envValue, 'None');
+ assert.equal(resolver.computeSiteState(states[deps[0]].envValue), 'Disabled');
+});
+
+for (const script of ['get-env', 'fetch-env-status', 'get-effective-status']) {
+ test(`${script} still fails on a real environment-read error`, async () => {
+ const h = harness([], 503);
+ await assert.rejects(h.run(script), (error) => error.exitCode === 1);
+ });
+}
diff --git a/plugins/power-pages/scripts/tests/governance/workflow-docs.test.js b/plugins/power-pages/scripts/tests/governance/workflow-docs.test.js
new file mode 100644
index 000000000..37b9dbc16
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/governance/workflow-docs.test.js
@@ -0,0 +1,214 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const skillRoot = path.join(__dirname, '../../../skills/manage-governance');
+const entry = 'SKILL.disabled.md';
+const read = (file) => fs.readFileSync(path.join(skillRoot, file), 'utf8');
+const documents = [
+ entry,
+ 'references/selection.md',
+ 'references/apply.md',
+ 'references/status.md',
+ 'HOW_IT_WORKS.md',
+];
+
+test('governance stays undiscoverable until its entry point is explicitly restored', () => {
+ assert.equal(fs.existsSync(path.join(skillRoot, 'SKILL.md')), false);
+ assert.equal(fs.existsSync(path.join(skillRoot, entry)), true);
+ const catalog = fs.readFileSync(path.join(skillRoot, '../../references/approval-gates.md'), 'utf8');
+ assert.doesNotMatch(catalog, /^\|\s*`manage-governance:[^`]+`\s*\|\s*gate\s*\|/m);
+ assert.match(catalog, /`manage-governance:2\.2\.consent`\s*\|\s*disabled/);
+ assert.match(catalog, /`manage-governance:4\.2\.3\.consent`\s*\|\s*disabled/);
+});
+
+test('governance is documented as disabled outside the user-invocable inventory', () => {
+ const agents = fs.readFileSync(path.join(skillRoot, '../../AGENTS.md'), 'utf8');
+ const skillsStart = agents.indexOf('### Skills');
+ const disabledStart = agents.indexOf('### Temporarily disabled skills');
+ const hooksStart = agents.indexOf('### Hooks', disabledStart);
+ assert.ok(skillsStart >= 0 && disabledStart > skillsStart && hooksStart > disabledStart);
+ assert.doesNotMatch(agents.slice(skillsStart, disabledStart), /`manage-governance`/);
+ const disabled = agents.slice(disabledStart, hooksStart);
+ assert.match(disabled, /`manage-governance`/);
+ assert.match(disabled, /Disabled pending Product approval/);
+ assert.match(disabled, /not user-invocable or automatically discoverable/);
+ assert.match(disabled, /HOW_IT_WORKS\.md#temporary-disablement/);
+});
+
+test('preserved governance workflow stays concise and requires each branch procedure', () => {
+ const skill = read(entry);
+ assert.ok(skill.split(/\r?\n/).length < 500, 'keep procedural detail out of the entry point');
+ for (const file of documents.filter((file) => file.startsWith('references/'))) {
+ assert.ok(skill.includes(`](${file})`), `entry point must load ${file}`);
+ }
+ assert.match(skill, /before executing its branch/);
+ assert.match(skill, /References are mandatory instructions/);
+ assert.doesNotMatch(skill, /\| Policy \| What it does \|/);
+ for (const file of documents) {
+ assert.doesNotMatch(read(file), /\$\{CLAUDE_PLUGIN_ROOT\}/);
+ }
+});
+
+test('governance procedure links and phase anchors resolve inside the installed skill', () => {
+ for (const file of documents) {
+ for (const match of read(file).matchAll(/\[[^\]]+\]\(([^)\s]+)\)/g)) {
+ const [target, anchor] = match[1].split('#');
+ const absolute = path.resolve(skillRoot, path.dirname(file), target || path.basename(file));
+ const relative = path.relative(skillRoot, absolute);
+ assert.ok(!relative.startsWith('..') && !path.isAbsolute(relative), `${file}: portable link`);
+ assert.ok(fs.existsSync(absolute), `${file}: missing link ${match[1]}`);
+ if (anchor) {
+ const headings = fs.readFileSync(absolute, 'utf8').split(/\r?\n/)
+ .filter((line) => /^#{1,6} /.test(line))
+ .map((line) => line.replace(/^#{1,6} /, '').toLowerCase()
+ .replace(/[^\p{L}\p{N}_ -]/gu, '').replace(/ /g, '-'));
+ assert.ok(headings.includes(anchor), `${file}: missing anchor ${match[1]}`);
+ }
+ }
+ }
+});
+
+test('governance selection preserves full environments and separate site-display rules', () => {
+ const selection = read('references/selection.md');
+ for (const required of [
+ 'complete fresh output verbatim',
+ 'assistant message before the selection form',
+ 'require explicit `keep`',
+ 'Never filter',
+ 'orderPortalsForDisplay()',
+ 'parser always validates against the **full** list',
+ 'do not apply',
+ 'parse-portal-input.js',
+ ]) {
+ assert.ok(selection.toLowerCase().includes(required.toLowerCase()), required);
+ }
+});
+
+test('empty environments require explicit all-only selection without bypassing Apply consent', () => {
+ const selection = read('references/selection.md');
+ const empty = selection.slice(selection.indexOf('If there are zero sites'), selection.indexOf('Resolve site input with:'));
+ assert.match(empty, /Accept only `all`/);
+ assert.match(empty, /Do not silently choose\s+`all`/);
+ assert.match(empty, /enable\/disable intent mapping/);
+ assert.match(empty, /explicit Apply now \/ Cancel\s+approval/);
+ assert.match(empty, /Fetch Site stops/);
+ assert.match(read('references/apply.md'), /empty inventory is not a list of blocked sites/);
+});
+
+test('ambiguous site names require exact IDs without automatic or partial selection', () => {
+ const selection = read('references/selection.md');
+ assert.match(selection, /When a name is ambiguous, display every matching site's name, URL, and site ID/);
+ assert.match(selection, /ask for the exact site\s+ID or cancel/);
+ assert.match(selection, /Never choose the first or last\s+match automatically/);
+ assert.match(selection, /do not\s+retain a partial selection/);
+});
+
+test('explicit environments skip redundant selection but retain fresh validation and consent', () => {
+ const selection = read('references/selection.md');
+ const supplied = selection.slice(
+ selection.indexOf('### Supplied environment name or ID'),
+ selection.indexOf('### Missing or unresolved environment'),
+ );
+ for (const required of [
+ 'fresh inventory',
+ 'case-insensitively',
+ '**exact matches only**',
+ '**Exact environment ID:**',
+ '**Unique exact environment name:**',
+ 'Duplicate exact names, conflicting name and ID, or only partial/fuzzy',
+ '**Unknown name or ID:**',
+ 'Never silently fall',
+ 'Using <display name> (<envId>)',
+ 'Do not show the environment picker or ask the user',
+ 'Apply now / Cancel',
+ ]) {
+ assert.ok(supplied.includes(required), required);
+ }
+ assert.match(supplied, /Apply,\s+Fetch Env, Fetch Site/);
+ assert.match(selection, /If no environment was supplied, or resolution above requires user input/);
+ assert.match(selection, /reuse only this operation's fresh result/);
+ assert.doesNotMatch(selection, /Even an environment named in the original request must be\s+confirmed/);
+ const skill = read(entry);
+ assert.match(skill, /skip re-selection for an exact ID or unique exact name/);
+ assert.match(skill, /resolution \(picker only when needed\)/);
+});
+
+test('governance apply keeps dependency, resumption, impact, and delta safeguards', () => {
+ const apply = read('references/apply.md');
+ for (const required of [
+ 'availabilityDependsOn',
+ 'no force/anyway override',
+ 'remediationChain',
+ '<PENDING_CHILD_INTENT>',
+ 'verification succeeds',
+ 'Redundant-operation guard',
+ 'Disclose collateral changes before approval',
+ '--removePortalIds',
+ 'render-impact-summary.js',
+ 'currentState: "Unknown"',
+ 'Sign-in failures still stop',
+ ]) {
+ assert.ok(apply.includes(required), required);
+ }
+});
+
+test('governance consent displays Markdown outside the plain-text approval form', () => {
+ const skill = read(entry);
+ const consent = skill.slice(
+ skill.indexOf('#### 4.2.3 Confirm before posting'),
+ skill.indexOf('#### 4.2.4 Apply and watch'),
+ );
+ assert.match(consent, /First send an \*\*assistant message\*\*/);
+ assert.ok(consent.indexOf('First send') < consent.indexOf('Then use `AskUserQuestion`:'));
+ assert.match(consent, /short plain-text\s+confirmation/);
+ assert.match(consent, /do not put the impact summary, table, warnings, or cascades in\s+the form's message, question, or field\/option descriptions/);
+ assert.match(consent, /before calling the tool in the same turn/);
+ assert.match(consent, /do not add a separate acknowledgement prompt/);
+ assert.match(consent, /Only selected \*\*Apply now\*\* authorizes the POST/);
+
+ const apply = read('references/apply.md');
+ assert.match(apply, /full output verbatim in an \*\*assistant message\*\*/);
+ assert.match(apply, /before calling the approval tool in the same\s+turn/);
+ assert.match(apply, /Do not put the summary or its disclosures in the form's message,\s+question, or field\/option descriptions/);
+ assert.match(apply, /only "Proceed with this change\?" in the form/);
+});
+
+test('governance selection and follow-up forms never contain the displayed tables', () => {
+ const skill = read(entry);
+ const display = skill.slice(
+ skill.indexOf('### Table display across all branches'),
+ skill.indexOf('## Workflow and task tracking'),
+ );
+ assert.match(display, /environment, site-selection, eligibility, impact, and status/);
+ assert.match(display, /assistant message\*\*, not inside an input form/);
+ assert.match(display, /before calling\s+the question tool in the same turn/);
+
+ const selection = read('references/selection.md');
+ assert.match(selection, /Do not put the environment table in\s+the form's message, question, or field\/option descriptions/);
+ assert.match(selection, /Do not put the site\/eligibility table or eligibility explanation\s+in the form's message, question, or field\/option descriptions/);
+ assert.match(selection, /free-text\s+environment value, not an option menu/);
+ assert.match(selection, /free-text scope value, not an\s+option menu/);
+ assert.match(read('references/status.md'), /Never embed the table in the\s+form's message, question, or field\/option descriptions/);
+});
+
+test('governance read procedures retain canonical output and distinct batch readers', () => {
+ const status = read('references/status.md');
+ for (const required of [
+ 'own AND every',
+ 'fail closed',
+ '# | Name | URL | Site ID | State',
+ '--markdown --no-color',
+ 'per policy in',
+ 'fetch-env-status.js',
+ 'get-effective-status.js',
+ 'Poll success alone is insufficient',
+ 'do not automatically retry the POST',
+ ]) {
+ assert.ok(status.toLowerCase().includes(required.toLowerCase()), required);
+ }
+ assert.match(status, /unfenced Markdown table/);
+ assert.match(status, /one physical line/);
+ assert.doesNotMatch(status, /--unicode/);
+});
diff --git a/plugins/power-pages/scripts/tests/lint-skills-alm.test.js b/plugins/power-pages/scripts/tests/lint-skills-alm.test.js
index adfdde365..e8091396f 100644
--- a/plugins/power-pages/scripts/tests/lint-skills-alm.test.js
+++ b/plugins/power-pages/scripts/tests/lint-skills-alm.test.js
@@ -538,6 +538,49 @@ test('findPromptLines: matches backticked AskUserQuestion followed by colon', ()
assert.deepEqual(lines, [2, 3]);
});
+test('preserved manage-governance consent call sites require markers when re-enabled', (t) => {
+ const skill = fs.readFileSync(
+ path.join(__dirname, '../../skills/manage-governance/SKILL.disabled.md'),
+ 'utf8',
+ );
+ const gates = [
+ {
+ id: 'manage-governance:2.2.consent',
+ start: '## 2.2 Validate',
+ end: '## 2.3 Supported policies',
+ },
+ {
+ id: 'manage-governance:4.2.3.consent',
+ start: '#### 4.2.3 Confirm before posting',
+ end: '#### 4.2.4 Apply and watch',
+ },
+ ];
+ for (const gate of gates) {
+ const start = skill.indexOf(gate.start);
+ const end = skill.indexOf(gate.end, start);
+ assert.ok(start >= 0 && end > start, `consent section ${gate.id} must exist`);
+ const section = skill.slice(start, end);
+ const markers = extractGateMarkers(section);
+ assert.equal(markers.length, 1);
+ assert.equal(markers[0].gateId, gate.id);
+ assert.equal(markers[0].category, 'consent');
+ assert.equal(markers[0].cancelLeaves, 'nothing');
+ assert.ok(findPromptLines(section).length > 0, `${gate.id} must have a detectable prompt`);
+
+ // Isolate each real call site so another phase's data-gathering marker
+ // cannot accidentally satisfy the missing-marker check.
+ const root = mkPluginRoot(t);
+ writeCatalog(root, [gate.id]);
+ writeSkill(root, 'manage-governance', section);
+ assert.deepEqual(collectFindings({ pluginRoot: root }), []);
+ writeSkill(root, 'manage-governance', section.replace(/<!--\s*gate:[^\n]+-->/g, ''));
+ assert.ok(
+ collectFindings({ pluginRoot: root }).some((finding) => finding.rule === 'GATE-must-have-marker'),
+ `removing ${gate.id} must fail lint`,
+ );
+ }
+});
+
test('splitIntoSections: treats ## and ### as section boundaries; not ####', () => {
const content = [
'preamble',
diff --git a/plugins/power-pages/scripts/tests/render-status-table.test.js b/plugins/power-pages/scripts/tests/render-status-table.test.js
new file mode 100644
index 000000000..3b49d1177
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/render-status-table.test.js
@@ -0,0 +1,214 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert');
+const path = require('node:path');
+
+const scriptsDir = path.join(
+ __dirname,
+ '..',
+ '..',
+ 'skills',
+ 'manage-governance',
+ 'scripts'
+);
+const {
+ loadMapping,
+ parentChainForPolicy,
+ statusColumnLabel,
+ effectiveState,
+ renderStatusTableMarkdown,
+} = require(path.join(scriptsDir, 'render-status-table.js'));
+
+const mapping = loadMapping();
+
+// --- parentChainForPolicy ---
+
+test('protocols depend only on External Auth', () => {
+ for (const p of [
+ 'EnableProtocolOpenIdConnect',
+ 'EnableProtocolSAML20',
+ 'EnableProtocolWsFederation',
+ 'EnableProtocolOpenAuth',
+ ]) {
+ assert.deepStrictEqual(parentChainForPolicy(p, mapping), ['EnableExternalAuthProviders']);
+ }
+});
+
+test('social IdPs depend on External Auth then OAuth, in that order', () => {
+ for (const p of ['EnableIdpOAuthFacebook', 'EnableIdpOAuthGoogle', 'EnableIdpOAuthMicrosoft']) {
+ assert.deepStrictEqual(parentChainForPolicy(p, mapping), [
+ 'EnableExternalAuthProviders',
+ 'EnableProtocolOpenAuth',
+ ]);
+ }
+});
+
+test('leaf / root policies have no parent columns', () => {
+ assert.deepStrictEqual(parentChainForPolicy('EnableMakerCopilotForExistingSites', mapping), []);
+ assert.deepStrictEqual(parentChainForPolicy('EnableAuthenticationLocalLogin', mapping), []);
+ assert.deepStrictEqual(parentChainForPolicy('EnableExternalAuthProviders', mapping), []);
+});
+
+// --- statusColumnLabel ---
+
+test('status column labels are the short human names', () => {
+ assert.strictEqual(statusColumnLabel('EnableExternalAuthProviders', mapping), 'External Auth');
+ assert.strictEqual(statusColumnLabel('EnableProtocolOpenAuth', mapping), 'OpenAuth Protocol');
+ assert.strictEqual(statusColumnLabel('EnableProtocolOpenIdConnect', mapping), 'OpenID Connect');
+ assert.strictEqual(statusColumnLabel('EnableProtocolSAML20', mapping), 'SAML 2.0');
+ assert.strictEqual(statusColumnLabel('EnableProtocolWsFederation', mapping), 'WS-Federation');
+ assert.strictEqual(statusColumnLabel('EnableIdpOAuthGoogle', mapping), 'Google');
+ assert.strictEqual(statusColumnLabel('EnableIdpOAuthFacebook', mapping), 'Facebook');
+ assert.strictEqual(statusColumnLabel('EnableIdpOAuthMicrosoft', mapping), 'Microsoft');
+});
+
+test('unknown policy falls back to its own name (no crash)', () => {
+ assert.strictEqual(statusColumnLabel('NotAPolicy', mapping), 'NotAPolicy');
+});
+
+test('effective header uses per-policy override when present, else default template', () => {
+ const { effectiveStatusLabel } = require(path.join(scriptsDir, 'render-status-table.js'));
+ // OpenAuth Protocol overrides the whole effective-header string via effectiveStatusLabel.
+ assert.strictEqual(effectiveStatusLabel('EnableProtocolOpenAuth', mapping), 'Effective OpenAuth State');
+ // Google has no override -> default "Effective <label> Status".
+ assert.strictEqual(effectiveStatusLabel('EnableIdpOAuthGoogle', mapping), 'Effective Google idp State');
+});
+
+// --- effectiveState ---
+
+test('effective is Enabled only when own AND every parent are Enabled', () => {
+ assert.strictEqual(effectiveState(['Enabled', 'Enabled', 'Enabled']), 'Enabled');
+ assert.strictEqual(effectiveState(['Enabled']), 'Enabled');
+});
+
+test('effective is Disabled when own or any parent is Disabled', () => {
+ // own on, parent off -> gated off (the key rule: child dark despite own=on)
+ assert.strictEqual(effectiveState(['Enabled', 'Disabled']), 'Disabled');
+ // own off, parents on
+ assert.strictEqual(effectiveState(['Disabled', 'Enabled', 'Enabled']), 'Disabled');
+ // one parent off among several
+ assert.strictEqual(effectiveState(['Enabled', 'Enabled', 'Disabled']), 'Disabled');
+});
+
+test('effective is Unknown when any state is Unknown (fail visible on partial read)', () => {
+ assert.strictEqual(effectiveState(['Enabled', 'Unknown']), 'Unknown');
+ assert.strictEqual(effectiveState(['Unknown']), 'Unknown');
+ assert.strictEqual(effectiveState([]), 'Unknown');
+ // A single Disabled with no Unknown still resolves Disabled even if other
+ // cells are Unknown? No — an Unknown present forces Unknown.
+ assert.strictEqual(effectiveState(['Disabled', 'Unknown']), 'Unknown');
+});
+
+// --- renderStatusTableMarkdown ---
+
+test('social IdP table has External Auth + OAuth parents + Effective (no own column)', () => {
+ const md = renderStatusTableMarkdown(
+ {
+ policy: 'EnableIdpOAuthGoogle',
+ portals: [
+ {
+ name: 'Portal_4',
+ url: 'https://x',
+ portalId: 'id4',
+ own: true,
+ parents: { EnableExternalAuthProviders: true, EnableProtocolOpenAuth: true },
+ },
+ ],
+ },
+ { mapping }
+ );
+ const lines = md.split('\n');
+ assert.strictEqual(
+ lines[0],
+ '| # | Name | URL | Site ID | External Auth | OpenAuth Protocol | Effective Google idp State |'
+ );
+ // both parents on + own on -> effective enabled (own has no column)
+ assert.match(lines[2], /🟢 Enabled \| 🟢 Enabled \| 🟢 Enabled \|$/);
+});
+
+test('social IdP effective is Disabled when OAuth parent is off even though own is on', () => {
+ const md = renderStatusTableMarkdown(
+ {
+ policy: 'EnableIdpOAuthGoogle',
+ portals: [
+ {
+ name: 'Portal_3',
+ url: 'https://x',
+ portalId: 'id3',
+ own: true,
+ parents: { EnableExternalAuthProviders: true, EnableProtocolOpenAuth: false },
+ },
+ ],
+ },
+ { mapping }
+ );
+ const row = md.split('\n')[2];
+ // ExternalAuth 🟢, OAuth 🔴, Effective 🔴 (own on but gated off by OAuth)
+ assert.match(row, /🟢 Enabled \| 🔴 Disabled \| 🔴 Disabled \|$/);
+});
+
+test('protocol table has External Auth parent + Effective (no OAuth/own columns)', () => {
+ const md = renderStatusTableMarkdown(
+ {
+ policy: 'EnableProtocolOpenAuth',
+ portals: [
+ {
+ name: 'Portal_1',
+ url: 'https://x',
+ portalId: 'id1',
+ own: true,
+ parents: { EnableExternalAuthProviders: false },
+ },
+ ],
+ },
+ { mapping }
+ );
+ const lines = md.split('\n');
+ assert.strictEqual(
+ lines[0],
+ '| # | Name | URL | Site ID | External Auth | Effective OpenAuth State |'
+ );
+ // External Auth off, own on -> effective off
+ assert.match(lines[2], /🔴 Disabled \| 🔴 Disabled \|$/);
+});
+
+test('unreadable parent renders Unknown and forces Effective Unknown', () => {
+ const md = renderStatusTableMarkdown(
+ {
+ policy: 'EnableIdpOAuthGoogle',
+ portals: [
+ {
+ name: 'Portal_1',
+ url: 'https://x',
+ portalId: 'id1',
+ own: true,
+ parents: { EnableExternalAuthProviders: false, EnableProtocolOpenAuth: null },
+ },
+ ],
+ },
+ { mapping }
+ );
+ const row = md.split('\n')[2];
+ assert.match(row, /Unknown \|$/);
+});
+
+test('--no-icons style (icons:false) omits the emoji markers', () => {
+ const md = renderStatusTableMarkdown(
+ {
+ policy: 'EnableIdpOAuthGoogle',
+ portals: [
+ {
+ name: 'P',
+ url: 'u',
+ portalId: 'id',
+ own: true,
+ parents: { EnableExternalAuthProviders: true, EnableProtocolOpenAuth: true },
+ },
+ ],
+ },
+ { mapping, icons: false }
+ );
+ assert.ok(!/🟢|🔴/.test(md));
+ assert.match(md.split('\n')[2], /Enabled \| Enabled \| Enabled \|$/);
+});
diff --git a/plugins/power-pages/scripts/tests/resolve-portal-availability-chain.test.js b/plugins/power-pages/scripts/tests/resolve-portal-availability-chain.test.js
new file mode 100644
index 000000000..17d45fb20
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/resolve-portal-availability-chain.test.js
@@ -0,0 +1,161 @@
+'use strict';
+
+// Tests for the ORDERED remediation chain added to resolve-portal-availability.js.
+//
+// Context (PR #309 review, defects 1 & 2): when a child auth policy is blocked
+// env-wide, the old remediation offered "enable External Auth OR enable OAuth"
+// as flat parallel options. OAuth 2.0 is itself gated by External Auth, so
+// picking OAuth first hit the same hard block — a dead-end. computeAvailability
+// now emits `remediationChain` (root-first ordered disabled parents) and `next`
+// (chain[0], the ONLY parent to offer at a time) so the orchestrator walks the
+// dependency order External Auth -> OAuth 2.0 -> child and never offers a
+// parent whose own parent is still off.
+
+const { test } = require('node:test');
+const assert = require('node:assert');
+const path = require('node:path');
+
+const scriptsDir = path.join(
+ __dirname,
+ '..',
+ '..',
+ 'skills',
+ 'manage-governance',
+ 'scripts'
+);
+const {
+ loadMapping,
+ transitiveParents,
+ availabilityDepth,
+ computeRemediationChain,
+ computeAvailability,
+} = require(path.join(scriptsDir, 'resolve-portal-availability.js'));
+
+const mapping = loadMapping();
+
+// One portal is enough to exercise env-wide blocking: a parent whose envValue is
+// 'None' is Disabled on every portal, so the single portal lands in `unavailable`
+// with that parent named — the union of which feeds the chain.
+const PORTAL = { portalId: 'p1', name: 'Portal_1', url: 'https://p1.example.com' };
+
+function availability(targetPolicy, parentStates) {
+ return computeAvailability(
+ { targetPolicy, portals: [PORTAL], parentStates },
+ { mapping }
+ );
+}
+
+// --- transitiveParents / availabilityDepth (the ordering primitives) ---
+
+test('transitiveParents: social IdP has both ancestors; protocol has one; root has none', () => {
+ assert.deepStrictEqual(
+ [...transitiveParents('EnableIdpOAuthGoogle', mapping)].sort(),
+ ['EnableExternalAuthProviders', 'EnableProtocolOpenAuth']
+ );
+ assert.deepStrictEqual(
+ [...transitiveParents('EnableProtocolSAML20', mapping)],
+ ['EnableExternalAuthProviders']
+ );
+ assert.deepStrictEqual([...transitiveParents('EnableExternalAuthProviders', mapping)], []);
+});
+
+test('availabilityDepth: root=0, OAuth 2.0=1, social IdP=2', () => {
+ assert.strictEqual(availabilityDepth('EnableExternalAuthProviders', mapping), 0);
+ assert.strictEqual(availabilityDepth('EnableProtocolOpenAuth', mapping), 1);
+ assert.strictEqual(availabilityDepth('EnableIdpOAuthGoogle', mapping), 2);
+});
+
+test('computeRemediationChain sorts root-first regardless of input order', () => {
+ // Feed the blockers in the WRONG (deepest-first) order; must come out root-first.
+ const chain = computeRemediationChain(
+ 'EnableIdpOAuthGoogle',
+ ['EnableProtocolOpenAuth', 'EnableExternalAuthProviders'],
+ mapping
+ );
+ assert.deepStrictEqual(
+ chain.map((c) => c.policyName),
+ ['EnableExternalAuthProviders', 'EnableProtocolOpenAuth']
+ );
+ // carries the human subject label for the orchestrator prompt
+ assert.strictEqual(chain[0].subject, 'External authentication providers');
+});
+
+// --- single-parent child (protocol) ---
+
+test('single-parent child, parent off env-wide: chain=[External Auth], next=root', () => {
+ const res = availability('EnableProtocolSAML20', {
+ EnableExternalAuthProviders: { envValue: 'None' },
+ });
+ assert.strictEqual(res.available.length, 0);
+ assert.deepStrictEqual(res.remediationChain.map((c) => c.policyName), [
+ 'EnableExternalAuthProviders',
+ ]);
+ assert.strictEqual(res.next.policyName, 'EnableExternalAuthProviders');
+});
+
+// --- two-parent social IdP, BOTH off: the dead-end case the fix targets ---
+
+test('social IdP, both parents off: chain=[External Auth, OAuth 2.0] (never OAuth first)', () => {
+ const res = availability('EnableIdpOAuthGoogle', {
+ EnableExternalAuthProviders: { envValue: 'None' },
+ EnableProtocolOpenAuth: { envValue: 'None' },
+ });
+ assert.strictEqual(res.available.length, 0);
+ assert.deepStrictEqual(res.remediationChain.map((c) => c.policyName), [
+ 'EnableExternalAuthProviders',
+ 'EnableProtocolOpenAuth',
+ ]);
+ // The orchestrator offers ONLY next — the root — never the gated OAuth first.
+ assert.strictEqual(res.next.policyName, 'EnableExternalAuthProviders');
+});
+
+// --- one parent already on: chain drops it (the auto-resume 2nd pass) ---
+
+test('social IdP, External Auth already on but OAuth off: chain=[OAuth 2.0] only', () => {
+ // This is the state after the admin enabled External Auth and the resolver
+ // re-ran: the root is no longer blocking, so only OAuth remains in the chain.
+ const res = availability('EnableIdpOAuthGoogle', {
+ EnableExternalAuthProviders: { envValue: 'All' },
+ EnableProtocolOpenAuth: { envValue: 'None' },
+ });
+ assert.strictEqual(res.available.length, 0);
+ assert.deepStrictEqual(res.remediationChain.map((c) => c.policyName), [
+ 'EnableProtocolOpenAuth',
+ ]);
+ assert.strictEqual(res.next.policyName, 'EnableProtocolOpenAuth');
+});
+
+test('social IdP, both parents on: portal available, empty chain, next=null', () => {
+ const res = availability('EnableIdpOAuthGoogle', {
+ EnableExternalAuthProviders: { envValue: 'All' },
+ EnableProtocolOpenAuth: { envValue: 'All' },
+ });
+ assert.strictEqual(res.available.length, 1);
+ assert.strictEqual(res.unavailable.length, 0);
+ assert.deepStrictEqual(res.remediationChain, []);
+ assert.strictEqual(res.next, null);
+});
+
+// --- unread parent fail-open: a parent we cannot read never blocks or chains ---
+
+test('unread parent is fail-open: not blocking, not in chain', () => {
+ // External Auth on; OAuth env value is unreadable (Unknown) -> fail-open: the
+ // portal stays AVAILABLE and the unread parent must NOT appear in the chain.
+ const res = availability('EnableIdpOAuthGoogle', {
+ EnableExternalAuthProviders: { envValue: 'All' },
+ EnableProtocolOpenAuth: { envValue: 'garbage-unreadable' },
+ });
+ assert.strictEqual(res.available.length, 1);
+ assert.deepStrictEqual(res.remediationChain, []);
+ assert.strictEqual(res.next, null);
+});
+
+// --- leaf/independent policy: no parents, never a chain ---
+
+test('leaf policy (Maker Copilot) has no dependencies, empty chain, next=null', () => {
+ const res = availability('EnableMakerCopilotForExistingSites', {});
+ assert.strictEqual(res.available.length, 1);
+ assert.deepStrictEqual(res.dependencies, []);
+ assert.deepStrictEqual(res.remediationChain, []);
+ assert.strictEqual(res.next, null);
+});
diff --git a/plugins/power-pages/skills/manage-governance/HOW_IT_WORKS.md b/plugins/power-pages/skills/manage-governance/HOW_IT_WORKS.md
new file mode 100644
index 000000000..1e01d2055
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/HOW_IT_WORKS.md
@@ -0,0 +1,158 @@
+# How `manage-governance` Works
+
+A brief guide to the Power Pages **Manage Governance Policies** skill — what it
+does, how a request flows through it, and which pieces do what.
+
+## Temporary disablement
+
+**Status: disabled pending Product approval.** The workflow is preserved in
+`SKILL.disabled.md`; there is deliberately no `SKILL.md` in this directory.
+Without that entry point, plugin skill discovery cannot register it for
+manual or automatic invocation. Scripts and tests remain available for
+development; this is not an API access restriction.
+
+To enable it when Product approves:
+
+1. Rename `SKILL.disabled.md` back to `SKILL.md`.
+2. Restore the two `manage-governance` rows in
+ `../../references/approval-gates.md` from Kind `disabled` to `gate`.
+3. Update the disabled-entry test paths/assertions and enabled-skill
+ documentation, then run the governance tests and approval-gate lint.
+4. Reload the plugin or start a fresh session.
+
+Existing installed copies and sessions that already loaded the skill are
+not revoked by this source change; they must update/reload as well.
+The sections below describe the preserved workflow, not an enabled skill.
+
+## What it does
+
+Applies and inspects **environment-level Power Pages governance policies**
+against any environment the signed-in admin has access to. Twenty-one policies
+are supported: Maker Copilot for existing sites, nine authentication toggles
+(sign-in protocols, social identity providers, local login, and external
+providers), and eleven `PowerPages_*` Copilot / site-control policies.
+Include / Exclude scopes can target multiple selected sites. Each policy can be turned on/off for
+**every site**, **no sites**, **only specific sites**, or **all except specific
+sites**.
+
+It is an **admin-only, environment-scoped** skill — it does **not** need a
+`powerpages.config.json` project root.
+
+## The three operations
+
+| Operation | Intent | What it does |
+|-----------|--------|--------------|
+| **Apply** (`apply`) | "Enable/Disable X …" | POST the policy, poll to a terminal state, then verify. |
+| **Fetch Env** (`fetchEnv`) | "Show/Is X … in \<env\>" | Read the env-wide value and render every site's state. |
+| **Fetch Site** (`fetchSite`) | "Is X on \<site\>?" | Read one site's state. |
+
+## Request flow
+
+```
+User free-text intent
+ │
+ ▼
+[2.1] Parse intent ──► { policy, direction, envId, scope, siteIds, … }
+ │ (policy shorthands + intent→policyValue from JSON)
+ ▼
+[2.2] Validate + fill gaps
+ │ • Env resolution → fresh inventory; exact supplied name/ID skips picker
+ │ • Env picker if needed → render-env-table.js (full list, default flagged)
+ │ • Scope → list-portals.js (all / specific sites)
+ ▼
+[4.2.3 Step 1b] Redundant-op guard (if already in requested state)
+ │ → ask eligible-site scope: "All" (no-op) vs comma-separated sites
+ ▼
+[4.2.3] Impact Summary in assistant message ──► render-impact-summary.js
+ │ (Rendered Markdown sites table, Current → New State, warnings/cascades)
+ ▼
+[4.2.3] Consent form: short question only, Apply now / Cancel
+ ▼
+[4.2.4] Apply ──► set-governance.js (POST + poll /governance/status)
+ ▼
+[4.2.5] Verify ──► get-effective-status.js + render-portal-table.js
+ ▼
+[5] Loop: re-prompt for the next request, or exit
+```
+
+## Workflow contracts
+
+This overview is not a second copy of the execution rules. The required
+procedures linked from `SKILL.disabled.md` own each contract:
+
+| Procedure | Contract |
+|-----------|----------|
+| [selection.md](references/selection.md) | Mapping-driven intent parsing, fresh validation of supplied environment names/IDs, full picker only when needed, site display and parsing |
+| [apply.md](references/apply.md) | Eligibility, parent remediation/resumption, redundant-op guard, collateral changes, additive membership/removals, impact preparation |
+| [Preserved workflow Phase 4.2.3](SKILL.disabled.md#423-confirm-before-posting) | One explicit Apply now / Cancel approval per change, including prerequisite parents |
+| [status.md](references/status.md) | Batched reads, effective state, complete five-column status output, verification and internal rollout status |
+
+Policy semantics, shorthands, side effects, and cascades live in
+`references/governance-mapping.json`. Terminal-status classification lives in
+`scripts/policies.js`; script flags, response shapes, and exit codes live in
+`references/commands.md`.
+
+All tables render in assistant messages, including environment selection,
+site selection/eligibility, impact, and final status. Input forms follow the
+table and contain only short plain-text prompts: putting Markdown tables
+inside a form can display the source text instead of a rendered grid.
+
+## Files
+
+### Scripts (`scripts/`)
+
+| File | Role |
+|------|------|
+| `list-envs.js` | List all environments the admin can access. |
+| `render-env-table.js` | Render the env picker table (Markdown or ASCII box). |
+| `list-portals.js` | List the sites in an environment. |
+| `parse-portal-input.js` | Resolve free-text site names/IDs to portal IDs. |
+| `render-impact-summary.js` | Render the consent-gate Impact Summary with a Markdown site table. |
+| `set-governance.js` | POST the policy + poll to a terminal state. Supports `--portalIds` (`ToBeAdded`) and `--removePortalIds` (`ToBeRemoved`) to grow/shrink an Include/Exclude list. |
+| `get-env.js` | Read the env-wide policy value. |
+| `get-portal.js` | Read a single site's inclusion/exclusion state. |
+| `get-status.js` | Read the last rollout status for a policy. |
+| `fetch-env-status.js` | Batch the environment site list and policy/parent reads for Fetch Env. |
+| `get-effective-status.js` | Batch policy/parent reads to compute effective site states for consent, Fetch Site, and verification. |
+| `resolve-portal-availability.js` | Partition a site list into available / unavailable for a child auth policy based on its parent policies' state (fail-open). Renders unavailable sites below available ones with the blocking parent named. |
+| `render-portal-table.js` | Render the Markdown site state table (🟢/🔴); fixed-width modes are also available. |
+| `policies.js` | Frozen `SUPPORTED_POLICIES` list + write-vocabulary mapping. |
+| `governance-context.js` | Resolves the API context; applies `--envId` override. |
+| `governance-route.js` | Builds the gateway URL and body for each op. |
+| `governance-transport.js` | Single network entry-point; issues the gateway call. |
+| `colors.js` | ANSI green/red helpers for state cells. |
+
+### References and documents
+
+| File | Role |
+|------|------|
+| `governance-mapping.json` | **Single source of truth** — policies, shorthands, intent→policyValue, cascade data, effect-line templates, state colors/paraphrases. |
+| `commands.md` | Script flags, response shapes, exit codes, polling semantics. |
+| `selection.md` | Intent, environment, and site-selection procedures. |
+| `apply.md` | Apply eligibility, remediation, impact, and submission procedures. |
+| `status.md` | Read, verification, and canonical output procedures. |
+
+### `SKILL.disabled.md`
+
+The preserved orchestrator spec (not discoverable while disabled) defines
+phases, prompts, env-picker and consent-gate rules. Reads all mappings from
+`governance-mapping.json`.
+
+## Transport
+
+All governance traffic uses a single transport — the **gateway**:
+`https://api.powerplatform.com/powerpages/environments/{envId}`, authenticated
+with an Azure CLI bearer (needs `PowerPages.Websites.*` admin consent). To target
+a non-production ring during testing, set the `PP_GOV_API_HOST` and
+`PP_GOV_TOKEN` env vars (see `governance-context.js`) — these redirect the same
+gateway transport without hardcoding any host.
+
+## Exit codes (`set-governance.js`)
+
+| Code | Meaning |
+|------|---------|
+| `0` | Rollout reached success. |
+| `2` | Sign-in required (`pac auth create` / `az login`). |
+| `3` | Polling timed out. |
+| `4` | Terminal state reached but `Failed`. |
+| `1` | Other failure. |
diff --git a/plugins/power-pages/skills/manage-governance/SKILL.disabled.md b/plugins/power-pages/skills/manage-governance/SKILL.disabled.md
new file mode 100644
index 000000000..ebe81d1a5
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/SKILL.disabled.md
@@ -0,0 +1,266 @@
+---
+name: manage-governance
+description: >-
+ Apply, inspect, and monitor Power Pages tenant governance policies. Covers
+ twenty-one policies: toggling Maker Copilot for existing sites, enabling/disabling
+ sign-in protocols (OpenID Connect, SAML 2.0, WS-Federation, OAuth 2.0), social
+ identity providers (Google, Facebook, Microsoft), local login, and external
+ auth providers, plus eleven Power Pages Copilot / site-control policies. Sets
+ a policy environment-wide or for selected sites, watches the rollout to
+ completion, and reads current state at the environment or site level. Use when
+ the user wants to "turn off OpenID Connect on Power Pages", "disable SAML on a
+ portal", "enable/disable Maker Copilot for existing sites", "enable
+ Google/Facebook/Microsoft sign-in", "turn off local login", "allow site Copilot
+ on sites", "disable external service calls from server logic", or "see the
+ governance status of my Power Pages sites" - even if they only name the policy
+ or its side effect without saying "governance".
+user-invocable: true
+argument-hint: "[optional policy or operation hint]"
+allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList
+model: opus
+---
+
+> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"`; show any output to the user before proceeding.
+
+# Manage Power Pages Governance Policies
+
+Tenant-admin workflow for applying and inspecting 21 governance policies.
+No Power Pages project root is required.
+
+**Initial request:** $ARGUMENTS
+
+## Required references
+
+All paths below are relative to `${PLUGIN_ROOT}/skills/manage-governance/`.
+Read the mapping at entry, then the applicable procedure and relevant command
+sections **before executing its branch**. References are mandatory instructions, not
+optional background reading.
+
+| Reference | Read when | Owns |
+|-----------|-----------|------|
+| [governance-mapping.json](references/governance-mapping.json) | Entry and intent resolution | Policy metadata, shorthands, intent/scope mapping, labels, dependencies, cascades, side effects |
+| [commands.md](references/commands.md) | Relevant script section before each helper call | Flags, JSON shapes, API contract, exit codes, polling semantics |
+| [selection.md](references/selection.md) | Every new request or picker | Intent parsing, fresh environment resolution, conditional picker, site display and parsing |
+| [apply.md](references/apply.md) | Every Apply, including prerequisite parents | Eligibility, parent remediation/resumption, redundant-operation guard, impact preparation, membership deltas |
+| [status.md](references/status.md) | Every read or post-Apply verification | Batched reads, effective state, full status output, verification and errors |
+
+Use **site** and **Fetch Site** in user-facing prose. Preserve actual API/code
+identifiers (`portalId`, `/websites`, script names) and helper-emitted labels.
+Use plain-language policy subjects; show technical names only when requested
+or in the consent renderer's technical mapping.
+
+### Table display across all branches
+
+Render every environment, site-selection, eligibility, impact, and status
+table in an **assistant message**, not inside an input form. Use unfenced
+Markdown with blank lines around each table, complete URLs/IDs, and the
+helper's state icons. Tool stdout alone is not the delivered table.
+
+When input is needed, send the table in an assistant message before calling
+the question tool in the same turn. Keep the form's message/question and
+field/option descriptions short and plain text; never put tables or the
+surrounding summary in those fields. This applies to free-text environment
+and scope selection as well as approval: input forms can display Markdown
+literally instead of rendering the grid.
+
+## Workflow and task tracking
+
+Create tasks for prerequisites, intent parsing, and environment/scope resolution
+at entry; add the selected operation when resolved and a summary/follow-up task
+after its result. Mark each in progress when starting and completed when done.
+
+The workflow is prerequisites → parse → resolve → run → loop. The phase numbers
+below remain the stable entry points for the procedure and command references.
+
+## 1. Prerequisites
+
+Confirm `pac auth who` and `az account show` both exit 0. If either fails, tell
+the user to sign in with `pac auth create` or `az login`, as appropriate, and
+stop. Exit code `2` from any helper also means sign-in required: explain and
+stop, never treat it as permission to continue.
+
+Use `--envId "<ENV_ID>"` on every environment-scoped helper so a chosen
+environment does not silently fall back to PAC's current environment.
+Site APIs require `/websites` **Id**, not Dataverse **WebsiteRecordId**.
+
+## 2. Entry point
+
+Start directly with Phase 2.1's free-text prompt, not an entry menu. Do not
+pre-warm or cache environments. Exit cleanly on done / that's all / exit /
+nothing. Only the consent gate uses an option question.
+
+## 2.1 Free-text intent prompt
+
+<!-- not-a-gate: data-gathering — intent parsing writes nothing; approval is required later -->
+
+Ask in prose: "Tell me what you'd like to do. For example, enable OpenID
+Connect on all sites in an environment, disable Google sign-in on Site 1 and
+Site 2, or show SAML status for an environment or a specific site."
+
+Follow [selection.md](references/selection.md#intent-resolution). Resolve
+against the mapping JSON, not an inline policy/alias table. Ask only for missing
+or ambiguous fields; never auto-invert an "everywhere except" request.
+
+## 2.2 Validate, ask for missing pieces, take consent, then submit
+
+<!-- gate: manage-governance:2.2.consent | category=consent | cancel-leaves=nothing -->
+> 🚦 **Gate (consent · manage-governance:2.2.consent):** Approve the resolved governance change after seeing its impact.
+>
+> **Trigger:** PER LOOP ITERATION for each policy/environment/scope change on the NLP path. Phase 4.2.3 implements this same approval, not a second prompt.
+> **Why we ask:** Governance changes can disable sign-in and sign out users; prior requests or approvals do not authorize later changes or prerequisite parents.
+> **Cancel leaves:** No change from this iteration; previously approved changes remain. Do not POST without a selected **Apply now**.
+
+After resolving fields and passing the Apply checks, use `AskUserQuestion`:
+**Apply now / Cancel**, exactly once at Phase 4.2.3. Do not submit directly
+from the NLP path or ask here and again at Phase 4.2.3.
+
+## 2.3 Supported policies and policyValue meaning
+
+Supported exact, case-sensitive names come from `SUPPORTED_POLICIES` in
+`scripts/policies.js`; reject custom names. Read all presentation/intent rules
+from `references/governance-mapping.json`, including `userShorthands`,
+`intentToPolicyValue`, `policyValueSemantics`, `ambiguousPhrasings`,
+`effectLineTemplates`, `availabilityDependsOn`, and cascade/side-effect data.
+All policies use the same Enable/Disable workflow; do not reinterpret the verb
+based on a policy's internal name.
+
+## 3. Determine the operation
+
+| Intent | Operation | Branch |
+|--------|-----------|--------|
+| `apply` | Apply | 4.2 |
+| `fetchEnv` | Fetch Env | 4.3 |
+| `fetchSite` | Fetch Site | 4.4 |
+
+Do not ask users to re-pick a clear operation. If ambiguous, describe these
+three operations in a free-text clarification. Rollout status is internal,
+not a fourth advertised operation.
+
+## 4. Run the operation
+
+### 4.1 Environment picker
+
+Follow [selection.md](references/selection.md#environment-picker) on **every
+new request**, including loop iterations: fetch fresh environments, show the
+resolved name/ID and skip re-selection for an exact ID or unique exact name
+supplied by the user. If missing, unknown, conflicting, or ambiguous, show the
+complete table in an assistant message before the selection form and require
+explicit `keep` / row / name / ID selection. Never silently choose a default
+or a partial/fuzzy match; never truncate or filter a displayed environment list.
+Then show the site picker and take the scope/site reply as specified there.
+
+### 4.2 Apply
+
+Read [apply.md](references/apply.md) in full before proceeding.
+
+#### 4.2.1 Choose scope
+
+Run the mapping-driven eligibility check before scope selection. For blocked
+children, follow [parent remediation and auto-resume](references/apply.md#parent-remediation-and-auto-resume).
+Otherwise take free-text `all` or comma-separated site names/IDs.
+
+#### 4.2.2 Site picker
+
+Use the shared [site picker and parser](references/selection.md#site-picker-and-parser).
+Validate against the full site list, not just visible rows.
+
+#### 4.2.2b Availability gate for named sites
+
+Directly named sites must pass the **same** [eligibility hard gate](references/apply.md#eligibility-hard-gate)
+as picker-selected sites. There is no force/anyway bypass in either direction.
+
+#### 4.2.3 Confirm before posting
+
+<!-- gate: manage-governance:4.2.3.consent | category=consent | cancel-leaves=nothing -->
+> 🚦 **Gate (consent · manage-governance:4.2.3.consent):** Authorize this specific POST after the Impact Summary.
+>
+> **Trigger:** PER LOOP ITERATION for each policy/environment/scope change, including prerequisite parent-policy changes.
+> **Why we ask:** A policy can disable sign-in and sign out users. Earlier intent, environment picks, and previous approvals do not authorize this POST. Phase 2.2 describes this same gate; ask once per change.
+> **Cancel leaves:** No change from this iteration; earlier approved changes remain. Cancel exits without a POST.
+
+Follow [impact preparation](references/apply.md#impact-preparation): one batched
+current-state read, the redundant-operation guard, and disclosure of collateral
+changes and membership removals **before** rendering and approval.
+First send an **assistant message** containing `render-impact-summary.js`
+output verbatim as Markdown, starting at `**Action:**` with no preamble or code
+fence. Preserve blank lines and keep table rows on single physical lines;
+do not hand-build, shorten, or supplement its cascade. Tool output alone does
+not count as displaying the summary.
+
+Then use `AskUserQuestion`: "Proceed with this change?" with exactly **Apply
+now** / **Cancel**. Keep the form's message/question to that short plain-text
+confirmation; do not put the impact summary, table, warnings, or cascades in
+the form's message, question, or field/option descriptions. The approval form
+can display Markdown literally, whereas the preceding assistant message
+renders the table. Send the summary before calling the tool in the same turn;
+do not add a separate acknowledgement prompt.
+
+Only selected **Apply now** authorizes the POST. Freeform
+"Other" text, cancellation, or any different reply is non-authorizing.
+On Cancel say "No change made" and return to the loop. Changed requests require
+a fresh summary and approval; never reuse consent.
+
+#### 4.2.4 Apply and watch
+
+Use [apply.md's submission procedure](references/apply.md#submit-and-watch).
+Run `set-governance.js` in the background (`run_in_background: true`); relay
+stderr progress no more than once every 30 seconds. Surface timeout/failure
+explicitly rather than claiming success.
+
+#### 4.2.5 Confirm after rollout
+
+Wait for terminal completion, then follow [post-Apply verification](references/status.md#post-apply-verification).
+Never trust polling alone. Verify the expected scope and site states, report
+mismatches, and deliver the complete status artifact.
+
+### 4.3 Check current state across an environment (Fetch Env)
+
+#### 4.3.1 Batched read and render
+
+Follow [Fetch Env](references/status.md#fetch-env): `fetch-env-status.js` is the
+single batched reader; no preliminary standalone governance reads.
+
+### 4.4 Check current state on one site (Fetch Site)
+
+#### 4.4.1 List sites and render the table
+
+Use the shared site picker from Phase 4.1; no duplicate list prompt is needed.
+
+#### 4.4.2 Ask which site
+
+Resolve exactly one site through `parse-portal-input.js`; surface errors and
+reprompt for zero or multiple matches.
+
+#### 4.4.3 Run the read and render the result
+
+Follow [Fetch Site](references/status.md#fetch-site): pipe one-site JSON directly
+into `get-effective-status.js`, then the canonical renderer. No temporary
+site-list file or sequential `get-*` calls.
+
+#### 4.4.4 Effective status for gated child sign-in methods
+
+Use the [effective-state contract](references/status.md#effective-state-and-output-contract).
+The helper computes own AND every gating parent; never add parent columns.
+
+### 4.5 Internal rollout status
+
+Consult [status.md](references/status.md#internal-rollout-status) for
+`get-status.js`. A last-rollout snapshot is not proof the current Apply landed.
+
+## 5. Loop or finish
+
+Summarize the result in one plain-language sentence using mapping-owned
+`summaryLabel` and scope labels; do not expose internal exit codes or fields.
+Keep the complete unfenced Markdown status table in the delivered response,
+not just tool output.
+
+A successfully verified prerequisite-parent enable with `<PENDING_CHILD_INTENT>`
+takes priority: [re-run eligibility and resume the child](references/apply.md#parent-remediation-and-auto-resume)
+before the generic prompt. Otherwise re-prompt as in Phase 2.1, without an
+operation menu. Every new request goes through a fresh Phase 4.1 environment
+resolution (picker only when needed). Done / exit finishes; a different request or cancel discards pending
+child intent.
+
+For tracking, read `${PLUGIN_ROOT}/references/skill-tracking-reference.md` and
+use `--skillName "ManageGovernance"`. A tracking no-op outside a project is
+expected; do not require local project artifacts.
diff --git a/plugins/power-pages/skills/manage-governance/references/apply.md b/plugins/power-pages/skills/manage-governance/references/apply.md
new file mode 100644
index 000000000..d68a754e4
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/references/apply.md
@@ -0,0 +1,211 @@
+# Apply procedures
+
+Required for every SKILL.md Phase 4.2 operation, including prerequisite
+parent changes. Read [selection.md](selection.md) and [status.md](status.md)
+for shared selection, batched reads, and final output. The approval decision
+itself stays at SKILL.md Phase 4.2.3; do not ask a second consent question here.
+
+## Eligibility hard gate
+
+Read the requested policy's `availabilityDependsOn` from
+`governance-mapping.json`. A policy without dependencies needs no availability
+filter; every site is eligible. Do not maintain a second dependency table.
+OAuth is both a child of External Auth and a parent of social providers;
+it is **not** a root-policy exception.
+
+When dependencies exist, run:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/resolve-portal-availability.js" \
+ --policy "<POLICY>" --envId "<ENV_ID>" --markdown
+```
+
+Emit the helper's table verbatim: **every** site, explicit `Eligible` Yes/No,
+eligible first and blocked sites immediately below naming the blocking parent.
+Never use `--available-only` for the picker. Only eligible sites may be selected.
+A child can be **neither enabled nor disabled** where a parent is Disabled;
+there is **no force/anyway override**.
+
+The resolver fails open for unread parents: note the uncertainty explicitly,
+but do not invent a block. This differs from effective status reads, which
+fail closed for an unread parent. See `commands.md` for the resolver's JSON
+fields and read/error behavior.
+
+An unread Include/Exclude membership list is not a successful empty list.
+The resolver preserves the known parent scope, records `membershipReadErrors`
+and per-site `unreadParents`, and marks affected eligibility as unverified.
+Display the helper's warning before selection and repeat the uncertainty
+before final consent, including on the named-site path. Do not claim these
+parents are Enabled or Disabled or offer remediation based on an unread list.
+Known disabled parents still block; membership HTTP 401/403 or context errors
+stop the operation instead of failing open.
+
+If the environment has zero sites, follow the all-only site-selection prompt
+in `selection.md`; an empty inventory is not a list of blocked sites. Preserve
+the requested enable/disable direction and the normal impact/consent gates.
+
+If the inventory is nonempty but no site is eligible, surface the helper's disabled-parent message instead
+of an all-No table, do not prompt for scope, do not render an impact summary,
+and do not POST. Follow the parent-remediation procedure below.
+
+### Named-site path (Phase 4.2.2b)
+
+The same gate applies when sites were named in the original request. Pipe
+resolved site JSON directly to the resolver (default JSON mode, no temporary
+site-list file):
+
+```bash
+echo '{ "portals": [ { "portalId": "<id>", "name": "<name>", "url": "<url>" } ] }' \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/resolve-portal-availability.js" \
+ --policy "<POLICY>" --envId "<ENV_ID>"
+```
+
+Use `available` and `unavailable` to partition the named sites. If some are
+blocked, remove them from the resolved IDs/names and explain each removal,
+naming its blocking parent; proceed only with eligible sites. If all are
+blocked, no summary or POST: save the original intent and offer remediation.
+If all are available, proceed unchanged. Neither direct naming nor switching
+enable/disable direction bypasses eligibility.
+
+## Parent remediation and auto-resume
+
+Read the resolver's JSON `remediationChain` (Disabled parents, root-first)
+and `next` (`remediationChain[0]`). Offer **only `next.subject`** as an enable
+action, in a free-text prompt, or cancel/different request. Never offer a flat
+"External Auth OR OAuth" choice, a deeper parent as a co-equal action, or an
+extra parent-diagnostics menu.
+
+Before pausing, save `<PENDING_CHILD_INTENT>` with the original policy,
+direction, environment, scope, site IDs/names. Tell the admin the original
+child request will resume after the prerequisite is enabled.
+
+If the admin replies with the offered enable command:
+
+1. Run that parent as a normal Apply, with fresh environment validation under
+ the selection procedure (no redundant picker for an exact supplied target), its own
+ eligibility checks, impact summary, and separately selected **Apply now**.
+ Never enable any parent silently using the child's request or approval.
+2. After the parent completes **and verification succeeds**, re-run the
+ availability resolver for the pending child in the same environment.
+3. If another parent is still blocked, offer only the new `next` and retain the
+ pending intent. If eligible, announce resumption in one line and continue
+ the original child at its eligibility/scope step (or the summary preparation
+ when scope/sites are already resolved). Recheck named sites as well; do not
+ assume the parent rollout made every requested site eligible.
+4. Clear pending intent when resuming the child. The child still needs its own
+ impact summary and consent. Do not fall into the generic loop and forget it.
+
+If the parent fails, times out, or verification mismatches, report it and do
+not resume as if successful. A different request or cancel discards pending
+intent. Auto-resume is an offer, not a lock-in.
+
+## Impact preparation
+
+### Batched current-state read
+
+Before any summary, read the current effective states with **one** batch:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/get-effective-status.js" \
+ --policy "<POLICY>" --envId "<ENV_ID>"
+```
+
+Do not loop per site or manually sequence `get-env.js`, `get-details.js`, or
+`get-portal.js`. Use returned effective `state` for each affected site.
+If a live state cannot be read, pass `currentState: "Unknown"` and disclose
+that uncertainty in a footnote; a current-state read error alone does not
+block consent. Sign-in failures still stop the skill.
+
+### Redundant-operation guard
+
+Before the Impact Summary, if every named site is already in the requested
+state (enable under `All`/existing `Include`, or disable under `None`/existing
+`Exclude`), do not silently POST. Ask in **free text**, not an option menu:
+
+> "The setting is already <enabled/disabled> on the eligible sites. Reply
+> **All** for no change, a comma-separated list of sites to <enable/disable>
+> only those, or **cancel**."
+
+`All` reports no change, skips consent/POST, and returns to the loop.
+Cancel also makes no change. A specific list re-scopes to `Include` (enable)
+or `Exclude` (disable), then proceeds to impact preparation and consent.
+
+**Disclose collateral changes before approval.** Narrowing `All` to `Include`
+turns unlisted sites off; changing `None` to `Exclude` turns unlisted sites on.
+List those out-of-scope sites and their Current → New states alongside the
+helper-rendered summary. Never imply that only the named sites can change.
+
+### Membership deltas
+
+`ToBeAdded` is additive, not replacement membership. A shorter Include/Exclude
+list does not remove existing members. When narrowing/shrinking an existing
+list, compare current membership from the batched read, explicitly pass removed
+IDs through `--removePortalIds` (`ToBeRemoved`), and disclose those removals
+before approval. Never claim replacement semantics from `ToBeAdded` alone.
+
+### Deterministic summary
+
+The renderer normalizes environment and site names to single-line literal
+Markdown text before inserting them into Environment, Scope, and Effect prose.
+Pass the original names to the helper; do not pre-escape them.
+
+Pipe the resolved request to the renderer:
+
+```bash
+echo '{
+ "policy": "<POLICY>",
+ "direction": "<enable|disable>",
+ "scope": "<all|specific>",
+ "policyValue": "<POLICY_VALUE>",
+ "env": { "displayName": "<ENV_DISPLAY>", "envId": "<ENV_ID>" },
+ "sites": [ { "name": "<name>", "url": "<url>", "portalId": "<id>", "currentState": "Enabled|Disabled|Unknown" } ]
+}' | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/render-impact-summary.js"
+```
+
+Use `scope: all` for `All`/`None`, with every environment site, or `specific`
+for `Include`/`Exclude`, with the selected sites. Use real values, not the
+placeholder alternatives shown above.
+
+The helper owns Action, Environment, Scope, the unfenced Markdown site table
+(name, URL, ID, Current/New State and CHANGED markers), Effect, Policy value
+and `ToBeAdded`, side effects, state icons, and nested cascades. Read its data
+from the mapping rather than copying policy-specific text into this procedure.
+Disabling authentication can sign out existing users; preserve that warning.
+Enable cascades describe availability, not forced child enablement.
+
+Emit its full output verbatim in an **assistant message**, starting at
+`**Action:**`, without a preamble or code fence. Preserve paragraph/table/list
+blank lines. Each site must stay on one physical Markdown row; visual wrapping
+is fine, hard line breaks within a row are not.
+Do not invent a cascade, explain its absence, or replace the Markdown impact
+table with a text box. Additional collateral-state/removal disclosures go
+after the helper output and before consent, without editing the helper output.
+Display that assistant message before calling the approval tool in the same
+turn. Do not put the summary or its disclosures in the form's message,
+question, or field/option descriptions: the approval form can display
+Markdown literally rather than render a table. Tool output alone is not a
+user-facing summary. Return to SKILL.md Phase 4.2.3 for the single approval
+decision, with only "Proceed with this change?" in the form and **Apply now**
+/ **Cancel** options. Do not add a separate acknowledgement prompt.
+
+## Submit and watch
+
+Only after selected **Apply now** at Phase 4.2.3:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/set-governance.js" \
+ --envId "<ENV_ID>" --policy "<POLICY>" --policyValue "<POLICY_VALUE>" \
+ [--portalIds "<PORTAL_IDS>"] [--removePortalIds "<REMOVED_PORTAL_IDS>"]
+```
+
+For `All`/`None`, omit site-list flags. For selected-site scopes, `--portalIds`
+accepts comma/whitespace-separated IDs; singular `--portalId` is legacy only.
+
+Run in the background and relay stderr progress at most once every 30 seconds.
+The helper POSTs `/governance` and polls the environment-scoped
+`/governance/status/{policy}`; default timeout is 15 minutes. Terminal
+classification and exit codes live in `scripts/policies.js` and `commands.md`,
+not a separate status table here. Surface errors and timeouts explicitly.
+Wait for completion, then perform [post-Apply verification](status.md#post-apply-verification).
diff --git a/plugins/power-pages/skills/manage-governance/references/commands.md b/plugins/power-pages/skills/manage-governance/references/commands.md
new file mode 100644
index 000000000..6a1eabe91
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/references/commands.md
@@ -0,0 +1,1066 @@
+# Manage Power Pages Governance — Commands
+
+Reference for the helper scripts under `scripts/`. Every script uses the
+shared `power-platform-api` client from the plugin root, so they share the
+same auth/context resolution, exit-code conventions, and the
+`Authorization: Bearer <token>` + `api-version=2022-03-01-preview` headers
+the Power Platform API expects.
+
+All scripts accept `--help` to print full usage.
+
+## Table of contents
+
+- [Supported policies](#supported-policies)
+- [Assumed API contract](#assumed-api-contract)
+- [Environment override](#environment-override)
+- [Ring selection (TIP vs Prod) and token generation](#ring-selection-tip-vs-prod-and-token-generation)
+- [`list-envs.js`](#list-envsjs)
+- [`list-portals.js`](#list-portalsjs)
+- [`set-governance.js`](#set-governancejs)
+- [`get-status.js`](#get-statusjs)
+- [`get-env.js`](#get-envjs)
+- [`get-portal.js`](#get-portaljs)
+- [`get-details.js`](#get-detailsjs)
+- [`resolve-portal-availability.js`](#resolve-portal-availabilityjs)
+- [`fetch-env-status.js`](#fetch-env-statusjs)
+- [`get-effective-status.js`](#get-effective-statusjs)
+- [`render-status-table.js`](#render-status-tablejs)
+- [`parse-portal-input.js`](#parse-portal-inputjs)
+- [Common error catalogue](#common-error-catalogue)
+
+---
+
+## Supported policies
+
+The skill validates every policy string against the frozen `SUPPORTED_POLICIES`
+array in `scripts/policies.js` — the single code-level source of truth. Add a
+policy by appending its string there; every script checks that list before
+calling the API.
+
+The **plain-language meaning, user shorthands, availability dependencies, and
+cascade data for each policy live in `references/governance-mapping.json`**
+(and are surfaced through the skill's mapping-driven prompts and renderers). This file
+deliberately does **not** re-list them — read the JSON so there is one source
+of truth rather than a third copy that can drift.
+
+`render-impact-summary.js` expands cascade items in mapping order. Items may be
+plain labels, `{ "label": "...", "note": "...", "state": "Enabled" }` entries,
+or grouped objects such as `{ "OAuth 2.0": ["Facebook", "Google"] }`. A group
+renders its label followed by all descendants, preserving notes and explicit
+states. Disable cascades mark each entry Disabled; enable cascades describe
+availability without claiming a child is enabled unless its item declares that
+state. Malformed items fail with an explicit error rather than omitting impact
+or rendering `undefined`.
+
+All policies share the **same API contract** regardless of what they govern:
+uniform governance with the canonical `policyValue` vocabulary
+(`All` / `None` / `Include` / `Exclude`). The eleven `PowerPages_*` Copilot /
+site-control policies are **independent leaves** — no parent/child availability
+gate and no cascade — so their effective state equals their own state.
+
+> **Read-value vocabulary.** The nine auth `Enable*` policies report their
+> environment-level state on read using the
+> canonical `policyValue` strings (`All` / `None` / `Include` / `Exclude`).
+> Only `EnableMakerCopilotForExistingSites` instead reports the `applyTo` enum
+> form (e.g. `AllSites`). `get-env.js` normalizes this via `normalizeEnvValue()`
+> and returns a canonical `value` field alongside the raw `body`; the alias
+> table lives in `scripts/policies.js` (`ENV_VALUE_ALIASES`) and mirrors
+> `readValueAliases` in `references/governance-mapping.json`.
+
+---
+
+## Assumed API contract
+
+The skill was authored against the existing Power Pages Power Platform API
+pattern (same base URL the `manage-firewall` skill uses). The exact request
+and response shapes for the governance endpoints are documented here as
+**assumptions** — patch the scripts in this folder if the real contract
+differs:
+
+| Operation | Method | Path | Body | Polled by |
+|-----------|--------|------|------|-----------|
+| Apply env-wide or portal-scoped | `POST` | `/governance` | Array — see below | `set-governance.js` polls `GET /governance/status/{policy}` |
+| Status snapshot | `GET` | `/governance/status/{policy}` | — | `get-status.js`, plus `set-governance.js` polling |
+| Env-level read | `GET` | `/governance/{policy}` | — | `get-env.js` |
+| Portal-level read | `GET` | `/websites/{portalId}/governance/{policy}` | — | `get-portal.js` |
+| Env-level membership read (inclusion/exclusion lists) | `GET` | `/governance/{policy}/details` | — | `get-details.js` |
+
+POST body shape (from the PowerApps-CoreServicesGateway gateway config — verified 2026-06-06):
+
+```json
+[
+ {
+ "policyName": "EnableProtocolOpenIdConnect",
+ "policyValue": "All",
+ "ToBeAdded": [],
+ "ToBeRemoved": []
+ }
+]
+```
+
+Field semantics encoded by `set-governance.js`:
+
+| Field | Env-wide call | Portal-scoped call |
+|-------|---------------|--------------------|
+| `policyName` | the policy string | the policy string |
+| `policyValue` | `"All"` | `"Include"` |
+| `ToBeAdded` | `[]` | `[ "<portalId>" ]` |
+| `ToBeRemoved` | `[]` | `[]` |
+
+`policyValue` is one of `All`, `None`, `Include`, `Exclude`:
+
+| Value | Effect on the env |
+|-------|-------------------|
+| `All` | Apply the policy to every portal in the env. |
+| `None` | Apply to no portals. Clears any inclusion/exclusion lists. |
+| `Include` | Allow-list mode — apply only to portals named in `ToBeAdded`. |
+| `Exclude` | Block-list mode — apply to every portal EXCEPT those in `ToBeAdded`. |
+
+The default `set-governance.js` mapping is `All` for env-wide calls and
+`Include` for portal-scoped calls; pass `--policyValue <name>` to override.
+The script always wraps the policy object in a single-element array, but the
+body is an array on purpose — the gateway accepts multiple policy objects in
+one POST.
+
+> **Write vocabulary (canonical → wire).** `--policyValue` and every internal
+> code path use the canonical `All` / `None` / `Include` / `Exclude` strings.
+> As of the **2026-07 A059 gateway shift** these short canonical forms ARE the
+> wire vocabulary — the older `applyTo` `*Sites` enums are now rejected. So
+> `set-governance.js buildPolicyPayload` → `policies.js toWritePolicyValue()`
+> forward-maps each canonical value to itself (an identity map, kept as a seam
+> in case the wire vocabulary shifts again):
+>
+> | Canonical (`--policyValue`) | Wire value (env-level policies) |
+> |-----------------------------|---------------------------------|
+> | `All` | `All` |
+> | `Include` | `Include` |
+> | `Exclude` | `Exclude` |
+> | `None` | `None` (disable is conveyed by the value itself) |
+>
+> **History:** originally (2024-10-01 gateway) env-level policies REQUIRED the
+> `applyTo` `*Sites` enums on write (`AllSites` / `IncludeSites` /
+> `ExcludeSites`) and rejected the short forms with the plain body
+> `Website id cannot be null or empty`. As of 2026-07 the gateway inverted that
+> contract for the sign-in protocol policies: it now rejects the `*Sites` forms
+> with HTTP 400 `{ "error": { "code": "A059", "message": "The provided policy
+> value is not a valid governance policy value." } }` and accepts the short
+> forms. The READ side still normalizes `*Sites` → canonical via
+> `policies.js normalizeEnvValue()` because the env can still read those back.
+> Verified empirically against Preprod on `EnableProtocolOpenAuth` (2026-07):
+> `AllSites`/`IncludeSites`/`ExcludeSites` → `400 A059`; `All`/`Include`/`Exclude`
+> → `200 "Policy upserts accepted."` (a short-form POST during an in-flight
+> rollout returns code `D006` with an empty message — a concurrency lock, not
+> value rejection; retry once `GET /governance/status` reports `Succeeded`).
+
+All paths are appended to the base URL:
+`https://api.powerplatform.com/powerpages/environments/{envId}` (or the
+cloud-specific equivalent — see `validation-helpers.js` for the mapping).
+
+The `set-governance.js` polling helper treats the following case-insensitive
+status values as terminal:
+
+- **Success**: `Succeeded`, `Completed`, `Created`, `OK`.
+- **Failure**: `Failed`, `Error`.
+
+Any other value is treated as in-progress. Update `TERMINAL_SUCCESS` /
+`TERMINAL_FAILURE` in `scripts/policies.js` if the real API uses different
+keywords.
+
+---
+
+## Environment override
+
+Each script accepts an optional `--envId <guid>`. Without it the script
+addresses whatever env the PAC CLI is currently signed into (`pac auth who`).
+With it, the env id segment of the base URL is rewritten before the request
+goes out — letting a tenant admin run the skill against any env they have
+admin access to without re-running `pac auth select`.
+
+The override is implemented in `scripts/governance-context.js`. It replaces
+the `…/environments/<id>/…` segment after the shared `resolveContext()` has
+acquired a token.
+
+---
+
+## Ring selection (TIP vs Prod) and token generation
+
+`governance-context.js` resolves both the **gateway host** and the **bearer
+token** per ring. **TIP/Preprod is the default ring**; Prod is opt-out.
+
+When `--envId` is omitted, the transport reuses a supplied context or resolves
+the current/configured environment before validating the route. If no
+environment can be resolved, it returns a `ContextError` without sending a
+request; supply `--envId` or select a current PAC environment.
+
+### Ring flag
+
+| Source | Effect |
+|--------|--------|
+| `app-settings.json activeRing=TIP` | TIP ring → host `https://api.preprod.powerplatform.com`. |
+| `app-settings.json activeRing=Prod` | Prod ring → host from the signed-in cloud (`api.powerplatform.com`, gov clouds, …). |
+| `PP_GOV_TIP_HOST=<url>` | Override the default TIP host (e.g. a different pre-production ring). |
+| `PP_GOV_API_HOST=<url>` | Pin an **arbitrary** host; outranks the ring entirely. |
+
+> The TIP host is `api.preprod.powerplatform.com`. `api.tip.powerplatform.com`
+> does **not** resolve in DNS and is not the Preprod gateway.
+
+### Token generation
+
+The governance gateway requires the delegated scopes
+`PowerPages.Websites.Read` / `PowerPages.Websites.Write`. The Azure CLI
+first-party client is **not** authorized for these and cannot be granted them,
+so an az-minted token 403s (`InsufficientDelegatedPermissions`). Token
+resolution precedence:
+
+1. **`PP_GOV_TOKEN`** — an explicit bearer always wins. Paste a scoped token
+ (e.g. from the admin portal, or one you minted yourself).
+2. **TIP ring → custom-app device-code flow.** `governance-context.js` runs
+ `tip-auth.js` (OAuth 2.0 device-code + silent refresh) to mint a token that
+ actually carries the PowerPages scopes. It defaults to the shipped
+ `pp-governance-cli` app (`c5ae9f06-f0bb-4ef6-9ee4-c7a3803da37a`) and the
+ `organizations` authority, so **no env vars are required** — the first run
+ prompts for an interactive browser sign-in; subsequent runs renew silently
+ from the cached refresh token. Override `PP_GOV_TIP_CLIENT_ID` /
+ `PP_GOV_TIP_TENANT` to point at a different registration.
+3. **Fallback** — if the device-code flow fails, it falls back to an az mint
+ (which will 403 on governance calls) and prints guidance.
+
+| Env var | Purpose |
+|---------|---------|
+| `PP_GOV_TIP_CLIENT_ID` | *(optional)* Public-client app id for the device-code flow. Defaults to the shipped `pp-governance-cli` app. |
+| `PP_GOV_TIP_TENANT` | *(optional)* Tenant id (or `organizations`) for the device-code authority. Defaults to `organizations`. |
+| `PP_GOV_TOKEN` | Explicit bearer token; overrides all generation. |
+| `PP_GOV_TOKEN_RESOURCE` | Override the token audience when it differs from the host. |
+
+The shipped app id is a **public identifier, not a secret** (the flow still
+requires an interactive user sign-in and uses no client secret), so it is safe
+to ship as a default. To use your own app instead, register a public-client
+app, add `PowerPages.Websites.Read` + `PowerPages.Websites.Write` as delegated
+permissions on the Power Platform API resource, grant consent, then:
+
+```bash
+export PP_GOV_TIP_CLIENT_ID="<app-id>"
+export PP_GOV_TIP_TENANT="<tenant-id>"
+```
+
+With the defaults, TIP works with no setup — just run any governance script:
+
+```bash
+# TIP is the default ring:
+node get-env.js --policy EnableProtocolSAML20 --envId <guid>
+```
+
+---
+
+## `list-envs.js`
+
+Lists Power Platform environments the signed-in PAC profile can administer.
+Prod uses `pac admin list --json` via the shared `pac-bap-shim.js`; TIP uses
+the configured BAP REST endpoint with an Azure CLI token. The TIP REST
+request has a **60-second total timeout**, including connection setup and
+response-body reads. On timeout the request is aborted and the command exits
+`1` with an explicit error, not an empty environment list. Prod/PAC discovery
+and governance rollout polling are unchanged.
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-envs.js" \
+ [--type <Production|Sandbox|Trial|Developer|Default>] \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/render-env-table.js" --markdown
+```
+
+Every invocation fetches the current environment inventory from the configured
+ring. The command intentionally has no file cache or TTL cache.
+
+### Response (stdout)
+
+```json
+{
+ "status": "ok",
+ "envs": [
+ { "envId": "<guid>", "displayName": "<name>", "envUrl": "<url>",
+ "type": "Production", "domain": "<domain>" }
+ ]
+}
+```
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success (including empty result) |
+| `2` | PAC CLI sign-in required (`pac auth create`) |
+| `1` | Any other failure |
+
+---
+
+## `list-portals.js`
+
+Lists Power Pages portals in an environment. Paginates over `/websites` and
+emits a flat list.
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" \
+ [--envId <guid>]
+```
+
+### Response (stdout)
+
+```json
+{
+ "status": "ok",
+ "portals": [
+ { "portalId": "<guid>", "name": "<portal name>",
+ "websiteUrl": "<url>", "websiteRecordId": "<guid>",
+ "type": "Production", "status": "StateConfigured",
+ "createdOn": "2026-07-19T07:30:42" }
+ ]
+}
+```
+
+The user-facing identifier is `portalId` — that is what the governance
+endpoints accept. `websiteRecordId` is shown for cross-reference with PAC
+and the Dataverse website record. `type` (`Production` / `Trial`), `status`
+(e.g. `StateConfigured`), and `createdOn` drive the display ordering below.
+
+### Display ordering (picker cap)
+
+The script always returns **every** portal in the environment (unbounded) so
+name/id resolution and the Fetch-Env site tables stay complete. The
+**orchestrator caps the rendered picker to 10 rows**. When an environment has
+more than 10 portals, render the top 10 using `orderPortalsForDisplay()`
+(exported from `list-portals.js`), which prioritizes:
+
+1. `type === "Production"` first,
+2. then `status === "StateConfigured"`,
+3. then oldest-first by `createdOn` (ascending).
+
+When there are 10 portals or fewer, the original order is preserved (no
+re-sort). The helper returns `{ shown, total, truncated, limit }`; when
+`truncated` is true, note "showing 10 of `total`" to the user. Because
+`parse-portal-input.js` validates against the full list, the user can still
+pick a site that isn't among the visible 10 by typing its name or id.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success (including empty result) |
+| `2` | Sign-in required |
+| `1` | Any other failure |
+
+---
+
+## `set-governance.js`
+
+Applies a governance policy and polls until the roll-out reports a terminal
+state. The POST body shape (policyValue + ToBeAdded list) is built from
+`--policyValue`, `--portalIds`, and `--portalId`.
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/set-governance.js" \
+ --policy <name> [--envId <guid>] \
+ [--policyValue All|None|Include|Exclude] \
+ [--portalIds "<id>,<id>,…"] [--portalId <guid>] \
+ [--timeoutMinutes <n>]
+```
+
+### Parameters
+
+| Flag | Required | Default | Description |
+|------|----------|---------|-------------|
+| `--policy` | Yes | — | One of the strings listed in [Supported policies](#supported-policies). |
+| `--policyValue` | No | derived | Explicit value (`All` / `None` / `Include` / `Exclude`). When omitted, defaults to `Include` if any portal ids are passed, else `All`. |
+| `--portalIds` | No | — | Comma- or whitespace-separated list of portal ids. Use for `Include` / `Exclude` scopes with multiple portals. |
+| `--portalId` | No | — | Legacy single-portal flag. Equivalent to `--portalIds <id>`. |
+| `--envId` | No | current PAC env | Target environment id. |
+| `--timeoutMinutes` | No | `15` | How long to poll before giving up. Polls every 30 seconds. |
+
+### Response (stdout)
+
+On success:
+
+```json
+{ "status": "applied", "policy": "<name>", "envId": "<guid>",
+ "portalIds": [ "<guid>", ... ], "transport": "...",
+ "attempts": <n>, "finalValue": "<state>" }
+```
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Roll-out reached a success terminal state. |
+| `2` | Sign-in required. |
+| `3` | Polling timed out — last seen status is in the stderr message. |
+| `4` | Terminal state reached, but it was a failure value. |
+| `1` | Any other failure (POST rejected, network error, etc.). |
+
+The skill orchestrator runs this script with `run_in_background: true` so the
+polling does not block the conversation. Progress lines are written to
+`stderr` ("Applying \<policy\>...") at start and at every poll attempt.
+
+The Apply invocation resolves its environment/auth context once and shares it
+across the POST, status polls, and any fallback reads. It does not silently
+reauthenticate or automatically replay the POST.
+
+Context failures and HTTP `401` stop immediately with exit `2` (sign-in
+required). HTTP `403` stops immediately with exit `1`, retaining the upstream
+error and advising the operator to check admin roles, delegated permissions,
+and access policies. These failures never enter transient retries or get
+overridden by a later status check, including when a fallback read fails.
+
+A definite HTTP `4xx`/`5xx` POST response fails immediately, retaining the
+status and error message, without recovery reads or polling. The auth-specific
+exit codes above take precedence; other HTTP errors exit `1`. Existing scope
+cannot override a rejected write, and the POST is not automatically replayed.
+The legacy uncertain-response fallback is unchanged: it compares environment
+scope only, not membership additions/removals. Full verification of uncertain
+delivery remains separate work.
+
+Polling intentionally retains the fixed 30-second delay between completed
+nonterminal checks and tolerated transient failures. Exponential backoff and
+`Retry-After` handling remain deferred; this change does not introduce them.
+
+---
+
+## `get-status.js`
+
+One-shot read of `GET /governance/status/{policy}`.
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/get-status.js" \
+ --policy <name> [--envId <guid>]
+```
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "policy": "<name>", "value": "<state>", "body": <raw> }
+```
+
+`value` is a best-effort top-level extract — either the bare body string,
+or `body.status` / `body.state` / `body.value` when the API returns an
+object. Callers can branch on `value` without re-parsing.
+
+### Exit codes
+
+Same as `get-env.js`.
+
+---
+
+## `get-env.js`
+
+Reads `GET /governance/{policy}`.
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/get-env.js" \
+ --policy <name> [--envId <guid>]
+```
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "policy": "<name>", "envId": "<guid>",
+ "value": "All"|"None"|"Include"|"Exclude", "body": <raw> }
+```
+
+The skill orchestrator renders `value` (the canonical, normalized state) in
+plain language for the user. `body` is the raw API value, left untouched on
+purpose so updates to the API contract do not require a script change — for
+env-level policies it may be an `applyTo` enum string (e.g. `AllSites`) that
+`value` has already normalized.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success |
+| `2` | Sign-in required |
+| `1` | Any other failure |
+
+---
+
+## `get-portal.js`
+
+Reads `GET /websites/{portalId}/governance/{policy}`.
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/get-portal.js" \
+ --policy <name> --portalId <guid> [--envId <guid>]
+```
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "policy": "<name>", "envId": "<guid>",
+ "portalId": "<guid>", "body": <raw> }
+```
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success |
+| `2` | Sign-in required |
+| `1` | Any other failure |
+
+---
+
+## `get-details.js`
+
+Reads `GET /governance/{policy}/details` — the policy's **env-level** per-site
+membership (inclusion/exclusion portal lists) in a **single call**, regardless of
+how many portals the environment has.
+
+### Why (kills the per-portal read loop)
+
+`get-portal.js` (`GET /websites/{portalId}/governance/{policy}`) is **per-portal**
+— one boolean per call — so reading N portals costs N cold-started calls and N
+chances at a transient "PAC not signed in". It also **404s on a dummy/non-existent
+portalId** (`Website with the given id does not exist`), so the old "call
+`get-portal.js` with `00000000-…` to fetch the env lists" trick never worked.
+`get-details.js` returns the whole membership once; combine it with `get-env.js`
+(the `All`/`None`/`Include`/`Exclude` env value) and resolve every portal's state
+**locally** via `resolvePortalStates()` (see `resolve-portal-availability.js`).
+That is **2 network calls per policy**, flat — vs `1 + N` for the loop.
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/get-details.js" \
+ --policy <name> [--envId <guid>]
+```
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "policy": "<name>", "envId": "<guid>", "transport": "gateway",
+ "includedSites": ["<portalId>", ...],
+ "excludedSites": ["<portalId>", ...],
+ "body": { "IncludedSites": ["<portalId>", ...], "ExcludedSites": null } }
+```
+
+`includedSites` / `excludedSites` are the normalized (lowercased) id arrays
+parsed from `body` by `extractLists()` — tolerant of the several field spellings
+observed across rings (`InclusionList` / `IncludedSites`, camel/Pascal, bare id
+or object). Skip this call when the env value is `All` / `None` — the lists are
+irrelevant there (every site's state is decided by the env value alone).
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success |
+| `2` | Sign-in required |
+| `1` | Any other failure |
+
+---
+
+## `resolve-portal-availability.js`
+
+Computes, for a **child** authentication policy, which portals are **available**
+to configure it on based on the live state of its **parent** policies, and which
+are **unavailable** (a required parent is Disabled). Used by the scope pickers
+(SKILL.md Phase 4.2.1 Step B.1 / Phase 4.2.2) — which render it with the default
+`--markdown` view so **every portal is listed with an explicit `Eligible`
+(Yes / No) column** (eligible first, ineligible just below with the blocking
+parent named, and a parent-disabled message when none qualify).
+
+### Availability contract
+
+The dependency tree is data-driven from
+`references/governance-mapping.json` — each policy's `availabilityDependsOn`
+array plus the top-level `policyAvailabilityDependencies` block:
+
+| Child policy | Requires (all must be Enabled) |
+|--------------|--------------------------------|
+| `EnableProtocolOpenIdConnect` | `EnableExternalAuthProviders` |
+| `EnableProtocolSAML20` | `EnableExternalAuthProviders` |
+| `EnableProtocolWsFederation` | `EnableExternalAuthProviders` |
+| `EnableProtocolOpenAuth` | `EnableExternalAuthProviders` |
+| `EnableIdpOAuthFacebook` | `EnableExternalAuthProviders`, `EnableProtocolOpenAuth` |
+| `EnableIdpOAuthGoogle` | `EnableExternalAuthProviders`, `EnableProtocolOpenAuth` |
+| `EnableIdpOAuthMicrosoft` | `EnableExternalAuthProviders`, `EnableProtocolOpenAuth` |
+
+A portal is **available** iff **every** parent in the list is Enabled on that
+portal (computed from each parent's env value + inclusion/exclusion lists via
+the Phase 4.4.3 site-state rules). Policies with no `availabilityDependsOn`
+(Maker Copilot, local login, and External Auth itself — the only pure root)
+report all portals available. Note `EnableProtocolOpenAuth` (OAuth 2.0) is
+**not** dependency-free — it is both a child of External Auth and the parent of
+the three social providers.
+
+**Fail-open posture.** Unknown parent states and unread Include/Exclude
+membership lists are recorded in each affected site's `unreadParents` and do
+**not** hide that site. Failed membership reads also appear in the top-level
+`membershipReadErrors` map as `{ "<parent>": { "statusCode", "message" } }`;
+the known parent scope is preserved rather than reinterpreted as an empty
+successful list. Both Markdown views emit a warning, and the full picker
+marks affected rows `Yes (unverified)`. Disclose this uncertainty before
+selection and final consent. Known disabled parents still block. Required
+environment-read failures remain fatal; membership HTTP 401/403 or context
+errors stop with exit 2. A documented environment-policy 404 is instead a
+known unconfigured/Disabled state, as described in Error handling below.
+
+**List-read source.** Parent inclusion/exclusion lists are read via the
+env-level **`getDetails`** op (`GET /governance/{policy}/details`), which returns
+the whole list as `{ "IncludedSites": [...], "ExcludedSites": [...] }`. Do **not**
+use `getPortal` (`GET /websites/{portalId}/governance/{policy}`) for this — that
+op is portal-scoped and returns only a single boolean for the one portal id, and
+it 404s on a dummy/non-existent id ("Website with the given id does not exist").
+The earlier dummy-all-zeros `getPortal` approach silently returned no list,
+leaving the inclusion set empty and mis-reporting an `Include` parent (enabled on
+a subset) as Disabled env-wide — so every eligible site was wrongly hidden.
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" --envId <guid> \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/resolve-portal-availability.js" \
+ --policy <childPolicy> [--envId <guid>] [--markdown] [--available-only]
+```
+
+Portal JSON is read from stdin (the script does not re-page `/websites`).
+`--portalsFile` remains a backward-compatible alternative. With
+`--markdown` (the default picker view), it prints ONE table of **every** portal
+with an `Eligible` (Yes / No) column — eligible rows (**✅ Yes**) first,
+ineligible rows (**🚫 No — blocked by &lt;parent&gt;**) directly below — and a
+single parent-disabled message in place of the table when none are eligible.
+Without `--markdown`, it prints the JSON below.
+
+**`--available-only`** (a stricter alternative view) changes the `--markdown`
+render so **only the eligible portals** are listed (the ineligible ones hidden
+entirely):
+
+- **Some available** — a table of just the eligible portals (`# | Portal Name |
+ Portal URL | Portal ID`). When only a subset qualifies, an info line follows
+ in plain "Governance setting" language: *"Showing N of M site(s) — the
+ &lt;child&gt; Governance setting can only be configured on sites where the
+ &lt;parent&gt; Governance setting is on. K site(s) are hidden because the
+ &lt;parent&gt; Governance setting is off on them, so the &lt;child&gt;
+ Governance setting can't apply there."* For a two-parent **social IdP** the
+ line names both, using **"and"** for the requirement and **"or"** for the
+ block: *"…the &lt;child&gt; Governance setting can only be configured on sites
+ where **both** the External authentication providers **and** OAuth 2.0 sign-in
+ Governance settings **are on**. K site(s) are hidden because the External
+ authentication providers **or** OAuth 2.0 sign-in Governance setting is off on
+ them, so the &lt;child&gt; Governance setting can't apply there."*
+- **None available** — no table; a single message: *"The &lt;parent&gt;
+ Governance setting is off for this environment. No sites are available to
+ configure &lt;child&gt; here — turn on the &lt;parent&gt; Governance setting
+ first, then try again."* For a two-parent **social IdP**
+ the message names both — *"The External authentication providers **or** OAuth
+ 2.0 sign-in Governance setting is off for this environment … turn on **both**
+ … Governance settings first"*. The orchestrator surfaces this and does not
+ prompt for a scope.
+
+### Response (stdout, JSON mode)
+
+```json
+{
+ "policy": "EnableIdpOAuthGoogle",
+ "dependencies": ["EnableExternalAuthProviders", "EnableProtocolOpenAuth"],
+ "available": [ { "portalId": "…", "name": "…", "url": "…" } ],
+ "unavailable": [
+ { "portalId": "…", "name": "…", "url": "…",
+ "blockingParents": ["EnableExternalAuthProviders"],
+ "blockedBy": ["External authentication providers"],
+ "unreadParents": [] }
+ ]
+}
+```
+
+### Exported helper: `resolvePortalStates(envValue, detailsBody, portals)`
+
+The batch, network-free classifier that makes the getDetails fast path work.
+Given a policy's **env value** (`get-env.js`) and its **getDetails body**
+(`get-details.js`), it resolves **every** portal's own state locally — the batch
+form of the Phase 4.4.3 site-state table — so no per-portal `get-portal.js` call
+is needed. `portals` accepts bare id strings **or** portal objects
+(`{ portalId|id|Id, name, url|websiteUrl }`); objects pass their `name`/`url`
+through. Returns `[{ portalId, state, name?, url? }]` where `state` is
+`Enabled` / `Disabled` / `Unknown`. Membership tests are case-insensitive; an
+env value that can't be canonicalized yields `Unknown` (never a guess). This is
+what the orchestrator uses in Fetch Env (4.3.1), the effective-status build
+(4.4.4), the consent-gate Current State (4.2.3), and the post-Set verify (4.2.5).
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success |
+| `2` | Sign-in required |
+| `1` | Any other failure |
+
+---
+
+## `fetch-env-status.js`
+
+The **one-shot Fetch Env status** script — the single command the skill triggers
+to answer *"what is the status of `<policy>` in `<env>`?"* (SKILL.md Phase
+4.3.1). It performs the **whole** Fetch Env in **one parallel wave** and emits a
+render-ready payload, so the orchestrator just runs it and pipes `.portals` into
+`render-portal-table.js`.
+
+### Why (folds the site-list fetch into the parallel batch)
+
+The previous Fetch Env flow was **two steps**: `list-portals.js` FIRST (a
+separate `GET /websites` round-trip), THEN `get-effective-status.js` for the
+governance reads. This script folds the site-list fetch into the **same**
+`Promise.all` as the governance reads — the `/websites` page(s) and every
+`GetEnvPolicy` + `getDetails` (for the policy and every gating parent) are all fired
+concurrently against **one** shared context/token — removing that extra serial
+round-trip. Total latency ≈ one round-trip regardless of parent count.
+
+Total reads: `1 (websites) + policies × 2` — **3** for a leaf policy, **5** for a
+protocol, **7** for a social IdP — all issued in parallel.
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/fetch-env-status.js" \
+ --policy <name> \
+ [--envId <guid>]
+```
+
+- `--policy` — any of the supported governance policy names.
+- `--envId` — optional; falls back to the current PAC env.
+
+Unlike `get-effective-status.js`, this script does **not** take `--portalsFile`
+— it fetches the site list itself as part of the batch.
+
+### Response (stdout, JSON)
+
+The `.portals` array is exactly what `render-portal-table.js` consumes, so pipe
+this straight into it:
+
+```json
+{
+ "status": "ok",
+ "policy": "EnableIdpOAuthFacebook",
+ "envId": "<guid>",
+ "envValue": "None",
+ "dependencies": ["EnableExternalAuthProviders", "EnableProtocolOpenAuth"],
+ "apiCalls": 7,
+ "portalCount": 5,
+ "effectiveEnabledCount": 0,
+ "headline": "This Governance setting is 🔴 Disabled for these Sites:",
+ "portals": [
+ { "name": "Portal_4", "url": "https://…", "portalId": "<guid>",
+ "state": false, "own": false,
+ "parents": { "EnableExternalAuthProviders": true, "EnableProtocolOpenAuth": true } }
+ ]
+}
+```
+
+- `envValue` — the **policy's own** env-level value (`All` / `None` / `Include` /
+ `Exclude`) for the plain-language env summary.
+- `state` — the **effective** boolean (own AND every parent) — the value the
+ 5-column Markdown status table renders.
+- `headline` — the pre-computed Phase 4.3.1 headline (green when at least one
+ site is effectively Enabled, red when off everywhere / zero sites).
+- `apiCalls` — `1 + policies × 2`, **all issued in parallel**.
+
+For a request that asks for the status of **multiple policies** in the same
+environment, call `fetch-env-status.js` **once per policy** and render each
+result separately. Do **not** post-process multiple policies into one compact
+matrix that drops the portal `url` / `portalId` columns; the contract is that
+each `fetch-env-status.js` result feeds one full `render-portal-table.js`
+render.
+
+Pipe `.portals` into the status render:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/fetch-env-status.js" \
+ --policy "<POLICY>" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/render-portal-table.js" --markdown --no-color
+```
+
+Fail-closed posture: a failed `getDetails` degrades to an empty membership list;
+a failed `/websites` read or `GetEnvPolicy` is fatal (cannot classify without them).
+An env with **zero sites** is not an error — `portals` is an empty array.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success (including an env with zero sites) |
+| `2` | Sign-in required |
+| `1` | Other failure |
+
+---
+
+## `get-effective-status.js`
+
+Computes the **effective** governance state of a policy for **every** portal in
+an environment in **ONE parallel batch** of reads. This is the canonical
+state-read for every SKILL.md status path — Fetch Env portal table (4.3.1),
+Fetch Site (4.4.3), the effective status for gated children (4.4.4), the post-Set
+verify (4.2.5), and the consent-gate Current State (4.2.3). It replaces the old
+sequential `get-env.js` → `get-details.js` → `resolvePortalStates` hand-issued
+loop, so the orchestrator MUST route per-site state through this script and
+**never** hand-issue `get-env.js` / `get-details.js` / `get-portal.js` per
+policy or per portal.
+
+### Why (kills the sequential per-policy reads)
+
+A gated child method is only live on a portal when the child's OWN setting **and**
+every gating parent are Enabled there. Reading that needs `GetEnvPolicy` + `getDetails`
+for the child **and** each parent — 4 calls for a protocol (child + External
+Auth), 6 for a social IdP (child + External Auth + OAuth 2.0). The previous flow
+issued those reads **sequentially** (a `for … await` loop), so a social-IdP
+status took 6 serial round-trips. Every call is independent, so this script fires
+**all** of them concurrently with a single `Promise.all` and only then assembles
+the report — collapsing 4–6 serial round-trips into one parallel wave (wall-clock
+≈ one round-trip regardless of parent count). Leaf policies with no parents
+(Maker Copilot, local login, External Auth) report their own state as the
+effective state (2 calls).
+
+### Usage
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" --envId <guid> \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/get-effective-status.js" \
+ --policy <name> [--envId <guid>]
+```
+
+- `--policy` — any of the twenty-one governance policy names.
+- stdin — `list-portals.js` output (`{ portals: [...] }` or a bare array).
+ `--portalsFile` remains a backward-compatible alternative.
+- `--envId` — optional; falls back to the current PAC env.
+
+### Response (stdout, JSON)
+
+The shape is what `render-portal-table.js` consumes directly (it reads
+`.portals`), so pipe this straight into it:
+
+```json
+{
+ "status": "ok",
+ "policy": "<name>",
+ "dependencies": ["<parent>", "..."],
+ "apiCalls": 6,
+ "effectiveEnabledCount": 2,
+ "portals": [
+ { "name": "Portal_4", "url": "https://…", "portalId": "<guid>",
+ "state": true,
+ "own": true,
+ "parents": { "EnableExternalAuthProviders": true, "EnableProtocolOpenAuth": true } }
+ ]
+}
+```
+
+- `state` — the **effective** boolean (own AND every parent) — the value the
+ 5-column Markdown status table renders.
+- `own` — the child's own setting on that portal.
+- `parents` — each gating parent's state on that portal.
+- `apiCalls` — policies × 2, **all issued in parallel**.
+
+Pipe `.portals` into the status render:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/get-effective-status.js" \
+ --policy "<POLICY>" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/render-portal-table.js" --markdown --no-color
+```
+
+Fail-closed posture: a failed `getDetails` degrades to an empty membership list;
+a failed `GetEnvPolicy` is fatal (cannot classify without the env value). A parent
+whose state can't be read makes the site's effective state `Unknown`.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success |
+| `2` | Sign-in required |
+| `1` | Other failure |
+
+---
+
+## `render-status-table.js`
+
+Renders the per-site **effective** governance-status Markdown table for a
+**gated child** policy — the child's own state plus a column for each gating
+parent, and a final **Effective Status** column. Used by the status-display
+paths (SKILL.md Phase 4.4.4, referenced from Fetch Env 4.3.1, Fetch Site 4.4.3,
+and the post-Set verify 4.2.5).
+
+### Effective-status contract
+
+A child method's own setting being Enabled is necessary but **not** sufficient —
+it is effectively Enabled on a portal only when **every** gating parent is also
+Enabled there (data-driven from `governance-mapping.json` — each child's
+`availabilityDependsOn`, and the readable `effectiveStatusRules` block):
+
+| Child policy | Parent context columns shown |
+|--------------|------------------------------|
+| `EnableProtocolOpenIdConnect` | External Auth |
+| `EnableProtocolSAML20` | External Auth |
+| `EnableProtocolWsFederation` | External Auth |
+| `EnableProtocolOpenAuth` | External Auth |
+| `EnableIdpOAuthFacebook` | External Auth, OpenAuth Protocol |
+| `EnableIdpOAuthGoogle` | External Auth, OpenAuth Protocol |
+| `EnableIdpOAuthMicrosoft` | External Auth, OpenAuth Protocol |
+
+`Effective = Enabled` iff own **and** every parent are Enabled; `Disabled` iff no
+state is Unknown and at least one is Disabled; `Unknown` otherwise (an own/parent
+state could not be read — fail visible, never claim a state on a partial read).
+Non-gated policies (Maker Copilot, local login, External Auth) have no parents —
+use the plain `render-portal-table.js` table instead.
+
+### Usage
+
+```bash
+echo '<JSON>' | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/render-status-table.js" [--no-icons]
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/render-status-table.js" --file <path>
+```
+
+### Input JSON
+
+```json
+{
+ "policy": "EnableIdpOAuthGoogle",
+ "portals": [
+ { "name": "Portal_4", "url": "https://…", "portalId": "<guid>",
+ "own": true,
+ "parents": { "EnableExternalAuthProviders": true, "EnableProtocolOpenAuth": true } }
+ ]
+}
+```
+
+`own` and each `parents` value accept `true|false|"Enabled"|"Disabled"|null`. A
+`null`/unreadable state renders `Unknown` and forces `Effective = Unknown`.
+Include the `EnableProtocolOpenAuth` parent key only for the social IdPs. The
+orchestrator assembles the live own/parent states via
+[`get-effective-status.js`](#get-effective-statusjs) — a **single parallel batch**
+that fires `GetEnvPolicy` + `getDetails` for the child and every gating parent
+concurrently and returns the effective per-portal state — **never** a sequential
+per-policy loop and **never** a per-portal `get-portal.js` loop. This helper
+itself is network-free.
+
+### Response (stdout)
+
+A GitHub-flavored Markdown table (emit un-fenced as a rendered table). Columns:
+`# | Name | URL | Site ID | <parents…> | Effective <child> Status` — parents
+first in dependency order (External Auth → OpenAuth Protocol), then a single
+net-result column. The net-result header is `Effective <statusColumnLabel>
+Status` by default, but a policy may override the whole string via
+`effectiveStatusLabel` in `governance-mapping.json` (OpenAuth Protocol →
+`Effective OpenAuth State`; Google → `Effective Google idp State`). The child's
+own state gates that column but has no column of its own.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success |
+| `1` | Could not parse the JSON input |
+
+---
+
+## `parse-portal-input.js`
+
+Parses the user's free-text portal selection in Phase 4.2.1 into a structured
+spec the orchestrator can hand to `set-governance.js`. Accepts shortcuts so
+admins don't have to paste full UUIDs for common cases.
+
+### Accepted input
+
+| User types | Maps to |
+|------------|---------|
+| `all` (case-insensitive) | `policyValue=All`, no portal list |
+| `none` | `policyValue=None`, no portal list |
+| `<id>` or `<id>, <id>, …` | `policyValue=Include`, `portalIds=[…]` |
+| `not <id>, <id>` (also `except <id>`) | `policyValue=Exclude`, `portalIds=[…]` |
+
+Separator can be commas, newlines, or both.
+After trimming surrounding whitespace, each token must be a complete UUID
+or an exact case-insensitive site name from the supplied site list. UUIDs
+embedded in prose, braces, or other extra text are not extracted. Any invalid
+token rejects the entire selection with errors and no selected IDs.
+
+Site names must match exactly one distinct site ID, case-insensitively. If
+multiple sites share a name, the parser reports ambiguity and the matching
+IDs; ask the user for an exact ID or cancel. Repeated inventory records for
+the same ID do not create ambiguity. Exact IDs remain usable when names clash.
+
+When the supplied site inventory is empty (`validIds: []` or
+`{"portals":[]}`), only `all` is accepted. Other input returns an error asking
+the user to enter `all` for environment-wide selection or cancel. This differs
+from omitting the validation list, which still permits format-only UUID
+parsing. Cancellation is handled by the orchestrator, not as a policy value.
+For Apply, preserve the enable/disable intent separately from the `all` scope.
+
+### Usage
+
+Pipe the user's reply to stdin and reference the `list-portals.js` output for
+validation:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/parse-portal-input.js" \
+ --portalsStdin --input "<USER_REPLY>"
+```
+
+Or use it programmatically:
+
+```js
+const { parsePortalInput } = require('./parse-portal-input');
+const result = parsePortalInput(userInput, { validIds: portals });
+```
+
+### Response (stdout)
+
+```json
+{
+ "policyValue": "Include",
+ "portalIds": ["3e13d603-…", "ea51fc54-…"],
+ "resolvedNames": ["Site 1", "Site 2"],
+ "errors": []
+}
+```
+
+- `policyValue` is `null` when parsing fails.
+- `resolvedNames` is populated only when `validIds` was provided as `{portalId, name}` objects.
+- `errors` lists every problem found — show them to the user and reprompt.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Parsed successfully |
+| `1` | One or more `errors` entries — orchestrator should reprompt |
+
+### When to use
+
+Called by the orchestrator inside Phase 4.2.1 of the manage-governance skill,
+after `list-portals.js` returns the portal table. Bypass it when the caller is
+non-interactive and is supplying `--policyValue` and `--portalIds` directly to
+`set-governance.js`.
+
+---
+
+## Common error catalogue
+
+| HTTP / signal | Likely cause | What the skill should do |
+|---------------|--------------|--------------------------|
+| `401` | Token expired between resolve and request. | Tell the user to re-run `az login`; the script exits 2. |
+| `403` | Signed-in user is not a tenant / env admin. | Surface the message; do not retry. |
+| `404` on `/governance/{policy}` | Policy has never been applied in this env. | Shared transport returns `ok: true`, `settingPresent: false`, and canonical `None`, retaining HTTP 404. Render as "no governance setting on record", not an explicitly configured `None`. Batched status readers list absent policies in `unconfiguredPolicies`; an absent prerequisite is Disabled and can enter parent remediation. Other routes' 404s are not normalized. |
+| `400 / "Unsupported policy"` | Policy string is misspelled or new. | Skill rejects unknown policies before the call; this should not surface unless `policies.js` is patched without the API. |
+| `409` during POST | A roll-out is already in progress. | Skip the POST, just poll the existing roll-out (future enhancement — today the script surfaces the error and stops). |
+| Timeout (exit `3`) | Roll-out exceeded `--timeoutMinutes`. | Tell the user the roll-out is still in flight; suggest running `get-status.js` later. |
diff --git a/plugins/power-pages/skills/manage-governance/references/governance-mapping.json b/plugins/power-pages/skills/manage-governance/references/governance-mapping.json
new file mode 100644
index 000000000..6e4b3abc6
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/references/governance-mapping.json
@@ -0,0 +1,586 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "governance-mapping.json",
+ "version": "6.0.0",
+ "policyModes": {
+ "uniformGovernance": [
+ {
+ "policyValue": "All",
+ "userIntent": "Enable the Governance Setting on every site in the environment.",
+ "apiBehavior": {
+ "applyTo": "All",
+ "enabled": true,
+ "inclusionList": [],
+ "exclusionList": []
+ }
+ },
+ {
+ "policyValue": "Include",
+ "userIntent": "Enable the Governance Setting only on the listed sites.",
+ "apiBehavior": {
+ "applyTo": "Include",
+ "enabled": true,
+ "siteList": ["site1", "site2"]
+ }
+ },
+ {
+ "policyValue": "None",
+ "userIntent": "Disable the Governance Setting on every site in the environment.",
+ "apiBehavior": {
+ "applyTo": "None",
+ "enabled": false,
+ "inclusionList": [],
+ "exclusionList": []
+ }
+ },
+ {
+ "policyValue": "Exclude",
+ "userIntent": "Disable the Governance Setting only on the listed sites.",
+ "apiBehavior": {
+ "applyTo": "Exclude",
+ "enabled": true,
+ "siteList": ["site1", "site2"]
+ }
+ }
+ ]
+ },
+
+ "policies": [
+ {
+ "policyName": "EnableMakerCopilotForExistingSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable Maker Copilot for existing sites",
+ "subject": "Maker Copilot",
+ "summaryLabel": "Maker Copilot rule",
+ "userShorthands": ["maker copilot", "copilot", "maker copilot for existing sites", "existing sites copilot", "MakerCopilot", "EnableMakerCopilotForExistingSites"],
+ "stateParaphrase": {
+ "Enabled": "Maker Copilot Enabled",
+ "Disabled": "Maker Copilot Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "EnableProtocolOpenIdConnect",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable the OpenID Connect protocol",
+ "subject": "OpenID Connect sign-in",
+ "summaryLabel": "OpenID Connect protocol",
+ "statusColumnLabel": "OpenID Connect",
+ "availabilityDependsOn": ["EnableExternalAuthProviders"],
+ "userShorthands": ["openid connect protocol", "oidc protocol", "enable openid connect", "enable oidc", "openid connect sign-in", "EnableProtocolOpenIdConnect", "openid connect", "oidc", "openidconnect", "openid"],
+ "stateParaphrase": {
+ "Enabled": "OpenID Connect sign-in Enabled",
+ "Disabled": "OpenID Connect sign-in Blocked"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": ["None", "Exclude"],
+ "message": "Disabling this signs out any users currently authenticated via OpenID Connect on the affected sites and blocks that sign-in method until it's re-enabled."
+ }
+ },
+ {
+ "policyName": "EnableProtocolSAML20",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable the SAML 2.0 protocol",
+ "subject": "SAML 2.0 sign-in",
+ "summaryLabel": "SAML 2.0 protocol",
+ "statusColumnLabel": "SAML 2.0",
+ "availabilityDependsOn": ["EnableExternalAuthProviders"],
+ "userShorthands": ["saml 2.0 protocol", "saml protocol", "saml20 protocol", "enable saml", "enable saml 2.0", "EnableProtocolSAML20", "saml", "saml 2.0", "saml20", "saml2", "saml2.0"],
+ "stateParaphrase": {
+ "Enabled": "SAML 2.0 sign-in Enabled",
+ "Disabled": "SAML 2.0 sign-in Blocked"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": ["None", "Exclude"],
+ "message": "Disabling this signs out any users currently authenticated via SAML 2.0 on the affected sites and blocks that sign-in method until it's re-enabled."
+ }
+ },
+ {
+ "policyName": "EnableProtocolWsFederation",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable the WS-Federation protocol",
+ "subject": "WS-Federation sign-in",
+ "summaryLabel": "WS-Federation protocol",
+ "statusColumnLabel": "WS-Federation",
+ "availabilityDependsOn": ["EnableExternalAuthProviders"],
+ "userShorthands": ["ws-federation", "wsfederation", "ws federation", "wsfed", "enable ws-federation", "ws-fed", "EnableProtocolWsFederation"],
+ "stateParaphrase": {
+ "Enabled": "WS-Federation protocol sign-in Enabled",
+ "Disabled": "WS-Federation protocol sign-in Blocked"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": ["None", "Exclude"],
+ "message": "Disabling this signs out any users currently authenticated via WS-Federation on the affected sites and blocks that sign-in method until it's re-enabled."
+ }
+ },
+ {
+ "policyName": "EnableProtocolOpenAuth",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable the OAuth 2.0 protocol",
+ "subject": "OAuth 2.0 sign-in",
+ "summaryLabel": "OAuth 2.0 protocol",
+ "statusColumnLabel": "OpenAuth Protocol",
+ "effectiveStatusLabel": "Effective OpenAuth State",
+ "availabilityDependsOn": ["EnableExternalAuthProviders"],
+ "userShorthands": ["openauth", "open auth", "oauth 2.0 protocol", "oauth protocol", "openauth protocol", "enable openauth", "oauth2", "oauth 2.0", "EnableProtocolOpenAuth"],
+ "stateParaphrase": {
+ "Enabled": "OAuth 2.0 sign-in Enabled",
+ "Disabled": "OAuth 2.0 sign-in Blocked"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": ["None", "Exclude"],
+ "message": "Disabling this setting signs out all users currently authenticated with OAuth 2.0 on the affected sites and prevents OAuth 2.0 sign-in until it is re-enabled."
+ },
+ "cascadeOnDisable": {
+ "heading": "Disabling OAuth 2.0 protocol will disable the following identity providers:",
+ "items": ["Facebook", "Google", "Microsoft"]
+ },
+ "cascadeOnEnable": {
+ "heading": "Enabling OAuth 2.0 protocol allows Social-based sign-in. Each identity provider must also be enabled individually through its corresponding governance setting:", "items": [
+ { "label": "Facebook", "note": "Controlled by the Facebook governance setting." },
+ { "label": "Google", "note": "Controlled by the Google governance setting." },
+ { "label": "Microsoft", "note": "Controlled by the Microsoft governance setting." }
+ ]
+ }
+ },
+ {
+ "policyName": "EnableIdpOAuthFacebook",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable Facebook sign-in",
+ "subject": "Facebook sign-in",
+ "summaryLabel": "Facebook sign-in provider",
+ "statusColumnLabel": "Facebook",
+ "availabilityDependsOn": ["EnableExternalAuthProviders", "EnableProtocolOpenAuth"],
+ "userShorthands": ["facebook", "facebook login", "facebook sign-in", "facebook oauth", "facebook idp", "enable facebook", "fb", "EnableIdpOAuthFacebook"],
+ "stateParaphrase": {
+ "Enabled": "Facebook sign-in Enabled",
+ "Disabled": "Facebook sign-in Blocked"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": ["None", "Exclude"],
+ "message": "Disabling this signs out any users currently authenticated with Facebook on the affected sites and blocks that sign-in method until it's re-enabled."
+ }
+ },
+ {
+ "policyName": "EnableIdpOAuthGoogle",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable Google sign-in",
+ "subject": "Google sign-in",
+ "summaryLabel": "Google sign-in provider",
+ "statusColumnLabel": "Google",
+ "effectiveStatusLabel": "Effective Google idp State",
+ "availabilityDependsOn": ["EnableExternalAuthProviders", "EnableProtocolOpenAuth"],
+ "userShorthands": ["google", "google login", "google sign-in", "google oauth", "google idp", "enable google", "gmail", "EnableIdpOAuthGoogle"],
+ "stateParaphrase": {
+ "Enabled": "Google sign-in Enabled",
+ "Disabled": "Google sign-in Blocked"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": ["None", "Exclude"],
+ "message": "Disabling this signs out any users currently authenticated with Google on the affected sites and blocks that sign-in method until it's re-enabled."
+ }
+ },
+ {
+ "policyName": "EnableIdpOAuthMicrosoft",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable Microsoft sign-in",
+ "subject": "Microsoft sign-in",
+ "summaryLabel": "Microsoft sign-in provider",
+ "statusColumnLabel": "Microsoft",
+ "availabilityDependsOn": ["EnableExternalAuthProviders", "EnableProtocolOpenAuth"],
+ "userShorthands": ["microsoft", "microsoft account", "microsoft login", "microsoft sign-in", "microsoft oauth", "microsoft idp", "enable microsoft", "msa", "EnableIdpOAuthMicrosoft"],
+ "stateParaphrase": {
+ "Enabled": "Microsoft sign-in Enabled",
+ "Disabled": "Microsoft sign-in Blocked"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": ["None", "Exclude"],
+ "message": "Disabling this signs out any users currently authenticated with a Microsoft account on the affected sites and blocks that sign-in method until it's re-enabled."
+ }
+ },
+ {
+ "policyName": "EnableAuthenticationLocalLogin",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable local login",
+ "subject": "Local (username & password) sign-in",
+ "summaryLabel": "Local login setting",
+ "userShorthands": ["local login", "local authentication", "local sign-in", "username and password", "username/password login", "enable local login", "password login", "EnableAuthenticationLocalLogin"],
+ "stateParaphrase": {
+ "Enabled": "Local sign-in Enabled",
+ "Disabled": "Local sign-in Blocked"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": ["None", "Exclude"],
+ "message": "Disabling this blocks username & password sign-in on the affected sites; users who rely on local accounts won't be able to sign in until it's re-enabled."
+ }
+ },
+ {
+ "policyName": "EnableExternalAuthProviders",
+ "policyMode": "uniformGovernance",
+ "displayName": "Enable external authentication providers",
+ "subject": "External authentication providers",
+ "summaryLabel": "External auth providers setting",
+ "statusColumnLabel": "External Auth",
+ "userShorthands": ["external auth providers", "external authentication providers", "external identity providers", "external providers", "enable external providers", "external idps", "external idp", "third-party identity providers", "third-party providers", "EnableExternalAuthProviders"],
+ "stateParaphrase": {
+ "Enabled": "External providers Enabled",
+ "Disabled": "External providers Blocked"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": ["None", "Exclude"],
+ "message": "Disabling this turns off all external (social / federated) identity providers on the affected sites; users who sign in through them will be signed out until it's re-enabled."
+ },
+ "cascadeOnDisable": {
+ "heading": "Disabling external authentication providers will disable these sign-in methods:",
+ "items": [
+ "Authentication Using OpenID Connect (OIDC) Protocol",
+ "Authentication Using SAML 2.0 Protocol",
+ {
+ "Authentication Using OAuth 2.0 Protocol": [
+ "Facebook Authentication",
+ "Google Authentication",
+ "Microsoft Authentication"
+ ]
+ },
+ "Authentication Using WS-Federation Protocol"
+ ]
+ },
+ "cascadeOnEnable": {
+ "heading": "Enabling external authentication providers makes these sign-in methods available:",
+ "items": [
+ "Authentication Using OpenID Connect (OIDC) Protocol",
+ "Authentication Using SAML 2.0 Protocol",
+ {
+ "Authentication Using OAuth 2.0 Protocol": [
+ "Facebook Authentication",
+ "Google Authentication",
+ "Microsoft Authentication"
+ ]
+ },
+ "Authentication Using WS-Federation Protocol"
+ ],
+ "footer": "Enabling the External Authentication policy restores support for these authentication methods. Each authentication provider must also be enabled and configured."
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowMakerCopilotsForNewSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow Maker Copilots for new sites",
+ "subject": "Maker Copilot for new sites",
+ "summaryLabel": "Maker Copilot (new sites) setting",
+ "userShorthands": ["maker copilots for new sites", "maker copilot for new sites", "new sites copilot", "maker copilot new sites", "new site copilot", "PowerPages_AllowMakerCopilotsForNewSites"],
+ "stateParaphrase": {
+ "Enabled": "Maker Copilot for new sites Enabled",
+ "Disabled": "Maker Copilot for new sites Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowMakerCopilotsForExistingSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow Maker Copilots for existing sites",
+ "subject": "Maker Copilot for existing sites",
+ "summaryLabel": "Maker Copilot (existing sites) setting",
+ "userShorthands": ["maker copilots for existing sites", "allow maker copilots for existing sites", "existing sites maker copilot", "maker copilot existing sites allow", "PowerPages_AllowMakerCopilotsForExistingSites"],
+ "stateParaphrase": {
+ "Enabled": "Maker Copilot for existing sites Enabled",
+ "Disabled": "Maker Copilot for existing sites Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowProDevCopilotsForSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow pro-dev Copilots for sites",
+ "subject": "Pro-dev Copilot for sites",
+ "summaryLabel": "Pro-dev Copilot (sites) setting",
+ "userShorthands": ["pro dev copilot for sites", "pro-dev copilot for sites", "prodev copilot for sites", "prodev copilot sites", "professional developer copilot for sites", "pro dev copilot sites", "PowerPages_AllowProDevCopilotsForSites"],
+ "stateParaphrase": {
+ "Enabled": "Pro-dev Copilot for sites Enabled",
+ "Disabled": "Pro-dev Copilot for sites Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowSiteCopilotForSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow site Copilot for sites",
+ "subject": "Site Copilot",
+ "summaryLabel": "Site Copilot setting",
+ "userShorthands": ["site copilot", "site copilot for sites", "sites copilot", "portal copilot", "PowerPages_AllowSiteCopilotForSites"],
+ "stateParaphrase": {
+ "Enabled": "Site Copilot Enabled",
+ "Disabled": "Site Copilot Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowSearchSummaryCopilotForSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow search summary Copilot for sites",
+ "subject": "Search summary Copilot",
+ "summaryLabel": "Search summary Copilot setting",
+ "userShorthands": ["search summary copilot", "search summary", "search summarization copilot", "search summary copilot for sites", "PowerPages_AllowSearchSummaryCopilotForSites"],
+ "stateParaphrase": {
+ "Enabled": "Search summary Copilot Enabled",
+ "Disabled": "Search summary Copilot Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowListSummaryCopilotForSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow list summary Copilot for sites",
+ "subject": "List summary Copilot",
+ "summaryLabel": "List summary Copilot setting",
+ "userShorthands": ["list summary copilot", "list summary", "list summarization copilot", "list summary copilot for sites", "PowerPages_AllowListSummaryCopilotForSites"],
+ "stateParaphrase": {
+ "Enabled": "List summary Copilot Enabled",
+ "Disabled": "List summary Copilot Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowIntelligentFormsCopilotForSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow intelligent forms Copilot for sites",
+ "subject": "Intelligent forms Copilot",
+ "summaryLabel": "Intelligent forms Copilot setting",
+ "userShorthands": ["intelligent forms copilot", "intelligent forms", "forms copilot", "intelligent forms copilot for sites", "smart forms copilot", "PowerPages_AllowIntelligentFormsCopilotForSites"],
+ "stateParaphrase": {
+ "Enabled": "Intelligent forms Copilot Enabled",
+ "Disabled": "Intelligent forms Copilot Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowSummarizationAPICopilotForSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow summarization API Copilot for sites",
+ "subject": "Summarization API Copilot",
+ "summaryLabel": "Summarization API Copilot setting",
+ "userShorthands": ["summarization api copilot", "summarization api", "summarization copilot", "summarisation api copilot", "summarization api copilot for sites", "PowerPages_AllowSummarizationAPICopilotForSites"],
+ "stateParaphrase": {
+ "Enabled": "Summarization API Copilot Enabled",
+ "Disabled": "Summarization API Copilot Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowProDevCopilotsForEnvironment",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow pro-dev Copilots for the environment",
+ "subject": "Pro-dev Copilot for the environment",
+ "summaryLabel": "Pro-dev Copilot (environment) setting",
+ "userShorthands": ["pro dev copilot for environment", "pro-dev copilot for environment", "prodev copilot for environment", "prodev copilot environment", "pro dev copilot environment", "professional developer copilot for environment", "PowerPages_AllowProDevCopilotsForEnvironment"],
+ "stateParaphrase": {
+ "Enabled": "Pro-dev Copilot for the environment Enabled",
+ "Disabled": "Pro-dev Copilot for the environment Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_AllowNonProdPublicSites",
+ "policyMode": "uniformGovernance",
+ "displayName": "Allow non-production public sites",
+ "subject": "Non-production public sites",
+ "summaryLabel": "Non-production public sites setting",
+ "userShorthands": ["non-prod public sites", "non prod public sites", "nonprod public sites", "non production public sites", "public non-prod sites", "allow non-prod public sites", "PowerPages_AllowNonProdPublicSites"],
+ "stateParaphrase": {
+ "Enabled": "Non-production public sites Enabled",
+ "Disabled": "Non-production public sites Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ },
+ {
+ "policyName": "PowerPages_DisableExtSvcCallsFromServerLogic",
+ "policyMode": "uniformGovernance",
+ "displayName": "Disable external service calls from server-side logic",
+ "subject": "External service calls from server-side logic",
+ "summaryLabel": "External service calls from server logic setting",
+ "userShorthands": ["external service calls from server logic", "disable external service calls", "ext svc calls from server logic", "external service calls server logic", "server logic external calls", "disable ext svc calls from server logic", "PowerPages_DisableExtSvcCallsFromServerLogic"],
+ "stateParaphrase": {
+ "Enabled": "External service calls from server-side logic Enabled",
+ "Disabled": "External service calls from server-side logic Disabled"
+ },
+ "sideEffectCallout": {
+ "policyValueTriggers": [],
+ "message": ""
+ }
+ }
+ ],
+
+ "policyAvailabilityDependencies": {
+ "description": "Parent/child availability model for Power Pages authentication governance. A portal (or the whole environment) is only ELIGIBLE ('available') for a CHILD policy's governance setting when EVERY parent listed in that child's `availabilityDependsOn` is Enabled for that portal/env. When a gating parent is Disabled for a portal/env, the portal is UNAVAILABLE for the child policy: it cannot be enabled or disabled there and must be shown in the picker BELOW the available portals with the blocking parent named. This mirrors the product rule that a specific sign-in method can only be governed on a portal where its umbrella provider is turned on. `EnableExternalAuthProviders` is the root parent (the Main Flag) of the four sign-in protocols; `EnableProtocolOpenAuth` (OAuth 2.0) is in turn the parent of the three OAuth-based social identity providers. Each dependent policy carries the same list in its own `availabilityDependsOn` field — the per-policy field is what the resolver reads; this block is the readable overview / single source of truth for the tree shape.",
+ "parents": {
+ "EnableExternalAuthProviders": [
+ "EnableProtocolOpenIdConnect",
+ "EnableProtocolSAML20",
+ "EnableProtocolWsFederation",
+ "EnableProtocolOpenAuth"
+ ],
+ "EnableProtocolOpenAuth": [
+ "EnableIdpOAuthFacebook",
+ "EnableIdpOAuthGoogle",
+ "EnableIdpOAuthMicrosoft"
+ ]
+ },
+ "unknownParentPosture": "fail-open",
+ "unknownParentPostureNote": "When a parent's live state cannot be read (network/parse failure), the portal is treated as AVAILABLE (fail-open) so a transient read error never hides portals from the admin. The resolver annotates such portals so the orchestrator can note the unread parent rather than silently blocking."
+ },
+
+ "effectiveStatusRules": {
+ "description": "How the EFFECTIVE (real, end-user-observable) status of a child sign-in method is computed for the status-display paths (Fetch Env portal table, Fetch Site, and the post-Set verify table). A child method's own governance setting being Enabled is necessary but NOT sufficient: the method only actually works on a portal when EVERY gating parent (the transitive `availabilityDependsOn` chain) is also Enabled on that portal. This mirrors the product runtime — e.g. Google sign-in is dark on a portal where OAuth 2.0 or External Auth is off even if the Google setting itself is Enabled, because the umbrella provider gates it. The status tables therefore show the child's own state PLUS a column for each parent, and an Effective column = own AND all parents. The parent columns to display are exactly the child's `availabilityDependsOn` list, in order (External Auth first, then OAuth 2.0 for social IdPs).",
+ "effectiveRule": "effective = Enabled iff (ownState == Enabled) AND every parent in availabilityDependsOn is Enabled for that portal; Disabled iff no state is Unknown and at least one of {own, ...parents} is Disabled; otherwise Unknown (a parent or own state could not be read).",
+ "parentColumnsByPolicy": {
+ "EnableProtocolOpenIdConnect": ["EnableExternalAuthProviders"],
+ "EnableProtocolSAML20": ["EnableExternalAuthProviders"],
+ "EnableProtocolWsFederation": ["EnableExternalAuthProviders"],
+ "EnableProtocolOpenAuth": ["EnableExternalAuthProviders"],
+ "EnableIdpOAuthFacebook": ["EnableExternalAuthProviders", "EnableProtocolOpenAuth"],
+ "EnableIdpOAuthGoogle": ["EnableExternalAuthProviders", "EnableProtocolOpenAuth"],
+ "EnableIdpOAuthMicrosoft": ["EnableExternalAuthProviders", "EnableProtocolOpenAuth"]
+ },
+ "note": "`parentColumnsByPolicy` is the readable overview; the renderer reads each child's own `availabilityDependsOn` field (authoritative). Policies absent here (Maker Copilot, local login, and External Auth itself as a root) have no parents — their effective status equals their own state and no parent columns render."
+ },
+
+ "readValueAliases": {
+ "AllSites": "All",
+ "IncludeSites": "Include",
+ "ExcludeSites": "Exclude",
+ "IncludedSites": "Include",
+ "AllSitesExceptExcluded": "Exclude",
+ "ExcludedSites": "Exclude",
+ "None": "None"
+ },
+
+ "stateColors": {
+ "description": "Color convention for rendering Governance Setting state in summary/verification/state tables. The Status column is wrapped in ANSI SGR codes so it renders green/red in an ANSI-capable terminal; the emoji marker is kept as a fallback indicator for surfaces that strip ANSI (e.g. some chat renderers). Wrap the whole Status cell as `<ansi><emoji> <label> (<paraphrase>)<reset>`.",
+ "ansi": { "green": "\u001b[32m", "red": "\u001b[31m", "reset": "\u001b[0m" },
+ "Enabled": { "color": "green", "emoji": "🟢", "ansi": "\u001b[32m" },
+ "Disabled": { "color": "red", "emoji": "🔴", "ansi": "\u001b[31m" },
+ "Unavailable": { "color": "gray", "emoji": "⚪", "ansi": "\u001b[90m" }
+ },
+
+ "intentToPolicyValue": [
+ {
+ "intentDirection": "enable",
+ "scope": "all",
+ "policyValue": "All",
+ "toBeAdded": "empty",
+ "scopeQualifiers": ["for all portals", "everywhere", "across the env", "for live portals", "for running portals"]
+ },
+ {
+ "intentDirection": "enable",
+ "scope": "specific",
+ "policyValue": "Include",
+ "toBeAdded": "pickedIds",
+ "scopeQualifiers": ["only X", "for X and Y", "specific sites", "just X", "for X"]
+ },
+ {
+ "intentDirection": "disable",
+ "scope": "all",
+ "policyValue": "None",
+ "toBeAdded": "empty",
+ "scopeQualifiers": ["for all portals", "everywhere", "across the env", "for no portals", "clear the policy"]
+ },
+ {
+ "intentDirection": "disable",
+ "scope": "specific",
+ "policyValue": "Exclude",
+ "toBeAdded": "pickedIds",
+ "scopeQualifiers": ["only X", "for X and Y", "specific sites"]
+ }
+ ],
+
+ "siteStateRules": [
+ { "envBody": "All", "inInclusionList": null, "inExclusionList": null, "siteState": "Enabled" },
+ { "envBody": "None", "inInclusionList": null, "inExclusionList": null, "siteState": "Disabled" },
+ { "envBody": "Include", "inInclusionList": true, "inExclusionList": null, "siteState": "Enabled" },
+ { "envBody": "Include", "inInclusionList": false, "inExclusionList": null, "siteState": "Disabled" },
+ { "envBody": "Exclude", "inInclusionList": null, "inExclusionList": true, "siteState": "Disabled" },
+ { "envBody": "Exclude", "inInclusionList": null, "inExclusionList": false, "siteState": "Enabled" }
+ ],
+
+ "ambiguousPhrasings": [
+ {
+ "phrase": "everywhere except X",
+ "rephrasePrompt": "Please re-phrase as either 'Enable for X' or 'Disable for X' so the uniform mapping applies cleanly."
+ },
+ {
+ "phrase": "all except X",
+ "rephrasePrompt": "Please re-phrase as either 'Enable for X' or 'Disable for X'."
+ }
+ ],
+
+ "effectLineTemplates": [
+ { "intentDirection": "enable", "scope": "all", "template": "{Subject} will be enabled on all sites in {EnvDisplay}." },
+ { "intentDirection": "enable", "scope": "specific", "template": "{Subject} will be enabled on the listed sites in {EnvDisplay}: {SiteNameList}." },
+ { "intentDirection": "disable", "scope": "all", "template": "{Subject} will be disabled on all sites in {EnvDisplay}." },
+ { "intentDirection": "disable", "scope": "specific", "template": "{Subject} will be disabled on the listed sites in {EnvDisplay}: {SiteNameList}." }
+ ],
+
+ "scopePicker": [
+ {
+ "label": "All portals in environment",
+ "description": "Apply the chosen Enable/Disable action to every site in the env. Clears any inclusion / exclusion list.",
+ "policyValueForEnable": "All",
+ "policyValueForDisable": "None",
+ "toBeAdded": "empty"
+ },
+ {
+ "label": "Specific portals",
+ "description": "I'll list the sites; you reply with the names or IDs (comma-separated).",
+ "policyValueForEnable": "Include",
+ "policyValueForDisable": "Exclude",
+ "toBeAdded": "pickedIds"
+ }
+ ],
+
+ "consentGate": {
+ "requiredRows": ["Action", "Environment", "Scope", "After-state site table", "API mapping", "Effect"],
+ "neverShowToUser": ["policyValue", "InclusionList", "ExclusionList", "Include", "Exclude"],
+ "rules": [
+ "Rows where the per-site state changes MUST be marked '<- CHANGED'.",
+ "When the env state transition would flip sites that aren't the user's target, surface a 'Side effect:' line with the count and the affected sites."
+ ]
+ },
+
+ "uiConstants": {
+ "envList": { "columns": ["#", "Environment Name", "Environment ID"], "excludedFields": ["envUrl", "type", "region", "domain"] },
+ "siteList": { "columns": ["#", "Name", "URL", "Portal ID"] }
+ }
+}
diff --git a/plugins/power-pages/skills/manage-governance/references/selection.md b/plugins/power-pages/skills/manage-governance/references/selection.md
new file mode 100644
index 000000000..02886d10a
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/references/selection.md
@@ -0,0 +1,181 @@
+# Intent and selection procedures
+
+Required for SKILL.md Phases 2.1, 2.2, 4.1, and 4.2.2. Script paths below
+are under `${PLUGIN_ROOT}/skills/manage-governance/scripts/`.
+
+## Intent resolution
+
+Parse the free-text request into these fields:
+
+| Field | Values / meaning |
+|-------|------------------|
+| `intent` | `apply`, `fetchEnv`, or `fetchSite` |
+| `policy`, `policyDisplayName` | Exact supported name and mapping-owned display name |
+| `intentDirection` | `enable`, `disable`, or `view` |
+| `envId`, `envDisplayName` | Chosen environment ID/name |
+| `scope` | Canonical `All`, `None`, `Include`, `Exclude`, or unresolved |
+| `siteIds`, `siteNames` | Resolved ID/name arrays |
+| `confidence`, `ambiguities` | Confidence and unresolved interpretation questions |
+
+Read `governance-mapping.json`: use each policy's `userShorthands`, `subject`,
+and display metadata. "OpenID Connect"/"OIDC" and "SAML" select their protocol
+toggles; do not use removed legacy authentication block rules. "Block" means
+disable the governance setting, not an inversion based on its internal name.
+
+Resolve direction plus scope through `intentToPolicyValue` and
+`policyValueSemantics`, uniformly across policies. Scope qualifiers such as
+"all sites", "across the environment", "live sites", or "running sites" mean
+every site in that environment, not a lifecycle-state filter. Read
+`ambiguousPhrasings`: ask users to restate "everywhere except X" as enable or
+disable for X; do not auto-invert.
+
+Ask only for missing/ambiguous policy, operation, direction, environment, scope, or site.
+Reject unsupported policies explicitly and suggest mapping-owned examples.
+An unknown environment/site is an error to surface and reprompt, not a reason
+to pick a default silently. A clear initial intent avoids redundant questions
+about those fields. A supplied environment must pass fresh validation below;
+it does not bypass the visible site/scope exchange, eligibility, or consent.
+
+## Environment picker
+
+For every new request/operation, including each loop iteration, fetch the
+complete fresh environment inventory:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-envs.js"
+```
+
+### Supplied environment name or ID
+
+Resolve the supplied value against that fresh inventory before showing a
+picker. Trim surrounding whitespace and compare IDs and display names
+case-insensitively, using **exact matches only** for automatic resolution.
+
+- **Exact environment ID:** accept only an ID present in the fresh inventory.
+- **Unique exact environment name:** accept only when exactly one environment
+ has that display name.
+- **Duplicate exact names, conflicting name and ID, or only partial/fuzzy
+ matches:** explain the ambiguity and ask the user to choose explicitly.
+ Never auto-select a fuzzy match or prefer one conflicting identifier.
+- **Unknown name or ID:** report that it was not found in the accessible
+ environment inventory, then ask for a valid selection. Never silently fall
+ back to PAC's environment, the recent environment, or a default.
+
+For a single unambiguous exact match, say "Using <display name> (<envId>)"
+in the assistant message, persist the resolved values, and continue directly
+to site/scope selection. **Do not show the environment picker or ask the user
+to select or confirm the same environment again.** This applies to Apply,
+Fetch Env, Fetch Site, and explicit targets supplied in loop requests.
+An explicitly resolved environment is not consent to a governance write;
+the impact summary and **Apply now / Cancel** gate remain mandatory.
+
+### Missing or unresolved environment
+
+If no environment was supplied, or resolution above requires user input,
+pass the fresh inventory JSON to `render-env-table.js` via stdin with
+`--markdown [--current "<RECENT_ENV_ID>"]`. Do not fetch the list again just
+to render it; reuse only this operation's fresh result, never a prior request's
+inventory.
+
+Emit the **complete fresh output verbatim as an unfenced Markdown table**,
+with every row, in an **assistant message before the selection form**. Never filter
+environments by policy eligibility, truncate them, collapse to a default row,
+insert ellipses, or refer back to a previous table. If the user cannot see it,
+re-run and re-display it. Do not use `--envsFile`, an earlier response, an
+in-memory cache, a TTL, or `governance-envs.json`.
+
+With no recent environment, omit `--current`; the renderer flags `type: Default`
+without another PAC call. Otherwise flag the recent ID. The flag is only a
+suggestion: require explicit `keep`, row number, environment name, or ID.
+Never auto-proceed on an empty reply or say "press Enter".
+
+After displaying the table, use the question tool with a short plain-text
+message: "Reply 'keep' to continue with <flagged name>, or a row number,
+environment name, or ID to switch. Reply 'cancel' to stop." Collect a free-text
+environment value, not an option menu. Do not put the environment table in
+the form's message, question, or field/option descriptions.
+Resolve the reply against this fresh list using the same exact-match rules,
+or its displayed row number; clarify ambiguous/partial/fuzzy matches rather
+than guessing. `keep` explicitly selects the flagged environment.
+Cancel makes no governance change.
+
+### Continue with the resolved environment
+
+Persist `<ENV_ID>`, `<ENV_DISPLAY>`, and `<RECENT_ENV>` after an exact supplied
+match or a valid picker reply.
+Immediately show the site picker below, then take the scope/site reply before
+any Apply summary or status operation. This applies to Apply, Fetch Env,
+and Fetch Site; do not skip it because the environment or sites were named
+in the original request.
+
+## Site picker and parser
+
+Fetch sites for the chosen environment:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" --envId "<ENV_ID>"
+```
+
+Show a table containing site name, URL, and site ID; retain row numbers for
+selection. For a **plain picker**, show all sites when there are at most 10.
+Above 10, use `orderPortalsForDisplay()` from `list-portals.js`: Production
+first, then `StateConfigured`, then oldest `createdOn`. Say "Showing 10 of
+<total> - type any site name or ID (including ones not listed), or 'all'."
+The parser always validates against the **full** list, never only visible rows.
+This cap applies neither to environments nor to final status output.
+
+Emit Markdown tables in an **assistant message**, unfenced with a blank line
+before and after them. Preserve each complete row on one physical line,
+including long URLs and IDs; do not manually wrap cells or paste a table as
+quoted/code-formatted text. The same display rule applies to the eligibility
+view below. Tool output alone does not display the table to the user.
+
+For a **child-policy Apply**, replace the plain table with the resolver's
+eligibility view from [apply.md](apply.md#eligibility-hard-gate): all sites,
+eligible first, blocked sites immediately below with reasons. Do not apply
+the plain-picker 10-row cap to that view. Reads do not filter sites by
+eligibility; an effectively disabled site is still a status result.
+
+After displaying the table, use the question tool with a short plain-text
+message requesting `all` for every eligible site or comma-separated names/IDs
+for specific sites, plus `cancel`. Collect a free-text scope value, not an
+option menu. Do not put the site/eligibility table or eligibility explanation
+in the form's message, question, or field/option descriptions. Send the table
+and any eligibility explanation before calling the tool in the same turn.
+Use the known
+enable/disable verb for Apply; map the reply with the JSON intent rules.
+Fetch Env uses `all`; a request to read one named site routes to Fetch Site.
+Fetch Site must resolve exactly one site, not `all` or multiple sites.
+
+If there are zero sites, say so explicitly and skip the empty picker table.
+For Apply, ask: "This environment has no sites. Enter all for environment-wide
+site selection, or cancel." Accept only `all` as the site-selection value;
+do not offer specific names/IDs, exclusions, or `none`. Do not silently choose
+`all`. Use the existing enable/disable intent mapping for the policy value:
+the user's `all` selects the environment-wide scope, not the action direction.
+Continue through the normal impact summary and explicit Apply now / Cancel
+approval; an empty inventory does not authorize a POST. Fetch Site stops, and
+Fetch Env may still report its empty environment result (zero sites is not an
+API failure).
+
+Resolve site input with:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/parse-portal-input.js" \
+ --portalsStdin --input "<USER_INPUT>"
+```
+
+The output has `policyValue`, `portalIds`, `resolvedNames`, and `errors`.
+When scope is already resolved, ignore the parser's `policyValue`; use only
+IDs/names. Surface every error and reprompt.
+
+When a name is ambiguous, display every matching site's name, URL, and site ID
+from the full inventory in an assistant message, then ask for the exact site
+ID or cancel using a short plain-text form. Never choose the first or last
+match automatically. Resolve the reply through the same parser and do not
+retain a partial selection from the failed input.
+
+Persist `<PORTAL_IDS>` and
+`<PORTAL_NAMES_LIST>` for Apply, or `<PORTAL_ID>` / `<PORTAL_NAME>` for Fetch
+Site. Use `/websites` IDs throughout, never Dataverse record IDs.
diff --git a/plugins/power-pages/skills/manage-governance/references/status.md b/plugins/power-pages/skills/manage-governance/references/status.md
new file mode 100644
index 000000000..047102fd1
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/references/status.md
@@ -0,0 +1,129 @@
+# Read, verification, and output procedures
+
+Required for SKILL.md Phases 4.2.5, 4.3, 4.4, and 4.5.
+Script flags, response fields, and error codes are defined in `commands.md`.
+
+## Effective-state and output contract
+
+Use helper-computed `state` directly. For a gated policy it is **own AND every
+gating parent**; for an independent policy it equals own state. Dependencies
+come from the mapping, not a hand-maintained policy list. Parent `own`/`parents`
+fields can explain a disabled state in prose, never additional table columns.
+
+Effective-status reads fail closed for unread parents; details failures degrade
+to empty membership. A failed required environment read is fatal; Fetch Env
+also treats a failed site-list read as fatal. Surface failures/uncertainty
+explicitly, and stop for sign-in errors (exit `2`). Do not substitute a
+success-shaped result. Zero sites is not a failed API call.
+
+A 404 specifically from `GET /governance/{policy}` is the documented
+unconfigured-policy state, not an unread-parent failure. The shared transport
+marks it `settingPresent: false` and classifies its scope as `None` (Disabled).
+For `get-env.js`, display its "No governance setting on record" message.
+For batched reads, disclose every entry in `unconfiguredPolicies` in prose
+before the table, including missing parent settings. Do not describe these
+as explicitly configured `None` policies. Other 404s remain errors.
+
+Every Fetch Env, Fetch Site, and post-Apply status result uses:
+
+```bash
+... | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/render-portal-table.js" --markdown --no-color
+```
+
+Emit **all stdout verbatim as an unfenced Markdown table**, in the delivered
+response itself, not merely tool output. Leave a blank line before and after
+the table. Keep each row on one physical line: do not insert hard line breaks
+into URLs, IDs, or state cells to fit a terminal width. Exactly five columns:
+`# | Name | URL | Site ID | State`. Keep icons on (Enabled/Disabled markers).
+Never truncate rows, reorder/rename/drop/add columns, add parent/Effective
+columns or paraphrases inside cells, insert ellipses, hand-build a recap,
+switch to a Unicode/ASCII box or ANSI rendering, or use `render-status-table.js` instead.
+Brevity preferences never override full delivery.
+
+If requesting follow-up input, display the status table in an assistant
+message before calling the question tool. Never embed the table in the
+form's message, question, or field/option descriptions; those can show
+Markdown literally rather than render it.
+
+Use mapping-owned state paraphrases and scope labels only in surrounding prose.
+The fixed helper output takes precedence over legacy alternative examples.
+
+For multiple requested policies, run the appropriate read once **per policy in
+user order** and emit each policy's complete independent result. Never replace
+them with a condensed cross-policy matrix.
+
+## Fetch Env
+
+After the shared environment/site selection, use `fetch-env-status.js` as the
+**single batched reader**:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/fetch-env-status.js" \
+ --policy "<POLICY>" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/render-portal-table.js" --markdown --no-color
+```
+
+It fetches the site list and environment/membership for the policy and its
+parents concurrently with shared context. Do not substitute a sequential
+`list-portals.js | get-effective-status.js` status read or preliminary
+standalone `get-env.js`/`get-details.js`/`get-portal.js` calls.
+The earlier picker does not replace this fresh batched status read.
+
+Use returned `headline` and `effectiveEnabledCount` for the effective status
+headline (enabled when at least one site is effectively enabled). Render every
+returned site, even if blocked for Apply. Add a **bold, icon-led** plain-language
+environment summary from the same result's `envValue` and mapping-owned scope
+labels; distinguish the policy's own scope from effective state.
+If zero sites, say so and still report the environment result. Preserve helper
+placeholders for unresolved membership sites, including missing name/URL.
+
+## Fetch Site
+
+Resolve exactly one site through the shared picker. Pipe one-site JSON
+directly into the batch, without a temporary site-list file:
+
+```bash
+echo '{ "portals": [ { "portalId": "<PORTAL_ID>", "name": "<PORTAL_NAME>", "url": "<URL>" } ] }' \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/get-effective-status.js" \
+ --policy "<POLICY>" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/render-portal-table.js" --markdown --no-color
+```
+
+The batch reads environment/membership and parents concurrently. Do not call
+`get-portal.js` separately or use a dummy ID. Use the effective state for a
+one-line "This governance setting is Enabled/Disabled for this site" headline,
+then the complete unfenced Markdown status table.
+
+## Post-Apply verification
+
+Wait for `set-governance.js` terminal completion before reading (mid-rollout
+membership can be stale). Poll success alone is insufficient: re-read the
+same scope once with `get-effective-status.js`:
+
+```bash
+node "${PLUGIN_ROOT}/skills/manage-governance/scripts/list-portals.js" --envId "<ENV_ID>" \
+ | node "${PLUGIN_ROOT}/skills/manage-governance/scripts/get-effective-status.js" \
+ --policy "<POLICY>" --envId "<ENV_ID>"
+```
+
+Compare the intended environment scope/membership and every targeted site's
+expected state with the batch result, including removals and collateral
+changes disclosed at consent. Never hand-sequence per-site/policy `get-*` calls.
+Render through the canonical helper: all environment sites for `All`/`None`,
+or the operation's targeted sites for `Include`/`Exclude`, with the actual
+returned states (not fabricated expected values).
+
+A mismatch is not verified success: report "The operation was sent, but the
+environment still reports the previous value. Re-check shortly." Surface read
+errors rather than claiming verification. Do not automatically retry the POST.
+Only a successful, verified prerequisite-parent enable triggers child resume.
+Report helper failures/timeouts as such, not as a successful rollout.
+
+## Internal rollout status
+
+Use `get-status.js --envId "<ENV_ID>" --policy "<POLICY>"` only as an internal
+last-rollout snapshot. Classification comes from `scripts/policies.js` and
+`commands.md`; do not maintain another inline terminal-state table.
+Explain whether the last rollout finished, failed, or is still in flight
+according to that shared contract. A last-rollout snapshot does **not** prove
+that the current request landed; use post-Apply verification for that.
diff --git a/plugins/power-pages/skills/manage-governance/scripts/app-settings.json b/plugins/power-pages/skills/manage-governance/scripts/app-settings.json
new file mode 100644
index 000000000..573618b97
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/app-settings.json
@@ -0,0 +1,27 @@
+{
+ "_comment": "Single-switch routing config for the manage-governance skill. Set activeRing to TIP or Prod and BOTH env-list (BAP) AND governance-gateway calls follow it. This file is the source of truth for ring selection; a missing/invalid file fails open to the built-in defaults in governance-context.js so calls never break.",
+
+ "activeRing": "TIP",
+ "_activeRing_comment": "THE endpoint switch: 'TIP' (Preprod / TEST) or 'Prod'. Drives env-list BAP routing AND the governance gateway.",
+
+ "targetEnv": "",
+ "_targetEnv_comment": "Default Power Platform environment GUID used when a script is called without --envId. Empty = fall back to the signed-in PAC env. Overridden by PP_GOV_ENV_ID or an explicit --envId.",
+
+ "rings": {
+ "TIP": {
+ "gatewayHost": "https://api.preprod.powerplatform.com",
+ "tokenStrategy": "device-code",
+ "bapStrategy": "rest",
+ "bapHost": "https://tip1.api.bap.microsoft.com",
+ "bapResource": "https://service.powerapps.com/"
+ },
+ "Prod": {
+ "gatewayHost": "https://api.powerplatform.com",
+ "tokenStrategy": "az",
+ "bapStrategy": "pac",
+ "bapHost": "https://api.bap.microsoft.com",
+ "bapResource": "https://service.powerapps.com/"
+ }
+ },
+ "_rings_comment": "Per-ring endpoints. GOVERNANCE GATEWAY: gatewayHost (overridden by PP_GOV_API_HOST / PP_GOV_TIP_HOST); tokenStrategy = how the gateway bearer is minted ('device-code' via tip-auth.js — the only path with PowerPages delegated scopes — or 'az'). ENV LIST (BAP): bapStrategy selects the fetch path — 'pac' runs `pac admin list --json` (follows PAC's signed-in cloud; used for Prod), 'rest' does a direct GET to bapHost/providers/Microsoft.BusinessAppPlatform/scopes/admin/environments with an az token for bapResource (used for TIP, which PAC cannot reach without a separate Preprod sign-in). bapResource = az token audience (service.powerapps.com for both rings). TIP hosts MUST stay api.preprod.powerplatform.com / tip1.api.bap.microsoft.com — the api.tip... form does not resolve in DNS."
+}
diff --git a/plugins/power-pages/skills/manage-governance/scripts/colors.js b/plugins/power-pages/skills/manage-governance/scripts/colors.js
new file mode 100644
index 000000000..3c8e1004b
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/colors.js
@@ -0,0 +1,108 @@
+#!/usr/bin/env node
+
+// colors.js — Tiny ANSI color helper modeled on PowerShell's
+// `Write-Host -ForegroundColor <Color>`. It lets scripts emit red / green /
+// yellow / cyan text WHEN — and only when — the output is a real interactive
+// terminal.
+//
+// Why opt-in / TTY-gated: this skill's tables are usually produced as JSON and
+// re-rendered by the agent into chat Markdown, which supports NO ANSI. If we
+// always wrapped text in escape codes, captured strings would show garbage like
+// `←[32mEnabled←[0m`. So coloring is OFF by default and only turns on when:
+// * `enabled: true` is passed explicitly (e.g. from a `--color` flag), OR
+// * stdout is a TTY, `NO_COLOR` is unset, and the caller didn't force it off.
+// `FORCE_COLOR` (any truthy value) forces it on; `NO_COLOR` forces it off.
+
+// ForegroundColor name -> SGR code. Names match PowerShell's ConsoleColor so a
+// caller can pass 'Green' / 'Red' / 'Yellow' / 'Cyan' just like -ForegroundColor.
+const FOREGROUND = {
+ black: 30,
+ red: 31,
+ green: 32,
+ yellow: 33,
+ blue: 34,
+ magenta: 35,
+ cyan: 36,
+ white: 37,
+ gray: 90,
+ grey: 90,
+};
+
+const RESET = '\u001b[0m';
+
+/**
+ * Decide whether ANSI coloring should be applied.
+ *
+ * @param {object} [opts]
+ * @param {boolean|null} [opts.enabled] - Tri-state override. `true` forces on,
+ * `false` forces off, `null`/`undefined` falls back to auto-detection.
+ * @param {NodeJS.WriteStream} [opts.stream] - Stream whose `.isTTY` is checked
+ * during auto-detection (defaults to `process.stdout`).
+ * @param {object} [opts.env] - Environment map (defaults to `process.env`).
+ * @returns {boolean}
+ */
+function shouldColor(opts = {}) {
+ if (opts.enabled === true) return true;
+ if (opts.enabled === false) return false;
+ const env = opts.env || process.env;
+ if (env.NO_COLOR != null && env.NO_COLOR !== '') return false;
+ if (env.FORCE_COLOR != null && env.FORCE_COLOR !== '' && env.FORCE_COLOR !== '0') {
+ return true;
+ }
+ const stream = opts.stream || process.stdout;
+ return Boolean(stream && stream.isTTY);
+}
+
+/**
+ * Wrap `text` in the ANSI escape for a ConsoleColor-style foreground color —
+ * the programmatic equivalent of `Write-Host $text -ForegroundColor <color>`.
+ * When coloring is disabled the text is returned unchanged, so JSON/chat output
+ * stays clean.
+ *
+ * @param {string} text
+ * @param {string} color - A ForegroundColor name ('Green', 'Red', ...).
+ * @param {object} [opts] - Passed through to `shouldColor` (e.g. `{ enabled }`).
+ * @returns {string}
+ */
+function foregroundColor(text, color, opts = {}) {
+ const s = String(text == null ? '' : text);
+ if (!shouldColor(opts)) return s;
+ const code = FOREGROUND[String(color || '').toLowerCase()];
+ if (code == null) return s;
+ return `\u001b[${code}m${s}${RESET}`;
+}
+
+// Convenience helpers named after the four colors this skill actually uses for
+// status output (green = enabled/success, red = disabled/error, yellow =
+// warning, cyan = info) — mirroring the PowerShell snippet.
+const green = (text, opts) => foregroundColor(text, 'Green', opts);
+const red = (text, opts) => foregroundColor(text, 'Red', opts);
+const yellow = (text, opts) => foregroundColor(text, 'Yellow', opts);
+const cyan = (text, opts) => foregroundColor(text, 'Cyan', opts);
+
+module.exports = {
+ FOREGROUND,
+ RESET,
+ shouldColor,
+ foregroundColor,
+ green,
+ red,
+ yellow,
+ cyan,
+};
+
+// Tiny CLI so you can eyeball the colors in a terminal:
+// node colors.js -> auto-detects TTY
+// node colors.js --color -> force on
+// node colors.js --no-color -> force off
+if (require.main === module) {
+ const argv = process.argv.slice(2);
+ let enabled = null;
+ if (argv.includes('--color')) enabled = true;
+ if (argv.includes('--no-color')) enabled = false;
+ const opts = { enabled };
+ process.stdout.write(green('Success', opts) + '\n');
+ process.stdout.write(yellow('Warning', opts) + '\n');
+ process.stdout.write(red('Error', opts) + '\n');
+ process.stdout.write(cyan('Info', opts) + '\n');
+}
diff --git a/plugins/power-pages/skills/manage-governance/scripts/fetch-env-status.js b/plugins/power-pages/skills/manage-governance/scripts/fetch-env-status.js
new file mode 100644
index 000000000..f4a80742f
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/fetch-env-status.js
@@ -0,0 +1,259 @@
+#!/usr/bin/env node
+
+// fetch-env-status.js — One-shot "Fetch Env status" for a governance policy.
+//
+// This is the single script the skill triggers to answer "what is the status of
+// <policy> in <env>?" (SKILL.md Phase 4.3.1). It performs the WHOLE Fetch Env in
+// ONE parallel wave and emits a render-ready payload, so the orchestrator just
+// runs it and pipes `.portals` into render-portal-table.js.
+//
+// What it batches (all fired concurrently against ONE shared context/token)
+// -----------------------------------------------------------------------
+// 1. GET /websites — the env's full site list (paged).
+// 2. getEnv + getDetails for the POLICY — the policy's own per-site state.
+// 3. getEnv + getDetails for EACH gating PARENT (External Auth, and for a
+// social IdP also OAuth 2.0) — needed to compute the EFFECTIVE state.
+//
+// Before this script the flow was two steps: list-portals.js FIRST (a separate
+// round-trip), THEN get-effective-status.js for the governance reads. Folding
+// the site-list fetch into the same Promise.all removes that extra serial
+// round-trip — the site list and all 4–6 governance reads now resolve together,
+// so total latency is ≈ one round-trip regardless of parent count.
+//
+// Why share ONE context: resolving the governance context mints a bearer token
+// via a blocking `tip-auth.js` subprocess (execSync). The token is env-scoped,
+// not policy-scoped, so every read in the batch reuses it — resolving per-call
+// would re-spawn the token helper 7× and serialize the whole batch behind those
+// subprocess spawns. See governance-transport.js `context` param.
+//
+// Effective state (for a gated child): a protocol/social IdP is only actually
+// live on a site when its OWN setting AND every gating parent are Enabled there
+// (governance-mapping.json `availabilityDependsOn`). For a leaf policy (Maker
+// Copilot, local login, External Auth, the 11 PowerPages_* policies) there are
+// no parents, so effective state == own state and only 2 governance reads fire.
+
+'use strict';
+
+const { assertPolicy, normalizeEnvValue } = require('./policies');
+const { callGovernance } = require('./governance-transport');
+const { resolveGovernanceContext } = require('./governance-context');
+const { fetchPortalsPaged } = require('./list-portals');
+const {
+ loadMapping,
+ dependenciesForPolicy,
+ canonicalizeEnvValue,
+ resolvePortalStates,
+} = require('./resolve-portal-availability');
+const { classifyPolicy } = require('./get-effective-status');
+
+// Per-request timeout for the parallel batch. The governance gateway is slow
+// (single reads observed at 20–40s wall) and gets slower under concurrent load,
+// so the request() 15s default trips a spurious "Request timed out" mid-batch.
+// 120s gives every concurrent read ample headroom without hanging forever.
+// Mirrors get-effective-status.js.
+const BATCH_REQUEST_TIMEOUT_MS = 120_000;
+
+const HELP = `fetch-env-status.js — One-shot Fetch Env status (site list + all reads in one parallel batch).
+
+Answers "what is the status of <policy> in <env>?" in a SINGLE parallel wave:
+the /websites site list plus getEnv + getDetails for the policy AND every
+gating parent (External Auth, and for a social IdP also OAuth 2.0) are all
+fired concurrently against one shared token, then each site's EFFECTIVE state
+(own AND every parent) is computed.
+
+Usage:
+ node fetch-env-status.js --policy <name> [--envId <guid>] [--json]
+
+Flags:
+ --policy Governance policy name (any of the supported policies). A leaf
+ policy with no parents reports its own state as the effective state
+ and issues only 2 governance reads.
+ --envId Optional environment id (falls back to the current PAC env).
+ --json (default) Emit JSON.
+ --help Show this help.
+
+Exit codes:
+ 0 Success (including an env with zero sites)
+ 2 Sign-in required
+ 1 Other failure
+
+Stdout (JSON) — the \`.portals\` array is exactly what render-portal-table.js
+consumes, so pipe it straight in:
+ {
+ "status": "ok",
+ "policy": "<name>",
+ "envId": "<guid>",
+ "envValue": "All|None|Include|Exclude", // the POLICY's own env-level value
+ "dependencies": ["<parent>", ...],
+ "apiCalls": <n>, // 1 (websites) + policies × 2
+ "portalCount": <n>,
+ "effectiveEnabledCount": <n>,
+ "headline": "This Governance setting is 🟢 Enabled for these Sites:" | "... 🔴 Disabled ...",
+ "portals": [
+ { "name", "url", "portalId",
+ "state": true|false, // EFFECTIVE (own AND all parents) — for the box
+ "own": true|false, // policy's own setting on this site
+ "parents": { "<parent>": true|false, ... } }
+ ]
+ }
+`;
+
+function parseFlags(argv) {
+ const out = {};
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--policy') out.policy = argv[++i];
+ else if (a === '--envId') out.envId = argv[++i];
+ else if (a === '--json') out.json = true;
+ else if (a === '--help') out.help = true;
+ }
+ return out;
+}
+
+// Headline mirrors SKILL.md Phase 4.3.1: green when at least one site is
+// effectively Enabled, red when the setting is off everywhere (including the
+// zero-site case, where there is nothing enabled).
+function pickHeadline(effectiveEnabledCount) {
+ return effectiveEnabledCount > 0
+ ? 'This Governance setting is \u{1F7E2} Enabled for these Sites:'
+ : 'This Governance setting is \u{1F534} Disabled for these Sites:';
+}
+
+async function main() {
+ const flags = parseFlags(process.argv);
+ if (flags.help) {
+ process.stdout.write(HELP);
+ return;
+ }
+ if (!flags.policy) {
+ process.stderr.write('Usage: node fetch-env-status.js --policy <name> [--envId <guid>]\n');
+ process.exit(1);
+ return;
+ }
+ assertPolicy(flags.policy);
+
+ const mapping = loadMapping();
+ const deps = dependenciesForPolicy(flags.policy, mapping);
+ // Child first so its own state is easy to pick out; parents follow.
+ const allPolicies = [flags.policy, ...deps];
+
+ // Resolve the governance context (which mints the bearer token via a
+ // tip-auth.js subprocess) EXACTLY ONCE and share it across the site-list fetch
+ // and every governance read — see the file header for why.
+ const context = resolveGovernanceContext(flags.envId);
+ if (context.error) {
+ process.stderr.write(`Failed to resolve governance context: ${context.error}\n`);
+ process.exit(2);
+ return;
+ }
+
+ // THE PARALLEL BATCH. The /websites site-list fetch and every getEnv +
+ // getDetails read are all promises kicked off before any is awaited, so
+ // Promise.all runs them in a single concurrent wave. The site-list result is
+ // tagged kind:'sites' so it can be separated from the governance reads when we
+ // regroup below.
+ const calls = [];
+ calls.push(fetchPortalsPaged(context).then((r) => ({ kind: 'sites', r })));
+ for (const p of allPolicies) {
+ calls.push(
+ callGovernance({ op: 'getEnv', envId: flags.envId, policy: p, context, timeout: BATCH_REQUEST_TIMEOUT_MS }).then((r) => ({ p, kind: 'env', r }))
+ );
+ calls.push(
+ callGovernance({ op: 'getDetails', envId: flags.envId, policy: p, context, timeout: BATCH_REQUEST_TIMEOUT_MS }).then((r) => ({ p, kind: 'details', r }))
+ );
+ }
+ const settled = await Promise.all(calls);
+
+ // Regroup the flat results: pull out the site list, and rebuild
+ // { policy: { env, details } } for each governance policy.
+ let sitesResult = null;
+ const byPolicy = {};
+ for (const item of settled) {
+ if (item.kind === 'sites') {
+ sitesResult = item.r;
+ continue;
+ }
+ byPolicy[item.p] = byPolicy[item.p] || {};
+ byPolicy[item.p][item.kind] = item.r;
+ }
+
+ // A failed /websites read is fatal — without the site list there is nothing to
+ // classify. (An empty list is NOT an error: the env legitimately has no sites.)
+ if (!sitesResult || sitesResult.error) {
+ process.stderr.write(`Listing sites failed: ${sitesResult ? sitesResult.error : 'no result'}\n`);
+ process.exit(1);
+ return;
+ }
+ const portals = sitesResult.portals || [];
+
+ // A failed getEnv is fatal — without the env value we cannot classify that
+ // policy at all. Surface a sign-in vs. other-failure exit code like the
+ // sibling scripts do. (A failed getDetails is tolerated as an empty list.)
+ for (const p of allPolicies) {
+ const envRes = byPolicy[p] && byPolicy[p].env;
+ if (!envRes || !envRes.ok) {
+ const msg = envRes?.error?.message || `status ${envRes?.statusCode}`;
+ const code = envRes?.error?.code === 'ContextError' ? 2 : 1;
+ process.stderr.write(`Reading "${p}" env state failed: ${msg}\n`);
+ process.exit(code);
+ return;
+ }
+ }
+
+ // The POLICY's own env-level value (canonical All/None/Include/Exclude) — kept
+ // in the payload so the caller can render the plain-language env summary.
+ const envValue = canonicalizeEnvValue(normalizeEnvValue(byPolicy[flags.policy].env.body));
+
+ // Classify each policy's per-portal state from its (env, details) pair, then
+ // fold parents into the child to get the EFFECTIVE state per site.
+ const childInfo = classifyPolicy(byPolicy[flags.policy].env, byPolicy[flags.policy].details, portals);
+ const parentInfos = {};
+ for (const parent of deps) {
+ parentInfos[parent] = classifyPolicy(byPolicy[parent].env, byPolicy[parent].details, portals);
+ }
+
+ const rows = childInfo.states.map((s) => {
+ const key = String(s.portalId).toLowerCase();
+ const own = s.state === 'Enabled';
+ const parents = {};
+ let effective = own;
+ for (const parent of deps) {
+ const on = parentInfos[parent].byId[key] === true;
+ parents[parent] = on;
+ effective = effective && on;
+ }
+ return { name: s.name, url: s.url, portalId: s.portalId, state: effective, own, parents };
+ });
+ // Effective-Enabled first (stable within each group) so the status box lists
+ // the live sites at the top, matching the rest of the skill's status renders.
+ rows.sort((a, b) => Number(b.state) - Number(a.state));
+
+ const effectiveEnabledCount = rows.filter((r) => r.state).length;
+
+ process.stdout.write(
+ JSON.stringify(
+ {
+ status: 'ok',
+ policy: flags.policy,
+ envId: flags.envId || null,
+ envValue,
+ settingPresent: byPolicy[flags.policy].env.settingPresent !== false,
+ unconfiguredPolicies: allPolicies.filter((p) => byPolicy[p].env.settingPresent === false),
+ dependencies: deps,
+ apiCalls: 1 + allPolicies.length * 2,
+ portalCount: rows.length,
+ effectiveEnabledCount,
+ headline: pickHeadline(effectiveEnabledCount),
+ portals: rows,
+ },
+ null,
+ 2
+ ) + '\n'
+ );
+}
+
+module.exports = { pickHeadline, parseFlags };
+
+if (require.main === module) {
+ main();
+}
diff --git a/plugins/power-pages/skills/manage-governance/scripts/get-details.js b/plugins/power-pages/skills/manage-governance/scripts/get-details.js
new file mode 100644
index 000000000..af6607f04
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/get-details.js
@@ -0,0 +1,115 @@
+#!/usr/bin/env node
+
+// get-details.js — Reads a governance policy's per-site membership (the
+// inclusion / exclusion portal lists) for the whole environment in ONE call via
+// the gateway transport: GET /governance/{policy}/details.
+//
+// WHY this exists — kill the per-portal read loop
+// -----------------------------------------------
+// The portal-scoped endpoint `GET /websites/{portalId}/governance/{policy}`
+// (get-portal.js) answers for exactly one portal and returns a single boolean,
+// so reading N portals costs N cold-started calls — each one a fresh chance to
+// hit a transient "PAC not signed in" (observed mid-loop in practice). It also
+// cannot be probed with a dummy portalId: a non-existent website id returns
+// 404 "Website with the given id does not exist", so the old "call get-portal
+// with 00000000-… to get the env lists" trick never worked.
+//
+// The `/details` endpoint returns the env-level inclusion/exclusion lists once:
+// { "IncludedSites": ["<portalId>", ...], "ExcludedSites": ["<portalId>", ...] }
+// (ExcludedSites is null when unused). Combined with get-env.js (the All / None
+// / Include / Exclude env value), the caller can resolve EVERY portal's state
+// locally via resolvePortalStates() — 2 network calls per policy regardless of
+// portal count, instead of 1 + N. See references/commands.md and SKILL.md
+// Phase 4.3.1 / 4.4.4 / 4.2.3 / 4.2.5.
+//
+// This is a thin network wrapper: the pure list-parsing + per-portal
+// classification lives in resolve-portal-availability.js (extractLists /
+// resolvePortalStates), reused here so there is a single source of truth for
+// the list field-name spellings and the siteStateRules contract.
+
+const {
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+const { SUPPORTED_POLICIES, assertPolicy } = require('./policies');
+const { callGovernance } = require('./governance-transport');
+const { extractLists } = require('./resolve-portal-availability');
+
+const HELP = `get-details.js — Reads a governance policy's inclusion/exclusion site lists.
+
+Reads the env-level per-site membership for a policy in a SINGLE call
+(GET /governance/{policy}/details), so every portal's state can be resolved
+locally without a per-portal read loop.
+
+Usage:
+ node get-details.js --policy <name> [--envId <guid>]
+
+Flags:
+ --policy Governance policy name. One of:
+ ${SUPPORTED_POLICIES.join('\n ')}
+ --envId Optional environment id. Falls back to the current PAC env.
+ --help Show this help message.
+
+Exit codes:
+ 0 Success
+ 2 Sign-in required
+ 1 Other failure
+
+Stdout (JSON):
+ { "status": "ok", "policy": "<name>", "envId": "<guid>",
+ "transport": "gateway",
+ "includedSites": ["<portalId>", ...],
+ "excludedSites": ["<portalId>", ...],
+ "body": <raw> }
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ if (!args.policy) {
+ fail('Usage: node get-details.js --policy <name> [--envId <guid>]', 1);
+ }
+ assertPolicy(args.policy);
+
+ const res = await callGovernance({
+ op: 'getDetails',
+ envId: args.envId,
+ policy: args.policy,
+ });
+
+ if (!res.ok) {
+ const code = res.error?.code === 'ContextError' ? 2 : 1;
+ const status = res.statusCode != null && res.statusCode !== 0 ? res.statusCode : 'no response';
+ const msg = res.error?.message?.trim() || res.error?.code || 'unknown error';
+ fail(`Get governance details failed (${status}): ${msg}`, code);
+ }
+
+ // Normalize the two lists through the shared parser so the emitted arrays use
+ // one canonical spelling (lowercased id strings) no matter how the gateway
+ // spelled the fields on this ring. Callers that want the raw shape still get
+ // it under `body`.
+ const { inclusion, exclusion } = extractLists(res.body);
+
+ process.stdout.write(
+ JSON.stringify(
+ {
+ status: 'ok',
+ policy: args.policy,
+ envId: args.envId,
+ transport: res.transport,
+ includedSites: [...inclusion],
+ excludedSites: [...exclusion],
+ body: res.body,
+ },
+ null,
+ 2
+ ) + '\n'
+ );
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-governance/scripts/get-effective-status.js b/plugins/power-pages/skills/manage-governance/scripts/get-effective-status.js
new file mode 100644
index 000000000..a18144bc5
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/get-effective-status.js
@@ -0,0 +1,254 @@
+#!/usr/bin/env node
+
+// get-effective-status.js — Compute the *effective* governance state of a
+// policy for every portal in an environment, in ONE parallel batch of reads.
+//
+// Why this script exists
+// ----------------------
+// A gated child sign-in method (a protocol or a social IdP) is only actually
+// live on a portal when the child's OWN setting AND every gating parent are
+// Enabled there (see governance-mapping.json `availabilityDependsOn` /
+// `effectiveStatusRules`). Reading that status means reading the child plus its
+// parents, and for each policy we need TWO calls — the env-level value
+// (`getEnv`) and, when that value is Include/Exclude, the per-site membership
+// (`getDetails`). So:
+// - a protocol (parent: External Auth) → 2 policies × 2 = 4 calls
+// - a social IdP (parents: External Auth + OAuth 2.0) → 3 policies × 2 = 6 calls
+//
+// The previous flow (resolve-portal-availability.js `readParentStates`) issued
+// those reads SEQUENTIALLY in a `for … await` loop, so a social-IdP status took
+// 6 round-trips end-to-end. Each call is independent, so this script fires ALL
+// of them concurrently with a single `Promise.all` and only then assembles the
+// report — turning 4–6 serial round-trips into one parallel wave. The wall-clock
+// cost drops to roughly a single round-trip regardless of the parent count.
+//
+// getEnv + getDetails are fired for EVERY policy unconditionally (even when the
+// env value turns out to be All/None, where the details list is irrelevant).
+// That is deliberate: firing both up-front keeps the batch a flat, fully
+// parallel Promise.all instead of a value-dependent second wave, and matches the
+// "6 calls, all parallel" model. A getDetails response for an All/None policy is
+// simply ignored downstream (resolvePortalStates derives All→Enabled /
+// None→Disabled without the list), and a failed getDetails is tolerated as an
+// empty list — only a failed getEnv is fatal (we cannot classify without it).
+
+'use strict';
+
+const path = require('path');
+
+const { SUPPORTED_POLICIES, assertPolicy, normalizeEnvValue } = require('./policies');
+const { callGovernance } = require('./governance-transport');
+const { resolveGovernanceContext } = require('./governance-context');
+const {
+ loadMapping,
+ dependenciesForPolicy,
+ canonicalizeEnvValue,
+ readPortalsInput,
+ resolvePortalStates,
+} = require('./resolve-portal-availability');
+
+// Per-request timeout for the parallel batch. The governance gateway is slow
+// (single reads observed at 20–40s wall) and gets slower under concurrent load,
+// so the request() 15s default trips a spurious "Request timed out" mid-batch.
+// 120s gives every concurrent read ample headroom without hanging forever.
+const BATCH_REQUEST_TIMEOUT_MS = 120_000;
+
+const HELP = `get-effective-status.js — Effective per-portal governance status in one parallel batch.
+
+Fires getEnv + getDetails for the CHILD policy and every gating parent
+concurrently (4 calls for a protocol, 6 for a social IdP), then reports each
+portal's EFFECTIVE state = child own AND all parents.
+
+Usage:
+ node list-portals.js [--envId <guid>] |
+ node get-effective-status.js --policy <name> [--envId <guid>] [--json]
+
+Flags:
+ --policy Governance policy name (${SUPPORTED_POLICIES.length} supported policies). Policies
+ without parents report their own state as the effective state.
+ stdin list-portals.js output ({ portals: [...] } or a bare array).
+ This script does NOT re-page /websites.
+ --portalsFile Backward-compatible alternative to stdin.
+ --envId Optional environment id (falls back to the current PAC env).
+ --json (default) Emit JSON.
+ --help Show this help.
+
+Exit codes:
+ 0 Success 2 Sign-in required 1 Other failure
+
+Stdout (JSON) — the shape render-portal-table.js consumes directly (it reads
+\`.portals\`), so you can pipe this straight into it:
+ {
+ "status": "ok",
+ "policy": "<name>",
+ "settingPresent": true|false,
+ "unconfiguredPolicies": ["<policy with no setting on record>", ...],
+ "dependencies": ["<parent>", ...],
+ "apiCalls": <n>, // policies × 2, all issued in parallel
+ "effectiveEnabledCount": <n>,
+ "portals": [
+ { "name", "url", "portalId",
+ "state": true|false, // EFFECTIVE (own AND all parents) — for the box
+ "own": true|false, // child's own setting on this portal
+ "parents": { "<parent>": true|false, ... } }
+ ]
+ }
+`;
+
+function parseFlags(argv) {
+ const out = {};
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--policy') out.policy = argv[++i];
+ else if (a === '--portalsFile') out.portalsFile = argv[++i];
+ else if (a === '--envId') out.envId = argv[++i];
+ else if (a === '--json') out.json = true;
+ else if (a === '--help') out.help = true;
+ }
+ return out;
+}
+
+/**
+ * Read one policy's env value + details concurrently is handled by the caller's
+ * flat Promise.all; this helper just classifies a completed (env, details) pair
+ * into per-portal Enabled/Disabled booleans keyed by portal id.
+ *
+ * @param {object} envRes - callGovernance getEnv envelope for this policy.
+ * @param {object} detailsRes- callGovernance getDetails envelope (may be !ok).
+ * @param {Array} portals - list-portals records.
+ * @returns {{ byId: Object<string,boolean>, states: Array }}
+ */
+function classifyPolicy(envRes, detailsRes, portals) {
+ const envValue = canonicalizeEnvValue(normalizeEnvValue(envRes.body));
+ // Only Include/Exclude actually consult the membership list; for All/None the
+ // details body is irrelevant, and a failed/absent details read degrades to an
+ // empty list (fail-closed for the list only — the env value was read fine).
+ const detailsBody = detailsRes && detailsRes.ok ? detailsRes.body : null;
+ const states = resolvePortalStates(envValue, detailsBody, portals);
+ const byId = {};
+ for (const s of states) byId[String(s.portalId).toLowerCase()] = s.state === 'Enabled';
+ return { byId, states };
+}
+
+async function main() {
+ const flags = parseFlags(process.argv);
+ if (flags.help) {
+ process.stdout.write(HELP);
+ return;
+ }
+ if (!flags.policy) {
+ process.stderr.write(
+ 'Usage: node list-portals.js | node get-effective-status.js --policy <name> [--envId <guid>]\n'
+ );
+ process.exit(1);
+ return;
+ }
+ assertPolicy(flags.policy);
+
+ let portals;
+ try {
+ portals = await readPortalsInput(flags.portalsFile);
+ } catch (e) {
+ process.stderr.write(`get-effective-status: could not read/parse portal JSON: ${e.message}\n`);
+ process.exit(1);
+ return;
+ }
+
+ const mapping = loadMapping();
+ const deps = dependenciesForPolicy(flags.policy, mapping);
+ // Child first so its own state is easy to pick out; parents follow.
+ const allPolicies = [flags.policy, ...deps];
+
+ // Resolve the governance context (which mints the bearer token via a
+ // tip-auth.js subprocess) EXACTLY ONCE and share it across every request in
+ // the batch. The token is env-scoped, not policy-scoped, so all 4–6 reads use
+ // the same context — resolving per-call would re-spawn the token helper 4–6×
+ // and serialize the batch behind those blocking subprocess spawns.
+ const context = resolveGovernanceContext(flags.envId);
+ if (context.error) {
+ process.stderr.write(`Failed to resolve governance context: ${context.error}\n`);
+ process.exit(2);
+ return;
+ }
+
+ // THE PARALLEL BATCH: every getEnv + getDetails for every policy is fired at
+ // once against the shared context. `Promise.all` waits for the whole wave, so
+ // total latency ≈ one round-trip instead of (2 × policy count) serial ones.
+ const calls = [];
+ for (const p of allPolicies) {
+ calls.push(
+ callGovernance({ op: 'getEnv', envId: flags.envId, policy: p, context, timeout: BATCH_REQUEST_TIMEOUT_MS }).then((r) => ({ p, kind: 'env', r }))
+ );
+ calls.push(
+ callGovernance({ op: 'getDetails', envId: flags.envId, policy: p, context, timeout: BATCH_REQUEST_TIMEOUT_MS }).then((r) => ({ p, kind: 'details', r }))
+ );
+ }
+ const settled = await Promise.all(calls);
+
+ // Regroup the flat results back into { policy: { env, details } }.
+ const byPolicy = {};
+ for (const { p, kind, r } of settled) {
+ byPolicy[p] = byPolicy[p] || {};
+ byPolicy[p][kind] = r;
+ }
+
+ // A failed getEnv is fatal — without the env value we cannot classify the
+ // policy at all. Surface a sign-in vs. other-failure exit code like the
+ // sibling scripts do.
+ for (const p of allPolicies) {
+ const envRes = byPolicy[p] && byPolicy[p].env;
+ if (!envRes || !envRes.ok) {
+ const msg = envRes?.error?.message || `status ${envRes?.statusCode}`;
+ const code = envRes?.error?.code === 'ContextError' ? 2 : 1;
+ process.stderr.write(`Reading "${p}" env state failed: ${msg}\n`);
+ process.exit(code);
+ return;
+ }
+ }
+
+ // Classify each policy's per-portal state from its (env, details) pair.
+ const childInfo = classifyPolicy(byPolicy[flags.policy].env, byPolicy[flags.policy].details, portals);
+ const parentInfos = {};
+ for (const parent of deps) {
+ parentInfos[parent] = classifyPolicy(byPolicy[parent].env, byPolicy[parent].details, portals);
+ }
+
+ // Effective = child own Enabled AND every parent Enabled on that portal.
+ const rows = childInfo.states.map((s) => {
+ const key = String(s.portalId).toLowerCase();
+ const own = s.state === 'Enabled';
+ const parents = {};
+ let effective = own;
+ for (const parent of deps) {
+ const on = parentInfos[parent].byId[key] === true;
+ parents[parent] = on;
+ effective = effective && on;
+ }
+ return { name: s.name, url: s.url, portalId: s.portalId, state: effective, own, parents };
+ });
+ // Effective-Enabled first (stable within each group) so the status box lists
+ // the live sites at the top, matching the rest of the skill's status renders.
+ rows.sort((a, b) => Number(b.state) - Number(a.state));
+
+ process.stdout.write(
+ JSON.stringify(
+ {
+ status: 'ok',
+ policy: flags.policy,
+ settingPresent: byPolicy[flags.policy].env.settingPresent !== false,
+ unconfiguredPolicies: allPolicies.filter((p) => byPolicy[p].env.settingPresent === false),
+ dependencies: deps,
+ apiCalls: allPolicies.length * 2,
+ effectiveEnabledCount: rows.filter((r) => r.state).length,
+ portals: rows,
+ },
+ null,
+ 2
+ ) + '\n'
+ );
+}
+
+module.exports = { classifyPolicy };
+
+if (require.main === module) {
+ main();
+}
diff --git a/plugins/power-pages/skills/manage-governance/scripts/get-env.js b/plugins/power-pages/skills/manage-governance/scripts/get-env.js
new file mode 100644
index 000000000..ec12a17c5
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/get-env.js
@@ -0,0 +1,84 @@
+#!/usr/bin/env node
+
+// get-env.js — Reads the environment-level state of a governance policy via the
+// gateway transport (`GET /governance/{policy}` against api.powerplatform.com,
+// env-scoped through the base URL).
+
+const {
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+const { SUPPORTED_POLICIES, assertPolicy, normalizeEnvValue } = require('./policies');
+const { callGovernance } = require('./governance-transport');
+
+const HELP = `get-env.js — Reads the environment-level governance policy state.
+
+Usage:
+ node get-env.js --policy <name> [--envId <guid>]
+
+Flags:
+ --policy Governance policy name. One of:
+ ${SUPPORTED_POLICIES.join('\n ')}
+ --envId Optional environment id. Falls back to the current PAC env.
+ --help Show this help message.
+
+Exit codes:
+ 0 Success
+ 2 Sign-in required
+ 1 Other failure
+
+Stdout (JSON):
+ { "status": "ok", "policy": "<name>", "envId": "<guid>",
+ "transport": "gateway",
+ "settingPresent": true|false,
+ "value": "All"|"None"|"Include"|"Exclude", "body": <raw> }
+
+A policy-read 404 reports settingPresent=false, value=None, and the message
+"No governance setting on record." Other request failures remain errors.
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ if (!args.policy) {
+ fail('Usage: node get-env.js --policy <name> [--envId <guid>]', 1);
+ }
+ assertPolicy(args.policy);
+
+ const res = await callGovernance({
+ op: 'getEnv',
+ envId: args.envId,
+ policy: args.policy,
+ });
+
+ if (!res.ok) {
+ const code = res.error?.code === 'ContextError' ? 2 : 1;
+ const status = res.statusCode != null && res.statusCode !== 0 ? res.statusCode : 'no response';
+ const msg = res.error?.message?.trim() || res.error?.code || 'unknown error';
+ fail(`Get env-level governance failed (${status}): ${msg}`, code);
+ }
+
+ process.stdout.write(
+ JSON.stringify(
+ {
+ status: 'ok',
+ policy: args.policy,
+ envId: args.envId,
+ transport: res.transport,
+ settingPresent: res.settingPresent !== false,
+ ...(res.settingPresent === false ? { message: 'No governance setting on record.' } : {}),
+ value: normalizeEnvValue(res.body),
+ body: res.body,
+ },
+ null,
+ 2
+ ) + '\n'
+ );
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-governance/scripts/get-portal.js b/plugins/power-pages/skills/manage-governance/scripts/get-portal.js
new file mode 100644
index 000000000..8547c09df
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/get-portal.js
@@ -0,0 +1,80 @@
+#!/usr/bin/env node
+
+// get-portal.js — Reads the portal-level state of a governance policy via the
+// gateway transport: GET /websites/{portalId}/governance/{policy}.
+
+const {
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+const { SUPPORTED_POLICIES, assertPolicy } = require('./policies');
+const { callGovernance } = require('./governance-transport');
+
+const HELP = `get-portal.js — Reads the portal-level governance policy state.
+
+Usage:
+ node get-portal.js --policy <name> --portalId <guid> [--envId <guid>]
+
+Flags:
+ --policy Governance policy name. One of:
+ ${SUPPORTED_POLICIES.join('\n ')}
+ --portalId Power Platform API portal id. Resolve via list-portals.js
+ — this is the value from the website record's "Id" field,
+ NOT the Dataverse WebsiteRecordId.
+ --envId Optional environment id. Falls back to the current PAC env.
+ --help Show this help message.
+
+Exit codes:
+ 0 Success
+ 2 Sign-in required
+ 1 Other failure
+
+Stdout (JSON):
+ { "status": "ok", "policy": "<name>", "envId": "<guid>",
+ "portalId": "<guid>", "transport": "gateway", "body": <raw> }
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ if (!args.policy || !args.portalId) {
+ fail('Usage: node get-portal.js --policy <name> --portalId <guid> [--envId <guid>]', 1);
+ }
+ assertPolicy(args.policy);
+
+ const res = await callGovernance({
+ op: 'getPortal',
+ envId: args.envId,
+ policy: args.policy,
+ portalId: args.portalId,
+ });
+
+ if (!res.ok) {
+ const code = res.error?.code === 'ContextError' ? 2 : 1;
+ const status = res.statusCode != null && res.statusCode !== 0 ? res.statusCode : 'no response';
+ const msg = res.error?.message?.trim() || res.error?.code || 'unknown error';
+ fail(`Get portal-level governance failed (${status}): ${msg}`, code);
+ }
+
+ process.stdout.write(
+ JSON.stringify(
+ {
+ status: 'ok',
+ policy: args.policy,
+ envId: args.envId,
+ portalId: args.portalId,
+ transport: res.transport,
+ body: res.body,
+ },
+ null,
+ 2
+ ) + '\n'
+ );
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-governance/scripts/get-status.js b/plugins/power-pages/skills/manage-governance/scripts/get-status.js
new file mode 100644
index 000000000..64522e344
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/get-status.js
@@ -0,0 +1,75 @@
+#!/usr/bin/env node
+
+// get-status.js — One-shot status read for a governance policy roll-out via the
+// gateway transport (`GET /governance/status/{policy}`).
+
+const {
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+const { SUPPORTED_POLICIES, assertPolicy } = require('./policies');
+const { callGovernance } = require('./governance-transport');
+
+const HELP = `get-status.js — Returns the current roll-out status for a governance policy.
+
+Usage:
+ node get-status.js --policy <name> [--envId <guid>]
+
+Flags:
+ --policy Governance policy name. One of:
+ ${SUPPORTED_POLICIES.join('\n ')}
+ --envId Optional environment id. Falls back to the current PAC env.
+ --help Show this help message.
+
+Exit codes:
+ 0 Success (including in-progress status)
+ 2 Sign-in required
+ 1 Other failure
+
+Stdout (JSON):
+ { "status": "ok", "policy": "<name>", "transport": "gateway",
+ "value": "<state>", "body": <raw> }
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ if (!args.policy) {
+ fail('Usage: node get-status.js --policy <name> [--envId <guid>]', 1);
+ }
+ assertPolicy(args.policy);
+
+ const res = await callGovernance({
+ op: 'getStatus',
+ envId: args.envId,
+ policy: args.policy,
+ });
+
+ if (!res.ok) {
+ const code = res.error?.code === 'ContextError' ? 2 : 1;
+ const status = res.statusCode != null && res.statusCode !== 0 ? res.statusCode : 'no response';
+ const msg = res.error?.message?.trim() || res.error?.code || 'unknown error';
+ fail(`Get governance status failed (${status}): ${msg}`, code);
+ }
+
+ const raw = res.body;
+ const value =
+ typeof raw === 'string'
+ ? raw
+ : raw?.status ?? raw?.state ?? raw?.value ?? null;
+
+ process.stdout.write(
+ JSON.stringify(
+ { status: 'ok', policy: args.policy, transport: res.transport, value, body: raw },
+ null,
+ 2
+ ) + '\n'
+ );
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-governance/scripts/governance-context.js b/plugins/power-pages/skills/manage-governance/scripts/governance-context.js
new file mode 100644
index 000000000..62f3df5bd
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/governance-context.js
@@ -0,0 +1,343 @@
+#!/usr/bin/env node
+
+'use strict';
+
+const { execFileSync } = require('child_process');
+const fs = require('fs');
+const path = require('path');
+const {
+ resolveContext,
+} = require('../../../scripts/lib/power-platform-api');
+const {
+ getAuthToken,
+} = require('../../../scripts/lib/validation-helpers');
+const {
+ resolveTipConfig,
+} = require('./tip-auth');
+
+// ---------------------------------------------------------------------------
+// Central ring registry — the single source of truth for "which endpoint + how
+// to get its token". The DATA defaults live in DEFAULT_RINGS below and can be
+// overridden by the co-located app-settings.json (loaded inline — no separate
+// config module). A single switch (resolveRing, app-settings.json > TIP)
+// selects the active entry, and BOTH the governance gateway AND the
+// env-list BAP path key off it.
+//
+// gatewayHost governance gateway base host (powerplatform.com API).
+// gatewayHostEnv optional per-ring env var overriding gatewayHost (sub-ring).
+// tokenStrategy how to mint the gateway bearer:
+// 'device-code' → custom public-client app via tip-auth.js.
+// The ONLY strategy that yields the PowerPages delegated
+// scopes (PowerPages.Websites.Read/Write). The az CLI
+// first-party client is NOT authorized for them, so it
+// 403s (InsufficientDelegatedPermissions).
+// 'az' → az account get-access-token against the
+// ring host's resource (prod, where the signed-in cloud
+// token is already scoped).
+// bapStrategy how the admin env list is fetched:
+// 'pac' → `pac admin list --json` (follows PAC's signed-in
+// cloud; correct for Prod).
+// 'rest' → direct GET to bapHost (correct for TIP, which
+// `pac admin list` cannot reach without a Preprod sign-in).
+// bapHost BAP host for the 'rest' strategy.
+// bapResource az token audience for the BAP REST call.
+//
+// NOTE the TIP hosts are api.preprod.powerplatform.com / tip1.api.bap.microsoft
+// .com — the `api.tip...` form does NOT resolve in DNS (verified 2026-07).
+// ---------------------------------------------------------------------------
+const DEFAULT_RINGS = Object.freeze({
+ TIP: Object.freeze({
+ label: 'TIP',
+ gatewayHost: 'https://api.preprod.powerplatform.com',
+ gatewayHostEnv: 'PP_GOV_TIP_HOST',
+ tokenStrategy: 'device-code',
+ bapStrategy: 'rest',
+ bapHost: 'https://tip1.api.bap.microsoft.com',
+ bapResource: 'https://service.powerapps.com/',
+ }),
+ Prod: Object.freeze({
+ label: 'Prod',
+ gatewayHost: 'https://api.powerplatform.com',
+ gatewayHostEnv: null,
+ tokenStrategy: 'az',
+ bapStrategy: 'pac',
+ bapHost: 'https://api.bap.microsoft.com',
+ bapResource: 'https://service.powerapps.com/',
+ }),
+});
+
+// The routing config file, co-located so a marketplace install (which copies
+// only the plugin dir) always ships it beside the code.
+const CONFIG_PATH = path.join(__dirname, 'app-settings.json');
+
+function stripTrailingSlashes(s) {
+ return String(s == null ? '' : s).trim().replace(/\/+$/, '');
+}
+
+// Memoize the parsed config for the process — app-settings.json is read-only
+// routing config, so re-forking fs on every governance call is wasted work.
+let cachedConfig;
+
+// Load + normalize app-settings.json. Fail-open: a missing file, IO error, or
+// invalid JSON all resolve to DEFAULT_RINGS rather than throwing — a governance
+// call must never break because the config was deleted or fat-fingered.
+// DEFAULT_RINGS remain the fail-open fallback when the file is absent/unusable.
+function loadConfig(filePath) {
+ if (!filePath && cachedConfig !== undefined) return cachedConfig;
+ let raw = {};
+ try {
+ raw = JSON.parse(fs.readFileSync(filePath || CONFIG_PATH, 'utf8'));
+ } catch {
+ raw = {};
+ }
+ const r = raw && typeof raw === 'object' ? raw : {};
+
+ // activeRing: accept case-insensitive TIP/preprod/test and Prod/production;
+ // ignore junk (→ null, so resolveRing falls through to its default).
+ let activeRing = null;
+ const ar = String(r.activeRing || '').trim().toLowerCase();
+ if (ar === 'tip' || ar === 'preprod' || ar === 'test') activeRing = 'TIP';
+ else if (ar.startsWith('prod')) activeRing = 'Prod';
+
+ const targetEnv = typeof r.targetEnv === 'string' ? r.targetEnv.trim() : '';
+
+ // Merge each file ring over its default. Accept legacy `host` as an alias for
+ // `gatewayHost` so an older single-host config still routes the gateway.
+ const rings = {};
+ for (const key of Object.keys(DEFAULT_RINGS)) {
+ const base = DEFAULT_RINGS[key];
+ const over = (r.rings && typeof r.rings === 'object' && r.rings[key]) || {};
+ rings[key] = Object.freeze({
+ label: base.label,
+ gatewayHost: stripTrailingSlashes(over.gatewayHost || over.host || base.gatewayHost),
+ gatewayHostEnv: base.gatewayHostEnv,
+ tokenStrategy: over.tokenStrategy || base.tokenStrategy,
+ bapStrategy: over.bapStrategy || base.bapStrategy,
+ bapHost: stripTrailingSlashes(over.bapHost || base.bapHost),
+ bapResource: over.bapResource || base.bapResource,
+ });
+ }
+
+ const cfg = Object.freeze({ activeRing, targetEnv, rings: Object.freeze(rings) });
+ if (!filePath) cachedConfig = cfg;
+ return cfg;
+}
+
+// Test-only seam: drop the process cache so a case can load a fresh fixture.
+function resetConfigCache() {
+ cachedConfig = undefined;
+}
+
+// Kept as a shared helper for existing callers/tests that still need the repo's
+// standard truthy parsing semantics, even though ring selection no longer uses
+// PP_GOV_PROD/PP_GOV_RING.
+function isTruthyFlag(v) {
+ if (v == null) return false;
+ return ['1', 'true', 'yes', 'on'].includes(String(v).trim().toLowerCase());
+}
+
+// THE central switch. Resolve which ring key ('TIP' | 'Prod') is active.
+// app-settings.json is the source of truth for ring selection. Runtime env vars
+// may still override hosts/tokens inside the chosen ring, but they do not get to
+// switch the ring away from the bundled config.
+function resolveRing(env) {
+ const cfg = loadConfig();
+ if (cfg.activeRing && DEFAULT_RINGS[cfg.activeRing]) return cfg.activeRing;
+ return 'TIP';
+}
+
+// The merged (defaults + app-settings.json overrides) ring object for the
+// active (or a named) ring. This is the single lookup both the gateway and BAP
+// paths use, so the same switch drives every endpoint.
+function getRing(env, ringName) {
+ const key = ringName || resolveRing(env);
+ const cfg = loadConfig();
+ return (cfg.rings && cfg.rings[key]) || DEFAULT_RINGS[key];
+}
+
+// Back-compat: a RINGS-shaped view (`.host` / `.hostEnv` / `.tokenStrategy`)
+// built from DEFAULT_RINGS for callers/tests that read the old shape.
+const RINGS = Object.freeze({
+ TIP: Object.freeze({
+ label: DEFAULT_RINGS.TIP.label,
+ host: DEFAULT_RINGS.TIP.gatewayHost,
+ hostEnv: DEFAULT_RINGS.TIP.gatewayHostEnv,
+ tokenStrategy: DEFAULT_RINGS.TIP.tokenStrategy,
+ }),
+ Prod: Object.freeze({
+ label: DEFAULT_RINGS.Prod.label,
+ host: DEFAULT_RINGS.Prod.gatewayHost,
+ hostEnv: DEFAULT_RINGS.Prod.gatewayHostEnv,
+ tokenStrategy: DEFAULT_RINGS.Prod.tokenStrategy,
+ }),
+});
+
+// TIP/Preprod is the DEFAULT ring for this skill (the team targets Preprod
+// first); Prod is the opt-out. Kept as named exports for back-compat.
+const TIP_GATEWAY_HOST = RINGS.TIP.host;
+const PROD_GATEWAY_HOST = RINGS.Prod.host;
+
+// Default target environment when a script gets no --envId. PP_GOV_ENV_ID wins
+// over the file (env-vars-first precedence); returns null when neither is set so
+// the caller falls back to the signed-in PAC env.
+function resolveTargetEnv(env) {
+ const e = env || process.env;
+ const fromEnv = (e.PP_GOV_ENV_ID || '').trim();
+ if (fromEnv) return fromEnv;
+ return loadConfig().targetEnv || null;
+}
+
+// Effective gateway host for the active ring. Explicit PP_GOV_API_HOST always
+// wins (pin an arbitrary host); otherwise the ring's gatewayHost (or its
+// per-ring hostEnv override) decides. For Prod we prefer the host resolveContext
+// already computed from the signed-in cloud (gov clouds etc.), falling back to
+// the ring host.
+function resolveHostOverride(env, prodApiHost) {
+ const e = env || process.env;
+ if (e.PP_GOV_API_HOST && e.PP_GOV_API_HOST.trim()) {
+ return e.PP_GOV_API_HOST.trim().replace(/\/+$/, '');
+ }
+ const ring = getRing(e);
+ // Prod: honor the signed-in cloud host (could be a gov cloud) over the
+ // config default. TIP: the config host is authoritative.
+ if (ring.label === 'Prod' && prodApiHost) {
+ return prodApiHost.replace(/\/+$/, '');
+ }
+ const perRingOverride = ring.gatewayHostEnv ? e[ring.gatewayHostEnv] : null;
+ return (perRingOverride || ring.gatewayHost).trim().replace(/\/+$/, '');
+}
+
+// Rewrite ONLY the scheme+authority of the env-scoped base URL, preserving the
+// /powerpages/environments/{envId} path.
+function applyHostOverride(ctx, host) {
+ const clean = host.replace(/\/+$/, '');
+ ctx.baseUrl = ctx.baseUrl.replace(/^https?:\/\/[^/]+/, clean);
+ ctx.apiHost = clean;
+ return ctx;
+}
+
+function applyEnvOverride(context, envId) {
+ if (!envId || typeof envId !== 'string') return context;
+ context.baseUrl = context.baseUrl.replace(
+ /\/environments\/[^/]+/,
+ `/environments/${encodeURIComponent(envId)}`
+ );
+ context.environmentId = envId;
+ return context;
+}
+
+// Build the AAD token *resource* (audience) for a gateway host. The Power
+// Platform API resource principal is the host with a single trailing slash,
+// e.g. `https://api.preprod.powerplatform.com/` — az returns
+// `aud=https://api.preprod.powerplatform.com/` for that value and the Preprod
+// gateway rejects (401) a token minted for the prod audience.
+function resourceForHost(host) {
+ return host.replace(/\/+$/, '') + '/';
+}
+
+// Synchronously obtain a TIP token via the device-code helper. The governance
+// call path is synchronous (resolveGovernanceContext returns a plain object), so
+// we run the async device-code/refresh flow in a child process and capture its
+// stdout. stderr is inherited so the one-time "open this URL / enter this code"
+// prompt reaches the operator live; a cached/refreshable token returns instantly
+// with no prompt. Returns null on any failure so the caller can fall back.
+function getTipTokenSync(env) {
+ const cfg = resolveTipConfig(env);
+ if (cfg.error) return null;
+ try {
+ // Use this Node runtime and argv so install paths never pass through a shell.
+ const out = execFileSync(process.execPath, [path.join(__dirname, 'tip-auth.js')], {
+ encoding: 'utf8',
+ // stdin ignored, stdout captured (the token), stderr inherited (prompt).
+ stdio: ['ignore', 'pipe', 'inherit'],
+ // Device-code sign-in can take a while; allow the full device-code lifetime.
+ timeout: 15 * 60 * 1000,
+ env,
+ });
+ const token = (out || '').trim();
+ return token || null;
+ } catch {
+ return null;
+ }
+}
+
+function resolveGovernanceContext(envId, env) {
+ const e = env || process.env;
+ const ctx = resolveContext();
+ if (ctx.error) return ctx;
+
+ // ONE switch → ring → { gatewayHost, tokenStrategy, ... }. Host is rewritten
+ // onto the env-scoped base URL (scheme+authority only) before the request.
+ const ring = getRing(e);
+ const host = resolveHostOverride(e, ctx.apiHost);
+ const hostChanged = host !== (ctx.apiHost || '').replace(/\/+$/, '');
+ if (hostChanged) applyHostOverride(ctx, host);
+
+ // Token resolution, driven by the SAME ring lookup:
+ // 1. PP_GOV_TOKEN — explicit bearer always wins (paste a portal/ring token).
+ // 2. tokenStrategy 'device-code' — custom-app token via tip-auth.js, the
+ // ONLY token carrying the PowerPages delegated scopes.
+ // 3. tokenStrategy 'az' — az mint against the (possibly overridden) host's
+ // resource; skipped when the host is unchanged since resolveContext()
+ // already minted the right prod token.
+ if (e.PP_GOV_TOKEN && e.PP_GOV_TOKEN.trim()) {
+ ctx.token = e.PP_GOV_TOKEN.trim();
+ } else if (ring.tokenStrategy === 'device-code') {
+ const tipToken = getTipTokenSync(e);
+ if (tipToken) {
+ ctx.token = tipToken;
+ } else {
+ // No custom-app config (or the flow failed). Fall back to an az mint for
+ // the ring resource so reads that don't need PowerPages scopes still work,
+ // and tell the operator how to unblock scoped writes.
+ const fallback = getAuthToken(tokenResourceFor(e, host));
+ if (fallback) ctx.token = fallback;
+ process.stderr.write(
+ `${ring.label} ring uses device-code auth but no token was generated. Set ` +
+ 'PP_GOV_TIP_CLIENT_ID + PP_GOV_TIP_TENANT (a custom app with ' +
+ 'PowerPages.Websites.Read/Write) or paste a scoped token via PP_GOV_TOKEN. ' +
+ 'Falling back to an az-minted token, which lacks PowerPages scopes and will ' +
+ '403 on governance calls.\n'
+ );
+ }
+ } else if (hostChanged) {
+ // 'az' strategy with an overridden host — re-mint for that host's resource
+ // since resolveContext() minted against the default cloud resource.
+ const hostToken = getAuthToken(tokenResourceFor(e, host));
+ if (hostToken) ctx.token = hostToken;
+ }
+
+ // Default the environment from app-settings.json (targetEnv) / PP_GOV_ENV_ID
+ // when the caller passed no explicit --envId, so a single config value can
+ // pin the test env for the whole skill.
+ const effectiveEnvId = envId || resolveTargetEnv(e);
+ return applyEnvOverride(ctx, effectiveEnvId);
+}
+
+// The AAD token resource (audience) to mint against. PP_GOV_TOKEN_RESOURCE lets
+// advanced callers override the audience when it differs from the host.
+function tokenResourceFor(env, host) {
+ const e = env || process.env;
+ return e.PP_GOV_TOKEN_RESOURCE ? e.PP_GOV_TOKEN_RESOURCE.trim() : resourceForHost(host);
+}
+
+module.exports = {
+ resolveGovernanceContext,
+ applyEnvOverride,
+ applyHostOverride,
+ resolveHostOverride,
+ resolveRing,
+ getRing,
+ loadConfig,
+ resetConfigCache,
+ resolveTargetEnv,
+ resourceForHost,
+ tokenResourceFor,
+ isTruthyFlag,
+ getTipTokenSync,
+ DEFAULT_RINGS,
+ CONFIG_PATH,
+ RINGS,
+ TIP_GATEWAY_HOST,
+ PROD_GATEWAY_HOST,
+};
diff --git a/plugins/power-pages/skills/manage-governance/scripts/governance-route.js b/plugins/power-pages/skills/manage-governance/scripts/governance-route.js
new file mode 100644
index 000000000..b5f198cf9
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/governance-route.js
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+
+// Builds the URL, and (optional) body for each governance API call.
+//
+// Single transport — the gateway:
+// Base: https://api.powerplatform.com/powerpages/environments/{envId}
+// Auth: Azure CLI bearer token (resource = apiHost)
+// The env-scoped base URL is supplied by resolveContext + governance-context,
+// so gateway routes are env-relative and the env id is embedded once in the
+// base URL rather than repeated in every op's path.
+
+'use strict';
+
+/**
+ * Builds a route descriptor for a governance operation.
+ *
+ * @param {object} args
+ * @param {'apply'|'getEnv'|'getStatus'|'getPortal'|'getDetails'} args.op
+ * @param {string} args.envId - Target environment id (always required).
+ * @param {string} [args.policy] - Policy name (required for everything but `apply` when env-wide).
+ * @param {string} [args.portalId] - Portal id (required for getPortal, optional for apply).
+ * @returns {{ method: string, path: string, transport: string }}
+ */
+function buildRoute(args) {
+ const { op, envId, policy, portalId } = args || {};
+ if (!op) throw new Error('buildRoute: op is required');
+ if (!envId) throw new Error('buildRoute: envId is required');
+ // getEnv/getStatus/getPortal/getDetails all encode `policy` into the path;
+ // a missing value would silently build `/governance/undefined` and 404 with
+ // a confusing URL instead of failing fast here. `apply` is exempt — its
+ // policy travels in the POST body, not the path.
+ if (op !== 'apply' && !policy) throw new Error('buildRoute: policy is required');
+ // getPortal is the only op that encodes portalId into the path.
+ if (op === 'getPortal' && !portalId) throw new Error('buildRoute: portalId is required');
+
+ // Gateway transport. The shared power-platform-api client supplies the
+ // env-scoped base URL, so gateway routes are env-relative and the env id
+ // does NOT repeat in the path.
+ switch (op) {
+ case 'apply':
+ return { method: 'POST', path: '/governance', transport: 'gateway' };
+ case 'getEnv':
+ return {
+ method: 'GET',
+ path: `/governance/${encodeURIComponent(policy)}`,
+ transport: 'gateway',
+ };
+ case 'getStatus':
+ return {
+ method: 'GET',
+ path: `/governance/status/${encodeURIComponent(policy)}`,
+ transport: 'gateway',
+ };
+ case 'getPortal':
+ return {
+ method: 'GET',
+ path: `/websites/${encodeURIComponent(portalId)}/governance/${encodeURIComponent(policy)}`,
+ transport: 'gateway',
+ };
+ case 'getDetails':
+ return {
+ method: 'GET',
+ path: `/governance/${encodeURIComponent(policy)}/details`,
+ transport: 'gateway',
+ };
+ default:
+ throw new Error(`buildRoute: unknown op "${op}"`);
+ }
+}
+
+module.exports = {
+ buildRoute,
+};
diff --git a/plugins/power-pages/skills/manage-governance/scripts/governance-transport.js b/plugins/power-pages/skills/manage-governance/scripts/governance-transport.js
new file mode 100644
index 000000000..b192faf4f
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/governance-transport.js
@@ -0,0 +1,100 @@
+#!/usr/bin/env node
+
+// Single network entry-point each script calls. All governance traffic goes
+// through the gateway transport only (api.powerplatform.com). The shared
+// resolveContext() + request() helper appends the api-version query param
+// automatically and issues the call against the env-scoped base URL. There is
+// no admin-portal / sitewide transport — every op resolves to the gateway.
+
+'use strict';
+
+const {
+ request,
+} = require('../../../scripts/lib/power-platform-api');
+const {
+ resolveGovernanceContext,
+} = require('./governance-context');
+const {
+ buildRoute,
+} = require('./governance-route');
+
+/**
+ * Issues a governance API call against the gateway. Caller fills out the
+ * op + envId + policy + portalId in `args`; we pick the URL shape and hand back
+ * a uniform `{ ok, statusCode, body, error }` envelope.
+ *
+ * Use this from each script instead of calling request() yourself.
+ *
+ * @param {object} args
+ * @param {'apply'|'getEnv'|'getStatus'|'getPortal'|'getDetails'} args.op
+ * @param {string} [args.envId] - Defaults to the resolved context's environment.
+ * @param {string} [args.policy]
+ * @param {string} [args.portalId]
+ * @param {object} [args.body] - POST body (apply op only).
+ * @param {object} [args.context] - Pre-resolved governance context.
+ * Resolving the context mints a bearer via a `tip-auth.js` SUBPROCESS
+ * (`execFileSync`), so a caller issuing many calls for the same env should
+ * resolve ONCE with `resolveGovernanceContext(envId)` and pass it here to
+ * every call — otherwise each call re-spawns the token helper. When omitted
+ * we resolve per-call (the original single-call behavior).
+ * @param {number} [args.timeout] - Per-request timeout (ms). Defaults
+ * to the request() default (15s). Raise it for slow gateways / parallel
+ * batches where the shared server is slower under concurrent load.
+ * @returns {Promise<{ ok: boolean, statusCode: number, body: any, transport: string, error?: { code: string, message: string } }>}
+ */
+async function callGovernance(args) {
+ // Gateway transport: env id goes into the base URL via resolveGovernanceContext,
+ // which also carries the Azure CLI bearer token (see governance-context.js).
+ // A caller may pass a pre-resolved `context` to avoid re-minting the token on
+ // every call (each mint is a blocking tip-auth.js subprocess).
+ const ctx = args.context || resolveGovernanceContext(args.envId);
+ if (ctx.error) {
+ return {
+ ok: false,
+ statusCode: 0,
+ body: null,
+ transport: 'gateway',
+ error: { code: 'ContextError', message: ctx.error },
+ };
+ }
+ // The route guard requires an environment, but omitted --envId is valid:
+ // resolve it from the current/configured context before checking the route.
+ const envId = args.envId || ctx.environmentId;
+ if (!envId) {
+ return {
+ ok: false,
+ statusCode: 0,
+ body: null,
+ transport: 'gateway',
+ error: {
+ code: 'ContextError',
+ message: 'No environment could be resolved. Supply --envId or select a current PAC environment.',
+ },
+ };
+ }
+ const route = buildRoute({ ...args, envId });
+ const res = await request({
+ context: ctx,
+ method: route.method,
+ path: route.path,
+ body: args.body,
+ ...(args.timeout != null && { timeout: args.timeout }),
+ });
+ // Only GET /governance/{policy} documents 404 as "never applied".
+ // Model its disabled scope while retaining absence explicitly; a missing
+ // site, rollout, details endpoint, or rejected write is still an error.
+ if (args.op === 'getEnv' && res.statusCode === 404) {
+ return {
+ ok: true,
+ statusCode: 404,
+ body: 'None',
+ settingPresent: false,
+ transport: 'gateway',
+ };
+ }
+ return { ...res, transport: 'gateway' };
+}
+
+module.exports = {
+ callGovernance,
+};
diff --git a/plugins/power-pages/skills/manage-governance/scripts/list-envs.js b/plugins/power-pages/skills/manage-governance/scripts/list-envs.js
new file mode 100644
index 000000000..1af0da26f
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/list-envs.js
@@ -0,0 +1,166 @@
+#!/usr/bin/env node
+
+// list-envs.js — Lists Power Platform environments the signed-in user has
+// admin access to. Backed by `pac admin list --json` via the shared shim.
+//
+// The environment inventory is intentionally fetched fresh on every invocation.
+// Governance targets are admin-sensitive, so the picker must reflect the API's
+// current environment list rather than a TTL or file cache.
+
+const https = require('https');
+const {
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+const { getAuthToken } = require('../../../scripts/lib/validation-helpers');
+const { listEnvsViaPac } = require('../../../scripts/lib/pac-bap-shim');
+const { resolveRing, getRing } = require('./governance-context');
+
+const BAP_REQUEST_TIMEOUT_MS = 60_000;
+
+const HELP = `list-envs.js — Lists Power Platform environments visible to the signed-in PAC profile.
+
+Routing follows the manage-governance ring switch from app-settings.json activeRing:
+ Prod ring → 'pac admin list --json' (follows PAC's signed-in cloud).
+ TIP ring → direct BAP REST GET against the ring's bapHost
+ (tip1.api.bap.microsoft.com) with an az token — PAC cannot reach
+ the Preprod BAP without a separate sign-in.
+ The REST request has a 60-second total timeout.
+
+Usage:
+ node list-envs.js [--type <Production|Sandbox|Trial|Developer|Default>]
+
+Flags:
+ --type Optional filter on environment SKU.
+ --help Show this help message.
+
+Exit codes:
+ 0 Success (including empty result)
+ 2 Sign-in required
+ 1 Other failure
+
+Stdout (JSON):
+ { "status": "ok", "ring": "TIP|Prod",
+ "envs": [ { "envId", "displayName", "envUrl", "type", "domain" } ] }
+`;
+
+function normalize(bapShapedEnv) {
+ const props = bapShapedEnv.properties || {};
+ const meta = props.linkedEnvironmentMetadata || {};
+ return {
+ envId: bapShapedEnv.name || null,
+ displayName: props.displayName || null,
+ envUrl: meta.instanceUrl || null,
+ type: props.environmentSku || null,
+ domain: meta.domainName || null,
+ };
+}
+
+// Fetch the admin env list straight from the BAP REST API for the TIP/Preprod
+// ring, which `pac admin list` cannot reach without a separate Preprod sign-in.
+// The endpoint returns the same BAP-shaped records `normalize()` already
+// consumes, wrapped in `{ value: [...] }`. Example (trimmed):
+// GET https://tip1.api.bap.microsoft.com/providers/Microsoft.BusinessAppPlatform/scopes/admin/environments?api-version=2020-10-01
+// { "value": [ { "name": "<envId>",
+// "properties": { "displayName": "...", "environmentSku": "Sandbox",
+// "linkedEnvironmentMetadata": { "instanceUrl": "https://...", "domainName": "..." } } } ] }
+function fetchEnvsViaBapRest(bapHost, token) {
+ const url =
+ `${bapHost.replace(/\/+$/, '')}` +
+ '/providers/Microsoft.BusinessAppPlatform/scopes/admin/environments?api-version=2020-10-01';
+ let timer;
+ return new Promise((resolve, reject) => {
+ const req = https.get(
+ url,
+ { headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' } },
+ (res) => {
+ let data = '';
+ res.on('error', reject);
+ res.on('data', (c) => (data += c));
+ res.on('end', () => {
+ if (res.statusCode < 200 || res.statusCode >= 300) {
+ return reject(
+ new Error(`BAP REST returned ${res.statusCode}: ${String(data).slice(0, 300)}`)
+ );
+ }
+ try {
+ const parsed = JSON.parse(data);
+ resolve(Array.isArray(parsed.value) ? parsed.value : []);
+ } catch (e) {
+ reject(new Error(`Failed to parse BAP REST response: ${e.message}`));
+ }
+ });
+ }
+ );
+ req.on('error', reject);
+ // A total deadline also bounds DNS/TLS setup and a response that keeps
+ // trickling data; a socket inactivity timeout alone would not cover both.
+ timer = setTimeout(() => {
+ const error = new Error('BAP environment-list request timed out after 60 seconds.');
+ req.destroy(error);
+ reject(error);
+ }, BAP_REQUEST_TIMEOUT_MS);
+ }).finally(() => clearTimeout(timer));
+}
+
+// Fetch the raw BAP-shaped env list using the strategy the active ring dictates
+// (the SAME switch that routes the governance gateway):
+// bapStrategy 'pac' → `pac admin list --json` (follows PAC's signed-in cloud;
+// used for Prod).
+// bapStrategy 'rest' → direct BAP REST GET against the ring's bapHost with an
+// az token for bapResource (used for TIP).
+async function fetchRawEnvs(env) {
+ const ring = getRing(env);
+ if (ring.bapStrategy === 'rest') {
+ const token = getAuthToken(ring.bapResource);
+ if (!token) {
+ // No az token for the BAP audience → the user is signed out of az.
+ const e = new Error(
+ `Azure CLI is not signed in (needed for the ${ring.label} BAP REST call). Run: az login`
+ );
+ e.signInRequired = true;
+ throw e;
+ }
+ return fetchEnvsViaBapRest(ring.bapHost, token);
+ }
+ // Default / 'pac' strategy: the canonical `pac admin list` path.
+ return listEnvsViaPac();
+}
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ const env = { ...process.env };
+ const ringKey = resolveRing(env);
+
+ let rawEnvs;
+ try {
+ rawEnvs = await fetchRawEnvs(env);
+ } catch (e) {
+ const msg = e && e.message ? e.message : String(e);
+ // Either explicit sign-in flag (BAP REST) or the pac shim's sign-out prose.
+ if (e.signInRequired || /not signed in|sign in|authentication/i.test(msg)) {
+ fail(`Sign-in required for the ${ringKey} ring. ${msg}`, 2);
+ }
+ fail(`Failed to list environments (${ringKey} ring): ${msg}`, 1);
+ }
+
+ let normalized = rawEnvs.map(normalize).filter((e) => e.envId);
+ if (args.type) {
+ const filter = String(args.type).toLowerCase();
+ normalized = normalized.filter((e) => (e.type || '').toLowerCase() === filter);
+ }
+
+ process.stdout.write(
+ JSON.stringify({ status: 'ok', ring: ringKey, envs: normalized }, null, 2) + '\n'
+ );
+}
+
+module.exports = { normalize, fetchEnvsViaBapRest, fetchRawEnvs };
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-governance/scripts/list-portals.js b/plugins/power-pages/skills/manage-governance/scripts/list-portals.js
new file mode 100644
index 000000000..1d8f8021b
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/list-portals.js
@@ -0,0 +1,157 @@
+#!/usr/bin/env node
+
+// list-portals.js — Lists Power Pages portals (websites) in an environment.
+//
+// gateway transport (the only transport): GET /websites on
+// api.powerplatform.com, env-scoped via base URL. The
+// client sends plain `select` (and `skip`) query keys —
+// NOT OData `$select`/`$skip` — which the gateway maps.
+// Paginates via @odata.nextLink.
+
+const {
+ request,
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+const { resolveGovernanceContext } = require('./governance-context');
+
+const HELP = `list-portals.js — Lists Power Pages portals in an environment.
+
+Usage:
+ node list-portals.js [--envId <guid>]
+
+Flags:
+ --envId Power Platform environment id. When omitted, uses the env
+ the PAC profile is currently signed into.
+ --help Show this help message.
+
+Exit codes:
+ 0 Success (including empty result)
+ 2 Sign-in required
+ 1 Other failure
+
+Stdout (JSON):
+ { "status": "ok", "transport": "gateway",
+ "portals": [ { "portalId", "name", "websiteUrl", "websiteRecordId",
+ "type", "status", "createdOn" } ] }
+`;
+
+const FIELDS = ['Id', 'Name', 'WebsiteUrl', 'WebsiteRecordId', 'Type', 'Status', 'CreatedOn'].join(',');
+const MAX_PAGES = 500;
+
+// Default display cap for the portal picker: show at most this many rows.
+const DISPLAY_LIMIT = 10;
+
+function nextSkipFrom(nextLink) {
+ if (typeof nextLink !== 'string') return null;
+ const match = nextLink.match(/[?&]skip=(\d+)/i);
+ if (!match) return null;
+ const value = Number.parseInt(match[1], 10);
+ return Number.isInteger(value) && value > 0 ? value : null;
+}
+
+function normalize(site) {
+ // The gateway /websites response is camelCase on preprod (id, name,
+ // websiteUrl, ...) but PascalCase on some rings. Accept either casing so the
+ // portal list isn't silently filtered to empty.
+ return {
+ portalId: site.id || site.Id || null,
+ name: site.name || site.Name || null,
+ websiteUrl: site.websiteUrl || site.WebsiteUrl || null,
+ websiteRecordId: site.websiteRecordId || site.WebsiteRecordId || null,
+ type: site.type || site.Type || null,
+ status: site.status || site.Status || null,
+ createdOn: site.createdOn || site.CreatedOn || site.created || site.Created || null,
+ };
+}
+
+// Prioritized ordering for the portal picker. When the environment has more
+// than `limit` portals, the full list is too long to render — so we surface
+// the most relevant `limit` rows using the ordering the skill defines:
+// 1. Production application type first (type === "Production").
+// 2. Then StateConfigured status (status === "StateConfigured").
+// 3. Then oldest-first by createdOn (ascending).
+// When the env has `limit` portals or fewer, the original order is preserved
+// (the special ordering only kicks in when we actually have to truncate).
+// Returns { shown, total, truncated, limit } — `shown` is the capped list to
+// render; `total` is the full count so the caller can note "showing N of M".
+function compareForDisplay(a, b) {
+ const isProd = (p) => String(p.type || '').trim().toLowerCase() === 'production';
+ const isConfigured = (p) => String(p.status || '').trim().toLowerCase() === 'stateconfigured';
+ const createdMs = (p) => {
+ const t = Date.parse(p.createdOn || '');
+ return Number.isNaN(t) ? Number.POSITIVE_INFINITY : t;
+ };
+ const prodRank = (isProd(a) ? 0 : 1) - (isProd(b) ? 0 : 1);
+ if (prodRank !== 0) return prodRank;
+ const configuredRank = (isConfigured(a) ? 0 : 1) - (isConfigured(b) ? 0 : 1);
+ if (configuredRank !== 0) return configuredRank;
+ return createdMs(a) - createdMs(b);
+}
+
+function orderPortalsForDisplay(portals, limit = DISPLAY_LIMIT) {
+ const list = Array.isArray(portals) ? portals.slice() : [];
+ const total = list.length;
+ if (total <= limit) {
+ return { shown: list, total, truncated: false, limit };
+ }
+ list.sort(compareForDisplay);
+ return { shown: list.slice(0, limit), total, truncated: true, limit };
+}
+
+async function listViaGateway(args) {
+ const ctx = resolveGovernanceContext(args.envId);
+ if (ctx.error) fail(ctx.error, 2);
+
+ const { portals, error } = await fetchPortalsPaged(ctx);
+ if (error) fail(error, 1);
+ return { transport: 'gateway', portals };
+}
+
+// Page through GET /websites for a PRE-RESOLVED context and return the
+// normalized portal records. Split out from listViaGateway so other scripts
+// (e.g. fetch-env-status.js) can fetch the site list as ONE promise inside a
+// parallel Promise.all batch — sharing the same governance context/token
+// instead of re-resolving it. Returns { portals, error }: a non-null `error`
+// string means a page read failed (the caller decides whether to fail() or
+// tolerate a partial list); `portals` always holds whatever was read so far.
+async function fetchPortalsPaged(ctx) {
+ const portals = [];
+ let skip;
+ for (let page = 0; page < MAX_PAGES; page += 1) {
+ const query = { select: FIELDS };
+ if (skip !== undefined) query.skip = String(skip);
+ const res = await request({ context: ctx, method: 'GET', path: '/websites', query });
+ if (!res.ok) {
+ return { portals, error: `List portals failed (${res.statusCode}): ${res.error?.message || ''}` };
+ }
+ const body = res.body && typeof res.body === 'object' ? res.body : {};
+ for (const site of body.value || []) {
+ const n = normalize(site);
+ if (n.portalId) portals.push(n);
+ }
+ const advance = nextSkipFrom(body['@odata.nextLink'] || body.nextLink);
+ if (advance == null || advance <= (skip ?? 0)) break;
+ skip = advance;
+ }
+ return { portals };
+}
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ const result = await listViaGateway(args);
+
+ process.stdout.write(
+ JSON.stringify({ status: 'ok', ...result }, null, 2) + '\n'
+ );
+}
+
+module.exports = { nextSkipFrom, normalize, compareForDisplay, orderPortalsForDisplay, fetchPortalsPaged, DISPLAY_LIMIT };
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-governance/scripts/parse-portal-input.js b/plugins/power-pages/skills/manage-governance/scripts/parse-portal-input.js
new file mode 100644
index 000000000..09c103613
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/parse-portal-input.js
@@ -0,0 +1,212 @@
+#!/usr/bin/env node
+
+// parse-portal-input.js — Parses free-text portal input from the user during
+// Phase 4.2 (apply) or Phase 4.4 (fetch portal) of the manage-governance skill
+// into a structured policy spec.
+//
+// Accepted inputs (case-insensitive on keywords; case-insensitive name match):
+// "all" → { policyValue: "All", portalIds: [] }
+// "none" → { policyValue: "None", portalIds: [] }
+// "<id>" / "<id>, <id>, …" → { policyValue: "Include", portalIds: [...] }
+// "<name>" / "<name>, <name>, …" → { policyValue: "Include", portalIds: [...] }
+// "<id>, <name>, …" → mixed ids and names — both work, in any order
+// "not <id|name>, …" → { policyValue: "Exclude", portalIds: [...] }
+// "except <id|name>, …" → alias for "not"
+//
+// When `validIds` is supplied, every parsed token is matched (case-insensitive)
+// against the list — by `portalId` first, then by `name`. Unknown tokens land
+// in `errors`. Names resolved from `validIds` (when entries are objects with
+// {portalId, name}) land in `resolvedNames` so callers can echo a friendly
+// summary on the consent gate.
+// Names matching multiple distinct site IDs are rejected; callers must ask
+// for an exact ID rather than choosing a site from inventory order.
+// An explicitly empty site list accepts only "all" for environment-wide scope;
+// it must never fall back to accepting unverified site IDs.
+//
+// Without `validIds`, only UUIDs are accepted as portal tokens; names cannot
+// be resolved with no list to match against and are rejected.
+//
+// Use it like:
+// const parsed = parsePortalInput(text, { validIds: portalList });
+// if (parsed.errors.length) { /* tell user; reprompt */ }
+
+'use strict';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const NOT_RE = /^\s*(not|except)\b\s*/i;
+
+/**
+ * @param {string} input
+ * @param {object} [opts]
+ * @param {Array<string|{portalId:string,name?:string}>} [opts.validIds]
+ * @returns {{ policyValue: string, portalIds: string[], resolvedNames?: string[], errors: string[] }}
+ */
+function parsePortalInput(input, opts = {}) {
+ const errors = [];
+ const valid = normalizeValidIds(opts.validIds);
+ if (valid && valid.byId.size === 0 && !/^all$/i.test(String(input ?? '').trim())) {
+ return makeResult(null, [], [], [
+ 'This environment has no sites. Enter "all" for environment-wide site selection, or cancel.',
+ ]);
+ }
+ if (input == null) {
+ errors.push('Empty input. Expected "all", "none", "<id>, <id>", or "not <id>, <id>".');
+ return makeResult(null, [], [], errors);
+ }
+ let s = String(input).trim();
+ if (s === '') {
+ errors.push('Empty input. Expected "all", "none", "<id>, <id>", or "not <id>, <id>".');
+ return makeResult(null, [], [], errors);
+ }
+ if (/^all$/i.test(s)) return makeResult('All', [], [], []);
+ if (/^none$/i.test(s)) return makeResult('None', [], [], []);
+
+ let mode = 'Include';
+ if (NOT_RE.test(s)) {
+ mode = 'Exclude';
+ s = s.replace(NOT_RE, '');
+ }
+
+ const rawTokens = s
+ .split(/[,\n]/)
+ .map((t) => t.trim())
+ .filter(Boolean);
+ if (rawTokens.length === 0) {
+ errors.push('No portal ids found after the keyword. Provide at least one id.');
+ return makeResult(null, [], [], errors);
+ }
+
+ const portalIds = [];
+ const resolvedNames = [];
+ const seen = new Set();
+
+ for (const tok of rawTokens) {
+ const isUuid = UUID_RE.test(tok);
+
+ if (isUuid) {
+ const id = tok;
+ const lower = id.toLowerCase();
+ if (seen.has(lower)) continue;
+ seen.add(lower);
+ if (valid) {
+ const entry = valid.byId.get(lower);
+ if (!entry) {
+ errors.push(`Site id not in the listed sites: ${id}.`);
+ continue;
+ }
+ portalIds.push(entry.portalId);
+ if (entry.name) resolvedNames.push(entry.name);
+ } else {
+ portalIds.push(id);
+ }
+ continue;
+ }
+
+ // Not a UUID — try to resolve by name from the validIds list.
+ if (!valid) {
+ errors.push(`Not a valid site id and no site list was provided to resolve "${tok}" by name.`);
+ continue;
+ }
+ const matches = valid.byName.get(tok.toLowerCase());
+ if (!matches) {
+ errors.push(`No site matched "${tok}" — not a known id or name.`);
+ continue;
+ }
+ if (matches.size > 1) {
+ const ids = [...matches.values()].map((entry) => entry.portalId).join(', ');
+ errors.push(`Site name "${tok}" is ambiguous. Matching site IDs: ${ids}. Provide the exact site ID or cancel.`);
+ continue;
+ }
+ const entry = matches.values().next().value;
+ const lower = entry.portalId.toLowerCase();
+ if (seen.has(lower)) continue;
+ seen.add(lower);
+ portalIds.push(entry.portalId);
+ if (entry.name) resolvedNames.push(entry.name);
+ }
+
+ if (errors.length > 0) return makeResult(null, [], [], errors);
+ if (portalIds.length === 0) {
+ errors.push('No usable portal ids parsed.');
+ return makeResult(null, [], [], errors);
+ }
+ return makeResult(mode, portalIds, resolvedNames, []);
+}
+
+function normalizeValidIds(validIds) {
+ if (!Array.isArray(validIds)) return null;
+ const byId = new Map();
+ const byName = new Map();
+ for (const entry of validIds) {
+ if (!entry) continue;
+ if (typeof entry === 'string') {
+ const lower = entry.toLowerCase();
+ byId.set(lower, { portalId: entry, name: null });
+ } else if (typeof entry === 'object' && entry.portalId) {
+ const lower = String(entry.portalId).toLowerCase();
+ const rec = { portalId: entry.portalId, name: entry.name || null };
+ byId.set(lower, rec);
+ if (entry.name) {
+ const name = String(entry.name).toLowerCase();
+ if (!byName.has(name)) byName.set(name, new Map());
+ // Repeated records for one ID are not distinct sites; ID casing is immaterial.
+ byName.get(name).set(lower, rec);
+ }
+ }
+ }
+ return { byId, byName };
+}
+
+function makeResult(policyValue, portalIds, resolvedNames, errors) {
+ const out = { policyValue, portalIds, errors };
+ if (resolvedNames.length > 0) out.resolvedNames = resolvedNames;
+ return out;
+}
+
+if (require.main === module) {
+ // CLI mode: read user input from stdin (or --input <text>). With
+ // --portalsStdin, stdin instead carries list-portals.js JSON so callers can
+ // validate names without creating a temporary file.
+ const argv = process.argv;
+ const arg = (k) => {
+ const i = argv.indexOf(k);
+ return i >= 0 && i + 1 < argv.length ? argv[i + 1] : null;
+ };
+ const readStdin = async () => {
+ return new Promise((resolve) => {
+ let buf = '';
+ process.stdin.on('data', (c) => (buf += c));
+ process.stdin.on('end', () => resolve(buf));
+ });
+ };
+ (async () => {
+ let validIds;
+ const file = arg('--portalsFile');
+ const portalsStdin = argv.includes('--portalsStdin');
+ if (file || portalsStdin) {
+ try {
+ const raw = file ? require('fs').readFileSync(file, 'utf8') : await readStdin();
+ const parsed = JSON.parse(raw);
+ const list = Array.isArray(parsed) ? parsed : parsed.portals;
+ if (Array.isArray(list)) {
+ validIds = list.map((p) => ({ portalId: p.portalId || p.Id, name: p.name || p.Name }));
+ }
+ } catch (e) {
+ process.stderr.write(`Failed to read portal list: ${e.message}\n`);
+ process.exit(1);
+ }
+ }
+ const inline = arg('--input');
+ if (portalsStdin && inline == null) {
+ process.stderr.write('--portalsStdin requires --input <text> because stdin contains the portal list.\n');
+ process.exit(1);
+ return;
+ }
+ const input = (inline != null ? inline : await readStdin()).trim();
+ const result = parsePortalInput(input, { validIds });
+ process.stdout.write(JSON.stringify(result, null, 2) + '\n');
+ process.exit(result.errors.length > 0 ? 1 : 0);
+ })();
+}
+
+module.exports = { parsePortalInput };
diff --git a/plugins/power-pages/skills/manage-governance/scripts/policies.js b/plugins/power-pages/skills/manage-governance/scripts/policies.js
new file mode 100644
index 000000000..7e4abc1f4
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/policies.js
@@ -0,0 +1,174 @@
+#!/usr/bin/env node
+
+// Single source of truth for the governance policy strings this skill supports.
+// Adding a new policy here is the only change required to expose it to the
+// other scripts in this skill (assertPolicy is the gate every script calls).
+
+'use strict';
+
+const SUPPORTED_POLICIES = Object.freeze([
+ 'EnableMakerCopilotForExistingSites',
+ 'EnableProtocolOpenIdConnect',
+ 'EnableProtocolSAML20',
+ 'EnableProtocolWsFederation',
+ 'EnableProtocolOpenAuth',
+ 'EnableIdpOAuthFacebook',
+ 'EnableIdpOAuthGoogle',
+ 'EnableIdpOAuthMicrosoft',
+ 'EnableAuthenticationLocalLogin',
+ 'EnableExternalAuthProviders',
+ // Power Pages Copilot / site-control governance policies. These use the
+ // `PowerPages_*` name prefix but are the SAME uniformGovernance type as the
+ // ten above — each supports the canonical All / None / Include / Exclude
+ // policyValue vocabulary and is independent (no parent/child availability
+ // gating, no cascade). Added per the 2026-07 enhancement request.
+ 'PowerPages_AllowMakerCopilotsForNewSites',
+ 'PowerPages_AllowMakerCopilotsForExistingSites',
+ 'PowerPages_AllowProDevCopilotsForSites',
+ 'PowerPages_AllowSiteCopilotForSites',
+ 'PowerPages_AllowSearchSummaryCopilotForSites',
+ 'PowerPages_AllowListSummaryCopilotForSites',
+ 'PowerPages_AllowIntelligentFormsCopilotForSites',
+ 'PowerPages_AllowSummarizationAPICopilotForSites',
+ 'PowerPages_AllowProDevCopilotsForEnvironment',
+ 'PowerPages_AllowNonProdPublicSites',
+ 'PowerPages_DisableExtSvcCallsFromServerLogic',
+]);
+
+// Some policies (env-level ones such as EnableMakerCopilotForExistingSites)
+// report their env-level state on read using the `applyTo` enum vocabulary
+// (e.g. "AllSites" / "IncludeSites" / "ExcludeSites") rather than the short
+// canonical policyValue vocabulary ("All" / "Include" / "Exclude"). This map
+// normalizes any read value back to the canonical
+// policyValue string so every render path can treat them the same. Values
+// already in canonical form pass through unchanged. The mapping mirrors
+// `apiBehavior.applyTo` in references/governance-mapping.json.
+//
+// Verified empirically against Preprod: after a portal-scoped enable the env
+// READS BACK as "IncludeSites" (and "ExcludeSites" for a block-list), so both
+// the `IncludeSites`/`ExcludeSites` enum forms AND the older
+// `IncludedSites`/`ExcludedSites`/`AllSitesExceptExcluded` spellings are
+// accepted here for forward/backward compatibility. (These were also the WRITE
+// tokens until the 2026-07 A059 shift moved writes to the short canonical
+// forms — see WRITE_VALUE_ALIASES below — but the read side must still fold
+// them because the env can continue to read them back.)
+const ENV_VALUE_ALIASES = Object.freeze({
+ allsites: 'All',
+ includesites: 'Include',
+ excludesites: 'Exclude',
+ includedsites: 'Include',
+ allsitesexceptexcluded: 'Exclude',
+ excludedsites: 'Exclude',
+});
+
+// WRITE vocabulary — the inverse of the read normalization above. This map
+// forward-maps the canonical policyValue (`All` / `None` / `Include` /
+// `Exclude`) to the token the Power Apps Core Services Gateway accepts on a
+// POST /governance upsert. It is an identity map today, but the seam is kept
+// (a) so call sites don't special-case per policy, and (b) because the wire
+// vocabulary has already shifted once under us (see history below) and may
+// shift again — this is the single place to re-pin it.
+//
+// HISTORY — the `*Sites` -> short-form migration (WHY this is an identity map
+// now, when it used to forward-map to `*Sites` enums):
+//
+// * Originally the gateway (applyTo API version 2024-10-01) REQUIRED the
+// `*Sites` enum forms on write for env-level (uniformGovernance) policies:
+// POSTing the short `policyValue:"All"` / `"Include"` / `"Exclude"` was
+// rejected with the plain body "Website id cannot be null or empty" and the
+// env was left unchanged. So the write path forward-mapped
+// All->AllSites, Include->IncludeSites, Exclude->ExcludeSites.
+// * As of 2026-07 the gateway INVERTED that contract for the sign-in
+// protocol policies (observed on EnableProtocolOpenAuth): it now REJECTS
+// the `*Sites` enum forms with HTTP 400
+// `{ "error": { "code": "A059", "message": "The provided policy value is
+// not a valid governance policy value." } }` and ACCEPTS the SHORT
+// canonical forms (-> 200 "Policy upserts accepted."). The short forms also
+// match the READ vocabulary the env reads back, so mapping to them keeps
+// read and write symmetric.
+//
+// Verified empirically against Preprod on EnableProtocolOpenAuth (2026-07):
+// - "AllSites" -> 400 A059 | "All" -> 200 "Policy upserts accepted."
+// - "IncludeSites" -> 400 A059 | "Include" -> 200 "Policy upserts accepted."
+// - "ExcludeSites" -> 400 A059 | "Exclude" -> 200 "Policy upserts accepted."
+// (a short-form POST while a prior rollout is still InProgress returns code
+// D006 with an empty message — that is a concurrency lock, NOT value
+// rejection; retry once the status endpoint reports Succeeded.)
+//
+// "None" (full env-wide disable) was always the literal "None" on the wire (the
+// disabled state is conveyed by the value itself), so it is unaffected by the
+// shift. All four values are therefore now the canonical short form.
+const WRITE_VALUE_ALIASES = Object.freeze({
+ All: 'All',
+ Include: 'Include',
+ Exclude: 'Exclude',
+ None: 'None',
+});
+
+// Terminal status values the polling helpers treat as "done". The Power Pages
+// runtime is known to report `Succeeded` / `Completed` on success and `Failed`
+// on failure; the skill is tolerant of casing differences.
+const TERMINAL_SUCCESS = Object.freeze(['succeeded', 'completed', 'created', 'ok']);
+const TERMINAL_FAILURE = Object.freeze(['failed', 'error']);
+
+function isSupportedPolicy(name) {
+ return SUPPORTED_POLICIES.includes(name);
+}
+
+function assertPolicy(name) {
+ if (!isSupportedPolicy(name)) {
+ const supported = SUPPORTED_POLICIES.join(', ');
+ process.stderr.write(
+ `Unsupported policy "${name}". Supported: ${supported}\n`
+ );
+ process.exit(1);
+ }
+}
+
+function classifyStatus(rawValue) {
+ const v = String(rawValue || '').toLowerCase().trim();
+ if (!v) return 'unknown';
+ if (TERMINAL_SUCCESS.includes(v)) return 'success';
+ if (TERMINAL_FAILURE.includes(v)) return 'failure';
+ return 'in-progress';
+}
+
+// Map a raw env-level governance read value to the canonical policyValue
+// vocabulary (`All` / `None` / `Include` / `Exclude`). Env-level policies may
+// return the `applyTo` enum form ("AllSites") on read, which this map folds
+// back to the canonical form. Anything unrecognized passes through
+// unchanged so callers can still render/inspect it.
+function normalizeEnvValue(rawValue) {
+ if (rawValue === null || rawValue === undefined) return rawValue;
+ const raw = String(rawValue).trim();
+ const alias = ENV_VALUE_ALIASES[raw.toLowerCase()];
+ return alias || raw;
+}
+
+// Forward-map a canonical policyValue (`All` / `None` / `Include` / `Exclude`)
+// to the value that actually goes on the wire for a POST /governance upsert.
+// Every supported policy is an env-level (uniformGovernance) policy that
+// requires the applyTo enum vocabulary ("AllSites" etc.), so the canonical
+// short form is always forward-mapped before POSTing. Unknown values pass
+// through unchanged so callers can still forward experimental / future values
+// without this helper silently dropping them. `policyName` is retained in the
+// signature for call-site compatibility and possible future per-policy
+// exemptions. See WRITE_VALUE_ALIASES above for the WHY and the empirical
+// Preprod verification.
+function toWritePolicyValue(canonicalValue, policyName) {
+ const alias = WRITE_VALUE_ALIASES[canonicalValue];
+ return alias || canonicalValue;
+}
+
+module.exports = {
+ SUPPORTED_POLICIES,
+ ENV_VALUE_ALIASES,
+ WRITE_VALUE_ALIASES,
+ TERMINAL_SUCCESS,
+ TERMINAL_FAILURE,
+ assertPolicy,
+ isSupportedPolicy,
+ classifyStatus,
+ normalizeEnvValue,
+ toWritePolicyValue,
+};
diff --git a/plugins/power-pages/skills/manage-governance/scripts/render-env-table.js b/plugins/power-pages/skills/manage-governance/scripts/render-env-table.js
new file mode 100644
index 000000000..e58a489e8
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/render-env-table.js
@@ -0,0 +1,205 @@
+#!/usr/bin/env node
+
+// render-env-table.js — Renders the environment picker as a fixed-width,
+// ASCII-only bordered box table so columns stay aligned in every terminal
+// and chat font. A marker column flags the current selection (the env that
+// applies when the user replies "keep").
+//
+// ASCII-only is deliberate: emoji / wide glyphs (➡️, ✅) render at unpredictable
+// widths and break monospace alignment, producing a "broken" table. Keep every
+// character inside the borders single-width ASCII.
+
+const CURRENT_TAG = '<-- CURRENT SELECTION (default)';
+const CURRENT_MARK = '>';
+
+const { pad, border } = require('./table');
+
+// Resolve the tenant-default env id straight from the list-envs.js payload so
+// the picker can pre-flag a sensible default WITHOUT a second round-trip. The
+// list already carries `type: "Default"` for the tenant's default environment
+// (Dataverse environments API surfaces the default flag), so deriving it here
+// avoids an extra `pac auth who` invocation — that separate call cold-starts
+// the .NET CLI and can trigger its own tool-approval prompt, which is exactly
+// the friction we want to remove from the "just show the list" step. Match is
+// case-insensitive because casing has varied across CLI versions
+// ("Default" vs "default").
+function resolveDefaultEnvId(envs) {
+ const list = Array.isArray(envs) ? envs : [];
+ const def = list.find(
+ (e) => e && typeof e.type === 'string' && e.type.toLowerCase() === 'default'
+ );
+ return def && def.envId ? def.envId : null;
+}
+
+/**
+ * Render the env list as an aligned ASCII box table.
+ *
+ * @param {Array<{displayName?: string, envId?: string}>} envs
+ * @param {object} [opts]
+ * @param {string|null} [opts.currentEnvId] - envId to flag as current selection.
+ * @returns {string} the rendered table (no trailing newline).
+ */
+function renderEnvTable(envs, opts = {}) {
+ const currentEnvId = opts.currentEnvId || null;
+ const list = Array.isArray(envs) ? envs : [];
+
+ const rows = list.map((e, i) => {
+ const isCurrent = currentEnvId != null && e && e.envId === currentEnvId;
+ const name = (e && e.displayName) || '(unnamed)';
+ return {
+ n: String(i + 1),
+ mark: isCurrent ? CURRENT_MARK : '',
+ name: isCurrent ? `${name} ${CURRENT_TAG}` : name,
+ id: (e && e.envId) || '',
+ };
+ });
+
+ const headers = { n: '#', mark: '', name: 'Environment Name', id: 'Environment ID' };
+ const all = [headers, ...rows];
+
+ const widths = [
+ Math.max(...all.map((r) => r.n.length)),
+ Math.max(CURRENT_MARK.length, ...all.map((r) => r.mark.length)),
+ Math.max(...all.map((r) => r.name.length)),
+ Math.max(...all.map((r) => r.id.length)),
+ ];
+
+ const line = (r) =>
+ `| ${pad(r.n, widths[0])} | ${pad(r.mark, widths[1])} | ${pad(r.name, widths[2])} | ${pad(r.id, widths[3])} |`;
+
+ const out = [];
+ out.push(border(widths, '+', '+', '+'));
+ out.push(line(headers));
+ out.push(border(widths, '+', '+', '+'));
+ for (const r of rows) out.push(line(r));
+ out.push(border(widths, '+', '+', '+'));
+ return out.join('\n');
+}
+
+// Escape a cell value for GitHub-flavored Markdown table cells. A literal '|'
+// would prematurely close the cell, and a backslash could escape the next
+// pipe — env display names are user-controlled, so both must be neutralized.
+function mdCell(str) {
+ return String(str == null ? '' : str)
+ .replace(/\\/g, '\\\\')
+ .replace(/\|/g, '\\|')
+ // A raw newline in a cell breaks the single-line Markdown table row (the
+ // renderer would spill the value onto a new, malformed row), so flatten
+ // any CR/LF runs to a single space.
+ .replace(/[\r\n]+/g, ' ');
+}
+
+/**
+ * Render the env list as a GitHub-flavored Markdown table. Unlike the ASCII
+ * box (which relies on a monospace font and can collapse to blank on chat
+ * surfaces that don't render fenced code blocks), a Markdown table renders
+ * reliably as a real table in chat UIs. A dedicated "Selected" column flags the
+ * env chosen earlier in the session (the row that applies on "keep").
+ *
+ * @param {Array<{displayName?: string, envId?: string}>} envs
+ * @param {object} [opts]
+ * @param {string|null} [opts.currentEnvId] - envId to flag as current selection.
+ * @returns {string} the rendered Markdown table (no trailing newline).
+ */
+function renderEnvMarkdown(envs, opts = {}) {
+ const currentEnvId = opts.currentEnvId || null;
+ const list = Array.isArray(envs) ? envs : [];
+ const out = [];
+ out.push('| # | Selected | Environment Name | Environment ID |');
+ out.push('|---|---|---|---|');
+ list.forEach((e, i) => {
+ const isCurrent = currentEnvId != null && e && e.envId === currentEnvId;
+ const name = (e && e.displayName) || '(unnamed)';
+ // A dedicated "Selected" column marks the env chosen earlier (the one that
+ // applies on "keep"), so the user can see at a glance which row is the
+ // current default without hunting for an inline tag.
+ const mark = isCurrent ? '**\u2190 selected earlier**' : '';
+ out.push(
+ `| ${i + 1} | ${mark} | ${mdCell(name)} | ${mdCell((e && e.envId) || '')} |`
+ );
+ });
+ return out.join('\n');
+}
+
+function readStdin() {
+ return new Promise((resolve) => {
+ let data = '';
+ process.stdin.setEncoding('utf8');
+ process.stdin.on('data', (chunk) => (data += chunk));
+ process.stdin.on('end', () => resolve(data));
+ });
+}
+
+const HELP = `render-env-table.js — Render the env picker as an aligned ASCII box table.
+
+Usage:
+ node list-envs.js | node render-env-table.js [--current <envId>]
+ node render-env-table.js --envsFile <path> [--current <envId>]
+
+Input:
+ A JSON object shaped like list-envs.js output: { "status": "ok", "envs": [ ... ] }
+ or a bare JSON array of { envId, displayName }.
+
+Flags:
+ --current <envId> Flag this env as the current selection (default) row.
+ When omitted, the env whose "type" is "Default" in the
+ list-envs.js payload is auto-flagged (no extra lookup).
+ --envsFile <path> Read the JSON from a file instead of stdin.
+ --markdown Emit a GitHub-flavored Markdown table (renders reliably
+ in chat UIs) instead of the ASCII box.
+ --help Show this help.
+`;
+
+function parseFlags(argv) {
+ const out = {};
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--current') out.current = argv[++i];
+ else if (a === '--envsFile') out.envsFile = argv[++i];
+ else if (a === '--markdown') out.markdown = true;
+ else if (a === '--help') out.help = true;
+ }
+ return out;
+}
+
+async function main() {
+ const flags = parseFlags(process.argv);
+ if (flags.help) {
+ process.stdout.write(HELP);
+ return;
+ }
+ let raw;
+ if (flags.envsFile) {
+ raw = require('fs').readFileSync(flags.envsFile, 'utf8');
+ } else {
+ raw = await readStdin();
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (e) {
+ process.stderr.write(`render-env-table: could not parse JSON input: ${e.message}\n`);
+ process.exit(1);
+ return;
+ }
+ const envs = Array.isArray(parsed) ? parsed : parsed.envs || [];
+ // Auto-flag the tenant-default env when the caller didn't pin one via
+ // --current. This makes "show me the env list" a single deterministic step:
+ // the list loads and renders with a sensible default already marked, with no
+ // separate lookup command (and therefore no extra approval prompt).
+ const currentEnvId = flags.current || resolveDefaultEnvId(envs);
+ const render = flags.markdown ? renderEnvMarkdown : renderEnvTable;
+ process.stdout.write(render(envs, { currentEnvId }) + '\n');
+}
+
+module.exports = {
+ renderEnvTable,
+ renderEnvMarkdown,
+ resolveDefaultEnvId,
+ CURRENT_TAG,
+ CURRENT_MARK,
+};
+
+if (require.main === module) {
+ main();
+}
diff --git a/plugins/power-pages/skills/manage-governance/scripts/render-impact-summary.js b/plugins/power-pages/skills/manage-governance/scripts/render-impact-summary.js
new file mode 100644
index 000000000..2f1d0e58f
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/render-impact-summary.js
@@ -0,0 +1,434 @@
+#!/usr/bin/env node
+
+// render-impact-summary.js — Deterministically render the Phase 2.2 / 4.2.3
+// consent-gate "impact summary" block from governance-mapping.json data plus a
+// resolved request. Feeding the same inputs through one renderer keeps the
+// Action / Environment / Scope / Sites / Effect
+// rows — and the sign-out Side-effect line — consistent with the committed spec
+// and the per-policy `subject` / `effectLineTemplates` / `sideEffectCallout`
+// data. It mirrors the render-env-table.js / render-portal-table.js pattern:
+// pure data-in → text-out, no network, no writes.
+//
+// The rendered block intentionally starts at the `**Action:**` line with NO lead-in
+// heading — SKILL.md forbids prepending "Impact summary:" or any label before
+// the Action row, so callers must emit this output verbatim.
+
+const fs = require('fs');
+const path = require('path');
+
+// Reuse the committed ANSI helper so the state cells can be colorized in a real
+// terminal, but stay plain (emoji-only) for chat surfaces that strip ANSI.
+const { green, red } = require('./colors');
+const { renderMarkdownTable, markdownText } = require('./table');
+
+const MAPPING_PATH = path.join(__dirname, '..', 'references', 'governance-mapping.json');
+
+function loadMapping(mappingPath) {
+ const raw = fs.readFileSync(mappingPath || MAPPING_PATH, 'utf8');
+ return JSON.parse(raw);
+}
+
+function capitalize(s) {
+ const str = String(s || '');
+ return str ? str[0].toUpperCase() + str.slice(1) : str;
+}
+
+// Normalize a free-form current-state string to the canonical 'Enabled' /
+// 'Disabled' / 'Unknown' used by governance-mapping.json `stateColors`. Live
+// reads (get-env.js / get-portal.js) can surface 'None', 'All', mixed casing,
+// or a missing value when a read fails — the consent gate must never crash on
+// that, so anything unrecognized renders as 'Unknown' (SKILL.md: "If a live
+// read fails, render Current State as Unknown ... never block the gate").
+function normalizeState(v) {
+ const s = String(v == null ? '' : v).trim().toLowerCase();
+ if (s === 'enabled' || s === 'enable' || s === 'on' || s === 'true') return 'Enabled';
+ if (s === 'disabled' || s === 'disable' || s === 'off' || s === 'false' || s === 'blocked') {
+ return 'Disabled';
+ }
+ return 'Unknown';
+}
+
+// The target state a site reaches after the requested direction is applied.
+// enable -> Enabled, disable -> Disabled. Only sites in scope are passed in, so
+// every provided site takes the target state.
+function newStateFor(direction) {
+ return direction === 'disable' ? 'Disabled' : 'Enabled';
+}
+
+// Wrap a state label with its emoji marker (and optional ANSI color). Emoji is
+// always present because some chat renderers strip ANSI; the color helper is a
+// no-op unless coloring is enabled, matching the committed stateColors contract.
+function stateCell(state, colorOpts) {
+ if (state === 'Enabled') return green('🟢 Enabled', colorOpts);
+ if (state === 'Disabled') return red('🔴 Disabled', colorOpts);
+ return '⚪ Unknown';
+}
+
+// Markdown cells stay ANSI-free; emoji carry the state cue in chat.
+function plainStateCell(state) {
+ if (state === 'Enabled') return '🟢 Enabled';
+ if (state === 'Disabled') return '🔴 Disabled';
+ return '⚪ Unknown';
+}
+
+// Plain-language scope line for the Scope row. Never leaks the internal
+// All/Include/None/Exclude policyValue terms (SKILL.md: "never leak the internal
+// All / Include / None / Exclude terms to the user").
+function scopeLine(scope, siteNames) {
+ if (scope === 'specific') {
+ const list = siteNames.length ? siteNames.map(markdownText).join(', ') : '(no sites listed)';
+ return `Only ${list}`;
+ }
+ return 'Every site in this environment';
+}
+
+// Build the Effect line from effectLineTemplates (keyed by direction + all/
+// specific) with the per-policy `subject`, env display, and the affected site
+// names substituted in.
+function effectLine(mapping, policy, direction, scope, envDisplay, siteNames) {
+ const key = scope === 'specific' ? 'specific' : 'all';
+ const tmpl = (mapping.effectLineTemplates || []).find(
+ (t) => t.intentDirection === direction && t.scope === key
+ );
+ if (!tmpl) {
+ // Fall back to a bare sentence rather than throwing — the gate must render.
+ return `${policy.subject} will be ${direction === 'disable' ? 'disabled' : 'enabled'} in ${markdownText(envDisplay)}.`;
+ }
+ return tmpl.template
+ // Function replacements preserve literal "$&" / "$`" in display names.
+ .replace('{Subject}', () => policy.subject)
+ .replace('{EnvDisplay}', () => markdownText(envDisplay))
+ .replace('{SiteNameList}', () => siteNames.map(markdownText).join(', '));
+}
+
+// The sign-out Side-effect line, only when the resulting policyValue is one of
+// the per-policy triggers. For the legacy Disable* block rules the triggers are
+// ["All","Include"] (turning the block ON blocks the protocol); for the Enable*
+// toggles they are ["None","Exclude"] (turning the toggle OFF blocks sign-in).
+// See governance-mapping.json policies[].sideEffectCallout.
+function sideEffectLine(policy, policyValue) {
+ const cb = policy.sideEffectCallout;
+ if (!cb || !Array.isArray(cb.policyValueTriggers) || !policyValue) return null;
+ if (!cb.policyValueTriggers.includes(policyValue)) return null;
+ return cb.message;
+}
+
+// Some "parent" policies affect a set of downstream sign-in methods, and the
+// admin needs to see that ripple at the consent gate — it isn't obvious from the
+// single-policy table. Both directions get a checklist under the summary:
+//
+// * disable -> the downstream methods that
+// this parent turns OFF (OAuth 2.0 -> Facebook/Google/Microsoft; External
+// Auth -> every protocol + social IdP), each marked red "🔴 Disabled".
+// * enable -> an informational list of the methods that become AVAILABLE
+// again (subject to their own per-provider config). Enabling a parent does
+// NOT force-enable the children, so these are annotated (e.g. "Controlled by
+// the Facebook setting.") and a footer note spells out that each provider
+// must still be configured — no green "Enabled" marker, because the child's
+// real state is unchanged by this apply.
+//
+// Both are data-driven from governance-mapping.json policies[].cascadeOnDisable /
+// cascadeOnEnable so adding/removing a downstream method never touches this file.
+// Items may be strings, { label, note, state } leaves, or grouped objects such
+// as { "OAuth 2.0": ["Facebook", "Google"] }. Keep the group followed by its
+// children so the consent summary never omits a downstream provider.
+// Returns the ready-to-emit lines (blank separator + heading + rows + optional
+// footer) or [] when the policy has no cascade for that direction.
+function cascadeLines(policy, direction, colorOpts) {
+ const isDisable = direction === 'disable';
+ const cascade = isDisable ? policy.cascadeOnDisable : policy.cascadeOnEnable;
+ if (!cascade || !Array.isArray(cascade.items) || cascade.items.length === 0) {
+ return [];
+ }
+ // Normalize each item to { label, note, state } so string and object forms
+ // coexist. `state` (e.g. 'Enabled') is optional and only used on the enable side
+ // to render a green "🟢 Enabled" marker mirroring the disable side's red one.
+ const items = flattenCascadeItems(cascade.items);
+ const lines = [];
+ lines.push('');
+ lines.push(`**${cascade.heading || (isDisable ? 'The following sign-in methods will be disabled:' : 'When enabled, the following become available:')}**`);
+ lines.push('');
+ items.forEach((it, i) => {
+ const num = `${i + 1}.`;
+ const label = String(it.label);
+ let marker;
+ if (isDisable) {
+ // Render the state marker through the SAME stateCell() convention the Sites
+ // table uses — "🔴 Disabled" wrapped in ANSI red. The 🔴 emoji is what makes
+ // the "red for Disable" cue visible on chat surfaces that strip ANSI (they
+ // drop the escape codes but keep the red circle); the ANSI red still applies
+ // in a real terminal. Green ("🟢 Enabled") is the symmetric marker for any
+ // enable-side row that declares an explicit `state` (see below).
+ marker = ' — ' + stateCell('Disabled', colorOpts);
+ } else if (it.state) {
+ // Enable rows may opt into an explicit state marker (data-driven via the
+ // item's `state` field). "Enabled" renders green "🟢 Enabled" — the mirror
+ // of the disable side — followed by the note when present.
+ marker = ' — ' + stateCell(it.state, colorOpts) + (it.note ? ' - ' + it.note : '');
+ } else {
+ // Default enable rows only annotate the provider-controlled entries; protocol
+ // rows (OpenID Connect, SAML 2.0, ...) have no note and render as label-only.
+ // No green "Enabled" marker here because enabling a parent does NOT force the
+ // child on — its real state is unchanged by this apply.
+ marker = it.note ? ' — ' + it.note : '';
+ }
+ // Trim trailing whitespace so label-only enable rows don't carry padding.
+ lines.push(`${num} ${label}${marker}`.replace(/\s+$/, ''));
+ });
+ if (cascade.footer) {
+ lines.push('');
+ lines.push(`**Note:** ${cascade.footer}`);
+ }
+ return lines;
+}
+
+function flattenCascadeItems(items) {
+ return items.flatMap((item) => {
+ if (typeof item === 'string' && item.trim()) return [{ label: item }];
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
+ if (typeof item.label === 'string' && item.label.trim()) {
+ return [{ label: item.label, note: item.note, state: item.state }];
+ }
+ const groups = Object.entries(item);
+ if (groups.length && groups.every(([label, children]) => label.trim() && Array.isArray(children))) {
+ return groups.flatMap(([label, children]) => [
+ { label },
+ ...flattenCascadeItems(children),
+ ]);
+ }
+ }
+ throw new Error('render-impact-summary: invalid cascade item; expected a label, labeled item, or group of items');
+ });
+}
+
+// Resolve the internal policyValue that the apply will POST, so the consent gate
+// can show the exact technical mapping beneath the Effect line (SKILL.md Phase
+// 2.1: "The API mapping line already shows the technical translation
+// (policyValue + ToBeAdded)"). Prefer an explicitly-resolved req.policyValue;
+// otherwise derive it from the uniform intent->policyValue rule:
+// enable + all -> All enable + specific -> Include
+// disable + all -> None disable + specific -> Exclude
+function resolvePolicyValue(direction, scope, explicit) {
+ if (explicit) return explicit;
+ if (scope === 'specific') return direction === 'disable' ? 'Exclude' : 'Include';
+ return direction === 'disable' ? 'None' : 'All';
+}
+
+// The API-mapping line shown under Effect: the internal policyValue that will be
+// POSTed, plus the ToBeAdded portal-id list for Include/Exclude (All/None carry
+// no list). This is the technical companion to the plain-English Effect line, so
+// the admin sees exactly what the apply call sets before approving.
+function policyValueLine(policyValue, sites) {
+ const listy = policyValue === 'Include' || policyValue === 'Exclude';
+ const ids = listy
+ ? (Array.isArray(sites) ? sites : []).map((s) => (s && s.portalId) || '').filter(Boolean)
+ : [];
+ const idPart = listy ? `, ToBeAdded = [${ids.join(', ')}]` : '';
+ return `${policyValue}${idPart}`;
+}
+
+// Color the consent-gate Action line by direction: green "🟢 Enable …" when the
+// operation turns something ON, red "🔴 Disable …" when it turns something OFF —
+// the same green=enabled / red=disabled convention as the state cells, and per
+// the SKILL.md rule to color the Action row. The emoji carries the cue where ANSI
+// is stripped (chat); the color helper adds ANSI in a real terminal.
+function actionCell(direction, action, colorOpts) {
+ return direction === 'disable'
+ ? red(`🔴 ${action}`, colorOpts)
+ : green(`🟢 ${action}`, colorOpts);
+}
+
+/**
+ * Render the consent-gate impact summary block.
+ *
+ * @param {object} req
+ * @param {string} req.policy - internal PolicyName (e.g. 'EnableProtocolOpenIdConnect').
+ * @param {string} req.direction - 'enable' | 'disable' (view never reaches the gate).
+ * @param {string} [req.scope] - 'all' | 'specific' (default 'all').
+ * @param {string} [req.policyValue]- resolved All/Include/None/Exclude, for the side-effect check.
+ * @param {{displayName?: string, envId?: string}} req.env
+ * @param {Array<{name?: string, url?: string, portalId?: string, currentState?: string}>} [req.sites]
+ * @param {object} [opts]
+ * @param {object} [opts.mapping] - preloaded mapping (defaults to the committed JSON).
+ * @param {boolean} [opts.color] - force ANSI color on the state cells.
+ * @returns {string} the rendered block (no trailing newline, starts at `**Action:**`).
+ */
+function renderImpactSummary(req, opts = {}) {
+ const mapping = opts.mapping || loadMapping();
+ const colorOpts = { enabled: opts.color === true };
+
+ const policy = (mapping.policies || []).find((p) => p.policyName === req.policy);
+ if (!policy) {
+ throw new Error(`render-impact-summary: unknown policy '${req.policy}'`);
+ }
+ const direction = req.direction === 'disable' ? 'disable' : 'enable';
+ const scope = req.scope === 'specific' ? 'specific' : 'all';
+ const env = req.env || {};
+ const envDisplay = env.displayName || '(unnamed env)';
+ const envLine = env.envId
+ ? `${markdownText(envDisplay)} (${markdownText(env.envId)})`
+ : markdownText(envDisplay);
+ const sites = Array.isArray(req.sites) ? req.sites : [];
+ const siteNames = sites.map((s) => (s && s.name) || '(unnamed)');
+
+ const action = `${capitalize(direction)} ${policy.subject}`;
+ const newState = newStateFor(direction);
+
+ const out = [];
+ out.push(`**Action:** ${actionCell(direction, action, colorOpts)}`);
+ out.push('');
+ out.push(`**Environment:** ${envLine}`);
+ out.push('');
+ out.push(`**Scope:** ${scopeLine(scope, siteNames)}`);
+ out.push('');
+
+ // Sites table with the required Current State / New State columns, rendered as
+ // a GitHub-flavored Markdown table (NOT a fixed-width Unicode box — see
+ // renderMarkdownTable for why the box broke in chat). A site whose state
+ // actually flips is tagged '← CHANGED' in its New State cell per the
+ // consentGate rules ("Rows where the per-site state changes MUST be marked
+ // CHANGED"). The chat client sizes the columns, so each site is one line.
+ const sitesLabel = scope === 'specific' ? '**Sites covered:**' : '**Sites in environment:**';
+ out.push(sitesLabel);
+ out.push('');
+ const tableHeaders = ['Site Name', 'URL', 'Site ID', 'Current State', 'New State'];
+ const tableRows = sites.map((s) => {
+ const cur = normalizeState(s && s.currentState);
+ // Only flag a change when we actually know the current state and it differs.
+ const changed = cur !== 'Unknown' && cur !== newState ? ' ← CHANGED' : '';
+ return [
+ (s && s.name) || '(unnamed)',
+ (s && s.url) || '',
+ (s && s.portalId) || '',
+ plainStateCell(cur),
+ plainStateCell(newState) + changed,
+ ];
+ });
+ for (const line of renderMarkdownTable(tableHeaders, tableRows).split('\n')) {
+ out.push(line);
+ }
+
+ // Terminate the Markdown table with a blank line before the trailing
+ // Effect / Policy value / Side effect / cascade lines. Without this separator
+ // a chat/terminal renderer treats the pipe-less "Effect: ..." and
+ // "Policy value: ..." lines as continuation rows of the table and boxes them
+ // into the grid (admins saw Effect/Policy value crammed into empty table
+ // cells). A blank line after a GFM table is the standard, portable way to
+ // close it so the following prose renders below the table, not inside it.
+ out.push('');
+
+ out.push(`**Effect:** ${effectLine(mapping, policy, direction, scope, envDisplay, siteNames)}`);
+ out.push('');
+
+ // Technical companion to the Effect line: the exact internal value + ToBeAdded
+ // list this apply will POST. Resolved once here so the side-effect check below
+ // uses the same value even when the caller omitted req.policyValue.
+ const policyValue = resolvePolicyValue(direction, scope, req.policyValue);
+ out.push(`**Policy value:** ${policyValueLine(policyValue, sites)}`);
+
+ const se = sideEffectLine(policy, policyValue);
+ if (se) {
+ out.push('');
+ out.push(`> **Side effect:** ${se}`);
+ }
+
+ // Downstream policies the admin should know about: on disable, the methods
+ // this parent turns off; on enable, the methods it makes available again
+ // (subject to their own config). No-op for every non-parent policy.
+ for (const line of cascadeLines(policy, direction, colorOpts)) out.push(line);
+
+ return out.join('\n');
+}
+
+function readStdin() {
+ return new Promise((resolve) => {
+ let data = '';
+ process.stdin.setEncoding('utf8');
+ process.stdin.on('data', (chunk) => (data += chunk));
+ process.stdin.on('end', () => resolve(data));
+ });
+}
+
+const HELP = `render-impact-summary.js — Render the consent-gate impact summary block.
+
+Usage:
+ node render-impact-summary.js --reqFile <path.json> [--color]
+ echo '<json>' | node render-impact-summary.js [--color]
+
+Input JSON shape:
+ {
+ "policy": "EnableProtocolOpenIdConnect",
+ "direction": "disable",
+ "scope": "all" | "specific",
+ "policyValue": "None",
+ "env": { "displayName": "Test environment", "envId": "env-1" },
+ "sites": [
+ { "name": "Site 1", "url": "https://...", "portalId": "3e13...", "currentState": "Enabled" }
+ ]
+ }
+
+Flags:
+ --reqFile <path> Read the request JSON from a file instead of stdin.
+ --color Force ANSI color for terminal callers (default: off for Markdown).
+ --help Show this help.
+
+Output is Markdown starting at '**Action:**' with no lead-in.
+Emit it verbatim without code fences; preserve blank lines and single-line table rows.
+`;
+
+function parseFlags(argv) {
+ const out = {};
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--reqFile') out.reqFile = argv[++i];
+ else if (a === '--color') out.color = true;
+ else if (a === '--help') out.help = true;
+ }
+ return out;
+}
+
+async function main() {
+ const flags = parseFlags(process.argv);
+ if (flags.help) {
+ process.stdout.write(HELP);
+ return;
+ }
+ let raw;
+ if (flags.reqFile) {
+ raw = fs.readFileSync(flags.reqFile, 'utf8');
+ } else {
+ raw = await readStdin();
+ }
+ let req;
+ try {
+ req = JSON.parse(raw);
+ } catch (e) {
+ process.stderr.write(`render-impact-summary: could not parse JSON input: ${e.message}\n`);
+ process.exit(1);
+ return;
+ }
+ try {
+ process.stdout.write(renderImpactSummary(req, { color: flags.color === true }) + '\n');
+ } catch (e) {
+ process.stderr.write(`render-impact-summary: ${e.message}\n`);
+ process.exit(1);
+ }
+}
+
+module.exports = {
+ renderImpactSummary,
+ loadMapping,
+ normalizeState,
+ newStateFor,
+ scopeLine,
+ effectLine,
+ resolvePolicyValue,
+ policyValueLine,
+ sideEffectLine,
+ cascadeLines,
+ actionCell,
+};
+
+if (require.main === module) {
+ main();
+}
diff --git a/plugins/power-pages/skills/manage-governance/scripts/render-portal-table.js b/plugins/power-pages/skills/manage-governance/scripts/render-portal-table.js
new file mode 100644
index 000000000..8cd6eae04
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/render-portal-table.js
@@ -0,0 +1,240 @@
+#!/usr/bin/env node
+
+// render-portal-table.js — Renders the per-site governance state table as a
+// fixed-width, ASCII-only bordered box table. The State column is colorized
+// green (Enabled) / red (Disabled) via colors.js — but ONLY when the output is
+// a real terminal (or coloring is forced with --color). In JSON/chat contexts
+// coloring is off, so the table stays plain and aligned.
+//
+// ANSI escapes are zero-width, so column widths are computed on the *visible*
+// (uncolored) text and the color is applied AFTER padding — alignment holds
+// whether or not color is on.
+
+const { foregroundColor, shouldColor } = require('./colors');
+const { pad, border, renderMarkdownTable } = require('./table');
+
+// Normalize a state value to the canonical 'Enabled' / 'Disabled' label.
+// Accepts booleans (true=Enabled), or strings like 'enabled'/'disabled'/
+// 'true'/'false'. Anything else falls through to 'Unknown'.
+function normalizeState(state) {
+ if (state === true) return 'Enabled';
+ if (state === false) return 'Disabled';
+ const s = String(state == null ? '' : state).trim().toLowerCase();
+ if (s === 'enabled' || s === 'true') return 'Enabled';
+ if (s === 'disabled' || s === 'false') return 'Disabled';
+ return 'Unknown';
+}
+
+// Green for Enabled, red for Disabled, left plain for Unknown.
+function colorForState(label) {
+ if (label === 'Enabled') return 'Green';
+ if (label === 'Disabled') return 'Red';
+ return null;
+}
+
+// Emoji marker for the state — a fallback indicator on surfaces that strip ANSI
+// (e.g. chat). Green circle = Enabled, red circle = Disabled, none for Unknown.
+function iconForState(label) {
+ if (label === 'Enabled') return '\u{1F7E2}';
+ if (label === 'Disabled') return '\u{1F534}';
+ return '';
+}
+
+// GitHub-flavored Markdown version of the per-site state table. This is the
+// chat-safe renderer: the ASCII box (renderPortalTable) misaligns on chat
+// surfaces because the State column carries a double-width 🟢/🔴 emoji while the
+// box padding counts characters, so every column after State shifts. A Markdown
+// table hands column sizing to the chat client, so each site stays on one row
+// and the emoji can be any width. Color/ANSI is intentionally omitted (it would
+// show as raw escapes in chat); the emoji is the green/red carrier. `icons`
+// defaults on — pass { icons: false } to omit them.
+function renderPortalTableMarkdown(portals, opts = {}) {
+ const list = Array.isArray(portals) ? portals : [];
+ const icons = opts.icons !== false;
+ const headers = ['#', 'Name', 'URL', 'Site ID', 'State'];
+ const rows = list.map((p, i) => {
+ const label = normalizeState(p && p.state);
+ const state = icons && iconForState(label) ? `${iconForState(label)} ${label}` : label;
+ return [
+ String(i + 1),
+ (p && p.name) || '(unnamed)',
+ (p && p.url) || '',
+ (p && p.portalId) || '',
+ state,
+ ];
+ });
+ return renderMarkdownTable(headers, rows);
+}
+
+/**
+ * Render the portal governance-state table.
+ *
+ * @param {Array<{name?: string, url?: string, portalId?: string, state?: (boolean|string)}>} portals
+ * @param {object} [opts]
+ * @param {boolean|null} [opts.color] - Tri-state color override. `true` forces
+ * on, `false` forces off, `null`/undefined auto-detects (TTY + NO_COLOR).
+ * @param {NodeJS.WriteStream} [opts.stream] - Stream used for TTY detection.
+ * @param {object} [opts.env] - Environment map for NO_COLOR/FORCE_COLOR.
+ * @returns {string} rendered table (no trailing newline).
+ */
+function renderPortalTable(portals, opts = {}) {
+ const list = Array.isArray(portals) ? portals : [];
+ const colorOpts = { enabled: opts.color == null ? null : opts.color, stream: opts.stream, env: opts.env };
+ const colorOn = shouldColor(colorOpts);
+ const icons = Boolean(opts.icons);
+ // Unicode box-drawing style (│ ┌ ┬ ┐ ├ ┼ ┤ └ ┴ ┘) with a horizontal rule
+ // between EVERY data row. This remains available for terminal callers;
+ // skill status responses use Markdown so chat clients size the columns. ASCII
+ // mode (default, `unicode` falsy) keeps the legacy +---+ box with no
+ // inter-row rules for backward compatibility (and the empty-list test that
+ // asserts a 4-line frame).
+ const uni = Boolean(opts.unicode);
+
+ const rows = list.map((p, i) => {
+ const label = normalizeState(p && p.state);
+ return {
+ n: String(i + 1),
+ name: (p && p.name) || '(unnamed)',
+ url: (p && p.url) || '',
+ id: (p && p.portalId) || '',
+ state: icons && iconForState(label) ? `${iconForState(label)} ${label}` : label,
+ };
+ });
+
+ const headers = { n: '#', name: 'Name', url: 'URL', id: 'Site ID', state: 'State' };
+ const all = [headers, ...rows];
+
+ // Widths from the visible (uncolored) text.
+ const widths = [
+ Math.max(...all.map((r) => r.n.length)),
+ Math.max(...all.map((r) => r.name.length)),
+ Math.max(...all.map((r) => r.url.length)),
+ Math.max(...all.map((r) => r.id.length)),
+ Math.max(...all.map((r) => r.state.length)),
+ ];
+
+ const vbar = uni ? '│' : '|';
+ const cell = (r, colorize) => {
+ const statePadded = pad(r.state, widths[4]);
+ // r.state may carry a leading icon (e.g. "🟢 Enabled"); derive the colour
+ // from the trailing label word so colorization still works with --icons.
+ const stateLabel = r.state.trim().split(/\s+/).pop();
+ const colorKey = colorForState(stateLabel);
+ const stateCell =
+ colorize && colorKey
+ ? foregroundColor(statePadded, colorKey, { enabled: true })
+ : statePadded;
+ return `${vbar} ${pad(r.n, widths[0])} ${vbar} ${pad(r.name, widths[1])} ${vbar} ${pad(r.url, widths[2])} ${vbar} ${pad(r.id, widths[3])} ${vbar} ${stateCell} ${vbar}`;
+ };
+
+ // Border glyph sets: Unicode box-drawing vs. the legacy ASCII '+' frame.
+ const top = uni ? border(widths, '┌', '┬', '┐', '─') : border(widths, '+', '+', '+');
+ const midRule = uni ? border(widths, '├', '┼', '┤', '─') : border(widths, '+', '+', '+');
+ const bottom = uni ? border(widths, '└', '┴', '┘', '─') : border(widths, '+', '+', '+');
+
+ const out = [];
+ out.push(top);
+ out.push(cell(headers, false));
+ out.push(midRule);
+ rows.forEach((r, i) => {
+ out.push(cell(r, colorOn));
+ // Unicode status format puts a rule between every data row; ASCII does not.
+ if (uni && i < rows.length - 1) out.push(midRule);
+ });
+ out.push(bottom);
+ return out.join('\n');
+}
+
+function readStdin() {
+ return new Promise((resolve) => {
+ let data = '';
+ process.stdin.setEncoding('utf8');
+ process.stdin.on('data', (chunk) => (data += chunk));
+ process.stdin.on('end', () => resolve(data));
+ });
+}
+
+const HELP = `render-portal-table.js — Render the per-site governance state table (colored State column).
+
+Usage:
+ node render-portal-table.js --portalsFile <path> [--color | --no-color]
+ cat portals.json | node render-portal-table.js [--color | --no-color]
+
+Input:
+ A JSON array (or { "portals": [ ... ] }) of:
+ { "name": "Portal_1", "url": "https://...", "portalId": "<guid>", "state": true|false|"Enabled"|"Disabled" }
+
+Flags:
+ --markdown Render as a GitHub-flavored Markdown table (chat-safe — the
+ client sizes columns so the 🟢/🔴 emoji never misalign it).
+ Emit this output as a rendered table, NOT inside a code fence.
+ --color Force ANSI color on (green=Enabled, red=Disabled). ASCII box only.
+ --no-color Force color off (plain ASCII — safe for capturing / chat).
+ --icons Prefix the State cell with 🟢 / 🔴 (default: on).
+ --no-icons Omit the state icons (plain "Enabled" / "Disabled").
+ --unicode Render the fixed-width Unicode box (┌─┬─┐ │ ├─┼─┤ └─┴─┘) with a
+ rule between every row for terminal callers. Skill status
+ responses use --markdown. Use --no-color with the box so the
+ ANSI escapes don't clutter the box. Ignored when --markdown set.
+ --portalsFile Read JSON from a file instead of stdin.
+ --help Show this help.
+
+Color is auto-detected otherwise: on when stdout is a TTY and NO_COLOR is unset.
+The state icons (🟢 Enabled / 🔴 Disabled) are shown by default — pass
+--no-icons to suppress them.
+`;
+
+function parseFlags(argv) {
+ const out = { color: null, icons: true, markdown: false, unicode: false };
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--color') out.color = true;
+ else if (a === '--no-color') out.color = false;
+ else if (a === '--icons') out.icons = true;
+ else if (a === '--no-icons') out.icons = false;
+ else if (a === '--markdown' || a === '--md') out.markdown = true;
+ else if (a === '--unicode' || a === '--box') out.unicode = true;
+ else if (a === '--portalsFile') out.portalsFile = argv[++i];
+ else if (a === '--help') out.help = true;
+ }
+ return out;
+}
+
+async function main() {
+ const flags = parseFlags(process.argv);
+ if (flags.help) {
+ process.stdout.write(HELP);
+ return;
+ }
+ let raw;
+ if (flags.portalsFile) {
+ raw = require('fs').readFileSync(flags.portalsFile, 'utf8');
+ } else {
+ raw = await readStdin();
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (e) {
+ process.stderr.write(`render-portal-table: could not parse JSON input: ${e.message}\n`);
+ process.exit(1);
+ return;
+ }
+ const portals = Array.isArray(parsed) ? parsed : parsed.portals || [];
+ const rendered = flags.markdown
+ ? renderPortalTableMarkdown(portals, { icons: flags.icons })
+ : renderPortalTable(portals, { color: flags.color, icons: flags.icons, unicode: flags.unicode });
+ process.stdout.write(rendered + '\n');
+}
+
+module.exports = {
+ renderPortalTable,
+ renderPortalTableMarkdown,
+ normalizeState,
+ colorForState,
+ iconForState,
+};
+
+if (require.main === module) {
+ main();
+}
diff --git a/plugins/power-pages/skills/manage-governance/scripts/render-status-table.js b/plugins/power-pages/skills/manage-governance/scripts/render-status-table.js
new file mode 100644
index 000000000..06dfd30b8
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/render-status-table.js
@@ -0,0 +1,280 @@
+#!/usr/bin/env node
+
+// render-status-table.js — Renders the per-site EFFECTIVE governance-status
+// table for a CHILD authentication policy, showing the parent context columns
+// alongside the child's own state.
+//
+// WHY this exists — effective status ≠ own status for gated children
+// ------------------------------------------------------------------
+// Power Pages authentication governance is a tree (see
+// references/governance-mapping.json `policyAvailabilityDependencies` /
+// `effectiveStatusRules`):
+//
+// EnableExternalAuthProviders (the "Main Flag" / root parent)
+// ├─ EnableProtocolOpenIdConnect
+// ├─ EnableProtocolSAML20
+// ├─ EnableProtocolWsFederation
+// └─ EnableProtocolOpenAuth (OAuth 2.0 — also a parent)
+// ├─ EnableIdpOAuthFacebook
+// ├─ EnableIdpOAuthGoogle
+// └─ EnableIdpOAuthMicrosoft
+//
+// A child method's OWN governance setting being Enabled is necessary but NOT
+// sufficient — the method only actually works on a portal when EVERY gating
+// parent is also Enabled there. So the runtime-observable ("effective") status
+// is: own AND all parents. Concretely:
+// * OAuth 2.0 / OpenID Connect / SAML 2.0 / WS-Federation are effectively
+// Enabled on a portal only if that protocol AND External Auth are Enabled.
+// * Facebook / Google / Microsoft are effectively Enabled only if that IdP
+// AND OAuth 2.0 AND External Auth are all Enabled.
+//
+// This helper renders a Markdown table with one column per gating parent (in
+// `availabilityDependsOn` order — External Auth first, then OAuth 2.0 for the
+// social IdPs), plus a single Effective <child> Status column carrying the AND
+// result (own AND all parents). The child's OWN state is an input to that AND
+// but is not shown as its own column. That is exactly the "portal-wise status"
+// view the admin needs to see WHY a child is dark: the parent context and the
+// net effective status.
+//
+// Pure-data-in / data-out (network-free, unit-testable). The CLI reads a
+// { policy, portals:[{name,url,portalId,own,parents:{policyName:bool|null}}] }
+// JSON blob from stdin (or --file) and prints the Markdown table. The
+// orchestrator is responsible for reading the live own/parent states (via
+// get-env.js / get-portal.js) and assembling that blob — this module never
+// touches the network (DRY: it does not re-implement the read transport).
+
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+
+// Reuse the single-policy renderer's state normalization + icon helpers so the
+// 🟢/🔴 markers and Enabled/Disabled labels stay identical across every status
+// surface (DRY — one source for the visual convention).
+const { normalizeState, iconForState } = require('./render-portal-table');
+
+const MAPPING_PATH = path.join(__dirname, '..', 'references', 'governance-mapping.json');
+
+function loadMapping(mappingPath) {
+ const raw = fs.readFileSync(mappingPath || MAPPING_PATH, 'utf8');
+ return JSON.parse(raw);
+}
+
+function findPolicy(mapping, policyName) {
+ return (mapping.policies || []).find((p) => p.policyName === policyName) || null;
+}
+
+// The ordered parent chain to render as context columns for a child policy.
+// Read straight from the child's own `availabilityDependsOn` (authoritative;
+// the top-level effectiveStatusRules.parentColumnsByPolicy block is only the
+// readable overview). Order is meaningful and preserved: External Auth first,
+// then OAuth 2.0 for the three social IdPs — matching the admin's mental model
+// ("External Auth + OAuth" for Facebook/Google/Microsoft). A leaf/independent
+// policy (Maker Copilot, local login) — or External Auth itself as the root —
+// returns [] (no parent columns; effective == own).
+function parentChainForPolicy(policyName, mapping) {
+ const policy = findPolicy(mapping, policyName);
+ if (!policy || !Array.isArray(policy.availabilityDependsOn)) return [];
+ return policy.availabilityDependsOn.slice();
+}
+
+// Short header label for a policy's status column. Prefer the explicit
+// `statusColumnLabel` (e.g. "External Auth", "OAuth 2.0", "Google"); fall back
+// to summaryLabel/subject/policyName so an unlabeled policy still renders a
+// sensible header rather than crashing.
+function statusColumnLabel(policyName, mapping) {
+ const policy = findPolicy(mapping, policyName);
+ if (!policy) return policyName;
+ return policy.statusColumnLabel || policy.summaryLabel || policy.subject || policyName;
+}
+
+// Header for the final "net result" column. Defaults to
+// `Effective <statusColumnLabel> Status`, but a policy may override the entire
+// header string via `effectiveStatusLabel` in the mapping (e.g. OAuth 2.0 uses
+// "Effective OpenAuth State") — the admin controls the exact wording per policy
+// without affecting that policy's parent-column label elsewhere.
+function effectiveStatusLabel(policyName, mapping) {
+ const policy = findPolicy(mapping, policyName);
+ if (policy && policy.effectiveStatusLabel) return policy.effectiveStatusLabel;
+ return `Effective ${statusColumnLabel(policyName, mapping)} Status`;
+}
+
+// Combine the child's own state with its parents' states into the EFFECTIVE
+// status per the effectiveStatusRules contract:
+// * 'Enabled' iff every state (own + all parents) is Enabled;
+// * 'Disabled' iff no state is Unknown and at least one is Disabled;
+// * 'Unknown' otherwise (some own/parent state could not be read — fail
+// visible, never silently claim Enabled/Disabled on a partial read).
+// `states` is an array of already-normalized 'Enabled'/'Disabled'/'Unknown'
+// labels (own first, then each parent).
+function effectiveState(states) {
+ const list = Array.isArray(states) ? states : [];
+ if (list.length === 0) return 'Unknown';
+ if (list.some((s) => s === 'Unknown')) return 'Unknown';
+ if (list.every((s) => s === 'Enabled')) return 'Enabled';
+ return 'Disabled';
+}
+
+// Escape a cell for a GitHub-flavored Markdown table: a literal `|` would be
+// read as a column separator, and a newline would break the single-line cell.
+function mdCell(s) {
+ return String(s == null ? '' : s).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
+}
+
+// Format a normalized state label as an icon + word cell (🟢 Enabled /
+// 🔴 Disabled / plain Unknown). `icons` defaults on; pass false for plain text.
+function stateCell(label, icons) {
+ const on = icons !== false;
+ const icon = on ? iconForState(label) : '';
+ return icon ? `${icon} ${label}` : label;
+}
+
+/**
+ * Render the per-site effective-status Markdown table for a child policy.
+ *
+ * @param {object} req
+ * @param {string} req.policy - the child policy name (e.g. EnableIdpOAuthGoogle).
+ * @param {Array<{name?:string,url?:string,portalId?:string,own?:(boolean|string),parents?:object}>} req.portals
+ * Each portal carries its OWN state (`own`) and a `parents` map keyed by
+ * parent policy name → boolean|string|null live state.
+ * @param {object} [opts]
+ * @param {object} [opts.mapping] - preloaded mapping (else loaded from disk).
+ * @param {boolean} [opts.icons=true] - prefix state cells with 🟢/🔴.
+ * @returns {string} Markdown table (no trailing newline).
+ */
+function renderStatusTableMarkdown(req, opts = {}) {
+ const mapping = opts.mapping || loadMapping();
+ const icons = opts.icons !== false;
+ const policyName = req && req.policy;
+ const portals = Array.isArray(req && req.portals) ? req.portals : [];
+
+ const parents = parentChainForPolicy(policyName, mapping);
+ const ownLabel = statusColumnLabel(policyName, mapping);
+ const parentLabels = parents.map((p) => statusColumnLabel(p, mapping));
+
+ // Column order follows the dependency chain top-down so the admin reads the
+ // gating context first: the parents (External Auth, then OAuth 2.0 for social
+ // IdPs), then a single Effective <child> Status column. The child's OWN
+ // governance-setting value is still an input to the effective computation
+ // (own AND all parents) but is NOT shown as its own column — the admin asked
+ // for just the parent context plus the net effective result.
+ const effectiveHeader = effectiveStatusLabel(policyName, mapping);
+ const headers = ['#', 'Name', 'URL', 'Site ID', ...parentLabels, effectiveHeader];
+
+ const rows = portals.map((p, i) => {
+ const ownState = normalizeState(p && p.own);
+ const parentStates = parents.map((parentName) => {
+ const pv = p && p.parents ? p.parents[parentName] : undefined;
+ return normalizeState(pv);
+ });
+ // Effective = own AND every parent (order-independent logical AND). The own
+ // state still gates the result even though it has no dedicated column.
+ const eff = effectiveState([ownState, ...parentStates]);
+ return [
+ String(i + 1),
+ (p && p.name) || '(unnamed)',
+ (p && p.url) || '',
+ (p && p.portalId) || '',
+ ...parentStates.map((s) => stateCell(s, icons)),
+ stateCell(eff, icons),
+ ];
+ });
+
+ const head = '| ' + headers.map(mdCell).join(' | ') + ' |';
+ const sep = '| ' + headers.map(() => '---').join(' | ') + ' |';
+ const body = rows.map((r) => '| ' + r.map(mdCell).join(' | ') + ' |');
+ return [head, sep, ...body].join('\n');
+}
+
+function readStdin() {
+ return new Promise((resolve) => {
+ let data = '';
+ process.stdin.setEncoding('utf8');
+ process.stdin.on('data', (chunk) => (data += chunk));
+ process.stdin.on('end', () => resolve(data));
+ });
+}
+
+const HELP = `render-status-table.js — Render the per-site EFFECTIVE governance-status table
+for a child authentication policy (own state + parent context columns).
+
+The effective status of a gated child = its own setting AND every parent:
+ * OAuth 2.0 / OpenID Connect / SAML 2.0 / WS-Federation → also needs External Auth.
+ * Facebook / Google / Microsoft → also needs OAuth 2.0 AND External Auth.
+
+Usage:
+ echo '<JSON>' | node render-status-table.js
+ node render-status-table.js --file <path>
+
+Input JSON:
+ {
+ "policy": "EnableIdpOAuthGoogle",
+ "portals": [
+ { "name": "Portal_4", "url": "https://...", "portalId": "<guid>",
+ "own": true,
+ "parents": { "EnableExternalAuthProviders": true, "EnableProtocolOpenAuth": true } }
+ ]
+ }
+
+ "own" and each "parents" value accept true|false|"Enabled"|"Disabled"|null.
+ A null/unreadable state renders "Unknown" and forces Effective = Unknown.
+
+Flags:
+ --file <path> Read the JSON from a file instead of stdin.
+ --no-icons Omit the 🟢 / 🔴 state icons (plain Enabled / Disabled).
+ --help Show this help.
+
+Output is a GitHub-flavored Markdown table — emit it as a rendered table, NOT
+inside a code fence. Columns: # | Name | URL | Site ID | <parents…> |
+Effective <child> Status (parents first: External Auth → OAuth 2.0; the child's
+own state gates the Effective column but has no column of its own).
+`;
+
+function parseFlags(argv) {
+ const out = { icons: true };
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--no-icons') out.icons = false;
+ else if (a === '--icons') out.icons = true;
+ else if (a === '--file') out.file = argv[++i];
+ else if (a === '--help') out.help = true;
+ }
+ return out;
+}
+
+async function main() {
+ const flags = parseFlags(process.argv);
+ if (flags.help) {
+ process.stdout.write(HELP);
+ return;
+ }
+ let raw;
+ if (flags.file) {
+ raw = fs.readFileSync(flags.file, 'utf8');
+ } else {
+ raw = await readStdin();
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (e) {
+ process.stderr.write(`render-status-table: could not parse JSON input: ${e.message}\n`);
+ process.exit(1);
+ return;
+ }
+ const rendered = renderStatusTableMarkdown(parsed, { icons: flags.icons });
+ process.stdout.write(rendered + '\n');
+}
+
+module.exports = {
+ loadMapping,
+ parentChainForPolicy,
+ statusColumnLabel,
+ effectiveStatusLabel,
+ effectiveState,
+ renderStatusTableMarkdown,
+};
+
+if (require.main === module) {
+ main();
+}
diff --git a/plugins/power-pages/skills/manage-governance/scripts/resolve-portal-availability.js b/plugins/power-pages/skills/manage-governance/scripts/resolve-portal-availability.js
new file mode 100644
index 000000000..99977dac0
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/resolve-portal-availability.js
@@ -0,0 +1,820 @@
+#!/usr/bin/env node
+
+// resolve-portal-availability.js — Partition an environment's portals into
+// AVAILABLE vs UNAVAILABLE for a given CHILD governance policy, based on the
+// live state of that policy's PARENT policies.
+//
+// WHY this exists — the parent/child availability rule
+// ----------------------------------------------------
+// Power Pages authentication governance is a tree (see
+// references/governance-mapping.json `policyAvailabilityDependencies`):
+//
+// EnableExternalAuthProviders (the "Main Flag" / root parent)
+// ├─ EnableProtocolOpenIdConnect
+// ├─ EnableProtocolSAML20
+// ├─ EnableProtocolWsFederation
+// └─ EnableProtocolOpenAuth (OAuth 2.0 — also a parent)
+// ├─ EnableIdpOAuthFacebook
+// ├─ EnableIdpOAuthGoogle
+// └─ EnableIdpOAuthMicrosoft
+//
+// A portal (or the whole env) is only ELIGIBLE for governing a child setting
+// where EVERY gating parent is Enabled for that portal. Concretely:
+// * If External Auth is Disabled on a portal/env, that portal is UNAVAILABLE
+// for OpenID Connect / SAML 2.0 / WS-Federation / OAuth 2.0.
+// * If OAuth 2.0 OR External Auth is Disabled on a portal/env, that portal is
+// UNAVAILABLE for Facebook / Google / Microsoft.
+// The picker must still SHOW the unavailable portals — listed below the
+// available ones with the blocking parent named — so the admin understands why
+// they cannot target them.
+//
+// This module is pure-data-in / data-out for the partition + render logic
+// (network-free, unit-testable). The optional CLI mode reads each parent's
+// env-level value (get-env op) plus the env's inclusion/exclusion lists
+// (get-portal op) via the shared governance transport, builds `parentStates`,
+// and prints the partition (JSON or Markdown). A portal list is supplied on
+// stdin from list-portals.js (or, for backward compatibility, by
+// --portalsFile) — this module never re-implements /websites pagination (DRY).
+
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+
+const MAPPING_PATH = path.join(__dirname, '..', 'references', 'governance-mapping.json');
+
+function loadMapping(mappingPath) {
+ const raw = fs.readFileSync(mappingPath || MAPPING_PATH, 'utf8');
+ return JSON.parse(raw);
+}
+
+function findPolicy(mapping, policyName) {
+ return (mapping.policies || []).find((p) => p.policyName === policyName) || null;
+}
+
+// The gating parents a child policy depends on. Read straight from the child's
+// own `availabilityDependsOn` (the per-policy field is authoritative; the
+// top-level policyAvailabilityDependencies block is only the readable overview).
+// A leaf/independent policy (e.g. Maker Copilot, local login) returns [].
+function dependenciesForPolicy(policyName, mapping) {
+ const policy = findPolicy(mapping, policyName);
+ if (!policy || !Array.isArray(policy.availabilityDependsOn)) return [];
+ return policy.availabilityDependsOn.slice();
+}
+
+// Transitive parent closure (ALL ancestors) of a policy, walked via each
+// policy's own `availabilityDependsOn`. For a social IdP (e.g. Google) this is
+// { EnableExternalAuthProviders, EnableProtocolOpenAuth }; for a protocol it is
+// { EnableExternalAuthProviders }; for a leaf/independent policy it is empty.
+// Used to keep the remediation chain restricted to real gating ancestors.
+function transitiveParents(policyName, mapping, acc = new Set()) {
+ for (const parent of dependenciesForPolicy(policyName, mapping)) {
+ if (!acc.has(parent)) {
+ acc.add(parent);
+ transitiveParents(parent, mapping, acc);
+ }
+ }
+ return acc;
+}
+
+// Depth of a policy in the availability DAG = longest path to a ROOT (a policy
+// with no `availabilityDependsOn`). Roots (EnableExternalAuthProviders) are
+// depth 0; OAuth 2.0 is depth 1; the social IdPs are depth 2. We topo-sort the
+// blocking parents by this depth so remediation ALWAYS offers the root blocker
+// first — never a parent (e.g. OAuth 2.0) before the parent that itself gates it
+// (External Auth). Offering the deeper one first is the "dead-end OR" defect: its
+// own parent is still off, so enabling it hits the same hard block.
+function availabilityDepth(policyName, mapping, memo = {}) {
+ if (memo[policyName] != null) return memo[policyName];
+ const parents = dependenciesForPolicy(policyName, mapping);
+ const d = parents.length === 0
+ ? 0
+ : 1 + Math.max(...parents.map((p) => availabilityDepth(p, mapping, memo)));
+ memo[policyName] = d;
+ return d;
+}
+
+// Ordered remediation chain: the currently-DISABLED gating parents the admin
+// must enable — IN DEPENDENCY ORDER (root-first) — to unblock `targetPolicy`.
+//
+// `blockingParentNames` is the set of parents that block at least one portal
+// (the union of every unavailable portal's `blockingParents`). We keep only the
+// ones inside `targetPolicy`'s transitive ancestor set, de-dupe, then sort by DAG
+// depth (root-first) with a stable name tie-break. Because the chain is derived
+// from the very blocking data computeAvailability just produced, re-running the
+// resolver after the admin enables one parent naturally drops it from the chain
+// on the next pass — that is what powers the "enable one parent → auto-resume the
+// original child intent" loop. The orchestrator must only ever offer `chain[0]`
+// (surfaced as `next`) at a time, never the whole list as parallel OR-options.
+function computeRemediationChain(targetPolicy, blockingParentNames, mapping) {
+ const closure = transitiveParents(targetPolicy, mapping);
+ const memo = {};
+ const seen = new Set();
+ const chain = [];
+ for (const name of blockingParentNames || []) {
+ if (!closure.has(name) || seen.has(name)) continue;
+ seen.add(name);
+ const p = findPolicy(mapping, name);
+ chain.push({
+ policyName: name,
+ subject: (p && p.subject) || name,
+ depth: availabilityDepth(name, mapping, memo),
+ });
+ }
+ chain.sort((a, b) => a.depth - b.depth || a.policyName.localeCompare(b.policyName));
+ return chain.map(({ policyName, subject }) => ({ policyName, subject }));
+}
+
+// Canonicalize an env-level governance value to All | None | Include | Exclude.
+// get-env.js already normalizes *Sites -> canonical, but be defensive: accept
+// the applyTo enum spellings too so this works whether it is fed the normalized
+// `value` or the raw `body`. Anything unrecognized (including a missing value
+// from a failed read) returns 'Unknown'.
+function canonicalizeEnvValue(v) {
+ const s = String(v == null ? '' : v).trim().toLowerCase();
+ if (s === 'all' || s === 'allsites') return 'All';
+ if (s === 'none') return 'None';
+ if (s === 'include' || s === 'includesites' || s === 'includedsites') return 'Include';
+ if (
+ s === 'exclude' ||
+ s === 'excludesites' ||
+ s === 'excludedsites' ||
+ s === 'allsitesexceptexcluded'
+ ) {
+ return 'Exclude';
+ }
+ return 'Unknown';
+}
+
+// Resolve a single portal's state under a parent policy, following the
+// siteStateRules contract (references/governance-mapping.json `siteStateRules`,
+// mirrored in SKILL.md Phase 4.4.3):
+//
+// env All -> Enabled
+// env None -> Disabled
+// env Include -> Enabled iff the portal is on the inclusion list
+// env Exclude -> Disabled iff the portal is on the exclusion list
+//
+// A parent env value we cannot canonicalize returns 'Unknown' (the availability
+// layer treats Unknown as fail-open — see computeAvailability).
+function computeSiteState(envValue, opts = {}) {
+ const canon = canonicalizeEnvValue(envValue);
+ const inInclusion = Boolean(opts.inInclusion);
+ const inExclusion = Boolean(opts.inExclusion);
+ if (canon === 'All') return 'Enabled';
+ if (canon === 'None') return 'Disabled';
+ if (canon === 'Include') return inInclusion ? 'Enabled' : 'Disabled';
+ if (canon === 'Exclude') return inExclusion ? 'Disabled' : 'Enabled';
+ return 'Unknown';
+}
+
+// Pull the inclusion/exclusion portal-id sets out of a get-portal (env-level)
+// response body. The gateway's exact field naming for these lists is documented
+// as an ASSUMPTION in references/commands.md and has been observed under several
+// spellings across rings (InclusionList / IncludedSites / details.IncludedSites,
+// camel- or Pascal-cased), and each entry may be a bare id string OR an object
+// carrying the id under id/Id/portalId/websiteId. Be liberal in what we accept
+// so a naming drift degrades to "list looks empty" (fail-open) rather than a
+// crash. Returns { inclusion: Set<string>, exclusion: Set<string> } of lowercased
+// id strings for case-insensitive membership tests.
+function extractLists(body) {
+ const inclusion = new Set();
+ const exclusion = new Set();
+ if (!body || typeof body !== 'object') return { inclusion, exclusion };
+
+ const details = body.details || body.Details || {};
+ const idOf = (entry) => {
+ if (entry == null) return null;
+ if (typeof entry === 'string') return entry;
+ if (typeof entry === 'object') {
+ return entry.id || entry.Id || entry.portalId || entry.PortalId || entry.websiteId || entry.WebsiteId || null;
+ }
+ return null;
+ };
+ const harvest = (arr, set) => {
+ if (!Array.isArray(arr)) return;
+ for (const entry of arr) {
+ const id = idOf(entry);
+ if (id) set.add(String(id).trim().toLowerCase());
+ }
+ };
+
+ // Inclusion spellings.
+ harvest(body.InclusionList || body.inclusionList, inclusion);
+ harvest(body.IncludedSites || body.includedSites, inclusion);
+ harvest(details.InclusionList || details.inclusionList, inclusion);
+ harvest(details.IncludedSites || details.includedSites, inclusion);
+ // Exclusion spellings.
+ harvest(body.ExclusionList || body.exclusionList, exclusion);
+ harvest(body.ExcludedSites || body.excludedSites, exclusion);
+ harvest(details.ExclusionList || details.exclusionList, exclusion);
+ harvest(details.ExcludedSites || details.excludedSites, exclusion);
+
+ return { inclusion, exclusion };
+}
+
+function portalIdOf(portal) {
+ if (!portal) return null;
+ const id = portal.portalId || portal.id || portal.Id || null;
+ return id == null ? null : String(id).trim();
+}
+
+function parsePortalsJson(raw) {
+ const parsed = JSON.parse(raw);
+ return Array.isArray(parsed) ? parsed : parsed.portals || [];
+}
+
+function readStdin() {
+ return new Promise((resolve, reject) => {
+ let data = '';
+ process.stdin.setEncoding('utf8');
+ process.stdin.on('data', (chunk) => (data += chunk));
+ process.stdin.on('end', () => resolve(data));
+ process.stdin.on('error', reject);
+ });
+}
+
+async function readPortalsInput(portalsFile) {
+ // Stdin is the default so callers can stream list-portals.js output directly
+ // without writing site metadata to a temporary file. --portalsFile remains
+ // supported for existing automation.
+ const raw = portalsFile ? fs.readFileSync(portalsFile, 'utf8') : await readStdin();
+ return parsePortalsJson(raw);
+}
+
+// Batch form of computeSiteState — resolve MANY portals' own state for a single
+// policy from ONE env read + ONE getDetails read, with zero per-portal network
+// calls. This is the whole point of the getDetails path: the gateway's
+// `GET /websites/{portalId}/governance/{policy}` endpoint is per-portal (one
+// boolean per call), so reading N portals costs N cold-started calls and N
+// chances to hit a transient "PAC not signed in". Instead read the env value
+// once (get-env.js) and the inclusion/exclusion lists once
+// (get-details.js -> GET /governance/{policy}/details), then classify every
+// portal locally against those lists via the same siteStateRules contract.
+//
+// `envValue` is the raw env-level policy value (All|None|Include|Exclude, any
+// casing). `detailsBody` is the getDetails response body (its IncludedSites /
+// ExcludedSites arrays are parsed by extractLists, which already tolerates the
+// several field spellings observed across rings). `portals` is an array of
+// portal ids (strings) or portal objects ({ portalId|id|Id, name, url, ... }).
+// Returns one entry per input portal preserving order and any passed-through
+// name/url, with `state` = 'Enabled'|'Disabled'|'Unknown'.
+function resolvePortalStates(envValue, detailsBody, portals) {
+ const { inclusion, exclusion } = extractLists(detailsBody);
+ const list = Array.isArray(portals) ? portals : [];
+ return list.map((entry) => {
+ // Accept either a bare id string or a portal object so callers can pass the
+ // raw id list OR the list-portals.js records straight through.
+ const isObj = entry && typeof entry === 'object';
+ const id = isObj ? portalIdOf(entry) : entry == null ? '' : String(entry).trim();
+ const key = String(id || '').toLowerCase();
+ const state = computeSiteState(envValue, {
+ inInclusion: inclusion.has(key),
+ inExclusion: exclusion.has(key),
+ });
+ const out = { portalId: id || '', state };
+ if (isObj) {
+ if (entry.name != null) out.name = entry.name;
+ // list-portals.js records carry the site URL under websiteUrl; the render
+ // helpers expect `url`, so surface both spellings when present.
+ const url = entry.url != null ? entry.url : entry.websiteUrl;
+ if (url != null) out.url = url;
+ }
+ return out;
+ });
+}
+
+/**
+ * Partition portals into available / unavailable for a target child policy.
+ *
+ * @param {object} req
+ * @param {string} req.targetPolicy - the CHILD policy the admin wants to govern.
+ * @param {Array<object>} req.portals - portal objects ({ portalId, name, websiteUrl|url, ... }).
+ * @param {object} req.parentStates - map keyed by parent policyName:
+ * { [parentPolicyName]: {
+ * envValue: 'All'|'None'|'Include'|'Exclude'|'Unknown',
+ * inclusion?: Set<string>|string[], // portal ids (any casing)
+ * exclusion?: Set<string>|string[],
+ * membershipReadError?: { statusCode: number, message: string }
+ * } }
+ * A parent absent from the map, or with envValue 'Unknown', is treated as
+ * fail-open (does not block) but recorded in `unreadParents`.
+ * @param {object} [opts]
+ * @param {object} [opts.mapping] - preloaded mapping (defaults to committed JSON).
+ * @returns {{
+ * policy: string,
+ * dependencies: string[],
+ * available: Array<object>,
+ * unavailable: Array<object & { blockingParents: string[], blockedBy: string[], unreadParents: string[] }>,
+ * remediationChain: Array<{ policyName: string, subject: string }>,
+ * next: { policyName: string, subject: string } | null
+ * }}
+ *
+ * `remediationChain` is the root-first ordered list of currently-disabled gating
+ * parents the admin must enable to unblock the child (empty for a leaf policy or
+ * when nothing blocks). `next` is `remediationChain[0]` — the ONLY parent the
+ * orchestrator should offer at a time (see computeRemediationChain).
+ */
+function computeAvailability(req, opts = {}) {
+ const mapping = opts.mapping || loadMapping();
+ const targetPolicy = req.targetPolicy;
+ const portals = Array.isArray(req.portals) ? req.portals : [];
+ const parentStates = req.parentStates || {};
+ const deps = dependenciesForPolicy(targetPolicy, mapping);
+
+ // No dependencies -> every portal is available (leaf/independent policy).
+ if (deps.length === 0) {
+ return {
+ policy: targetPolicy,
+ dependencies: [],
+ available: portals.slice(),
+ unavailable: [],
+ remediationChain: [],
+ next: null,
+ };
+ }
+
+ // Pre-normalize each parent's membership sets once.
+ const norm = {};
+ const membershipReadErrors = {};
+ for (const parent of deps) {
+ const st = parentStates[parent] || {};
+ const toSet = (v) => {
+ if (v instanceof Set) {
+ return new Set([...v].map((x) => String(x).trim().toLowerCase()));
+ }
+ if (Array.isArray(v)) return new Set(v.map((x) => String(x).trim().toLowerCase()));
+ return new Set();
+ };
+ norm[parent] = {
+ envValue: st.envValue,
+ inclusion: toSet(st.inclusion),
+ exclusion: toSet(st.exclusion),
+ membershipUnread: Boolean(st.membershipReadError)
+ && ['Include', 'Exclude'].includes(canonicalizeEnvValue(st.envValue)),
+ };
+ if (norm[parent].membershipUnread) membershipReadErrors[parent] = st.membershipReadError;
+ }
+
+ const available = [];
+ const unavailable = [];
+ for (const portal of portals) {
+ const pid = (portalIdOf(portal) || '').toLowerCase();
+ const blockingParents = [];
+ const unreadParents = [];
+ for (const parent of deps) {
+ const st = norm[parent];
+ const state = st.membershipUnread ? 'Unknown' : computeSiteState(st.envValue, {
+ inInclusion: st.inclusion.has(pid),
+ inExclusion: st.exclusion.has(pid),
+ });
+ if (state === 'Disabled') blockingParents.push(parent);
+ else if (state === 'Unknown') unreadParents.push(parent);
+ }
+ if (blockingParents.length > 0) {
+ unavailable.push({
+ ...portal,
+ blockingParents,
+ // Human-facing parent labels (the `subject` from the mapping, e.g.
+ // "External authentication providers"), for the "blocked by" reason.
+ blockedBy: blockingParents.map((n) => {
+ const p = findPolicy(mapping, n);
+ return (p && p.subject) || n;
+ }),
+ unreadParents,
+ });
+ } else {
+ // Fail-open: an unread parent does NOT hide the portal, but we surface it
+ // so the caller must disclose "couldn't confirm <parent>" before consent.
+ available.push(unreadParents.length ? { ...portal, unreadParents } : portal);
+ }
+ }
+ // Ordered remediation chain (root-first) from the parents that block at least
+ // one portal. Derived from the same blocking data above, so it shortens by one
+ // each time the admin enables a parent and the resolver is re-run — powering
+ // the "enable one parent -> auto-resume the original child" loop. Only chain[0]
+ // (`next`) is ever offered at a time; a two-parent social IdP with both parents
+ // off yields [External Auth, OAuth 2.0], never the reverse.
+ const blockingUnion = [];
+ const seenBlocking = new Set();
+ for (const u of unavailable) {
+ for (const bp of u.blockingParents) {
+ if (!seenBlocking.has(bp)) {
+ seenBlocking.add(bp);
+ blockingUnion.push(bp);
+ }
+ }
+ }
+ const remediationChain = computeRemediationChain(targetPolicy, blockingUnion, mapping);
+ return {
+ policy: targetPolicy,
+ dependencies: deps,
+ available,
+ unavailable,
+ remediationChain,
+ next: remediationChain[0] || null,
+ ...(Object.keys(membershipReadErrors).length ? { membershipReadErrors } : {}),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Rendering — the partitioned picker table (Markdown, chat-safe)
+// ---------------------------------------------------------------------------
+function mdCell(s) {
+ return String(s == null ? '' : s).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
+}
+
+function urlOf(portal) {
+ return (portal && (portal.url || portal.websiteUrl || portal.WebsiteUrl)) || '';
+}
+
+function withUnreadParentWarning(partition, rendered) {
+ const parents = [...new Set(
+ [...(partition.available || []), ...(partition.unavailable || [])]
+ .flatMap((portal) => portal.unreadParents || [])
+ )];
+ if (parents.length === 0) return rendered;
+ return `**Warning:** Could not verify parent state or site membership for ${parents.map(mdCell).join(', ')}. ` +
+ 'Eligibility is unverified for affected sites; unread parents do not block selection (fail-open).\n\n' +
+ rendered;
+}
+
+// Render ONE Markdown table listing EVERY portal with an explicit **Eligible**
+// (Yes / No) column: the ELIGIBLE portals first, then the INELIGIBLE ones
+// directly BELOW (per the requirement "Disabled Portal or Environment should be
+// shown just below it"). The Eligible column carries a ✅ Yes / 🚫 No marker;
+// ineligible rows also name the blocking parent so the admin sees *why* the
+// portal can't be targeted. This is the picker the admin sees for the seven
+// child auth policies — the user asked to ALWAYS see the full portal list with a
+// Yes/No eligibility status rather than the filtered available-only view.
+//
+// Empty-state exception: when NO portal is eligible (a required parent is
+// Disabled env-wide), an all-"No" table would be useless and misleading — the
+// child cannot be governed anywhere until the parent is enabled. In that case we
+// delegate to renderAvailablePortalsMarkdown, which returns the single
+// "<parent> is off for this environment" message (and the orchestrator must not
+// prompt for a scope). Emit the output as a rendered Markdown table (NOT inside a
+// code fence). `opts.icons` defaults on.
+function renderAvailabilityMarkdown(partition, opts = {}) {
+ const icons = opts.icons !== false;
+ const avail = Array.isArray(partition.available) ? partition.available : [];
+ const unavail = Array.isArray(partition.unavailable) ? partition.unavailable : [];
+
+ // No eligible portal anywhere -> show the parent-disabled message instead of a
+ // table of all-"No" rows (reuses the available-only renderer's empty-state
+ // branch so the phrasing stays identical and single-sourced).
+ if (avail.length === 0 && unavail.length > 0) {
+ return renderAvailablePortalsMarkdown(partition, opts);
+ }
+
+ const headers = ['#', 'Portal Name', 'Portal URL', 'Portal ID', 'Eligible'];
+
+ const rows = [];
+ let n = 0;
+ for (const p of avail) {
+ n += 1;
+ rows.push([
+ String(n),
+ (p && p.name) || '(unnamed)',
+ urlOf(p),
+ portalIdOf(p) || '',
+ (icons ? '✅ Yes' : 'Yes') + (p.unreadParents?.length ? ' (unverified)' : ''),
+ ]);
+ }
+ for (const p of unavail) {
+ n += 1;
+ const reason = (p.blockedBy && p.blockedBy.length)
+ ? `blocked by ${p.blockedBy.join(', ')} (Disabled)`
+ : 'blocked by a parent setting (Disabled)';
+ rows.push([
+ String(n),
+ (p && p.name) || '(unnamed)',
+ urlOf(p),
+ portalIdOf(p) || '',
+ (icons ? '🚫 No — ' : 'No — ') + reason,
+ ]);
+ }
+
+ const head = '| ' + headers.map(mdCell).join(' | ') + ' |';
+ const sep = '| ' + headers.map(() => '---').join(' | ') + ' |';
+ const body = rows.map((r) => '| ' + r.map(mdCell).join(' | ') + ' |');
+ return withUnreadParentWarning(partition, [head, sep, ...body].join('\n'));
+}
+
+// Render ONLY the AVAILABLE portals for a child auth policy — the scope picker
+// the admin uses for the four sign-in protocols (OpenID Connect / SAML 2.0 /
+// WS-Federation / OAuth 2.0) and the social IdPs. Per the requirement, the
+// scope list must show ONLY the sites the admin can actually target:
+// * list only the portals where the gating parent (External Auth — and for
+// the social IdPs also OAuth 2.0) is ENABLED;
+// * if NONE are available, show a single clear "<parent> is Disabled for this
+// environment" message INSTEAD of an empty table — the child cannot be
+// governed anywhere in the env until the parent is enabled, so the
+// orchestrator must not prompt for a scope;
+// * if only SOME are available, list just those and append an info line
+// naming how many sites were hidden and why.
+// This differs from renderAvailabilityMarkdown (which lists the ineligible
+// portals BELOW the eligible ones): here the unavailable portals are OMITTED
+// from the table and only summarized, because the scope picker only needs the
+// actionable set.
+function renderAvailablePortalsMarkdown(partition, opts = {}) {
+ const mapping = opts.mapping || loadMapping();
+ const icons = opts.icons !== false;
+ const avail = Array.isArray(partition.available) ? partition.available : [];
+ const unavail = Array.isArray(partition.unavailable) ? partition.unavailable : [];
+
+ const childPolicy = findPolicy(mapping, partition.policy);
+ const childSubject = (childPolicy && childPolicy.subject) || partition.policy || 'this setting';
+
+ // Distinct human-facing name(s) of the parent(s) that blocked sites. Prefer
+ // the `blockedBy` labels actually recorded on the unavailable portals; fall
+ // back to the child's declared dependency subjects when nothing is blocked
+ // (so the empty-state message still names a parent even in odd data).
+ const blockingSubjects = [];
+ const seen = new Set();
+ for (const p of unavail) {
+ for (const subj of p.blockedBy || []) {
+ if (!seen.has(subj)) { seen.add(subj); blockingSubjects.push(subj); }
+ }
+ }
+ if (blockingSubjects.length === 0) {
+ for (const dep of partition.dependencies || []) {
+ const pp = findPolicy(mapping, dep);
+ const subj = (pp && pp.subject) || dep;
+ if (!seen.has(subj)) { seen.add(subj); blockingSubjects.push(subj); }
+ }
+ }
+ const subjects = blockingSubjects.length
+ ? blockingSubjects
+ : ['The required parent setting'];
+ // The social IdPs (Facebook / Google / Microsoft) depend on TWO parents —
+ // External authentication providers AND OAuth 2.0 sign-in — so a site is only
+ // eligible when BOTH are enabled, and is blocked when EITHER is disabled.
+ // That asymmetry drives two different conjunctions:
+ // * disabled-state phrasing uses "or" — either parent being off blocks the
+ // child ("the External Auth OR OAuth 2.0 Governance setting is off");
+ // * enable / enabled-state phrasing uses "and" — every parent must be on
+ // ("turn on both the External Auth AND OAuth 2.0 Governance settings";
+ // "both … Governance settings are on").
+ const multi = subjects.length > 1;
+ const orList = subjects.join(' or ');
+ const andList = subjects.join(' and ');
+ // Plain-language "Governance setting" phrasing for the availability messages,
+ // so the admin sees WHY a portal is filtered in the same vocabulary the rest
+ // of the skill uses: the child and its blocking parent(s) are each named as
+ // "the <subject> Governance setting", their state as on/off, and the
+ // consequence spelled out as "… can't apply". E.g. "the OAuth 2.0 sign-in
+ // Governance setting can't apply because the External authentication providers
+ // Governance setting is off". See the parent/child availability model in
+ // references/governance-mapping.json.
+ const childGov = `the ${childSubject} Governance setting`;
+ // Disabled-state reference to the blocking parent(s). Singular "setting" even
+ // in the multi-parent case because the "or" makes it read as a single either
+ // clause ("the X or Y Governance setting is off").
+ const parentGovOff = `the ${orList} Governance setting`;
+ // Enable instruction (empty state): every parent must be turned on, so the
+ // multi-parent case says "both … Governance settings".
+ const enableInstruction = multi
+ ? `turn on both the ${andList} Governance settings`
+ : `turn on the ${andList} Governance setting`;
+ // Subset "only where …" clause: every parent must be on.
+ const enabledClause = multi
+ ? `both the ${andList} Governance settings are on`
+ : `the ${andList} Governance setting is on`;
+
+ // Empty state — no site is eligible because a parent is Disabled env-wide (or
+ // Disabled on every site). For a social IdP that means External Auth or OAuth
+ // 2.0 (or both) is off. Return the single message the picker shows in place of
+ // a table; the orchestrator must NOT prompt for a scope here.
+ if (avail.length === 0) {
+ const dot = icons ? '🔴 ' : '';
+ return withUnreadParentWarning(partition,
+ `**${dot}The ${orList} Governance setting is off for this environment.** ` +
+ `No sites are available to configure ${childGov} here — ${enableInstruction} first, then try again.`);
+ }
+
+ // Render only the available portals (the actionable set).
+ const headers = ['#', 'Portal Name', 'Portal URL', 'Portal ID'];
+ const head = '| ' + headers.join(' | ') + ' |';
+ const sep = '| ' + headers.map(() => '---').join(' | ') + ' |';
+ const rows = avail.map((p, i) => '| ' + [
+ String(i + 1),
+ mdCell((p && p.name) || '(unnamed)'),
+ mdCell(urlOf(p)),
+ mdCell(portalIdOf(p) || ''),
+ ].join(' | ') + ' |');
+ const out = [head, sep, ...rows];
+
+ // "Proper information" when only a subset is eligible: name how many sites are
+ // shown vs hidden and why, in plain "Governance setting" language so the admin
+ // understands the list was filtered and what would unblock the hidden sites.
+ if (unavail.length > 0) {
+ const total = avail.length + unavail.length;
+ const dot = icons ? '🟢 ' : '';
+ out.push('');
+ out.push(
+ `> ${dot}Showing ${avail.length} of ${total} site(s) — ${childGov} can only ` +
+ `be configured on sites where ${enabledClause}. ` +
+ `${unavail.length} site(s) are hidden because ${parentGovOff} is off on them, ` +
+ `so ${childGov} can't apply there.`
+ );
+ }
+ return withUnreadParentWarning(partition, out.join('\n'));
+}
+
+// ---------------------------------------------------------------------------
+// CLI — read parent states via the governance transport, partition, print.
+// ---------------------------------------------------------------------------
+async function readParentStates(deps, envId) {
+ // Lazy-require the transport so the pure functions above (and their tests)
+ // never pull in the network stack.
+ const { callGovernance } = require('./governance-transport');
+ const { normalizeEnvValue } = require('./policies');
+ const parentStates = {};
+ for (const parent of deps) {
+ // Env-level value for this parent.
+ const envRes = await callGovernance({ op: 'getEnv', envId, policy: parent });
+ if (!envRes.ok) {
+ const msg = envRes.error?.message || `status ${envRes.statusCode}`;
+ const code = envRes.error?.code === 'ContextError' ? 2 : 1;
+ const err = new Error(`Reading parent "${parent}" env state failed: ${msg}`);
+ err.exitCode = code;
+ throw err;
+ }
+ const envValue = canonicalizeEnvValue(normalizeEnvValue(envRes.body));
+
+ // Inclusion/exclusion lists only matter for Include/Exclude env values.
+ //
+ // These lists come from the env-level `getDetails` op
+ // (`GET /governance/{policy}/details`), which returns the whole list, e.g.:
+ // { "IncludedSites": ["096b20ff-…","214d497a-…"], "ExcludedSites": null }
+ //
+ // NOT from `getPortal` (`GET /websites/{portalId}/governance/{policy}`):
+ // that op is portal-scoped and returns only a single boolean for the one
+ // portal id (`{ ..., "body": true|false }`) — it never returns the env's
+ // full list. It also 404s on a dummy all-zero id ("Website with the given
+ // id does not exist"), so the previous dummy-id `getPortal` call always
+ // came back empty, leaving `inclusion` empty and making every portal
+ // resolve to Disabled — i.e. an `Include` parent (enabled on a subset) was
+ // mis-reported as disabled env-wide. `getDetails` is the correct source.
+ let inclusion = new Set();
+ let exclusion = new Set();
+ let membershipReadError;
+ if (envValue === 'Include' || envValue === 'Exclude') {
+ const listRes = await callGovernance({
+ op: 'getDetails',
+ envId,
+ policy: parent,
+ });
+ if (listRes.ok) {
+ const lists = extractLists(listRes.body);
+ inclusion = lists.inclusion;
+ exclusion = lists.exclusion;
+ } else {
+ const message = listRes.error?.message || `status ${listRes.statusCode}`;
+ if (listRes.statusCode === 401 || listRes.statusCode === 403 || listRes.error?.code === 'ContextError') {
+ const error = new Error(`Reading parent "${parent}" site membership failed: ${message}`);
+ error.exitCode = 2;
+ throw error;
+ }
+ // An unread Include/Exclude list is not an empty successful list.
+ // Preserve its scope but mark per-site eligibility Unknown (fail-open).
+ membershipReadError = { statusCode: listRes.statusCode || 0, message };
+ }
+ }
+ parentStates[parent] = {
+ envValue, inclusion, exclusion,
+ ...(membershipReadError ? { membershipReadError } : {}),
+ };
+ }
+ return parentStates;
+}
+
+const HELP = `resolve-portal-availability.js — Partition portals into available /
+unavailable for a CHILD governance policy, based on its parent policies' state.
+
+Usage:
+ node list-portals.js [--envId <guid>] |
+ node resolve-portal-availability.js --policy <childPolicy> [--envId <guid>] [--markdown]
+
+Flags:
+ --policy Child policy name (e.g. EnableProtocolOpenIdConnect,
+ EnableIdpOAuthGoogle). Leaf policies with no parents return
+ every portal as available.
+ stdin JSON produced by list-portals.js ({ portals: [...] } or a bare
+ array). This script does NOT re-page /websites.
+ --portalsFile Backward-compatible alternative to stdin.
+ --envId Optional environment id (falls back to the current PAC env).
+ --markdown Print the picker table (Markdown) instead of JSON. The default
+ --markdown view lists EVERY portal with an explicit Eligible
+ (Yes / No) column — eligible portals first, ineligible ones
+ below with the blocking parent named — and falls back to a
+ single "<parent> is off for this environment" message when NO
+ portal is eligible.
+ --available-only With --markdown, list ONLY the eligible portals (a stricter
+ view that hides the ineligible ones entirely). Shows the same
+ "<parent> is Disabled for this environment" message when none
+ are eligible, and an info line when only a subset is.
+ --help Show this help.
+
+Exit codes:
+ 0 Success 2 Sign-in required 1 Other failure
+
+Stdout (JSON, default):
+ { "status": "ok", "policy": "<name>", "dependencies": [ ... ],
+ "available": [ { portal } ... ],
+ "unavailable": [ { portal, "blockingParents": [...], "blockedBy": [...] } ... ] }
+`;
+
+function parseFlags(argv) {
+ const out = { markdown: false };
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--policy') out.policy = argv[++i];
+ else if (a === '--portalsFile') out.portalsFile = argv[++i];
+ else if (a === '--envId') out.envId = argv[++i];
+ else if (a === '--markdown' || a === '--md') out.markdown = true;
+ else if (a === '--available-only' || a === '--availableOnly') out.availableOnly = true;
+ else if (a === '--help') out.help = true;
+ }
+ return out;
+}
+
+async function main() {
+ const flags = parseFlags(process.argv);
+ if (flags.help) {
+ process.stdout.write(HELP);
+ return;
+ }
+ if (!flags.policy) {
+ process.stderr.write('Usage: node list-portals.js | node resolve-portal-availability.js --policy <name> [--envId <guid>] [--markdown]\n');
+ process.exit(1);
+ return;
+ }
+
+ const { assertPolicy } = require('./policies');
+ assertPolicy(flags.policy);
+
+ const mapping = loadMapping();
+ let portals;
+ try {
+ portals = await readPortalsInput(flags.portalsFile);
+ } catch (e) {
+ process.stderr.write(`resolve-portal-availability: could not read/parse portal JSON: ${e.message}\n`);
+ process.exit(1);
+ return;
+ }
+ const deps = dependenciesForPolicy(flags.policy, mapping);
+
+ let parentStates = {};
+ if (deps.length > 0) {
+ try {
+ parentStates = await readParentStates(deps, flags.envId);
+ } catch (e) {
+ process.stderr.write(`${e.message}\n`);
+ process.exit(e.exitCode || 1);
+ return;
+ }
+ }
+
+ const partition = computeAvailability(
+ { targetPolicy: flags.policy, portals, parentStates },
+ { mapping }
+ );
+
+ if (flags.markdown) {
+ // `--available-only` shows ONLY the eligible portals (the strictly
+ // actionable set). The default markdown view (used by the scope picker)
+ // lists EVERY portal with an explicit Eligible (Yes/No) column — eligible
+ // rows first, ineligible ones below with the blocking parent named.
+ const render = flags.availableOnly
+ ? renderAvailablePortalsMarkdown(partition, { mapping })
+ : renderAvailabilityMarkdown(partition, { mapping });
+ process.stdout.write(render + '\n');
+ return;
+ }
+ process.stdout.write(JSON.stringify({ status: 'ok', ...partition }, null, 2) + '\n');
+}
+
+module.exports = {
+ loadMapping,
+ findPolicy,
+ dependenciesForPolicy,
+ transitiveParents,
+ availabilityDepth,
+ computeRemediationChain,
+ canonicalizeEnvValue,
+ computeSiteState,
+ extractLists,
+ parsePortalsJson,
+ readPortalsInput,
+ resolvePortalStates,
+ computeAvailability,
+ renderAvailabilityMarkdown,
+ renderAvailablePortalsMarkdown,
+ readParentStates,
+};
+
+if (require.main === module) {
+ main();
+}
diff --git a/plugins/power-pages/skills/manage-governance/scripts/set-governance.js b/plugins/power-pages/skills/manage-governance/scripts/set-governance.js
new file mode 100644
index 000000000..7bd191327
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/set-governance.js
@@ -0,0 +1,372 @@
+#!/usr/bin/env node
+
+// set-governance.js — Applies a governance policy to an environment or to a
+// single portal, then polls the matching status endpoint until terminal.
+//
+// Request shape (per Power Apps Core Services Gateway appsettings.json):
+// Body: [
+// { policyName: "<policy>",
+// policyValue: "All" | "None" | "Include" | "Exclude",
+// ToBeAdded: [ "<portalId>", ... ],
+// ToBeRemoved: [ "<portalId>", ... ] }
+// ]
+//
+// Semantics (per Power Apps gateway contract):
+// - "All" apply to every portal in the env
+// - "None" apply to no portals (clears any inclusion / exclusion list)
+// - "Include" apply ONLY to portals listed in ToBeAdded (allow-list)
+// - "Exclude" apply to every portal EXCEPT those in ToBeAdded (block-list)
+//
+// Transport: gateway only — POST /governance (env id implied by base URL).
+//
+// Defaults this script encodes when --policyValue is not passed explicitly:
+// --portalId omitted → policyValue="All", ToBeAdded=[] (env-wide).
+// --portalId given → policyValue="Include", ToBeAdded=[portalId] (allow-list).
+// Override with --policyValue to pick any of All|None|Include|Exclude.
+
+const {
+ pollUntil,
+ parseCliArgs,
+ parseTimeoutMs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+const { SUPPORTED_POLICIES, assertPolicy, classifyStatus, toWritePolicyValue, normalizeEnvValue } = require('./policies');
+const { callGovernance } = require('./governance-transport');
+const { resolveGovernanceContext } = require('./governance-context');
+
+const DEFAULT_TIMEOUT_MIN = 15;
+const POLL_INTERVAL_MS = 30_000;
+// How many consecutive transient errors we tolerate inside the poll loop
+// before bailing. 5 × 30s = ~2.5 minutes of "give the server another chance"
+// before the script gives up on the status endpoint.
+const MAX_CONSECUTIVE_POLL_ERRORS = 5;
+const VALID_POLICY_VALUES = ['All', 'None', 'Include', 'Exclude'];
+
+// Builds a useful error message from a callGovernance failure envelope. Never
+// returns the literal string "undefined" — that was the symptom of the original
+// polling bug, where the fallback chain `error?.message || ${statusCode}`
+// would degrade to the string "undefined" when both fields were empty.
+function describeFetchError(r) {
+ const trimmedMsg = (r && r.error && typeof r.error.message === 'string')
+ ? r.error.message.trim()
+ : '';
+ if (trimmedMsg) return trimmedMsg;
+ const code = (r && r.error && r.error.code) ? r.error.code : null;
+ if (r && r.statusCode != null && r.statusCode !== 0) {
+ return code ? `HTTP ${r.statusCode} (${code})` : `HTTP ${r.statusCode}`;
+ }
+ if (code) return code;
+ return 'status endpoint returned an unparseable response';
+}
+
+function failOnAuthError(response, operation) {
+ if (response.error?.code === 'ContextError') {
+ fail(`${operation}: ${describeFetchError(response)}`, 2);
+ }
+ // Authentication/authorization failures cannot be fixed by the poll delay.
+ // Exit here so neither state-based recovery nor a stale final status can
+ // overwrite them. HTTP semantics: https://www.rfc-editor.org/rfc/rfc9110#section-15.5.2
+ if (response.statusCode === 401) {
+ fail(`${operation}: HTTP 401 - ${describeFetchError(response)}. Authentication failed; sign in again for the configured governance ring and rerun the command.`, 2);
+ }
+ if (response.statusCode === 403) {
+ fail(`${operation}: HTTP 403 - ${describeFetchError(response)}. Access denied; check the account's admin role, delegated permissions, and access policies for this environment.`, 1);
+ }
+}
+
+const HELP = `set-governance.js — Applies a governance policy and watches the roll-out.
+
+Usage:
+ node set-governance.js --policy <name> [--portalId <guid>] [--envId <guid>]
+ [--timeoutMinutes <n>]
+
+Flags:
+ --policy Governance policy name. One of:
+ ${SUPPORTED_POLICIES.join('\n ')}
+ --portalId Optional single portal id. Legacy flag.
+ --portalIds Optional comma- or space-separated list of portal ids.
+ Use this for Include / Exclude scopes with multiple
+ portals. When provided, the policy defaults to
+ policyValue="Include" + ToBeAdded=[ids]. When omitted
+ and --portalId is also omitted, defaults to "All".
+ --removePortalIds Optional comma- or space-separated list of portal ids to
+ DROP from an existing Include allow-list / Exclude
+ block-list (populates ToBeRemoved). The gateway treats
+ ToBeAdded as additive, so this is the ONLY way to shrink a
+ list without clearing the whole policy via "None". Combine
+ with --policyValue Include (or Exclude) to keep the mode.
+ --policyValue Optional explicit policy value (overrides the default
+ derived from --portalId). One of: ${VALID_POLICY_VALUES.join(', ')}.
+ Use "None" for a safe round-trip test of the write path.
+ --envId Optional environment id. Falls back to the current PAC env.
+ --timeoutMinutes Maximum wait for terminal status (default: ${DEFAULT_TIMEOUT_MIN}).
+ --help Show this help message.
+
+Exit codes:
+ 0 Roll-out reached a success terminal state
+ 2 Sign-in required
+ 3 Polling timed out before terminal state
+ 4 Terminal state reached but it was Failed
+ 1 Other failure
+
+Stdout (JSON):
+ { "status": "applied", "policy", "envId", "portalId", "transport",
+ "attempts", "finalValue" }
+`;
+
+function buildPolicyPayload(policy, portalIdsArg, policyValueOverride, removePortalIdsArg) {
+ // Accept either a single portalId string (legacy) or an array of ids.
+ let portalIds;
+ if (portalIdsArg == null || portalIdsArg === '') {
+ portalIds = [];
+ } else if (Array.isArray(portalIdsArg)) {
+ portalIds = portalIdsArg.filter(Boolean);
+ } else {
+ portalIds = [portalIdsArg];
+ }
+ // ToBeRemoved is the gateway's REMOVAL delta for an Include/Exclude allow-list.
+ // The gateway treats ToBeAdded as an ADDITIVE delta against the existing list
+ // (NOT a full replace, despite the doc contract's "apply only to portals in
+ // ToBeAdded" wording): re-posting Include with a SHORTER ToBeAdded leaves the
+ // previously-added sites on the list untouched. So the ONLY way to drop a site
+ // from an Include allow-list (or an Exclude block-list) without clearing the
+ // whole policy (None) is to name it here in ToBeRemoved. Observed live on
+ // EnableProtocolOpenIdConnect: Include=[P1,P2] then re-post Include=[P1] ->
+ // env still reads {P1,P2}; Include + ToBeRemoved=[P2] -> env reads {P1}.
+ let removePortalIds;
+ if (removePortalIdsArg == null || removePortalIdsArg === '') {
+ removePortalIds = [];
+ } else if (Array.isArray(removePortalIdsArg)) {
+ removePortalIds = removePortalIdsArg.filter(Boolean);
+ } else {
+ removePortalIds = [removePortalIdsArg];
+ }
+ // Derive the canonical policyValue (All / None / Include / Exclude) first,
+ // then forward-map it to the gateway WRITE vocabulary. As of the 2026-07
+ // A059 shift the wire form IS the short canonical value — the older applyTo
+ // `*Sites` enums ("AllSites"/"IncludeSites"/"ExcludeSites") are now rejected
+ // with HTTP 400 A059 "The provided policy value is not a valid governance
+ // policy value." So the forward-map is currently an identity map; the seam
+ // is retained in case the vocabulary shifts again. See policies.js
+ // toWritePolicyValue / WRITE_VALUE_ALIASES for the WHY and empirical proof.
+ // A removal-only edit (drop a site from the allow-list, keep the mode) passes
+ // no ToBeAdded, so fall back to Include as the mode when only removals are
+ // present — the caller keeps the env in allow-list mode, it just shrinks.
+ const canonicalValue =
+ policyValueOverride ||
+ (portalIds.length > 0 || removePortalIds.length > 0 ? 'Include' : 'All');
+ return [
+ {
+ policyName: policy,
+ policyValue: toWritePolicyValue(canonicalValue, policy),
+ ToBeAdded: portalIds,
+ ToBeRemoved: removePortalIds,
+ },
+ ];
+}
+
+function parsePortalIdsFlag(flagValue) {
+ // Comma- or space-separated list of portal ids.
+ if (!flagValue) return [];
+ return String(flagValue)
+ .split(/[,\s]+/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+}
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ if (!args.policy) {
+ fail('Usage: node set-governance.js --policy <name> [--portalId <guid>] [--envId <guid>]', 1);
+ }
+ assertPolicy(args.policy);
+ const timeoutMs = parseTimeoutMs(args.timeoutMinutes, DEFAULT_TIMEOUT_MIN);
+ const portalIdsFromFlag = parsePortalIdsFlag(args.portalIds);
+ const portalIds = portalIdsFromFlag.length > 0
+ ? portalIdsFromFlag
+ : (args.portalId ? [args.portalId] : []);
+ const removePortalIds = parsePortalIdsFlag(args.removePortalIds);
+ const policyValueOverride = args.policyValue || null;
+ if (policyValueOverride && !VALID_POLICY_VALUES.includes(policyValueOverride)) {
+ fail(`--policyValue must be one of: ${VALID_POLICY_VALUES.join(', ')}`, 1);
+ }
+
+ // Context resolution can spawn the token helper. Reuse this invocation's
+ // environment-scoped context for the POST, polls, and fallback reads rather
+ // than spawning it again for each request. Expired/rejected auth stops below;
+ // this command does not silently reauthenticate or replay a governance POST.
+ const context = resolveGovernanceContext(args.envId);
+ if (context.error) {
+ fail(`Failed to resolve governance context: ${context.error}`, 2);
+ }
+
+ const transportLabel = 'gateway';
+ const scopeLabel = portalIds.length > 0
+ ? `${portalIds.length} portal(s)`
+ : (removePortalIds.length > 0
+ ? `remove ${removePortalIds.length} portal(s)`
+ : `env ${args.envId || '<current>'}`);
+ process.stderr.write(
+ `Applying ${args.policy} to ${scopeLabel} via ${transportLabel}...\n`
+ );
+
+ const body = buildPolicyPayload(args.policy, portalIds, policyValueOverride, removePortalIds);
+ // The canonical scope (All/None/Include/Exclude) we are asking the gateway to
+ // set — mirrors the derivation inside buildPolicyPayload. Used below to verify
+ // the write against the ACTUAL env state, not the (possibly stale) status
+ // endpoint.
+ const requestedCanonical =
+ policyValueOverride ||
+ (portalIds.length > 0 || removePortalIds.length > 0 ? 'Include' : 'All');
+ const start = await callGovernance({
+ context,
+ op: 'apply',
+ envId: args.envId,
+ policy: args.policy,
+ portalId: portalIds[0] || null,
+ body,
+ });
+ failOnAuthError(start, 'POST governance failed');
+ // Existing scope is not evidence that this POST succeeded: an Include
+ // membership edit may be rejected while the environment remains Include.
+ // Never let state-based recovery override a definite HTTP error response.
+ if (start.statusCode >= 400 && start.statusCode <= 599) {
+ fail(`POST governance failed (HTTP ${start.statusCode}): ${describeFetchError(start)}`, 1);
+ }
+
+ // Preserve the existing fallback for an uncertain/unexpected response.
+ // This compares only environment scope, not membership additions/removals;
+ // full uncertain-delivery verification is separate from rejecting HTTP errors.
+ if (start.statusCode !== 200 && start.statusCode !== 202 && start.statusCode !== 204) {
+ // Live-state reality check: does the env now reflect the scope we asked for?
+ const envCheck = await callGovernance({
+ context,
+ op: 'getEnv',
+ envId: args.envId,
+ policy: args.policy,
+ });
+ failOnAuthError(envCheck, 'Governance recovery read failed');
+ const envValue = envCheck.ok ? normalizeEnvValue(envCheck.body) : null;
+ if (envValue && envValue === requestedCanonical) {
+ // POST landed (env reflects the requested scope) even though our parsing
+ // of the POST response was off — log and continue to the polling loop.
+ process.stderr.write(
+ ` POST response was unparseable (${describeFetchError(start)}); env now reports "${envValue}" (matches request) — continuing to poll.\n`
+ );
+ } else {
+ const observed = envValue ? `env still reports "${envValue}"` : 'live state unreadable';
+ fail(`POST governance failed (${start.statusCode != null ? start.statusCode : 'no response'}): ${describeFetchError(start)} — ${observed}, expected "${requestedCanonical}".`, 1);
+ }
+ }
+
+ let finalValue = '';
+ let consecutiveErrors = 0;
+ let lastErrorMessage = '';
+ const poll = await pollUntil({
+ fetchStatus: async () => {
+ const r = await callGovernance({
+ context,
+ op: 'getStatus',
+ envId: args.envId,
+ policy: args.policy,
+ });
+ failOnAuthError(r, 'Governance status poll failed');
+ if (!r.ok) {
+ // Transient failure on the status endpoint — retry on the next tick
+ // unless we've hit the consecutive-error ceiling. Reports each retry
+ // to stderr so the orchestrator sees what's happening.
+ consecutiveErrors += 1;
+ lastErrorMessage = describeFetchError(r);
+ if (consecutiveErrors >= MAX_CONSECUTIVE_POLL_ERRORS) {
+ return { ok: false, error: lastErrorMessage };
+ }
+ process.stderr.write(
+ ` status poll ${consecutiveErrors}/${MAX_CONSECUTIVE_POLL_ERRORS} transient error: ${lastErrorMessage}; retrying...\n`
+ );
+ return { ok: true, body: 'in-progress' };
+ }
+ consecutiveErrors = 0;
+ const raw = r.body;
+ const value =
+ typeof raw === 'string'
+ ? raw
+ : raw?.status ?? raw?.state ?? raw?.value ?? '';
+ finalValue = String(value);
+ const cls = classifyStatus(finalValue);
+ if (cls === 'failure') {
+ return { ok: false, error: `roll-out reached terminal state "${finalValue}"` };
+ }
+ return { ok: true, body: cls };
+ },
+ isDone: (cls) => cls === 'success',
+ timeoutMs,
+ intervalMs: POLL_INTERVAL_MS,
+ });
+
+ // If the poll loop bailed without seeing a terminal success state, give the
+ // status endpoint one last chance — sometimes the rollout actually completed
+ // while we were in the middle of a transient outage. This is the safety net
+ // that turns "Polling failed" false negatives into successful exits when the
+ // real state has already flipped.
+ if (!poll.ok) {
+ const finalCheck = await callGovernance({
+ context,
+ op: 'getStatus',
+ envId: args.envId,
+ policy: args.policy,
+ });
+ failOnAuthError(finalCheck, 'Final governance status read failed');
+ if (finalCheck.ok) {
+ const raw = finalCheck.body;
+ const value =
+ typeof raw === 'string'
+ ? raw
+ : raw?.status ?? raw?.state ?? raw?.value ?? '';
+ finalValue = String(value);
+ const cls = classifyStatus(finalValue);
+ if (cls === 'success') {
+ poll.ok = true;
+ poll.body = cls;
+ } else if (cls === 'failure') {
+ // Fall through to the failure-terminal-state branch below.
+ }
+ }
+ }
+
+ if (!poll.ok && poll.error === 'timeout') {
+ fail(`Roll-out did not reach a success state before timeout. Last seen: "${finalValue}".`, 3);
+ }
+ if (!poll.ok && classifyStatus(finalValue) === 'failure') {
+ fail(`Roll-out reported a failure terminal state ("${finalValue}").`, 4);
+ }
+ if (!poll.ok) {
+ const msg = poll.error || lastErrorMessage || 'status endpoint unavailable';
+ fail(`Polling failed: ${msg}`, 1);
+ }
+
+ process.stdout.write(
+ JSON.stringify(
+ {
+ status: 'applied',
+ policy: args.policy,
+ envId: args.envId,
+ portalIds,
+ transport: start.transport,
+ attempts: poll.attempts,
+ finalValue,
+ },
+ null,
+ 2
+ ) + '\n'
+ );
+}
+
+module.exports = { buildPolicyPayload, parsePortalIdsFlag };
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-governance/scripts/table.js b/plugins/power-pages/skills/manage-governance/scripts/table.js
new file mode 100644
index 000000000..a0c2c5066
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/table.js
@@ -0,0 +1,58 @@
+#!/usr/bin/env node
+
+// table.js — Shared fixed-width and Markdown table primitives used by the render-*
+// scripts (render-env-table.js, render-portal-table.js). These two helpers were
+// previously copy-pasted verbatim into each renderer; keeping one definition
+// avoids the two drifting apart (a padding/border off-by-one in one but not the
+// other would silently misalign only some tables).
+//
+// The fixed-width helpers assume ASCII / single-width cells. ANSI color escapes
+// are zero-width, so callers must compute widths on the *visible* (uncolored)
+// text and apply color AFTER padding — see render-portal-table.js.
+
+// Right-pad an ASCII string to a fixed visible width. Null/undefined render as
+// empty; never truncates (a cell wider than `width` is returned unchanged, so
+// the border math in `border()` still lines up because widths are derived from
+// the same cell values).
+function pad(str, width) {
+ const s = String(str == null ? '' : str);
+ return s + ' '.repeat(Math.max(0, width - s.length));
+}
+
+// Build one horizontal border line from the per-column visible widths. `fill`
+// is the run character (default '-' for the ASCII '+---+' frame; pass '─' for
+// the Unicode box). Each column is padded by +2 to match the single space of
+// left/right cell padding the row renderers add around every value.
+function border(widths, left, mid, right, fill) {
+ const f = fill || '-';
+ return left + widths.map((w) => f.repeat(w + 2)).join(mid) + right;
+}
+
+// GFM rows cannot span physical lines, and a literal pipe starts another
+// column. For example, "A|B\r\nPreview" must become "A\\|B Preview".
+function markdownCell(value) {
+ return String(value == null ? '' : value)
+ .replace(/\r\n|[\r\n\u2028\u2029]/g, ' ')
+ .replace(/\|/g, '\\|');
+}
+
+// Names in prose must remain a single literal line, e.g. "*Site*\n[link](url)".
+// Escape HTML entities as well as Markdown syntax so neither can introduce markup.
+function markdownText(value) {
+ return String(value == null ? '' : value)
+ .replace(/\r\n|[\r\n\u2028\u2029]/g, ' ')
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
+ .replace(/&/g, '&amp;')
+ .replace(/[\\`*_{}\[\]()<>#!|~]/g, '\\$&');
+}
+
+function renderMarkdownTable(headers, rows) {
+ const row = (cells) => '| ' + cells.map(markdownCell).join(' | ') + ' |';
+ return [
+ row(headers),
+ row(headers.map(() => '---')),
+ ...rows.map(row),
+ ].join('\n');
+}
+
+module.exports = { pad, border, renderMarkdownTable, markdownText };
diff --git a/plugins/power-pages/skills/manage-governance/scripts/tip-auth.js b/plugins/power-pages/skills/manage-governance/scripts/tip-auth.js
new file mode 100644
index 000000000..258fc18af
--- /dev/null
+++ b/plugins/power-pages/skills/manage-governance/scripts/tip-auth.js
@@ -0,0 +1,271 @@
+#!/usr/bin/env node
+
+// tip-auth.js — Acquires a DELEGATED Power Platform API access token for the
+// TIP/Preprod ring using a CUSTOM public-client app via the OAuth 2.0
+// device-code flow, with silent refresh-token renewal between runs.
+//
+// WHY this exists (and why we can't just use `az account get-access-token`):
+// The governance gateway requires the delegated scopes
+// `PowerPages.Websites.Read` / `PowerPages.Websites.Write`. The Azure CLI
+// first-party client (04b07795-8ddb-461a-bbee-02f9e1bf7b46) is NOT preauthorized
+// for those scopes and CANNOT be granted them (it's Microsoft-owned; the API
+// owner controls preauthorization), so an az-minted token 403s with
+// InsufficientDelegatedPermissions. A tenant-registered public-client app CAN
+// hold those delegated scopes, but az can't mint for an arbitrary client id —
+// hence this standalone device-code implementation.
+//
+// Device-code flow reference:
+// https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-device-code
+//
+// Output contract: prints ONLY the access token to stdout (so callers can
+// `execSync` and capture it verbatim); all human-facing prompts go to stderr.
+//
+// Config (all from env, so the skill stays generic — no app id is hard-coded):
+// PP_GOV_TIP_CLIENT_ID (required) public-client app id with the PP scopes
+// PP_GOV_TIP_TENANT (required) tenant id (or 'organizations'/'common')
+// PP_GOV_TIP_HOST (optional) gateway host; default api.preprod...
+
+'use strict';
+
+const https = require('https');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { URLSearchParams } = require('url');
+
+const AUTHORITY = 'https://login.microsoftonline.com';
+const DEFAULT_TIP_HOST = 'https://api.preprod.powerplatform.com';
+// Default public-client app id for the TIP device-code flow: "pp-governance-cli"
+// (registered with delegated PowerPages.Websites.Read/Write on the Preprod Power
+// Platform API resource). A client id is a PUBLIC identifier, not a secret, so it
+// is safe to ship as a default — the flow still requires an interactive user
+// sign-in, and no client secret is involved. Override with PP_GOV_TIP_CLIENT_ID
+// to point at a different registration.
+const DEFAULT_TIP_CLIENT_ID = 'c5ae9f06-f0bb-4ef6-9ee4-c7a3803da37a';
+// Default authority tenant. `organizations` lets any work/school account complete
+// the sign-in (the app is single-tenant, so AAD still scopes consent to the
+// registering tenant). Override with PP_GOV_TIP_TENANT to pin a specific tenant.
+const DEFAULT_TIP_TENANT = 'organizations';
+// Refresh when the cached token is within this many seconds of expiry so a
+// long-running set-governance poll never dies mid-flight on an expired bearer.
+const EXPIRY_SKEW_SECONDS = 300;
+
+// Delegated scopes the governance gateway demands. offline_access asks AAD for a
+// refresh token so subsequent runs renew silently without another browser
+// sign-in. Scopes are resource-qualified (host + '/' + scope) per the v2
+// endpoint contract, e.g. `https://api.preprod.powerplatform.com/PowerPages.Websites.Read`.
+function buildScope(host) {
+ const h = String(host || '').replace(/\/+$/, '');
+ return `${h}/PowerPages.Websites.Read ${h}/PowerPages.Websites.Write offline_access`;
+}
+
+function resolveTipConfig(env) {
+ const e = env || process.env;
+ // Client id and tenant default to the shipped pp-governance-cli app and the
+ // `organizations` authority, so the TIP flow works out-of-the-box with no
+ // env vars. Both remain overridable for a different app/tenant.
+ const clientId = (e.PP_GOV_TIP_CLIENT_ID || '').trim() || DEFAULT_TIP_CLIENT_ID;
+ const tenantId = (e.PP_GOV_TIP_TENANT || '').trim() || DEFAULT_TIP_TENANT;
+ const host = (e.PP_GOV_TIP_HOST || DEFAULT_TIP_HOST).trim().replace(/\/+$/, '');
+ return { clientId, tenantId, host };
+}
+
+// Decode the `exp` (seconds since epoch) from a JWT WITHOUT verifying the
+// signature — we only need the expiry to decide whether to reuse the cache.
+// A JWT is header.payload.signature; the payload is the middle base64url
+// segment. base64url uses '-'/'_' instead of '+'/'/' and drops '=' padding, so
+// restore both before decoding. Example payload JSON: {"aud":"...","exp":1790000000,...}
+function decodeJwtExp(token) {
+ if (!token || typeof token !== 'string') return null;
+ const parts = token.split('.');
+ if (parts.length < 2) return null;
+ let p = parts[1].replace(/-/g, '+').replace(/_/g, '/');
+ while (p.length % 4) p += '=';
+ try {
+ const claims = JSON.parse(Buffer.from(p, 'base64').toString('utf8'));
+ return typeof claims.exp === 'number' ? claims.exp : null;
+ } catch {
+ return null;
+ }
+}
+
+function isTokenFresh(token, skewSeconds = EXPIRY_SKEW_SECONDS) {
+ const exp = decodeJwtExp(token);
+ if (!exp) return false;
+ return exp > Math.floor(Date.now() / 1000) + skewSeconds;
+}
+
+// Single cache file in the OS temp dir. The filename is fixed but the contents
+// are validated against clientId+host on read, so switching app/ring forces a
+// fresh sign-in rather than replaying a token minted for the wrong app/audience.
+function cachePath() {
+ return path.join(os.tmpdir(), 'pp-gov-tip-token.json');
+}
+
+function readCache() {
+ try {
+ return JSON.parse(fs.readFileSync(cachePath(), 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function writeCache(obj) {
+ try {
+ // mode 0o600: the file holds a refresh token (a long-lived credential), so
+ // restrict it to the owner. Best-effort — a failure to persist must not
+ // break auth, it just means the next run re-prompts.
+ fs.writeFileSync(cachePath(), JSON.stringify(obj), { mode: 0o600 });
+ } catch {
+ /* ignore — cache is an optimization, not a requirement */
+ }
+}
+
+function postForm(url, form) {
+ const body = new URLSearchParams(form).toString();
+ return new Promise((resolve, reject) => {
+ const req = https.request(
+ url,
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'Content-Length': Buffer.byteLength(body),
+ },
+ },
+ (res) => {
+ let data = '';
+ res.on('data', (c) => (data += c));
+ res.on('end', () => {
+ let parsed = null;
+ try {
+ parsed = JSON.parse(data);
+ } catch {
+ /* non-JSON error body — leave parsed null, raw carries the text */
+ }
+ resolve({ statusCode: res.statusCode, body: parsed, raw: data });
+ });
+ }
+ );
+ req.on('error', reject);
+ req.write(body);
+ req.end();
+ });
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// Exchange a stored refresh token for a new access token. AAD ROTATES refresh
+// tokens on redemption, so the caller must persist the returned refresh_token.
+async function tryRefresh(cfg, refreshToken) {
+ const res = await postForm(`${AUTHORITY}/${cfg.tenantId}/oauth2/v2.0/token`, {
+ grant_type: 'refresh_token',
+ client_id: cfg.clientId,
+ refresh_token: refreshToken,
+ scope: buildScope(cfg.host),
+ });
+ if (res.statusCode === 200 && res.body && res.body.access_token) return res.body;
+ return null;
+}
+
+// Full interactive device-code flow: request a code, print the prompt, then
+// poll the token endpoint until the user completes the browser sign-in.
+async function deviceCode(cfg) {
+ const dc = await postForm(`${AUTHORITY}/${cfg.tenantId}/oauth2/v2.0/devicecode`, {
+ client_id: cfg.clientId,
+ scope: buildScope(cfg.host),
+ });
+ if (dc.statusCode !== 200 || !dc.body || !dc.body.device_code) {
+ throw new Error(`Device code request failed: ${dc.raw}`);
+ }
+ // The prompt MUST go to stderr — stdout is reserved for the token so the
+ // parent process can capture it cleanly.
+ process.stderr.write(`\n${dc.body.message}\n\n`);
+ const deadline = Date.now() + Number(dc.body.expires_in) * 1000;
+ let interval = Number(dc.body.interval || 5);
+ while (Date.now() < deadline) {
+ await sleep(interval * 1000);
+ const res = await postForm(`${AUTHORITY}/${cfg.tenantId}/oauth2/v2.0/token`, {
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
+ client_id: cfg.clientId,
+ device_code: dc.body.device_code,
+ });
+ if (res.statusCode === 200 && res.body && res.body.access_token) return res.body;
+ const err = res.body && res.body.error;
+ // Per the device-code spec, authorization_pending = keep polling, and
+ // slow_down = AAD asks us to add 5s to the interval. Anything else
+ // (expired_token, access_denied, ...) is terminal.
+ if (err === 'authorization_pending') continue;
+ if (err === 'slow_down') {
+ interval += 5;
+ continue;
+ }
+ throw new Error(`Device-code auth failed: ${err || res.raw}`);
+ }
+ throw new Error('Timed out waiting for device-code sign-in.');
+}
+
+// Acquire a token, cheapest path first: (1) reuse a fresh cached access token,
+// (2) silent refresh, (3) interactive device-code. Steps 1–2 require the cache
+// to match the requested clientId+host.
+async function getTipToken(env) {
+ const cfg = resolveTipConfig(env);
+ if (cfg.error) throw new Error(cfg.error);
+
+ const cache = readCache();
+ const cacheMatchesConfig =
+ cache && cache.clientId === cfg.clientId && cache.host === cfg.host;
+
+ if (cacheMatchesConfig && isTokenFresh(cache.accessToken)) {
+ return cache.accessToken;
+ }
+ if (cacheMatchesConfig && cache.refreshToken) {
+ const refreshed = await tryRefresh(cfg, cache.refreshToken);
+ if (refreshed) {
+ writeCache({
+ clientId: cfg.clientId,
+ host: cfg.host,
+ accessToken: refreshed.access_token,
+ refreshToken: refreshed.refresh_token || cache.refreshToken,
+ });
+ return refreshed.access_token;
+ }
+ // Refresh failed (RT expired/revoked — delegated RTs die after ~90d of
+ // inactivity). Fall through to an interactive sign-in.
+ }
+ const tok = await deviceCode(cfg);
+ writeCache({
+ clientId: cfg.clientId,
+ host: cfg.host,
+ accessToken: tok.access_token,
+ refreshToken: tok.refresh_token || null,
+ });
+ return tok.access_token;
+}
+
+async function main() {
+ const token = await getTipToken(process.env);
+ // Contract: ONLY the token on stdout so callers (governance-context.js) can
+ // capture it verbatim via execSync.
+ process.stdout.write(token);
+}
+
+if (require.main === module) {
+ main().catch((e) => {
+ process.stderr.write(`tip-auth: ${e.message}\n`);
+ process.exit(1);
+ });
+}
+
+module.exports = {
+ buildScope,
+ resolveTipConfig,
+ decodeJwtExp,
+ isTokenFresh,
+ cachePath,
+ getTipToken,
+ DEFAULT_TIP_HOST,
+ DEFAULT_TIP_CLIENT_ID,
+ DEFAULT_TIP_TENANT,
+ EXPIRY_SKEW_SECONDS,
+};