Crash and vitals health: storebound health [--weekly], validate findings, store-health skill
Play Developer Reporting API v1beta1 (crashRateMetricSet / anrRateMetricSet DAILY queries in America/Los_Angeles, user-perceived 28-day rates, worst device models, errorIssues:search) and App Store Connect perfPowerMetrics, diagnostic signatures and TestFlight crash submissions. Thresholds 1.09 % crash / 0.47 % ANR / 8 % per device (developer.android.com/topic/performance/vitals): over = blocker, from 80 % = warn, in validate too (--no-health). Weekly Markdown report with week-over-week change in .storebound/health/. MCP: health (read-only), health_report.
This commit is contained in:
parent
3f12452e3f
commit
56e107dbbe
16 changed files with 592 additions and 6 deletions
|
|
@ -46,6 +46,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
||||||
- `skills/release-management/SKILL.md`: Ship updates safely after the first release
|
- `skills/release-management/SKILL.md`: Ship updates safely after the first release
|
||||||
- `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game
|
- `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game
|
||||||
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile game
|
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile game
|
||||||
|
- `skills/store-health/SKILL.md`: Watch a released mobile game's crash and ANR health on both stores
|
||||||
- `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
|
- `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
|
||||||
- `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile game
|
- `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile game
|
||||||
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages
|
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages
|
||||||
|
|
|
||||||
1
.github/copilot-instructions.md
vendored
1
.github/copilot-instructions.md
vendored
|
|
@ -48,6 +48,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
||||||
| `release-management` | Ship updates safely after the first release |
|
| `release-management` | Ship updates safely after the first release |
|
||||||
| `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game |
|
| `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game |
|
||||||
| `store-declarations` | Answer the store compliance forms for a mobile game |
|
| `store-declarations` | Answer the store compliance forms for a mobile game |
|
||||||
|
| `store-health` | Watch a released mobile game's crash and ANR health on both stores |
|
||||||
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
|
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
|
||||||
| `store-preflight` | Run and read the storebound readiness checks before submitting a mobile game |
|
| `store-preflight` | Run and read the storebound readiness checks before submitting a mobile game |
|
||||||
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages |
|
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages |
|
||||||
|
|
|
||||||
|
|
@ -46,6 +46,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
||||||
- `skills/release-management/SKILL.md`: Ship updates safely after the first release
|
- `skills/release-management/SKILL.md`: Ship updates safely after the first release
|
||||||
- `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game
|
- `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game
|
||||||
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile game
|
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile game
|
||||||
|
- `skills/store-health/SKILL.md`: Watch a released mobile game's crash and ANR health on both stores
|
||||||
- `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
|
- `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
|
||||||
- `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile game
|
- `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile game
|
||||||
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages
|
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
||||||
| `release-management` | Ship updates safely after the first release |
|
| `release-management` | Ship updates safely after the first release |
|
||||||
| `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game |
|
| `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game |
|
||||||
| `store-declarations` | Answer the store compliance forms for a mobile game |
|
| `store-declarations` | Answer the store compliance forms for a mobile game |
|
||||||
|
| `store-health` | Watch a released mobile game's crash and ANR health on both stores |
|
||||||
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
|
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
|
||||||
| `store-preflight` | Run and read the storebound readiness checks before submitting a mobile game |
|
| `store-preflight` | Run and read the storebound readiness checks before submitting a mobile game |
|
||||||
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages |
|
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages |
|
||||||
|
|
|
||||||
|
|
@ -46,6 +46,17 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
||||||
return t ? JSON.parse(t) : {};
|
return t ? JSON.parse(t) : {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** GET with a vendor media type, e.g. perfPowerMetrics (application/vnd.apple.xcode-metrics+json). Parsed JSON. */
|
||||||
|
async function getAs(path: string, accept: string): Promise<J> {
|
||||||
|
for (let attempt = 1; ; attempt++) {
|
||||||
|
const r = await fetch('https://api.appstoreconnect.apple.com' + path, { headers: { Authorization: 'Bearer ' + jwt(), Accept: accept } });
|
||||||
|
const t = await r.text();
|
||||||
|
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await Bun.sleep(2000 * attempt); continue; }
|
||||||
|
if (!r.ok) throw new Error(`GET ${path} -> ${r.status} ${t.slice(0, 800)}`);
|
||||||
|
return t ? JSON.parse(t) : {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Every item of a paged GET. */
|
/** Every item of a paged GET. */
|
||||||
async function all(path: string): Promise<J[]> {
|
async function all(path: string): Promise<J[]> {
|
||||||
const out: J[] = [];
|
const out: J[] = [];
|
||||||
|
|
@ -95,5 +106,5 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
||||||
return res.id;
|
return res.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
return { asc, all, maybe, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
|
return { asc, all, maybe, getAs, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
102
cli/health.ts
Normal file
102
cli/health.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
||||||
|
// Crash and vitals health of the released game, read-only on both stores.
|
||||||
|
// storebound health [--apple] [--play] [--days 7] [--json]
|
||||||
|
// storebound health --weekly [--out .storebound/health] [--dry] also writes <date>.md (+ <date>.json for the next
|
||||||
|
// comparison); --dry prints the report instead of writing it
|
||||||
|
// Google Play: Play Developer Reporting API (user-perceived crash and ANR rates, 28-day user-weighted, the worst
|
||||||
|
// device models, top error issues). The service account needs "View app information (read-only)" and the API enabled
|
||||||
|
// in its Cloud project. App Store: power and performance metrics (perfPowerMetrics), diagnostic signatures of the
|
||||||
|
// latest builds, TestFlight crash submissions. Thresholds and sources: cli/lib/health.ts. `validate` reuses the
|
||||||
|
// same collection and adds the findings (over a Play bad behavior threshold = blocker).
|
||||||
|
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { ascClient, type J } from './apple/asc';
|
||||||
|
import type { Ctx } from './lib/ctx';
|
||||||
|
import { REPORTING_SCOPE } from './lib/google-auth';
|
||||||
|
import {
|
||||||
|
type AppleHealth, ANR_METRICS, betaCrashCounts, CRASH_METRICS, deviceBreakdown, healthFindings, healthMarkdown, type HealthSnapshot, healthTable,
|
||||||
|
issuesQuery, latestDailyEnd, metricQuery, parseIssues, parseMetricRows, parsePerfPower, type PlayHealth, ymd, ymdString,
|
||||||
|
} from './lib/health';
|
||||||
|
import { done, log, warn } from './lib/log';
|
||||||
|
import { formatFindings } from './lib/validate-rules';
|
||||||
|
import { googleClient, REPORTING_API } from './play/google';
|
||||||
|
|
||||||
|
export async function collectPlayHealth(root: string, pkg: string, days: number): Promise<PlayHealth> {
|
||||||
|
const g = googleClient(root, REPORTING_SCOPE);
|
||||||
|
const app = `${REPORTING_API}/apps/${encodeURIComponent(pkg)}`;
|
||||||
|
log('health', 'play: vitals freshness');
|
||||||
|
const set = await g.json<Parameters<typeof latestDailyEnd>[0]>('GET', `${app}/crashRateMetricSet`);
|
||||||
|
const end = latestDailyEnd(set) ?? ymd(new Date(), 2);
|
||||||
|
log('health', `play: crash and ANR rates to ${ymdString(end)} (${days} days, America/Los_Angeles days)`);
|
||||||
|
const crash = parseMetricRows(await g.json('POST', `${app}/crashRateMetricSet:query`, metricQuery(CRASH_METRICS, end, days)));
|
||||||
|
const anr = parseMetricRows(await g.json('POST', `${app}/anrRateMetricSet:query`, metricQuery(ANR_METRICS, end, days)));
|
||||||
|
log('health', 'play: per device model (28 days) and top issues');
|
||||||
|
const crashDev = parseMetricRows(await g.json('POST', `${app}/crashRateMetricSet:query`, metricQuery(['userPerceivedCrashRate', 'distinctUsers'], end, 28, ['deviceModel'])));
|
||||||
|
const anrDev = parseMetricRows(await g.json('POST', `${app}/anrRateMetricSet:query`, metricQuery(['userPerceivedAnrRate', 'distinctUsers'], end, 28, ['deviceModel'])));
|
||||||
|
const issues = parseIssues(await g.json('GET', `${app}/errorIssues:search?${issuesQuery(end, days)}`));
|
||||||
|
const start = ymd(new Date(Date.UTC(end.year, end.month - 1, end.day)), days);
|
||||||
|
return { window: { start: ymdString(start), end: ymdString(end), days }, crash, anr, devices: deviceBreakdown(crashDev, anrDev), issues };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function collectAppleHealth(root: string, bundleId: string, appIdHint: string | undefined, days: number): Promise<AppleHealth> {
|
||||||
|
const c = await ascClient(root, bundleId, appIdHint);
|
||||||
|
const appId = await c.app();
|
||||||
|
log('health', 'apple: power and performance metrics');
|
||||||
|
const metrics = parsePerfPower(await c.getAs(`/v1/apps/${appId}/perfPowerMetrics?filter[platform]=IOS`, 'application/vnd.apple.xcode-metrics+json'));
|
||||||
|
const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&filter[processingState]=VALID&sort=-uploadedDate&limit=3`)).data as J[];
|
||||||
|
const signatures: AppleHealth['signatures'] = [];
|
||||||
|
for (const b of builds) {
|
||||||
|
log('health', `apple: diagnostic signatures of build ${b.attributes.version}`);
|
||||||
|
for (const s of (await c.asc('GET', `/v1/builds/${b.id}/diagnosticSignatures?limit=10`)).data as J[])
|
||||||
|
signatures.push({ build: b.attributes.version, type: s.attributes.diagnosticType, signature: s.attributes.signature ?? '', weight: Number(s.attributes.weight ?? 0) });
|
||||||
|
}
|
||||||
|
signatures.sort((a, b) => b.weight - a.weight);
|
||||||
|
log('health', 'apple: TestFlight crash reports');
|
||||||
|
const since = new Date(Date.now() - days * 86_400_000).toISOString();
|
||||||
|
const subs = await c.all(`/v1/apps/${appId}/betaFeedbackCrashSubmissions?sort=-createdDate&limit=200`).catch(e => { warn('health', `TestFlight crash reports: ${(e as Error).message.slice(0, 160)}`); return []; });
|
||||||
|
const buildNo = new Map<string, string>(builds.map(b => [b.id, b.attributes.version] as const));
|
||||||
|
return { metrics, signatures: signatures.slice(0, 15), betaCrashes: betaCrashCounts(subs, buildNo, since) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Both stores (or the chosen one); a store that cannot be read becomes { error } instead of failing the run. */
|
||||||
|
export async function collectHealth(ctx: Ctx, o: { apple: boolean; play: boolean; days: number }): Promise<HealthSnapshot> {
|
||||||
|
const { config, root } = ctx.loaded;
|
||||||
|
const h: HealthSnapshot = { date: new Date().toISOString().slice(0, 10) };
|
||||||
|
if (o.play && config.play) {
|
||||||
|
try { h.play = await collectPlayHealth(root, config.play.packageName, o.days); } catch (e) { h.play = { error: (e as Error).message }; }
|
||||||
|
}
|
||||||
|
if (o.apple && config.apple) {
|
||||||
|
try { h.apple = await collectAppleHealth(root, config.apple.bundleId, config.apple.appId, o.days); } catch (e) { h.apple = { error: (e as Error).message }; }
|
||||||
|
}
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Newest earlier snapshot in the health folder (for week-over-week). */
|
||||||
|
export function previousSnapshot(dir: string, before: string): HealthSnapshot | null {
|
||||||
|
if (!existsSync(dir)) return null;
|
||||||
|
const f = readdirSync(dir).filter(n => /^\d{4}-\d{2}-\d{2}\.json$/.test(n) && n.slice(0, 10) < before).sort().at(-1);
|
||||||
|
return f ? JSON.parse(readFileSync(join(dir, f), 'utf8')) as HealthSnapshot : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function run(ctx: Ctx): Promise<void> {
|
||||||
|
const a = ctx.args;
|
||||||
|
const both = !a.has('apple') && !a.has('play');
|
||||||
|
const weekly = a.has('weekly');
|
||||||
|
const days = a.num('days', 7);
|
||||||
|
if (!(days >= 1 && days <= 90)) throw new Error('--days: 1-90');
|
||||||
|
const h = await collectHealth(ctx, { apple: both || a.has('apple'), play: both || a.has('play'), days });
|
||||||
|
if (a.has('json')) { console.log(JSON.stringify(h, null, 2)); return; }
|
||||||
|
console.log(healthTable(h));
|
||||||
|
console.log('\n' + formatFindings(healthFindings(h)));
|
||||||
|
if (weekly) {
|
||||||
|
const dir = ctx.loaded.resolve(a.get('out') ?? '.storebound/health');
|
||||||
|
const md = healthMarkdown(h, { appName: ctx.loaded.config.app.name, previous: previousSnapshot(dir, h.date) });
|
||||||
|
if (a.has('dry')) { console.log('\n' + md); log('health', `dry run: would write ${join(dir, `${h.date}.md`)}`); return; }
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
writeFileSync(join(dir, `${h.date}.md`), md);
|
||||||
|
writeFileSync(join(dir, `${h.date}.json`), JSON.stringify(h, null, 2) + '\n');
|
||||||
|
log('health', `report: ${join(dir, `${h.date}.md`)}`);
|
||||||
|
}
|
||||||
|
const over = healthFindings(h).filter(f => f.level === 'blocker').length;
|
||||||
|
done('health', over ? `${over} metric(s) over a store threshold` : 'no metric over a store threshold');
|
||||||
|
if (over) process.exitCode = 1;
|
||||||
|
}
|
||||||
|
|
@ -17,6 +17,7 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
|
||||||
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
||||||
'check': [() => import('./check'), 'validate config, copy files, data safety answers and products (offline); --aso keyword audit'],
|
'check': [() => import('./check'), 'validate config, copy files, data safety answers and products (offline); --aso keyword audit'],
|
||||||
'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play), plus local renders checks (--no-local skips); exit 1 on blockers'],
|
'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play), plus local renders checks (--no-local skips); exit 1 on blockers'],
|
||||||
|
'health': [() => import('./health'), 'crash / ANR vitals (Play) and diagnostics (App Store), read-only; --weekly writes a markdown report; exit 1 over a threshold'],
|
||||||
'whats-new': [() => import('./whats-new'), 'draft player-facing release notes from git log into the listing files (--since <tag>)'],
|
'whats-new': [() => import('./whats-new'), 'draft player-facing release notes from git log into the listing files (--since <tag>)'],
|
||||||
'play products': [() => import('./play/products'), 'one-time products: create / update, regional prices, activate'],
|
'play products': [() => import('./play/products'), 'one-time products: create / update, regional prices, activate'],
|
||||||
'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language'],
|
'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language'],
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,10 @@
|
||||||
import type { ServiceAccount } from './credentials';
|
import type { ServiceAccount } from './credentials';
|
||||||
|
|
||||||
export const PLAY_SCOPE = 'https://www.googleapis.com/auth/androidpublisher';
|
export const PLAY_SCOPE = 'https://www.googleapis.com/auth/androidpublisher';
|
||||||
|
/** Play Developer Reporting API (vitals): https://developers.google.com/play/developer/reporting/reference/rest */
|
||||||
|
export const REPORTING_SCOPE = 'https://www.googleapis.com/auth/playdeveloperreporting';
|
||||||
|
/** Cloud Storage read-only (Play statistics exports in the pubsite_prod_rev_ bucket). */
|
||||||
|
export const STORAGE_READ_SCOPE = 'https://www.googleapis.com/auth/devstorage.read_only';
|
||||||
const b64u = (b: ArrayBuffer | string): string => Buffer.from(typeof b === 'string' ? b : new Uint8Array(b)).toString('base64url');
|
const b64u = (b: ArrayBuffer | string): string => Buffer.from(typeof b === 'string' ? b : new Uint8Array(b)).toString('base64url');
|
||||||
|
|
||||||
function pemToDer(pem: string): ArrayBuffer {
|
function pemToDer(pem: string): ArrayBuffer {
|
||||||
|
|
@ -20,12 +24,12 @@ export async function signAssertion(sa: ServiceAccount, nowS: number, scope = PL
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cached access token getter (refreshes 5 minutes before expiry). */
|
/** Cached access token getter (refreshes 5 minutes before expiry). */
|
||||||
export function tokenSource(sa: ServiceAccount): () => Promise<string> {
|
export function tokenSource(sa: ServiceAccount, scope = PLAY_SCOPE): () => Promise<string> {
|
||||||
let token = '';
|
let token = '';
|
||||||
let until = 0;
|
let until = 0;
|
||||||
return async () => {
|
return async () => {
|
||||||
if (token && Date.now() < until) return token;
|
if (token && Date.now() < until) return token;
|
||||||
const assertion = await signAssertion(sa, Math.floor(Date.now() / 1000));
|
const assertion = await signAssertion(sa, Math.floor(Date.now() / 1000), scope);
|
||||||
const r = await fetch(sa.token_uri || 'https://oauth2.googleapis.com/token', {
|
const r = await fetch(sa.token_uri || 'https://oauth2.googleapis.com/token', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
|
|
||||||
253
cli/lib/health.ts
Normal file
253
cli/lib/health.ts
Normal file
|
|
@ -0,0 +1,253 @@
|
||||||
|
// Crash and vitals health of a released game, as pure parts: request builders, response parsers, threshold findings
|
||||||
|
// and the report. `storebound health` and `storebound validate` collect the data (read-only) and use these.
|
||||||
|
//
|
||||||
|
// Google Play Developer Reporting API v1beta1 (scope playdeveloperreporting; the service account needs "View app
|
||||||
|
// information (read-only)" for the app in Play Console, and the API enabled in its Cloud project):
|
||||||
|
// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.crashrate
|
||||||
|
// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.anrrate
|
||||||
|
// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.errors.issues/search
|
||||||
|
// DAILY timelines only take the America/Los_Angeles time zone, dates without hours; endTime is exclusive.
|
||||||
|
// Bad behavior thresholds (user-perceived, 28-day average, checked daily): crash 1.09 %, ANR 0.47 % overall; 8 % on a
|
||||||
|
// single phone model. https://developer.android.com/topic/performance/vitals and Play Console Help answer 9844486
|
||||||
|
// https://support.google.com/googleplay/android-developer/answer/9844486
|
||||||
|
// App Store Connect (power and performance, read-only):
|
||||||
|
// https://developer.apple.com/documentation/appstoreconnectapi/power-and-performance-metrics-and-logs
|
||||||
|
// GET /v1/apps/{id}/perfPowerMetrics (application/vnd.apple.xcode-metrics+json), GET /v1/builds/{id}/diagnosticSignatures
|
||||||
|
// (HANGS, DISK_WRITES, LAUNCHES), GET /v1/apps/{id}/betaFeedbackCrashSubmissions (TestFlight crash reports, API 4.0+).
|
||||||
|
import type { Finding, Level } from './validate-rules';
|
||||||
|
import { mdTable, pct, textTable } from './table';
|
||||||
|
|
||||||
|
export const PLAY_THRESHOLDS = { crash: 0.0109, anr: 0.0047, perDevice: 0.08 } as const;
|
||||||
|
/** Warn when a rate reaches this share of its threshold. */
|
||||||
|
export const WARN_AT = 0.8;
|
||||||
|
|
||||||
|
export const CRASH_METRICS = ['userPerceivedCrashRate', 'userPerceivedCrashRate28dUserWeighted', 'crashRate', 'distinctUsers'] as const;
|
||||||
|
export const ANR_METRICS = ['userPerceivedAnrRate', 'userPerceivedAnrRate28dUserWeighted', 'anrRate', 'distinctUsers'] as const;
|
||||||
|
|
||||||
|
export interface Ymd { year: number; month: number; day: number }
|
||||||
|
const LA = { id: 'America/Los_Angeles' };
|
||||||
|
|
||||||
|
/** Calendar date `days` before `d` (UTC arithmetic on the date only). */
|
||||||
|
export function ymd(d: Date, minusDays = 0): Ymd {
|
||||||
|
const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - minusDays));
|
||||||
|
return { year: t.getUTCFullYear(), month: t.getUTCMonth() + 1, day: t.getUTCDate() };
|
||||||
|
}
|
||||||
|
export const ymdString = (x: Ymd): string => `${x.year}-${String(x.month).padStart(2, '0')}-${String(x.day).padStart(2, '0')}`;
|
||||||
|
|
||||||
|
/** Body of POST v1beta1/apps/{package}/{crashRate|anrRate}MetricSet:query: a DAILY timeline [end - days, end). */
|
||||||
|
export function metricQuery(metrics: readonly string[], end: Ymd, days: number, dimensions: string[] = []): Record<string, unknown> {
|
||||||
|
const start = ymd(new Date(Date.UTC(end.year, end.month - 1, end.day)), days);
|
||||||
|
return {
|
||||||
|
timelineSpec: { aggregationPeriod: 'DAILY', startTime: { ...start, timeZone: LA }, endTime: { ...end, timeZone: LA } },
|
||||||
|
...(dimensions.length ? { dimensions } : {}),
|
||||||
|
metrics: [...metrics],
|
||||||
|
pageSize: 100000,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Latest complete day of a metric set (freshnessInfo.freshnesses[DAILY].latestEndTime, exclusive). */
|
||||||
|
export function latestDailyEnd(metricSet: { freshnessInfo?: { freshnesses?: { aggregationPeriod?: string; latestEndTime?: Partial<Ymd> }[] } }): Ymd | null {
|
||||||
|
const f = metricSet.freshnessInfo?.freshnesses?.find(x => x.aggregationPeriod === 'DAILY')?.latestEndTime;
|
||||||
|
return f?.year && f.month && f.day ? { year: f.year, month: f.month, day: f.day } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MetricRow { date: string; dims: Record<string, string>; values: Record<string, number> }
|
||||||
|
|
||||||
|
interface ApiRow {
|
||||||
|
startTime?: Partial<Ymd>;
|
||||||
|
dimensions?: { dimension: string; stringValue?: string; int64Value?: string; valueLabel?: string }[];
|
||||||
|
metrics?: { metric: string; decimalValue?: { value?: string } }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Query response rows -> plain rows (rates as fractions, e.g. 0.0109 = 1.09 %). */
|
||||||
|
export function parseMetricRows(resp: { rows?: ApiRow[] }): MetricRow[] {
|
||||||
|
return (resp.rows ?? []).map(r => ({
|
||||||
|
date: r.startTime?.year ? ymdString(r.startTime as Ymd) : '',
|
||||||
|
dims: Object.fromEntries((r.dimensions ?? []).map(d => [d.dimension, d.valueLabel ?? d.stringValue ?? d.int64Value ?? ''])),
|
||||||
|
values: Object.fromEntries((r.metrics ?? []).filter(m => m.decimalValue?.value !== undefined).map(m => [m.metric, Number(m.decimalValue!.value)])),
|
||||||
|
})).sort((a, b) => a.date.localeCompare(b.date));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** errorIssues:search query string: the top issues of a window, most reports first. */
|
||||||
|
export function issuesQuery(end: Ymd, days: number, o: { type?: 'CRASH' | 'ANR'; pageSize?: number } = {}): string {
|
||||||
|
const start = ymd(new Date(Date.UTC(end.year, end.month - 1, end.day)), days);
|
||||||
|
const p = new URLSearchParams();
|
||||||
|
for (const [k, v] of Object.entries({ start, end })) {
|
||||||
|
const x = v as Ymd;
|
||||||
|
p.set(`interval.${k}Time.year`, String(x.year)); p.set(`interval.${k}Time.month`, String(x.month)); p.set(`interval.${k}Time.day`, String(x.day));
|
||||||
|
p.set(`interval.${k}Time.timeZone.id`, LA.id);
|
||||||
|
}
|
||||||
|
if (o.type) p.set('filter', `errorIssueType = ${o.type}`);
|
||||||
|
p.set('orderBy', 'errorReportCount desc');
|
||||||
|
p.set('pageSize', String(o.pageSize ?? 10));
|
||||||
|
return p.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Issue { type: string; cause: string; location: string; reports: number; users: number; lastVersion?: string; uri?: string }
|
||||||
|
|
||||||
|
export function parseIssues(resp: { errorIssues?: { type?: string; cause?: string; location?: string; errorReportCount?: string; distinctUsers?: string; lastAppVersion?: { versionCode?: string }; issueUri?: string }[] }): Issue[] {
|
||||||
|
return (resp.errorIssues ?? []).map(i => ({ type: i.type === 'APPLICATION_NOT_RESPONDING' ? 'ANR' : i.type ?? '?', cause: i.cause ?? '', location: i.location ?? '',
|
||||||
|
reports: Number(i.errorReportCount ?? 0), users: Number(i.distinctUsers ?? 0), lastVersion: i.lastAppVersion?.versionCode, uri: i.issueUri }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlayHealth {
|
||||||
|
window: { start: string; end: string; days: number };
|
||||||
|
crash: MetricRow[];
|
||||||
|
anr: MetricRow[];
|
||||||
|
/** Worst device models by user-perceived crash / ANR rate over the window (optional). */
|
||||||
|
devices?: { model: string; crash?: number; anr?: number; users?: number }[];
|
||||||
|
issues: Issue[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AppleHealth {
|
||||||
|
/** Latest values per metric identifier (e.g. hangRate, launchTime) from perfPowerMetrics, with the app version. */
|
||||||
|
metrics: { category: string; metric: string; unit: string; version: string; value: number; goal?: string }[];
|
||||||
|
/** Top diagnostic signatures of the latest builds. */
|
||||||
|
signatures: { build: string; type: string; signature: string; weight: number }[];
|
||||||
|
/** TestFlight crash submissions in the window (count per build). */
|
||||||
|
betaCrashes: { build: string; count: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HealthSnapshot { date: string; play?: PlayHealth | { error: string }; apple?: AppleHealth | { error: string } }
|
||||||
|
|
||||||
|
/** Last value of a metric over the rows (the 28-day rolling metrics: the latest row is the store's current view). */
|
||||||
|
export function lastValue(rows: MetricRow[], metric: string): number | null {
|
||||||
|
for (let i = rows.length - 1; i >= 0; i--) { const v = rows[i]!.values[metric]; if (v !== undefined && !Number.isNaN(v)) return v; }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Distinct-users-weighted average of a daily metric. */
|
||||||
|
export function weightedAverage(rows: MetricRow[], metric: string): number | null {
|
||||||
|
let num = 0, den = 0;
|
||||||
|
for (const r of rows) { const v = r.values[metric], u = r.values.distinctUsers ?? 1; if (v === undefined) continue; num += v * u; den += u; }
|
||||||
|
return den ? num / den : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Per device model over the window: users-weighted user-perceived crash / ANR rates, only models with at least
|
||||||
|
* `minUsers` (summed daily distinct users, so small samples do not raise alarms), worst first, top `n`. */
|
||||||
|
export function deviceBreakdown(crash: MetricRow[], anr: MetricRow[], o: { minUsers?: number; n?: number } = {}): NonNullable<PlayHealth['devices']> {
|
||||||
|
const agg = new Map<string, { cn: number; cd: number; an: number; ad: number }>();
|
||||||
|
const add = (rows: MetricRow[], metric: string, which: 'c' | 'a') => {
|
||||||
|
for (const r of rows) {
|
||||||
|
const m = r.dims.deviceModel;
|
||||||
|
const v = r.values[metric], u = r.values.distinctUsers ?? 0;
|
||||||
|
if (!m || v === undefined) continue;
|
||||||
|
const x = agg.get(m) ?? { cn: 0, cd: 0, an: 0, ad: 0 };
|
||||||
|
if (which === 'c') { x.cn += v * u; x.cd += u; } else { x.an += v * u; x.ad += u; }
|
||||||
|
agg.set(m, x);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
add(crash, 'userPerceivedCrashRate', 'c');
|
||||||
|
add(anr, 'userPerceivedAnrRate', 'a');
|
||||||
|
return [...agg.entries()].filter(([, x]) => Math.max(x.cd, x.ad) >= (o.minUsers ?? 500))
|
||||||
|
.map(([model, x]) => ({ model, crash: x.cd ? x.cn / x.cd : undefined, anr: x.ad ? x.an / x.ad : undefined, users: Math.max(x.cd, x.ad) }))
|
||||||
|
.sort((a, b) => Math.max(b.crash ?? 0, b.anr ?? 0) - Math.max(a.crash ?? 0, a.anr ?? 0)).slice(0, o.n ?? 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TestFlight crash submissions -> count per build number within [since, now]. */
|
||||||
|
export function betaCrashCounts(subs: { attributes?: { createdDate?: string }; relationships?: { build?: { data?: { id: string } } } }[], builds: Map<string, string>, since: string): AppleHealth['betaCrashes'] {
|
||||||
|
const n = new Map<string, number>();
|
||||||
|
for (const s of subs) {
|
||||||
|
if ((s.attributes?.createdDate ?? '') < since) continue;
|
||||||
|
const b = builds.get(s.relationships?.build?.data?.id ?? '') ?? '?';
|
||||||
|
n.set(b, (n.get(b) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
return [...n.entries()].map(([build, count]) => ({ build, count })).sort((a, b) => b.count - a.count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** perfPowerMetrics (xcode-metrics JSON) -> latest point per metric. */
|
||||||
|
export function parsePerfPower(j: { productData?: { metricCategories?: { identifier?: string; metrics?: { identifier?: string; unit?: { displayName?: string; identifier?: string }; datasets?: { filterCriteria?: { device?: string; percentile?: string }; points?: { version?: string; value?: number; goal?: string }[] }[] }[] }[] }[] }): AppleHealth['metrics'] {
|
||||||
|
const out: AppleHealth['metrics'] = [];
|
||||||
|
for (const p of j.productData ?? []) for (const c of p.metricCategories ?? []) for (const m of c.metrics ?? []) {
|
||||||
|
const ds = (m.datasets ?? []).find(d => (d.filterCriteria?.device ?? 'all_iphones') === 'all_iphones' && /fifty|50|typical/i.test(d.filterCriteria?.percentile ?? 'percentile.fifty')) ?? m.datasets?.[0];
|
||||||
|
const pt = ds?.points?.at(-1);
|
||||||
|
if (!pt || pt.value === undefined) continue;
|
||||||
|
out.push({ category: c.identifier ?? '', metric: m.identifier ?? '', unit: m.unit?.displayName ?? m.unit?.identifier ?? '', version: pt.version ?? '', value: pt.value, goal: pt.goal });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const levelFor = (v: number | null, limit: number): Level => (v === null ? 'ok' : v >= limit ? 'blocker' : v >= limit * WARN_AT ? 'warn' : 'ok');
|
||||||
|
|
||||||
|
/** Health -> validate findings. Over a Play bad behavior threshold = blocker (Play lowers discoverability and may
|
||||||
|
* warn users on the listing), from 80 % of it = warn. Apple publishes no thresholds: "poor" goals and heavy
|
||||||
|
* diagnostic signatures are warnings. */
|
||||||
|
export function healthFindings(h: HealthSnapshot, o: { unreadable?: Level } = {}): Finding[] {
|
||||||
|
const f: Finding[] = [];
|
||||||
|
const play = h.play;
|
||||||
|
if (play && 'error' in play) f.push({ store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: ${play.error.slice(0, 200)}`, fix: 'store-health skill (Reporting API access)' });
|
||||||
|
else if (play) {
|
||||||
|
const crash = lastValue(play.crash, 'userPerceivedCrashRate28dUserWeighted') ?? weightedAverage(play.crash, 'userPerceivedCrashRate');
|
||||||
|
const anr = lastValue(play.anr, 'userPerceivedAnrRate28dUserWeighted') ?? weightedAverage(play.anr, 'userPerceivedAnrRate');
|
||||||
|
const fix = 'storebound health; fix the top issues, ship a build with a higher versionCode (store-health skill)';
|
||||||
|
if (crash === null && anr === null) f.push({ store: 'play', level: 'ok', code: 'vitals', msg: 'no vitals data yet (too few users or no release)' });
|
||||||
|
else {
|
||||||
|
f.push({ store: 'play', level: levelFor(crash, PLAY_THRESHOLDS.crash), code: 'vitals-crash', msg: `user-perceived crash rate (28 d) ${pct(crash)} (bad behavior threshold ${pct(PLAY_THRESHOLDS.crash)})`, fix });
|
||||||
|
f.push({ store: 'play', level: levelFor(anr, PLAY_THRESHOLDS.anr), code: 'vitals-anr', msg: `user-perceived ANR rate (28 d) ${pct(anr)} (bad behavior threshold ${pct(PLAY_THRESHOLDS.anr)})`, fix });
|
||||||
|
}
|
||||||
|
for (const d of play.devices ?? []) {
|
||||||
|
const worst = Math.max(d.crash ?? 0, d.anr ?? 0);
|
||||||
|
const lv = levelFor(worst, PLAY_THRESHOLDS.perDevice);
|
||||||
|
if (lv !== 'ok') f.push({ store: 'play', level: lv, code: 'vitals-device', msg: `${d.model}: crash ${pct(d.crash ?? null)}, ANR ${pct(d.anr ?? null)} (per-device threshold ${pct(PLAY_THRESHOLDS.perDevice)})`, fix });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const apple = h.apple;
|
||||||
|
if (apple && 'error' in apple) f.push({ store: 'apple', level: o.unreadable ?? 'warn', code: 'diagnostics', msg: `diagnostics not readable: ${apple.error.slice(0, 200)}` });
|
||||||
|
else if (apple) {
|
||||||
|
const poor = apple.metrics.filter(m => m.goal === 'poor');
|
||||||
|
for (const m of poor) f.push({ store: 'apple', level: 'warn', code: 'perf', msg: `${m.metric} ${m.value} ${m.unit} on ${m.version}: Apple rates it poor`, fix: 'Xcode Organizer > Metrics; store-health skill' });
|
||||||
|
const heavy = apple.signatures.filter(s => s.weight >= 0.25);
|
||||||
|
for (const s of heavy) f.push({ store: 'apple', level: 'warn', code: 'diagnostics', msg: `build ${s.build} ${s.type}: ${s.signature.slice(0, 120)} (${Math.round(s.weight * 100)} % of reports)`, fix: 'Xcode Organizer > Hangs / Disk Writes / Launches' });
|
||||||
|
if (!poor.length && !heavy.length) f.push({ store: 'apple', level: 'ok', code: 'diagnostics', msg: `${apple.metrics.length} metrics, ${apple.signatures.length} diagnostic signatures, nothing rated poor` });
|
||||||
|
}
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Terminal summary table of a snapshot. */
|
||||||
|
export function healthTable(h: HealthSnapshot): string {
|
||||||
|
const rows: (string | number)[][] = [];
|
||||||
|
if (h.play && !('error' in h.play)) {
|
||||||
|
const p = h.play;
|
||||||
|
rows.push(['play', 'crash rate (user-perceived, 28 d)', pct(lastValue(p.crash, 'userPerceivedCrashRate28dUserWeighted')), pct(PLAY_THRESHOLDS.crash)]);
|
||||||
|
rows.push(['play', `crash rate (user-perceived, ${p.window.days} d avg)`, pct(weightedAverage(p.crash, 'userPerceivedCrashRate')), '']);
|
||||||
|
rows.push(['play', 'ANR rate (user-perceived, 28 d)', pct(lastValue(p.anr, 'userPerceivedAnrRate28dUserWeighted')), pct(PLAY_THRESHOLDS.anr)]);
|
||||||
|
rows.push(['play', `ANR rate (user-perceived, ${p.window.days} d avg)`, pct(weightedAverage(p.anr, 'userPerceivedAnrRate')), '']);
|
||||||
|
rows.push(['play', 'top issues', p.issues.length, '']);
|
||||||
|
} else if (h.play) rows.push(['play', 'error', h.play.error.slice(0, 80), '']);
|
||||||
|
if (h.apple && !('error' in h.apple)) {
|
||||||
|
for (const m of h.apple.metrics.slice(0, 12)) rows.push(['apple', `${m.metric} (${m.version})`, `${m.value} ${m.unit}`.trim(), m.goal ?? '']);
|
||||||
|
rows.push(['apple', 'diagnostic signatures', h.apple.signatures.length, '']);
|
||||||
|
rows.push(['apple', 'TestFlight crash reports', h.apple.betaCrashes.reduce((n, b) => n + b.count, 0), '']);
|
||||||
|
} else if (h.apple) rows.push(['apple', 'error', h.apple.error.slice(0, 80), '']);
|
||||||
|
return textTable(['store', 'metric', 'value', 'threshold / goal'], rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Markdown report (weekly summary): table, findings, top issues, week-over-week change when `previous` is given. */
|
||||||
|
export function healthMarkdown(h: HealthSnapshot, o: { appName: string; previous?: HealthSnapshot | null } = { appName: '' }): string {
|
||||||
|
const out: string[] = [`# Health report · ${o.appName} · ${h.date}`, ''];
|
||||||
|
const f = healthFindings(h);
|
||||||
|
const icon: Record<Level, string> = { blocker: 'OVER THRESHOLD', warn: 'watch', ok: 'ok' };
|
||||||
|
out.push('## Summary', '', mdTable(['store', 'status', 'finding'], f.map(x => [x.store, icon[x.level], x.msg])), '');
|
||||||
|
const p = h.play && !('error' in h.play) ? h.play : null;
|
||||||
|
const prev = o.previous?.play && !('error' in o.previous.play) ? o.previous.play : null;
|
||||||
|
if (p) {
|
||||||
|
out.push(`## Google Play vitals (${p.window.start} to ${p.window.end})`, '');
|
||||||
|
const delta = (cur: number | null, old: number | null) => (cur === null || old === null ? '' : `${cur >= old ? '+' : ''}${((cur - old) * 100).toFixed(2)} pt`);
|
||||||
|
const c = weightedAverage(p.crash, 'userPerceivedCrashRate'), a = weightedAverage(p.anr, 'userPerceivedAnrRate');
|
||||||
|
out.push(mdTable(['metric', 'this window', 'previous', 'change', 'threshold'], [
|
||||||
|
['user-perceived crash rate', pct(c), pct(prev ? weightedAverage(prev.crash, 'userPerceivedCrashRate') : null), delta(c, prev ? weightedAverage(prev.crash, 'userPerceivedCrashRate') : null), pct(PLAY_THRESHOLDS.crash)],
|
||||||
|
['user-perceived ANR rate', pct(a), pct(prev ? weightedAverage(prev.anr, 'userPerceivedAnrRate') : null), delta(a, prev ? weightedAverage(prev.anr, 'userPerceivedAnrRate') : null), pct(PLAY_THRESHOLDS.anr)],
|
||||||
|
]), '');
|
||||||
|
if (p.issues.length) out.push('### Top issues', '', mdTable(['type', 'cause', 'location', 'reports', 'users', 'last versionCode'],
|
||||||
|
p.issues.map(i => [i.type, i.cause.slice(0, 80), i.location.slice(0, 80), i.reports, i.users, i.lastVersion ?? ''])), '');
|
||||||
|
}
|
||||||
|
const ap = h.apple && !('error' in h.apple) ? h.apple : null;
|
||||||
|
if (ap) {
|
||||||
|
out.push('## App Store diagnostics', '');
|
||||||
|
if (ap.metrics.length) out.push(mdTable(['category', 'metric', 'version', 'value', 'goal'], ap.metrics.map(m => [m.category, m.metric, m.version, `${m.value} ${m.unit}`.trim(), m.goal ?? ''])), '');
|
||||||
|
if (ap.signatures.length) out.push('### Diagnostic signatures', '', mdTable(['build', 'type', 'signature', 'weight'], ap.signatures.map(s => [s.build, s.type, s.signature.slice(0, 100), `${Math.round(s.weight * 100)} %`])), '');
|
||||||
|
if (ap.betaCrashes.length) out.push('### TestFlight crash reports', '', mdTable(['build', 'reports'], ap.betaCrashes.map(b => [b.build, b.count])), '');
|
||||||
|
}
|
||||||
|
out.push('Sources: Play Developer Reporting API (vitals, 28-day user-weighted rates, America/Los_Angeles days) and App Store Connect power and performance metrics. Thresholds: developer.android.com/topic/performance/vitals.', '');
|
||||||
|
return out.join('\n');
|
||||||
|
}
|
||||||
|
|
@ -42,6 +42,14 @@ export const TOOLS: ToolDef[] = [
|
||||||
description: 'Read-only readiness report for App Store Connect and/or Google Play with ordered blockers (build, encryption, metadata, screenshots, review details, age rating, prices, IAPs, privacy URL, app-ads.txt, tracks, products).',
|
description: 'Read-only readiness report for App Store Connect and/or Google Play with ordered blockers (build, encryption, metadata, screenshots, review details, age rating, prices, IAPs, privacy URL, app-ads.txt, tracks, products).',
|
||||||
props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } },
|
props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } },
|
||||||
args: i => (i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []) },
|
args: i => (i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []) },
|
||||||
|
{ name: 'health', title: 'Crash and vitals health', command: ['health'], write: false, network: true,
|
||||||
|
description: 'Read-only crash / ANR vitals from the Play Developer Reporting API (user-perceived rates vs the bad behavior thresholds 1.09 % / 0.47 %, worst device models, top issues) and App Store power and performance metrics, diagnostic signatures and TestFlight crash reports. Exit 1 when a metric is over a store threshold.',
|
||||||
|
props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' }, days: { type: 'integer', minimum: 1, maximum: 90, default: 7 } },
|
||||||
|
args: i => [...(i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []), ...opt('days', i.days)] },
|
||||||
|
{ name: 'health_report', title: 'Weekly health report', command: ['health', '--weekly'], write: true, network: true, idempotent: true,
|
||||||
|
description: 'Weekly health summary as Markdown in .storebound/health/<date>.md (plus <date>.json for the next week-over-week comparison). Local files only; dry_run prints the report.',
|
||||||
|
props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } },
|
||||||
|
args: i => (i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []) },
|
||||||
{ name: 'apple_status', title: 'App Store status', command: ['apple', 'status'], write: false, network: true,
|
{ name: 'apple_status', title: 'App Store status', command: ['apple', 'status'], write: false, network: true,
|
||||||
description: 'Read-only App Store Connect overview: versions and their states, recent builds, in-app purchases, review submissions.' },
|
description: 'Read-only App Store Connect overview: versions and their states, recent builds, in-app purchases, review submissions.' },
|
||||||
{ name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true,
|
{ name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true,
|
||||||
|
|
|
||||||
31
cli/play/google.ts
Normal file
31
cli/play/google.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
// Small client for the other Google APIs storebound reads with the same Play service account: the Play Developer
|
||||||
|
// Reporting API (vitals) and Cloud Storage (Play statistics exports). Read-only callers; retries 429 / 5xx.
|
||||||
|
import { playServiceAccount } from '../lib/credentials';
|
||||||
|
import { tokenSource } from '../lib/google-auth';
|
||||||
|
|
||||||
|
export const REPORTING_API = 'https://playdeveloperreporting.googleapis.com/v1beta1';
|
||||||
|
|
||||||
|
export function googleClient(root: string, scope: string) {
|
||||||
|
const token = tokenSource(playServiceAccount(root), scope);
|
||||||
|
async function send(method: string, url: string, body?: unknown): Promise<Response> {
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
const r = await fetch(url, { method, headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body) });
|
||||||
|
if ((r.status === 429 || r.status >= 500) && attempt < 4) { await r.body?.cancel(); await Bun.sleep(2000 * (attempt + 1)); continue; }
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
async json<T = unknown>(method: string, url: string, body?: unknown): Promise<T> {
|
||||||
|
const r = await send(method, url, body);
|
||||||
|
const t = await r.text();
|
||||||
|
if (!r.ok) throw new Error(`${method} ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${/^\s*</.test(t) ? '(HTML error page)' : t.slice(0, 800)}`);
|
||||||
|
return (t ? JSON.parse(t) : {}) as T;
|
||||||
|
},
|
||||||
|
async bytes(url: string): Promise<Uint8Array> {
|
||||||
|
const r = await send('GET', url);
|
||||||
|
if (!r.ok) throw new Error(`GET ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${(await r.text()).slice(0, 300)}`);
|
||||||
|
return new Uint8Array(await r.arrayBuffer());
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -1,17 +1,21 @@
|
||||||
// Store readiness report (read-only on both stores): what still blocks a submission, in the order to fix it.
|
// Store readiness report (read-only on both stores): what still blocks a submission, in the order to fix it.
|
||||||
// storebound validate [--apple] [--play] [--json] [--src store/renders] [--no-local]
|
// storebound validate [--apple] [--play] [--json] [--src store/renders] [--no-local] [--no-health]
|
||||||
// Without --apple / --play: every store the config has. Exit code 1 when there is at least one blocker.
|
// Without --apple / --play: every store the config has. Exit code 1 when there is at least one blocker.
|
||||||
// Reads only: GETs on App Store Connect, a Play edit that is opened, read and deleted (never committed), and plain GETs
|
// Reads only: GETs on App Store Connect, a Play edit that is opened, read and deleted (never committed), and plain GETs
|
||||||
// of the public privacy policy and app-ads.txt URLs. Also checks the local renders folder (if there is one) with the
|
// of the public privacy policy and app-ads.txt URLs. Also checks the local renders folder (if there is one) with the
|
||||||
// `shots check` rules: wrong pixel size, alpha, too few / many images, Play 8 MB and feature graphic format are
|
// `shots check` rules: wrong pixel size, alpha, too few / many images, Play 8 MB and feature graphic format are
|
||||||
// blockers (the upload would fail), text overflow flags from the last render are warnings. --no-local skips it.
|
// blockers (the upload would fail), text overflow flags from the last render are warnings. --no-local skips it.
|
||||||
|
// Live apps: crash / ANR vitals (Play Reporting API) and App Store diagnostics, as in `storebound health`: over a Play
|
||||||
|
// bad behavior threshold is a blocker, near it a warning; a store without vitals access is only noted. --no-health skips.
|
||||||
import { ascClient, type J } from './apple/asc';
|
import { ascClient, type J } from './apple/asc';
|
||||||
import { requiredDisplayTypes } from './apple/screenshots';
|
import { requiredDisplayTypes } from './apple/screenshots';
|
||||||
import { playCodes } from './lib/config';
|
import { playCodes } from './lib/config';
|
||||||
import type { Ctx } from './lib/ctx';
|
import type { Ctx } from './lib/ctx';
|
||||||
import { checkUrl } from './lib/http';
|
import { checkUrl } from './lib/http';
|
||||||
|
import { collectHealth } from './health';
|
||||||
|
import { healthFindings } from './lib/health';
|
||||||
import { log, warn } from './lib/log';
|
import { log, warn } from './lib/log';
|
||||||
import { type AppleSnapshot, appleRules, type Finding, formatFindings, PLAY_REQUIRED_IMAGES, type PlaySnapshot, playRules, rendersFindings } from './lib/validate-rules';
|
import { type AppleSnapshot, appleRules, type Finding, formatFindings, PLAY_REQUIRED_IMAGES, type PlaySnapshot, playRules, rendersFindings, sortFindings } from './lib/validate-rules';
|
||||||
import { rendersCheck } from './shots/check';
|
import { rendersCheck } from './shots/check';
|
||||||
import { playClient } from './play/client';
|
import { playClient } from './play/client';
|
||||||
import { listOneTimeProducts } from './play/products';
|
import { listOneTimeProducts } from './play/products';
|
||||||
|
|
@ -118,6 +122,11 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
try { findings.push(...playRules({ ...(await collectPlay(ctx)), renders: local?.play })); }
|
try { findings.push(...playRules({ ...(await collectPlay(ctx)), renders: local?.play })); }
|
||||||
catch (e) { findings.push({ store: 'play', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }, ...rendersFindings('play', local?.play)); }
|
catch (e) { findings.push({ store: 'play', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }, ...rendersFindings('play', local?.play)); }
|
||||||
} else if (a.has('play')) warn('validate', 'no play section in the config');
|
} else if (a.has('play')) warn('validate', 'no play section in the config');
|
||||||
|
if (!a.has('no-health') && (config.apple || config.play)) {
|
||||||
|
log('validate', 'vitals and diagnostics (last 7 days)');
|
||||||
|
const h = await collectHealth(ctx, { apple: (both || a.has('apple')) && !!config.apple, play: (both || a.has('play')) && !!config.play, days: 7 });
|
||||||
|
findings.push(...sortFindings(healthFindings(h, { unreadable: 'ok' })));
|
||||||
|
}
|
||||||
const blockers = findings.filter(f => f.level === 'blocker').length;
|
const blockers = findings.filter(f => f.level === 'blocker').length;
|
||||||
if (a.has('json')) console.log(JSON.stringify({ blockers, findings }, null, 2));
|
if (a.has('json')) console.log(JSON.stringify({ blockers, findings }, null, 2));
|
||||||
else {
|
else {
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,8 @@ presses release; you prepare, dry-run and report. `storebound mcp` deliberately
|
||||||
4. Problem: `storebound play rollout --halt` (no confirmation needed; stops new installs of the update). Like Apple's
|
4. Problem: `storebound play rollout --halt` (no confirmation needed; stops new installs of the update). Like Apple's
|
||||||
pause it is **not a rollback**: updated users keep it. Ship a fixed build with a higher versionCode; resume with
|
pause it is **not a rollback**: updated users keep it. Ship a fixed build with a higher versionCode; resume with
|
||||||
`--resume [--fraction x]` only if the halted build is fine after all.
|
`--resume [--fraction x]` only if the halted build is fine after all.
|
||||||
5. Done: `storebound play rollout --complete` (100 %).
|
5. Done: `storebound play rollout --complete` (100 %). Before each increase, `storebound health --play` (store-health
|
||||||
|
skill): crash / ANR rates near Play's thresholds are a reason to halt, not to widen.
|
||||||
6. Every rollout command runs in an edit: a Console save at the same time makes it retry once.
|
6. Every rollout command runs in an edit: a Console save at the same time makes it retry once.
|
||||||
|
|
||||||
## Review wait
|
## Review wait
|
||||||
|
|
|
||||||
48
skills/store-health/SKILL.md
Normal file
48
skills/store-health/SKILL.md
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
---
|
||||||
|
name: store-health
|
||||||
|
description: Watch a released mobile game's crash and ANR health on both stores - Google Play Android vitals (user-perceived crash rate 1.09 % and ANR rate 0.47 % bad behavior thresholds, 8 % per device model) through the Play Developer Reporting API, App Store power and performance metrics, diagnostic signatures and TestFlight crash reports, a weekly Markdown report, and validate blockers when a threshold is crossed. Use when the user asks about crashes, ANRs, vitals, stability, a weekly health check, or why Play shows a quality warning.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Store health (crashes, ANRs, diagnostics)
|
||||||
|
|
||||||
|
CLI: `storebound health` (read-only, both stores; `--apple` / `--play`, `--days 7`), `storebound health --weekly`
|
||||||
|
(also writes `.storebound/health/<date>.md` and `<date>.json`; the next week compares against it; `--dry` prints
|
||||||
|
instead). `storebound validate` runs the same checks for live apps. MCP: `health` (read-only), `health_report`.
|
||||||
|
|
||||||
|
## Setup (once)
|
||||||
|
- **Google Play**: enable the **Google Play Developer Reporting API** in the Google Cloud project of the service
|
||||||
|
account (Cloud Console > APIs & Services > Library). In Play Console > Users and permissions, the service account
|
||||||
|
needs **View app information (read-only)** for the app. Scope used: `playdeveloperreporting`. Reference:
|
||||||
|
https://developers.google.com/play/developer/reporting/reference/rest
|
||||||
|
- **App Store**: the API key that storebound already uses (Admin, App Manager or Developer role reads metrics).
|
||||||
|
Metrics come from users who share analytics with developers; small games may show none.
|
||||||
|
|
||||||
|
## Read the numbers
|
||||||
|
- **Play bad behavior thresholds** (28-day average, user-perceived, checked daily; sources:
|
||||||
|
https://developer.android.com/topic/performance/vitals and Play Console Help answer 9844486):
|
||||||
|
user-perceived crash rate **1.09 %**, user-perceived ANR rate **0.47 %**, and **8 %** on any single phone model.
|
||||||
|
Over a threshold, Play can lower the game's visibility and show a warning on its store listing. storebound marks
|
||||||
|
over = blocker, from 80 % of a threshold = warn.
|
||||||
|
- Daily values swing on small user counts; the 28-day user-weighted rate is what Play judges. Device rows with fewer
|
||||||
|
than 500 users are ignored.
|
||||||
|
- **App Store**: Apple publishes no thresholds. storebound warns on metrics Apple itself rates `poor` (hang rate,
|
||||||
|
launch time, memory, disk writes, battery) and on diagnostic signatures with a large share of reports (Xcode >
|
||||||
|
Organizer shows the stack traces). TestFlight crash reports count crashes testers sent from the beta.
|
||||||
|
|
||||||
|
## Act on it
|
||||||
|
1. Start with the top issues table (Play: cause + location + versionCode; Apple: signature + build).
|
||||||
|
2. Reproduce on the named device model / OS; for ANRs look for main-thread work (I/O, ads SDK init, big asset
|
||||||
|
loads), for crashes the null / out-of-memory paths.
|
||||||
|
3. Ship the fix with a higher versionCode / build number (release-management skill). Halting a rollout stops new
|
||||||
|
installs but is not a rollback.
|
||||||
|
4. Next week: `storebound health --weekly` shows the change in percentage points next to last week.
|
||||||
|
|
||||||
|
## Gotchas
|
||||||
|
- `vitals not readable`: the API is not enabled, the service account lacks the permission, or the app has no release
|
||||||
|
yet. `validate` only notes it; `storebound health` warns.
|
||||||
|
- storebound reads the Reporting API rates as fractions (0.0109 = 1.09 %). The API reference calls them a
|
||||||
|
"percentage of distinct users" without stating the scale (not verified against a live response yet): the first
|
||||||
|
time, compare one number with Play Console > Android vitals and report a mismatch.
|
||||||
|
- Never share crash logs that contain player data outside the team; never paste tester emails from TestFlight crash
|
||||||
|
reports into chats or issues.
|
||||||
|
- Nothing here changes the store: it is safe to run any time.
|
||||||
|
|
@ -36,6 +36,11 @@ Each line: number, level (`BLOCKER`, `warn`, `ok`), store, message, and a `fix:`
|
||||||
| app-ads.txt lacks lines / 404 | ad networks cannot verify you | `ads-levelplay-checks`; the file lives at the root of the developer website |
|
| app-ads.txt lacks lines / 404 | ad networks cannot verify you | `ads-levelplay-checks`; the file lives at the root of the developer website |
|
||||||
| no release on any track | nothing uploaded | `play release <aab>` |
|
| no release on any track | nothing uploaded | `play release <aab>` |
|
||||||
| product purchase option DRAFT | not active | `play products` |
|
| product purchase option DRAFT | not active | `play products` |
|
||||||
|
| user-perceived crash / ANR rate over 1.09 % / 0.47 % (live apps) | Play's bad behavior threshold is crossed | `store-health` skill: `storebound health`, fix the top issues, ship a higher versionCode |
|
||||||
|
| Apple metric rated poor / heavy diagnostic signature | hangs, launches, disk writes | `store-health` skill (Xcode Organizer for the stack) |
|
||||||
|
|
||||||
|
Vitals need the Play Developer Reporting API enabled for the service account; without it `validate` only notes
|
||||||
|
"vitals not readable". `--no-health` skips these checks.
|
||||||
|
|
||||||
## What validate cannot see (UI-only, check by hand)
|
## What validate cannot see (UI-only, check by hand)
|
||||||
App Privacy labels published, Play App content declarations (ads, target audience, content rating, advertising ID),
|
App Privacy labels published, Play App content declarations (ads, target audience, content rating, advertising ID),
|
||||||
|
|
|
||||||
109
tests/health.test.ts
Normal file
109
tests/health.test.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { previousSnapshot } from '../cli/health';
|
||||||
|
import {
|
||||||
|
ANR_METRICS, betaCrashCounts, CRASH_METRICS, deviceBreakdown, healthFindings, healthMarkdown, type HealthSnapshot, healthTable, issuesQuery,
|
||||||
|
lastValue, latestDailyEnd, metricQuery, parseIssues, parseMetricRows, parsePerfPower, PLAY_THRESHOLDS, weightedAverage, ymd,
|
||||||
|
} from '../cli/lib/health';
|
||||||
|
import { TOOLS, toArgv } from '../cli/mcp-tools';
|
||||||
|
|
||||||
|
const row = (day: number, values: Record<string, string>, dims: Record<string, string> = {}) => ({
|
||||||
|
startTime: { year: 2026, month: 10, day, timeZone: { id: 'America/Los_Angeles' } },
|
||||||
|
dimensions: Object.entries(dims).map(([dimension, stringValue]) => ({ dimension, stringValue })),
|
||||||
|
metrics: Object.entries(values).map(([metric, value]) => ({ metric, decimalValue: { value } })),
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('reporting api requests', () => {
|
||||||
|
test('DAILY timeline in America/Los_Angeles, exclusive end, the documented metric names', () => {
|
||||||
|
const q = metricQuery(CRASH_METRICS, { year: 2026, month: 10, day: 8 }, 7) as { timelineSpec: Record<string, unknown>; metrics: string[]; dimensions?: string[] };
|
||||||
|
expect(q.timelineSpec).toEqual({ aggregationPeriod: 'DAILY', startTime: { year: 2026, month: 10, day: 1, timeZone: { id: 'America/Los_Angeles' } }, endTime: { year: 2026, month: 10, day: 8, timeZone: { id: 'America/Los_Angeles' } } });
|
||||||
|
expect(q.metrics).toEqual(['userPerceivedCrashRate', 'userPerceivedCrashRate28dUserWeighted', 'crashRate', 'distinctUsers']);
|
||||||
|
expect(ANR_METRICS).toContain('userPerceivedAnrRate28dUserWeighted');
|
||||||
|
expect(q.dimensions).toBeUndefined();
|
||||||
|
expect((metricQuery(['x'], { year: 2026, month: 3, day: 1 }, 1, ['deviceModel']) as { dimensions: string[]; timelineSpec: { startTime: unknown } }).timelineSpec.startTime).toMatchObject({ month: 2, day: 28 });
|
||||||
|
expect(ymd(new Date('2026-01-01T10:00:00Z'), 1)).toEqual({ year: 2025, month: 12, day: 31 });
|
||||||
|
});
|
||||||
|
test('freshness and issue search parameters', () => {
|
||||||
|
expect(latestDailyEnd({ freshnessInfo: { freshnesses: [{ aggregationPeriod: 'HOURLY', latestEndTime: { year: 2026, month: 10, day: 9 } }, { aggregationPeriod: 'DAILY', latestEndTime: { year: 2026, month: 10, day: 8 } }] } })).toEqual({ year: 2026, month: 10, day: 8 });
|
||||||
|
expect(latestDailyEnd({})).toBeNull();
|
||||||
|
const p = new URLSearchParams(issuesQuery({ year: 2026, month: 10, day: 8 }, 7, { type: 'CRASH' }));
|
||||||
|
expect(p.get('interval.startTime.day')).toBe('1');
|
||||||
|
expect(p.get('interval.endTime.timeZone.id')).toBe('America/Los_Angeles');
|
||||||
|
expect(p.get('filter')).toBe('errorIssueType = CRASH');
|
||||||
|
expect(p.get('orderBy')).toBe('errorReportCount desc');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('parsing', () => {
|
||||||
|
const crash = parseMetricRows({ rows: [row(2, { userPerceivedCrashRate: '0.004', distinctUsers: '1000', userPerceivedCrashRate28dUserWeighted: '0.006' }), row(1, { userPerceivedCrashRate: '0.010', distinctUsers: '3000' })] });
|
||||||
|
test('rows sorted by date, decimals as numbers, weighted averages', () => {
|
||||||
|
expect(crash.map(r => r.date)).toEqual(['2026-10-01', '2026-10-02']);
|
||||||
|
expect(lastValue(crash, 'userPerceivedCrashRate28dUserWeighted')).toBe(0.006);
|
||||||
|
expect(lastValue(crash, 'nope')).toBeNull();
|
||||||
|
expect(weightedAverage(crash, 'userPerceivedCrashRate')).toBeCloseTo((0.01 * 3000 + 0.004 * 1000) / 4000, 10);
|
||||||
|
});
|
||||||
|
test('devices: weighted per model, small samples dropped, worst first', () => {
|
||||||
|
const c = parseMetricRows({ rows: [row(1, { userPerceivedCrashRate: '0.09', distinctUsers: '600' }, { deviceModel: 'acme/old' }), row(1, { userPerceivedCrashRate: '0.5', distinctUsers: '10' }, { deviceModel: 'acme/rare' }),
|
||||||
|
row(1, { userPerceivedCrashRate: '0.01', distinctUsers: '5000' }, { deviceModel: 'acme/new' })] });
|
||||||
|
const d = deviceBreakdown(c, []);
|
||||||
|
expect(d.map(x => x.model)).toEqual(['acme/old', 'acme/new']);
|
||||||
|
expect(d[0]!.crash).toBeCloseTo(0.09, 10);
|
||||||
|
});
|
||||||
|
test('issues, Apple metrics, TestFlight crashes', () => {
|
||||||
|
expect(parseIssues({ errorIssues: [{ type: 'APPLICATION_NOT_RESPONDING', cause: 'Input dispatching timed out', location: 'com.example.Main', errorReportCount: '12', distinctUsers: '9', lastAppVersion: { versionCode: '42' } }] }))
|
||||||
|
.toEqual([{ type: 'ANR', cause: 'Input dispatching timed out', location: 'com.example.Main', reports: 12, users: 9, lastVersion: '42', uri: undefined }]);
|
||||||
|
const perf = parsePerfPower({ productData: [{ metricCategories: [{ identifier: 'HANG', metrics: [{ identifier: 'hangRate', unit: { displayName: 's/hr' },
|
||||||
|
datasets: [{ filterCriteria: { device: 'all_iphones', percentile: 'percentile.fifty' }, points: [{ version: '1.0', value: 0.5, goal: 'good' }, { version: '1.1', value: 4.2, goal: 'poor' }] }] }] }] }] });
|
||||||
|
expect(perf).toEqual([{ category: 'HANG', metric: 'hangRate', unit: 's/hr', version: '1.1', value: 4.2, goal: 'poor' }]);
|
||||||
|
const subs = [{ attributes: { createdDate: '2026-10-05T10:00:00Z' }, relationships: { build: { data: { id: 'b1' } } } }, { attributes: { createdDate: '2026-10-06T10:00:00Z' }, relationships: { build: { data: { id: 'b1' } } } },
|
||||||
|
{ attributes: { createdDate: '2026-09-01T10:00:00Z' }, relationships: { build: { data: { id: 'b1' } } } }];
|
||||||
|
expect(betaCrashCounts(subs, new Map([['b1', '42']]), '2026-10-01')).toEqual([{ build: '42', count: 2 }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findings and report', () => {
|
||||||
|
const play = (crash: string, anr: string) => ({ window: { start: '2026-10-01', end: '2026-10-08', days: 7 },
|
||||||
|
crash: parseMetricRows({ rows: [row(7, { userPerceivedCrashRate: crash, userPerceivedCrashRate28dUserWeighted: crash, distinctUsers: '1000' })] }),
|
||||||
|
anr: parseMetricRows({ rows: [row(7, { userPerceivedAnrRate: anr, userPerceivedAnrRate28dUserWeighted: anr, distinctUsers: '1000' })] }), devices: [], issues: [] });
|
||||||
|
test('thresholds: over = blocker, from 80 % = warn, under = ok', () => {
|
||||||
|
expect(PLAY_THRESHOLDS).toEqual({ crash: 0.0109, anr: 0.0047, perDevice: 0.08 });
|
||||||
|
const levels = (h: HealthSnapshot) => Object.fromEntries(healthFindings(h).map(f => [f.code, f.level]));
|
||||||
|
expect(levels({ date: 'd', play: play('0.0120', '0.0010') })).toEqual({ 'vitals-crash': 'blocker', 'vitals-anr': 'ok' });
|
||||||
|
expect(levels({ date: 'd', play: play('0.0090', '0.0040') })).toEqual({ 'vitals-crash': 'warn', 'vitals-anr': 'warn' });
|
||||||
|
const dev = healthFindings({ date: 'd', play: { ...play('0.001', '0.001'), devices: [{ model: 'acme/old', crash: 0.09, users: 600 }] } });
|
||||||
|
expect(dev.find(f => f.code === 'vitals-device')).toMatchObject({ level: 'blocker' });
|
||||||
|
expect(healthFindings({ date: 'd', play: { error: '403 forbidden' } })[0]).toMatchObject({ level: 'warn', code: 'vitals' });
|
||||||
|
expect(healthFindings({ date: 'd', play: { error: '403' } }, { unreadable: 'ok' })[0]!.level).toBe('ok');
|
||||||
|
expect(healthFindings({ date: 'd', play: { ...play('0', '0'), crash: [], anr: [] } })[0]!.msg).toContain('no vitals data yet');
|
||||||
|
const apple = healthFindings({ date: 'd', apple: { metrics: [{ category: 'HANG', metric: 'hangRate', unit: 's/hr', version: '1.1', value: 4, goal: 'poor' }], signatures: [{ build: '42', type: 'HANGS', signature: 'main thread', weight: 0.4 }], betaCrashes: [] } });
|
||||||
|
expect(apple.map(f => f.level)).toEqual(['warn', 'warn']);
|
||||||
|
});
|
||||||
|
test('table and markdown with week-over-week change', () => {
|
||||||
|
const h: HealthSnapshot = { date: '2026-10-09', play: { ...play('0.0120', '0.0010'), issues: [{ type: 'CRASH', cause: 'NullPointerException', location: 'Main.kt', reports: 5, users: 4, lastVersion: '42' }] },
|
||||||
|
apple: { metrics: [], signatures: [], betaCrashes: [{ build: '42', count: 2 }] } };
|
||||||
|
const t = healthTable(h);
|
||||||
|
expect(t).toContain('1.20%');
|
||||||
|
expect(t).toContain('TestFlight crash reports');
|
||||||
|
const md = healthMarkdown(h, { appName: 'Example Game', previous: { date: '2026-10-02', play: play('0.0100', '0.0010') } });
|
||||||
|
expect(md).toContain('# Health report · Example Game · 2026-10-09');
|
||||||
|
expect(md).toContain('OVER THRESHOLD');
|
||||||
|
expect(md).toContain('+0.20 pt');
|
||||||
|
expect(md).toContain('| CRASH | NullPointerException | Main.kt | 5 | 4 | 42 |');
|
||||||
|
});
|
||||||
|
test('previous snapshot is the newest one before today', () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'storebound-health-'));
|
||||||
|
writeFileSync(join(dir, '2026-09-25.json'), JSON.stringify({ date: '2026-09-25' }));
|
||||||
|
writeFileSync(join(dir, '2026-10-02.json'), JSON.stringify({ date: '2026-10-02' }));
|
||||||
|
writeFileSync(join(dir, '2026-10-09.json'), JSON.stringify({ date: '2026-10-09' }));
|
||||||
|
expect(previousSnapshot(dir, '2026-10-09')!.date).toBe('2026-10-02');
|
||||||
|
expect(previousSnapshot(join(dir, 'none'), '2026-10-09')).toBeNull();
|
||||||
|
});
|
||||||
|
test('mcp: health is read-only, the report is a dry-by-default local write', () => {
|
||||||
|
const t = (n: string) => TOOLS.find(x => x.name === n)!;
|
||||||
|
expect(t('health')).toMatchObject({ write: false, network: true });
|
||||||
|
expect(toArgv(t('health'), { store: 'play', days: 28 }).argv).toEqual(['health', '--play', '--days', '28']);
|
||||||
|
expect(toArgv(t('health_report'), {}).argv).toEqual(['health', '--weekly', '--dry']);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue