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
Fix plugin root resolution (#207)
Priyanshu Agrawal0188a8b62da7
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 1028cf6e9..43bc23599 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -10,123 +10,23 @@"plugins": [{"name": "power-pages",- "source": "./plugins/power-pages",- "description": "Power Pages development and management plugin for Claude Code and GitHub Copilot",- "category": "development",- "version": "2.6.0",- "license": "MIT",- "tags": [- "power platform",- "power pages",- "microsoft power platform",- "microsoft"- ],- "keywords": [- "power platform",- "power pages",- "microsoft power platform",- "microsoft"- ]+ "source": "./plugins/power-pages"},{"name": "model-apps",- "source": "./plugins/model-apps",- "description": "Build and deploy generative pages for Power Apps model-driven apps",- "category": "development",- "version": "2.2.0",- "license": "MIT",- "tags": [- "power platform",- "power apps",- "model-driven apps",- "generative pages",- "genux",- "microsoft"- ],- "keywords": [- "power platform",- "power apps",- "model-driven apps",- "generative pages",- "genux",- "microsoft"- ]+ "source": "./plugins/model-apps"},{"name": "mcp-apps",- "source": "./plugins/mcp-apps",- "description": "Generate MCP App widgets for MCP tools",- "category": "development",- "version": "1.0.0",- "license": "MIT",- "tags": [- "mcp",- "mcp-apps",- "widget",- "power platform",- "microsoft"- ],- "keywords": [- "mcp",- "mcp-apps",- "widget",- "power platform",- "microsoft"- ]+ "source": "./plugins/mcp-apps"},{"name": "canvas-apps",- "source": "./plugins/canvas-apps",- "description": "Build Power Apps Canvas Apps using the Canvas Authoring MCP server",- "category": "development",- "version": "2.1.0",- "license": "MIT",- "tags": [- "power platform",- "power apps",- "canvas apps",- "pa-yaml",- "msapp",- "connectors",- "microsoft"- ],- "keywords": [- "power platform",- "power apps",- "canvas apps",- "pa-yaml",- "msapp",- "connectors",- "microsoft"- ]+ "source": "./plugins/canvas-apps"},{"name": "code-apps-preview",- "source": "./plugins/code-apps",- "description": "Build and deploy Power Apps code apps using React, Vite, and Power Platform connectors",- "category": "development",- "version": "1.0.0",- "license": "MIT",- "tags": [- "power platform",- "power apps",- "code apps",- "react",- "vite",- "dataverse",- "connectors",- "microsoft"- ],- "keywords": [- "power platform",- "power apps",- "code apps",- "react",- "vite",- "dataverse",- "connectors",- "microsoft"- ]+ "source": "./plugins/code-apps"}]}diff --git a/AGENTS.md b/AGENTS.mdindex c05194d0c..d51265c6f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -63,15 +63,15 @@ Skills that apply to all plugins live in `shared/skills/<skill-name>/`. The work- `shared/skills/<skill-name>/<workflow>.md` — Full workflow (phases, instructions, field definitions)- `shared/skills/<skill-name>/SKILL.template.md` — Template SKILL.md (frontmatter + reference to workflow); supports `{{PLUGIN_NAME}}` placeholder- `plugins/<plugin>/skills/<skill-name>/SKILL.md` — Per-plugin wrapper generated from the template above-- `plugins/<plugin>/skills/<skill-name>/<workflow>.md` — Symlink to the shared workflow when the plugin must work after installing only its own plugin directory+- `plugins/<plugin>/skills/<skill-name>/<workflow>.md` — Copied workflow file bundled with the plugin so it works after installing only its own plugin directory-This 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 `${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.+This 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 `${PLUGIN_ROOT}/skills/<skill-name>/<workflow>.md` and keep a physical copy of the shared workflow at that per-plugin path. Do not use Git symlinks for shared content; Windows and plugin-host installs can materialize them as plain link files. When updating a shared skill, edit the workflow file and/or `SKILL.template.md` in `shared/`, then refresh the per-plugin wrappers (frontmatter + bundled workflow reference, with `{{PLUGIN_NAME}}` substituted) and copy the workflow content into each adopting plugin. Commit the shared source and per-plugin copies 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.+1DS telemetry code for all plugins lives at `shared/telemetry/`. Each adopting plugin keeps a physical copy of the library in its own tree at `plugins/<plugin>/scripts/lib/telemetry/lib`, alongside that plugin's real `ikey.json`. Do not use Git symlinks for this copy; plugin hosts may not dereference them reliably.-Edit `shared/telemetry/` directly — the symlink makes changes live for every adopting plugin immediately; there is nothing to re-sync.+Edit `shared/telemetry/` first, then refresh every adopting plugin's copied `scripts/lib/telemetry/lib` directory in the same change so the canonical source and bundled plugin content stay in sync.Per-plugin iKey/collector routing is pluggable via a `resolver.js` placed next to the plugin's `ikey.json` (implementing the `resolve`/`isProvisioned` contract); the shared library ships only that contract plus a static-key fallback, not any routing logic. A per-plugin opt-out env var `POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` (derived as the uppercased plugin name with non-alphanumerics collapsed to `_`, suffixed `_OPTOUT`) disables transmission for automation when set to `1`/`true` (dotnet `*_TELEMETRY_OPTOUT` convention); it has the **highest precedence**, overriding both the persisted `config.json` choice and `/<plugin>:telemetry on`.@@ -98,12 +98,15 @@ Current adopters: `power-pages`. Others adopt on demand.Keep the root `.claude-plugin/marketplace.json` and each plugin's`.claude-plugin/plugin.json` as JSON mirrors of their Open Plugins counterparts.-The shared root marketplace must stay dual-compatible: use repository-root-relative-plugin `source` paths and preserve legacy `category`/`tags` fields alongside Open-Plugins metadata. Existing marketplace subscriptions may still resolve the legacy-paths during auto-update, so removing or drifting these files can force users to-reinstall. Because mirrors are committed files (not symlinks), update both source-and legacy copies together, then run+The shared root marketplace must stay dual-compatible while keeping per-plugin+entries minimal: each plugin entry should include only the required `name` and+repository-root-relative `source` fields. Keep marketplace-level `owner` and+`metadata` because they describe the collection, but store per-plugin display/update+metadata (description, version, license, keywords, etc.) in each `.plugin/plugin.json`+instead of duplicating or overriding it in the marketplace index. Existing marketplace+subscriptions may still resolve the legacy paths during auto-update, so removing or+drifting these files can force users to reinstall. Because mirrors are committed+files (not symlinks), update both source and legacy copies together, then run`node scripts/validate-legacy-compatibility.js` after metadata changes.## Code Conventionsdiff --git a/README.md b/README.mdindex 46eae5fce..0c2b9aa86 100644--- a/README.md+++ b/README.md@@ -208,9 +208,11 @@ power-platform-skills/The `.claude-plugin` files are compatibility mirrors for users who subscribedbefore the Open Plugins migration. The root legacy marketplace mirrors`marketplace.json`, and per-plugin legacy manifests mirror `.plugin/plugin.json`.-The shared marketplace uses repository-root-relative plugin `source` paths so-existing subscriptions can auto-update without requiring users to remove and-reinstall the marketplace or plugins.+The shared marketplace keeps marketplace-level `owner` and `metadata`, while each+plugin entry is intentionally just `name` plus repository-root-relative `source`.+Plugin descriptions, versions, licenses, and keywords are controlled from each+plugin's `.plugin/plugin.json`. This keeps existing subscriptions updating without+duplicating display/update metadata.## Documentationdiff --git a/marketplace.json b/marketplace.jsonindex 1028cf6e9..43bc23599 100644--- a/marketplace.json+++ b/marketplace.json@@ -10,123 +10,23 @@"plugins": [{"name": "power-pages",- "source": "./plugins/power-pages",- "description": "Power Pages development and management plugin for Claude Code and GitHub Copilot",- "category": "development",- "version": "2.6.0",- "license": "MIT",- "tags": [- "power platform",- "power pages",- "microsoft power platform",- "microsoft"- ],- "keywords": [- "power platform",- "power pages",- "microsoft power platform",- "microsoft"- ]+ "source": "./plugins/power-pages"},{"name": "model-apps",- "source": "./plugins/model-apps",- "description": "Build and deploy generative pages for Power Apps model-driven apps",- "category": "development",- "version": "2.2.0",- "license": "MIT",- "tags": [- "power platform",- "power apps",- "model-driven apps",- "generative pages",- "genux",- "microsoft"- ],- "keywords": [- "power platform",- "power apps",- "model-driven apps",- "generative pages",- "genux",- "microsoft"- ]+ "source": "./plugins/model-apps"},{"name": "mcp-apps",- "source": "./plugins/mcp-apps",- "description": "Generate MCP App widgets for MCP tools",- "category": "development",- "version": "1.0.0",- "license": "MIT",- "tags": [- "mcp",- "mcp-apps",- "widget",- "power platform",- "microsoft"- ],- "keywords": [- "mcp",- "mcp-apps",- "widget",- "power platform",- "microsoft"- ]+ "source": "./plugins/mcp-apps"},{"name": "canvas-apps",- "source": "./plugins/canvas-apps",- "description": "Build Power Apps Canvas Apps using the Canvas Authoring MCP server",- "category": "development",- "version": "2.1.0",- "license": "MIT",- "tags": [- "power platform",- "power apps",- "canvas apps",- "pa-yaml",- "msapp",- "connectors",- "microsoft"- ],- "keywords": [- "power platform",- "power apps",- "canvas apps",- "pa-yaml",- "msapp",- "connectors",- "microsoft"- ]+ "source": "./plugins/canvas-apps"},{"name": "code-apps-preview",- "source": "./plugins/code-apps",- "description": "Build and deploy Power Apps code apps using React, Vite, and Power Platform connectors",- "category": "development",- "version": "1.0.0",- "license": "MIT",- "tags": [- "power platform",- "power apps",- "code apps",- "react",- "vite",- "dataverse",- "connectors",- "microsoft"- ],- "keywords": [- "power platform",- "power apps",- "code apps",- "react",- "vite",- "dataverse",- "connectors",- "microsoft"- ]+ "source": "./plugins/code-apps"}]}diff --git a/plugins/canvas-apps/skills/report-issue/report-issue-workflow.md b/plugins/canvas-apps/skills/report-issue/report-issue-workflow.mddeleted file mode 120000index 467fa9175..000000000--- a/plugins/canvas-apps/skills/report-issue/report-issue-workflow.md+++ /dev/null@@ -1 +0,0 @@-../../../../shared/skills/report-issue/report-issue-workflow.md\ No newline at end of filediff --git a/plugins/canvas-apps/skills/report-issue/report-issue-workflow.md b/plugins/canvas-apps/skills/report-issue/report-issue-workflow.mdnew file mode 100644index 000000000..20401ebb8--- /dev/null+++ b/plugins/canvas-apps/skills/report-issue/report-issue-workflow.md@@ -0,0 +1,230 @@+# Report Issue++File a bug report on the [power-platform-skills](https://github.com/microsoft/power-platform-skills) GitHub repository. This workflow gathers the required information, presents a full preview, and creates the issue on the user's behalf.++**Initial request:** $ARGUMENTS++> **WARNING:** Before proceeding, inform the user: "This will create an issue on the **public** GitHub repository [microsoft/power-platform-skills](https://github.com/microsoft/power-platform-skills). **Do not include any sensitive information** such as credentials, internal URLs, tenant IDs, customer data, or proprietary code in the bug report."++---++## Phase 1: Identify Plugin & Version++**Goal**: Determine which plugin the bug is for and its version.++**Actions**:++1. Create a task list with all 5 phases (see [Progress Tracking](#progress-tracking) table).+2. **Auto-detect the plugin name** from the current plugin context by reading `${PLUGIN_ROOT}/.plugin/plugin.json`. Extract the `name` field.+3. **Auto-detect the plugin version** from the same `plugin.json` — extract the `version` field.+4. If the plugin name or version cannot be determined, use `AskUserQuestion` to ask the user.++**Output**: Plugin name and version confirmed.++---++## Phase 2: Gather Bug Details++**Goal**: Collect all required and optional fields for the bug report.++**Actions**:++### 2.1 Check Arguments++If `$ARGUMENTS` contains a description of the bug, extract as much information as possible from it to pre-fill the fields below. Still confirm with the user.++### 2.2 Ask for Bug Details++Use `AskUserQuestion` to gather bug details. `AskUserQuestion` supports 1-4 questions per call, but each question requires 2-4 predefined options. Since bug report fields are free-text, use options as prompt hints and let the user type their actual response via "Other". Skip any field the user already provided in `$ARGUMENTS`.++**Call 1** — Skill and bug description (2 questions):++1. **"Which skill or command were you using?"** (header: "Skill") — Provide the plugin's known skills as options (e.g., `deploy-site`, `create-site`). This is optional — the user can skip it.+2. **"Please describe the bug clearly and concisely."** (header: "Bug") — Provide short prompt-hint options like "Skill failed with error", "Unexpected behavior", "Skill hangs or times out". The user will typically select "Other" to type their description.++**Call 2** — Repro steps and expected vs actual (3 questions):++1. **"What steps reproduce the bug?"** (header: "Repro steps") — Provide prompt-hint options like "Ran the skill with default settings", "Ran the skill with custom arguments". The user will typically select "Other" to type their steps.+2. **"What did you expect to happen?"** (header: "Expected") — Provide prompt-hint options like "Skill should have succeeded", "Different output expected". The user will typically select "Other" to type their answer.+3. **"What actually happened?"** (header: "Actual") — Provide prompt-hint options like "Got an error message", "Wrong output produced", "Skill hung or timed out". The user will typically select "Other" to type their answer.++**Call 3** — Environment details:++Use `AskUserQuestion` with a single question: **"We recommend including environment details (OS, Claude Code version, PAC CLI version) to help maintainers reproduce and debug the issue faster. Include them?"** (header: "Environment") — Options: "Yes, auto-collect them" (recommended), "No, skip".++- If **yes**: Auto-collect the following by running shell commands:+ - **OS**: Detect the user's OS name and version using an appropriate command for their platform.+ - **Claude Code version**: Run `claude --version`+ - **PAC CLI version**: Run `pac help` and extract the version from the output+ - Present the collected details to the user.+- If **no**: Skip environment fields.++**Call 4** — Logs:++Use `AskUserQuestion` with a single question: **"Do you want to include any relevant logs or error messages?"** (header: "Logs") — Options: "Yes, I'll paste them", "No, skip".++- If **yes**: Use `AskUserQuestion` to ask: **"Please paste any relevant logs or error messages."** (header: "Paste logs") — Provide prompt-hint options like "Error message from terminal", "Skill output log". The user will typically select "Other" to paste their content.+- If **no**: Skip this field.++**Output**: All bug report fields gathered.++---++## Phase 3: Preview Issue++**Goal**: Present the complete issue to the user for review before creating it.++**Actions**:++Remind the user: **"This issue will be created on the public GitHub repository. Please review and make sure it does not contain any sensitive information (credentials, internal URLs, tenant IDs, customer data, or proprietary code)."**++Format and display the full issue exactly as it will be filed:++```+===== ISSUE PREVIEW =====++Title: [Bug] <short summary>++Plugin: <plugin-name>+Plugin Version: <version>+Skill / Command: <skill or "N/A">++Bug Description:+<description>++Steps to Reproduce:+<steps>++Expected Behavior:+<expected>++Actual Behavior:+<actual>++Relevant Logs / Screenshots:+<logs or "None">++Environment:+<environment details or "None">++Labels: bug, <plugin-name>++---+🤖 This issue was created using the /report-issue skill.++===== END PREVIEW =====+```++Use `AskUserQuestion` to confirm:++> "Here's the issue that will be created. Would you like to proceed, or would you like to make any changes?"++- If the user wants changes, go back and update the relevant fields, then preview again.+- If the user approves, proceed to Phase 4.++**Output**: User-approved issue ready for creation.++---++## Phase 4: Create Issue++**Goal**: Create the GitHub issue using the `gh` CLI.++**Actions**:++1. Build the issue body from the gathered fields, matching the bug report template structure:++ ```+ ### Plugin++ <plugin-name>++ ### Plugin Version++ <version>++ ### Skill / Command++ <skill or empty>++ ### Bug Description++ <description>++ ### Steps to Reproduce++ <steps>++ ### Expected Behavior++ <expected>++ ### Actual Behavior++ <actual>++ ### Relevant Logs / Screenshots++ <logs or "None">++ ### Environment++ <environment details or "None">++ ---+ 🤖 *This issue was created using the `/report-issue` skill.*+ ```++2. Create the issue via `gh`:++ ```bash+ gh issue create --repo microsoft/power-platform-skills --title "[Bug] <short summary>" --label "bug" --label "<plugin-name>" --body "<body>"+ ```++ Use a HEREDOC for the body to preserve formatting.++3. Capture and display the issue URL to the user.++**Output**: Issue created, URL shared with user.++---++## Phase 5: Summarize++**Goal**: Confirm success and suggest next steps.++**Actions**:++1. Display the created issue URL.+2. Let the user know they can track the issue on GitHub.++**Output**: Issue URL and next steps presented.++---++## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase.+- **Always use AskUserQuestion** before collecting any environment information — never run commands to gather system details without explicit user consent.+- **Always preview the full issue** before creating it — the user must approve the content.+- **Use the `gh` CLI** to create the issue — confirm it is authenticated before attempting.++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Identify plugin and version | Identifying plugin | Auto-detect plugin name and version from plugin.json |+| Gather bug details | Gathering details | Collect bug description, repro steps, expected/actual behavior |+| Preview issue | Previewing issue | Show complete issue for user review and approval |+| Create issue | Creating issue | File the bug report on GitHub via gh CLI |+| Summarize | Summarizing | Confirm success and share issue URL |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`.++---++**Begin with Phase 1: Identify Plugin & Version**diff --git a/plugins/code-apps/skills/report-issue/report-issue-workflow.md b/plugins/code-apps/skills/report-issue/report-issue-workflow.mddeleted file mode 120000index 467fa9175..000000000--- a/plugins/code-apps/skills/report-issue/report-issue-workflow.md+++ /dev/null@@ -1 +0,0 @@-../../../../shared/skills/report-issue/report-issue-workflow.md\ No newline at end of filediff --git a/plugins/code-apps/skills/report-issue/report-issue-workflow.md b/plugins/code-apps/skills/report-issue/report-issue-workflow.mdnew file mode 100644index 000000000..20401ebb8--- /dev/null+++ b/plugins/code-apps/skills/report-issue/report-issue-workflow.md@@ -0,0 +1,230 @@+# Report Issue++File a bug report on the [power-platform-skills](https://github.com/microsoft/power-platform-skills) GitHub repository. This workflow gathers the required information, presents a full preview, and creates the issue on the user's behalf.++**Initial request:** $ARGUMENTS++> **WARNING:** Before proceeding, inform the user: "This will create an issue on the **public** GitHub repository [microsoft/power-platform-skills](https://github.com/microsoft/power-platform-skills). **Do not include any sensitive information** such as credentials, internal URLs, tenant IDs, customer data, or proprietary code in the bug report."++---++## Phase 1: Identify Plugin & Version++**Goal**: Determine which plugin the bug is for and its version.++**Actions**:++1. Create a task list with all 5 phases (see [Progress Tracking](#progress-tracking) table).+2. **Auto-detect the plugin name** from the current plugin context by reading `${PLUGIN_ROOT}/.plugin/plugin.json`. Extract the `name` field.+3. **Auto-detect the plugin version** from the same `plugin.json` — extract the `version` field.+4. If the plugin name or version cannot be determined, use `AskUserQuestion` to ask the user.++**Output**: Plugin name and version confirmed.++---++## Phase 2: Gather Bug Details++**Goal**: Collect all required and optional fields for the bug report.++**Actions**:++### 2.1 Check Arguments++If `$ARGUMENTS` contains a description of the bug, extract as much information as possible from it to pre-fill the fields below. Still confirm with the user.++### 2.2 Ask for Bug Details++Use `AskUserQuestion` to gather bug details. `AskUserQuestion` supports 1-4 questions per call, but each question requires 2-4 predefined options. Since bug report fields are free-text, use options as prompt hints and let the user type their actual response via "Other". Skip any field the user already provided in `$ARGUMENTS`.++**Call 1** — Skill and bug description (2 questions):++1. **"Which skill or command were you using?"** (header: "Skill") — Provide the plugin's known skills as options (e.g., `deploy-site`, `create-site`). This is optional — the user can skip it.+2. **"Please describe the bug clearly and concisely."** (header: "Bug") — Provide short prompt-hint options like "Skill failed with error", "Unexpected behavior", "Skill hangs or times out". The user will typically select "Other" to type their description.++**Call 2** — Repro steps and expected vs actual (3 questions):++1. **"What steps reproduce the bug?"** (header: "Repro steps") — Provide prompt-hint options like "Ran the skill with default settings", "Ran the skill with custom arguments". The user will typically select "Other" to type their steps.+2. **"What did you expect to happen?"** (header: "Expected") — Provide prompt-hint options like "Skill should have succeeded", "Different output expected". The user will typically select "Other" to type their answer.+3. **"What actually happened?"** (header: "Actual") — Provide prompt-hint options like "Got an error message", "Wrong output produced", "Skill hung or timed out". The user will typically select "Other" to type their answer.++**Call 3** — Environment details:++Use `AskUserQuestion` with a single question: **"We recommend including environment details (OS, Claude Code version, PAC CLI version) to help maintainers reproduce and debug the issue faster. Include them?"** (header: "Environment") — Options: "Yes, auto-collect them" (recommended), "No, skip".++- If **yes**: Auto-collect the following by running shell commands:+ - **OS**: Detect the user's OS name and version using an appropriate command for their platform.+ - **Claude Code version**: Run `claude --version`+ - **PAC CLI version**: Run `pac help` and extract the version from the output+ - Present the collected details to the user.+- If **no**: Skip environment fields.++**Call 4** — Logs:++Use `AskUserQuestion` with a single question: **"Do you want to include any relevant logs or error messages?"** (header: "Logs") — Options: "Yes, I'll paste them", "No, skip".++- If **yes**: Use `AskUserQuestion` to ask: **"Please paste any relevant logs or error messages."** (header: "Paste logs") — Provide prompt-hint options like "Error message from terminal", "Skill output log". The user will typically select "Other" to paste their content.+- If **no**: Skip this field.++**Output**: All bug report fields gathered.++---++## Phase 3: Preview Issue++**Goal**: Present the complete issue to the user for review before creating it.++**Actions**:++Remind the user: **"This issue will be created on the public GitHub repository. Please review and make sure it does not contain any sensitive information (credentials, internal URLs, tenant IDs, customer data, or proprietary code)."**++Format and display the full issue exactly as it will be filed:++```+===== ISSUE PREVIEW =====++Title: [Bug] <short summary>++Plugin: <plugin-name>+Plugin Version: <version>+Skill / Command: <skill or "N/A">++Bug Description:+<description>++Steps to Reproduce:+<steps>++Expected Behavior:+<expected>++Actual Behavior:+<actual>++Relevant Logs / Screenshots:+<logs or "None">++Environment:+<environment details or "None">++Labels: bug, <plugin-name>++---+🤖 This issue was created using the /report-issue skill.++===== END PREVIEW =====+```++Use `AskUserQuestion` to confirm:++> "Here's the issue that will be created. Would you like to proceed, or would you like to make any changes?"++- If the user wants changes, go back and update the relevant fields, then preview again.+- If the user approves, proceed to Phase 4.++**Output**: User-approved issue ready for creation.++---++## Phase 4: Create Issue++**Goal**: Create the GitHub issue using the `gh` CLI.++**Actions**:++1. Build the issue body from the gathered fields, matching the bug report template structure:++ ```+ ### Plugin++ <plugin-name>++ ### Plugin Version++ <version>++ ### Skill / Command++ <skill or empty>++ ### Bug Description++ <description>++ ### Steps to Reproduce++ <steps>++ ### Expected Behavior++ <expected>++ ### Actual Behavior++ <actual>++ ### Relevant Logs / Screenshots++ <logs or "None">++ ### Environment++ <environment details or "None">++ ---+ 🤖 *This issue was created using the `/report-issue` skill.*+ ```++2. Create the issue via `gh`:++ ```bash+ gh issue create --repo microsoft/power-platform-skills --title "[Bug] <short summary>" --label "bug" --label "<plugin-name>" --body "<body>"+ ```++ Use a HEREDOC for the body to preserve formatting.++3. Capture and display the issue URL to the user.++**Output**: Issue created, URL shared with user.++---++## Phase 5: Summarize++**Goal**: Confirm success and suggest next steps.++**Actions**:++1. Display the created issue URL.+2. Let the user know they can track the issue on GitHub.++**Output**: Issue URL and next steps presented.++---++## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase.+- **Always use AskUserQuestion** before collecting any environment information — never run commands to gather system details without explicit user consent.+- **Always preview the full issue** before creating it — the user must approve the content.+- **Use the `gh` CLI** to create the issue — confirm it is authenticated before attempting.++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Identify plugin and version | Identifying plugin | Auto-detect plugin name and version from plugin.json |+| Gather bug details | Gathering details | Collect bug description, repro steps, expected/actual behavior |+| Preview issue | Previewing issue | Show complete issue for user review and approval |+| Create issue | Creating issue | File the bug report on GitHub via gh CLI |+| Summarize | Summarizing | Confirm success and share issue URL |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`.++---++**Begin with Phase 1: Identify Plugin & Version**diff --git a/plugins/mcp-apps/skills/report-issue/report-issue-workflow.md b/plugins/mcp-apps/skills/report-issue/report-issue-workflow.mddeleted file mode 120000index 467fa9175..000000000--- a/plugins/mcp-apps/skills/report-issue/report-issue-workflow.md+++ /dev/null@@ -1 +0,0 @@-../../../../shared/skills/report-issue/report-issue-workflow.md\ No newline at end of filediff --git a/plugins/mcp-apps/skills/report-issue/report-issue-workflow.md b/plugins/mcp-apps/skills/report-issue/report-issue-workflow.mdnew file mode 100644index 000000000..20401ebb8--- /dev/null+++ b/plugins/mcp-apps/skills/report-issue/report-issue-workflow.md@@ -0,0 +1,230 @@+# Report Issue++File a bug report on the [power-platform-skills](https://github.com/microsoft/power-platform-skills) GitHub repository. This workflow gathers the required information, presents a full preview, and creates the issue on the user's behalf.++**Initial request:** $ARGUMENTS++> **WARNING:** Before proceeding, inform the user: "This will create an issue on the **public** GitHub repository [microsoft/power-platform-skills](https://github.com/microsoft/power-platform-skills). **Do not include any sensitive information** such as credentials, internal URLs, tenant IDs, customer data, or proprietary code in the bug report."++---++## Phase 1: Identify Plugin & Version++**Goal**: Determine which plugin the bug is for and its version.++**Actions**:++1. Create a task list with all 5 phases (see [Progress Tracking](#progress-tracking) table).+2. **Auto-detect the plugin name** from the current plugin context by reading `${PLUGIN_ROOT}/.plugin/plugin.json`. Extract the `name` field.+3. **Auto-detect the plugin version** from the same `plugin.json` — extract the `version` field.+4. If the plugin name or version cannot be determined, use `AskUserQuestion` to ask the user.++**Output**: Plugin name and version confirmed.++---++## Phase 2: Gather Bug Details++**Goal**: Collect all required and optional fields for the bug report.++**Actions**:++### 2.1 Check Arguments++If `$ARGUMENTS` contains a description of the bug, extract as much information as possible from it to pre-fill the fields below. Still confirm with the user.++### 2.2 Ask for Bug Details++Use `AskUserQuestion` to gather bug details. `AskUserQuestion` supports 1-4 questions per call, but each question requires 2-4 predefined options. Since bug report fields are free-text, use options as prompt hints and let the user type their actual response via "Other". Skip any field the user already provided in `$ARGUMENTS`.++**Call 1** — Skill and bug description (2 questions):++1. **"Which skill or command were you using?"** (header: "Skill") — Provide the plugin's known skills as options (e.g., `deploy-site`, `create-site`). This is optional — the user can skip it.+2. **"Please describe the bug clearly and concisely."** (header: "Bug") — Provide short prompt-hint options like "Skill failed with error", "Unexpected behavior", "Skill hangs or times out". The user will typically select "Other" to type their description.++**Call 2** — Repro steps and expected vs actual (3 questions):++1. **"What steps reproduce the bug?"** (header: "Repro steps") — Provide prompt-hint options like "Ran the skill with default settings", "Ran the skill with custom arguments". The user will typically select "Other" to type their steps.+2. **"What did you expect to happen?"** (header: "Expected") — Provide prompt-hint options like "Skill should have succeeded", "Different output expected". The user will typically select "Other" to type their answer.+3. **"What actually happened?"** (header: "Actual") — Provide prompt-hint options like "Got an error message", "Wrong output produced", "Skill hung or timed out". The user will typically select "Other" to type their answer.++**Call 3** — Environment details:++Use `AskUserQuestion` with a single question: **"We recommend including environment details (OS, Claude Code version, PAC CLI version) to help maintainers reproduce and debug the issue faster. Include them?"** (header: "Environment") — Options: "Yes, auto-collect them" (recommended), "No, skip".++- If **yes**: Auto-collect the following by running shell commands:+ - **OS**: Detect the user's OS name and version using an appropriate command for their platform.+ - **Claude Code version**: Run `claude --version`+ - **PAC CLI version**: Run `pac help` and extract the version from the output+ - Present the collected details to the user.+- If **no**: Skip environment fields.++**Call 4** — Logs:++Use `AskUserQuestion` with a single question: **"Do you want to include any relevant logs or error messages?"** (header: "Logs") — Options: "Yes, I'll paste them", "No, skip".++- If **yes**: Use `AskUserQuestion` to ask: **"Please paste any relevant logs or error messages."** (header: "Paste logs") — Provide prompt-hint options like "Error message from terminal", "Skill output log". The user will typically select "Other" to paste their content.+- If **no**: Skip this field.++**Output**: All bug report fields gathered.++---++## Phase 3: Preview Issue++**Goal**: Present the complete issue to the user for review before creating it.++**Actions**:++Remind the user: **"This issue will be created on the public GitHub repository. Please review and make sure it does not contain any sensitive information (credentials, internal URLs, tenant IDs, customer data, or proprietary code)."**++Format and display the full issue exactly as it will be filed:++```+===== ISSUE PREVIEW =====++Title: [Bug] <short summary>++Plugin: <plugin-name>+Plugin Version: <version>+Skill / Command: <skill or "N/A">++Bug Description:+<description>++Steps to Reproduce:+<steps>++Expected Behavior:+<expected>++Actual Behavior:+<actual>++Relevant Logs / Screenshots:+<logs or "None">++Environment:+<environment details or "None">++Labels: bug, <plugin-name>++---+🤖 This issue was created using the /report-issue skill.++===== END PREVIEW =====+```++Use `AskUserQuestion` to confirm:++> "Here's the issue that will be created. Would you like to proceed, or would you like to make any changes?"++- If the user wants changes, go back and update the relevant fields, then preview again.+- If the user approves, proceed to Phase 4.++**Output**: User-approved issue ready for creation.++---++## Phase 4: Create Issue++**Goal**: Create the GitHub issue using the `gh` CLI.++**Actions**:++1. Build the issue body from the gathered fields, matching the bug report template structure:++ ```+ ### Plugin++ <plugin-name>++ ### Plugin Version++ <version>++ ### Skill / Command++ <skill or empty>++ ### Bug Description++ <description>++ ### Steps to Reproduce++ <steps>++ ### Expected Behavior++ <expected>++ ### Actual Behavior++ <actual>++ ### Relevant Logs / Screenshots++ <logs or "None">++ ### Environment++ <environment details or "None">++ ---+ 🤖 *This issue was created using the `/report-issue` skill.*+ ```++2. Create the issue via `gh`:++ ```bash+ gh issue create --repo microsoft/power-platform-skills --title "[Bug] <short summary>" --label "bug" --label "<plugin-name>" --body "<body>"+ ```++ Use a HEREDOC for the body to preserve formatting.++3. Capture and display the issue URL to the user.++**Output**: Issue created, URL shared with user.++---++## Phase 5: Summarize++**Goal**: Confirm success and suggest next steps.++**Actions**:++1. Display the created issue URL.+2. Let the user know they can track the issue on GitHub.++**Output**: Issue URL and next steps presented.++---++## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase.+- **Always use AskUserQuestion** before collecting any environment information — never run commands to gather system details without explicit user consent.+- **Always preview the full issue** before creating it — the user must approve the content.+- **Use the `gh` CLI** to create the issue — confirm it is authenticated before attempting.++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Identify plugin and version | Identifying plugin | Auto-detect plugin name and version from plugin.json |+| Gather bug details | Gathering details | Collect bug description, repro steps, expected/actual behavior |+| Preview issue | Previewing issue | Show complete issue for user review and approval |+| Create issue | Creating issue | File the bug report on GitHub via gh CLI |+| Summarize | Summarizing | Confirm success and share issue URL |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`.++---++**Begin with Phase 1: Identify Plugin & Version**diff --git a/plugins/model-apps/.mcp.json b/plugins/model-apps/.mcp.jsonindex a6cd108c9..e6330aa1b 100644--- a/plugins/model-apps/.mcp.json+++ b/plugins/model-apps/.mcp.json@@ -3,7 +3,8 @@"playwright": {"command": "node","args": [- "${CLAUDE_PLUGIN_ROOT}/scripts/launch-playwright-mcp.js"+ "-e",+ "const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root) throw new Error('PLUGIN_ROOT is not set'); const mod=require(path.resolve(root,'scripts','launch-playwright-mcp.js')); if(mod&&typeof mod.launch==='function') mod.launch();"]}}diff --git a/plugins/model-apps/skills/report-issue/report-issue-workflow.md b/plugins/model-apps/skills/report-issue/report-issue-workflow.mddeleted file mode 120000index 467fa9175..000000000--- a/plugins/model-apps/skills/report-issue/report-issue-workflow.md+++ /dev/null@@ -1 +0,0 @@-../../../../shared/skills/report-issue/report-issue-workflow.md\ No newline at end of filediff --git a/plugins/model-apps/skills/report-issue/report-issue-workflow.md b/plugins/model-apps/skills/report-issue/report-issue-workflow.mdnew file mode 100644index 000000000..20401ebb8--- /dev/null+++ b/plugins/model-apps/skills/report-issue/report-issue-workflow.md@@ -0,0 +1,230 @@+# Report Issue++File a bug report on the [power-platform-skills](https://github.com/microsoft/power-platform-skills) GitHub repository. This workflow gathers the required information, presents a full preview, and creates the issue on the user's behalf.++**Initial request:** $ARGUMENTS++> **WARNING:** Before proceeding, inform the user: "This will create an issue on the **public** GitHub repository [microsoft/power-platform-skills](https://github.com/microsoft/power-platform-skills). **Do not include any sensitive information** such as credentials, internal URLs, tenant IDs, customer data, or proprietary code in the bug report."++---++## Phase 1: Identify Plugin & Version++**Goal**: Determine which plugin the bug is for and its version.++**Actions**:++1. Create a task list with all 5 phases (see [Progress Tracking](#progress-tracking) table).+2. **Auto-detect the plugin name** from the current plugin context by reading `${PLUGIN_ROOT}/.plugin/plugin.json`. Extract the `name` field.+3. **Auto-detect the plugin version** from the same `plugin.json` — extract the `version` field.+4. If the plugin name or version cannot be determined, use `AskUserQuestion` to ask the user.++**Output**: Plugin name and version confirmed.++---++## Phase 2: Gather Bug Details++**Goal**: Collect all required and optional fields for the bug report.++**Actions**:++### 2.1 Check Arguments++If `$ARGUMENTS` contains a description of the bug, extract as much information as possible from it to pre-fill the fields below. Still confirm with the user.++### 2.2 Ask for Bug Details++Use `AskUserQuestion` to gather bug details. `AskUserQuestion` supports 1-4 questions per call, but each question requires 2-4 predefined options. Since bug report fields are free-text, use options as prompt hints and let the user type their actual response via "Other". Skip any field the user already provided in `$ARGUMENTS`.++**Call 1** — Skill and bug description (2 questions):++1. **"Which skill or command were you using?"** (header: "Skill") — Provide the plugin's known skills as options (e.g., `deploy-site`, `create-site`). This is optional — the user can skip it.+2. **"Please describe the bug clearly and concisely."** (header: "Bug") — Provide short prompt-hint options like "Skill failed with error", "Unexpected behavior", "Skill hangs or times out". The user will typically select "Other" to type their description.++**Call 2** — Repro steps and expected vs actual (3 questions):++1. **"What steps reproduce the bug?"** (header: "Repro steps") — Provide prompt-hint options like "Ran the skill with default settings", "Ran the skill with custom arguments". The user will typically select "Other" to type their steps.+2. **"What did you expect to happen?"** (header: "Expected") — Provide prompt-hint options like "Skill should have succeeded", "Different output expected". The user will typically select "Other" to type their answer.+3. **"What actually happened?"** (header: "Actual") — Provide prompt-hint options like "Got an error message", "Wrong output produced", "Skill hung or timed out". The user will typically select "Other" to type their answer.++**Call 3** — Environment details:++Use `AskUserQuestion` with a single question: **"We recommend including environment details (OS, Claude Code version, PAC CLI version) to help maintainers reproduce and debug the issue faster. Include them?"** (header: "Environment") — Options: "Yes, auto-collect them" (recommended), "No, skip".++- If **yes**: Auto-collect the following by running shell commands:+ - **OS**: Detect the user's OS name and version using an appropriate command for their platform.+ - **Claude Code version**: Run `claude --version`+ - **PAC CLI version**: Run `pac help` and extract the version from the output+ - Present the collected details to the user.+- If **no**: Skip environment fields.++**Call 4** — Logs:++Use `AskUserQuestion` with a single question: **"Do you want to include any relevant logs or error messages?"** (header: "Logs") — Options: "Yes, I'll paste them", "No, skip".++- If **yes**: Use `AskUserQuestion` to ask: **"Please paste any relevant logs or error messages."** (header: "Paste logs") — Provide prompt-hint options like "Error message from terminal", "Skill output log". The user will typically select "Other" to paste their content.+- If **no**: Skip this field.++**Output**: All bug report fields gathered.++---++## Phase 3: Preview Issue++**Goal**: Present the complete issue to the user for review before creating it.++**Actions**:++Remind the user: **"This issue will be created on the public GitHub repository. Please review and make sure it does not contain any sensitive information (credentials, internal URLs, tenant IDs, customer data, or proprietary code)."**++Format and display the full issue exactly as it will be filed:++```+===== ISSUE PREVIEW =====++Title: [Bug] <short summary>++Plugin: <plugin-name>+Plugin Version: <version>+Skill / Command: <skill or "N/A">++Bug Description:+<description>++Steps to Reproduce:+<steps>++Expected Behavior:+<expected>++Actual Behavior:+<actual>++Relevant Logs / Screenshots:+<logs or "None">++Environment:+<environment details or "None">++Labels: bug, <plugin-name>++---+🤖 This issue was created using the /report-issue skill.++===== END PREVIEW =====+```++Use `AskUserQuestion` to confirm:++> "Here's the issue that will be created. Would you like to proceed, or would you like to make any changes?"++- If the user wants changes, go back and update the relevant fields, then preview again.+- If the user approves, proceed to Phase 4.++**Output**: User-approved issue ready for creation.++---++## Phase 4: Create Issue++**Goal**: Create the GitHub issue using the `gh` CLI.++**Actions**:++1. Build the issue body from the gathered fields, matching the bug report template structure:++ ```+ ### Plugin++ <plugin-name>++ ### Plugin Version++ <version>++ ### Skill / Command++ <skill or empty>++ ### Bug Description++ <description>++ ### Steps to Reproduce++ <steps>++ ### Expected Behavior++ <expected>++ ### Actual Behavior++ <actual>++ ### Relevant Logs / Screenshots++ <logs or "None">++ ### Environment++ <environment details or "None">++ ---+ 🤖 *This issue was created using the `/report-issue` skill.*+ ```++2. Create the issue via `gh`:++ ```bash+ gh issue create --repo microsoft/power-platform-skills --title "[Bug] <short summary>" --label "bug" --label "<plugin-name>" --body "<body>"+ ```++ Use a HEREDOC for the body to preserve formatting.++3. Capture and display the issue URL to the user.++**Output**: Issue created, URL shared with user.++---++## Phase 5: Summarize++**Goal**: Confirm success and suggest next steps.++**Actions**:++1. Display the created issue URL.+2. Let the user know they can track the issue on GitHub.++**Output**: Issue URL and next steps presented.++---++## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase.+- **Always use AskUserQuestion** before collecting any environment information — never run commands to gather system details without explicit user consent.+- **Always preview the full issue** before creating it — the user must approve the content.+- **Use the `gh` CLI** to create the issue — confirm it is authenticated before attempting.++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Identify plugin and version | Identifying plugin | Auto-detect plugin name and version from plugin.json |+| Gather bug details | Gathering details | Collect bug description, repro steps, expected/actual behavior |+| Preview issue | Previewing issue | Show complete issue for user review and approval |+| Create issue | Creating issue | File the bug report on GitHub via gh CLI |+| Summarize | Summarizing | Confirm success and share issue URL |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`.++---++**Begin with Phase 1: Identify Plugin & Version**diff --git a/plugins/power-pages/.mcp.json b/plugins/power-pages/.mcp.jsonindex c5353da3d..b256d7aee 100644--- a/plugins/power-pages/.mcp.json+++ b/plugins/power-pages/.mcp.json@@ -3,7 +3,8 @@"playwright": {"command": "node","args": [- "${CLAUDE_PLUGIN_ROOT}/scripts/launch-playwright-mcp.js"+ "-e",+ "const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root) throw new Error('PLUGIN_ROOT is not set'); const mod=require(path.resolve(root,'scripts','launch-playwright-mcp.js')); if(mod&&typeof mod.launch==='function') mod.launch();"]},"microsoft-learn": {diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex 64776b302..9be05f207 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -414,9 +414,9 @@ These patterns have caused repeated PR review feedback. Check for them before su## 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.+This plugin ships 1DS telemetry for skill-run and script-run signals. The canonical shared library lives at the repo-root `shared/telemetry/`; `scripts/lib/telemetry/lib` is a physical copy bundled with this plugin so local checkouts and installed plugins do not depend on symlink handling. Zero npm dependencies — nothing to install.-- **`scripts/lib/telemetry/lib` is a symlink** to the repo-root `shared/telemetry/lib` — edit `shared/telemetry/lib/` directly; there is no copy to re-sync. The real files under `scripts/lib/telemetry/` are `ikey.json` (this plugin's config) and `resolver.js` (the resolver contract implementation). **Posture:** the committed `ikey.json` ships `disabled: false` — transmission is enabled for power-pages (the tenant-side Kusto stream + annotation for `PagesAIPluginEvent` are provisioned). Set `disabled: true` to hard-off (no POST, no local log) if you need to suppress all telemetry at the source.+- **`scripts/lib/telemetry/lib` is copied** from the repo-root `shared/telemetry/lib` — edit `shared/telemetry/lib/` first, then refresh this plugin's copy in the same change. The real files next to the copy are `ikey.json` (this plugin's config) and `resolver.js` (the resolver contract implementation). **Posture:** the committed `ikey.json` ships `disabled: false` — transmission is enabled for power-pages (the tenant-side Kusto stream + annotation for `PagesAIPluginEvent` are provisioned). Set `disabled: true` to hard-off (no POST, no local log) if you need to suppress all telemetry at the source.- **Region routing (Artemis geo + cloud stamp)** lives in `scripts/lib/telemetry/region/` and is wired through `scripts/lib/telemetry/resolver.js`, which implements the resolver contract (`resolve({ event, cfg, cloud, configDir })` / `isProvisioned(cfg)`). The shared dispatcher is routing-agnostic — it auto-discovers `resolver.js` by convention (sibling of `ikey.json`) and calls it; the `region/` implementation is entirely plugin-owned and never referenced by the shared library.- **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`. Automation/CI can disable transmission by setting `POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT=1` (or `true`); this opt-out has the **highest precedence** — it overrides both a persisted `/power-pages:telemetry` choice and `/power-pages:telemetry on`. Transmission-only suppression — the local mirror is still written.- **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.diff --git a/plugins/power-pages/hooks/hooks.json b/plugins/power-pages/hooks/hooks.jsonindex 605e22b3a..663b8621a 100644--- a/plugins/power-pages/hooks/hooks.json+++ b/plugins/power-pages/hooks/hooks.json@@ -6,7 +6,7 @@"hooks": [{"type": "command",- "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/run-skill-pretool-telemetry.js\"",+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-skill-pretool-telemetry.js'));\"","timeout": 30}]@@ -18,7 +18,7 @@"hooks": [{"type": "command",- "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/run-skill-posttool-validation.js\"",+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-skill-posttool-validation.js'));\"","timeout": 30}]@@ -29,7 +29,7 @@"hooks": [{"type": "command",- "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/run-user-prompt-telemetry.js\"",+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-user-prompt-telemetry.js'));\"","timeout": 30}]diff --git a/plugins/power-pages/hooks/run-skill-pretool-telemetry.js b/plugins/power-pages/hooks/run-skill-pretool-telemetry.jsindex 128290bf9..cad9ba2f3 100644--- a/plugins/power-pages/hooks/run-skill-pretool-telemetry.js+++ b/plugins/power-pages/hooks/run-skill-pretool-telemetry.js@@ -156,9 +156,9 @@ function readStdin() {configDir,fakeProbe,// Point the dispatcher at the same ikey.json readIkey() used — the- // override seam when set, otherwise this plugin's real config. (lib/ is- // a symlink to shared/, so the dispatcher's __dirname default would- // otherwise hit shared/'s placeholder.)+ // override seam when set, otherwise this plugin's real config. This keeps+ // shared-source tests and plugin-bundled library copies from accidentally+ // falling back to shared/telemetry's placeholder ikey.json.ikeyJsonPath: ikeyPath,});diff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.mdindex b63488cfa..a41131b9c 100644--- a/plugins/power-pages/references/approval-gates.md+++ b/plugins/power-pages/references/approval-gates.md@@ -672,7 +672,7 @@ New skill introduced by PR #144. Orchestrates AI summarization API integration a### Cross-plugin shared skills — out of catalog scope-`report-issue` — The power-pages SKILL.md wrapper at `plugins/power-pages/skills/report-issue/SKILL.md` is a thin re-export that contains no prompts. The actual workflow with `AskUserQuestion` calls lives in `shared/skills/report-issue/report-issue-workflow.md`, which is consumed by every plugin (not just power-pages). The shared workflow lies outside the per-plugin lint scope (`plugins/power-pages/skills/`), so its prompts are not catalogued here. If the shared workflow is ever ported into per-plugin SKILL.md files, add a `report-issue:*` section to this catalog.+`report-issue` — Its prompts are cross-plugin, not power-pages-specific, so they are not catalogued here. If the shared workflow is ever governed by per-plugin approval-gate linting, add a `report-issue:*` section to this catalog.---@@ -715,7 +715,7 @@ These need explicit confirmation from the reviewer before SKILL.md edits land. R- Markers added to all non-ALM SKILL.md files (HTML comment + 🚦 block per gate; `not-a-gate` comment per data-gathering prompt or meta-mention).- `scripts/lint-skills-alm.js` warn-only branch removed — all skills now hard-fail.- `AGENTS.md` Key Patterns updated — Approval Gate convention applies plugin-wide; new skills must extend §6 in the same PR they introduce a prompt.-- `report-issue` excluded from the catalog (cross-plugin shared workflow lives outside the per-plugin lint scope). **Cross-plugin TODO:** the `AskUserQuestion` calls in `shared/skills/report-issue/report-issue-workflow.md` are not caught by any per-plugin lint today. A future cross-plugin sweep should either (a) define a `shared:*` namespace in the catalog and add markers in the shared workflow, or (b) duplicate the workflow into each plugin so the per-plugin lint covers it.+- `report-issue` excluded from the catalog because its `AskUserQuestion` calls come from a cross-plugin shared workflow. **Cross-plugin TODO:** those shared prompts are not caught by any per-plugin lint today. A future cross-plugin sweep should define a `shared:*` namespace in the catalog or explicitly opt each plugin copy into per-plugin lint coverage.- v3 lint changes: removed warn-only branch; tightened `m <= promptLine` to strict `m <`; relaxed `CATALOG_GATE_ID_PATTERN` to case-insensitive on the skill-name segment; added two new rules — `CATALOG-row-must-have-marker` (reverse check — catalog rows of `kind: gate` must have a matching SKILL.md marker; prevents the orphan-row class of bug v3 closed by hand) and `GATE-prose-block-required` (every marker must be followed within 10 lines by a 🚦 sentinel; minimum-viable check against prose-block deletion). Field rename: `Blast radius if skipped:` → `Why we ask:` across all ~60 prose blocks plus §4.1 template.---diff --git a/plugins/power-pages/scripts/lib/telemetry/lib b/plugins/power-pages/scripts/lib/telemetry/libdeleted file mode 120000index 25132cce3..000000000--- a/plugins/power-pages/scripts/lib/telemetry/lib+++ /dev/null@@ -1 +0,0 @@-../../../../../shared/telemetry/lib\ No newline at end of filediff --git a/plugins/power-pages/scripts/lib/telemetry/lib/agent-info.js b/plugins/power-pages/scripts/lib/telemetry/lib/agent-info.jsnew file mode 100644index 000000000..3904f5bc1--- /dev/null+++ b/plugins/power-pages/scripts/lib/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/plugins/power-pages/scripts/lib/telemetry/lib/emit-dispatcher.js b/plugins/power-pages/scripts/lib/telemetry/lib/emit-dispatcher.jsnew file mode 100644index 000000000..833aec31f--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/lib/emit-dispatcher.js@@ -0,0 +1,245 @@+#!/usr/bin/env node+"use strict";++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const https = require("node:https");+const { FIELD_TYPES, pick } = require("./events");+const { loadResolver } = require("./resolver-loader");+const { isTransmissionOptedOut } = require("./user-config");++function exitSilently() {+ process.exit(0);+}+process.on("uncaughtException", exitSilently);+process.on("unhandledRejection", exitSilently);+process.stdin.on("error", exitSilently);++const PLACEHOLDER_IKEY = "PLACEHOLDER_REPLACE_BEFORE_SHIPPING";+const DEFAULT_LOCAL_DIR = path.join(os.homedir(), ".power-platform-skills");+const FAKE_PROBE = process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "";+const CONFIG_DIR_ENV = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";+const CLOUD_ENV = process.env.POWER_PLATFORM_SKILLS_CLOUD || "";+// Override env vars — TEST seams only. Production resolves the iKey/collector+// via the plugin resolver / static config in ikey.json and never sets these.+const IKEY_OVERRIDE = process.env.POWER_PLATFORM_SKILLS_IKEY || "";+const COLLECTOR_OVERRIDE = process.env.POWER_PLATFORM_SKILLS_COLLECTOR || "";++function localConfigDir() {+ return CONFIG_DIR_ENV || DEFAULT_LOCAL_DIR;+}++// Anonymous telemetry is default-on. The user opt-out is per-plugin and lives in+// config.json (telemetry[<pluginName>] === "off"), written by the telemetry skill.+// It suppresses TRANSMISSION only; the local mirror is written before this gate.+function 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 / region state.+function ikeyJsonPath() {+ return (+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON ||+ path.join(__dirname, "..", "ikey.json")+ );+}++// Returns the parsed ikey.json, or null when it is missing/unreadable. null is+// treated as the repo kill switch (fail CLOSED): if we cannot read the config+// we cannot confirm emission is authorized, so we suppress rather than risk a+// POST / local log in an unexpected state.+function readIkeyConfig() {+ try {+ return JSON.parse(fs.readFileSync(ikeyJsonPath(), "utf8"));+ } catch {+ return null;+ }+}++// Repo-side kill switch: a missing/unreadable config (null) or an explicit+// `"disabled": true` suppresses ALL events regardless of opt-out or region+// state. Lets infrastructure PRs land while the tenant-side annotation + Kusto+// table are still being provisioned. Flip `disabled` to false when ready.+function isDisabledByConfig(cfg) {+ return !cfg || cfg.disabled === true;+}++// Reserved meta fields that builders always write into event.data. They are+// not user-facing telemetry columns, so they live outside FIELD_TYPES but+// must survive sanitization.+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(eventName, time, sanitized, resolvedIKey, eventStreamName) {+ return {+ ver: "4.0",+ name: eventStreamName || eventName || "",+ time,+ iKey: "o:" + String(resolvedIKey || "").split("-")[0],+ data: sanitized,+ };+}++function writeProbe(filePath, { headers, body }) {+ try {+ fs.writeFileSync(filePath, JSON.stringify({ headers, body }), "utf8");+ } catch {+ // ignore+ }+}++function writeLocalLog(record) {+ try {+ const { appendLocal } = require("./local-log");+ appendLocal(record, { configDir: localConfigDir() });+ } catch {+ // fail closed+ }+}++// ---- Read config + repo-side kill switch (applies before ANY side effect) --+// The `disabled` repo config (and an unreadable config) is the one true+// hard-off: no local log, no POST. The per-plugin user opt-out is NOT checked+// here — it suppresses transmission only, and is applied below AFTER the local+// mirror is written. cfg is reused for resolver context + static fallback in+// the stdin handler.+const cfg = readIkeyConfig();+if (isDisabledByConfig(cfg)) exitSilently();+const resolver = loadResolver(path.dirname(ikeyJsonPath()));++// ---- Read stdin ------------------------------------------------------------+let raw = "";+process.stdin.setEncoding("utf8");+process.stdin.on("data", (c) => (raw += c));+process.stdin.on("end", async () => {+ 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 resolves AND irrespective of the+ // per-plugin transmission opt-out. The file stays on the user's machine; it+ // is a local diagnostic mirror of what is (or would be) sent to Kusto, not+ // transmitted telemetry. (A `disabled: true` repo config wrote nothing — it+ // 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();++ // Resolve the destination iKey + collector. Precedence: env override (test+ // seam) → plugin resolver.js (region/tenant/etc., owned by the plugin) →+ // static single-key config in ikey.json → none. The shared dispatcher knows+ // nothing about regions; the plugin's resolver.js owns that.+ let iKey = IKEY_OVERRIDE;+ let collectorUrl = COLLECTOR_OVERRIDE;+ if (!iKey || !collectorUrl) {+ if (resolver && typeof resolver.resolve === "function") {+ let resolved = null;+ try {+ resolved = await resolver.resolve({+ event,+ cfg,+ cloud: CLOUD_ENV,+ configDir: CONFIG_DIR_ENV || undefined,+ });+ } catch {+ // A plugin resolver threw/rejected — continue with no resolution rather+ // than letting the global unhandledRejection handler exit. The local+ // mirror was already written above; the static fallback below still+ // runs, so a transient resolver failure degrades to the configured+ // static key (or "no transmission") instead of crashing.+ resolved = null;+ }+ if (resolved) {+ iKey = iKey || resolved.iKey || "";+ collectorUrl = collectorUrl || resolved.collectorUrl || "";+ }+ }+ // Static fallback — documented precedence is resolver → static → none, so+ // this runs whether or not a resolver was present. A resolver that returns+ // nothing (or threw) still falls through to a configured static key rather+ // than silently disabling transmission.+ iKey = iKey || cfg.instrumentationKey || "";+ collectorUrl = collectorUrl || cfg.collector_url || "";+ }++ // Placeholder / unprovisioned mode → local mirror already written; no POST.+ const keyMissing = !iKey || iKey === PLACEHOLDER_IKEY || !collectorUrl;+ if (keyMissing) {+ return exitSilently();+ }++ // Real iKey → Common Schema envelope (reuses the same time + sanitized data+ // as the local mirror) → HTTPS POST.+ const envelope = buildEnvelope(event.name, time, sanitized, iKey, cfg.event_stream_name);+ const body = JSON.stringify(envelope) + "\n";+ const headers = {+ "Content-Type": "application/x-json-stream; charset=utf-8",+ "x-apikey": iKey,+ "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(collectorUrl);+ } 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/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.js b/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.jsnew file mode 100644index 000000000..b89bd1693--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.js@@ -0,0 +1,140 @@+"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 { loadResolver } = require("./resolver-loader");+const { readPacAuth } = require("./pac-auth");+const { readPacCliVersion, readAiAgent } = require("./agent-info");++function readIkey(telemetryDir) {+ // Test/override seam: POWER_PLATFORM_SKILLS_IKEY_JSON points at an alternate+ // ikey.json so tests don't have to mutate the checked-in config file.+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ const overridePath = override && override.trim() ? override : "";+ // Guard a missing/invalid telemetryDir (a caller bug this fail-closed helper+ // must tolerate): with no override there is no config to read, so fail CLOSED+ // (disabled: true) instead of letting path.join throw out of the library.+ if (!overridePath && (typeof telemetryDir !== "string" || !telemetryDir)) {+ return { cfg: null, dir: "", ikeyPath: "", eventStreamName: "", disabled: true };+ }+ const ikeyPath = overridePath || path.join(telemetryDir, "ikey.json");+ const dir = path.dirname(ikeyPath);+ try {+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));+ return { cfg, dir, ikeyPath, eventStreamName: cfg.event_stream_name || "", disabled: cfg.disabled === true };+ } catch {+ // ikey.json missing/unreadable → fail CLOSED (disabled: true), matching+ // emit-dispatcher.js's isDisabledByConfig(). If we can't read the config we+ // cannot confirm emission is authorized, so suppress.+ return { cfg: null, dir, ikeyPath, 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 or half-provisioned plugin pays effectively+ // no cost. The user opt-out is NOT checked here: the event is still built and+ // dispatched so the detached dispatcher can write the local diagnostic mirror;+ // the dispatcher reads the per-plugin config and skips the POST when opted out.+ const { cfg, dir, ikeyPath, eventStreamName, disabled } = readIkey(telemetryDir);+ if (disabled) return { emitted: false, skillName };+ // Provisioning fast-gate (generic): a plugin resolver decides "is there a key+ // worth paying the pac shellout for?"; default is "static key present".+ const resolver = loadResolver(dir);+ let provisioned;+ try {+ provisioned =+ resolver && typeof resolver.isProvisioned === "function"+ ? resolver.isProvisioned(cfg)+ : !!(cfg && cfg.instrumentationKey);+ } catch {+ // A plugin-provided resolver threw (or assumed cfg non-null) — treat as not+ // provisioned so a bad resolver can't break prompt handling (fail closed).+ provisioned = false;+ }+ if (!provisioned) return { emitted: false, skillName };++ const pacReader = typeof _readPacAuth === "function" ? _readPacAuth : readPacAuth;+ let pacAuth = null;+ 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, {+ cloud: (pacAuth && pacAuth.cloud) || "",+ configDir: process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "",+ fakeProbe: process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "",+ ikeyJsonPath: ikeyPath,+ });+ } catch {+ // fail closed — telemetry never propagates errors+ }++ return { emitted: true, skillName };+}++module.exports = { emitSkillStartedFromPrompt };diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/emit-spawn.js b/plugins/power-pages/scripts/lib/telemetry/lib/emit-spawn.jsnew file mode 100644index 000000000..0bd839d8a--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/lib/emit-spawn.js@@ -0,0 +1,72 @@+"use strict";++const { spawn } = require("node:child_process");+const path = require("node:path");+const { telemetryOptOutEnvVarName } = require("./user-config");++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 || "";+ const cloud = opts.cloud || "";+ const pluginName = event && event.data && event.data.pluginName;+ const optOutVarName = pluginName ? telemetryOptOutEnvVarName(pluginName) : "";+ const optOutValue =+ optOutVarName && process.env[optOutVarName] ? process.env[optOutVarName] : "";+ // Absolute path to the CALLING plugin's ikey.json. Tests and shared-source+ // development can execute this module from shared/telemetry/lib, whose default+ // __dirname-based ikey path is the shared placeholder, not the plugin's real+ // config. Passing the path explicitly makes the dispatcher read the right file+ // regardless of whether this library is running from shared/ or a plugin copy.+ 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,+ POWER_PLATFORM_SKILLS_CLOUD: cloud,+ // ikey.json path: an explicit env override (test seam) wins; otherwise+ // the calling plugin's ikey.json path so the dispatcher reads the+ // plugin's real config rather than shared/'s placeholder.+ POWER_PLATFORM_SKILLS_IKEY_JSON:+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON || ikeyJsonPath || "",+ // The opt-out is enforced in the detached dispatcher, which reads the+ // child's process.env — so the minimal allowlist must forward this var+ // explicitly or the highest-precedence opt-out never reaches it. Forward+ // only when actually set: an empty/unset value is a no-op for the+ // dispatcher's check (it trims and matches only "1"/"true"), so there's+ // no point planting an empty var in the child env.+ ...(optOutVarName && optOutValue+ ? { [optOutVarName]: optOutValue }+ : {}),+ },+ });+ 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/plugins/power-pages/scripts/lib/telemetry/lib/events.js b/plugins/power-pages/scripts/lib/telemetry/lib/events.jsnew file mode 100644index 000000000..51013e754--- /dev/null+++ b/plugins/power-pages/scripts/lib/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/plugins/power-pages/scripts/lib/telemetry/lib/local-log.js b/plugins/power-pages/scripts/lib/telemetry/lib/local-log.jsnew file mode 100644index 000000000..c5c27ba90--- /dev/null+++ b/plugins/power-pages/scripts/lib/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/plugins/power-pages/scripts/lib/telemetry/lib/pac-auth.js b/plugins/power-pages/scripts/lib/telemetry/lib/pac-auth.jsnew file mode 100644index 000000000..9c74c126f--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/lib/pac-auth.js@@ -0,0 +1,74 @@+"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");+ const cloud = pickLine(output, "Cloud");+ if (!tenantId && !orgId) {+ cache = null;+ return null;+ }+ cache = {+ orgId: orgId || "",+ tenantId: tenantId || "",+ cloud: cloud || "",+ };+ return cache;+}++module.exports = { readPacAuth, _resetCache };diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/prompt-detector.js b/plugins/power-pages/scripts/lib/telemetry/lib/prompt-detector.jsnew file mode 100644index 000000000..69ebd6701--- /dev/null+++ b/plugins/power-pages/scripts/lib/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/plugins/power-pages/scripts/lib/telemetry/lib/resolver-loader.js b/plugins/power-pages/scripts/lib/telemetry/lib/resolver-loader.jsnew file mode 100644index 000000000..5c5c2bb67--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/lib/resolver-loader.js@@ -0,0 +1,26 @@+"use strict";++const path = require("node:path");++// Discover an optional, plugin-provided resolver module that owns iKey/collector+// selection (region routing, tenant routing, etc.). Convention: a `resolver.js`+// next to the plugin's ikey.json. The shared library never imports a resolver+// directly — it loads whatever the plugin drops here and calls the documented+// contract: { resolve({event, cfg, cloud, configDir}), isProvisioned(cfg) }.+//+// Returns the resolver module, or null when none is present or it fails to load+// (callers then fall back to static config / a generic gate — fail open).+function loadResolver(dir) {+ if (!dir) return null;+ try {+ // path.resolve (not path.join): require() treats a non-"./"-prefixed+ // relative path as a module ID and searches node_modules. A relative `dir`+ // (e.g. from a relative POWER_PLATFORM_SKILLS_IKEY_JSON override) would then+ // miss the intended resolver.js. Resolve to an absolute path first.+ return require(path.resolve(dir, "resolver.js"));+ } catch {+ return null;+ }+}++module.exports = { loadResolver };diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/scrubber.js b/plugins/power-pages/scripts/lib/telemetry/lib/scrubber.jsnew file mode 100644index 000000000..517188404--- /dev/null+++ b/plugins/power-pages/scripts/lib/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/plugins/power-pages/scripts/lib/telemetry/lib/session.js b/plugins/power-pages/scripts/lib/telemetry/lib/session.jsnew file mode 100644index 000000000..cbf89884d--- /dev/null+++ b/plugins/power-pages/scripts/lib/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/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.jsnew file mode 100644index 000000000..4d5ede265--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js@@ -0,0 +1,91 @@+#!/usr/bin/env node+"use strict";++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { setTelemetryChoice, effectiveTelemetryChoice } = require("./user-config");++const ANONYMITY =+ "ℹ️ No personal data is collected. Telemetry is anonymous — it records only\n" ++ " operational fields like skill name, plugin version, OS/Node versions,\n" ++ " PAC CLI and agent versions, and Dataverse org/tenant IDs when available.\n" ++ " It never includes file paths, prompts, tool inputs, site names, URLs,\n" ++ " credentials, 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 = effectiveTelemetryChoice(dir, plugin) !== "off"; // default ON; honors env override when no stored choice+ 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/plugins/power-pages/scripts/lib/telemetry/lib/user-config.js b/plugins/power-pages/scripts/lib/telemetry/lib/user-config.jsnew file mode 100644index 000000000..ea0597f73--- /dev/null+++ b/plugins/power-pages/scripts/lib/telemetry/lib/user-config.js@@ -0,0 +1,106 @@+"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);+}++function isPlainObject(value) {+ return value && typeof value === "object" && !Array.isArray(value);+}++// 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 isPlainObject(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 (!isPlainObject(t)) return null;+ const v = t[pluginName];+ return v === "on" || v === "off" ? v : null;+}++// Builds the per-plugin opt-out var name: POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT+// where <PLUGIN> is the plugin name uppercased with non-alphanumeric runs -> "_".+function telemetryOptOutEnvVarName(pluginName) {+ return (+ "POWER_PLATFORM_SKILLS_TELEMETRY_" ++ String(pluginName).toUpperCase().replace(/[^A-Z0-9]+/g, "_") ++ "_OPTOUT"+ );+}++// True when the per-plugin opt-out env var is set to a truthy value (`1` or+// `true`, case-insensitive). Follows the dotnet `*_TELEMETRY_OPTOUT` convention:+// the var only disables — it is never used to re-enable. Unset / empty / `0` /+// `false` / anything else => not opted out. `env` is injectable so tests never+// mutate the real process.env.+function readTelemetryEnvOptOut(pluginName, env = process.env) {+ if (!pluginName) return false;+ const v = String(env[telemetryOptOutEnvVarName(pluginName)] || "").trim().toLowerCase();+ return v === "1" || v === "true";+}++// Resolves the effective on/off choice by precedence (highest first):+// 1. the env-var opt-out (when truthy => "off"; overrides everything below)+// 2. persisted config.json per-plugin choice (set via the slash skill)+// 3. null = default-on+// The env var has the highest precedence and can only force "off"; it never+// re-enables a config opt-out.+function effectiveTelemetryChoice(configDir, pluginName, env = process.env) {+ if (readTelemetryEnvOptOut(pluginName, env)) return "off";+ return readTelemetryChoice(configDir, pluginName) ?? null;+}++function isTransmissionOptedOut(configDir, pluginName, env = process.env) {+ return effectiveTelemetryChoice(configDir, pluginName, env) === "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);+ // `telemetry` itself can also be malformed, e.g. `"telemetry": []`. Assigning+ // `cfg.telemetry[pluginName]` on an array creates a non-index property that+ // JSON.stringify drops, so normalize any non-plain telemetry value before write.+ if (!isPlainObject(cfg.telemetry)) 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,+ telemetryOptOutEnvVarName,+ readTelemetryEnvOptOut,+ effectiveTelemetryChoice,+ CONFIG_FILE_NAME,+};diff --git a/plugins/power-pages/skills/report-issue/report-issue-workflow.md b/plugins/power-pages/skills/report-issue/report-issue-workflow.mddeleted file mode 120000index 467fa9175..000000000--- a/plugins/power-pages/skills/report-issue/report-issue-workflow.md+++ /dev/null@@ -1 +0,0 @@-../../../../shared/skills/report-issue/report-issue-workflow.md\ No newline at end of filediff --git a/plugins/power-pages/skills/report-issue/report-issue-workflow.md b/plugins/power-pages/skills/report-issue/report-issue-workflow.mdnew file mode 100644index 000000000..20401ebb8--- /dev/null+++ b/plugins/power-pages/skills/report-issue/report-issue-workflow.md@@ -0,0 +1,230 @@+# Report Issue++File a bug report on the [power-platform-skills](https://github.com/microsoft/power-platform-skills) GitHub repository. This workflow gathers the required information, presents a full preview, and creates the issue on the user's behalf.++**Initial request:** $ARGUMENTS++> **WARNING:** Before proceeding, inform the user: "This will create an issue on the **public** GitHub repository [microsoft/power-platform-skills](https://github.com/microsoft/power-platform-skills). **Do not include any sensitive information** such as credentials, internal URLs, tenant IDs, customer data, or proprietary code in the bug report."++---++## Phase 1: Identify Plugin & Version++**Goal**: Determine which plugin the bug is for and its version.++**Actions**:++1. Create a task list with all 5 phases (see [Progress Tracking](#progress-tracking) table).+2. **Auto-detect the plugin name** from the current plugin context by reading `${PLUGIN_ROOT}/.plugin/plugin.json`. Extract the `name` field.+3. **Auto-detect the plugin version** from the same `plugin.json` — extract the `version` field.+4. If the plugin name or version cannot be determined, use `AskUserQuestion` to ask the user.++**Output**: Plugin name and version confirmed.++---++## Phase 2: Gather Bug Details++**Goal**: Collect all required and optional fields for the bug report.++**Actions**:++### 2.1 Check Arguments++If `$ARGUMENTS` contains a description of the bug, extract as much information as possible from it to pre-fill the fields below. Still confirm with the user.++### 2.2 Ask for Bug Details++Use `AskUserQuestion` to gather bug details. `AskUserQuestion` supports 1-4 questions per call, but each question requires 2-4 predefined options. Since bug report fields are free-text, use options as prompt hints and let the user type their actual response via "Other". Skip any field the user already provided in `$ARGUMENTS`.++**Call 1** — Skill and bug description (2 questions):++1. **"Which skill or command were you using?"** (header: "Skill") — Provide the plugin's known skills as options (e.g., `deploy-site`, `create-site`). This is optional — the user can skip it.+2. **"Please describe the bug clearly and concisely."** (header: "Bug") — Provide short prompt-hint options like "Skill failed with error", "Unexpected behavior", "Skill hangs or times out". The user will typically select "Other" to type their description.++**Call 2** — Repro steps and expected vs actual (3 questions):++1. **"What steps reproduce the bug?"** (header: "Repro steps") — Provide prompt-hint options like "Ran the skill with default settings", "Ran the skill with custom arguments". The user will typically select "Other" to type their steps.+2. **"What did you expect to happen?"** (header: "Expected") — Provide prompt-hint options like "Skill should have succeeded", "Different output expected". The user will typically select "Other" to type their answer.+3. **"What actually happened?"** (header: "Actual") — Provide prompt-hint options like "Got an error message", "Wrong output produced", "Skill hung or timed out". The user will typically select "Other" to type their answer.++**Call 3** — Environment details:++Use `AskUserQuestion` with a single question: **"We recommend including environment details (OS, Claude Code version, PAC CLI version) to help maintainers reproduce and debug the issue faster. Include them?"** (header: "Environment") — Options: "Yes, auto-collect them" (recommended), "No, skip".++- If **yes**: Auto-collect the following by running shell commands:+ - **OS**: Detect the user's OS name and version using an appropriate command for their platform.+ - **Claude Code version**: Run `claude --version`+ - **PAC CLI version**: Run `pac help` and extract the version from the output+ - Present the collected details to the user.+- If **no**: Skip environment fields.++**Call 4** — Logs:++Use `AskUserQuestion` with a single question: **"Do you want to include any relevant logs or error messages?"** (header: "Logs") — Options: "Yes, I'll paste them", "No, skip".++- If **yes**: Use `AskUserQuestion` to ask: **"Please paste any relevant logs or error messages."** (header: "Paste logs") — Provide prompt-hint options like "Error message from terminal", "Skill output log". The user will typically select "Other" to paste their content.+- If **no**: Skip this field.++**Output**: All bug report fields gathered.++---++## Phase 3: Preview Issue++**Goal**: Present the complete issue to the user for review before creating it.++**Actions**:++Remind the user: **"This issue will be created on the public GitHub repository. Please review and make sure it does not contain any sensitive information (credentials, internal URLs, tenant IDs, customer data, or proprietary code)."**++Format and display the full issue exactly as it will be filed:++```+===== ISSUE PREVIEW =====++Title: [Bug] <short summary>++Plugin: <plugin-name>+Plugin Version: <version>+Skill / Command: <skill or "N/A">++Bug Description:+<description>++Steps to Reproduce:+<steps>++Expected Behavior:+<expected>++Actual Behavior:+<actual>++Relevant Logs / Screenshots:+<logs or "None">++Environment:+<environment details or "None">++Labels: bug, <plugin-name>++---+🤖 This issue was created using the /report-issue skill.++===== END PREVIEW =====+```++Use `AskUserQuestion` to confirm:++> "Here's the issue that will be created. Would you like to proceed, or would you like to make any changes?"++- If the user wants changes, go back and update the relevant fields, then preview again.+- If the user approves, proceed to Phase 4.++**Output**: User-approved issue ready for creation.++---++## Phase 4: Create Issue++**Goal**: Create the GitHub issue using the `gh` CLI.++**Actions**:++1. Build the issue body from the gathered fields, matching the bug report template structure:++ ```+ ### Plugin++ <plugin-name>++ ### Plugin Version++ <version>++ ### Skill / Command++ <skill or empty>++ ### Bug Description++ <description>++ ### Steps to Reproduce++ <steps>++ ### Expected Behavior++ <expected>++ ### Actual Behavior++ <actual>++ ### Relevant Logs / Screenshots++ <logs or "None">++ ### Environment++ <environment details or "None">++ ---+ 🤖 *This issue was created using the `/report-issue` skill.*+ ```++2. Create the issue via `gh`:++ ```bash+ gh issue create --repo microsoft/power-platform-skills --title "[Bug] <short summary>" --label "bug" --label "<plugin-name>" --body "<body>"+ ```++ Use a HEREDOC for the body to preserve formatting.++3. Capture and display the issue URL to the user.++**Output**: Issue created, URL shared with user.++---++## Phase 5: Summarize++**Goal**: Confirm success and suggest next steps.++**Actions**:++1. Display the created issue URL.+2. Let the user know they can track the issue on GitHub.++**Output**: Issue URL and next steps presented.++---++## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase.+- **Always use AskUserQuestion** before collecting any environment information — never run commands to gather system details without explicit user consent.+- **Always preview the full issue** before creating it — the user must approve the content.+- **Use the `gh` CLI** to create the issue — confirm it is authenticated before attempting.++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Identify plugin and version | Identifying plugin | Auto-detect plugin name and version from plugin.json |+| Gather bug details | Gathering details | Collect bug description, repro steps, expected/actual behavior |+| Preview issue | Previewing issue | Show complete issue for user review and approval |+| Create issue | Creating issue | File the bug report on GitHub via gh CLI |+| Summarize | Summarizing | Confirm success and share issue URL |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`.++---++**Begin with Phase 1: Identify Plugin & Version**diff --git a/plugins/power-pages/skills/telemetry/telemetry-workflow.md b/plugins/power-pages/skills/telemetry/telemetry-workflow.mddeleted file mode 120000index 182d8d58a..000000000--- a/plugins/power-pages/skills/telemetry/telemetry-workflow.md+++ /dev/null@@ -1 +0,0 @@-../../../../shared/skills/telemetry/telemetry-workflow.md\ No newline at end of filediff --git a/plugins/power-pages/skills/telemetry/telemetry-workflow.md b/plugins/power-pages/skills/telemetry/telemetry-workflow.mdnew file mode 100644index 000000000..7fed7f370--- /dev/null+++ b/plugins/power-pages/skills/telemetry/telemetry-workflow.md@@ -0,0 +1,33 @@+# 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 "${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.**.+- `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.+- **Automation/CI** can disable telemetry by setting the opt-out env var+ `POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` (e.g.+ `POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT=1`) instead of running this+ command. Set it to `1` or `true` (the dotnet `*_TELEMETRY_OPTOUT` convention).+ `<PLUGIN>` is the plugin name uppercased with non-alphanumerics collapsed to `_`.+ This opt-out has the highest precedence — it overrides a saved choice from this+ command and even `on`. It suppresses transmission only, like `off`.diff --git a/scripts/validate-legacy-compatibility.js b/scripts/validate-legacy-compatibility.jsindex 5de949f86..ae1d9923f 100644--- a/scripts/validate-legacy-compatibility.js+++ b/scripts/validate-legacy-compatibility.js@@ -1,11 +1,10 @@#!/usr/bin/env node/**- * Validates that legacy .claude-plugin manifests mirror the Open Plugins- * metadata. Existing marketplace subscriptions still resolve the legacy paths- * during auto-update, so these files must stay in sync. Mirrors are committed- * files (not links), so this guard must pass whenever marketplace/plugin- * metadata changes.+ * Validates that the legacy .claude-plugin manifests mirror their Open Plugins+ * counterparts. Existing marketplace subscriptions still resolve the legacy paths+ * during auto-update, so these committed mirror files must stay semantically in+ * sync whenever marketplace/plugin metadata changes.*/const fs = require('fs');@@ -37,6 +36,60 @@ function assertJsonMirror(legacyPath, sourcePath) {assert.deepEqual(readJson(legacyPath), readJson(sourcePath));}+function assertMinimalMarketplaceEntry(plugin) {+ // Open Plugins marketplace entries only require `name` and `source`. Optional+ // fields like description/version/license/keywords are override fields, so keep+ // the marketplace as an index and let each plugin's `.plugin/plugin.json` remain+ // the single source of truth for display and update metadata.+ // See: https://open-plugins.com/plugin-builders/marketplace+ assert.deepEqual(Object.keys(plugin).sort(), ['name', 'source']);+ assert.equal(typeof plugin.name, 'string', 'name must be a string');+ assert.notEqual(plugin.name.trim(), '', 'name must not be empty');+ assert.equal(typeof plugin.source, 'string', 'source must be a string');+ assert.match(plugin.source, /^\.\//, 'source must start with ./');+}++function assertMinimalMarketplace(marketplace) {+ // Keep marketplace-level metadata here because it describes the collection, not+ // any individual plugin. Per-plugin optional fields still stay out of `plugins`+ // entries to avoid overriding the corresponding `.plugin/plugin.json` metadata.+ assert.deepEqual(Object.keys(marketplace).sort(), ['metadata', 'name', 'owner', 'plugins']);+ assert.equal(typeof marketplace.name, 'string', 'name must be a string');+ assert.notEqual(marketplace.name.trim(), '', 'name must not be empty');+ assert.equal(typeof marketplace.owner?.name, 'string', 'owner.name must be a string');+ assert.notEqual(marketplace.owner.name.trim(), '', 'owner.name must not be empty');+ assert.equal(typeof marketplace.metadata?.description, 'string', 'metadata.description must be a string');+ assert.notEqual(marketplace.metadata.description.trim(), '', 'metadata.description must not be empty');+ assert.equal(typeof marketplace.metadata?.pluginRoot, 'string', 'metadata.pluginRoot must be a string');+ assert.match(marketplace.metadata.pluginRoot, /^\./, 'metadata.pluginRoot must be relative');+ assert.ok(Array.isArray(marketplace.plugins), 'plugins must be an array');+ assert.ok(marketplace.plugins.length > 0, 'plugins must contain at least one entry');+}++function assertPluginMetadata(pluginName, manifest) {+ // Marketplace plugin entries intentionally omit these optional override fields.+ // Keep them in each plugin manifest instead so `plugin.json` remains the single+ // source of truth for display/update metadata.+ assert.equal(manifest.name, pluginName);+ assert.match(manifest.version, /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/, 'version must be semantic');+ assert.equal(typeof manifest.description, 'string', 'description must be a string');+ assert.notEqual(manifest.description.trim(), '', 'description must not be empty');+ assert.equal(typeof manifest.author?.name, 'string', 'author.name must be a string');+ assert.notEqual(manifest.author.name.trim(), '', 'author.name must not be empty');+ assert.equal(typeof manifest.homepage, 'string', 'homepage must be a string');+ assert.notEqual(manifest.homepage.trim(), '', 'homepage must not be empty');+ assert.equal(typeof manifest.repository, 'string', 'repository must be a string');+ assert.notEqual(manifest.repository.trim(), '', 'repository must not be empty');+ assert.equal(typeof manifest.license, 'string', 'license must be a string');+ assert.notEqual(manifest.license.trim(), '', 'license must not be empty');+ assert.ok(Array.isArray(manifest.keywords), 'keywords must be an array');+ assert.ok(manifest.keywords.length > 0, 'keywords must contain at least one entry');+ for (const [index, keyword] of manifest.keywords.entries()) {+ assert.equal(typeof keyword, 'string', `keywords[${index}] must be a string`);+ assert.notEqual(keyword.trim(), '', `keywords[${index}] must not be empty`);+ }+}+const errors = [];function check(label, fn) {@@ -62,6 +115,11 @@ if (errors.length === 0) {assert.equal(legacyMarketplace.name, openMarketplace.name);});+ check('marketplace shape', () => {+ assertMinimalMarketplace(openMarketplace);+ assertMinimalMarketplace(legacyMarketplace);+ });+for (const plugin of openMarketplace.plugins || []) {openPluginNames.add(plugin.name);const pluginDirectory = pluginDirectoryFromOpenEntry(openMarketplace, plugin);@@ -73,14 +131,13 @@ if (errors.length === 0) {const legacyPlugin = legacyPlugins.get(plugin.name);assert.ok(legacyPlugin, 'missing from .claude-plugin/marketplace.json');assert.equal(legacyPlugin.source, expectedLegacySource(pluginDirectory));- assert.equal(legacyPlugin.description, plugin.description);- assert.equal(legacyPlugin.category, 'development');- assert.deepEqual(legacyPlugin.tags || [], plugin.keywords || []);+ assertMinimalMarketplaceEntry(plugin);+ assertMinimalMarketplaceEntry(legacyPlugin);});- check(`${plugin.name} marketplace version`, () => {+ check(`${plugin.name} plugin manifest`, () => {const pluginManifest = readJson(openManifestPath);- assert.equal(plugin.version, pluginManifest.version);+ assertPluginMetadata(plugin.name, pluginManifest);});check(relativeLegacyManifestPath, () => {diff --git a/shared/telemetry/README.md b/shared/telemetry/README.mdindex 6f4640f03..65aa7f233 100644--- a/shared/telemetry/README.md+++ b/shared/telemetry/README.md@@ -1,8 +1,8 @@# 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.+Canonical source for 1DS telemetry used by plugins in this repo. Each adopting plugin keeps a physical copy of this library in its own tree at `plugins/<plugin>/scripts/lib/telemetry/lib`, so plugin-host installs and Windows checkouts never depend on symlink behavior.-`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.+`shared/telemetry/lib` is the canonical source. Per-plugin copies must be refreshed from it whenever the shared library changes. Each plugin keeps its own real `ikey.json` next to the copied library.Zero npm dependencies. Node stdlib only.@@ -140,29 +140,33 @@ shared/telemetry/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+### 1. Copy 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).+Copy `shared/telemetry/lib` into `plugins/<your-plugin>/scripts/lib/telemetry/lib`.-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):+Use a physical directory, not a Git symlink. Some Windows checkouts and plugin hosts materialize symlinks as plain link files, which makes hook-time `require()` calls fail before the dispatcher can write the local diagnostic log. Any recursive copy command is fine; examples:++```powershell+$target = "plugins/<your-plugin>/scripts/lib/telemetry/lib"+Remove-Item -LiteralPath $target -Recurse -Force -ErrorAction SilentlyContinue+Copy-Item -LiteralPath "shared/telemetry/lib" -Destination $target -Recurse -Force+``````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"+target="plugins/<your-plugin>/scripts/lib/telemetry/lib"+rm -rf "$target"+mkdir -p "$(dirname "$target")"+cp -R shared/telemetry/lib "$target"```-Now `scripts/lib/telemetry/lib` resolves to the shared library — there is no copy to keep in sync.+Now `scripts/lib/telemetry/lib` is self-contained inside the plugin directory. Commit the copied files together with any shared library change.### 2. Configure `ikey.json`-Create `plugins/<your-plugin>/scripts/lib/telemetry/ikey.json` — a **real file, not symlinked** (it carries this plugin's config, distinct from `shared/`'s placeholder).+Create `plugins/<your-plugin>/scripts/lib/telemetry/ikey.json` as a real file (it carries this plugin's config, distinct from `shared/`'s placeholder).**Tier 1 — one static key (no routing).** Create a flat-`plugins/<your-plugin>/scripts/lib/telemetry/ikey.json` (a real file, not symlinked):+`plugins/<your-plugin>/scripts/lib/telemetry/ikey.json`:```json{@@ -208,11 +212,11 @@ Then invoke one of your tracked skills with `disabled: true` and confirm via Cla## 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.+Edit `shared/telemetry/lib/` directly, then refresh each adopting plugin's copied `scripts/lib/telemetry/lib` directory from it in the same change.-Each plugin's `ikey.json` is a separate real file (not symlinked), so editing the shared library never touches a plugin's provisioned key.+Each plugin's `ikey.json` is separate, so refreshing the copied library must not overwrite 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.+If you change the wire-level shape (envelope, transport, allowlist), refresh every adopting plugin copy, bump as needed, and validate accordingly.## Strict allowlistdiff --git a/shared/telemetry/lib/emit-spawn.js b/shared/telemetry/lib/emit-spawn.jsindex 12123821d..0bd839d8a 100644--- a/shared/telemetry/lib/emit-spawn.js+++ b/shared/telemetry/lib/emit-spawn.js@@ -16,11 +16,11 @@ function fireAndForget(event, opts = {}) {const optOutVarName = pluginName ? telemetryOptOutEnvVarName(pluginName) : "";const optOutValue =optOutVarName && process.env[optOutVarName] ? process.env[optOutVarName] : "";- // Absolute path to the CALLING plugin's ikey.json. The dispatcher lives in- // shared/telemetry/lib (reached via the per-plugin symlink), so its own- // __dirname-based default would resolve to shared/'s placeholder, not the- // plugin's real config. Passing the path explicitly makes the dispatcher- // read the right file regardless of how lib/ is linked.+ // Absolute path to the CALLING plugin's ikey.json. Tests and shared-source+ // development can execute this module from shared/telemetry/lib, whose default+ // __dirname-based ikey path is the shared placeholder, not the plugin's real+ // config. Passing the path explicitly makes the dispatcher read the right file+ // regardless of whether this library is running from shared/ or a plugin copy.const ikeyJsonPath = opts.ikeyJsonPath || "";try {diff --git a/shared/telemetry/lib/telemetry-config.js b/shared/telemetry/lib/telemetry-config.jsindex 9977c3656..4d5ede265 100644--- a/shared/telemetry/lib/telemetry-config.js+++ b/shared/telemetry/lib/telemetry-config.js@@ -8,9 +8,10 @@ const { setTelemetryChoice, effectiveTelemetryChoice } = 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.";+ " operational fields like skill name, plugin version, OS/Node versions,\n" ++ " PAC CLI and agent versions, and Dataverse org/tenant IDs when available.\n" ++ " It never includes file paths, prompts, tool inputs, site names, URLs,\n" ++ " credentials, usernames, or hostnames.";function getArg(name) {const i = process.argv.indexOf(`--${name}`);diff --git a/shared/telemetry/lib/user-config.js b/shared/telemetry/lib/user-config.jsindex 42b9d29d5..ea0597f73 100644--- a/shared/telemetry/lib/user-config.js+++ b/shared/telemetry/lib/user-config.js@@ -9,6 +9,10 @@ function configPath(configDir) {return path.join(configDir, CONFIG_FILE_NAME);}+function isPlainObject(value) {+ return value && typeof value === "object" && !Array.isArray(value);+}+// Reads the whole config object; returns {} on any error (missing/corrupt).function readConfig(configDir) {try {@@ -16,7 +20,7 @@ function readConfig(configDir) {// 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 : {};+ return isPlainObject(parsed) ? parsed : {};} catch {return {};}@@ -26,7 +30,7 @@ function readConfig(configDir) {function readTelemetryChoice(configDir, pluginName) {if (!configDir || !pluginName) return null;const t = readConfig(configDir).telemetry;- if (!t || typeof t !== "object") return null;+ if (!isPlainObject(t)) return null;const v = t[pluginName];return v === "on" || v === "off" ? v : null;}@@ -78,7 +82,10 @@ function setTelemetryChoice(configDir, pluginName, choice) {return false;}const cfg = readConfig(configDir);- if (!cfg.telemetry || typeof cfg.telemetry !== "object") cfg.telemetry = {};+ // `telemetry` itself can also be malformed, e.g. `"telemetry": []`. Assigning+ // `cfg.telemetry[pluginName]` on an array creates a non-index property that+ // JSON.stringify drops, so normalize any non-plain telemetry value before write.+ if (!isPlainObject(cfg.telemetry)) cfg.telemetry = {};cfg.telemetry[pluginName] = choice;try {fs.writeFileSync(configPath(configDir), JSON.stringify(cfg, null, 2) + "\n", "utf8");diff --git a/shared/telemetry/tests/emit-spawn.test.js b/shared/telemetry/tests/emit-spawn.test.jsindex 99e3622c4..14e46622c 100644--- a/shared/telemetry/tests/emit-spawn.test.js+++ b/shared/telemetry/tests/emit-spawn.test.js@@ -76,11 +76,11 @@ test("dispatcher child receives the event and writes the probe", async () => {});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.+ // Regression guard: shared-source tests execute the dispatcher from+ // shared/telemetry/lib, so its __dirname default resolves to shared/'s+ // placeholder (disabled:true). 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");diff --git a/shared/telemetry/tests/user-config.test.js b/shared/telemetry/tests/user-config.test.jsindex 95ca5d6c2..ad7221898 100644--- a/shared/telemetry/tests/user-config.test.js+++ b/shared/telemetry/tests/user-config.test.js@@ -93,6 +93,23 @@ test("an array config.json is ignored — setTelemetryChoice still persists", ()assert.deepEqual(readRaw(dir), { telemetry: { "power-pages": "off" } });});+test("an array telemetry value is normalized before writing", () => {+ const dir = mkTmp();+ // JSON arrays accept arbitrary JS properties at runtime, but JSON.stringify+ // serializes only numeric indices. Without normalizing this nested value,+ // setTelemetryChoice would return true while persisting none of the choice.+ fs.writeFileSync(+ path.join(dir, CONFIG_FILE_NAME),+ JSON.stringify({ schemaVersion: 1, telemetry: [] })+ );+ assert.equal(readTelemetryChoice(dir, "power-pages"), null);+ assert.equal(setTelemetryChoice(dir, "power-pages", "off"), true);+ assert.deepEqual(readRaw(dir), {+ schemaVersion: 1,+ 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");