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
1DS telemetry: region-aware routing via a per-plugin resolver contract (#190)
amitjoshi438ba8497e71eb1
diff --git a/AGENTS.md b/AGENTS.mdindex 99b19a876..e17089b83 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -69,6 +69,8 @@ This keeps the skill discoverable in each plugin while preserving install-time pEdit `shared/telemetry/` directly — the symlink makes changes live for every adopting plugin immediately; there is nothing to re-sync.+Per-plugin iKey/collector routing is pluggable via a `resolver.js` placed next to the plugin's `ikey.json` (implementing the `resolve`/`isProvisioned` contract); the shared library ships only that contract plus a static-key fallback, not any routing logic.+Current adopters: `power-pages`. Others adopt on demand.## Code Conventionsdiff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex 78f5fe917..7ce380da5 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -407,7 +407,8 @@ These patterns have caused repeated PR review feedback. Check for them before suThis plugin ships 1DS telemetry for skill-run and script-run signals. The shared library lives at the repo-root `shared/telemetry/`; `scripts/lib/telemetry/lib` is a **symlink** to `shared/telemetry/lib`, so the shared code is the live code. Zero npm dependencies — nothing to install.-- **`scripts/lib/telemetry/lib` is a symlink** to the repo-root `shared/telemetry/lib` — edit `shared/telemetry/lib/` directly; there is no copy to re-sync. The one real file under `scripts/lib/telemetry/` is `ikey.json` (this plugin's config). **Posture:** the committed `ikey.json` ships `disabled: true`; a working-tree `disabled: false` is a local experiment only — never commit it.+- **`scripts/lib/telemetry/lib` is a symlink** to the repo-root `shared/telemetry/lib` — edit `shared/telemetry/lib/` directly; there is no copy to re-sync. The real files under `scripts/lib/telemetry/` are `ikey.json` (this plugin's config) and `resolver.js` (the resolver contract implementation). **Posture:** the committed `ikey.json` ships `disabled: true`; a working-tree `disabled: false` is a local experiment only — never commit it.+- **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.- **Privacy posture:** anonymous telemetry is **default-on**. 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`.- **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.diff --git a/plugins/power-pages/hooks/hooks.json b/plugins/power-pages/hooks/hooks.jsonindex c4529f934..605e22b3a 100644--- a/plugins/power-pages/hooks/hooks.json+++ b/plugins/power-pages/hooks/hooks.json@@ -2,7 +2,7 @@"hooks": {"PreToolUse": [{- "matcher": "Skill",+ "matcher": "Skill|skill","hooks": [{"type": "command",@@ -14,7 +14,7 @@],"PostToolUse": [{- "matcher": "Skill",+ "matcher": "Skill|skill","hooks": [{"type": "command",diff --git a/plugins/power-pages/hooks/run-skill-pretool-telemetry.js b/plugins/power-pages/hooks/run-skill-pretool-telemetry.jsindex 576605fb2..128290bf9 100644--- a/plugins/power-pages/hooks/run-skill-pretool-telemetry.js+++ b/plugins/power-pages/hooks/run-skill-pretool-telemetry.js@@ -9,13 +9,14 @@ 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;+let emitSpawn, eventsLib, sessionLib, pacAuthLib, agentInfoLib, resolverLoader;try {emitSpawn = require(path.join(TELEMETRY_DIR, "lib", "emit-spawn"));eventsLib = require(path.join(TELEMETRY_DIR, "lib", "events"));sessionLib = require(path.join(TELEMETRY_DIR, "lib", "session"));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"));} catch {process.exit(0);}@@ -40,7 +41,7 @@ function readPluginVersion() {function readIkey() {// Test/override seam: POWER_PLATFORM_SKILLS_IKEY_JSON points at an alternate- // ikey.json so tests can flip disabled/iKey state without mutating the+ // ikey.json so tests can flip disabled/region state without mutating the// checked-in config file. Mirrors emit-dispatcher.js / emit-from-prompt.js.const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;const ikeyPath =@@ -49,17 +50,12 @@ function readIkey() {: path.join(TELEMETRY_DIR, "ikey.json");try {const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));- return {- ikey: cfg.instrumentationKey || "",- collectorUrl: cfg.collector_url || "",- eventStreamName: cfg.event_stream_name || "",- disabled: cfg.disabled === true,- };+ return { cfg, ikeyPath, eventStreamName: cfg.event_stream_name || "", disabled: cfg.disabled === true };} catch {- // ikey.json missing/unreadable → fail CLOSED (disabled: true), matching- // emit-dispatcher.js's isDisabledByConfig() so the kill switch can't be- // bypassed by a missing/corrupt config.- return { ikey: "", collectorUrl: "", eventStreamName: "", disabled: true };+ // ikey.json missing/unreadable → fail CLOSED (disabled: true), matching the+ // dispatcher's kill-switch semantics so a missing/corrupt config can't be+ // bypassed into an emit attempt.+ return { cfg: null, ikeyPath, eventStreamName: "", disabled: true };}}@@ -98,9 +94,21 @@ function readStdin() {// enriched event is still built and dispatched so the detached dispatcher can// write the local diagnostic mirror; it reads the per-plugin config and skips// the POST. (Opting out therefore costs the same as an enabled run.)- const { ikey, collectorUrl, eventStreamName, disabled } = readIkey();+ const { cfg, ikeyPath, eventStreamName, disabled } = readIkey();if (disabled) process.exit(0);- if (!ikey) process.exit(0);+ const resolver = resolverLoader.loadResolver(path.dirname(ikeyPath));+ let provisioned;+ try {+ provisioned =+ resolver && typeof resolver.isProvisioned === "function"+ ? resolver.isProvisioned(cfg)+ : !!(cfg && cfg.instrumentationKey);+ } catch {+ // A plugin resolver threw — treat as not provisioned so a bad resolver+ // can't crash the pretool hook and impact the tool run (fail closed).+ provisioned = false;+ }+ if (!provisioned) process.exit(0);const correlation_id = crypto.randomUUID();@@ -144,13 +152,14 @@ function readStdin() {emitSpawn.fireAndForget(eventsLib.buildSkillStarted(eventStreamName, fields),{- iKey: ikey,- collectorUrl,+ cloud: (pacAuth && pacAuth.cloud) || "",configDir,fakeProbe,- // Point the dispatcher at this plugin's real ikey.json (lib/ is shared,- // so its __dirname default would otherwise hit shared/'s placeholder).- ikeyJsonPath: path.join(TELEMETRY_DIR, "ikey.json"),+ // Point the dispatcher at the same ikey.json readIkey() used — the+ // override seam when set, otherwise this plugin's real config. (lib/ is+ // a symlink to shared/, so the dispatcher's __dirname default would+ // otherwise hit shared/'s placeholder.)+ ikeyJsonPath: ikeyPath,});} catch {diff --git a/plugins/power-pages/scripts/lib/telemetry/ikey.json b/plugins/power-pages/scripts/lib/telemetry/ikey.jsonindex fda9ae55d..eba9b9358 100644--- a/plugins/power-pages/scripts/lib/telemetry/ikey.json+++ b/plugins/power-pages/scripts/lib/telemetry/ikey.json@@ -1,6 +1,35 @@{- "instrumentationKey": "197418c5cb8c4426b201f9db2e87b914-87887378-2790-49b0-9295-51f43b6204b1-7172",- "collector_url": "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/","event_stream_name": "PagesAIPluginEvent",- "disabled": true+ "disabled": true,+ "default_region": "us",+ "regions": {+ "internal": {+ "instrumentation_key": "ffdb4c99ca3a4ad5b8e9ffb08bf7da0d-65357ff3-efcd-47fc-b2fd-ad95a52373f4-7402",+ "collector_url": "https://self.pipe.aria.int.microsoft.com/OneCollector/1.0/"+ },+ "us": {+ "instrumentation_key": "197418c5cb8c4426b201f9db2e87b914-87887378-2790-49b0-9295-51f43b6204b1-7172",+ "collector_url": "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/"+ },+ "eu": {+ "instrumentation_key": "197418c5cb8c4426b201f9db2e87b914-87887378-2790-49b0-9295-51f43b6204b1-7172",+ "collector_url": "https://eu-mobile.events.data.microsoft.com/OneCollector/1.0/"+ },+ "gov": {+ "instrumentation_key": "47d84c9b995341e19219d73ab0c6bcd2-e951660d-d17d-4de3-83c3-6a766bd23de8-7007",+ "collector_url": "https://tb.events.data.microsoft.com/OneCollector/1.0/"+ },+ "high": {+ "instrumentation_key": "4a07e143372c46aabf3841dc4f0ef795-a753031e-2005-4282-9451-a086fea4234a-6942",+ "collector_url": "https://tb.events.data.microsoft.com/OneCollector/1.0/"+ },+ "dod": {+ "instrumentation_key": "af47f3d608774379a53fa07cf36362ea-69701588-1aad-43ee-8b52-f71125849774-6656",+ "collector_url": "https://pf.events.data.microsoft.com/OneCollector/1.0/"+ },+ "mooncake": {+ "instrumentation_key": "f9b6e63b5e394453ba8f58f7a7b9aea7-f38fcfa2-eb34-48bc-9ae2-61fba4abbd39-7390",+ "collector_url": "https://collector.azure.cn/OneCollector/1.0/"+ }+ }}diff --git a/plugins/power-pages/scripts/lib/telemetry/region/artemis-service.js b/plugins/power-pages/scripts/lib/telemetry/region/artemis-service.jsnew file mode 100644index 000000000..29af804ce--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/region/artemis-service.js@@ -0,0 +1,98 @@+"use strict";++const https = require("node:https");++const TIMEOUT_MS = 5000;++function normalizeCloud(cloud) {+ const c = String(cloud || "").toLowerCase();+ // "usgov" is the token `pac auth who` actually emits for GCC (see+ // validation-helpers.js CLOUD_TO_API). The other spellings are defensive+ // aliases. Exact `===` matching means this can't shadow usgovhigh/usgovdod.+ if (c === "usgov" || c === "usgovgcc" || c === "gcc" || c === "gov") return "Gov";+ if (c === "usgovhigh" || c === "high") return "High";+ if (c === "usgovdod" || c === "dod") return "Dod";+ if (c === "china" || c === "mooncake" || c === "chinacloud") return "Mooncake";+ if (c === "tip1" || c === "tip2" || c === "test" || c === "preprod") return "Internal";+ return "Public";+}++function urlFor(orgId, cloud) {+ const noDashes = String(orgId || "").replace(/-/g, "");+ const stamp = normalizeCloud(cloud);+ if (stamp === "Public") {+ const domain = noDashes.slice(0, -2);+ const suffix = noDashes.slice(-2);+ return `https://${domain}.${suffix}.organization.api.powerplatform.com/gateway/cluster?api-version=1`;+ }+ const domain = noDashes.slice(0, -1);+ const suffix = noDashes.slice(-1);+ if (stamp === "Gov") {+ return `https://${domain}.${suffix}.organization.api.gov.powerplatform.microsoft.us/gateway/cluster?api-version=1`;+ }+ if (stamp === "High") {+ return `https://${domain}.${suffix}.organization.api.high.powerplatform.microsoft.us/gateway/cluster?api-version=1`;+ }+ if (stamp === "Dod") {+ return `https://${domain}.${suffix}.organization.api.appsplatform.us/gateway/cluster?api-version=1`;+ }+ if (stamp === "Mooncake") {+ return `https://${domain}.${suffix}.organization.api.powerplatform.partner.microsoftonline.cn/gateway/cluster?api-version=1`;+ }+ // Internal+ return `https://${domain}.${suffix}.organization.api.test.powerplatform.com/gateway/cluster?api-version=1`;+}++function defaultHttpsGet(url) {+ return new Promise((resolve, reject) => {+ let u;+ try {+ u = new URL(url);+ } catch (e) {+ reject(e);+ return;+ }+ const req = https.request(+ {+ hostname: u.hostname,+ path: u.pathname + (u.search || ""),+ method: "GET",+ },+ (res) => {+ let body = "";+ res.setEncoding("utf8");+ res.on("data", (c) => (body += c));+ res.on("end", () => resolve({ statusCode: res.statusCode, body }));+ }+ );+ req.on("error", reject);+ req.setTimeout(TIMEOUT_MS, () => {+ req.destroy(new Error("timeout"));+ });+ req.end();+ });+}++async function fetchGeo(orgId, cloud, opts = {}) {+ if (!orgId) return null;+ const url = urlFor(orgId, cloud);+ const httpsGet = typeof opts._httpsGet === "function" ? opts._httpsGet : defaultHttpsGet;+ let resp;+ try {+ resp = await httpsGet(url);+ } catch {+ return null;+ }+ if (!resp || typeof resp.statusCode !== "number") return null;+ if (resp.statusCode < 200 || resp.statusCode >= 300) return null;+ let body;+ try {+ body = JSON.parse(resp.body || "");+ } catch {+ return null;+ }+ if (!body || typeof body.geoName !== "string" || !body.geoName) return null;+ return { geoName: body.geoName, stamp: normalizeCloud(cloud) };+}++module.exports = { fetchGeo, urlFor, normalizeCloud, TIMEOUT_MS };diff --git a/plugins/power-pages/scripts/lib/telemetry/region/region-cache.js b/plugins/power-pages/scripts/lib/telemetry/region/region-cache.jsnew file mode 100644index 000000000..df378941d--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/region/region-cache.js@@ -0,0 +1,87 @@+"use strict";++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++const DIR_NAME = "region-cache";+const TTL_MS = 24 * 60 * 60 * 1000;++// orgId comes from `pac auth who` ("Organization Id") — a Dataverse org GUID.+// Validate the shape before using it as a filename: defensive against a+// malformed/spoofed value containing path separators (`/`, `\`, `..`), and it+// doubles as the falsy-orgId guard.+const ORG_ID_RE =+ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;++function defaultDir() {+ return path.join(os.homedir(), ".power-platform-skills");+}++function cacheDir(configDir) {+ return path.join(configDir || defaultDir(), DIR_NAME);+}++function entryFile(orgId, configDir) {+ return path.join(cacheDir(configDir), `${orgId}.json`);+}++// Returns the cached { region } for an org, or null when missing / unreadable /+// malformed / expired. Only the plugin-INDEPENDENT org→region mapping is cached;+// the caller maps region→iKey from its own regionsMap (so a cache shared across+// plugins can never hand one plugin another plugin's key).+function read(orgId, configDir) {+ if (!ORG_ID_RE.test(String(orgId || ""))) return null;+ let entry;+ try {+ entry = JSON.parse(fs.readFileSync(entryFile(orgId, configDir), "utf8"));+ } catch {+ return null;+ }+ if (+ !entry ||+ typeof entry.expiresAt !== "number" ||+ entry.expiresAt < Date.now()+ ) {+ return null;+ }+ return { region: entry.region };+}++// Per-process counter so concurrent writers never collide on the temp name.+let writeSeq = 0;++function write(orgId, entry, configDir) {+ if (!ORG_ID_RE.test(String(orgId || "")) || !entry || !entry.region) return;+ const dir = cacheDir(configDir);+ try {+ fs.mkdirSync(dir, { recursive: true });+ } catch {+ return;+ }+ const file = path.join(dir, `${orgId}.json`);+ const payload = JSON.stringify({+ region: entry.region,+ expiresAt: Date.now() + TTL_MS,+ });+ // Per-org file + atomic rename: each org owns its own file, so concurrent+ // detached dispatchers (one per skill invocation) writing DIFFERENT orgs can+ // never clobber each other — the shared read-modify-write is gone, and+ // same-org concurrent writes are idempotent (identical content). The temp name+ // is per-process so writers don't collide; rename is an atomic replace (incl.+ // Windows via MoveFileEx) so a reader never sees a torn/half-written file.+ const tmp = `${file}.tmp.${process.pid}.${writeSeq++}`;+ try {+ fs.writeFileSync(tmp, payload, "utf8");+ fs.renameSync(tmp, file);+ } catch {+ // fail closed: cache miss next time. Best-effort cleanup of the temp file.+ try {+ fs.unlinkSync(tmp);+ } catch {+ // temp may not have been created; ignore+ }+ }+}++module.exports = { read, write, TTL_MS };diff --git a/plugins/power-pages/scripts/lib/telemetry/region/region-resolver.js b/plugins/power-pages/scripts/lib/telemetry/region/region-resolver.jsnew file mode 100644index 000000000..81cdff74a--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/region/region-resolver.js@@ -0,0 +1,91 @@+"use strict";++const { fetchGeo: defaultFetchGeo, normalizeCloud } = require("./artemis-service");+const defaultCache = require("./region-cache");++// Public-cloud geoName values → routing region. Anything not listed falls+// through to defaultRegion. Sovereign clouds short-circuit via the stamp.+const PUBLIC_US_GEOS = new Set(["us", "br", "jp", "in", "au", "ca", "as", "za", "ae", "kr"]);+const PUBLIC_EU_GEOS = new Set(["eu", "uk", "de", "fr", "no", "ch"]);++// Derive the plugin-INDEPENDENT routing region from the org's cloud stamp + geo,+// or null when the public geo is unrecognized (caller falls back to its own+// defaultRegion). Only a non-null result is safe to cache: it's a property of+// the org, not of any plugin's config.+function deriveRegion(cloud, geoName) {+ const stamp = normalizeCloud(cloud);+ if (stamp === "Gov") return "gov";+ if (stamp === "High") return "high";+ if (stamp === "Dod") return "dod";+ if (stamp === "Mooncake") return "mooncake";+ if (stamp === "Internal") return "internal";+ // stamp === "Public"+ const g = String(geoName || "").toLowerCase();+ if (PUBLIC_US_GEOS.has(g)) return "us";+ if (PUBLIC_EU_GEOS.has(g)) return "eu";+ return null;+}++function mapToRegion(cloud, geoName, defaultRegion) {+ return deriveRegion(cloud, geoName) || defaultRegion;+}++function entryFromMap(regionsMap, region) {+ const e = regionsMap && regionsMap[region];+ if (!e || !e.instrumentation_key) return null;+ return {+ region,+ iKey: e.instrumentation_key,+ collectorUrl: e.collector_url || "",+ };+}++async function resolve({+ orgId,+ cloud,+ regionsMap,+ defaultRegion,+ configDir,+ _fetchGeo,+ _cache,+}) {+ const cache = _cache || defaultCache;+ const fetchGeo = typeof _fetchGeo === "function" ? _fetchGeo : defaultFetchGeo;+ const fallback = entryFromMap(regionsMap, defaultRegion);++ if (!orgId) return fallback;++ // Cache holds only the plugin-independent org→region mapping; map it to THIS+ // plugin's iKey/collector from regionsMap on every hit, so a cache shared+ // across plugins can never hand one plugin another plugin's key.+ const cached = cache.read(orgId, configDir);+ if (cached && cached.region) {+ return entryFromMap(regionsMap, cached.region) || fallback;+ }++ let artemis;+ try {+ artemis = await fetchGeo(orgId, cloud);+ } catch {+ artemis = null;+ }+ if (!artemis) return fallback;++ // Only a region DERIVED from a recognized geo/stamp is plugin-independent and+ // cacheable; an unrecognized geo falls back to this plugin's defaultRegion,+ // which must NOT be cached (another plugin's default may differ).+ const derived = deriveRegion(cloud, artemis.geoName);+ const region = derived || defaultRegion;+ const entry = entryFromMap(regionsMap, region) || fallback;+ if (!entry) return null;+ if (derived) {+ try {+ cache.write(orgId, { region: derived }, configDir);+ } catch {+ // swallow+ }+ }+ return entry;+}++module.exports = { resolve, mapToRegion };diff --git a/plugins/power-pages/scripts/lib/telemetry/resolver.js b/plugins/power-pages/scripts/lib/telemetry/resolver.jsnew file mode 100644index 000000000..e2b9b9fdb--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/resolver.js@@ -0,0 +1,27 @@+"use strict";++// Power-pages telemetry resolver: region routing via Artemis geo + cloud stamp.+// Implements the shared dispatcher's resolver contract. All artemis/region code+// lives in ./region/ — shared/telemetry knows nothing about it.+const { resolve: resolveRegion } = require("./region/region-resolver");++// Resolve the destination iKey/collector for THIS event's org region.+async function resolve({ event, cfg, cloud, configDir }) {+ return resolveRegion({+ orgId: (event && event.data && event.data.orgId) || "",+ cloud,+ regionsMap: (cfg && cfg.regions) || {},+ defaultRegion: (cfg && cfg.default_region) || "us",+ configDir,+ });+}++// Sync fast-gate: is the default region's key configured? Lets the hooks skip+// the ~3-5s pac shellout when the plugin isn't provisioned yet.+function isProvisioned(cfg) {+ const dr = (cfg && cfg.default_region) || "us";+ const entry = cfg && cfg.regions && cfg.regions[dr];+ return !!(entry && entry.instrumentation_key);+}++module.exports = { resolve, isProvisioned };diff --git a/plugins/power-pages/scripts/tests/artemis-service.test.js b/plugins/power-pages/scripts/tests/artemis-service.test.jsnew file mode 100644index 000000000..d0bb1ba76--- /dev/null+++ b/plugins/power-pages/scripts/tests/artemis-service.test.js@@ -0,0 +1,118 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");++const { fetchGeo, urlFor } = require("../lib/telemetry/region/artemis-service");++const orgId = "c7809087-d9b8-4a00-a78a-a4b901caa23f";++test("urlFor builds the Public template (two-char suffix)", () => {+ const u = urlFor(orgId, "Public");+ assert.match(u, /^https:\/\/c7809087d9b84a00a78aa4b901caa2\.3f\.organization\.api\.powerplatform\.com\/gateway\/cluster\?api-version=1$/);+});++test("urlFor builds the Gov template (single-char suffix, gov host)", () => {+ const u = urlFor(orgId, "Gov");+ assert.match(u, /^https:\/\/c7809087d9b84a00a78aa4b901caa23\.f\.organization\.api\.gov\.powerplatform\.microsoft\.us\/gateway\/cluster\?api-version=1$/);+});++test("urlFor builds the Gov template for the real PAC token 'UsGov' (GCC)", () => {+ const u = urlFor(orgId, "UsGov");+ assert.match(u, /api\.gov\.powerplatform\.microsoft\.us/);+ assert.doesNotMatch(u, /api\.powerplatform\.com\b/);+});++test("urlFor builds the High template", () => {+ const u = urlFor(orgId, "High");+ assert.match(u, /api\.high\.powerplatform\.microsoft\.us/);+});++test("urlFor builds the Dod template", () => {+ const u = urlFor(orgId, "Dod");+ assert.match(u, /api\.appsplatform\.us/);+});++test("urlFor builds the Mooncake template", () => {+ const u = urlFor(orgId, "Mooncake");+ assert.match(u, /powerplatform\.partner\.microsoftonline\.cn/);+});++test("urlFor builds the Internal template", () => {+ const u = urlFor(orgId, "Tip1");+ assert.match(u, /api\.test\.powerplatform\.com/);+});++test("urlFor falls back to Public when cloud is unknown or empty", () => {+ const u = urlFor(orgId, "WhoKnows");+ assert.match(u, /api\.powerplatform\.com\b/);+ assert.doesNotMatch(u, /\.gov\.|\.high\.|\.appsplatform\.|\.cn\b|\.test\./);+});++test("fetchGeo returns null when _httpsGet rejects", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () => Promise.reject(new Error("network down")),+ });+ assert.equal(result, null);+});++test("fetchGeo returns null on non-2xx status", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () => Promise.resolve({ statusCode: 404, body: "" }),+ });+ assert.equal(result, null);+});++test("fetchGeo returns null on malformed JSON", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () => Promise.resolve({ statusCode: 200, body: "<<<<<" }),+ });+ assert.equal(result, null);+});++test("fetchGeo returns null when body has no geoName", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () =>+ Promise.resolve({ statusCode: 200, body: JSON.stringify({ environment: "x" }) }),+ });+ assert.equal(result, null);+});++test("fetchGeo returns { geoName, stamp } on success", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () =>+ Promise.resolve({+ statusCode: 200,+ body: JSON.stringify({+ geoName: "us",+ environment: "prod",+ clusterNumber: 7,+ }),+ }),+ });+ assert.equal(result.geoName, "us");+ assert.equal(result.stamp, "Public");+});++test("fetchGeo uses the cloud-specific URL", async () => {+ let capturedUrl;+ await fetchGeo(orgId, "Mooncake", {+ _httpsGet: (u) => {+ capturedUrl = u;+ return Promise.resolve({+ statusCode: 200,+ body: JSON.stringify({ geoName: "cn", environment: "prod" }),+ });+ },+ });+ assert.match(capturedUrl, /\.partner\.microsoftonline\.cn/);+});++test("fetchGeo returns null when orgId is falsy (no HTTP call made)", async () => {+ let called = false;+ const fakeGet = () => { called = true; return Promise.resolve({ statusCode: 200, body: "{}" }); };+ assert.equal(await fetchGeo("", "Public", { _httpsGet: fakeGet }), null);+ assert.equal(await fetchGeo(null, "Public", { _httpsGet: fakeGet }), null);+ assert.equal(await fetchGeo(undefined, "Public", { _httpsGet: fakeGet }), null);+ assert.equal(called, false);+});diff --git a/plugins/power-pages/scripts/tests/region-cache.test.js b/plugins/power-pages/scripts/tests/region-cache.test.jsnew file mode 100644index 000000000..db469efc2--- /dev/null+++ b/plugins/power-pages/scripts/tests/region-cache.test.js@@ -0,0 +1,134 @@+"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 { read, write, TTL_MS } = require("../lib/telemetry/region/region-cache");++function mkTmp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-rc-"));+}++// Path of an org's per-org cache file under a config dir.+function entryPath(tmp, orgId) {+ return path.join(tmp, "region-cache", `${orgId}.json`);+}++// Write a raw entry file directly (for malformed/expired fixtures).+function writeRaw(tmp, orgId, contents) {+ fs.mkdirSync(path.join(tmp, "region-cache"), { recursive: true });+ fs.writeFileSync(entryPath(tmp, orgId), contents);+}++const orgIdA = "11111111-1111-1111-1111-111111111111";+const orgIdB = "22222222-2222-2222-2222-222222222222";+const entryUS = { region: "us" };+const entryEU = { region: "eu" };++test("read returns null when file does not exist", () => {+ const tmp = mkTmp();+ assert.equal(read(orgIdA, tmp), null);+});++test("write then read returns the region for the same orgId", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ assert.equal(read(orgIdA, tmp).region, "us");+});++test("cache stores only the region (no iKey/collectorUrl)", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ const onDisk = JSON.parse(fs.readFileSync(entryPath(tmp, orgIdA), "utf8"));+ assert.deepEqual(Object.keys(onDisk).sort(), ["expiresAt", "region"]);+});++test("read returns null for an orgId that was never written", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ assert.equal(read(orgIdB, tmp), null);+});++test("multiple orgIds coexist as separate files", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ write(orgIdB, entryEU, tmp);+ assert.equal(read(orgIdA, tmp).region, "us");+ assert.equal(read(orgIdB, tmp).region, "eu");+ assert.ok(fs.existsSync(entryPath(tmp, orgIdA)));+ assert.ok(fs.existsSync(entryPath(tmp, orgIdB)));+});++test("read returns null when entry is expired", () => {+ const tmp = mkTmp();+ writeRaw(+ tmp,+ orgIdA,+ JSON.stringify({ region: "us", expiresAt: Date.now() - 1000 })+ );+ assert.equal(read(orgIdA, tmp), null);+});++test("read returns null when JSON is malformed", () => {+ const tmp = mkTmp();+ writeRaw(tmp, orgIdA, "not json {");+ assert.equal(read(orgIdA, tmp), null);+});++test("write swallows disk errors (target dir unwritable)", () => {+ const notADir = path.join(os.tmpdir(), "ppskills-not-a-dir-" + Date.now());+ fs.writeFileSync(notADir, "");+ assert.doesNotThrow(() => write(orgIdA, entryUS, notADir));+});++test("write is atomic: leaves no temp files and produces complete per-org files", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ write(orgIdB, entryEU, tmp);+ const leftover = fs+ .readdirSync(path.join(tmp, "region-cache"))+ .filter((f) => f.includes(".tmp."));+ assert.deepEqual(leftover, [], "atomic write must not leave .tmp files behind");+ assert.equal(+ JSON.parse(fs.readFileSync(entryPath(tmp, orgIdA), "utf8")).region,+ "us"+ );+ assert.equal(+ JSON.parse(fs.readFileSync(entryPath(tmp, orgIdB), "utf8")).region,+ "eu"+ );+});++test("read returns null when orgId is falsy", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ assert.equal(read("", tmp), null);+ assert.equal(read(null, tmp), null);+ assert.equal(read(undefined, tmp), null);+});++test("non-GUID orgId is rejected (no read, no write, no path traversal)", () => {+ const tmp = mkTmp();+ // Write attempt with a traversal-style id must be a no-op.+ assert.doesNotThrow(() => write("../evil", entryUS, tmp));+ assert.equal(read("../evil", tmp), null);+ // Nothing should have been created outside the (uncreated) cache dir.+ assert.equal(fs.existsSync(path.join(tmp, "region-cache")), false);+});++test("write is a silent no-op when orgId or entry is falsy", () => {+ const tmp = mkTmp();+ assert.doesNotThrow(() => write("", entryUS, tmp));+ assert.doesNotThrow(() => write(orgIdA, null, tmp));+ assert.doesNotThrow(() => write(orgIdA, undefined, tmp));+ assert.doesNotThrow(() => write(orgIdA, {}, tmp)); // entry with no region+ // No cache dir/file should exist after no-op writes.+ assert.equal(fs.existsSync(path.join(tmp, "region-cache")), false);+});++test("TTL_MS is exported as 24 hours", () => {+ assert.equal(TTL_MS, 24 * 60 * 60 * 1000);+});diff --git a/plugins/power-pages/scripts/tests/region-resolver.test.js b/plugins/power-pages/scripts/tests/region-resolver.test.jsnew file mode 100644index 000000000..94a1fd74c--- /dev/null+++ b/plugins/power-pages/scripts/tests/region-resolver.test.js@@ -0,0 +1,220 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");++const { resolve, mapToRegion } = require("../lib/telemetry/region/region-resolver");++const REGIONS = {+ internal: { instrumentation_key: "ik-int", collector_url: "https://int/" },+ us: { instrumentation_key: "ik-us", collector_url: "https://us/" },+ eu: { instrumentation_key: "ik-eu", collector_url: "https://eu/" },+ gov: { instrumentation_key: "ik-gov", collector_url: "https://gov/" },+ high: { instrumentation_key: "ik-hi", collector_url: "https://hi/" },+ dod: { instrumentation_key: "ik-dod", collector_url: "https://dod/" },+ mooncake: { instrumentation_key: "ik-mc", collector_url: "https://mc/" },+};++const noopCache = {+ read: () => null,+ write: () => {},+};++test("mapToRegion: Public + us → us", () => {+ assert.equal(mapToRegion("Public", "us", "us"), "us");+});++test("mapToRegion: Public + eu → eu", () => {+ assert.equal(mapToRegion("Public", "eu", "us"), "eu");+});++test("mapToRegion: Public + in (Asia-Pacific) → us", () => {+ assert.equal(mapToRegion("Public", "in", "us"), "us");+});++test("mapToRegion: Public + uk → eu", () => {+ assert.equal(mapToRegion("Public", "uk", "us"), "eu");+});++test("mapToRegion: Public + unknown geo → default", () => {+ assert.equal(mapToRegion("Public", "mars", "us"), "us");+});++test("mapToRegion: Gov → gov (geo ignored)", () => {+ assert.equal(mapToRegion("Gov", "us", "us"), "gov");+});++test("mapToRegion: UsGov (real PAC GCC token) → gov (geo ignored)", () => {+ assert.equal(mapToRegion("UsGov", "us", "us"), "gov");+});++test("mapToRegion: UsGovHigh → high (geo ignored)", () => {+ assert.equal(mapToRegion("UsGovHigh", "anything", "us"), "high");+});++test("mapToRegion: Dod → dod", () => {+ assert.equal(mapToRegion("Dod", "us", "us"), "dod");+});++test("mapToRegion: China → mooncake", () => {+ assert.equal(mapToRegion("China", "cn", "us"), "mooncake");+});++test("mapToRegion: Tip1 → internal", () => {+ assert.equal(mapToRegion("Tip1", "us", "us"), "internal");+});++test("mapToRegion: empty cloud → treated as Public", () => {+ assert.equal(mapToRegion("", "eu", "us"), "eu");+});++test("resolve: no orgId → default region without calling Artemis or cache", async () => {+ let cacheReadCalled = false;+ let fetchCalled = false;+ const result = await resolve({+ orgId: "",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => { fetchCalled = true; return Promise.resolve({ geoName: "us", stamp: "Public" }); },+ _cache: { read: () => { cacheReadCalled = true; return null; }, write: () => {} },+ });+ assert.equal(result.region, "us");+ assert.equal(result.iKey, "ik-us");+ assert.equal(result.collectorUrl, "https://us/");+ assert.equal(fetchCalled, false);+ assert.equal(cacheReadCalled, false);+});++test("resolve: cache hit maps the cached region to THIS plugin's iKey (not a cached key)", async () => {+ let fetchCalled = false;+ // Cache holds region only. The iKey must come from regionsMap, never the cache —+ // this is what stops a shared cache from misrouting one plugin's events to+ // another plugin's collector.+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => { fetchCalled = true; return Promise.resolve(null); },+ _cache: { read: () => ({ region: "eu" }), write: () => {} },+ });+ assert.equal(result.region, "eu");+ assert.equal(result.iKey, "ik-eu");+ assert.equal(result.collectorUrl, "https://eu/");+ assert.equal(fetchCalled, false);+});++test("resolve: cache hit on a region missing from regionsMap → falls back to default", async () => {+ const partial = { us: REGIONS.us };+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: partial,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve(null),+ _cache: { read: () => ({ region: "eu" }), write: () => {} },+ });+ assert.equal(result.region, "us"); // default fallback, since partial has no eu+});++test("resolve: cache miss + Artemis success → region-only cache write", async () => {+ let written;+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "eu", stamp: "Public" }),+ _cache: {+ read: () => null,+ write: (orgId, entry) => { written = { orgId, entry }; },+ },+ });+ assert.equal(result.region, "eu");+ assert.equal(result.iKey, "ik-eu");+ // Only the plugin-independent region is persisted — no iKey/collectorUrl.+ assert.deepEqual(written.entry, { region: "eu" });+});++test("resolve: unrecognized geo (falls back to defaultRegion) is NOT cached", async () => {+ let writeCalled = false;+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "eu",+ _fetchGeo: () => Promise.resolve({ geoName: "mars", stamp: "Public" }),+ _cache: { read: () => null, write: () => { writeCalled = true; } },+ });+ assert.equal(result.region, "eu"); // defaultRegion+ assert.equal(writeCalled, false, "a per-plugin default fallback must not be cached");+});++test("resolve: cache miss + Artemis null → default region, no cache write", async () => {+ let writeCalled = false;+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve(null),+ _cache: {+ read: () => null,+ write: () => { writeCalled = true; },+ },+ });+ assert.equal(result.region, "us");+ assert.equal(result.iKey, "ik-us");+ assert.equal(writeCalled, false);+});++test("resolve: regions map missing the resolved key → falls back to default", async () => {+ const partial = { us: REGIONS.us };+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Gov",+ regionsMap: partial,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "us", stamp: "Gov" }),+ _cache: noopCache,+ });+ assert.equal(result.region, "us");+});++test("resolve: regions map missing default too → returns null", async () => {+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: {},+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "us", stamp: "Public" }),+ _cache: noopCache,+ });+ assert.equal(result, null);+});++test("resolve: empty cloud + Artemis returns us → us region", async () => {+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "us", stamp: "Public" }),+ _cache: noopCache,+ });+ assert.equal(result.region, "us");+});++test("resolve: Mooncake cloud + ignored geo → mooncake region", async () => {+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Mooncake",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "cn", stamp: "Mooncake" }),+ _cache: noopCache,+ });+ assert.equal(result.region, "mooncake");+ assert.equal(result.iKey, "ik-mc");+});diff --git a/plugins/power-pages/scripts/tests/resolver.test.js b/plugins/power-pages/scripts/tests/resolver.test.jsnew file mode 100644index 000000000..4a2d21b15--- /dev/null+++ b/plugins/power-pages/scripts/tests/resolver.test.js@@ -0,0 +1,35 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");++const resolver = require("../lib/telemetry/resolver");++const REGIONS = {+ us: { instrumentation_key: "ikeyus", collector_url: "https://us.invalid/" },+ eu: { instrumentation_key: "ikeyeu", collector_url: "https://eu.invalid/" },+};++test("isProvisioned is true when the default region has a key", () => {+ assert.equal(resolver.isProvisioned({ default_region: "us", regions: REGIONS }), true);+});++test("isProvisioned is false when the default-region key is missing", () => {+ assert.equal(+ resolver.isProvisioned({ default_region: "us", regions: { us: { collector_url: "x" } } }),+ false+ );+ assert.equal(resolver.isProvisioned({}), false);+ assert.equal(resolver.isProvisioned(null), false);+});++test("resolve falls back to the default region with no orgId (no network)", async () => {+ const r = await resolver.resolve({+ event: { data: {} },+ cfg: { default_region: "us", regions: REGIONS },+ cloud: "Public",+ configDir: undefined,+ });+ assert.equal(r.iKey, "ikeyus");+ assert.equal(r.collectorUrl, "https://us.invalid/");+});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 42682b1d2..b47ff60a8 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@@ -10,10 +10,10 @@ const { spawnSync } = require("node:child_process");const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");const HOOK = path.join(PLUGIN_ROOT, "hooks", "run-user-prompt-telemetry.js");-// The live telemetry gates are the per-plugin opt-out in config.json and the-// `disabled` flag in ikey.json — no consent file is read. So this just needs-// to hand back an isolated tmpdir for the probe / ikey override.function mkConfigDir() {+ // An isolated config dir. Emission is NOT gated by any telemetry.json here —+ // the per-plugin opt-out is a config.json with telemetry[plugin] = "off"+ // (see user-config.js); tests that need opt-out write that file explicitly.return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-upt-"));}@@ -60,12 +60,31 @@ test("hook emits PagesPluginEvent with top-level fields for tracked slash commanfs.writeFileSync(ikeyPath,JSON.stringify({- instrumentationKey: "test-ikey-32-chars-minimum-aaaaaaaaaaaaaa",- collector_url: "https://example.invalid/OneCollector/1.0/",event_stream_name: "PagesPluginEvent",disabled: false,+ default_region: "us",+ regions: {+ us: {+ instrumentation_key: "test-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collector_url: "https://example.invalid/OneCollector/1.0/",+ },+ },}));+ // The dispatcher discovers region routing via a resolver.js next to ikey.json.+ // Mirror the shipped plugin layout by dropping one beside the temp config that+ // re-exports the real region resolver from scripts/lib/telemetry/resolver.js.+ 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`+ );const { status } = runHook({prompt: "/power-pages:add-seo",diff --git a/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.js b/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.jsindex 9b11dc080..2a1b85535 100644--- a/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.js+++ b/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.js@@ -34,12 +34,3 @@ test("posttool hook exits 0 with no tracked skill (preserves existing behavior)"});assert.equal(status, 0);});--test("posttool hook exits 0 when env opt-out is set (no emit, validator still runs)", () => {- const { status } = runHook({- input: JSON.stringify({ tool_input: { skill: "create-site" } }),- configDir: mkConfigDir(),- off: true,- });- assert.equal(status, 0);-});diff --git a/plugins/power-pages/scripts/tests/telemetry-hook-pretool.test.js b/plugins/power-pages/scripts/tests/telemetry-hook-pretool.test.jsindex ed64ea750..6377f956f 100644--- a/plugins/power-pages/scripts/tests/telemetry-hook-pretool.test.js+++ b/plugins/power-pages/scripts/tests/telemetry-hook-pretool.test.js@@ -7,49 +7,25 @@ const os = require("node:os");const path = require("node:path");const { spawnSync } = require("node:child_process");-const HOOK = path.resolve(- __dirname,- "../../hooks/run-skill-pretool-telemetry.js"-);+const PLUGIN_ROOT = path.resolve(__dirname, "../..");+const HOOK = path.join(PLUGIN_ROOT, "hooks", "run-skill-pretool-telemetry.js");function mkConfigDir() {return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-ph-"));}-function runHook({ input, configDir, off, fakeProbe, ikeyPath }) {- // Opt-out is a per-plugin config.json in the config dir (env var removed).- if (off) {- fs.writeFileSync(- path.join(configDir, "config.json"),- JSON.stringify({ telemetry: { "power-pages": "off" } })- );- }+function runHook({ input, configDir, ikeyPath }) {return spawnSync(process.execPath, [HOOK], {input,encoding: "utf8",env: {...process.env,POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,- POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || "",},- timeout: 30_000,});}-// 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);-}--function waitForFile(filePath, timeoutMs) {- const deadline = Date.now() + timeoutMs;- while (!fs.existsSync(filePath) && Date.now() < deadline) {- sleep(25);- }- return fs.existsSync(filePath);-}-test("exits 0 and emits nothing when tool_input has no tracked skill", () => {const { status } = runHook({input: JSON.stringify({ tool_input: { skill: "other-plugin:foo" } }),@@ -58,38 +34,6 @@ test("exits 0 and emits nothing when tool_input has no tracked skill", () => {assert.equal(status, 0);});-test("config opt-out still writes the local mirror but does NOT POST", () => {- // A per-plugin config opt-out suppresses transmission only. With an enabled- // ikey.json (via the override seam) + a fake-https probe + the opt-out set, the- // hook builds and dispatches the event; the dispatcher writes events.jsonl and- // skips the POST.- const configDir = mkConfigDir();- const probePath = path.join(configDir, "probe.json");- const ikeyPath = path.join(configDir, "ikey.json");- fs.writeFileSync(- ikeyPath,- JSON.stringify({- instrumentationKey: "test-ikey-32-chars-minimum-aaaaaaaaaaaaaa",- collector_url: "https://example.invalid/OneCollector/1.0/",- event_stream_name: "PagesPluginEvent",- disabled: false,- })- );- const { status } = runHook({- input: JSON.stringify({ tool_input: { skill: "create-site" } }),- configDir,- fakeProbe: probePath,- ikeyPath,- off: true,- });- assert.equal(status, 0);- assert.ok(- waitForFile(path.join(configDir, "events.jsonl"), 5_000),- "opt-out must still write the local mirror"- );- assert.ok(!fs.existsSync(probePath), "opt-out must skip the POST");-});-test("exits 0 when malformed stdin", () => {const { status } = runHook({ input: "{not json", configDir: mkConfigDir() });assert.equal(status, 0);@@ -103,46 +47,41 @@ test("exits 0 when skill is tracked (placeholder iKey → no-op emit)", () => {assert.equal(status, 0);});-test("emits skill_started for a tracked skill when pointed at an enabled ikey.json via the override seam", () => {- // Exercises the enabled emit path without mutating the checked-in ikey.json:- // the hook's readIkey() honors POWER_PLATFORM_SKILLS_IKEY_JSON.+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 race+ // with other test files running in parallel and leave the repo dirty on+ // interrupt).const configDir = mkConfigDir();- const probePath = path.join(configDir, "probe.json");const ikeyPath = path.join(configDir, "ikey.json");fs.writeFileSync(ikeyPath,JSON.stringify({- instrumentationKey: "test-ikey-32-chars-minimum-aaaaaaaaaaaaaa",- collector_url: "https://example.invalid/OneCollector/1.0/",event_stream_name: "PagesPluginEvent",disabled: false,+ default_region: "us",+ regions: { us: { collector_url: "https://x" } },}));+ // Mirror the shipped layout: a resolver.js beside ikey.json so the region+ // isProvisioned() gate actually runs (default_region 'us' has a collector but+ // no instrumentation_key → not provisioned → exit 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`+ );const { status } = runHook({- input: JSON.stringify({ tool_input: { skill: "create-site" } }),+ input: JSON.stringify({ tool_input: { skill: "add-seo" } }),configDir,- fakeProbe: probePath,ikeyPath,});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(body.name, "PagesPluginEvent");- assert.equal(body.data.eventName, "skill_started");- assert.equal(body.data.skillName, "create-site");-});--test("fails closed (no emit) when override ikey.json path does not exist", () => {- const configDir = mkConfigDir();- const probePath = path.join(configDir, "probe.json");- const { status } = runHook({- input: JSON.stringify({ tool_input: { skill: "create-site" } }),- configDir,- fakeProbe: probePath,- ikeyPath: path.join(configDir, "does-not-exist.json"),- });- assert.equal(status, 0);- sleep(500);- assert.ok(!fs.existsSync(probePath), "missing config must fail closed (no emit)");});diff --git a/shared/telemetry/README.md b/shared/telemetry/README.mdindex 43566d7e6..ee600fc61 100644--- a/shared/telemetry/README.md+++ b/shared/telemetry/README.md@@ -10,7 +10,7 @@ Zero npm dependencies. Node stdlib only.## What it does-Anonymous `skill_started` telemetry over the 1DS Common Schema 4.0 envelope. A detached dispatcher child posts to the configured collector URL; the hook that emitted the event returns before the POST happens.+Anonymous `skill_started` 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.```hook (~5ms when disabled, ~3-5s otherwise — incl. when the user opted out)@@ -18,28 +18,53 @@ hook (~5ms when disabled, ~3-5s otherwise — incl. when the user opted out)└─ fireAndForget(event, opts) ← shared/telemetry/lib/emit-spawn.js│└─ spawn(emit-dispatcher.js, detached) ← runs in background- ├─ read ikey.json+ ├─ read ikey.json (null/unreadable → HARD OFF)├─ kill switch (cfg.disabled) → exit ← HARD OFF: no local log, no POST├─ sanitizeData (FIELD_TYPES allowlist)├─ appendLocal({time,name,data}) → events.jsonl ← ALWAYS (the mirror)├─ user opt-out (config.json telemetry[plugin]="off") → exit (mirror written, no POST)+ ├─ resolve destination → iKey + collector_url ← resolver.js (plugin) or static key├─ iKey missing/placeholder → exit (mirror already written, no POST)├─ build CS4.0 envelope (same time + sanitized data)- └─ HTTPS POST to collector_url+ └─ HTTPS POST to the resolved collector_url```The local log is the on-disk **mirror** of what is (or would be) sent to Kusto:each line is `{time, name, data}` where `data` is the sanitized payload whosefield names ARE the Kusto column names. It is written for **every** event thatclears the repo `disabled` kill switch — irrespective of whether a real iKey is-configured **and** irrespective of the user opt-out. Only the repo-`disabled: true` kill switch produces zero side effects.+resolved **and** irrespective of the user opt-out. Only the repo+`disabled: true` kill switch (or a missing/unreadable `ikey.json`) produces zero+side effects.The per-plugin user opt-out (`config.json` `telemetry[<plugin>] === "off"`, setvia `/<plugin>:telemetry off`) suppresses **transmission**, not the localdiagnostic mirror — so an opted-out run still writes `events.jsonl` (and pays thesame event-building cost as an enabled run), it just never POSTs.+### Custom routing (the resolver contract)++The destination iKey/collector is **not** hard-coded, and the shared library is+routing-agnostic. A plugin may drop a `resolver.js` next to its `ikey.json` to+own that decision:++```js+module.exports = {+ // async; may do network I/O (must cache). Returns { iKey, collectorUrl } or null.+ async resolve({ event, cfg, cloud, configDir }) { /* ... */ },+ // optional sync fast-gate so hooks skip the ~3-5s pac shellout when unprovisioned.+ isProvisioned(cfg) { return true; },+};+```++The dispatcher discovers it by convention (a `resolver.js` sibling of `ikey.json`)+and resolves the destination by precedence: env override (test seam) →+`resolver.js` → static `instrumentationKey`/`collector_url` in `ikey.json` → none.+The power-pages plugin ships a `resolver.js` that does Artemis geo + cloud-stamp+region routing; that implementation lives entirely in+`plugins/power-pages/scripts/lib/telemetry/region/` — the shared library knows+nothing about it.+## What is sentEvery event carries a fixed allowlist enforced by `lib/events.js`. Field names match the destination Kusto column names (camelCase).@@ -54,7 +79,7 @@ Every event carries a fixed allowlist enforced by `lib/events.js`. Field names m**PAC + agent (when available, otherwise omitted):**-- `orgId`, `tenantId` — Dataverse org GUID and Entra tenant GUID, read from `pac auth who` if the user is signed in+- `orgId`, `tenantId` — Dataverse org GUID and Entra tenant GUID, read from `pac auth who` if the user is signed in (`orgId` is passed to the plugin resolver — power-pages uses it for Artemis region routing)- `pacCliVersion` — semver from `pac --version`- `aiAgentName`, `aiAgentVersion` — host AI agent detected via env in the hook process before the detached dispatcher is spawned. Claude Code (`CLAUDECODE=1`) reports `Claude Code` with the version read from its installed `package.json` via `CLAUDE_CODE_EXECPATH`; that `package.json` only exists for npm-global installs, so when it can't be read (e.g. the native installer's standalone binary) the version falls back to the dotted semver parsed out of `AI_AGENT` (`claude-code_<maj>-<min>-<patch>_agent`), which Claude Code sets regardless of install method. GitHub Copilot CLI (`COPILOT_CLI=1`) reports `Copilot CLI` with the version from `COPILOT_CLI_BINARY_VERSION` or `COPILOT_CLI_VERSION`. Codex, OpenCode, Hermes, and OpenClaw are detected from their agent-specific env flags/version variables (`CODEX_*`, `OPENCODE_*`, `HERMES_*`, `OPENCLAW_*`) or from `AI_AGENT` when it includes a recognizable agent name. Explicit `AI_AGENT_NAME` / `AI_AGENT_VERSION` env vars override detection (used for testing); when `AI_AGENT_NAME` is set but `AI_AGENT_VERSION` is empty, the version is backfilled from whichever detector matches.@@ -65,7 +90,7 @@ Every event carries a fixed allowlist enforced by `lib/events.js`. Field names m## What is NEVER sent-File paths, cwd, env vars (except the telemetry kill switch), site names, Dataverse URLs, stack traces, `err.message` text, skill arguments, tool inputs, prompt text, usernames, hostnames.+File paths, cwd, env vars, site names, Dataverse URLs, stack traces, `err.message` text, skill arguments, tool inputs, prompt text, usernames, hostnames.The dispatcher runs a defense-in-depth allowlist filter against `FIELD_TYPES` before serializing, so any field that bypasses the builders is dropped before it reaches the wire.@@ -73,7 +98,7 @@ The dispatcher runs a defense-in-depth allowlist filter against `FIELD_TYPES` be- **Default-on.** Anonymous telemetry is enabled by default. No first-run prompt.- **Opt out of transmission** via `/<plugin>:telemetry off` (per-user, per-plugin). This writes `telemetry[<plugin>] = "off"` into `~/.power-platform-skills/config.json` and stops the network POST to the collector — **nothing leaves the machine** — but the local diagnostic mirror (`events.jsonl`) is still written so the user/developer can see exactly what would have been sent. It is therefore an opt-out of *transmission*, not of local logging. CI/headless can opt out by writing that file directly. Re-enable with `/<plugin>:telemetry on`.-- **Repo-side kill switch (true hard-off).** `ikey.json` carries a `disabled` flag. When `true`, every entry point — hooks and `emit-from-prompt` — short-circuits BEFORE any PAC shellout or process spawn, so there is **no POST and no local log**. Ship `true` and flip to `false` only after the tenant-side Kusto stream and annotation are provisioned.+- **Repo-side kill switch (true hard-off).** `ikey.json` carries a `disabled` flag. When `true` (or when `ikey.json` is missing/unreadable), every entry point — hooks, `emit-from-prompt`, and the dispatcher — short-circuits BEFORE any PAC shellout or process spawn, so there is **no POST and no local log**. Ship `true` and flip to `false` only after the tenant-side Kusto stream and annotation are provisioned.The `disabled` flag is checked at every layer that could perform user-facing work: the pretool/posttool hooks and `emit-from-prompt.js`. A disabled plugin emits zero side effects. The per-plugin user opt-out, by contrast, is enforced inside the detached dispatcher AFTER the local mirror is written — so an opted-out run still produces `events.jsonl` (and incurs the same event-building cost as an enabled run) but never transmits.@@ -87,9 +112,12 @@ shared/telemetry/├─ lib/│ ├─ events.js # FIELD_TYPES allowlist + buildSkillStarted│ ├─ emit-spawn.js # fireAndForget — spawn detached dispatcher-│ ├─ emit-dispatcher.js # detached child — kill switches, sanitize, POST+│ ├─ 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_started-│ ├─ pac-auth.js # parses `pac auth who` for orgId / tenantId+│ ├─ resolver-loader.js # discovers an optional plugin resolver.js next to ikey.json+│ ├─ user-config.js # reads/writes the per-plugin telemetry opt-out in config.json+│ ├─ telemetry-config.js # CLI behind /<plugin>:telemetry on|off|status+│ ├─ pac-auth.js # parses `pac auth who` for orgId / tenantId / cloud│ ├─ agent-info.js # detects AI agent host + reads `pac --version`│ ├─ session.js # per-process session UUID│ ├─ prompt-detector.js # parses `/plugin:skill` slash commands from prompt text@@ -123,7 +151,10 @@ Now `scripts/lib/telemetry/lib` resolves to the shared library — there is no c### 2. Configure `ikey.json`-Create `plugins/<your-plugin>/scripts/lib/telemetry/ikey.json` — a **real file, not symlinked** (it carries this plugin's config, distinct from `shared/`'s placeholder):+Create `plugins/<your-plugin>/scripts/lib/telemetry/ikey.json` — a **real file, not symlinked** (it carries this plugin's config, distinct from `shared/`'s placeholder).++**Tier 1 — one static key (no routing).** Create a flat+`plugins/<your-plugin>/scripts/lib/telemetry/ikey.json` (a real file, not symlinked):```json{@@ -134,9 +165,16 @@ Create `plugins/<your-plugin>/scripts/lib/telemetry/ikey.json` — a **real file}```-**Ship with `disabled: true`** until the tenant-side annotation, Kusto table, and FieldNameMappings are provisioned. Flip to `false` in a separate PR once verified.+No resolver needed — the dispatcher uses the static `instrumentationKey` / `collector_url`.++**Tier 2 — bring your own routing.** Shape `ikey.json` however your resolver wants,+and drop a `resolver.js` next to it implementing `resolve()` (and optionally+`isProvisioned()`). The dispatcher auto-discovers and calls it; the shared library+is never touched. (Power-pages is the reference example: see+`plugins/power-pages/scripts/lib/telemetry/resolver.js` + `region/`.)-**Posture rule:** the **committed** `ikey.json` must stay `disabled: true`. A working-tree `disabled: false` is a local experiment only — never commit it.+**Ship with `disabled: true`** until the tenant-side annotation, Kusto table, and+FieldNameMappings are provisioned. The committed `ikey.json` must stay `disabled: true`.### 3. Register hooks@@ -146,7 +184,7 @@ In `plugins/<your-plugin>/hooks/hooks.json`, register the three hook scripts tha- `run-skill-posttool-validation.js` — runs your validator on `PostToolUse(Skill)`- `run-user-prompt-telemetry.js` — emits `skill_started` on `UserPromptSubmit` when the prompt is a tracked `/plugin:skill` slash command-These hooks must call out to your plugin's `scripts/lib/<plugin>-hook-utils.js` for the tracked-skill list. Adapt the imports to your plugin's layout.+These hooks must call out to your plugin's `scripts/lib/<plugin>-hook-utils.js` for the tracked-skill list, and pass `ikeyJsonPath` (the plugin's own `ikey.json`) into `fireAndForget` so the dispatcher reads the plugin's config rather than `shared/`'s placeholder. Adapt the imports to your plugin's layout.### 4. Verify locally@@ -183,7 +221,7 @@ Every module exposes injectable test seams via `opts._xxx` properties so tests r- `pac-auth.js` — `opts._exec` swaps `execFileSync`- `agent-info.js` — `opts._exec` swaps `execFileSync`- `emit-from-prompt.js` — `opts._emit`, `opts._readPacAuth`, `opts._readAgentInfo`-- `emit-dispatcher.js` — `POWER_PLATFORM_SKILLS_FAKE_HTTPS` env var captures the would-be POST to a probe file+- `emit-dispatcher.js` — `POWER_PLATFORM_SKILLS_FAKE_HTTPS` env var captures the would-be POST to a probe file; `POWER_PLATFORM_SKILLS_IKEY` / `POWER_PLATFORM_SKILLS_COLLECTOR` bypass resolver.js / static-key resolution- `session.js` — `_resetCache()` clears the per-process session-id cache between tests; `getSessionId(override)` accepts an explicit id (no filesystem state to redirect)Follow this pattern for any new module.diff --git a/shared/telemetry/ikey.json b/shared/telemetry/ikey.jsonindex 50d1c141b..aa6e1ed39 100644--- a/shared/telemetry/ikey.json+++ b/shared/telemetry/ikey.json@@ -1,6 +1,35 @@{- "instrumentationKey": "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",- "collector_url": "","event_stream_name": "PluginEventStreamPlaceholder",- "disabled": true+ "disabled": true,+ "default_region": "us",+ "regions": {+ "internal": {+ "instrumentation_key": "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",+ "collector_url": ""+ },+ "us": {+ "instrumentation_key": "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",+ "collector_url": ""+ },+ "eu": {+ "instrumentation_key": "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",+ "collector_url": ""+ },+ "gov": {+ "instrumentation_key": "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",+ "collector_url": ""+ },+ "high": {+ "instrumentation_key": "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",+ "collector_url": ""+ },+ "dod": {+ "instrumentation_key": "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",+ "collector_url": ""+ },+ "mooncake": {+ "instrumentation_key": "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",+ "collector_url": ""+ }+ }}diff --git a/shared/telemetry/lib/emit-dispatcher.js b/shared/telemetry/lib/emit-dispatcher.jsindex b1954723d..833aec31f 100644--- a/shared/telemetry/lib/emit-dispatcher.js+++ b/shared/telemetry/lib/emit-dispatcher.js@@ -1,41 +1,44 @@#!/usr/bin/env node"use strict";-const https = require("node:https");const fs = require("node:fs");const os = require("node:os");const path = require("node:path");+const https = require("node:https");const { FIELD_TYPES, pick } = require("./events");+const { loadResolver } = require("./resolver-loader");+const { isTransmissionOptedOut } = require("./user-config");function exitSilently() {process.exit(0);}-process.on("uncaughtException", exitSilently);process.on("unhandledRejection", exitSilently);process.stdin.on("error", exitSilently);const PLACEHOLDER_IKEY = "PLACEHOLDER_REPLACE_BEFORE_SHIPPING";const DEFAULT_LOCAL_DIR = path.join(os.homedir(), ".power-platform-skills");--const IKEY = process.env.POWER_PLATFORM_SKILLS_IKEY || "";-const COLLECTOR_URL = process.env.POWER_PLATFORM_SKILLS_COLLECTOR || "";const FAKE_PROBE = process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "";+const CONFIG_DIR_ENV = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";+const CLOUD_ENV = process.env.POWER_PLATFORM_SKILLS_CLOUD || "";+// Override env vars — TEST seams only. Production resolves the iKey/collector+// via the plugin resolver / static config in ikey.json and never sets these.+const IKEY_OVERRIDE = process.env.POWER_PLATFORM_SKILLS_IKEY || "";+const COLLECTOR_OVERRIDE = process.env.POWER_PLATFORM_SKILLS_COLLECTOR || "";-const { isTransmissionOptedOut } = require("./user-config");+function localConfigDir() {+ return CONFIG_DIR_ENV || DEFAULT_LOCAL_DIR;+}// Anonymous telemetry is default-on. The user opt-out is per-plugin and lives in// config.json (telemetry[<pluginName>] === "off"), written by the telemetry skill.// It suppresses TRANSMISSION only; the local mirror is written before this gate.-function localConfigDir() {- return process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || DEFAULT_LOCAL_DIR;-}function isUserOptedOut(pluginName) {return isTransmissionOptedOut(localConfigDir(), pluginName);}// Path to the ikey.json config. Overridable via POWER_PLATFORM_SKILLS_IKEY_JSON-// so tests can point at a temp file with their own disabled / iKey state.+// so tests can point at a temp file with their own disabled / region state.function ikeyJsonPath() {return (process.env.POWER_PLATFORM_SKILLS_IKEY_JSON ||@@ -43,23 +46,26 @@ function ikeyJsonPath() {);}-// Repo-side kill switch: when ikey.json contains "disabled": true, no events-// are emitted regardless of opt-out or iKey state. Lets the infrastructure-// PRs land while the tenant-side annotation + Kusto table are still being-// provisioned. Flip to false in a single PR when ready.-function isDisabledByConfig() {+// Returns the parsed ikey.json, or null when it is missing/unreadable. null is+// treated as the repo kill switch (fail CLOSED): if we cannot read the config+// we cannot confirm emission is authorized, so we suppress rather than risk a+// POST / local log in an unexpected state.+function readIkeyConfig() {try {- const cfg = JSON.parse(fs.readFileSync(ikeyJsonPath(), "utf8"));- return cfg.disabled === true;+ return JSON.parse(fs.readFileSync(ikeyJsonPath(), "utf8"));} catch {- // ikey.json missing/unreadable → fail CLOSED (treat as disabled). The- // config is a kill switch; if we can't read it we cannot confirm emission- // is authorized, so we suppress rather than risk a POST / local log in an- // unexpected state.- return true;+ return null;}}+// Repo-side kill switch: a missing/unreadable config (null) or an explicit+// `"disabled": true` suppresses ALL events regardless of opt-out or region+// state. Lets infrastructure PRs land while the tenant-side annotation + Kusto+// table are still being provisioned. Flip `disabled` to false when ready.+function isDisabledByConfig(cfg) {+ return !cfg || cfg.disabled === true;+}+// Reserved meta fields that builders always write into event.data. They are// not user-facing telemetry columns, so they live outside FIELD_TYPES but// must survive sanitization.@@ -82,12 +88,12 @@ function sanitizeData(data) {// Build the CS4.0 envelope from a pre-sanitized payload + timestamp. Both are// computed once in the stdin handler and shared with the local mirror so the// on-disk record and the wire envelope carry byte-identical `data` and `time`.-function buildEnvelope(name, time, sanitized) {+function buildEnvelope(eventName, time, sanitized, resolvedIKey, eventStreamName) {return {ver: "4.0",- name,+ name: eventStreamName || eventName || "",time,- iKey: "o:" + IKEY.split("-")[0],+ iKey: "o:" + String(resolvedIKey || "").split("-")[0],data: sanitized,};}@@ -100,26 +106,30 @@ function writeProbe(filePath, { headers, body }) {}}-function writeLocalLog(event) {+function writeLocalLog(record) {try {const { appendLocal } = require("./local-log");- appendLocal(event, { configDir: localConfigDir() });+ appendLocal(record, { configDir: localConfigDir() });} catch {// fail closed}}-// ---- Repo-side kill switch (applies before ANY side effect) -----------------// The `disabled` repo config is the one true hard-off: no local log, no POST.-// The per-plugin user opt-out is NOT checked here — it suppresses transmission-// only, and is applied below AFTER the local mirror is written.-if (isDisabledByConfig()) exitSilently();+// ---- Read config + repo-side kill switch (applies before ANY side effect) --+// The `disabled` repo config (and an unreadable config) is the one true+// hard-off: no local log, no POST. The per-plugin user opt-out is NOT checked+// here — it suppresses transmission only, and is applied below AFTER the local+// mirror is written. cfg is reused for resolver context + static fallback in+// the stdin handler.+const cfg = readIkeyConfig();+if (isDisabledByConfig(cfg)) exitSilently();+const resolver = loadResolver(path.dirname(ikeyJsonPath()));// ---- Read stdin ------------------------------------------------------------let raw = "";process.stdin.setEncoding("utf8");process.stdin.on("data", (c) => (raw += c));-process.stdin.on("end", () => {+process.stdin.on("end", async () => {let event;try {event = JSON.parse(raw);@@ -135,7 +145,7 @@ process.stdin.on("end", () => {const localRecord = { time, name: event.name, data: sanitized };// Mirror to the local log for EVERY event that clears the repo kill switch —- // irrespective of whether a real iKey is configured AND irrespective of the+ // irrespective of whether a real iKey resolves AND irrespective of the// per-plugin transmission opt-out. The file stays on the user's machine; it// is a local diagnostic mirror of what is (or would be) sent to Kusto, not// transmitted telemetry. (A `disabled: true` repo config wrote nothing — it@@ -146,19 +156,56 @@ process.stdin.on("end", () => {const pluginName = event && event.data && event.data.pluginName;if (isUserOptedOut(pluginName)) return exitSilently();+ // Resolve the destination iKey + collector. Precedence: env override (test+ // seam) → plugin resolver.js (region/tenant/etc., owned by the plugin) →+ // static single-key config in ikey.json → none. The shared dispatcher knows+ // nothing about regions; the plugin's resolver.js owns that.+ let iKey = IKEY_OVERRIDE;+ let collectorUrl = COLLECTOR_OVERRIDE;+ if (!iKey || !collectorUrl) {+ if (resolver && typeof resolver.resolve === "function") {+ let resolved = null;+ try {+ resolved = await resolver.resolve({+ event,+ cfg,+ cloud: CLOUD_ENV,+ configDir: CONFIG_DIR_ENV || undefined,+ });+ } catch {+ // A plugin resolver threw/rejected — continue with no resolution rather+ // than letting the global unhandledRejection handler exit. The local+ // mirror was already written above; the static fallback below still+ // runs, so a transient resolver failure degrades to the configured+ // static key (or "no transmission") instead of crashing.+ resolved = null;+ }+ if (resolved) {+ iKey = iKey || resolved.iKey || "";+ collectorUrl = collectorUrl || resolved.collectorUrl || "";+ }+ }+ // Static fallback — documented precedence is resolver → static → none, so+ // this runs whether or not a resolver was present. A resolver that returns+ // nothing (or threw) still falls through to a configured static key rather+ // than silently disabling transmission.+ iKey = iKey || cfg.instrumentationKey || "";+ collectorUrl = collectorUrl || cfg.collector_url || "";+ }+// Placeholder / unprovisioned mode → local mirror already written; no POST.- const keyMissing = !IKEY || IKEY === PLACEHOLDER_IKEY || !COLLECTOR_URL;+ const keyMissing = !iKey || iKey === PLACEHOLDER_IKEY || !collectorUrl;if (keyMissing) {return exitSilently();}// Real iKey → Common Schema envelope (reuses the same time + sanitized data// as the local mirror) → HTTPS POST.- const envelope = buildEnvelope(event.name, time, sanitized);+ const envelope = buildEnvelope(event.name, time, sanitized, iKey, cfg.event_stream_name);const body = JSON.stringify(envelope) + "\n";const headers = {"Content-Type": "application/x-json-stream; charset=utf-8",- "x-apikey": IKEY,+ "x-apikey": iKey,"Content-Length": Buffer.byteLength(body),};@@ -171,7 +218,7 @@ process.stdin.on("end", () => {let url;try {- url = new URL(COLLECTOR_URL);+ url = new URL(collectorUrl);} catch {return exitSilently();}diff --git a/shared/telemetry/lib/emit-from-prompt.js b/shared/telemetry/lib/emit-from-prompt.jsindex 5a6b199b9..b89bd1693 100644--- a/shared/telemetry/lib/emit-from-prompt.js+++ b/shared/telemetry/lib/emit-from-prompt.js@@ -9,34 +9,31 @@ const { detectSlashCommand } = require("./prompt-detector");const { buildSkillStarted } = require("./events");const { getSessionId } = require("./session");const { fireAndForget } = require("./emit-spawn");+const { loadResolver } = require("./resolver-loader");const { readPacAuth } = require("./pac-auth");const { readPacCliVersion, readAiAgent } = require("./agent-info");function readIkey(telemetryDir) {+ // Test/override seam: POWER_PLATFORM_SKILLS_IKEY_JSON points at an alternate+ // ikey.json so tests don't have to mutate the checked-in config file.+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ const overridePath = override && override.trim() ? override : "";+ // Guard a missing/invalid telemetryDir (a caller bug this fail-closed helper+ // must tolerate): with no override there is no config to read, so fail CLOSED+ // (disabled: true) instead of letting path.join throw out of the library.+ if (!overridePath && (typeof telemetryDir !== "string" || !telemetryDir)) {+ return { cfg: null, dir: "", ikeyPath: "", eventStreamName: "", disabled: true };+ }+ const ikeyPath = overridePath || path.join(telemetryDir, "ikey.json");+ const dir = path.dirname(ikeyPath);try {- // Test/override seam: POWER_PLATFORM_SKILLS_IKEY_JSON points at an alternate- // ikey.json so tests don't have to mutate the checked-in config file.- // Path resolution is inside the try so a missing/invalid telemetryDir- // (path.join throws on undefined) fails CLOSED rather than crashing the- // caller — keeps the function self-protecting per the fail-closed contract.- const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;- const ikeyPath =- override && override.trim()- ? override- : path.join(telemetryDir, "ikey.json");const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));- return {- ikey: cfg.instrumentationKey || "",- collectorUrl: cfg.collector_url || "",- eventStreamName: cfg.event_stream_name || "",- disabled: cfg.disabled === true,- };+ return { cfg, dir, ikeyPath, eventStreamName: cfg.event_stream_name || "", disabled: cfg.disabled === true };} catch {// ikey.json missing/unreadable → fail CLOSED (disabled: true), matching- // emit-dispatcher.js's isDisabledByConfig(). We can't confirm emission is- // authorized, so suppress. (`ikey: ""` already blocks emission downstream;- // returning disabled: true keeps the kill-switch semantics honest too.)- return { ikey: "", collectorUrl: "", eventStreamName: "", disabled: true };+ // emit-dispatcher.js's isDisabledByConfig(). If we can't read the config we+ // cannot confirm emission is authorized, so suppress.+ return { cfg: null, dir, ikeyPath, eventStreamName: "", disabled: true };}}@@ -63,13 +60,27 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {if (!skillName) return { emitted: false, skillName: null };// Repo-side hard-off: short-circuit BEFORE any PAC / agent-info shellouts- // (~3-5s combined) so a disabled plugin pays effectively no cost. The user- // opt-out is NOT checked here: the event is still built and dispatched so the- // detached dispatcher can write the local diagnostic mirror; the dispatcher- // reads the per-plugin config and skips the POST when the plugin is opted out.- const { ikey, collectorUrl, eventStreamName, disabled } = readIkey(telemetryDir);+ // (~3-5s combined) so a disabled or half-provisioned plugin pays effectively+ // no cost. The user opt-out is NOT checked here: the event is still built and+ // dispatched so the detached dispatcher can write the local diagnostic mirror;+ // the dispatcher reads the per-plugin config and skips the POST when opted out.+ const { cfg, dir, ikeyPath, eventStreamName, disabled } = readIkey(telemetryDir);if (disabled) return { emitted: false, skillName };- if (!ikey) return { emitted: false, skillName };+ // Provisioning fast-gate (generic): a plugin resolver decides "is there a key+ // worth paying the pac shellout for?"; default is "static key present".+ const resolver = loadResolver(dir);+ let provisioned;+ try {+ provisioned =+ resolver && typeof resolver.isProvisioned === "function"+ ? resolver.isProvisioned(cfg)+ : !!(cfg && cfg.instrumentationKey);+ } catch {+ // A plugin-provided resolver threw (or assumed cfg non-null) — treat as not+ // provisioned so a bad resolver can't break prompt handling (fail closed).+ provisioned = false;+ }+ if (!provisioned) return { emitted: false, skillName };const pacReader = typeof _readPacAuth === "function" ? _readPacAuth : readPacAuth;let pacAuth = null;@@ -114,13 +125,10 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {const emit = typeof _emit === "function" ? _emit : fireAndForget;try {emit(event, {- iKey: ikey,- collectorUrl,+ cloud: (pacAuth && pacAuth.cloud) || "",configDir: process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "",fakeProbe: process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "",- // Tell the dispatcher where this plugin's real ikey.json lives so its- // kill-switch doesn't fall back to shared/'s placeholder via __dirname.- ikeyJsonPath: telemetryDir ? path.join(telemetryDir, "ikey.json") : "",+ ikeyJsonPath: ikeyPath,});} catch {// fail closed — telemetry never propagates errorsdiff --git a/shared/telemetry/lib/emit-spawn.js b/shared/telemetry/lib/emit-spawn.jsindex 1b5497f2a..f1bfb0264 100644--- a/shared/telemetry/lib/emit-spawn.js+++ b/shared/telemetry/lib/emit-spawn.js@@ -10,11 +10,12 @@ function fireAndForget(event, opts = {}) {const collectorUrl = opts.collectorUrl || "";const configDir = opts.configDir || "";const fakeProbe = opts.fakeProbe || "";+ const cloud = opts.cloud || "";// Absolute path to the CALLING plugin's ikey.json. The dispatcher lives in- // shared/telemetry/lib (reached via symlink or relative require), so its own+ // shared/telemetry/lib (reached via the per-plugin symlink), so its own// __dirname-based default would resolve to shared/'s placeholder, not the- // plugin's real config. Passing the path explicitly makes the dispatcher's- // kill-switch read the right file regardless of how lib/ is linked.+ // plugin's real config. Passing the path explicitly makes the dispatcher+ // read the right file regardless of how lib/ is linked.const ikeyJsonPath = opts.ikeyJsonPath || "";try {@@ -34,9 +35,10 @@ function fireAndForget(event, opts = {}) {POWER_PLATFORM_SKILLS_COLLECTOR: collectorUrl,POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe,+ POWER_PLATFORM_SKILLS_CLOUD: cloud,// ikey.json path: an explicit env override (test seam) wins; otherwise- // the calling plugin's ikey.json path so the dispatcher's kill-switch- // reads the plugin's real config rather than shared/'s placeholder.+ // the calling plugin's ikey.json path so the dispatcher reads the+ // plugin's real config rather than shared/'s placeholder.POWER_PLATFORM_SKILLS_IKEY_JSON:process.env.POWER_PLATFORM_SKILLS_IKEY_JSON || ikeyJsonPath || "",},diff --git a/shared/telemetry/lib/pac-auth.js b/shared/telemetry/lib/pac-auth.jsindex 2f413d506..9c74c126f 100644--- a/shared/telemetry/lib/pac-auth.js+++ b/shared/telemetry/lib/pac-auth.js@@ -58,6 +58,7 @@ function readPacAuth(opts = {}) {}const tenantId = pickLine(output, "Tenant Id");const orgId = pickLine(output, "Organization Id");+ const cloud = pickLine(output, "Cloud");if (!tenantId && !orgId) {cache = null;return null;@@ -65,6 +66,7 @@ function readPacAuth(opts = {}) {cache = {orgId: orgId || "",tenantId: tenantId || "",+ cloud: cloud || "",};return cache;}diff --git a/shared/telemetry/lib/resolver-loader.js b/shared/telemetry/lib/resolver-loader.jsnew file mode 100644index 000000000..5c5c2bb67--- /dev/null+++ b/shared/telemetry/lib/resolver-loader.js@@ -0,0 +1,26 @@+"use strict";++const path = require("node:path");++// Discover an optional, plugin-provided resolver module that owns iKey/collector+// selection (region routing, tenant routing, etc.). Convention: a `resolver.js`+// next to the plugin's ikey.json. The shared library never imports a resolver+// directly — it loads whatever the plugin drops here and calls the documented+// contract: { resolve({event, cfg, cloud, configDir}), isProvisioned(cfg) }.+//+// Returns the resolver module, or null when none is present or it fails to load+// (callers then fall back to static config / a generic gate — fail open).+function loadResolver(dir) {+ if (!dir) return null;+ try {+ // path.resolve (not path.join): require() treats a non-"./"-prefixed+ // relative path as a module ID and searches node_modules. A relative `dir`+ // (e.g. from a relative POWER_PLATFORM_SKILLS_IKEY_JSON override) would then+ // miss the intended resolver.js. Resolve to an absolute path first.+ return require(path.resolve(dir, "resolver.js"));+ } catch {+ return null;+ }+}++module.exports = { loadResolver };diff --git a/shared/telemetry/tests/emit-dispatcher.test.js b/shared/telemetry/tests/emit-dispatcher.test.jsindex e11d8e141..361aa3504 100644--- a/shared/telemetry/tests/emit-dispatcher.test.js+++ b/shared/telemetry/tests/emit-dispatcher.test.js@@ -32,7 +32,7 @@ function mkEnabledIkey(tmp) {function runDispatcher({ event, env }) {const tmp = env.configDir;const ikeyJsonPath = env.ikeyJsonPath || mkEnabledIkey(tmp);- // Opt-out is now a per-plugin config.json in the config dir (env var removed).+ // Opt-out is a per-plugin config.json in the config dir (env var removed).if (env.off) {fs.writeFileSync(path.join(tmp, "config.json"),@@ -49,6 +49,7 @@ function runDispatcher({ event, env }) {POWER_PLATFORM_SKILLS_COLLECTOR: env.collectorUrl || "",POWER_PLATFORM_SKILLS_FAKE_HTTPS: env.fakeProbe || "",POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyJsonPath,+ POWER_PLATFORM_SKILLS_CLOUD: env.cloud || "",},});}@@ -393,3 +394,110 @@ test("local mirror records the same data + time that gets POSTed to Kusto", () =assert.equal(local.ver, undefined, "local mirror omits envelope-only ver");assert.equal(local.iKey, undefined, "local mirror omits envelope-only iKey");});++// ---- iKey/collector resolution (generic seam) -----------------------------++test("dispatcher uses static instrumentationKey/collector_url when no resolver is present", () => {+ // mkEnabledIkey writes a flat ikey.json (instrumentationKey + collector_url)+ // and there is no resolver.js beside it → the static fallback is used.+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const { status } = runDispatcher({+ event: fakeEvent,+ env: { configDir: tmp, iKey: "", collectorUrl: "", fakeProbe: probePath },+ });+ assert.equal(status, 0);+ assert.ok(fs.existsSync(probePath), "static-key config must POST");+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));+ assert.equal(probe.headers["x-apikey"], "placeholder");+});++test("dispatcher uses an injected resolver.js to pick iKey/collector", () => {+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const ikeyPath = path.join(tmp, "ikey.json");+ fs.writeFileSync(+ ikeyPath,+ JSON.stringify({+ event_stream_name: "PagesPluginEvent",+ disabled: false,+ default_region: "us",+ regions: {+ us: {+ instrumentation_key: "ikeyusresolved",+ collector_url: "https://example.invalid/OneCollector/1.0/",+ },+ },+ })+ );+ // resolver.js beside ikey.json — discovered by convention.+ fs.writeFileSync(+ path.join(tmp, "resolver.js"),+ "module.exports = {" ++ "async resolve({ cfg }) {" ++ " const e = cfg.regions[cfg.default_region];" ++ " return { iKey: e.instrumentation_key, collectorUrl: e.collector_url };" ++ "}," ++ "isProvisioned: () => true };"+ );+ const { status } = runDispatcher({+ event: { name: "PagesPluginEvent", data: { eventName: "skill_started", eventType: "Trace", severity: "Info" } },+ env: { configDir: tmp, iKey: "", collectorUrl: "", fakeProbe: probePath, ikeyJsonPath: ikeyPath },+ });+ assert.equal(status, 0);+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));+ assert.equal(probe.headers["x-apikey"], "ikeyusresolved");+});++test("dispatcher falls back to the static key when a resolver resolves to nothing", () => {+ // Documented precedence is resolver → static → none. A resolver present but+ // returning null/undefined must NOT suppress a configured static key.+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const ikeyPath = path.join(tmp, "ikey.json");+ fs.writeFileSync(+ ikeyPath,+ JSON.stringify({+ instrumentationKey: "static-ikey-32-chars-minimum-aaaaaaaaaaaa",+ collector_url: "https://example.invalid/OneCollector/1.0/",+ event_stream_name: "PagesPluginEvent",+ disabled: false,+ })+ );+ // resolver.js that always resolves to nothing (no region matched).+ fs.writeFileSync(+ path.join(tmp, "resolver.js"),+ "module.exports = { async resolve() { return null; }, isProvisioned: () => true };"+ );+ const { status } = runDispatcher({+ event: fakeEvent,+ env: { configDir: tmp, iKey: "", collectorUrl: "", fakeProbe: probePath, ikeyJsonPath: ikeyPath },+ });+ assert.equal(status, 0);+ assert.ok(fs.existsSync(probePath), "resolver→null must fall back to the static key and POST");+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));+ assert.equal(probe.headers["x-apikey"], "static-ikey-32-chars-minimum-aaaaaaaaaaaa");+});++test("dispatcher writes the mirror but does NOT POST when neither resolver nor static key resolves", () => {+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const ikeyPath = path.join(tmp, "ikey.json");+ // Region-shaped but unprovisioned: no static instrumentationKey, no resolver.js.+ fs.writeFileSync(+ ikeyPath,+ JSON.stringify({+ event_stream_name: "PagesPluginEvent",+ disabled: false,+ default_region: "us",+ regions: { us: { collector_url: "https://x" } },+ })+ );+ const { status } = runDispatcher({+ event: fakeEvent,+ env: { configDir: tmp, iKey: "", collectorUrl: "", fakeProbe: probePath, ikeyJsonPath: ikeyPath },+ });+ assert.equal(status, 0);+ assert.ok(!fs.existsSync(probePath), "no key resolved → no POST");+ assert.ok(fs.existsSync(path.join(tmp, "events.jsonl")), "local mirror still written");+});diff --git a/shared/telemetry/tests/emit-from-prompt.test.js b/shared/telemetry/tests/emit-from-prompt.test.jsindex 9ed52a1a7..6d35cf04e 100644--- a/shared/telemetry/tests/emit-from-prompt.test.js+++ b/shared/telemetry/tests/emit-from-prompt.test.js@@ -13,12 +13,23 @@ function mkTelemetryDir({ instrumentationKey, collectorUrl, eventStreamName, disfs.writeFileSync(path.join(tmp, "ikey.json"),JSON.stringify({- instrumentationKey,- collector_url: collectorUrl,event_stream_name: eventStreamName,disabled: disabled === true,+ default_region: "us",+ regions: { us: { instrumentation_key: instrumentationKey, collector_url: collectorUrl } },}));+ // Drop the region resolver beside ikey.json so the generic isProvisioned gate+ // behaves exactly like production (provisioned == default-region key present).+ 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;}@@ -55,6 +66,33 @@ test("returns { emitted: false } when detection returns null", () => {assert.equal(captured.event, undefined);});+test("returns { emitted: false } when default region has no instrumentation_key", () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-efp-nokey-"));+ fs.writeFileSync(+ path.join(tmp, "ikey.json"),+ JSON.stringify({+ event_stream_name: "PowerPagesPluginEvent",+ disabled: false,+ default_region: "us",+ regions: { us: { collector_url: "https://x" } },+ })+ );+ const captured = {};+ const result = emitSkillStartedFromPrompt("/power-pages:add-seo", {+ pluginName: "power-pages",+ pluginVersion: "1.2.3",+ trackedSkills: TRACKED,+ telemetryDir: tmp,+ _emit: (event, spawnOpts) => {+ captured.event = event;+ captured.spawnOpts = spawnOpts;+ },+ _readPacAuth: () => null,+ });+ assert.deepEqual(result, { emitted: false, skillName: "add-seo" });+ assert.equal(captured.event, undefined);+});+test("emits skill_started with envelope name from ikey.json", () => {const telemetryDir = mkTelemetryDir({instrumentationKey: "x",@@ -187,6 +225,63 @@ test("forwards POWER_PLATFORM_SKILLS_CONFIG_DIR and FAKE_HTTPS into spawn opts",assert.equal(captured.spawnOpts.fakeProbe, "/tmp/fake-probe.json");});+test("forwards the plugin ikey.json path into spawn opts (so the dispatcher reads the plugin config, not shared/'s placeholder)", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ // Production-faithful: no IKEY_JSON override → ikeyPath resolves to telemetryDir/ikey.json.+ const prevOverride = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ delete process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ const captured = {};+ try {+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ });+ } finally {+ if (prevOverride === undefined) delete process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ else process.env.POWER_PLATFORM_SKILLS_IKEY_JSON = prevOverride;+ }+ assert.equal(captured.spawnOpts.ikeyJsonPath, path.join(telemetryDir, "ikey.json"));+});++test("forwards pacAuth.cloud into spawn opts", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ pacAuth: { cloud: "UsGov" },+ });+ assert.equal(captured.spawnOpts.cloud, "UsGov");+ assert.equal(captured.spawnOpts.iKey, undefined);+ assert.equal(captured.spawnOpts.collectorUrl, undefined);+});++test("spawn opts include empty cloud when pacAuth has no cloud", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ pacAuth: null,+ });+ assert.equal(captured.spawnOpts.cloud, "");+});+test("does not throw when ikey.json is missing", () => {const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-efp-noikey-"));const captured = {};@@ -203,34 +298,7 @@ test("does not throw when ikey.json is missing", () => {_readPacAuth: () => null,}));-});--test("fails closed (no throw, no emit) when telemetryDir is missing and no override is set", () => {- // Guards against path.join(undefined, ...) throwing out of readIkey — the- // library must self-protect even if a caller forgets telemetryDir.- const prev = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;- delete process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;- const captured = {};- let result;- try {- assert.doesNotThrow(() => {- result = emitSkillStartedFromPrompt("/power-pages:add-seo", {- pluginName: "power-pages",- pluginVersion: "1.2.3",- trackedSkills: TRACKED,- // telemetryDir intentionally omitted- _emit: (e, o) => {- captured.event = e;- captured.spawnOpts = o;- },- _readPacAuth: () => null,- });- });- } finally {- if (prev === undefined) delete process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;- else process.env.POWER_PLATFORM_SKILLS_IKEY_JSON = prev;- }- assert.deepEqual(result, { emitted: false, skillName: "add-seo" });+ // Missing ikey.json → unreadable config fails CLOSED (disabled) → no emit.assert.equal(captured.event, undefined);});diff --git a/shared/telemetry/tests/emit-spawn.test.js b/shared/telemetry/tests/emit-spawn.test.jsindex bbbf86939..53f8abb36 100644--- a/shared/telemetry/tests/emit-spawn.test.js+++ b/shared/telemetry/tests/emit-spawn.test.js@@ -121,3 +121,15 @@ test("fireAndForget does not throw on empty-opts invocation", () => {fireAndForget({ name: "X", data: {} }, { iKey: "", collectorUrl: "" });// No assertion needed: test passes if no throw.});++test("fireAndForget forwards opts.cloud as POWER_PLATFORM_SKILLS_CLOUD env var", () => {+ // We can't easily inspect the child env, but we can test that opts.cloud+ // is accepted without throwing. The integration test in the dispatcher+ // suite verifies the env-var is actually received by the child.+ assert.doesNotThrow(() =>+ fireAndForget(+ { name: "X", data: {} },+ { iKey: "", collectorUrl: "", cloud: "Public" }+ )+ );+});diff --git a/shared/telemetry/tests/events.test.js b/shared/telemetry/tests/events.test.jsindex efcb8a17e..7f7bd9a7d 100644--- a/shared/telemetry/tests/events.test.js+++ b/shared/telemetry/tests/events.test.js@@ -209,7 +209,7 @@ test("durationMs always lands as a non-negative integer (number type)", () => {{ input: "1234", expect: 1234 }, // string-int coerced{ input: "abc", expect: 0 }, // unparseable → 0{ input: "", expect: 0 }, // empty string → 0 (NOT '' on the wire)- { input: true, expect: 1 }, // boolean true coerces to 1 (Number(true)) — kept, not dropped+ { input: true, expect: 1 }, // boolean true coerces to 1 — drop guarded by clamp];for (const { input, expect } of cases) {const ev = buildSkillCompleted(ENVELOPE, {diff --git a/shared/telemetry/tests/pac-auth.test.js b/shared/telemetry/tests/pac-auth.test.jsindex fdab3d3b2..6b8d87b38 100644--- a/shared/telemetry/tests/pac-auth.test.js+++ b/shared/telemetry/tests/pac-auth.test.js@@ -29,6 +29,7 @@ test("returns { orgId, tenantId } parsed from `pac auth who` output", () => {assert.deepEqual(result, {orgId: "33333333-3333-3333-3333-333333333333",tenantId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",});});@@ -41,6 +42,7 @@ test("returns { orgId: '', tenantId } when only Tenant Id line present", () => {assert.deepEqual(result, {orgId: "",tenantId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",});});@@ -53,6 +55,7 @@ test("returns { tenantId: '', orgId } when only Organization Id line present", (assert.deepEqual(result, {orgId: "33333333-3333-3333-3333-333333333333",tenantId: "",+ cloud: "Public",});});@@ -139,5 +142,35 @@ test("parses values with extra whitespace and mixed casing in label", () => {assert.deepEqual(result, {orgId: "33333333-3333-3333-3333-333333333333",tenantId: "11111111-1111-1111-1111-111111111111",+ cloud: "",});});++test("readPacAuth parses Cloud line", () => {+ pacAuth._resetCache();+ const fakeExec = () =>+ "Tenant Id: 11111111-1111-1111-1111-111111111111\n" ++ "Organization Id: 22222222-2222-2222-2222-222222222222\n" ++ "Cloud: Public\n";+ const result = pacAuth.readPacAuth({ _exec: fakeExec });+ assert.equal(result.cloud, "Public");+});++test("readPacAuth returns empty cloud when Cloud line is missing", () => {+ pacAuth._resetCache();+ const fakeExec = () =>+ "Tenant Id: 11111111-1111-1111-1111-111111111111\n" ++ "Organization Id: 22222222-2222-2222-2222-222222222222\n";+ const result = pacAuth.readPacAuth({ _exec: fakeExec });+ assert.equal(result.cloud, "");+});++test("readPacAuth parses Cloud with sovereign values", () => {+ pacAuth._resetCache();+ const fakeExec = () =>+ "Tenant Id: 11111111-1111-1111-1111-111111111111\n" ++ "Organization Id: 22222222-2222-2222-2222-222222222222\n" ++ "Cloud: UsGovHigh\n";+ const result = pacAuth.readPacAuth({ _exec: fakeExec });+ assert.equal(result.cloud, "UsGovHigh");+});diff --git a/shared/telemetry/tests/resolver-loader.test.js b/shared/telemetry/tests/resolver-loader.test.jsnew file mode 100644index 000000000..799b86004--- /dev/null+++ b/shared/telemetry/tests/resolver-loader.test.js@@ -0,0 +1,38 @@+"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 { loadResolver } = require("../lib/resolver-loader");++function mkTmp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-rl-"));+}++test("loads a resolver.js sitting next to ikey.json", () => {+ const dir = mkTmp();+ fs.writeFileSync(+ path.join(dir, "resolver.js"),+ "module.exports = { resolve: async () => ({ iKey: 'k', collectorUrl: 'u' }), isProvisioned: () => true };"+ );+ const r = loadResolver(dir);+ assert.equal(typeof r.resolve, "function");+ assert.equal(r.isProvisioned({}), true);+});++test("returns null when no resolver.js is present", () => {+ assert.equal(loadResolver(mkTmp()), null);+});++test("returns null when the module throws on load", () => {+ const dir = mkTmp();+ fs.writeFileSync(path.join(dir, "resolver.js"), "throw new Error('boom');");+ assert.equal(loadResolver(dir), null);+});++test("returns null for a falsy dir", () => {+ assert.equal(loadResolver(""), null);+});