A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
[Pages] Add Localization Workflow Telemetry (#540)
Sandeep Satheeshaab121f4ab2e
diff --git a/README.md b/README.mdindex 8af9bdd20..e3f86ed69 100644--- a/README.md+++ b/README.md@@ -364,6 +364,6 @@ Any use of third-party trademarks or logos are subject to those third-party's po## Telemetry-Power Pages, Mobile Apps, Model Apps, and Power Automate ship 1DS telemetry code, but their committed configurations and event schemas differ. All four are enabled and default-on. Power Pages events can include Dataverse organization and Entra tenant GUIDs when PAC is signed in, plus the signed-in user's Entra object ID when PAC exposes it. Mobile Apps excludes those identity fields and records its documented invocation, project-instance, checkpoint, and App Insights selection fields. Model Apps events can include organization and tenant GUIDs but exclude the signed-in user's Entra object ID. Power Automate records the same identity fields as Power Pages from its skill hooks, and its bundled MCP server and CLI additionally record a per-invocation outcome (success or failure), duration, and, on failure, the error's class name and code — never the error message. Power Automate provisions public-cloud ingestion only, so events outside public cloud stay in the local mirror.+Power Pages, Mobile Apps, Model Apps, and Power Automate ship 1DS telemetry code, but their committed configurations and event schemas differ. All four are enabled and default-on. Power Pages events can include Dataverse organization and Entra tenant GUIDs when PAC is signed in, plus the signed-in user's Entra object ID when PAC exposes it. Power Pages also records approved create-site/localization choices, canonical locales, public localization package names and versions, stable validation failure codes, and localization completion data. It never records site names, free-text requirements, paths, prompts, raw errors, evidence URLs, or private-use locale subtags. Mobile Apps excludes those identity fields and records its documented invocation, project-instance, checkpoint, and App Insights selection fields. Model Apps events can include organization and tenant GUIDs but exclude the signed-in user's Entra object ID. Power Automate records the same identity fields as Power Pages from its skill hooks, and its bundled MCP server and CLI additionally record a per-invocation outcome (success or failure), duration, and, on failure, the error's class name and code — never the error message. Power Automate provisions public-cloud ingestion only, so events outside public cloud stay in the local mirror.For an enabled plugin, users opt out of transmission via `/<plugin>:telemetry off` (for example, `/power-pages:telemetry off`), stored in `~/.power-platform-skills/config.json`. The local diagnostic mirror is still written after this transmission-only opt-out. Each adopting plugin also honors `POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` for automation and CI. The environment variable has highest precedence and disables transmission regardless of the saved command choice. See the [shared telemetry guide](shared/telemetry/README.md) for the full field list, current plugin states, geo-routing behavior, kill-switch semantics, and local-mirror behavior.diff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/events.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/events.jsindex 13f35c3ac..f7b2ffc12 100644--- a/plugins/mobile-apps/scripts/lib/telemetry/lib/events.js+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/events.js@@ -114,14 +114,22 @@ function buildEvent(envelopeName, eventName, info, severity) {}function buildSkillStarted(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_started", input, "Info");+}++function buildSkillEvent(envelopeName, eventName, input, severity = "Info") {return buildEvent(envelopeName,- "skill_started",+ eventName,pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),- "Info"+ severity);}+function buildSkillConfigured(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_configured", input, "Info");+}+function buildSkillCompleted(envelopeName, input) {const severity = input && input.outcome === "failure" ? "Error" : "Info";return buildEvent(@@ -134,6 +142,8 @@ function buildSkillCompleted(envelopeName, input) {module.exports = {buildSkillStarted,+ buildSkillEvent,+ buildSkillConfigured,buildSkillCompleted,FIELD_TYPES,pick,diff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.jsindex bf92b8a38..8950e32c5 100644--- a/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.js+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.js@@ -14,7 +14,10 @@ function dataDisclosure(plugin) {" eventInfo.aadObjectId when PAC exposes it, and the SPA framework of the\n" +" Power Pages code site being worked in as eventInfo.framework when detected.\n" +" The framework is one of react, vue, angular, or astro and describes the\n" +- " scaffold only — it is never a site name or path.\n"+ " scaffold only — it is never a site name or path.\n" ++ " Telemetry records usage fields for approved create-site/localization\n" ++ " choices, canonical locales, public package names/versions, stable\n" ++ " validation outcomes, and localization completion.\n": plugin === "model-apps"? " Model Apps excludes the signed-in user's Entra object ID.\n": "";@@ -27,7 +30,8 @@ function dataDisclosure(plugin) {" fields even when transmission is off. A plugin whose committed telemetry\n" +" config has disabled: true is hard-disabled and writes no log.\n" +" Events do not include file paths, prompts, tool inputs, site names,\n" +- " Dataverse URLs, credentials, usernames, or hostnames."+ " free-text requirements, Dataverse URLs, credentials, usernames,\n" ++ " hostnames, private-use locale subtags, evidence URLs, or raw errors.");}diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/events.js b/plugins/model-apps/scripts/lib/telemetry/lib/events.jsindex 13f35c3ac..f7b2ffc12 100644--- a/plugins/model-apps/scripts/lib/telemetry/lib/events.js+++ b/plugins/model-apps/scripts/lib/telemetry/lib/events.js@@ -114,14 +114,22 @@ function buildEvent(envelopeName, eventName, info, severity) {}function buildSkillStarted(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_started", input, "Info");+}++function buildSkillEvent(envelopeName, eventName, input, severity = "Info") {return buildEvent(envelopeName,- "skill_started",+ eventName,pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),- "Info"+ severity);}+function buildSkillConfigured(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_configured", input, "Info");+}+function buildSkillCompleted(envelopeName, input) {const severity = input && input.outcome === "failure" ? "Error" : "Info";return buildEvent(@@ -134,6 +142,8 @@ function buildSkillCompleted(envelopeName, input) {module.exports = {buildSkillStarted,+ buildSkillEvent,+ buildSkillConfigured,buildSkillCompleted,FIELD_TYPES,pick,diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.jsindex bf92b8a38..8950e32c5 100644--- a/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js+++ b/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js@@ -14,7 +14,10 @@ function dataDisclosure(plugin) {" eventInfo.aadObjectId when PAC exposes it, and the SPA framework of the\n" +" Power Pages code site being worked in as eventInfo.framework when detected.\n" +" The framework is one of react, vue, angular, or astro and describes the\n" +- " scaffold only — it is never a site name or path.\n"+ " scaffold only — it is never a site name or path.\n" ++ " Telemetry records usage fields for approved create-site/localization\n" ++ " choices, canonical locales, public package names/versions, stable\n" ++ " validation outcomes, and localization completion.\n": plugin === "model-apps"? " Model Apps excludes the signed-in user's Entra object ID.\n": "";@@ -27,7 +30,8 @@ function dataDisclosure(plugin) {" fields even when transmission is off. A plugin whose committed telemetry\n" +" config has disabled: true is hard-disabled and writes no log.\n" +" Events do not include file paths, prompts, tool inputs, site names,\n" +- " Dataverse URLs, credentials, usernames, or hostnames."+ " free-text requirements, Dataverse URLs, credentials, usernames,\n" ++ " hostnames, private-use locale subtags, evidence URLs, or raw errors.");}diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/events.js b/plugins/power-automate/scripts/lib/telemetry/lib/events.jsindex 13f35c3ac..f7b2ffc12 100644--- a/plugins/power-automate/scripts/lib/telemetry/lib/events.js+++ b/plugins/power-automate/scripts/lib/telemetry/lib/events.js@@ -114,14 +114,22 @@ function buildEvent(envelopeName, eventName, info, severity) {}function buildSkillStarted(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_started", input, "Info");+}++function buildSkillEvent(envelopeName, eventName, input, severity = "Info") {return buildEvent(envelopeName,- "skill_started",+ eventName,pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),- "Info"+ severity);}+function buildSkillConfigured(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_configured", input, "Info");+}+function buildSkillCompleted(envelopeName, input) {const severity = input && input.outcome === "failure" ? "Error" : "Info";return buildEvent(@@ -134,6 +142,8 @@ function buildSkillCompleted(envelopeName, input) {module.exports = {buildSkillStarted,+ buildSkillEvent,+ buildSkillConfigured,buildSkillCompleted,FIELD_TYPES,pick,diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.jsindex bf92b8a38..8950e32c5 100644--- a/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.js+++ b/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.js@@ -14,7 +14,10 @@ function dataDisclosure(plugin) {" eventInfo.aadObjectId when PAC exposes it, and the SPA framework of the\n" +" Power Pages code site being worked in as eventInfo.framework when detected.\n" +" The framework is one of react, vue, angular, or astro and describes the\n" +- " scaffold only — it is never a site name or path.\n"+ " scaffold only — it is never a site name or path.\n" ++ " Telemetry records usage fields for approved create-site/localization\n" ++ " choices, canonical locales, public package names/versions, stable\n" ++ " validation outcomes, and localization completion.\n": plugin === "model-apps"? " Model Apps excludes the signed-in user's Entra object ID.\n": "";@@ -27,7 +30,8 @@ function dataDisclosure(plugin) {" fields even when transmission is off. A plugin whose committed telemetry\n" +" config has disabled: true is hard-disabled and writes no log.\n" +" Events do not include file paths, prompts, tool inputs, site names,\n" +- " Dataverse URLs, credentials, usernames, or hostnames."+ " free-text requirements, Dataverse URLs, credentials, usernames,\n" ++ " hostnames, private-use locale subtags, evidence URLs, or raw errors.");}diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex d5aa17e02..46fa58905 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -52,6 +52,7 @@ scripts/audit-bidirectional-readiness.js ← Audits generated source for deterministic bidirectional blockers and review findingsvalidate-site-integrity.js ← Shared post-modification/deployment localization and bidirectional integrity checkvalidate-i18n-package.js ← Validates npm localization package compatibility, stability, maintenance, mode, docs, and license+ emit-localization-completed-telemetry.js ← Emits add-localization completion only after final workflow verificationcheck-activation-status.js ← Checks if site is already activated (used by deploy-site, activate-site)poll-async-operation.js ← Polls Dataverse asyncoperations until terminal state (used by export-solution, import-solution)encode-solution-file.js ← Base64-encodes a solution zip for OData request bodies (used by import-solution)@@ -222,7 +223,8 @@ Shared utility scripts live at `scripts/` and are referenced by multiple skills- `encode-solution-file.js`: Base64-encodes a solution zip file for use in Dataverse OData request bodies (`ImportSolutionAsync`, `StageSolution`). Args: `--zipPath`. Outputs `{ encoded, fileSizeBytes, fileName }`. Used by `import-solution`.- `parse-deployment-errors.js`: Parses PAC CLI stderr output or OData error JSON into structured findings array. Each finding has `{ patternId, type, severity, message, rawMatch, autoFixAvailable, suggestedFix }`. Reads from `--input`, `--file`, or stdin. Used by `diagnose-deployment`.- `detect-framework.js`: Reports React, Vue, Angular, or Astro evidence for an explicit project root through the shared framework detector. Returns all candidates and does not guess when evidence is ambiguous.-- `validate-i18n-package.js`: Validates an npm localization package/version against the detected framework, selected runtime/static mode, peer range, stable-release requirement, 24-month maintenance window, documented automatic license policy, and documentation metadata. Non-listed, compound, custom, or missing license metadata requires explicit maker confirmation; license confirmation never bypasses other validation failures. Returns stable `failureCodes`. Used by `add-localization`.+- `validate-i18n-package.js`: Validates an npm localization package/version against the detected framework, selected runtime/static mode, peer range, stable-release requirement, 24-month maintenance window, documented automatic license policy, and documentation metadata. Non-listed, compound, custom, or missing license metadata requires explicit maker confirmation; license confirmation never bypasses other validation failures. Returns stable `failureCodes` and emits a privacy-filtered `localization_package_validation` event when the add-localization workflow passes its canonical locale/operation/selection context. Used by `add-localization`.+- `emit-localization-completed-telemetry.js`: Emits privacy-filtered `skill_completed` telemetry from add-localization's final workflow phase or immediately before a known terminal post-configuration failure. Failure calls accept only stable allowlisted classifications and work without a readable manifest; abrupt cancellation or process termination remains unobservable. It is fail-closed and removes correlation state only after a completion event is dispatched.Shared lib modules live at `scripts/lib/` and are imported by other scripts via `require('./validation-helpers')` or sibling requires. Never inline their logic in skill scripts — always require from `scripts/lib/`.@@ -479,11 +481,11 @@ These requirements apply to scripts, hooks, skills, templates, reports, and docu## Telemetry-This plugin ships 1DS telemetry for skill-run and script-run signals. The canonical shared library lives at the repo-root `shared/telemetry/`; `scripts/lib/telemetry/lib` is a physical copy bundled with this plugin so local checkouts and installed plugins do not depend on symlink handling. Zero npm dependencies — nothing to install.+This plugin ships 1DS telemetry for skill starts, approved create-site/localization configuration, localization package validation, and localization completion. The canonical shared library lives at the repo-root `shared/telemetry/`; `scripts/lib/telemetry/lib` is a physical copy bundled with this plugin so local checkouts and installed plugins do not depend on symlink handling. Zero npm dependencies — nothing to install.- **`scripts/lib/telemetry/lib` is copied** from the repo-root `shared/telemetry/lib` — edit `shared/telemetry/lib/` first, then refresh this plugin's copy in the same change. The real files next to the copy are `ikey.json` (this plugin's config) and `resolver.js` (the resolver contract implementation). **Posture:** the committed `ikey.json` ships `disabled: false` — transmission is enabled for power-pages (the tenant-side Kusto stream + annotation for `PagesAIPluginEvent` are provisioned). Set `disabled: true` to hard-off (no POST, no local log) if you need to suppress all telemetry at the source.- **Region routing (Artemis geo + cloud stamp)** lives in `scripts/lib/telemetry/region/` and is wired through `scripts/lib/telemetry/resolver.js`, which implements the resolver contract (`resolve({ event, cfg, cloud, configDir })` / `isProvisioned(cfg)`). The shared dispatcher is routing-agnostic — it auto-discovers `resolver.js` by convention (sibling of `ikey.json`) and calls it; the `region/` implementation is entirely plugin-owned and never referenced by the shared library. model-apps bundles a **verbatim copy** of `region/` (its own `resolver.js` differs); `plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js` fails when the two drift, so apply a `region/` change to both copies in the same PR.-- **Privacy posture:** usage telemetry is **default-on**. When PAC is signed in, events include the Dataverse organization GUID (`orgId`) and Entra tenant GUID (`tenantId`). Power Pages also includes the signed-in user's Entra object ID (`eventInfo.aadObjectId`) when PAC exposes it; otherwise that field is omitted. The local diagnostic mirror retains the same fields. Events do not include file paths, prompts, tool inputs, site names, Dataverse URLs, credentials, usernames, or hostnames. There is no consent prompt in skills. Users opt out via `/power-pages:telemetry off`, which stores a per-plugin choice in `~/.power-platform-skills/config.json` (`telemetry["power-pages"] = "off"`). Opting out stops transmission only; the local diagnostic mirror is still written. Re-enable with `/power-pages:telemetry on`. Automation/CI can disable transmission by setting `POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT=1` (or `true`); this opt-out has the **highest precedence** and overrides both a persisted `/power-pages:telemetry` choice and `/power-pages:telemetry on`.+- **Privacy posture:** usage telemetry is **default-on**. When PAC is signed in, events include the Dataverse organization GUID (`orgId`) and Entra tenant GUID (`tenantId`). Power Pages also includes the signed-in user's Entra object ID (`eventInfo.aadObjectId`) when PAC exposes it; otherwise that field is omitted. In addition to skill/runtime context, Power Pages records approved create-site/localization configuration, canonical locales, public localization package/version choices, stable package-validation failure codes, and localization completion/duration. It never records site names, free-text requirements, paths, prompts, raw errors, evidence URLs, private-use locale subtags, Dataverse URLs, credentials, usernames, or hostnames. There is no consent prompt in skills. Users opt out via `/power-pages:telemetry off`, which stores a per-plugin choice in `~/.power-platform-skills/config.json` (`telemetry["power-pages"] = "off"`). Opting out stops transmission only; the local diagnostic mirror is still written with the same fields. Re-enable with `/power-pages:telemetry on`. Automation/CI can disable transmission by setting `POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT=1` (or `true`); this opt-out has the **highest precedence** — it overrides both a persisted `/power-pages:telemetry` choice and `/power-pages:telemetry on`. Transmission-only suppression still retains the local mirror.- **Strict allowlist:** `shared/telemetry/lib/events.js` enforces exactly the fields listed in the spec. Never add a field to a builder without first adding it to the allowlist and documenting it in the design doc.- **Fail closed:** telemetry code must never change a script's exit code or break a skill run. Emission is fire-and-forget via a detached dispatcher child, so the hook or script returns before the HTTPS POST completes.- **Site framework in `eventInfo`:** both emission points attach the SPA framework of the site under work (`react` / `vue` / `angular` / `astro`) to the existing `eventInfo` dynamic column. Detection lives in `scripts/lib/detect-site-framework.js`: it walks up to the nearest Power Pages project boundary, then scans **one level of children** when cwd itself is not a site, and reads **declared** deps from `package.json`. A code-site marker is trusted only when `powerpages.config.json` is a regular file containing a JSON object; malformed or directory-shaped markers stop attribution. The child scan is load-bearing: `create-site`'s recommended layout puts the site in a *child* of the host cwd, and the skill's `cd` runs in a Bash subshell that never moves it. Unlike `findPath`, the scan counts both code (`powerpages.config.json`) and declarative (`.powerpages-site/`) children and returns a code site only when exactly one total site matches; hooks do not identify which child a skill will target, so mixed or multi-site workspaces must emit no framework rather than whichever directory the filesystem enumerates first. A nearer declarative root likewise stops the upward walk so an enclosing code site's framework is not misattributed. Framework fingerprints require non-empty string versions for scaffold tooling (`@vitejs/plugin-react`, `@vitejs/plugin-vue`, `@angular/core`, `astro`) rather than merely checking that a key exists; Astro wins because it legitimately hosts other framework integrations, while conflicting non-Astro markers report `null`. It never throws and returns `null` for malformed markers, invalid dependency values, non-Pages directories, ambiguous workspaces, declarative-only roots, and unrecognized stacks — the key is then omitted. `create-site`'s own run reports no framework (the project doesn't exist yet); it appears on subsequent skill runs.diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex 9df3957e6..2521bb521 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -479,6 +479,7 @@ Enables, disables, or checks the status of usage telemetry. Per-user and per-plu- `/power-pages:telemetry off` — stop sending telemetry (nothing leaves your machine)- `/power-pages:telemetry on` — resume sending telemetry- When PAC is signed in, events include organization and tenant IDs; they can also include the signed-in user's Entra object ID when PAC exposes it+- Records approved create-site/localization choices, canonical locales, public package names/versions, and stable validation outcomes; never records site names, prompts, paths, free-text requirements, credentials, private-use locale subtags, or raw errors- Automation/CI: set `POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT=1` to disable (highest precedence — overrides any saved choice)## Agents@@ -588,7 +589,8 @@ This plugin sends usage telemetry by default to help Microsoft improve it.Events include skill name, plugin/PAC/agent versions, OS/Node versions, session and correlation IDs, and, when PAC is signed in, the Dataverse organization GUID and Entra tenant GUID.When PAC exposes the signed-in user's Entra object ID, Power Pages stores it under `eventInfo.aadObjectId`; otherwise that field is omitted.When you are working in a Power Pages code site, the site's SPA framework (`react`, `vue`, `angular`, or `astro`) is recorded under `eventInfo.framework`; that field is omitted otherwise. It names the scaffold only, never your site or its location.-Events do not include file paths, prompts, tool inputs, site names, Dataverse URLs, credentials, usernames, or hostnames.+It also records approved create-site and localization choices, canonical locales, public localization package/version choices, stable validation failure codes, and localization completion data.+Events do not include file paths, prompts, tool inputs, site names, free-text requirements, Dataverse URLs, credentials, usernames, hostnames, private-use locale subtags, evidence URLs, or raw errors.**Turn it on or off (per-user, applies to every project):**diff --git a/plugins/power-pages/hooks/run-skill-posttool-validation.js b/plugins/power-pages/hooks/run-skill-posttool-validation.jsindex 012acab6a..e435b4d02 100644--- a/plugins/power-pages/hooks/run-skill-posttool-validation.js+++ b/plugins/power-pages/hooks/run-skill-posttool-validation.js@@ -31,6 +31,7 @@ process.stdin.on('end', () => {let validatorStatus = 0;let skillName = null;let input = null;+ let cwd = process.cwd();try {input = JSON.parse(inputData);@@ -40,7 +41,7 @@ process.stdin.on('end', () => {process.exit(0);}- const cwd = input.cwd || process.cwd();+ cwd = input.cwd || process.cwd();const validatorScript = getValidatorScript(skillName);if (validatorScript) {diff --git a/plugins/power-pages/hooks/run-skill-pretool-telemetry.js b/plugins/power-pages/hooks/run-skill-pretool-telemetry.jsindex 07cf25655..0ef3d1101 100644--- a/plugins/power-pages/hooks/run-skill-pretool-telemetry.js+++ b/plugins/power-pages/hooks/run-skill-pretool-telemetry.js@@ -9,7 +9,7 @@ const crypto = require("node:crypto");const PLUGIN_ROOT = path.resolve(__dirname, "..");const TELEMETRY_DIR = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry");-let emitSpawn, eventsLib, sessionLib, pacAuthLib, agentInfoLib, resolverLoader;+let emitSpawn, eventsLib, sessionLib, pacAuthLib, agentInfoLib, resolverLoader, invocationState;try {emitSpawn = require(path.join(TELEMETRY_DIR, "lib", "emit-spawn"));eventsLib = require(path.join(TELEMETRY_DIR, "lib", "events"));@@ -17,6 +17,7 @@ try {pacAuthLib = require(path.join(TELEMETRY_DIR, "lib", "pac-auth"));agentInfoLib = require(path.join(TELEMETRY_DIR, "lib", "agent-info"));resolverLoader = require(path.join(TELEMETRY_DIR, "lib", "resolver-loader"));+ invocationState = require(path.join(TELEMETRY_DIR, "invocation-state"));} catch {process.exit(0);}@@ -122,6 +123,23 @@ function readStdin() {}if (!provisioned) process.exit(0);+ const resolvedSessionId = sessionLib.getSessionId(+ sessionLib.resolveHostSessionId(parsed)+ );+ // The skill resolves its actual project root after this hook runs. Record a+ // path-free pending start now; the first project-aware telemetry call binds+ // it only when that pending invocation is unambiguous.+ if (skillName === "create-site" || skillName === "add-localization") {+ try {+ invocationState.recordPendingStart(+ skillName,+ resolvedSessionId+ );+ } catch {+ // Correlation state is best-effort and must never block the skill start.+ }+ }+const correlation_id = crypto.randomUUID();const configDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";@@ -164,7 +182,7 @@ function readStdin() {const fields = {pluginName: "power-pages",pluginVersion: readPluginVersion(),- sessionId: sessionLib.getSessionId(sessionLib.resolveHostSessionId(parsed)),+ sessionId: resolvedSessionId,correlationId: correlation_id,osName: osFriendlyName(process.platform),osVersion: os.release(),diff --git a/plugins/power-pages/scripts/emit-create-site-template-outcome.js b/plugins/power-pages/scripts/emit-create-site-template-outcome.jsindex 53de6bdb7..e8abeb18c 100644--- a/plugins/power-pages/scripts/emit-create-site-template-outcome.js+++ b/plugins/power-pages/scripts/emit-create-site-template-outcome.js@@ -1,7 +1,13 @@#!/usr/bin/env node'use strict';-const { emitTemplateOutcome } = require('./lib/create-site-template-telemetry');+let emitTemplateOutcome = null;+try {+ ({ emitTemplateOutcome } = require('./lib/create-site-template-telemetry'));+} catch {+ // Template telemetry is optional and must never affect the create-site flow.+}+const { formatJsonResult } = require('./lib/template-cli-args');// Accepted argv shape:@@ -24,6 +30,7 @@ function parseArgs(argv) {}function run(argv = process.argv.slice(2)) {+ if (!emitTemplateOutcome) return null;const args = parseArgs(argv);return emitTemplateOutcome(args);}@@ -35,7 +42,9 @@ function toCliResult(result) {}if (require.main === module) {- process.stdout.write(formatJsonResult(toCliResult(run())));+ if (formatJsonResult) {+ process.stdout.write(formatJsonResult(toCliResult(run())));+ }}module.exports = { parseArgs, run, toCliResult };diff --git a/plugins/power-pages/scripts/emit-localization-completed-telemetry.js b/plugins/power-pages/scripts/emit-localization-completed-telemetry.jsnew file mode 100644index 000000000..05249a07f--- /dev/null+++ b/plugins/power-pages/scripts/emit-localization-completed-telemetry.js@@ -0,0 +1,85 @@+#!/usr/bin/env node+"use strict";++const fs = require("node:fs");+const path = require("node:path");++let telemetry = null;+try {+ telemetry = require("./lib/telemetry/power-pages-telemetry");+} catch {+ // Completion telemetry must never affect the completed localization workflow.+}++function parseArgs(argv) {+ const args = {};+ for (let index = 0; index < argv.length; index += 1) {+ const key = argv[index];+ if (!key.startsWith("--")) continue;+ args[key.slice(2)] = argv[index + 1];+ index += 1;+ }+ return args;+}++function main() {+ if (!telemetry) return;+ const args = parseArgs(process.argv.slice(2));+ if (typeof args.projectRoot !== "string" || !args.projectRoot.trim()) return;+ const projectRoot = path.resolve(args.projectRoot);+ const outcome = String(args.outcome || "success").trim().toLowerCase();+ const validationOutcome = String(+ args.validationOutcome || (outcome === "failure" ? "failed" : "passed")+ ).trim().toLowerCase();+ if (!new Set(["success", "failure"]).has(outcome)) return;+ if (!new Set(["passed", "failed"]).has(validationOutcome)) return;+ if (+ outcome === "failure" &&+ !telemetry.LOCALIZATION_COMPLETION_ERROR_CLASSES.has(args.errorClass)+ ) {+ return;+ }+ let manifest = null;+ try {+ manifest = JSON.parse(+ fs.readFileSync(+ path.join(projectRoot, ".powerpages-localization.json"),+ "utf8"+ )+ );+ } catch {+ if (outcome === "success") return;+ }+ const readiness = manifest?.bidirectionalReadiness?.status;+ telemetry.emitLocalizationCompleted(projectRoot, {+ sessionId: "",+ outcome,+ errorClass: outcome === "failure" ? args.errorClass : undefined,+ eventInfo: telemetry.buildLocalizationCompletionEventInfo({+ validationOutcome,+ bidirectionalReadiness:+ typeof readiness === "string"+ ? readiness+ : manifest+ ? "not-required"+ : undefined,+ unavailableLocaleCount: Array.isArray(manifest?.unavailableLocales)+ ? manifest.unavailableLocales.length+ : undefined,+ configuredLocaleCount: Array.isArray(manifest?.locales)+ ? manifest.locales.length+ : undefined,+ translationMethod:+ manifest?.translationMethod === "agent" ||+ manifest?.translationMethod === "blank"+ ? manifest.translationMethod+ : undefined,+ }),+ });+}++try {+ main();+} catch {+ // Completion telemetry is optional and must remain fail-closed.+}diff --git a/plugins/power-pages/scripts/emit-skill-configured-telemetry.js b/plugins/power-pages/scripts/emit-skill-configured-telemetry.jsnew file mode 100644index 000000000..4fdb66648--- /dev/null+++ b/plugins/power-pages/scripts/emit-skill-configured-telemetry.js@@ -0,0 +1,71 @@+#!/usr/bin/env node+"use strict";++let telemetry = null;+try {+ telemetry = require("./lib/telemetry/power-pages-telemetry");+} catch {+ // Configuration telemetry is optional and must never affect the workflow.+}++function parseArgs(argv) {+ const args = {};+ for (let index = 0; index < argv.length; index += 1) {+ const key = argv[index];+ if (!key.startsWith("--")) continue;+ args[key.slice(2)] = argv[index + 1];+ index += 1;+ }+ return args;+}++function parseBoolean(value) {+ if (String(value).toLowerCase() === "true") return true;+ if (String(value).toLowerCase() === "false") return false;+ return undefined;+}++function main() {+ if (!telemetry) return;+ const args = parseArgs(process.argv.slice(2));+ const skillName = args.skillName;+ if (skillName === "create-site") {+ telemetry.emitSkillConfigured(+ skillName,+ args.projectRoot,+ telemetry.buildCreateSiteEventInfo({+ framework: args.framework,+ siteContentLocale: args.siteContentLocale,+ purpose: args.purpose,+ audience: args.audience,+ choiceSource: args.choiceSource,+ })+ );+ } else if (skillName === "add-localization") {+ telemetry.emitSkillConfigured(+ skillName,+ args.projectRoot,+ telemetry.buildLocalizationEventInfo({+ framework: args.framework,+ operation: args.operation,+ invocationSource: args.invocationSource,+ existingLocalizationDetected: parseBoolean(args.existingLocalizationDetected),+ mode: args.mode,+ defaultLocale: args.defaultLocale,+ addedLocales: args.addedLocales,+ resultingLocales: args.resultingLocales,+ packageName: args.packageName,+ packageVersion: args.packageVersion,+ packageSelection: args.packageSelection,+ packageVerification: args.packageVerification,+ translationMethod: args.translationMethod,+ })+ );+ }+}++try {+ main();+} catch {+ // Configuration telemetry must never change a skill's behavior or exit code.+}diff --git a/plugins/power-pages/scripts/lib/telemetry/invocation-state.js b/plugins/power-pages/scripts/lib/telemetry/invocation-state.jsnew file mode 100644index 000000000..89ba78ed4--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/invocation-state.js@@ -0,0 +1,246 @@+"use strict";++const crypto = require("node:crypto");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++const MAX_AGE_MS = 24 * 60 * 60 * 1000;++function configDir() {+ return (+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR ||+ path.join(os.homedir(), ".power-platform-skills")+ );+}++function safeSkillName(skillName) {+ return String(skillName || "").replace(/[^a-z0-9-]/gi, "_") || "unknown";+}++function projectHash(projectRoot) {+ if (typeof projectRoot !== "string" || !projectRoot.trim()) return "";+ const resolved = path.resolve(projectRoot);+ return crypto+ .createHash("sha256")+ .update(process.platform === "win32" ? resolved.toLowerCase() : resolved)+ .digest("hex");+}++function stateDir(skillName) {+ return path.join(+ configDir(),+ "telemetry",+ "power-pages",+ "invocations",+ safeSkillName(skillName)+ );+}++function stateFile(skillName, state) {+ const invocationKey =+ state.invocationId ||+ `${String(state.startedAt || "nostart")}:${state.projectHash || "pending"}`;+ const invocationHash = crypto+ .createHash("sha256")+ .update(+ `${String(state.sessionId || "nosession")}\0` ++ `${state.projectHash || "pending"}\0${invocationKey}`+ )+ .digest("hex");+ return path.join(stateDir(skillName), `${invocationHash}.json`);+}++function writeState(skillName, state) {+ const { file: previousFile, ...persistedState } = state;+ const hasProjectHash = /^[a-f0-9]{64}$/.test(+ persistedState.projectHash || ""+ );+ const isPending = persistedState.pending === true && !persistedState.projectHash;+ if (!hasProjectHash && !isPending) return null;+ const file = stateFile(skillName, persistedState);+ try {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const tmp = `${file}.tmp.${process.pid}`;+ fs.writeFileSync(tmp, JSON.stringify(persistedState), "utf8");+ fs.renameSync(tmp, file);+ if (previousFile && path.resolve(previousFile) !== path.resolve(file)) {+ try {+ fs.unlinkSync(previousFile);+ } catch {+ // A legacy timing record may already have been removed.+ }+ }+ return file;+ } catch {+ return null;+ }+}++function recordStart(skillName, sessionId, projectRoot, now = Date.now()) {+ if (!skillName || !sessionId) return null;+ const hash = projectHash(projectRoot);+ if (!hash) return null;+ prune(skillName, now);+ return writeState(skillName, {+ invocationId: crypto.randomUUID(),+ sessionId,+ startedAt: now,+ projectHash: hash,+ });+}++function recordPendingStart(skillName, sessionId, now = Date.now()) {+ if (!skillName || !sessionId) return null;+ prune(skillName, now);+ return writeState(skillName, {+ invocationId: crypto.randomUUID(),+ sessionId,+ startedAt: now,+ pending: true,+ });+}++function readStates(skillName, now = Date.now()) {+ let entries;+ try {+ entries = fs.readdirSync(stateDir(skillName), { withFileTypes: true });+ } catch {+ return [];+ }+ const states = [];+ for (const entry of entries) {+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;+ const file = path.join(stateDir(skillName), entry.name);+ try {+ const state = JSON.parse(fs.readFileSync(file, "utf8"));+ if (+ typeof state.sessionId !== "string" ||+ typeof state.startedAt !== "number" ||+ (+ !/^[a-f0-9]{64}$/.test(state.projectHash || "") &&+ !(state.pending === true && !state.projectHash)+ ) ||+ now - state.startedAt > MAX_AGE_MS+ ) {+ continue;+ }+ states.push({ ...state, file });+ } catch {+ // Ignore a partial or malformed best-effort timing record.+ }+ }+ return states.sort((a, b) => b.startedAt - a.startedAt);+}++function findActive(+ skillName,+ projectRoot,+ {+ requireConfigured = false,+ sessionId = "",+ allowLatestFallback = false,+ allowSessionOnly = false,+ } = {}+) {+ const states = readStates(skillName).filter(+ (state) =>+ state.pending !== true &&+ (!requireConfigured || typeof state.configuredAt === "number")+ );+ const hash = projectHash(projectRoot);+ if (sessionId && hash) {+ return states.find(+ (state) =>+ state.sessionId === sessionId &&+ state.projectHash === hash+ ) || null;+ }+ if (sessionId) {+ if (!allowSessionOnly) return null;+ const sessionMatches = states.filter(+ (state) => state.sessionId === sessionId+ );+ return sessionMatches.length === 1 ? sessionMatches[0] : null;+ }+ if (!hash) return null;+ const projectMatches = states.filter((state) => state.projectHash === hash);+ if (projectMatches.length === 1) return projectMatches[0];+ return allowLatestFallback && projectMatches.length === 0 ? states[0] : null;+}++function bindPending(skillName, projectRoot) {+ const hash = projectHash(projectRoot);+ if (!hash) return null;+ const existing = findActive(skillName, projectRoot);+ const pending = readStates(skillName).filter(+ (state) => state.pending === true && !state.projectHash+ );+ if (pending.length === 0) return existing;+ // A bound record plus a pending record could represent overlapping runs on+ // the same project. Refuse to guess which invocation produced this event.+ if (pending.length !== 1 || existing) return null;+ return writeState(skillName, {+ ...pending[0],+ pending: false,+ projectHash: hash,+ })+ ? findActive(skillName, projectRoot)+ : null;+}++function findOrBindActive(skillName, projectRoot) {+ return bindPending(skillName, projectRoot);+}++function markConfigured(skillName, projectRoot, now = Date.now()) {+ const active = findOrBindActive(skillName, projectRoot);+ if (!active) return null;+ return writeState(skillName, { ...active, configuredAt: now });+}++function removeState(state) {+ if (!state || !state.file) return;+ try {+ fs.unlinkSync(state.file);+ } catch {+ // A missing timing record only means duration cannot be correlated again.+ }+}++function prune(skillName, now = Date.now()) {+ let entries;+ try {+ entries = fs.readdirSync(stateDir(skillName), { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;+ const file = path.join(stateDir(skillName), entry.name);+ try {+ const state = JSON.parse(fs.readFileSync(file, "utf8"));+ if (typeof state.startedAt !== "number" || now - state.startedAt > MAX_AGE_MS) {+ fs.unlinkSync(file);+ }+ } catch {+ try {+ fs.unlinkSync(file);+ } catch {+ // Best-effort cleanup only.+ }+ }+ }+}++module.exports = {+ MAX_AGE_MS,+ bindPending,+ findActive,+ findOrBindActive,+ markConfigured,+ projectHash,+ recordPendingStart,+ recordStart,+ removeState,+};diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/events.js b/plugins/power-pages/scripts/lib/telemetry/lib/events.jsindex 13f35c3ac..f7b2ffc12 100644--- a/plugins/power-pages/scripts/lib/telemetry/lib/events.js+++ b/plugins/power-pages/scripts/lib/telemetry/lib/events.js@@ -114,14 +114,22 @@ function buildEvent(envelopeName, eventName, info, severity) {}function buildSkillStarted(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_started", input, "Info");+}++function buildSkillEvent(envelopeName, eventName, input, severity = "Info") {return buildEvent(envelopeName,- "skill_started",+ eventName,pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),- "Info"+ severity);}+function buildSkillConfigured(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_configured", input, "Info");+}+function buildSkillCompleted(envelopeName, input) {const severity = input && input.outcome === "failure" ? "Error" : "Info";return buildEvent(@@ -134,6 +142,8 @@ function buildSkillCompleted(envelopeName, input) {module.exports = {buildSkillStarted,+ buildSkillEvent,+ buildSkillConfigured,buildSkillCompleted,FIELD_TYPES,pick,diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.jsindex bf92b8a38..8950e32c5 100644--- a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js+++ b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js@@ -14,7 +14,10 @@ function dataDisclosure(plugin) {" eventInfo.aadObjectId when PAC exposes it, and the SPA framework of the\n" +" Power Pages code site being worked in as eventInfo.framework when detected.\n" +" The framework is one of react, vue, angular, or astro and describes the\n" +- " scaffold only — it is never a site name or path.\n"+ " scaffold only — it is never a site name or path.\n" ++ " Telemetry records usage fields for approved create-site/localization\n" ++ " choices, canonical locales, public package names/versions, stable\n" ++ " validation outcomes, and localization completion.\n": plugin === "model-apps"? " Model Apps excludes the signed-in user's Entra object ID.\n": "";@@ -27,7 +30,8 @@ function dataDisclosure(plugin) {" fields even when transmission is off. A plugin whose committed telemetry\n" +" config has disabled: true is hard-disabled and writes no log.\n" +" Events do not include file paths, prompts, tool inputs, site names,\n" +- " Dataverse URLs, credentials, usernames, or hostnames."+ " free-text requirements, Dataverse URLs, credentials, usernames,\n" ++ " hostnames, private-use locale subtags, evidence URLs, or raw errors.");}diff --git a/plugins/power-pages/scripts/lib/telemetry/power-pages-telemetry.js b/plugins/power-pages/scripts/lib/telemetry/power-pages-telemetry.jsnew file mode 100644index 000000000..526cc4b13--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/power-pages-telemetry.js@@ -0,0 +1,425 @@+"use strict";++const crypto = require("node:crypto");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++const TELEMETRY_DIR = __dirname;+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..", "..");+const events = require("./lib/events");+const emitSpawn = require("./lib/emit-spawn");+const session = require("./lib/session");+const pacAuth = require("./lib/pac-auth");+const agentInfo = require("./lib/agent-info");+const resolverLoader = require("./lib/resolver-loader");+const invocationState = require("./invocation-state");++const PURPOSES = new Set([+ "company-portal",+ "blog-content",+ "dashboard",+ "landing-page",+ "other",+]);+const FRAMEWORKS = new Set(["react", "vue", "angular", "astro"]);+const LOCALIZATION_OPERATIONS = new Set([+ "create",+ "add-languages",+ "repair",+ "reconfigure",+]);+const LOCALIZATION_MODES = new Set(["runtime", "static"]);+const PACKAGE_SELECTIONS = new Set(["recommended", "alternative", "preserved"]);+const PACKAGE_VERIFICATIONS = new Set(["verified", "unverified", "not-approved"]);+const TRANSLATION_METHODS = new Set(["agent", "blank"]);+const VALIDATION_STATUSES = new Set(["supported", "unsupported", "inconclusive", "error"]);+const READINESS_STATUSES = new Set([+ "ready",+ "approved-with-limitations",+ "pending-remediation",+ "not-required",+]);+const LOCALIZATION_COMPLETION_ERROR_CLASSES = new Set([+ "package-revalidation-failed",+ "localization-validation-failed",+ "localization-build-failed",+ "browser-verification-failed",+ "site-integrity-validation-failed",+ "maker-rejected",+]);+const PACKAGE_FAILURE_CODES = new Set([+ "package-not-resolvable",+ "package-deprecated",+ "prerelease-not-approved",+ "license-not-approved",+ "license-review-required",+ "license-unknown",+ "package-stale",+ "framework-not-supported",+ "framework-peer-incompatible",+ "angular-major-mismatch",+ "documentation-missing",+ "documentation-fetch-failed",+ "mode-unsupported",+ "mode-inconclusive",+ "npm-resolution-failed",+ "package-validation-error",+]);++function enumValue(value, allowed, fallback = undefined) {+ const normalized = String(value || "").trim().toLowerCase();+ return allowed.has(normalized) ? normalized : fallback;+}++function sanitizeLocale(value) {+ const raw = String(value || "").trim();+ if (!raw || /^x-/i.test(raw)) return null;+ const parts = raw.split("-");+ const extensionIndex = parts.findIndex(+ (part, index) => index > 0 && /^[0-9a-z]$/i.test(part)+ );+ const projected = (extensionIndex === -1 ? parts : parts.slice(0, extensionIndex)).join("-");+ try {+ return Intl.getCanonicalLocales(projected)[0] || null;+ } catch {+ return null;+ }+}++function sanitizeLocales(values) {+ const source = Array.isArray(values) ? values : String(values || "").split(",");+ return [...new Set(source.map(sanitizeLocale).filter(Boolean))];+}++function sanitizePackageName(value) {+ const packageName = String(value || "").trim().toLowerCase();+ if (+ packageName.length > 214 ||+ !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(packageName)+ ) {+ return undefined;+ }+ return packageName;+}++function sanitizeVersion(value) {+ const version = String(value || "").trim();+ return /^[a-z0-9][a-z0-9._+-]{0,79}$/i.test(version) ? version : undefined;+}++function normalizePurpose(value) {+ const normalized = String(value || "")+ .trim()+ .toLowerCase()+ .replace(/[\/\s]+/g, "-");+ const aliases = {+ portal: "company-portal",+ "company-portal": "company-portal",+ blog: "blog-content",+ content: "blog-content",+ "blog-content": "blog-content",+ dashboard: "dashboard",+ "landing-page": "landing-page",+ landing: "landing-page",+ };+ return enumValue(aliases[normalized] || "other", PURPOSES, "other");+}++function compactObject(value) {+ return Object.fromEntries(+ Object.entries(value).filter(([, field]) => field !== undefined && field !== null)+ );+}++function buildCreateSiteEventInfo(input) {+ return compactObject({+ configurationType: "create-site",+ framework: enumValue(input.framework, FRAMEWORKS),+ siteContentLocale: sanitizeLocale(input.siteContentLocale),+ purpose: normalizePurpose(input.purpose),+ audience: enumValue(input.audience, new Set(["internal", "external"])),+ choiceSource: enumValue(input.choiceSource, new Set(["prompt", "arguments"])),+ });+}++function buildLocalizationEventInfo(input) {+ return compactObject({+ configurationType: "localization",+ framework: enumValue(input.framework, FRAMEWORKS),+ operation: enumValue(input.operation, LOCALIZATION_OPERATIONS),+ invocationSource: enumValue(input.invocationSource, new Set(["direct", "create-site"])),+ existingLocalizationDetected:+ typeof input.existingLocalizationDetected === "boolean"+ ? input.existingLocalizationDetected+ : undefined,+ mode: enumValue(input.mode, LOCALIZATION_MODES),+ defaultLocale: sanitizeLocale(input.defaultLocale),+ addedLocales: sanitizeLocales(input.addedLocales),+ resultingLocales: sanitizeLocales(input.resultingLocales),+ packageName: sanitizePackageName(input.packageName),+ packageVersion: sanitizeVersion(input.packageVersion),+ packageSelection: enumValue(input.packageSelection, PACKAGE_SELECTIONS),+ packageVerification: enumValue(input.packageVerification, PACKAGE_VERIFICATIONS),+ translationMethod: enumValue(input.translationMethod, TRANSLATION_METHODS),+ });+}++function buildPackageValidationEventInfo(input) {+ return compactObject({+ framework: enumValue(input.framework, FRAMEWORKS),+ operation: enumValue(input.operation, LOCALIZATION_OPERATIONS),+ intendedLocales: sanitizeLocales(input.intendedLocales),+ packageName: sanitizePackageName(input.packageName),+ resolvedVersion: sanitizeVersion(input.resolvedVersion),+ packageSelection: enumValue(input.packageSelection, PACKAGE_SELECTIONS),+ mode: enumValue(input.mode, LOCALIZATION_MODES),+ validationStatus: enumValue(input.validationStatus, VALIDATION_STATUSES, "error"),+ failureCodes: [+ ...new Set(+ (Array.isArray(input.failureCodes) ? input.failureCodes : [])+ .map((code) => String(code || "").trim().toLowerCase())+ .filter((code) => PACKAGE_FAILURE_CODES.has(code))+ ),+ ],+ prerelease: typeof input.prerelease === "boolean" ? input.prerelease : undefined,+ unverifiedOverrideRequested:+ typeof input.unverifiedOverrideRequested === "boolean"+ ? input.unverifiedOverrideRequested+ : undefined,+ });+}++function nonNegativeInteger(value) {+ if (value === undefined || value === null || value === "") return undefined;+ const number = Number(value);+ return Number.isFinite(number) && number >= 0 ? Math.floor(number) : 0;+}++function buildLocalizationCompletionEventInfo(input) {+ return compactObject({+ validationOutcome: enumValue(input.validationOutcome, new Set(["passed", "failed"])),+ bidirectionalReadiness:+ input.bidirectionalReadiness === undefined+ ? undefined+ : enumValue(+ input.bidirectionalReadiness,+ READINESS_STATUSES,+ "not-required"+ ),+ unavailableLocaleCount: nonNegativeInteger(input.unavailableLocaleCount),+ configuredLocaleCount: nonNegativeInteger(input.configuredLocaleCount),+ translationMethod: enumValue(input.translationMethod, TRANSLATION_METHODS),+ });+}++function readPluginVersion() {+ try {+ const manifest = JSON.parse(+ fs.readFileSync(path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"), "utf8")+ );+ return manifest.version || "unknown";+ } catch {+ return "unknown";+ }+}++function readIkey() {+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ const ikeyPath =+ override && override.trim()+ ? override+ : path.join(TELEMETRY_DIR, "ikey.json");+ try {+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));+ return {+ cfg,+ ikeyPath,+ eventStreamName: cfg.event_stream_name || "",+ disabled: cfg.disabled === true,+ };+ } catch {+ return { cfg: null, ikeyPath, eventStreamName: "", disabled: true };+ }+}++function isProvisioned(cfg, ikeyPath) {+ try {+ const resolver = resolverLoader.loadResolver(path.dirname(ikeyPath));+ return resolver && typeof resolver.isProvisioned === "function"+ ? resolver.isProvisioned(cfg)+ : !!(cfg && cfg.instrumentationKey);+ } catch {+ return false;+ }+}++function osFriendlyName(platform) {+ if (platform === "win32") return "Windows";+ if (platform === "darwin") return "Mac";+ if (platform === "linux") return "Linux";+ return platform;+}++function commonFields(skillName, projectRoot, eventInfo, activeOverride) {+ const active =+ activeOverride || invocationState.findOrBindActive(skillName, projectRoot);+ let auth = null;+ let detectedAgent = {};+ try {+ auth = pacAuth.readPacAuth();+ } catch {+ auth = null;+ }+ try {+ detectedAgent = {+ ...agentInfo.readAiAgent(),+ pacCliVersion: agentInfo.readPacCliVersion(),+ };+ } catch {+ detectedAgent = {};+ }+ const mergedEventInfo = {+ ...(eventInfo || {}),+ ...(auth && auth.objectId ? { aadObjectId: auth.objectId } : {}),+ };+ return {+ fields: compactObject({+ pluginName: "power-pages",+ pluginVersion: readPluginVersion(),+ sessionId: session.getSessionId(active && active.sessionId),+ correlationId: crypto.randomUUID(),+ osName: osFriendlyName(process.platform),+ osVersion: os.release(),+ nodeVersion: "v" + String(process.versions.node).split(".")[0],+ skillName,+ orgId: auth && auth.orgId,+ tenantId: auth && auth.tenantId,+ eventInfo: mergedEventInfo,+ aiAgentName: detectedAgent.aiAgentName,+ aiAgentVersion: detectedAgent.aiAgentVersion,+ pacCliVersion: detectedAgent.pacCliVersion,+ }),+ cloud: (auth && auth.cloud) || "",+ active,+ };+}++function emit(+ kind,+ skillName,+ projectRoot,+ eventInfo,+ extraFields = {},+ { active } = {}+) {+ const { cfg, ikeyPath, eventStreamName, disabled } = readIkey();+ if (disabled || !isProvisioned(cfg, ikeyPath)) return false;+ const context = commonFields(skillName, projectRoot, eventInfo, active);+ const builders = {+ configured: events.buildSkillConfigured,+ packageValidation: buildLocalizationPackageValidationEvent,+ completed: events.buildSkillCompleted,+ };+ const builder = builders[kind];+ if (!builder) return false;+ emitSpawn.fireAndForget(+ builder(eventStreamName, { ...context.fields, ...extraFields }),+ {+ cloud: context.cloud,+ configDir: process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "",+ fakeProbe: process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "",+ ikeyJsonPath: ikeyPath,+ }+ );+ return { active: context.active };+}++function buildLocalizationPackageValidationEvent(envelopeName, input) {+ const severity =+ input?.eventInfo?.validationStatus === "supported" ? "Info" : "Error";+ return events.buildSkillEvent(+ envelopeName,+ "localization_package_validation",+ input,+ severity+ );+}++function emitSkillConfigured(skillName, projectRoot, eventInfo) {+ const emitted = emit(+ "configured",+ skillName,+ projectRoot,+ eventInfo+ );+ if (emitted && skillName === "add-localization") {+ invocationState.markConfigured(skillName, projectRoot);+ } else if (emitted?.active && skillName === "create-site") {+ // Configuration is create-site's final correlated event. Remove only the+ // invocation used for this event; other projects and ambiguous starts may+ // belong to concurrent workflows and must remain untouched.+ invocationState.removeState(emitted.active);+ }+ return Boolean(emitted);+}++function emitPackageValidation(projectRoot, eventInfo) {+ return Boolean(+ emit("packageValidation", "add-localization", projectRoot, eventInfo)+ );+}++function emitLocalizationCompleted(projectRoot, input) {+ const outcome = enumValue(+ input.outcome,+ new Set(["success", "failure"])+ );+ const errorClass =+ outcome === "failure"+ ? enumValue(input.errorClass, LOCALIZATION_COMPLETION_ERROR_CLASSES)+ : undefined;+ if (!outcome || (outcome === "failure" && !errorClass)) return false;+ const active = invocationState.findActive(+ "add-localization",+ projectRoot,+ {+ requireConfigured: true,+ sessionId: input.sessionId,+ }+ );+ if (!active) return false;+ const durationMs =+ Number.isFinite(active.startedAt) && Date.now() >= active.startedAt+ ? Date.now() - active.startedAt+ : undefined;+ const emitted = emit(+ "completed",+ "add-localization",+ projectRoot,+ input.eventInfo,+ compactObject({+ outcome,+ durationMs,+ errorClass,+ }),+ { active }+ );+ if (emitted) invocationState.removeState(active);+ return Boolean(emitted);+}++module.exports = {+ LOCALIZATION_COMPLETION_ERROR_CLASSES,+ PACKAGE_FAILURE_CODES,+ buildCreateSiteEventInfo,+ buildLocalizationPackageValidationEvent,+ buildLocalizationCompletionEventInfo,+ buildLocalizationEventInfo,+ buildPackageValidationEventInfo,+ emitLocalizationCompleted,+ emitPackageValidation,+ emitSkillConfigured,+ sanitizeLocale,+ sanitizeLocales,+};diff --git a/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js b/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.jsindex ac1c515a4..8e5c662c7 100644--- a/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js+++ b/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js@@ -2,6 +2,10 @@const test = require('node:test');const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');const { buildTemplateOutcomeEvent, emitTemplateOutcome, normalizeBool, sanitizeTemplateOutcomeInfo } = require('../lib/create-site-template-telemetry');const { parseArgs, toCliResult } = require('../emit-create-site-template-outcome');@@ -206,6 +210,42 @@ test('telemetry CLI output excludes the emitted event and organization identifieassert.deepEqual(toCliResult(null), { ok: false });});+test('template telemetry CLI exits 0 when its optional module cannot load', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ppskills-template-load-'));+ const preload = path.join(tempDir, 'block-template-telemetry-load.js');+ fs.writeFileSync(+ preload,+ [+ "'use strict';",+ "const Module = require('node:module');",+ 'const originalLoad = Module._load;',+ 'Module._load = function (request, parent, isMain) {',+ " if (String(request).includes('create-site-template-telemetry')) {",+ " throw new Error('simulated template telemetry load failure');",+ ' }',+ ' return originalLoad.call(this, request, parent, isMain);',+ '};',+ '',+ ].join('\n'),+ 'utf8'+ );++ const result = spawnSync(+ process.execPath,+ [+ '--require',+ preload,+ path.resolve(__dirname, '../emit-create-site-template-outcome.js'),+ '--eventName',+ 'create_site_from_scratch',+ ],+ { encoding: 'utf8', timeout: 30_000 }+ );++ assert.equal(result.status, 0);+ assert.doesNotMatch(result.stderr, /simulated template telemetry load failure/);+});+test('sanitizeTemplateOutcomeInfo drops invalid dynamic telemetry values', () => {assert.deepEqual(sanitizeTemplateOutcomeInfo({eventName: 'template_used',diff --git a/plugins/power-pages/scripts/tests/emit-localization-completed-telemetry.test.js b/plugins/power-pages/scripts/tests/emit-localization-completed-telemetry.test.jsnew file mode 100644index 000000000..9d6694fab--- /dev/null+++ b/plugins/power-pages/scripts/tests/emit-localization-completed-telemetry.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 path = require("node:path");+const { spawnSync } = require("node:child_process");++const SCRIPT = path.resolve(+ __dirname,+ "../emit-localization-completed-telemetry.js"+);+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");+const invocationState = require("../lib/telemetry/invocation-state");++function sleep(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function waitForFile(filePath, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (!fs.existsSync(filePath) && Date.now() < deadline) sleep(25);+ return fs.existsSync(filePath);+}++function writeProvisionedConfig(configDir) {+ const ikeyPath = path.join(configDir, "ikey.json");+ fs.writeFileSync(+ ikeyPath,+ JSON.stringify({+ event_stream_name: "PagesAIPluginEvent",+ disabled: false,+ default_region: "us",+ regions: {+ us: {+ instrumentation_key: "test-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collector_url: "https://example.invalid/OneCollector/1.0/",+ },+ },+ })+ );+ fs.writeFileSync(+ path.join(configDir, "resolver.js"),+ `module.exports = require(${JSON.stringify(+ path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry", "resolver.js")+ )});\n`+ );+ return ikeyPath;+}++test("emits completion only from the explicit final workflow command", (t) => {+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-completed-"));+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-localized-"));+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);+ fs.writeFileSync(+ path.join(projectRoot, ".powerpages-localization.json"),+ JSON.stringify({+ locales: ["en-US", "fr-FR"],+ unavailableLocales: ["fr-FR"],+ bidirectionalReadiness: { status: "pending-remediation" },+ translationMethod: "agent",+ })+ );++ const originalConfigDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (originalConfigDir === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = originalConfigDir;+ }+ });+ invocationState.recordStart(+ "add-localization",+ "completion-session",+ projectRoot,+ Date.now() - 250+ );+ invocationState.markConfigured("add-localization", projectRoot);++ const result = spawnSync(+ process.execPath,+ [SCRIPT, "--projectRoot", projectRoot],+ {+ encoding: "utf8",+ env: {+ ...process.env,+ PATH: "",+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",+ },+ timeout: 30_000,+ }+ );++ assert.equal(result.status, 0);+ assert.ok(waitForFile(probePath, 5_000), "completion dispatcher should write probe");+ const envelope = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ const eventInfo = JSON.parse(envelope.data.eventInfo);+ assert.equal(envelope.data.eventName, "skill_completed");+ assert.equal(envelope.data.skillName, "add-localization");+ assert.equal(envelope.data.sessionId, "completion-session");+ assert.equal(envelope.data.outcome, "success");+ assert.ok(envelope.data.durationMs >= 250);+ assert.equal(eventInfo.validationOutcome, "passed");+ assert.equal(eventInfo.bidirectionalReadiness, "pending-remediation");+ assert.equal(eventInfo.unavailableLocaleCount, 1);+ assert.equal(eventInfo.configuredLocaleCount, 2);+ assert.equal(eventInfo.translationMethod, "agent");+ assert.equal(+ invocationState.findActive(+ "add-localization",+ projectRoot,+ { requireConfigured: true }+ ),+ null+ );+});++test("emits an allowlisted failure when no manifest is available", (t) => {+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-failed-"));+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-localized-"));+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);+ const originalConfigDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (originalConfigDir === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = originalConfigDir;+ }+ });+ invocationState.recordStart(+ "add-localization",+ "failure-session",+ projectRoot,+ Date.now() - 250+ );+ invocationState.markConfigured("add-localization", projectRoot);++ const result = spawnSync(+ process.execPath,+ [+ SCRIPT,+ "--projectRoot", projectRoot,+ "--outcome", "failure",+ "--validationOutcome", "failed",+ "--errorClass", "localization-build-failed",+ ],+ {+ encoding: "utf8",+ env: {+ ...process.env,+ PATH: "",+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",+ },+ timeout: 30_000,+ }+ );++ assert.equal(result.status, 0);+ assert.ok(waitForFile(probePath, 5_000), "failure dispatcher should write probe");+ const envelope = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ const eventInfo = JSON.parse(envelope.data.eventInfo);+ assert.equal(envelope.data.sessionId, "failure-session");+ assert.equal(envelope.data.outcome, "failure");+ assert.equal(envelope.data.errorClass, "localization-build-failed");+ assert.equal(envelope.data.severity, "Error");+ assert.equal(eventInfo.validationOutcome, "failed");+ assert.equal(eventInfo.configuredLocaleCount, undefined);+ assert.equal(eventInfo.unavailableLocaleCount, undefined);+ assert.equal(+ invocationState.findActive(+ "add-localization",+ projectRoot,+ { requireConfigured: true }+ ),+ null+ );+});++test("rejects non-allowlisted failure classifications", (t) => {+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-failed-"));+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-localized-"));+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);+ const originalConfigDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (originalConfigDir === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = originalConfigDir;+ }+ });+ invocationState.recordStart(+ "add-localization",+ "invalid-failure-session",+ projectRoot+ );+ invocationState.markConfigured("add-localization", projectRoot);++ const result = spawnSync(+ process.execPath,+ [+ SCRIPT,+ "--projectRoot", projectRoot,+ "--outcome", "failure",+ "--validationOutcome", "failed",+ "--errorClass", "C:\\customer\\private-error.txt",+ ],+ {+ encoding: "utf8",+ env: {+ ...process.env,+ PATH: "",+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",+ },+ timeout: 30_000,+ }+ );++ assert.equal(result.status, 0);+ assert.equal(waitForFile(probePath, 250), false);+ assert.ok(+ invocationState.findActive(+ "add-localization",+ projectRoot,+ { requireConfigured: true }+ )+ );+});diff --git a/plugins/power-pages/scripts/tests/emit-skill-configured-telemetry.test.js b/plugins/power-pages/scripts/tests/emit-skill-configured-telemetry.test.jsnew file mode 100644index 000000000..ef395be4d--- /dev/null+++ b/plugins/power-pages/scripts/tests/emit-skill-configured-telemetry.test.js@@ -0,0 +1,386 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { spawnSync } = require("node:child_process");++const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");+const SCRIPT = path.join(+ PLUGIN_ROOT,+ "scripts",+ "emit-skill-configured-telemetry.js"+);+const PRETOOL_HOOK = path.join(+ PLUGIN_ROOT,+ "hooks",+ "run-skill-pretool-telemetry.js"+);+const invocationState = require("../lib/telemetry/invocation-state");++function sleep(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function waitForEnvelope(filePath, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ try {+ const probe = JSON.parse(fs.readFileSync(filePath, "utf8"));+ return JSON.parse(probe.body);+ } catch {+ sleep(25);+ }+ }+ return null;+}++function writeTelemetryConfig(configDir) {+ const ikeyPath = path.join(configDir, "ikey.json");+ fs.writeFileSync(+ ikeyPath,+ JSON.stringify({+ event_stream_name: "PagesAIPluginEvent",+ disabled: false,+ default_region: "us",+ regions: {+ us: {+ instrumentation_key: "test-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collector_url: "https://example.invalid/OneCollector/1.0/",+ },+ },+ })+ );+ fs.writeFileSync(+ path.join(configDir, "resolver.js"),+ `module.exports = require(${JSON.stringify(+ path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry", "resolver.js")+ )});\n`+ );+ return ikeyPath;+}++function runStart({ configDir, hostRoot, ikeyPath, sessionId, skillName, probeName }) {+ return spawnSync(+ process.execPath,+ [PRETOOL_HOOK],+ {+ input: JSON.stringify({+ cwd: hostRoot,+ session_id: sessionId,+ tool_input: { skill: skillName },+ }),+ encoding: "utf8",+ env: {+ ...process.env,+ PATH: "",+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: path.join(configDir, probeName),+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",+ },+ timeout: 30_000,+ }+ );+}++function runCreateSiteConfigured({ configDir, projectRoot, ikeyPath, probeName }) {+ const probePath = path.join(configDir, probeName);+ const result = spawnSync(+ process.execPath,+ [+ SCRIPT,+ "--skillName", "create-site",+ "--projectRoot", projectRoot,+ "--framework", "react",+ "--siteContentLocale", "en-US",+ "--purpose", "company-portal",+ "--audience", "internal",+ "--choiceSource", "prompt",+ ],+ {+ encoding: "utf8",+ env: {+ ...process.env,+ PATH: "",+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",+ },+ timeout: 30_000,+ }+ );+ assert.equal(result.status, 0);+ const envelope = waitForEnvelope(probePath, 5_000);+ assert.ok(envelope, "configured dispatcher should write a complete probe");+ return envelope;+}++function invocationFileCount(configDir, skillName) {+ const dir = path.join(+ configDir,+ "telemetry",+ "power-pages",+ "invocations",+ skillName+ );+ try {+ return fs.readdirSync(dir).filter((entry) => entry.endsWith(".json")).length;+ } catch {+ return 0;+ }+}++test("configuration helper exits 0 when optional telemetry cannot load", () => {+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-config-load-"));+ const preload = path.join(configDir, "block-telemetry-load.js");+ fs.writeFileSync(+ preload,+ [+ '"use strict";',+ 'const Module = require("node:module");',+ "const originalLoad = Module._load;",+ "Module._load = function (request, parent, isMain) {",+ ' if (String(request).includes("power-pages-telemetry")) {',+ ' throw new Error("simulated telemetry load failure");',+ " }",+ " return originalLoad.call(this, request, parent, isMain);",+ "};",+ "",+ ].join("\n"),+ "utf8"+ );++ const result = spawnSync(+ process.execPath,+ [+ "--require",+ preload,+ SCRIPT,+ "--skillName",+ "create-site",+ "--projectRoot",+ configDir,+ ],+ { encoding: "utf8", timeout: 30_000 }+ );++ assert.equal(result.status, 0);+ assert.doesNotMatch(result.stderr, /simulated telemetry load failure/);+});++test("emits approved localization configuration with the start-hook session", (t) => {+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-config-event-"));+ const hostRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-config-host-"));+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-config-project-"));+ const probePath = path.join(configDir, "probe.json");+ const startProbePath = path.join(configDir, "start-probe.json");+ const ikeyPath = writeTelemetryConfig(configDir);++ const originalConfigDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (originalConfigDir === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = originalConfigDir;+ }+ });+ const startResult = spawnSync(+ process.execPath,+ [PRETOOL_HOOK],+ {+ input: JSON.stringify({+ cwd: hostRoot,+ session_id: "configured-session",+ tool_input: { skill: "add-localization" },+ }),+ encoding: "utf8",+ env: {+ ...process.env,+ PATH: "",+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: startProbePath,+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",+ },+ timeout: 30_000,+ }+ );+ assert.equal(startResult.status, 0);++ const result = spawnSync(+ process.execPath,+ [+ SCRIPT,+ "--skillName", "add-localization",+ "--projectRoot", projectRoot,+ "--framework", "angular",+ "--operation", "add-languages",+ "--invocationSource", "direct",+ "--existingLocalizationDetected", "true",+ "--mode", "runtime",+ "--defaultLocale", "en-US",+ "--addedLocales", "ar-SA-x-customer,fr-FR",+ "--resultingLocales", "en-US,ar-SA-x-customer,fr-FR",+ "--packageName", "@jsverse/transloco",+ "--packageVersion", "8.0.0",+ "--packageSelection", "recommended",+ "--packageVerification", "verified",+ "--translationMethod", "blank",+ ],+ {+ encoding: "utf8",+ env: {+ ...process.env,+ PATH: "",+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",+ },+ timeout: 30_000,+ }+ );++ assert.equal(result.status, 0);+ const envelope = waitForEnvelope(probePath, 5_000);+ assert.ok(envelope, "configured dispatcher should write a complete probe");+ const eventInfo = JSON.parse(envelope.data.eventInfo);+ assert.equal(envelope.data.eventName, "skill_configured");+ assert.equal(envelope.data.sessionId, "configured-session");+ assert.deepEqual(eventInfo.addedLocales, ["ar-SA", "fr-FR"]);+ assert.equal(eventInfo.translationMethod, "blank");+ assert.equal(eventInfo.addedLocaleCount, undefined);+ assert.ok(+ invocationState.findActive(+ "add-localization",+ projectRoot,+ { requireConfigured: true }+ )+ );+});++test("create-site removes only the invocation matched by configuration", (t) => {+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-create-config-"));+ const hostRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-create-host-"));+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-create-project-"));+ const ikeyPath = writeTelemetryConfig(configDir);+ const originalConfigDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (originalConfigDir === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = originalConfigDir;+ }+ });++ assert.equal(+ runStart({+ configDir,+ hostRoot,+ ikeyPath,+ sessionId: "create-session-1",+ skillName: "create-site",+ probeName: "start-1.json",+ }).status,+ 0+ );+ const first = runCreateSiteConfigured({+ configDir,+ projectRoot,+ ikeyPath,+ probeName: "configured-1.json",+ });+ assert.equal(first.data.sessionId, "create-session-1");+ assert.equal(invocationFileCount(configDir, "create-site"), 0);++ assert.equal(+ runStart({+ configDir,+ hostRoot,+ ikeyPath,+ sessionId: "create-session-2",+ skillName: "create-site",+ probeName: "start-2.json",+ }).status,+ 0+ );+ const second = runCreateSiteConfigured({+ configDir,+ projectRoot,+ ikeyPath,+ probeName: "configured-2.json",+ });+ assert.equal(second.data.sessionId, "create-session-2");+ assert.equal(invocationFileCount(configDir, "create-site"), 0);++ const otherProjectRoot = fs.mkdtempSync(+ path.join(os.tmpdir(), "ppskills-create-other-project-")+ );+ invocationState.recordStart(+ "create-site",+ "other-project-session",+ otherProjectRoot+ );+ assert.equal(+ runStart({+ configDir,+ hostRoot,+ ikeyPath,+ sessionId: "current-project-session",+ skillName: "create-site",+ probeName: "start-current.json",+ }).status,+ 0+ );+ const current = runCreateSiteConfigured({+ configDir,+ projectRoot,+ ikeyPath,+ probeName: "configured-current.json",+ });+ assert.equal(current.data.sessionId, "current-project-session");+ assert.equal(invocationFileCount(configDir, "create-site"), 1);+ const other = invocationState.findActive(+ "create-site",+ otherProjectRoot,+ { sessionId: "other-project-session" }+ );+ assert.ok(other);+ invocationState.removeState(other);++ assert.equal(+ runStart({+ configDir,+ hostRoot,+ ikeyPath,+ sessionId: "ambiguous-session-1",+ skillName: "create-site",+ probeName: "start-ambiguous-1.json",+ }).status,+ 0+ );+ assert.equal(+ runStart({+ configDir,+ hostRoot,+ ikeyPath,+ sessionId: "ambiguous-session-2",+ skillName: "create-site",+ probeName: "start-ambiguous-2.json",+ }).status,+ 0+ );+ const ambiguous = runCreateSiteConfigured({+ configDir,+ projectRoot,+ ikeyPath,+ probeName: "configured-ambiguous.json",+ });+ assert.notEqual(ambiguous.data.sessionId, "ambiguous-session-1");+ assert.notEqual(ambiguous.data.sessionId, "ambiguous-session-2");+ assert.equal(invocationFileCount(configDir, "create-site"), 2);+});diff --git a/plugins/power-pages/scripts/tests/power-pages-telemetry.test.js b/plugins/power-pages/scripts/tests/power-pages-telemetry.test.jsnew file mode 100644index 000000000..68ac17377--- /dev/null+++ b/plugins/power-pages/scripts/tests/power-pages-telemetry.test.js@@ -0,0 +1,174 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");++const telemetry = require("../lib/telemetry/power-pages-telemetry");++test("create-site telemetry keeps only the approved taxonomy", () => {+ const info = telemetry.buildCreateSiteEventInfo({+ framework: "React",+ siteContentLocale: "en-US-x-contoso",+ purpose: "Company Portal",+ audience: "Internal",+ choiceSource: "prompt",+ siteDirection: "ltr",+ siteContentLanguage: "en",+ siteName: "Contoso",+ });++ assert.deepEqual(info, {+ configurationType: "create-site",+ framework: "react",+ siteContentLocale: "en-US",+ purpose: "company-portal",+ audience: "internal",+ choiceSource: "prompt",+ });+});++test("localization telemetry strips locale extensions and removed count fields", () => {+ const info = telemetry.buildLocalizationEventInfo({+ framework: "angular",+ operation: "add-languages",+ invocationSource: "direct",+ existingLocalizationDetected: true,+ mode: "runtime",+ defaultLocale: "en-US",+ addedLocales: ["ar-SA-x-customer", "de-DE-u-co-phonebk"],+ resultingLocales: ["en-US", "ar-SA-x-customer", "de-DE-u-co-phonebk"],+ packageName: "@jsverse/transloco",+ packageVersion: "8.0.0",+ packageSelection: "recommended",+ packageVerification: "verified",+ translationMethod: "agent",+ addedLocaleCount: 2,+ resultingLocaleCount: 3,+ directionClassification: "mixed",+ introducesMixedDirection: true,+ });++ assert.deepEqual(info, {+ configurationType: "localization",+ framework: "angular",+ operation: "add-languages",+ invocationSource: "direct",+ existingLocalizationDetected: true,+ mode: "runtime",+ defaultLocale: "en-US",+ addedLocales: ["ar-SA", "de-DE"],+ resultingLocales: ["en-US", "ar-SA", "de-DE"],+ packageName: "@jsverse/transloco",+ packageVersion: "8.0.0",+ packageSelection: "recommended",+ packageVerification: "verified",+ translationMethod: "agent",+ });+});++test("package validation telemetry accepts only standardized failure codes", () => {+ const info = telemetry.buildPackageValidationEventInfo({+ framework: "react",+ operation: "create",+ intendedLocales: "en-US,fr-FR-x-private",+ packageName: "React-I18Next",+ resolvedVersion: "16.2.0",+ packageSelection: "alternative",+ mode: "runtime",+ validationStatus: "unsupported",+ failureCodes: [+ "framework-peer-incompatible",+ "license-review-required",+ "package-validation-error",+ "raw npm error text",+ "framework-peer-incompatible",+ ],+ prerelease: false,+ unverifiedOverrideRequested: false,+ });++ assert.deepEqual(info, {+ framework: "react",+ operation: "create",+ intendedLocales: ["en-US", "fr-FR"],+ packageName: "react-i18next",+ resolvedVersion: "16.2.0",+ packageSelection: "alternative",+ mode: "runtime",+ validationStatus: "unsupported",+ failureCodes: [+ "framework-peer-incompatible",+ "license-review-required",+ "package-validation-error",+ ],+ prerelease: false,+ unverifiedOverrideRequested: false,+ });+});++test("Power Pages owns localization package event name and severity", () => {+ const supported = telemetry.buildLocalizationPackageValidationEvent(+ "PagesAIPluginEvent",+ {+ pluginName: "power-pages",+ skillName: "add-localization",+ eventInfo: { validationStatus: "supported" },+ }+ );+ const rejected = telemetry.buildLocalizationPackageValidationEvent(+ "PagesAIPluginEvent",+ {+ pluginName: "power-pages",+ skillName: "add-localization",+ eventInfo: {+ validationStatus: "unsupported",+ failureCodes: ["mode-unsupported"],+ },+ }+ );++ assert.equal(supported.data.eventName, "localization_package_validation");+ assert.equal(supported.data.severity, "Info");+ assert.equal(rejected.data.eventName, "localization_package_validation");+ assert.equal(rejected.data.severity, "Error");+ assert.deepEqual(+ rejected.data.eventInfo.failureCodes,+ ["mode-unsupported"]+ );+});++test("private-use-only locale identifiers are not collected", () => {+ assert.equal(telemetry.sanitizeLocale("x-contoso"), null);+});++test("completion telemetry constrains readiness and count values", () => {+ assert.deepEqual(+ telemetry.buildLocalizationCompletionEventInfo({+ validationOutcome: "failed",+ bidirectionalReadiness: "customer-specific-value",+ unavailableLocaleCount: -2,+ configuredLocaleCount: 3.8,+ translationMethod: "blank",+ }),+ {+ validationOutcome: "failed",+ bidirectionalReadiness: "not-required",+ unavailableLocaleCount: 0,+ configuredLocaleCount: 3,+ translationMethod: "blank",+ }+ );+ assert.deepEqual(+ telemetry.buildLocalizationCompletionEventInfo({+ validationOutcome: "failed",+ }),+ {+ validationOutcome: "failed",+ }+ );+ assert.ok(+ telemetry.LOCALIZATION_COMPLETION_ERROR_CLASSES.has(+ "browser-verification-failed"+ )+ );+});diff --git a/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.js b/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.jsindex 2a1b85535..e39bdd915 100644--- a/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.js+++ b/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.js@@ -6,27 +6,75 @@ const fs = require("node:fs");const os = require("node:os");const path = require("node:path");const { spawnSync } = require("node:child_process");+const invocationState = require("../lib/telemetry/invocation-state");const HOOK = path.resolve(__dirname,"../../hooks/run-skill-posttool-validation.js");+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");function mkConfigDir() {return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-ho-"));}-function runHook({ input, configDir }) {- return spawnSync(process.execPath, [HOOK], {+function runHook({ input, configDir, ikeyPath, fakeProbe, preload }) {+ const args = preload ? ["--require", preload, HOOK] : [HOOK];+ return spawnSync(process.execPath, args, {input,encoding: "utf8",env: {...process.env,+ PATH: "",POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || "",+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",},+ timeout: 30_000,});}+function sleep(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function waitForFile(filePath, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (!fs.existsSync(filePath) && Date.now() < deadline) sleep(25);+ return fs.existsSync(filePath);+}++function writeProvisionedConfig(configDir) {+ const ikeyPath = path.join(configDir, "ikey.json");+ fs.writeFileSync(+ ikeyPath,+ JSON.stringify({+ event_stream_name: "PagesAIPluginEvent",+ disabled: false,+ default_region: "us",+ regions: {+ us: {+ instrumentation_key: "test-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collector_url: "https://example.invalid/OneCollector/1.0/",+ },+ },+ })+ );+ const shippedResolver = path.join(+ PLUGIN_ROOT,+ "scripts",+ "lib",+ "telemetry",+ "resolver.js"+ );+ fs.writeFileSync(+ path.join(configDir, "resolver.js"),+ `module.exports = require(${JSON.stringify(shippedResolver)});\n`+ );+ return ikeyPath;+}+test("posttool hook exits 0 with no tracked skill (preserves existing behavior)", () => {const { status } = runHook({input: JSON.stringify({ tool_input: { skill: "nothing" } }),@@ -34,3 +82,166 @@ test("posttool hook exits 0 with no tracked skill (preserves existing behavior)"});assert.equal(status, 0);});++test("validation continues when the optional telemetry module cannot load", () => {+ const configDir = mkConfigDir();+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-localized-"));+ const preload = path.join(configDir, "block-telemetry-load.js");+ fs.writeFileSync(+ preload,+ [+ '"use strict";',+ 'const Module = require("node:module");',+ "const originalLoad = Module._load;",+ "Module._load = function (request, parent, isMain) {",+ ' if (String(request).includes("power-pages-telemetry")) {',+ ' throw new Error("simulated telemetry load failure");',+ " }",+ " return originalLoad.call(this, request, parent, isMain);",+ "};",+ "",+ ].join("\n"),+ "utf8"+ );+ fs.writeFileSync(+ path.join(projectRoot, ".powerpages-localization.json"),+ JSON.stringify({+ locales: ["en-US", "fr-FR"],+ translationMethod: "agent",+ })+ );+ fs.writeFileSync(+ path.join(projectRoot, "package.json"),+ JSON.stringify({+ dependencies: {+ react: "^19.0.0",+ "react-dom": "^19.0.0",+ },+ })+ );+ fs.writeFileSync(+ path.join(projectRoot, "powerpages.config.json"),+ JSON.stringify({ siteName: "Telemetry Test" })+ );++ const result = runHook({+ input: JSON.stringify({+ cwd: projectRoot,+ session_id: "telemetry-load-failure-session",+ tool_input: { skill: "add-localization" },+ }),+ configDir,+ preload,+ });++ assert.equal(result.status, 2);+ assert.doesNotMatch(result.stderr, /simulated telemetry load failure/);+});++test("does not emit completion when the Skill hook runs before implementation", (t) => {+ const configDir = mkConfigDir();+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-localized-"));+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);+ fs.writeFileSync(+ path.join(projectRoot, ".powerpages-localization.json"),+ JSON.stringify({+ locales: ["en-US", "fr-FR"],+ translationMethod: "agent",+ })+ );+ fs.writeFileSync(+ path.join(projectRoot, "package.json"),+ JSON.stringify({+ dependencies: {+ react: "^19.0.0",+ "react-dom": "^19.0.0",+ },+ })+ );+ fs.writeFileSync(+ path.join(projectRoot, "powerpages.config.json"),+ JSON.stringify({ siteName: "Telemetry Test" })+ );++ const originalConfigDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (originalConfigDir === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = originalConfigDir;+ }+ });+ invocationState.recordStart(+ "add-localization",+ "completion-session",+ projectRoot,+ Date.now() - 250+ );+ invocationState.markConfigured("add-localization", projectRoot);++ const { status } = runHook({+ input: JSON.stringify({+ cwd: projectRoot,+ session_id: "completion-session",+ tool_input: { skill: "add-localization" },+ }),+ configDir,+ ikeyPath,+ fakeProbe: probePath,+ });++ assert.equal(status, 2);+ assert.equal(waitForFile(probePath, 250), false);+ assert.ok(+ invocationState.findActive(+ "add-localization",+ projectRoot,+ { requireConfigured: true, sessionId: "completion-session" }+ )+ );+});++test("unexpected hook errors do not emit or remove ambiguous state", (t) => {+ const configDir = mkConfigDir();+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-localized-"));+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);++ const originalConfigDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (originalConfigDir === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = originalConfigDir;+ }+ });+ invocationState.recordStart(+ "add-localization",+ "hook-error-session",+ projectRoot+ );+ invocationState.markConfigured("add-localization", projectRoot);++ const result = runHook({+ input: JSON.stringify({+ cwd: { invalid: true },+ session_id: "hook-error-session",+ tool_input: { skill: "add-localization" },+ }),+ configDir,+ ikeyPath,+ fakeProbe: probePath,+ });++ assert.equal(result.status, 0);+ assert.match(result.stderr, /Unexpected error/);+ assert.equal(fs.existsSync(probePath), false);+ assert.ok(invocationState.findActive(+ "add-localization",+ projectRoot,+ { sessionId: "hook-error-session" }+ ));+});diff --git a/plugins/power-pages/scripts/tests/telemetry-invocation-state.test.js b/plugins/power-pages/scripts/tests/telemetry-invocation-state.test.jsnew file mode 100644index 000000000..393635be8--- /dev/null+++ b/plugins/power-pages/scripts/tests/telemetry-invocation-state.test.js@@ -0,0 +1,304 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++const state = require("../lib/telemetry/invocation-state");++test("persists correlation state without storing the project path", (t) => {+ const original = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-state-"));+ const projectRoot = path.join(configDir, "customer-project");+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (original === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = original;+ }+ });++ const now = Date.now();+ assert.equal(state.projectHash({ invalid: "cwd" }), "");+ assert.equal(+ state.recordStart(+ "add-localization",+ "invalid-project-session",+ { invalid: "cwd" },+ now+ ),+ null+ );+ const file = state.recordStart(+ "add-localization",+ "host-session-123",+ projectRoot,+ now+ );+ assert.ok(file);+ const raw = fs.readFileSync(file, "utf8");+ assert.doesNotMatch(raw, /customer-project/);+ assert.equal(state.findActive("add-localization", projectRoot).sessionId, "host-session-123");++ state.markConfigured("add-localization", projectRoot, now + 1);+ const configured = state.findActive(+ "add-localization",+ projectRoot,+ { requireConfigured: true }+ );+ assert.equal(configured.configuredAt, now + 1);+ assert.equal(+ state.findActive("add-localization", projectRoot, {+ requireConfigured: true,+ sessionId: "different-session",+ }),+ null+ );++ state.removeState(configured);+ assert.equal(+ state.findActive("add-localization", projectRoot, { requireConfigured: true }),+ null+ );+});++test("binds one pending invocation to the resolved project root", (t) => {+ const original = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-state-"));+ const projectRoot = path.join(configDir, "resolved-project");+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (original === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = original;+ }+ });++ const pendingFile = state.recordPendingStart(+ "add-localization",+ "pending-session"+ );+ assert.ok(pendingFile);+ const raw = fs.readFileSync(pendingFile, "utf8");+ assert.doesNotMatch(raw, /resolved-project/);+ assert.equal(JSON.parse(raw).projectHash, undefined);++ const bound = state.bindPending("add-localization", projectRoot);+ assert.equal(bound.sessionId, "pending-session");+ assert.equal(bound.projectHash, state.projectHash(projectRoot));+ assert.equal(fs.existsSync(pendingFile), false);+});++test("does not guess when multiple project-less invocations are pending", (t) => {+ const original = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-state-"));+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (original === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = original;+ }+ });++ state.recordPendingStart("add-localization", "first-session");+ state.recordPendingStart("add-localization", "second-session");++ assert.equal(+ state.bindPending(+ "add-localization",+ path.join(configDir, "ambiguous-project")+ ),+ null+ );+});++test("does not bind over an existing project invocation", (t) => {+ const original = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-state-"));+ const projectRoot = path.join(configDir, "shared-project");+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (original === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = original;+ }+ });++ state.recordStart("add-localization", "bound-session", projectRoot);+ state.recordPendingStart("add-localization", "pending-session");++ assert.equal(+ state.findOrBindActive("add-localization", projectRoot),+ null+ );+});++test("rejects ambiguous project-only matches", (t) => {+ const original = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-state-"));+ const projectRoot = path.join(configDir, "shared-project");+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (original === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = original;+ }+ });++ state.recordStart("add-localization", "first-session", projectRoot);+ state.recordStart("add-localization", "second-session", projectRoot);++ assert.equal(state.findActive("add-localization", projectRoot), null);+ assert.equal(+ state.findActive(+ "add-localization",+ projectRoot,+ { sessionId: "first-session" }+ ).sessionId,+ "first-session"+ );+});++test("keeps projects separate when a host session is reused", (t) => {+ const original = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-state-"));+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (original === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = original;+ }+ });++ const firstRoot = path.join(configDir, "first-project");+ const secondRoot = path.join(configDir, "second-project");+ const now = Date.now();+ state.recordStart("add-localization", "shared-session", firstRoot, now);+ state.recordStart("add-localization", "shared-session", secondRoot, now + 1);++ assert.equal(state.findActive("add-localization", undefined), null);+ assert.equal(state.findActive("add-localization", { invalid: true }), null);+ assert.equal(+ state.findActive(+ "add-localization",+ firstRoot,+ { sessionId: "different-session" }+ ),+ null+ );+ assert.equal(+ state.findActive(+ "add-localization",+ path.join(configDir, "unrelated-project"),+ { sessionId: "shared-session" }+ ),+ null+ );+ const first = state.findActive(+ "add-localization",+ firstRoot,+ { sessionId: "shared-session" }+ );+ const second = state.findActive(+ "add-localization",+ secondRoot,+ { sessionId: "shared-session" }+ );+ assert.equal(first.projectHash, state.projectHash(firstRoot));+ assert.equal(second.projectHash, state.projectHash(secondRoot));+ assert.notEqual(first.file, second.file);+ assert.equal(+ fs.readdirSync(path.dirname(first.file))+ .filter((entry) => entry.endsWith(".json")).length,+ 2+ );+ assert.equal(+ state.findActive(+ "add-localization",+ undefined,+ { sessionId: "shared-session", allowSessionOnly: true }+ ),+ null+ );+ assert.equal(+ state.findActive(+ "add-localization",+ path.join(configDir, "unrelated-project"),+ { allowLatestFallback: true }+ ).sessionId,+ "shared-session"+ );++ state.removeState(first);+ assert.equal(+ state.findActive(+ "add-localization",+ firstRoot,+ { sessionId: "shared-session" }+ ),+ null+ );+ assert.equal(+ state.findActive(+ "add-localization",+ secondRoot,+ { sessionId: "shared-session" }+ ).projectHash,+ state.projectHash(secondRoot)+ );+ assert.equal(+ state.findActive(+ "add-localization",+ undefined,+ { sessionId: "shared-session", allowSessionOnly: true }+ ).projectHash,+ state.projectHash(secondRoot)+ );+});++test("migrates a matching legacy state file when configuration is marked", (t) => {+ const original = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-state-"));+ const projectRoot = path.join(configDir, "legacy-project");+ const legacyDir = path.join(+ configDir,+ "telemetry",+ "power-pages",+ "invocations",+ "add-localization"+ );+ const legacyFile = path.join(legacyDir, "legacy-session.json");+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ t.after(() => {+ if (original === undefined) {+ delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ } else {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = original;+ }+ });++ fs.mkdirSync(legacyDir, { recursive: true });+ fs.writeFileSync(legacyFile, JSON.stringify({+ sessionId: "legacy-session",+ startedAt: Date.now(),+ projectHash: state.projectHash(projectRoot),+ }));++ const migratedFile = state.markConfigured(+ "add-localization",+ projectRoot+ );++ assert.ok(migratedFile);+ assert.notEqual(migratedFile, legacyFile);+ assert.equal(fs.existsSync(legacyFile), false);+ assert.ok(fs.existsSync(migratedFile));+});diff --git a/plugins/power-pages/scripts/tests/validate-i18n-package.test.js b/plugins/power-pages/scripts/tests/validate-i18n-package.test.jsindex 98abce334..dad86377d 100644--- a/plugins/power-pages/scripts/tests/validate-i18n-package.test.js+++ b/plugins/power-pages/scripts/tests/validate-i18n-package.test.js@@ -2,6 +2,10 @@const test = require('node:test');const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');const {assessModeSupport,@@ -10,6 +14,7 @@ const {fetchText,isPublicIpAddress,packageSupportsFramework,+ parseTelemetryErrorContext,peerRangeAllowsMajor,resolveInstalledVersion,resolvePublicHostname,@@ -22,6 +27,48 @@ const {versionSatisfiesRangeWithNpm,} = require('../validate-i18n-package');const { createTempProject, writeProjectFile } = require('./test-utils');+const VALIDATOR = path.resolve(__dirname, '../validate-i18n-package.js');+const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');++function sleep(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function waitForFile(filePath, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (!fs.existsSync(filePath) && Date.now() < deadline) sleep(25);+ return fs.existsSync(filePath);+}++function writeProvisionedTelemetryConfig(configDir) {+ const ikeyPath = path.join(configDir, 'ikey.json');+ fs.writeFileSync(+ ikeyPath,+ JSON.stringify({+ event_stream_name: 'PagesAIPluginEvent',+ disabled: false,+ default_region: 'us',+ regions: {+ us: {+ instrumentation_key: 'test-ikey-32-chars-minimum-aaaaaaaaaaaaaa',+ collector_url: 'https://example.invalid/OneCollector/1.0/',+ },+ },+ })+ );+ const shippedResolver = path.join(+ PLUGIN_ROOT,+ 'scripts',+ 'lib',+ 'telemetry',+ 'resolver.js'+ );+ fs.writeFileSync(+ path.join(configDir, 'resolver.js'),+ `module.exports = require(${JSON.stringify(shippedResolver)});\n`+ );+ return ikeyPath;+}function metadata(overrides = {}) {return {@@ -49,6 +96,148 @@ function evaluationOptions(overrides = {}) {};}+test('package evaluation remains available when optional telemetry cannot load', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ppskills-i18n-telemetry-'));+ const preload = path.join(tempDir, 'block-telemetry-load.js');+ fs.writeFileSync(+ preload,+ [+ "'use strict';",+ "const Module = require('node:module');",+ 'const originalLoad = Module._load;',+ 'Module._load = function (request, parent, isMain) {',+ " if (String(request).includes('power-pages-telemetry')) {",+ " throw new Error('simulated telemetry load failure');",+ ' }',+ ' return originalLoad.call(this, request, parent, isMain);',+ '};',+ '',+ ].join('\n'),+ 'utf8'+ );+ const script = `+ const validator = require(${JSON.stringify(VALIDATOR)});+ const baseMetadata = {+ version: '16.2.0',+ license: 'MIT',+ description: 'Internationalization for React with runtime language switching',+ homepage: 'https://example.test/docs',+ peerDependencies: { react: '>=16.8.0 <20' },+ time: { '16.2.0': '2026-07-01T00:00:00.000Z' }+ };+ const options = {+ packageName: 'react-i18next',+ framework: 'react',+ frameworkVersion: '^19.0.0',+ frameworkVersions: { react: '^19.0.0', 'react-dom': '^19.0.0' },+ mode: 'runtime',+ now: new Date('2026-07-30T00:00:00.000Z'),+ rangeSatisfies: () => true+ };+ const supported = validator.evaluatePackage(baseMetadata, options);+ const rejected = validator.evaluatePackage(+ {+ ...baseMetadata,+ version: '17.0.0-rc.1',+ time: { '17.0.0-rc.1': '2026-07-01T00:00:00.000Z' }+ },+ options+ );+ process.stdout.write(JSON.stringify({+ supported: supported.viable,+ rejected: rejected.viable,+ rejectedCodes: rejected.failureCodes+ }));+ `;++ const result = spawnSync(+ process.execPath,+ ['--require', preload, '-e', script],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 0, result.stderr);+ assert.deepEqual(JSON.parse(result.stdout), {+ supported: true,+ rejected: false,+ rejectedCodes: ['prerelease-not-approved'],+ });+});++test('CLI error telemetry uses a stable generic failure code', () => {+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ppskills-i18n-error-'));+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ppskills-i18n-project-'));+ const probePath = path.join(configDir, 'probe.json');+ const ikeyPath = writeProvisionedTelemetryConfig(configDir);++ const result = spawnSync(+ process.execPath,+ [+ VALIDATOR,+ '--projectRoot', projectRoot,+ '--package', 'react-i18next',+ '--mode', 'runtime',+ '--framework', 'react',+ '--telemetryLocales', 'fr-FR',+ '--telemetryOperation', 'add-languages',+ '--telemetryPackageSelection', 'recommended',+ ],+ {+ encoding: 'utf8',+ env: {+ ...process.env,+ PATH: '',+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: '',+ },+ timeout: 30_000,+ }+ );++ assert.equal(result.status, 1);+ assert.ok(waitForFile(probePath, 5_000), 'error dispatcher should write probe');+ const envelope = JSON.parse(JSON.parse(fs.readFileSync(probePath, 'utf8')).body);+ const eventInfo = JSON.parse(envelope.data.eventInfo);+ assert.equal(envelope.data.eventName, 'localization_package_validation');+ assert.equal(eventInfo.validationStatus, 'error');+ assert.deepEqual(eventInfo.failureCodes, ['package-validation-error']);+ assert.deepEqual(eventInfo.intendedLocales, ['fr-FR']);+ assert.equal(eventInfo.operation, 'add-languages');+ assert.equal(eventInfo.packageSelection, 'recommended');+});++test('requires complete, usable context before emitting error telemetry', () => {+ assert.equal(parseTelemetryErrorContext([]), null);+ assert.equal(+ parseTelemetryErrorContext([+ '--projectRoot', '--package',+ '--mode', 'runtime',+ ]),+ null+ );+ assert.equal(+ parseTelemetryErrorContext([+ '--projectRoot', '.',+ '--package', 'react-i18next',+ ]),+ null+ );+ assert.deepEqual(+ parseTelemetryErrorContext([+ '--projectRoot', '.',+ '--package', 'react-i18next',+ '--mode', 'runtime',+ ]),+ {+ projectRoot: path.resolve('.'),+ package: 'react-i18next',+ mode: 'runtime',+ }+ );+});+test('accepts a stable, maintained, compatible runtime package', () => {const result = evaluatePackage(metadata(), evaluationOptions());@@ -75,6 +264,7 @@ test('rejects prereleases without explicit confirmation', () => {assert.equal(result.viable, false);assert.match(result.failures.join('\n'), /prerelease/);+ assert.deepEqual(result.failureCodes, ['prerelease-not-approved']);});test('reports license review alongside hard package failures', () => {@@ -173,6 +363,7 @@ test('requires mode evidence for unknown alternatives', () => {assert.equal(result.requiresConfirmation, true);assert.equal(result.modeEvidence.classificationRequired, true);assert.equal(result.failures.length, 0);+ assert.deepEqual(result.failureCodes, ['mode-inconclusive']);assert.match(result.warnings.join('\n'), /requires agent classification/);});diff --git a/plugins/power-pages/scripts/validate-i18n-package.js b/plugins/power-pages/scripts/validate-i18n-package.jsindex 2701fe244..6d56bc694 100644--- a/plugins/power-pages/scripts/validate-i18n-package.js+++ b/plugins/power-pages/scripts/validate-i18n-package.js@@ -23,6 +23,14 @@ const {sanitizeUntrustedText,} = require('./lib/safe-untrusted-text');+let telemetry = null;+try {+ telemetry = require('./lib/telemetry/power-pages-telemetry');+} catch {+ // Telemetry is optional. Package validation must remain available when the+ // bundled telemetry module is missing, invalid, or has a load-time failure.+}+const MAX_EVIDENCE_TEXT_CHARS = 200000;const MAX_NPM_METADATA_BYTES = 10 * 1024 * 1024;const OFFICIAL_NPM_REGISTRY = 'https://registry.npmjs.org/';@@ -872,6 +880,21 @@ function parseArgs(argv) {return args;}+function parseTelemetryErrorContext(argv) {+ const args = parseArgs(argv);+ for (const required of ['projectRoot', 'package', 'mode']) {+ const value = args[required];+ if (typeof value !== 'string' || !value.trim() ||+ value.startsWith('--')) {+ return null;+ }+ }+ return {+ ...args,+ projectRoot: path.resolve(args.projectRoot),+ };+}+async function runCli() {const args = parseArgs(process.argv.slice(2));if (!args.projectRoot || !args.package || !args.mode) {@@ -881,7 +904,10 @@ async function runCli() {'--mode <runtime|static> [--modeEvidenceUrl <official-https-url>] ' +'[--modeEvidenceClassificationFile <project-relative-json-path>] ' +'[--allowPrerelease] [--allowUnverifiedMode] ' +- '[--confirmLicenseReview]'+ '[--confirmLicenseReview] ' ++ '[--telemetryLocales <canonical-tags>] ' ++ '[--telemetryOperation <operation>] ' ++ '[--telemetryPackageSelection <selection>]');}const projectRoot = path.resolve(args.projectRoot);@@ -915,7 +941,13 @@ async function runCli() {projectDependencies[peerName]);}- const metadata = await resolvePackage(args.package, args.version || 'latest');+ let metadata;+ try {+ metadata = await resolvePackage(args.package, args.version || 'latest');+ } catch (error) {+ error.telemetryFailureCode = 'npm-resolution-failed';+ throw error;+ }let modeEvidenceDocument = null;let modeEvidenceClassification = null;let modeEvidenceUrl = null;@@ -985,12 +1017,57 @@ async function runCli() {),rangeSatisfies: versionSatisfiesRangeWithNpm,});+ if (telemetry) {+ try {+ telemetry.emitPackageValidation(+ projectRoot,+ telemetry.buildPackageValidationEventInfo({+ framework,+ operation: args.telemetryOperation,+ intendedLocales: args.telemetryLocales,+ packageName: args.package,+ resolvedVersion: result.version,+ packageSelection: args.telemetryPackageSelection,+ mode: args.mode,+ validationStatus: result.status,+ failureCodes: result.failureCodes,+ prerelease: result.prerelease,+ unverifiedOverrideRequested: Boolean(args.allowUnverifiedMode),+ })+ );+ } catch {+ // Package validation results must not depend on telemetry availability.+ }+ }process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);process.exitCode = result.viable ? 0 : 1;}if (require.main === module) {- runCli().catch(() => {+ runCli().catch((error) => {+ try {+ const args = parseTelemetryErrorContext(process.argv.slice(2));+ if (args && telemetry) {+ telemetry.emitPackageValidation(+ args.projectRoot,+ telemetry.buildPackageValidationEventInfo({+ framework: args.framework,+ operation: args.telemetryOperation,+ intendedLocales: args.telemetryLocales,+ packageName: args.package,+ packageSelection: args.telemetryPackageSelection,+ mode: args.mode,+ validationStatus: 'error',+ failureCodes: [+ error.telemetryFailureCode || 'package-validation-error',+ ],+ unverifiedOverrideRequested: Boolean(args.allowUnverifiedMode),+ })+ );+ }+ } catch {+ // Preserve the original validation failure.+ }process.stderr.write('Localization package validation failed before a result could be produced.\n');@@ -1011,6 +1088,7 @@ module.exports = {modeSupported,normalizeLicense,packageSupportsFramework,+ parseTelemetryErrorContext,peerRangeAllowsMajor,resolveInstalledVersion,validateOfficialArtifactMetadata,diff --git a/plugins/power-pages/skills/add-localization/SKILL.md b/plugins/power-pages/skills/add-localization/SKILL.mdindex ee7aef466..ae24ad915 100644--- a/plugins/power-pages/skills/add-localization/SKILL.md+++ b/plugins/power-pages/skills/add-localization/SKILL.md@@ -221,9 +221,16 @@ npm-backed package selected during a new setup or repair, including theframework recommendation and any alternative, run:```bash-node "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>"+node "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>" --telemetryLocales "<CANONICAL_RESULTING_LOCALES>" --telemetryOperation "<create|add-languages|repair|reconfigure>" --telemetryPackageSelection "<recommended|alternative|preserved>"```+Pass the same telemetry context on every rerun, including unsupported,+inconclusive, prerelease-confirmation, official-evidence, and explicitly+unverified attempts. The script emits only the normalized package name,+resolved public version when available, intended canonical locales, validation+status, and stable failure codes. It never emits npm error text or evidence+URLs.+<!-- not-a-gate: prerelease acknowledgement still precedes the approved plan and any install -->Interpret the JSON result as follows:@@ -257,11 +264,11 @@ legal approval. For review and acceptance, require explicit maker confirmation,then rerun with:```bash-node "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>" --confirmLicenseReview+node "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>" --confirmLicenseReview --telemetryLocales "<CANONICAL_RESULTING_LOCALES>" --telemetryOperation "<create|add-languages|repair|reconfigure>" --telemetryPackageSelection "<recommended|alternative|preserved>"```-Preserve the same telemetry arguments from the original command. This-confirmation overrides only the license criterion. Missing evidence,+Preserve any other previously approved validation flags from the original+command. This confirmation overrides only the license criterion. Missing evidence,deprecation, maintenance, compatibility, mode, and package-health failurescontinue to block.@@ -272,7 +279,13 @@ mode-evidence result with `AskUserQuestion`:|---|---|---|| The package's runtime/static support could not be verified. How should this proceed? | Package evidence | Use the framework recommendation (Recommended), Provide an official documentation URL, Proceed as explicitly unverified, Cancel |-For an official URL, rerun with `--modeEvidenceUrl "<HTTPS_URL>"`. The script+For an official URL, rerun with:++```bash+node "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>" --modeEvidenceUrl "<HTTPS_URL>" --telemetryLocales "<CANONICAL_RESULTING_LOCALES>" --telemetryOperation "<create|add-languages|repair|reconfigure>" --telemetryPackageSelection "<recommended|alternative|preserved>"+```++Preserve any other previously approved validation flags. The scriptaccepts only the package homepage or repository hostname published in npmmetadata, rejects local/internal hosts, fetches at most 1 MiB, strips activeHTML content, and returns bounded plain text in@@ -311,7 +324,7 @@ section, or when a condition cannot be checked.Write the classification to a temporary project-relative JSON file and rerun:```bash-node "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>" --modeEvidenceUrl "<HTTPS_URL>" --modeEvidenceClassificationFile "<PROJECT_RELATIVE_JSON_PATH>"+node "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>" --modeEvidenceUrl "<HTTPS_URL>" --modeEvidenceClassificationFile "<PROJECT_RELATIVE_JSON_PATH>" --telemetryLocales "<CANONICAL_RESULTING_LOCALES>" --telemetryOperation "<create|add-languages|repair|reconfigure>" --telemetryPackageSelection "<recommended|alternative|preserved>"```The script verifies the classification shape, requested mode, URL, and that@@ -326,11 +339,23 @@ classification file after the rerun.- `inconclusive`: return to the package-evidence question above.For an unverified override, explain that completion requires successful build-and browser verification, obtain explicit confirmation, and rerun with-`--allowUnverifiedMode`. Never use that flag for an unsupported result.+and browser verification, obtain explicit confirmation, and rerun with:++```bash+node "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>" --allowUnverifiedMode --telemetryLocales "<CANONICAL_RESULTING_LOCALES>" --telemetryOperation "<create|add-languages|repair|reconfigure>" --telemetryPackageSelection "<recommended|alternative|preserved>"+```++Never use that flag for an unsupported result. Preserve any other previously+approved validation flags.A prerelease requires a separate explicit `AskUserQuestion` confirmation and-rerun with `--allowPrerelease`.+rerun with:++```bash+node "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>" --allowPrerelease --telemetryLocales "<CANONICAL_RESULTING_LOCALES>" --telemetryOperation "<create|add-languages|repair|reconfigure>" --telemetryPackageSelection "<recommended|alternative|preserved>"+```++Preserve any other previously approved validation flags.For any alternative package whose initialization is not recognized bydeterministic discovery, identify the repository-relative initialization file@@ -411,6 +436,43 @@ Use `AskUserQuestion`:Loop through Phase 2 for revisions. Do not install or edit before approval.+After approval, emit the final configuration before Phase 4 changes any files:++```bash+node "${PLUGIN_ROOT}/scripts/emit-skill-configured-telemetry.js" --skillName "add-localization" --projectRoot "<PROJECT_ROOT>" --framework "<react|vue|angular|astro>" --operation "<create|add-languages|repair|reconfigure>" --invocationSource "<direct|create-site>" --existingLocalizationDetected "<true|false>" --mode "<runtime|static>" --defaultLocale "<DEFAULT_LOCALE>" --addedLocales "<CANONICAL_ADDED_LOCALES>" --resultingLocales "<CANONICAL_RESULTING_LOCALES>" --packageName "<PACKAGE_NAME>" --packageVersion "<RESOLVED_VERSION_OR_BUILT_IN>" --packageSelection "<recommended|alternative|preserved>" --packageVerification "<verified|unverified>" --translationMethod "<agent|blank>"+```++`invocationSource` is `create-site` only when `$ARGUMENTS` contains+`[FROM_CREATE_SITE]`; otherwise it is `direct`. For add-languages mode,+`addedLocales` contains only genuinely new locales while `resultingLocales`+contains the complete resulting set. The helper strips private-use and extension+subtags before emission.++After this configuration event, emit a failure completion before any terminal+workflow stop caused by implementation, verification, or explicit maker+rejection. Do not emit failure while retrying a recoverable check, for a+revision loop, or when deployment is skipped. Use only the matching stable+classification:++| Terminal reason | `errorClass` |+|---|---|+| Installed package no longer passes validation/provenance | `package-revalidation-failed` |+| Localization validator cannot be remediated | `localization-validation-failed` |+| Project build cannot be remediated | `localization-build-failed` |+| Rendered/browser verification cannot be remediated | `browser-verification-failed` |+| Final site-integrity errors cannot be remediated | `site-integrity-validation-failed` |+| Maker explicitly rejects the implemented localization and ends the workflow | `maker-rejected` |++Run the matching command silently immediately before the terminal stop:++```bash+node "${PLUGIN_ROOT}/scripts/emit-localization-completed-telemetry.js" --projectRoot "<PROJECT_ROOT>" --outcome "failure" --validationOutcome "failed" --errorClass "<STABLE_ERROR_CLASS>"+```++Never pass raw errors, file paths, URLs, user text, or dynamically invented+classifications. An abrupt host/process termination cannot run this best-effort+command; its invocation state expires normally.+---## Phase 4: Configure localization infrastructure@@ -437,8 +499,9 @@ result. Require all of the following before editing localization files:- `lockfileProvenance.present` and `lockfileProvenance.verified` are both`true`.-If any check fails, stop. Do not delete or rewrite a conflicting lockfile-entry outside the approved repair plan. Follow+If any check fails and cannot be remediated, emit failure completion with+`package-revalidation-failed`, then stop. Do not delete or rewrite a+conflicting lockfile entry outside the approved repair plan. Follow`${PLUGIN_ROOT}/references/i18n-frameworks.md` for the selected framework/mode.Adopt valid existing conventions rather than creating a second initialization@@ -542,9 +605,12 @@ Run the independent validator:node "${PLUGIN_ROOT}/skills/add-localization/scripts/validate-localization.js" --projectRoot "<PROJECT_ROOT>"```Fix all reported errors.+If the errors cannot be remediated and the workflow must end, emit failure+completion with `localization-validation-failed` before stopping.-Run the project's existing build. Start or reuse its dev server and verify-with Playwright:+Run the project's existing build. If the build cannot be remediated, emit+failure completion with `localization-build-failed` before stopping. Start or+reuse its dev server and verify with Playwright:- Default locale and one target locale.- Selector behavior or equivalent static locale navigation.@@ -566,8 +632,9 @@ that stale resource requests cannot overwrite a newer selection.For an explicitly unverified package, all build, initialization, switching orroute navigation, resource loading, `lang`/`dir`, and console checks are-mandatory. If any check fails, stop and recommend the framework package; do-not silently replace the approved package.+mandatory. If any browser or rendered check fails and cannot be remediated,+emit failure completion with `browser-verification-failed`, then stop and+recommend the framework package; do not silently replace the approved package.Repeat the AI translation warning when applicable.@@ -580,9 +647,11 @@ are complete, run:node "${PLUGIN_ROOT}/scripts/validate-site-integrity.js" --projectRoot "<PROJECT_ROOT>"```-Fix every blocking error before reviewing or completing the skill. Inspect and report review-findings in both directions and with expanded content. Rerun this gate after any subsequent source-change.+Fix every blocking error before reviewing or completing the skill. If the+blocking errors cannot be remediated, emit failure completion with+`site-integrity-validation-failed` before stopping. Inspect and report review+findings in both directions and with expanded content. Rerun this gate after+any subsequent source change.---@@ -632,6 +701,17 @@ offer deployment in Phase 8.Record usage with skill name `AddLocalization`.+After usage is recorded, emit completion telemetry. This command runs only+after implementation, validation, build, browser verification, and maker+review are complete:++```bash+node "${PLUGIN_ROOT}/scripts/emit-localization-completed-telemetry.js" --projectRoot "<PROJECT_ROOT>" --outcome "success" --validationOutcome "passed"+```++Run it silently. The helper is fail-closed and reads only the approved+localization manifest fields; do not add free-text arguments.+If `$ARGUMENTS` contains `[FROM_CREATE_SITE]`, return control to create-sitewithout asking about deployment.diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.mdindex 353d3dd88..75b272641 100644--- a/plugins/power-pages/skills/create-site/SKILL.md+++ b/plugins/power-pages/skills/create-site/SKILL.md@@ -783,8 +783,22 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to readsite name, technical slug, framework, purpose, audience, project location,`SITE_LANGUAGE` (`SITE_LOCALE`, `SITE_DIRECTION`), and the explicit statementthat Dataverse and Power Pages system messages remain English.+14. After confirmation, emit the approved, taxonomy-only site configuration:-14. Append the from-scratch task list (Phases 2-8) to the todo list (see+ - Map the purpose to `company-portal`, `blog-content`, `dashboard`,+ `landing-page`, or `other`. Never pass the maker's free-text purpose.+ - Set `choiceSource` to `arguments` only when both framework and content+ locale came from the initial request; otherwise use `prompt`.++ ```bash+ node "${PLUGIN_ROOT}/scripts/emit-skill-configured-telemetry.js" --skillName "create-site" --projectRoot "<PROJECT_ROOT>" --framework "<react|vue|angular|astro>" --siteContentLocale "<SITE_LOCALE>" --purpose "<PURPOSE_TAXONOMY>" --audience "<internal|external>" --choiceSource "<arguments|prompt>"+ ```++ The telemetry helper is fail-closed and removes locale extensions/private-use+ subtags. Do not add the site name, description, pages, routes, components,+ feature labels, or any other free-text requirement to this command.++15. Append the from-scratch task list (Phases 2-8) to the todo list (see[Progress Tracking](#progress-tracking)), then mark **Select template orchoose from-scratch** as `completed`.diff --git a/plugins/power-pages/skills/telemetry/telemetry-workflow.md b/plugins/power-pages/skills/telemetry/telemetry-workflow.mdindex 6683c182a..7970fd9e3 100644--- a/plugins/power-pages/skills/telemetry/telemetry-workflow.md+++ b/plugins/power-pages/skills/telemetry/telemetry-workflow.md@@ -27,12 +27,16 @@ telemetry for this plugin. Default to `status` when no argument is given.`eventInfo.aadObjectId` when PAC exposes it, and the SPA framework of thePower Pages code site being worked in (`react`, `vue`, `angular`, or `astro`)as `eventInfo.framework`. The framework name describes the scaffold only —- it is never a site name or path. Model Apps excludes both.+ it is never a site name or path.+ Power Pages also records approved create-site/localization choices, canonical+ locales, public localization package names/versions, stable validation+ outcomes, and localization completion.When plugin telemetry is enabled, the local diagnostic mirror retains the sameevent fields even when transmission is off.A plugin whose committed telemetry config has `disabled: true` writes no mirror.- Events do not include file paths, prompts, tool inputs, site names, Dataverse- URLs, credentials, usernames, or hostnames.+ URLs, credentials, usernames, hostnames, free-text requirements, private-use+ locale subtags, evidence URLs, or raw errors.- **Automation/CI** can disable telemetry by setting the opt-out env var`POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT=1` instead of running thiscommand. The value can be `1` or `true` (the dotnet `*_TELEMETRY_OPTOUT`diff --git a/shared/telemetry/README.md b/shared/telemetry/README.mdindex a687edad5..b567ed916 100644--- a/shared/telemetry/README.md+++ b/shared/telemetry/README.md@@ -12,7 +12,12 @@ For the repository-level user disclosure, see [Telemetry](../../README.md#teleme## What it does-`skill_started` usage telemetry over the 1DS Common Schema 4.0 envelope. A detached dispatcher child resolves the destination iKey + collector URL (env override → plugin `resolver.js` → static key in `ikey.json`), then POSTs the event; the hook that emitted it returns before the POST happens.+Usage telemetry over the 1DS Common Schema 4.0 envelope. All+adopters emit `skill_started`; plugins may also emit allowlisted configuration,+validation, and completion events. A detached dispatcher child resolves the+destination iKey + collector URL (env override → plugin `resolver.js` → static+key in `ikey.json`), then POSTs the event; the process that emitted it returns+before the POST happens.```hook (~5ms when disabled, ~3-5s otherwise — incl. when the user opted out)@@ -155,9 +160,32 @@ Every event carries a fixed allowlist enforced by `lib/events.js`. Field names m`emitSkillStartedFromPrompt(promptText, opts)` accepts an optional `opts.eventInfo` so a plugin can contribute its own approved keys from the `UserPromptSubmit` hook. It takes either a plain object or a **thunk** returning one; the thunk is preferred, and is invoked only *after* the slash-command, `disabled`, and `isProvisioned` gates pass — that hook fires on every user prompt, so any real work (filesystem probing, shellouts) must not run on untracked prompts. A thunk that throws contributes nothing and never blocks the event. Non-object values (including arrays) are ignored.+Power Pages additionally emits:++- `skill_configured` for approved `create-site` and `add-localization`+ configuration. Create-site records framework, canonical content locale,+ fixed purpose/audience categories, and whether the choice came from the+ initial request or a prompt. Localization records framework, operation,+ invocation source, existing-setup flag, mode, canonical default/added/resulting+ locales, package name/version/selection/verification, and `agent` versus+ `blank` translation population.+- `localization_package_validation` for each package-validation attempt. It+ records intended canonical locales, package/mode selection, validation+ status, prerelease/unverified flags, and stable failure codes. Raw npm errors,+ exception messages, and evidence URLs are never included.+- `skill_completed` only for Power Pages `add-localization`. It records outcome,+ duration, a stable error class on failure, validation outcome, readiness+ status, configured/unavailable locale counts, and translation method.++Locale telemetry strips private-use (`-x-*`) and extension sequences before+emission. Private-use-only identifiers are dropped.+## What is NEVER sent-File paths, cwd, env vars, site names, Dataverse URLs, stack traces, `err.message` text, skill arguments, tool inputs, prompt text, usernames, hostnames.+File paths, cwd, env vars, site names, site descriptions, page/route/component+names, free-text requirements, Dataverse URLs, stack traces, `err.message` text,+raw npm errors, evidence URLs, skill arguments, tool inputs, prompt text,+usernames, hostnames, or private-use locale subtags.The dispatcher runs a defense-in-depth allowlist filter against `FIELD_TYPES` before serializing, so any top-level field that bypasses the builders is dropped before it reaches the wire. This filter does not inspect nested `eventInfo` keys; the caller restriction above is part of the telemetry contract.@@ -193,7 +221,7 @@ The `disabled` flag is checked at every layer that could perform user-facing worshared/telemetry/├─ ikey.json # placeholder template config (each plugin keeps its own real ikey.json)├─ lib/-│ ├─ events.js # FIELD_TYPES allowlist + buildSkillStarted+│ ├─ events.js # FIELD_TYPES allowlist + event builders│ ├─ emit-spawn.js # fireAndForget — spawn detached dispatcher│ ├─ emit-dispatcher.js # detached child — kill switches, opt-out, destination resolve (resolver.js or static key), sanitize, POST│ ├─ emit-from-prompt.js # UserPromptSubmit hook helper — detect slash command + emit skill_starteddiff --git a/shared/telemetry/lib/events.js b/shared/telemetry/lib/events.jsindex 13f35c3ac..f7b2ffc12 100644--- a/shared/telemetry/lib/events.js+++ b/shared/telemetry/lib/events.js@@ -114,14 +114,22 @@ function buildEvent(envelopeName, eventName, info, severity) {}function buildSkillStarted(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_started", input, "Info");+}++function buildSkillEvent(envelopeName, eventName, input, severity = "Info") {return buildEvent(envelopeName,- "skill_started",+ eventName,pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),- "Info"+ severity);}+function buildSkillConfigured(envelopeName, input) {+ return buildSkillEvent(envelopeName, "skill_configured", input, "Info");+}+function buildSkillCompleted(envelopeName, input) {const severity = input && input.outcome === "failure" ? "Error" : "Info";return buildEvent(@@ -134,6 +142,8 @@ function buildSkillCompleted(envelopeName, input) {module.exports = {buildSkillStarted,+ buildSkillEvent,+ buildSkillConfigured,buildSkillCompleted,FIELD_TYPES,pick,diff --git a/shared/telemetry/lib/telemetry-config.js b/shared/telemetry/lib/telemetry-config.jsindex bf92b8a38..8950e32c5 100644--- a/shared/telemetry/lib/telemetry-config.js+++ b/shared/telemetry/lib/telemetry-config.js@@ -14,7 +14,10 @@ function dataDisclosure(plugin) {" eventInfo.aadObjectId when PAC exposes it, and the SPA framework of the\n" +" Power Pages code site being worked in as eventInfo.framework when detected.\n" +" The framework is one of react, vue, angular, or astro and describes the\n" +- " scaffold only — it is never a site name or path.\n"+ " scaffold only — it is never a site name or path.\n" ++ " Telemetry records usage fields for approved create-site/localization\n" ++ " choices, canonical locales, public package names/versions, stable\n" ++ " validation outcomes, and localization completion.\n": plugin === "model-apps"? " Model Apps excludes the signed-in user's Entra object ID.\n": "";@@ -27,7 +30,8 @@ function dataDisclosure(plugin) {" fields even when transmission is off. A plugin whose committed telemetry\n" +" config has disabled: true is hard-disabled and writes no log.\n" +" Events do not include file paths, prompts, tool inputs, site names,\n" +- " Dataverse URLs, credentials, usernames, or hostnames."+ " free-text requirements, Dataverse URLs, credentials, usernames,\n" ++ " hostnames, private-use locale subtags, evidence URLs, or raw errors.");}diff --git a/shared/telemetry/tests/events.test.js b/shared/telemetry/tests/events.test.jsindex 7f7bd9a7d..8004e5666 100644--- a/shared/telemetry/tests/events.test.js+++ b/shared/telemetry/tests/events.test.js@@ -4,6 +4,8 @@ const test = require("node:test");const assert = require("node:assert/strict");const {buildSkillStarted,+ buildSkillEvent,+ buildSkillConfigured,buildSkillCompleted,} = require("../lib/events");@@ -32,6 +34,37 @@ test("buildSkillStarted returns top-level fields with envelope name", () => {assert.equal(ev.data.nodeVersion, "v22");});+test("buildSkillConfigured carries approved configuration in eventInfo", () => {+ const eventInfo = {+ configurationType: "create-site",+ framework: "react",+ siteContentLocale: "fr-FR",+ };+ const ev = buildSkillConfigured(ENVELOPE, {+ ...common,+ skillName: "create-site",+ eventInfo,+ });+ assert.equal(ev.data.eventName, "skill_configured");+ assert.equal(ev.data.severity, "Info");+ assert.deepEqual(ev.data.eventInfo, eventInfo);+});++test("buildSkillEvent applies a caller-owned event name and severity", () => {+ const eventInfo = {+ validationStatus: "unsupported",+ failureCodes: ["mode-unsupported"],+ };+ const event = buildSkillEvent(ENVELOPE, "skill_validation", {+ ...common,+ skillName: "add-localization",+ eventInfo,+ }, "Error");+ assert.equal(event.data.eventName, "skill_validation");+ assert.equal(event.data.severity, "Error");+ assert.deepEqual(event.data.eventInfo, eventInfo);+});+test("buildSkillCompleted with success outcome → severity Info", () => {const ev = buildSkillCompleted(ENVELOPE, {...common,diff --git a/shared/telemetry/tests/telemetry-config.test.js b/shared/telemetry/tests/telemetry-config.test.jsindex 681ddd774..a4f54f87b 100644--- a/shared/telemetry/tests/telemetry-config.test.js+++ b/shared/telemetry/tests/telemetry-config.test.js@@ -38,6 +38,7 @@ test("off writes the per-plugin opt-out and confirms", () => {assert.match(stdout, /When plugin telemetry is enabled/);assert.match(stdout, /committed telemetry\s+config has disabled: true/);assert.match(stdout, /hard-disabled and writes no log/);+ assert.match(stdout, /Telemetry records usage fields/);assert.doesNotMatch(stdout, /anonymous/i);const cfg = JSON.parse(fs.readFileSync(path.join(dir, "config.json"), "utf8"));assert.equal(cfg.telemetry["power-pages"], "off");@@ -83,6 +84,7 @@ test("status reports ON by default and never reads ikey.json", () => {assert.match(stdout, /When plugin telemetry is enabled/);assert.match(stdout, /committed telemetry\s+config has disabled: true/);assert.match(stdout, /hard-disabled and writes no log/);+ assert.match(stdout, /Telemetry records usage fields/);assert.doesNotMatch(stdout, /anonymous/i);});