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.

end to end testing for developer telemetry (#531)

Nikhil agrawal2fdef417f09d
diff --git a/plugins/mobile-apps/hooks/run-telemetry.js b/plugins/mobile-apps/hooks/run-telemetry.js
index 6c6d1134e..aa9b92ca0 100644
--- a/plugins/mobile-apps/hooks/run-telemetry.js
+++ b/plugins/mobile-apps/hooks/run-telemetry.js
@@ -109,7 +109,7 @@ async function run(mode) {
const invocationCwd = resolveInvocationCwd(payload);
withStableDispatchCwd(() => {
- const context = telemetry.createTelemetryContext(payload);
+ const context = telemetry.createTelemetryContext(payload, { cwd: invocationCwd });
if (context) {
telemetry.emitSkillStarted(
context,
diff --git a/plugins/mobile-apps/scripts/emit-telemetry-checkpoint.js b/plugins/mobile-apps/scripts/emit-telemetry-checkpoint.js
index 1d7e64fe6..280d77e75 100644
--- a/plugins/mobile-apps/scripts/emit-telemetry-checkpoint.js
+++ b/plugins/mobile-apps/scripts/emit-telemetry-checkpoint.js
@@ -45,11 +45,12 @@ function emitCheckpoint(payload, opts = {}) {
if (!invocation) return null;
const createContext = opts.createTelemetryContext || telemetry.createTelemetryContext;
- const context = createContext({});
+ const cwd = opts.cwd || process.cwd();
+ const context = createContext({}, { cwd });
if (!context) return null;
const emit = opts.emitCheckpoint || telemetry.emitCheckpoint;
- return emit(context, invocation, { cwd: opts.cwd || process.cwd() });
+ return emit(context, invocation, { cwd });
} catch {
return null;
}
diff --git a/plugins/mobile-apps/scripts/lib/app-identity.js b/plugins/mobile-apps/scripts/lib/app-identity.js
index 0b7090fec..2e7b66c6d 100644
--- a/plugins/mobile-apps/scripts/lib/app-identity.js
+++ b/plugins/mobile-apps/scripts/lib/app-identity.js
@@ -62,11 +62,9 @@ function readTelemetryCluster(projectRoot = process.cwd()) {
}
function writeTelemetryCluster(projectRoot, cluster) {
- if (!projectRoot || !TELEMETRY_CLUSTERS.has(cluster)) return;
+ if (!projectRoot || (cluster !== null && !TELEMETRY_CLUSTERS.has(cluster))) return;
const filePath = appJsonPath(projectRoot);
- // Re-read here rather than reusing an earlier parse: telemetry runs in a
- // detached child that can overlap with project tooling which also owns
- // app.json, so the write window must stay as small as possible.
+ // Re-read to keep the write window small when other project tooling updates app.json.
const appJson = readJsonFile(filePath);
if (!isPlainObject(appJson) || !isPlainObject(appJson.expo)) return;
const extra = isPlainObject(appJson.expo.extra) ? appJson.expo.extra : {};
@@ -91,9 +89,7 @@ function ensureAppInstanceId(projectRoot = process.cwd()) {
const filePath = appJsonPath(root);
const appJson = readJsonFile(filePath);
- // The create workflow gates on the supported Expo template before calling
- // this helper. Refuse to manufacture a minimal config when that invariant is
- // broken because doing so would hide scaffold damage and overwrite evidence.
+ // Telemetry must not manufacture project configuration outside a valid Expo app.
if (!isPlainObject(appJson) || !isPlainObject(appJson.expo)) {
throw new Error('Cannot create app identity without an existing, valid Expo app.json');
}
diff --git a/plugins/mobile-apps/scripts/lib/environment-resolution.js b/plugins/mobile-apps/scripts/lib/environment-resolution.js
new file mode 100644
index 000000000..fbfb093a2
--- /dev/null
+++ b/plugins/mobile-apps/scripts/lib/environment-resolution.js
@@ -0,0 +1,312 @@
+'use strict';
+
+const { execFileSync } = require('child_process');
+const fs = require('fs');
+const https = require('https');
+const path = require('path');
+
+const BAP_RESOURCE = 'https://api.bap.microsoft.com';
+const BAP_TOKEN_FALLBACK_RESOURCE = 'https://service.powerapps.com/';
+const BAP_API_VERSION = '2020-10-01';
+const BAP_HOST = 'https://api.bap.microsoft.com';
+const CACHE_FILE = '.resolved-environment.json';
+const AUTH_CONFIG_FILE = 'auth.config.json';
+const GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+function normalizeUrl(value) {
+ return value.replace(/\/+$/, '');
+}
+
+function isUrl(value) {
+ return /^https:\/\//i.test(value);
+}
+
+function readJsonFile(filePath) {
+ try {
+ if (!fs.existsSync(filePath)) return null;
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function cacheMatchesTarget(cache, target) {
+ if (!cache || !cache.environmentUrl) return false;
+ if (!target) return true;
+ if (GUID_RE.test(target)) {
+ return Boolean(cache.environmentId && cache.environmentId.toLowerCase() === target.toLowerCase());
+ }
+ if (isUrl(target)) {
+ return normalizeUrl(cache.environmentUrl).toLowerCase() === normalizeUrl(target).toLowerCase();
+ }
+ return false;
+}
+
+function readCachedResolution(target, projectRoot) {
+ const sidecarCache = readJsonFile(path.join(projectRoot, CACHE_FILE));
+ const authConfig = readJsonFile(path.join(projectRoot, AUTH_CONFIG_FILE));
+ const authCache = authConfig && authConfig.environment ? authConfig.environment : null;
+ for (const cache of [sidecarCache, authCache]) {
+ if (cacheMatchesTarget(cache, target)) return cache;
+ }
+ return null;
+}
+
+function hasCachedEnvironmentDetails(value) {
+ return Boolean(value && value.environmentUrl && value.tenantId);
+}
+
+function canUseCachedResolution(value, target, allowLegacyCache = false) {
+ return hasCachedEnvironmentDetails(value) &&
+ (Boolean(allowLegacyCache) || !GUID_RE.test(target) ||
+ (typeof value.clusterEnvironment === 'string' && value.clusterEnvironment.trim() !== '' &&
+ typeof value.clusterGeoName === 'string' && value.clusterGeoName.trim() !== ''));
+}
+
+function toEnvironmentResult(value, source) {
+ return {
+ environmentUrl: value.environmentUrl,
+ environmentId: value.environmentId || null,
+ displayName: value.displayName || null,
+ tenantId: value.tenantId || null,
+ clusterEnvironment: typeof value.clusterEnvironment === 'string' ? value.clusterEnvironment : null,
+ clusterGeoName: typeof value.clusterGeoName === 'string' ? value.clusterGeoName : null,
+ source,
+ };
+}
+
+function shouldWriteCache(result, projectRoot) {
+ return Boolean(result && result.environmentId && result.environmentUrl
+ && fs.existsSync(path.join(projectRoot, AUTH_CONFIG_FILE)));
+}
+
+function writeCacheIfProject(result, projectRoot) {
+ if (!shouldWriteCache(result, projectRoot)) return;
+ const cachePath = path.join(projectRoot, CACHE_FILE);
+ const cache = { ...result, cachedAt: new Date().toISOString() };
+ fs.writeFileSync(cachePath, `${JSON.stringify(cache, null, 2)}\n`);
+
+ const authPath = path.join(projectRoot, AUTH_CONFIG_FILE);
+ const authConfig = readJsonFile(authPath);
+ if (authConfig && typeof authConfig === 'object') {
+ authConfig.environment = cache;
+ fs.writeFileSync(authPath, `${JSON.stringify(authConfig, null, 2)}\n`);
+ }
+}
+
+function getAzTenantId() {
+ try {
+ return execFileSync('az', ['account', 'show', '--query', 'tenantId', '-o', 'tsv'], {
+ encoding: 'utf8',
+ timeout: 10000,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim() || null;
+ } catch {
+ return null;
+ }
+}
+
+function getAzToken(resource, tenantId = null) {
+ const args = ['account', 'get-access-token'];
+ if (tenantId) args.push('--tenant', tenantId);
+ args.push('--resource', resource, '--query', 'accessToken', '-o', 'tsv');
+ try {
+ return execFileSync('az', args, {
+ encoding: 'utf8',
+ timeout: 20000,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim() || null;
+ } catch {
+ return null;
+ }
+}
+
+function requestJson(url, token = null, timeout = 20000) {
+ return new Promise((resolve) => {
+ const req = https.request(url, {
+ method: 'GET',
+ headers: token ? { Authorization: `Bearer ${token}`, Accept: 'application/json' } : { Accept: 'application/json' },
+ timeout,
+ }, (res) => {
+ let body = '';
+ res.on('data', chunk => (body += chunk));
+ res.on('end', () => {
+ let data = null;
+ try { data = body ? JSON.parse(body) : null; } catch { data = body; }
+ resolve({ statusCode: res.statusCode, headers: res.headers, data });
+ });
+ });
+ req.on('error', error => resolve({ error: error.message }));
+ req.on('timeout', () => {
+ req.destroy();
+ resolve({ error: 'request timed out' });
+ });
+ req.end();
+ });
+}
+
+function extractTenantFromAuthenticate(header) {
+ if (!header) return null;
+ const value = Array.isArray(header) ? header.join(',') : String(header);
+ const patterns = [
+ /authorization_uri="https:\/\/login\.microsoftonline\.com\/([^/"\s]+)\//i,
+ /authorization="https:\/\/login\.microsoftonline\.com\/([^/"\s]+)\//i,
+ /https:\/\/login\.microsoftonline\.com\/([^/"\s]+)\//i,
+ ];
+ for (const pattern of patterns) {
+ const match = value.match(pattern);
+ if (match && !['common', 'organizations', 'consumers'].includes(match[1])) return match[1];
+ }
+ return null;
+}
+
+async function getTenantFromDataverseChallenge(environmentUrl) {
+ const res = await requestJson(`${normalizeUrl(environmentUrl)}/api/data/v9.2/`, null, 10000);
+ return extractTenantFromAuthenticate(res.headers && res.headers['www-authenticate']);
+}
+
+function buildEnvironmentApiUrl(environmentId) {
+ return `${BAP_HOST}/providers/Microsoft.BusinessAppPlatform/scopes/admin/environments/${encodeURIComponent(environmentId.toLowerCase())}?api-version=${BAP_API_VERSION}`;
+}
+
+function normalizeDataverseUrl(value) {
+ if (!value || typeof value !== 'string' || !/^https:\/\//i.test(value)) return null;
+ const apiIndex = value.toLowerCase().indexOf('/api/data/');
+ const baseUrl = apiIndex >= 0 ? value.slice(0, apiIndex) : value;
+ return normalizeUrl(baseUrl);
+}
+
+function findDataverseUrl(value) {
+ if (!value) return null;
+ if (typeof value === 'string') {
+ return /\.crm\d*\.dynamics\.com\b/i.test(value) ? normalizeDataverseUrl(value) : null;
+ }
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ const found = findDataverseUrl(item);
+ if (found) return found;
+ }
+ return null;
+ }
+ if (typeof value === 'object') {
+ for (const item of Object.values(value)) {
+ const found = findDataverseUrl(item);
+ if (found) return found;
+ }
+ }
+ return null;
+}
+
+function pickEnvironmentRecord(data, environmentId) {
+ const candidates = Array.isArray(data && data.value) ? data.value : [data];
+ return candidates.find((item) => {
+ if (!item || typeof item !== 'object') return false;
+ return [item.name, item.id, item.environmentId, item.properties && item.properties.environmentId]
+ .filter(Boolean)
+ .some(candidate => String(candidate).toLowerCase().includes(environmentId.toLowerCase()));
+ }) || candidates.find(item => item && typeof item === 'object') || null;
+}
+
+function environmentFromPowerPlatformPayload(payload, environmentId) {
+ const props = payload.properties || {};
+ const linked = props.linkedEnvironmentMetadata || {};
+ const cluster = props.cluster || {};
+ const environmentUrl = normalizeDataverseUrl(linked.instanceUrl)
+ || normalizeDataverseUrl(props.instanceUrl)
+ || normalizeDataverseUrl(payload.instanceUrl)
+ || findDataverseUrl(payload);
+ return {
+ environmentId: payload.name || props.environmentId || payload.environmentId || environmentId || null,
+ displayName: props.displayName || linked.friendlyName || null,
+ environmentUrl,
+ clusterEnvironment: typeof cluster.environment === 'string' ? cluster.environment : null,
+ clusterGeoName: typeof cluster.geoShortName === 'string' ? cluster.geoShortName : null,
+ tenantId: (props.createdBy && props.createdBy.tenantId) || props.tenantId || linked.tenantId || null,
+ };
+}
+
+async function resolveEnvironmentId(environmentId, tenantId) {
+ const token = getAzToken(BAP_RESOURCE, tenantId)
+ || getAzToken(BAP_TOKEN_FALLBACK_RESOURCE, tenantId)
+ || getAzToken(BAP_RESOURCE)
+ || getAzToken(BAP_TOKEN_FALLBACK_RESOURCE);
+ if (!token) throw new Error('Could not get Azure CLI token for the BAP admin API. Run az login and retry.');
+
+ const endpointUrl = buildEnvironmentApiUrl(environmentId);
+ const res = await requestJson(endpointUrl, token);
+ if (res.statusCode === 200 && res.data) {
+ const record = pickEnvironmentRecord(res.data, environmentId);
+ if (record) return environmentFromPowerPlatformPayload(record, environmentId);
+ }
+
+ const apiMessage = res.data && typeof res.data === 'object'
+ ? [res.data.code, res.data.message, res.data.innererror && res.data.innererror.message].filter(Boolean).join(': ')
+ : res.error || `HTTP ${res.statusCode}`;
+ const recovery = /Forbidden|Unauthorized|Authorization|permission|privilege|Insufficient/i.test(apiMessage || '')
+ ? ' The Azure CLI account may not have permission to read this environment through the BAP admin API. Use an account with environment read access, or provide the Dataverse environment URL directly.'
+ : '';
+ throw new Error(`Could not resolve environment ID ${environmentId} through ${endpointUrl}: ${apiMessage || 'unknown error'}.${recovery}`);
+}
+
+async function resolveEnvironment(target, projectRoot = process.cwd(), allowLegacyCache = false) {
+ if (!target) {
+ const powerConfig = readJsonFile(path.join(projectRoot, 'power.config.json'));
+ target = powerConfig?.environmentId || readCachedResolution(null, projectRoot)?.environmentId;
+ if (typeof target !== 'string' || !GUID_RE.test(target)) return null;
+ }
+ const cached = readCachedResolution(target, projectRoot);
+ if (canUseCachedResolution(cached, target, allowLegacyCache)) {
+ const result = toEnvironmentResult(cached, 'cache');
+ writeCacheIfProject(result, projectRoot);
+ return result;
+ }
+
+ const loginTenantId = getAzTenantId();
+ let resolved;
+ if (isUrl(target)) {
+ const normalizedUrl = normalizeUrl(target);
+ const challengeTenant = await getTenantFromDataverseChallenge(normalizedUrl);
+ resolved = {
+ environmentUrl: normalizedUrl,
+ environmentId: cached && cached.environmentId ? cached.environmentId : null,
+ displayName: cached && cached.displayName ? cached.displayName : null,
+ clusterEnvironment: cached && cached.clusterEnvironment || null,
+ clusterGeoName: cached && cached.clusterGeoName || null,
+ tenantId: challengeTenant || (cached && cached.tenantId) || null,
+ };
+ } else if (GUID_RE.test(target)) {
+ try {
+ resolved = await resolveEnvironmentId(target, loginTenantId);
+ } catch (error) {
+ if (cached && cached.environmentUrl) {
+ resolved = {
+ environmentUrl: cached.environmentUrl,
+ environmentId: cached.environmentId || target,
+ displayName: cached.displayName || null,
+ clusterEnvironment: cached.clusterEnvironment || null,
+ clusterGeoName: cached.clusterGeoName || null,
+ tenantId: cached.tenantId || null,
+ source: 'cache-refresh',
+ };
+ } else {
+ throw error;
+ }
+ }
+ } else {
+ throw new Error(`Expected an HTTPS environment URL or environment GUID, got: ${target}`);
+ }
+
+ if (!resolved.environmentUrl) {
+ throw new Error('Environment URL was not present in the Power Platform environment metadata. Provide the Dataverse URL directly.');
+ }
+
+ if (!resolved.tenantId) {
+ resolved.tenantId = await getTenantFromDataverseChallenge(resolved.environmentUrl);
+ }
+
+ const result = toEnvironmentResult(resolved, resolved.source || (isUrl(target) ? 'environment-url' : 'environment-id'));
+ writeCacheIfProject(result, projectRoot);
+ return result;
+}
+
+module.exports = { cacheMatchesTarget, canUseCachedResolution, toEnvironmentResult, environmentFromPowerPlatformPayload, resolveEnvironment };
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js
index 3b3ed5916..f3abecd54 100644
--- a/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js
+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js
@@ -8,7 +8,9 @@ const os = require('node:os');
const path = require('node:path');
const { FIELD_TYPES, pick } = require('./telemetry/lib/events');
-const { appendLocal } = require('./telemetry/lib/local-log');
+const { appendLocal, pluginLogDir } = require('./telemetry/lib/local-log');
+const { findAppInstanceId, readTelemetryCluster } = require('./app-identity');
+const { resolveClusterEnvironment } = require('./telemetry/region/region-resolver');
const { loadResolver } = require('./telemetry/lib/resolver-loader');
const {
isTransmissionOptedOut,
@@ -19,6 +21,59 @@ 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']);
+function readPriorEvents(projectRoot, env = process.env) {
+ const configDir = env.POWER_PLATFORM_SKILLS_CONFIG_DIR || DEFAULT_LOCAL_DIR;
+ const { cfg } = readIkeyConfig(env);
+ const appInstanceId = findAppInstanceId(projectRoot);
+ if (!appInstanceId || !cfg || cfg.disabled === true || isTransmissionOptedOut(configDir, 'mobile-app', env)) return [];
+ const records = [];
+ const sessionsRoot = pluginLogDir(configDir, 'mobile-app');
+ // Carry each parent directory explicitly so nested logs do not depend on
+ // Dirent.parentPath or the deprecated Dirent.path metadata.
+ const directories = [sessionsRoot];
+ while (directories.length) {
+ const directory = directories.pop();
+ try {
+ for (const file of fs.readdirSync(directory, { withFileTypes: true })) {
+ const filePath = path.join(directory, file.name);
+ if (file.isDirectory()) {
+ directories.push(filePath);
+ continue;
+ }
+ if (!file.isFile() || !/^events(?:\.jsonl|\.\d{14}\.old)$/.test(file.name)) continue;
+ let contents;
+ try { contents = fs.readFileSync(filePath, 'utf8'); } catch { continue; }
+ for (const line of contents.split('\n')) {
+ try {
+ const record = JSON.parse(line);
+ if (record.data?.pluginName === 'mobile-app' && record.data?.eventInfo?.appInstanceId === appInstanceId &&
+ Number.isFinite(Date.parse(record.time))) records.push(record);
+ } catch { /* Skip malformed or incomplete JSONL records. */ }
+ }
+ }
+ } catch { /* Missing or pruned logs must not block environment resolution. */ }
+ }
+ return records.sort((first, second) => Date.parse(first.time) - Date.parse(second.time));
+}
+
+async function prepareTelemetryBatch(projectRoot, env, environment = null) {
+ // Snapshot before resolution can publish a cluster, excluding events sent afterward.
+ const replay = readTelemetryCluster(projectRoot) ? [] : readPriorEvents(projectRoot, env);
+ const cluster = await resolveClusterEnvironment(projectRoot, environment);
+ return { cluster, replay: cluster ? replay : [] };
+}
+
+async function flushPriorEvents(projectRoot, environment, env = process.env) {
+ const { cluster, replay } = await prepareTelemetryBatch(projectRoot, env, environment);
+ if (!cluster || !replay.length) return;
+ fireAndForget({ data: { pluginName: 'mobile-app' }, replay }, {
+ projectRoot, env,
+ configDir: env.POWER_PLATFORM_SKILLS_CONFIG_DIR,
+ ikeyJsonPath: env.POWER_PLATFORM_SKILLS_IKEY_JSON,
+ fakeProbe: env.POWER_PLATFORM_SKILLS_FAKE_HTTPS,
+ });
+}
+
function fireAndForget(event, opts = {}) {
const env = opts.env || process.env;
const pluginName = event && event.data && event.data.pluginName;
@@ -44,6 +99,8 @@ function fireAndForget(event, opts = {}) {
...(optOutName && optOutValue ? { [optOutName]: optOutValue } : {}),
},
});
+ child.on('error', () => {});
+ child.stdin.on('error', () => {});
child.stdin.end(JSON.stringify(event));
child.unref();
} catch {
@@ -142,37 +199,46 @@ async function dispatch(raw, env) {
const data = sanitizeData(event.data);
const time = new Date().toISOString();
const configDir = env.POWER_PLATFORM_SKILLS_CONFIG_DIR || DEFAULT_LOCAL_DIR;
- appendLocal({ time, name: event.name, data }, { configDir });
-
+ if (!Array.isArray(event.replay)) {
+ appendLocal({ time, name: event.name, data }, { configDir });
+ }
if (isTransmissionOptedOut(configDir, data.pluginName, env)) return;
+ let records = Array.isArray(event.replay) ? event.replay : [{ data, time }];
let iKey = '';
let collectorUrl = '';
const resolver = loadResolver(path.dirname(configPath));
if (resolver && typeof resolver.resolve === 'function') {
try {
- // Resolved here, not in the hook: an unresolved cluster costs a `pac auth
- // who` cold start, and this child is already detached from skill execution.
+ let cluster;
+ if (data.pluginName === 'mobile-app') {
+ const batch = await prepareTelemetryBatch(env.POWER_PLATFORM_SKILLS_PROJECT_ROOT || '', env);
+ cluster = batch.cluster;
+ if (!cluster) return;
+ if (!Array.isArray(event.replay) && batch.replay.length) records = batch.replay;
+ }
const resolved = await resolver.resolve({
event,
cfg,
configDir,
projectRoot: env.POWER_PLATFORM_SKILLS_PROJECT_ROOT || '',
+ cluster,
});
iKey = resolved && resolved.iKey || '';
collectorUrl = resolved && resolved.collectorUrl || '';
} catch {
// A resolver failure leaves the event in the local mirror.
}
- if (!iKey || !collectorUrl) return;
} else {
iKey = cfg.instrumentationKey || '';
collectorUrl = cfg.collector_url || '';
}
if (!iKey || iKey === PLACEHOLDER_IKEY || !collectorUrl) return;
- const envelope = buildEnvelope(data, time, iKey, cfg.event_stream_name);
- const body = `${JSON.stringify(envelope)}\n`;
+ if (!records.length) return;
+ const body = records.map(record => JSON.stringify(
+ buildEnvelope(sanitizeData(record.data), record.time, iKey, cfg.event_stream_name),
+ )).join('\n') + '\n';
const headers = {
'Content-Type': 'application/x-json-stream; charset=utf-8',
'x-apikey': iKey,
@@ -232,4 +298,6 @@ module.exports = {
buildEnvelope,
buildNormalEventData,
fireAndForget,
+ readPriorEvents,
+ flushPriorEvents,
};
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry-session.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry-session.js
new file mode 100644
index 000000000..3b436f06b
--- /dev/null
+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry-session.js
@@ -0,0 +1,101 @@
+'use strict';
+
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+
+const HOST_PROCESS = /^(?:node|nodejs|copilot|claude|codex|opencode|hermes|openclaw|code(?: helper(?: \(plugin\))?)?)(?:\.exe)?$/i;
+let cachedScope;
+
+function readProcessScope(opts = {}) {
+ if (cachedScope !== undefined && !opts.exec) return cachedScope;
+ const exec = opts.exec || execFileSync;
+ const platform = opts.platform || process.platform;
+ let scope = '';
+ try {
+ const commandOptions = {
+ // PowerShell/CIM cold starts can exceed two seconds on busy Windows hosts.
+ // Keep the lookup bounded below the telemetry hook's ten-second deadline.
+ encoding: 'utf8', timeout: platform === 'win32' ? 5000 : 2000, maxBuffer: 2 * 1024 * 1024,
+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
+ env: { ...process.env, LC_ALL: 'C' },
+ };
+ let rows;
+ if (platform === 'win32') {
+ // Request only identity fields from CIM, not unused command lines or paths.
+ const output = exec('powershell.exe', [
+ '-NoProfile', '-NonInteractive', '-Command',
+ 'Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate,Name | Select-Object ProcessId,ParentProcessId,CreationDate,Name | ConvertTo-Json -Compress',
+ ], commandOptions);
+ rows = [].concat(JSON.parse(output)).map((row) => ({
+ pid: Number(row.ProcessId), parent: Number(row.ParentProcessId),
+ started: row.CreationDate, name: row.Name,
+ }));
+ } else {
+ // ps emits e.g. "123 1 Tue Sep 8 05:00:00 2026 /path/to/copilot".
+ // Read executable names, never command arguments, environment, or tokens.
+ const output = exec('ps', ['-A', '-o', 'pid=,ppid=,lstart=,comm='], commandOptions);
+ rows = String(output).split('\n').flatMap((line) => {
+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/);
+ return match ? [{
+ pid: Number(match[1]), parent: Number(match[2]), started: match[3], name: match[4],
+ }] : [];
+ });
+ }
+ const processes = new Map(rows.map((row) => [row.pid, row]));
+ const visited = new Set();
+ let parentPid = opts.parentPid || process.ppid;
+ while (parentPid > 1 && visited.size < 32 && !visited.has(parentPid)) {
+ visited.add(parentPid);
+ const parent = processes.get(parentPid);
+ if (!parent) break;
+ const name = platform === 'win32' ? path.win32.basename(parent.name) : path.basename(parent.name);
+ if (parent.started && HOST_PROCESS.test(name)) {
+ // A PID alone can be reused after the host exits. Its creation time is
+ // part of the local key so unrelated runs cannot inherit old sessions.
+ scope = `${parent.pid}:${parent.started}`;
+ break;
+ }
+ parentPid = parent.parent;
+ }
+ } catch {
+ // Unsupported hosts or unavailable process metadata keep the old fallback.
+ }
+ if (!opts.exec) cachedScope = scope;
+ return scope;
+}
+
+function resolveProcessSessionId(hostSessionId, opts = {}) {
+ let temporaryPath;
+ try {
+ if (!opts.cwd || !opts.configDir) return hostSessionId;
+ const scope = (opts.readProcessScope || readProcessScope)();
+ if (!scope) return hostSessionId;
+ const projectRoot = fs.realpathSync(opts.cwd);
+ const key = crypto.createHash('sha256').update(JSON.stringify([projectRoot, scope])).digest('hex');
+ const directory = path.join(opts.configDir, 'telemetry', 'mobile-app', 'host-sessions');
+ const contextPath = path.join(directory, `${key}.json`);
+ if (hostSessionId) {
+ // This is a host-context handoff, not an event queue. The only stored
+ // value is the host session id; project/process metadata stays in a hash.
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
+ temporaryPath = `${contextPath}.${crypto.randomUUID()}.tmp`;
+ fs.writeFileSync(temporaryPath, JSON.stringify({ sessionId: hostSessionId }), {
+ encoding: 'utf8', flag: 'wx', mode: 0o600,
+ });
+ fs.renameSync(temporaryPath, contextPath);
+ return hostSessionId;
+ }
+ const saved = JSON.parse(fs.readFileSync(contextPath, 'utf8'));
+ return typeof saved.sessionId === 'string' ? saved.sessionId : '';
+ } catch {
+ return hostSessionId;
+ } finally {
+ if (temporaryPath) {
+ try { fs.rmSync(temporaryPath, { force: true }); } catch { /* best effort */ }
+ }
+ }
+}
+
+module.exports = { readProcessScope, resolveProcessSessionId };
\ 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 aa9a7baf6..992279ce7 100644
--- a/plugins/mobile-apps/scripts/lib/mobile-telemetry.js
+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry.js
@@ -13,7 +13,8 @@ const events = require('./telemetry/lib/events');
const { fireAndForget } = require('./mobile-telemetry-dispatcher');
const { loadResolver } = require('./telemetry/lib/resolver-loader');
const session = require('./telemetry/lib/session');
-const { findAppInstanceId } = require('./app-identity');
+const { ensureAppInstanceId } = require('./app-identity');
+const { resolveProcessSessionId } = require('./mobile-telemetry-session');
function readPluginVersion() {
const manifestPath = path.resolve(__dirname, '..', '..', '.claude-plugin', 'plugin.json');
@@ -200,7 +201,12 @@ function resolveCopilotRootSessionId(hostSessionId, opts) {
function resolveSessionId(payload, opts = {}) {
const hostSessionId = session.resolveHostSessionId(payload);
- return session.getSessionId(resolveCopilotRootSessionId(hostSessionId, opts));
+ const rootSessionId = resolveCopilotRootSessionId(hostSessionId, opts);
+ return session.getSessionId(resolveProcessSessionId(rootSessionId, {
+ ...opts,
+ cwd: opts.cwd || (payload && payload.cwd),
+ configDir: configDir(opts.env),
+ }));
}
function createTelemetryContext(payload, opts = {}) {
@@ -249,7 +255,12 @@ function commonFields(context, invocation, opts = {}) {
const eventInfo = {};
if (invocation.source) eventInfo.invocationSource = invocation.source;
if (invocation.additionalInfo) eventInfo.additionalInfo = invocation.additionalInfo;
- const appInstanceId = findAppInstanceId(opts.cwd) || null;
+ let appInstanceId = null;
+ try {
+ if (opts.cwd) appInstanceId = ensureAppInstanceId(opts.cwd);
+ } catch {
+ // Identity persistence must never block a skill invocation.
+ }
eventInfo.appInstanceId = appInstanceId;
if (Object.keys(eventInfo).length) fields.eventInfo = eventInfo;
diff --git a/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js b/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js
index c960ab463..b28e2a6a1 100644
--- a/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js
+++ b/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js
@@ -90,11 +90,12 @@ function getTrackedSkillFromToolInput(toolInput) {
function getTrackedSkillFromPrompt(prompt) {
if (typeof prompt !== 'string') return null;
- // Copilot CLI expands a manual slash command before the hook runs and emits no
- // Skill pre-tool event, so the raw `/mobile-app:<skill>` text never arrives:
- // <skill-context name="add-connector">\n<instructions>...
- const expanded = prompt.match(/^\s*<skill-context\s+name="(?:mobile-app:)?([a-z0-9-]+)"/i);
- if (expanded) return trackedName(expanded[1]);
+ // Interactive Copilot can prepend its explicit invocation sentence to <skill-context>.
+ const expanded = prompt.match(/^\s*(?:The user explicitly invoked the "(\/(?:mobile-app:)?[a-z0-9-]+)" skill\. Follow its instructions now\.\s*)?<skill-context\s+name="(?:mobile-app:)?([a-z0-9-]+)"/i);
+ if (expanded) {
+ const skillName = trackedName(expanded[2]);
+ return !expanded[1] || detectTrackedSkill(expanded[1]) === skillName ? skillName : null;
+ }
const command = prompt.match(/^\s*(\/(?:mobile-app:)?[a-z0-9-]+)(?=\s|$)/i);
return command ? detectTrackedSkill(command[1]) : null;
diff --git a/plugins/mobile-apps/scripts/lib/telemetry/region/region-resolver.js b/plugins/mobile-apps/scripts/lib/telemetry/region/region-resolver.js
index 6e328a81c..2361f03f1 100644
--- a/plugins/mobile-apps/scripts/lib/telemetry/region/region-resolver.js
+++ b/plugins/mobile-apps/scripts/lib/telemetry/region/region-resolver.js
@@ -1,19 +1,23 @@
"use strict";
-const { fetchGeo: defaultFetchGeo, normalizeCloud } = require("./artemis-service");
-const { readPacAuth: defaultReadPacAuth } = require("../lib/pac-auth");
const appIdentity = require("../../app-identity");
+const { resolveEnvironment } = require("../../environment-resolution");
-const PUBLIC_US_GEOS = new Set(["us", "br", "jp", "in", "au", "ca", "as", "za", "ae", "kr"]);
-const PUBLIC_EU_GEOS = new Set(["eu", "uk", "de", "fr", "no", "ch"]);
+// BAP's `unitedstatesfirstrelease` is the public Preview (United States) region.
+// See: https://learn.microsoft.com/en-us/power-platform/admin/preview-environments
+const PUBLIC_US_GEOS = new Set(["us", "br", "jp", "in", "au", "ca", "as", "za", "ae", "kr",
+ "unitedstates", "unitedstatesfirstrelease", "southamerica", "brazil", "japan", "india", "australia", "canada", "asia", "southafrica", "unitedarabemirates", "uae", "korea"]);
+const PUBLIC_EU_GEOS = new Set(["eu", "uk", "de", "fr", "no", "ch", "europe", "unitedkingdom",
+ "germany", "france", "norway", "switzerland", "sweden", "poland", "italy"]);
function deriveRegion(cloud, geoName) {
- const stamp = normalizeCloud(cloud);
- if (stamp === "Gov") return "gov";
- if (stamp === "High") return "high";
- if (stamp === "Dod") return "dod";
- if (stamp === "Mooncake") return "mooncake";
- if (stamp === "Internal") return "internal";
+ const stamp = String(cloud || "").toLowerCase();
+ if (["gccmoderate", "usgov"].includes(stamp)) return "gov";
+ if (["gcchigh", "usgovhigh"].includes(stamp)) return "high";
+ if (["dod", "usgovdod"].includes(stamp)) return "dod";
+ if (["mooncake", "china"].includes(stamp)) return "mooncake";
+ if (["test", "preprod", "tip1", "tip2"].includes(stamp)) return "internal";
+ if (!["", "public", "prod", "preview"].includes(stamp)) return "";
const geo = String(geoName || "").toLowerCase();
if (PUBLIC_US_GEOS.has(geo)) return "us";
if (PUBLIC_EU_GEOS.has(geo)) return "eu";
@@ -26,33 +30,32 @@ function entryFromMap(regionsMap, cluster) {
return { region: cluster, iKey: entry.instrumentation_key, collectorUrl: entry.collector_url };
}
-async function clusterFromWhoAmI(readPacAuth, fetchGeo) {
- const auth = readPacAuth() || {};
- if (!auth.orgId) return "";
- let geo;
+async function resolveClusterEnvironment(projectRoot, resolvedEnvironment = null) {
+ if (!projectRoot) return null;
try {
- geo = await fetchGeo(auth.orgId, auth.cloud);
+ const savedCluster = appIdentity.readTelemetryCluster(projectRoot);
+ if (savedCluster) return savedCluster;
+ const environment = resolvedEnvironment || await resolveEnvironment(null, projectRoot);
+ const cluster = environment?.clusterEnvironment && environment?.clusterGeoName
+ ? deriveRegion(environment.clusterEnvironment, environment.clusterGeoName) : "";
+ if (!cluster) return null;
+ const currentCluster = appIdentity.readTelemetryCluster(projectRoot);
+ if (currentCluster) return currentCluster;
+ appIdentity.writeTelemetryCluster(projectRoot, cluster);
+ return appIdentity.readTelemetryCluster(projectRoot) || null;
} catch {
- return "";
+ return null;
}
- return geo ? deriveRegion(auth.cloud, geo.geoName) : "";
}
-async function resolve({ projectRoot, regionsMap, _readPacAuth, _fetchGeo, _appIdentity }) {
- const identity = _appIdentity || appIdentity;
- let cluster = identity.readTelemetryCluster(projectRoot);
-
- if (!cluster) {
- cluster = await clusterFromWhoAmI(
- _readPacAuth || defaultReadPacAuth,
- typeof _fetchGeo === "function" ? _fetchGeo : defaultFetchGeo,
- );
- // Persisting here is what keeps this off the hot path: every later event in
- // this project reads the cluster from app.json instead of forking `pac`.
- if (cluster) identity.writeTelemetryCluster(projectRoot, cluster);
+async function resolve({ projectRoot, regionsMap, cluster }) {
+ if (!projectRoot) return null;
+ try {
+ const resolvedCluster = cluster === undefined ? await resolveClusterEnvironment(projectRoot) : cluster;
+ return resolvedCluster ? entryFromMap(regionsMap, resolvedCluster) : null;
+ } catch {
+ return null;
}
-
- return cluster ? entryFromMap(regionsMap, cluster) : null;
}
-module.exports = { resolve, deriveRegion };
+module.exports = { resolve, deriveRegion, resolveClusterEnvironment };
diff --git a/plugins/mobile-apps/scripts/lib/telemetry/resolver.js b/plugins/mobile-apps/scripts/lib/telemetry/resolver.js
index 94596567a..78dc717cc 100644
--- a/plugins/mobile-apps/scripts/lib/telemetry/resolver.js
+++ b/plugins/mobile-apps/scripts/lib/telemetry/resolver.js
@@ -2,10 +2,11 @@
const { resolve: resolveRegion } = require("./region/region-resolver");
-function resolve({ cfg, projectRoot }) {
+function resolve({ cfg, projectRoot, cluster }) {
return resolveRegion({
projectRoot: projectRoot || "",
regionsMap: (cfg && cfg.regions) || {},
+ cluster,
});
}
diff --git a/plugins/mobile-apps/scripts/resolve-environment.js b/plugins/mobile-apps/scripts/resolve-environment.js
index afbb03c65..5cab38f58 100644
--- a/plugins/mobile-apps/scripts/resolve-environment.js
+++ b/plugins/mobile-apps/scripts/resolve-environment.js
@@ -4,245 +4,9 @@
// Usage: node scripts/resolve-environment.js <environment-url-or-id>
// Output: JSON with environmentUrl, environmentId, tenantId, and displayName when available.
-const { execFileSync } = require('child_process');
-const fs = require('fs');
-const https = require('https');
-const path = require('path');
-
-const BAP_RESOURCE = 'https://api.bap.microsoft.com';
-const BAP_TOKEN_FALLBACK_RESOURCE = 'https://service.powerapps.com/';
-const BAP_API_VERSION = '2020-10-01';
-const BAP_HOST = 'https://api.bap.microsoft.com';
-const CACHE_FILE = '.resolved-environment.json';
-const AUTH_CONFIG_FILE = 'auth.config.json';
-const GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-
-function normalizeUrl(value) {
- return value.replace(/\/+$/, '');
-}
-
-function isUrl(value) {
- return /^https:\/\//i.test(value);
-}
-
-function readJsonFile(filePath) {
- try {
- if (!fs.existsSync(filePath)) return null;
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
- } catch {
- return null;
- }
-}
-
-function cacheMatchesTarget(cache, target) {
- if (!cache || !cache.environmentUrl) return false;
- if (!target) return true;
- if (GUID_RE.test(target)) {
- return Boolean(cache.environmentId && cache.environmentId.toLowerCase() === target.toLowerCase());
- }
- if (isUrl(target)) {
- return normalizeUrl(cache.environmentUrl).toLowerCase() === normalizeUrl(target).toLowerCase();
- }
- return false;
-}
-
-function readCachedResolution(target) {
- const sidecarCache = readJsonFile(path.join(process.cwd(), CACHE_FILE));
- const authConfig = readJsonFile(path.join(process.cwd(), AUTH_CONFIG_FILE));
- const authCache = authConfig && authConfig.environment ? authConfig.environment : null;
- for (const cache of [sidecarCache, authCache]) {
- if (cacheMatchesTarget(cache, target)) return cache;
- }
- return null;
-}
-
-function hasCachedEnvironmentDetails(value) {
- return Boolean(value && value.environmentUrl && value.tenantId);
-}
-
-function toEnvironmentResult(value, source) {
- return {
- environmentUrl: value.environmentUrl,
- environmentId: value.environmentId || null,
- displayName: value.displayName || null,
- tenantId: value.tenantId || null,
- source,
- };
-}
-
-function shouldWriteCache(result) {
- return Boolean(result && result.environmentId && result.environmentUrl
- && fs.existsSync(path.join(process.cwd(), AUTH_CONFIG_FILE)));
-}
-
-function writeCacheIfProject(result) {
- if (!shouldWriteCache(result)) return;
- const cachePath = path.join(process.cwd(), CACHE_FILE);
- const cache = { ...result, cachedAt: new Date().toISOString() };
- fs.writeFileSync(cachePath, `${JSON.stringify(cache, null, 2)}\n`);
-
- const authPath = path.join(process.cwd(), AUTH_CONFIG_FILE);
- const authConfig = readJsonFile(authPath);
- if (authConfig && typeof authConfig === 'object') {
- authConfig.environment = cache;
- fs.writeFileSync(authPath, `${JSON.stringify(authConfig, null, 2)}\n`);
- }
-}
-
-function printResult(result) {
- console.log(JSON.stringify(result, null, 2));
-}
-
-function getAzTenantId() {
- try {
- return execFileSync('az', ['account', 'show', '--query', 'tenantId', '-o', 'tsv'], {
- encoding: 'utf8',
- timeout: 10000,
- stdio: ['ignore', 'pipe', 'ignore'],
- }).trim() || null;
- } catch {
- return null;
- }
-}
-
-function getAzToken(resource, tenantId = null) {
- const args = ['account', 'get-access-token'];
- if (tenantId) args.push('--tenant', tenantId);
- args.push('--resource', resource, '--query', 'accessToken', '-o', 'tsv');
- try {
- return execFileSync('az', args, {
- encoding: 'utf8',
- timeout: 20000,
- stdio: ['ignore', 'pipe', 'ignore'],
- }).trim() || null;
- } catch {
- return null;
- }
-}
-
-function requestJson(url, token = null, timeout = 20000) {
- return new Promise((resolve) => {
- const req = https.request(url, {
- method: 'GET',
- headers: token ? { Authorization: `Bearer ${token}`, Accept: 'application/json' } : { Accept: 'application/json' },
- timeout,
- }, (res) => {
- let body = '';
- res.on('data', chunk => (body += chunk));
- res.on('end', () => {
- let data = null;
- try { data = body ? JSON.parse(body) : null; } catch { data = body; }
- resolve({ statusCode: res.statusCode, headers: res.headers, data });
- });
- });
- req.on('error', error => resolve({ error: error.message }));
- req.on('timeout', () => {
- req.destroy();
- resolve({ error: 'request timed out' });
- });
- req.end();
- });
-}
-
-function extractTenantFromAuthenticate(header) {
- if (!header) return null;
- const value = Array.isArray(header) ? header.join(',') : String(header);
- const patterns = [
- /authorization_uri="https:\/\/login\.microsoftonline\.com\/([^/"\s]+)\//i,
- /authorization="https:\/\/login\.microsoftonline\.com\/([^/"\s]+)\//i,
- /https:\/\/login\.microsoftonline\.com\/([^/"\s]+)\//i,
- ];
- for (const pattern of patterns) {
- const match = value.match(pattern);
- if (match && !['common', 'organizations', 'consumers'].includes(match[1])) return match[1];
- }
- return null;
-}
-
-async function getTenantFromDataverseChallenge(environmentUrl) {
- const res = await requestJson(`${normalizeUrl(environmentUrl)}/api/data/v9.2/`, null, 10000);
- return extractTenantFromAuthenticate(res.headers && res.headers['www-authenticate']);
-}
-
-function buildEnvironmentApiUrl(environmentId) {
- return `${BAP_HOST}/providers/Microsoft.BusinessAppPlatform/scopes/admin/environments/${encodeURIComponent(environmentId.toLowerCase())}?api-version=${BAP_API_VERSION}`;
-}
-
-function normalizeDataverseUrl(value) {
- if (!value || typeof value !== 'string' || !/^https:\/\//i.test(value)) return null;
- const apiIndex = value.toLowerCase().indexOf('/api/data/');
- const baseUrl = apiIndex >= 0 ? value.slice(0, apiIndex) : value;
- return normalizeUrl(baseUrl);
-}
-
-function findDataverseUrl(value) {
- if (!value) return null;
- if (typeof value === 'string') {
- return /\.crm\d*\.dynamics\.com\b/i.test(value) ? normalizeDataverseUrl(value) : null;
- }
- if (Array.isArray(value)) {
- for (const item of value) {
- const found = findDataverseUrl(item);
- if (found) return found;
- }
- return null;
- }
- if (typeof value === 'object') {
- for (const item of Object.values(value)) {
- const found = findDataverseUrl(item);
- if (found) return found;
- }
- }
- return null;
-}
-
-function pickEnvironmentRecord(data, environmentId) {
- const candidates = Array.isArray(data && data.value) ? data.value : [data];
- return candidates.find((item) => {
- if (!item || typeof item !== 'object') return false;
- return [item.name, item.id, item.environmentId, item.properties && item.properties.environmentId]
- .filter(Boolean)
- .some(candidate => String(candidate).toLowerCase().includes(environmentId.toLowerCase()));
- }) || candidates.find(item => item && typeof item === 'object') || null;
-}
-
-function environmentFromPowerPlatformPayload(payload, environmentId) {
- const props = payload.properties || {};
- const linked = props.linkedEnvironmentMetadata || {};
- const environmentUrl = normalizeDataverseUrl(linked.instanceUrl)
- || normalizeDataverseUrl(props.instanceUrl)
- || normalizeDataverseUrl(payload.instanceUrl)
- || findDataverseUrl(payload);
- return {
- environmentId: payload.name || props.environmentId || payload.environmentId || environmentId || null,
- displayName: props.displayName || linked.friendlyName || null,
- environmentUrl,
- tenantId: (props.createdBy && props.createdBy.tenantId) || props.tenantId || linked.tenantId || null,
- };
-}
-
-async function resolveEnvironmentId(environmentId, tenantId) {
- const token = getAzToken(BAP_RESOURCE, tenantId)
- || getAzToken(BAP_TOKEN_FALLBACK_RESOURCE, tenantId)
- || getAzToken(BAP_RESOURCE)
- || getAzToken(BAP_TOKEN_FALLBACK_RESOURCE);
- if (!token) throw new Error('Could not get Azure CLI token for the BAP admin API. Run az login and retry.');
-
- const endpointUrl = buildEnvironmentApiUrl(environmentId);
- const res = await requestJson(endpointUrl, token);
- if (res.statusCode === 200 && res.data) {
- const record = pickEnvironmentRecord(res.data, environmentId);
- if (record) return environmentFromPowerPlatformPayload(record, environmentId);
- }
-
- const apiMessage = res.data && typeof res.data === 'object'
- ? [res.data.code, res.data.message, res.data.innererror && res.data.innererror.message].filter(Boolean).join(': ')
- : res.error || `HTTP ${res.statusCode}`;
- const recovery = /Forbidden|Unauthorized|Authorization|permission|privilege|Insufficient/i.test(apiMessage || '')
- ? ' The Azure CLI account may not have permission to read this environment through the BAP admin API. Use an account with environment read access, or provide the Dataverse environment URL directly.'
- : '';
- throw new Error(`Could not resolve environment ID ${environmentId} through ${endpointUrl}: ${apiMessage || 'unknown error'}.${recovery}`);
-}
+const environmentResolution = require('./lib/environment-resolution');
+const { readTelemetryCluster } = require('./lib/app-identity');
+const { flushPriorEvents } = require('./lib/mobile-telemetry-dispatcher');
async function main() {
const target = process.argv[2];
@@ -251,59 +15,17 @@ async function main() {
process.exit(1);
}
- const cached = readCachedResolution(target);
- if (hasCachedEnvironmentDetails(cached)) {
- const result = toEnvironmentResult(cached, 'cache');
- writeCacheIfProject(result);
- printResult(result);
- return;
- }
-
- const loginTenantId = getAzTenantId();
- let resolved;
- if (isUrl(target)) {
- const normalizedUrl = normalizeUrl(target);
- const challengeTenant = await getTenantFromDataverseChallenge(normalizedUrl);
- resolved = {
- environmentUrl: normalizedUrl,
- environmentId: cached && cached.environmentId ? cached.environmentId : null,
- displayName: cached && cached.displayName ? cached.displayName : null,
- tenantId: challengeTenant || (cached && cached.tenantId) || null,
- };
- } else if (GUID_RE.test(target)) {
- try {
- resolved = await resolveEnvironmentId(target, loginTenantId);
- } catch (error) {
- if (cached && cached.environmentUrl) {
- resolved = {
- environmentUrl: cached.environmentUrl,
- environmentId: cached.environmentId || target,
- displayName: cached.displayName || null,
- tenantId: cached.tenantId || null,
- source: 'cache-refresh',
- };
- } else {
- throw error;
- }
- }
- } else {
- throw new Error(`Expected an HTTPS environment URL or environment GUID, got: ${target}`);
- }
-
- if (!resolved.environmentUrl) {
- throw new Error('Environment URL was not present in the Power Platform environment metadata. Provide the Dataverse URL directly.');
- }
-
- if (!resolved.tenantId) {
- resolved.tenantId = await getTenantFromDataverseChallenge(resolved.environmentUrl);
- }
+ const projectRoot = process.cwd();
+ const result = await environmentResolution.resolveEnvironment(target, projectRoot, Boolean(readTelemetryCluster(projectRoot)));
+ await flushPriorEvents(projectRoot, result);
+ console.log(JSON.stringify(result, null, 2));
+}
- const result = toEnvironmentResult(resolved, resolved.source || (isUrl(target) ? 'environment-url' : 'environment-id'));
- writeCacheIfProject(result);
- printResult(result);
+if (require.main === module) {
+ main().catch((error) => {
+ process.stderr.write(`${error.message}\n`);
+ process.exit(1);
+ });
}
-main().catch((error) => {
- process.stderr.write(`${error.message}\n`);
- process.exit(1);
-});
\ No newline at end of file
+module.exports = environmentResolution;
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js b/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js
index 6cf959c37..0e80c46be 100644
--- a/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js
+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js
@@ -116,6 +116,110 @@ test('hook dispatch runs outside the caller project and restores its cwd', () =>
assert.equal(process.cwd(), originalCwd);
});
+test('interactive Copilot invocation creates identity and logs before environment resolution', (t) => {
+ const context = fixture(t);
+ const appPath = path.join(context.projectRoot, 'app.json');
+ fs.writeFileSync(appPath, JSON.stringify({ expo: { extra: { telemetry: { appInstanceId: null, cluster: null } } } }));
+ const result = runHook('prompt', {
+ cwd: context.projectRoot,
+ session_id: 'session-1',
+ prompt: 'The user explicitly invoked the "/mobile-app:create-mobile-app" skill. Follow its instructions now.\n\n' +
+ '<skill-context name="create-mobile-app">\nredacted instructions',
+ }, context);
+ assert.equal(result.status, 0, result.stderr);
+ const telemetry = JSON.parse(fs.readFileSync(appPath, 'utf8')).expo.extra.telemetry;
+ assert.match(telemetry.appInstanceId, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
+ assert.equal(telemetry.cluster, null);
+ const events = waitForEvents(context, 1);
+ assert.equal(events.length, 1);
+ assert.equal(events[0].data.skillName, 'create-mobile-app');
+ assert.equal(events[0].data.eventInfo.appInstanceId, telemetry.appInstanceId);
+});
+
+test('checkpoint CLI records and dispatches every lifecycle state without host-specific path variables', (t) => {
+ const context = fixture(t);
+ const appPath = path.join(context.projectRoot, 'app.json');
+ fs.writeFileSync(appPath, JSON.stringify({ expo: { extra: { telemetry: { appInstanceId: null, cluster: 'us' } } } }));
+ for (const state of ['started', 'completed', 'skipped', 'failed']) {
+ const probePath = path.join(context.root, `checkpoint-${state}.json`);
+ const additionalInfo = state === 'failed' ? '|app_not_initialized' : '';
+ const result = spawnSync(process.execPath, [
+ path.join(PLUGIN_ROOT, 'scripts', 'emit-telemetry-checkpoint.js'),
+ `add-connector|validate_connector_project|${state}${additionalInfo}`,
+ ], {
+ cwd: context.projectRoot, encoding: 'utf8', timeout: 10_000,
+ env: {
+ ...process.env,
+ PLUGIN_ROOT: '',
+ CLAUDE_SKILL_DIR: '',
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: context.configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: context.ikeyPath,
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '',
+ },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ const probe = waitForJson(probePath);
+ assert.ok(probe, `checkpoint ${state} must reach the dispatcher`);
+ const envelope = JSON.parse(probe.body);
+ const dimensions = JSON.parse(envelope.data.customDimensions);
+ assert.equal(envelope.data.event_Name, `validate_connector_project_${state}`);
+ assert.equal(envelope.data.severity, state === 'failed' ? 'Error' : 'Info');
+ assert.equal(dimensions.skillName, 'add-connector');
+ assert.equal(dimensions.eventInfo.invocationSource, 'checkpoint');
+ assert.equal(dimensions.eventInfo.appInstanceId, JSON.parse(fs.readFileSync(appPath, 'utf8')).expo.extra.telemetry.appInstanceId);
+ assert.equal(dimensions.eventInfo.additionalInfo, state === 'failed' ? 'app_not_initialized' : undefined);
+ const records = waitForEvents(context, 1, dimensions.sessionId);
+ assert.equal(records.length, 1);
+ assert.deepEqual(Object.keys(records[0]).sort(), ['data', 'name', 'time']);
+ assert.equal(records[0].data.eventName, envelope.data.event_Name);
+ assert.equal(records[0].time, envelope.time);
+ }
+});
+
+test('checkpoint CLI keeps the invoking hook session across fresh processes', (t) => {
+ const context = fixture(t);
+ fs.writeFileSync(path.join(context.projectRoot, 'app.json'), JSON.stringify({
+ expo: { extra: { telemetry: { appInstanceId: null, cluster: 'us' } } },
+ }));
+ assert.equal(runHook('prompt', {
+ cwd: context.projectRoot,
+ session_id: 'session-1',
+ prompt: '/mobile-app:create-mobile-app',
+ }, context).status, 0);
+ assert.equal(waitForEvents(context, 1).length, 1);
+
+ for (const checkpoint of [
+ 'validate_development_toolchain|completed',
+ 'gather_app_requirements|started',
+ ]) {
+ const result = spawnSync(process.execPath, [
+ path.join(PLUGIN_ROOT, 'scripts', 'emit-telemetry-checkpoint.js'),
+ `create-mobile-app|${checkpoint}`,
+ ], {
+ cwd: context.projectRoot,
+ encoding: 'utf8',
+ timeout: 10_000,
+ env: {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: context.configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: context.ikeyPath,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',
+ },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ }
+
+ const records = waitForEvents(context, 3);
+ assert.deepEqual(records.map((record) => record.data.eventName).sort(), [
+ 'gather_app_requirements_started',
+ 'skill_started',
+ 'validate_development_toolchain_completed',
+ ]);
+ assert.ok(records.every((record) => record.data.sessionId === 'session-1'));
+ assert.equal(new Set(records.map((record) => record.data.correlationId)).size, 3);
+});
+
test('prompt and pretool paths emit independent start signals', (t) => {
const context = fixture(t);
assert.equal(runHook('prompt', {
diff --git a/plugins/mobile-apps/scripts/tests/mobile-telemetry-region.test.js b/plugins/mobile-apps/scripts/tests/mobile-telemetry-region.test.js
index 993ad9ada..f43c026fa 100644
--- a/plugins/mobile-apps/scripts/tests/mobile-telemetry-region.test.js
+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry-region.test.js
@@ -8,7 +8,7 @@ const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { resolve: resolveDestination } = require('../lib/telemetry/resolver');
-const { deriveRegion, resolve } = require('../lib/telemetry/region/region-resolver');
+const { deriveRegion, resolve, resolveClusterEnvironment } = require('../lib/telemetry/region/region-resolver');
const { urlFor } = require('../lib/telemetry/region/artemis-service');
const { readTelemetryCluster, writeTelemetryCluster } = require('../lib/app-identity');
@@ -27,7 +27,12 @@ function project(t, telemetry) {
return root;
}
-const neverCalled = () => { throw new Error('must not run'); };
+function resolvedEnvironment(root, clusterGeoName, environmentId = orgId) {
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify({
+ environmentId, tenantId: environmentId, environmentUrl: 'https://contoso.crm4.dynamics.com',
+ clusterEnvironment: 'Prod', clusterGeoName,
+ }));
+}
test('Mobile declares the seven Power Apps telemetry destinations', () => {
assert.deepEqual(Object.keys(config.regions).sort(), [
@@ -35,52 +40,75 @@ test('Mobile declares the seven Power Apps telemetry destinations', () => {
]);
});
-test('step 1: a cluster in app.json is used without touching pac or Artemis', async (t) => {
+test('resolveClusterEnvironment returns a saved cluster, resolves a cache miss, or returns null', async (t) => {
+ const root = project(t, { appInstanceId: null, cluster: 'us' });
+ assert.equal(await resolveClusterEnvironment(root), 'us');
+ writeTelemetryCluster(root, null);
+ assert.equal(await resolveClusterEnvironment(root), null);
+ resolvedEnvironment(root, 'EU');
+ assert.equal(await resolveClusterEnvironment(root), 'eu');
+ assert.equal(readTelemetryCluster(root), 'eu');
+ writeTelemetryCluster(root, null);
+ resolvedEnvironment(root, 'unknown');
+ assert.equal(await resolveClusterEnvironment(root), null);
+ assert.equal(readTelemetryCluster(root), '');
+ assert.equal(await resolveClusterEnvironment(''), null);
+ assert.deepEqual(fs.readdirSync(root).sort(), ['.resolved-environment.json', 'app.json']);
+ resolvedEnvironment(root, 'EU');
+ fs.writeFileSync(path.join(root, 'app.json'), '{bad json');
+ assert.equal(await resolveClusterEnvironment(root), null);
+ assert.equal(fs.readFileSync(path.join(root, 'app.json'), 'utf8'), '{bad json');
+ fs.unlinkSync(path.join(root, 'app.json'));
+ assert.equal(await resolveClusterEnvironment(root), null);
+ assert.equal(fs.existsSync(path.join(root, 'app.json')), false);
+});
+
+test('cluster resolution has no dependency on telemetry delivery or the CLI entry point', () => {
+ const pending = [require.cache[require.resolve('../lib/telemetry/region/region-resolver')]];
+ const visited = new Set();
+ const forbidden = new Set([
+ require.resolve('../lib/mobile-telemetry-dispatcher'),
+ require.resolve('../resolve-environment'),
+ ]);
+ while (pending.length) {
+ const current = pending.pop();
+ if (visited.has(current.id)) continue;
+ visited.add(current.id);
+ assert.equal(forbidden.has(current.id), false, current.id);
+ pending.push(...current.children);
+ }
+});
+
+test('app.json cluster alone selects the collector without mutating configuration', async (t) => {
const root = project(t, { appInstanceId: null, cluster: 'eu' });
+ const before = fs.readFileSync(path.join(root, 'app.json'), 'utf8');
const destination = await resolve({
projectRoot: root,
regionsMap: config.regions,
- _readPacAuth: neverCalled,
- _fetchGeo: neverCalled,
});
assert.equal(destination.region, 'eu');
assert.equal(destination.iKey, config.regions.eu.instrumentation_key);
assert.equal(destination.collectorUrl, config.regions.eu.collector_url);
+ assert.equal(fs.readFileSync(path.join(root, 'app.json'), 'utf8'), before);
});
-test('step 2: an unresolved cluster falls back to whoami and is persisted', async (t) => {
- const root = project(t, { appInstanceId: null, cluster: null });
- const destination = await resolve({
- projectRoot: root,
- regionsMap: config.regions,
- _readPacAuth: () => ({ orgId, cloud: 'Public' }),
- _fetchGeo: () => Promise.resolve({ geoName: 'eu', stamp: 'Public' }),
- });
- assert.equal(destination.region, 'eu');
- assert.equal(readTelemetryCluster(root), 'eu');
-
- // The persisted value is what makes later events skip the pac fork entirely.
- const second = await resolve({
- projectRoot: root,
- regionsMap: config.regions,
- _readPacAuth: neverCalled,
- _fetchGeo: neverCalled,
- });
- assert.equal(second.region, 'eu');
+test('routing follows cluster updates and clearing in app.json', async (t) => {
+ const root = project(t, { appInstanceId: null, cluster: 'eu' });
+ writeTelemetryCluster(root, 'us');
+ assert.equal((await resolve({ projectRoot: root, regionsMap: config.regions })).region, 'us');
+ writeTelemetryCluster(root, null);
+ assert.equal(await resolve({ projectRoot: root, regionsMap: config.regions }), null);
});
-test('step 3: still unresolved stays local', async (t) => {
+test('missing or invalid clusters resolve from the known environment before choosing a destination', async (t) => {
const root = project(t, { appInstanceId: null, cluster: null });
- const cases = [
- { _readPacAuth: () => null, _fetchGeo: neverCalled },
- { _readPacAuth: () => ({ orgId, cloud: 'Public' }), _fetchGeo: () => Promise.resolve(null) },
- { _readPacAuth: () => ({ orgId, cloud: 'Public' }), _fetchGeo: () => Promise.reject(new Error('offline')) },
- { _readPacAuth: () => ({ orgId, cloud: 'Public' }), _fetchGeo: () => Promise.resolve({ geoName: 'zz' }) },
- ];
- for (const seam of cases) {
- assert.equal(await resolve({ projectRoot: root, regionsMap: config.regions, ...seam }), null);
+ resolvedEnvironment(root, 'EU');
+ for (const cluster of [null, '', 'moon-base']) {
+ fs.writeFileSync(path.join(root, 'app.json'), JSON.stringify({ expo: { extra: { telemetry: { cluster } } } }));
+ assert.equal((await resolve({ projectRoot: root, regionsMap: config.regions })).region, 'eu');
+ assert.equal(readTelemetryCluster(root), 'eu');
}
- assert.equal(readTelemetryCluster(root), '');
+ assert.equal(await resolve({ projectRoot: root, regionsMap: config.regions, cluster: null }), null);
assert.equal(await resolveDestination({ cfg: config, projectRoot: '' }), null);
});
@@ -89,6 +117,24 @@ test('a hand-edited cluster is ignored rather than trusted', (t) => {
assert.equal(readTelemetryCluster(root), '');
});
+test('routing ignores CLI configuration and environment caches', async (t) => {
+ const root = project(t, { cluster: 'us' });
+ fs.writeFileSync(path.join(root, 'power.config.json'), '{bad json');
+ fs.writeFileSync(path.join(root, 'auth.config.json'), '{bad json');
+ resolvedEnvironment(root, 'EU');
+ assert.equal((await resolve({ projectRoot: root, regionsMap: config.regions })).region, 'us');
+});
+
+test('all seven saved clusters select their configured destinations', async (t) => {
+ const root = project(t, { cluster: null });
+ for (const [cluster, entry] of Object.entries(config.regions)) {
+ writeTelemetryCluster(root, cluster);
+ assert.deepEqual(await resolve({ projectRoot: root, regionsMap: config.regions }), {
+ region: cluster, iKey: entry.instrumentation_key, collectorUrl: entry.collector_url,
+ });
+ }
+});
+
test('persisting a cluster preserves unrelated app.json content', (t) => {
const root = project(t, { appInstanceId: 'keep-me', cluster: null });
writeTelemetryCluster(root, 'gov');
@@ -98,8 +144,38 @@ test('persisting a cluster preserves unrelated app.json content', (t) => {
assert.equal(appJson.expo.extra.telemetry.cluster, 'gov');
});
+// Canonical BAP `location` names from the live public-cloud catalog, verified 2026-09-07.
+// Display names, properties.code, macroRegionId, and azureRegions are separate fields.
+// See: https://learn.microsoft.com/en-us/powershell/module/microsoft.powerapps.administration.powershell/get-adminpowerappenvironmentlocations
+test('every catalogued public BAP location maps to the expected cluster', () => {
+ const locationsByCluster = {
+ us: [
+ 'unitedstates', 'unitedstatesfirstrelease', 'asia', 'australia', 'india', 'japan',
+ 'canada', 'southamerica', 'unitedarabemirates', 'korea', 'southafrica',
+ ],
+ eu: [
+ 'europe', 'unitedkingdom', 'france', 'germany', 'switzerland', 'norway',
+ 'sweden', 'italy', 'poland',
+ ],
+ };
+ for (const [cluster, locations] of Object.entries(locationsByCluster)) {
+ for (const location of locations) {
+ assert.equal(deriveRegion('Public', location), cluster, location);
+ assert.equal(deriveRegion('Public', location.toUpperCase()), cluster, location);
+ assert.equal(deriveRegion('Preview', location), cluster, location);
+ }
+ }
+ for (const location of ['EMEA', 'north-america', 'eu-efta', 'eastus', 'westeurope', 'europefirstrelease']) {
+ assert.equal(deriveRegion('Public', location), '', location);
+ }
+});
+
test('cloud and public geography map to the expected cluster', () => {
assert.equal(deriveRegion('Public', 'us'), 'us');
+ assert.equal(deriveRegion('Public', 'unitedstatesfirstrelease'), 'us');
+ assert.equal(deriveRegion('Preview', 'UnitedStatesFirstRelease'), 'us');
+ assert.equal(deriveRegion('Public', 'unitedstatesfirstrelease-unknown'), '');
+ assert.equal(deriveRegion('unknown', 'unitedstatesfirstrelease'), '');
assert.equal(deriveRegion('Public', 'eu'), 'eu');
assert.equal(deriveRegion('UsGov', 'anything'), 'gov');
assert.equal(deriveRegion('UsGovHigh', 'anything'), 'high');
@@ -137,7 +213,7 @@ function waitForJson(filePath) {
// The other tests inject seams. This one runs the real hook against the real
// ikey.json so the shipped resolver.js is actually loaded and its regional keys
// are the ones that reach the wire.
-test('end to end: the real hook routes to the cluster recorded in app.json', (t) => {
+test('end to end: a connector start initializes a null cluster before app prerequisites', (t) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-region-e2e-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const projectRoot = path.join(root, 'project');
@@ -150,8 +226,11 @@ test('end to end: the real hook routes to the cluster recorded in app.json', (t)
);
fs.writeFileSync(
path.join(projectRoot, 'app.json'),
- JSON.stringify({ expo: { name: 'demo', extra: { telemetry: { appInstanceId: null, cluster: 'eu' } } } }),
+ JSON.stringify({ expo: { name: 'demo', extra: { telemetry: { appInstanceId: null, cluster: null } } } }),
);
+ resolvedEnvironment(projectRoot, 'EU');
+ assert.equal(readTelemetryCluster(projectRoot), '');
+ assert.equal(fs.existsSync(path.join(projectRoot, 'power.config.json')), false);
const probePath = path.join(root, 'probe.json');
const result = spawnSync(
@@ -159,7 +238,9 @@ test('end to end: the real hook routes to the cluster recorded in app.json', (t)
[path.join(PLUGIN_ROOT, 'hooks', 'run-telemetry.js'), 'prompt'],
{
cwd: projectRoot,
- input: JSON.stringify({ cwd: projectRoot, session_id: 'session-1', prompt: '/mobile-app:deploy' }),
+ input: JSON.stringify({ cwd: projectRoot, session_id: 'session-1',
+ prompt: 'The user explicitly invoked the "/mobile-app:add-connector" skill. Follow its instructions now.\n\n' +
+ '<skill-context name="add-connector">\nredacted instructions\n</skill-context>\ntet' }),
encoding: 'utf8',
timeout: 20_000,
env: {
@@ -169,6 +250,7 @@ test('end to end: the real hook routes to the cluster recorded in app.json', (t)
// The probe keeps this off the network while still proving which key won.
POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,
POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '',
+ PATH: '',
},
},
);
@@ -176,6 +258,7 @@ test('end to end: the real hook routes to the cluster recorded in app.json', (t)
assert.equal(result.status, 0);
const probe = waitForJson(probePath);
assert.ok(probe, 'dispatcher should write the fake HTTPS probe');
+ assert.equal(readTelemetryCluster(projectRoot), 'eu');
assert.equal(probe.headers['x-apikey'], config.regions.eu.instrumentation_key);
assert.equal(probe.url, config.regions.eu.collector_url);
// US and EU share the production key, so the collector is the real discriminator.
@@ -209,7 +292,7 @@ test('end to end: an unresolvable cluster transmits nothing', (t) => {
POWER_PLATFORM_SKILLS_IKEY_JSON: REAL_IKEY_PATH,
POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,
POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '',
- // No PAC on PATH, so step 2 cannot resolve and the event must stay local.
+ // A missing cluster must leave the event local without CLI discovery.
PATH: '',
},
},
diff --git a/plugins/mobile-apps/scripts/tests/mobile-telemetry-replay.test.js b/plugins/mobile-apps/scripts/tests/mobile-telemetry-replay.test.js
new file mode 100644
index 000000000..a0abc5b88
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry-replay.test.js
@@ -0,0 +1,193 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { setTimeout: delay } = require('node:timers/promises');
+const { appendLocal } = require('../lib/telemetry/lib/local-log');
+const { readPriorEvents } = require('../lib/mobile-telemetry-dispatcher');
+
+const appInstanceId = '11111111-1111-4111-8111-111111111111';
+const environmentId = '22222222-2222-4222-8222-222222222222';
+
+test('prior event scan reads nested and rotated logs without Dirent path metadata', (context) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-replay-paths-'));
+ context.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const configDir = path.join(root, 'config');
+ const env = { POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '' };
+ fs.writeFileSync(path.join(root, 'app.json'), JSON.stringify({
+ expo: { extra: { telemetry: { appInstanceId, cluster: null } } },
+ }));
+ const makeRecord = (sessionId, time) => ({
+ time, name: 'event',
+ data: { pluginName: 'mobile-app', eventName: 'skill_started', sessionId,
+ eventInfo: { appInstanceId } },
+ });
+ const records = [
+ makeRecord('older', '2026-09-07T01:00:00.000Z'),
+ makeRecord('newer', '2026-09-07T02:00:00.000Z'),
+ ];
+ for (const record of records) appendLocal(record, { configDir });
+ const history = path.join(configDir, 'telemetry', 'mobile-app', 'sessions', 'older');
+ fs.renameSync(path.join(history, 'events.jsonl'), path.join(history, 'events.20260907010000.old'));
+
+ const readDirectory = fs.readdirSync;
+ context.mock.method(fs, 'readdirSync', (directory, options) => {
+ const entries = readDirectory(directory, options);
+ if (!options?.withFileTypes) return entries;
+ return entries.map((entry) => ({
+ name: entry.name,
+ isFile: () => entry.isFile(),
+ isDirectory: () => entry.isDirectory(),
+ }));
+ });
+
+ assert.deepEqual(readPriorEvents(root, env), records);
+});
+
+test('first resolution replays this app across sessions without duplicating logs or replaying twice', async (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-replay-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const configDir = path.join(root, 'config');
+ const probe = path.join(root, 'probe.json');
+ const env = { ...process.env, PATH: '', POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: path.resolve(__dirname, '../lib/telemetry/ikey.json'),
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probe, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '' };
+ fs.writeFileSync(path.join(root, 'app.json'), JSON.stringify({ expo: { extra: { telemetry: { appInstanceId, cluster: null } } } }));
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify({ environmentId,
+ environmentUrl: 'https://contoso.crm4.dynamics.com', tenantId: environmentId,
+ 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 } },
+ });
+ appendLocal(makeRecord('first'), { configDir });
+ appendLocal(makeRecord('second'), { configDir });
+ appendLocal(makeRecord('other', environmentId), { configDir });
+ const history = path.join(configDir, 'telemetry/mobile-app/sessions/first');
+ fs.renameSync(path.join(history, 'events.jsonl'), path.join(history, 'events.20260907010000.old'));
+ fs.writeFileSync(path.join(history, 'events.jsonl'), '{incomplete\n');
+ assert.equal(readPriorEvents(root, { ...env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' }).length, 0);
+ fs.writeFileSync(path.join(configDir, 'config.json'), JSON.stringify({ telemetry: { 'mobile-app': 'off' } }));
+ assert.equal(readPriorEvents(root, env).length, 0);
+ fs.writeFileSync(path.join(configDir, 'config.json'), '{}');
+ const run = () => spawnSync(process.execPath, [path.resolve(__dirname, '../resolve-environment.js'), environmentId], {
+ cwd: root, env, encoding: 'utf8', timeout: 5000,
+ });
+ const result = run();
+ assert.equal(result.status, 0, result.stderr);
+ let captured;
+ for (let attempt = 0; attempt < 100; attempt += 1) {
+ try { captured = JSON.parse(fs.readFileSync(probe, 'utf8')); break; } catch { await delay(20); }
+ }
+ assert.ok(captured, 'first resolution should send existing logs without another event');
+ const envelopes = captured.body.trim().split('\n').map(line => JSON.parse(line));
+ assert.deepEqual(envelopes.map(event => event.data.session_Id).sort(), ['first', 'second']);
+ assert.ok(envelopes.every(event => event.time === '2026-09-07T01:00:00.000Z'));
+ const log = path.join(history, 'events.20260907010000.old');
+ assert.equal(fs.readFileSync(log, 'utf8').trim().split('\n').length, 1);
+ fs.writeFileSync(probe, 'unchanged');
+ assert.equal(run().status, 0);
+ await delay(100);
+ assert.equal(fs.readFileSync(probe, 'utf8'), 'unchanged');
+});
+
+test('null results stay local and the first non-null cluster dispatches history once', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-replay-auto-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const configDir = path.join(root, 'config');
+ const env = { ...process.env, PATH: '', POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_PROJECT_ROOT: root,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: path.resolve(__dirname, '../lib/telemetry/ikey.json'),
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: path.join(root, 'probe.json'), POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '' };
+ const appPath = path.join(root, 'app.json');
+ const authPath = path.join(root, 'auth.config.json');
+ fs.writeFileSync(appPath, JSON.stringify({ expo: { extra: { telemetry: { appInstanceId, cluster: null } } } }));
+ const dataFor = (sessionId, identity = appInstanceId) => ({ pluginName: 'mobile-app', sessionId,
+ eventName: 'skill_started', skillName: 'add-connector', eventInfo: { appInstanceId: identity } });
+ const previousTime = '2026-09-07T01:00:00.000Z';
+ appendLocal({ time: previousTime, name: 'event', data: dataFor('previous') }, { configDir });
+ appendLocal({ time: previousTime, name: 'event', data: dataFor('other', environmentId) }, { configDir });
+ const run = (sessionId) => {
+ const result = spawnSync(process.execPath, [path.resolve(__dirname, '../lib/mobile-telemetry-dispatcher.js')], {
+ cwd: os.tmpdir(), env, encoding: 'utf8', timeout: 5000,
+ input: JSON.stringify({ name: 'event', data: dataFor(sessionId) }),
+ });
+ assert.equal(result.status, 0, result.stderr);
+ if (!fs.existsSync(env.POWER_PLATFORM_SKILLS_FAKE_HTTPS)) return [];
+ const captured = JSON.parse(fs.readFileSync(env.POWER_PLATFORM_SKILLS_FAKE_HTTPS, 'utf8'));
+ return captured.body.trim().split('\n').map(line => JSON.parse(line));
+ };
+ assert.deepEqual(run('waiting'), []);
+ assert.equal(JSON.parse(fs.readFileSync(appPath, 'utf8')).expo.extra.telemetry.cluster, null);
+ const waitingPath = path.join(configDir, 'telemetry/mobile-app/sessions/waiting/events.jsonl');
+ const waitingRecord = fs.readFileSync(waitingPath, 'utf8');
+ fs.writeFileSync(authPath, JSON.stringify({ msal: { clientId: 'preserve' }, environment: { environmentId,
+ environmentUrl: 'https://contoso.crm4.dynamics.com', tenantId: environmentId,
+ clusterEnvironment: 'Prod', clusterGeoName: 'EU' } }));
+ const first = run('current');
+ assert.deepEqual(first.map(event => event.data.session_Id), ['previous', 'waiting', 'current']);
+ assert.equal(first[0].time, previousTime);
+ assert.equal(first[1].time, JSON.parse(waitingRecord).time);
+ assert.equal(fs.readFileSync(waitingPath, 'utf8'), waitingRecord);
+ const savedApp = fs.readFileSync(appPath, 'utf8');
+ assert.deepEqual(JSON.parse(savedApp).expo.extra.telemetry, { appInstanceId, cluster: 'eu' });
+ assert.equal(JSON.parse(fs.readFileSync(authPath, 'utf8')).msal.clientId, 'preserve');
+
+ fs.unlinkSync(path.join(root, '.resolved-environment.json'));
+ fs.writeFileSync(authPath, '{bad json');
+ fs.writeFileSync(path.join(root, 'power.config.json'), '{bad json');
+ const second = run('next');
+ assert.deepEqual(second.map(event => event.data.session_Id), ['next']);
+ assert.equal(fs.readFileSync(appPath, 'utf8'), savedApp);
+ assert.equal(fs.readFileSync(authPath, 'utf8'), '{bad json');
+ assert.equal(fs.existsSync(path.join(root, '.resolved-environment.json')), false);
+ const records = readPriorEvents(root, env);
+ assert.equal(records.length, 4);
+ for (const record of records) {
+ assert.deepEqual(Object.keys(record).sort(), ['data', 'name', 'time']);
+ assert.deepEqual(record.data, dataFor(record.data.sessionId));
+ }
+});
+
+test('dispatcher preserves the original event shape for unresolved, opted-out and routed events', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-replay-log-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const configDir = path.join(root, 'config');
+ const env = { ...process.env, PATH: '', POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_PROJECT_ROOT: root,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: path.resolve(__dirname, '../lib/telemetry/ikey.json'),
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: path.join(root, 'probe.json'), POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '' };
+ const appPath = path.join(root, 'app.json');
+ fs.writeFileSync(appPath, JSON.stringify({ expo: { extra: { telemetry: { appInstanceId, cluster: null } } } }));
+ const cached = { environmentId, environmentUrl: 'https://contoso.crm4.dynamics.com', tenantId: environmentId };
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify(cached));
+ 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 } } }),
+ });
+ assert.equal(result.status, 0, result.stderr);
+ };
+ run('unresolved');
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify({ ...cached,
+ clusterEnvironment: 'Prod', clusterGeoName: 'EU' }));
+ run('opted-out', { ...env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' });
+ assert.equal(JSON.parse(fs.readFileSync(appPath, 'utf8')).expo.extra.telemetry.cluster, null);
+ assert.equal(fs.existsSync(env.POWER_PLATFORM_SKILLS_FAKE_HTTPS), false);
+ fs.writeFileSync(appPath, JSON.stringify({ expo: { extra: { telemetry: { appInstanceId, cluster: 'eu' } } } }));
+ run('routed');
+ assert.ok(fs.existsSync(env.POWER_PLATFORM_SKILLS_FAKE_HTTPS));
+ for (const sessionId of ['unresolved', 'opted-out', 'routed']) {
+ const logPath = path.join(configDir, 'telemetry/mobile-app/sessions', sessionId, 'events.jsonl');
+ const record = JSON.parse(fs.readFileSync(logPath, 'utf8').trim());
+ 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 } });
+ }
+});
\ 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 2849aa95a..fc970a406 100644
--- a/plugins/mobile-apps/scripts/tests/mobile-telemetry.test.js
+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry.test.js
@@ -18,6 +18,7 @@ const {
} = require('../emit-telemetry-checkpoint');
const { ensureAppInstanceId, findAppInstanceId } = require('../lib/app-identity');
const { TRACKED_SKILL_NAMES } = require('../lib/mobileapp-hook-utils');
+const { readProcessScope } = require('../lib/mobile-telemetry-session');
const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');
const TELEMETRY_CLI = path.join(
@@ -136,6 +137,40 @@ test('provisioned context uses host session and isolated config paths', () => {
assert.equal(context.eventStreamName, 'MobileAppsTestEvent');
});
+test('Windows session lookup requests only identity fields within the hook deadline', () => {
+ let command;
+ const scope = readProcessScope({
+ platform: 'win32',
+ parentPid: 300,
+ exec: (executable, args, options) => {
+ command = { executable, args, options };
+ return JSON.stringify([
+ { ProcessId: 300, ParentProcessId: 200, CreationDate: '/Date(1788850001000)/', Name: 'cmd.exe' },
+ { ProcessId: 200, ParentProcessId: 100, CreationDate: '/Date(1788850000000)/', Name: 'C:\\Program Files\\nodejs\\node.exe' },
+ ]);
+ },
+ });
+
+ assert.equal(scope, '200:/Date(1788850000000)/');
+ assert.equal(command.executable, 'powershell.exe');
+ assert.ok(command.args.includes('-NoProfile'));
+ assert.ok(command.args.includes('-NonInteractive'));
+ assert.match(command.args.at(-1), /Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate,Name/);
+ assert.doesNotMatch(command.args.at(-1), /CommandLine|ExecutablePath/);
+ assert.ok(command.options.timeout >= 5000 && command.options.timeout < 10000,
+ 'allow bounded PowerShell startup time while staying below the ten-second hook deadline');
+});
+
+test('Windows session lookup remains fail-open when process metadata is unavailable', () => {
+ for (const code of ['ETIMEDOUT', 'ENOENT']) {
+ assert.equal(readProcessScope({
+ platform: 'win32',
+ exec: () => { throw Object.assign(new Error('Process metadata unavailable'), { code }); },
+ }), '');
+ }
+ assert.equal(readProcessScope({ platform: 'win32', exec: () => '{incomplete' }), '');
+});
+
test('nested Copilot call resolves to its owning root session', (t) => {
const rootSessionId = 'e58e3db3-8361-4516-ac4b-6b143c22100a';
const nestedSessionId = 'call_ayAuxKIYLLOtpejidbHsMAmu';
@@ -315,6 +350,22 @@ test('checkpoint event carries only static checkpoint enrichment', (t) => {
}
});
+test('shared instructions own checkpoint execution and lifecycle rules', () => {
+ const shared = fs.readFileSync(path.join(PLUGIN_ROOT, 'shared', 'shared-instructions.md'), 'utf8');
+ 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.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, /fail-open/);
+ assert.match(checkpointSection, /Do not duplicate emissions/);
+});
+
test('create-mobile-app uses precise checkpoint names at major workflow boundaries', () => {
const shared = fs.readFileSync(path.join(PLUGIN_ROOT, 'shared', 'shared-instructions.md'), 'utf8');
const workflow = fs.readFileSync(
@@ -322,7 +373,8 @@ test('create-mobile-app uses precise checkpoint names at major workflow boundari
'utf8',
);
- assert.match(shared, /node "\$\{CLAUDE_SKILL_DIR\}\/\.\.\/\.\.\/scripts\/emit-telemetry-checkpoint\.js"/);
+ assert.match(shared, /node "\$\{PLUGIN_ROOT\}\/scripts\/emit-telemetry-checkpoint\.js"/);
+ assert.doesNotMatch(shared, /node "\$\{CLAUDE_SKILL_DIR\}/);
assert.doesNotMatch(shared, /trigger-telemetry/);
assert.deepEqual(
[...workflow.matchAll(/\*\*Telemetry checkpoint: `([^`]+)`\*\*/g)]
@@ -364,6 +416,11 @@ test('every tracked operational skill has precise checkpoint markers', () => {
}
assert.ok(matches.length > 0, `${skillName} must define at least one checkpoint`);
+ assert.match(workflow.slice(0, matches[0].index),
+ /\[[^\]]+\]\((?:\.\.\/\.\.\/|\$\{PLUGIN_ROOT\}\/)shared\/shared-instructions\.md\)/,
+ `${skillName} must reference shared instructions before its first checkpoint`);
+ assert.doesNotMatch(workflow, /\*\*Checkpoint execution:\*\*|emit-telemetry-checkpoint\.js/,
+ `${skillName} must inherit checkpoint execution from shared instructions`);
const names = matches.map((match) => match[1]);
assert.equal(new Set(names).size, names.length, `${skillName} checkpoint names must be unique`);
@@ -457,6 +514,25 @@ test('events outside a project carry no app identity', (t) => {
assert.equal(findAppInstanceId(tempProject(t)), '');
});
+test('event identity initialization leaves missing or invalid project files untouched', (t) => {
+ const context = contextFor(provisioned);
+ const emitFrom = (cwd) => emitSkillStarted(context, invocation, {
+ emit: () => {},
+ readAiAgent: () => ({}),
+ cwd,
+ }).data;
+
+ for (const contents of [null, '{ invalid json', '{}']) {
+ const project = tempProject(t);
+ const filePath = path.join(project, 'app.json');
+ if (contents !== null) fs.writeFileSync(filePath, contents);
+ assert.equal(emitFrom(project).eventInfo.appInstanceId, null);
+ assert.equal(fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : null, contents);
+ }
+ assert.equal(emitFrom('').eventInfo.appInstanceId, null);
+ assert.equal(emitFrom(undefined).eventInfo.appInstanceId, null);
+});
+
test('a hand-edited app identity is ignored rather than emitted', (t) => {
const project = tempProject(t);
fs.writeFileSync(
@@ -474,7 +550,7 @@ test('a hand-edited app identity is ignored rather than emitted', (t) => {
assert.equal(findAppInstanceId(project), '');
});
-test('two apps in one session emit distinct app identities', (t) => {
+test('first events generate distinct app identities and later events reuse them', (t) => {
const context = contextFor(provisioned);
const emitFrom = (project) => emitSkillStarted(context, invocation, {
emit: () => {},
@@ -491,10 +567,14 @@ test('two apps in one session emit distinct app identities', (t) => {
const projectB = tempProject(t);
fs.writeFileSync(path.join(projectA, 'app.json'), JSON.stringify({ expo: {} }));
fs.writeFileSync(path.join(projectB, 'app.json'), JSON.stringify({ expo: {} }));
- ensureAppInstanceId(projectA);
- ensureAppInstanceId(projectB);
const a = emitFrom(projectA);
const b = emitFrom(projectB);
+ assert.match(a.eventInfo.appInstanceId, /^[0-9a-f-]{36}$/);
+ assert.match(b.eventInfo.appInstanceId, /^[0-9a-f-]{36}$/);
+ assert.equal(findAppInstanceId(projectA), a.eventInfo.appInstanceId);
+ assert.equal(findAppInstanceId(projectB), b.eventInfo.appInstanceId);
+ assert.equal(emitFrom(projectA).eventInfo.appInstanceId, a.eventInfo.appInstanceId);
+ assert.equal(emitFrom(projectB).eventInfo.appInstanceId, b.eventInfo.appInstanceId);
assert.notEqual(a.eventInfo.appInstanceId, b.eventInfo.appInstanceId);
assert.equal(a.sessionId, b.sessionId);
});
diff --git a/plugins/mobile-apps/scripts/tests/mobileapp-hook-utils.test.js b/plugins/mobile-apps/scripts/tests/mobileapp-hook-utils.test.js
index 767833c41..5984b391f 100644
--- a/plugins/mobile-apps/scripts/tests/mobileapp-hook-utils.test.js
+++ b/plugins/mobile-apps/scripts/tests/mobileapp-hook-utils.test.js
@@ -89,6 +89,16 @@ test('prompt detection accepts Copilot manual skill-context wrappers', () => {
);
});
+test('prompt detection accepts the observed interactive Copilot invocation prefix', () => {
+ const prefix = 'The user explicitly invoked the "/mobile-app:create-mobile-app" skill. Follow its instructions now.\n\n';
+ const wrapper = '<skill-context name="create-mobile-app">\nredacted instructions';
+ assert.equal(getTrackedSkillFromPrompt(prefix + wrapper), 'create-mobile-app');
+ assert.equal(getTrackedSkillFromPrompt(prefix.replace('mobile-app:', '') + wrapper), 'create-mobile-app');
+ assert.equal(getTrackedSkillFromPrompt(prefix + '<skill-context name="deploy">'), null);
+ assert.equal(getTrackedSkillFromPrompt(prefix.replace('mobile-app:', 'other-plugin:') + wrapper), null);
+ assert.equal(getTrackedSkillFromPrompt('please read this: ' + prefix + wrapper), null);
+});
+
test('reads known host tool-input field variants', () => {
assert.equal(getTrackedSkillFromToolInput({ skill: 'deploy' }), 'deploy');
assert.equal(getTrackedSkillFromToolInput({ skill_name: 'mobile-app:debug-app' }), 'debug-app');
diff --git a/plugins/mobile-apps/scripts/tests/resolve-environment.test.js b/plugins/mobile-apps/scripts/tests/resolve-environment.test.js
new file mode 100644
index 000000000..2599e4288
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/resolve-environment.test.js
@@ -0,0 +1,293 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { EventEmitter } = require('node:events');
+const { createRequire } = require('node:module');
+const vm = require('node:vm');
+const { cacheMatchesTarget, canUseCachedResolution, toEnvironmentResult, environmentFromPowerPlatformPayload } = require('../resolve-environment');
+
+const environmentId = '11111111-1111-4111-8111-111111111111';
+
+test('environment resolution preserves cluster routing metadata through cache serialization', () => {
+ for (const metadata of [{ location: 'unitedstatesfirstrelease', properties: {} }, { properties: { location: 'europe' } }]) {
+ const resolved = environmentFromPowerPlatformPayload({
+ ...metadata,
+ name: environmentId,
+ properties: {
+ ...metadata.properties,
+ linkedEnvironmentMetadata: { instanceUrl: 'https://contoso.crm4.dynamics.com' },
+ cluster: { environment: 'Prod', geoShortName: 'EU', category: 'FirstRelease' },
+ },
+ }, environmentId);
+ assert.equal(resolved.environmentId, environmentId);
+ assert.equal(Object.hasOwn(resolved, 'organizationId'), false);
+ assert.equal(resolved.clusterEnvironment, 'Prod');
+ assert.equal(resolved.clusterGeoName, 'EU');
+ assert.equal(toEnvironmentResult(resolved, 'cache').clusterEnvironment, 'Prod');
+ assert.equal(toEnvironmentResult(resolved, 'cache').clusterGeoName, 'EU');
+ assert.equal(Object.hasOwn(resolved, 'location'), false);
+ assert.equal(Object.hasOwn(toEnvironmentResult({ ...resolved, location: 'europe' }, 'cache'), 'location'), false);
+ assert.equal(cacheMatchesTarget(resolved, environmentId), true);
+ assert.equal(cacheMatchesTarget(resolved, '22222222-2222-4222-8222-222222222222'), false);
+ }
+ for (const cluster of [undefined, null, { category: 'FirstRelease' }, { environment: ['Prod'], geoShortName: ['EU'] }]) {
+ const resolved = environmentFromPowerPlatformPayload({
+ name: environmentId, properties: { cluster },
+ }, environmentId);
+ assert.equal(resolved.clusterEnvironment, null);
+ assert.equal(resolved.clusterGeoName, null);
+ }
+ assert.equal(Object.hasOwn(toEnvironmentResult({}, 'cache'), 'location'), false);
+ assert.equal(toEnvironmentResult({}, 'cache').clusterEnvironment, null);
+ assert.equal(toEnvironmentResult({}, 'cache').clusterGeoName, null);
+});
+
+test('old ID caches refresh for cluster metadata while URL caches remain compatible', () => {
+ const cached = { environmentId, environmentUrl: 'https://contoso.crm4.dynamics.com', tenantId: environmentId };
+ assert.equal(canUseCachedResolution(cached, environmentId), false);
+ assert.equal(canUseCachedResolution(cached, environmentId, 'eu'), true);
+ assert.equal(canUseCachedResolution(null, environmentId, 'eu'), false);
+ assert.equal(canUseCachedResolution({ ...cached, location: 'europe' }, environmentId), false);
+ assert.equal(canUseCachedResolution({ ...cached, clusterEnvironment: 'Prod', clusterGeoName: 'EU' }, environmentId), true);
+ assert.equal(canUseCachedResolution({ ...cached, clusterGeoName: 'EU' }, environmentId), false);
+ assert.equal(canUseCachedResolution({ ...cached, clusterEnvironment: 'Prod', clusterGeoName: ' ' }, environmentId), false);
+ assert.equal(canUseCachedResolution(cached, cached.environmentUrl), true);
+});
+
+test('failed cluster metadata refresh preserves connection details and auth settings', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-env-cache-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const cached = { environmentId, environmentUrl: 'https://contoso.crm4.dynamics.com', tenantId: environmentId, displayName: 'Example' };
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify({ ...cached, location: 'europe' }));
+ fs.writeFileSync(path.join(root, 'auth.config.json'), JSON.stringify({ msal: { clientId: 'preserve' } }));
+ const appPath = path.join(root, 'app.json');
+ fs.writeFileSync(appPath, JSON.stringify({ expo: { name: 'demo', extra: { telemetry: { appInstanceId: 'preserve', cluster: null } } } }));
+ const result = spawnSync(process.execPath, [path.resolve(__dirname, '../resolve-environment.js'), environmentId], {
+ cwd: root, encoding: 'utf8', timeout: 5000, env: { ...process.env, PATH: '' },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(JSON.parse(result.stdout), { ...cached, clusterEnvironment: null, clusterGeoName: null, source: 'cache-refresh' });
+ const auth = JSON.parse(fs.readFileSync(path.join(root, 'auth.config.json'), 'utf8'));
+ assert.equal(auth.msal.clientId, 'preserve');
+ assert.equal(auth.environment.environmentId, environmentId);
+ assert.equal(Object.hasOwn(auth.environment, 'location'), false);
+ assert.equal(Object.hasOwn(JSON.parse(fs.readFileSync(path.join(root, '.resolved-environment.json'), 'utf8')), 'location'), false);
+ assert.equal(JSON.parse(fs.readFileSync(appPath, 'utf8')).expo.extra.telemetry.cluster, null);
+
+ cached.clusterEnvironment = 'Prod';
+ cached.clusterGeoName = 'EU';
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify(cached));
+ const hit = spawnSync(process.execPath, [path.resolve(__dirname, '../resolve-environment.js'), environmentId], {
+ cwd: root, encoding: 'utf8', timeout: 5000, env: { ...process.env, PATH: '' },
+ });
+ assert.equal(hit.status, 0, hit.stderr);
+ assert.deepEqual(JSON.parse(hit.stdout), { ...cached, source: 'cache' });
+ const app = JSON.parse(fs.readFileSync(appPath, 'utf8'));
+ assert.equal(app.expo.extra.telemetry.cluster, 'eu');
+ assert.equal(app.expo.extra.telemetry.appInstanceId, 'preserve');
+ assert.equal(app.expo.name, 'demo');
+
+ const failed = spawnSync(process.execPath, [path.resolve(__dirname, '../resolve-environment.js'), '22222222-2222-4222-8222-222222222222'], {
+ cwd: root, encoding: 'utf8', timeout: 5000, env: { ...process.env, PATH: '' },
+ });
+ assert.equal(failed.status, 1);
+ assert.equal(JSON.parse(fs.readFileSync(appPath, 'utf8')).expo.extra.telemetry.cluster, 'eu');
+});
+
+test('a valid saved cluster avoids metadata refresh and is never overwritten', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-env-saved-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const appPath = path.join(root, 'app.json');
+ const app = JSON.stringify({ expo: { name: 'demo', extra: { telemetry: { cluster: 'eu' } } } });
+ fs.writeFileSync(appPath, app);
+ for (const clusterGeoName of [null, 'US', 'unknown']) {
+ const cached = { environmentId, environmentUrl: 'https://contoso.crm4.dynamics.com', tenantId: environmentId, clusterEnvironment: 'Prod', clusterGeoName };
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify(cached));
+ const result = spawnSync(process.execPath, [path.resolve(__dirname, '../resolve-environment.js'), environmentId], {
+ cwd: root, encoding: 'utf8', timeout: 5000, env: { ...process.env, PATH: '' },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(result.stdout).source, 'cache');
+ assert.equal(fs.readFileSync(appPath, 'utf8'), app);
+ }
+});
+
+test('an invalid cluster is filled when existing environment resolution provides cluster metadata', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-env-invalid-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const appPath = path.join(root, 'app.json');
+ for (const [clusterEnvironment, clusterGeoName, expected] of [
+ ['Prod', 'US', 'us'], ['Prod', 'EU', 'eu'], ['GccModerate', 'US', 'gov'],
+ ['GccHigh', 'US', 'high'], ['DoD', 'US', 'dod'], ['Mooncake', 'CN', 'mooncake'], ['Test', 'US', 'internal'],
+ ]) {
+ fs.writeFileSync(appPath, JSON.stringify({ expo: { extra: { telemetry: { cluster: 'unknown' } } } }));
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify({
+ environmentId, environmentUrl: 'https://contoso.crm4.dynamics.com', tenantId: environmentId, clusterEnvironment, clusterGeoName,
+ }));
+ const result = spawnSync(process.execPath, [path.resolve(__dirname, '../resolve-environment.js'), environmentId], {
+ cwd: root, encoding: 'utf8', timeout: 5000, env: { ...process.env, PATH: '' },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(fs.readFileSync(appPath, 'utf8')).expo.extra.telemetry.cluster, expected, clusterEnvironment);
+ }
+});
+
+test('missing or unknown cluster metadata never falls back to provisioning location', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-env-unresolved-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const appPath = path.join(root, 'app.json');
+ const app = JSON.stringify({ expo: { extra: { telemetry: { cluster: null } } } });
+ fs.writeFileSync(appPath, app);
+ for (const clusterMetadata of [
+ {}, { clusterEnvironment: 'Prod' }, { clusterGeoName: 'US' },
+ { clusterEnvironment: 'unknown', clusterGeoName: 'US' },
+ { clusterEnvironment: 'Prod', clusterGeoName: 'unknown' },
+ ]) {
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify({
+ environmentId, environmentUrl: 'https://contoso.crm.dynamics.com', tenantId: environmentId,
+ location: 'unitedstatesfirstrelease', ...clusterMetadata,
+ }));
+ const result = spawnSync(process.execPath, [path.resolve(__dirname, '../resolve-environment.js'), environmentId], {
+ cwd: root, encoding: 'utf8', timeout: 5000, env: { ...process.env, PATH: '' },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(Object.hasOwn(JSON.parse(result.stdout), 'location'), false);
+ assert.equal(fs.readFileSync(appPath, 'utf8'), app);
+ }
+});
+
+test('cached cluster geo overrides legacy provisioning location without discovery', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-env-first-release-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const appPath = path.join(root, 'app.json');
+ fs.writeFileSync(path.join(root, '.resolved-environment.json'), JSON.stringify({
+ environmentId, environmentUrl: 'https://contoso.crm.dynamics.com', tenantId: environmentId, location: 'unitedstatesfirstrelease',
+ clusterEnvironment: 'Prod', clusterGeoName: 'EU',
+ }));
+ for (const cluster of [null, 'unknown']) {
+ const app = { expo: { name: 'demo', extra: { telemetry: { appInstanceId: environmentId, cluster } } } };
+ fs.writeFileSync(appPath, JSON.stringify(app));
+ const result = spawnSync(process.execPath, [path.resolve(__dirname, '../resolve-environment.js'), environmentId], {
+ cwd: root, encoding: 'utf8', timeout: 5000,
+ env: { ...process.env, PATH: '', POWER_PLATFORM_SKILLS_CONFIG_DIR: path.join(root, 'config'), POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(result.stdout).source, 'cache');
+ assert.equal(Object.hasOwn(JSON.parse(result.stdout), 'location'), false);
+ app.expo.extra.telemetry.cluster = 'eu';
+ assert.deepEqual(JSON.parse(fs.readFileSync(appPath, 'utf8')), app);
+ }
+});
+
+test('resolveClusterEnvironment refreshes legacy metadata, skips saved lookups, and returns null on failure', async (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-env-initialize-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const appPath = path.join(root, 'app.json');
+ const cachePath = path.join(root, '.resolved-environment.json');
+ const authPath = path.join(root, 'auth.config.json');
+ const powerPath = path.join(root, 'power.config.json');
+ const app = { expo: { name: 'demo', extra: { telemetry: { appInstanceId: environmentId, cluster: null } } } };
+ fs.writeFileSync(appPath, JSON.stringify(app));
+ fs.writeFileSync(cachePath, JSON.stringify({ environmentId,
+ environmentUrl: 'https://contoso.crm.dynamics.com', tenantId: environmentId, location: 'europe' }));
+ fs.writeFileSync(authPath, JSON.stringify({ msal: { clientId: 'preserve' } }));
+
+ const scriptPath = path.resolve(__dirname, '../lib/environment-resolution.js');
+ const requireFromScript = createRequire(scriptPath);
+ const cliCalls = [];
+ const requests = [];
+ const environmentReads = [];
+ const resolverModule = { exports: {} };
+ let offline = false;
+ const mockedRequire = (name) => {
+ if (name === 'child_process') return { execFileSync(command, args) {
+ cliCalls.push({ command, args });
+ assert.equal(command, 'az');
+ if (offline) throw new Error('offline');
+ return args[1] === 'show' ? environmentId : 'test-token';
+ } };
+ if (name === 'https') return { request(url, options, callback) {
+ requests.push(url);
+ assert.equal(options.headers.Authorization, 'Bearer test-token');
+ const request = new EventEmitter();
+ request.destroy = () => {};
+ request.end = () => {
+ const response = new EventEmitter();
+ response.statusCode = 200;
+ response.headers = {};
+ callback(response);
+ response.emit('data', JSON.stringify({
+ name: new URL(url).pathname.split('/').pop(),
+ properties: { tenantId: environmentId,
+ linkedEnvironmentMetadata: { instanceUrl: 'https://contoso.crm.dynamics.com' },
+ cluster: { environment: 'Prod', geoShortName: 'US', category: 'FirstRelease' } },
+ }));
+ response.emit('end');
+ };
+ return request;
+ } };
+ if (name === 'fs') return { ...fs, readFileSync(filePath, ...args) {
+ environmentReads.push(filePath);
+ return fs.readFileSync(filePath, ...args);
+ } };
+ return requireFromScript(name);
+ };
+ vm.runInNewContext(fs.readFileSync(scriptPath, 'utf8'), {
+ require: mockedRequire, module: resolverModule, process, console, URL,
+ }, { filename: scriptPath });
+ const clusterPath = path.resolve(__dirname, '../lib/telemetry/region/region-resolver.js');
+ const requireFromCluster = createRequire(clusterPath);
+ const clusterModule = { exports: {} };
+ vm.runInNewContext(fs.readFileSync(clusterPath, 'utf8'), {
+ require: name => name === '../../environment-resolution' ? resolverModule.exports : requireFromCluster(name),
+ module: clusterModule,
+ }, { filename: clusterPath });
+ const { resolveClusterEnvironment } = clusterModule.exports;
+ assert.equal(await resolveClusterEnvironment(root), 'us');
+ assert.equal(requests.length, 1);
+ assert.match(requests[0], new RegExp(`/scopes/admin/environments/${environmentId}\\?`));
+ assert.deepEqual(cliCalls.map(call => call.args[1]), ['show', 'get-access-token']);
+ app.expo.extra.telemetry.cluster = 'us';
+ assert.deepEqual(JSON.parse(fs.readFileSync(appPath, 'utf8')), app);
+ const auth = JSON.parse(fs.readFileSync(authPath, 'utf8'));
+ assert.equal(auth.msal.clientId, 'preserve');
+ assert.equal(auth.environment.clusterEnvironment, 'Prod');
+ assert.equal(auth.environment.clusterGeoName, 'US');
+ assert.equal(Object.hasOwn(auth.environment, 'location'), false);
+ assert.equal(Object.hasOwn(JSON.parse(fs.readFileSync(cachePath, 'utf8')), 'location'), false);
+
+ const readsBefore = environmentReads.slice();
+ const savedApp = fs.readFileSync(appPath, 'utf8');
+ fs.writeFileSync(powerPath, '{bad json');
+ fs.writeFileSync(cachePath, '{bad json');
+ fs.writeFileSync(authPath, '{bad json');
+ assert.equal(await resolveClusterEnvironment(root), 'us');
+ assert.deepEqual(environmentReads, readsBefore);
+ assert.equal(cliCalls.length, 2);
+ assert.equal(requests.length, 1);
+ assert.equal(fs.readFileSync(appPath, 'utf8'), savedApp);
+
+ const selectedEnvironmentId = '22222222-2222-4222-8222-222222222222';
+ app.expo.extra.telemetry.cluster = null;
+ fs.writeFileSync(appPath, JSON.stringify(app));
+ fs.writeFileSync(powerPath, JSON.stringify({ environmentId: selectedEnvironmentId }));
+ fs.writeFileSync(cachePath, JSON.stringify({ environmentId,
+ environmentUrl: 'https://contoso.crm4.dynamics.com', tenantId: environmentId,
+ clusterEnvironment: 'Prod', clusterGeoName: 'EU' }));
+ assert.equal(await resolveClusterEnvironment(root), 'us');
+ assert.equal(requests.length, 2);
+ assert.match(requests[1], new RegExp(`/scopes/admin/environments/${selectedEnvironmentId}\\?`));
+ assert.equal(JSON.parse(fs.readFileSync(appPath, 'utf8')).expo.extra.telemetry.cluster, 'us');
+
+ fs.writeFileSync(appPath, JSON.stringify(app));
+ fs.unlinkSync(cachePath);
+ offline = true;
+ assert.equal(await resolveClusterEnvironment(root), null);
+ assert.equal(requests.length, 2);
+ assert.deepEqual(JSON.parse(fs.readFileSync(appPath, 'utf8')), app);
+});
\ No newline at end of file
diff --git a/plugins/mobile-apps/shared/shared-instructions.md b/plugins/mobile-apps/shared/shared-instructions.md
index c16529b23..17653c9b0 100644
--- a/plugins/mobile-apps/shared/shared-instructions.md
+++ b/plugins/mobile-apps/shared/shared-instructions.md
@@ -14,25 +14,23 @@ Run at the start of every skill execution (at most once per day). Notifies the u
---
-## Workflow Checkpoint Telemetry
+## Workflow Checkpoints
-A workflow opts a step into telemetry with this marker directly below its heading:
+Only steps with this marker directly below the heading emit checkpoint telemetry:
```markdown
**Telemetry checkpoint: `<static_snake_case_name>`**
```
-At a marked boundary, run this command with the current top-level skill 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.
```bash
-node "${CLAUDE_SKILL_DIR}/../../scripts/emit-telemetry-checkpoint.js" "<skill-name>|<checkpoint-name>|<state>|<optional-info>"
+node "${PLUGIN_ROOT}/scripts/emit-telemetry-checkpoint.js" "<skill-name>|<checkpoint-name>|<state>" || true
```
-Use `started` immediately before the work, then `completed` after success or `failed` before stopping on failure. A valid branch that bypasses the work emits only `skipped`. Omit the final `|<optional-info>` when no extra classification is needed.
-
-Checkpoint names and optional info must be fixed, author-written `snake_case` values of at most 64 characters. Optional info is for low-cardinality classifications such as `dependency_missing`; never interpolate prompts, errors, paths, names, identifiers, URLs, command output, or other runtime data. Do not emit checkpoints for unmarked steps. Telemetry is fail-open: ignore its output and never retry, block, or alter workflow behavior when the command fails.
-
-Name checkpoints with a precise verb-object phrase that identifies the work being measured, such as `validate_fresh_template` or `generate_connector_data_source`. Do not use broad phase labels such as `planning`, `scaffold`, `screens`, or `app_ready`, and do not include a lifecycle suffix such as `_started`, `_completed`, `_skipped`, or `_failed`; the emitter appends that state.
+- 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.
---
diff --git a/plugins/mobile-apps/skills/add-connector/SKILL.md b/plugins/mobile-apps/skills/add-connector/SKILL.md
index a67a89688..51e92aa93 100644
--- a/plugins/mobile-apps/skills/add-connector/SKILL.md
+++ b/plugins/mobile-apps/skills/add-connector/SKILL.md
@@ -27,6 +27,8 @@ The native host runtime (`@microsoft/power-apps-native-host`) handles connector
### Step 1 — Check Memory Bank
+**Telemetry checkpoint: `validate_connector_project`**
+
Check for `memory-bank.md` per [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md).
Also confirm we're inside a Power Apps mobile app:
diff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
index 003f1144b..f42c3e233 100644
--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
@@ -89,14 +89,6 @@ After the resume check, run the **fresh-template gate** from the section above.
**Do not silently copy a bundled template over the user's folder.** A fresh `plugins/mobile-apps/template` template may contain placeholder `power.config.json` with an empty `environmentId`; Step 5 removes that placeholder immediately before Step 6 runs `npx power-apps init`.
-After the fresh-template gate succeeds, or after the user confirms a resume, initialize the app identity before continuing:
-
-```bash
-node "${PLUGIN_ROOT}/scripts/lib/app-identity.js" "<working_dir>"
-```
-
-`app-identity.js` mints `app.json` `expo.extra.telemetry.appInstanceId` — a random per-project ID that lets usage telemetry tell this app apart from other apps built in the same session, and recognize it again in later sessions. It is idempotent, so a resume or re-run keeps the original ID. It contains no app name, path, or environment data. Commit it: it is the app's identity, not a per-machine cache.
-
### Step 1 — Prerequisites
**Telemetry checkpoint: `validate_development_toolchain`**