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
[power-pages] Log the site SPA framework in skill telemetry (#466)
amitjoshi4380264d38b97ea
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/emit-from-prompt.js b/plugins/model-apps/scripts/lib/telemetry/lib/emit-from-prompt.jsindex 0ec329005..38113ebd9 100644--- a/plugins/model-apps/scripts/lib/telemetry/lib/emit-from-prompt.js+++ b/plugins/model-apps/scripts/lib/telemetry/lib/emit-from-prompt.js@@ -51,6 +51,12 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {trackedSkills,telemetryDir,sessionId, // primed from Claude Code's hook payload (parsed.session_id)+ // Optional plugin-supplied dynamic payload merged into `eventInfo` below.+ // Accepts a plain object, or a thunk returning one. Prefer the thunk: it is+ // invoked only after the slash-command / `disabled` / `isProvisioned` gates+ // below, so a plugin whose payload costs real work (filesystem probing, etc.)+ // pays nothing on untracked prompts or a disabled plugin.+ eventInfo,_emit, // test seam; defaults to fireAndForget_readPacAuth, // test seam; defaults to lib/pac-auth_readAgentInfo, // test seam; defaults to lib/agent-info@@ -122,7 +128,29 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {};if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;- if (pacAuth && pacAuth.objectId) fields.eventInfo = { aadObjectId: pacAuth.objectId };+ // `eventInfo` is assembled from two INDEPENDENT sources and assigned only when+ // non-empty. Building it inside the objectId guard instead would drop the+ // caller's payload on every unauthenticated run (`pac auth who` surfaces no+ // object id), and any later `fields.eventInfo.x = ...` would throw on the+ // undefined — a throw the fail-closed wrapper swallows, silently degrading the+ // run to no event at all. The caller owns not putting PII in its payload;+ // `aadObjectId` is written last so the library's own field always wins.+ const mergedEventInfo = {};+ let callerEventInfo = eventInfo;+ if (typeof callerEventInfo === "function") {+ try {+ callerEventInfo = callerEventInfo();+ } catch {+ // A caller thunk threw — drop its contribution rather than lose the whole+ // event. The library's own fields below are unaffected.+ callerEventInfo = null;+ }+ }+ if (callerEventInfo && typeof callerEventInfo === "object" && !Array.isArray(callerEventInfo)) {+ Object.assign(mergedEventInfo, callerEventInfo);+ }+ if (pacAuth && pacAuth.objectId) mergedEventInfo.aadObjectId = pacAuth.objectId;+ if (Object.keys(mergedEventInfo).length > 0) fields.eventInfo = mergedEventInfo;if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.jsindex 073b7cfd0..bf92b8a38 100644--- a/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js+++ b/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js@@ -11,7 +11,10 @@ function dataDisclosure(plugin) {const pluginSpecific =plugin === "power-pages"? " Power Pages can also record the signed-in user's Entra object ID as\n" +- " eventInfo.aadObjectId when PAC exposes it.\n"+ " 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": plugin === "model-apps"? " Model Apps excludes the signed-in user's Entra object ID.\n": "";diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex 40e5a6a49..ba73e795f 100644--- a/plugins/power-pages/.claude-plugin/plugin.json+++ b/plugins/power-pages/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.6.3",+ "version": "2.6.4","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/.plugin/plugin.json b/plugins/power-pages/.plugin/plugin.jsonindex 40e5a6a49..ba73e795f 100644--- a/plugins/power-pages/.plugin/plugin.json+++ b/plugins/power-pages/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.6.3",+ "version": "2.6.4","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex e360b32ad..677850f33 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -439,6 +439,11 @@ This plugin ships 1DS telemetry for skill-run and script-run signals. The canoni- **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`.- **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.+- **Optional telemetry enrichment must load non-fatally.** `detect-site-framework` is required in its own `try/catch` that degrades to `null`, *not* in the hooks' mandatory require block. Bundling optional enrichment there would widen the blast radius of any packaging slip or syntax error from "no framework" to **no telemetry at all**. Apply the same separation to any future optional field.+- **Detection cost scales with the entry count of cwd.** A child miss performs one directory enumeration and at most two marker checks per immediate subdirectory; direct or upward site hits do not scan children. Typical directories cost single-digit ms against the hook's much larger PAC/agent-info work. It runs only *after* the hard-disabled / `isProvisioned` gates; user opt-out still builds the event because the local diagnostic mirror is retained.+- **`eventInfo` keys are independent.** Build the object unconditionally and assign it only when non-empty. Never nest a new key inside the `pacAuth.objectId` guard: that both drops the key on unauthenticated runs and throws on `undefined`, which the fail-closed wrapper swallows into *no event at all*.+- **The bundled lib copy is CI-guarded.** `scripts/tests/telemetry-lib-copy.test.js` asserts byte-equality with `shared/telemetry/lib` (skipping when `shared/` is absent, i.e. an installed plugin) and exercises the copy's defensive branches — `shared/telemetry/tests` has no workflow, so behavior asserted only there is not CI-covered.See `shared/telemetry/README.md` for the integration guide.diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex 1c93188ee..b111f9af9 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -528,6 +528,7 @@ This Dataverse relationship check is intended for local validation only and shouThis 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.**Turn it on or off (per-user, applies to every project):**diff --git a/plugins/power-pages/hooks/run-skill-pretool-telemetry.js b/plugins/power-pages/hooks/run-skill-pretool-telemetry.jsindex 884734b8c..07cf25655 100644--- a/plugins/power-pages/hooks/run-skill-pretool-telemetry.js+++ b/plugins/power-pages/hooks/run-skill-pretool-telemetry.js@@ -28,6 +28,18 @@ try {process.exit(0);}+// Loaded separately and NON-fatally: the framework signal is one optional field+// inside `eventInfo`, so it must not be able to take the whole event down with+// it. Bundling optional enrichment into the block above would widen the blast+// radius of any packaging slip or syntax error from "no framework" to+// "no telemetry".+let detectFramework = null;+try {+ detectFramework = require(path.join(PLUGIN_ROOT, "scripts", "lib", "detect-site-framework"));+} catch {+ detectFramework = null;+}+function readPluginVersion() {try {const manifest = JSON.parse(@@ -132,6 +144,23 @@ function readStdin() {agentInfo = {};}+ // Which SPA framework the site under work uses. Resolved AFTER the hard-off /+ // isProvisioned gates above so a disabled or unprovisioned plugin pays nothing+ // for it. User opt-out still builds the event for the local diagnostic mirror.+ // Claude Code supplies the host session's working directory on the hook payload+ // (same field run-skill-posttool-validation.js reads); fall back to this+ // process's cwd for hosts that don't.+ let framework = null;+ try {+ framework = detectFramework+ ? detectFramework.detectSiteFramework(+ typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd : process.cwd()+ )+ : null;+ } catch {+ framework = null;+ }+const fields = {pluginName: "power-pages",pluginVersion: readPluginVersion(),@@ -144,7 +173,15 @@ function readStdin() {};if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;- if (pacAuth && pacAuth.objectId) fields.eventInfo = { aadObjectId: pacAuth.objectId };+ // `eventInfo` carries two INDEPENDENT signals, so it is assembled up front and+ // assigned only when non-empty. Creating it inside the objectId guard instead+ // would drop `framework` on every unauthenticated run (`pac auth who` surfaces+ // no object id), and mutating the undefined would throw — a throw the+ // fail-closed wrapper swallows, silently degrading the run to no event at all.+ const eventInfo = {};+ if (framework) eventInfo.framework = framework;+ if (pacAuth && pacAuth.objectId) eventInfo.aadObjectId = pacAuth.objectId;+ if (Object.keys(eventInfo).length > 0) fields.eventInfo = eventInfo;if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;diff --git a/plugins/power-pages/hooks/run-user-prompt-telemetry.js b/plugins/power-pages/hooks/run-user-prompt-telemetry.jsindex 1c47cc447..2e1c49322 100644--- a/plugins/power-pages/hooks/run-user-prompt-telemetry.js+++ b/plugins/power-pages/hooks/run-user-prompt-telemetry.js@@ -25,6 +25,23 @@ try {process.exit(0);}+// Loaded separately and NON-fatally: the framework signal is one optional field+// inside `eventInfo`, so it must not be able to take the whole event down with+// it. Bundling optional enrichment into the block above would widen the blast+// radius of any packaging slip or syntax error from "no framework" to+// "no telemetry".+let detectFramework = null;+try {+ detectFramework = require(path.join(+ PLUGIN_ROOT,+ "scripts",+ "lib",+ "detect-site-framework"+ ));+} catch {+ detectFramework = null;+}+function readPluginVersion() {try {const manifest = JSON.parse(@@ -70,6 +87,19 @@ function readStdin() {trackedSkills: hookUtils.TRACKED_SKILLS,telemetryDir: TELEMETRY_DIR,sessionId: sessionLib.resolveHostSessionId(parsed),+ // Thunk, not a value: this hook fires on EVERY user prompt, but the+ // library invokes this only after the prompt is confirmed to be a tracked+ // slash command AND the plugin is enabled + provisioned. Detecting eagerly+ // here would walk the filesystem on every keystroke-level prompt for no+ // reason. Claude Code supplies the host cwd on the payload; fall back to+ // this process's cwd for hosts that don't.+ eventInfo: () => {+ if (!detectFramework) return null;+ const framework = detectFramework.detectSiteFramework(+ typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd : process.cwd()+ );+ return framework ? { framework } : null;+ },});} catch {// fail closed — telemetry never blocks the user's promptdiff --git a/plugins/power-pages/scripts/lib/detect-site-framework.js b/plugins/power-pages/scripts/lib/detect-site-framework.jsnew file mode 100644index 000000000..91c0f8a03--- /dev/null+++ b/plugins/power-pages/scripts/lib/detect-site-framework.js@@ -0,0 +1,186 @@+"use strict";++// Detects which SPA framework a Power Pages **code site** is built with, for+// telemetry only (emitted inside the dynamic `eventInfo` column — see+// shared/telemetry/README.md "What is sent").+//+// Runs on the telemetry hot path (PreToolUse(Skill) + UserPromptSubmit), so it+// is fail-closed and cheap: every failure mode returns null rather than+// throwing, because telemetry must never change a hook's exit code.++const fs = require("node:fs");+const path = require("node:path");++// `powerpages.config.json` means "Power Pages code site". `.powerpages-site/`+// marks a declarative design-studio site from `pac pages download`; it has no+// SPA framework, but still matters as a site boundary and when deciding whether+// a child workspace identifies exactly one site.+const CONFIG_MARKER = "powerpages.config.json";+const DECLARATIVE_MARKER = ".powerpages-site";+const MARKER_ABSENT = "absent";+const MARKER_VALID = "valid";+const MARKER_INVALID = "invalid";++// Ordered marker list — the FIRST match wins, so order is load-bearing:+//+// * `astro` wins over every other match because an Astro site can legitimately+// declare React/Vue tooling for island components. Such a site is still an+// Astro scaffold.+// * `@angular/core` (not `angular`) is the Angular marker — `angular` is the+// long-dead AngularJS 1.x package name and would be a false positive.+// * React and Vue use their scaffold build plugins instead of their runtime+// packages. A React application can legitimately consume Vue (and vice+// versa); the Vite plugin is the stronger fingerprint of how the site was+// scaffolded.+//+// For non-Astro sites exactly ONE marker must match; ambiguity reports null.+// Kept in sync with the four scaffolds under skills/create-site/assets/.+const FRAMEWORK_MARKERS = [+ ["astro", "astro"],+ ["angular", "@angular/core"],+ ["vue", "@vitejs/plugin-vue"],+ ["react", "@vitejs/plugin-react"],+];++function readJson(filePath) {+ try {+ return JSON.parse(fs.readFileSync(filePath, "utf8"));+ } catch {+ // Missing, unreadable, or malformed → indistinguishable from "no site" for+ // telemetry purposes. Callers omit the field entirely rather than guess.+ return null;+ }+}++// A code-site marker is trusted only when it is a regular file containing a+// JSON object. `existsSync` alone also accepts directories, and malformed JSON+// must stop attribution rather than allowing an enclosing/adjacent site to win.+function configMarkerState(dir) {+ const markerPath = path.join(dir, CONFIG_MARKER);+ try {+ const stat = fs.statSync(markerPath);+ if (!stat.isFile()) return MARKER_INVALID;+ const config = readJson(markerPath);+ return config && typeof config === "object" && !Array.isArray(config)+ ? MARKER_VALID+ : MARKER_INVALID;+ } catch (error) {+ return error && error.code === "ENOENT" ? MARKER_ABSENT : MARKER_INVALID;+ }+}++/**+ * Resolves the root of the Power Pages code site containing `startDir`.+ *+ * Same two-phase shape as `validation-helpers.findProjectRoot` — walk UP, then+ * scan ONE level of immediate children. Declarative markers do not produce a+ * framework, but they stop an upward walk and participate in child ambiguity.+ *+ * The child scan is not optional polish: `create-site`'s recommended target+ * location is "New folder in current directory", which puts the config in a+ * CHILD of the host session cwd that later hooks report. (The skill's+ * `cd "<PROJECT_ROOT>"` calls run in Bash-tool subshells and never move the host+ * cwd.) An upward-only walk would miss the most common layout on every+ * subsequent skill run, biasing the metric toward users who scaffolded in place.+ *+ * Why not call `findProjectRoot` directly: its child fallback returns the first+ * matching directory. Hook payloads do not identify which child a skill will+ * target, so a multi-site cwd is ambiguous and must report null. This detector+ * scans children once and counts both site types before attributing a framework.+ */+function findCodeSiteRoot(startDir) {+ let current = path.resolve(startDir);+ while (true) {+ const markerState = configMarkerState(current);+ if (markerState === MARKER_VALID) return current;+ if (markerState === MARKER_INVALID) return null;+ // A nearer declarative site is the project under work. Continuing upward+ // could incorrectly attribute an enclosing code site's framework.+ if (fs.existsSync(path.join(current, DECLARATIVE_MARKER))) return null;+ const parent = path.dirname(current);+ if (parent === current) break;+ current = parent;+ }++ // A first-hit helper is correct for project discovery but not telemetry+ // attribution. Count code and declarative children in one pass; exactly one+ // total site must exist, and it must be a code site.+ let childRoot = null;+ let siteCount = 0;+ try {+ for (const entry of fs.readdirSync(startDir, { withFileTypes: true })) {+ if (+ !entry.isDirectory() ||+ entry.name === "node_modules" ||+ entry.name === ".git"+ ) {+ continue;+ }+ const candidate = path.join(startDir, entry.name);+ const markerState = configMarkerState(candidate);+ const hasCodeMarker = markerState !== MARKER_ABSENT;+ const isDeclarativeSite = fs.existsSync(+ path.join(candidate, DECLARATIVE_MARKER)+ );+ if (!hasCodeMarker && !isDeclarativeSite) continue;+ siteCount += 1;+ if (siteCount > 1) return null;+ childRoot = markerState === MARKER_VALID ? candidate : null;+ }+ } catch {+ return null;+ }+ return childRoot;+}++/**+ * Resolves the framework of the Power Pages code site containing `startDir`.+ *+ * Known limitation: a site scaffolded into an unrelated absolute path ("Any+ * other directory") is unreachable from cwd and reports null.+ *+ * @param {string} startDir - Directory to resolve from (the hook's cwd).+ * @returns {"astro"|"angular"|"vue"|"react"|null} null when `startDir` is not+ * inside a Power Pages code site, or the framework is not recognized.+ */+function detectSiteFramework(startDir) {+ try {+ const dir = startDir || process.cwd();++ let projectRoot;+ try {+ projectRoot = findCodeSiteRoot(dir);+ } catch {+ projectRoot = null;+ }+ if (!projectRoot) return null;++ const pkg = readJson(path.join(projectRoot, "package.json"));+ if (!pkg || typeof pkg !== "object") return null;++ // DECLARED dependencies only — deliberately not resolved `node_modules`.+ // A site that was never `npm install`ed, or one whose deps are hoisted by a+ // workspace root, still lists its own direct framework dependency here.+ const deps = Object.assign(+ {},+ pkg.dependencies && typeof pkg.dependencies === "object" ? pkg.dependencies : null,+ pkg.devDependencies && typeof pkg.devDependencies === "object" ? pkg.devDependencies : null+ );++ const matches = FRAMEWORK_MARKERS.filter(([, marker]) => {+ if (!Object.prototype.hasOwnProperty.call(deps, marker)) return false;+ const declaredVersion = deps[marker];+ return (+ typeof declaredVersion === "string" && declaredVersion.trim().length > 0+ );+ }).map(([framework]) => framework);+ if (matches.includes("astro")) return "astro";+ return matches.length === 1 ? matches[0] : null;+ } catch {+ // Fail closed — an unexpected fs/permission error must not surface to the+ // hook, which would silently downgrade the run to "no telemetry event".+ return null;+ }+}++module.exports = { detectSiteFramework, FRAMEWORK_MARKERS };diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.js b/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.jsindex 0ec329005..38113ebd9 100644--- a/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.js+++ b/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.js@@ -51,6 +51,12 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {trackedSkills,telemetryDir,sessionId, // primed from Claude Code's hook payload (parsed.session_id)+ // Optional plugin-supplied dynamic payload merged into `eventInfo` below.+ // Accepts a plain object, or a thunk returning one. Prefer the thunk: it is+ // invoked only after the slash-command / `disabled` / `isProvisioned` gates+ // below, so a plugin whose payload costs real work (filesystem probing, etc.)+ // pays nothing on untracked prompts or a disabled plugin.+ eventInfo,_emit, // test seam; defaults to fireAndForget_readPacAuth, // test seam; defaults to lib/pac-auth_readAgentInfo, // test seam; defaults to lib/agent-info@@ -122,7 +128,29 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {};if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;- if (pacAuth && pacAuth.objectId) fields.eventInfo = { aadObjectId: pacAuth.objectId };+ // `eventInfo` is assembled from two INDEPENDENT sources and assigned only when+ // non-empty. Building it inside the objectId guard instead would drop the+ // caller's payload on every unauthenticated run (`pac auth who` surfaces no+ // object id), and any later `fields.eventInfo.x = ...` would throw on the+ // undefined — a throw the fail-closed wrapper swallows, silently degrading the+ // run to no event at all. The caller owns not putting PII in its payload;+ // `aadObjectId` is written last so the library's own field always wins.+ const mergedEventInfo = {};+ let callerEventInfo = eventInfo;+ if (typeof callerEventInfo === "function") {+ try {+ callerEventInfo = callerEventInfo();+ } catch {+ // A caller thunk threw — drop its contribution rather than lose the whole+ // event. The library's own fields below are unaffected.+ callerEventInfo = null;+ }+ }+ if (callerEventInfo && typeof callerEventInfo === "object" && !Array.isArray(callerEventInfo)) {+ Object.assign(mergedEventInfo, callerEventInfo);+ }+ if (pacAuth && pacAuth.objectId) mergedEventInfo.aadObjectId = pacAuth.objectId;+ if (Object.keys(mergedEventInfo).length > 0) fields.eventInfo = mergedEventInfo;if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.jsindex 073b7cfd0..bf92b8a38 100644--- a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js+++ b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js@@ -11,7 +11,10 @@ function dataDisclosure(plugin) {const pluginSpecific =plugin === "power-pages"? " Power Pages can also record the signed-in user's Entra object ID as\n" +- " eventInfo.aadObjectId when PAC exposes it.\n"+ " 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": plugin === "model-apps"? " Model Apps excludes the signed-in user's Entra object ID.\n": "";diff --git a/plugins/power-pages/scripts/tests/detect-site-framework.test.js b/plugins/power-pages/scripts/tests/detect-site-framework.test.jsnew file mode 100644index 000000000..143948ada--- /dev/null+++ b/plugins/power-pages/scripts/tests/detect-site-framework.test.js@@ -0,0 +1,243 @@+"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 { detectSiteFramework } = require("../lib/detect-site-framework");+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");++function mkTmp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-fw-"));+}++// Builds a Power Pages code site on disk: the `powerpages.config.json` marker+// plus a package.json carrying `deps` as its dependencies.+function mkSite(root, deps, { config = true, pkg = true } = {}) {+ fs.mkdirSync(root, { recursive: true });+ if (config) {+ fs.writeFileSync(+ path.join(root, "powerpages.config.json"),+ JSON.stringify({ siteName: "Test Site", compiledPath: "dist" })+ );+ }+ if (pkg) {+ fs.writeFileSync(+ path.join(root, "package.json"),+ JSON.stringify({ name: "test-site", private: true, dependencies: deps })+ );+ }+ return root;+}++test("detects each supported framework from its scaffold dependencies", () => {+ const cases = [+ ["react", { react: "^19.0.0", "@vitejs/plugin-react": "^4.3.0" }],+ ["vue", { vue: "^3.5.0", "@vitejs/plugin-vue": "^5.2.0" }],+ ["angular", { "@angular/core": "^19.1.0", "@angular/router": "^19.1.0", rxjs: "~7.8.0" }],+ ["astro", { astro: "^7.1.0" }],+ ];+ for (const [expected, deps] of cases) {+ const root = mkSite(path.join(mkTmp(), "site"), deps);+ assert.equal(detectSiteFramework(root), expected, `expected ${expected}`);+ }+});++test("detects every shipped create-site scaffold manifest", () => {+ for (const expected of ["react", "vue", "angular", "astro"]) {+ const root = path.join(mkTmp(), "site");+ fs.mkdirSync(root, { recursive: true });+ fs.writeFileSync(path.join(root, "powerpages.config.json"), "{}");+ fs.copyFileSync(+ path.join(+ PLUGIN_ROOT,+ "skills",+ "create-site",+ "assets",+ expected,+ "package.json"+ ),+ path.join(root, "package.json")+ );+ assert.equal(detectSiteFramework(root), expected, `expected ${expected}`);+ }+});++test("detects framework declared only in devDependencies", () => {+ const root = path.join(mkTmp(), "site");+ fs.mkdirSync(root, { recursive: true });+ fs.writeFileSync(path.join(root, "powerpages.config.json"), "{}");+ fs.writeFileSync(+ path.join(root, "package.json"),+ JSON.stringify({ devDependencies: { "@vitejs/plugin-vue": "^5.2.0" } })+ );+ assert.equal(detectSiteFramework(root), "vue");+});++test("finds a site in a CHILD of cwd — the recommended create-site layout", () => {+ // Regression guard for the dominant real-world case: create-site's recommended+ // "New folder in current directory" option puts powerpages.config.json one+ // level BELOW the host session cwd, and the skill's `cd <PROJECT_ROOT>` runs in+ // a Bash subshell that never moves that cwd. An upward-only root walk reports+ // null here and silently under-reports the metric for most users.+ const parent = mkTmp();+ mkSite(path.join(parent, "contoso-portal"), {+ react: "^19.0.0",+ "@vitejs/plugin-react": "^4.3.0",+ });+ assert.equal(detectSiteFramework(parent), "react");+});++test("returns null when cwd contains multiple child sites", () => {+ // Hook payloads identify only cwd, not which child a skill will target. The+ // filesystem's first directory entry is not a safe attribution signal.+ const parent = mkTmp();+ mkSite(path.join(parent, "react-portal"), { react: "^19.0.0" });+ mkSite(path.join(parent, "vue-portal"), { "@vitejs/plugin-vue": "^5.2.0" });+ assert.equal(detectSiteFramework(parent), null);+});++test("returns null when child workspace mixes code and declarative sites", () => {+ const parent = mkTmp();+ mkSite(path.join(parent, "react-portal"), {+ react: "^19.0.0",+ "@vitejs/plugin-react": "^4.3.0",+ });+ fs.mkdirSync(+ path.join(parent, "declarative-portal", ".powerpages-site", ".portalconfig"),+ { recursive: true }+ );+ assert.equal(detectSiteFramework(parent), null);+});++test("returns null inside a declarative site nested under a code site", () => {+ const codeRoot = mkSite(path.join(mkTmp(), "code-site"), {+ react: "^19.0.0",+ "@vitejs/plugin-react": "^4.3.0",+ });+ const declarativeRoot = path.join(codeRoot, "declarative-site");+ const nested = path.join(declarativeRoot, ".powerpages-site", ".portalconfig");+ fs.mkdirSync(nested, { recursive: true });+ assert.equal(detectSiteFramework(nested), null);+});++test("detects a code child that also contains a declarative marker", () => {+ const parent = mkTmp();+ const site = mkSite(path.join(parent, "react-portal"), {+ react: "^19.0.0",+ "@vitejs/plugin-react": "^4.3.0",+ });+ fs.mkdirSync(path.join(site, ".powerpages-site"), { recursive: true });+ assert.equal(detectSiteFramework(parent), "react");+});++test("walks up from a nested directory inside the site", () => {+ const root = mkSite(path.join(mkTmp(), "site"), { astro: "^7.1.0" });+ const nested = path.join(root, "src", "pages", "deep");+ fs.mkdirSync(nested, { recursive: true });+ assert.equal(detectSiteFramework(nested), "astro");+});++test("prefers astro over a React integration dependency in the same site", () => {+ // An Astro site may declare @astrojs/react + react for island components; it is+ // still an Astro site. Marker order in detect-site-framework.js encodes this.+ const root = mkSite(path.join(mkTmp(), "site"), {+ astro: "^7.1.0",+ "@astrojs/react": "^4.0.0",+ react: "^19.0.0",+ "@vitejs/plugin-react": "^4.3.0",+ });+ assert.equal(detectSiteFramework(root), "astro");+});++test("uses scaffold tooling when a React site also consumes Vue", () => {+ const root = mkSite(path.join(mkTmp(), "site"), {+ react: "^19.0.0",+ "@vitejs/plugin-react": "^4.3.0",+ vue: "^3.5.0",+ });+ assert.equal(detectSiteFramework(root), "react");+});++test("returns null when non-Astro scaffold markers conflict", () => {+ const root = mkSite(path.join(mkTmp(), "site"), {+ react: "^19.0.0",+ vue: "^3.5.0",+ "@vitejs/plugin-react": "^4.3.0",+ "@vitejs/plugin-vue": "^5.2.0",+ });+ assert.equal(detectSiteFramework(root), null);+});++test("returns null for a project that is not a Power Pages code site", () => {+ // package.json present, powerpages.config.json absent — an unrelated repo the+ // user happens to be sitting in must not pollute the framework metric.+ const root = mkSite(path.join(mkTmp(), "not-a-site"), { react: "^19.0.0" }, { config: false });+ assert.equal(detectSiteFramework(root), null);+});++test("returns null for a declarative .powerpages-site/ project", () => {+ // findProjectRoot also matches .powerpages-site/ (design-studio sites via+ // `pac pages download`). Those have no SPA framework, so they must not fall+ // through to a package.json probe.+ const root = path.join(mkTmp(), "declarative");+ fs.mkdirSync(path.join(root, ".powerpages-site", ".portalconfig"), { recursive: true });+ fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ dependencies: { react: "^19.0.0" } }));+ assert.equal(detectSiteFramework(root), null);+});++test("returns null when the site has no package.json", () => {+ const root = mkSite(path.join(mkTmp(), "site"), null, { pkg: false });+ assert.equal(detectSiteFramework(root), null);+});++test("returns null when package.json is malformed", () => {+ const root = path.join(mkTmp(), "site");+ fs.mkdirSync(root, { recursive: true });+ fs.writeFileSync(path.join(root, "powerpages.config.json"), "{}");+ fs.writeFileSync(path.join(root, "package.json"), "{ not valid json");+ assert.equal(detectSiteFramework(root), null);+});++test("returns null when powerpages.config.json is malformed", () => {+ const root = mkSite(path.join(mkTmp(), "site"), {+ "@vitejs/plugin-react": "^4.3.0",+ });+ fs.writeFileSync(path.join(root, "powerpages.config.json"), "{ not valid json");+ assert.equal(detectSiteFramework(root), null);+});++test("returns null when powerpages.config.json is a directory", () => {+ const root = mkSite(+ path.join(mkTmp(), "site"),+ { "@vitejs/plugin-react": "^4.3.0" },+ { config: false }+ );+ fs.mkdirSync(path.join(root, "powerpages.config.json"));+ assert.equal(detectSiteFramework(root), null);+});++test("returns null when framework dependency values are not non-empty strings", () => {+ for (const invalid of [null, "", " ", false, 0, {}]) {+ const root = mkSite(path.join(mkTmp(), "site"), {+ "@vitejs/plugin-react": invalid,+ });+ assert.equal(+ detectSiteFramework(root),+ null,+ `expected ${JSON.stringify(invalid)} to be rejected`+ );+ }+});++test("returns null when no recognized framework dependency is present", () => {+ // Includes the AngularJS 1.x trap: `angular` is NOT the Angular marker.+ const root = mkSite(path.join(mkTmp(), "site"), { angular: "^1.8.0", lodash: "^4.0.0" });+ assert.equal(detectSiteFramework(root), null);+});++test("returns null instead of throwing for a nonexistent directory", () => {+ assert.equal(detectSiteFramework(path.join(mkTmp(), "does-not-exist")), null);+});diff --git a/plugins/power-pages/scripts/tests/run-user-prompt-telemetry.test.js b/plugins/power-pages/scripts/tests/run-user-prompt-telemetry.test.jsindex 4314bff59..c106a4eb2 100644--- a/plugins/power-pages/scripts/tests/run-user-prompt-telemetry.test.js+++ b/plugins/power-pages/scripts/tests/run-user-prompt-telemetry.test.js@@ -17,9 +17,9 @@ function mkConfigDir() {return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-upt-"));}-function runHook({ prompt, configDir, fakeProbe, ikeyPath }) {+function runHook({ prompt, configDir, fakeProbe, ikeyPath, cwd, extraEnv = {} }) {return spawnSync(process.execPath, [HOOK], {- input: JSON.stringify({ prompt }),+ input: JSON.stringify(cwd ? { prompt, cwd } : { prompt }),encoding: "utf8",env: {...process.env,@@ -29,6 +29,7 @@ function runHook({ prompt, configDir, fakeProbe, ikeyPath }) {// Clear the workflow-wide opt-out backstop (set in power-pages-script-tests.yml)// so the emit-detection test still exercises the real path to its probe.POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",+ ...extraEnv,},// The enabled path shells out to `pac auth who` + `pac --version`, each// capped at 8s (see lib/pac-auth.js). The hook's documented budget is ~30s;@@ -38,6 +39,24 @@ function runHook({ prompt, configDir, fakeProbe, ikeyPath }) {});}+function writeDetectorFailurePreload(configDir) {+ const preload = path.join(configDir, "fail-detector-load.cjs");+ fs.writeFileSync(+ preload,+ `"use strict";+const Module = require("node:module");+const originalLoad = Module._load;+Module._load = function(request, parent, isMain) {+ if (typeof request === "string" && request.endsWith("detect-site-framework")) {+ throw new Error("injected optional detector load failure");+ }+ return originalLoad.call(this, request, parent, isMain);+};+`+ );+ return preload;+}+// Synchronous sleep that parks the thread instead of busy-spinning the CPU.function sleep(ms) {Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);@@ -53,12 +72,11 @@ function waitForFile(filePath, timeoutMs) {return fs.existsSync(filePath);}-test("hook emits PagesAIPluginEvent with top-level fields for tracked slash command", () => {- const configDir = mkConfigDir();- const probePath = path.join(configDir, "probe.json");- // Point the hook at a temp ikey.json via the override seam instead of- // mutating the checked-in scripts/lib/telemetry/ikey.json (which would race- // with other test files running in parallel).+// Writes an isolated, provisioned telemetry config into configDir (temp+// ikey.json + a resolver.js sibling — the dispatcher discovers region routing by+// that convention) so emission runs against an example.invalid key instead of+// the checked-in prod config. Returns the ikey path.+function writeProvisionedConfig(configDir) {const ikeyPath = path.join(configDir, "ikey.json");fs.writeFileSync(ikeyPath,@@ -88,6 +106,31 @@ test("hook emits PagesAIPluginEvent with top-level fields for tracked slash commpath.join(configDir, "resolver.js"),`module.exports = require(${JSON.stringify(shippedResolver)});\n`);+ return ikeyPath;+}++// Materializes a Power Pages code site (config marker + package.json) so the+// framework detector has something to find from the hook's reported cwd.+function mkSite(deps) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-site-"));+ fs.writeFileSync(+ path.join(root, "powerpages.config.json"),+ JSON.stringify({ siteName: "Test Site", compiledPath: "dist" })+ );+ fs.writeFileSync(+ path.join(root, "package.json"),+ JSON.stringify({ name: "test-site", dependencies: deps })+ );+ return root;+}++test("hook emits PagesAIPluginEvent with top-level fields for tracked slash command", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ // Point the hook at a temp ikey.json via the override seam instead of+ // mutating the checked-in scripts/lib/telemetry/ikey.json (which would race+ // with other test files running in parallel).+ const ikeyPath = writeProvisionedConfig(configDir);const { status } = runHook({prompt: "/power-pages:add-seo",@@ -116,6 +159,85 @@ test("hook emits PagesAIPluginEvent with top-level fields for tracked slash commassert.match(body.data.nodeVersion, /^v\d+$/);});+test("hook reports the site framework in eventInfo from the payload cwd", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);++ const { status } = runHook({+ prompt: "/power-pages:add-seo",+ configDir,+ fakeProbe: probePath,+ ikeyPath,+ cwd: mkSite({+ vue: "^3.5.0",+ "vue-router": "^4.5.0",+ "@vitejs/plugin-vue": "^5.2.0",+ }),+ });+ assert.equal(status, 0);+ assert.ok(waitForFile(probePath, 5_000), "dispatcher should have written probe");+ const body = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ // eventInfo is JSON-stringified for the wire (the tenant-side field mapping+ // flattens data.<key> and doesn't recurse) — see emit-dispatcher buildEnvelope.+ assert.equal(typeof body.data.eventInfo, "string");+ const eventInfo = JSON.parse(body.data.eventInfo);+ // Asserted WITHOUT requiring aadObjectId: `framework` must survive whether or+ // not `pac auth who` surfaces an object id (it won't on a CI runner with no+ // pac / no signed-in user). Regression guard against rebuilding eventInfo+ // inside the objectId guard, which would drop the framework on every+ // unauthenticated run.+ assert.equal(eventInfo.framework, "vue");+});++test("hook omits framework when cwd is not a Power Pages code site", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);++ const { status } = runHook({+ prompt: "/power-pages:add-seo",+ configDir,+ fakeProbe: probePath,+ ikeyPath,+ cwd: fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-nosite-")),+ });+ assert.equal(status, 0);+ assert.ok(waitForFile(probePath, 5_000), "dispatcher should have written probe");+ const body = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ const eventInfo =+ typeof body.data.eventInfo === "string" ? JSON.parse(body.data.eventInfo) : {};+ assert.ok(+ !("framework" in eventInfo),+ "no framework key should be emitted outside a Power Pages code site"+ );+});++test("hook emits and exits 0 when optional detector fails to load", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);+ const preload = writeDetectorFailurePreload(configDir);++ const { status, stdout, stderr } = runHook({+ prompt: "/power-pages:add-seo",+ configDir,+ fakeProbe: probePath,+ ikeyPath,+ cwd: mkSite({ react: "^19.0.0", "@vitejs/plugin-react": "^4.3.0" }),+ extraEnv: { NODE_OPTIONS: `--require=${preload}` },+ });+ assert.equal(status, 0);+ assert.equal(stdout, "");+ assert.equal(stderr, "");+ assert.ok(waitForFile(probePath, 5_000), "dispatcher should still emit the event");+ const body = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ assert.equal(body.data.eventName, "skill_started");+ const eventInfo =+ typeof body.data.eventInfo === "string" ? JSON.parse(body.data.eventInfo) : {};+ assert.ok(!("framework" in eventInfo));+});+test("hook exits 0 and emits nothing for an unrelated prompt", () => {const configDir = mkConfigDir();const probePath = path.join(configDir, "probe.json");diff --git a/plugins/power-pages/scripts/tests/telemetry-hook-pretool.test.js b/plugins/power-pages/scripts/tests/telemetry-hook-pretool.test.jsindex efd940575..1fcf56d62 100644--- a/plugins/power-pages/scripts/tests/telemetry-hook-pretool.test.js+++ b/plugins/power-pages/scripts/tests/telemetry-hook-pretool.test.js@@ -14,7 +14,7 @@ function mkConfigDir() {return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-ph-"));}-function runHook({ input, configDir, ikeyPath, fakeProbe }) {+function runHook({ input, configDir, ikeyPath, fakeProbe, extraEnv = {} }) {return spawnSync(process.execPath, [HOOK], {input,encoding: "utf8",@@ -29,6 +29,7 @@ function runHook({ input, configDir, ikeyPath, fakeProbe }) {// Without it, the provisioned path (checked-in ikey.json ships enabled +// a real key) would POST a fake event to prod telemetry on every CI run.POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",+ ...extraEnv,},// The provisioned path shells out to `pac auth who` + `pac --version`, each// capped at 8s (see lib/pac-auth.js). Match the hook's ~30s budget so the@@ -37,6 +38,24 @@ function runHook({ input, configDir, ikeyPath, fakeProbe }) {});}+function writeDetectorFailurePreload(configDir) {+ const preload = path.join(configDir, "fail-detector-load.cjs");+ fs.writeFileSync(+ preload,+ `"use strict";+const Module = require("node:module");+const originalLoad = Module._load;+Module._load = function(request, parent, isMain) {+ if (typeof request === "string" && request.endsWith("detect-site-framework")) {+ throw new Error("injected optional detector load failure");+ }+ return originalLoad.call(this, request, parent, isMain);+};+`+ );+ return preload;+}+// Synchronous sleep that parks the thread instead of busy-spinning the CPU.function sleep(ms) {Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);@@ -123,6 +142,167 @@ test("exits 0 and emits skill_started to probe when skill is tracked (provisioneassert.equal(body.data.skillName, "create-site");});+// Materializes a Power Pages code site (config marker + package.json) so the+// framework detector has something to find from the hook's reported cwd.+function mkSite(deps) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-site-"));+ fs.writeFileSync(+ path.join(root, "powerpages.config.json"),+ JSON.stringify({ siteName: "Test Site", compiledPath: "dist" })+ );+ fs.writeFileSync(+ path.join(root, "package.json"),+ JSON.stringify({ name: "test-site", dependencies: deps })+ );+ return root;+}++test("pretool hook reports the site framework in eventInfo from the payload cwd", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);++ const { status } = runHook({+ input: JSON.stringify({+ tool_input: { skill: "add-seo" },+ // Claude Code puts the host session's working directory on the hook+ // payload (same field run-skill-posttool-validation.js reads).+ cwd: mkSite({ "@angular/core": "^19.1.0", rxjs: "~7.8.0" }),+ }),+ configDir,+ ikeyPath,+ fakeProbe: probePath,+ });+ assert.equal(status, 0);+ assert.ok(waitForFile(probePath, 5_000), "dispatcher should have written probe");+ const body = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ // eventInfo is JSON-stringified for the wire (the tenant-side field mapping+ // flattens data.<key> and doesn't recurse) — see emit-dispatcher buildEnvelope.+ assert.equal(typeof body.data.eventInfo, "string");+ const eventInfo = JSON.parse(body.data.eventInfo);+ // Asserted WITHOUT requiring aadObjectId: `framework` must survive whether or+ // not `pac auth who` surfaces an object id (it won't on a CI runner with no+ // pac / no signed-in user). Regression guard against rebuilding eventInfo+ // inside the objectId guard, which would drop the framework on every+ // unauthenticated run.+ assert.equal(eventInfo.framework, "angular");+});++test("pretool hook finds a site in a CHILD of cwd (recommended create-site layout)", () => {+ // create-site's recommended target is "New folder in current directory", which+ // leaves powerpages.config.json one level BELOW the host cwd that later hooks+ // report. Guards the root-discovery path that makes the metric representative.+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);++ const parent = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-parent-"));+ const site = path.join(parent, "contoso-portal");+ fs.mkdirSync(site);+ fs.writeFileSync(path.join(site, "powerpages.config.json"), "{}");+ fs.writeFileSync(+ path.join(site, "package.json"),+ JSON.stringify({+ dependencies: { react: "^19.0.0" },+ devDependencies: { "@vitejs/plugin-react": "^4.3.0" },+ })+ );++ const { status } = runHook({+ input: JSON.stringify({ tool_input: { skill: "add-seo" }, cwd: parent }),+ configDir,+ ikeyPath,+ fakeProbe: probePath,+ });+ assert.equal(status, 0);+ assert.ok(waitForFile(probePath, 5_000), "dispatcher should have written probe");+ const body = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ assert.equal(JSON.parse(body.data.eventInfo).framework, "react");+});++test("pretool hook emits without framework when cwd has multiple child sites", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);+ const parent = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-multisite-"));++ for (const [name, dependencies] of [+ ["react-portal", { react: "^19.0.0" }],+ ["vue-portal", { vue: "^3.5.0", "@vitejs/plugin-vue": "^5.2.0" }],+ ]) {+ const site = path.join(parent, name);+ fs.mkdirSync(site);+ fs.writeFileSync(path.join(site, "powerpages.config.json"), "{}");+ fs.writeFileSync(path.join(site, "package.json"), JSON.stringify({ dependencies }));+ }++ const { status } = runHook({+ input: JSON.stringify({ tool_input: { skill: "add-seo" }, cwd: parent }),+ configDir,+ ikeyPath,+ fakeProbe: probePath,+ });+ assert.equal(status, 0);+ assert.ok(waitForFile(probePath, 5_000), "dispatcher should still emit the event");+ const body = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ const eventInfo =+ typeof body.data.eventInfo === "string" ? JSON.parse(body.data.eventInfo) : {};+ assert.ok(!("framework" in eventInfo), "ambiguous child sites must omit framework");+ assert.equal(body.data.eventName, "skill_started");+});++test("pretool hook emits and exits 0 when optional detector fails to load", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);+ const preload = writeDetectorFailurePreload(configDir);++ const { status, stdout, stderr } = runHook({+ input: JSON.stringify({+ tool_input: { skill: "add-seo" },+ cwd: mkSite({ react: "^19.0.0", "@vitejs/plugin-react": "^4.3.0" }),+ }),+ configDir,+ ikeyPath,+ fakeProbe: probePath,+ extraEnv: { NODE_OPTIONS: `--require=${preload}` },+ });+ assert.equal(status, 0);+ assert.equal(stdout, "");+ assert.equal(stderr, "");+ assert.ok(waitForFile(probePath, 5_000), "dispatcher should still emit the event");+ const body = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ assert.equal(body.data.eventName, "skill_started");+ const eventInfo =+ typeof body.data.eventInfo === "string" ? JSON.parse(body.data.eventInfo) : {};+ assert.ok(!("framework" in eventInfo));+});++test("pretool hook omits framework when cwd is not a Power Pages code site", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ const ikeyPath = writeProvisionedConfig(configDir);++ const { status } = runHook({+ input: JSON.stringify({+ tool_input: { skill: "add-seo" },+ cwd: fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-nosite-")),+ }),+ configDir,+ ikeyPath,+ fakeProbe: probePath,+ });+ assert.equal(status, 0);+ assert.ok(waitForFile(probePath, 5_000), "dispatcher should have written probe");+ const body = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ const eventInfo =+ typeof body.data.eventInfo === "string" ? JSON.parse(body.data.eventInfo) : {};+ assert.ok(+ !("framework" in eventInfo),+ "no framework key should be emitted outside a Power Pages code site"+ );+});+test("pretool hook exits 0 when ikey.json has regions but default_region entry has no key", () => {// Point the hook at a temp ikey.json via the override seam instead of// mutating the checked-in scripts/lib/telemetry/ikey.json (which would racediff --git a/plugins/power-pages/scripts/tests/telemetry-lib-copy.test.js b/plugins/power-pages/scripts/tests/telemetry-lib-copy.test.jsnew file mode 100644index 000000000..4cab9638c--- /dev/null+++ b/plugins/power-pages/scripts/tests/telemetry-lib-copy.test.js@@ -0,0 +1,176 @@+"use strict";++// Guards the plugin's BUNDLED copy of the shared telemetry library.+//+// `plugins/power-pages/scripts/lib/telemetry/lib` is a physical copy of+// `shared/telemetry/lib` (not a symlink — some Windows checkouts and plugin+// hosts materialize symlinks as plain link files, which breaks hook-time+// require()). Nothing else in CI compares the two: `shared/telemetry/tests` has+// no workflow, and validate-legacy-compatibility.js only mirrors the marketplace+// manifests. So an author who edits the shared source and forgets to refresh the+// copy gets a green build while the plugin ships stale code.+//+// This suite runs in power-pages-script-tests.yml, so it turns that silent drift+// into a CI failure — and additionally exercises the copy's behavior directly,+// since the shared suite that normally covers it never runs in CI.++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 PLUGIN_LIB = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry", "lib");+// Repo root is three levels above the plugin (plugins/power-pages -> plugins -> repo).+const SHARED_LIB = path.resolve(PLUGIN_ROOT, "..", "..", "shared", "telemetry", "lib");++test("bundled telemetry lib is byte-identical to shared/telemetry/lib", (t) => {+ // A marketplace install copies only the plugin directory, so `shared/` is+ // absent there. Skip rather than fail — the check is meaningful only in a+ // full repo checkout, which is what CI runs.+ if (!fs.existsSync(SHARED_LIB)) {+ t.skip("shared/telemetry/lib not present (installed plugin, not a repo checkout)");+ return;+ }++ const sharedFiles = fs.readdirSync(SHARED_LIB).filter((f) => f.endsWith(".js")).sort();+ const pluginFiles = fs.readdirSync(PLUGIN_LIB).filter((f) => f.endsWith(".js")).sort();+ assert.deepEqual(+ pluginFiles,+ sharedFiles,+ "plugin copy and shared source must contain the same modules — refresh the copy"+ );++ const drifted = sharedFiles.filter(+ (f) =>+ fs.readFileSync(path.join(SHARED_LIB, f), "utf8") !==+ fs.readFileSync(path.join(PLUGIN_LIB, f), "utf8")+ );+ assert.deepEqual(+ drifted,+ [],+ "bundled copy has drifted from shared/telemetry/lib — re-copy these files"+ );+});++test("bundled telemetry CLI discloses the Power Pages framework field", () => {+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-disclosure-"));+ const result = spawnSync(+ process.execPath,+ [+ path.join(PLUGIN_LIB, "telemetry-config.js"),+ "--action",+ "status",+ "--plugin",+ "power-pages",+ ],+ {+ encoding: "utf8",+ env: {+ ...process.env,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",+ },+ }+ );+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stdout, /eventInfo\.framework/);+ assert.match(result.stdout, /react, vue, angular, or astro/);+ assert.match(result.stdout, /never a site name or path/);+});++// --- Behavior of the bundled copy -------------------------------------------+// The hook tests cover the happy path end-to-end; these pin the defensive+// branches of the caller-supplied `eventInfo` seam, which otherwise live only in+// the never-run shared suite.++const { emitSkillStartedFromPrompt } = require(path.join(PLUGIN_LIB, "emit-from-prompt"));++// Minimal provisioned telemetry dir: ikey.json plus the resolver.js sibling the+// generic isProvisioned gate discovers by convention.+function mkTelemetryDir() {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-copy-"));+ fs.writeFileSync(+ path.join(tmp, "ikey.json"),+ 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(tmp, "resolver.js"),+ "module.exports = {" ++ "async resolve() { return null; }," ++ "isProvisioned(cfg) {" ++ " const e = cfg && cfg.regions && cfg.regions[(cfg && cfg.default_region) || 'us'];" ++ " return !!(e && e.instrumentation_key);" ++ "} };"+ );+ return tmp;+}++function emit({ eventInfo, objectId }) {+ const captured = {};+ const result = emitSkillStartedFromPrompt("/power-pages:add-seo", {+ pluginName: "power-pages",+ pluginVersion: "1.2.3",+ trackedSkills: { "add-seo": {} },+ telemetryDir: mkTelemetryDir(),+ eventInfo,+ _emit: (event) => {+ captured.event = event;+ },+ _readPacAuth: () => (objectId ? { objectId } : null),+ _readAgentInfo: () => ({}),+ });+ return { result, data: captured.event && captured.event.data };+}++test("bundled copy keeps caller eventInfo when no Entra objectId is present", () => {+ // Regression guard: building eventInfo inside the objectId guard would drop+ // `framework` on every unauthenticated run.+ const { data } = emit({ eventInfo: { framework: "react" } });+ assert.deepEqual(data.eventInfo, { framework: "react" });+});++test("bundled copy merges caller eventInfo with aadObjectId", () => {+ const { data } = emit({+ eventInfo: { framework: "vue" },+ objectId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",+ });+ assert.deepEqual(data.eventInfo, {+ framework: "vue",+ aadObjectId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",+ });+});++test("bundled copy drops a throwing eventInfo thunk without losing the event", () => {+ const { result, data } = emit({+ eventInfo: () => {+ throw new Error("boom");+ },+ objectId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",+ });+ assert.equal(result.emitted, true);+ assert.deepEqual(data.eventInfo, { aadObjectId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" });+});++test("bundled copy ignores non-object eventInfo values", () => {+ for (const bad of ["react", 42, true, ["react"]]) {+ const { data } = emit({ eventInfo: bad });+ assert.equal(+ data.eventInfo,+ undefined,+ `non-object eventInfo (${JSON.stringify(bad)}) must be dropped`+ );+ }+});diff --git a/plugins/power-pages/skills/telemetry/telemetry-workflow.md b/plugins/power-pages/skills/telemetry/telemetry-workflow.mdindex 7183c52e2..74416e61c 100644--- a/plugins/power-pages/skills/telemetry/telemetry-workflow.md+++ b/plugins/power-pages/skills/telemetry/telemetry-workflow.md@@ -24,7 +24,10 @@ telemetry for this plugin. Default to `status` when no argument is given.and correlation IDs, and Dataverse organization and Entra tenant GUIDs when PACis signed in.Power Pages can also include the signed-in user's Entra object ID as- `eventInfo.aadObjectId` when PAC exposes it; Model Apps excludes it.+ `eventInfo.aadObjectId` when PAC exposes it, and the SPA framework of the+ Power 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.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.diff --git a/shared/telemetry/README.md b/shared/telemetry/README.mdindex 854294e15..817ee20a5 100644--- a/shared/telemetry/README.md+++ b/shared/telemetry/README.md@@ -92,9 +92,18 @@ Every event carries a fixed allowlist enforced by `lib/events.js`. Field names m**Per-event:**- `skillName` (on every event)-- `eventInfo` — caller-supplied JSON object (dynamic Kusto column). Power Pages populates it with `aadObjectId`, the signed-in user's stable Entra ID / AAD directory object ID parsed from `pac auth who`, when available. The field is omitted when `pac auth who` does not surface an object ID. On the wire it is sent as a JSON **string** (re-serialized by `emit-dispatcher.js`, not the local mirror) because the tenant-side field mapping flattens `data.<key>` to a single `data_<key>` leaf and does not recurse into nested objects. The Kusto side must `parse_json()` / `todynamic()` it back into a dynamic value.+- `eventInfo` — caller-supplied JSON object (dynamic Kusto column). Power Pages populates it with:- `FIELD_TYPES` enforces only that `eventInfo` is a structured JSON value; it does **not** enforce nested keys. Callers **MUST** restrict it to the documented schema. The only approved nested field is currently Power Pages `aadObjectId` as a string. Callers **MUST NOT** add other personal data, prompts, project or site identifiers, paths, URLs, credentials, or arbitrary caller payloads. Any proposed expansion requires review and approval, plus updates to this privacy disclosure, the documented event schema, and tests before code emits the new field.+ - `aadObjectId` — the signed-in user's stable Entra ID / AAD directory object ID, parsed from `pac auth who`, when available. Omitted when `pac auth who` does not surface an object ID.+ - `framework` — the SPA framework of the Power Pages **code site** the skill is running against, drawn from the closed set `react`, `vue`, `angular`, `astro`. Omitted unless the working directory resolves to a site with a `powerpages.config.json`.++ Each key is omitted independently when its source is unavailable; `eventInfo` itself is omitted only when every key would be absent.++ On the wire it is sent as a JSON **string** (re-serialized by `emit-dispatcher.js`, not the local mirror) because the tenant-side field mapping flattens `data.<key>` to a single `data_<key>` leaf and does not recurse into nested objects. The Kusto side must `parse_json()` / `todynamic()` it back into a dynamic value.++ `FIELD_TYPES` enforces only that `eventInfo` is a structured JSON value; it does **not** enforce nested keys. Callers **MUST** restrict it to the documented schema. The approved nested fields are currently Power Pages `aadObjectId` (string) and `framework` (string, restricted to the closed set above — it describes the scaffold a site was built from, is shared by every site built from that scaffold, and therefore identifies no user, project, or site). Callers **MUST NOT** add other personal data, prompts, project or site identifiers, paths, URLs, credentials, or arbitrary caller payloads. Any proposed expansion requires review and approval, plus updates to this privacy disclosure, the documented event schema, and tests before code emits the new field.++ `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.## What is NEVER sentdiff --git a/shared/telemetry/lib/emit-from-prompt.js b/shared/telemetry/lib/emit-from-prompt.jsindex 0ec329005..38113ebd9 100644--- a/shared/telemetry/lib/emit-from-prompt.js+++ b/shared/telemetry/lib/emit-from-prompt.js@@ -51,6 +51,12 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {trackedSkills,telemetryDir,sessionId, // primed from Claude Code's hook payload (parsed.session_id)+ // Optional plugin-supplied dynamic payload merged into `eventInfo` below.+ // Accepts a plain object, or a thunk returning one. Prefer the thunk: it is+ // invoked only after the slash-command / `disabled` / `isProvisioned` gates+ // below, so a plugin whose payload costs real work (filesystem probing, etc.)+ // pays nothing on untracked prompts or a disabled plugin.+ eventInfo,_emit, // test seam; defaults to fireAndForget_readPacAuth, // test seam; defaults to lib/pac-auth_readAgentInfo, // test seam; defaults to lib/agent-info@@ -122,7 +128,29 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {};if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;- if (pacAuth && pacAuth.objectId) fields.eventInfo = { aadObjectId: pacAuth.objectId };+ // `eventInfo` is assembled from two INDEPENDENT sources and assigned only when+ // non-empty. Building it inside the objectId guard instead would drop the+ // caller's payload on every unauthenticated run (`pac auth who` surfaces no+ // object id), and any later `fields.eventInfo.x = ...` would throw on the+ // undefined — a throw the fail-closed wrapper swallows, silently degrading the+ // run to no event at all. The caller owns not putting PII in its payload;+ // `aadObjectId` is written last so the library's own field always wins.+ const mergedEventInfo = {};+ let callerEventInfo = eventInfo;+ if (typeof callerEventInfo === "function") {+ try {+ callerEventInfo = callerEventInfo();+ } catch {+ // A caller thunk threw — drop its contribution rather than lose the whole+ // event. The library's own fields below are unaffected.+ callerEventInfo = null;+ }+ }+ if (callerEventInfo && typeof callerEventInfo === "object" && !Array.isArray(callerEventInfo)) {+ Object.assign(mergedEventInfo, callerEventInfo);+ }+ if (pacAuth && pacAuth.objectId) mergedEventInfo.aadObjectId = pacAuth.objectId;+ if (Object.keys(mergedEventInfo).length > 0) fields.eventInfo = mergedEventInfo;if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;diff --git a/shared/telemetry/lib/telemetry-config.js b/shared/telemetry/lib/telemetry-config.jsindex 073b7cfd0..bf92b8a38 100644--- a/shared/telemetry/lib/telemetry-config.js+++ b/shared/telemetry/lib/telemetry-config.js@@ -11,7 +11,10 @@ function dataDisclosure(plugin) {const pluginSpecific =plugin === "power-pages"? " Power Pages can also record the signed-in user's Entra object ID as\n" +- " eventInfo.aadObjectId when PAC exposes it.\n"+ " 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": plugin === "model-apps"? " Model Apps excludes the signed-in user's Entra object ID.\n": "";diff --git a/shared/telemetry/tests/emit-from-prompt.test.js b/shared/telemetry/tests/emit-from-prompt.test.jsindex 1afd0a4f0..434d42a05 100644--- a/shared/telemetry/tests/emit-from-prompt.test.js+++ b/shared/telemetry/tests/emit-from-prompt.test.js@@ -35,12 +35,13 @@ function mkTelemetryDir({ instrumentationKey, collectorUrl, eventStreamName, disconst TRACKED = { "add-seo": {}, "create-site": {} };-function callWithStub({ promptText, telemetryDir, captured, pacAuth, agentInfo }) {+function callWithStub({ promptText, telemetryDir, captured, pacAuth, agentInfo, eventInfo }) {return emitSkillStartedFromPrompt(promptText, {pluginName: "power-pages",pluginVersion: "1.2.3",trackedSkills: TRACKED,telemetryDir,+ eventInfo,_emit: (event, spawnOpts) => {captured.event = event;captured.spawnOpts = spawnOpts;@@ -183,6 +184,148 @@ test("omits eventInfo when the Entra objectId is absent", () => {assert.equal(captured.event.data.eventInfo, undefined);});+test("merges a caller-supplied eventInfo object alongside aadObjectId", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ pacAuth: { objectId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" },+ eventInfo: { framework: "react" },+ });+ assert.deepEqual(captured.event.data.eventInfo, {+ framework: "react",+ aadObjectId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",+ });+});++test("keeps a caller-supplied eventInfo when the Entra objectId is absent", () => {+ // The caller's payload is INDEPENDENT of AAD identity. Assembling eventInfo+ // inside the objectId guard would silently drop it on every unauthenticated+ // run — the exact regression this guards.+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ pacAuth: null,+ eventInfo: { framework: "astro" },+ });+ assert.deepEqual(captured.event.data.eventInfo, { framework: "astro" });+});++test("resolves a caller-supplied eventInfo thunk", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ eventInfo: () => ({ framework: "vue" }),+ });+ assert.deepEqual(captured.event.data.eventInfo, { framework: "vue" });+});++test("does not invoke the eventInfo thunk for an untracked prompt", () => {+ // The thunk exists so plugins can defer real work (filesystem probing) until+ // after the slash-command / disabled / provisioned gates. If it ran eagerly,+ // every user keystroke-level prompt would pay that cost.+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ let calls = 0;+ callWithStub({+ promptText: "not a slash command",+ telemetryDir,+ captured: {},+ eventInfo: () => {+ calls += 1;+ return { framework: "react" };+ },+ });+ assert.equal(calls, 0);+});++test("does not invoke the eventInfo thunk when the plugin is disabled", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ disabled: true,+ });+ let calls = 0;+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured: {},+ eventInfo: () => {+ calls += 1;+ return { framework: "react" };+ },+ });+ assert.equal(calls, 0);+});++test("drops a throwing eventInfo thunk without losing the event", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ const result = callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ pacAuth: { objectId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" },+ eventInfo: () => {+ throw new Error("boom");+ },+ });+ assert.equal(result.emitted, true);+ assert.deepEqual(captured.event.data.eventInfo, {+ aadObjectId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",+ });+});++test("ignores non-object eventInfo values", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ for (const bad of ["react", 42, true, ["react"]]) {+ const captured = {};+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ eventInfo: bad,+ });+ assert.equal(+ captured.event.data.eventInfo,+ undefined,+ `non-object eventInfo (${JSON.stringify(bad)}) must be dropped`+ );+ }+});+test("populates aiAgentName/aiAgentVersion/pacCliVersion when agentInfo is present", () => {const telemetryDir = mkTelemetryDir({instrumentationKey: "x",diff --git a/shared/telemetry/tests/telemetry-config.test.js b/shared/telemetry/tests/telemetry-config.test.jsindex df7d65dd7..493b925bf 100644--- a/shared/telemetry/tests/telemetry-config.test.js+++ b/shared/telemetry/tests/telemetry-config.test.js@@ -32,6 +32,9 @@ test("off writes the per-plugin opt-out and confirms", () => {assert.match(stdout, /Dataverse organization and Entra tenant IDs/);assert.match(stdout, /eventInfo\.aadObjectId/);assert.match(stdout, /when PAC exposes it/);+ assert.match(stdout, /eventInfo\.framework/);+ assert.match(stdout, /react, vue, angular, or astro/);+ assert.match(stdout, /never a site name or path/);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/);@@ -74,6 +77,9 @@ test("status reports ON by default and never reads ikey.json", () => {assert.match(stdout, /Dataverse organization and Entra tenant IDs/);assert.match(stdout, /eventInfo\.aadObjectId/);assert.match(stdout, /when PAC exposes it/);+ assert.match(stdout, /eventInfo\.framework/);+ assert.match(stdout, /react, vue, angular, or astro/);+ assert.match(stdout, /never a site name or path/);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/);