diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index a13e44b3..2a24ae36 100644 --- a/.cursor/rules/storebound.mdc +++ b/.cursor/rules/storebound.mdc @@ -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/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game - `skills/review-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile game the safe way +- `skills/store-analytics/SKILL.md`: Take store analytics snapshots for a mobile game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git - `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 diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index b4684b99..1a4e096d 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -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 | | `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game | | `review-replies` | Reply to App Store and Google Play reviews of a mobile game the safe way | +| `store-analytics` | Take store analytics snapshots for a mobile game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git | | `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 | diff --git a/AGENTS.md b/AGENTS.md index 61e1aa54..331db522 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game - `skills/review-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile game the safe way +- `skills/store-analytics/SKILL.md`: Take store analytics snapshots for a mobile game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git - `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 diff --git a/GEMINI.md b/GEMINI.md index eca9ab61..2c95d2fa 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -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 | | `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game | | `review-replies` | Reply to App Store and Google Play reviews of a mobile game the safe way | +| `store-analytics` | Take store analytics snapshots for a mobile game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git | | `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 | diff --git a/cli/analytics.ts b/cli/analytics.ts new file mode 100644 index 00000000..2df81f7d --- /dev/null +++ b/cli/analytics.ts @@ -0,0 +1,153 @@ +// Store analytics snapshots next to the listing changes. +// storebound analytics setup [--dry] App Store: create the ONGOING analytics report request (Admin key; once) +// storebound analytics snapshot [--days 28] [--store apple|play] [--dry] -> .storebound/analytics/.json +// storebound analytics compare [--days 7] [--paths store,storebound.config.ts] [--md] +// App Store: Analytics Reports API (Discovery and Engagement: impressions, product page views; Downloads: first-time +// downloads and redownloads), every segment checked against its md5 checksum. Google Play has no statistics API: +// the monthly CSV exports in your Cloud Storage bucket (play.reportsBucket = "pubsite_prod_rev_", Play Console > +// Download reports > Statistics > Copy Cloud Storage URI) are read with the service account (store listing visitors, +// acquisitions, daily user installs). compare lines the snapshots up with the git history of the store files (listing +// text, screenshots, config): the days before vs after each change. Read-only on both stores except `setup`. +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { ascClient, type Asc, type J } from './apple/asc'; +import type { Ctx } from './lib/ctx'; +import { + type AppleDay, APPLE_REPORTS, appleDaily, appleTotals, bucketName, checksumOk, compareAroundEvents, decodeText, effectMarkdown, effectTable, inWindow, + latestPerDate, mergeSeries, monthsBetween, parseGitLog, parseReport, pickReport, type PlayDay, playDaily, playObjects, playTotals, type Snapshot, +} from './lib/analytics'; +import { STORAGE_READ_SCOPE } from './lib/google-auth'; +import { done, log, warn } from './lib/log'; +import { pct, textTable } from './lib/table'; +import { googleClient } from './play/google'; + +const TAG = 'analytics'; +const day = (d: Date) => d.toISOString().slice(0, 10); + +async function ongoingRequest(c: Asc, appId: string): Promise { + const reqs = await c.all(`/v1/apps/${appId}/analyticsReportRequests?filter[accessType]=ONGOING&limit=50`); + return reqs.find(r => !r.attributes?.stoppedDueToInactivity) ?? null; +} + +async function reportRows(c: Asc, report: J, start: string, tag: string): Promise[]> { + const instances = (await c.all(`/v1/analyticsReports/${report.id}/instances?filter[granularity]=DAILY&limit=200`)) + .filter(i => (i.attributes?.processingDate ?? '') >= start).sort((a, b) => a.attributes.processingDate.localeCompare(b.attributes.processingDate)); + log(TAG, `apple: ${tag}: ${instances.length} daily instance(s) since ${start}`); + const parts: { processingDate: string; rows: Record[] }[] = []; + for (const inst of instances) { + const rows: Record[] = []; + for (const seg of await c.all(`/v1/analyticsReportInstances/${inst.id}/segments?limit=200`)) { + // Segment URLs are pre-signed (valid 5 minutes): fetched without the API token. + const r = await fetch(seg.attributes.url); + if (!r.ok) throw new Error(`segment ${seg.id}: HTTP ${r.status}`); + const gz = new Uint8Array(await r.arrayBuffer()); + const raw = gz[0] === 0x1f && gz[1] === 0x8b ? Bun.gunzipSync(gz) : gz; + // Apple documents an md5 checksum per segment without saying of which bytes: accept the file or its content. + if (seg.attributes.checksum && !checksumOk(gz, seg.attributes.checksum) && !checksumOk(raw, seg.attributes.checksum)) throw new Error(`segment ${seg.id}: md5 checksum mismatch`); + rows.push(...parseReport(decodeText(raw))); + } + parts.push({ processingDate: inst.attributes.processingDate, rows }); + } + return latestPerDate(parts); +} + +async function appleSnapshot(ctx: Ctx, start: string, end: string): Promise<{ daily: AppleDay[] }> { + const { config, root } = ctx.loaded; + const c = await ascClient(root, config.apple!.bundleId, config.apple?.appId); + const appId = await c.app(); + const req = await ongoingRequest(c, appId); + if (!req) throw new Error('no active ONGOING analytics report request: run storebound analytics setup (Admin key), data starts 1-2 days later'); + const reports = await c.all(`/v1/analyticsReportRequests/${req.id}/reports?limit=200`); + const eng = pickReport(reports.filter(r => r.attributes?.category === APPLE_REPORTS.engagement.category), APPLE_REPORTS.engagement.match); + const dl = pickReport(reports.filter(r => r.attributes?.category === APPLE_REPORTS.downloads.category), APPLE_REPORTS.downloads.match); + if (!eng || !dl) throw new Error(`reports not found yet (${reports.length} listed): wait a day after setup`); + const daily = appleDaily(await reportRows(c, eng, start, eng.attributes.name), await reportRows(c, dl, start, dl.attributes.name)); + return { daily: inWindow(daily, start, end) }; +} + +async function playSnapshot(ctx: Ctx, start: string, end: string): Promise<{ daily: PlayDay[] }> { + const { config, root } = ctx.loaded; + const bucket = config.play?.reportsBucket; + if (!bucket) throw new Error('play.reportsBucket is not set (Play Console > Download reports > Statistics > Copy Cloud Storage URI)'); + const g = googleClient(root, STORAGE_READ_SCOPE); + const sp: Record[] = [], inst: Record[] = []; + for (const month of monthsBetween(start, end)) { + const o = playObjects(config.play!.packageName, month); + for (const [name, into] of [[o.storePerformance, sp], [o.installs, inst]] as const) { + const url = `https://storage.googleapis.com/storage/v1/b/${encodeURIComponent(bucketName(bucket))}/o/${encodeURIComponent(name)}?alt=media`; + try { into.push(...parseReport(decodeText(await g.bytes(url)))); log(TAG, `play: ${name}`); } + catch (e) { if (/-> 404/.test(String(e))) warn(TAG, `play: ${name} not there (yet)`); else throw e; } + } + } + return { daily: inWindow(playDaily(sp, inst), start, end) }; +} + +function readSnapshots(dir: string): Snapshot[] { + if (!existsSync(dir)) return []; + return readdirSync(dir).filter(n => /^\d{4}-\d{2}-\d{2}\.json$/.test(n)).sort().map(n => JSON.parse(readFileSync(join(dir, n), 'utf8')) as Snapshot); +} + +export async function run(ctx: Ctx): Promise { + const { config, root, resolve } = ctx.loaded; + const a = ctx.args; + const sub = a._[0]; + const dir = resolve(a.get('dir') ?? '.storebound/analytics'); + const dry = a.has('dry'); + + if (sub === 'setup') { + if (!config.apple) throw new Error('no apple section in the config (Google Play needs no setup: set play.reportsBucket)'); + const c = await ascClient(root, config.apple.bundleId, config.apple.appId); + const appId = await c.app(); + const cur = await ongoingRequest(c, appId); + if (cur) { done(TAG, `apple: ONGOING report request exists (${cur.id})`); return; } + const body = { data: { type: 'analyticsReportRequests', attributes: { accessType: 'ONGOING' }, relationships: { app: { data: { type: 'apps', id: appId } } } } }; + if (dry) { log(TAG, 'would POST /v1/analyticsReportRequests {accessType=ONGOING} (dry)'); return; } + await c.asc('POST', '/v1/analyticsReportRequests', body); + done(TAG, 'apple: ONGOING report request created; the first reports appear after 1-2 days, then daily'); + return; + } + + if (sub === 'snapshot') { + const days = a.num('days', 28); + if (!(days >= 1 && days <= 120)) throw new Error('--days: 1-120'); + const store = a.get('store'); + const now = new Date(); + const end = day(new Date(now.getTime() - 86_400_000)), start = day(new Date(now.getTime() - days * 86_400_000)); + const snap: Snapshot = { date: day(now), window: { start, end, days } }; + if ((!store || store === 'apple') && config.apple) { + try { const r = await appleSnapshot(ctx, start, end); snap.apple = { daily: r.daily, totals: appleTotals(r.daily) }; } + catch (e) { snap.apple = { error: (e as Error).message.slice(0, 400) }; warn(TAG, `apple: ${snap.apple.error}`); } + } + if ((!store || store === 'play') && config.play) { + try { const r = await playSnapshot(ctx, start, end); snap.play = { daily: r.daily, totals: playTotals(r.daily) }; } + catch (e) { snap.play = { error: (e as Error).message.slice(0, 400) }; warn(TAG, `play: ${snap.play.error}`); } + } + const rows: (string | number)[][] = []; + if (snap.apple && !('error' in snap.apple)) { const t = snap.apple.totals; rows.push(['apple', `${t.impressions} impressions`, `${t.pageViews} page views`, `${t.downloads} downloads`, pct(t.conversion ?? null)]); } + if (snap.play && !('error' in snap.play)) { const t = snap.play.totals; rows.push(['play', `${t.visitors} visitors`, `${t.acquisitions} acquisitions`, `${t.installs} installs`, pct(t.conversion ?? null)]); } + if (rows.length) console.log(textTable(['store', 'reach', 'interest', 'installs', 'conversion'], rows)); + const file = join(dir, `${snap.date}.json`); + if (dry) { done(TAG, `dry run: would write ${file} (${start} to ${end})`); return; } + mkdirSync(dir, { recursive: true }); + writeFileSync(file, JSON.stringify(snap, null, 2) + '\n'); + done(TAG, `snapshot ${file} (${start} to ${end})`); + return; + } + + if (sub === 'compare') { + const snaps = readSnapshots(dir); + if (!snaps.length) throw new Error(`no snapshots in ${dir} (storebound analytics snapshot)`); + const series = mergeSeries(snaps); + const first = [series.apple[0]?.date, series.play[0]?.date].filter(Boolean).sort()[0] ?? snaps[0]!.window.start; + const paths = a.list('paths').length ? a.list('paths') : ['store', 'storebound.config.ts', ...(config.shots?.copy ? [config.shots.copy] : [])]; + const g = Bun.spawnSync(['git', 'log', `--since=${first}`, '--date=short', '--format=%x1e%h%x1f%ad%x1f%s', '--name-only', '--', ...paths], { cwd: root, stdout: 'pipe', stderr: 'pipe' }); + if (g.exitCode !== 0) throw new Error(`git log: ${g.stderr.toString().trim()}`); + const events = parseGitLog(g.stdout.toString()).reverse(); + log(TAG, `${snaps.length} snapshot(s), ${series.apple.length} App Store day(s), ${series.play.length} Play day(s), ${events.length} store change(s) since ${first}`); + const fx = compareAroundEvents(series, events, a.num('days', 7)); + console.log(a.has('md') ? effectMarkdown(fx) : effectTable(fx)); + log(TAG, 'reading: a change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too'); + return; + } + throw new Error('usage: storebound analytics setup | snapshot | compare'); +} diff --git a/cli/index.ts b/cli/index.ts index 80f70517..bdfd2778 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -17,6 +17,7 @@ const PLAIN: Record Promise, string]> = { const COMMANDS: Record Promise, string]> = { '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'], + 'analytics': [() => import('./analytics'), 'setup (App Store report request) | snapshot (impressions, page views, installs, conversion -> .storebound/analytics) | compare (vs listing changes in git)'], 'health': [() => import('./health'), 'crash / ANR vitals (Play) and diagnostics (App Store), read-only; --weekly writes a markdown report; exit 1 over a threshold'], 'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes)'], 'reviews': [() => import('./reviews'), 'list | draft (local reply drafts in .storebound/replies) | send (approved drafts only, asks first)'], diff --git a/cli/lib/analytics.ts b/cli/lib/analytics.ts new file mode 100644 index 00000000..f27b0fbf --- /dev/null +++ b/cli/lib/analytics.ts @@ -0,0 +1,186 @@ +// Store analytics snapshots (impressions, product page views, downloads / installs, conversion) and their comparison +// with listing changes, as pure parts. `storebound analytics` downloads the data (read-only) and writes the snapshots. +// Sources (checked October 2026): +// App Store Connect Analytics Reports API: an ONGOING analyticsReportRequest (Admin creates it once; first data after +// 1-2 days, then daily; instances kept 35 days; a request stops after long inactivity: stoppedDueToInactivity), +// reports -> instances (DAILY) -> segments (url valid 5 minutes, md5 checksum, gzip text files; every segment of +// an instance is needed). A later processingDate replaces rows of the same Date: never sum one Date across instances. +// https://developer.apple.com/documentation/appstoreconnectapi/downloading-analytics-reports +// https://developer.apple.com/documentation/analytics-reports/app-store-discovery-and-engagement +// https://developer.apple.com/documentation/analytics-reports/app-download +// Google Play: no API for store listing statistics (the Reporting API has vitals only). Monthly CSV exports in the +// developer's Cloud Storage bucket gs://pubsite_prod_rev_ (Play Console > Download reports > Statistics, "Copy +// Cloud Storage URI"), UTF-16, read with the service account (Play Console permission "View app information and +// download bulk reports", scope devstorage.read_only): +// stats/store_performance/store_performance___country.csv (Store listing acquisitions / visitors) +// stats/installs/installs___country.csv (Daily User Installs, ...) +// https://support.google.com/googleplay/android-developer/answer/6135870 +import { createHash } from 'node:crypto'; +import { parseCsvRecords } from './csv'; +import { mdTable, pct, textTable } from './table'; + +export const APPLE_REPORTS = { + engagement: { category: 'APP_STORE_ENGAGEMENT', match: /discovery and engagement/i }, + downloads: { category: 'COMMERCE', match: /download/i }, +} as const; + +/** Standard over Detailed (Detailed adds noise for privacy and splits by campaign). */ +export function pickReport(reports: T[], match: RegExp): T | null { + const hits = reports.filter(r => match.test(r.attributes?.name ?? '')); + return hits.find(r => /standard/i.test(r.attributes?.name ?? '')) ?? hits[0] ?? null; +} + +/** Bytes of a downloaded segment vs its md5 checksum. */ +export const checksumOk = (b: Uint8Array, checksum: string): boolean => createHash('md5').update(b).digest('hex').toLowerCase() === checksum.toLowerCase(); + +/** Text of a report file: UTF-16 with a BOM (Play exports), else UTF-8. */ +export function decodeText(b: Uint8Array): string { + if (b[0] === 0xff && b[1] === 0xfe) return new TextDecoder('utf-16le').decode(b.subarray(2)); + if (b[0] === 0xfe && b[1] === 0xff) return new TextDecoder('utf-16be').decode(b.subarray(2)); + return new TextDecoder('utf-8').decode(b); +} + +/** Tab- or comma-separated report text -> records keyed by lower-case column name (by name: Apple may reorder). */ +export function parseReport(text: string): Record[] { + const first = text.replace(/^/, '').split(/\r?\n/, 1)[0] ?? ''; + return parseCsvRecords(text, first.includes('\t') ? '\t' : ','); +} + +/** Rows of several instances: per Date only the rows of the newest processingDate (later instances restate days). */ +export function latestPerDate(instances: { processingDate: string; rows: Record[] }[]): Record[] { + const best = new Map(); + for (const i of instances) for (const r of i.rows) { const d = r.date ?? ''; if (!best.has(d) || best.get(d)! < i.processingDate) best.set(d, i.processingDate); } + return instances.flatMap(i => i.rows.filter(r => best.get(r.date ?? '') === i.processingDate)); +} + +export interface AppleDay { date: string; impressions: number; uniqueImpressions: number; pageViews: number; uniquePageViews: number; downloads: number; firstTimeDownloads: number } +export interface PlayDay { date: string; visitors: number; acquisitions: number; installs: number } + +const num = (v: string | undefined) => { const n = Number((v ?? '').replace(/,/g, '')); return Number.isFinite(n) ? n : 0; }; + +/** Discovery and Engagement + Downloads rows -> one line per day (App Store, every territory and source summed). */ +export function appleDaily(engagement: Record[], downloads: Record[]): AppleDay[] { + const days = new Map(); + const day = (d: string) => days.get(d) ?? days.set(d, { date: d, impressions: 0, uniqueImpressions: 0, pageViews: 0, uniquePageViews: 0, downloads: 0, firstTimeDownloads: 0 }).get(d)!; + for (const r of engagement) { + if (!r.date) continue; + const ev = (r.event ?? '').toLowerCase(); + const x = day(r.date); + if (ev === 'impression') { x.impressions += num(r.counts); x.uniqueImpressions += num(r.unique_counts); } + else if (ev === 'page view') { x.pageViews += num(r.counts); x.uniquePageViews += num(r.unique_counts); } + } + for (const r of downloads) { + if (!r.date) continue; + const t = (r.download_type ?? '').toLowerCase(); + const x = day(r.date); + if (t === 'first-time download') { x.firstTimeDownloads += num(r.counts); x.downloads += num(r.counts); } + else if (t === 'redownload') x.downloads += num(r.counts); + } + return [...days.values()].sort((a, b) => a.date.localeCompare(b.date)); +} + +/** Play store performance + installs CSV rows (country files) -> one line per day. Dates are YYYY-MM-DD. */ +export function playDaily(storePerformance: Record[], installs: Record[]): PlayDay[] { + const days = new Map(); + const day = (d: string) => days.get(d) ?? days.set(d, { date: d, visitors: 0, acquisitions: 0, installs: 0 }).get(d)!; + for (const r of storePerformance) if (r.date) { const x = day(r.date); x.visitors += num(r.store_listing_visitors); x.acquisitions += num(r.store_listing_acquisitions); } + for (const r of installs) if (r.date) day(r.date).installs += num(r.daily_user_installs); + return [...days.values()].sort((a, b) => a.date.localeCompare(b.date)); +} + +/** Months (yyyyMM) a date window touches, for the Play file names. */ +export function monthsBetween(start: string, end: string): string[] { + const out: string[] = []; + let y = Number(start.slice(0, 4)), m = Number(start.slice(5, 7)); + const ey = Number(end.slice(0, 4)), em = Number(end.slice(5, 7)); + while (y < ey || (y === ey && m <= em)) { out.push(`${y}${String(m).padStart(2, '0')}`); if (++m > 12) { m = 1; y++; } } + return out; +} + +export const playObjects = (pkg: string, month: string) => ({ + storePerformance: `stats/store_performance/store_performance_${pkg}_${month}_country.csv`, + installs: `stats/installs/installs_${pkg}_${month}_country.csv`, +}); + +/** "gs://pubsite_prod_rev_123/" or "pubsite_prod_rev_123" -> bucket name. */ +export const bucketName = (b: string): string => b.replace(/^gs:\/\//, '').replace(/\/.*$/, ''); + +export interface Totals { impressions?: number; pageViews?: number; downloads?: number; conversion?: number | null; visitors?: number; acquisitions?: number; installs?: number } + +export function appleTotals(days: AppleDay[]): Totals { + const s = (k: keyof AppleDay) => days.reduce((n, d) => n + (d[k] as number), 0); + const uniq = s('uniqueImpressions'); + return { impressions: s('impressions'), pageViews: s('pageViews'), downloads: s('downloads'), conversion: uniq ? s('downloads') / uniq : null }; +} +export function playTotals(days: PlayDay[]): Totals { + const s = (k: keyof PlayDay) => days.reduce((n, d) => n + (d[k] as number), 0); + const v = s('visitors'); + return { visitors: v, acquisitions: s('acquisitions'), installs: s('installs'), conversion: v ? s('acquisitions') / v : null }; +} + +export interface Snapshot { + date: string; + window: { start: string; end: string; days: number }; + apple?: { daily: AppleDay[]; totals: Totals } | { error: string }; + play?: { daily: PlayDay[]; totals: Totals } | { error: string }; +} + +export const inWindow = (rows: T[], start: string, end: string): T[] => rows.filter(r => r.date >= start && r.date <= end); + +// ---- compare with listing changes ---- + +export interface Event { date: string; commit: string; subject: string; files: string[] } + +/** `git log --date=short --format=%x1e%h%x1f%ad%x1f%s --name-only -- ` -> events. */ +export function parseGitLog(out: string): Event[] { + return out.split('\x1e').map(s => s.trim()).filter(Boolean).map(block => { + const [head, ...files] = block.split('\n'); + const [commit = '', date = '', subject = ''] = (head ?? '').split('\x1f'); + return { date, commit, subject, files: files.map(f => f.trim()).filter(Boolean) }; + }).filter(e => /^\d{4}-\d{2}-\d{2}$/.test(e.date)); +} + +/** Snapshots -> one series per store (newest snapshot wins for a date). */ +export function mergeSeries(snaps: Snapshot[]): { apple: AppleDay[]; play: PlayDay[] } { + const a = new Map(), p = new Map(); + for (const s of [...snaps].sort((x, y) => x.date.localeCompare(y.date))) { + if (s.apple && !('error' in s.apple)) for (const d of s.apple.daily) a.set(d.date, d); + if (s.play && !('error' in s.play)) for (const d of s.play.daily) p.set(d.date, d); + } + return { apple: [...a.values()].sort((x, y) => x.date.localeCompare(y.date)), play: [...p.values()].sort((x, y) => x.date.localeCompare(y.date)) }; +} + +const addDays = (d: string, n: number) => new Date(Date.parse(d + 'T00:00:00Z') + n * 86_400_000).toISOString().slice(0, 10); + +export interface EventEffect { event: Event; store: 'apple' | 'play'; before: Totals; after: Totals; daysBefore: number; daysAfter: number } + +/** For every event: the `days` before it (excluding the event day) vs the `days` from it, per store, where data exists. */ +export function compareAroundEvents(series: { apple: AppleDay[]; play: PlayDay[] }, events: Event[], days = 7): EventEffect[] { + const out: EventEffect[] = []; + for (const e of events) { + const bs = addDays(e.date, -days), be = addDays(e.date, -1), as = e.date, ae = addDays(e.date, days - 1); + const ab = inWindow(series.apple, bs, be), aa = inWindow(series.apple, as, ae); + if (ab.length || aa.length) out.push({ event: e, store: 'apple', before: appleTotals(ab), after: appleTotals(aa), daysBefore: ab.length, daysAfter: aa.length }); + const pb = inWindow(series.play, bs, be), pa = inWindow(series.play, as, ae); + if (pb.length || pa.length) out.push({ event: e, store: 'play', before: playTotals(pb), after: playTotals(pa), daysBefore: pb.length, daysAfter: pa.length }); + } + return out; +} + +const perDay = (v: number | undefined, n: number) => (v === undefined || !n ? null : v / n); +const fmtN = (v: number | null) => (v === null ? 'n/a' : v >= 100 ? Math.round(v).toString() : v.toFixed(1)); +const delta = (a: number | null | undefined, b: number | null | undefined) => (a == null || b == null || a === 0 ? '' : `${b >= a ? '+' : ''}${(((b - a) / a) * 100).toFixed(0)}%`); + +/** Rows for the comparison table: per event and store, daily averages before / after and the conversion change. */ +export function effectRows(fx: EventEffect[]): (string | number)[][] { + return fx.map(f => { + const top = f.store === 'apple' ? 'impressions' : 'visitors'; + const b = perDay(f.before[top], f.daysBefore), a = perDay(f.after[top], f.daysAfter); + return [f.event.date, f.store, f.event.subject.slice(0, 48), `${fmtN(b)} -> ${fmtN(a)} ${delta(b, a)}`.trim(), + `${pct(f.before.conversion ?? null)} -> ${pct(f.after.conversion ?? null)}`, `${f.daysBefore}/${f.daysAfter}`]; + }); +} + +export const EFFECT_HEAD = ['date', 'store', 'change', 'impressions or visitors / day', 'conversion', 'days before/after']; +export const effectTable = (fx: EventEffect[]): string => (fx.length ? textTable(EFFECT_HEAD, effectRows(fx)) : 'no listing changes inside the snapshot data yet'); +export const effectMarkdown = (fx: EventEffect[]): string => mdTable(EFFECT_HEAD, effectRows(fx)); diff --git a/cli/lib/config.ts b/cli/lib/config.ts index c363d15d..d5eb2499 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -271,6 +271,9 @@ export interface ShipConfig { packageName: string; defaultLanguage?: string; listing?: string; icon?: string; /** Promo video: a YouTube URL (public or unlisted, ads off, embeddable). Play takes no video upload. Sent by `play listing`. */ video?: string; + /** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_" (Play Console > + * Download reports > Statistics > Copy Cloud Storage URI). Used by `storebound analytics snapshot`. */ + reportsBucket?: string; }; apple?: { bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string; @@ -335,6 +338,8 @@ export function validateConfig(c: unknown): string[] { if (cfg.play && !ID_RE.test(cfg.play.packageName ?? '')) e.push('play.packageName: not a package name (com.example.game)'); if (cfg.play?.video && !/^https:\/\/(www\.youtube\.com\/watch\?v=[\w-]{6,}|youtu\.be\/[\w-]{6,})$/.test(cfg.play.video)) e.push('play.video: a plain YouTube video URL (https://www.youtube.com/watch?v=... or https://youtu.be/...), no playlist, channel or extra parameters'); + if (cfg.play?.reportsBucket && !/^(gs:\/\/)?pubsite_prod(_rev)?_\d+\/?$/.test(cfg.play.reportsBucket)) + e.push('play.reportsBucket: the Play reports bucket, e.g. "pubsite_prod_rev_" (Play Console > Download reports > Copy Cloud Storage URI)'); if (cfg.apple) { if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)'); if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)'); diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index a3ac67fa..69bd7e83 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -68,6 +68,16 @@ export const TOOLS: ToolDef[] = [ description: 'Read the current prices of every product on both stores and write them as the prices CSV (local file only; Apple equalized prices with with_automatic, marked kind=auto). dry_run prints the CSV.', props: { out: { type: 'string', description: 'CSV path' }, store: { type: 'string', enum: ['apple', 'play'] }, only, with_automatic: { type: 'boolean', default: false } }, args: i => [...opt('out', i.out), ...opt('store', i.store), ...opt('only', i.only), ...flag('with-automatic', i.with_automatic)] }, + { name: 'analytics_snapshot', title: 'Store analytics snapshot', command: ['analytics', 'snapshot'], write: true, network: true, idempotent: true, + description: 'Read store analytics (App Store: impressions, product page views, downloads via the Analytics Reports API; Google Play: store listing visitors, acquisitions, installs from the Play reports bucket) and write .storebound/analytics/.json. Local file only; dry_run reads and prints the totals.', + props: { days: { type: 'integer', minimum: 1, maximum: 120, default: 28 }, store: { type: 'string', enum: ['apple', 'play'] } }, + args: i => [...opt('days', i.days), ...opt('store', i.store)] }, + { name: 'analytics_compare', title: 'Analytics vs listing changes', command: ['analytics', 'compare'], write: false, network: false, + description: 'Offline: line the analytics snapshots up with the git history of the store files (listing text, screenshots, config) and show daily impressions / visitors and conversion in the days before vs after each change.', + props: { days: { type: 'integer', minimum: 1, maximum: 60, default: 7 }, md: { type: 'boolean', default: false, description: 'Markdown table' } }, + args: i => [...opt('days', i.days), ...flag('md', i.md)] }, + { name: 'analytics_setup', title: 'Start App Store analytics reports', command: ['analytics', 'setup'], write: true, network: true, idempotent: true, + description: 'Create the ONGOING App Store Connect analytics report request once (needs an Admin key; reports start 1-2 days later). Changes nothing public.' }, { 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.' }, { name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true, diff --git a/skills/aso-basics/SKILL.md b/skills/aso-basics/SKILL.md index 9d4ce383..9f27fa54 100644 --- a/skills/aso-basics/SKILL.md +++ b/skills/aso-basics/SKILL.md @@ -40,4 +40,5 @@ true; never use competitor or other games' names, "best / #1", or unrelated popu 2. Put the best 1-2 in name / title and subtitle / short description; the rest in the keyword field per locale. 3. `storebound check --aso`, fix errors, read warnings. 4. Push with `apple listing` / `play listing`; measure after a few weeks (App Store Connect / Play Console acquisition - by search term) and change a few terms per release, not all at once. + by search term; `storebound analytics snapshot` + `analytics compare` line impressions and conversion up with + each committed listing change, store-analytics skill) and change a few terms per release, not all at once. diff --git a/skills/store-analytics/SKILL.md b/skills/store-analytics/SKILL.md new file mode 100644 index 00000000..c573f9a5 --- /dev/null +++ b/skills/store-analytics/SKILL.md @@ -0,0 +1,47 @@ +--- +name: store-analytics +description: Take store analytics snapshots for a mobile game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git. Use when the user asks whether a listing change, new screenshots or a store experiment worked, wants install / conversion numbers, or sets up store reporting. +--- + +# Store analytics + +CLI: `storebound analytics setup | snapshot | compare`. MCP: `analytics_snapshot`, `analytics_compare` (offline), +`analytics_setup`. Read-only on both stores except `setup` (creates the App Store report request). Snapshots go to +`.storebound/analytics/.json` (gitignored; they are your business numbers). + +## What is possible (and what is not) +- **App Store**: the Analytics Reports API. An Admin key creates one ONGOING report request (`storebound analytics + setup`); the first reports come 1-2 days later, then daily, and Apple keeps instances for 35 days, so take a + snapshot at least monthly (weekly is better). A request left unread for a long time stops + (`stoppedDueToInactivity`); `setup` makes a new one. storebound reads "App Store Discovery and Engagement" (Event + Impression / Page view, Counts and Unique Counts) and "App Store Downloads" (First-time Download, Redownload; updates + are left out), checks each segment's md5 checksum and keeps, per day, the newest processing of that day. + Conversion = (first-time downloads + redownloads) / unique impressions. Source: + https://developer.apple.com/documentation/appstoreconnectapi/downloading-analytics-reports +- **Google Play**: there is **no API** for store listing statistics (the Play Developer Reporting API only has + vitals). Play Console writes monthly CSV exports into your own Cloud Storage bucket; storebound reads them with + the service account. Setup: Play Console > Download reports > Statistics > **Copy Cloud Storage URI** and put the + bucket into `play.reportsBucket` (`pubsite_prod_rev_`); the service account needs "View app information and + download bulk reports" (Play Console Help answer 6135870). Files appear with a few days' delay; the current month's + file grows daily. Conversion = store listing acquisitions / store listing visitors. +- **Not possible through any API**: Play store listing experiment results and App Store Product Page Optimization + results (read them in the consoles; `storebound apple ppo status` shows the App Store test state), Play + "Explore" search terms beyond the traffic source file. + +## Flow +1. Once: `storebound analytics setup` (App Store) and `play.reportsBucket` (Play). +2. Weekly: `storebound analytics snapshot` (default the last 28 days; `--dry` prints totals only). +3. Change the listing as usual and commit it (`store/appstore.md`, `store/listing.md`, `store/shots/...`, the config). + One change at a time, with a clear commit subject ("new first screenshot: boss fight"), makes the comparison + readable. +4. `storebound analytics compare` (or `--md` for a report): for every commit that touched the store files, daily + impressions (App Store) or visitors (Play) and conversion in the 7 days before vs the 7 days from the change + (`--days 14` for small games). + +## Read it honestly +- Small numbers swing: under a few hundred page views a week, a 20 % change is noise. Say so. +- Seasonality, featuring, ads campaigns, a rating drop and price changes move the same numbers. Look at the same + weekday span and mention other things that changed in that window. +- A before / after comparison is not an experiment. For a real answer use the store tests: Play store listing + experiments (Console) and App Store Product Page Optimization (`storebound apple ppo`, store-screenshots skill). +- Never present estimates as facts to the owner, and never put these numbers into public text (listings, replies). diff --git a/tests/analytics.test.ts b/tests/analytics.test.ts new file mode 100644 index 00000000..6b97c4b6 --- /dev/null +++ b/tests/analytics.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, test } from 'bun:test'; +import { createHash } from 'node:crypto'; +import { + appleDaily, appleTotals, bucketName, checksumOk, compareAroundEvents, decodeText, effectMarkdown, effectTable, latestPerDate, mergeSeries, monthsBetween, + parseGitLog, parseReport, pickReport, playDaily, playObjects, playTotals, type Snapshot, +} from '../cli/lib/analytics'; +import { validateConfig } from '../cli/lib/config'; +import { TOOLS, toArgv } from '../cli/mcp-tools'; + +const ENG = 'Date\tApp Name\tApp Apple Identifier\tEvent\tPage Type\tSource Type\tEngagement Type\tDevice\tPlatform Version\tTerritory\tCounts\tUnique Counts\n' + + '2026-10-01\tExample\t1\tImpression\tProduct page\tApp Store search\t\tiPhone\tiOS 26\tUS\t100\t80\n' + + '2026-10-01\tExample\t1\tImpression\tProduct page\tApp Store browse\t\tiPhone\tiOS 26\tTR\t50\t20\n' + + '2026-10-01\tExample\t1\tPage view\tProduct page\tApp Store search\t\tiPhone\tiOS 26\tUS\t30\t25\n' + + '2026-10-01\tExample\t1\tTap\tProduct page\tApp Store search\t\tiPhone\tiOS 26\tUS\t9\t9\n'; +const DL = 'Date,App Name,App Apple Identifier,Download Type,App Version,Device,Platform Version,Source Type,Page Type,Pre-Order,Territory,Counts\n' + + '2026-10-01,Example,1,First-time Download,1.0,iPhone,iOS 26,App Store search,Product page,,US,10\n' + + '2026-10-01,Example,1,Redownload,1.0,iPhone,iOS 26,App Store search,Product page,,US,2\n' + + '2026-10-01,Example,1,Auto-update,1.0,iPhone,iOS 26,,,,US,500\n'; + +describe('apple analytics reports', () => { + test('pick the Standard report by name', () => { + const rs = [{ id: 'd', attributes: { name: 'App Store Discovery and Engagement Detailed' } }, { id: 's', attributes: { name: 'App Store Discovery and Engagement Standard' } }, { id: 'x', attributes: { name: 'App Sessions Standard' } }]; + expect(pickReport(rs, /discovery and engagement/i)!.id).toBe('s'); + expect(pickReport(rs.slice(0, 1), /discovery and engagement/i)!.id).toBe('d'); + expect(pickReport(rs, /nope/)).toBeNull(); + }); + test('tab and comma files by column name; daily sums', () => { + const eng = parseReport(ENG), dl = parseReport(DL); + expect(eng[0]!.unique_counts).toBe('80'); + expect(dl[0]!.download_type).toBe('First-time Download'); + expect(appleDaily(eng, dl)).toEqual([{ date: '2026-10-01', impressions: 150, uniqueImpressions: 100, pageViews: 30, uniquePageViews: 25, downloads: 12, firstTimeDownloads: 10 }]); + expect(appleTotals(appleDaily(eng, dl)).conversion).toBeCloseTo(0.12, 10); + }); + test('a later processingDate replaces the same Date', () => { + const rows = latestPerDate([ + { processingDate: '2026-10-02', rows: [{ date: '2026-10-01', counts: '1' }] }, + { processingDate: '2026-10-04', rows: [{ date: '2026-10-01', counts: '5' }, { date: '2026-10-03', counts: '7' }] }, + ]); + expect(rows).toEqual([{ date: '2026-10-01', counts: '5' }, { date: '2026-10-03', counts: '7' }]); + }); + test('md5 checksum and text decoding', () => { + const b = new TextEncoder().encode('hello'); + expect(checksumOk(b, createHash('md5').update(b).digest('hex').toUpperCase())).toBe(true); + expect(checksumOk(b, '00')).toBe(false); + const utf16 = new Uint8Array([0xff, 0xfe, ...[...'Date,x'].flatMap(c => [c.charCodeAt(0), 0])]); + expect(decodeText(utf16)).toBe('Date,x'); + expect(decodeText(new TextEncoder().encode('ok'))).toBe('ok'); + }); +}); + +describe('play statistics exports', () => { + test('file names, months, bucket', () => { + expect(monthsBetween('2026-11-20', '2027-02-01')).toEqual(['202611', '202612', '202701', '202702']); + expect(playObjects('com.example.game', '202610')).toEqual({ storePerformance: 'stats/store_performance/store_performance_com.example.game_202610_country.csv', installs: 'stats/installs/installs_com.example.game_202610_country.csv' }); + expect(bucketName('gs://pubsite_prod_rev_0000/stats')).toBe('pubsite_prod_rev_0000'); + }); + test('daily sums across countries', () => { + const sp = parseReport('Date,Package name,Country / region,Store listing acquisitions,Store listing visitors,Store listing conversion rate\n2026-10-01,com.example.game,US,10,100,10%\n2026-10-01,com.example.game,TR,5,50,10%\n'); + const inst = parseReport('Date,Package Name,Country,Daily Device Installs,Daily User Installs\n2026-10-01,com.example.game,US,12,11\n2026-10-02,com.example.game,US,3,3\n'); + const d = playDaily(sp, inst); + expect(d).toEqual([{ date: '2026-10-01', visitors: 150, acquisitions: 15, installs: 11 }, { date: '2026-10-02', visitors: 0, acquisitions: 0, installs: 3 }]); + expect(playTotals(d).conversion).toBeCloseTo(0.1, 10); + }); + test('config: reports bucket', () => { + const base = { app: { name: 'X', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'a@example.com' }, languages: [{ id: 'en' }] }; + expect(validateConfig({ ...base, play: { packageName: 'com.example.game', reportsBucket: 'gs://pubsite_prod_rev_0000/' } })).toEqual([]); + expect(validateConfig({ ...base, play: { packageName: 'com.example.game', reportsBucket: 'my-bucket' } })[0]).toContain('play.reportsBucket'); + }); +}); + +describe('compare with listing changes', () => { + const days = (from: number, n: number, f: (i: number) => { impressions: number; uniqueImpressions: number; downloads: number }) => + Array.from({ length: n }, (_, i) => ({ date: `2026-10-${String(from + i).padStart(2, '0')}`, pageViews: 0, uniquePageViews: 0, firstTimeDownloads: 0, ...f(i) })); + const snaps: Snapshot[] = [ + { date: '2026-10-08', window: { start: '2026-10-01', end: '2026-10-07', days: 7 }, apple: { daily: days(1, 7, () => ({ impressions: 100, uniqueImpressions: 100, downloads: 5 })), totals: {} } }, + { date: '2026-10-15', window: { start: '2026-10-08', end: '2026-10-14', days: 7 }, apple: { daily: days(8, 7, () => ({ impressions: 150, uniqueImpressions: 150, downloads: 12 })), totals: {} }, play: { error: 'no bucket' } }, + ]; + test('git log parsing', () => { + const out = '\x1eabc1234\x1f2026-10-08\x1fnew first screenshot\n\nstore/shots/copy.json\nstore/appstore.md\n\x1edef5678\x1f2026-10-02\x1fsubtitle tweak\n\nstore/appstore.md\n'; + expect(parseGitLog(out)).toEqual([ + { commit: 'abc1234', date: '2026-10-08', subject: 'new first screenshot', files: ['store/shots/copy.json', 'store/appstore.md'] }, + { commit: 'def5678', date: '2026-10-02', subject: 'subtitle tweak', files: ['store/appstore.md'] }]); + }); + test('before / after per event', () => { + const series = mergeSeries(snaps); + expect(series.apple).toHaveLength(14); + const fx = compareAroundEvents(series, [{ date: '2026-10-08', commit: 'abc', subject: 'new first screenshot', files: [] }], 7); + expect(fx).toHaveLength(1); + expect(fx[0]).toMatchObject({ store: 'apple', daysBefore: 7, daysAfter: 7 }); + expect(fx[0]!.before.conversion).toBeCloseTo(0.05, 10); + expect(fx[0]!.after.conversion).toBeCloseTo(0.08, 10); + const t = effectTable(fx); + expect(t).toContain('100 -> 150 +50%'); + expect(t).toContain('5.00% -> 8.00%'); + expect(effectMarkdown(fx)).toContain('| 2026-10-08 | apple | new first screenshot |'); + expect(effectTable([])).toContain('no listing changes'); + }); + test('mcp tools', () => { + const t = (n: string) => TOOLS.find(x => x.name === n)!; + expect(toArgv(t('analytics_snapshot'), { days: 14 }).argv).toEqual(['analytics', 'snapshot', '--days', '14', '--dry']); + expect(t('analytics_compare')).toMatchObject({ write: false, network: false }); + expect(toArgv(t('analytics_setup'), {}).argv).toEqual(['analytics', 'setup', '--dry']); + }); +});