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
feat(telemetry): 1DS skill-run telemetry infra (#176)
amitjoshi43898430e92c468
diff --git a/.gitignore b/.gitignoreindex 70b5e619b..b563fdf76 100644--- a/.gitignore+++ b/.gitignore@@ -48,3 +48,6 @@ ENV/Thumbs.db.playwright-mcp/++# oh-my-claudecode scratch state+.omc/diff --git a/AGENTS.md b/AGENTS.mdindex 12167bacf..99b19a876 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -63,6 +63,14 @@ Skills that apply to all plugins live in `shared/skills/<skill-name>/`. The workThis keeps the skill discoverable in each plugin while preserving install-time portability. Marketplace installs copy only the plugin directory, so per-plugin wrappers must not reference repo-root `shared/` paths at runtime. Instead, point the wrapper at `${CLAUDE_PLUGIN_ROOT}/skills/<skill-name>/<workflow>.md` and keep a symlink from that per-plugin path to the repo-root shared workflow; marketplace installers dereference same-marketplace symlinks into the installed plugin cache. When updating a shared skill, edit the workflow file and/or `SKILL.template.md` in `shared/`, then update the per-plugin wrappers (frontmatter + bundled workflow reference, with `{{PLUGIN_NAME}}` substituted) and ensure any per-plugin symlinks still resolve under `plugins/<plugin>/skills/<skill-name>/`. Commit the shared source and per-plugin symlinks together.+## Shared Telemetry++1DS telemetry code for all plugins lives at `shared/telemetry/`. Each adopting plugin **symlinks** the library into its own tree — `plugins/<plugin>/scripts/lib/telemetry/lib` is a symlink to `shared/telemetry/lib`. The marketplace installer dereferences that symlink into the installed plugin at install time, so the shared code ships without copying it into each plugin. Each plugin keeps its own real `ikey.json` next to the symlink.++Edit `shared/telemetry/` directly — the symlink makes changes live for every adopting plugin immediately; there is nothing to re-sync.++Current adopters: `power-pages`. Others adopt on demand.+## Code Conventions**DRY (Don't Repeat Yourself):** Never duplicate logic across files. Each plugin has shared utilities (e.g., `scripts/lib/`) and shared reference docs (e.g., `references/`). Always check for and reuse existing helpers before writing new code. When adding shared logic, put it in the plugin's shared modules — not in individual skill directories.diff --git a/README.md b/README.mdindex 2ae816aa5..5e6b43d81 100644--- a/README.md+++ b/README.md@@ -211,3 +211,7 @@ trademarks or logos is subject to and must follow[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general).Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.Any use of third-party trademarks or logos are subject to those third-party's policies.++## Telemetry++Plugins that ship 1DS telemetry (currently: `power-pages`) gather anonymous usage signals. Telemetry is default-on; users opt out per-plugin via the `/<plugin>:telemetry off` command (e.g. `/power-pages:telemetry off`), stored in `~/.power-platform-skills/config.json`. See `shared/telemetry/README.md` for what is sent.diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex ebb4420aa..9a79de602 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -153,15 +153,15 @@ Skills are defined in `SKILL.md` files with YAML frontmatter (name, description,### Hooks-Hook registration is centralized in `hooks/hooks.json` — a single PostToolUse hook (matcher `Skill`) runs `hooks/run-skill-posttool-validation.js` after every Skill tool call. The runner consults the `TRACKED_SKILLS` map in `scripts/lib/powerpages-hook-utils.js`, looks up the validator for the skill that just completed, and invokes it with the current cwd.+Hook registration is centralized in `hooks/hooks.json` — a single PostToolUse hook (matcher `Skill`) runs `hooks/run-skill-posttool-validation.js` after every Skill tool call. The runner derives tracked skills directly from `skills/*/SKILL.md` via `scripts/lib/powerpages-hook-utils.js`, looks up an optional `skills/<skill>/scripts/validate*.js` validator for the skill that just completed, and invokes it with the current cwd.To wire a new skill into validation:1. Write the validator at `skills/<skill>/scripts/validate-<skill>.js` using the `runValidation((cwd) => { ... })` pattern from `scripts/lib/validation-helpers.js`.-2. Register the skill in `TRACKED_SKILLS` (in `scripts/lib/powerpages-hook-utils.js`) with its `validatorScript` path.-3. Add test coverage in `scripts/tests/powerpages-hook-utils.test.js` so an unregistered skill is caught in CI.+2. No manual tracked-skill registration is needed. Any folder with `skills/<skill>/SKILL.md` is automatically tracked for telemetry and hook detection.+3. Add or update test coverage in `scripts/tests/powerpages-hook-utils.test.js` if you introduce a new validator naming pattern.-Skills currently registered with command-backed validators: `activate-site`, `add-cloud-flow`, `add-seo`, `add-server-logic`, `audit-permissions`, `configure-env-variables`, `create-site`, `create-webroles`, `deploy-pipeline`, `ensure-pipelines-host`, `export-solution`, `force-link-environment`, `import-solution`, `integrate-webapi`, `plan-alm`, `setup-auth`, `setup-datamodel`, `setup-pipeline`, `setup-solution`. `add-sample-data` and `test-site` are tracked without command validators (no artifacts to verify). `diagnose-deployment` is intentionally not tracked — it's read-only and produces no artifacts to verify.+All skill folders are tracked. Skills without a `scripts/validate*.js` file are tracked for telemetry/detection but skip validation.**Anti-patterns** (see `PLUGIN_DEVELOPMENT_GUIDE.md` for the rationale): do not add `hooks: Stop:` blocks to individual SKILL.md frontmatter — they duplicate the centralized PostToolUse hook and fire too often. Do not use `type: prompt` Stop hooks for skill-completion checks — they create runaway forced-continuation loops.@@ -342,7 +342,7 @@ This runs a lightweight check comparing the local plugin version against `origin- **Approval Gates** — Every load-bearing `AskUserQuestion` is an **Approval Gate**. Pause at minimum after gathering requirements, after presenting a plan, after implementation, and before deployment (Three-Point Approval Pattern). For ALM skills, every gate must (a) be catalogued in `references/approval-gates.md` §6 with a stable `gate-id`, and (b) be marked in SKILL.md with the explicit-pairing comment `<!-- gate: skill:phase | category=<intent|plan|progress|consent|final|pause> | cancel-leaves=<vocab> -->` followed by a human-readable `> 🚦 **Gate (...)**` block. New ALM skills must extend the catalog in the same PR that introduces the skill. Non-ALM skills should follow the same convention as the catalog is extended in a follow-up; lint runs warn-only on non-ALM skills until then. Do not coin alternative terms ("review gate", "approval checkpoint", "manual step" etc.) — the canonical term is **Approval Gate**.- **Deployment prompt** — Skills that modify site artifacts should end by asking "Ready to deploy?" and invoke `/deploy-site` if yes.-- **Lifecycle hooks** — If a skill needs command validation or checklist enforcement, update `hooks/hooks.json` and `scripts/lib/powerpages-hook-utils.js`. Do not define hook registration in individual `SKILL.md` files.+- **Lifecycle hooks** — Hook registration is centralized in `hooks/hooks.json`; `scripts/lib/powerpages-hook-utils.js` derives tracked skills from `skills/*/SKILL.md` and discovers optional `scripts/validate*.js` validators. Do not define hook registration in individual `SKILL.md` files.- **Graceful failure** — Track API call results, never auto-rollback, report failures clearly, continue with remaining items.- **Token refresh** — Refresh Azure CLI token every ~20 records / 3-4 tables / ~60 seconds.- **Git commits** — Commit after every significant milestone (each page/component, design foundations, phase completion).@@ -388,6 +388,17 @@ These patterns have caused repeated PR review feedback. Check for them before su- **Template placeholders in `<script>` blocks need special care** — `render-template.js` injects string values as-is (no encoding), which is safe for HTML text contexts but risky inside JavaScript. Avoid declaring JS variables with `"__PLACEHOLDER__"` in script blocks; prefer reading from the DOM or using `JSON.stringify` for JS contexts.- **Guidance must be consistent within a skill** — If one section says "always use raw fetch", a framework-specific table in the same file must not recommend a different HTTP client without qualification. Reviewers will flag contradictions.+## Telemetry++This 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.+- **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.++See `shared/telemetry/README.md` for the integration guide.+## Maintaining This FileUpdate when plugin structure or conventions change or you learn something which can be useful for new skills or agents.diff --git a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.mdindex dddaccad7..45400a0ed 100644--- a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md+++ b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md@@ -197,7 +197,7 @@ LLMs are probabilistic. When an LLM constructs inline bash commands for Datavers|--------|---------|| `validation-helpers.js` | `runValidation()`, `findPath()`, `findProjectRoot()`, `approve()`, `block()` — shared boilerplate for all validators || `powerpages-config.js` | Loads `.powerpages-site` YAML files (table permissions, site settings, web roles) with consistent parsing |-| `powerpages-hook-utils.js` | Maps skill names to validator scripts for the hook dispatcher |+| `powerpages-hook-utils.js` | Discovers skill folders and optional validator scripts for the hook dispatcher || `powerpages-schema-validator.js` | Validates permission/site-setting YAML schema || `table-permissions-validator.js` | Validates table permission YAML || `web-roles-validator.js` | Validates web role YAML |@@ -410,7 +410,7 @@ echo '{"reason":"ni-dev — ALM handled by infra"}' > .alm-deferredPostToolUse on the `Skill` tool fires **once per skill invocation**. Stop fires on **every assistant pause** (including user-input waits — every "Continue?" prompt fires it).-This plugin uses PostToolUse via `hooks/hooks.json` → `run-skill-posttool-validation.js` → per-skill validator. Skill frontmatter must NOT declare its own `hooks: Stop:` block — those duplicate the centralized PostToolUse hook and fire too often. To wire validation for a new skill, register it in the `TRACKED_SKILLS` map in `scripts/lib/powerpages-hook-utils.js` (see `AGENTS.md` → "Hooks" for the registration steps).+This plugin uses PostToolUse via `hooks/hooks.json` → `run-skill-posttool-validation.js` → per-skill validator. Skill frontmatter must NOT declare its own `hooks: Stop:` block — those duplicate the centralized PostToolUse hook and fire too often. `scripts/lib/powerpages-hook-utils.js` automatically tracks every `skills/*/SKILL.md` folder and discovers an optional `skills/<skill>/scripts/validate*.js` validator, so new skills do not need manual hook registration.#### 4. Skills write explicit status, not just artifact presencediff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex ac266980c..49bf17129 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -38,7 +38,7 @@ This keeps hook behavior in one place and avoids relying on skill-frontmatter ho## Skills-The plugin provides 29 skills that cover the full lifecycle of a Power Pages code site — scaffolding, deployment, data modeling, backend integration, authentication, ALM and CI/CD, security review, testing, and auditing. Each skill is invoked conversationally — just describe what you want to do.+The plugin provides 30 skills that cover the full lifecycle of a Power Pages code site — scaffolding, deployment, data modeling, backend integration, authentication, ALM and CI/CD, security review, testing, and auditing. Each skill is invoked conversationally — just describe what you want to do.### Site scaffolding and deployment@@ -373,6 +373,17 @@ Collects context about the current session and opens a pre-filled GitHub issue a- Attaches relevant file paths and environment info- Opens the issue in your browser for final review+#### `/telemetry`++> "Turn off telemetry" · "Disable telemetry" · "Telemetry status"++Enables, disables, or checks the status of anonymous usage telemetry. Per-user and per-plugin; the choice is stored in `~/.power-platform-skills/config.json`. See [Telemetry & privacy](#telemetry--privacy) below.++- `/power-pages:telemetry status` — show the current setting+- `/power-pages:telemetry off` — stop sending telemetry (nothing leaves your machine)+- `/power-pages:telemetry on` — resume sending telemetry+- No personal data is ever collected (anonymous: skill name, plugin version, OS, Node version)+## AgentsThe plugin includes 4 specialized agents that are spawned automatically by skills when needed:@@ -476,6 +487,27 @@ node plugins/power-pages/scripts/validate-permissions-schema.js --projectRoot /pThis Dataverse relationship check is intended for local validation only and should not be used in CI.+## Telemetry & privacy++This plugin sends **anonymous** usage telemetry by default to help Microsoft+improve it. **No personal data is ever collected** — only things like skill name,+plugin version, OS, and Node version. It never includes file paths, prompts, tool+inputs, site names, URLs, credentials, usernames, or hostnames.++**Turn it on or off (per-user, applies to every project):**++```bash+/power-pages:telemetry status # show the current setting+/power-pages:telemetry off # stop sending telemetry+/power-pages:telemetry on # resume sending telemetry+```++When **off**, nothing leaves your machine. A local diagnostic copy of each event+is still written to `~/.power-platform-skills/events.jsonl` so you can see exactly+what would have been sent; delete it anytime. The setting is stored at+`~/.power-platform-skills/config.json` (`{ "telemetry": { "power-pages": "off" } }`),+so CI/headless environments can opt out by writing that file directly.+## License[MIT](../../LICENSE)diff --git a/plugins/power-pages/hooks/hooks.json b/plugins/power-pages/hooks/hooks.jsonindex 60b8753b3..c4529f934 100644--- a/plugins/power-pages/hooks/hooks.json+++ b/plugins/power-pages/hooks/hooks.json@@ -1,5 +1,17 @@{"hooks": {+ "PreToolUse": [+ {+ "matcher": "Skill",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/run-skill-pretool-telemetry.js\"",+ "timeout": 30+ }+ ]+ }+ ],"PostToolUse": [{"matcher": "Skill",@@ -11,6 +23,17 @@}]}+ ],+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/run-user-prompt-telemetry.js\"",+ "timeout": 30+ }+ ]+ }]}}diff --git a/plugins/power-pages/hooks/run-skill-posttool-validation.js b/plugins/power-pages/hooks/run-skill-posttool-validation.jsindex 760cb6b53..b53595790 100644--- a/plugins/power-pages/hooks/run-skill-posttool-validation.js+++ b/plugins/power-pages/hooks/run-skill-posttool-validation.js@@ -23,41 +23,36 @@ process.stdin.on('data', (chunk) => {process.stdin.on('end', () => {debug(`[power-pages hook] stdin closed, received ${inputData.length} bytes\n`);++ let validatorStatus = 0;+ let skillName = null;+ let input = null;+try {- const input = JSON.parse(inputData);- const skillName = getTrackedSkillFromToolInput(input.tool_input);+ input = JSON.parse(inputData);+ skillName = getTrackedSkillFromToolInput(input.tool_input);if (!skillName) {debug('[power-pages hook] No tracked skill detected — skipping validation\n');process.exit(0);}const validatorScript = getValidatorScript(skillName);- if (!validatorScript) {- debug(`[power-pages hook] Skill "${skillName}" has no validator — skipping\n`);- process.exit(0);+ if (validatorScript) {+ const validatorPath = path.join(__dirname, '..', validatorScript);+ const result = spawnSync(process.execPath, [validatorPath], {+ input: inputData,+ encoding: 'utf8',+ cwd: input.cwd || process.cwd(),+ });+ if (result.stdout) process.stdout.write(result.stdout);+ if (result.stderr) process.stderr.write(result.stderr);+ validatorStatus = result.status ?? 0;+ debug(`[power-pages hook] Validator exited with code ${validatorStatus}\n`);}-- debug(`[power-pages hook] Running validator for skill "${skillName}": ${validatorScript}\n`);-- const validatorPath = path.join(__dirname, '..', validatorScript);- const result = spawnSync(process.execPath, [validatorPath], {- input: inputData,- encoding: 'utf8',- cwd: input.cwd || process.cwd(),- });-- if (result.stdout) {- process.stdout.write(result.stdout);- }-- if (result.stderr) {- process.stderr.write(result.stderr);- }-- debug(`[power-pages hook] Validator exited with code ${result.status ?? 0}\n`);- process.exit(result.status ?? 0);} catch (err) {process.stderr.write(`[power-pages hook] Unexpected error: ${err.message}\n`);- process.exit(0);+ validatorStatus = 0;}++ process.exit(validatorStatus);});diff --git a/plugins/power-pages/hooks/run-skill-pretool-telemetry.js b/plugins/power-pages/hooks/run-skill-pretool-telemetry.jsnew file mode 100644index 000000000..576605fb2--- /dev/null+++ b/plugins/power-pages/hooks/run-skill-pretool-telemetry.js@@ -0,0 +1,161 @@+#!/usr/bin/env node+"use strict";++const path = require("node:path");+const fs = require("node:fs");+const os = require("node:os");+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;+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"));+} catch {+ process.exit(0);+}++let hookUtils;+try {+ hookUtils = require(path.join(PLUGIN_ROOT, "scripts", "lib", "powerpages-hook-utils"));+} catch {+ process.exit(0);+}++function readPluginVersion() {+ try {+ const manifest = JSON.parse(+ fs.readFileSync(path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"), "utf8")+ );+ return manifest.version || "unknown";+ } catch {+ return "unknown";+ }+}++function readIkey() {+ // Test/override seam: POWER_PLATFORM_SKILLS_IKEY_JSON points at an alternate+ // ikey.json so tests can flip disabled/iKey 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 =+ override && override.trim()+ ? override+ : 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,+ };+ } 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 };+ }+}++function osFriendlyName(platform) {+ if (platform === "win32") return "Windows";+ if (platform === "darwin") return "Mac";+ if (platform === "linux") return "Linux";+ return platform;+}++function readStdin() {+ return new Promise((resolve) => {+ let buf = "";+ process.stdin.setEncoding("utf8");+ process.stdin.on("data", (c) => (buf += c));+ process.stdin.on("end", () => resolve(buf));+ process.stdin.on("error", () => resolve(buf));+ });+}++(async () => {+ const raw = await readStdin();+ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch {+ process.exit(0);+ }++ const skillName = hookUtils.getTrackedSkillFromToolInput(parsed.tool_input);+ if (!skillName) process.exit(0);++ // Repo-side hard-off / unconfigured: gate BEFORE the pac shell-outs+ // (`pac auth who` ~3s + `pac --version` ~2s) so a disabled or unconfigured+ // plugin costs effectively nothing. The user opt-out is NOT a fast-path: the+ // 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();+ if (disabled) process.exit(0);+ if (!ikey) process.exit(0);++ const correlation_id = crypto.randomUUID();++ const configDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";+ const fakeProbe = process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "";++ let pacAuth = null;+ try {+ pacAuth = pacAuthLib.readPacAuth();+ } catch {+ pacAuth = null;+ }++ let agentInfo = {};+ try {+ agentInfo = {+ ...agentInfoLib.readAiAgent(),+ pacCliVersion: agentInfoLib.readPacCliVersion(),+ };+ } catch {+ agentInfo = {};+ }++ const fields = {+ pluginName: "power-pages",+ pluginVersion: readPluginVersion(),+ sessionId: sessionLib.getSessionId(sessionLib.resolveHostSessionId(parsed)),+ correlationId: correlation_id,+ osName: osFriendlyName(process.platform),+ osVersion: os.release(),+ nodeVersion: "v" + String(process.versions.node).split(".")[0],+ skillName,+ };+ if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;+ if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;+ if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;+ if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;+ if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;++ try {+ emitSpawn.fireAndForget(+ eventsLib.buildSkillStarted(eventStreamName, fields),+ {+ iKey: ikey,+ collectorUrl,+ 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"),+ }+ );+ } catch {+ // fail closed+ }++ process.exit(0);+})().catch(() => process.exit(0));diff --git a/plugins/power-pages/hooks/run-user-prompt-telemetry.js b/plugins/power-pages/hooks/run-user-prompt-telemetry.jsnew file mode 100644index 000000000..1c47cc447--- /dev/null+++ b/plugins/power-pages/hooks/run-user-prompt-telemetry.js@@ -0,0 +1,79 @@+#!/usr/bin/env node+"use strict";++const path = require("node:path");+const fs = require("node:fs");++const PLUGIN_ROOT = path.resolve(__dirname, "..");+const TELEMETRY_DIR = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry");++let emitFromPrompt, hookUtils, sessionLib;+try {+ emitFromPrompt = require(path.join(+ TELEMETRY_DIR,+ "lib",+ "emit-from-prompt"+ ));+ hookUtils = require(path.join(+ PLUGIN_ROOT,+ "scripts",+ "lib",+ "powerpages-hook-utils"+ ));+ sessionLib = require(path.join(TELEMETRY_DIR, "lib", "session"));+} catch {+ process.exit(0);+}++function readPluginVersion() {+ try {+ const manifest = JSON.parse(+ fs.readFileSync(+ path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"),+ "utf8"+ )+ );+ return manifest.version || "unknown";+ } catch {+ return "unknown";+ }+}++function readStdin() {+ return new Promise((resolve) => {+ let buf = "";+ process.stdin.setEncoding("utf8");+ process.stdin.on("data", (c) => (buf += c));+ process.stdin.on("end", () => resolve(buf));+ process.stdin.on("error", () => resolve(buf));+ });+}++(async () => {+ const raw = await readStdin();+ if (!raw) process.exit(0);++ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch {+ process.exit(0);+ }++ const prompt = typeof parsed.prompt === "string" ? parsed.prompt : "";+ if (!prompt) process.exit(0);++ try {+ emitFromPrompt.emitSkillStartedFromPrompt(prompt, {+ pluginName: "power-pages",+ pluginVersion: readPluginVersion(),+ trackedSkills: hookUtils.TRACKED_SKILLS,+ telemetryDir: TELEMETRY_DIR,+ sessionId: sessionLib.resolveHostSessionId(parsed),+ });+ } catch {+ // fail closed — telemetry never blocks the user's prompt+ }++ process.exit(0);+})().catch(() => process.exit(0));diff --git a/plugins/power-pages/scripts/lib/powerpages-hook-utils.js b/plugins/power-pages/scripts/lib/powerpages-hook-utils.jsindex a7c8878c4..9775fe0d5 100644--- a/plugins/power-pages/scripts/lib/powerpages-hook-utils.js+++ b/plugins/power-pages/scripts/lib/powerpages-hook-utils.js@@ -1,64 +1,60 @@-const TRACKED_SKILLS = {- 'activate-site': {- validatorScript: 'skills/activate-site/scripts/validate-activation.js',- },- 'add-sample-data': {},- 'add-seo': {- validatorScript: 'skills/add-seo/scripts/validate-seo.js',- },- 'audit-permissions': {- validatorScript: 'skills/audit-permissions/scripts/validate-audit.js',- },- 'configure-env-variables': {- validatorScript: 'skills/configure-env-variables/scripts/validate-env-variables.js',- },- 'create-site': {- validatorScript: 'skills/create-site/scripts/validate-site.js',- },- 'create-webroles': {- validatorScript: 'skills/create-webroles/scripts/validate-webroles.js',- },- 'deploy-pipeline': {- validatorScript: 'skills/deploy-pipeline/scripts/validate-deploy-pipeline.js',- },- 'ensure-pipelines-host': {- validatorScript: 'skills/ensure-pipelines-host/scripts/validate-ensure-host.js',- },- 'force-link-environment': {- validatorScript: 'skills/force-link-environment/scripts/validate-force-link.js',- },- 'export-solution': {- validatorScript: 'skills/export-solution/scripts/validate-export.js',- },- 'import-solution': {- validatorScript: 'skills/import-solution/scripts/validate-import.js',- },- 'add-cloud-flow': {- validatorScript: 'skills/add-cloud-flow/scripts/validate-cloudflow.js',- },- 'add-server-logic': {- validatorScript: 'skills/add-server-logic/scripts/validate-serverlogic.js',- },- 'integrate-webapi': {- validatorScript: 'skills/integrate-webapi/scripts/validate-webapi-integration.js',- },- 'plan-alm': {- validatorScript: 'skills/plan-alm/scripts/validate-plan-alm.js',- },- 'setup-auth': {- validatorScript: 'skills/setup-auth/scripts/validate-auth.js',- },- 'setup-datamodel': {- validatorScript: 'skills/setup-datamodel/scripts/validate-datamodel.js',- },- 'setup-pipeline': {- validatorScript: 'skills/setup-pipeline/scripts/validate-pipeline.js',- },- 'setup-solution': {- validatorScript: 'skills/setup-solution/scripts/validate-solution.js',- },- 'test-site': {},-};+const fs = require('fs');+const path = require('path');++const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');+const SKILLS_DIR = path.join(PLUGIN_ROOT, 'skills');++// Skills that must never emit usage telemetry about themselves. The telemetry+// control skill is excluded so checking/toggling telemetry does not self-emit.+const EXCLUDED_FROM_TRACKING = new Set(['telemetry']);++function discoverValidatorScript(skillName) {+ const scriptsDir = path.join(SKILLS_DIR, skillName, 'scripts');+ if (!fs.existsSync(scriptsDir)) {+ return null;+ }++ const validators = fs+ .readdirSync(scriptsDir, { withFileTypes: true })+ .filter((entry) => entry.isFile() && /^validate.*\.js$/.test(entry.name))+ .map((entry) => entry.name)+ .sort();++ if (validators.length === 0) {+ return null;+ }++ return path.posix.join('skills', skillName, 'scripts', validators[0]);+}++function discoverTrackedSkills() {+ // Null-prototype map: membership is tested via bracket access (TRACKED_SKILLS[name]),+ // so a plain {} would make inherited keys like "toString"/"constructor"/"__proto__"+ // test truthy and emit bogus skill names. A null-proto object has no such keys.+ const trackedSkills = Object.create(null);++ const entries = fs+ .readdirSync(SKILLS_DIR, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .sort((a, b) => a.name.localeCompare(b.name));++ for (const entry of entries) {+ const skillName = entry.name;+ if (EXCLUDED_FROM_TRACKING.has(skillName)) {+ continue;+ }+ if (!fs.existsSync(path.join(SKILLS_DIR, skillName, 'SKILL.md'))) {+ continue;+ }++ const validatorScript = discoverValidatorScript(skillName);+ trackedSkills[skillName] = validatorScript ? { validatorScript } : {};+ }++ return trackedSkills;+}++const TRACKED_SKILLS = discoverTrackedSkills();function detectTrackedSkill(value) {if (typeof value !== 'string') {diff --git a/plugins/power-pages/scripts/lib/telemetry/ikey.json b/plugins/power-pages/scripts/lib/telemetry/ikey.jsonnew file mode 100644index 000000000..fda9ae55d--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/ikey.json@@ -0,0 +1,6 @@+{+ "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+}diff --git a/plugins/power-pages/scripts/lib/telemetry/lib b/plugins/power-pages/scripts/lib/telemetry/libnew file mode 120000index 000000000..25132cce3--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/lib@@ -0,0 +1 @@+../../../../../shared/telemetry/lib\ No newline at end of filediff --git a/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js b/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.jsindex 227bf0de4..57caade55 100644--- a/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js+++ b/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js@@ -4,6 +4,7 @@ const fs = require('fs');const path = require('path');const {+ TRACKED_SKILLS,detectTrackedSkill,getTrackedSkillFromToolInput,getValidatorScript,@@ -15,7 +16,7 @@ test('detectTrackedSkill recognizes tracked skill references', () => {assert.equal(detectTrackedSkill('create-site'), 'create-site');assert.equal(detectTrackedSkill('/power-pages:setup-auth'), 'setup-auth');assert.equal(detectTrackedSkill('power-pages:add-seo'), 'add-seo');- assert.equal(detectTrackedSkill('/power-pages:deploy-site'), null);+ assert.equal(detectTrackedSkill('/power-pages:deploy-site'), 'deploy-site');});test('detectTrackedSkill recognizes slash command aliases without plugin prefix', () => {@@ -25,7 +26,7 @@ test('detectTrackedSkill recognizes slash command aliases without plugin prefix'assert.equal(detectTrackedSkill('/add-cloud-flow'), 'add-cloud-flow');assert.equal(detectTrackedSkill('/integrate-webapi'), 'integrate-webapi');assert.equal(detectTrackedSkill('/audit-permissions'), 'audit-permissions');- assert.equal(detectTrackedSkill('/deploy-site'), null);+ assert.equal(detectTrackedSkill('/deploy-site'), 'deploy-site');});test('getTrackedSkillFromToolInput finds a tracked skill in common fields', () => {@@ -39,13 +40,21 @@ test('getTrackedSkillFromToolInput finds a tracked skill in common fields', () =getTrackedSkillFromToolInput({ command: 'run /power-pages:integrate-webapi for this repo' }),'integrate-webapi');- assert.equal(getTrackedSkillFromToolInput({ name: 'deploy-site' }), null);+ assert.equal(getTrackedSkillFromToolInput({ name: 'deploy-site' }), 'deploy-site');});-test('getValidatorScript returns validator paths only for command-backed skills', () => {+test('getValidatorScript returns discovered validator paths when present', () => {assert.match(getValidatorScript('create-site'), /validate-site\.js$/);assert.match(getValidatorScript('add-server-logic'), /validate-serverlogic\.js$/);+ assert.match(getValidatorScript('deploy-pipeline'), /validate-deploy-pipeline\.js$/);+});++test('getValidatorScript returns null for tracked skills without validators', () => {+ assert.equal(detectTrackedSkill('deploy-site'), 'deploy-site');+ assert.equal(detectTrackedSkill('diagnose-deployment'), 'diagnose-deployment');assert.equal(getValidatorScript('test-site'), null);+ assert.equal(getValidatorScript('deploy-site'), null);+ assert.equal(getValidatorScript('diagnose-deployment'), null);assert.equal(getValidatorScript('missing-skill'), null);});@@ -77,6 +86,24 @@ test('force-link-environment is wired into TRACKED_SKILLS with its validator', (assert.match(getValidatorScript('force-link-environment'), /validate-force-link\.js$/);});+test('TRACKED_SKILLS is derived from every skill folder', () => {+ // The `telemetry` skill is intentionally excluded from tracking so checking/+ // toggling telemetry never self-emits (see EXCLUDED_FROM_TRACKING).+ const skillFolders = fs+ .readdirSync(SKILLS_DIR, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name)+ .filter((skillName) => fs.existsSync(path.join(SKILLS_DIR, skillName, 'SKILL.md')))+ .filter((skillName) => skillName !== 'telemetry')+ .sort();++ assert.deepEqual(Object.keys(TRACKED_SKILLS).sort(), skillFolders);+ for (const skillName of skillFolders) {+ assert.equal(detectTrackedSkill(`/power-pages:${skillName}`), skillName);+ assert.equal(detectTrackedSkill(`/${skillName}`), skillName);+ }+});+test('no SKILL.md declares its own hooks frontmatter (centralized PostToolUse only)', () => {// Skill-specific Stop hooks are an anti-pattern documented in// PLUGIN_DEVELOPMENT_GUIDE.md — they duplicate the centralized PostToolUse@@ -102,3 +129,20 @@ test('no SKILL.md declares its own hooks frontmatter (centralized PostToolUse on`These SKILL.md files declare hooks frontmatter — register the skill in TRACKED_SKILLS instead: ${offenders.join(', ')}`);});++test('the telemetry skill is excluded from tracking (no self-emit)', () => {+ assert.equal(TRACKED_SKILLS.telemetry, undefined);+ assert.equal(detectTrackedSkill('/power-pages:telemetry'), null);+ assert.equal(detectTrackedSkill('telemetry'), null);+ assert.equal(getTrackedSkillFromToolInput({ skill: 'power-pages:telemetry' }), null);+});++test('Object.prototype keys are not mistaken for tracked skills', () => {+ // TRACKED_SKILLS is a null-prototype map. With a plain {} these names would+ // resolve to inherited functions on bracket access and emit bogus events.+ assert.equal(detectTrackedSkill('toString'), null);+ assert.equal(detectTrackedSkill('constructor'), null);+ assert.equal(detectTrackedSkill('hasOwnProperty'), null);+ assert.equal(detectTrackedSkill('__proto__'), null);+ assert.equal(getTrackedSkillFromToolInput({ skill: 'toString' }), null);+});diff --git a/plugins/power-pages/scripts/tests/run-user-prompt-telemetry.test.js b/plugins/power-pages/scripts/tests/run-user-prompt-telemetry.test.jsnew file mode 100644index 000000000..42682b1d2--- /dev/null+++ b/plugins/power-pages/scripts/tests/run-user-prompt-telemetry.test.js@@ -0,0 +1,138 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+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() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-upt-"));+}++function runHook({ prompt, configDir, fakeProbe, ikeyPath }) {+ return spawnSync(process.execPath, [HOOK], {+ input: JSON.stringify({ prompt }),+ encoding: "utf8",+ env: {+ ...process.env,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || "",+ },+ // The enabled path shells out to `pac auth who` + `pac --version`, each+ // capped at 8s (see lib/pac-auth.js). The hook's documented budget is ~30s;+ // a 10s spawn timeout sits right on the cold-start cost and flakes when pac+ // is installed. Match the hook budget so the integration path is reliable.+ 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);+}++// Poll for a file up to timeoutMs, sleeping between checks so the test runner+// stays responsive. Returns whether the file exists at the end.+function waitForFile(filePath, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (!fs.existsSync(filePath) && Date.now() < deadline) {+ sleep(25);+ }+ return fs.existsSync(filePath);+}++test("hook emits PagesPluginEvent with top-level fields for tracked slash command", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ // Point the hook at a temp ikey.json via the override seam instead of+ // mutating the checked-in scripts/lib/telemetry/ikey.json (which would race+ // with other test files running in parallel).+ const ikeyPath = 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({+ prompt: "/power-pages:add-seo",+ configDir,+ fakeProbe: probePath,+ ikeyPath,+ });+ assert.equal(status, 0);+ assert.ok(waitForFile(probePath, 5_000), "dispatcher should have written probe");+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));+ assert.ok(probe.body.endsWith("\n"), "body must be newline-terminated");+ const body = JSON.parse(probe.body);+ assert.deepEqual(Object.keys(body).sort(), ["data", "iKey", "name", "time", "ver"]);+ assert.equal(body.name, "PagesPluginEvent");+ assert.equal(body.ver, "4.0");+ assert.match(body.iKey, /^o:/);+ assert.equal(body.data.eventName, "skill_started");+ assert.equal(body.data.eventType, "Trace");+ assert.equal(body.data.severity, "Info");+ assert.equal(body.data.pluginName, "power-pages");+ assert.equal(body.data.skillName, "add-seo");+ assert.equal(typeof body.data.sessionId, "string");+ assert.equal(typeof body.data.correlationId, "string");+ assert.equal(typeof body.data.osName, "string");+ assert.equal(typeof body.data.osVersion, "string");+ assert.match(body.data.nodeVersion, /^v\d+$/);+});++test("hook exits 0 and emits nothing for an unrelated prompt", () => {+ const configDir = mkConfigDir();+ const probePath = path.join(configDir, "probe.json");+ const { status } = runHook({+ prompt: "just some user text",+ configDir,+ fakeProbe: probePath,+ });+ assert.equal(status, 0);+ // Give any (wrongly) spawned dispatcher a chance to write before asserting+ // that nothing was emitted.+ sleep(500);+ assert.ok(!fs.existsSync(probePath), "unrelated prompt must not emit");+});++test("hook exits 0 on malformed stdin", () => {+ const configDir = mkConfigDir();+ const { status } = spawnSync(process.execPath, [HOOK], {+ input: "not json",+ encoding: "utf8",+ env: {+ ...process.env,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ },+ timeout: 10_000,+ });+ assert.equal(status, 0);+});++test("hook exits 0 on empty stdin", () => {+ const configDir = mkConfigDir();+ const { status } = spawnSync(process.execPath, [HOOK], {+ input: "",+ encoding: "utf8",+ env: {+ ...process.env,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ },+ timeout: 10_000,+ });+ assert.equal(status, 0);+});diff --git a/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.js b/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.jsnew file mode 100644index 000000000..9b11dc080--- /dev/null+++ b/plugins/power-pages/scripts/tests/telemetry-hook-posttool.test.js@@ -0,0 +1,45 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { spawnSync } = require("node:child_process");++const HOOK = path.resolve(+ __dirname,+ "../../hooks/run-skill-posttool-validation.js"+);++function mkConfigDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-ho-"));+}++function runHook({ input, configDir }) {+ return spawnSync(process.execPath, [HOOK], {+ input,+ encoding: "utf8",+ env: {+ ...process.env,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ },+ });+}++test("posttool hook exits 0 with no tracked skill (preserves existing behavior)", () => {+ const { status } = runHook({+ input: JSON.stringify({ tool_input: { skill: "nothing" } }),+ configDir: mkConfigDir(),+ });+ 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.jsnew file mode 100644index 000000000..ed64ea750--- /dev/null+++ b/plugins/power-pages/scripts/tests/telemetry-hook-pretool.test.js@@ -0,0 +1,148 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { spawnSync } = require("node:child_process");++const HOOK = path.resolve(+ __dirname,+ "../../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" } })+ );+ }+ 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" } }),+ configDir: mkConfigDir(),+ });+ 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);+});++test("exits 0 when skill is tracked (placeholder iKey → no-op emit)", () => {+ const { status } = runHook({+ input: JSON.stringify({ tool_input: { skill: "create-site" } }),+ configDir: mkConfigDir(),+ });+ 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.+ 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,+ });+ 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/plugins/power-pages/skills/telemetry/SKILL.md b/plugins/power-pages/skills/telemetry/SKILL.mdnew file mode 100644index 000000000..082300b49--- /dev/null+++ b/plugins/power-pages/skills/telemetry/SKILL.md@@ -0,0 +1,16 @@+---+name: telemetry+description: >+ Use this skill when the user wants to enable, disable, turn on or off, opt out+ of, opt in to, or check the status of power-pages telemetry / anonymous usage+ data. Triggers: "disable telemetry", "turn off telemetry", "opt out of+ telemetry", "stop collecting usage data", "enable telemetry", "telemetry status".+user-invocable: true+argument-hint: "on | off | status"+allowed-tools: Bash+model: haiku+---++> **Plugin check**: Run `node "${CLAUDE_PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.++**Workflow: [telemetry-workflow.md](${CLAUDE_PLUGIN_ROOT}/skills/telemetry/telemetry-workflow.md)** — Read and follow all steps defined in that bundled file.diff --git a/plugins/power-pages/skills/telemetry/telemetry-workflow.md b/plugins/power-pages/skills/telemetry/telemetry-workflow.mdnew file mode 120000index 000000000..182d8d58a--- /dev/null+++ b/plugins/power-pages/skills/telemetry/telemetry-workflow.md@@ -0,0 +1 @@+../../../../shared/skills/telemetry/telemetry-workflow.md\ No newline at end of filediff --git a/shared/skills/telemetry/SKILL.template.md b/shared/skills/telemetry/SKILL.template.mdnew file mode 100644index 000000000..866cc1587--- /dev/null+++ b/shared/skills/telemetry/SKILL.template.md@@ -0,0 +1,14 @@+---+name: telemetry+description: >+ Use this skill when the user wants to enable, disable, turn on or off, opt out+ of, opt in to, or check the status of {{PLUGIN_NAME}} telemetry / anonymous+ usage data. Triggers: "disable telemetry", "turn off telemetry", "opt out of+ telemetry", "stop collecting usage data", "enable telemetry", "telemetry status".+user-invocable: true+argument-hint: "on | off | status"+allowed-tools: Bash+model: haiku+---++**Workflow: [telemetry-workflow.md](${CLAUDE_PLUGIN_ROOT}/skills/telemetry/telemetry-workflow.md)** — Read and follow all steps defined in that bundled file.diff --git a/shared/skills/telemetry/telemetry-workflow.md b/shared/skills/telemetry/telemetry-workflow.mdnew file mode 100644index 000000000..8d33066f5--- /dev/null+++ b/shared/skills/telemetry/telemetry-workflow.md@@ -0,0 +1,27 @@+# Telemetry control workflow++The user invoked `/<plugin>:telemetry [on | off | status]` to control anonymous+usage telemetry for this plugin. Default to `status` when no argument is given.++## Steps++1. Read the action from `$ARGUMENTS`. It must be one of `on`, `off`, or `status`.+ If it is empty or anything else, use `status`.+2. Run the synced CLI (it auto-detects the plugin from the plugin manifest):++ ```bash+ node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/telemetry/lib/telemetry-config.js" --action <action>+ ```++3. Show the command's stdout to the user verbatim. Do not add or remove lines.++## What to know (for answering follow-ups)++- `off` stops transmission to Microsoft. **Nothing leaves the machine.** A local+ diagnostic log is still written at `~/.power-platform-skills/events.jsonl`.+- `on` re-enables transmission. The choice is **per-user and per-plugin** and+ takes effect on the next event (no restart).+- **No personal data is ever collected.** Telemetry is anonymous: it records only+ things like skill name, plugin version, OS, and Node version. It never includes+ file paths, prompts, tool inputs, site names, URLs, credentials, usernames, or+ hostnames.diff --git a/shared/telemetry/README.md b/shared/telemetry/README.mdnew file mode 100644index 000000000..43566d7e6--- /dev/null+++ b/shared/telemetry/README.md@@ -0,0 +1,189 @@+# Shared 1DS Telemetry Library++Canonical source for 1DS telemetry used by plugins in this repo. Each adopting plugin **symlinks** this library into its own tree: `plugins/<plugin>/scripts/lib/telemetry/lib` is a symlink to `shared/telemetry/lib`, so there is a single source of truth and no copy to keep in sync.++`shared/telemetry/lib` is the **only** copy of the library. The marketplace installer dereferences the per-plugin symlink into the installed plugin at install time, so the library ships without a per-plugin copy. Each plugin keeps its own real `ikey.json` next to the symlink.++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.++```+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+ ├─ 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)+ ├─ iKey missing/placeholder → exit (mirror already written, no POST)+ ├─ build CS4.0 envelope (same time + sanitized data)+ └─ HTTPS POST to 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 whose+field names ARE the Kusto column names. It is written for **every** event that+clears 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.++The per-plugin user opt-out (`config.json` `telemetry[<plugin>] === "off"`, set+via `/<plugin>:telemetry off`) suppresses **transmission**, not the local+diagnostic mirror — so an opted-out run still writes `events.jsonl` (and pays the+same event-building cost as an enabled run), it just never POSTs.++## What is sent++Every event carries a fixed allowlist enforced by `lib/events.js`. Field names match the destination Kusto column names (camelCase).++**Identity / context (on every event):**++- `pluginName`, `pluginVersion` — read from the plugin's `.claude-plugin/plugin.json`+- `sessionId` — random UUID generated once per Node process; not persisted+- `correlationId` — a per-start unique ID generated inline at emit time+- `osName`, `osVersion` — `process.platform` and OS release string+- `nodeVersion` — major version only, e.g. `v22`++**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+- `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.++**Per-event:**++- `skillName` (on every event)+- `eventInfo` — caller-supplied JSON object (dynamic Kusto column). The caller is responsible for not putting PII in this payload.++## 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.++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.++## Privacy posture++- **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.++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.++---++## Layout++```+shared/telemetry/+├─ ikey.json # placeholder template config (each plugin keeps its own real ikey.json)+├─ lib/+│ ├─ events.js # FIELD_TYPES allowlist + buildSkillStarted+│ ├─ emit-spawn.js # fireAndForget — spawn detached dispatcher+│ ├─ emit-dispatcher.js # detached child — kill switches, 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+│ ├─ 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+│ ├─ scrubber.js # legacy text-scrubbing helper (unused by default — kept for callers that need it)+│ └─ local-log.js # appends every emitted event to ~/.power-platform-skills/events.jsonl (irrespective of iKey), with 10 MB rotation+└─ tests/ # node:test coverage for every module above+```++---++## Adopting in a new plugin++These steps assume your plugin already lives under `plugins/<your-plugin>/` with a `.claude-plugin/plugin.json` and `hooks/hooks.json`.++### 1. Link the library++Create a git symlink at `plugins/<your-plugin>/scripts/lib/telemetry/lib` pointing at the relative path to `shared/telemetry/lib`. From the `telemetry` directory that target is `../../../../../shared/telemetry/lib` (five levels up to the repo root).++Create it as a mode-`120000` blob so it works on every checkout regardless of local symlink privileges (the same way the skill-workflow symlinks under `skills/*/` were made):++```bash+# from the repo root+TARGET=plugins/<your-plugin>/scripts/lib/telemetry+mkdir -p "$TARGET"+hash=$(printf '../../../../../shared/telemetry/lib' | git hash-object -w --stdin)+git update-index --add --cacheinfo 120000,$hash,"$TARGET/lib"+git checkout -- "$TARGET/lib"+```++Now `scripts/lib/telemetry/lib` resolves to the shared library — there is no copy to keep in sync.++### 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):++```json+{+ "instrumentationKey": "<your 1DS instrumentation key>",+ "collector_url": "https://<region>-mobile.events.data.microsoft.com/OneCollector/1.0/",+ "event_stream_name": "<your Kusto stream / annotation name>",+ "disabled": true+}+```++**Ship with `disabled: true`** until the tenant-side annotation, Kusto table, and FieldNameMappings are provisioned. Flip to `false` in a separate PR once verified.++**Posture rule:** the **committed** `ikey.json` must stay `disabled: true`. A working-tree `disabled: false` is a local experiment only — never commit it.++### 3. Register hooks++In `plugins/<your-plugin>/hooks/hooks.json`, register the three hook scripts that ship with this library pattern. The Power Pages plugin's `hooks.json` is the reference example. Copy these three hook entry points into your `hooks/` directory:++- `run-skill-pretool-telemetry.js` — emits `skill_started` on `PreToolUse(Skill)`+- `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.++### 4. Verify locally++Run the plugin's test suite:++```bash+node --test plugins/<your-plugin>/scripts/tests/*.test.js+```++Then invoke one of your tracked skills with `disabled: true` and confirm via Claude Code's hook logs that no telemetry-related work happens. With `disabled: false` and a real iKey, set `POWER_PLATFORM_SKILLS_FAKE_HTTPS=/tmp/probe.json` and verify the probe file is written with the expected envelope shape.++---++## Updating the shared library++Edit `shared/telemetry/lib/` directly. Because each adopting plugin's `scripts/lib/telemetry/lib` is a **symlink** to this directory, the change is live for every plugin immediately — there is no copy to re-sync and nothing to propagate per-plugin.++Each plugin's `ikey.json` is a separate real file (not symlinked), so editing the shared library never touches a plugin's provisioned key.++If you change the wire-level shape (envelope, transport, allowlist), it applies to every adopting plugin at once — bump and validate accordingly.++## Strict allowlist++`shared/telemetry/lib/events.js` enforces exactly the fields documented above. Never add a field to a builder without:++1. Adding it to `FIELD_TYPES` in `events.js`+2. Adding the corresponding column to the Kusto stream / annotation+3. Updating this README's "What is sent" section++## Test seams++Every module exposes injectable test seams via `opts._xxx` properties so tests run hermetically (no real network, no real PAC shellouts):++- `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+- `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.jsonnew file mode 100644index 000000000..50d1c141b--- /dev/null+++ b/shared/telemetry/ikey.json@@ -0,0 +1,6 @@+{+ "instrumentationKey": "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",+ "collector_url": "",+ "event_stream_name": "PluginEventStreamPlaceholder",+ "disabled": true+}diff --git a/shared/telemetry/lib/agent-info.js b/shared/telemetry/lib/agent-info.jsnew file mode 100644index 000000000..3904f5bc1--- /dev/null+++ b/shared/telemetry/lib/agent-info.js@@ -0,0 +1,214 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const { execFileSync } = require("node:child_process");++let pacCliVersionCache;++// Reads the PAC CLI version once per process via `pac --version`. Best-effort+// and fail-closed: missing executable, timeout, or unparseable output all+// resolve to "".+//+// PAC 2.x prints the version banner ("Version: X.Y.Z+...") to stdout as part+// of its preamble but then treats `--version` as an unknown command and+// exits with status 1. execFileSync throws on non-zero exit, attaching the+// captured stdout to err.stdout — so we parse that fallback path too.+function readPacCliVersion(opts = {}) {+ if (pacCliVersionCache !== undefined) return pacCliVersionCache;+ if (opts._exec === false) {+ pacCliVersionCache = "";+ return "";+ }+ const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ let stdout = "";+ try {+ stdout = exec("pac", ["--version"], {+ encoding: "utf8",+ timeout: 8000,+ stdio: ["ignore", "pipe", "pipe"],+ });+ } catch (err) {+ stdout = (err && err.stdout) ? String(err.stdout) : "";+ }+ const match = String(stdout || "").match(/Version:\s*(\d+\.\d+\.\d+(?:\.\d+)?)/);+ pacCliVersionCache = match ? match[1] : "";+ return pacCliVersionCache;+}++// Test seam.+function _resetCache() {+ pacCliVersionCache = undefined;+}++// Parses a dotted semver out of the AI_AGENT env var. Claude Code sets+// AI_AGENT=claude-code_<maj>-<min>-<patch>_agent (e.g.+// "claude-code_2-1-156_agent"); the version segment uses dashes, so we+// normalize separators to dots. The "claude-code" name prefix carries no+// digits, so the first numeric run is the version.+function parseVersionFromAiAgent(aiAgent) {+ if (typeof aiAgent !== "string") return "";+ const match = aiAgent.match(/\d+(?:[._-]\d+)+/);+ return match ? match[0].replace(/[._-]/g, ".") : "";+}++// Reads the Claude Code CLI version. Primary source is the installed+// package.json: the hook subprocess inherits CLAUDE_CODE_EXECPATH from Claude+// Code, and jumping one directory above the executable's bin/ lands on the npm+// package root. That layout only exists for npm-global installs — the native+// installer ships a standalone binary with no sibling package.json — so when+// the read yields nothing, fall back to the version carried in AI_AGENT, which+// Claude Code sets regardless of install method.+function readClaudeCodeVersion(env) {+ const execPath = env.CLAUDE_CODE_EXECPATH;+ if (execPath) {+ try {+ const pkgPath = path.join(path.dirname(execPath), "..", "package.json");+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));+ if (pkg && typeof pkg.version === "string") return pkg.version;+ } catch {+ // pkg unreadable; fall through to the AI_AGENT fallback+ }+ }+ return parseVersionFromAiAgent(env.AI_AGENT);+}++function isTruthyEnv(value) {+ if (typeof value !== "string") return false;+ const normalized = value.trim().toLowerCase();+ return normalized !== "" && normalized !== "0" && normalized !== "false";+}++function firstEnv(env, keys) {+ for (const key of keys) {+ if (typeof env[key] === "string" && env[key]) return env[key];+ }+ return "";+}++function normalizeAgentName(name) {+ return String(name || "").toLowerCase().replace(/[^a-z0-9]/g, "");+}++const AGENT_DETECTORS = [+ {+ name: "Claude Code",+ aliases: ["claude", "claudecode"],+ isPresent: (env) => isTruthyEnv(env.CLAUDECODE),+ version: readClaudeCodeVersion,+ },+ {+ name: "Copilot CLI",+ aliases: ["copilot", "copilotcli", "githubcopilot", "githubcopilotcli"],+ isPresent: (env) => isTruthyEnv(env.COPILOT_CLI),+ version: (env) =>+ firstEnv(env, ["COPILOT_CLI_BINARY_VERSION", "COPILOT_CLI_VERSION"]),+ },+ {+ name: "Codex",+ aliases: ["codex", "codexcli", "openaicodex"],+ isPresent: (env) => isTruthyEnv(env.CODEX_CLI) || isTruthyEnv(env.CODEX),+ version: (env) =>+ firstEnv(env, [+ "CODEX_CLI_BINARY_VERSION",+ "CODEX_CLI_VERSION",+ "CODEX_VERSION",+ ]) || parseVersionFromAiAgent(env.AI_AGENT),+ },+ {+ name: "OpenCode",+ aliases: ["opencode", "opencodecli", "open_code"],+ isPresent: (env) => isTruthyEnv(env.OPENCODE_CLI) || isTruthyEnv(env.OPENCODE),+ version: (env) =>+ firstEnv(env, [+ "OPENCODE_CLI_BINARY_VERSION",+ "OPENCODE_CLI_VERSION",+ "OPENCODE_VERSION",+ ]) || parseVersionFromAiAgent(env.AI_AGENT),+ },+ {+ name: "Hermes",+ aliases: ["hermes", "hermescli", "hermesagent"],+ isPresent: (env) =>+ isTruthyEnv(env.HERMES_CLI) ||+ isTruthyEnv(env.HERMES) ||+ isTruthyEnv(env.HERMES_AGENT),+ version: (env) =>+ firstEnv(env, [+ "HERMES_CLI_BINARY_VERSION",+ "HERMES_CLI_VERSION",+ "HERMES_AGENT_VERSION",+ "HERMES_VERSION",+ ]) || parseVersionFromAiAgent(env.AI_AGENT),+ },+ {+ name: "OpenClaw",+ aliases: ["openclaw", "openclawcli"],+ isPresent: (env) =>+ isTruthyEnv(env.OPENCLAW_CLI) || isTruthyEnv(env.OPENCLAW),+ version: (env) =>+ firstEnv(env, [+ "OPENCLAW_CLI_BINARY_VERSION",+ "OPENCLAW_CLI_VERSION",+ "OPENCLAW_VERSION",+ ]) || parseVersionFromAiAgent(env.AI_AGENT),+ },+];++function detectorForName(name) {+ const normalized = normalizeAgentName(name);+ return AGENT_DETECTORS.find((detector) =>+ detector.aliases.some((alias) => normalizeAgentName(alias) === normalized)+ );+}++function detectFromAiAgent(env) {+ const aiAgent = env.AI_AGENT;+ if (typeof aiAgent !== "string" || !aiAgent) return null;+ const normalized = normalizeAgentName(aiAgent);+ const detector = AGENT_DETECTORS.find((candidate) =>+ candidate.aliases.some((alias) => normalized.includes(normalizeAgentName(alias)))+ );+ if (!detector) return null;+ return {+ aiAgentName: detector.name,+ aiAgentVersion: detector.version(env) || parseVersionFromAiAgent(aiAgent),+ };+}++function detectKnownAgent(env) {+ for (const detector of AGENT_DETECTORS) {+ if (detector.isPresent(env)) {+ return {+ aiAgentName: detector.name,+ aiAgentVersion: detector.version(env) || "",+ };+ }+ }+ return detectFromAiAgent(env);+}++// Detects the AI agent host. Prefers explicit env vars; falls back to+// built-in detection for known CLI hosts. When AI_AGENT_NAME is set explicitly+// but AI_AGENT_VERSION is empty, backfill the version from whichever detector+// matches — avoids emitting an empty aiAgentVersion just because the settings+// file only carried half the pair.+function readAiAgent(env = process.env) {+ const explicitName = env.AI_AGENT_NAME;+ const explicitVersion = env.AI_AGENT_VERSION;+ if (explicitName) {+ let version = explicitVersion || "";+ if (!version) {+ const explicitDetector = detectorForName(explicitName);+ const detected = detectKnownAgent(env);+ if (explicitDetector) version = explicitDetector.version(env) || "";+ if (!version && detected) version = detected.aiAgentVersion || "";+ }+ return { aiAgentName: explicitName, aiAgentVersion: version };+ }+ const detected = detectKnownAgent(env);+ if (detected) return detected;+ return { aiAgentName: "", aiAgentVersion: "" };+}++module.exports = { readPacCliVersion, readAiAgent, _resetCache };diff --git a/shared/telemetry/lib/emit-dispatcher.js b/shared/telemetry/lib/emit-dispatcher.jsnew file mode 100644index 000000000..b1954723d--- /dev/null+++ b/shared/telemetry/lib/emit-dispatcher.js@@ -0,0 +1,198 @@+#!/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 { FIELD_TYPES, pick } = require("./events");++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 { isTransmissionOptedOut } = require("./user-config");++// 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.+function ikeyJsonPath() {+ return (+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON ||+ path.join(__dirname, "..", "ikey.json")+ );+}++// 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() {+ try {+ const cfg = JSON.parse(fs.readFileSync(ikeyJsonPath(), "utf8"));+ return cfg.disabled === true;+ } 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;+ }+}++// 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.+const RESERVED_META_FIELDS = new Set(["eventName", "eventType", "severity"]);++// Defense-in-depth allowlist filter. The builders in events.js are the+// intended entry point and already enforce FIELD_TYPES, but the dispatcher+// receives JSON over stdin from a separate process and cannot assume that.+// Re-run pick() against FIELD_TYPES here so any field that bypasses the+// builders is dropped before it reaches the wire.+function sanitizeData(data) {+ if (!data || typeof data !== "object") return {};+ const filtered = pick(data, Object.keys(FIELD_TYPES));+ for (const key of RESERVED_META_FIELDS) {+ if (typeof data[key] === "string") filtered[key] = data[key];+ }+ return filtered;+}++// 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) {+ return {+ ver: "4.0",+ name,+ time,+ iKey: "o:" + IKEY.split("-")[0],+ data: sanitized,+ };+}++function writeProbe(filePath, { headers, body }) {+ try {+ fs.writeFileSync(filePath, JSON.stringify({ headers, body }), "utf8");+ } catch {+ // ignore+ }+}++function writeLocalLog(event) {+ try {+ const { appendLocal } = require("./local-log");+ appendLocal(event, { 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 stdin ------------------------------------------------------------+let raw = "";+process.stdin.setEncoding("utf8");+process.stdin.on("data", (c) => (raw += c));+process.stdin.on("end", () => {+ let event;+ try {+ event = JSON.parse(raw);+ } catch {+ return exitSilently();+ }++ // Compute the sanitized payload + timestamp ONCE. The sanitized data is+ // exactly what lands in Kusto (its field names ARE the Kusto column names);+ // the local mirror and the wire envelope share it so they can never diverge.+ const time = new Date().toISOString();+ const sanitized = sanitizeData(event.data);+ 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+ // 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+ // short-circuited before stdin was even read.)+ writeLocalLog(localRecord);++ // User opt-out (per plugin) — transmission only; the local mirror above is kept.+ const pluginName = event && event.data && event.data.pluginName;+ if (isUserOptedOut(pluginName)) return exitSilently();++ // Placeholder / unprovisioned mode → local mirror already written; no POST.+ const keyMissing = !IKEY || IKEY === PLACEHOLDER_IKEY || !COLLECTOR_URL;+ 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 body = JSON.stringify(envelope) + "\n";+ const headers = {+ "Content-Type": "application/x-json-stream; charset=utf-8",+ "x-apikey": IKEY,+ "Content-Length": Buffer.byteLength(body),+ };++ // Test seam: if POWER_PLATFORM_SKILLS_FAKE_HTTPS is set, write the probe+ // payload to that file and exit without calling the real network.+ if (FAKE_PROBE) {+ writeProbe(FAKE_PROBE, { headers, body });+ return exitSilently();+ }++ let url;+ try {+ url = new URL(COLLECTOR_URL);+ } catch {+ return exitSilently();+ }+ const req = https.request(+ {+ hostname: url.hostname,+ port: url.port || undefined,+ path: url.pathname + (url.search || ""),+ method: "POST",+ headers,+ },+ (res) => {+ res.on("data", () => {});+ res.on("end", exitSilently);+ }+ );+ req.on("error", exitSilently);+ req.setTimeout(4000, () => {+ req.destroy();+ exitSilently();+ });+ req.write(body);+ req.end();+});diff --git a/shared/telemetry/lib/emit-from-prompt.js b/shared/telemetry/lib/emit-from-prompt.jsnew file mode 100644index 000000000..5a6b199b9--- /dev/null+++ b/shared/telemetry/lib/emit-from-prompt.js@@ -0,0 +1,132 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const os = require("node:os");+const crypto = require("node:crypto");++const { detectSlashCommand } = require("./prompt-detector");+const { buildSkillStarted } = require("./events");+const { getSessionId } = require("./session");+const { fireAndForget } = require("./emit-spawn");+const { readPacAuth } = require("./pac-auth");+const { readPacCliVersion, readAiAgent } = require("./agent-info");++function readIkey(telemetryDir) {+ 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,+ };+ } 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 };+ }+}++function osFriendlyName(platform) {+ if (platform === "win32") return "Windows";+ if (platform === "darwin") return "Mac";+ if (platform === "linux") return "Linux";+ return platform;+}++function emitSkillStartedFromPrompt(promptText, opts = {}) {+ const {+ pluginName,+ pluginVersion,+ trackedSkills,+ telemetryDir,+ sessionId, // primed from Claude Code's hook payload (parsed.session_id)+ _emit, // test seam; defaults to fireAndForget+ _readPacAuth, // test seam; defaults to lib/pac-auth+ _readAgentInfo, // test seam; defaults to lib/agent-info+ } = opts;++ const skillName = detectSlashCommand(promptText, { pluginName, trackedSkills });+ 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);+ if (disabled) return { emitted: false, skillName };+ if (!ikey) return { emitted: false, skillName };++ const pacReader = typeof _readPacAuth === "function" ? _readPacAuth : readPacAuth;+ let pacAuth = null;+ try {+ pacAuth = pacReader();+ } catch {+ pacAuth = null;+ }++ const agentReader =+ typeof _readAgentInfo === "function"+ ? _readAgentInfo+ : () => ({+ ...readAiAgent(),+ pacCliVersion: readPacCliVersion(),+ });+ let agentInfo;+ try {+ agentInfo = agentReader() || {};+ } catch {+ agentInfo = {};+ }++ const fields = {+ pluginName,+ pluginVersion: pluginVersion || "unknown",+ sessionId: getSessionId(sessionId),+ correlationId: crypto.randomUUID(),+ osName: osFriendlyName(process.platform),+ osVersion: os.release(),+ nodeVersion: "v" + String(process.versions.node).split(".")[0],+ skillName,+ };+ if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;+ if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;+ if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;+ if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;+ if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;++ const event = buildSkillStarted(eventStreamName, fields);++ const emit = typeof _emit === "function" ? _emit : fireAndForget;+ try {+ emit(event, {+ iKey: ikey,+ collectorUrl,+ 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") : "",+ });+ } catch {+ // fail closed — telemetry never propagates errors+ }++ return { emitted: true, skillName };+}++module.exports = { emitSkillStartedFromPrompt };diff --git a/shared/telemetry/lib/emit-spawn.js b/shared/telemetry/lib/emit-spawn.jsnew file mode 100644index 000000000..1b5497f2a--- /dev/null+++ b/shared/telemetry/lib/emit-spawn.js@@ -0,0 +1,56 @@+"use strict";++const { spawn } = require("node:child_process");+const path = require("node:path");++const DISPATCHER = path.resolve(__dirname, "emit-dispatcher.js");++function fireAndForget(event, opts = {}) {+ const iKey = opts.iKey || "";+ const collectorUrl = opts.collectorUrl || "";+ const configDir = opts.configDir || "";+ const fakeProbe = opts.fakeProbe || "";+ // 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+ // __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.+ const ikeyJsonPath = opts.ikeyJsonPath || "";++ try {+ const child = spawn(process.execPath, [DISPATCHER], {+ detached: true,+ stdio: ["pipe", "ignore", "ignore"],+ env: {+ // Pass only the minimum env the dispatcher needs. Avoid spreading+ // process.env so secrets (AZURE_CLIENT_SECRET, GITHUB_TOKEN, etc.)+ // never reach the telemetry child.+ PATH: process.env.PATH || "",+ SystemRoot: process.env.SystemRoot || "",+ HOME: process.env.HOME || "",+ USERPROFILE: process.env.USERPROFILE || "",+ APPDATA: process.env.APPDATA || "",+ POWER_PLATFORM_SKILLS_IKEY: iKey,+ POWER_PLATFORM_SKILLS_COLLECTOR: collectorUrl,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe,+ // 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.+ POWER_PLATFORM_SKILLS_IKEY_JSON:+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON || ikeyJsonPath || "",+ },+ });+ try {+ child.stdin.write(JSON.stringify(event));+ child.stdin.end();+ } catch {+ // child may have already exited; swallow.+ }+ child.unref();+ } catch {+ // spawn failed — fail closed.+ }+}++module.exports = { fireAndForget };diff --git a/shared/telemetry/lib/events.js b/shared/telemetry/lib/events.jsnew file mode 100644index 000000000..51013e754--- /dev/null+++ b/shared/telemetry/lib/events.js@@ -0,0 +1,135 @@+"use strict";++// Per-field type metadata. Drives the type-aware picker so the wire payload+// always matches the Kusto column type. Types and defaults:+//+// "string" — Kusto column type `string`. Empty strings ARE sent (lets+// errorClass/errorDescription distinguish "explicit empty"+// from "not present"). Non-strings are dropped.+// "int" — Kusto column type `int`. Coerced via Number(); non-finite+// or negative values clamp to 0. Sent as number, not string.+// "object" — Kusto column type `dynamic` (JSON). Plain objects and+// arrays pass through; primitives, Date, RegExp, etc. are+// dropped to avoid Kusto type confusion.+// "enum:a|b|c" — Kusto column type `string`. Only the listed values are+// accepted; anything else is dropped.+//+// Both `null` and `undefined` are dropped uniformly. Empty string is allowed+// only for "string" types (deliberate — see above).+const FIELD_TYPES = {+ // Common — identity / context+ pluginName: "string",+ pluginVersion: "string",+ sessionId: "string",+ correlationId: "string",+ osName: "string",+ osVersion: "string",+ nodeVersion: "string",+ // Common — PAC + agent+ orgId: "string",+ tenantId: "string",+ pacCliVersion: "string",+ aiAgentName: "string",+ aiAgentVersion: "string",+ // Common — caller-supplied dynamic JSON+ eventInfo: "object",+ // Skill+ skillName: "string",+ // Completed-only+ outcome: "enum:success|failure",+ durationMs: "int",+ errorClass: "string",+ errorDescription: "string",+};++const COMMON_FIELDS = [+ "pluginName",+ "pluginVersion",+ "sessionId",+ "correlationId",+ "osName",+ "osVersion",+ "nodeVersion",+ "orgId",+ "tenantId",+ "pacCliVersion",+ "aiAgentName",+ "aiAgentVersion",+ "eventInfo",+];++const SKILL_FIELDS = ["skillName"];+const COMPLETED_FIELDS = ["outcome", "durationMs", "errorClass", "errorDescription"];++function isPlainStructured(v) {+ if (v === null || typeof v !== "object") return false;+ if (Array.isArray(v)) return true;+ // Only plain objects (prototype Object.prototype or null) pass through —+ // class instances like Date, RegExp, Map, Set, and Error are rejected so+ // the dynamic `eventInfo` field can't carry unexpected shapes.+ const proto = Object.getPrototypeOf(v);+ return proto === Object.prototype || proto === null;+}++function clampInt(v) {+ const n = Number(v);+ if (!Number.isFinite(n) || n < 0) return 0;+ return Math.floor(n);+}++// Type-aware pick. Drops null/undefined for every type. For each kept value,+// validates against its declared type and coerces as needed.+function pick(input, keys) {+ const out = {};+ if (!input || typeof input !== "object") return out;+ for (const k of keys) {+ const v = input[k];+ if (v === undefined || v === null) continue;+ const type = FIELD_TYPES[k];+ if (type === "string") {+ if (typeof v === "string") out[k] = v;+ } else if (type === "int") {+ out[k] = clampInt(v);+ } else if (type === "object") {+ if (isPlainStructured(v)) out[k] = v;+ } else if (typeof type === "string" && type.startsWith("enum:")) {+ const allowed = type.slice(5).split("|");+ if (typeof v === "string" && allowed.includes(v)) out[k] = v;+ }+ // unknown types: drop (defensive — no field should hit this branch).+ }+ return out;+}++function buildEvent(envelopeName, eventName, info, severity) {+ return {+ name: envelopeName,+ data: { eventName, eventType: "Trace", severity, ...info },+ };+}++function buildSkillStarted(envelopeName, input) {+ return buildEvent(+ envelopeName,+ "skill_started",+ pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),+ "Info"+ );+}++function buildSkillCompleted(envelopeName, input) {+ const severity = input && input.outcome === "failure" ? "Error" : "Info";+ return buildEvent(+ envelopeName,+ "skill_completed",+ pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS, ...COMPLETED_FIELDS]),+ severity+ );+}++module.exports = {+ buildSkillStarted,+ buildSkillCompleted,+ FIELD_TYPES,+ pick,+};diff --git a/shared/telemetry/lib/local-log.js b/shared/telemetry/lib/local-log.jsnew file mode 100644index 000000000..c5c27ba90--- /dev/null+++ b/shared/telemetry/lib/local-log.js@@ -0,0 +1,52 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");++const LOG_FILE_NAME = "events.jsonl";+const ROTATE_BYTES = 10 * 1024 * 1024; // 10 MB++function rotationName(now = new Date()) {+ const pad = (n) => String(n).padStart(2, "0");+ const stamp =+ now.getUTCFullYear().toString() ++ pad(now.getUTCMonth() + 1) ++ pad(now.getUTCDate()) ++ pad(now.getUTCHours()) ++ pad(now.getUTCMinutes()) ++ pad(now.getUTCSeconds());+ return `events.${stamp}.old`;+}++function rotateIfNeeded(dir, logFile) {+ try {+ const stat = fs.statSync(logFile);+ if (stat.size > ROTATE_BYTES) {+ try {+ fs.renameSync(logFile, path.join(dir, rotationName()));+ } catch {+ // best effort: if rename fails (file locked, etc.), keep appending.+ }+ }+ } catch {+ // no existing log — nothing to rotate+ }+}++function appendLocal(event, { configDir } = {}) {+ if (!configDir) return;+ try {+ fs.mkdirSync(configDir, { recursive: true });+ } catch {+ return;+ }+ const logFile = path.join(configDir, LOG_FILE_NAME);+ rotateIfNeeded(configDir, logFile);+ try {+ fs.appendFileSync(logFile, JSON.stringify(event) + "\n", "utf8");+ } catch {+ // swallow — fail closed+ }+}++module.exports = { appendLocal, LOG_FILE_NAME, ROTATE_BYTES };diff --git a/shared/telemetry/lib/pac-auth.js b/shared/telemetry/lib/pac-auth.jsnew file mode 100644index 000000000..2f413d506--- /dev/null+++ b/shared/telemetry/lib/pac-auth.js@@ -0,0 +1,72 @@+"use strict";++const { execFileSync } = require("node:child_process");++// Reads PAC CLI auth state by shelling out to `pac auth who` and parsing the+// banner output. Matches the convention used by+// plugins/power-pages/scripts/lib/validation-helpers.js (getPacAuthInfo /+// getEnvironmentUrl) so telemetry stays consistent with the rest of the repo.+//+// PAC's JSON profile files are an internal/undocumented format that varies+// across versions. The banner output is stable and is what other code paths+// already parse via the AUTH_KEYS list documented in the VSCode 1DS extension.+//+// Best-effort and fail-closed: missing executable, timeout, non-zero exit, or+// unparseable output all resolve to null. The result is cached per process so+// repeated hook invocations only fork once.++// Cold-start `pac auth who` on Windows is consistently ~3.5-4s (.NET runtime+// startup + cached-token validation). 3s was too tight and produced silent+// timeouts that surfaced as missing orgId/tenantId in every event. 8s gives+// comfortable headroom while staying well under the hook's 30s budget.+const TIMEOUT_MS = 8000;++let cache;++function _resetCache() {+ cache = undefined;+}++function pickLine(text, label) {+ // Match "Label: value" — case-insensitive, trims whitespace.+ const re = new RegExp("^\\s*" + label + "\\s*:\\s*(\\S.*?)\\s*$", "im");+ const match = text.match(re);+ return match ? match[1] : null;+}++function readPacAuth(opts = {}) {+ if (cache !== undefined) return cache;+ if (opts._exec === false) {+ cache = null;+ return null;+ }+ const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;+ let output;+ try {+ output = exec("pac", ["auth", "who"], {+ encoding: "utf8",+ timeout: TIMEOUT_MS,+ stdio: ["ignore", "pipe", "ignore"],+ });+ } catch {+ cache = null;+ return null;+ }+ if (typeof output !== "string" || !output) {+ cache = null;+ return null;+ }+ const tenantId = pickLine(output, "Tenant Id");+ const orgId = pickLine(output, "Organization Id");+ if (!tenantId && !orgId) {+ cache = null;+ return null;+ }+ cache = {+ orgId: orgId || "",+ tenantId: tenantId || "",+ };+ return cache;+}++module.exports = { readPacAuth, _resetCache };diff --git a/shared/telemetry/lib/prompt-detector.js b/shared/telemetry/lib/prompt-detector.jsnew file mode 100644index 000000000..69ebd6701--- /dev/null+++ b/shared/telemetry/lib/prompt-detector.js@@ -0,0 +1,28 @@+"use strict";++function detectSlashCommand(promptText, { pluginName, trackedSkills } = {}) {+ if (typeof promptText !== "string" || !promptText) return null;+ if (!pluginName || !trackedSkills) return null;++ // Match both the namespaced form (`/power-pages:add-seo`) and the bare form+ // (`/add-seo`). The `pluginName:` prefix is optional because the host tool+ // controls how the slash command is surfaced in the prompt and may emit the+ // bare form without the plugin namespace. Either way the captured skill name+ // is validated against trackedSkills below, so a bare `/foo` only counts when+ // `foo` is a known skill. The trailing boundary lookahead still rejects a+ // different plugin's namespaced command (e.g. `/other-plugin:add-seo`, where+ // `other-plugin` is followed by `:` rather than a word boundary).+ const escapedPlugin = pluginName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ const re = new RegExp(+ String.raw`^\s*\/(?:` + escapedPlugin + String.raw`:)?([a-z0-9-]+)(?=\s|$|\r|\n)`+ );+ const match = promptText.match(re);+ if (!match) return null;++ const skillName = match[1];+ return Object.prototype.hasOwnProperty.call(trackedSkills, skillName)+ ? skillName+ : null;+}++module.exports = { detectSlashCommand };diff --git a/shared/telemetry/lib/scrubber.js b/shared/telemetry/lib/scrubber.jsnew file mode 100644index 000000000..517188404--- /dev/null+++ b/shared/telemetry/lib/scrubber.js@@ -0,0 +1,11 @@+"use strict";++// Placeholder. The spec allowlist already restricts payload fields to values+// that cannot contain PII. This module exists as a documented seam for a+// future regex-based pass if the allowlist ever needs to carry user strings.++function scrub(value) {+ return value;+}++module.exports = { scrub };diff --git a/shared/telemetry/lib/session.js b/shared/telemetry/lib/session.jsnew file mode 100644index 000000000..cbf89884d--- /dev/null+++ b/shared/telemetry/lib/session.js@@ -0,0 +1,43 @@+"use strict";++const crypto = require("node:crypto");++// Hooks run as fresh Node processes, so a module-level UUID would be unique+// per hook invocation — every event in a Claude Code session would carry a+// different sessionId, breaking session-scoped analysis. Each hook reads+// Claude Code's session_id from the stdin payload and primes this cache+// with it so all events emitted from that hook (and within that process)+// share a single sessionId.+let cached;++function getSessionId(override) {+ if (typeof override === "string" && override) {+ cached = override;+ return cached;+ }+ if (!cached) cached = crypto.randomUUID();+ return cached;+}++// Multi-host session-id resolver. Both Claude Code and GitHub Copilot CLI+// surface their session id through the hook stdin payload. Field-name+// convention may vary by host; check known variants in precedence order.+// Returns "" when no usable id is present so the caller's subsequent+// getSessionId("") falls back to a per-process UUID.+function resolveHostSessionId(payload) {+ if (!payload || typeof payload !== "object") return "";+ if (typeof payload.session_id === "string" && payload.session_id) {+ return payload.session_id;+ }+ if (typeof payload.sessionId === "string" && payload.sessionId) {+ return payload.sessionId;+ }+ return "";+}++// Test seam.+function _resetCache() {+ cached = undefined;+}++module.exports = { getSessionId, resolveHostSessionId, _resetCache };diff --git a/shared/telemetry/lib/telemetry-config.js b/shared/telemetry/lib/telemetry-config.jsnew file mode 100644index 000000000..6753004fa--- /dev/null+++ b/shared/telemetry/lib/telemetry-config.js@@ -0,0 +1,90 @@+#!/usr/bin/env node+"use strict";++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { readTelemetryChoice, setTelemetryChoice } = require("./user-config");++const ANONYMITY =+ "ℹ️ No personal data is collected. Telemetry is anonymous — it records only\n" ++ " things like skill name, plugin version, OS, and Node version. It never\n" ++ " includes file paths, prompts, tool inputs, site names, URLs, credentials,\n" ++ " usernames, or hostnames.";++function getArg(name) {+ const i = process.argv.indexOf(`--${name}`);+ return i !== -1 && i + 1 < process.argv.length ? process.argv[i + 1] : null;+}++function configDir() {+ return (+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR ||+ path.join(os.homedir(), ".power-platform-skills")+ );+}++function logPath() {+ return path.join(configDir(), "events.jsonl");+}++// --plugin wins; otherwise auto-detect from the plugin manifest 4 levels up+// (.../plugins/<plugin>/scripts/lib/telemetry/lib/telemetry-config.js).+function resolvePlugin() {+ const explicit = getArg("plugin");+ if (explicit) return explicit;+ try {+ const manifestPath = path.resolve(+ __dirname, "..", "..", "..", "..", ".claude-plugin", "plugin.json"+ );+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));+ return manifest.name || null;+ } catch {+ return null;+ }+}++function out(s) {+ process.stdout.write(s + "\n");+}++function main() {+ const action = getArg("action");+ const plugin = resolvePlugin();+ if (!plugin || !["on", "off", "status"].includes(action)) {+ out("Usage: telemetry-config.js --action <on|off|status> [--plugin <name>]");+ process.exit(2);+ }+ const dir = configDir();++ if (action === "status") {+ const on = readTelemetryChoice(dir, plugin) !== "off"; // default ON+ if (on) {+ out(`Telemetry (${plugin}): ON`);+ out(ANONYMITY);+ out(`Local log: ${logPath()}`);+ } else {+ out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);+ out(`A local diagnostic log is still kept at ${logPath()}.`);+ out(`Re-enable anytime with /${plugin}:telemetry on.`);+ out(ANONYMITY);+ }+ process.exit(0);+ }++ if (!setTelemetryChoice(dir, plugin, action)) {+ out(`Could not update the telemetry setting (config dir not writable).`);+ process.exit(1);+ }+ if (action === "off") {+ out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);+ out(`A local diagnostic log is still kept at ${logPath()}.`);+ out(`Re-enable anytime with /${plugin}:telemetry on.`);+ } else {+ out(`Telemetry (${plugin}): ON`);+ }+ out(ANONYMITY);+ process.exit(0);+}++main();diff --git a/shared/telemetry/lib/user-config.js b/shared/telemetry/lib/user-config.jsnew file mode 100644index 000000000..01941a237--- /dev/null+++ b/shared/telemetry/lib/user-config.js@@ -0,0 +1,64 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");++const CONFIG_FILE_NAME = "config.json";++function configPath(configDir) {+ return path.join(configDir, CONFIG_FILE_NAME);+}++// Reads the whole config object; returns {} on any error (missing/corrupt).+function readConfig(configDir) {+ try {+ const parsed = JSON.parse(fs.readFileSync(configPath(configDir), "utf8"));+ // Arrays pass `typeof === "object"` but break the merge-write: setTelemetryChoice+ // would set `.telemetry` on the array and JSON.stringify would silently drop it,+ // reporting success while persisting nothing. Treat non-plain objects as empty.+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};+ } catch {+ return {};+ }+}++// Returns "on" | "off" | null (null = unset / not a valid value).+function readTelemetryChoice(configDir, pluginName) {+ if (!configDir || !pluginName) return null;+ const t = readConfig(configDir).telemetry;+ if (!t || typeof t !== "object") return null;+ const v = t[pluginName];+ return v === "on" || v === "off" ? v : null;+}++function isTransmissionOptedOut(configDir, pluginName) {+ return readTelemetryChoice(configDir, pluginName) === "off";+}++// Merge-writes { telemetry: { [pluginName]: choice } }, preserving every other+// key. Returns true on success, false on bad input or I/O failure. Never throws.+function setTelemetryChoice(configDir, pluginName, choice) {+ if (!configDir || !pluginName) return false;+ if (choice !== "on" && choice !== "off") return false;+ try {+ fs.mkdirSync(configDir, { recursive: true });+ } catch {+ return false;+ }+ const cfg = readConfig(configDir);+ if (!cfg.telemetry || typeof cfg.telemetry !== "object") cfg.telemetry = {};+ cfg.telemetry[pluginName] = choice;+ try {+ fs.writeFileSync(configPath(configDir), JSON.stringify(cfg, null, 2) + "\n", "utf8");+ return true;+ } catch {+ return false;+ }+}++module.exports = {+ readTelemetryChoice,+ setTelemetryChoice,+ isTransmissionOptedOut,+ CONFIG_FILE_NAME,+};diff --git a/shared/telemetry/tests/agent-info.test.js b/shared/telemetry/tests/agent-info.test.jsnew file mode 100644index 000000000..a948f7733--- /dev/null+++ b/shared/telemetry/tests/agent-info.test.js@@ -0,0 +1,347 @@+"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 agentInfo = require("../lib/agent-info");++function withClaudeCodeFixture(fn) {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-agent-"));+ fs.mkdirSync(path.join(tmp, "bin"));+ fs.writeFileSync(+ path.join(tmp, "package.json"),+ JSON.stringify({ name: "@anthropic-ai/claude-code", version: "2.0.0" })+ );+ const execPath = path.join(tmp, "bin", "claude.exe");+ fs.writeFileSync(execPath, "");+ try {+ fn({ tmp, execPath });+ } finally {+ fs.rmSync(tmp, { recursive: true, force: true });+ }+}++test("readAiAgent returns Claude Code + version when CLAUDECODE=1 and pkg.json exists", () => {+ withClaudeCodeFixture(({ execPath }) => {+ const result = agentInfo.readAiAgent({+ CLAUDECODE: "1",+ CLAUDE_CODE_EXECPATH: execPath,+ });+ assert.deepEqual(result, { aiAgentName: "Claude Code", aiAgentVersion: "2.0.0" });+ });+});++test("readAiAgent returns Claude Code with empty version when EXECPATH missing and no AI_AGENT", () => {+ const result = agentInfo.readAiAgent({ CLAUDECODE: "1" });+ assert.deepEqual(result, { aiAgentName: "Claude Code", aiAgentVersion: "" });+});++test("readAiAgent falls back to AI_AGENT version on native installs (EXECPATH has no sibling package.json)", () => {+ // Native installer: execpath points at a standalone binary with no+ // ../package.json. The npm-layout read fails; AI_AGENT carries the version.+ const result = agentInfo.readAiAgent({+ CLAUDECODE: "1",+ CLAUDE_CODE_EXECPATH: path.join(os.tmpdir(), "does-not-exist", "bin", "claude.exe"),+ AI_AGENT: "claude-code_2-1-156_agent",+ });+ assert.deepEqual(result, { aiAgentName: "Claude Code", aiAgentVersion: "2.1.156" });+});++test("readAiAgent falls back to AI_AGENT version when EXECPATH is unset", () => {+ const result = agentInfo.readAiAgent({+ CLAUDECODE: "1",+ AI_AGENT: "claude-code_2-1-156_agent",+ });+ assert.deepEqual(result, { aiAgentName: "Claude Code", aiAgentVersion: "2.1.156" });+});++test("readAiAgent: npm package.json version wins over AI_AGENT when both available", () => {+ withClaudeCodeFixture(({ execPath }) => {+ const result = agentInfo.readAiAgent({+ CLAUDECODE: "1",+ CLAUDE_CODE_EXECPATH: execPath, // package.json says 2.0.0+ AI_AGENT: "claude-code_9-9-9_agent",+ });+ assert.equal(result.aiAgentVersion, "2.0.0");+ });+});++test("readAiAgent: AI_AGENT with no parseable version yields empty version", () => {+ const result = agentInfo.readAiAgent({+ CLAUDECODE: "1",+ AI_AGENT: "claude-code_agent", // no numeric version segment+ });+ assert.deepEqual(result, { aiAgentName: "Claude Code", aiAgentVersion: "" });+});++test("readAiAgent: AI_AGENT fallback also backfills when only AI_AGENT_NAME is set", () => {+ const result = agentInfo.readAiAgent({+ AI_AGENT_NAME: "Claude Code",+ // No AI_AGENT_VERSION, no resolvable EXECPATH+ CLAUDECODE: "1",+ AI_AGENT: "claude-code_2-1-156_agent",+ });+ assert.deepEqual(result, { aiAgentName: "Claude Code", aiAgentVersion: "2.1.156" });+});++test("readAiAgent returns empty when CLAUDECODE not set and no explicit env", () => {+ const result = agentInfo.readAiAgent({});+ assert.deepEqual(result, { aiAgentName: "", aiAgentVersion: "" });+});++test("readAiAgent honours explicit AI_AGENT_NAME / AI_AGENT_VERSION", () => {+ const result = agentInfo.readAiAgent({+ AI_AGENT_NAME: "Custom Agent",+ AI_AGENT_VERSION: "3.1.4",+ });+ assert.deepEqual(result, { aiAgentName: "Custom Agent", aiAgentVersion: "3.1.4" });+});++test("readAiAgent backfills aiAgentVersion from CLAUDECODE when only AI_AGENT_NAME is set", () => {+ withClaudeCodeFixture(({ execPath }) => {+ const result = agentInfo.readAiAgent({+ AI_AGENT_NAME: "Claude Code",+ // No AI_AGENT_VERSION+ CLAUDECODE: "1",+ CLAUDE_CODE_EXECPATH: execPath,+ });+ assert.deepEqual(result, { aiAgentName: "Claude Code", aiAgentVersion: "2.0.0" });+ });+});++test("readAiAgent backfills aiAgentVersion from COPILOT_CLI when only AI_AGENT_NAME is set", () => {+ const result = agentInfo.readAiAgent({+ AI_AGENT_NAME: "Copilot CLI",+ // No AI_AGENT_VERSION+ COPILOT_CLI: "1",+ COPILOT_CLI_BINARY_VERSION: "1.2.3",+ });+ assert.deepEqual(result, { aiAgentName: "Copilot CLI", aiAgentVersion: "1.2.3" });+});++test("readAiAgent returns explicit AI_AGENT_VERSION even when CLAUDECODE detect could also resolve", () => {+ // Explicit version wins over backfill+ withClaudeCodeFixture(({ execPath }) => {+ const result = agentInfo.readAiAgent({+ AI_AGENT_NAME: "Claude Code",+ AI_AGENT_VERSION: "99.99.99-explicit",+ CLAUDECODE: "1",+ CLAUDE_CODE_EXECPATH: execPath,+ });+ assert.equal(result.aiAgentVersion, "99.99.99-explicit");+ });+});++test("readAiAgent returns empty version when AI_AGENT_NAME set but no detector matches", () => {+ const result = agentInfo.readAiAgent({+ AI_AGENT_NAME: "Mystery Agent",+ // No CLAUDECODE, no COPILOT_CLI+ });+ assert.deepEqual(result, { aiAgentName: "Mystery Agent", aiAgentVersion: "" });+});++test("readAiAgent: explicit AI_AGENT_NAME wins over CLAUDECODE", () => {+ const result = agentInfo.readAiAgent({+ CLAUDECODE: "1",+ AI_AGENT_NAME: "Custom Agent",+ AI_AGENT_VERSION: "9.9.9",+ });+ assert.deepEqual(result, { aiAgentName: "Custom Agent", aiAgentVersion: "9.9.9" });+});++test("readAiAgent returns Copilot CLI + version when COPILOT_CLI=1", () => {+ const result = agentInfo.readAiAgent({+ COPILOT_CLI: "1",+ COPILOT_CLI_BINARY_VERSION: "1.0.48-2",+ });+ assert.deepEqual(result, {+ aiAgentName: "Copilot CLI",+ aiAgentVersion: "1.0.48-2",+ });+});++test("readAiAgent returns Copilot CLI with empty version when COPILOT_CLI_BINARY_VERSION missing", () => {+ const result = agentInfo.readAiAgent({ COPILOT_CLI: "1" });+ assert.deepEqual(result, { aiAgentName: "Copilot CLI", aiAgentVersion: "" });+});++test("readAiAgent: explicit AI_AGENT_NAME wins over COPILOT_CLI", () => {+ const result = agentInfo.readAiAgent({+ COPILOT_CLI: "1",+ COPILOT_CLI_BINARY_VERSION: "1.0.48-2",+ AI_AGENT_NAME: "Custom Agent",+ AI_AGENT_VERSION: "9.9.9",+ });+ assert.deepEqual(result, { aiAgentName: "Custom Agent", aiAgentVersion: "9.9.9" });+});++test("readAiAgent: CLAUDECODE wins over COPILOT_CLI when both set", () => {+ const result = agentInfo.readAiAgent({+ CLAUDECODE: "1",+ COPILOT_CLI: "1",+ COPILOT_CLI_BINARY_VERSION: "1.0.48-2",+ });+ assert.equal(result.aiAgentName, "Claude Code");+});++test("readAiAgent returns Copilot CLI when COPILOT_CLI is truthy", () => {+ const result = agentInfo.readAiAgent({+ COPILOT_CLI: "true",+ COPILOT_CLI_VERSION: "1.0.57",+ });+ assert.deepEqual(result, {+ aiAgentName: "Copilot CLI",+ aiAgentVersion: "1.0.57",+ });+});++test("readAiAgent returns Codex from CODEX_CLI env", () => {+ const result = agentInfo.readAiAgent({+ CODEX_CLI: "1",+ CODEX_CLI_VERSION: "0.8.1",+ });+ assert.deepEqual(result, {+ aiAgentName: "Codex",+ aiAgentVersion: "0.8.1",+ });+});++test("readAiAgent returns OpenCode from OPENCODE env", () => {+ const result = agentInfo.readAiAgent({+ OPENCODE: "1",+ OPENCODE_VERSION: "2.3.4",+ });+ assert.deepEqual(result, {+ aiAgentName: "OpenCode",+ aiAgentVersion: "2.3.4",+ });+});++test("readAiAgent returns Hermes from HERMES_AGENT env", () => {+ const result = agentInfo.readAiAgent({+ HERMES_AGENT: "1",+ HERMES_AGENT_VERSION: "3.4.5",+ });+ assert.deepEqual(result, {+ aiAgentName: "Hermes",+ aiAgentVersion: "3.4.5",+ });+});++test("readAiAgent returns OpenClaw from OPENCLAW_CLI env", () => {+ const result = agentInfo.readAiAgent({+ OPENCLAW_CLI: "1",+ OPENCLAW_CLI_BINARY_VERSION: "4.5.6",+ });+ assert.deepEqual(result, {+ aiAgentName: "OpenClaw",+ aiAgentVersion: "4.5.6",+ });+});++test("readAiAgent detects known agent and version from AI_AGENT", () => {+ const result = agentInfo.readAiAgent({+ AI_AGENT: "opencode_2-1-0_agent",+ });+ assert.deepEqual(result, {+ aiAgentName: "OpenCode",+ aiAgentVersion: "2.1.0",+ });+});++test("readAiAgent backfills explicit known agent version from matching env", () => {+ const result = agentInfo.readAiAgent({+ AI_AGENT_NAME: "Codex",+ CODEX_CLI_VERSION: "0.9.0",+ });+ assert.deepEqual(result, {+ aiAgentName: "Codex",+ aiAgentVersion: "0.9.0",+ });+});++test("readAiAgent ignores falsey known-agent env flags", () => {+ const result = agentInfo.readAiAgent({+ CODEX_CLI: "0",+ OPENCODE: "false",+ });+ assert.deepEqual(result, { aiAgentName: "", aiAgentVersion: "" });+});++test("readPacCliVersion parses semver from pac --version output", () => {+ agentInfo._resetCache();+ const result = agentInfo.readPacCliVersion({+ _exec: () => "Microsoft PowerPlatform CLI Version: 1.36.0",+ });+ assert.equal(result, "1.36.0");+});++test("readPacCliVersion returns empty string when pac is missing", () => {+ agentInfo._resetCache();+ const result = agentInfo.readPacCliVersion({+ _exec: () => {+ const e = new Error("ENOENT");+ e.code = "ENOENT";+ throw e;+ },+ });+ assert.equal(result, "");+});++test("readPacCliVersion returns empty string when output unparseable", () => {+ agentInfo._resetCache();+ const result = agentInfo.readPacCliVersion({+ _exec: () => "no version here",+ });+ assert.equal(result, "");+});++test("readPacCliVersion caches result across calls", () => {+ agentInfo._resetCache();+ let calls = 0;+ const exec = () => {+ calls++;+ return "Microsoft PowerPlatform CLI Version: 1.36.0";+ };+ agentInfo.readPacCliVersion({ _exec: exec });+ agentInfo.readPacCliVersion({ _exec: exec });+ assert.equal(calls, 1, "second call should hit cache");+});++test("readPacCliVersion respects _exec=false short-circuit", () => {+ agentInfo._resetCache();+ const result = agentInfo.readPacCliVersion({ _exec: false });+ assert.equal(result, "");+});++test("readPacCliVersion parses version from err.stdout when pac exits non-zero (PAC 2.x behavior)", () => {+ // PAC 2.x prints the version banner to stdout but exits with status 1+ // because it treats `--version` as an unknown command. execFileSync+ // throws on non-zero exit; we must read err.stdout for the banner.+ agentInfo._resetCache();+ const result = agentInfo.readPacCliVersion({+ _exec: () => {+ const e = new Error("Command failed: pac --version");+ e.status = 1;+ e.stdout =+ "Microsoft PowerPlatform CLI\n" ++ "Version: 2.7.4+g06bb2eb (.NET Framework 4.8.9332.0)\n" ++ "Online documentation: https://aka.ms/PowerPlatformCLI\n";+ throw e;+ },+ });+ assert.equal(result, "2.7.4");+});++test("readPacCliVersion prefers PAC version line over .NET Framework version", () => {+ agentInfo._resetCache();+ const result = agentInfo.readPacCliVersion({+ _exec: () =>+ "Microsoft PowerPlatform CLI\n" ++ "Version: 2.7.4+g06bb2eb (.NET Framework 4.8.9332.0)\n",+ });+ assert.equal(result, "2.7.4");+});diff --git a/shared/telemetry/tests/emit-dispatcher.test.js b/shared/telemetry/tests/emit-dispatcher.test.jsnew file mode 100644index 000000000..e11d8e141--- /dev/null+++ b/shared/telemetry/tests/emit-dispatcher.test.js@@ -0,0 +1,395 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { spawnSync } = require("node:child_process");++const DISPATCHER = path.resolve(__dirname, "../lib/emit-dispatcher.js");++function mkTmp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-disp-"));+}++// Writes an ikey.json with `disabled: false` so the dispatcher's kill-switch+// gate doesn't block emission-path tests. Returns its path.+function mkEnabledIkey(tmp) {+ const p = path.join(tmp, "ikey.json");+ fs.writeFileSync(+ p,+ JSON.stringify({+ instrumentationKey: "placeholder",+ collector_url: "https://example.invalid/",+ event_stream_name: "PowerPagesPluginEvent",+ disabled: false,+ })+ );+ return p;+}++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).+ if (env.off) {+ fs.writeFileSync(+ path.join(tmp, "config.json"),+ JSON.stringify({ telemetry: { "power-pages": "off" } })+ );+ }+ return spawnSync(process.execPath, [DISPATCHER], {+ input: JSON.stringify(event),+ encoding: "utf8",+ env: {+ ...process.env,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: tmp,+ POWER_PLATFORM_SKILLS_IKEY: env.iKey || "",+ POWER_PLATFORM_SKILLS_COLLECTOR: env.collectorUrl || "",+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: env.fakeProbe || "",+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyJsonPath,+ },+ });+}++const fakeEvent = {+ name: "PowerPagesPluginEvent",+ data: {+ eventName: "skill_started",+ eventType: "Trace",+ severity: "Info",+ pluginName: "power-pages",+ skillName: "add-seo",+ },+};++test("dispatcher exits 0 when iKey is placeholder", () => {+ const tmp = mkTmp();+ const { status } = runDispatcher({+ event: fakeEvent,+ env: { configDir: tmp, iKey: "PLACEHOLDER_REPLACE_BEFORE_SHIPPING", collectorUrl: "https://x" },+ });+ assert.equal(status, 0);+});++test("dispatcher exits 0 when collector URL missing", () => {+ const tmp = mkTmp();+ const { status } = runDispatcher({+ event: fakeEvent,+ env: { configDir: tmp, iKey: "real-ikey", collectorUrl: "" },+ });+ assert.equal(status, 0);+});++test("dispatcher POSTs by default (no opt-out present)", () => {+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const { status } = runDispatcher({+ event: fakeEvent,+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ fakeProbe: probePath,+ },+ });+ assert.equal(status, 0);+ assert.ok(+ fs.existsSync(probePath),+ "default-on: dispatcher must POST when no opt-out is set"+ );+});++test("dispatcher exits 0 when the plugin is opted out via config.json", () => {+ const tmp = mkTmp();+ const { status } = runDispatcher({+ event: fakeEvent,+ env: { configDir: tmp, iKey: "real-ikey", collectorUrl: "https://x", off: true },+ });+ assert.equal(status, 0);+});++test("dispatcher exits 0 on malformed stdin", () => {+ const tmp = mkTmp();+ const { status } = spawnSync(process.execPath, [DISPATCHER], {+ input: "not json",+ encoding: "utf8",+ env: {+ ...process.env,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: tmp,+ POWER_PLATFORM_SKILLS_IKEY: "real-ikey",+ POWER_PLATFORM_SKILLS_COLLECTOR: "https://x",+ POWER_PLATFORM_SKILLS_IKEY_JSON: mkEnabledIkey(tmp),+ },+ });+ assert.equal(status, 0);+});++test("dispatcher writes a probe file when fake-https points to one (happy path)", () => {+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const { status } = runDispatcher({+ event: fakeEvent,+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ fakeProbe: probePath,+ },+ });+ assert.equal(status, 0);+ assert.ok(fs.existsSync(probePath), "expected dispatcher to write probe file");+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));+ assert.equal(probe.headers["x-apikey"], "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa");+ assert.equal(probe.headers["Content-Type"], "application/x-json-stream; charset=utf-8");+ assert.ok(probe.body.endsWith("\n"), "body must be newline-terminated for x-json-stream");+ const body = JSON.parse(probe.body);+ assert.deepEqual(Object.keys(body).sort(), ["data", "iKey", "name", "time", "ver"]);+ assert.equal(body.ver, "4.0");+ assert.equal(body.name, "PowerPagesPluginEvent");+ assert.equal(body.iKey, "o:real");+ assert.match(body.time, /^\d{4}-\d{2}-\d{2}T/);+ assert.deepEqual(body.data, fakeEvent.data);+});++test("dispatcher strips unknown fields from event.data (defense-in-depth)", () => {+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const eventWithExtras = {+ name: "PowerPagesPluginEvent",+ data: {+ eventName: "skill_started",+ eventType: "Trace",+ severity: "Info",+ pluginName: "power-pages",+ skillName: "add-seo",+ // None of these should reach the wire — not in FIELD_TYPES allowlist.+ filePath: "/Users/secret/repo/file.ts",+ stackTrace: "Error: oops\n at ...",+ rawPrompt: "user prompt text",+ tokenValue: "sk-abcd1234",+ },+ };+ const { status } = runDispatcher({+ event: eventWithExtras,+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ fakeProbe: probePath,+ },+ });+ assert.equal(status, 0);+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));+ const body = JSON.parse(probe.body);+ assert.deepEqual(Object.keys(body.data).sort(), [+ "eventName",+ "eventType",+ "pluginName",+ "severity",+ "skillName",+ ]);+ assert.equal(body.data.filePath, undefined);+ assert.equal(body.data.stackTrace, undefined);+ assert.equal(body.data.rawPrompt, undefined);+ assert.equal(body.data.tokenValue, undefined);+});++test("dispatcher exits 0 when HTTPS connect is refused", () => {+ const tmp = mkTmp();+ const { status } = runDispatcher({+ event: fakeEvent,+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://127.0.0.1:1/OneCollector/1.0/",+ },+ });+ assert.equal(status, 0);+});++test("dispatcher appends to events.jsonl when iKey is placeholder", () => {+ const tmp = mkTmp();+ const { status } = runDispatcher({+ event: fakeEvent,+ env: {+ configDir: tmp,+ iKey: "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",+ collectorUrl: "https://x",+ },+ });+ assert.equal(status, 0);+ const logFile = path.join(tmp, "events.jsonl");+ assert.ok(fs.existsSync(logFile), "expected events.jsonl to be written");+ const lines = fs.readFileSync(logFile, "utf8").trim().split("\n");+ assert.equal(lines.length, 1);+ const parsed = JSON.parse(lines[0]);+ assert.equal(parsed.name, "PowerPagesPluginEvent");+ assert.equal(parsed.data.eventName, "skill_started");+});++test("dispatcher ALSO appends to events.jsonl when a real iKey POSTs (irrespective of iKey presence)", () => {+ // The local log must mirror every event sent to the collector, not only the+ // placeholder/unprovisioned case. With a real iKey + fake-https probe, BOTH+ // the probe (the would-be POST) and events.jsonl (the local mirror) exist.+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const { status } = runDispatcher({+ event: fakeEvent,+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ fakeProbe: probePath,+ },+ });+ assert.equal(status, 0);+ assert.ok(fs.existsSync(probePath), "real iKey must still POST");+ const logFile = path.join(tmp, "events.jsonl");+ assert.ok(+ fs.existsSync(logFile),+ "real iKey must ALSO write the local log"+ );+ const lines = fs.readFileSync(logFile, "utf8").trim().split("\n");+ assert.equal(lines.length, 1);+ const parsed = JSON.parse(lines[0]);+ assert.equal(parsed.name, "PowerPagesPluginEvent");+ assert.equal(parsed.data.eventName, "skill_started");+ assert.equal(parsed.data.skillName, "add-seo");+});++test("dispatcher honours the repo kill switch (ikey.json disabled:true)", () => {+ // When the configured ikey.json has `disabled: true`, the dispatcher+ // must exit before either the HTTPS POST or the local-log path runs.+ const tmp = mkTmp();+ const disabledIkey = path.join(tmp, "ikey.json");+ fs.writeFileSync(+ disabledIkey,+ JSON.stringify({+ instrumentationKey: "x",+ collector_url: "https://x",+ event_stream_name: "X",+ disabled: true,+ })+ );+ const probePath = path.join(tmp, "probe.json");+ const { status } = runDispatcher({+ event: fakeEvent,+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ fakeProbe: probePath,+ ikeyJsonPath: disabledIkey,+ },+ });+ assert.equal(status, 0);+ assert.ok(!fs.existsSync(probePath), "kill switch must skip POST");+ assert.ok(+ !fs.existsSync(path.join(tmp, "events.jsonl")),+ "kill switch must skip local log"+ );+});++test("dispatcher fails closed when ikey.json is missing/unreadable", () => {+ // The kill switch must suppress emission when its config can't be read —+ // no HTTPS POST and no local log — even though a real iKey is in env.+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const { status } = runDispatcher({+ event: fakeEvent,+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ fakeProbe: probePath,+ ikeyJsonPath: path.join(tmp, "does-not-exist.json"),+ },+ });+ assert.equal(status, 0);+ assert.ok(!fs.existsSync(probePath), "missing config must skip POST");+ assert.ok(+ !fs.existsSync(path.join(tmp, "events.jsonl")),+ "missing config must skip local log"+ );+});++test("dispatcher writes the local mirror when opted out via config, but does NOT POST", () => {+ // A per-plugin config opt-out suppresses TRANSMISSION only — the local+ // diagnostic mirror is still written. With a real iKey + fake-https probe AND+ // the opt-out set, the local log exists and the probe (would-be POST) does not.+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const { status } = runDispatcher({+ event: fakeEvent,+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ fakeProbe: probePath,+ off: true,+ },+ });+ assert.equal(status, 0);+ assert.ok(!fs.existsSync(probePath), "config opt-out must skip the POST");+ const logFile = path.join(tmp, "events.jsonl");+ assert.ok(+ fs.existsSync(logFile),+ "config opt-out must still write the local mirror"+ );+ const parsed = JSON.parse(fs.readFileSync(logFile, "utf8").trim());+ assert.equal(parsed.name, "PowerPagesPluginEvent");+ assert.equal(parsed.data.eventName, "skill_started");+});++test("a DIFFERENT plugin's opt-out does not silence this plugin", () => {+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ // config opts out 'model-apps', but the event is for 'power-pages'+ fs.writeFileSync(+ path.join(tmp, "config.json"),+ JSON.stringify({ telemetry: { "model-apps": "off" } })+ );+ const { status } = runDispatcher({+ event: fakeEvent, // pluginName: "power-pages"+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ fakeProbe: probePath,+ },+ });+ assert.equal(status, 0);+ assert.ok(+ fs.existsSync(probePath),+ "power-pages must still POST when only model-apps is off"+ );+});++test("local mirror records the same data + time that gets POSTed to Kusto", () => {+ // The on-disk record and the wire envelope share one sanitized `data` (== the+ // Kusto columns) and one `time`. The mirror intentionally omits the envelope-+ // only transport fields (ver, iKey).+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const { status } = runDispatcher({+ event: fakeEvent,+ env: {+ configDir: tmp,+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ fakeProbe: probePath,+ },+ });+ assert.equal(status, 0);+ const wire = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);+ const local = JSON.parse(+ fs.readFileSync(path.join(tmp, "events.jsonl"), "utf8").trim()+ );+ assert.equal(local.name, wire.name);+ assert.equal(local.time, wire.time);+ assert.deepEqual(local.data, wire.data);+ assert.equal(local.ver, undefined, "local mirror omits envelope-only ver");+ assert.equal(local.iKey, undefined, "local mirror omits envelope-only iKey");+});diff --git a/shared/telemetry/tests/emit-from-prompt.test.js b/shared/telemetry/tests/emit-from-prompt.test.jsnew file mode 100644index 000000000..9ed52a1a7--- /dev/null+++ b/shared/telemetry/tests/emit-from-prompt.test.js@@ -0,0 +1,316 @@+"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 { emitSkillStartedFromPrompt } = require("../lib/emit-from-prompt");++function mkTelemetryDir({ instrumentationKey, collectorUrl, eventStreamName, disabled }) {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-efp-"));+ fs.writeFileSync(+ path.join(tmp, "ikey.json"),+ JSON.stringify({+ instrumentationKey,+ collector_url: collectorUrl,+ event_stream_name: eventStreamName,+ disabled: disabled === true,+ })+ );+ return tmp;+}++const TRACKED = { "add-seo": {}, "create-site": {} };++function callWithStub({ promptText, telemetryDir, captured, pacAuth, agentInfo }) {+ return emitSkillStartedFromPrompt(promptText, {+ pluginName: "power-pages",+ pluginVersion: "1.2.3",+ trackedSkills: TRACKED,+ telemetryDir,+ _emit: (event, spawnOpts) => {+ captured.event = event;+ captured.spawnOpts = spawnOpts;+ },+ _readPacAuth: pacAuth === undefined ? () => null : () => pacAuth,+ _readAgentInfo: agentInfo === undefined ? () => ({}) : () => agentInfo,+ });+}++test("returns { emitted: false } when detection returns null", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ const result = callWithStub({+ promptText: "not a slash command",+ telemetryDir,+ captured,+ });+ assert.deepEqual(result, { emitted: false, skillName: null });+ assert.equal(captured.event, undefined);+});++test("emits skill_started with envelope name from ikey.json", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ const result = callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ });+ assert.equal(result.emitted, true);+ assert.equal(result.skillName, "add-seo");+ assert.equal(captured.event.name, "PowerPagesPluginEvent");+ assert.equal(captured.event.data.eventName, "skill_started");+ assert.equal(captured.event.data.eventType, "Trace");+ assert.equal(captured.event.data.severity, "Info");+ assert.equal(captured.event.data.pluginName, "power-pages");+ assert.equal(captured.event.data.pluginVersion, "1.2.3");+ assert.equal(captured.event.data.skillName, "add-seo");+ assert.equal(typeof captured.event.data.sessionId, "string");+ assert.equal(typeof captured.event.data.correlationId, "string");+ assert.equal(typeof captured.event.data.osName, "string");+ assert.equal(typeof captured.event.data.osVersion, "string");+ assert.match(captured.event.data.nodeVersion, /^v\d+$/);+});++test("populates orgId/tenantId when PAC auth is present", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ pacAuth: {+ orgId: "22222222-2222-2222-2222-222222222222",+ tenantId: "11111111-1111-1111-1111-111111111111",+ },+ });+ assert.equal(captured.event.data.orgId, "22222222-2222-2222-2222-222222222222");+ assert.equal(captured.event.data.tenantId, "11111111-1111-1111-1111-111111111111");+});++test("populates aiAgentName/aiAgentVersion/pacCliVersion when agentInfo is present", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ agentInfo: {+ aiAgentName: "Claude Code",+ aiAgentVersion: "2.0.0",+ pacCliVersion: "1.36.0",+ },+ });+ assert.equal(captured.event.data.aiAgentName, "Claude Code");+ assert.equal(captured.event.data.aiAgentVersion, "2.0.0");+ assert.equal(captured.event.data.pacCliVersion, "1.36.0");+});++test("omits agent fields when agentInfo returns empty values", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ agentInfo: { aiAgentName: "", aiAgentVersion: "", pacCliVersion: "" },+ });+ assert.equal(captured.event.data.aiAgentName, undefined);+ assert.equal(captured.event.data.aiAgentVersion, undefined);+ assert.equal(captured.event.data.pacCliVersion, undefined);+});++test("omits orgId/tenantId when PAC auth is absent", () => {+ 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.event.data.orgId, undefined);+ assert.equal(captured.event.data.tenantId, undefined);+});++test("forwards POWER_PLATFORM_SKILLS_CONFIG_DIR and FAKE_HTTPS into spawn opts", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const prevCfg = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ const prevProbe = process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS;+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = "/tmp/fake-config";+ process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS = "/tmp/fake-probe.json";+ const captured = {};+ try {+ callWithStub({+ promptText: "/power-pages:add-seo",+ telemetryDir,+ captured,+ });+ } finally {+ if (prevCfg === undefined) delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ else process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = prevCfg;+ if (prevProbe === undefined) delete process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS;+ else process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS = prevProbe;+ }+ assert.equal(captured.spawnOpts.configDir, "/tmp/fake-config");+ assert.equal(captured.spawnOpts.fakeProbe, "/tmp/fake-probe.json");+});++test("does not throw when ikey.json is missing", () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-efp-noikey-"));+ const captured = {};+ assert.doesNotThrow(() =>+ emitSkillStartedFromPrompt("/power-pages:add-seo", {+ pluginName: "power-pages",+ pluginVersion: "1.2.3",+ trackedSkills: TRACKED,+ telemetryDir: tmp,+ _emit: (e, o) => {+ captured.event = e;+ captured.spawnOpts = o;+ },+ _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" });+ assert.equal(captured.event, undefined);+});++test("does not throw when _emit throws", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ assert.doesNotThrow(() =>+ emitSkillStartedFromPrompt("/power-pages:add-seo", {+ pluginName: "power-pages",+ pluginVersion: "1.2.3",+ trackedSkills: TRACKED,+ telemetryDir,+ _emit: () => {+ throw new Error("boom");+ },+ _readPacAuth: () => null,+ })+ );+});++test("disabled:true short-circuits BEFORE PAC / agent-info shellouts", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "x",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ disabled: true,+ });+ const captured = {};+ let pacCalled = false;+ let agentCalled = false;+ const result = emitSkillStartedFromPrompt("/power-pages:add-seo", {+ pluginName: "power-pages",+ pluginVersion: "1.2.3",+ trackedSkills: TRACKED,+ telemetryDir,+ _emit: (e, o) => {+ captured.event = e;+ captured.spawnOpts = o;+ },+ _readPacAuth: () => {+ pacCalled = true;+ return null;+ },+ _readAgentInfo: () => {+ agentCalled = true;+ return {};+ },+ });+ assert.deepEqual(result, { emitted: false, skillName: "add-seo" });+ assert.equal(captured.event, undefined);+ assert.equal(pacCalled, false, "PAC must not be invoked when disabled");+ assert.equal(agentCalled, false, "agent-info must not be invoked when disabled");+});++test("missing instrumentationKey short-circuits BEFORE PAC / agent-info", () => {+ const telemetryDir = mkTelemetryDir({+ instrumentationKey: "",+ collectorUrl: "https://x",+ eventStreamName: "PowerPagesPluginEvent",+ });+ const captured = {};+ let pacCalled = false;+ const result = emitSkillStartedFromPrompt("/power-pages:add-seo", {+ pluginName: "power-pages",+ pluginVersion: "1.2.3",+ trackedSkills: TRACKED,+ telemetryDir,+ _emit: (e, o) => {+ captured.event = e;+ captured.spawnOpts = o;+ },+ _readPacAuth: () => {+ pacCalled = true;+ return null;+ },+ });+ assert.deepEqual(result, { emitted: false, skillName: "add-seo" });+ assert.equal(captured.event, undefined);+ assert.equal(pacCalled, false, "PAC must not be invoked when iKey is missing");+});diff --git a/shared/telemetry/tests/emit-spawn.test.js b/shared/telemetry/tests/emit-spawn.test.jsnew file mode 100644index 000000000..bbbf86939--- /dev/null+++ b/shared/telemetry/tests/emit-spawn.test.js@@ -0,0 +1,123 @@+"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 { fireAndForget } = require("../lib/emit-spawn");++function mkTmp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-spawn-"));+}++const sampleEvent = {+ name: "PowerPagesPluginEvent",+ data: {+ eventName: "skill_started",+ eventType: "Trace",+ severity: "Info",+ skillName: "hello",+ },+};++test("fireAndForget returns synchronously (<100 ms)", () => {+ const start = Date.now();+ fireAndForget(sampleEvent, {+ iKey: "real-ikey",+ collectorUrl: "https://example.invalid/",+ });+ const elapsed = Date.now() - start;+ assert.ok(elapsed < 100, `expected <100ms, got ${elapsed}ms`);+});++test("dispatcher child receives the event and writes the probe", async () => {+ const tmp = mkTmp();+ const probe = path.join(tmp, "probe.json");+ // Point the dispatcher at a temp ikey.json with disabled:false so emission+ // proceeds (production ships disabled:true until tenant routing is live).+ const ikeyJsonPath = path.join(tmp, "ikey.json");+ fs.writeFileSync(+ ikeyJsonPath,+ JSON.stringify({+ instrumentationKey: "placeholder",+ collector_url: "https://example.invalid/",+ event_stream_name: "PowerPagesPluginEvent",+ disabled: false,+ })+ );+ const prevIkeyJson = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON = ikeyJsonPath;+ try {+ fireAndForget(sampleEvent, {+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ configDir: tmp,+ fakeProbe: probe,+ });+ } finally {+ if (prevIkeyJson === undefined) delete process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ else process.env.POWER_PLATFORM_SKILLS_IKEY_JSON = prevIkeyJson;+ }+ // Wait up to 2s for the child to write the probe.+ for (let i = 0; i < 20; i++) {+ if (fs.existsSync(probe)) break;+ await new Promise((r) => setTimeout(r, 100));+ }+ assert.ok(fs.existsSync(probe), "probe file was not written");+ const contents = JSON.parse(fs.readFileSync(probe, "utf8"));+ assert.ok(contents.body.endsWith("\n"), "body must be newline-terminated");+ const body = JSON.parse(contents.body);+ assert.deepEqual(Object.keys(body).sort(), ["data", "iKey", "name", "time", "ver"]);+ assert.equal(body.name, "PowerPagesPluginEvent");+ assert.equal(body.data.eventName, "skill_started");+ assert.equal(body.data.skillName, "hello");+});++test("opts.ikeyJsonPath points the dispatcher at the caller's ikey.json (no env override)", async () => {+ // Regression guard: the dispatcher lives in shared/telemetry/lib, so its+ // __dirname default resolves to shared/'s placeholder (disabled:true). When+ // lib/ is shared via symlink or relative require, the spawner must forward+ // the plugin's real ikey.json via opts.ikeyJsonPath. With NO env override+ // set, an enabled ikey.json passed this way must still produce a probe.+ const tmp = mkTmp();+ const probe = path.join(tmp, "probe.json");+ const ikeyJsonPath = path.join(tmp, "ikey.json");+ fs.writeFileSync(+ ikeyJsonPath,+ JSON.stringify({+ instrumentationKey: "placeholder",+ collector_url: "https://example.invalid/",+ event_stream_name: "PowerPagesPluginEvent",+ disabled: false,+ })+ );+ const prevIkeyJson = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ delete process.env.POWER_PLATFORM_SKILLS_IKEY_JSON; // ensure opts path is what's exercised+ try {+ fireAndForget(sampleEvent, {+ iKey: "real-ikey-32-chars-minimum-aaaaaaaaaaaaaa",+ collectorUrl: "https://example.invalid/OneCollector/1.0/",+ configDir: tmp,+ fakeProbe: probe,+ ikeyJsonPath,+ });+ } finally {+ if (prevIkeyJson === undefined) delete process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ else process.env.POWER_PLATFORM_SKILLS_IKEY_JSON = prevIkeyJson;+ }+ for (let i = 0; i < 20; i++) {+ if (fs.existsSync(probe)) break;+ await new Promise((r) => setTimeout(r, 100));+ }+ assert.ok(+ fs.existsSync(probe),+ "dispatcher should have read the enabled ikey.json passed via opts.ikeyJsonPath"+ );+});++test("fireAndForget does not throw on empty-opts invocation", () => {+ fireAndForget({ name: "X", data: {} }, { iKey: "", collectorUrl: "" });+ // No assertion needed: test passes if no throw.+});diff --git a/shared/telemetry/tests/events.test.js b/shared/telemetry/tests/events.test.jsnew file mode 100644index 000000000..efcb8a17e--- /dev/null+++ b/shared/telemetry/tests/events.test.js@@ -0,0 +1,329 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const {+ buildSkillStarted,+ buildSkillCompleted,+} = require("../lib/events");++const ENVELOPE = "PowerPagesPluginEvent";++const common = {+ pluginName: "power-pages",+ pluginVersion: "1.2.2",+ sessionId: "sess-uuid",+ correlationId: "corr-1",+ osName: "Windows",+ osVersion: "10.0.26200",+ nodeVersion: "v22",+};++test("buildSkillStarted returns top-level fields with envelope name", () => {+ const ev = buildSkillStarted(ENVELOPE, { ...common, skillName: "add-seo" });+ assert.equal(ev.name, ENVELOPE);+ assert.equal(ev.data.eventName, "skill_started");+ assert.equal(ev.data.eventType, "Trace");+ assert.equal(ev.data.severity, "Info");+ assert.equal(ev.data.pluginName, "power-pages");+ assert.equal(ev.data.skillName, "add-seo");+ assert.equal(ev.data.osName, "Windows");+ assert.equal(ev.data.osVersion, "10.0.26200");+ assert.equal(ev.data.nodeVersion, "v22");+});++test("buildSkillCompleted with success outcome → severity Info", () => {+ const ev = buildSkillCompleted(ENVELOPE, {+ ...common,+ skillName: "add-seo",+ outcome: "success",+ durationMs: 1234,+ errorClass: "",+ });+ assert.equal(ev.data.eventName, "skill_completed");+ assert.equal(ev.data.severity, "Info");+ assert.equal(ev.data.outcome, "success");+ assert.equal(ev.data.durationMs, 1234);+ assert.equal(ev.data.errorClass, "");+});++test("buildSkillCompleted with failure outcome → severity Error", () => {+ const ev = buildSkillCompleted(ENVELOPE, {+ ...common,+ skillName: "add-seo",+ outcome: "failure",+ durationMs: 50,+ errorClass: "TypeError",+ });+ assert.equal(ev.data.severity, "Error");+ assert.equal(ev.data.outcome, "failure");+ assert.equal(ev.data.errorClass, "TypeError");+});++test("buildSkillStarted drops fields not in allowlist", () => {+ const ev = buildSkillStarted(ENVELOPE, {+ ...common,+ skillName: "add-seo",+ tenantId: "11111111-1111-1111-1111-111111111111",+ orgId: "22222222-2222-2222-2222-222222222222",+ leaked_field: "SHOULD_NOT_APPEAR",+ file_path: "/etc/passwd",+ error_message: "secret",+ });+ assert.equal(ev.data.tenantId, "11111111-1111-1111-1111-111111111111");+ assert.equal(ev.data.orgId, "22222222-2222-2222-2222-222222222222");+ assert.equal(ev.data.leaked_field, undefined);+ assert.equal(ev.data.file_path, undefined);+ assert.equal(ev.data.error_message, undefined);+});++test("orgId/tenantId omitted when input is missing", () => {+ const ev = buildSkillStarted(ENVELOPE, { ...common, skillName: "add-seo" });+ assert.equal(ev.data.orgId, undefined);+ assert.equal(ev.data.tenantId, undefined);+});++test("severity is Info for *_started events even when outcome=failure is supplied (started has no outcome)", () => {+ const ev = buildSkillStarted(ENVELOPE, {+ ...common,+ skillName: "add-seo",+ outcome: "failure",+ });+ assert.equal(ev.data.severity, "Info");+ assert.equal(ev.data.outcome, undefined);+});++test("envelope name flows through unchanged", () => {+ const ev = buildSkillStarted("CustomPluginEvent", {+ ...common,+ skillName: "x",+ });+ assert.equal(ev.name, "CustomPluginEvent");+});++test("data has stable key set across calls (no key drift)", () => {+ const ev = buildSkillStarted(ENVELOPE, {+ ...common,+ skillName: "x",+ orgId: "o",+ tenantId: "t",+ pacCliVersion: "1.36.0",+ aiAgentName: "Claude Code",+ aiAgentVersion: "2.0.0",+ eventInfo: { detail: "anything" },+ });+ const expectedKeys = [+ "aiAgentName", "aiAgentVersion",+ "correlationId", "eventInfo", "eventName", "eventType",+ "nodeVersion", "orgId", "osName", "osVersion",+ "pacCliVersion",+ "pluginName", "pluginVersion", "sessionId", "severity",+ "skillName", "tenantId",+ ];+ assert.deepEqual(Object.keys(ev.data).sort(), expectedKeys);+});++test("eventInfo passes through as a dynamic object (not stringified)", () => {+ const eventInfo = { region: "us-west", attempt: 3, nested: { a: 1 } };+ const ev = buildSkillStarted(ENVELOPE, {+ ...common,+ skillName: "add-seo",+ eventInfo,+ });+ assert.equal(typeof ev.data.eventInfo, "object");+ assert.deepEqual(ev.data.eventInfo, eventInfo);+});++test("buildSkillCompleted carries errorDescription", () => {+ const ev = buildSkillCompleted(ENVELOPE, {+ ...common,+ skillName: "add-seo",+ outcome: "failure",+ durationMs: 50,+ errorClass: "TypeError",+ errorDescription: "Cannot read properties of undefined (reading 'foo')",+ });+ assert.equal(ev.data.errorDescription, "Cannot read properties of undefined (reading 'foo')");+});++test("AI agent + PAC CLI version pass through when supplied", () => {+ const ev = buildSkillStarted(ENVELOPE, {+ ...common,+ skillName: "add-seo",+ aiAgentName: "Claude Code",+ aiAgentVersion: "2.0.0",+ pacCliVersion: "1.36.0",+ });+ assert.equal(ev.data.aiAgentName, "Claude Code");+ assert.equal(ev.data.aiAgentVersion, "2.0.0");+ assert.equal(ev.data.pacCliVersion, "1.36.0");+});++test("errorDescription dropped from *_started events (only allowed on completed)", () => {+ const ev = buildSkillStarted(ENVELOPE, {+ ...common,+ skillName: "add-seo",+ errorDescription: "should not be here",+ });+ assert.equal(ev.data.errorDescription, undefined);+});++// ---------------------------------------------------------------------------+// Type-safety tests — every column gets the right type or is dropped.+// ---------------------------------------------------------------------------++test("string fields drop non-string values (no silent coercion to '42' etc.)", () => {+ const ev = buildSkillStarted(ENVELOPE, {+ ...common,+ skillName: 42, // wrong type+ pluginName: { not: "a string" }, // wrong type+ pluginVersion: ["1.0"], // wrong type+ });+ assert.equal(ev.data.skillName, undefined);+ assert.equal(ev.data.pluginName, undefined);+ // pluginVersion was set in `common` to "1.2.2" but caller passed array;+ // the array overwrites and gets dropped, so field is undefined.+ assert.equal(ev.data.pluginVersion, undefined);+});++test("string fields preserve empty strings (intentional for errorClass/errorDescription)", () => {+ const ev = buildSkillCompleted(ENVELOPE, {+ ...common,+ skillName: "x",+ outcome: "success",+ durationMs: 0,+ errorClass: "",+ errorDescription: "",+ });+ assert.equal(ev.data.errorClass, "");+ assert.equal(ev.data.errorDescription, "");+});++test("durationMs always lands as a non-negative integer (number type)", () => {+ const cases = [+ { input: 1234, expect: 1234 },+ { input: 1234.7, expect: 1234 }, // floor+ { input: -5, expect: 0 }, // negative clamp+ { input: Number.NaN, expect: 0 },+ { input: Number.POSITIVE_INFINITY, expect: 0 },+ { 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+ ];+ for (const { input, expect } of cases) {+ const ev = buildSkillCompleted(ENVELOPE, {+ ...common,+ skillName: "x",+ outcome: "success",+ durationMs: input,+ errorClass: "",+ });+ assert.equal(typeof ev.data.durationMs, "number", `input=${String(input)}`);+ assert.equal(ev.data.durationMs, expect, `input=${String(input)}`);+ }+});++test("durationMs absent when caller does not provide", () => {+ const ev = buildSkillCompleted(ENVELOPE, {+ ...common,+ skillName: "x",+ outcome: "success",+ errorClass: "",+ });+ // Field absent → Kusto column will be null. Better than sending 0 by default.+ assert.equal(ev.data.durationMs, undefined);+});++test("eventInfo drops non-object values (no Kusto dynamic-type confusion)", () => {+ const cases = [+ "a string", // strings rejected+ 42, // numbers rejected+ true, // booleans rejected+ new Date(), // Date rejected+ /regex/, // RegExp rejected+ ];+ for (const v of cases) {+ const ev = buildSkillStarted(ENVELOPE, {+ ...common,+ skillName: "x",+ eventInfo: v,+ });+ assert.equal(ev.data.eventInfo, undefined, `input=${String(v)}`);+ }+});++test("eventInfo accepts arrays (valid JSON for dynamic column)", () => {+ const ev = buildSkillStarted(ENVELOPE, {+ ...common,+ skillName: "x",+ eventInfo: [1, 2, 3],+ });+ assert.deepEqual(ev.data.eventInfo, [1, 2, 3]);+});++test("outcome enforces enum: only 'success' or 'failure' pass through", () => {+ const okSuccess = buildSkillCompleted(ENVELOPE, {+ ...common, skillName: "x", outcome: "success", errorClass: "",+ });+ const okFailure = buildSkillCompleted(ENVELOPE, {+ ...common, skillName: "x", outcome: "failure", errorClass: "",+ });+ const bogus = buildSkillCompleted(ENVELOPE, {+ ...common, skillName: "x", outcome: "weird", errorClass: "",+ });+ const numeric = buildSkillCompleted(ENVELOPE, {+ ...common, skillName: "x", outcome: 1, errorClass: "",+ });+ assert.equal(okSuccess.data.outcome, "success");+ assert.equal(okFailure.data.outcome, "failure");+ assert.equal(bogus.data.outcome, undefined);+ assert.equal(numeric.data.outcome, undefined);+});++test("null and undefined dropped uniformly across all types", () => {+ const ev = buildSkillCompleted(ENVELOPE, {+ pluginName: null,+ pluginVersion: undefined,+ sessionId: null,+ skillName: null,+ durationMs: null,+ outcome: null,+ eventInfo: null,+ errorClass: null,+ errorDescription: undefined,+ });+ assert.equal(ev.data.pluginName, undefined);+ assert.equal(ev.data.pluginVersion, undefined);+ assert.equal(ev.data.sessionId, undefined);+ assert.equal(ev.data.skillName, undefined);+ assert.equal(ev.data.durationMs, undefined);+ assert.equal(ev.data.outcome, undefined);+ assert.equal(ev.data.eventInfo, undefined);+ assert.equal(ev.data.errorClass, undefined);+ assert.equal(ev.data.errorDescription, undefined);+});++test("severity defaults to Info when outcome is dropped (invalid enum)", () => {+ // Even if outcome is a non-enum value, severity should fall back to Info,+ // not crash.+ const ev = buildSkillCompleted(ENVELOPE, {+ ...common, skillName: "x", outcome: "weird-value", errorClass: "",+ });+ assert.equal(ev.data.severity, "Info");+});++test("FIELD_TYPES is exported and covers every field used in builders", () => {+ const { FIELD_TYPES } = require("../lib/events");+ const usedFields = [+ "pluginName", "pluginVersion", "sessionId", "correlationId",+ "osName", "osVersion", "nodeVersion",+ "orgId", "tenantId", "pacCliVersion", "aiAgentName", "aiAgentVersion",+ "eventInfo",+ "skillName",+ "outcome", "durationMs", "errorClass", "errorDescription",+ ];+ for (const f of usedFields) {+ assert.ok(FIELD_TYPES[f], `FIELD_TYPES missing entry for "${f}"`);+ }+});diff --git a/shared/telemetry/tests/local-log.test.js b/shared/telemetry/tests/local-log.test.jsnew file mode 100644index 000000000..e722efdf0--- /dev/null+++ b/shared/telemetry/tests/local-log.test.js@@ -0,0 +1,75 @@+"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 { appendLocal, LOG_FILE_NAME, ROTATE_BYTES } = require("../lib/local-log");++function mkTmp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-local-log-"));+}++test("exports the log filename and rotate threshold", () => {+ assert.equal(LOG_FILE_NAME, "events.jsonl");+ assert.equal(typeof ROTATE_BYTES, "number");+ assert.ok(ROTATE_BYTES >= 1024 * 1024);+});++test("appendLocal creates the configDir and writes one JSON line", () => {+ const tmp = mkTmp();+ const nested = path.join(tmp, "sub", "dir"); // doesn't exist yet+ appendLocal({ name: "X", data: { eventName: "hello" } }, { configDir: nested });+ const logFile = path.join(nested, LOG_FILE_NAME);+ assert.ok(fs.existsSync(logFile));+ const lines = fs.readFileSync(logFile, "utf8").trim().split("\n");+ assert.equal(lines.length, 1);+ const parsed = JSON.parse(lines[0]);+ assert.equal(parsed.name, "X");+ assert.equal(parsed.data.eventName, "hello");+});++test("appendLocal appends multiple events on subsequent calls", () => {+ const tmp = mkTmp();+ appendLocal({ name: "A", data: {} }, { configDir: tmp });+ appendLocal({ name: "B", data: {} }, { configDir: tmp });+ appendLocal({ name: "C", data: {} }, { configDir: tmp });+ const contents = fs.readFileSync(path.join(tmp, LOG_FILE_NAME), "utf8");+ const names = contents+ .trim()+ .split("\n")+ .map((l) => JSON.parse(l).name);+ assert.deepEqual(names, ["A", "B", "C"]);+});++test("appendLocal rotates when file exceeds ROTATE_BYTES", () => {+ const tmp = mkTmp();+ const logFile = path.join(tmp, LOG_FILE_NAME);+ // Pre-fill log with > ROTATE_BYTES of data+ const filler = "x".repeat(1024);+ const lines = Math.ceil(ROTATE_BYTES / filler.length) + 1;+ fs.writeFileSync(logFile, Array(lines).fill(filler).join("\n") + "\n");+ assert.ok(fs.statSync(logFile).size > ROTATE_BYTES);++ appendLocal({ name: "AFTER-ROTATE", data: {} }, { configDir: tmp });++ const olds = fs+ .readdirSync(tmp)+ .filter((f) => f.startsWith("events.") && f.endsWith(".old"));+ assert.equal(olds.length, 1, `expected one rotated file, found ${olds.length}`);++ const fresh = fs.readFileSync(logFile, "utf8").trim().split("\n");+ assert.equal(fresh.length, 1);+ assert.equal(JSON.parse(fresh[0]).name, "AFTER-ROTATE");+});++test("appendLocal never throws even when configDir is not writable", () => {+ // Pass a path that cannot be created as a directory because a file exists there+ const tmp = mkTmp();+ const blocker = path.join(tmp, "blocker");+ fs.writeFileSync(blocker, "i am a file, not a directory");+ // Calling appendLocal with `blocker` as configDir should not throw.+ appendLocal({ name: "X", data: {} }, { configDir: blocker });+});diff --git a/shared/telemetry/tests/pac-auth.test.js b/shared/telemetry/tests/pac-auth.test.jsnew file mode 100644index 000000000..fdab3d3b2--- /dev/null+++ b/shared/telemetry/tests/pac-auth.test.js@@ -0,0 +1,143 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");++const pacAuth = require("../lib/pac-auth");++const SAMPLE_OUTPUT = `Type: Universal+Cloud: Public+Tenant Id: 11111111-1111-1111-1111-111111111111+Tenant Country: US+User: [email protected]+Entra ID Object Id: aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa+PUID: 10000000ABCDEF01+User Country/Region: US+Token Expires: 2026-05-05T18:00:00Z+Authority: https://login.microsoftonline.com/...+Environment Geo: NorthAmerica+Environment Id: 22222222-2222-2222-2222-222222222222+Environment Type: Sandbox+Organization Id: 33333333-3333-3333-3333-333333333333+Organization Unique Name: contoso+Organization Friendly Name: Contoso+`;++test("returns { orgId, tenantId } parsed from `pac auth who` output", () => {+ pacAuth._resetCache();+ const result = pacAuth.readPacAuth({ _exec: () => SAMPLE_OUTPUT });+ assert.deepEqual(result, {+ orgId: "33333333-3333-3333-3333-333333333333",+ tenantId: "11111111-1111-1111-1111-111111111111",+ });+});++test("returns { orgId: '', tenantId } when only Tenant Id line present", () => {+ pacAuth._resetCache();+ const result = pacAuth.readPacAuth({+ _exec: () =>+ "Cloud: Public\nTenant Id: 11111111-1111-1111-1111-111111111111\n",+ });+ assert.deepEqual(result, {+ orgId: "",+ tenantId: "11111111-1111-1111-1111-111111111111",+ });+});++test("returns { tenantId: '', orgId } when only Organization Id line present", () => {+ pacAuth._resetCache();+ const result = pacAuth.readPacAuth({+ _exec: () =>+ "Cloud: Public\nOrganization Id: 33333333-3333-3333-3333-333333333333\n",+ });+ assert.deepEqual(result, {+ orgId: "33333333-3333-3333-3333-333333333333",+ tenantId: "",+ });+});++test("returns null when neither Tenant Id nor Organization Id is found", () => {+ pacAuth._resetCache();+ const result = pacAuth.readPacAuth({+ _exec: () => "Type: Universal\nCloud: Public\n",+ });+ assert.equal(result, null);+});++test("returns null when pac is missing (ENOENT)", () => {+ pacAuth._resetCache();+ const result = pacAuth.readPacAuth({+ _exec: () => {+ const e = new Error("spawn pac ENOENT");+ e.code = "ENOENT";+ throw e;+ },+ });+ assert.equal(result, null);+});++test("returns null when pac auth who times out", () => {+ pacAuth._resetCache();+ const result = pacAuth.readPacAuth({+ _exec: () => {+ const e = new Error("ETIMEDOUT");+ e.code = "ETIMEDOUT";+ throw e;+ },+ });+ assert.equal(result, null);+});++test("returns null when pac exits non-zero", () => {+ pacAuth._resetCache();+ const result = pacAuth.readPacAuth({+ _exec: () => {+ const e = new Error("Command failed");+ e.status = 1;+ throw e;+ },+ });+ assert.equal(result, null);+});++test("does not throw on unparseable / empty output", () => {+ pacAuth._resetCache();+ assert.doesNotThrow(() =>+ pacAuth.readPacAuth({ _exec: () => "" })+ );+ pacAuth._resetCache();+ assert.doesNotThrow(() =>+ pacAuth.readPacAuth({ _exec: () => null })+ );+});++test("caches result across calls (single fork per process)", () => {+ pacAuth._resetCache();+ let calls = 0;+ const exec = () => {+ calls++;+ return SAMPLE_OUTPUT;+ };+ pacAuth.readPacAuth({ _exec: exec });+ pacAuth.readPacAuth({ _exec: exec });+ pacAuth.readPacAuth({ _exec: exec });+ assert.equal(calls, 1, "second + third calls should hit cache");+});++test("respects _exec=false short-circuit (returns null without forking)", () => {+ pacAuth._resetCache();+ const result = pacAuth.readPacAuth({ _exec: false });+ assert.equal(result, null);+});++test("parses values with extra whitespace and mixed casing in label", () => {+ pacAuth._resetCache();+ const result = pacAuth.readPacAuth({+ _exec: () =>+ "tenant ID: 11111111-1111-1111-1111-111111111111\nORGANIZATION ID: 33333333-3333-3333-3333-333333333333\n",+ });+ assert.deepEqual(result, {+ orgId: "33333333-3333-3333-3333-333333333333",+ tenantId: "11111111-1111-1111-1111-111111111111",+ });+});diff --git a/shared/telemetry/tests/prompt-detector.test.js b/shared/telemetry/tests/prompt-detector.test.jsnew file mode 100644index 000000000..192e0f7c4--- /dev/null+++ b/shared/telemetry/tests/prompt-detector.test.js@@ -0,0 +1,81 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const { detectSlashCommand } = require("../lib/prompt-detector");++const TRACKED = { "add-seo": {}, "create-site": {}, "test-site": {} };+const OPTS = { pluginName: "power-pages", trackedSkills: TRACKED };++test("matches a bare slash command at start of prompt", () => {+ assert.equal(detectSlashCommand("/power-pages:add-seo", OPTS), "add-seo");+});++test("matches when followed by args", () => {+ assert.equal(+ detectSlashCommand("/power-pages:add-seo --foo bar", OPTS),+ "add-seo"+ );+});++test("matches when preceded by leading whitespace", () => {+ assert.equal(detectSlashCommand(" \n/power-pages:create-site", OPTS), "create-site");+});++test("matches when followed by newline", () => {+ assert.equal(detectSlashCommand("/power-pages:test-site\nmore text", OPTS), "test-site");+});++test("returns null for casual mid-sentence mention", () => {+ assert.equal(+ detectSlashCommand("I was thinking about /power-pages:add-seo earlier", OPTS),+ null+ );+});++test("matches the bare form without the plugin namespace", () => {+ assert.equal(detectSlashCommand("/add-seo", OPTS), "add-seo");+ assert.equal(detectSlashCommand(" /create-site", OPTS), "create-site");+ assert.equal(detectSlashCommand("/test-site --foo", OPTS), "test-site");+ assert.equal(detectSlashCommand("/add-seo\nmore", OPTS), "add-seo");+});++test("returns null for a bare command that is not a tracked skill", () => {+ assert.equal(detectSlashCommand("/clear", OPTS), null);+ assert.equal(detectSlashCommand("/not-a-real-skill", OPTS), null);+});++test("returns null for a bare substring of a tracked skill", () => {+ assert.equal(detectSlashCommand("/add-seo-extra", OPTS), null);+});++test("returns null for unknown skill", () => {+ assert.equal(detectSlashCommand("/power-pages:not-a-real-skill", OPTS), null);+});++test("returns null for different plugin", () => {+ assert.equal(detectSlashCommand("/other-plugin:add-seo", OPTS), null);+});++test("returns null for substring skill name (add-seo-extra must not match add-seo)", () => {+ assert.equal(detectSlashCommand("/power-pages:add-seo-extra", OPTS), null);+});++test("returns null for empty string", () => {+ assert.equal(detectSlashCommand("", OPTS), null);+});++test("returns null for non-string prompt", () => {+ assert.equal(detectSlashCommand(null, OPTS), null);+ assert.equal(detectSlashCommand(undefined, OPTS), null);+ assert.equal(detectSlashCommand(42, OPTS), null);+});++test("case-sensitive: uppercase variants do not match", () => {+ assert.equal(detectSlashCommand("/Power-Pages:Add-SEO", OPTS), null);+});++test("respects trackedSkills parameter — 'add-seo' not tracked returns null", () => {+ const opts = { pluginName: "power-pages", trackedSkills: { "create-site": {} } };+ assert.equal(detectSlashCommand("/power-pages:add-seo", opts), null);+});diff --git a/shared/telemetry/tests/scrubber.test.js b/shared/telemetry/tests/scrubber.test.jsnew file mode 100644index 000000000..1b4b23031--- /dev/null+++ b/shared/telemetry/tests/scrubber.test.js@@ -0,0 +1,20 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const { scrub } = require("../lib/scrubber");++test("scrub returns its input unchanged for strings", () => {+ assert.equal(scrub("hello world"), "hello world");+});++test("scrub returns its input unchanged for non-strings", () => {+ assert.equal(scrub(42), 42);+ assert.equal(scrub(null), null);+ assert.equal(scrub(undefined), undefined);+});++test("scrub never throws", () => {+ scrub({ nested: "obj" });+ scrub([]);+});diff --git a/shared/telemetry/tests/session.test.js b/shared/telemetry/tests/session.test.jsnew file mode 100644index 000000000..7a52868d3--- /dev/null+++ b/shared/telemetry/tests/session.test.js@@ -0,0 +1,105 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const path = require("node:path");+const { spawnSync } = require("node:child_process");++const sessionPath = path.resolve(__dirname, "../lib/session.js");++test("getSessionId returns a non-empty string", () => {+ const { getSessionId } = require(sessionPath);+ const id = getSessionId();+ assert.equal(typeof id, "string");+ assert.ok(id.length >= 32, `expected UUID-length, got ${id}`);+});++test("getSessionId is stable within a process", () => {+ const { getSessionId } = require(sessionPath);+ assert.equal(getSessionId(), getSessionId());+});++test("getSessionId is unique across processes when no override is provided", () => {+ const script = `process.stdout.write(require('${sessionPath.replace(/\\/g, "\\\\")}').getSessionId());`;+ const a = spawnSync(process.execPath, ["-e", script], { encoding: "utf8" });+ const b = spawnSync(process.execPath, ["-e", script], { encoding: "utf8" });+ assert.notEqual(a.stdout, b.stdout);+ assert.ok(a.stdout.length >= 32);+});++test("getSessionId honors the override (sessionId provided by hook payload)", () => {+ const { getSessionId, _resetCache } = require(sessionPath);+ _resetCache();+ const claudeSessionId = "abc-claude-session-123";+ assert.equal(getSessionId(claudeSessionId), claudeSessionId);+ // subsequent calls without override return the cached primed value+ assert.equal(getSessionId(), claudeSessionId);+ assert.equal(getSessionId(""), claudeSessionId);+ assert.equal(getSessionId(undefined), claudeSessionId);+});++test("getSessionId override wins over a previously cached UUID", () => {+ const { getSessionId, _resetCache } = require(sessionPath);+ _resetCache();+ const generated = getSessionId();+ const claudeSessionId = "xyz-claude-session-456";+ assert.equal(getSessionId(claudeSessionId), claudeSessionId);+ assert.notEqual(generated, claudeSessionId);+});++test("getSessionId is stable across multiple processes when same override is used", () => {+ const script = `process.stdout.write(require('${sessionPath.replace(/\\/g, "\\\\")}').getSessionId("primed-id-999"));`;+ const a = spawnSync(process.execPath, ["-e", script], { encoding: "utf8" });+ const b = spawnSync(process.execPath, ["-e", script], { encoding: "utf8" });+ assert.equal(a.stdout, "primed-id-999");+ assert.equal(b.stdout, "primed-id-999");+});++const { resolveHostSessionId } = require(sessionPath);++test("resolveHostSessionId returns payload.session_id when present (Claude Code shape)", () => {+ assert.equal(+ resolveHostSessionId({ session_id: "claude-snake-case-id" }),+ "claude-snake-case-id"+ );+});++test("resolveHostSessionId returns payload.sessionId when only camelCase is present", () => {+ assert.equal(+ resolveHostSessionId({ sessionId: "camel-case-id" }),+ "camel-case-id"+ );+});++test("resolveHostSessionId prefers session_id over sessionId when both present", () => {+ assert.equal(+ resolveHostSessionId({ session_id: "snake-wins", sessionId: "camel-loses" }),+ "snake-wins"+ );+});++test("resolveHostSessionId returns empty string for null payload", () => {+ assert.equal(resolveHostSessionId(null), "");+});++test("resolveHostSessionId returns empty string for undefined payload", () => {+ assert.equal(resolveHostSessionId(undefined), "");+});++test("resolveHostSessionId returns empty string for non-object payload", () => {+ assert.equal(resolveHostSessionId("not an object"), "");+ assert.equal(resolveHostSessionId(42), "");+ assert.equal(resolveHostSessionId(true), "");+});++test("resolveHostSessionId returns empty string for object without known fields", () => {+ assert.equal(resolveHostSessionId({ foo: "bar", other: "value" }), "");+});++test("resolveHostSessionId returns empty string for empty-string field values", () => {+ assert.equal(resolveHostSessionId({ session_id: "", sessionId: "" }), "");+});++test("resolveHostSessionId returns empty string for non-string field values", () => {+ assert.equal(resolveHostSessionId({ session_id: 123, sessionId: { x: 1 } }), "");+});diff --git a/shared/telemetry/tests/telemetry-config.test.js b/shared/telemetry/tests/telemetry-config.test.jsnew file mode 100644index 000000000..32f9148bc--- /dev/null+++ b/shared/telemetry/tests/telemetry-config.test.js@@ -0,0 +1,63 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { spawnSync } = require("node:child_process");++const CLI = path.resolve(__dirname, "../lib/telemetry-config.js");++function mkTmp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-cli-"));+}+function run(args, configDir) {+ return spawnSync(process.execPath, [CLI, ...args], {+ encoding: "utf8",+ env: { ...process.env, POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir },+ });+}++test("off writes the per-plugin opt-out and confirms", () => {+ const dir = mkTmp();+ const { status, stdout } = run(["--action", "off", "--plugin", "power-pages"], dir);+ assert.equal(status, 0);+ assert.match(stdout, /OFF/);+ assert.match(stdout, /No personal data is collected/);+ const cfg = JSON.parse(fs.readFileSync(path.join(dir, "config.json"), "utf8"));+ assert.equal(cfg.telemetry["power-pages"], "off");+});++test("on writes the per-plugin opt-in and confirms", () => {+ const dir = mkTmp();+ run(["--action", "off", "--plugin", "power-pages"], dir);+ const { status, stdout } = run(["--action", "on", "--plugin", "power-pages"], dir);+ assert.equal(status, 0);+ assert.match(stdout, /ON/);+ const cfg = JSON.parse(fs.readFileSync(path.join(dir, "config.json"), "utf8"));+ assert.equal(cfg.telemetry["power-pages"], "on");+});++test("status reports ON by default and never reads ikey.json", () => {+ const dir = mkTmp();+ const { status, stdout } = run(["--action", "status", "--plugin", "power-pages"], dir);+ assert.equal(status, 0);+ assert.match(stdout, /Telemetry \(power-pages\): ON/);+ assert.match(stdout, /No personal data is collected/);+});++test("status reports OFF after opt-out", () => {+ const dir = mkTmp();+ run(["--action", "off", "--plugin", "power-pages"], dir);+ const { stdout } = run(["--action", "status", "--plugin", "power-pages"], dir);+ assert.match(stdout, /Telemetry \(power-pages\): OFF/);+ assert.match(stdout, /local diagnostic log is still kept/i);+});++test("usage error on bad action", () => {+ const dir = mkTmp();+ const { status, stdout } = run(["--action", "bogus", "--plugin", "power-pages"], dir);+ assert.equal(status, 2);+ assert.match(stdout, /Usage:/);+});diff --git a/shared/telemetry/tests/user-config.test.js b/shared/telemetry/tests/user-config.test.jsnew file mode 100644index 000000000..e7e804b0d--- /dev/null+++ b/shared/telemetry/tests/user-config.test.js@@ -0,0 +1,91 @@+"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 {+ readTelemetryChoice,+ setTelemetryChoice,+ isTransmissionOptedOut,+ CONFIG_FILE_NAME,+} = require("../lib/user-config");++function mkTmp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-cfg-"));+}+function readRaw(dir) {+ return JSON.parse(fs.readFileSync(path.join(dir, CONFIG_FILE_NAME), "utf8"));+}++test("readTelemetryChoice returns null when no config file exists", () => {+ const dir = mkTmp();+ assert.equal(readTelemetryChoice(dir, "power-pages"), null);+ assert.equal(isTransmissionOptedOut(dir, "power-pages"), false);+});++test("setTelemetryChoice writes a per-plugin key and reads back", () => {+ const dir = mkTmp();+ assert.equal(setTelemetryChoice(dir, "power-pages", "off"), true);+ assert.equal(readTelemetryChoice(dir, "power-pages"), "off");+ assert.equal(isTransmissionOptedOut(dir, "power-pages"), true);+ assert.deepEqual(readRaw(dir), { telemetry: { "power-pages": "off" } });+});++test("setTelemetryChoice is per-plugin isolated and preserves other keys", () => {+ const dir = mkTmp();+ // seed an unrelated top-level key + another plugin's choice+ fs.writeFileSync(+ path.join(dir, CONFIG_FILE_NAME),+ JSON.stringify({ schemaVersion: 1, telemetry: { "model-apps": "off" } })+ );+ setTelemetryChoice(dir, "power-pages", "off");+ const raw = readRaw(dir);+ assert.equal(raw.schemaVersion, 1, "must preserve unrelated keys");+ assert.equal(raw.telemetry["model-apps"], "off", "must not touch other plugins");+ assert.equal(raw.telemetry["power-pages"], "off");+ // a different plugin is unaffected by power-pages being off+ assert.equal(isTransmissionOptedOut(dir, "code-apps"), false);+});++test("setTelemetryChoice flips off -> on", () => {+ const dir = mkTmp();+ setTelemetryChoice(dir, "power-pages", "off");+ setTelemetryChoice(dir, "power-pages", "on");+ assert.equal(readTelemetryChoice(dir, "power-pages"), "on");+ assert.equal(isTransmissionOptedOut(dir, "power-pages"), false);+});++test("setTelemetryChoice rejects invalid input without throwing", () => {+ const dir = mkTmp();+ assert.equal(setTelemetryChoice(dir, "power-pages", "maybe"), false);+ assert.equal(setTelemetryChoice(dir, "", "off"), false);+ assert.equal(readTelemetryChoice(dir, "power-pages"), null);+});++test("readTelemetryChoice tolerates a corrupt config file (returns null)", () => {+ const dir = mkTmp();+ fs.writeFileSync(path.join(dir, CONFIG_FILE_NAME), "{ not json");+ assert.equal(readTelemetryChoice(dir, "power-pages"), null);+});++test("an array config.json is ignored — setTelemetryChoice still persists", () => {+ const dir = mkTmp();+ // A JSON array passes `typeof === "object"`. Without the array guard, the write+ // would set `.telemetry` on the array, JSON.stringify would drop it, and the+ // choice would silently vanish while setTelemetryChoice returned true.+ fs.writeFileSync(path.join(dir, CONFIG_FILE_NAME), JSON.stringify(["junk"]));+ assert.equal(setTelemetryChoice(dir, "power-pages", "off"), true);+ assert.equal(readTelemetryChoice(dir, "power-pages"), "off");+ assert.deepEqual(readRaw(dir), { telemetry: { "power-pages": "off" } });+});++test("setTelemetryChoice fails safe (returns false) when the dir cannot be created", () => {+ const dir = mkTmp();+ const blocker = path.join(dir, "blocker");+ fs.writeFileSync(blocker, "i am a file");+ // configDir is a path *under* a file, so mkdir must fail+ assert.equal(setTelemetryChoice(path.join(blocker, "sub"), "power-pages", "off"), false);+});