Skip to content

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.

feat(mobile-apps): measure skill lifecycle telemetry (#637)

Shubham Agarwale2ff29991a34
diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.md
index 3e9c14ce2..ec0d627f9 100644
--- a/plugins/mobile-apps/AGENTS.md
+++ b/plugins/mobile-apps/AGENTS.md
@@ -87,10 +87,10 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr
Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-root `shared/telemetry/lib` at `scripts/lib/telemetry/lib`. Edit the shared source first, then refresh this physical copy in the same change; never copy another plugin's `ikey.json` or resolver.
-- **Lifecycle:** `UserPromptSubmit` records explicit slash-command starts and `PreToolUse(Skill)` records programmatic Skill-tool starts; both may fire for one visible slash command. `UserPromptSubmit` payloads differ by host — Claude Code passes the raw `/mobile-app:<skill>` text, Copilot CLI pre-expands it to a `<skill-context name="<skill>">` wrapper and emits no Skill pre-tool event — so both shapes must stay recognized or manual runs go uncaptured. Marked workflow boundaries emit explicit checkpoints through `scripts/emit-telemetry-checkpoint.js`; do not broaden hook matchers to observe commands. Every tracked operational skill has checkpoints; the `telemetry` preference skill is intentionally exempt because changing the preference can suppress one side of its own checkpoint lifecycle. Do not infer `skill_completed`, duration, or outcome from hook boundaries.
+- **Lifecycle:** `UserPromptSubmit` and `PreToolUse(Skill)` remain legacy activity observations, not measured workflow starts. Every tracked operational skill follows `shared/shared-instructions.md` to begin and end a schema-v2 skill span and measure registered checkpoints through `scripts/emit-telemetry-checkpoint.js`. Durable span state uses the Mobile Apps-owned `scripts/lib/mobile-lifecycle.js` helper; orchestration remains in the existing checkpoint CLI. Pass explicit run, parent, and span IDs across Skill, Task, subprocess, and resume boundaries. Do not infer completion from hook returns or recover run identity from an unrelated session. The `telemetry` preference skill remains exempt.
- **Coverage and attribution:** `scripts/lib/mobileapp-hook-utils.js` discovers every user- or model-invocable top-level skill, including `telemetry`. Direct-read helpers with `disable-model-invocation: true` are not independently invoked and are excluded. Bare and `mobile-app:`-qualified names are both attributed; explicitly foreign plugin namespaces are excluded.
- **Session correlation:** Stable host session ids pass through unchanged. Copilot CLI reports a transient `call_*` id to nested-agent hooks, so `resolveCopilotRootSessionId` in `scripts/lib/mobile-telemetry.js` resolves it to the unique recent UUID session whose local `~/.copilot/session-state/<uuid>/events.jsonl` structurally owns that `agentId`, reading only a bounded tail. Keep host-specific quirks contained in that one function. The verified root is cached as one atomic 30-minute alias file per hashed call id so fresh hook processes reuse it; aliases hold no prompts, cwd, or tool arguments and are never transmitted. Missing, stale, malformed, or ambiguous state fails open to the original id, and Claude Code and Codex ids are not rewritten.
-- **Privacy:** Mobile Apps sends no prompt, tool input, cwd, path, URL, credential, username, hostname, Dataverse org/tenant ID, or Entra object ID. The dynamic `eventInfo` contains only `invocationSource` (`prompt`, `pretool`, or `checkpoint`), a random per-project `appInstanceId` (or `null` outside a prepared project), optional author-defined checkpoint `additionalInfo` validated as `snake_case` with a 64-character limit, and `appInsightsSelection` (`enabled` or `disabled`) from the `/setup-app-insights` skill.
+- **Privacy:** Only the exact field schema enforced by `scripts/lib/mobile-telemetry-dispatcher.js` and disclosed in this plugin's README and telemetry skill is allowed. Verified environment, tenant, and organization IDs support adoption and support correlation; they are organization-identifying metadata. Mobile telemetry must never capture or transmit an Entra user/object ID, Dataverse UserId, username, email, or guessed home-account ID. Never send prompts, arguments, records, file contents, paths, URLs, credentials, names, hostnames, or raw errors. The dispatcher filters top-level and nested values before local logging and transmission; arbitrary `eventInfo` enrichment is forbidden.
- **Destination and controls:** Mobile-owned `scripts/lib/mobile-telemetry-dispatcher.js` maps shared events to the Power Apps `event` stream configured by `scripts/lib/telemetry/ikey.json`. The repository `disabled` switch is a hard-off; user and CI opt-outs suppress transmission while preserving the local diagnostic mirror.
- **CI:** Every Mobile Apps test job must set `POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT=1`. The single positive wire test clears that backstop only in its child process and routes the event to `POWER_PLATFORM_SKILLS_FAKE_HTTPS`; all other positive tests remain opted out and exercise the local mirror.
diff --git a/plugins/mobile-apps/README.md b/plugins/mobile-apps/README.md
index c05cd3c52..1f1e1055e 100644
--- a/plugins/mobile-apps/README.md
+++ b/plugins/mobile-apps/README.md
@@ -295,9 +295,13 @@ Example edit flows:
## Telemetry and privacy
-The Mobile Apps plugin sends start-only usage telemetry to Microsoft. A start event can include the skill name, plugin version, session and per-start correlation IDs, OS/Node versions, AI-agent name/version, invocation source, and a random per-project app instance ID. It never includes prompts, skill arguments, tool inputs, file paths, cwd, app/site names, URLs, credentials, usernames, hostnames, Dataverse organization or tenant IDs, or Entra object IDs.
+The Mobile Apps plugin sends usage and measured workflow telemetry to Microsoft by default. Events can include skill and checkpoint names, plugin/agent/OS/Node versions, random app/run/span/event IDs, measured durations, outcomes, retry attempts, and fixed error classifications. When verified target metadata is available, events can also include Power Platform environment and Entra tenant IDs plus the Dataverse organization ID.
-Both host surfaces are covered — an explicit slash command and a programmatic Skill-tool call — so some hosts may produce two `skill_started` records for one visible run. The plugin does not emit `skill_completed`, success/failure, error, or duration data because the available hook boundary does not prove that the workflow itself completed.
+Events never include Entra user/object IDs, Dataverse user IDs, prompts, arguments, tool inputs, business records, document contents, file paths, cwd, app/site names, URLs, credentials, usernames, email addresses, hostnames, or raw error descriptions. Organization and environment identifiers are identifying metadata, not anonymous user counts. The same field filtering applies before local logging and transmission.
+
+Before local logging and again before transmission (including replay), the dispatcher retains organization, tenant, and environment IDs only when they match the current project's verified span or ancestor context. A missing, pruned, or mismatched verification record drops those identifiers while preserving the remaining usage event.
+
+Prompt and Skill-tool hooks remain legacy activity observations and can both fire for one visible command. Measured metrics use schema-v2 lifecycle records with explicit run/span IDs instead. A missing terminal event remains incomplete; it is not inferred from a hook return. Each measured run returns a Support ID that can be included in an issue report without exposing project content.
Control the per-user transmission preference with:
@@ -307,7 +311,7 @@ Control the per-user transmission preference with:
/mobile-app:telemetry on
```
-`off` stops network transmission but retains the sanitized local diagnostic mirror under `~/.power-platform-skills/telemetry/mobile-app/sessions/<sessionId>/events.jsonl`. Automation can force transmission off with `POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT=1`; this overrides the saved preference and `on`.
+`off` stops network transmission but retains the sanitized local diagnostic mirror under `~/.power-platform-skills/telemetry/mobile-app/sessions/<sessionId>/events.jsonl`. Private lifecycle state is retained separately under `~/.power-platform-skills/telemetry/mobile-app/runs/` for support reports and cross-process timing; it contains generated IDs, registered skill/checkpoint names, fixed states, and timestamps, never prompts or command content. Automation can force transmission off with `POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT=1`; this overrides the saved preference and `on`.
## Known blockers
diff --git a/plugins/mobile-apps/scripts/dataverse-request.js b/plugins/mobile-apps/scripts/dataverse-request.js
index 4692b023c..f6842880f 100644
--- a/plugins/mobile-apps/scripts/dataverse-request.js
+++ b/plugins/mobile-apps/scripts/dataverse-request.js
@@ -185,6 +185,19 @@ async function doRequest(envUrl, method, apiPath, body, token, includeHeaders, s
: READ_REQUEST_TIMEOUT_MS,
});
+ if (
+ res.statusCode >= 200 &&
+ res.statusCode < 300 &&
+ /^WhoAmI(?:\(\))?(?:\?|$)/i.test(apiPath)
+ ) {
+ try {
+ const whoAmI = JSON.parse(res.body);
+ require('./emit-telemetry-checkpoint')
+ .captureSuccessfulDataverseRequest(envUrl, token, whoAmI);
+ } catch {
+ // Telemetry enrichment cannot change a successful Dataverse response.
+ }
+ }
return res;
}
diff --git a/plugins/mobile-apps/scripts/emit-telemetry-checkpoint.js b/plugins/mobile-apps/scripts/emit-telemetry-checkpoint.js
index 280d77e75..65e9dae8e 100644
--- a/plugins/mobile-apps/scripts/emit-telemetry-checkpoint.js
+++ b/plugins/mobile-apps/scripts/emit-telemetry-checkpoint.js
@@ -1,10 +1,19 @@
#!/usr/bin/env node
'use strict';
-const { TRACKED_SKILL_NAMES } = require('./lib/mobileapp-hook-utils');
+const {
+ TELEMETRY_STATES,
+ TRACKED_SKILL_NAMES,
+ isKnownTelemetryEvent,
+ isTelemetryStaticInfo,
+} = require('./lib/mobileapp-hook-utils');
+const {
+ GUID,
+ recordVerifiedDataverseOrganization,
+} = require('./lib/mobile-telemetry-context');
const telemetry = require('./lib/mobile-telemetry');
-const CHECKPOINT_STATES = new Set(['started', 'completed', 'skipped', 'failed']);
+const CHECKPOINT_STATES = new Set(TELEMETRY_STATES);
const CHECKPOINT_NAME_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
const CHECKPOINT_SKILLS = new Set(TRACKED_SKILL_NAMES);
@@ -23,9 +32,14 @@ function parseCheckpointPayload(payload) {
) {
return null;
}
+ if (!isKnownTelemetryEvent(skillName, `${checkpointName}_${state}`)) return null;
if (
additionalInfo &&
- (additionalInfo.length > 64 || !CHECKPOINT_NAME_PATTERN.test(additionalInfo))
+ (
+ additionalInfo.length > 64 ||
+ !CHECKPOINT_NAME_PATTERN.test(additionalInfo) ||
+ !isTelemetryStaticInfo(additionalInfo)
+ )
) {
return null;
}
@@ -46,9 +60,13 @@ function emitCheckpoint(payload, opts = {}) {
const createContext = opts.createTelemetryContext || telemetry.createTelemetryContext;
const cwd = opts.cwd || process.cwd();
- const context = createContext({}, { cwd });
+ const context = createContext({}, {
+ cwd,
+ ...(opts.runId ? { readProcessScope: () => '' } : {}),
+ });
if (!context) return null;
+ if (opts.runId) return emitTrackedCheckpoint(payload, context, { ...opts, cwd });
const emit = opts.emitCheckpoint || telemetry.emitCheckpoint;
return emit(context, invocation, { cwd });
} catch {
@@ -56,8 +74,210 @@ function emitCheckpoint(payload, opts = {}) {
}
}
+function captureSuccessfulDataverseRequest(environmentUrl, token, whoAmI, env = process.env) {
+ try {
+ const runId = env.POWER_PLATFORM_SKILLS_MOBILE_RUN_ID;
+ const spanId = env.POWER_PLATFORM_SKILLS_MOBILE_SPAN_ID;
+ if (!GUID.test(runId || '') || !GUID.test(spanId || '')) return false;
+ const projectRoot = env.POWER_PLATFORM_SKILLS_PROJECT_ROOT || process.cwd();
+ const context = telemetry.createTelemetryContext({}, {
+ cwd: projectRoot,
+ env,
+ readProcessScope: () => '',
+ });
+ if (!context) return false;
+ return recordVerifiedDataverseOrganization({
+ projectRoot,
+ configDir: context.configDir,
+ runId,
+ spanId,
+ environmentUrl,
+ lifecycle: telemetry.lifecycle,
+ token,
+ whoAmI,
+ });
+ } catch {
+ // Verification enrichment is observational and cannot alter the request.
+ return false;
+ }
+}
+
+function publicContext(span) {
+ return {
+ schemaVersion: 2,
+ runId: span.runId,
+ spanId: span.spanId,
+ parentSpanId: span.parentSpanId,
+ sessionId: span.sessionId,
+ skillName: span.skillName,
+ state: span.state,
+ ...(span.durationMs === undefined ? {} : { durationMs: span.durationMs }),
+ };
+}
+
+function emitTrackedCheckpoint(payload, context, opts) {
+ const invocation = parseCheckpointPayload(payload);
+ if (!invocation) throw new Error('invalid_input');
+ const [, checkpointName, state] = payload.split('|').map((part) => part.trim());
+ const options = {
+ ...opts,
+ configDir: context.configDir,
+ projectRoot: opts.cwd,
+ skillName: invocation.skillName,
+ checkpointName,
+ additionalInfo: invocation.additionalInfo,
+ state,
+ };
+ let span;
+ if (state === 'started') {
+ span = telemetry.lifecycle.beginSpan(options);
+ } else if (state === 'skipped' && !opts.spanId) {
+ const start = telemetry.lifecycle.beginSpan(options);
+ span = telemetry.lifecycle.finishSpan({ ...options, spanId: start.spanId });
+ } else {
+ const start = telemetry.lifecycle.readSpan(options).record;
+ if (start.skillName !== invocation.skillName || start.checkpointName !== checkpointName) {
+ throw new Error('invalid_context');
+ }
+ span = telemetry.lifecycle.finishSpan(options);
+ }
+ const emit = opts.emitLifecycle || telemetry.emitLifecycle;
+ emit(context, span, { cwd: opts.cwd });
+ return publicContext(span);
+}
+
+function parseOptions(argv) {
+ const names = {
+ '--begin': 'begin',
+ '--finish': 'finish',
+ '--resume': 'resume',
+ '--run-id': 'runId',
+ '--span-id': 'spanId',
+ '--parent-span-id': 'parentSpanId',
+ '--retry-of': 'retryOf',
+ '--error-class': 'errorClass',
+ '--project-root': 'cwd',
+ };
+ const result = {};
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index];
+ if (argument === '--') {
+ result.command = argv.slice(index + 1);
+ break;
+ }
+ if (argument === '--report') {
+ result.report = true;
+ } else if (names[argument]) {
+ if (
+ !argv[index + 1] ||
+ argv[index + 1].startsWith('--') ||
+ result[names[argument]] !== undefined
+ ) {
+ throw new Error('invalid_input');
+ }
+ result[names[argument]] = argv[++index];
+ } else if (!argument.startsWith('--') && result.payload === undefined) {
+ result.payload = argument;
+ } else {
+ throw new Error('invalid_input');
+ }
+ }
+ return result;
+}
+
+function runCommand(argv = process.argv.slice(2), overrides = {}) {
+ try {
+ const args = parseOptions(argv);
+ const commands = [
+ args.begin,
+ args.finish,
+ args.resume,
+ args.payload,
+ args.report,
+ ].filter(Boolean);
+ if (commands.length !== 1) throw new Error('invalid_input');
+ if (args.command) throw new Error('invalid_input');
+ if (args.payload && !args.runId) {
+ return emitCheckpoint(args.payload, {
+ ...overrides,
+ cwd: args.cwd || overrides.cwd,
+ });
+ }
+
+ const cwd = args.cwd || process.cwd();
+ if (args.report) {
+ return telemetry.lifecycle.reportRun({
+ projectRoot: cwd,
+ runId: args.runId,
+ configDir: telemetry.getTelemetryConfigDir(overrides.env || process.env),
+ });
+ }
+
+ const createContext = overrides.createTelemetryContext || telemetry.createTelemetryContext;
+ const context = createContext({}, {
+ cwd,
+ env: overrides.env,
+ ...(args.runId ? { readProcessScope: () => '' } : {}),
+ });
+ if (!context) return { status: 'disabled' };
+ const options = {
+ ...args,
+ projectRoot: cwd,
+ configDir: context.configDir,
+ sessionId: context.sessionId,
+ };
+ let span;
+ if (args.begin) {
+ span = telemetry.lifecycle.beginSpan({ ...options, skillName: args.begin });
+ } else if (args.finish) {
+ span = telemetry.lifecycle.finishSpan({ ...options, state: args.finish });
+ } else if (args.resume) {
+ span = telemetry.lifecycle.resumeSpan({ ...options, spanId: args.resume });
+ } else {
+ return emitTrackedCheckpoint(args.payload, context, { ...args, ...overrides, cwd });
+ }
+ (overrides.emitLifecycle || telemetry.emitLifecycle)(context, span, { cwd });
+ return publicContext(span);
+ } catch (error) {
+ const safeReasons = new Set([
+ 'invalid_input',
+ 'invalid_context',
+ 'invalid_skill',
+ 'invalid_checkpoint',
+ 'invalid_additional_info',
+ 'missing_parent',
+ 'parent_finished',
+ 'invalid_parent',
+ 'invalid_retry',
+ 'invalid_resume',
+ 'already_finished',
+ 'invalid_state',
+ 'invalid_error_class',
+ 'invalid_clock',
+ 'children_pending',
+ 'lock_timeout',
+ ]);
+ return {
+ status: 'unavailable',
+ reason: safeReasons.has(error.message) ? error.message : 'telemetry_unavailable',
+ };
+ }
+}
+
if (require.main === module) {
- emitCheckpoint(process.argv[2]);
+ const result = runCommand();
+ if (
+ result &&
+ (result.schemaVersion === 2 || result.status)
+ ) {
+ process.stdout.write(`${JSON.stringify(result)}\n`);
+ }
}
-module.exports = { emitCheckpoint, parseCheckpointPayload };
\ No newline at end of file
+module.exports = {
+ captureSuccessfulDataverseRequest,
+ emitCheckpoint,
+ parseCheckpointPayload,
+ parseOptions,
+ runCommand,
+};
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/lib/environment-resolution.js b/plugins/mobile-apps/scripts/lib/environment-resolution.js
index 93b8a2635..51a094660 100644
--- a/plugins/mobile-apps/scripts/lib/environment-resolution.js
+++ b/plugins/mobile-apps/scripts/lib/environment-resolution.js
@@ -90,6 +90,15 @@ function readCachedResolution(target, projectRoot) {
return null;
}
+function readProjectEnvironment(projectRoot) {
+ const powerConfig = readJsonFile(path.join(projectRoot, 'power.config.json'));
+ const configuredEnvironmentId = powerConfig && powerConfig.environmentId;
+ if (configuredEnvironmentId && !GUID_RE.test(configuredEnvironmentId)) return null;
+ const cached = readCachedResolution(configuredEnvironmentId || null, projectRoot);
+ if (!cached || !GUID_RE.test(cached.environmentId || '')) return null;
+ return toEnvironmentResult(cached, 'cache');
+}
+
function hasCachedEnvironmentDetails(value) {
return Boolean(value && value.environmentUrl && value.tenantId);
}
@@ -361,6 +370,7 @@ module.exports = {
describeResponseShape,
formatRequestFailure,
redactDiagnostic,
+ readProjectEnvironment,
resolveEnvironment,
shouldWriteCache,
writeCacheIfProject,
diff --git a/plugins/mobile-apps/scripts/lib/mobile-lifecycle.js b/plugins/mobile-apps/scripts/lib/mobile-lifecycle.js
new file mode 100644
index 000000000..9d5dbe8bc
--- /dev/null
+++ b/plugins/mobile-apps/scripts/lib/mobile-lifecycle.js
@@ -0,0 +1,569 @@
+'use strict';
+
+// Lifecycle persistence is Mobile Apps-specific so other telemetry adopters
+// can evolve independently without taking this workflow contract.
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const os = require('node:os');
+const {
+ TELEMETRY_ERROR_CLASSES,
+ TELEMETRY_STATES,
+ TRACKED_SKILL_NAMES,
+ getTelemetryCheckpointNames,
+ isTelemetryStaticInfo,
+} = require('./mobileapp-hook-utils');
+
+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const DEFAULT_RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
+const DEFAULT_LOCK_TIMEOUT_MS = 5000;
+const DEFAULT_LOCK_RETRY_MS = 10;
+const LOCK_DIRECTORY = '.lifecycle.lock';
+const LOCK_RECOVERY_DIRECTORY = '.lifecycle.lock.recovery';
+
+function filesystem(options) {
+ return options.fs || fs;
+}
+
+function normalizePolicy(input) {
+ if (!input || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(input.pluginName || '')) {
+ throw new TypeError('Lifecycle telemetry requires a valid plugin name');
+ }
+ if (!(input.trackedSkillNames instanceof Set) || typeof input.checkpointNames !== 'function') {
+ throw new TypeError('Lifecycle telemetry requires skill and checkpoint validators');
+ }
+ if (typeof input.isAdditionalInfo !== 'function') {
+ throw new TypeError('Lifecycle telemetry requires an additional-info validator');
+ }
+ return Object.freeze({
+ pluginName: input.pluginName,
+ trackedSkillNames: new Set(input.trackedSkillNames),
+ exemptSkillNames: new Set(input.exemptSkillNames || []),
+ checkpointNames: input.checkpointNames,
+ isAdditionalInfo: input.isAdditionalInfo,
+ terminalStates: new Set(input.terminalStates || [
+ 'completed', 'failed', 'blocked', 'cancelled', 'skipped', 'needs_context',
+ ]),
+ errorClasses: new Set(input.errorClasses || []),
+ retentionMs: Number.isSafeInteger(input.retentionMs) && input.retentionMs > 0
+ ? input.retentionMs
+ : DEFAULT_RETENTION_MS,
+ });
+}
+
+function checkpointNames(policy, skillName) {
+ if (!policy.trackedSkillNames.has(skillName) || policy.exemptSkillNames.has(skillName)) {
+ return new Set();
+ }
+ const names = policy.checkpointNames(skillName);
+ return names instanceof Set ? names : new Set();
+}
+
+function requireGuid(value) {
+ if (typeof value !== 'string' || !GUID.test(value)) throw new Error('invalid_context');
+ return value.toLowerCase();
+}
+
+function scopeKey(projectRoot) {
+ return crypto.createHash('sha256').update(fs.realpathSync(projectRoot)).digest('hex');
+}
+
+function runDirectory(policy, configDir, runId) {
+ return path.join(configDir, 'telemetry', policy.pluginName, 'runs', requireGuid(runId));
+}
+
+function readJson(filename) {
+ if (fs.statSync(filename).size > 32 * 1024) throw new Error('invalid_context');
+ return JSON.parse(fs.readFileSync(filename, 'utf8'));
+}
+
+function writeExclusive(filename, value) {
+ const temporary = `${filename}.${crypto.randomUUID()}.tmp`;
+ try {
+ fs.writeFileSync(temporary, JSON.stringify(value), { encoding: 'utf8', flag: 'wx', mode: 0o600 });
+ // Publish without replacing an existing record or exposing a half-written
+ // JSON file to a concurrent finish. Both links stay in the private directory.
+ fs.linkSync(temporary, filename);
+ } finally {
+ try { fs.rmSync(temporary, { force: true }); } catch { /* best effort */ }
+ }
+}
+
+function processIsAlive(pid, options) {
+ if (typeof options.isProcessAlive === 'function') return options.isProcessAlive(pid);
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return error.code !== 'ESRCH';
+ }
+}
+
+function readLockOwner(lockPath) {
+ try {
+ const owner = readJson(lockPath);
+ if (
+ Number.isSafeInteger(owner.pid) &&
+ owner.pid > 0 &&
+ typeof owner.token === 'string' &&
+ GUID.test(owner.token) &&
+ Number.isSafeInteger(owner.acquiredAtMs)
+ ) {
+ return owner;
+ }
+ } catch {
+ // Missing or malformed metadata is handled after the initialization grace.
+ }
+ return null;
+}
+
+function lockOwner(token) {
+ return {
+ pid: process.pid,
+ token,
+ acquiredAtMs: Date.now(),
+ };
+}
+
+function releaseOwnedLock(lockPath, token) {
+ try {
+ const owner = readLockOwner(lockPath);
+ if (owner?.token === token) fs.rmSync(lockPath, { force: true });
+ } catch {
+ // A release failure is recovered when the owner process is no longer live.
+ }
+}
+
+function publishOwnedLock(lockPath, token, options = {}) {
+ const fileSystem = filesystem(options);
+ const temporaryPath = `${lockPath}.${process.pid}.${token}.pending`;
+ try {
+ fileSystem.writeFileSync(temporaryPath, JSON.stringify(lockOwner(token)), {
+ encoding: 'utf8',
+ flag: 'wx',
+ mode: 0o600,
+ });
+ fileSystem.linkSync(temporaryPath, lockPath);
+ return true;
+ } catch (error) {
+ // EEXIST proves another owner won publication. That owner may release the
+ // path before this catch runs, so a follow-up existsSync check is racy.
+ if (error.code === 'EEXIST') return false;
+ throw error;
+ } finally {
+ try {
+ fileSystem.rmSync(temporaryPath, { force: true });
+ } catch {
+ // A pending file is never treated as the stable lock.
+ }
+ }
+}
+
+function sameFile(leftPath, rightPath) {
+ try {
+ const left = fs.statSync(leftPath);
+ const right = fs.statSync(rightPath);
+ return left.dev === right.dev && left.ino === right.ino;
+ } catch {
+ return false;
+ }
+}
+
+function tryRecoverRunLock(directory, options) {
+ const lockPath = path.join(directory, LOCK_DIRECTORY);
+ const recoveryPath = path.join(directory, LOCK_RECOVERY_DIRECTORY);
+ try {
+ // This hard link is an atomic claim on the exact lock inode. Even if the
+ // stable path is later replaced, recovery can only unlink the inode claimed
+ // here and therefore cannot delete a newly acquired live lock.
+ fs.linkSync(lockPath, recoveryPath);
+ } catch (error) {
+ if (error.code === 'ENOENT') return true;
+ if (error.code !== 'EEXIST') throw error;
+ const claimedOwner = readLockOwner(recoveryPath);
+ if (claimedOwner && !processIsAlive(claimedOwner.pid, options)) {
+ fs.rmSync(recoveryPath, { force: true });
+ }
+ return false;
+ }
+
+ try {
+ const owner = readLockOwner(recoveryPath);
+ if (!owner || processIsAlive(owner.pid, options)) return false;
+ if (sameFile(lockPath, recoveryPath)) fs.rmSync(lockPath, { force: true });
+ return true;
+ } finally {
+ fs.rmSync(recoveryPath, { force: true });
+ }
+}
+
+function acquireRunLock(directory, options = {}) {
+ const timeoutMs = Number.isSafeInteger(options.lockTimeoutMs) && options.lockTimeoutMs >= 0
+ ? options.lockTimeoutMs
+ : DEFAULT_LOCK_TIMEOUT_MS;
+ const retryMs = Number.isSafeInteger(options.lockRetryMs) && options.lockRetryMs > 0
+ ? options.lockRetryMs
+ : DEFAULT_LOCK_RETRY_MS;
+ const lockPath = path.join(directory, LOCK_DIRECTORY);
+ const token = crypto.randomUUID();
+ const startedAt = Date.now();
+
+ while (true) {
+ if (publishOwnedLock(lockPath, token, options)) {
+ return () => releaseOwnedLock(lockPath, token);
+ }
+ if (tryRecoverRunLock(directory, options)) continue;
+ if (Date.now() - startedAt >= timeoutMs) throw new Error('lock_timeout');
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, retryMs);
+ }
+}
+
+function clockReading(options) {
+ return {
+ wallMs: options.now === undefined ? Date.now() : options.now,
+ monotonicMs: options.monotonicMs ?? (options.now === undefined ? Number(process.hrtime.bigint() / 1000000n) : null),
+ uptimeMs: options.uptimeMs ?? (options.now === undefined ? Math.round(os.uptime() * 1000) : null),
+ };
+}
+
+function readRun(policy, options) {
+ const directory = runDirectory(policy, options.configDir, options.runId);
+ const record = readJson(path.join(directory, 'run.json'));
+ if (record.schemaVersion !== 2 || record.runId !== options.runId ||
+ !GUID.test(record.rootSpanId || '') || !GUID.test(record.sessionId || '') ||
+ !Number.isSafeInteger(record.startedAtMs) ||
+ record.scopeKey !== scopeKey(options.projectRoot)) throw new Error('invalid_context');
+ return { directory, record };
+}
+
+function readSpan(policy, options) {
+ const { directory, record: run } = readRun(policy, options);
+ const spanId = requireGuid(options.spanId);
+ const record = readJson(path.join(directory, `${spanId}.start.json`));
+ if (record.runId !== run.runId || record.spanId !== spanId ||
+ !policy.trackedSkillNames.has(record.skillName) ||
+ !['skill', 'checkpoint'].includes(record.spanType) ||
+ !GUID.test(record.eventId || '') || record.sessionId !== run.sessionId ||
+ (record.parentSpanId !== null && !GUID.test(record.parentSpanId || '')) ||
+ (record.retryOfSpanId != null && !GUID.test(record.retryOfSpanId)) ||
+ !Number.isSafeInteger(record.attempt) || record.attempt < 1 ||
+ !Number.isSafeInteger(record.startedAtMs)) throw new Error('invalid_context');
+ if (record.spanType === 'checkpoint' && !checkpointNames(policy, record.skillName).has(record.checkpointName)) {
+ throw new Error('invalid_context');
+ }
+ if (record.additionalInfo != null && !policy.isAdditionalInfo(record.additionalInfo)) {
+ throw new Error('invalid_context');
+ }
+ return { directory, run, record };
+}
+
+function persistSpan(policy, options, context) {
+ const { clock, directory, parentSpanId, run, spanId } = context;
+ let attempt = 1;
+ if (options.retryOf) {
+ const prior = readSpan(policy, {
+ ...options,
+ runId: run.runId,
+ spanId: options.retryOf,
+ }).record;
+ if (prior.parentSpanId !== parentSpanId || prior.skillName !== options.skillName ||
+ prior.checkpointName !== (options.checkpointName || null) ||
+ !fs.existsSync(path.join(directory, `${prior.spanId}.end.json`))) throw new Error('invalid_retry');
+ // Both resume and explicit retry hold the run lock here. A consumed attempt
+ // cannot fork another child that would leave the parent pending.
+ if (listSpans(policy, { ...options, runId: run.runId })
+ .some((span) => span.retryOfSpanId === prior.spanId)) throw new Error('invalid_retry');
+ attempt = prior.attempt + 1;
+ }
+ const record = { schemaVersion: 2, runId: run.runId, spanId, parentSpanId: parentSpanId || null,
+ spanType: options.checkpointName ? 'checkpoint' : 'skill',
+ skillName: options.skillName, checkpointName: options.checkpointName || null,
+ additionalInfo: options.additionalInfo || null,
+ retryOfSpanId: options.retryOf || null,
+ sessionId: run.sessionId, attempt, eventId: crypto.randomUUID(),
+ startedMonotonicMs: clock.monotonicMs, startedUptimeMs: clock.uptimeMs,
+ startedAtMs: clock.wallMs, time: new Date(clock.wallMs).toISOString(), state: 'started' };
+ // One immutable file per span avoids lost updates when independent agents run
+ // concurrently. Project/process paths never enter the event record.
+ writeExclusive(path.join(directory, `${spanId}.start.json`), record);
+ return record;
+}
+
+function beginSpan(policy, options) {
+ const { skillName, checkpointName } = options;
+ if (!policy.trackedSkillNames.has(skillName) || policy.exemptSkillNames.has(skillName)) {
+ throw new Error('invalid_skill');
+ }
+ if (checkpointName && !checkpointNames(policy, skillName).has(checkpointName)) {
+ throw new Error('invalid_checkpoint');
+ }
+ if (options.additionalInfo && !policy.isAdditionalInfo(options.additionalInfo)) {
+ throw new Error('invalid_additional_info');
+ }
+ const clock = clockReading(options);
+ if (!Number.isSafeInteger(clock.wallMs) || clock.wallMs < 0) throw new Error('invalid_clock');
+ const spanId = crypto.randomUUID();
+ const runId = options.runId;
+ const parentSpanId = options.parentSpanId;
+
+ if (runId || parentSpanId) {
+ if (!runId || !parentSpanId) throw new Error('missing_parent');
+ const initialParent = readSpan(policy, { ...options, spanId: parentSpanId });
+ const release = acquireRunLock(initialParent.directory, options);
+ try {
+ const parent = readSpan(policy, { ...options, spanId: parentSpanId });
+ if (fs.existsSync(path.join(parent.directory, `${parent.record.spanId}.end.json`))) {
+ throw new Error('parent_finished');
+ }
+ if (checkpointName && parent.record.skillName !== skillName) {
+ throw new Error('invalid_parent');
+ }
+ return persistSpan(policy, options, {
+ clock,
+ directory: parent.directory,
+ parentSpanId: parent.record.spanId,
+ run: parent.run,
+ spanId,
+ });
+ } finally {
+ release();
+ }
+ }
+
+ if (checkpointName) throw new Error('missing_parent');
+ pruneRuns(policy, options.configDir, clock.wallMs);
+ const newRunId = crypto.randomUUID();
+ const directory = runDirectory(policy, options.configDir, newRunId);
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
+ const run = {
+ schemaVersion: 2,
+ runId: newRunId,
+ rootSpanId: spanId,
+ scopeKey: scopeKey(options.projectRoot),
+ sessionId: GUID.test(options.sessionId || '') ? options.sessionId : newRunId,
+ startedAtMs: clock.wallMs,
+ };
+ writeExclusive(path.join(directory, 'run.json'), run);
+ return persistSpan(policy, options, {
+ clock,
+ directory,
+ parentSpanId: null,
+ run,
+ spanId,
+ });
+}
+
+function finishSpan(policy, options) {
+ if (!policy.terminalStates.has(options.state)) throw new Error('invalid_state');
+ if (options.errorClass && !policy.errorClasses.has(options.errorClass)) {
+ throw new Error('invalid_error_class');
+ }
+ const initial = readSpan(policy, options);
+ const release = acquireRunLock(initial.directory, options);
+ try {
+ const { directory, record } = readSpan(policy, options);
+ const endPath = path.join(directory, `${record.spanId}.end.json`);
+ if (fs.existsSync(endPath)) {
+ const previous = readJson(endPath);
+ validateEnd(policy, record, previous);
+ if (previous.state !== options.state) throw new Error('already_finished');
+ return previous;
+ }
+ if (options.state === 'completed') {
+ const spans = listSpans(policy, options);
+ const byId = new Map(spans.map((span) => [span.spanId, span]));
+ const resumedSpanIds = new Set(
+ spans.map((span) => span.retryOfSpanId).filter(Boolean),
+ );
+ for (const candidate of spans) {
+ if (
+ candidate.spanId === record.spanId ||
+ (candidate.state !== 'started' &&
+ !(candidate.state === 'needs_context' && !resumedSpanIds.has(candidate.spanId)))
+ ) {
+ continue;
+ }
+ let parent = candidate.parentSpanId;
+ const visited = new Set();
+ while (parent && !visited.has(parent)) {
+ if (parent === record.spanId) throw new Error('children_pending');
+ visited.add(parent);
+ parent = byId.get(parent)?.parentSpanId;
+ }
+ }
+ }
+ const clock = clockReading(options);
+ const now = clock.wallMs;
+ if (!Number.isSafeInteger(now) || now < 0) throw new Error('invalid_clock');
+ const wallElapsed = now - record.startedAtMs;
+ const hasMonotonic = Number.isSafeInteger(record.startedMonotonicMs) &&
+ Number.isSafeInteger(clock.monotonicMs);
+ const monotonicElapsed = hasMonotonic ? clock.monotonicMs - record.startedMonotonicMs : wallElapsed;
+ const uptimeElapsed = Number.isSafeInteger(record.startedUptimeMs) &&
+ Number.isSafeInteger(clock.uptimeMs)
+ ? clock.uptimeMs - record.startedUptimeMs
+ : wallElapsed;
+ const measured = wallElapsed >= 0 && monotonicElapsed >= 0 && uptimeElapsed >= 0 &&
+ Math.abs(wallElapsed - monotonicElapsed) <= 2000 &&
+ Math.abs(wallElapsed - uptimeElapsed) <= 2000;
+ const result = {
+ ...record,
+ eventId: crypto.randomUUID(),
+ state: options.state,
+ time: new Date(now).toISOString(),
+ timingStatus: options.state === 'skipped'
+ ? 'not_applicable'
+ : measured
+ ? 'measured'
+ : 'clock_invalid',
+ };
+ if (measured && options.state !== 'skipped') result.durationMs = monotonicElapsed;
+ if (options.errorClass) result.errorClass = options.errorClass;
+ writeExclusive(endPath, result);
+ return result;
+ } finally {
+ release();
+ }
+}
+
+function resumeSpan(policy, options) {
+ const initial = readSpan(policy, options);
+ const release = acquireRunLock(initial.directory, options);
+ try {
+ const { directory, run, record } = readSpan(policy, options);
+ if (record.spanType !== 'skill') throw new Error('invalid_resume');
+ const end = readJsonIfPresent(path.join(directory, `${record.spanId}.end.json`));
+ if (!end) throw new Error('invalid_resume');
+ validateEnd(policy, record, end);
+ if (end.state !== 'needs_context') throw new Error('invalid_resume');
+ if (
+ record.parentSpanId &&
+ fs.existsSync(path.join(directory, `${record.parentSpanId}.end.json`))
+ ) {
+ throw new Error('parent_finished');
+ }
+ const clock = clockReading(options);
+ if (!Number.isSafeInteger(clock.wallMs) || clock.wallMs < 0) {
+ throw new Error('invalid_clock');
+ }
+ return persistSpan(policy, {
+ ...options,
+ skillName: record.skillName,
+ checkpointName: null,
+ additionalInfo: record.additionalInfo,
+ retryOf: record.spanId,
+ }, {
+ clock,
+ directory,
+ parentSpanId: record.parentSpanId,
+ run,
+ spanId: crypto.randomUUID(),
+ });
+ } finally {
+ release();
+ }
+}
+
+function listSpans(policy, options) {
+ const { directory } = readRun(policy, options);
+ const files = fs.readdirSync(directory).filter((name) => /^[0-9a-f-]{36}\.start\.json$/i.test(name));
+ if (files.length > 4096) throw new Error('invalid_context');
+ return files.map((name) => {
+ const spanId = name.slice(0, 36);
+ const start = readSpan(policy, { ...options, spanId }).record;
+ const end = readJsonIfPresent(path.join(directory, `${spanId}.end.json`));
+ if (end) validateEnd(policy, start, end);
+ return end || start;
+ });
+}
+
+function readJsonIfPresent(filename) {
+ try { return readJson(filename); } catch (error) {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ }
+}
+
+function validateEnd(policy, start, end) {
+ for (const field of ['runId', 'spanId', 'parentSpanId', 'skillName', 'checkpointName', 'additionalInfo', 'retryOfSpanId', 'spanType', 'sessionId', 'attempt', 'startedAtMs', 'startedMonotonicMs', 'startedUptimeMs']) {
+ if (start[field] !== end[field]) throw new Error('invalid_context');
+ }
+ if (!policy.terminalStates.has(end.state) || !GUID.test(end.eventId || '') ||
+ !Number.isFinite(Date.parse(end.time)) ||
+ (end.durationMs !== undefined && (!Number.isSafeInteger(end.durationMs) || end.durationMs < 0))) {
+ throw new Error('invalid_context');
+ }
+}
+
+function pruneRuns(policy, configDir, now = Date.now()) {
+ const root = path.join(configDir, 'telemetry', policy.pluginName, 'runs');
+ try {
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
+ if (!entry.isDirectory() || !GUID.test(entry.name)) continue;
+ const directory = path.join(root, entry.name);
+ const run = readJsonIfPresent(path.join(directory, 'run.json'));
+ if (
+ run?.runId === entry.name &&
+ Number.isSafeInteger(run.startedAtMs) &&
+ now - run.startedAtMs > policy.retentionMs
+ ) {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+ }
+ } catch { /* Retention cleanup is best effort and never blocks a workflow. */ }
+}
+
+function reportRun(policy, options) {
+ const { record: run } = readRun(policy, options);
+ const rawSpans = listSpans(policy, options);
+ const initialRoot = rawSpans.find((span) => span.spanId === run.rootSpanId);
+ const currentRoot = rawSpans
+ .filter((span) => span.spanType === 'skill' &&
+ span.parentSpanId === null &&
+ span.skillName === initialRoot?.skillName)
+ .sort((left, right) =>
+ right.attempt - left.attempt ||
+ right.startedAtMs - left.startedAtMs ||
+ right.spanId.localeCompare(left.spanId))[0];
+ const spans = rawSpans.map((span) => ({
+ spanId: span.spanId, parentSpanId: span.parentSpanId, skill: span.skillName,
+ step: span.checkpointName, type: span.spanType, attempt: span.attempt,
+ ...(GUID.test(span.retryOfSpanId || '') ? { retryOfSpanId: span.retryOfSpanId } : {}),
+ state: span.state === 'started' ? 'incomplete' : span.state,
+ startedAt: new Date(span.startedAtMs).toISOString(),
+ ...(span.state === 'started' ? {} : { finishedAt: new Date(span.time).toISOString() }),
+ ...(span.durationMs === undefined ? {} : { durationMs: span.durationMs }),
+ ...(policy.errorClasses.has(span.errorClass) ? { errorClass: span.errorClass } : {}),
+ ...(policy.isAdditionalInfo(span.additionalInfo) ? { additionalInfo: span.additionalInfo } : {}),
+ }));
+ return { schemaVersion: 2, supportId: run.runId, runId: run.runId,
+ state: currentRoot?.state === 'started' ? 'incomplete' : currentRoot?.state || 'incomplete', spans };
+}
+
+function createLifecycle(input) {
+ const policy = normalizePolicy(input);
+ return Object.freeze({
+ beginSpan: (options) => beginSpan(policy, options),
+ finishSpan: (options) => finishSpan(policy, options),
+ listSpans: (options) => listSpans(policy, options),
+ pruneRuns: (configDir, now) => pruneRuns(policy, configDir, now),
+ readRun: (options) => readRun(policy, options),
+ readSpan: (options) => readSpan(policy, options),
+ reportRun: (options) => reportRun(policy, options),
+ resumeSpan: (options) => resumeSpan(policy, options),
+ runDirectory: (configDir, runId) => runDirectory(policy, configDir, runId),
+ });
+}
+
+const lifecycle = createLifecycle({
+ pluginName: 'mobile-app',
+ trackedSkillNames: new Set(TRACKED_SKILL_NAMES),
+ exemptSkillNames: new Set(['telemetry']),
+ checkpointNames: getTelemetryCheckpointNames,
+ isAdditionalInfo: isTelemetryStaticInfo,
+ terminalStates: new Set(TELEMETRY_STATES.filter((state) => state !== 'started')),
+ errorClasses: new Set(TELEMETRY_ERROR_CLASSES),
+});
+
+module.exports = { GUID, createLifecycle, lifecycle, publishOwnedLock };
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry-config.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry-config.js
index 2fcaf0e4e..d13f898f6 100644
--- a/plugins/mobile-apps/scripts/lib/mobile-telemetry-config.js
+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry-config.js
@@ -11,9 +11,11 @@ const GENERIC_DISCLOSURE =
' when PAC is signed in.';
const MOBILE_DISCLOSURE =
'\u2139\ufe0f Usage telemetry records skill, plugin, agent, OS, Node, session, and\n' +
- ' correlation fields, plus invocation source and a random per-project app\n' +
- ' instance ID. Mobile Apps does not record PAC CLI version, Dataverse\n' +
- ' organization or Entra tenant IDs, or an Entra object ID.';
+ ' event/run/span IDs, measured durations, outcomes, and fixed error classes.\n' +
+ ' It can include verified environment, tenant, and Dataverse organization IDs,\n' +
+ ' plus a random app instance ID and invocation source. It does not collect an\n' +
+ ' Entra user/object ID, Dataverse user ID, username, or email address.\n' +
+ ' No business records, file contents, emails, tokens, or raw errors are sent.';
function run(args = process.argv.slice(2), env = process.env) {
const result = spawnSync(
diff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry-context.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry-context.js
new file mode 100644
index 000000000..fe20d4441
--- /dev/null
+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry-context.js
@@ -0,0 +1,139 @@
+'use strict';
+
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const { readProjectEnvironment } = require('./environment-resolution');
+
+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+function readJsonFile(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function guid(value) {
+ return typeof value === 'string' && GUID.test(value) ? value.toLowerCase() : undefined;
+}
+
+function readProjectTelemetryContext(projectRoot, options = {}) {
+ try {
+ const target = readProjectEnvironment(projectRoot);
+ const tenantId = guid(target?.tenantId);
+ if (
+ !options.lifecycle ||
+ !options.runId ||
+ !GUID.test(options.spanId || '') ||
+ !options.configDir ||
+ !target?.environmentId ||
+ !tenantId
+ ) {
+ return {};
+ }
+
+ const lifecycleOptions = { ...options, projectRoot };
+ let current = options.lifecycle.readSpan(lifecycleOptions);
+ const visited = new Set();
+ while (current.record && !visited.has(current.record.spanId)) {
+ visited.add(current.record.spanId);
+ const organization = readJsonFile(
+ path.join(current.directory, `${current.record.spanId}.environment.json`),
+ );
+ if (
+ organization?.spanId === current.record.spanId &&
+ organization.environmentId === target.environmentId &&
+ guid(organization.tenantId) === tenantId &&
+ guid(organization.orgId)
+ ) {
+ return {
+ environmentId: target.environmentId,
+ tenantId,
+ orgId: organization.orgId,
+ };
+ }
+ if (!current.record.parentSpanId) break;
+ current = options.lifecycle.readSpan({
+ ...lifecycleOptions,
+ spanId: current.record.parentSpanId,
+ });
+ }
+ return {};
+ } catch {
+ return {};
+ }
+}
+
+function writeAtomic(filename, value) {
+ if (JSON.stringify(readJsonFile(filename)) === JSON.stringify(value)) return;
+ const temporary = `${filename}.${crypto.randomUUID()}.tmp`;
+ try {
+ fs.writeFileSync(temporary, JSON.stringify(value), {
+ encoding: 'utf8',
+ flag: 'wx',
+ mode: 0o600,
+ });
+ fs.renameSync(temporary, filename);
+ } finally {
+ try {
+ fs.rmSync(temporary, { force: true });
+ } catch {
+ // Best-effort cleanup cannot alter a successful Dataverse operation.
+ }
+ }
+}
+
+function recordVerifiedDataverseOrganization(options) {
+ try {
+ const {
+ projectRoot,
+ environmentUrl,
+ lifecycle,
+ spanId,
+ token,
+ whoAmI,
+ } = options;
+ const target = readProjectEnvironment(projectRoot);
+ const tenantId = guid(target?.tenantId);
+ // WhoAmI supplies the organization ID while the token proves the selected
+ // tenant. User claims and the Dataverse UserId are never persisted.
+ if (
+ !target?.environmentId ||
+ !tenantId ||
+ !GUID.test(spanId || '') ||
+ typeof target.environmentUrl !== 'string' ||
+ target.environmentUrl.replace(/\/+$/, '').toLowerCase() !==
+ environmentUrl.replace(/\/+$/, '').toLowerCase()
+ ) {
+ return false;
+ }
+
+ const { directory, record: span } = lifecycle.readSpan(options);
+ const claims = JSON.parse(
+ Buffer.from(String(token).split('.')[1], 'base64url').toString('utf8'),
+ );
+ if (guid(claims.tid) !== tenantId) return false;
+
+ const orgId = guid(whoAmI?.OrganizationId);
+ if (orgId) {
+ writeAtomic(path.join(directory, `${span.spanId}.environment.json`), {
+ spanId: span.spanId,
+ environmentId: target.environmentId,
+ tenantId,
+ orgId,
+ });
+ }
+ return Boolean(orgId);
+ } catch {
+ return false;
+ }
+}
+
+module.exports = {
+ GUID,
+ readProjectTelemetryContext,
+ recordVerifiedDataverseOrganization,
+};
diff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js
index 8a24d7787..91b417f02 100644
--- a/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js
+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js
@@ -10,16 +10,40 @@ const path = require('node:path');
const { FIELD_TYPES, pick } = require('./telemetry/lib/events');
const { appendLocal, pluginLogDir } = require('./telemetry/lib/local-log');
const { findAppInstanceId, readTelemetryCluster } = require('./app-identity');
+const { lifecycle } = require('./mobile-lifecycle');
+const { readProjectTelemetryContext } = require('./mobile-telemetry-context');
const { resolveClusterEnvironment } = require('./telemetry/region/region-resolver');
const { loadResolver } = require('./telemetry/lib/resolver-loader');
const {
isTransmissionOptedOut,
telemetryOptOutEnvVarName,
} = require('./telemetry/lib/user-config');
+const {
+ TELEMETRY_ERROR_CLASSES,
+ TELEMETRY_STATES,
+ TRACKED_SKILL_NAMES,
+ isKnownTelemetryEvent,
+ isTelemetryStaticInfo,
+} = require('./mobileapp-hook-utils');
const PLACEHOLDER_IKEY = 'PLACEHOLDER_REPLACE_BEFORE_SHIPPING';
const DEFAULT_LOCAL_DIR = path.join(os.homedir(), '.power-platform-skills');
const RESERVED_META_FIELDS = new Set(['eventName', 'eventType', 'severity']);
+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const SOURCES = new Set(['prompt', 'pretool', 'checkpoint']);
+const ID_FIELDS = ['appInstanceId', 'runId', 'spanId', 'parentSpanId'];
+const AGENT_NAMES = new Set([
+ 'GitHub Copilot',
+ 'Copilot CLI',
+ 'Claude Code',
+ 'Codex',
+ 'OpenCode',
+ 'Hermes',
+ 'OpenClaw',
+]);
+const TRACKED_SKILLS = new Set(TRACKED_SKILL_NAMES);
+const ERROR_CLASSES = new Set(TELEMETRY_ERROR_CLASSES);
+const STATES = new Set(TELEMETRY_STATES);
function readPriorEvents(projectRoot, env = process.env) {
const configDir = env.POWER_PLATFORM_SKILLS_CONFIG_DIR || DEFAULT_LOCAL_DIR;
@@ -122,12 +146,127 @@ function readIkeyConfig(env) {
}
}
-function sanitizeData(data) {
- if (!data || typeof data !== 'object') return {};
+function sanitizeData(data, options = {}) {
+ if (
+ !data ||
+ data.pluginName !== 'mobile-app' ||
+ !TRACKED_SKILLS.has(data.skillName) ||
+ !isKnownTelemetryEvent(data.skillName, data.eventName)
+ ) {
+ 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];
+ if (typeof data[key] === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,127}$/.test(data[key])) {
+ filtered[key] = data[key];
+ }
+ }
+ delete filtered.errorDescription;
+ delete filtered.pacCliVersion;
+ delete filtered.orgId;
+ delete filtered.tenantId;
+
+ for (const name of ['pluginVersion', 'nodeVersion', 'aiAgentVersion', 'osVersion']) {
+ if (
+ filtered[name] !== undefined &&
+ !/^(?:unknown|v?\d[\dA-Za-z.+_-]{0,63})$/.test(filtered[name])
+ ) {
+ delete filtered[name];
+ }
+ }
+ if (
+ filtered.osName !== undefined &&
+ !['Windows', 'Mac', 'Linux'].includes(filtered.osName)
+ ) {
+ delete filtered.osName;
+ }
+ if (filtered.aiAgentName !== undefined && !AGENT_NAMES.has(filtered.aiAgentName)) {
+ delete filtered.aiAgentName;
+ }
+ for (const name of ['sessionId', 'correlationId']) {
+ if (
+ filtered[name] !== undefined &&
+ !/^[A-Za-z0-9_-]{1,128}$/.test(filtered[name])
+ ) {
+ delete filtered[name];
+ }
+ }
+ if (!ERROR_CLASSES.has(filtered.errorClass)) delete filtered.errorClass;
+ if (
+ typeof data.durationMs !== 'number' ||
+ !Number.isSafeInteger(data.durationMs) ||
+ data.durationMs < 0
+ ) {
+ delete filtered.durationMs;
+ }
+
+ const source = data.eventInfo &&
+ typeof data.eventInfo === 'object' &&
+ !Array.isArray(data.eventInfo)
+ ? data.eventInfo
+ : {};
+ const eventInfo = {};
+ for (const name of ID_FIELDS) {
+ if (typeof source[name] === 'string' && GUID.test(source[name])) {
+ eventInfo[name] = source[name].toLowerCase();
+ }
+ }
+ if (source.appInstanceId === null) eventInfo.appInstanceId = null;
+ if (SOURCES.has(source.invocationSource)) {
+ eventInfo.invocationSource = source.invocationSource;
}
+ if (isTelemetryStaticInfo(source.additionalInfo)) {
+ eventInfo.additionalInfo = source.additionalInfo;
+ }
+ if (['enabled', 'disabled'].includes(source.appInsightsSelection)) {
+ eventInfo.appInsightsSelection = source.appInsightsSelection;
+ }
+ if (source.schemaVersion === 2) {
+ if (
+ !eventInfo.runId ||
+ !eventInfo.spanId ||
+ !['skill', 'checkpoint'].includes(source.spanType) ||
+ !STATES.has(source.state) ||
+ !GUID.test(filtered.correlationId || '') ||
+ !GUID.test(filtered.sessionId || '')
+ ) {
+ return {};
+ }
+ eventInfo.schemaVersion = 2;
+ eventInfo.spanType = source.spanType;
+ eventInfo.state = source.state;
+ if (Number.isSafeInteger(source.attempt) && source.attempt > 0) {
+ eventInfo.attempt = source.attempt;
+ }
+ if (['measured', 'clock_invalid', 'not_applicable'].includes(source.timingStatus)) {
+ eventInfo.timingStatus = source.timingStatus;
+ }
+ if (source.timingStatus !== 'measured') delete filtered.durationMs;
+
+ // GUID shape alone cannot prove organization attribution. Recheck the local
+ // span/ancestor verification before logging and again when replaying to wire.
+ const verified = options.projectRoot && options.configDir
+ ? readProjectTelemetryContext(options.projectRoot, {
+ configDir: options.configDir,
+ lifecycle,
+ runId: eventInfo.runId,
+ spanId: eventInfo.spanId,
+ })
+ : {};
+ for (const name of ['orgId', 'tenantId']) {
+ if (typeof data[name] === 'string' && verified[name] &&
+ data[name].toLowerCase() === verified[name].toLowerCase()) {
+ filtered[name] = verified[name].toLowerCase();
+ }
+ }
+ if (typeof source.environmentId === 'string' && verified.environmentId &&
+ source.environmentId.toLowerCase() === verified.environmentId.toLowerCase()) {
+ eventInfo.environmentId = verified.environmentId.toLowerCase();
+ }
+ }
+
+ filtered.eventInfo = eventInfo;
return filtered;
}
@@ -146,6 +285,10 @@ function buildNormalEventData(data, time) {
device_Id: 'react-native',
event_Name: data.eventName || '',
session_Id: data.sessionId || '',
+ ...(data.tenantId ? { tenantId: data.tenantId } : {}),
+ ...(data.eventInfo?.environmentId
+ ? { environmentId: data.eventInfo.environmentId }
+ : {}),
severity: data.severity || 'Info',
timestamp: time,
customDimensions: JSON.stringify(dimensions),
@@ -200,11 +343,20 @@ async function dispatch(raw, env) {
return;
}
- const data = sanitizeData(event.data);
- const time = new Date().toISOString();
+ const replaying = Array.isArray(event.replay);
+ if (replaying && event.data?.pluginName !== 'mobile-app') return;
const configDir = env.POWER_PLATFORM_SKILLS_CONFIG_DIR || DEFAULT_LOCAL_DIR;
- if (!Array.isArray(event.replay)) {
- appendLocal({ time, name: event.name, data }, { configDir });
+ const context = {
+ configDir,
+ projectRoot: env.POWER_PLATFORM_SKILLS_PROJECT_ROOT || '',
+ };
+ const data = replaying ? { pluginName: 'mobile-app' } : sanitizeData(event.data, context);
+ if (!data.pluginName) return;
+ const time = typeof event.time === 'string' && Number.isFinite(Date.parse(event.time))
+ ? new Date(event.time).toISOString()
+ : new Date().toISOString();
+ if (!replaying) {
+ appendLocal({ time, name: cfg.event_stream_name, data }, { configDir });
}
if (isTransmissionOptedOut(configDir, data.pluginName, env)) return;
@@ -239,9 +391,17 @@ async function dispatch(raw, env) {
}
if (!iKey || iKey === PLACEHOLDER_IKEY || !collectorUrl) return;
+ records = records.flatMap((record) => {
+ const filtered = sanitizeData(record.data, context);
+ return filtered.pluginName &&
+ typeof record.time === 'string' &&
+ Number.isFinite(Date.parse(record.time))
+ ? [{ data: filtered, time: new Date(record.time).toISOString() }]
+ : [];
+ });
if (!records.length) return;
const body = records.map(record => JSON.stringify(
- buildEnvelope(sanitizeData(record.data), record.time, iKey, cfg.event_stream_name),
+ buildEnvelope(record.data, record.time, iKey, cfg.event_stream_name),
)).join('\n') + '\n';
const headers = {
'Content-Type': 'application/x-json-stream; charset=utf-8',
@@ -302,6 +462,7 @@ module.exports = {
buildEnvelope,
buildNormalEventData,
fireAndForget,
- readPriorEvents,
flushPriorEvents,
+ readPriorEvents,
+ sanitizeData,
};
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry.js
index 5c25041fd..52d2eff6b 100644
--- a/plugins/mobile-apps/scripts/lib/mobile-telemetry.js
+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry.js
@@ -10,10 +10,12 @@ const PLACEHOLDER_IKEY = 'PLACEHOLDER_REPLACE_BEFORE_SHIPPING';
const agentInfo = require('./telemetry/lib/agent-info');
const events = require('./telemetry/lib/events');
-const { fireAndForget } = require('./mobile-telemetry-dispatcher');
+const { lifecycle } = require('./mobile-lifecycle');
+const { fireAndForget, sanitizeData } = require('./mobile-telemetry-dispatcher');
const { loadResolver } = require('./telemetry/lib/resolver-loader');
const session = require('./telemetry/lib/session');
const { ensureAppInstanceId } = require('./app-identity');
+const { readProjectTelemetryContext } = require('./mobile-telemetry-context');
const { resolveProcessSessionId } = require('./mobile-telemetry-session');
function readPluginVersion() {
@@ -262,6 +264,19 @@ function commonFields(context, invocation, opts = {}) {
// Identity persistence must never block a skill invocation.
}
eventInfo.appInstanceId = appInstanceId;
+ const projectContext = opts.cwd
+ ? readProjectTelemetryContext(opts.cwd, {
+ lifecycle,
+ configDir: context.configDir,
+ runId: opts.runId,
+ spanId: opts.spanId,
+ })
+ : {};
+ if (projectContext.tenantId) fields.tenantId = projectContext.tenantId;
+ if (projectContext.orgId) fields.orgId = projectContext.orgId;
+ for (const name of ['environmentId']) {
+ if (projectContext[name]) eventInfo[name] = projectContext[name];
+ }
if (Object.keys(eventInfo).length) fields.eventInfo = eventInfo;
if (ai.aiAgentName) fields.aiAgentName = ai.aiAgentName;
@@ -332,9 +347,58 @@ function emitCheckpoint(context, invocation, opts = {}) {
return event;
}
+function emitLifecycle(context, span, opts = {}) {
+ const fields = commonFields(
+ { ...context, sessionId: span.sessionId },
+ {
+ skillName: span.skillName,
+ source: 'checkpoint',
+ additionalInfo: span.additionalInfo,
+ },
+ {
+ ...opts,
+ correlationId: span.eventId,
+ runId: span.runId,
+ spanId: span.spanId,
+ },
+ );
+ fields.eventInfo = {
+ ...fields.eventInfo,
+ schemaVersion: 2,
+ runId: span.runId,
+ spanId: span.spanId,
+ parentSpanId: span.parentSpanId,
+ spanType: span.spanType,
+ state: span.state,
+ attempt: span.attempt,
+ timingStatus: span.timingStatus,
+ };
+ if (span.durationMs !== undefined) fields.durationMs = span.durationMs;
+ if (span.errorClass) fields.errorClass = span.errorClass;
+ if (span.state === 'completed') fields.outcome = 'success';
+ if (span.state === 'failed') fields.outcome = 'failure';
+
+ const event = span.state === 'started'
+ ? events.buildSkillStarted(context.eventStreamName, fields)
+ : events.buildSkillCompleted(context.eventStreamName, fields);
+ event.data.eventName = `${span.spanType === 'skill' ? 'skill' : span.checkpointName}_${span.state}`;
+ event.data.severity = ['failed', 'blocked'].includes(span.state) ? 'Error' : 'Info';
+ event.data = sanitizeData(event.data, {
+ projectRoot: opts.cwd,
+ configDir: context.configDir,
+ });
+ if (!event.data.pluginName) return null;
+ event.time = span.time;
+ dispatch(context, event, opts);
+ return event;
+}
+
module.exports = {
createTelemetryContext,
emitAppInsightsSelection,
emitCheckpoint,
+ emitLifecycle,
emitSkillStarted,
+ getTelemetryConfigDir: configDir,
+ lifecycle,
};
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js b/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js
index b28e2a6a1..fdf6fb629 100644
--- a/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js
+++ b/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js
@@ -5,6 +5,35 @@ const path = require('node:path');
const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');
const SKILLS_DIR = path.join(PLUGIN_ROOT, 'skills');
+const TELEMETRY_STATES = Object.freeze([
+ 'started',
+ 'completed',
+ 'failed',
+ 'blocked',
+ 'cancelled',
+ 'skipped',
+ 'needs_context',
+]);
+const TELEMETRY_ERROR_CLASSES = Object.freeze([
+ 'auth_required',
+ 'permission_denied',
+ 'network_error',
+ 'timeout',
+ 'invalid_input',
+ 'validation_failed',
+ 'unsupported',
+ 'missing_dependency',
+ 'user_cancelled',
+ 'unknown',
+]);
+const TELEMETRY_STATIC_INFO = new Set([
+ 'app_not_initialized',
+ 'dependency_missing',
+ 'with_dataverse',
+ 'connector_only',
+ 'inline',
+ 'delegated',
+]);
function readInvocationMetadata(skillFile) {
let text;
@@ -101,11 +130,46 @@ function getTrackedSkillFromPrompt(prompt) {
return command ? detectTrackedSkill(command[1]) : null;
}
+function getTelemetryCheckpointNames(skillName) {
+ const normalized = trackedName(skillName);
+ if (!normalized || normalized === 'telemetry') return new Set();
+ let source;
+ try {
+ source = fs.readFileSync(path.join(SKILLS_DIR, normalized, 'SKILL.md'), 'utf8');
+ } catch {
+ return new Set();
+ }
+ return new Set(
+ [...source.matchAll(/\*\*Telemetry checkpoint: `([^`]+)`\*\*/g)]
+ .map((match) => match[1]),
+ );
+}
+
+function isKnownTelemetryEvent(skillName, eventName) {
+ const normalized = trackedName(skillName);
+ if (!normalized || typeof eventName !== 'string') return false;
+ if (eventName === 'app_insights_selection') return normalized === 'setup-app-insights';
+ if (new RegExp(`^skill_(?:${TELEMETRY_STATES.join('|')})$`).test(eventName)) return true;
+ const match = new RegExp(`^(.+)_(?:${TELEMETRY_STATES.join('|')})$`).exec(eventName);
+ if (!match) return false;
+ if (getTelemetryCheckpointNames(normalized).has(match[1])) return true;
+ return normalized === 'create-mobile-app' && ['planning', 'template_gate'].includes(match[1]);
+}
+
+function isTelemetryStaticInfo(value) {
+ return typeof value === 'string' && TELEMETRY_STATIC_INFO.has(value);
+}
+
module.exports = {
+ TELEMETRY_ERROR_CLASSES,
+ TELEMETRY_STATES,
TRACKED_SKILL_NAMES,
detectTrackedSkill,
+ getTelemetryCheckpointNames,
getTrackedSkillFromPrompt,
getTrackedSkillFromToolInput,
+ isKnownTelemetryEvent,
+ isTelemetryStaticInfo,
isInvocable,
readInvocationMetadata,
};
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/run-with-telemetry.sh b/plugins/mobile-apps/scripts/run-with-telemetry.sh
new file mode 100644
index 000000000..79f80261a
--- /dev/null
+++ b/plugins/mobile-apps/scripts/run-with-telemetry.sh
@@ -0,0 +1,135 @@
+#!/usr/bin/env bash
+
+# The real command is owned by this dependency-free shell boundary, not by the
+# telemetry module. A broken or hung emitter therefore cannot suppress work.
+
+execute=
+run_id=
+parent_span_id=
+project_root=
+command_args=()
+
+while (($# > 0)); do
+ case "$1" in
+ --execute)
+ execute=${2-}
+ shift 2
+ ;;
+ --run-id)
+ run_id=${2-}
+ shift 2
+ ;;
+ --parent-span-id)
+ parent_span_id=${2-}
+ shift 2
+ ;;
+ --project-root)
+ project_root=${2-}
+ shift 2
+ ;;
+ --)
+ shift
+ command_args=("$@")
+ break
+ ;;
+ *)
+ shift
+ ;;
+ esac
+done
+
+if ((${#command_args[@]} == 0)); then
+ printf '%s\n' 'Missing command after --' >&2
+ exit 1
+fi
+
+script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
+telemetry_cli="$script_dir/emit-telemetry-checkpoint.js"
+telemetry_node=${POWER_PLATFORM_SKILLS_NODE_BINARY:-node}
+
+if [[ -z "$project_root" ]]; then
+ project_root=$PWD
+fi
+if ! cd -- "$project_root"; then
+ exit 1
+fi
+project_root=$PWD
+
+run_telemetry_bounded() {
+ local output_file pid attempt status
+ output_file=$(mktemp "${TMPDIR:-/tmp}/mobile-telemetry.XXXXXX") || return 1
+ "$telemetry_node" "$telemetry_cli" "$@" >"$output_file" 2>/dev/null &
+ pid=$!
+ attempt=0
+ while kill -0 "$pid" 2>/dev/null; do
+ if ((attempt >= 20)); then
+ kill "$pid" 2>/dev/null || true
+ # A telemetry signal handler must not turn the final wait into a hang.
+ sleep 0.05
+ kill -KILL "$pid" 2>/dev/null || true
+ wait "$pid" 2>/dev/null || true
+ rm -f -- "$output_file"
+ return 1
+ fi
+ sleep 0.05
+ ((attempt += 1))
+ done
+ wait "$pid"
+ status=$?
+ if ((status == 0)); then
+ cat -- "$output_file"
+ fi
+ rm -f -- "$output_file"
+ return "$status"
+}
+
+span_id=
+if [[ -n "$execute" && -n "$run_id" && -n "$parent_span_id" ]]; then
+ start_output=$(run_telemetry_bounded \
+ "$execute|started" \
+ --run-id "$run_id" \
+ --parent-span-id "$parent_span_id" \
+ --project-root "$project_root") || start_output=
+ span_id=$(printf '%s\n' "$start_output" |
+ sed -n 's/.*"spanId":"\([0-9A-Fa-f-]*\)".*/\1/p' |
+ tail -n 1)
+fi
+
+guid_pattern='^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$'
+if [[ "$run_id" =~ $guid_pattern && "$span_id" =~ $guid_pattern ]]; then
+ export POWER_PLATFORM_SKILLS_MOBILE_RUN_ID=$run_id
+ export POWER_PLATFORM_SKILLS_MOBILE_SPAN_ID=$span_id
+ export POWER_PLATFORM_SKILLS_MOBILE_SKILL_SPAN_ID=$parent_span_id
+ export POWER_PLATFORM_SKILLS_PROJECT_ROOT=$project_root
+else
+ span_id=
+ unset POWER_PLATFORM_SKILLS_MOBILE_RUN_ID
+ unset POWER_PLATFORM_SKILLS_MOBILE_SPAN_ID
+ unset POWER_PLATFORM_SKILLS_MOBILE_SKILL_SPAN_ID
+ unset POWER_PLATFORM_SKILLS_PROJECT_ROOT
+fi
+
+"${command_args[@]}"
+exit_code=$?
+
+if [[ -n "$span_id" ]]; then
+ state=failed
+ error_args=(--error-class unknown)
+ if ((exit_code == 0)); then
+ state=completed
+ error_args=()
+ elif ((exit_code == 129 || exit_code == 130 || exit_code == 143)); then
+ state=cancelled
+ error_args=(--error-class user_cancelled)
+ elif ((exit_code == 126 || exit_code == 127)); then
+ error_args=(--error-class missing_dependency)
+ fi
+ run_telemetry_bounded \
+ "$execute|$state" \
+ --run-id "$run_id" \
+ --span-id "$span_id" \
+ --project-root "$project_root" \
+ "${error_args[@]}" >/dev/null || true
+fi
+
+exit "$exit_code"
diff --git a/plugins/mobile-apps/scripts/tests/mobile-telemetry-lifecycle.test.js b/plugins/mobile-apps/scripts/tests/mobile-telemetry-lifecycle.test.js
new file mode 100644
index 000000000..9e5db1790
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry-lifecycle.test.js
@@ -0,0 +1,1298 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawn, spawnSync } = require('node:child_process');
+const test = require('node:test');
+
+const {
+ createTelemetryContext,
+ emitLifecycle,
+ lifecycle,
+} = require('../lib/mobile-telemetry');
+const { publishOwnedLock } = require('../lib/mobile-lifecycle');
+const { sanitizeData } = require('../lib/mobile-telemetry-dispatcher');
+const {
+ readProjectTelemetryContext,
+ recordVerifiedDataverseOrganization,
+} = require('../lib/mobile-telemetry-context');
+const { readProjectEnvironment } = require('../lib/environment-resolution');
+const {
+ captureSuccessfulDataverseRequest,
+ runCommand,
+} = require('../emit-telemetry-checkpoint');
+
+const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');
+const COMMAND_RUNNER = path.join(PLUGIN_ROOT, 'scripts', 'run-with-telemetry.sh');
+const provisioned = {
+ instrumentationKey: 'test-mobile-key',
+ collector_url: 'https://example.invalid/OneCollector/1.0/',
+ event_stream_name: 'MobileAppsTestEvent',
+ disabled: false,
+};
+
+function tempProject(context) {
+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-lifecycle-'));
+ context.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));
+ return projectRoot;
+}
+
+function telemetryContext(projectRoot) {
+ const configDir = path.join(projectRoot, 'config');
+ const ikeyPath = path.join(configDir, 'ikey.json');
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(ikeyPath, JSON.stringify(provisioned));
+ return createTelemetryContext(
+ { session_id: '11111111-1111-4111-8111-111111111111' },
+ {
+ env: {
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,
+ },
+ },
+ );
+}
+
+test('durable lifecycle spans preserve identity and measured time', (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ now: 1000,
+ });
+ const step = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ runId: root.runId,
+ parentSpanId: root.spanId,
+ checkpointName: 'gather_app_requirements',
+ now: 1500,
+ });
+ assert.throws(() => lifecycle.resumeSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ spanId: step.spanId,
+ }), /invalid_resume/);
+
+ const completed = lifecycle.finishSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ spanId: step.spanId,
+ state: 'completed',
+ now: 4500,
+ });
+ assert.equal(completed.durationMs, 3000);
+ assert.equal(completed.timingStatus, 'measured');
+ assert.notEqual(completed.eventId, step.eventId);
+ assert.deepEqual(
+ lifecycle.finishSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ spanId: step.spanId,
+ state: 'completed',
+ now: 9000,
+ }),
+ completed,
+ );
+});
+
+test('durable lifecycle rejects unknown checkpoints and cross-project context', (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ now: 1000,
+ });
+ assert.throws(
+ () => lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ runId: root.runId,
+ parentSpanId: root.spanId,
+ checkpointName: 'customer_private_data',
+ }),
+ /invalid_checkpoint/,
+ );
+ assert.throws(
+ () => lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ runId: root.runId,
+ parentSpanId: root.spanId,
+ checkpointName: 'gather_app_requirements',
+ additionalInfo: 'customer_private_data',
+ }),
+ /invalid_additional_info/,
+ );
+ assert.throws(
+ () => lifecycle.finishSpan({
+ projectRoot: tempProject(context),
+ configDir,
+ runId: root.runId,
+ spanId: root.spanId,
+ state: 'completed',
+ }),
+ /invalid_context/,
+ );
+ const completed = lifecycle.finishSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ spanId: root.spanId,
+ state: 'completed',
+ now: 500,
+ });
+ assert.equal(completed.timingStatus, 'clock_invalid');
+ assert.equal(completed.durationMs, undefined);
+});
+
+test('lifecycle events filter dynamic customer content before dispatch', (context) => {
+ const projectRoot = tempProject(context);
+ const telemetry = telemetryContext(projectRoot);
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir: telemetry.configDir,
+ skillName: 'create-mobile-app',
+ now: 1000,
+ });
+ const completed = lifecycle.finishSpan({
+ projectRoot,
+ configDir: telemetry.configDir,
+ runId: root.runId,
+ spanId: root.spanId,
+ state: 'completed',
+ now: 2500,
+ });
+ const started = emitLifecycle(telemetry, root, {
+ cwd: projectRoot,
+ emit: () => {},
+ readAiAgent: () => ({}),
+ });
+ assert.equal(started.data.eventName, 'skill_started');
+ assert.equal(sanitizeData(started.data).eventName, 'skill_started');
+ let captured;
+ const event = emitLifecycle(telemetry, completed, {
+ cwd: projectRoot,
+ emit: (value) => {
+ captured = value;
+ },
+ readAiAgent: () => ({}),
+ });
+ assert.equal(captured, event);
+ assert.equal(event.data.eventName, 'skill_completed');
+ assert.equal(sanitizeData(event.data).eventName, 'skill_completed');
+ assert.equal(event.time, '1970-01-01T00:00:02.500Z');
+ assert.equal(event.data.durationMs, 1500);
+ assert.equal(event.data.eventInfo.runId, root.runId);
+
+ const filtered = sanitizeData({
+ ...event.data,
+ aiAgentName: '[email protected]',
+ aiAgentVersion: 'customer secret',
+ osVersion: '/private/host',
+ errorDescription: 'customer document contents',
+ errorClass: '[email protected]',
+ objectId: '33333333-3333-4333-8333-333333333333',
+ tenantId: 'not-an-id',
+ eventInfo: {
+ ...event.data.eventInfo,
+ aadObjectId: '33333333-3333-4333-8333-333333333333',
+ identitySource: 'dataverse',
+ principalType: 'user',
+ userId: '55555555-5555-4555-8555-555555555555',
+ prompt: 'private prompt',
+ filePath: '/private/customer-file',
+ email: '[email protected]',
+ nested: { token: 'secret' },
+ },
+ });
+ assert.equal(filtered.errorDescription, undefined);
+ assert.equal(filtered.errorClass, undefined);
+ assert.equal(filtered.tenantId, undefined);
+ assert.equal(filtered.objectId, undefined);
+ assert.equal(filtered.eventInfo.aadObjectId, undefined);
+ assert.equal(filtered.eventInfo.identitySource, undefined);
+ assert.equal(filtered.eventInfo.principalType, undefined);
+ assert.equal(filtered.eventInfo.userId, undefined);
+ assert.doesNotMatch(JSON.stringify(filtered), /private|customer|secret|33333333|55555555/);
+});
+
+test('command runner preserves exit code and propagates measured span context', (context) => {
+ const projectRoot = tempProject(context);
+ const telemetry = telemetryContext(projectRoot);
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir: telemetry.configDir,
+ skillName: 'create-mobile-app',
+ });
+ const capturedEnv = path.join(projectRoot, 'captured-env.json');
+ const commandScript = path.join(projectRoot, 'capture-runner-env.js');
+ fs.writeFileSync(commandScript, [
+ "'use strict';",
+ "const fs = require('node:fs');",
+ "fs.writeFileSync('captured-env.json', JSON.stringify({",
+ ' runId: process.env.POWER_PLATFORM_SKILLS_MOBILE_RUN_ID,',
+ ' spanId: process.env.POWER_PLATFORM_SKILLS_MOBILE_SPAN_ID,',
+ ' parentSpanId: process.env.POWER_PLATFORM_SKILLS_MOBILE_SKILL_SPAN_ID,',
+ ' projectRoot: process.env.POWER_PLATFORM_SKILLS_PROJECT_ROOT,',
+ '}));',
+ 'process.exit(7);',
+ '',
+ ].join('\n'));
+ const env = {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: telemetry.configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: telemetry.ikeyPath,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',
+ POWER_PLATFORM_SKILLS_NODE_BINARY: process.execPath,
+ };
+ const result = spawnSync('bash', [
+ COMMAND_RUNNER,
+ '--execute',
+ 'create-mobile-app|validate_fresh_template',
+ '--run-id',
+ root.runId,
+ '--parent-span-id',
+ root.spanId,
+ '--project-root',
+ projectRoot,
+ '--',
+ process.execPath,
+ commandScript,
+ ], {
+ encoding: 'utf8',
+ env,
+ timeout: 10_000,
+ });
+ assert.equal(result.status, 7, result.stderr);
+ const commandEnv = JSON.parse(fs.readFileSync(capturedEnv, 'utf8'));
+ assert.equal(commandEnv.runId, root.runId);
+ assert.match(commandEnv.spanId, /^[0-9a-f-]{36}$/);
+ assert.equal(commandEnv.parentSpanId, root.spanId);
+ assert.equal(path.resolve(commandEnv.projectRoot), path.resolve(projectRoot));
+
+ const report = lifecycle.reportRun({
+ projectRoot,
+ configDir: telemetry.configDir,
+ runId: root.runId,
+ });
+ assert.equal(report.supportId, root.runId);
+ assert.equal(
+ report.spans.find((span) => span.spanId === commandEnv.spanId).state,
+ 'failed',
+ );
+ assert.doesNotMatch(JSON.stringify(report), /captured-env|writeFileSync/);
+});
+
+test('command runner executes once when telemetry has syntax or import failures', (context) => {
+ for (const [name, emitter] of [
+ ['syntax', 'this is not valid JavaScript'],
+ ['import', "require('./missing-telemetry-module');"],
+ ]) {
+ const projectRoot = tempProject(context);
+ const wrapperRoot = fs.mkdtempSync(path.join(os.tmpdir(), `mobile-runner-${name}-`));
+ context.after(() => fs.rmSync(wrapperRoot, { recursive: true, force: true }));
+ fs.copyFileSync(COMMAND_RUNNER, path.join(wrapperRoot, 'run-with-telemetry.sh'));
+ fs.writeFileSync(
+ path.join(wrapperRoot, 'emit-telemetry-checkpoint.js'),
+ emitter,
+ );
+ const marker = path.join(projectRoot, `${name}.txt`);
+ const commandScript = path.join(projectRoot, `${name}-command.js`);
+ fs.writeFileSync(commandScript, [
+ "'use strict';",
+ "require('node:fs').appendFileSync(" +
+ `${JSON.stringify(`${name}.txt`)}, 'x');`,
+ 'process.exit(7);',
+ '',
+ ].join('\n'));
+ const result = spawnSync('bash', [
+ path.join(wrapperRoot, 'run-with-telemetry.sh'),
+ '--execute',
+ 'create-mobile-app|validate_fresh_template',
+ '--run-id',
+ '11111111-1111-4111-8111-111111111111',
+ '--parent-span-id',
+ '22222222-2222-4222-8222-222222222222',
+ '--project-root',
+ projectRoot,
+ '--',
+ process.execPath,
+ commandScript,
+ ], {
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_NODE_BINARY: process.execPath,
+ },
+ timeout: 10_000,
+ });
+ assert.equal(result.status, 7, `${name}: ${result.stderr}`);
+ assert.equal(fs.readFileSync(marker, 'utf8'), 'x');
+ }
+});
+
+test('command runner never falls back to a different execution directory', (context) => {
+ const projectRoot = tempProject(context);
+ const commandScript = path.join(projectRoot, 'wrong-directory-command.js');
+ fs.writeFileSync(commandScript, "require('node:fs').writeFileSync('ran.txt', 'x');");
+ const result = spawnSync('bash', [
+ COMMAND_RUNNER,
+ '--project-root', path.join(projectRoot, 'missing'),
+ '--', process.execPath, commandScript,
+ ], {
+ cwd: projectRoot,
+ encoding: 'utf8',
+ timeout: 10_000,
+ });
+ assert.equal(result.status, 1, result.stderr);
+ assert.notEqual(result.stderr, '');
+ assert.equal(fs.existsSync(path.join(projectRoot, 'ran.txt')), false);
+});
+
+test('command runner bounds a hung telemetry emitter even when it ignores SIGTERM', (context) => {
+ const projectRoot = tempProject(context);
+ const wrapperRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-runner-hang-'));
+ context.after(() => fs.rmSync(wrapperRoot, { recursive: true, force: true }));
+ const pidFile = path.join(wrapperRoot, 'emitter.pid');
+ fs.copyFileSync(COMMAND_RUNNER, path.join(wrapperRoot, 'run-with-telemetry.sh'));
+ fs.writeFileSync(
+ path.join(wrapperRoot, 'emit-telemetry-checkpoint.js'),
+ [
+ "require('node:fs').writeFileSync(require('node:path').join(__dirname, 'emitter.pid'), String(process.pid));",
+ "process.on('SIGTERM', () => {});",
+ 'setInterval(() => {}, 1000);',
+ ].join('\n'),
+ );
+ const marker = path.join(projectRoot, 'hang.txt');
+ const commandScript = path.join(projectRoot, 'hang-command.js');
+ fs.writeFileSync(commandScript, [
+ "'use strict';",
+ "require('node:fs').appendFileSync('hang.txt', 'x');",
+ 'process.exit(7);',
+ '',
+ ].join('\n'));
+ const startedAt = Date.now();
+ const result = spawnSync('bash', [
+ path.join(wrapperRoot, 'run-with-telemetry.sh'),
+ '--execute',
+ 'create-mobile-app|validate_fresh_template',
+ '--run-id',
+ '11111111-1111-4111-8111-111111111111',
+ '--parent-span-id',
+ '22222222-2222-4222-8222-222222222222',
+ '--project-root',
+ projectRoot,
+ '--',
+ process.execPath,
+ commandScript,
+ ], {
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_NODE_BINARY: process.execPath,
+ },
+ timeout: 10_000,
+ });
+ if (result.error && fs.existsSync(pidFile)) {
+ // If the wrapper regresses, its timeout kills only Bash, not the emitter.
+ const pid = Number(fs.readFileSync(pidFile, 'utf8'));
+ try {
+ process.kill(pid, 'SIGKILL');
+ } catch (error) {
+ if (error.code !== 'ESRCH') throw error;
+ }
+ }
+ assert.equal(result.status, 7, result.stderr);
+ assert.equal(fs.readFileSync(marker, 'utf8'), 'x');
+ assert.ok(Date.now() - startedAt < 3000, 'telemetry hang must stay bounded');
+});
+
+test('tracked checkpoints preserve allowlisted static classifications', (context) => {
+ const projectRoot = tempProject(context);
+ const telemetry = telemetryContext(projectRoot);
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir: telemetry.configDir,
+ skillName: 'create-mobile-app',
+ });
+ const spans = [];
+ const overrides = {
+ createTelemetryContext: () => telemetry,
+ emitLifecycle: (_telemetry, span) => spans.push(span),
+ };
+ const started = runCommand([
+ 'create-mobile-app|gather_app_requirements|started|with_dataverse',
+ '--run-id', root.runId,
+ '--parent-span-id', root.spanId,
+ '--project-root', projectRoot,
+ ], overrides);
+ const completed = runCommand([
+ 'create-mobile-app|gather_app_requirements|completed',
+ '--run-id', root.runId,
+ '--span-id', started.spanId,
+ '--project-root', projectRoot,
+ ], overrides);
+
+ assert.equal(started.state, 'started');
+ assert.equal(completed.state, 'completed');
+ assert.equal(spans.length, 2);
+ assert.equal(spans[0].additionalInfo, 'with_dataverse');
+ assert.equal(spans[1].additionalInfo, 'with_dataverse');
+
+ const event = emitLifecycle(telemetry, spans[1], {
+ cwd: projectRoot,
+ emit: () => {},
+ readAiAgent: () => ({}),
+ });
+ assert.equal(event.data.eventName, 'gather_app_requirements_completed');
+ assert.equal(event.data.eventInfo.additionalInfo, 'with_dataverse');
+ const report = lifecycle.reportRun({
+ projectRoot,
+ configDir: telemetry.configDir,
+ runId: root.runId,
+ });
+ assert.equal(
+ report.spans.find((span) => span.spanId === started.spanId).additionalInfo,
+ 'with_dataverse',
+ );
+});
+
+test('checkpoint CLI carries lifecycle context across fresh processes', (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const ikeyPath = path.join(configDir, 'ikey.json');
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(ikeyPath, JSON.stringify(provisioned));
+ const env = {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',
+ };
+ const cli = path.join(PLUGIN_ROOT, 'scripts', 'emit-telemetry-checkpoint.js');
+ const run = (...args) => {
+ const result = spawnSync(process.execPath, [cli, ...args], {
+ cwd: projectRoot,
+ encoding: 'utf8',
+ env,
+ timeout: 10000,
+ });
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(result.stdout);
+ };
+
+ const root = run(
+ '--begin',
+ 'create-mobile-app',
+ '--project-root',
+ projectRoot,
+ );
+ const step = run(
+ 'create-mobile-app|gather_app_requirements|started',
+ '--run-id',
+ root.runId,
+ '--parent-span-id',
+ root.spanId,
+ '--project-root',
+ projectRoot,
+ );
+ const completedStep = run(
+ 'create-mobile-app|gather_app_requirements|completed',
+ '--run-id',
+ root.runId,
+ '--span-id',
+ step.spanId,
+ '--project-root',
+ projectRoot,
+ );
+ assert.equal(completedStep.state, 'completed');
+ assert.equal(completedStep.runId, root.runId);
+
+ const completedRoot = run(
+ '--finish',
+ 'completed',
+ '--run-id',
+ root.runId,
+ '--span-id',
+ root.spanId,
+ '--project-root',
+ projectRoot,
+ );
+ assert.equal(completedRoot.state, 'completed');
+
+ const report = run(
+ '--report',
+ '--run-id',
+ root.runId,
+ '--project-root',
+ projectRoot,
+ );
+ assert.equal(report.supportId, root.runId);
+ assert.equal(report.state, 'completed');
+ assert.deepEqual(
+ report.spans.map((span) => span.state).sort(),
+ ['completed', 'completed'],
+ );
+
+ const paused = run(
+ '--begin',
+ 'create-mobile-app',
+ '--project-root',
+ projectRoot,
+ );
+ const pause = run(
+ '--finish',
+ 'needs_context',
+ '--run-id',
+ paused.runId,
+ '--span-id',
+ paused.spanId,
+ '--project-root',
+ projectRoot,
+ );
+ assert.equal(pause.state, 'needs_context');
+
+ const resumed = run(
+ '--resume',
+ paused.spanId,
+ '--run-id',
+ paused.runId,
+ '--project-root',
+ projectRoot,
+ );
+ assert.equal(resumed.state, 'started');
+ assert.notEqual(resumed.spanId, paused.spanId);
+ const resumedComplete = run(
+ '--finish',
+ 'completed',
+ '--run-id',
+ paused.runId,
+ '--span-id',
+ resumed.spanId,
+ '--project-root',
+ projectRoot,
+ );
+ assert.equal(resumedComplete.state, 'completed');
+ const resumedReport = run(
+ '--report',
+ '--run-id',
+ paused.runId,
+ '--project-root',
+ projectRoot,
+ );
+ assert.equal(resumedReport.state, 'completed');
+ assert.deepEqual(
+ resumedReport.spans
+ .map((span) => [span.attempt, span.state])
+ .sort((left, right) => left[0] - right[0]),
+ [[1, 'needs_context'], [2, 'completed']],
+ );
+});
+
+test('successful parent completion requires every child to finish', (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ });
+ const child = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ parentSpanId: root.spanId,
+ skillName: 'create-mobile-app',
+ checkpointName: 'gather_app_requirements',
+ });
+ const finishRoot = {
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ spanId: root.spanId,
+ state: 'completed',
+ };
+ assert.throws(() => lifecycle.finishSpan(finishRoot), /children_pending/);
+ lifecycle.finishSpan({
+ ...finishRoot,
+ spanId: child.spanId,
+ state: 'cancelled',
+ errorClass: 'user_cancelled',
+ });
+ assert.equal(lifecycle.finishSpan(finishRoot).state, 'completed');
+});
+
+test('nested needs-context attempts keep their parent open until resumed', (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ });
+ const child = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ parentSpanId: root.spanId,
+ skillName: 'add-dataverse',
+ });
+ lifecycle.finishSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ spanId: child.spanId,
+ state: 'needs_context',
+ });
+ const finishRoot = {
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ spanId: root.spanId,
+ state: 'completed',
+ };
+ assert.throws(() => lifecycle.finishSpan(finishRoot), /children_pending/);
+
+ const resumed = lifecycle.resumeSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ spanId: child.spanId,
+ });
+ assert.equal(resumed.parentSpanId, root.spanId);
+ assert.equal(resumed.retryOfSpanId, child.spanId);
+ assert.equal(resumed.attempt, 2);
+ assert.throws(() => lifecycle.finishSpan(finishRoot), /children_pending/);
+ assert.throws(() => lifecycle.resumeSpan({
+ projectRoot, configDir, runId: root.runId, spanId: child.spanId,
+ }), /invalid_retry/);
+
+ lifecycle.finishSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ spanId: resumed.spanId,
+ state: 'needs_context',
+ });
+ const third = lifecycle.resumeSpan({
+ projectRoot, configDir, runId: root.runId, spanId: resumed.spanId,
+ });
+ assert.equal(third.attempt, 3);
+ assert.equal(third.retryOfSpanId, resumed.spanId);
+ lifecycle.finishSpan({
+ projectRoot, configDir, runId: root.runId, spanId: third.spanId,
+ state: 'completed',
+ });
+ assert.equal(lifecycle.finishSpan(finishRoot).state, 'completed');
+});
+
+test('checkpoint needs_context resumes through an explicit retry without blocking completion', (context) => {
+ const projectRoot = tempProject(context);
+ const telemetry = telemetryContext(projectRoot);
+ const overrides = {
+ env: { POWER_PLATFORM_SKILLS_CONFIG_DIR: telemetry.configDir },
+ createTelemetryContext: () => telemetry,
+ emitLifecycle: () => {},
+ };
+ const run = (...args) => runCommand([...args, '--project-root', projectRoot], overrides);
+ const root = run('--begin', 'create-mobile-app');
+ const step = run(
+ 'create-mobile-app|gather_app_requirements|started',
+ '--run-id', root.runId, '--parent-span-id', root.spanId,
+ );
+ assert.equal(run(
+ 'create-mobile-app|gather_app_requirements|needs_context',
+ '--run-id', root.runId, '--span-id', step.spanId,
+ ).state, 'needs_context');
+ const finishParent = () => run(
+ '--finish', 'completed', '--run-id', root.runId, '--span-id', root.spanId,
+ );
+ assert.equal(finishParent().reason, 'children_pending');
+ const retry = run(
+ 'create-mobile-app|gather_app_requirements|started',
+ '--run-id', root.runId, '--parent-span-id', root.spanId,
+ '--retry-of', step.spanId,
+ );
+ assert.equal(retry.state, 'started');
+ assert.notEqual(retry.spanId, step.spanId);
+ assert.equal(finishParent().reason, 'children_pending');
+ assert.equal(run(
+ 'create-mobile-app|gather_app_requirements|completed',
+ '--run-id', root.runId, '--span-id', retry.spanId,
+ ).state, 'completed');
+ assert.equal(finishParent().state, 'completed');
+ const report = run('--report', '--run-id', root.runId);
+ assert.equal(report.state, 'completed');
+ assert.equal(report.spans.find((span) => span.spanId === step.spanId).state, 'needs_context');
+ const retried = report.spans.find((span) => span.spanId === retry.spanId);
+ assert.equal(retried.retryOfSpanId, step.spanId);
+ assert.equal(retried.attempt, 2);
+});
+
+test('run lock serializes parent completion and retry creation across processes', async (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const ikeyPath = path.join(configDir, 'ikey.json');
+ const cli = path.join(PLUGIN_ROOT, 'scripts', 'emit-telemetry-checkpoint.js');
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(ikeyPath, JSON.stringify(provisioned));
+ const env = {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',
+ };
+ const runCli = (args) => new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [cli, ...args], {
+ cwd: projectRoot,
+ env,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.setEncoding('utf8');
+ child.stderr.setEncoding('utf8');
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
+ child.on('error', reject);
+ child.on('close', (code) => resolve({ code, stdout, stderr }));
+ });
+
+ for (let attempt = 0; attempt < 8; attempt += 1) {
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ });
+ const [childResult, parentResult] = await Promise.all([
+ runCli([
+ 'create-mobile-app|gather_app_requirements|started',
+ '--run-id', root.runId,
+ '--parent-span-id', root.spanId,
+ '--project-root', projectRoot,
+ ]),
+ runCli([
+ '--finish', 'completed',
+ '--run-id', root.runId,
+ '--span-id', root.spanId,
+ '--project-root', projectRoot,
+ ]),
+ ]);
+ assert.equal(childResult.code, 0, childResult.stderr);
+ assert.equal(parentResult.code, 0, parentResult.stderr);
+
+ const report = lifecycle.reportRun({ projectRoot, configDir, runId: root.runId });
+ const rootSpan = report.spans.find((span) => span.spanId === root.spanId);
+ const openChild = report.spans.some(
+ (span) => span.parentSpanId === root.spanId && span.state === 'incomplete',
+ );
+ assert.equal(
+ rootSpan.state === 'completed' && openChild,
+ false,
+ 'a completed parent must never gain an incomplete child',
+ );
+ }
+
+ for (const spanType of ['skill', 'checkpoint']) {
+ const root = lifecycle.beginSpan({
+ projectRoot, configDir, skillName: 'create-mobile-app',
+ });
+ const child = lifecycle.beginSpan({
+ projectRoot, configDir, runId: root.runId, parentSpanId: root.spanId,
+ skillName: 'create-mobile-app',
+ ...(spanType === 'checkpoint' ? { checkpointName: 'gather_app_requirements' } : {}),
+ });
+ const options = { projectRoot, configDir, runId: root.runId };
+ lifecycle.finishSpan({ ...options, spanId: child.spanId, state: 'needs_context' });
+ const args = [
+ ...(spanType === 'skill'
+ ? ['--resume', child.spanId]
+ : [
+ 'create-mobile-app|gather_app_requirements|started',
+ '--parent-span-id', root.spanId, '--retry-of', child.spanId,
+ ]),
+ '--run-id', root.runId, '--project-root', projectRoot,
+ ];
+ const results = await Promise.all([runCli(args), runCli(args)]);
+ const attempts = results.map((result) => {
+ assert.equal(result.code, 0, result.stderr);
+ return JSON.parse(result.stdout);
+ });
+ assert.equal(attempts.filter((attempt) => attempt.state === 'started').length, 1);
+ assert.equal(attempts.filter((attempt) => attempt.reason === 'invalid_retry').length, 1);
+ const retry = attempts.find((attempt) => attempt.state === 'started');
+ lifecycle.finishSpan({ ...options, spanId: retry.spanId, state: 'completed' });
+ const repeated = await runCli(args);
+ assert.equal(repeated.code, 0, repeated.stderr);
+ assert.equal(JSON.parse(repeated.stdout).reason, 'invalid_retry');
+ assert.equal(lifecycle.finishSpan({
+ ...options, spanId: root.spanId, state: 'completed',
+ }).state, 'completed');
+ const report = lifecycle.reportRun(options);
+ assert.equal(report.spans.length, 3);
+ assert.equal(report.state, 'completed');
+ }
+});
+
+test('run lock times out instead of writing through another process lock', (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ });
+ const lockPath = path.join(
+ lifecycle.runDirectory(configDir, root.runId),
+ '.lifecycle.lock',
+ );
+ fs.writeFileSync(lockPath, JSON.stringify({
+ pid: process.pid,
+ token: '11111111-1111-4111-8111-111111111111',
+ acquiredAtMs: Date.now(),
+ }));
+ try {
+ assert.throws(() => lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ parentSpanId: root.spanId,
+ skillName: 'create-mobile-app',
+ checkpointName: 'gather_app_requirements',
+ lockTimeoutMs: 0,
+ }), /lock_timeout/);
+ } finally {
+ fs.rmSync(lockPath, { force: true });
+ }
+});
+
+test('lock publication treats transient EEXIST as contention after release', (context) => {
+ const directory = tempProject(context);
+ const lockPath = path.join(directory, '.lifecycle.lock');
+ const pendingPaths = [];
+ const fakeFs = {
+ writeFileSync(filename, contents, options) {
+ pendingPaths.push(filename);
+ fs.writeFileSync(filename, contents, options);
+ },
+ linkSync() {
+ // Simulate another process winning and releasing before this catch runs.
+ throw Object.assign(new Error('already existed'), { code: 'EEXIST' });
+ },
+ rmSync(filename, options) {
+ fs.rmSync(filename, options);
+ },
+ };
+ assert.equal(
+ publishOwnedLock(
+ lockPath,
+ '11111111-1111-4111-8111-111111111111',
+ { fs: fakeFs },
+ ),
+ false,
+ );
+ assert.equal(fs.existsSync(lockPath), false);
+ assert.ok(pendingPaths.every((filename) => !fs.existsSync(filename)));
+});
+
+test('run lock recovers when its recorded owner process is dead', (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ });
+ const runDirectory = lifecycle.runDirectory(configDir, root.runId);
+ const lockPath = path.join(runDirectory, '.lifecycle.lock');
+ const recoveryPath = path.join(runDirectory, '.lifecycle.lock.recovery');
+ fs.writeFileSync(lockPath, JSON.stringify({
+ pid: 424242,
+ token: '11111111-1111-4111-8111-111111111111',
+ acquiredAtMs: Date.now() - 5000,
+ }));
+ fs.linkSync(lockPath, recoveryPath);
+
+ const child = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ parentSpanId: root.spanId,
+ skillName: 'create-mobile-app',
+ checkpointName: 'gather_app_requirements',
+ isProcessAlive: () => false,
+ });
+ assert.equal(child.parentSpanId, root.spanId);
+ assert.equal(fs.existsSync(lockPath), false);
+});
+
+test('verified Dataverse context excludes user identity and token claims', (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const environmentId = '11111111-1111-4111-8111-111111111111';
+ const tenantId = '22222222-2222-4222-8222-222222222222';
+ const orgId = '44444444-4444-4444-8444-444444444444';
+ const environmentUrl = 'https://contoso.crm.dynamics.com';
+ fs.writeFileSync(
+ path.join(projectRoot, 'power.config.json'),
+ JSON.stringify({ environmentId }),
+ );
+ fs.writeFileSync(
+ path.join(projectRoot, '.resolved-environment.json'),
+ JSON.stringify({
+ environmentId,
+ tenantId,
+ environmentUrl,
+ displayName: 'PRIVATE CUSTOMER NAME',
+ }),
+ );
+ const root = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ skillName: 'create-mobile-app',
+ });
+ const verifiedStep = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ parentSpanId: root.spanId,
+ skillName: 'create-mobile-app',
+ checkpointName: 'select_app_environment',
+ });
+ const descendant = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ parentSpanId: verifiedStep.spanId,
+ skillName: 'add-dataverse',
+ });
+ const sibling = lifecycle.beginSpan({
+ projectRoot,
+ configDir,
+ runId: root.runId,
+ parentSpanId: root.spanId,
+ skillName: 'create-mobile-app',
+ checkpointName: 'gather_app_requirements',
+ });
+ const token = `header.${Buffer.from(JSON.stringify({
+ oid: '33333333-3333-4333-8333-333333333333',
+ tid: tenantId,
+ exp: Math.floor(Date.now() / 1000) + 300,
+ scp: 'user_impersonation',
+ preferred_username: '[email protected]',
+ })).toString('base64url')}.signature`;
+ const options = {
+ projectRoot,
+ configDir,
+ lifecycle,
+ runId: root.runId,
+ spanId: verifiedStep.spanId,
+ };
+ assert.deepEqual(readProjectTelemetryContext(projectRoot, options), {});
+ assert.deepEqual(readProjectTelemetryContext(projectRoot), {});
+ let unverified;
+ emitLifecycle({
+ configDir,
+ env: {},
+ eventStreamName: 'event',
+ sessionId: root.sessionId,
+ }, root, {
+ cwd: projectRoot,
+ emit: (value) => {
+ unverified = value;
+ },
+ readAiAgent: () => ({}),
+ });
+ assert.equal(unverified.data.orgId, undefined);
+ assert.equal(unverified.data.tenantId, undefined);
+ assert.equal(unverified.data.eventInfo.environmentId, undefined);
+
+ const ikeyPath = path.join(configDir, 'ikey.json');
+ fs.writeFileSync(ikeyPath, JSON.stringify(provisioned));
+ assert.equal(captureSuccessfulDataverseRequest(
+ environmentUrl,
+ token,
+ {
+ OrganizationId: orgId,
+ UserId: '55555555-5555-4555-8555-555555555555',
+ },
+ {
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,
+ POWER_PLATFORM_SKILLS_MOBILE_RUN_ID: root.runId,
+ POWER_PLATFORM_SKILLS_MOBILE_SPAN_ID: verifiedStep.spanId,
+ POWER_PLATFORM_SKILLS_PROJECT_ROOT: projectRoot,
+ },
+ ), true);
+ assert.deepEqual(readProjectTelemetryContext(projectRoot, options), {
+ environmentId,
+ tenantId,
+ orgId,
+ });
+ assert.deepEqual(readProjectTelemetryContext(projectRoot, {
+ ...options,
+ spanId: descendant.spanId,
+ }), {
+ environmentId,
+ tenantId,
+ orgId,
+ });
+ assert.deepEqual(readProjectTelemetryContext(projectRoot, {
+ ...options,
+ spanId: root.spanId,
+ }), {});
+ assert.deepEqual(readProjectTelemetryContext(projectRoot, {
+ ...options,
+ spanId: sibling.spanId,
+ }), {});
+ let captured;
+ const event = emitLifecycle({
+ configDir,
+ env: {},
+ eventStreamName: 'event',
+ sessionId: root.sessionId,
+ }, verifiedStep, {
+ cwd: projectRoot,
+ emit: (value) => {
+ captured = value;
+ },
+ readAiAgent: () => ({}),
+ });
+ assert.equal(captured, event);
+ assert.equal(event.data.orgId, orgId);
+ assert.equal(event.data.tenantId, tenantId);
+ assert.equal(event.data.eventInfo.environmentId, environmentId);
+ assert.equal(event.data.eventInfo.aadObjectId, undefined);
+ assert.equal(event.data.eventInfo.userId, undefined);
+
+ let siblingEvent;
+ emitLifecycle({
+ configDir,
+ env: {},
+ eventStreamName: 'event',
+ sessionId: root.sessionId,
+ }, sibling, {
+ cwd: projectRoot,
+ emit: (value) => {
+ siblingEvent = value;
+ },
+ readAiAgent: () => ({}),
+ });
+ assert.equal(siblingEvent.data.orgId, undefined);
+ assert.equal(siblingEvent.data.tenantId, undefined);
+ assert.equal(siblingEvent.data.eventInfo.environmentId, undefined);
+
+ const runDirectory = lifecycle.runDirectory(configDir, root.runId);
+ const recorded = fs.readdirSync(runDirectory)
+ .map((name) => fs.readFileSync(path.join(runDirectory, name), 'utf8'))
+ .join('\n');
+ assert.doesNotMatch(
+ recorded,
+ /PRIVATE|private@example|signature|user_impersonation|55555555|33333333/,
+ );
+});
+
+test('verified Dataverse context requires matching valid tenant GUIDs regardless of case', (context) => {
+ const projectRoot = tempProject(context);
+ const configDir = path.join(projectRoot, 'config');
+ const environmentId = '11111111-1111-4111-8111-111111111111';
+ const tenantId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+ const orgId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+ const environmentUrl = 'https://contoso.crm.dynamics.com';
+ const cases = [
+ [null, null, false],
+ ['malformed', 'malformed', false],
+ [tenantId, 'malformed', false],
+ ['malformed', tenantId, false],
+ [tenantId, null, false],
+ [null, tenantId, false],
+ [tenantId, orgId, false],
+ [tenantId, tenantId, true],
+ [tenantId.toUpperCase(), tenantId, true],
+ [tenantId, tenantId.toUpperCase(), true],
+ [tenantId.toUpperCase(), tenantId.toUpperCase(), true],
+ ];
+ for (const [cachedTenant, claimTenant, expected] of cases) {
+ fs.writeFileSync(path.join(projectRoot, '.resolved-environment.json'), JSON.stringify({
+ environmentId, tenantId: cachedTenant, environmentUrl,
+ }));
+ const root = lifecycle.beginSpan({
+ projectRoot, configDir, skillName: 'create-mobile-app',
+ });
+ const options = {
+ projectRoot, configDir, lifecycle, runId: root.runId, spanId: root.spanId,
+ };
+ const token = `header.${Buffer.from(JSON.stringify({ tid: claimTenant })).toString('base64url')}.signature`;
+ assert.equal(recordVerifiedDataverseOrganization({
+ ...options, environmentUrl, token, whoAmI: { OrganizationId: orgId },
+ }), expected);
+ const filename = path.join(
+ lifecycle.runDirectory(configDir, root.runId),
+ `${root.spanId}.environment.json`,
+ );
+ assert.equal(fs.existsSync(filename), expected);
+ assert.deepEqual(readProjectTelemetryContext(projectRoot, options), expected
+ ? { environmentId, tenantId, orgId }
+ : {});
+ if (expected) {
+ assert.equal(JSON.parse(fs.readFileSync(filename, 'utf8')).tenantId, tenantId);
+ }
+ }
+});
+
+test('dispatcher revalidates organization attribution before local logging and replay transmission', (context) => {
+ const projectRoot = tempProject(context);
+ const telemetry = telemetryContext(projectRoot);
+ const environmentId = '11111111-1111-4111-8111-111111111111';
+ const tenantId = '22222222-2222-4222-8222-222222222222';
+ const orgId = '44444444-4444-4444-8444-444444444444';
+ const forgedId = '99999999-9999-4999-8999-999999999999';
+ const environmentUrl = 'https://contoso.crm.dynamics.com';
+ const targetPath = path.join(projectRoot, '.resolved-environment.json');
+ const target = { environmentId, tenantId, environmentUrl };
+ fs.writeFileSync(targetPath, JSON.stringify(target));
+ const root = lifecycle.beginSpan({
+ projectRoot, configDir: telemetry.configDir, skillName: 'create-mobile-app',
+ });
+ const stepOptions = {
+ projectRoot, configDir: telemetry.configDir, skillName: 'create-mobile-app',
+ runId: root.runId, parentSpanId: root.spanId,
+ };
+ const step = lifecycle.beginSpan({
+ ...stepOptions, checkpointName: 'select_app_environment',
+ });
+ const sibling = lifecycle.beginSpan({
+ ...stepOptions, checkpointName: 'gather_app_requirements',
+ });
+ const probePath = path.join(projectRoot, 'dispatch-probe.json');
+ const expected = { orgId, tenantId, environmentId };
+ const eventFor = (span, claimed = expected) => {
+ const event = emitLifecycle(telemetry, span, {
+ cwd: projectRoot, emit: () => {}, readAiAgent: () => ({}),
+ });
+ return {
+ ...event,
+ data: {
+ ...event.data,
+ orgId: claimed.orgId,
+ tenantId: claimed.tenantId,
+ eventInfo: { ...event.data.eventInfo, environmentId: claimed.environmentId },
+ },
+ };
+ };
+ const assertIds = (data, ids) => {
+ assert.equal(data.orgId, ids.orgId);
+ assert.equal(data.tenantId, ids.tenantId);
+ assert.equal(data.eventInfo.environmentId, ids.environmentId);
+ };
+ const send = (event, ids, directory = projectRoot, replay = false) => {
+ fs.rmSync(probePath, { force: true });
+ const result = spawnSync(process.execPath, [
+ path.join(PLUGIN_ROOT, 'scripts/lib/mobile-telemetry-dispatcher.js'),
+ ], {
+ cwd: os.tmpdir(),
+ encoding: 'utf8',
+ timeout: 5000,
+ input: JSON.stringify(replay
+ ? { data: { pluginName: 'mobile-app' }, replay: [event] }
+ : event),
+ env: {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: telemetry.configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: telemetry.ikeyPath,
+ POWER_PLATFORM_SKILLS_PROJECT_ROOT: directory,
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '',
+ },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ const probe = JSON.parse(fs.readFileSync(probePath, 'utf8'));
+ const envelope = JSON.parse(probe.body);
+ assertIds(JSON.parse(envelope.data.customDimensions), ids);
+ assert.equal(envelope.data.tenantId, ids.tenantId);
+ assert.equal(envelope.data.environmentId, ids.environmentId);
+ if (!replay) {
+ const log = path.join(telemetry.configDir, 'telemetry/mobile-app/sessions', root.sessionId, 'events.jsonl');
+ const records = fs.readFileSync(log, 'utf8').trim().split('\n').map(JSON.parse);
+ assertIds(records.at(-1).data, ids);
+ }
+ };
+
+ send(eventFor(step), {});
+ const token = `header.${Buffer.from(JSON.stringify({ tid: tenantId })).toString('base64url')}.signature`;
+ assert.equal(recordVerifiedDataverseOrganization({
+ projectRoot, configDir: telemetry.configDir, lifecycle,
+ runId: root.runId, spanId: step.spanId, environmentUrl, token,
+ whoAmI: { OrganizationId: orgId },
+ }), true);
+
+ const verified = eventFor(step);
+ send(verified, expected);
+ send(verified, expected, projectRoot, true);
+ const forged = eventFor(step, { orgId: forgedId, tenantId: forgedId, environmentId: forgedId });
+ send(forged, {});
+ send(forged, {}, projectRoot, true);
+ send(eventFor(sibling), {});
+ send(verified, {}, '');
+ send(verified, {}, tempProject(context));
+ send({
+ ...verified,
+ data: { ...verified.data, eventInfo: { environmentId } },
+ }, {});
+ send({
+ ...verified,
+ data: { ...verified.data, eventInfo: { ...verified.data.eventInfo, runId: forgedId } },
+ }, {});
+ fs.writeFileSync(targetPath, JSON.stringify({ ...target, environmentId: forgedId }));
+ send(verified, {});
+ send(verified, {}, projectRoot, true);
+ fs.writeFileSync(targetPath, JSON.stringify(target));
+ fs.unlinkSync(path.join(
+ lifecycle.runDirectory(telemetry.configDir, root.runId),
+ `${step.spanId}.environment.json`,
+ ));
+ send(verified, {});
+ send(verified, {}, projectRoot, true);
+});
+
+test('project environment rejects malformed cached environment IDs', (context) => {
+ const projectRoot = tempProject(context);
+ fs.writeFileSync(path.join(projectRoot, '.resolved-environment.json'), JSON.stringify({
+ environmentId: '../outside',
+ environmentUrl: 'https://contoso.crm.dynamics.com',
+ tenantId: '22222222-2222-4222-8222-222222222222',
+ }));
+ assert.equal(readProjectEnvironment(projectRoot), null);
+});
+
+test('mobile telemetry reuses canonical helpers without parallel modules', () => {
+ const lib = path.join(PLUGIN_ROOT, 'scripts', 'lib');
+ for (const obsolete of [
+ 'mobile-telemetry-fields.js',
+ 'mobile-telemetry-identity.js',
+ 'mobile-telemetry-lifecycle.js',
+ ]) {
+ assert.equal(fs.existsSync(path.join(lib, obsolete)), false, obsolete);
+ }
+ assert.equal(
+ fs.existsSync(path.join(PLUGIN_ROOT, 'scripts', 'planning-timings.js')),
+ false,
+ );
+ assert.equal(
+ fs.existsSync(path.join(lib, 'mobile-lifecycle.js')),
+ true,
+ );
+});
diff --git a/plugins/mobile-apps/scripts/tests/mobile-telemetry-replay.test.js b/plugins/mobile-apps/scripts/tests/mobile-telemetry-replay.test.js
index a0abc5b88..c07e75b5b 100644
--- a/plugins/mobile-apps/scripts/tests/mobile-telemetry-replay.test.js
+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry-replay.test.js
@@ -24,7 +24,8 @@ test('prior event scan reads nested and rotated logs without Dirent path metadat
}));
const makeRecord = (sessionId, time) => ({
time, name: 'event',
- data: { pluginName: 'mobile-app', eventName: 'skill_started', sessionId,
+ data: { pluginName: 'mobile-app', skillName: 'create-mobile-app',
+ eventName: 'skill_started', sessionId,
eventInfo: { appInstanceId } },
});
const records = [
@@ -63,7 +64,8 @@ test('first resolution replays this app across sessions without duplicating logs
clusterEnvironment: 'Prod', clusterGeoName: 'EU' }));
const makeRecord = (sessionId, identity = appInstanceId) => ({
time: '2026-09-07T01:00:00.000Z', name: 'event',
- data: { pluginName: 'mobile-app', eventName: 'skill_started', sessionId, eventInfo: { appInstanceId: identity } },
+ data: { pluginName: 'mobile-app', skillName: 'create-mobile-app',
+ eventName: 'skill_started', sessionId, eventInfo: { appInstanceId: identity } },
});
appendLocal(makeRecord('first'), { configDir });
appendLocal(makeRecord('second'), { configDir });
@@ -91,6 +93,22 @@ test('first resolution replays this app across sessions without duplicating logs
const log = path.join(history, 'events.20260907010000.old');
assert.equal(fs.readFileSync(log, 'utf8').trim().split('\n').length, 1);
fs.writeFileSync(probe, 'unchanged');
+ const optedOutReplay = spawnSync(
+ process.execPath,
+ [path.resolve(__dirname, '../lib/mobile-telemetry-dispatcher.js')],
+ {
+ cwd: os.tmpdir(),
+ env: { ...env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },
+ input: JSON.stringify({
+ data: { pluginName: 'mobile-app' },
+ replay: [makeRecord('first')],
+ }),
+ encoding: 'utf8',
+ timeout: 5000,
+ },
+ );
+ assert.equal(optedOutReplay.status, 0);
+ assert.equal(fs.readFileSync(probe, 'utf8'), 'unchanged');
assert.equal(run().status, 0);
await delay(100);
assert.equal(fs.readFileSync(probe, 'utf8'), 'unchanged');
@@ -169,7 +187,13 @@ test('dispatcher preserves the original event shape for unresolved, opted-out an
const run = (sessionId, childEnv = env) => {
const result = spawnSync(process.execPath, [path.resolve(__dirname, '../lib/mobile-telemetry-dispatcher.js')], {
cwd: root, env: childEnv, encoding: 'utf8', timeout: 5000,
- input: JSON.stringify({ name: 'event', data: { pluginName: 'mobile-app', sessionId, eventInfo: { appInstanceId } } }),
+ input: JSON.stringify({ name: 'event', data: {
+ pluginName: 'mobile-app',
+ skillName: 'create-mobile-app',
+ eventName: 'skill_started',
+ sessionId,
+ eventInfo: { appInstanceId },
+ } }),
});
assert.equal(result.status, 0, result.stderr);
};
@@ -188,6 +212,12 @@ test('dispatcher preserves the original event shape for unresolved, opted-out an
assert.deepEqual(Object.keys(record).sort(), ['data', 'name', 'time']);
assert.equal(record.name, 'event');
assert.ok(Number.isFinite(Date.parse(record.time)));
- assert.deepEqual(record.data, { pluginName: 'mobile-app', sessionId, eventInfo: { appInstanceId } });
+ assert.deepEqual(record.data, {
+ pluginName: 'mobile-app',
+ skillName: 'create-mobile-app',
+ eventName: 'skill_started',
+ sessionId,
+ eventInfo: { appInstanceId },
+ });
}
});
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/tests/mobile-telemetry.test.js b/plugins/mobile-apps/scripts/tests/mobile-telemetry.test.js
index bc1ef1576..107860741 100644
--- a/plugins/mobile-apps/scripts/tests/mobile-telemetry.test.js
+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry.test.js
@@ -16,6 +16,7 @@ const {
const {
emitCheckpoint: emitCheckpointCommand,
parseCheckpointPayload,
+ runCommand,
} = require('../emit-telemetry-checkpoint');
const { ensureAppInstanceId, findAppInstanceId } = require('../lib/app-identity');
const { TRACKED_SKILL_NAMES } = require('../lib/mobileapp-hook-utils');
@@ -361,6 +362,46 @@ test('checkpoint command emits directly and remains fail-open', () => {
}), null);
});
+test('tracked checkpoint context skips host process discovery', () => {
+ let contextOptions;
+ const result = emitCheckpointCommand(
+ 'create-mobile-app|gather_app_requirements|started',
+ {
+ cwd: '/private-project',
+ runId: '11111111-1111-4111-8111-111111111111',
+ parentSpanId: '22222222-2222-4222-8222-222222222222',
+ createTelemetryContext: (_payload, options) => {
+ contextOptions = options;
+ return null;
+ },
+ },
+ );
+ assert.equal(result, null);
+ assert.equal(contextOptions.cwd, '/private-project');
+ assert.equal(contextOptions.readProcessScope(), '');
+});
+
+test('tracked lifecycle CLI skips host process discovery', () => {
+ let contextOptions;
+ const result = runCommand([
+ 'create-mobile-app|gather_app_requirements|started',
+ '--run-id',
+ '11111111-1111-4111-8111-111111111111',
+ '--parent-span-id',
+ '22222222-2222-4222-8222-222222222222',
+ '--project-root',
+ '/private-project',
+ ], {
+ createTelemetryContext: (_payload, options) => {
+ contextOptions = options;
+ return null;
+ },
+ });
+ assert.deepEqual(result, { status: 'disabled' });
+ assert.equal(contextOptions.cwd, '/private-project');
+ assert.equal(contextOptions.readProcessScope(), '');
+});
+
test('checkpoint event carries only static checkpoint enrichment', (t) => {
const context = contextFor(provisioned);
const event = emitCheckpointEvent(context, {
@@ -394,15 +435,31 @@ test('shared instructions own checkpoint execution and lifecycle rules', () => {
const checkpointSection = shared.match(/## Workflow Checkpoints\r?\n([\s\S]*?)(?=\r?\n---)/)?.[1];
assert.ok(checkpointSection, 'shared instructions must define the checkpoint policy');
assert.match(checkpointSection, /frontmatter `name`/);
- assert.match(checkpointSection, /node "\$\{PLUGIN_ROOT\}\/scripts\/emit-telemetry-checkpoint\.js" "<skill-name>\|<checkpoint-name>\|<state>" \|\| true/);
- for (const state of ['started', 'completed', 'failed', 'skipped']) {
+ assert.match(checkpointSection, /--begin "<skill-name>"/);
+ assert.match(checkpointSection, /--finish <completed\|failed\|blocked\|cancelled>/);
+ assert.match(checkpointSection, /run-with-telemetry\.sh/);
+ assert.match(checkpointSection, /--execute "<skill-name>\|<checkpoint-name>"/);
+ assert.match(checkpointSection, /Support ID: <runId>/);
+ for (const state of [
+ 'started',
+ 'completed',
+ 'failed',
+ 'blocked',
+ 'cancelled',
+ 'skipped',
+ 'needs_context',
+ ]) {
assert.ok(checkpointSection.includes(`\`${state}\``), `shared policy must explain ${state}`);
}
- assert.match(checkpointSection, /only `skipped`, without `started`/);
- assert.match(checkpointSection, /author-written `snake_case` values of at most 64 characters/);
- assert.match(checkpointSection, /never include prompts, errors, paths, names, identifiers, URLs, command output, or other runtime data/);
+ assert.match(checkpointSection, /only `skipped` without `started`/);
+ assert.match(
+ checkpointSection,
+ /author-written `snake_case` values of at most\s+64 characters/,
+ );
+ assert.match(checkpointSection, /Never include prompts, raw errors,\s+paths, names, URLs, record contents, command output, or runtime payloads/);
assert.match(checkpointSection, /fail-open/);
- assert.match(checkpointSection, /Do not duplicate emissions/);
+ assert.match(checkpointSection, /missing terminal event remains incomplete/);
+ assert.match(checkpointSection, /do not append `\|\| true`/);
});
test('create-mobile-app uses precise checkpoint names at major workflow boundaries', () => {
@@ -650,8 +707,10 @@ test('Mobile control wrapper updates preference with accurate disclosure', (t) =
});
assert.equal(status.status, 0);
assert.match(status.stdout, /Telemetry \(mobile-app\): ON/);
- assert.match(status.stdout, /does not record PAC CLI version/);
- assert.match(status.stdout, /organization or Entra tenant IDs/);
+ assert.match(status.stdout, /event\/run\/span IDs/);
+ assert.match(status.stdout, /verified environment, tenant, and Dataverse organization/);
+ assert.match(status.stdout, /does not collect an\s+Entra user\/object ID, Dataverse user ID, username, or email address/);
+ assert.match(status.stdout, /No business records, file contents, emails, tokens, or raw errors/);
assert.doesNotMatch(status.stdout, /when PAC is signed in/);
const off = spawnSync(process.execPath, [TELEMETRY_CLI, '--action', 'off'], {
diff --git a/plugins/mobile-apps/scripts/verify-dataverse-access.js b/plugins/mobile-apps/scripts/verify-dataverse-access.js
index 1a19e916e..86b0e3f59 100644
--- a/plugins/mobile-apps/scripts/verify-dataverse-access.js
+++ b/plugins/mobile-apps/scripts/verify-dataverse-access.js
@@ -41,6 +41,12 @@ async function main() {
}
const data = JSON.parse(res.body);
+ try {
+ require('./emit-telemetry-checkpoint')
+ .captureSuccessfulDataverseRequest(envUrl, token, data);
+ } catch {
+ // Telemetry enrichment cannot change verified Dataverse access.
+ }
// Extract tenantId from JWT token payload
let tenantId = null;
try {
diff --git a/plugins/mobile-apps/shared/shared-instructions.md b/plugins/mobile-apps/shared/shared-instructions.md
index d58c7fddd..623780d79 100644
--- a/plugins/mobile-apps/shared/shared-instructions.md
+++ b/plugins/mobile-apps/shared/shared-instructions.md
@@ -16,21 +16,104 @@ Run at the start of every skill execution (at most once per day). Notifies the u
## Workflow Checkpoints
-Only steps with this marker directly below the heading emit checkpoint telemetry:
+Every tracked operational skill uses the measured lifecycle below. The `telemetry`
+preference skill is exempt. Host prompt and Skill hooks remain activity observations;
+they are not measured workflow starts or proof of completion.
+
+At workflow entry, use the invoked top-level skill's frontmatter `name` and actual
+project root. Start once, retain the returned `runId` and skill `spanId` as
+`RUN_ID` and `SKILL_SPAN_ID`, and include `Support ID: <runId>` in the final
+summary when a measured run was created:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/emit-telemetry-checkpoint.js" \
+ --begin "<skill-name>" --project-root "<working_dir>" || true
+```
+
+A nested skill uses the supplied run ID and caller span by adding `--run-id`
+and `--parent-span-id`; its returned span is a new skill invocation. Pass both
+IDs as orchestration context when invoking another Skill or Task, not as Power
+Apps CLI flags. Never infer a parent from a process or session ID. On resume,
+use `--resume "<skill-span-id>" --run-id "<run-id>" --project-root "<working_dir>"`
+instead of starting a second run, then replace `SKILL_SPAN_ID` with the newly
+returned span ID. Resume is valid only after `needs_context`; it creates a new
+immutable attempt in the same run. Each attempt can have only one retry;
+subsequent pauses or retries must use the newest returned span ID. An expired or
+unavailable context is unmeasured, not permission to invent IDs or pair unrelated runs.
+
+Only steps with this marker directly below the heading emit ordinary checkpoints:
```markdown
**Telemetry checkpoint: `<static_snake_case_name>`**
```
-Run from the app directory using the invoked top-level skill's frontmatter `name` and the exact checkpoint marker. `${PLUGIN_ROOT}` is the installed plugin directory.
+For agent work or approval waiting, start immediately before the work with the
+exact marker and retain the returned step `spanId` as `STEP_SPAN_ID`. Finish
+that same span afterward:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/emit-telemetry-checkpoint.js" \
+ "<skill-name>|<checkpoint-name>|started" \
+ --run-id "$RUN_ID" --parent-span-id "$SKILL_SPAN_ID" \
+ --project-root "<working_dir>" || true
+node "${PLUGIN_ROOT}/scripts/emit-telemetry-checkpoint.js" \
+ "<skill-name>|<checkpoint-name>|completed" \
+ --run-id "$RUN_ID" --span-id "$STEP_SPAN_ID" \
+ --project-root "<working_dir>" || true
+```
+
+For one foreground command, prefer the wrapper so timing and outcome come from
+the real process. Supply an executable plus separate arguments, not a shell
+command string. Use a real executable or `node <script>` on Windows, not a
+`.cmd` shim. Do not wrap persistent servers, watchers, or interactive sign-in:
```bash
-node "${PLUGIN_ROOT}/scripts/emit-telemetry-checkpoint.js" "<skill-name>|<checkpoint-name>|<state>" || true
+bash "${PLUGIN_ROOT}/scripts/run-with-telemetry.sh" \
+ --execute "<skill-name>|<checkpoint-name>" --run-id "$RUN_ID" \
+ --parent-span-id "$SKILL_SPAN_ID" --project-root "<working_dir>" \
+ -- node "<script-path>" "<argument>"
```
-- Emit `started` immediately before the work, then `completed` after success or `failed` before stopping on failure. When a valid branch bypasses the work, emit only `skipped`, without `started`. Do not duplicate emissions already embedded in a command block.
-- Keep checkpoint names and optional info fixed, author-written `snake_case` values of at most 64 characters. Use precise verb-object names without lifecycle suffixes. Append `|<optional-info>` only when a static classification is needed; never include prompts, errors, paths, names, identifiers, URLs, command output, or other runtime data.
-- Keep telemetry fail-open and secondary to the workflow. Ignore emitter output, never retry or inspect the emitter, and never change the work when emission fails. Do not emit checkpoints for unmarked steps.
+The dependency-free shell wrapper owns the real command and invokes telemetry as
+a bounded best-effort child. A syntax/import error or hang in the telemetry JS
+cannot suppress or rerun the command. The wrapper preserves the command's exit
+code; do not append `|| true`. Its command, arguments, stdout, and stderr never
+enter telemetry. For multi-command phases, use the explicit start/finish pair
+and report the aggregate outcome.
+
+Each wrapper telemetry call has an approximately one-second budget, followed by
+TERM and then KILL after a short grace period if needed. `--project-root` also sets
+the real command's working directory. If that directory is unavailable, the
+wrapper fails rather than running the command against a different project.
+
+Direct begin/start/finish telemetry calls are observational and therefore end
+with `|| true`. If they produce no valid IDs, continue the workflow unmeasured;
+never fabricate context or retry telemetry.
+
+- Emit `started` immediately before work, then `completed`, `failed`, `blocked`,
+ or `cancelled` as observed. A missing terminal event remains incomplete,
+ never zero-duration or successful. A rejected approval finishes the wait;
+ the subsequent revision is a separate attempt, not an automatic failure.
+- For a valid bypass, emit only `skipped` without `started`, using `--run-id`
+ and `--parent-span-id` without `--span-id`. Retry with a new start and
+ `--retry-of "<prior-step-span-id>"`; do not overwrite the previous attempt.
+- When context is needed, close only that attempt with `needs_context` and keep
+ the workflow open. Resume a skill with `--resume`; restart a checkpoint with
+ `started` and `--retry-of "<prior-step-span-id>"`, using the same run and parent
+ IDs. Finish the new attempt before completing its parent. End the skill with
+ `--finish <completed|failed|blocked|cancelled>` plus its run and skill span
+ IDs only after the owning workflow actually ends. `DONE_WITH_CONCERNS`
+ remains completed, with concerns surfaced separately.
+- Checkpoint names are registered author-written `snake_case` values of at most
+ 64 characters. Optional `|<optional-info>` and `--error-class` values must
+ come from the helper's fixed allowlists. Never include prompts, raw errors,
+ paths, names, URLs, record contents, command output, or runtime payloads.
+- The command wrapper supplies the measured run and span IDs to child
+ Dataverse calls for principal attribution to that exact step. Bare operations
+ without that verified span must not borrow an account ID from another step.
+- Keep telemetry fail-open and secondary to the workflow. If context creation
+ or emission fails, continue the actual work without fabricated measurements.
+ Never retry or inspect the emitter, and do not emit unmarked checkpoints.
---
diff --git a/plugins/mobile-apps/skills/report-issue/SKILL.md b/plugins/mobile-apps/skills/report-issue/SKILL.md
index 29642a49e..2973d6786 100644
--- a/plugins/mobile-apps/skills/report-issue/SKILL.md
+++ b/plugins/mobile-apps/skills/report-issue/SKILL.md
@@ -102,6 +102,12 @@ echo "ANDROID_HOME=$ANDROID_HOME"
Run `npx expo doctor` and capture the text output verbatim.
+Ask for the affected workflow's Support ID when available. Use the telemetry
+helper's read-only `--report` mode from the affected project to inspect only its
+allowlisted timeline. Include the Support ID and relevant step/error category in
+the issue body, not environment, tenant, or organization IDs. Do not
+upload the telemetry directory or raw timing/authentication files.
+
If the user pasted an error, capture verbatim. Otherwise look for recent failure signals:
- Last 50 lines of any Metro / Gradle / Xcode log if user mentions a build failure
@@ -114,6 +120,8 @@ If the user pasted an error, capture verbatim. Otherwise look for recent failure
- Connection IDs unless the user explicitly opted in (PII / can map to tenant)
- Anything under `node_modules/`
- Package source excerpts, patched package contents, or proposed fork code
+- Tenant/environment/organization IDs in a public issue, even though verified
+ IDs can exist in access-controlled telemetry
### Step 4 — Render issue body
@@ -152,11 +160,12 @@ Print this block — user copies into a new issue:
### Project context
<if in project>
-- Project: `<name>` v`<version>`
-- Power Platform env: `<env-id>`
+- Mobile project detected: yes
+- Support ID: `<affected workflow run GUID, or unavailable>`
+- Failed step / error category: `<registered step and fixed category, or unknown>`
- Memory bank present: <yes/no>
- Plan present: <yes/no>
-- Connectors registered: <list from src/generated/services>
+- Connector count: <count, not generated service or business-table names>
</if>
<if not in project>
diff --git a/plugins/mobile-apps/skills/telemetry/telemetry-workflow.md b/plugins/mobile-apps/skills/telemetry/telemetry-workflow.md
index 04ddf8eed..b116ccf5d 100644
--- a/plugins/mobile-apps/skills/telemetry/telemetry-workflow.md
+++ b/plugins/mobile-apps/skills/telemetry/telemetry-workflow.md
@@ -24,11 +24,14 @@ usage telemetry for this plugin. Default to `status` when no argument is given.
remains under `~/.power-platform-skills/telemetry/<plugin>/sessions/`.
- `on` re-enables transmission. The choice is **per-user and per-plugin** and
takes effect on the next event (no restart).
-- Mobile Apps records start-only operational fields such as skill name, plugin
- version, session and correlation IDs, OS/Node versions, AI-agent name/version,
- invocation source, and a random per-project app instance ID. It never includes
- file paths, prompts, tool inputs, site names, URLs, credentials, usernames,
- hostnames, Dataverse organization or tenant IDs, or Entra object IDs.
+- Mobile Apps records operational and measured lifecycle fields such as
+ skill/checkpoint names, plugin/agent/OS/Node versions, generated
+ session/run/span/event IDs, durations, outcomes, fixed error classes,
+ invocation source, and a random per-project app instance ID. Verified target
+ operations can add environment, tenant, and Dataverse organization IDs. It
+ never includes Entra user/object IDs, Dataverse user IDs, business records,
+ document contents, file paths, prompts, tool inputs, URLs, credentials,
+ usernames, email addresses, hostnames, or raw error descriptions.
- A repository configuration with `disabled: true` is a hard-off: it writes no
local mirror and sends no event, regardless of the saved user preference.
- **Automation/CI** can disable telemetry by setting the opt-out env var