From 3f12452e3f06ff18316efd7fc06df97bb448439a Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 10 Oct 2026 23:08:37 +0800 Subject: [PATCH 1/8] TestFlight through the App Store Connect API: apple testflight status | groups | testers | what-to-test | info | distribute Beta groups from apple.testflight.groups (created when missing, never changed), testers from a CSV in .storebound/ (masked in logs, confirmation before Apple emails invitations, --remove / --invite), What to Test per locale from the App Store listing (whatToTest or whatsNew), Test Information and Beta App Review details, builds by exact number to groups, Beta App Review submission behind --submit-review and a confirmation. Pure planners in cli/lib/testflight.ts, shared CSV / table / JSON:API helpers. MCP: apple_testflight_status, _groups, _what_to_test, _info, _distribute (internal groups only). Skill testflight. --- .cursor/rules/storebound.mdc | 1 + .github/copilot-instructions.md | 1 + AGENTS.md | 1 + GEMINI.md | 1 + cli/apple/jsonapi.ts | 29 +++ cli/apple/testflight.ts | 182 +++++++++++++++ cli/index.ts | 1 + cli/init.ts | 1 + cli/lib/config.ts | 4 + cli/lib/csv.ts | 43 ++++ cli/lib/table.ts | 16 ++ cli/lib/testflight.ts | 297 +++++++++++++++++++++++++ cli/mcp-tools.ts | 19 +- skills/appstore-first-release/SKILL.md | 5 +- skills/store-preflight/SKILL.md | 3 +- skills/testflight/SKILL.md | 79 +++++++ templates/storebound.config.ts | 8 + templates/testers.csv | 1 + tests/testflight.test.ts | 150 +++++++++++++ 19 files changed, 838 insertions(+), 4 deletions(-) create mode 100644 cli/apple/jsonapi.ts create mode 100644 cli/apple/testflight.ts create mode 100644 cli/lib/csv.ts create mode 100644 cli/lib/table.ts create mode 100644 cli/lib/testflight.ts create mode 100644 skills/testflight/SKILL.md create mode 100644 templates/testers.csv create mode 100644 tests/testflight.test.ts diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index 2fb58d1..fb0757a 100644 --- a/.cursor/rules/storebound.mdc +++ b/.cursor/rules/storebound.mdc @@ -49,4 +49,5 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `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-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages +- `skills/testflight/SKILL.md`: Run TestFlight for a mobile game through the App Store Connect API - `skills/whats-new/SKILL.md`: Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index dbf4edb..9782c12 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -51,4 +51,5 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `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-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages | +| `testflight` | Run TestFlight for a mobile game through the App Store Connect API | | `whats-new` | Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag | diff --git a/AGENTS.md b/AGENTS.md index cd0b267..cf7e1b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `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-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages +- `skills/testflight/SKILL.md`: Run TestFlight for a mobile game through the App Store Connect API - `skills/whats-new/SKILL.md`: Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag ## Working on storebound itself diff --git a/GEMINI.md b/GEMINI.md index fa776b2..b082126 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -50,4 +50,5 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `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-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages | +| `testflight` | Run TestFlight for a mobile game through the App Store Connect API | | `whats-new` | Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag | diff --git a/cli/apple/jsonapi.ts b/cli/apple/jsonapi.ts new file mode 100644 index 0000000..7276464 --- /dev/null +++ b/cli/apple/jsonapi.ts @@ -0,0 +1,29 @@ +// JSON:API request builders for App Store Connect. Pure: commands build `Req`s, print them on --dry and send them +// with the client otherwise. Request / response format: https://developer.apple.com/documentation/appstoreconnectapi +import { log } from '../lib/log'; + +export interface Req { method: 'GET' | 'POST' | 'PATCH' | 'DELETE'; path: string; body?: unknown; note?: string } + +export const one = (type: string, id: string) => ({ data: { type, id } }); +export const many = (type: string, ids: string[]) => ({ data: ids.map(id => ({ type, id })) }); + +/** One-line description of a request for dry runs and logs. Attribute values are cut short; `hide` keys (emails, + * passwords) are masked. */ +export function describeReq(r: Req, hide: string[] = ['email', 'demoAccountPassword', 'contactEmail', 'contactPhone']): string { + const attrs = (r.body as { data?: { attributes?: Record } } | undefined)?.data?.attributes; + const show = (k: string, v: unknown) => (hide.includes(k) ? '"***"' : typeof v === 'string' && v.length > 40 ? JSON.stringify(v.slice(0, 37) + '...') : JSON.stringify(v)); + const keys = attrs ? Object.entries(attrs).map(([k, v]) => `${k}=${show(k, v)}`) : []; + return `${r.method} ${r.path}${keys.length ? ` {${keys.join(', ')}}` : ''}${r.note ? ` # ${r.note}` : ''}`; +} + +/** Logs every planned request; sends them in order unless dry. Returns the responses (empty on dry). */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export async function execute(asc: (m: string, p: string, b?: unknown) => Promise, reqs: Req[], o: { dry: boolean; tag: string }): Promise { + const out: unknown[] = []; + for (const r of reqs) { + if (o.dry) { log(o.tag, `would ${describeReq(r)}`); continue; } + out.push(await asc(r.method, r.path, r.body)); + log(o.tag, `${describeReq(r)}: done`); + } + return out; +} diff --git a/cli/apple/testflight.ts b/cli/apple/testflight.ts new file mode 100644 index 0000000..626b55f --- /dev/null +++ b/cli/apple/testflight.ts @@ -0,0 +1,182 @@ +// TestFlight through the App Store Connect API. +// storebound apple testflight status groups, testers per group, recent builds + beta states +// storebound apple testflight groups [--dry] create the groups of apple.testflight.groups that are missing +// storebound apple testflight testers [--csv f] [--group a,b] [--remove] [--invite] [--dry] [--yes] +// storebound apple testflight what-to-test --build N [--version x.y.z] [--locale en-US,tr] [--text "..."] [--dry] +// storebound apple testflight info [--dry] Test Information + Beta App Review contact / notes +// storebound apple testflight distribute --build N --group a,b [--version x.y.z] [--internal-only] [--submit-review] [--dry] [--yes] +// Testers come from a CSV in .storebound/ (gitignored; never commit tester emails): email, first_name, last_name, +// groups (";"-separated). Emails are masked in every log line. Adding testers makes Apple email TestFlight invitations +// (once the group has a build), so `testers` asks first; `--remove` takes testers out of the managed groups. +// `distribute --submit-review` sends the build to Beta App Review (external groups) after a confirmation; neither +// testers nor external distribution nor the review submission are MCP tools. Pure planning: cli/lib/testflight.ts. +import { existsSync, readFileSync } from 'node:fs'; +import type { Ctx } from '../lib/ctx'; +import { confirm, need } from '../lib/ctx'; +import { reviewContact } from '../lib/credentials'; +import { done, log, warn } from '../lib/log'; +import { textTable } from '../lib/table'; +import { + type ApiBuild, betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail, + parseTesters, pickBuild, planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, whatToTestFromListing, +} from '../lib/testflight'; +import { type Asc, ascClient, type J } from './asc'; +import { execute } from './jsonapi'; + +const TAG = 'testflight'; +const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group '; + +async function groups(c: Asc, appId: string): Promise { + return (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).map(groupFromApi); +} + +async function findBuild(c: Asc, appId: string, number: string, marketing?: string): Promise { + const q = new URLSearchParams({ 'filter[app]': appId, 'filter[version]': number, 'filter[preReleaseVersion.platform]': 'IOS', include: 'preReleaseVersion,buildBetaDetail', limit: '50' }); + if (marketing) q.set('filter[preReleaseVersion.version]', marketing); + const resp = await c.asc('GET', `/v1/builds?${q}`); + const b = pickBuild(buildsWithVersion(resp), number, marketing); + const detail = (resp.included ?? []).find((x: J) => x.type === 'buildBetaDetails' && x.id === (b as J).relationships?.buildBetaDetail?.data?.id)?.attributes ?? null; + return { ...b, detail }; +} + +export async function run(ctx: Ctx): Promise { + const { config, root, resolve } = ctx.loaded; + const a = ctx.args; + const sub = a._[0]; + if (!sub) throw new Error(USAGE); + const dry = a.has('dry'); + const tf = config.apple?.testflight; + const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); + const appId = await c.app(); + + if (sub === 'status') { + const gs = await groups(c, appId); + const rows: (string | number)[][] = []; + for (const g of gs) { + const testers = await c.all(`/v1/betaGroups/${g.id}/betaTesters?limit=200`); + const builds = await c.all(`/v1/betaGroups/${g.id}/builds?limit=200`); + rows.push([g.name, g.internal ? 'internal' : 'external', testers.length, g.internal && g.hasAccessToAllBuilds ? 'all' : builds.length, g.publicLinkEnabled ? 'public link on' : '']); + } + console.log(textTable(['group', 'kind', 'testers', 'builds', ''], rows)); + const q = new URLSearchParams({ 'filter[app]': appId, include: 'preReleaseVersion,buildBetaDetail', sort: '-uploadedDate', limit: '8' }); + const resp = await c.asc('GET', `/v1/builds?${q}`); + const details = new Map((resp.included ?? []).filter((x: J) => x.type === 'buildBetaDetails').map((x: J) => [x.id, x.attributes] as const)); + console.log('\n' + textTable(['version', 'build', 'processing', 'internal', 'external', 'uploaded'], buildsWithVersion(resp).map(b => { + const d = details.get((b as J).relationships?.buildBetaDetail?.data?.id) as J; + return [b.marketing ?? '', b.attributes.version ?? '', b.attributes.processingState ?? '', d?.internalBuildState ?? '', d?.externalBuildState ?? '', (b.attributes.uploadedDate ?? '').slice(0, 10)]; + }))); + const missing = (tf?.groups ?? []).filter(w => !gs.some(g => g.name === w.name)).map(w => w.name); + if (missing.length) warn(TAG, `configured but not on App Store Connect: ${missing.join(', ')} (storebound apple testflight groups)`); + return; + } + + if (sub === 'groups') { + const plan = planGroups(appId, await groups(c, appId), tf?.groups ?? []); + if (!tf?.groups?.length) warn(TAG, 'apple.testflight.groups is empty: nothing to create'); + for (const n of plan.existing) log(TAG, `group "${n}": exists`); + await execute(c.asc, plan.create, { dry, tag: TAG }); + done(TAG, dry ? `groups checked (dry run): ${plan.create.length} to create` : `groups done (${plan.create.length} created)`); + return; + } + + if (sub === 'testers') { + const csvPath = resolve(a.get('csv') ?? tf?.testers ?? '.storebound/testers.csv'); + if (!existsSync(csvPath)) throw new Error(`no tester CSV at ${csvPath} (columns: email, first_name, last_name, groups; keep it in .storebound/)`); + const only = a.list('group'); + const want = parseTesters(readFileSync(csvPath, 'utf8'), only.length === 1 ? only[0] : undefined); + const gs = await groups(c, appId); + const existing = new Map(); + const resp = await c.all(`/v1/betaTesters?filter[apps]=${appId}&include=betaGroups&limit=200`); + for (const t of resp) existing.set(String(t.attributes.email ?? '').toLowerCase(), { id: t.id, groupIds: (t.relationships?.betaGroups?.data ?? []).map((g: J) => g.id), state: t.attributes.state }); + const plan = planTesters(gs, existing, want, { remove: a.has('remove'), only }); + if (plan.unknownGroups.length) throw new Error(`unknown group(s): ${plan.unknownGroups.join(', ')} (storebound apple testflight groups creates the configured ones)`); + const internal = gs.filter(g => g.internal && want.some(t => t.groups.includes(g.name))); + if (internal.length) warn(TAG, `internal groups (${internal.map(g => g.name).join(', ')}) only take App Store Connect users of your team (Users and Access)`); + log(TAG, `${want.length} testers in the CSV: ${plan.summary.join(', ')}`); + const reqs = [...plan.create, ...plan.add, ...plan.remove]; + if (!reqs.length && !a.has('invite')) { done(TAG, 'testers up to date'); return; } + if (dry) { await execute(c.asc, reqs, { dry, tag: TAG }); done(TAG, 'testers checked (dry run)'); return; } + if (reqs.length && !(await confirm(ctx, `Apply ${plan.summary.join(', ')}? New testers get a TestFlight invitation email from Apple.`))) return; + await execute(c.asc, reqs, { dry, tag: TAG }); + if (a.has('invite')) { + const fresh = new Map((await c.all(`/v1/betaTesters?filter[apps]=${appId}&limit=200`)).map((t: J) => [String(t.attributes.email ?? '').toLowerCase(), t] as const)); + const pending = want.map(t => fresh.get(t.email)).filter((t): t is J => !!t && ['NOT_INVITED', 'INVITED'].includes(t.attributes.state)); + if (pending.length && await confirm(ctx, `(Re)send the TestFlight invitation email to ${pending.length} tester(s)?`)) + await execute(c.asc, pending.map(t => inviteReq(appId, t.id, maskEmail(String(t.attributes.email)))), { dry: false, tag: TAG }); + } + done(TAG, 'testers done'); + return; + } + + if (sub === 'what-to-test') { + const number = need(a.get('build'), '--build N (the exact build number)'); + const b = await findBuild(c, appId, number, a.get('version')); + let want: Record; + const locales = a.list('locale'); + if (a.get('text')) { + const ls = locales.length ? locales : [config.apple?.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US']; + want = Object.fromEntries(ls.map(l => [l, a.get('text')!])); + } else { + const f = resolve(config.apple?.listing ?? 'store/appstore.md'); + want = whatToTestFromListing(readFileSync(f, 'utf8')); + if (locales.length) want = Object.fromEntries(Object.entries(want).filter(([l]) => locales.includes(l))); + if (!Object.keys(want).length) throw new Error(`${f}: no "### whatToTest" or "### whatsNew" block (storebound whats-new drafts one), or pass --text`); + } + const existing = (await c.all(`/v1/builds/${b.id}/betaBuildLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, whatsNew: l.attributes.whatsNew })); + const reqs = planWhatToTest(b.id, existing, want); + if (!reqs.length) { done(TAG, `build ${number}: What to Test up to date (${Object.keys(want).join(', ')})`); return; } + await execute(c.asc, reqs, { dry, tag: TAG }); + done(TAG, dry ? `build ${number}: ${reqs.length} locale(s) to set (dry run)` : `build ${number}: What to Test set for ${reqs.length} locale(s)`); + return; + } + + if (sub === 'info') { + const desc = betaDescriptions(tf, config.languages); + if (!Object.keys(desc).length) warn(TAG, 'apple.testflight.description is not set: external testing needs a Beta App Description per locale'); + const want = Object.fromEntries(Object.entries(desc).map(([locale, description]) => [locale, { description, feedbackEmail: config.app.contactEmail, + privacyPolicyUrl: config.app.privacyPolicyUrl, marketingUrl: config.app.marketingUrl ?? config.app.website }])); + const locs = (await c.all(`/v1/apps/${appId}/betaAppLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, attributes: l.attributes })); + const detail = (await c.maybe(`/v1/apps/${appId}/betaAppReviewDetail`))?.data ?? null; + const contact = reviewContact(root); + if (!contact) warn(TAG, 'no reviewContact in .storebound/credentials.json: Beta App Review contact left as it is'); + const reqs = [...planBetaInfo(appId, locs, want), ...planBetaReviewDetail(detail, contact, tf?.reviewNotes ?? config.apple?.info?.reviewNotes)]; + await execute(c.asc, reqs, { dry, tag: TAG }); + done(TAG, reqs.length ? (dry ? `${reqs.length} change(s) (dry run)` : `test information updated (${reqs.length})`) : 'test information up to date'); + return; + } + + if (sub === 'distribute') { + const number = need(a.get('build'), '--build N (the exact build number you uploaded)'); + const names = a.list('group'); + if (!names.length) throw new Error('--group [,]: which beta groups get the build'); + const gs = await groups(c, appId); + const target = names.map(n => gs.find(g => g.name === n) ?? (() => { throw new Error(`unknown group "${n}" (${gs.map(g => g.name).join(', ')})`); })()); + const external = target.filter(g => !g.internal); + if (a.has('internal-only') && external.length) throw new Error(`external group(s) ${external.map(g => g.name).join(', ')}: distribute to external testers from the terminal (asks first)`); + const b = await findBuild(c, appId, number, a.get('version')); + const problems = betaReadiness(b.attributes, b.detail); + if (problems.length) throw new Error(`build ${number}: ${problems.join('; ')}`); + log(TAG, `build ${number} (${b.marketing ?? '?'}): internal ${b.detail?.internalBuildState ?? '?'}, external ${b.detail?.externalBuildState ?? '?'}`); + const inGroups = (await c.all(`/v1/betaGroups?filter[app]=${appId}&filter[builds]=${b.id}&limit=200`)).map((g: J) => g.id); + const reqs = planDistribute(b.id, target, inGroups); + const review = a.has('submit-review') && external.length ? (await c.maybe(`/v1/builds/${b.id}/betaAppReviewSubmission`))?.data ?? null : null; + const wantsReview = a.has('submit-review') && external.length > 0 && !review && !['BETA_APPROVED', 'IN_BETA_REVIEW', 'WAITING_FOR_BETA_REVIEW', 'IN_BETA_TESTING'].includes(b.detail?.externalBuildState); + if (a.has('submit-review') && review) log(TAG, `beta review: already submitted (${review.attributes?.betaReviewState ?? '?'})`); + if (external.length && !a.has('submit-review') && b.detail?.externalBuildState === 'READY_FOR_BETA_SUBMISSION') + warn(TAG, 'external testers only get the build after Beta App Review: add --submit-review (asks first) or submit it in App Store Connect'); + if (dry) { + await execute(c.asc, [...reqs, ...(wantsReview ? [betaReviewReq(b.id)] : [])], { dry, tag: TAG }); + done(TAG, 'distribute checked (dry run)'); + return; + } + if (external.length && reqs.some(r => external.some(g => r.path.includes(g.id))) && !(await confirm(ctx, `Give build ${number} to external group(s) ${external.map(g => g.name).join(', ')}? Testers are notified once Beta App Review approves it.`))) return; + await execute(c.asc, reqs, { dry, tag: TAG }); + if (wantsReview) { + if (await confirm(ctx, `Submit build ${number} to Beta App Review now? Apple reviews it for external testing (Test Information must be complete: storebound apple testflight info).`)) + await execute(c.asc, [betaReviewReq(b.id)], { dry: false, tag: TAG }); + } + done(TAG, `build ${number}: ${reqs.length ? `added to ${reqs.length} group(s)` : 'already in every group'}`); + return; + } + throw new Error(`unknown testflight command "${sub}"\n${USAGE}`); +} diff --git a/cli/index.ts b/cli/index.ts index 5552234..0318a97 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -38,6 +38,7 @@ const COMMANDS: Record Promise, string]> = { 'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'], 'apple next-build': [() => import('./apple/next-build'), 'next safe build number (prints the number)'], 'apple encryption': [() => import('./apple/encryption'), 'export compliance answer for builds, from the config'], + 'apple testflight': [() => import('./apple/testflight'), 'TestFlight: status | groups | testers (CSV in .storebound/) | what-to-test --build N | info | distribute --build N --group g [--submit-review]'], 'icons': [() => import('./icons'), 'App Store / Play / web / adaptive / legacy launcher icons from one artwork'], 'shots capture': [() => import('./shots/capture'), 'raw frames: --source web (playwright) | ios-sim (simctl) | android-emu (adb) | folder; --dry'], 'shots fonts': [() => import('./shots/fonts'), 'download font subsets for the copy (CJK / Arabic / Cyrillic ...)'], diff --git a/cli/init.ts b/cli/init.ts index 55e1c15..fbf4ff9 100644 --- a/cli/init.ts +++ b/cli/init.ts @@ -15,6 +15,7 @@ const FILES: [string, string][] = [ ['declarations.md', 'store/declarations.md'], ['privacy-policy.html', 'store/privacy-policy.html'], ['credentials.example.json', '.storebound/credentials.json'], + ['testers.csv', '.storebound/testers.csv'], ]; export async function run(args: Args): Promise { diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 219c954..2dbb50d 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -3,6 +3,7 @@ import { existsSync } from 'node:fs'; import { dirname, isAbsolute, join, resolve } from 'node:path'; import { validateCapture, validateRecord } from '../shots/devices'; +import { type TfConfig, validateTestflight } from './testflight'; export type ProductType = 'consumable' | 'non_consumable'; @@ -283,6 +284,8 @@ export interface ShipConfig { screenshotTypes?: string[]; /** The app runs on iPad: renders, checks and uploads 13" iPad screenshots (2064 x 2752) and iPad app previews. */ ipad?: boolean; + /** TestFlight beta groups, the tester CSV (in .storebound/) and Test Information (`storebound apple testflight`). */ + testflight?: TfConfig; }; products?: Product[]; dataSafety?: DataSafety; @@ -331,6 +334,7 @@ export function validateConfig(c: unknown): string[] { const enc = cfg.apple.usesNonExemptEncryption; if (enc !== undefined && typeof enc !== 'boolean') e.push('apple.usesNonExemptEncryption: true | false'); if (cfg.apple.screenshotTypes && !cfg.apple.screenshotTypes.every(t => /^APP_[A-Z0-9_]+$/.test(t))) e.push('apple.screenshotTypes: display types like APP_IPHONE_67'); + e.push(...validateTestflight(cfg.apple.testflight)); } if (cfg.ads?.appAdsTxt && !cfg.ads.appAdsTxt.every(l => typeof l === 'string' && l.split(',').length >= 3)) e.push('ads.appAdsTxt: lines like "example-network.com, pub-123, DIRECT, abc123"'); diff --git a/cli/lib/csv.ts b/cli/lib/csv.ts new file mode 100644 index 0000000..f39b6a1 --- /dev/null +++ b/cli/lib/csv.ts @@ -0,0 +1,43 @@ +// Small RFC 4180 CSV reader / writer (quotes, doubled quotes, CR LF, a UTF-8 BOM). Pure. Used for tester lists, +// price sheets and the Play statistics exports. +import { csvCell } from './data-safety'; + +/** Rows of cells. Empty lines are dropped. */ +export function parseCsv(text: string, sep = ','): string[][] { + const rows: string[][] = []; + let row: string[] = []; + let cell = ''; + let quoted = false; + const s = text.replace(/^/, ''); + for (let i = 0; i < s.length; i++) { + const ch = s[i]!; + if (quoted) { + if (ch === '"') { if (s[i + 1] === '"') { cell += '"'; i++; } else quoted = false; } + else cell += ch; + continue; + } + if (ch === '"' && cell === '') { quoted = true; continue; } + if (ch === sep) { row.push(cell); cell = ''; continue; } + if (ch === '\n' || ch === '\r') { + if (ch === '\r' && s[i + 1] === '\n') i++; + row.push(cell); cell = ''; + if (row.some(c => c !== '')) rows.push(row); + row = []; + continue; + } + cell += ch; + } + row.push(cell); + if (row.some(c => c !== '')) rows.push(row); + return rows; +} + +/** Header row -> objects keyed by the lower-cased, trimmed header (spaces and dashes become "_"). */ +export function parseCsvRecords(text: string, sep = ','): Record[] { + const [head, ...rest] = parseCsv(text, sep); + if (!head) return []; + const keys = head.map(h => h.trim().toLowerCase().replace(/[\s-]+/g, '_')); + return rest.map(r => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? '').trim()]))); +} + +export const toCsv = (rows: (string | number)[][]): string => rows.map(r => r.map(c => csvCell(String(c))).join(',')).join('\n') + '\n'; diff --git a/cli/lib/table.ts b/cli/lib/table.ts new file mode 100644 index 0000000..d2f082c --- /dev/null +++ b/cli/lib/table.ts @@ -0,0 +1,16 @@ +// Aligned text tables for the terminal and Markdown tables for reports. Pure. + +export function textTable(head: string[], rows: (string | number)[][]): string { + const all = [head, ...rows.map(r => r.map(String))]; + const w = head.map((_, i) => Math.max(...all.map(r => [...(r[i] ?? '')].length))); + const line = (r: string[]) => r.map((c, i) => c + ' '.repeat(w[i]! - [...c].length)).join(' ').trimEnd(); + return [line(head), line(w.map(n => '-'.repeat(n))), ...all.slice(1).map(line)].join('\n'); +} + +const md = (c: string | number) => String(c).replace(/\|/g, '\\|').replace(/\n/g, ' '); +export function mdTable(head: string[], rows: (string | number)[][]): string { + return [`| ${head.map(md).join(' | ')} |`, `|${head.map(() => '---').join('|')}|`, ...rows.map(r => `| ${r.map(md).join(' | ')} |`)].join('\n'); +} + +/** 0.01234 -> "1.23%" */ +export const pct = (x: number | null | undefined, digits = 2): string => (x === null || x === undefined || Number.isNaN(x) ? 'n/a' : `${(x * 100).toFixed(digits)}%`); diff --git a/cli/lib/testflight.ts b/cli/lib/testflight.ts new file mode 100644 index 0000000..cb7d073 --- /dev/null +++ b/cli/lib/testflight.ts @@ -0,0 +1,297 @@ +// TestFlight through the App Store Connect API, as pure planners: what exists (read with GETs) + what the config / CSV +// wants -> the requests to send. The command (cli/apple/testflight.ts) reads, plans, prints the plan on --dry and sends. +// API references (checked October 2026): +// beta groups https://developer.apple.com/documentation/appstoreconnectapi/beta-groups +// beta testers https://developer.apple.com/documentation/appstoreconnectapi/beta-testers +// invitations https://developer.apple.com/documentation/appstoreconnectapi/beta-tester-invitations +// What to Test https://developer.apple.com/documentation/appstoreconnectapi/beta-build-localizations +// beta review https://developer.apple.com/documentation/appstoreconnectapi/beta-app-review-submissions +// test information https://developer.apple.com/documentation/appstoreconnectapi/beta-app-localizations +// https://developer.apple.com/documentation/appstoreconnectapi/beta-app-review-details +import { type Req, many, one } from '../apple/jsonapi'; +import { parseCsvRecords } from './csv'; +import { len } from './copy'; + +/** "What to Test" per build and locale (betaBuildLocalizations.whatsNew). Apple's API docs state no maximum; 4000 is + * assumed (the App Store "What's New" limit). NOT VERIFIED: keep it well below, testers read it on a phone. */ +export const WHAT_TO_TEST_LIMIT = 4000; +/** Beta App Review notes (betaAppReviewDetails.notes): "Review notes have a maximum of 4,000 characters." */ +export const BETA_NOTES_LIMIT = 4000; +/** Beta App Description (betaAppLocalizations.description) shown to external testers. */ +export const BETA_DESCRIPTION_LIMIT = 4000; + +export interface TfGroupSpec { + name: string; + /** Internal group (App Store Connect users of your team; no beta review). Default false = external. */ + internal?: boolean; + /** Internal groups only: every new build is available to the group automatically. */ + allBuilds?: boolean; + /** External groups only: public TestFlight link (anyone with the link can join, up to publicLinkLimit). */ + publicLink?: boolean; + publicLinkLimit?: number; + /** Testers can send feedback (screenshots, comments) from TestFlight. Default true. */ + feedback?: boolean; +} + +export interface TfConfig { + groups?: TfGroupSpec[]; + /** CSV of testers: email, first_name, last_name, groups (";"-separated group names). Must live in .storebound/ + * (gitignored): tester emails are personal data and never go into the repo. Default .storebound/testers.csv. */ + testers?: string; + /** Beta App Description per language id (or one text for every locale); shown to external testers. */ + description?: string | Record; + /** Notes for Beta App Review (where to find what, test account hints). The contact comes from + * .storebound/credentials.json reviewContact like for App Review. */ + reviewNotes?: string; +} + +export interface Group { id: string; name: string; internal: boolean; publicLinkEnabled?: boolean; publicLink?: string | null; hasAccessToAllBuilds?: boolean } + +export const groupFromApi = (g: { id: string; attributes: Record }): Group => ({ + id: g.id, name: String(g.attributes.name ?? ''), internal: g.attributes.isInternalGroup === true, + publicLinkEnabled: g.attributes.publicLinkEnabled as boolean | undefined, publicLink: (g.attributes.publicLink as string | null | undefined) ?? null, + hasAccessToAllBuilds: g.attributes.hasAccessToAllBuilds as boolean | undefined, +}); + +/** Problems with the testflight config. Pure. */ +export function validateTestflight(t: TfConfig | undefined): string[] { + if (!t) return []; + const e: string[] = []; + const names = new Set(); + for (const [i, g] of (t.groups ?? []).entries()) { + const at = `apple.testflight.groups[${i}]`; + if (!g.name || len(g.name) > 50) e.push(`${at}.name: 1-50 characters`); + if (names.has(g.name)) e.push(`${at}.name: duplicate "${g.name}"`); + names.add(g.name); + if (g.internal && (g.publicLink || g.publicLinkLimit !== undefined)) e.push(`${at}: public links are for external groups only`); + if (!g.internal && g.allBuilds !== undefined) e.push(`${at}.allBuilds: internal groups only (external builds go through beta review one by one)`); + if (g.publicLinkLimit !== undefined && !(Number.isInteger(g.publicLinkLimit) && g.publicLinkLimit >= 1 && g.publicLinkLimit <= 10000)) e.push(`${at}.publicLinkLimit: 1-10000`); + } + if (t.testers !== undefined && !/^\.storebound\//.test(t.testers.replace(/^\.\//, ''))) + e.push('apple.testflight.testers: keep the tester CSV in .storebound/ (gitignored); emails never go into the repo'); + return e; +} + +/** POST /v1/betaGroups for every configured group missing on App Store Connect (matched by name). Existing groups are + * never renamed, changed or deleted. */ +export function planGroups(appId: string, existing: Group[], want: TfGroupSpec[]): { create: Req[]; existing: string[] } { + const have = new Set(existing.map(g => g.name)); + const create: Req[] = want.filter(g => !have.has(g.name)).map(g => ({ + method: 'POST', path: '/v1/betaGroups', note: `${g.internal ? 'internal' : 'external'} group "${g.name}"`, + body: { data: { type: 'betaGroups', attributes: { + name: g.name, + ...(g.internal ? { isInternalGroup: true, hasAccessToAllBuilds: g.allBuilds ?? false } : {}), + ...(!g.internal && g.publicLink ? { publicLinkEnabled: true, publicLinkLimitEnabled: g.publicLinkLimit !== undefined, ...(g.publicLinkLimit !== undefined ? { publicLinkLimit: g.publicLinkLimit } : {}) } : {}), + feedbackEnabled: g.feedback ?? true, + }, relationships: { app: one('apps', appId) } } }, + })); + return { create, existing: want.filter(g => have.has(g.name)).map(g => g.name) }; +} + +export interface Tester { email: string; firstName?: string; lastName?: string; groups: string[] } + +const EMAIL = /^[^@\s,;]+@[^@\s,;]+\.[^@\s,;]+$/; + +/** Tester CSV -> testers. Columns (header row, any order): email, first_name (or firstname / first), last_name, + * groups (";"-separated group names; empty = `defaultGroup`). Throws on bad emails or duplicates. */ +export function parseTesters(csv: string, defaultGroup?: string): Tester[] { + const out: Tester[] = []; + const seen = new Set(); + const errors: string[] = []; + for (const [i, r] of parseCsvRecords(csv).entries()) { + const email = (r.email ?? '').toLowerCase(); + if (!EMAIL.test(email)) { errors.push(`row ${i + 2}: "${maskEmail(email)}" is not an email`); continue; } + if (seen.has(email)) { errors.push(`row ${i + 2}: ${maskEmail(email)} listed twice`); continue; } + seen.add(email); + const groups = (r.groups ?? r.group ?? '').split(';').map(s => s.trim()).filter(Boolean); + if (!groups.length && defaultGroup) groups.push(defaultGroup); + out.push({ email, firstName: r.first_name || r.firstname || r.first || undefined, lastName: r.last_name || r.lastname || r.last || undefined, groups }); + } + if (errors.length) throw new Error(`testers CSV: ${errors.join('; ')}`); + return out; +} + +/** "jane.doe@example.com" -> "j***@example.com": emails in logs and MCP output stay readable but not harvestable. */ +export function maskEmail(e: string): string { + const at = e.indexOf('@'); + if (at < 1) return '***'; + return `${e[0]}***${e.slice(at)}`; +} + +export interface TesterPlan { + /** New testers: POST /v1/betaTesters with their groups (Apple emails the invitation once a build is available). */ + create: Req[]; + /** Existing testers added to more groups: POST /v1/betaGroups/{id}/relationships/betaTesters. */ + add: Req[]; + /** Testers in a managed group but not in the CSV (only with remove): DELETE .../relationships/betaTesters. */ + remove: Req[]; + unknownGroups: string[]; + summary: string[]; +} + +/** + * Testers of the managed groups (those named in the CSV or `only`) vs the CSV. `existing` maps a beta tester (by + * lower-case email) to its id and current group ids. Removal only with `remove` (it ends their access to the builds + * of that group; the tester record itself is kept). + */ +export function planTesters(groups: Group[], existing: Map, want: Tester[], o: { remove?: boolean; only?: string[] } = {}): TesterPlan { + const byName = new Map(groups.map(g => [g.name, g] as const)); + const plan: TesterPlan = { create: [], add: [], remove: [], unknownGroups: [], summary: [] }; + const managed = new Set(o.only?.length ? o.only : want.flatMap(t => t.groups)); + for (const n of managed) if (!byName.has(n)) plan.unknownGroups.push(n); + const addTo = new Map(); + for (const t of want) { + const target = t.groups.filter(n => managed.has(n) && byName.has(n)).map(n => byName.get(n)!); + if (!target.length) continue; + const cur = existing.get(t.email); + if (!cur) { + plan.create.push({ method: 'POST', path: '/v1/betaTesters', note: `${maskEmail(t.email)} -> ${target.map(g => g.name).join(', ')}`, + body: { data: { type: 'betaTesters', attributes: { email: t.email, ...(t.firstName ? { firstName: t.firstName } : {}), ...(t.lastName ? { lastName: t.lastName } : {}) }, + relationships: { betaGroups: many('betaGroups', target.map(g => g.id)) } } } }); + continue; + } + for (const g of target) if (!cur.groupIds.includes(g.id)) addTo.set(g.id, [...(addTo.get(g.id) ?? []), cur.id]); + } + for (const [gid, ids] of addTo) { + const g = groups.find(x => x.id === gid)!; + plan.add.push({ method: 'POST', path: `/v1/betaGroups/${gid}/relationships/betaTesters`, body: many('betaTesters', ids), note: `${ids.length} existing tester(s) -> "${g.name}"` }); + } + if (o.remove) { + const wanted = new Map>(); + for (const t of want) for (const n of t.groups) if (byName.has(n)) wanted.set(byName.get(n)!.id, (wanted.get(byName.get(n)!.id) ?? new Set()).add(t.email)); + const drop = new Map(); + for (const [email, cur] of existing) for (const gid of cur.groupIds) { + const g = groups.find(x => x.id === gid); + if (!g || !managed.has(g.name)) continue; + if (!wanted.get(gid)?.has(email)) drop.set(gid, [...(drop.get(gid) ?? []), cur.id]); + } + for (const [gid, ids] of drop) { + const g = groups.find(x => x.id === gid)!; + plan.remove.push({ method: 'DELETE', path: `/v1/betaGroups/${gid}/relationships/betaTesters`, body: many('betaTesters', ids), note: `${ids.length} tester(s) leave "${g.name}"` }); + } + } + plan.summary.push(`${plan.create.length} new tester(s)`, `${plan.add.reduce((n, r) => n + (r.body as { data: unknown[] }).data.length, 0)} added to groups`, + `${plan.remove.reduce((n, r) => n + (r.body as { data: unknown[] }).data.length, 0)} removed from groups`); + return plan; +} + +/** POST /v1/betaTesterInvitations: (re)send the TestFlight invitation email of one tester for this app. */ +export const inviteReq = (appId: string, testerId: string, label: string): Req => ({ method: 'POST', path: '/v1/betaTesterInvitations', note: `invite ${label}`, + body: { data: { type: 'betaTesterInvitations', relationships: { app: one('apps', appId), betaTester: one('betaTesters', testerId) } } } }); + +/** POST /v1/betaGroups/{id}/relationships/builds for every group that does not have the build yet. */ +export function planDistribute(buildId: string, groups: Group[], buildGroupIds: string[]): Req[] { + return groups.filter(g => !buildGroupIds.includes(g.id) && !(g.internal && g.hasAccessToAllBuilds)).map(g => ({ method: 'POST', path: `/v1/betaGroups/${g.id}/relationships/builds`, + body: many('builds', [buildId]), note: `build -> ${g.internal ? 'internal' : 'external'} group "${g.name}"` })); +} + +/** + * "What to Test" texts for TestFlight per App Store locale from the App Store listing file: a `### whatToTest` block + * when a locale section has one, else its `### whatsNew` block (what `storebound whats-new` drafts). Pure. + */ +export function whatToTestFromListing(md: string): Record { + const out: Record = {}; + for (const sec of md.split(/^## /m).slice(1)) { + const locale = sec.split(/[\s·]/)[0]!.trim(); + if (!/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(locale)) continue; + const block = (name: string) => new RegExp(`^### ${name}[^\\n]*\\n\`\`\`[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``, 'm').exec(sec)?.[1]?.trim(); + const text = block('whatToTest') ?? block('whatsNew'); + if (text) out[locale] = text; + } + return out; +} + +/** betaBuildLocalizations to create (POST) or update (PATCH) so the build has exactly these texts. Locales on the + * build that are not in `want` are left alone. Throws when a text is over the limit. */ +export function planWhatToTest(buildId: string, existing: { id: string; locale: string; whatsNew?: string | null }[], want: Record): Req[] { + const tooLong = Object.entries(want).filter(([, t]) => len(t) > WHAT_TO_TEST_LIMIT).map(([l, t]) => `${l} ${len(t)}`); + if (tooLong.length) throw new Error(`What to Test over ${WHAT_TO_TEST_LIMIT} characters: ${tooLong.join(', ')}`); + const have = new Map(existing.map(l => [l.locale, l] as const)); + const out: Req[] = []; + for (const [locale, whatsNew] of Object.entries(want)) { + const cur = have.get(locale); + if (!cur) out.push({ method: 'POST', path: '/v1/betaBuildLocalizations', note: locale, + body: { data: { type: 'betaBuildLocalizations', attributes: { locale, whatsNew }, relationships: { build: one('builds', buildId) } } } }); + else if ((cur.whatsNew ?? '') !== whatsNew) out.push({ method: 'PATCH', path: `/v1/betaBuildLocalizations/${cur.id}`, note: locale, + body: { data: { type: 'betaBuildLocalizations', id: cur.id, attributes: { whatsNew } } } }); + } + return out; +} + +/** POST /v1/betaAppReviewSubmissions: send one build to Beta App Review (needed once per version for external + * testing; later builds of the same version are often approved automatically). */ +export const betaReviewReq = (buildId: string): Req => ({ method: 'POST', path: '/v1/betaAppReviewSubmissions', note: 'submit for Beta App Review', + body: { data: { type: 'betaAppReviewSubmissions', relationships: { build: one('builds', buildId) } } } }); + +/** Build states in which a build can be tested / sent to beta review. */ +export function betaReadiness(b: { processingState?: string; expired?: boolean; usesNonExemptEncryption?: boolean | null }, detail: { externalBuildState?: string; internalBuildState?: string } | null): string[] { + const p: string[] = []; + if (b.processingState !== 'VALID') p.push(`processing state ${b.processingState ?? 'unknown'} (wait for VALID)`); + if (b.expired) p.push('expired (TestFlight builds expire after 90 days)'); + if (b.usesNonExemptEncryption === null || b.usesNonExemptEncryption === undefined) { + if (detail?.internalBuildState === 'MISSING_EXPORT_COMPLIANCE' || detail?.externalBuildState === 'MISSING_EXPORT_COMPLIANCE') + p.push('export compliance missing (storebound apple encryption --build N)'); + } + return p; +} + +export interface BetaInfo { description?: string; feedbackEmail?: string; privacyPolicyUrl?: string; marketingUrl?: string } + +/** Test Information per locale (betaAppLocalizations): POST missing locales, PATCH changed fields. Apple requires a + * description on every beta app localization before a build can go to Beta App Review; fields cannot be cleared. */ +export function planBetaInfo(appId: string, existing: { id: string; locale: string; attributes: BetaInfo }[], want: Record): Req[] { + const have = new Map(existing.map(l => [l.locale, l] as const)); + const out: Req[] = []; + for (const [locale, w] of Object.entries(want)) { + const attrs = Object.fromEntries(Object.entries(w).filter(([, v]) => v !== undefined && v !== '')) as BetaInfo; + if (attrs.description && len(attrs.description) > BETA_DESCRIPTION_LIMIT) throw new Error(`beta description ${locale}: over ${BETA_DESCRIPTION_LIMIT} characters`); + const cur = have.get(locale); + if (!cur) { out.push({ method: 'POST', path: '/v1/betaAppLocalizations', note: locale, body: { data: { type: 'betaAppLocalizations', attributes: { locale, ...attrs }, relationships: { app: one('apps', appId) } } } }); continue; } + const changed = Object.fromEntries(Object.entries(attrs).filter(([k, v]) => (cur.attributes as Record)[k] !== v)); + if (Object.keys(changed).length) out.push({ method: 'PATCH', path: `/v1/betaAppLocalizations/${cur.id}`, note: locale, body: { data: { type: 'betaAppLocalizations', id: cur.id, attributes: changed } } }); + } + return out; +} + +export interface ReviewContactLike { firstName: string; lastName: string; phone: string; email: string } + +/** Beta App Review contact + notes (PATCH /v1/betaAppReviewDetails/{id}; the record exists for every app). */ +export function planBetaReviewDetail(detail: { id: string; attributes: Record } | null, contact: ReviewContactLike | null, notes?: string): Req[] { + if (!detail) return []; + if (notes && len(notes) > BETA_NOTES_LIMIT) throw new Error(`beta review notes: over ${BETA_NOTES_LIMIT} characters`); + const want: Record = { + ...(contact ? { contactFirstName: contact.firstName, contactLastName: contact.lastName, contactPhone: contact.phone, contactEmail: contact.email } : {}), + ...(notes ? { notes } : {}), + }; + const changed = Object.fromEntries(Object.entries(want).filter(([k, v]) => v && detail.attributes[k] !== v)); + return Object.keys(changed).length ? [{ method: 'PATCH', path: `/v1/betaAppReviewDetails/${detail.id}`, note: 'Beta App Review contact / notes', + body: { data: { type: 'betaAppReviewDetails', id: detail.id, attributes: changed } } }] : []; +} + +export interface ApiBuild { id: string; attributes: { version?: string; processingState?: string; expired?: boolean; usesNonExemptEncryption?: boolean | null; uploadedDate?: string }; marketing?: string } + +/** The one build with this number (CFBundleVersion), optionally of one marketing version. Never "the latest". */ +export function pickBuild(builds: ApiBuild[], number: string, marketing?: string): ApiBuild { + const hits = builds.filter(b => b.attributes.version === number && (!marketing || b.marketing === marketing)); + if (!hits.length) throw new Error(`no build ${number}${marketing ? ` of version ${marketing}` : ''} on App Store Connect (still processing? storebound apple status)`); + if (hits.length > 1) throw new Error(`build number ${number} exists for several versions (${hits.map(b => b.marketing ?? '?').join(', ')}): add --version x.y.z`); + return hits[0]!; +} + +/** Builds response with include=preReleaseVersion -> builds tagged with their marketing version. */ +export function buildsWithVersion(resp: { data?: ApiBuild[]; included?: { type: string; id: string; attributes?: { version?: string } }[] }): ApiBuild[] { + const pre = new Map((resp.included ?? []).filter(x => x.type === 'preReleaseVersions').map(x => [x.id, x.attributes?.version] as const)); + return (resp.data ?? []).map(b => ({ ...b, marketing: pre.get((b as unknown as { relationships?: { preReleaseVersion?: { data?: { id: string } } } }).relationships?.preReleaseVersion?.data?.id ?? '') })); +} + +/** Beta App Description per App Store locale from the config (a string = every locale). */ +export function betaDescriptions(t: TfConfig | undefined, langs: { id: string; apple?: string }[]): Record { + if (!t?.description) return {}; + const out: Record = {}; + for (const l of langs) { + if (!l.apple) continue; + const d = typeof t.description === 'string' ? t.description : t.description[l.id]; + if (d) out[l.apple] = d; + } + return out; +} diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index a555d21..f3f5c0c 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -129,12 +129,29 @@ export const TOOLS: ToolDef[] = [ description: 'Sync app preview videos per locale to the editable App Store version (checked locally first; MD5-idempotent, changed sets are replaced; poster frame time code). Not public until the version is submitted and released. Slow: prefer the terminal with a log.', props: { only, poster: { type: 'integer', minimum: 0, maximum: 29, description: 'Poster frame second (default shots.video.poster or 5)' } }, args: i => [...opt('only', i.only), ...opt('poster', i.poster)] }, + { name: 'apple_testflight_status', title: 'TestFlight status', command: ['apple', 'testflight', 'status'], write: false, network: true, + description: 'Read-only TestFlight overview: beta groups (internal / external, tester and build counts, public link), recent builds with processing, internal and external beta states.' }, + { name: 'apple_testflight_groups', title: 'Create TestFlight groups', command: ['apple', 'testflight', 'groups'], write: true, network: true, idempotent: true, + description: 'Create the beta groups of apple.testflight.groups that are missing on App Store Connect (matched by name; existing groups are never changed or deleted). Sends nothing to testers.' }, + { name: 'apple_testflight_what_to_test', title: 'TestFlight What to Test', command: ['apple', 'testflight', 'what-to-test'], write: true, network: true, idempotent: true, + description: 'Set "What to Test" (betaBuildLocalizations) of one build, by its exact number, per locale from the App Store listing file (### whatToTest, else ### whatsNew) or from text.', + props: { build: { type: 'string', pattern: '^[0-9][0-9.]*$', description: 'Exact build number (CFBundleVersion) you uploaded' }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$', description: 'Marketing version when the build number repeats' }, + locale: { type: 'string', description: 'Comma-separated App Store locales (default: every locale with text)' }, text: { type: 'string', description: 'Same text for the given locales instead of the listing file' } }, + required: ['build'], args: i => [...opt('build', i.build), ...opt('version', i.version), ...opt('locale', i.locale), ...opt('text', i.text)] }, + { name: 'apple_testflight_info', title: 'TestFlight test information', command: ['apple', 'testflight', 'info'], write: true, network: true, idempotent: true, + description: 'Beta App Description per locale (apple.testflight.description), feedback email, privacy and marketing URLs, and the Beta App Review contact (.storebound/credentials.json) and notes. Needed before external testing.' }, + { name: 'apple_testflight_distribute', title: 'Build to internal TestFlight groups', command: ['apple', 'testflight', 'distribute'], write: true, network: true, idempotent: true, + description: 'Add one build (exact number) to INTERNAL beta groups (your App Store Connect team; they get the TestFlight notification). External groups and Beta App Review submissions are owner-only terminal commands.', + props: { build: { type: 'string', pattern: '^[0-9][0-9.]*$', description: 'Exact build number you uploaded' }, groups: { type: 'string', description: 'Comma-separated internal group names' }, + version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' } }, + required: ['build', 'groups'], args: i => [...opt('build', i.build), ...opt('group', i.groups), ...opt('version', i.version), '--internal-only'] }, { name: 'icons', title: 'Generate icons', command: ['icons'], write: true, network: false, idempotent: true, description: 'Write every store / launcher / web icon from the artwork in the config (local files, needs ffmpeg).' }, ]; /** CLI flags / commands that must never be reachable through MCP. Tests assert none of the tools can produce them. */ -export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete']; +export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete', + '--submit-review', '--remove', '--invite', 'testers']; export function inputSchema(t: ToolDef): Record { const props: Record = { ...(t.props ?? {}) }; diff --git a/skills/appstore-first-release/SKILL.md b/skills/appstore-first-release/SKILL.md index 8d410ed..4e9a174 100644 --- a/skills/appstore-first-release/SKILL.md +++ b/skills/appstore-first-release/SKILL.md @@ -35,8 +35,9 @@ of a first version is the owner's click. Shared agent rules: `docs/agents-core.m automatic. `MARKETING_VERSION` / `CURRENT_PROJECT_VERSION` overrides beat the project values. Take the build number from `storebound apple next-build` right before archiving and **note it**: every later step selects that exact build, never "the latest". Processing takes 5-30 min (`storebound apple status` shows VALID). -6. **UI · TestFlight.** Create an internal group with "access to all builds" (hasAccessToAllBuilds) once: every new - build reaches the testers automatically. Sandbox testers: Users and Access > Sandbox. +6. **API · TestFlight.** Put an internal group with `allBuilds: true` in `apple.testflight.groups` and run + `storebound apple testflight groups`: every new build reaches the team automatically. External testers, What to + Test, Test Information and Beta App Review: the testflight skill. Sandbox testers stay UI: Users and Access > Sandbox. 7. **API · Version + text.** Fill `store/appstore.md`, then `storebound apple listing --version 1.0.0 --build 3` (version, copyright, MANUAL release, the build with exactly that number, name / subtitle / privacy URL, description / keywords / promo / URLs). Then `storebound apple release --phased on`: manual release + phased diff --git a/skills/store-preflight/SKILL.md b/skills/store-preflight/SKILL.md index 70d2073..160550e 100644 --- a/skills/store-preflight/SKILL.md +++ b/skills/store-preflight/SKILL.md @@ -39,4 +39,5 @@ Each line: number, level (`BLOCKER`, `warn`, `ok`), store, message, and a `fix:` ## What validate cannot see (UI-only, check by hand) App Privacy labels published, Play App content declarations (ads, target audience, content rating, advertising ID), -agreements / tax / banking, TestFlight groups, countries for production on Play. Tell the owner which are still open. +agreements / tax / banking, countries for production on Play. (TestFlight groups and testers: `storebound apple +testflight status`.) Tell the owner which are still open. diff --git a/skills/testflight/SKILL.md b/skills/testflight/SKILL.md new file mode 100644 index 0000000..6dc64fe --- /dev/null +++ b/skills/testflight/SKILL.md @@ -0,0 +1,79 @@ +--- +name: testflight +description: Run TestFlight for a mobile game through the App Store Connect API - beta groups (internal / external, public links), testers from a CSV that never enters git, adding a build by its exact number to groups, "What to Test" per locale from the release notes, Test Information, and the Beta App Review submission the owner confirms. Use when the user wants testers on a build, sets up beta groups, writes What to Test, or asks why external testers do not see a build. +--- + +# TestFlight + +CLI: `storebound apple testflight ` (or `bunx storebound` +in a project that has it). Every write has `--dry`; run it first and show the plan. API references are cited at the top +of `cli/lib/testflight.ts` (developer.apple.com/documentation/appstoreconnectapi: beta groups, beta testers, beta build +localizations, beta app localizations, beta app review submissions). + +## Prerequisites +- The build is uploaded and processed (`storebound apple status`, `VALID`), with export compliance answered + (`storebound apple encryption --build N`, export-compliance skill). A build missing it shows + `MISSING_EXPORT_COMPLIANCE` and nobody can test it. +- API key role Admin or App Manager. + +## 1. Groups (config, no emails) +```ts +apple: { + testflight: { + groups: [ + { name: 'Team', internal: true, allBuilds: true }, // App Store Connect users of your team, no review + { name: 'Friends' }, // external, by email, Beta App Review first + { name: 'Public', publicLink: true, publicLinkLimit: 500 }, + ], + description: { en: 'Match tiles, clear 60 levels.', tr: '...' }, // Beta App Description per language id + reviewNotes: 'No login needed. IAPs are sandbox purchases.', + }, +}, +``` +`storebound apple testflight groups --dry`, then without `--dry`. Groups are matched by name; storebound never renames, +changes or deletes a group. + +## 2. Testers (CSV in .storebound/, never in git) +- Columns: `email,first_name,last_name,groups` (groups separated by `;`). Default path `.storebound/testers.csv` + (gitignored); the config refuses a path outside `.storebound/`. Never paste tester emails into chat, docs, issues or + commits; storebound masks them in every log line (`j***@example.com`). +- `storebound apple testflight testers --dry` shows: new testers, testers added to more groups, (with `--remove`) + testers who leave a managed group. The real run **asks first**: Apple emails each new tester an invitation once the + group has a build. `--invite` (re)sends invitations to testers still `NOT_INVITED` / `INVITED` (asks again). +- Internal groups only take App Store Connect users (Users and Access); add people there first. +- Testers are an owner action: not an MCP tool. An agent prepares the CSV format and the dry run, the owner runs it. + +## 3. What to Test +- `storebound whats-new` drafts release notes into `store/appstore.md` (`### whatsNew` per locale). For testers you can + add a `### whatToTest` block per locale: it wins over `whatsNew` for TestFlight. +- `storebound apple testflight what-to-test --build N --dry`, then for real. `--text "..." --locale en-US` sets one + text instead. Pick the build by the exact number you uploaded, never "the latest"; `--version x.y.z` when the same + build number exists for two versions. +- Write it for testers: what changed, what to try, known issues. Short; it is read on a phone. Apple documents no + maximum; storebound stops at 4000 characters (assumption, see the README's unverified list). + +## 4. Test Information (needed for external testing) +`storebound apple testflight info --dry`: Beta App Description per locale (`apple.testflight.description`), feedback +email (`app.contactEmail`), privacy policy and marketing URL, and the Beta App Review contact (from +`.storebound/credentials.json` `reviewContact`) plus notes (4000 characters max). Apple requires a description on every +beta app localization before a Beta App Review submission, and fields cannot be cleared once set. + +## 5. Distribute +- Internal: `storebound apple testflight distribute --build N --group Team --dry`, then for real (MCP: + `apple_testflight_distribute`, internal groups only). Groups with `allBuilds: true` get every build automatically. +- External: same command with an external group; it asks first. External testers only get the build after **Beta App + Review**: add `--submit-review` (asks again) or submit in App Store Connect. The first build of a version is + reviewed; later builds of the same version are often approved quickly. Beta review states: `WAITING_FOR_REVIEW`, + `IN_REVIEW`, `APPROVED`, `REJECTED` (`storebound apple testflight status` shows internal / external build states). +- The Beta App Review submission is public-facing and the owner's call: never through MCP; an agent explains and the + owner confirms in the terminal. + +## Gotchas +- Builds expire after 90 days in TestFlight; upload a new one (`storebound apple next-build`). +- Up to 100 internal testers and 10,000 external testers per app (TestFlight overview in App Store Connect Help: + https://developer.apple.com/help/app-store-connect/test-a-beta-version/testflight-overview). +- A public link (`publicLink: true`) lets anyone with it join, up to `publicLinkLimit` (1-10000). Share it only where + the owner wants; it still needs the approved build. +- External testers of a game with IAP buy with sandbox accounts automatically (no charge); say so in What to Test. +- Rejected beta review: read the message in App Store Connect > TestFlight, fix, upload a new build, submit again + (review-rejections skill for the tone of the reply). diff --git a/templates/storebound.config.ts b/templates/storebound.config.ts index 0b3ddec..acd92b6 100644 --- a/templates/storebound.config.ts +++ b/templates/storebound.config.ts @@ -41,6 +41,14 @@ const config: ShipConfig = { // usesNonExemptEncryption: false, // ipad: true, // the app runs on iPad: 13" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded // screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale (default; + APP_IPAD_PRO_3GEN_129 with ipad) + // TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only. + testflight: { + groups: [ + { name: 'Team', internal: true, allBuilds: true }, + { name: 'Friends' }, + ], + description: { en: 'Example Game beta: try the new levels and tell us what feels too hard.' }, + }, info: { categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' }, ageRating: { advertising: true }, // everything else NONE / false diff --git a/templates/testers.csv b/templates/testers.csv new file mode 100644 index 0000000..987ced9 --- /dev/null +++ b/templates/testers.csv @@ -0,0 +1 @@ +email,first_name,last_name,groups diff --git a/tests/testflight.test.ts b/tests/testflight.test.ts new file mode 100644 index 0000000..da41337 --- /dev/null +++ b/tests/testflight.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, test } from 'bun:test'; +import { describeReq } from '../cli/apple/jsonapi'; +import { parseCsv, parseCsvRecords, toCsv } from '../cli/lib/csv'; +import { validateConfig } from '../cli/lib/config'; +import { + betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail, parseTesters, pickBuild, + planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, validateTestflight, whatToTestFromListing, +} from '../cli/lib/testflight'; +import { TOOLS, toArgv, validateInput } from '../cli/mcp-tools'; + +const G: Group[] = [ + { id: 'g-int', name: 'Team', internal: true, hasAccessToAllBuilds: false }, + { id: 'g-all', name: 'Everyone inside', internal: true, hasAccessToAllBuilds: true }, + { id: 'g-ext', name: 'Friends', internal: false }, +]; + +describe('csv', () => { + test('quotes, doubled quotes, CRLF, BOM, empty lines', () => { + expect(parseCsv('a,b\r\n"x, y","say ""hi"""\r\n\r\nz,\n')).toEqual([['a', 'b'], ['x, y', 'say "hi"'], ['z', '']]); + expect(parseCsv('a\tb\n1\t2', '\t')).toEqual([['a', 'b'], ['1', '2']]); + expect(parseCsvRecords('Email, First Name\nA@example.com ,Jo')).toEqual([{ email: 'A@example.com', first_name: 'Jo' }]); + expect(toCsv([['a', 'b,c'], [1, 'say "x"']])).toBe('a,"b,c"\n1,"say ""x"""\n'); + }); +}); + +describe('testflight config', () => { + test('groups and the tester CSV location', () => { + expect(validateTestflight({ groups: [{ name: 'Team', internal: true, allBuilds: true }, { name: 'Friends', publicLink: true, publicLinkLimit: 100 }], testers: '.storebound/testers.csv' })).toEqual([]); + const e = validateTestflight({ groups: [{ name: 'A', internal: true, publicLink: true }, { name: 'A', allBuilds: true }, { name: 'B', publicLinkLimit: 0 }], testers: 'store/testers.csv' }); + expect(e.join('\n')).toContain('public links are for external groups only'); + expect(e.join('\n')).toContain('duplicate "A"'); + expect(e.join('\n')).toContain('allBuilds: internal groups only'); + expect(e.join('\n')).toContain('publicLinkLimit: 1-10000'); + expect(e.join('\n')).toContain('keep the tester CSV in .storebound/'); + 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', apple: 'en-US' }] }; + expect(validateConfig({ ...base, apple: { bundleId: 'com.example.game', testflight: { testers: 'testers.csv' } } }).join()).toContain('.storebound/'); + }); +}); + +describe('testflight groups', () => { + test('creates only missing groups, with the right attributes', () => { + const p = planGroups('app1', G, [{ name: 'Team', internal: true }, { name: 'QA', internal: true, allBuilds: true }, { name: 'Public', publicLink: true, publicLinkLimit: 500, feedback: false }]); + expect(p.existing).toEqual(['Team']); + expect(p.create).toHaveLength(2); + expect(p.create[0]!.body).toEqual({ data: { type: 'betaGroups', attributes: { name: 'QA', isInternalGroup: true, hasAccessToAllBuilds: true, feedbackEnabled: true }, relationships: { app: { data: { type: 'apps', id: 'app1' } } } } }); + expect((p.create[1]!.body as { data: { attributes: unknown } }).data.attributes).toEqual({ name: 'Public', publicLinkEnabled: true, publicLinkLimitEnabled: true, publicLinkLimit: 500, feedbackEnabled: false }); + expect(groupFromApi({ id: 'x', attributes: { name: 'N', isInternalGroup: true, hasAccessToAllBuilds: true } })).toMatchObject({ id: 'x', name: 'N', internal: true, hasAccessToAllBuilds: true }); + }); +}); + +describe('testflight testers', () => { + const csv = 'email,first_name,last_name,groups\nJane@Example.com,Jane,Doe,Friends\nbob@example.com,,,Friends;Team\nnew@example.com,New,,\n'; + test('parse: lower-cases emails, default group, rejects bad rows without leaking emails', () => { + const t = parseTesters(csv, 'Friends'); + expect(t.map(x => [x.email, x.groups])).toEqual([['jane@example.com', ['Friends']], ['bob@example.com', ['Friends', 'Team']], ['new@example.com', ['Friends']]]); + expect(() => parseTesters('email\nnot-an-email\n')).toThrow('is not an email'); + try { parseTesters('email\nsecret.person@example.com\nsecret.person@example.com\n'); } catch (e) { expect(String(e)).toContain('s***@example.com listed twice'); expect(String(e)).not.toContain('secret.person'); } + expect(maskEmail('jane.doe@example.com')).toBe('j***@example.com'); + }); + test('plan: create new, add existing to more groups, remove only with --remove and only from managed groups', () => { + const want = parseTesters(csv, 'Friends'); + const existing = new Map([ + ['jane@example.com', { id: 't-jane', groupIds: ['g-ext'] }], + ['bob@example.com', { id: 't-bob', groupIds: ['g-ext'] }], + ['old@example.com', { id: 't-old', groupIds: ['g-ext', 'g-all'] }], + ]); + const p = planTesters(G, existing, want); + expect(p.create).toHaveLength(1); + expect(p.create[0]!.body).toEqual({ data: { type: 'betaTesters', attributes: { email: 'new@example.com', firstName: 'New' }, relationships: { betaGroups: { data: [{ type: 'betaGroups', id: 'g-ext' }] } } } }); + expect(p.add).toEqual([{ method: 'POST', path: '/v1/betaGroups/g-int/relationships/betaTesters', body: { data: [{ type: 'betaTesters', id: 't-bob' }] }, note: '1 existing tester(s) -> "Team"' }]); + expect(p.remove).toEqual([]); + const r = planTesters(G, existing, want, { remove: true }); + expect(r.remove).toEqual([{ method: 'DELETE', path: '/v1/betaGroups/g-ext/relationships/betaTesters', body: { data: [{ type: 'betaTesters', id: 't-old' }] }, note: '1 tester(s) leave "Friends"' }]); + expect(r.summary).toEqual(['1 new tester(s)', '1 added to groups', '1 removed from groups']); + expect(planTesters(G, existing, want, { only: ['Nope'] }).unknownGroups).toEqual(['Nope']); + expect(describeReq(p.create[0]!)).not.toContain('new@example.com'); + expect(describeReq(p.create[0]!)).toContain('n***@example.com'); + }); + test('invitation request', () => { + expect(inviteReq('app1', 't1', 'x').body).toEqual({ data: { type: 'betaTesterInvitations', relationships: { app: { data: { type: 'apps', id: 'app1' } }, betaTester: { data: { type: 'betaTesters', id: 't1' } } } } }); + }); +}); + +describe('testflight builds', () => { + const resp = { + data: [ + { id: 'b1', attributes: { version: '42', processingState: 'VALID' }, relationships: { preReleaseVersion: { data: { id: 'p1' } } } }, + { id: 'b2', attributes: { version: '42', processingState: 'VALID' }, relationships: { preReleaseVersion: { data: { id: 'p2' } } } }, + { id: 'b3', attributes: { version: '43', processingState: 'PROCESSING' }, relationships: { preReleaseVersion: { data: { id: 'p2' } } } }, + ], + included: [{ type: 'preReleaseVersions', id: 'p1', attributes: { version: '1.0.0' } }, { type: 'preReleaseVersions', id: 'p2', attributes: { version: '1.1.0' } }], + }; + test('pick by explicit number, ambiguity needs --version', () => { + const builds = buildsWithVersion(resp); + expect(pickBuild(builds, '43').id).toBe('b3'); + expect(pickBuild(builds, '42', '1.1.0').id).toBe('b2'); + expect(() => pickBuild(builds, '42')).toThrow('add --version'); + expect(() => pickBuild(builds, '99')).toThrow('no build 99'); + }); + test('readiness', () => { + expect(betaReadiness({ processingState: 'VALID', usesNonExemptEncryption: false }, { internalBuildState: 'READY_FOR_BETA_TESTING' })).toEqual([]); + expect(betaReadiness({ processingState: 'PROCESSING' }, null)[0]).toContain('PROCESSING'); + expect(betaReadiness({ processingState: 'VALID', expired: true }, null)[0]).toContain('expired'); + expect(betaReadiness({ processingState: 'VALID', usesNonExemptEncryption: null }, { internalBuildState: 'MISSING_EXPORT_COMPLIANCE' })[0]).toContain('export compliance'); + }); + test('distribute skips groups that have it and internal all-builds groups', () => { + expect(planDistribute('b1', G, ['g-ext']).map(r => r.path)).toEqual(['/v1/betaGroups/g-int/relationships/builds']); + expect(planDistribute('b1', G, [])[0]!.body).toEqual({ data: [{ type: 'builds', id: 'b1' }] }); + expect(betaReviewReq('b1').body).toEqual({ data: { type: 'betaAppReviewSubmissions', relationships: { build: { data: { type: 'builds', id: 'b1' } } } } }); + }); +}); + +describe('testflight what to test and info', () => { + const md = '# App Store\n\n## en-US · English\n\n### whatsNew\n```\nNew: desert world.\n```\n\n### whatToTest\n```\nPlay level 3 twice.\n```\n\n## tr · Türkçe\n\n### whatsNew\n```\nYeni: çöl dünyası.\n```\n\n## Notes\n\ntext\n'; + test('listing -> per locale text, whatToTest wins over whatsNew', () => { + expect(whatToTestFromListing(md)).toEqual({ 'en-US': 'Play level 3 twice.', tr: 'Yeni: çöl dünyası.' }); + }); + test('create missing, patch changed, leave equal, refuse over the limit', () => { + const reqs = planWhatToTest('b1', [{ id: 'l1', locale: 'en-US', whatsNew: 'old' }, { id: 'l2', locale: 'de-DE', whatsNew: 'x' }, { id: 'l3', locale: 'ja', whatsNew: 'same' }], { 'en-US': 'new', tr: 'yeni', ja: 'same' }); + expect(reqs.map(r => `${r.method} ${r.path}`)).toEqual(['PATCH /v1/betaBuildLocalizations/l1', 'POST /v1/betaBuildLocalizations']); + expect(reqs[1]!.body).toEqual({ data: { type: 'betaBuildLocalizations', attributes: { locale: 'tr', whatsNew: 'yeni' }, relationships: { build: { data: { type: 'builds', id: 'b1' } } } } }); + expect(() => planWhatToTest('b1', [], { en: 'x'.repeat(4001) })).toThrow('over 4000'); + }); + test('test information and beta review details', () => { + const want = { 'en-US': { description: 'A puzzle game.', feedbackEmail: 'support@example.com', privacyPolicyUrl: 'https://example.com/p' }, tr: { description: 'Bulmaca.' } }; + const r = planBetaInfo('app1', [{ id: 'bl1', locale: 'en-US', attributes: { description: 'A puzzle game.', feedbackEmail: 'old@example.com' } }], want); + expect(r.map(x => `${x.method} ${x.path}`)).toEqual(['PATCH /v1/betaAppLocalizations/bl1', 'POST /v1/betaAppLocalizations']); + expect((r[0]!.body as { data: { attributes: unknown } }).data.attributes).toEqual({ feedbackEmail: 'support@example.com', privacyPolicyUrl: 'https://example.com/p' }); + expect(betaDescriptions({ description: { en: 'Hi' } }, [{ id: 'en', apple: 'en-US' }, { id: 'tr', apple: 'tr' }])).toEqual({ 'en-US': 'Hi' }); + expect(betaDescriptions({ description: 'All' }, [{ id: 'en', apple: 'en-US' }, { id: 'x' }])).toEqual({ 'en-US': 'All' }); + const d = planBetaReviewDetail({ id: 'd1', attributes: { contactEmail: 'a@example.com', notes: null } }, { firstName: 'A', lastName: 'B', phone: '+1 555 0100', email: 'a@example.com' }, 'Tap Play.'); + expect((d[0]!.body as { data: { attributes: unknown } }).data.attributes).toEqual({ contactFirstName: 'A', contactLastName: 'B', contactPhone: '+1 555 0100', notes: 'Tap Play.' }); + expect(describeReq(d[0]!)).not.toContain('555'); + expect(planBetaReviewDetail(null, null, 'x')).toEqual([]); + expect(() => planBetaReviewDetail({ id: 'd', attributes: {} }, null, 'x'.repeat(4001))).toThrow('4000'); + }); +}); + +describe('testflight mcp tools', () => { + const tool = (n: string) => TOOLS.find(t => t.name === n)!; + test('status read-only, writes dry by default, distribute is internal-only, testers / review not exposed', () => { + expect(tool('apple_testflight_status')).toMatchObject({ write: false, network: true }); + expect(toArgv(tool('apple_testflight_groups')).argv).toEqual(['apple', 'testflight', 'groups', '--dry']); + expect(toArgv(tool('apple_testflight_what_to_test'), { build: '42', locale: 'en-US,tr' }).argv).toEqual(['apple', 'testflight', 'what-to-test', '--build', '42', '--locale', 'en-US,tr', '--dry']); + expect(toArgv(tool('apple_testflight_distribute'), { build: '42', groups: 'Team', dry_run: false }).argv).toEqual(['apple', 'testflight', 'distribute', '--build', '42', '--group', 'Team', '--internal-only']); + expect(validateInput(tool('apple_testflight_distribute'), { build: 'latest', groups: 'Team' })[0]).toContain('does not match'); + expect(TOOLS.some(t => t.command.includes('testers'))).toBe(false); + for (const t of TOOLS) expect(toArgv(t, { build: '1', groups: 'x', dry_run: false }).argv).not.toContain('--submit-review'); + }); +}); From 56e107dbbec6275ba956a5c263c1c06b7429a6f4 Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 10 Oct 2026 23:11:56 +0800 Subject: [PATCH 2/8] 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. --- .cursor/rules/storebound.mdc | 1 + .github/copilot-instructions.md | 1 + AGENTS.md | 1 + GEMINI.md | 1 + cli/apple/asc.ts | 13 +- cli/health.ts | 102 ++++++++++++ cli/index.ts | 1 + cli/lib/google-auth.ts | 8 +- cli/lib/health.ts | 253 +++++++++++++++++++++++++++++ cli/mcp-tools.ts | 8 + cli/play/google.ts | 31 ++++ cli/validate.ts | 13 +- skills/release-management/SKILL.md | 3 +- skills/store-health/SKILL.md | 48 ++++++ skills/store-preflight/SKILL.md | 5 + tests/health.test.ts | 109 +++++++++++++ 16 files changed, 592 insertions(+), 6 deletions(-) create mode 100644 cli/health.ts create mode 100644 cli/lib/health.ts create mode 100644 cli/play/google.ts create mode 100644 skills/store-health/SKILL.md create mode 100644 tests/health.test.ts diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index fb0757a..2d5df59 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/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-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 diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 9782c12..e8d34f1 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 | | `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-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 | diff --git a/AGENTS.md b/AGENTS.md index cf7e1b3..d0e5df4 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/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-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 diff --git a/GEMINI.md b/GEMINI.md index b082126..2060327 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 | | `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-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 | diff --git a/cli/apple/asc.ts b/cli/apple/asc.ts index 3ce3eba..11a0adf 100644 --- a/cli/apple/asc.ts +++ b/cli/apple/asc.ts @@ -46,6 +46,17 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri 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 { + 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. */ async function all(path: string): Promise { const out: J[] = []; @@ -95,5 +106,5 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri 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 }; } diff --git a/cli/health.ts b/cli/health.ts new file mode 100644 index 0000000..67631f1 --- /dev/null +++ b/cli/health.ts @@ -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 .md (+ .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 { + const g = googleClient(root, REPORTING_SCOPE); + const app = `${REPORTING_API}/apps/${encodeURIComponent(pkg)}`; + log('health', 'play: vitals freshness'); + const set = await g.json[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 { + 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(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 { + 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 { + 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; +} diff --git a/cli/index.ts b/cli/index.ts index 0318a97..4f5f2d2 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'], + '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 )'], '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'], diff --git a/cli/lib/google-auth.ts b/cli/lib/google-auth.ts index 9d8843e..106f798 100644 --- a/cli/lib/google-auth.ts +++ b/cli/lib/google-auth.ts @@ -2,6 +2,10 @@ import type { ServiceAccount } from './credentials'; 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'); 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). */ -export function tokenSource(sa: ServiceAccount): () => Promise { +export function tokenSource(sa: ServiceAccount, scope = PLAY_SCOPE): () => Promise { let token = ''; let until = 0; return async () => { 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', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, diff --git a/cli/lib/health.ts b/cli/lib/health.ts new file mode 100644 index 0000000..a5b618a --- /dev/null +++ b/cli/lib/health.ts @@ -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 { + 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 | 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; values: Record } + +interface ApiRow { + startTime?: Partial; + 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 { + const agg = new Map(); + 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, since: string): AppleHealth['betaCrashes'] { + const n = new Map(); + 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 = { 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'); +} diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index f3f5c0c..54699cc 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -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).', props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } }, 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/.md (plus .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, 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/cli/play/google.ts b/cli/play/google.ts new file mode 100644 index 0000000..561b3fb --- /dev/null +++ b/cli/play/google.ts @@ -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 { + 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(method: string, url: string, body?: unknown): Promise { + 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* { + 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()); + }, + }; +} diff --git a/cli/validate.ts b/cli/validate.ts index 6365f82..9ffe816 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -1,17 +1,21 @@ // 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. // 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 // `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. +// 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 { requiredDisplayTypes } from './apple/screenshots'; import { playCodes } from './lib/config'; import type { Ctx } from './lib/ctx'; import { checkUrl } from './lib/http'; +import { collectHealth } from './health'; +import { healthFindings } from './lib/health'; 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 { playClient } from './play/client'; import { listOneTimeProducts } from './play/products'; @@ -118,6 +122,11 @@ export async function run(ctx: Ctx): Promise { 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)); } } 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; if (a.has('json')) console.log(JSON.stringify({ blockers, findings }, null, 2)); else { diff --git a/skills/release-management/SKILL.md b/skills/release-management/SKILL.md index 28bd515..aaed7df 100644 --- a/skills/release-management/SKILL.md +++ b/skills/release-management/SKILL.md @@ -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 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. -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. ## Review wait diff --git a/skills/store-health/SKILL.md b/skills/store-health/SKILL.md new file mode 100644 index 0000000..a8f3e01 --- /dev/null +++ b/skills/store-health/SKILL.md @@ -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/.md` and `.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. diff --git a/skills/store-preflight/SKILL.md b/skills/store-preflight/SKILL.md index 160550e..b45b562 100644 --- a/skills/store-preflight/SKILL.md +++ b/skills/store-preflight/SKILL.md @@ -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 | | no release on any track | nothing uploaded | `play release ` | | 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) App Privacy labels published, Play App content declarations (ads, target audience, content rating, advertising ID), diff --git a/tests/health.test.ts b/tests/health.test.ts new file mode 100644 index 0000000..3a1c45f --- /dev/null +++ b/tests/health.test.ts @@ -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, dims: Record = {}) => ({ + 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; 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']); + }); +}); From c99febc45bd4a09f4383fda80402b16833f76c09 Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 10 Oct 2026 23:14:48 +0800 Subject: [PATCH 3/8] Review replies: storebound reviews list | draft | send, review-replies skill App Store customerReviews / customerReviewResponses and Google Play reviews.list / reviews.reply. draft writes one Markdown file per unanswered review to .storebound/replies (front matter approved: false, never overwritten); send only sends approved, unsent drafts that pass the checks (Play 350 characters, no incentives or rating requests, personal data / link / tone warnings) after a confirmation, and marks them sent. MCP: reviews_list, reviews_draft; send is never exposed. --- .cursor/rules/storebound.mdc | 1 + .github/copilot-instructions.md | 1 + AGENTS.md | 1 + GEMINI.md | 1 + cli/index.ts | 1 + cli/lib/frontmatter.ts | 34 +++++++ cli/lib/reviews.ts | 155 ++++++++++++++++++++++++++++++++ cli/mcp-tools.ts | 12 ++- cli/reviews.ts | 143 +++++++++++++++++++++++++++++ skills/review-replies/SKILL.md | 54 +++++++++++ tests/reviews.test.ts | 106 ++++++++++++++++++++++ 11 files changed, 508 insertions(+), 1 deletion(-) create mode 100644 cli/lib/frontmatter.ts create mode 100644 cli/lib/reviews.ts create mode 100644 cli/reviews.ts create mode 100644 skills/review-replies/SKILL.md create mode 100644 tests/reviews.test.ts diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index 2d5df59..a13e44b 100644 --- a/.cursor/rules/storebound.mdc +++ b/.cursor/rules/storebound.mdc @@ -45,6 +45,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile games - `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-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 e8d34f1..b4684b9 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -47,6 +47,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile games | | `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-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 d0e5df4..61e1aa5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,6 +45,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile games - `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-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 2060327..eca9ab6 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -46,6 +46,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile games | | `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-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/index.ts b/cli/index.ts index 4f5f2d2..50ff97c 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -18,6 +18,7 @@ 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'], 'health': [() => import('./health'), 'crash / ANR vitals (Play) and diagnostics (App Store), read-only; --weekly writes a markdown report; exit 1 over a threshold'], + 'reviews': [() => import('./reviews'), 'list | draft (local reply drafts in .storebound/replies) | send (approved drafts only, asks first)'], 'whats-new': [() => import('./whats-new'), 'draft player-facing release notes from git log into the listing files (--since )'], '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'], diff --git a/cli/lib/frontmatter.ts b/cli/lib/frontmatter.ts new file mode 100644 index 0000000..f9e0f22 --- /dev/null +++ b/cli/lib/frontmatter.ts @@ -0,0 +1,34 @@ +// Minimal front matter for the local Markdown drafts storebound writes (review replies): "---", one `key: value` per +// line (strings, numbers, true / false, null; strings JSON-quoted when needed), "---", then the body. Pure. + +export type FmValue = string | number | boolean | null; + +export function parseFrontMatter(text: string): { data: Record; body: string } { + const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text); + if (!m) return { data: {}, body: text }; + const data: Record = {}; + for (const line of m[1]!.split(/\r?\n/)) { + const kv = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line); + if (!kv) continue; + data[kv[1]!] = scalar(kv[2]!.trim()); + } + return { data, body: text.slice(m[0].length) }; +} + +function scalar(v: string): FmValue { + if (v === 'true') return true; + if (v === 'false') return false; + if (v === 'null' || v === '~' || v === '') return null; + if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v); + if (v.startsWith('"')) { try { return JSON.parse(v) as string; } catch { return v; } } + if (v.startsWith("'") && v.endsWith("'")) return v.slice(1, -1).replace(/''/g, "'"); + return v; +} + +const plain = (s: string) => /^[\w./@+-][\w ./@:+-]*$/.test(s) && !/^(true|false|null|~|-?\d+(\.\d+)?)$/.test(s) && !/ $/.test(s); + +export function stringifyFrontMatter(data: Record, body: string): string { + const lines = Object.entries(data).filter(([, v]) => v !== undefined) + .map(([k, v]) => `${k}: ${v === null ? 'null' : typeof v === 'string' ? (plain(v) ? v : JSON.stringify(v)) : String(v)}`); + return `---\n${lines.join('\n')}\n---\n${body.startsWith('\n') ? body : '\n' + body}`; +} diff --git a/cli/lib/reviews.ts b/cli/lib/reviews.ts new file mode 100644 index 0000000..4fa7411 --- /dev/null +++ b/cli/lib/reviews.ts @@ -0,0 +1,155 @@ +// Store review replies as pure parts: normalising both stores' reviews, the local draft files the owner / agent edit +// (.storebound/replies/-.md, front matter + the review + "## Reply"), and the checks a reply must pass +// before `storebound reviews send` sends it (only drafts with `approved: true`, after a confirmation). +// Sources (checked October 2026): +// App Store: GET /v1/apps/{id}/customerReviews, POST /v1/customerReviewResponses (one response per review; a new POST +// replaces it; it shows after up to 24 hours) https://developer.apple.com/documentation/appstoreconnectapi/customer-review-responses +// Guidance: https://developer.apple.com/app-store/responding-to-reviews/ (no personal info, marketing or spam) +// Length: Apple documents no maximum; 5970 characters is the limit App Store Connect is commonly reported to +// enforce (NOT VERIFIED), so storebound warns above it instead of blocking. +// Google Play: reviews.list returns reviews created or edited in the last week only; reviews.reply {replyText}, +// at most 350 characters (HTML tags stripped, not counted) https://developers.google.com/android-publisher/reply-to-reviews +import { len } from './copy'; +import { type FmValue, parseFrontMatter, stringifyFrontMatter } from './frontmatter'; + +export type ReviewStore = 'apple' | 'play'; +export const REPLY_LIMITS: Record = { play: 350, apple: 5970 }; + +export interface Review { + store: ReviewStore; + id: string; + rating: number; + title?: string; + body: string; + author?: string; + /** Apple: territory (alpha-3); Play: reviewer language. */ + where?: string; + date: string; + appVersion?: string; + reply?: { text: string; date?: string; state?: string }; +} + +interface AppleReviewsResp { + data?: { id: string; attributes: { rating?: number; title?: string; body?: string; reviewerNickname?: string; createdDate?: string; territory?: string }; relationships?: { response?: { data?: { id: string } | null } } }[]; + included?: { type: string; id: string; attributes?: { responseBody?: string; lastModifiedDate?: string; state?: string } }[]; +} + +export function parseAppleReviews(resp: AppleReviewsResp): Review[] { + const responses = new Map((resp.included ?? []).filter(x => x.type === 'customerReviewResponses').map(x => [x.id, x.attributes ?? {}] as const)); + return (resp.data ?? []).map(r => { + const resp1 = responses.get(r.relationships?.response?.data?.id ?? ''); + return { store: 'apple' as const, id: r.id, rating: r.attributes.rating ?? 0, title: r.attributes.title || undefined, body: r.attributes.body ?? '', + author: r.attributes.reviewerNickname, where: r.attributes.territory, date: r.attributes.createdDate ? new Date(r.attributes.createdDate).toISOString() : '', + ...(resp1?.responseBody ? { reply: { text: resp1.responseBody, date: resp1.lastModifiedDate, state: resp1.state } } : {}) }; + }); +} + +interface PlayReviewsResp { + reviews?: { reviewId: string; authorName?: string; comments?: { userComment?: { text?: string; lastModified?: { seconds?: string }; starRating?: number; reviewerLanguage?: string; appVersionName?: string }; + developerComment?: { text?: string; lastModified?: { seconds?: string } } }[] }[]; +} + +const isoFromSeconds = (s?: string) => (s ? new Date(Number(s) * 1000).toISOString() : ''); + +export function parsePlayReviews(resp: PlayReviewsResp): Review[] { + return (resp.reviews ?? []).map(r => { + const u = r.comments?.find(c => c.userComment)?.userComment ?? {}; + const d = r.comments?.find(c => c.developerComment)?.developerComment; + // A review with a separate title comes as "title\tbody". + const [title, body] = (u.text ?? '').includes('\t') ? (u.text ?? '').split('\t', 2) as [string, string] : [undefined, u.text ?? '']; + return { store: 'play' as const, id: r.reviewId, rating: u.starRating ?? 0, title: title?.trim() || undefined, body: body.trim(), author: r.authorName, + where: u.reviewerLanguage, date: isoFromSeconds(u.lastModified?.seconds), appVersion: u.appVersionName, + ...(d?.text ? { reply: { text: d.text, date: isoFromSeconds(d.lastModified?.seconds) } } : {}) }; + }); +} + +/** Reviews newer than `sinceIso`, optional filters, newest first. */ +export function filterReviews(rs: Review[], o: { since?: string; unanswered?: boolean; ratings?: number[] } = {}): Review[] { + return rs.filter(r => (!o.since || r.date >= o.since) && (!o.unanswered || !r.reply) && (!o.ratings?.length || o.ratings.includes(r.rating))) + .sort((a, b) => b.date.localeCompare(a.date)); +} + +/** File name of a draft: -.md with unsafe characters replaced. */ +export const draftName = (r: Pick): string => `${r.store}-${r.id.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120)}.md`; + +export const REPLY_PLACEHOLDER = ''; + +/** A new draft: front matter (approved: false), the review as a quote, an empty "## Reply" section. */ +export function draftMarkdown(r: Review): string { + const quote = (t: string) => t.split('\n').map(l => `> ${l}`).join('\n'); + const body = [ + `# ${'★'.repeat(Math.max(0, Math.min(5, r.rating)))}${'☆'.repeat(Math.max(0, 5 - r.rating))} ${r.title ?? ''}`.trimEnd(), '', + quote(r.body || '(no text)'), '', + `${r.where ? `${r.where} · ` : ''}${r.date.slice(0, 10)}${r.appVersion ? ` · version ${r.appVersion}` : ''}`, '', + ...(r.reply ? ['## Current reply', '', quote(r.reply.text), ''] : []), + '## Reply', '', REPLY_PLACEHOLDER, '', '', + ].join('\n'); + const meta: Record = { store: r.store, review_id: r.id, rating: r.rating, where: r.where ?? null, date: r.date, limit: REPLY_LIMITS[r.store], approved: false, sent: null }; + return stringifyFrontMatter(meta, body); +} + +export interface Draft { file: string; store: ReviewStore; reviewId: string; approved: boolean; sent: string | null; reply: string; meta: Record } + +/** A draft file -> its reply text (after "## Reply", HTML comments removed) and state. */ +export function parseDraft(file: string, text: string): Draft { + const { data, body } = parseFrontMatter(text); + const store = data.store; + if (store !== 'apple' && store !== 'play') throw new Error(`${file}: front matter "store" must be apple or play`); + if (!data.review_id) throw new Error(`${file}: front matter "review_id" missing`); + const at = body.search(/^## Reply\s*$/m); + const reply = at < 0 ? '' : body.slice(at).replace(/^## Reply\s*$/m, '').replace(//g, '').trim(); + return { file, store, reviewId: String(data.review_id), approved: data.approved === true, sent: typeof data.sent === 'string' ? data.sent : null, reply, meta: data }; +} + +/** Front matter `sent: ` (and approved kept) after a successful send. */ +export function markSent(text: string, iso: string): string { + const { data, body } = parseFrontMatter(text); + return stringifyFrontMatter({ ...data, sent: iso }, body); +} + +const INCENTIVE = [ + /\b(free|bonus|extra|gift|reward|compensat\w*)\b[^.!?\n]{0,40}\b(coins?|gems?|diamonds?|credits?|lives|items?|currency|refund)\b/i, + /\b(change|update|raise|edit|improve|revise)\s+(your\s+)?(rating|review|stars?|score)\b/i, + /\b(5|five)[ -]?stars?\b/i, + /\b(rate|review)\s+us\b/i, +]; + +export interface ReplyIssue { level: 'error' | 'warn'; msg: string } + +/** Problems with a reply before sending. Errors block `reviews send`; warnings are shown. */ +export function checkReply(reply: string, store: ReviewStore): ReplyIssue[] { + const e: ReplyIssue[] = []; + const text = store === 'play' ? reply.replace(/<[^>]*>/g, '') : reply; + if (!text.trim()) e.push({ level: 'error', msg: 'empty reply' }); + const n = len(text); + if (store === 'play' && n > REPLY_LIMITS.play) e.push({ level: 'error', msg: `${n} > ${REPLY_LIMITS.play} characters (Google Play limit)` }); + if (store === 'apple' && n > REPLY_LIMITS.apple) e.push({ level: 'warn', msg: `${n} characters: App Store Connect is reported to stop at ${REPLY_LIMITS.apple}` }); + if (INCENTIVE.some(re => re.test(text))) e.push({ level: 'error', msg: 'offers something for a rating or asks to change / give stars: not allowed (no incentives, no rating manipulation)' }); + if (/[^@\s]+@[^@\s]+\.[a-z]{2,}/i.test(text)) e.push({ level: 'warn', msg: 'contains an email address: only your public support address, never a player\'s' }); + if (/(\+?\d[\d\s().-]{7,}\d)/.test(text)) e.push({ level: 'warn', msg: 'contains a phone-like number: no personal data in public replies' }); + if (/https?:\/\//i.test(text)) e.push({ level: 'warn', msg: 'contains a link: support pages only, no marketing' }); + if (/[A-Z]{6,}/.test(text) || /!{3,}/.test(text)) e.push({ level: 'warn', msg: 'shouting (caps / !!!): keep it calm' }); + return e; +} + +/** Which drafts `send` would send, and why the others are skipped. */ +export function sendPlan(drafts: Draft[]): { send: Draft[]; skip: { file: string; why: string }[] } { + const send: Draft[] = []; + const skip: { file: string; why: string }[] = []; + for (const d of drafts) { + if (d.sent) { skip.push({ file: d.file, why: `already sent ${d.sent.slice(0, 10)}` }); continue; } + if (!d.approved) { skip.push({ file: d.file, why: 'not approved (set approved: true after reading it)' }); continue; } + const errors = checkReply(d.reply, d.store).filter(i => i.level === 'error'); + if (errors.length) { skip.push({ file: d.file, why: errors.map(i => i.msg).join('; ') }); continue; } + send.push(d); + } + return { send, skip }; +} + +/** The request that sends one reply. Apple: a POST replaces an earlier response; Play: :reply creates or updates. */ +export function replyRequest(d: Draft, packageName?: string): { method: 'POST'; url: string; body: unknown } { + if (d.store === 'apple') return { method: 'POST', url: '/v1/customerReviewResponses', body: { data: { type: 'customerReviewResponses', attributes: { responseBody: d.reply }, + relationships: { review: { data: { type: 'customerReviews', id: d.reviewId } } } } } }; + if (!packageName) throw new Error('play.packageName is not set'); + return { method: 'POST', url: `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageName}/reviews/${encodeURIComponent(d.reviewId)}:reply`, body: { replyText: d.reply } }; +} diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 54699cc..6b362fa 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -50,6 +50,16 @@ export const TOOLS: ToolDef[] = [ description: 'Weekly health summary as Markdown in .storebound/health/.md (plus .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: 'reviews_list', title: 'Store reviews', command: ['reviews', 'list'], write: false, network: true, + description: 'Read-only list of recent App Store and Google Play reviews (date, stars, territory / language, replied or not, text). Google Play only returns reviews from the last 7 days.', + props: { store: { type: 'string', enum: ['apple', 'play'], description: 'Default: both' }, days: { type: 'integer', minimum: 1, maximum: 365, default: 14 }, + unanswered: { type: 'boolean', default: false }, rating: { type: 'string', pattern: '^[1-5](,[1-5])*$', description: 'e.g. 1,2' } }, + args: i => [...opt('store', i.store), ...opt('days', i.days), ...flag('unanswered', i.unanswered), ...opt('rating', i.rating)] }, + { name: 'reviews_draft', title: 'Draft review replies', command: ['reviews', 'draft'], write: true, network: true, idempotent: true, + description: 'Write one local Markdown draft per unanswered review into .storebound/replies/-.md (approved: false; existing drafts are kept). Then write the reply under "## Reply" following the review-replies skill; the owner approves and sends from the terminal. Nothing is sent to a store.', + props: { store: { type: 'string', enum: ['apple', 'play'], description: 'Default: both' }, days: { type: 'integer', minimum: 1, maximum: 365, default: 14 }, + rating: { type: 'string', pattern: '^[1-5](,[1-5])*$', description: 'Only these star ratings, e.g. 1,2,3' } }, + args: i => [...opt('store', i.store), ...opt('days', i.days), ...opt('rating', i.rating)] }, { 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, @@ -159,7 +169,7 @@ export const TOOLS: ToolDef[] = [ /** CLI flags / commands that must never be reachable through MCP. Tests assert none of the tools can produce them. */ export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete', - '--submit-review', '--remove', '--invite', 'testers']; + '--submit-review', '--remove', '--invite', 'testers', 'send']; export function inputSchema(t: ToolDef): Record { const props: Record = { ...(t.props ?? {}) }; diff --git a/cli/reviews.ts b/cli/reviews.ts new file mode 100644 index 0000000..7a17a18 --- /dev/null +++ b/cli/reviews.ts @@ -0,0 +1,143 @@ +// Store reviews and replies. +// storebound reviews list [--store apple|play] [--days 14] [--unanswered] [--rating 1,2] [--json] +// storebound reviews draft [--store apple|play] [--days 14] [--rating 1,2,3] [--all] [--dir .storebound/replies] [--dry] +// storebound reviews send [--dir .storebound/replies] [--dry] [--yes] +// `draft` writes one Markdown file per unanswered review into .storebound/replies/ (gitignored): front matter +// (store, review_id, rating, approved: false), the review, and an empty "## Reply" section. Existing files are never +// overwritten (your edits stay). The owner or an agent with the review-replies skill writes the reply; the owner sets +// `approved: true`. `send` sends only approved, unsent drafts that pass the checks (length, no incentives), after a +// confirmation, then writes `sent: