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
telemetry: per-plugin, per-session local diagnostic logs (#232)
amitjoshi438e83c98f9222a
diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex 38e728746..53bb6c115 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -527,9 +527,11 @@ inputs, site names, URLs, credentials, usernames, or hostnames.```When **off**, nothing leaves your machine. A local diagnostic copy of each event-is still written to `~/.power-platform-skills/events.jsonl` so you can see exactly-what would have been sent; delete it anytime. The setting is stored at-`~/.power-platform-skills/config.json`+is still written under+`~/.power-platform-skills/telemetry/power-pages/sessions/<sessionId>/events.jsonl`+so you can see exactly what would have been sent; delete it anytime. Run+`/power-pages:telemetry status` to see the logs directory and the most recent+session file. The setting is stored at `~/.power-platform-skills/config.json`(`{ "telemetry": { "power-pages": "off" } }`).For automation / CI, set the per-plugin opt-out environment variable instead of@@ -542,7 +544,7 @@ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT=1 # stop sending telemetrySet it to `1` or `true` (dotnet `*_TELEMETRY_OPTOUT` convention). This opt-out hasthe **highest precedence** — it overrides a saved `/power-pages:telemetry` choiceand even `/power-pages:telemetry on`. Like `off` from the command, it suppresses-transmission only — the local `events.jsonl` mirror is still written.+transmission only — the local per-session `events.jsonl` mirror is still written.## Licensediff --git a/plugins/power-pages/scripts/lib/telemetry/lib/local-log.js b/plugins/power-pages/scripts/lib/telemetry/lib/local-log.jsindex c5c27ba90..ed61032d4 100644--- a/plugins/power-pages/scripts/lib/telemetry/lib/local-log.js+++ b/plugins/power-pages/scripts/lib/telemetry/lib/local-log.js@@ -4,8 +4,36 @@ const fs = require("node:fs");const path = require("node:path");const LOG_FILE_NAME = "events.jsonl";-const ROTATE_BYTES = 10 * 1024 * 1024; // 10 MB+const ROTATE_BYTES = 10 * 1024 * 1024; // 10 MB per-session size safety cap+const MAX_LOG_AGE_DAYS = 14;+const MAX_LOG_AGE_MS = MAX_LOG_AGE_DAYS * 24 * 60 * 60 * 1000;+// pluginName and sessionId become DIRECTORY names, so each is reduced to one safe+// path segment — a malformed record must never write outside telemetry/. Reject+// "." / ".." outright, then collapse anything outside [A-Za-z0-9_-] to "_". Dots+// are excluded so "../evil" can't leave a ".." fragment (it becomes "___evil");+// an empty result falls back to the sentinel.+function sanitizeSegment(value, fallback) {+ if (typeof value !== "string") return fallback;+ if (value === "." || value === "..") return fallback;+ const cleaned = value.replace(/[^A-Za-z0-9_-]/g, "_");+ if (!cleaned) return fallback;+ return cleaned;+}++// <configDir>/telemetry/<plugin>/sessions — the directory that holds one+// subdirectory per session. Pure path helper, no I/O.+function pluginLogDir(configDir, pluginName) {+ const plugin = sanitizeSegment(pluginName, "unknown");+ return path.join(configDir, "telemetry", plugin, "sessions");+}++function sessionDir(configDir, pluginName, sessionId) {+ const session = sanitizeSegment(sessionId, "nosession");+ return path.join(pluginLogDir(configDir, pluginName), session);+}++// events.YYYYMMDDHHMMSS.old — UTC stamp so rolled files sort chronologically.function rotationName(now = new Date()) {const pad = (n) => String(n).padStart(2, "0");const stamp =@@ -18,6 +46,9 @@ function rotationName(now = new Date()) {return `events.${stamp}.old`;}+// Per-session size cap. A single session almost never reaches 10 MB; this is a+// safety valve against a pathological runaway session, not the primary+// retention mechanism (that is age-based pruning of whole session dirs).function rotateIfNeeded(dir, logFile) {try {const stat = fs.statSync(logFile);@@ -33,20 +64,107 @@ function rotateIfNeeded(dir, logFile) {}}-function appendLocal(event, { configDir } = {}) {+function appendLocal(record, { configDir } = {}) {if (!configDir) return;+ const data = (record && record.data) || {};+ // Deterministic path — derived purely from the record. No directory scan, so+ // the many short-lived dispatcher processes that may write the same session+ // concurrently cannot race on "find this session's file".+ const dir = sessionDir(configDir, data.pluginName, data.sessionId);+ let created;try {- fs.mkdirSync(configDir, { recursive: true });+ // mkdirSync(recursive) returns the first path it created, or undefined if the+ // dir already existed — a free "is this a brand-new session?" signal.+ created = fs.mkdirSync(dir, { recursive: true });} catch {return;}- const logFile = path.join(configDir, LOG_FILE_NAME);- rotateIfNeeded(configDir, logFile);+ const logFile = path.join(dir, LOG_FILE_NAME);+ rotateIfNeeded(dir, logFile);try {- fs.appendFileSync(logFile, JSON.stringify(event) + "\n", "utf8");+ fs.appendFileSync(logFile, JSON.stringify(record) + "\n", "utf8");} catch {- // swallow — fail closed+ // swallow — fail closed; telemetry must never break a skill run+ }+ // The retention sweep scans every session dir, so run it only on a session's+ // first event (when we just created its dir), not on every append.+ if (created) pruneOldSessions(configDir, data.pluginName);+}++// Best-effort age-based retention — the primary cleanup mechanism. Remove any+// session dir whose events.jsonl was last written more than MAX_LOG_AGE_DAYS ago;+// a dir with no readable log is judged by its OWN mtime, so a just-created dir from+// a concurrent dispatcher isn't deleted out from under it. Never throws.+function pruneOldSessions(configDir, pluginName, now = Date.now()) {+ if (!configDir) return; // fail closed: pluginLogDir -> path.join would throw on undefined+ const sessionsRoot = pluginLogDir(configDir, pluginName);+ let entries;+ try {+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });+ } catch {+ return; // no sessions dir yet — nothing to prune+ }+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const dir = path.join(sessionsRoot, entry.name);+ try {+ let mtimeMs;+ try {+ mtimeMs = fs.statSync(path.join(dir, LOG_FILE_NAME)).mtimeMs;+ } catch {+ // No readable log file — fall back to the directory's own mtime.+ mtimeMs = fs.statSync(dir).mtimeMs;+ }+ if (now - mtimeMs > MAX_LOG_AGE_MS) {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ } catch {+ // best effort per dir; skip on any error+ }+ }+}++// Absolute path to the most-recently-written session's events.jsonl for a plugin,+// or null when there are none ("most recent" = highest events.jsonl mtime). Dirs+// without a readable events.jsonl are skipped so the returned path always exists —+// status surfaces it for the user to share, and a phantom path would point them at+// a file that isn't there. Read-only.+function latestSessionLog(configDir, pluginName) {+ if (!configDir) return null; // fail closed: pluginLogDir -> path.join would throw on undefined+ const sessionsRoot = pluginLogDir(configDir, pluginName);+ let entries;+ try {+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });+ } catch {+ return null;+ }+ let best = null;+ let bestMtime = -Infinity;+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const logFile = path.join(sessionsRoot, entry.name, LOG_FILE_NAME);+ let mtimeMs;+ try {+ // Skip dirs without a readable events.jsonl so `best` can't point at a missing file.+ mtimeMs = fs.statSync(logFile).mtimeMs;+ } catch {+ continue;+ }+ if (mtimeMs > bestMtime) {+ bestMtime = mtimeMs;+ best = logFile;+ }}+ return best;}-module.exports = { appendLocal, LOG_FILE_NAME, ROTATE_BYTES };+module.exports = {+ appendLocal,+ pluginLogDir,+ latestSessionLog,+ pruneOldSessions,+ sanitizeSegment,+ LOG_FILE_NAME,+ ROTATE_BYTES,+ MAX_LOG_AGE_DAYS,+};diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.jsindex 4d5ede265..7dbe62041 100644--- a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js+++ b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js@@ -5,6 +5,7 @@ const fs = require("node:fs");const os = require("node:os");const path = require("node:path");const { setTelemetryChoice, effectiveTelemetryChoice } = require("./user-config");+const { pluginLogDir, latestSessionLog } = require("./local-log");const ANONYMITY ="ℹ️ No personal data is collected. Telemetry is anonymous — it records only\n" +@@ -25,10 +26,6 @@ function configDir() {);}-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() {@@ -49,6 +46,21 @@ function out(s) {process.stdout.write(s + "\n");}+// Print where this plugin's local diagnostic logs live and name the newest+// session file, so a user can hand over exactly the log for the session they+// just hit a problem in. Reuses the shared layout helpers (DRY — no path logic+// is duplicated in the skill).+function emitLogLocations(dir, plugin) {+ out(`Logs directory: ${pluginLogDir(dir, plugin)}`);+ const latest = latestSessionLog(dir, plugin);+ if (latest) {+ out(`Most recent session: ${latest}`);+ out("ℹ️ Share that file when reporting an issue (it covers your latest session).");+ } else {+ out(`No local logs yet for ${plugin}.`);+ }+}+function main() {const action = getArg("action");const plugin = resolvePlugin();@@ -63,10 +75,11 @@ function main() {if (on) {out(`Telemetry (${plugin}): ON`);out(ANONYMITY);- out(`Local log: ${logPath()}`);+ emitLogLocations(dir, plugin);} else {out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);- out(`A local diagnostic log is still kept at ${logPath()}.`);+ out(`A local diagnostic log is still kept.`);+ emitLogLocations(dir, plugin);out(`Re-enable anytime with /${plugin}:telemetry on.`);out(ANONYMITY);}@@ -79,7 +92,8 @@ function main() {}if (action === "off") {out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);- out(`A local diagnostic log is still kept at ${logPath()}.`);+ out(`A local diagnostic log is still kept.`);+ emitLogLocations(dir, plugin);out(`Re-enable anytime with /${plugin}:telemetry on.`);} else {out(`Telemetry (${plugin}): ON`);diff --git a/shared/telemetry/README.md b/shared/telemetry/README.mdindex 1acda0f14..e19f0e3ef 100644--- a/shared/telemetry/README.md+++ b/shared/telemetry/README.md@@ -21,7 +21,7 @@ hook (~5ms when disabled, ~3-5s otherwise — incl. when the user opted out)├─ read ikey.json (null/unreadable → HARD OFF)├─ kill switch (cfg.disabled) → exit ← HARD OFF: no local log, no POST├─ sanitizeData (FIELD_TYPES allowlist)- ├─ appendLocal({time,name,data}) → events.jsonl ← ALWAYS (the mirror)+ ├─ appendLocal({time,name,data}) → telemetry/<plugin>/sessions/<sessionId>/events.jsonl ← ALWAYS (the mirror)├─ user opt-out (env var POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT=1 OR config.json choice "off"; env wins) → exit (mirror written, no POST)├─ resolve destination → iKey + collector_url ← resolver.js (plugin) or static key├─ iKey missing/placeholder → exit (mirror already written, no POST)@@ -39,8 +39,14 @@ side effects.The per-plugin user opt-out (`config.json` `telemetry[<plugin>] === "off"`, setvia `/<plugin>:telemetry off`) suppresses **transmission**, not the local-diagnostic mirror — so an opted-out run still writes `events.jsonl` (and pays the-same event-building cost as an enabled run), it just never POSTs.+diagnostic mirror — so an opted-out run still writes the session's `events.jsonl`+(and pays the same event-building cost as an enabled run), it just never POSTs.++The mirror is laid out per-plugin, per-session at+`~/.power-platform-skills/telemetry/<pluginName>/sessions/<sessionId>/events.jsonl`,+so a user can hand over one self-contained file per problem. Session directories+older than 14 days are pruned best-effort whenever a new session starts, and an+individual session log is rotated to `events.<stamp>.old` if it ever exceeds 10 MB.### Custom routing (the resolver contract)@@ -97,7 +103,7 @@ The dispatcher runs a defense-in-depth allowlist filter against `FIELD_TYPES` be## Privacy posture- **Default-on.** Anonymous telemetry is enabled by default. No first-run prompt.-- **Opt out of transmission** via `/<plugin>:telemetry off` (per-user, per-plugin). This writes `telemetry[<plugin>] = "off"` into `~/.power-platform-skills/config.json` and stops the network POST to the collector — **nothing leaves the machine** — but the local diagnostic mirror (`events.jsonl`) is still written so the user/developer can see exactly what would have been sent. It is therefore an opt-out of *transmission*, not of local logging. CI/headless can opt out by writing that file directly. Re-enable with `/<plugin>:telemetry on`.+- **Opt out of transmission** via `/<plugin>:telemetry off` (per-user, per-plugin). This writes `telemetry[<plugin>] = "off"` into `~/.power-platform-skills/config.json` and stops the network POST to the collector — **nothing leaves the machine** — but the local diagnostic mirror (a per-session `events.jsonl`) is still written so the user/developer can see exactly what would have been sent. It is therefore an opt-out of *transmission*, not of local logging. CI/headless can opt out by writing that file directly. Re-enable with `/<plugin>:telemetry on`.- **Opt out for automation** via the per-plugin opt-out env var`POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` (e.g.`POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT=1`). Set it to `1` or `true`@@ -108,7 +114,7 @@ The dispatcher runs a defense-in-depth allowlist filter against `FIELD_TYPES` besuppresses transmission only — the local mirror is still written.- **Repo-side kill switch (true hard-off).** `ikey.json` carries a `disabled` flag. When `true` (or when `ikey.json` is missing/unreadable), every entry point — hooks, `emit-from-prompt`, and the dispatcher — short-circuits BEFORE any PAC shellout or process spawn, so there is **no POST and no local log**. Ship `true` and flip to `false` only after the tenant-side Kusto stream and annotation are provisioned.-The `disabled` flag is checked at every layer that could perform user-facing work: the pretool/posttool hooks and `emit-from-prompt.js`. A disabled plugin emits zero side effects. The per-plugin user opt-out, by contrast, is enforced inside the detached dispatcher AFTER the local mirror is written — so an opted-out run still produces `events.jsonl` (and incurs the same event-building cost as an enabled run) but never transmits.+The `disabled` flag is checked at every layer that could perform user-facing work: the pretool/posttool hooks and `emit-from-prompt.js`. A disabled plugin emits zero side effects. The per-plugin user opt-out, by contrast, is enforced inside the detached dispatcher AFTER the local mirror is written — so an opted-out run still produces the session's `events.jsonl` (and incurs the same event-building cost as an enabled run) but never transmits.---@@ -130,7 +136,7 @@ shared/telemetry/│ ├─ session.js # per-process session UUID│ ├─ prompt-detector.js # parses `/plugin:skill` slash commands from prompt text│ ├─ scrubber.js # legacy text-scrubbing helper (unused by default — kept for callers that need it)-│ └─ local-log.js # appends every emitted event to ~/.power-platform-skills/events.jsonl (irrespective of iKey), with 10 MB rotation+│ └─ local-log.js # appends every emitted event to ~/.power-platform-skills/telemetry/<plugin>/sessions/<sessionId>/events.jsonl (irrespective of iKey), with 14-day session retention and a 10 MB per-session rollover└─ tests/ # node:test coverage for every module above```diff --git a/shared/telemetry/lib/local-log.js b/shared/telemetry/lib/local-log.jsindex c5c27ba90..ed61032d4 100644--- a/shared/telemetry/lib/local-log.js+++ b/shared/telemetry/lib/local-log.js@@ -4,8 +4,36 @@ const fs = require("node:fs");const path = require("node:path");const LOG_FILE_NAME = "events.jsonl";-const ROTATE_BYTES = 10 * 1024 * 1024; // 10 MB+const ROTATE_BYTES = 10 * 1024 * 1024; // 10 MB per-session size safety cap+const MAX_LOG_AGE_DAYS = 14;+const MAX_LOG_AGE_MS = MAX_LOG_AGE_DAYS * 24 * 60 * 60 * 1000;+// pluginName and sessionId become DIRECTORY names, so each is reduced to one safe+// path segment — a malformed record must never write outside telemetry/. Reject+// "." / ".." outright, then collapse anything outside [A-Za-z0-9_-] to "_". Dots+// are excluded so "../evil" can't leave a ".." fragment (it becomes "___evil");+// an empty result falls back to the sentinel.+function sanitizeSegment(value, fallback) {+ if (typeof value !== "string") return fallback;+ if (value === "." || value === "..") return fallback;+ const cleaned = value.replace(/[^A-Za-z0-9_-]/g, "_");+ if (!cleaned) return fallback;+ return cleaned;+}++// <configDir>/telemetry/<plugin>/sessions — the directory that holds one+// subdirectory per session. Pure path helper, no I/O.+function pluginLogDir(configDir, pluginName) {+ const plugin = sanitizeSegment(pluginName, "unknown");+ return path.join(configDir, "telemetry", plugin, "sessions");+}++function sessionDir(configDir, pluginName, sessionId) {+ const session = sanitizeSegment(sessionId, "nosession");+ return path.join(pluginLogDir(configDir, pluginName), session);+}++// events.YYYYMMDDHHMMSS.old — UTC stamp so rolled files sort chronologically.function rotationName(now = new Date()) {const pad = (n) => String(n).padStart(2, "0");const stamp =@@ -18,6 +46,9 @@ function rotationName(now = new Date()) {return `events.${stamp}.old`;}+// Per-session size cap. A single session almost never reaches 10 MB; this is a+// safety valve against a pathological runaway session, not the primary+// retention mechanism (that is age-based pruning of whole session dirs).function rotateIfNeeded(dir, logFile) {try {const stat = fs.statSync(logFile);@@ -33,20 +64,107 @@ function rotateIfNeeded(dir, logFile) {}}-function appendLocal(event, { configDir } = {}) {+function appendLocal(record, { configDir } = {}) {if (!configDir) return;+ const data = (record && record.data) || {};+ // Deterministic path — derived purely from the record. No directory scan, so+ // the many short-lived dispatcher processes that may write the same session+ // concurrently cannot race on "find this session's file".+ const dir = sessionDir(configDir, data.pluginName, data.sessionId);+ let created;try {- fs.mkdirSync(configDir, { recursive: true });+ // mkdirSync(recursive) returns the first path it created, or undefined if the+ // dir already existed — a free "is this a brand-new session?" signal.+ created = fs.mkdirSync(dir, { recursive: true });} catch {return;}- const logFile = path.join(configDir, LOG_FILE_NAME);- rotateIfNeeded(configDir, logFile);+ const logFile = path.join(dir, LOG_FILE_NAME);+ rotateIfNeeded(dir, logFile);try {- fs.appendFileSync(logFile, JSON.stringify(event) + "\n", "utf8");+ fs.appendFileSync(logFile, JSON.stringify(record) + "\n", "utf8");} catch {- // swallow — fail closed+ // swallow — fail closed; telemetry must never break a skill run+ }+ // The retention sweep scans every session dir, so run it only on a session's+ // first event (when we just created its dir), not on every append.+ if (created) pruneOldSessions(configDir, data.pluginName);+}++// Best-effort age-based retention — the primary cleanup mechanism. Remove any+// session dir whose events.jsonl was last written more than MAX_LOG_AGE_DAYS ago;+// a dir with no readable log is judged by its OWN mtime, so a just-created dir from+// a concurrent dispatcher isn't deleted out from under it. Never throws.+function pruneOldSessions(configDir, pluginName, now = Date.now()) {+ if (!configDir) return; // fail closed: pluginLogDir -> path.join would throw on undefined+ const sessionsRoot = pluginLogDir(configDir, pluginName);+ let entries;+ try {+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });+ } catch {+ return; // no sessions dir yet — nothing to prune+ }+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const dir = path.join(sessionsRoot, entry.name);+ try {+ let mtimeMs;+ try {+ mtimeMs = fs.statSync(path.join(dir, LOG_FILE_NAME)).mtimeMs;+ } catch {+ // No readable log file — fall back to the directory's own mtime.+ mtimeMs = fs.statSync(dir).mtimeMs;+ }+ if (now - mtimeMs > MAX_LOG_AGE_MS) {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ } catch {+ // best effort per dir; skip on any error+ }+ }+}++// Absolute path to the most-recently-written session's events.jsonl for a plugin,+// or null when there are none ("most recent" = highest events.jsonl mtime). Dirs+// without a readable events.jsonl are skipped so the returned path always exists —+// status surfaces it for the user to share, and a phantom path would point them at+// a file that isn't there. Read-only.+function latestSessionLog(configDir, pluginName) {+ if (!configDir) return null; // fail closed: pluginLogDir -> path.join would throw on undefined+ const sessionsRoot = pluginLogDir(configDir, pluginName);+ let entries;+ try {+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });+ } catch {+ return null;+ }+ let best = null;+ let bestMtime = -Infinity;+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const logFile = path.join(sessionsRoot, entry.name, LOG_FILE_NAME);+ let mtimeMs;+ try {+ // Skip dirs without a readable events.jsonl so `best` can't point at a missing file.+ mtimeMs = fs.statSync(logFile).mtimeMs;+ } catch {+ continue;+ }+ if (mtimeMs > bestMtime) {+ bestMtime = mtimeMs;+ best = logFile;+ }}+ return best;}-module.exports = { appendLocal, LOG_FILE_NAME, ROTATE_BYTES };+module.exports = {+ appendLocal,+ pluginLogDir,+ latestSessionLog,+ pruneOldSessions,+ sanitizeSegment,+ LOG_FILE_NAME,+ ROTATE_BYTES,+ MAX_LOG_AGE_DAYS,+};diff --git a/shared/telemetry/lib/telemetry-config.js b/shared/telemetry/lib/telemetry-config.jsindex 4d5ede265..7dbe62041 100644--- a/shared/telemetry/lib/telemetry-config.js+++ b/shared/telemetry/lib/telemetry-config.js@@ -5,6 +5,7 @@ const fs = require("node:fs");const os = require("node:os");const path = require("node:path");const { setTelemetryChoice, effectiveTelemetryChoice } = require("./user-config");+const { pluginLogDir, latestSessionLog } = require("./local-log");const ANONYMITY ="ℹ️ No personal data is collected. Telemetry is anonymous — it records only\n" +@@ -25,10 +26,6 @@ function configDir() {);}-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() {@@ -49,6 +46,21 @@ function out(s) {process.stdout.write(s + "\n");}+// Print where this plugin's local diagnostic logs live and name the newest+// session file, so a user can hand over exactly the log for the session they+// just hit a problem in. Reuses the shared layout helpers (DRY — no path logic+// is duplicated in the skill).+function emitLogLocations(dir, plugin) {+ out(`Logs directory: ${pluginLogDir(dir, plugin)}`);+ const latest = latestSessionLog(dir, plugin);+ if (latest) {+ out(`Most recent session: ${latest}`);+ out("ℹ️ Share that file when reporting an issue (it covers your latest session).");+ } else {+ out(`No local logs yet for ${plugin}.`);+ }+}+function main() {const action = getArg("action");const plugin = resolvePlugin();@@ -63,10 +75,11 @@ function main() {if (on) {out(`Telemetry (${plugin}): ON`);out(ANONYMITY);- out(`Local log: ${logPath()}`);+ emitLogLocations(dir, plugin);} else {out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);- out(`A local diagnostic log is still kept at ${logPath()}.`);+ out(`A local diagnostic log is still kept.`);+ emitLogLocations(dir, plugin);out(`Re-enable anytime with /${plugin}:telemetry on.`);out(ANONYMITY);}@@ -79,7 +92,8 @@ function main() {}if (action === "off") {out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);- out(`A local diagnostic log is still kept at ${logPath()}.`);+ out(`A local diagnostic log is still kept.`);+ emitLogLocations(dir, plugin);out(`Re-enable anytime with /${plugin}:telemetry on.`);} else {out(`Telemetry (${plugin}): ON`);diff --git a/shared/telemetry/tests/emit-dispatcher.test.js b/shared/telemetry/tests/emit-dispatcher.test.jsindex f3ec3e558..41d19ad1a 100644--- a/shared/telemetry/tests/emit-dispatcher.test.js+++ b/shared/telemetry/tests/emit-dispatcher.test.js@@ -13,6 +13,12 @@ function mkTmp() {return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-disp-"));}+// Local-mirror path for fakeEvent under the per-session layout. fakeEvent has+// pluginName "power-pages" and NO sessionId, so it falls back to "nosession".+function mirrorPath(tmp) {+ return path.join(tmp, "telemetry", "power-pages", "sessions", "nosession", "events.jsonl");+}+// Writes an ikey.json with `disabled: false` so the dispatcher's kill-switch// gate doesn't block emission-path tests. Returns its path.function mkEnabledIkey(tmp) {@@ -185,9 +191,9 @@ test("dispatcher stringifies eventInfo on the wire but keeps it an object in the);assert.deepEqual(JSON.parse(body.data.eventInfo), eventWithInfo.data.eventInfo);- const mirrorPath = path.join(tmp, "events.jsonl");+ const mirror = mirrorPath(tmp);const mirrorLine = fs- .readFileSync(mirrorPath, "utf8")+ .readFileSync(mirror, "utf8").trim().split("\n").pop();@@ -267,7 +273,7 @@ test("dispatcher appends to events.jsonl when iKey is placeholder", () => {},});assert.equal(status, 0);- const logFile = path.join(tmp, "events.jsonl");+ const logFile = mirrorPath(tmp);assert.ok(fs.existsSync(logFile), "expected events.jsonl to be written");const lines = fs.readFileSync(logFile, "utf8").trim().split("\n");assert.equal(lines.length, 1);@@ -293,7 +299,7 @@ test("dispatcher ALSO appends to events.jsonl when a real iKey POSTs (irrespecti});assert.equal(status, 0);assert.ok(fs.existsSync(probePath), "real iKey must still POST");- const logFile = path.join(tmp, "events.jsonl");+ const logFile = mirrorPath(tmp);assert.ok(fs.existsSync(logFile),"real iKey must ALSO write the local log"@@ -334,7 +340,7 @@ test("dispatcher honours the repo kill switch (ikey.json disabled:true)", () =>assert.equal(status, 0);assert.ok(!fs.existsSync(probePath), "kill switch must skip POST");assert.ok(- !fs.existsSync(path.join(tmp, "events.jsonl")),+ !fs.existsSync(path.join(tmp, "telemetry")),"kill switch must skip local log");});@@ -357,7 +363,7 @@ test("dispatcher fails closed when ikey.json is missing/unreadable", () => {assert.equal(status, 0);assert.ok(!fs.existsSync(probePath), "missing config must skip POST");assert.ok(- !fs.existsSync(path.join(tmp, "events.jsonl")),+ !fs.existsSync(path.join(tmp, "telemetry")),"missing config must skip local log");});@@ -380,7 +386,7 @@ test("dispatcher writes the local mirror when opted out via config, but does NOT});assert.equal(status, 0);assert.ok(!fs.existsSync(probePath), "config opt-out must skip the POST");- const logFile = path.join(tmp, "events.jsonl");+ const logFile = mirrorPath(tmp);assert.ok(fs.existsSync(logFile),"config opt-out must still write the local mirror"@@ -432,7 +438,7 @@ test("local mirror records the same data + time that gets POSTed to Kusto", () =assert.equal(status, 0);const wire = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);const local = JSON.parse(- fs.readFileSync(path.join(tmp, "events.jsonl"), "utf8").trim()+ fs.readFileSync(mirrorPath(tmp), "utf8").trim());assert.equal(local.name, wire.name);assert.equal(local.time, wire.time);@@ -545,7 +551,7 @@ test("dispatcher writes the mirror but does NOT POST when neither resolver nor s});assert.equal(status, 0);assert.ok(!fs.existsSync(probePath), "no key resolved → no POST");- assert.ok(fs.existsSync(path.join(tmp, "events.jsonl")), "local mirror still written");+ assert.ok(fs.existsSync(mirrorPath(tmp)), "local mirror still written");});test("env opt-out (no config choice) suppresses the POST but still writes the mirror", () => {@@ -564,7 +570,7 @@ test("env opt-out (no config choice) suppresses the POST but still writes the miassert.equal(status, 0);assert.ok(!fs.existsSync(probePath), "env opt-out must skip the POST");assert.ok(- fs.existsSync(path.join(tmp, "events.jsonl")),+ fs.existsSync(mirrorPath(tmp)),"env opt-out must still write the local mirror");});@@ -592,7 +598,7 @@ test("env opt-out overrides a persisted 'on' choice (env wins) — no POST", ()"env opt-out has highest precedence → must skip the POST even with config 'on'");assert.ok(- fs.existsSync(path.join(tmp, "events.jsonl")),+ fs.existsSync(mirrorPath(tmp)),"opt-out suppresses transmission only — the local mirror is still written");});diff --git a/shared/telemetry/tests/emit-spawn.test.js b/shared/telemetry/tests/emit-spawn.test.jsindex 14e46622c..385b60d69 100644--- a/shared/telemetry/tests/emit-spawn.test.js+++ b/shared/telemetry/tests/emit-spawn.test.js@@ -166,7 +166,9 @@ test("env-var opt-out suppresses the POST through the real spawn chain (mirror s// The local mirror is written BEFORE the opt-out gate, so wait on it to know// the detached child actually ran and reached the gate (rather than asserting// absence against a child that simply hadn't started yet).- const mirror = path.join(tmp, "events.jsonl");+ // The event carries pluginName "power-pages" and no sessionId, so the local+ // mirror lands under the per-session layout at the "nosession" fallback.+ const mirror = path.join(tmp, "telemetry", "power-pages", "sessions", "nosession", "events.jsonl");for (let i = 0; i < 30; i++) {if (fs.existsSync(mirror)) break;await new Promise((r) => setTimeout(r, 100));diff --git a/shared/telemetry/tests/local-log.test.js b/shared/telemetry/tests/local-log.test.jsindex e722efdf0..0a5638728 100644--- a/shared/telemetry/tests/local-log.test.js+++ b/shared/telemetry/tests/local-log.test.js@@ -6,24 +6,43 @@ const fs = require("node:fs");const os = require("node:os");const path = require("node:path");-const { appendLocal, LOG_FILE_NAME, ROTATE_BYTES } = require("../lib/local-log");+const {+ appendLocal,+ pluginLogDir,+ latestSessionLog,+ pruneOldSessions,+ sanitizeSegment,+ LOG_FILE_NAME,+ ROTATE_BYTES,+ MAX_LOG_AGE_DAYS,+} = require("../lib/local-log");function mkTmp() {return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-local-log-"));}-test("exports the log filename and rotate threshold", () => {+// Path where an event for (plugin, session) should land under the new layout.+function sessionLog(root, plugin, session) {+ return path.join(root, "telemetry", plugin, "sessions", session, LOG_FILE_NAME);+}++test("exports filename, rotate threshold, and retention window", () => {assert.equal(LOG_FILE_NAME, "events.jsonl");assert.equal(typeof ROTATE_BYTES, "number");assert.ok(ROTATE_BYTES >= 1024 * 1024);+ assert.equal(MAX_LOG_AGE_DAYS, 14);});-test("appendLocal creates the configDir and writes one JSON line", () => {- const tmp = mkTmp();- const nested = path.join(tmp, "sub", "dir"); // doesn't exist yet- appendLocal({ name: "X", data: { eventName: "hello" } }, { configDir: nested });- const logFile = path.join(nested, LOG_FILE_NAME);- assert.ok(fs.existsSync(logFile));+test("appendLocal writes to telemetry/<plugin>/sessions/<session>/events.jsonl", () => {+ const root = mkTmp();+ const record = {+ name: "X",+ data: { eventName: "hello", pluginName: "power-pages", sessionId: "sess-1" },+ };+ appendLocal(record, { configDir: root });++ const logFile = sessionLog(root, "power-pages", "sess-1");+ assert.ok(fs.existsSync(logFile), "expected per-session events.jsonl");const lines = fs.readFileSync(logFile, "utf8").trim().split("\n");assert.equal(lines.length, 1);const parsed = JSON.parse(lines[0]);@@ -31,32 +50,93 @@ test("appendLocal creates the configDir and writes one JSON line", () => {assert.equal(parsed.data.eventName, "hello");});-test("appendLocal appends multiple events on subsequent calls", () => {- const tmp = mkTmp();- appendLocal({ name: "A", data: {} }, { configDir: tmp });- appendLocal({ name: "B", data: {} }, { configDir: tmp });- appendLocal({ name: "C", data: {} }, { configDir: tmp });- const contents = fs.readFileSync(path.join(tmp, LOG_FILE_NAME), "utf8");- const names = contents- .trim()- .split("\n")- .map((l) => JSON.parse(l).name);+test("appendLocal appends multiple events for the same session in order", () => {+ const root = mkTmp();+ const base = { pluginName: "power-pages", sessionId: "sess-1" };+ appendLocal({ name: "A", data: { ...base } }, { configDir: root });+ appendLocal({ name: "B", data: { ...base } }, { configDir: root });+ appendLocal({ name: "C", data: { ...base } }, { configDir: root });++ const contents = fs.readFileSync(sessionLog(root, "power-pages", "sess-1"), "utf8");+ const names = contents.trim().split("\n").map((l) => JSON.parse(l).name);assert.deepEqual(names, ["A", "B", "C"]);});-test("appendLocal rotates when file exceeds ROTATE_BYTES", () => {- const tmp = mkTmp();- const logFile = path.join(tmp, LOG_FILE_NAME);- // Pre-fill log with > ROTATE_BYTES of data+test("different sessions and plugins land in distinct directories", () => {+ const root = mkTmp();+ appendLocal({ name: "A", data: { pluginName: "power-pages", sessionId: "s1" } }, { configDir: root });+ appendLocal({ name: "B", data: { pluginName: "power-pages", sessionId: "s2" } }, { configDir: root });+ appendLocal({ name: "C", data: { pluginName: "model-apps", sessionId: "s1" } }, { configDir: root });++ assert.ok(fs.existsSync(sessionLog(root, "power-pages", "s1")));+ assert.ok(fs.existsSync(sessionLog(root, "power-pages", "s2")));+ assert.ok(fs.existsSync(sessionLog(root, "model-apps", "s1")));+});++test("missing pluginName/sessionId fall back to unknown/nosession", () => {+ const root = mkTmp();+ appendLocal({ name: "A", data: { eventName: "x" } }, { configDir: root });+ assert.ok(fs.existsSync(sessionLog(root, "unknown", "nosession")));+});++test("filesystem-unsafe plugin/session are sanitized to one safe segment", () => {+ const root = mkTmp();+ appendLocal(+ { name: "A", data: { pluginName: "../evil", sessionId: "a/b c" } },+ { configDir: root }+ );+ // "../evil" -> "___evil" (each of ".", ".", "/" collapses to "_"); "a/b c"+ // -> "a_b_c" — the point is that nothing escapes outside telemetry/.+ assert.ok(fs.existsSync(sessionLog(root, "___evil", "a_b_c")));+ // nothing was written outside the telemetry tree+ assert.ok(!fs.existsSync(path.join(root, "evil")));+});++test("sanitizeSegment collapses unsafe chars and rejects dot segments", () => {+ assert.equal(sanitizeSegment("power-pages", "fb"), "power-pages");+ assert.equal(sanitizeSegment("a/b", "fb"), "a_b");+ assert.equal(sanitizeSegment("..", "fb"), "fb");+ assert.equal(sanitizeSegment(".", "fb"), "fb");+ assert.equal(sanitizeSegment("", "fb"), "fb");+ assert.equal(sanitizeSegment(undefined, "fb"), "fb");+});++test("appendLocal never throws when the target is not writable", () => {+ const root = mkTmp();+ // A file where the plugin directory needs to be — mkdir of a subpath fails.+ fs.mkdirSync(path.join(root, "telemetry"), { recursive: true });+ fs.writeFileSync(path.join(root, "telemetry", "power-pages"), "i am a file");+ appendLocal(+ { name: "X", data: { pluginName: "power-pages", sessionId: "s1" } },+ { configDir: root }+ );+});++test("appendLocal is a no-op when configDir is missing", () => {+ // Must not throw; nothing to assert beyond that.+ appendLocal({ name: "X", data: { pluginName: "p", sessionId: "s" } }, {});+});++test("appendLocal rotates a session log that exceeds ROTATE_BYTES", () => {+ const root = mkTmp();+ const dir = path.join(root, "telemetry", "power-pages", "sessions", "s1");+ fs.mkdirSync(dir, { recursive: true });+ const logFile = path.join(dir, LOG_FILE_NAME);++ // Pre-fill the session log with > ROTATE_BYTES of data.const filler = "x".repeat(1024);const lines = Math.ceil(ROTATE_BYTES / filler.length) + 1;fs.writeFileSync(logFile, Array(lines).fill(filler).join("\n") + "\n");assert.ok(fs.statSync(logFile).size > ROTATE_BYTES);- appendLocal({ name: "AFTER-ROTATE", data: {} }, { configDir: tmp });+ appendLocal(+ { name: "AFTER-ROTATE", data: { pluginName: "power-pages", sessionId: "s1" } },+ { configDir: root }+ );+ // The oversized file was renamed to events.<stamp>.old in the SAME session dir.const olds = fs- .readdirSync(tmp)+ .readdirSync(dir).filter((f) => f.startsWith("events.") && f.endsWith(".old"));assert.equal(olds.length, 1, `expected one rotated file, found ${olds.length}`);@@ -65,11 +145,104 @@ test("appendLocal rotates when file exceeds ROTATE_BYTES", () => {assert.equal(JSON.parse(fresh[0]).name, "AFTER-ROTATE");});-test("appendLocal never throws even when configDir is not writable", () => {- // Pass a path that cannot be created as a directory because a file exists there- const tmp = mkTmp();- const blocker = path.join(tmp, "blocker");- fs.writeFileSync(blocker, "i am a file, not a directory");- // Calling appendLocal with `blocker` as configDir should not throw.- appendLocal({ name: "X", data: {} }, { configDir: blocker });+test("appendLocal prunes session dirs older than 14 days, keeps recent ones", () => {+ const root = mkTmp();+ // An OLD session: write it, then backdate its events.jsonl 15 days.+ appendLocal({ name: "old", data: { pluginName: "power-pages", sessionId: "old" } }, { configDir: root });+ const oldLog = sessionLog(root, "power-pages", "old");+ const fifteenDaysAgo = new Date(Date.now() - 15 * 24 * 60 * 60 * 1000);+ fs.utimesSync(oldLog, fifteenDaysAgo, fifteenDaysAgo);++ // A NEW write in another session triggers the prune sweep.+ appendLocal({ name: "new", data: { pluginName: "power-pages", sessionId: "new" } }, { configDir: root });++ assert.ok(!fs.existsSync(path.dirname(oldLog)), "old session dir should be pruned");+ assert.ok(fs.existsSync(sessionLog(root, "power-pages", "new")), "new session kept");+});++test("appendLocal does NOT prune on a repeat append to an existing session", () => {+ const root = mkTmp();+ // Establish an existing session, then age a second session's log past the window.+ appendLocal({ name: "keep", data: { pluginName: "power-pages", sessionId: "keep" } }, { configDir: root });+ appendLocal({ name: "old", data: { pluginName: "power-pages", sessionId: "old" } }, { configDir: root });+ const oldLog = sessionLog(root, "power-pages", "old");+ const fifteenDaysAgo = new Date(Date.now() - 15 * 24 * 60 * 60 * 1000);+ fs.utimesSync(oldLog, fifteenDaysAgo, fifteenDaysAgo);++ // A second append to the EXISTING "keep" session must not create a dir, so the+ // sweep is skipped and the aged "old" session survives until a new session starts.+ appendLocal({ name: "keep2", data: { pluginName: "power-pages", sessionId: "keep" } }, { configDir: root });++ assert.ok(fs.existsSync(path.dirname(oldLog)), "old session dir kept — no sweep on repeat append");+});++test("pruneOldSessions removes an orphan dir only when its own mtime is past the window", () => {+ const root = mkTmp();+ const sessionsRoot = pluginLogDir(root, "power-pages");+ // Orphan dir (no events.jsonl) backdated 15 days -> removed.+ const stale = path.join(sessionsRoot, "stale-orphan");+ fs.mkdirSync(stale, { recursive: true });+ const fifteenDaysAgo = new Date(Date.now() - 15 * 24 * 60 * 60 * 1000);+ fs.utimesSync(stale, fifteenDaysAgo, fifteenDaysAgo);+ // Fresh orphan dir (no events.jsonl, just created) -> kept (race guard).+ const fresh = path.join(sessionsRoot, "fresh-orphan");+ fs.mkdirSync(fresh, { recursive: true });++ pruneOldSessions(root, "power-pages");++ assert.ok(!fs.existsSync(stale), "stale orphan dir pruned");+ assert.ok(fs.existsSync(fresh), "fresh orphan dir kept");+});++test("pruneOldSessions never throws when the sessions dir does not exist", () => {+ const root = mkTmp();+ pruneOldSessions(root, "never-used-plugin"); // must be a silent no-op+});++test("pruneOldSessions is a silent no-op when configDir is missing", () => {+ // Documented contract is "never throws"; a falsy configDir must not reach path.join.+ pruneOldSessions(undefined, "power-pages");+});++test("latestSessionLog returns null when no sessions exist", () => {+ const root = mkTmp();+ assert.equal(latestSessionLog(root, "power-pages"), null);+});++test("latestSessionLog returns null when configDir is missing", () => {+ // User-facing status path must fail closed rather than throw from path.join.+ assert.equal(latestSessionLog(undefined, "power-pages"), null);+});++test("latestSessionLog returns the most-recently-written session's log", () => {+ const root = mkTmp();+ appendLocal({ name: "A", data: { pluginName: "power-pages", sessionId: "old" } }, { configDir: root });+ appendLocal({ name: "B", data: { pluginName: "power-pages", sessionId: "new" } }, { configDir: root });++ // Make "old" clearly older so mtime ordering is deterministic.+ const tenMinAgo = new Date(Date.now() - 10 * 60 * 1000);+ fs.utimesSync(sessionLog(root, "power-pages", "old"), tenMinAgo, tenMinAgo);++ assert.equal(latestSessionLog(root, "power-pages"), sessionLog(root, "power-pages", "new"));+});++test("latestSessionLog skips session dirs that have no events.jsonl", () => {+ const root = mkTmp();+ // A real session that actually wrote a log.+ appendLocal({ name: "A", data: { pluginName: "power-pages", sessionId: "real" } }, { configDir: root });++ // An orphaned session dir with no events.jsonl (e.g. mkdir succeeded but the+ // process died before the first append). Make it NEWER than the real one so a+ // naive dir-mtime scan would wrongly prefer it — the returned path must still+ // be the real log, because status surfaces this path for the user to share.+ const orphanDir = path.join(pluginLogDir(root, "power-pages"), "orphan");+ fs.mkdirSync(orphanDir, { recursive: true });++ assert.equal(latestSessionLog(root, "power-pages"), sessionLog(root, "power-pages", "real"));+});++test("latestSessionLog returns null when every session dir lacks a log", () => {+ const root = mkTmp();+ fs.mkdirSync(path.join(pluginLogDir(root, "power-pages"), "orphan"), { recursive: true });+ assert.equal(latestSessionLog(root, "power-pages"), null);});diff --git a/shared/telemetry/tests/telemetry-config.test.js b/shared/telemetry/tests/telemetry-config.test.jsindex 10211680e..2b7a2ab99 100644--- a/shared/telemetry/tests/telemetry-config.test.js+++ b/shared/telemetry/tests/telemetry-config.test.js@@ -96,3 +96,33 @@ test("status: env opt-out overrides a persisted 'on' choice → OFF", () => {);assert.match(stdout, /Telemetry \(power-pages\): OFF/);});++const { appendLocal } = require("../lib/local-log");++test("status names the logs directory and says none yet when empty", () => {+ const dir = mkTmp();+ const { status, stdout } = run(["--action", "status", "--plugin", "power-pages"], dir);+ assert.equal(status, 0);+ assert.match(stdout, /Logs directory:/);+ assert.match(stdout, /No local logs yet for power-pages/);+});++test("status names the most recent session log when one exists", () => {+ const dir = mkTmp();+ // Seed a session log under the new layout via the real writer.+ appendLocal(+ { name: "X", data: { pluginName: "power-pages", sessionId: "sess-9" } },+ { configDir: dir }+ );+ const { stdout } = run(["--action", "status", "--plugin", "power-pages"], dir);+ assert.match(stdout, /Most recent session:/);+ assert.match(stdout, /sess-9/);+ assert.match(stdout, /Share that file when reporting an issue/);+});++test("off output names the logs directory too", () => {+ const dir = mkTmp();+ const { stdout } = run(["--action", "off", "--plugin", "power-pages"], dir);+ assert.match(stdout, /local diagnostic log is still kept/i);+ assert.match(stdout, /Logs directory:/);+});