CLI workspace for many apps and studios, credential profiles, release trains (release status / plan)

- storebound.workspace.json: app folders (globs), studios with accounts by credential profile, ignore list, the
  desktop's pairing overrides; ws init | list | status | check | validate | run | apps import | desktop export/import
- credential profiles in ~/.storebound/credentials/<profile>.json or env, --account <profile> on any command
- release status / release plan <version>, table or --json; MCP workspace_list, workspace_status, release_status,
  release_plan (read-only)
- pairing rules (cli/lib/identity.ts), release lanes (cli/lib/train.ts) and the per-app status read
  (cli/lib/app-status.ts) shared with the desktop instead of copied
- tests with sanitized fixtures, README, skills, CHANGELOG
This commit is contained in:
CRTkafa 2026-10-11 15:35:45 +00:00
parent 02d90de77a
commit 7d70e58d76
26 changed files with 2220 additions and 292 deletions

View file

@ -19,6 +19,8 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
'desktop': [() => import('./desktop'), 'open the storebound desktop app (in an app folder: add or select it there); not installed: the download for this system, --download saves it to ~/Downloads after checking its signature (never installs)'],
'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'],
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
'ws': [() => import('./workspace'), 'many apps and studios (storebound.workspace.json): init | list | status (apps x stores, parallel) | check | validate | run <command> --apps a,b|--all (writes dry unless --apply) | apps import --account <profile> | desktop export|import'],
'release': [() => import('./release'), 'status [--app a,b] [--versions]: both stores on one train per version (build > testing > review > live > rollout %) | plan <version>: what is left on each store, in fix order; read-only, --json'],
};
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'inspect': [() => import('./inspect'), 'offline summary of the config (name, store ids, languages, products, subscriptions); --json'],
@ -73,8 +75,9 @@ usage: storebound <command> [options]
${Object.entries(PLAIN).map(([k, [, d]]) => ` ${k.padEnd(25)} ${d}`).join('\n')}
${Object.entries(COMMANDS).map(([k, [, d]]) => ` ${k.padEnd(25)} ${d}`).join('\n')}
common options: --config <path> --dry (no writes) --only <ids> --yes (skip confirmations)
credentials: PLAY_SERVICE_ACCOUNT, ASC_KEY_ID, ASC_ISSUER_ID, ASC_P8, REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD (env or .storebound/credentials.json)
common options: --config <path> --dry (no writes) --only <ids> --yes (skip confirmations) --account <profile> (credential profile)
credentials: PLAY_SERVICE_ACCOUNT, ASC_KEY_ID, ASC_ISSUER_ID, ASC_P8, REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD (env or .storebound/credentials.json);
profiles for many accounts: ~/.storebound/credentials/<profile>.json (same names), picked with --account <profile>
docs: README.md and the skills/ folder of the toolchain`);
}
@ -82,6 +85,16 @@ async function main(): Promise<void> {
// tools (adb, emulator, ffmpeg…) are also looked up where they usually live, for apps started without a shell PATH
process.env.PATH = toolPath(process.env);
const argv = process.argv.slice(2);
// --account <profile>: the credential profile for this run (ws apps import reads its own --account)
if (argv[0] !== 'ws') {
const i = argv.findIndex(x => x === '--account' || x.startsWith('--account='));
if (i >= 0) {
const name = argv[i]!.includes('=') ? argv[i]!.slice(10) : argv[i + 1];
if (!name || name.startsWith('--')) throw new Error('--account <credential profile>');
process.env.STOREBOUND_PROFILE = name;
argv.splice(i, argv[i]!.includes('=') ? 1 : 2);
}
}
const [a, b] = argv;
if (!a || a === 'help' || a === '--help' || a === '-h') return help();
if (a === 'version' || a === '--version') return console.log((await import('../package.json')).version);

61
cli/lib/app-status.ts Normal file
View file

@ -0,0 +1,61 @@
// One app's portfolio status: identity, offline config check, catalog parity and (live) the release trains from
// `apple status --json` / `play status --json`. Shared by the desktop's `portfolio.status` (cli/serve.ts) and the CLI
// workspace (`storebound ws status`, `storebound release status`), so all of them read an app the same way.
// Every read is a storebound child command; `exec` runs it (serve tracks it for cancellation, the CLI just awaits it).
import type { AppStatus, ProjectSummary } from './desktop-protocol';
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './portfolio';
import type { RunResult } from './runner';
export type Exec = (argv: string[], cwd: string) => Promise<RunResult>;
export const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
export const emptyStatus = (project: string): AppStatus =>
({ project, ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] });
/** `inspect --json` of a folder; throws "project: <reason>" when the config does not load. */
export async function inspectApp(dir: string, exec: Exec): Promise<ProjectSummary> {
const r = await exec(['inspect', '--json'], dir);
if (r.cancelled) throw new Error('Request cancelled');
if (r.code !== 0 || !r.data) throw new Error(`project: ${lastLine(r.out) || 'config could not be loaded'}`);
return r.data as ProjectSummary;
}
/**
* Fills `e` for the app in `dir`: summary, identity, check (skipped for a store-only app), and with `live` the release
* trains and the live catalog parity. Errors are thrown; the caller records them in `e.errors`.
*/
export async function fillAppStatus(e: AppStatus, dir: string, o: { live: boolean; virtual?: boolean; exec: Exec }): Promise<AppStatus> {
const summary = e.summary = await inspectApp(dir, o.exec);
e.app = appIdentity(summary);
e.catalog = catalogParity(summary);
if (o.virtual) e.check = { ok: true, problems: [], warnings: [] };
else {
const c = await o.exec(['check', '--json'], dir);
const cd = c.data as { ok?: boolean; problems?: string[]; warnings?: string[] } | undefined;
e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] };
}
if (o.live) {
const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => {
const r = await o.exec(argv, dir);
return r.code === 0 && r.data !== undefined ? { data: r.data } : { error: lastLine(r.out) || `exit ${r.code}` };
};
const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]);
if (apple?.error) e.storeErrors.ios = apple.error;
if (play?.error) e.storeErrors.android = play.error;
const ios = apple?.data ? appleReleases(apple.data) : [], android = play?.data ? playReleases(play.data) : [];
e.release = { source: 'live', ...releaseTrains(ios, android), all: [...ios, ...android] };
e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined);
}
e.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true);
return e;
}
/** Runs `fn` over `items`, at most `limit` at a time; results in input order. */
export async function pool<T, R>(items: T[], limit: number, fn: (x: T, i: number) => Promise<R>): Promise<R[]> {
const out = new Array<R>(items.length);
let next = 0;
const n = Math.max(1, Math.min(limit, items.length));
await Promise.all(Array.from({ length: n }, async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]!, i); } }));
return out;
}

View file

@ -7,9 +7,13 @@
// "reviewDemoAccount": { "username": "", "password": "" } }
// The demo account for App Review can also come from env: REVIEW_DEMO_USER, REVIEW_DEMO_PASSWORD.
// 3. ASC_P8 only: ~/.appstoreconnect/private_keys/AuthKey_<ASC_KEY_ID>.p8 (where Xcode / altool keep it)
// With a credential profile (`--profile <name>` or STOREBOUND_PROFILE), the profile comes before all of these:
// ~/.storebound/credentials/<name>.json (same four names; relative paths are relative to that file; folder:
// STOREBOUND_CREDENTIALS_DIR) or env STOREBOUND_PROFILE_<NAME>_<KEY> (NAME upper case, other characters as _).
// Many studios / store accounts from one machine: one profile per account; storebound.workspace.json names them.
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { isAbsolute, join, resolve } from 'node:path';
export interface ServiceAccount { client_email: string; private_key: string; token_uri?: string }
export interface AscKey { keyId: string; issuerId: string; pem: string }
@ -23,7 +27,51 @@ function fileStore(root: string): Store {
try { return JSON.parse(readFileSync(p, 'utf8')) as Store; } catch (e) { throw new Error(`${p}: ${(e as Error).message}`); }
}
/** The store credential names a profile holds (the same as the env names). */
export const PROFILE_KEYS = ['PLAY_SERVICE_ACCOUNT', 'ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8'] as const;
export const PROFILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
export const profileDir = (): string => process.env.STOREBOUND_CREDENTIALS_DIR || join(homedir(), '.storebound', 'credentials');
const profileEnvName = (profile: string, key: string): string => `STOREBOUND_PROFILE_${profile.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_${key}`;
/**
* The credentials of one profile as env values (never printed). Env STOREBOUND_PROFILE_<NAME>_<KEY> wins over the
* profile file; a relative key path in the file is relative to the file. Throws on a bad name or an unreadable file.
*/
export function profileEnv(profile: string): Record<string, string> {
if (!PROFILE_RE.test(profile)) throw new Error(`credential profile "${profile}": letters, digits, . _ - (max 64)`);
const file = join(profileDir(), `${profile}.json`);
let stored: Store = {};
if (existsSync(file)) {
try { stored = JSON.parse(readFileSync(file, 'utf8')) as Store; } catch (e) { throw new Error(`credential profile ${profile}: ${file}: ${(e as Error).message}`); }
}
const out: Record<string, string> = {};
for (const k of PROFILE_KEYS) {
const env = process.env[profileEnvName(profile, k)];
const v = env || (typeof stored[k] === 'string' ? stored[k] as string : '');
if (!v) continue;
// a path in the file: relative to the profile folder (inline JSON / PEM stays as it is)
const isPath = !env && !/^\s*\{/.test(v) && !/BEGIN PRIVATE KEY/.test(v) && (k === 'PLAY_SERVICE_ACCOUNT' || k === 'ASC_P8');
out[k] = isPath && !isAbsolute(v) && !v.startsWith('~') ? resolve(profileDir(), v) : v;
}
return out;
}
/** Which stores a profile can reach, and where it comes from. No values. */
export function profileStatus(profile: string): { profile: string; source: 'file' | 'env' | 'missing' | 'invalid'; apple: boolean; play: boolean; error?: string } {
try {
const env = profileEnv(profile);
const fromEnv = PROFILE_KEYS.some(k => !!process.env[profileEnvName(profile, k)]);
const source = fromEnv ? 'env' : existsSync(join(profileDir(), `${profile}.json`)) ? 'file' : 'missing';
return { profile, source, apple: !!(env.ASC_KEY_ID && env.ASC_ISSUER_ID), play: !!env.PLAY_SERVICE_ACCOUNT };
} catch (e) {
return { profile, source: 'invalid', apple: false, play: false, error: (e as Error).message };
}
}
function value(root: string, name: string): string | undefined {
const profile = process.env.STOREBOUND_PROFILE;
if (profile) { const v = profileEnv(profile)[name]; if (v) return v; }
const env = process.env[name];
if (env) return env;
const v = fileStore(root)[name];

200
cli/lib/identity.ts Normal file
View file

@ -0,0 +1,200 @@
// One app card per product, across studios and store accounts: the pairing rules the desktop app (apps/desktop) and
// the CLI workspace (`storebound ws`, cli/lib/workspace.ts) share. Pure, so tests pin every rule
// (apps/desktop/tests/identity.test.ts, tests/workspace.test.ts).
//
// Inputs: app folders (with the store ids of their config), the apps each store account can see (`apps list`), and
// the owner's overrides (manual pairs / unpairs, links of a store app to a folder, studio moves, the ignore list).
// Order of matching:
// 1. a folder takes the store apps its config names (explicit link > App Store app id > bundle id / package name),
// preferring the accounts mapped to the folder;
// 2. the remaining store apps pair iOS + Android: manual pairs, then the same bundle id and package name, then a
// close id (".ios" / ".android" suffixes, case, punctuation) or the same name; unpairs block an automatic pair;
// 3. what is left is a single-platform store-only app.
// A store-only app is read through a "store target" (store:ios:<account>:<app id>:<bundle>;android:<account>:<package>).
import type { ProjectSummary, StoreApp } from './desktop-protocol';
/** An app folder as both front ends know it (the desktop's Project carries more fields). */
export interface IdProject { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null }
/** A store account: an id (16 hex) and its studio. */
export interface IdAccount { id: string; studio?: string | null }
export interface Pair { ios: string; android: string }
export interface Overrides {
pairs: Pair[];
unpairs: Pair[];
links: { key: string; project: string }[];
appStudio: { key: string; studio: string }[];
ignored: string[];
}
export const NO_OVERRIDES: Overrides = { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] };
/** One app record of one store account. */
export interface StoreRef { key: string; account: string; store: 'ios' | 'android'; app: StoreApp }
export type Pairing = 'folder' | 'manual' | 'id' | 'close' | 'name' | 'single';
export interface UnifiedApp<P extends IdProject = IdProject> {
/** Route and list key: the project id, else the store target. */
key: string;
/** What reads use: the project id, else the store target ("store:..."). */
target: string;
name: string;
project: P | null;
ios: StoreRef | null;
android: StoreRef | null;
studio: string | null;
pairing: Pairing;
/** The keys an "ignore" puts on the list ("project:<id>" or "app:<store key>"). */
ignoreKeys: string[];
ignored: boolean;
/** Store icon (data URL) when the folder has none. */
storeIcon: string | null;
}
export const refKey = (account: string, a: StoreApp): string => `${a.store}:${account}:${a.id}`;
/** Store target of a store-only app. */
export function storeTarget(ios: StoreRef | null, android: StoreRef | null): string {
const parts: string[] = [];
if (ios) parts.push(`ios:${ios.account}:${ios.app.id}:${ios.app.bundleId}`);
if (android) parts.push(`android:${android.account}:${android.app.id}`);
return `store:${parts.join(';')}`;
}
/** "com.example.Puzzle.ios" -> "comexamplepuzzle": ids that differ only by a platform suffix, case or punctuation. */
export function normId(id: string): string {
return id.toLowerCase().replace(/[._-](ios|iphone|android|droid|app)$/g, '').replace(/[^a-z0-9]/g, '');
}
export const normName = (n: string): string => n.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]/g, '');
const samePair = (p: Pair, ios: string, android: string) => p.ios === ios && p.android === android;
export interface BuildInput<P extends IdProject = IdProject> {
projects: P[];
/** Store ids of each folder's config (from the offline portfolio read). */
summaryOf: (p: P) => ProjectSummary | null | undefined;
accounts: IdAccount[];
/** The last app list of each account. */
storeApps: { account: string; apps: StoreApp[] }[];
overrides: Overrides;
}
export function buildApps<P extends IdProject>(i: BuildInput<P>): UnifiedApp<P>[] {
const o = i.overrides;
const ignoredAccounts = new Set(o.ignored.filter(x => x.startsWith('account:')).map(x => x.slice(8)));
const accountStudio = new Map(i.accounts.map(a => [a.id, a.studio ?? null] as const));
const known = new Set(i.accounts.map(a => a.id));
// every store app of every (not ignored) account
const refs: StoreRef[] = [];
for (const s of i.storeApps) {
if (!known.has(s.account) || ignoredAccounts.has(s.account)) continue;
for (const app of s.apps) refs.push({ key: refKey(s.account, app), account: s.account, store: app.store, app });
}
const used = new Set<string>();
const take = (r: StoreRef | null | undefined): StoreRef | null => { if (!r || used.has(r.key)) return null; used.add(r.key); return r; };
const studioOverride = new Map(o.appStudio.map(x => [x.key, x.studio] as const));
const ignored = new Set(o.ignored);
const out: UnifiedApp<P>[] = [];
// 1. folders
for (const p of i.projects) {
const s = i.summaryOf(p);
const mine = (r: StoreRef) => r.account === (r.store === 'ios' ? p.appleAccount : p.playAccount);
const rank = (rs: StoreRef[]) => [...rs].sort((a, b) => Number(mine(b)) - Number(mine(a)));
const linked = o.links.filter(l => l.project === p.id).map(l => refs.find(r => r.key === l.key)).filter((r): r is StoreRef => !!r && !used.has(r.key));
let ios = take(linked.find(r => r.store === 'ios'));
let android = take(linked.find(r => r.store === 'android'));
if (!ios && s?.apple) {
const free = refs.filter(r => r.store === 'ios' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
ios = take(rank(free.filter(r => s.apple!.appId && r.app.id === s.apple!.appId))[0] ?? rank(free.filter(r => r.app.bundleId === s.apple!.bundleId))[0]);
}
if (!android && s?.play) {
const free = refs.filter(r => r.store === 'android' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
android = take(rank(free.filter(r => r.app.id === s.play!.packageName))[0]);
}
const studio = studioOverride.get(`project:${p.id}`)
?? (p.appleAccount && accountStudio.get(p.appleAccount)) ?? (p.playAccount && accountStudio.get(p.playAccount))
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
out.push({
key: p.id, target: p.id, name: p.name, project: p, ios, android, studio, pairing: 'folder',
ignoreKeys: [`project:${p.id}`], ignored: ignored.has(`project:${p.id}`), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
});
}
// 2. pairs among the remaining store apps
const freeIos = () => refs.filter(r => r.store === 'ios' && !used.has(r.key));
const freeAndroid = () => refs.filter(r => r.store === 'android' && !used.has(r.key));
const blocked = (a: StoreRef, b: StoreRef) => o.unpairs.some(p => samePair(p, a.key, b.key));
const sameStudio = (a: StoreRef, b: StoreRef) => (accountStudio.get(a.account) ?? null) === (accountStudio.get(b.account) ?? null);
const pairs: [StoreRef, StoreRef, Pairing][] = [];
for (const m of o.pairs) {
const a = freeIos().find(r => r.key === m.ios), b = freeAndroid().find(r => r.key === m.android);
if (a && b) { take(a); take(b); pairs.push([a, b, 'manual']); }
}
const auto = (how: Pairing, match: (a: StoreRef, b: StoreRef) => boolean) => {
for (const a of freeIos()) {
const cands = freeAndroid().filter(b => !blocked(a, b) && match(a, b)).sort((x, y) => Number(sameStudio(a, y)) - Number(sameStudio(a, x)));
const b = cands[0];
if (b) { take(a); take(b); pairs.push([a, b, how]); }
}
};
auto('id', (a, b) => a.app.bundleId === b.app.id);
auto('close', (a, b) => normId(a.app.bundleId) !== '' && normId(a.app.bundleId) === normId(b.app.id));
auto('name', (a, b) => normName(a.app.name) !== '' && normName(a.app.name) === normName(b.app.name));
const storeOnly = (ios: StoreRef | null, android: StoreRef | null, pairing: Pairing) => {
const target = storeTarget(ios, android);
const keys = [ios, android].filter((r): r is StoreRef => !!r).map(r => r.key);
const studio = keys.map(k => studioOverride.get(k)).find(Boolean)
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
out.push({
key: target, target, name: ios?.app.name ?? android?.app.name ?? '?', project: null, ios, android, studio, pairing,
ignoreKeys: keys.map(k => `app:${k}`), ignored: keys.some(k => ignored.has(`app:${k}`)), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
});
};
for (const [a, b, how] of pairs) storeOnly(a, b, how);
// 3. singles
for (const r of refs) if (!used.has(r.key)) { used.add(r.key); storeOnly(r.store === 'ios' ? r : null, r.store === 'android' ? r : null, 'single'); }
return out;
}
/** Candidates to pair a single-platform app with (the other store's single apps), closest first. */
export function pairCandidates<P extends IdProject>(app: UnifiedApp<P>, all: UnifiedApp<P>[]): UnifiedApp<P>[] {
if (app.project || (app.ios && app.android)) return [];
const want = app.ios ? 'android' : 'ios';
const me = (app.ios ?? app.android)!;
const score = (x: UnifiedApp<P>) => {
const r = (want === 'ios' ? x.ios : x.android)!;
return (normId(r.app.bundleId) === normId(me.app.bundleId) ? 4 : 0) + (normName(r.app.name) === normName(me.app.name) ? 2 : 0) + (x.studio === app.studio ? 1 : 0);
};
return all.filter(x => !x.project && !x.ignored && (want === 'ios' ? x.ios && !x.android : x.android && !x.ios)).sort((a, b) => score(b) - score(a) || a.name.localeCompare(b.name));
}
/** Overrides after pairing two single store apps by hand (drops an unpair of the same two). */
export function withPair(o: Overrides, ios: string, android: string): Overrides {
return { ...o, pairs: [...o.pairs.filter(p => p.ios !== ios && p.android !== android), { ios, android }], unpairs: o.unpairs.filter(p => !samePair(p, ios, android)) };
}
/** Overrides after splitting a paired app (keeps it apart from now on). */
export function withUnpair(o: Overrides, ios: string, android: string): Overrides {
return { ...o, pairs: o.pairs.filter(p => !samePair(p, ios, android)), unpairs: [...o.unpairs.filter(p => !samePair(p, ios, android)), { ios, android }] };
}
export function withIgnored(o: Overrides, keys: string[], on: boolean): Overrides {
const set = new Set(o.ignored);
for (const k of keys) { if (on) set.add(k); else set.delete(k); }
return { ...o, ignored: [...set] };
}
/** Moves an app to a studio (null: back to its accounts' studio). */
export function withStudio(o: Overrides, app: UnifiedApp, studio: string | null): Overrides {
const keys = app.project ? [`project:${app.project.id}`] : [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
const rest = o.appStudio.filter(x => !keys.includes(x.key));
return { ...o, appStudio: studio ? [...rest, ...keys.map(key => ({ key, studio }))] : rest };
}
/** Links the store apps of a store-only app to a folder. */
export function withLink(o: Overrides, app: UnifiedApp, project: string): Overrides {
const keys = [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
return { ...o, links: [...o.links.filter(l => !keys.includes(l.key)), ...keys.map(key => ({ key, project }))] };
}

229
cli/lib/train.ts Normal file
View file

@ -0,0 +1,229 @@
// Release trains: one version across the App Store and Google Play, on one track of stages
// (build -> testing -> review -> live -> rollout). The desktop app's Releases tab (apps/desktop/src/lib/model.ts
// re-exports these) and `storebound release status | plan` (cli/release.ts) share this file, so both show the same
// stage for the same store state. Pure; the store reads are `apple status --json` / `play status --json`, turned into
// StoreRelease rows by cli/lib/portfolio.ts.
import type { ReleaseTrain, StoreRelease } from './desktop-protocol';
import { cmpVersion } from './portfolio';
import type { Finding } from './validate-rules';
export { cmpVersion };
export type Tone = 'ok' | 'warn' | 'bad' | 'info' | 'neutral' | 'accent';
/** Stages of one version on one store, left to right. */
export const STAGES = ['build', 'testing', 'review', 'live', 'rollout'] as const;
export type Stage = (typeof STAGES)[number];
export interface Lane {
store: 'ios' | 'android';
release: StoreRelease | null;
/** Index of the stage it is at (-1: not on this store). */
at: number;
tone: Tone;
/** Rollout share 0-1 when live or rolling out (1 = everyone). */
share: number | null;
/** The store's state word, for a tooltip. */
state: string;
}
/** Where a store release is on the track. Rollout counts as the last stage; a full release fills it. */
export function laneOf(store: 'ios' | 'android', r: StoreRelease | null, testflightReached = false): Lane {
if (!r) return { store, release: null, at: -1, tone: 'neutral', share: null, state: '' };
const base = { store, release: r, state: r.state };
switch (r.phase) {
case 'draft': return { ...base, at: testflightReached ? 1 : 0, tone: testflightReached ? 'info' : 'neutral', share: null };
case 'testing': return { ...base, at: 1, tone: 'info', share: null };
case 'review': return { ...base, at: 2, tone: 'warn', share: null };
case 'approved': return { ...base, at: 2, tone: 'ok', share: null };
case 'rejected': return { ...base, at: 2, tone: 'bad', share: null };
case 'live': return { ...base, at: 4, tone: 'ok', share: 1 };
case 'rollout': return { ...base, at: 4, tone: 'accent', share: r.fraction ?? null };
case 'halted': return { ...base, at: 4, tone: 'bad', share: r.fraction ?? null };
default: return { ...base, at: 0, tone: 'neutral', share: null };
}
}
/** TestFlight builds as `apple testflight status --json` lists them (only what the lanes need). */
export interface BetaBuilds { builds: { version: string | null; internal: string | null; external: string | null }[] }
/** Both lanes of a train; iOS counts TestFlight as reached when a build of that version is in beta testing. */
export function trainLanes(t: ReleaseTrain, tf?: BetaBuilds | null): Lane[] {
const inBeta = !!tf?.builds.some(b => b.version === t.version && /IN_BETA_TESTING|BETA_APPROVED|READY_FOR_BETA_TESTING/.test(`${b.internal ?? ''} ${b.external ?? ''}`));
return [laneOf('ios', t.ios, inBeta), laneOf('android', t.android)];
}
/** Every distinct version of the store releases, newest first, with both stores' release (best phase per store). */
export function versionHistory(all: StoreRelease[]): ReleaseTrain[] {
const rank: Record<string, number> = { live: 0, rollout: 1, halted: 2, approved: 3, review: 4, rejected: 5, testing: 6, draft: 7, other: 8 };
const versions = [...new Set(all.map(r => r.version).filter((v): v is string => !!v))].sort(cmpVersion).reverse();
const best = (store: 'ios' | 'android', v: string) => all.filter(r => r.store === store && r.version === v).sort((a, b) => (rank[a.phase] ?? 9) - (rank[b.phase] ?? 9))[0] ?? null;
return versions.map(v => ({ version: v, ios: best('ios', v), android: best('android', v) }));
}
/** On one store: the highest version reaching users (live or rolling out) and the highest version above it. */
export function storeNow(all: StoreRelease[], store: 'ios' | 'android'): { now: StoreRelease | null; next: StoreRelease | null } {
const rs = all.filter((r): r is StoreRelease & { version: string } => r.store === store && !!r.version);
const desc = (a: { version: string }, b: { version: string }) => cmpVersion(b.version, a.version);
const now = rs.filter(r => r.phase === 'live' || r.phase === 'rollout' || r.phase === 'halted').sort(desc)[0] ?? null;
const next = rs.filter(r => !now || cmpVersion(r.version, now.version) > 0).sort(desc)[0] ?? null;
return { now, next };
}
// ---- Terminal view of a lane (release status) ----
const pctText = (x: number | null): string => (x === null ? '' : `${Math.round(x * 1000) / 10}%`);
/** "review (approved)", "rollout 20%", "rollout (halted) 5%", "live", "-" for a store without this version. */
export function laneText(l: Lane): string {
if (!l.release) return '-';
const stage = STAGES[l.at] ?? 'build';
const p = l.release.phase;
if (p === 'live') return 'live'; // the whole track filled: everyone has it
const word = p === stage || (p === 'draft' && stage === 'build') || (p === 'other' && stage === 'build') ? stage : `${stage} (${p})`;
if (p === 'rollout' || p === 'halted') return `${word} ${pctText(l.share)}`.trim();
return word;
}
/** "build > testing > [review] > live > rollout" with the reached stage in brackets. */
export function trackText(l: Lane): string {
return STAGES.map((s, i) => (i === l.at ? `[${s}]` : s)).join(' > ');
}
// ---- Release plan: what is left for one version on each store, in fix order ----
export type PlanKind = 'config' | 'store' | 'blocker' | 'owner' | 'wait' | 'warning' | 'done';
export interface PlanStep {
kind: PlanKind;
text: string;
/** The command or console place that does it. Owner steps name what the owner runs; storebound never does them. */
fix?: string;
code?: string;
}
export interface StorePlan {
store: 'ios' | 'android';
/** The store's release of this version (best phase), or null when the version is not on the store yet. */
release: StoreRelease | null;
lane: Lane;
steps: PlanStep[];
done: boolean;
}
export interface ReleasePlan {
version: string;
/** Offline config problems (storebound check): both stores need them fixed first. */
shared: PlanStep[];
ios: StorePlan | null;
android: StorePlan | null;
/** Every store the app is on has the version live to everyone. */
done: boolean;
/** What the plan could not read ("unknown, never false"). */
unknown: string[];
}
export interface PlanInput {
version: string;
platforms: { ios: boolean; android: boolean };
/** `storebound check --json`, or null when it did not run. */
check: { problems: string[]; warnings: string[] } | null;
/** `storebound validate --json` findings, or null when it did not run. Validate reads the editable App Store version
* and the Play edit, so its blockers count for a version that is not yet in review. */
validate: Finding[] | null;
/** Every store release read (`AppStatus.release.all`), or null when the stores were not read. */
releases: StoreRelease[] | null;
storeErrors?: { ios?: string; android?: string };
}
const STORE_NAME = { ios: 'App Store', android: 'Google Play' } as const;
/** Phases where the store blockers of `validate` still matter (nothing is submitted yet). */
const BEFORE_REVIEW = new Set(['none', 'draft', 'testing', 'rejected', 'other']);
function storeSteps(store: 'ios' | 'android', v: string, r: StoreRelease | null, findings: Finding[] | null): PlanStep[] {
const steps: PlanStep[] = [];
const phase = r?.phase ?? 'none';
const name = STORE_NAME[store];
// 1. the version itself on the store
if (!r) {
steps.push(store === 'ios'
? { kind: 'store', text: `${v} is not on ${name} yet: upload a build (Xcode / Transporter), then create the version with its texts`, fix: `storebound apple next-build; storebound apple listing --version ${v} --build <N> --dry` }
: { kind: 'store', text: `${v} is not on ${name} yet: upload the AAB to a testing track`, fix: 'storebound play next-version-code; storebound play release <aab> --internal completed --dry' });
} else if (phase === 'rejected') {
steps.push({ kind: 'blocker', text: `${v} was rejected (${r.state}): read the reason, fix it, then resubmit`, fix: 'review-rejections skill', code: 'rejected' });
}
// 2. store blockers (validate, already in fix order), only while nothing is submitted
const tag = store === 'ios' ? 'apple' : 'play';
const mine = (findings ?? []).filter(f => f.store === tag);
if (BEFORE_REVIEW.has(phase)) for (const f of mine.filter(x => x.level === 'blocker')) steps.push({ kind: 'blocker', text: f.msg, ...(f.fix ? { fix: f.fix } : {}), code: f.code });
// 3. the next move on the track
switch (phase) {
case 'none': case 'other':
break;
case 'draft':
steps.push(store === 'ios'
? { kind: 'owner', text: `submit ${v} for App Review (owner)`, fix: 'App Store Connect > the version > Add for Review' }
: r!.track && r!.track !== 'production'
? { kind: 'owner', text: `roll out the ${r!.track} draft of ${v} to its testers (owner)`, fix: `Play Console > Test and release > ${r!.track}` }
: { kind: 'owner', text: `send the production draft of ${v} for review (owner)`, fix: 'Play Console > Publishing overview > Send for review' });
break;
case 'testing':
steps.push({ kind: 'owner', text: `promote ${v} from ${r!.track ?? 'testing'} to production (owner)`, fix: 'Play Console > Test and release > Production, or `storebound play release <aab> --production draft` in a terminal' });
break;
case 'rejected':
steps.push({ kind: 'owner', text: `resubmit ${v} after the fix (owner)`, fix: store === 'ios' ? 'App Store Connect > App Review > reply / resubmit' : 'Play Console > Publishing overview' });
break;
case 'review':
steps.push({ kind: 'wait', text: `${v} is in review (${r!.state}); nothing to do until the store answers`, fix: store === 'ios' ? 'storebound apple status --wait-review' : 'storebound play status' });
break;
case 'approved':
steps.push({ kind: 'owner', text: `${v} is approved (${r!.state}): release it (owner)`, fix: store === 'ios' ? 'App Store Connect > Release this version, or `storebound apple release --manual-release` in a terminal' : 'Play Console > Publishing overview' });
break;
case 'rollout':
steps.push({ kind: 'owner', text: `${v} reaches ${pctText(r!.fraction) || 'part'} of users: raise or complete the rollout when health is good (owner)`,
fix: store === 'ios' ? 'storebound health; then `storebound apple release --phased complete` in a terminal' : 'storebound health; then `storebound play rollout --fraction <x>` or `--complete` in a terminal' });
break;
case 'halted':
steps.push({ kind: 'owner', text: `the rollout of ${v} is halted at ${pctText(r!.fraction) || '?'}: fix and resume, or ship a new version (owner)`,
fix: store === 'ios' ? '`storebound apple release --phased resume` in a terminal' : '`storebound play rollout --resume` in a terminal' });
break;
case 'live':
steps.push({ kind: 'done', text: `${v} is live on ${name} for everyone` });
break;
}
// 4. warnings last (they do not block)
if (BEFORE_REVIEW.has(phase)) for (const f of mine.filter(x => x.level === 'warn')) steps.push({ kind: 'warning', text: f.msg, ...(f.fix ? { fix: f.fix } : {}), code: f.code });
return steps;
}
/**
* What is left for `version` on each store, in fix order: config problems (offline check) first, then per store the
* version itself, the store blockers (validate), the next move on the track (owner steps are named, never done) and
* the warnings. A store whose state could not be read is listed in `unknown`, never planned as "not there".
*/
export function releasePlan(i: PlanInput): ReleasePlan {
const unknown: string[] = [];
const shared: PlanStep[] = [];
if (i.check) {
for (const p of i.check.problems) shared.push({ kind: 'config', text: p, fix: 'storebound check' });
} else unknown.push('config check did not run');
const trains = i.releases ? versionHistory(i.releases) : [];
const train = trains.find(t => cmpVersion(t.version, i.version) === 0 && t.version.split('.').length === i.version.split('.').length)
?? trains.find(t => cmpVersion(t.version, i.version) === 0) ?? null;
const one = (store: 'ios' | 'android'): StorePlan | null => {
if (!i.platforms[store]) return null;
const err = i.storeErrors?.[store];
if (!i.releases || err) {
unknown.push(`${STORE_NAME[store]} state not read${err ? `: ${err}` : ''}`);
return { store, release: null, lane: laneOf(store, null), steps: [{ kind: 'store', text: `${STORE_NAME[store]} could not be read: the plan for this store is unknown`, fix: store === 'ios' ? 'storebound apple status' : 'storebound play status' }], done: false };
}
const r = train?.[store] ?? null;
const steps = storeSteps(store, i.version, r, i.validate);
return { store, release: r, lane: laneOf(store, r), steps, done: r?.phase === 'live' };
};
if (!i.validate) unknown.push('store readiness (validate) did not run');
const ios = one('ios'), android = one('android');
const stores = [ios, android].filter((x): x is StorePlan => !!x);
return { version: i.version, shared, ios, android, done: !shared.length && stores.length > 0 && stores.every(s => s.done), unknown };
}

404
cli/lib/workspace.ts Normal file
View file

@ -0,0 +1,404 @@
// The multi-app workspace: one storebound.workspace.json (or .ts) in a folder above many app folders. It names the
// app folders (globs allowed), the studios and their store accounts (by credential profile, never a secret), an
// ignore list and the owner's pairing overrides. It is the same model as the desktop app's state (studios, accounts,
// projects, overrides: apps/desktop/src-tauri/src/store.rs, workspace.rs), so `storebound ws desktop export | import`
// moves it both ways. Pairing of store apps with folders is cli/lib/identity.ts, shared with the desktop.
//
// {
// "apps": ["apps/*", { "path": "games/puzzle", "apple": "acme-apple", "play": "acme-play" }],
// "studios": [{ "name": "Acme Games", "color": "indigo", "apps": ["games/*"],
// "accounts": [{ "store": "apple", "profile": "acme-apple" }, { "store": "play", "profile": "acme-play" }] }],
// "accounts": [{ "store": "play", "profile": "solo-play" }],
// "ignore": ["apps/old-*", "app:ios:<account id>:<app id>", "account:solo-play"],
// "overrides": { "pairs": [], "unpairs": [], "links": [], "appStudio": [] },
// "concurrency": 4
// }
import { createHash } from 'node:crypto';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { CONFIG_NAMES } from './config';
import { PROFILE_RE } from './credentials';
import type { StoreApp } from './desktop-protocol';
import { type IdProject, NO_OVERRIDES, type Overrides, type Pair } from './identity';
export const WORKSPACE_NAMES = ['storebound.workspace.json', 'storebound.workspace.ts', 'storebound.workspace.js'];
/** Colours a studio can carry: the desktop's set (workspace.rs STUDIO_COLORS). */
export const STUDIO_COLORS = ['indigo', 'violet', 'rose', 'amber', 'emerald', 'teal', 'sky', 'slate'] as const;
export type StudioColor = (typeof STUDIO_COLORS)[number];
export type Store = 'apple' | 'play';
export interface WsAccount {
store: Store;
/** Credential profile: ~/.storebound/credentials/<profile>.json or env STOREBOUND_PROFILE_<NAME>_* */
profile: string;
label?: string;
/** The desktop's account id (16 hex) when it came from there; else derived from store + profile. */
id?: string;
}
export interface WsStudio { id?: string; name: string; color?: StudioColor; accounts?: WsAccount[]; apps?: string[] }
export interface WsAppEntry { path: string; name?: string; apple?: string; play?: string }
/** Pairing overrides as the desktop keeps them; a project is named by its folder (relative to the workspace). */
export interface WsOverrides { pairs?: Pair[]; unpairs?: Pair[]; links?: { key: string; project: string }[]; appStudio?: { key: string; studio: string }[] }
export interface Workspace {
apps: (string | WsAppEntry)[];
studios?: WsStudio[];
accounts?: WsAccount[];
ignore?: string[];
overrides?: WsOverrides;
/** Apps read at the same time (1-8, default 4: the desktop's default). */
concurrency?: number;
}
/** For a storebound.workspace.ts: `export default defineWorkspace({ ... })`. */
export const defineWorkspace = (w: Workspace): Workspace => w;
export interface LoadedWorkspace { file: string; root: string; ws: Workspace }
/** Resolved account: the workspace entry with its id and studio. */
export interface Account extends WsAccount { id: string; studio: string | null }
export interface Studio { id: string; name: string; color: StudioColor }
/** One app folder of the workspace. `id` is its path relative to the workspace (forward slashes). */
export interface AppFolder extends IdProject { rel: string; ignored: boolean; studio: string | null; appleProfile: string | null; playProfile: string | null }
const hex16 = (s: string): string => createHash('sha256').update(s).digest('hex').slice(0, 16);
export const accountId = (a: WsAccount): string => (a.id && /^[0-9a-f]{16}$/.test(a.id) ? a.id : hex16(`${a.store}:${a.profile}`));
export const slug = (s: string): string => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'studio';
export const studioId = (s: WsStudio): string => s.id || slug(s.name);
const posix = (p: string): string => p.split(sep).join('/');
/** Finds the workspace file in `from` or a folder above it. */
export function findWorkspace(from: string, explicit?: string): string | null {
if (explicit) {
const p = resolve(from, explicit);
if (existsSync(p) && statSync(p).isDirectory()) return WORKSPACE_NAMES.map(n => join(p, n)).find(existsSync) ?? null;
return existsSync(p) ? p : null;
}
let d = resolve(from);
for (;;) {
const hit = WORKSPACE_NAMES.map(n => join(d, n)).find(existsSync);
if (hit) return hit;
const up = resolve(d, '..');
if (up === d) return null;
d = up;
}
}
export async function loadWorkspace(from: string, explicit?: string): Promise<LoadedWorkspace> {
const file = findWorkspace(from, explicit);
if (!file) throw new Error(`no storebound.workspace.json in ${from} or above (storebound ws init creates one)`);
let raw: unknown;
if (file.endsWith('.json')) {
try { raw = JSON.parse(readFileSync(file, 'utf8')); } catch (e) { throw new Error(`${file}: ${(e as Error).message}`); }
} else raw = ((await import(file)) as { default?: unknown }).default;
const problems = checkWorkspace(raw);
if (problems.length) throw new Error(`${file}:\n ${problems.join('\n ')}`);
return { file, root: resolve(file, '..'), ws: raw as Workspace };
}
const ACCOUNT_KEYS = ['store', 'profile', 'label', 'id'];
/** Problems of a workspace file (empty = fine). Secrets are refused: only profile names belong here. */
export function checkWorkspace(raw: unknown): string[] {
const e: string[] = [];
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return ['not an object'];
const w = raw as Record<string, unknown>;
const known = ['$schema', 'apps', 'studios', 'accounts', 'ignore', 'overrides', 'concurrency'];
for (const k of Object.keys(w)) if (!known.includes(k)) e.push(`${k}: unknown field (${known.slice(1).join(', ')})`);
if (!Array.isArray(w.apps)) e.push('apps: a list of app folders or globs ("apps/*")');
else w.apps.forEach((a, i) => {
if (typeof a === 'string') { if (!a.trim()) e.push(`apps[${i}]: empty`); return; }
if (typeof a !== 'object' || a === null || typeof (a as WsAppEntry).path !== 'string') { e.push(`apps[${i}]: a path or { path, name?, apple?, play? }`); return; }
for (const k of Object.keys(a)) if (!['path', 'name', 'apple', 'play'].includes(k)) e.push(`apps[${i}].${k}: unknown`);
for (const s of ['apple', 'play'] as const) { const p = (a as WsAppEntry)[s]; if (p !== undefined && (typeof p !== 'string' || !PROFILE_RE.test(p))) e.push(`apps[${i}].${s}: a credential profile name`); }
});
const account = (a: unknown, where: string) => {
if (typeof a !== 'object' || a === null) { e.push(`${where}: { store, profile }`); return; }
const o = a as Record<string, unknown>;
for (const k of Object.keys(o)) if (!ACCOUNT_KEYS.includes(k)) e.push(`${where}.${k}: unknown (secrets never go here: put them in the credential profile)`);
if (o.store !== 'apple' && o.store !== 'play') e.push(`${where}.store: apple or play`);
if (typeof o.profile !== 'string' || !PROFILE_RE.test(o.profile)) e.push(`${where}.profile: a credential profile name (letters, digits, . _ -)`);
if (o.id !== undefined && (typeof o.id !== 'string' || !/^[0-9a-f]{16}$/.test(o.id))) e.push(`${where}.id: 16 hex characters (the desktop's account id)`);
if (o.label !== undefined && (typeof o.label !== 'string' || o.label.length > 60)) e.push(`${where}.label: up to 60 characters`);
};
if (w.accounts !== undefined) { if (!Array.isArray(w.accounts)) e.push('accounts: a list'); else w.accounts.forEach((a, i) => account(a, `accounts[${i}]`)); }
if (w.studios !== undefined) {
if (!Array.isArray(w.studios)) e.push('studios: a list');
else w.studios.forEach((s, i) => {
if (typeof s !== 'object' || s === null) { e.push(`studios[${i}]: { name, color?, accounts?, apps? }`); return; }
const o = s as Record<string, unknown>;
for (const k of Object.keys(o)) if (!['id', 'name', 'color', 'accounts', 'apps'].includes(k)) e.push(`studios[${i}].${k}: unknown`);
if (typeof o.name !== 'string' || !o.name.trim() || o.name.length > 48) e.push(`studios[${i}].name: 1 to 48 characters`);
if (o.color !== undefined && !(STUDIO_COLORS as readonly unknown[]).includes(o.color)) e.push(`studios[${i}].color: one of ${STUDIO_COLORS.join(', ')}`);
if (o.accounts !== undefined) { if (!Array.isArray(o.accounts)) e.push(`studios[${i}].accounts: a list`); else o.accounts.forEach((a, j) => account(a, `studios[${i}].accounts[${j}]`)); }
if (o.apps !== undefined && (!Array.isArray(o.apps) || o.apps.some(x => typeof x !== 'string'))) e.push(`studios[${i}].apps: a list of folder globs`);
});
}
if (w.ignore !== undefined && (!Array.isArray(w.ignore) || w.ignore.some(x => typeof x !== 'string'))) e.push('ignore: a list of folder globs, app:<store app key> or account:<profile>');
if (w.concurrency !== undefined && !(Number.isInteger(w.concurrency) && (w.concurrency as number) >= 1 && (w.concurrency as number) <= 8)) e.push('concurrency: 1 to 8');
if (w.overrides !== undefined && (typeof w.overrides !== 'object' || w.overrides === null || Array.isArray(w.overrides))) e.push('overrides: { pairs, unpairs, links, appStudio }');
// duplicate profiles per store would make two accounts with one id
const all = [...((w.accounts as WsAccount[] | undefined) ?? []), ...(((w.studios as WsStudio[] | undefined) ?? []).flatMap(s => s?.accounts ?? []))];
const seen = new Set<string>();
for (const a of all) { const k = `${a?.store}:${a?.profile}`; if (seen.has(k)) e.push(`account ${k}: listed twice`); seen.add(k); }
return e;
}
/** Every account of the workspace (studio accounts and the loose ones) with ids and studios. */
export function accountsOf(ws: Workspace): Account[] {
const out: Account[] = [];
for (const s of ws.studios ?? []) for (const a of s.accounts ?? []) out.push({ ...a, id: accountId(a), studio: studioId(s) });
for (const a of ws.accounts ?? []) out.push({ ...a, id: accountId(a), studio: null });
return out;
}
export const studiosOf = (ws: Workspace): Studio[] =>
(ws.studios ?? []).map((s, i) => ({ id: studioId(s), name: s.name, color: s.color ?? STUDIO_COLORS[i % STUDIO_COLORS.length]! }));
const isGlob = (p: string): boolean => /[*?[{]/.test(p);
const matchAny = (globs: string[], rel: string): boolean => globs.some(g => new Bun.Glob(g.replace(/\/+$/, '')).match(rel));
const hasConfig = (dir: string): boolean => CONFIG_NAMES.some(n => existsSync(join(dir, n)));
/**
* The app folders: globs expanded (folders with a storebound config only; node_modules and dot folders skipped), the
* ignore globs applied (kept with `ignored: true`, so `ws list --all` can show them), accounts and studio resolved:
* an entry's own profiles > the single account of that store in the studio whose `apps` globs match > the single
* account of that store in the workspace > none (the folder's own credentials, env or .storebound/).
*/
export function resolveApps(l: LoadedWorkspace): { apps: AppFolder[]; warnings: string[] } {
const { root, ws } = l;
const warnings: string[] = [];
const found = new Map<string, WsAppEntry>();
for (const a of ws.apps) {
const entry: WsAppEntry = typeof a === 'string' ? { path: a } : a;
const p = entry.path.replace(/^~(?=\/)/, homedir());
if (isGlob(p)) {
const base = isAbsolute(p) ? '/' : root;
const pattern = isAbsolute(p) ? p.slice(1) : p;
let hits = 0;
for (const m of new Bun.Glob(pattern.replace(/\/+$/, '')).scanSync({ cwd: base, onlyFiles: false, dot: false })) {
if (/(^|\/)(node_modules|\.git)(\/|$)/.test(m)) continue;
const dir = resolve(base, m);
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
if (!hasConfig(dir)) continue;
hits++;
if (!found.has(dir)) found.set(dir, { ...entry, path: dir });
}
if (!hits) warnings.push(`${entry.path}: no app folder (with a storebound config) matches`);
} else {
const dir = resolve(root, p);
if (!existsSync(dir)) { warnings.push(`${entry.path}: folder not found`); continue; }
if (!hasConfig(dir)) { warnings.push(`${entry.path}: no storebound.config.ts in it`); continue; }
found.set(dir, { ...found.get(dir), ...entry, path: dir });
}
}
const accounts = accountsOf(ws);
const byProfile = (store: Store, profile: string | undefined) => (profile ? accounts.find(a => a.store === store && a.profile === profile) : undefined);
const ignoreGlobs = (ws.ignore ?? []).filter(x => !/^(app|account|project):/.test(x));
const apps: AppFolder[] = [];
for (const [dir, entry] of found) {
const rel = posix(relative(root, dir)) || '.';
const studio = (ws.studios ?? []).find(s => matchAny(s.apps ?? [], rel)) ?? null;
const pick = (store: Store): WsAccount | null => {
const named = entry[store];
// a profile the workspace does not list is still usable (its id is derived the same way)
if (named) return byProfile(store, named) ?? { store, profile: named };
const inStudio = (studio?.accounts ?? []).filter(a => a.store === store);
if (inStudio.length === 1) return inStudio[0]!;
const all = accounts.filter(a => a.store === store);
return all.length === 1 ? all[0]! : null;
};
const apple = pick('apple'), play = pick('play');
apps.push({ id: rel, rel, path: dir, name: entry.name ?? basename(dir), appleAccount: apple ? accountId(apple) : null, playAccount: play ? accountId(play) : null,
appleProfile: apple?.profile ?? null, playProfile: play?.profile ?? null,
ignored: matchAny(ignoreGlobs, rel) || (ws.ignore ?? []).includes(`project:${rel}`), studio: studio ? studioId(studio) : null });
}
apps.sort((a, b) => a.rel.localeCompare(b.rel));
return { apps, warnings };
}
/** Desktop-style overrides of the workspace: folder studios from `studios[].apps`, ignore keys with account ids. */
export function overridesOf(ws: Workspace, apps: AppFolder[]): Overrides {
const o = ws.overrides ?? {};
const accounts = accountsOf(ws);
const explicit = o.appStudio ?? [];
const fromGlobs = apps.filter(a => a.studio && !explicit.some(x => x.key === `project:${a.id}`)).map(a => ({ key: `project:${a.id}`, studio: a.studio! }));
const ignored: string[] = [];
for (const x of ws.ignore ?? []) {
if (x.startsWith('app:') || x.startsWith('project:')) ignored.push(x);
else if (x.startsWith('account:')) {
const p = x.slice(8);
const hit = accounts.filter(a => a.profile === p || a.id === p);
ignored.push(...(hit.length ? hit.map(a => `account:${a.id}`) : [x]));
}
}
for (const a of apps) if (a.ignored && !ignored.includes(`project:${a.id}`)) ignored.push(`project:${a.id}`);
return { ...NO_OVERRIDES, pairs: o.pairs ?? [], unpairs: o.unpairs ?? [], links: o.links ?? [], appStudio: [...explicit, ...fromGlobs], ignored };
}
/** Filters apps by `--apps a,b` (folder, folder name or app name, case-insensitive; globs allowed). */
export function selectApps<T extends { rel: string; name: string }>(apps: T[], names: string[]): { picked: T[]; unknown: string[] } {
if (!names.length) return { picked: apps, unknown: [] };
const unknown: string[] = [];
const picked = new Set<T>();
for (const n of names) {
const lc = n.toLowerCase();
const hits = apps.filter(a => a.rel.toLowerCase() === lc || basename(a.rel).toLowerCase() === lc || a.name.toLowerCase() === lc || (isGlob(n) && new Bun.Glob(n).match(a.rel)));
if (!hits.length) unknown.push(n);
hits.forEach(h => picked.add(h));
}
return { picked: apps.filter(a => picked.has(a)), unknown };
}
// ---- Store app lists (ws apps import): a local cache, gitignored with the rest of .storebound/ ----
export interface StoreAppsCache { profile: string; store: Store; account: string; at: string; apps: StoreApp[] }
export const cacheDir = (root: string): string => join(root, '.storebound', 'workspace');
export const cacheFile = (root: string, a: { store: Store; profile: string }): string => join(cacheDir(root), `apps-${a.store}-${a.profile}.json`);
export function readStoreApps(root: string, accounts: Account[]): { account: string; apps: StoreApp[]; at: string }[] {
const out: { account: string; apps: StoreApp[]; at: string }[] = [];
for (const a of accounts) {
const f = cacheFile(root, a);
if (!existsSync(f)) continue;
try {
const c = JSON.parse(readFileSync(f, 'utf8')) as StoreAppsCache;
if (Array.isArray(c.apps)) out.push({ account: a.id, apps: c.apps, at: c.at });
} catch { /* a broken cache is a cache miss */ }
}
return out;
}
// ---- The desktop's state (state.json in its data folder) <-> the workspace ----
export interface DesktopProject { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string }
export interface DesktopAccount { id: string; label: string; kind: Store; created: string; studio: string | null }
export interface DesktopStudio { id: string; name: string; color: string; logo: string | null; created: string }
export interface DesktopState {
version: number;
projects: DesktopProject[];
accounts: DesktopAccount[];
studios: DesktopStudio[];
overrides: Overrides;
settings?: unknown;
}
/** Where the desktop app keeps state.json (Tauri app data folder of dev.storebound.desktop). */
export function desktopStateFile(env: Record<string, string | undefined> = process.env, platform = process.platform): string {
if (env.STOREBOUND_DESKTOP_DATA) return join(env.STOREBOUND_DESKTOP_DATA, 'state.json');
const id = 'dev.storebound.desktop';
if (platform === 'darwin') return join(homedir(), 'Library', 'Application Support', id, 'state.json');
if (platform === 'win32') return join(env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'), id, 'state.json');
return join(env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), id, 'state.json');
}
/** The desktop's project id of a folder: stable per absolute path (16 hex, like the desktop's own ids). */
export const desktopProjectId = (absPath: string): string => hex16(`project:${absPath}`);
/**
* Workspace -> desktop state (format 2). Accounts carry labels only: their keys go into the desktop's keychain from
* its Accounts screen (the desktop never reads the profiles). Project keys in the overrides become the desktop's ids.
*/
export function toDesktopState(ws: Workspace, apps: AppFolder[], now = new Date().toISOString()): DesktopState {
const accounts = accountsOf(ws);
const idOf = new Map(apps.map(a => [a.id, desktopProjectId(a.path)] as const));
const mapKey = (k: string) => (k.startsWith('project:') && idOf.has(k.slice(8)) ? `project:${idOf.get(k.slice(8))}` : k);
const o = overridesOf(ws, apps);
return {
version: 2,
projects: apps.map(a => ({ id: idOf.get(a.id)!, path: a.path, name: a.name, playAccount: a.playAccount, appleAccount: a.appleAccount, added: now })),
accounts: accounts.map(a => ({ id: a.id, label: a.label ?? a.profile, kind: a.store, created: now, studio: a.studio })),
studios: studiosOf(ws).map(s => ({ id: s.id, name: s.name, color: s.color, logo: null, created: now })),
overrides: {
pairs: o.pairs, unpairs: o.unpairs,
links: o.links.map(l => ({ key: l.key, project: idOf.get(l.project) ?? l.project })),
appStudio: o.appStudio.map(x => ({ key: mapKey(x.key), studio: x.studio })),
ignored: o.ignored.map(mapKey),
},
};
}
/** A profile name for a desktop account: its label as a slug, made unique per store. */
function profileFor(a: DesktopAccount, taken: Set<string>): string {
const base = (slug(a.label).slice(0, 56) || 'account');
let name = taken.has(base) ? `${base}-${a.kind}` : base;
for (let i = 2; taken.has(name); i++) name = `${base}-${a.kind}-${i}`;
taken.add(name);
return name;
}
/**
* Desktop state -> workspace. Folders under `root` become relative paths, others stay absolute. Each account becomes
* a credential profile name (the owner creates ~/.storebound/credentials/<profile>.json; the desktop's keychain is
* never read). Account ids are kept, so the overrides' store app keys stay valid.
*/
export function fromDesktopState(state: DesktopState, root: string): { ws: Workspace; profiles: { profile: string; store: Store; label: string }[] } {
const taken = new Set<string>();
const profile = new Map(state.accounts.map(a => [a.id, profileFor(a, taken)] as const));
const acc = (a: DesktopAccount): WsAccount => ({ store: a.kind, profile: profile.get(a.id)!, label: a.label, id: a.id });
const relOf = new Map(state.projects.map(p => {
const r = posix(relative(root, p.path));
return [p.id, !r || r.startsWith('..') || isAbsolute(r) ? p.path : r] as const;
}));
const proj = (k: string) => (k.startsWith('project:') && relOf.has(k.slice(8)) ? `project:${relOf.get(k.slice(8))}` : k);
const studios: WsStudio[] = state.studios.map(s => ({ id: s.id, name: s.name, ...((STUDIO_COLORS as readonly string[]).includes(s.color) ? { color: s.color as StudioColor } : {}),
accounts: state.accounts.filter(a => a.studio === s.id).map(acc) }));
const ignore: string[] = [];
for (const x of state.overrides?.ignored ?? []) {
if (x.startsWith('account:')) ignore.push(`account:${profile.get(x.slice(8)) ?? x.slice(8)}`);
else ignore.push(proj(x));
}
const ws: Workspace = {
apps: state.projects.map(p => {
const e: WsAppEntry = { path: relOf.get(p.id)! };
if (p.name && p.name !== basename(p.path)) e.name = p.name;
if (p.appleAccount && profile.has(p.appleAccount)) e.apple = profile.get(p.appleAccount)!;
if (p.playAccount && profile.has(p.playAccount)) e.play = profile.get(p.playAccount)!;
return Object.keys(e).length === 1 ? e.path : e;
}),
studios,
accounts: state.accounts.filter(a => !a.studio || !state.studios.some(s => s.id === a.studio)).map(acc),
ignore,
overrides: {
pairs: state.overrides?.pairs ?? [], unpairs: state.overrides?.unpairs ?? [],
links: (state.overrides?.links ?? []).map(l => ({ key: l.key, project: relOf.get(l.project) ?? l.project })),
appStudio: (state.overrides?.appStudio ?? []).map(x => ({ key: proj(x.key), studio: x.studio })),
},
};
return { ws, profiles: state.accounts.map(a => ({ profile: profile.get(a.id)!, store: a.kind, label: a.label })) };
}
/**
* Adds the workspace's desktop state to an existing desktop state: folders by path (an existing project keeps its id
* and accounts), accounts and studios by id (existing ones win), overrides as a union. Nothing is removed.
*/
export function mergeDesktopState(cur: DesktopState, add: DesktopState): { state: DesktopState; added: { projects: number; accounts: number; studios: number; overrides: number } } {
const idMap = new Map<string, string>();
const projects = [...cur.projects];
let np = 0;
for (const p of add.projects) {
const have = projects.find(x => x.path === p.path);
if (have) idMap.set(p.id, have.id);
else { projects.push(p); np++; }
}
const remap = (k: string) => (k.startsWith('project:') && idMap.has(k.slice(8)) ? `project:${idMap.get(k.slice(8))}` : k);
const accounts = [...cur.accounts];
let na = 0;
for (const a of add.accounts) if (!accounts.some(x => x.id === a.id)) { accounts.push(a); na++; }
const studios = [...cur.studios];
let ns = 0;
for (const s of add.studios) if (!studios.some(x => x.id === s.id)) { studios.push(s); ns++; }
const co = { ...NO_OVERRIDES, ...cur.overrides };
const ao = add.overrides;
const uniq = <T>(xs: T[]) => { const seen = new Set<string>(); return xs.filter(x => { const k = JSON.stringify(x); if (seen.has(k)) return false; seen.add(k); return true; }); };
const overrides: Overrides = {
pairs: uniq([...co.pairs, ...ao.pairs]),
unpairs: uniq([...co.unpairs, ...ao.unpairs]),
links: uniq([...co.links, ...ao.links.map(l => ({ key: l.key, project: idMap.get(l.project) ?? l.project }))]),
appStudio: uniq([...co.appStudio, ...ao.appStudio.map(x => ({ key: remap(x.key), studio: x.studio })).filter(x => !co.appStudio.some(y => y.key === x.key))]),
ignored: uniq([...co.ignored, ...ao.ignored.map(remap)]),
};
const count = (o: Overrides) => o.pairs.length + o.unpairs.length + o.links.length + o.appStudio.length + o.ignored.length;
return { state: { ...cur, version: Math.max(cur.version ?? 1, 2), projects, accounts, studios, overrides }, added: { projects: np, accounts: na, studios: ns, overrides: count(overrides) - count(co) } };
}

View file

@ -28,6 +28,7 @@ const only: JsonSchema = { type: 'string', description: 'Comma-separated ids / l
const lang: JsonSchema = { type: 'string', description: 'Comma-separated language ids from the config (default: all)' };
const variant: JsonSchema = { type: 'string', pattern: '^[a-z0-9][a-z0-9-]*$', description: 'A/B variant id from shots.variants (default: the base renders)' };
const source: JsonSchema = { type: 'string', enum: ['web', 'ios-sim', 'android-emu', 'folder'], description: 'Default: from the config' };
const APP_NAMES = '^[^,\\x00-\\x1f]{1,120}(,[^,\\x00-\\x1f]{1,120}){0,99}$';
const opt = (flag: string, v: unknown): string[] => (v === undefined || v === null || v === '' ? [] : [`--${flag}`, String(v)]);
const flag = (name: string, v: unknown): string[] => (v === true ? [`--${name}`] : []);
@ -211,6 +212,25 @@ export const TOOLS: ToolDef[] = [
props: { dir: { type: 'string', pattern: '^(?!/)(?!.*\\.\\.)(?!.*,/)[A-Za-z0-9._ /,-]{1,400}$', description: 'fastlane folder(s) relative to the project, comma-separated (default: fastlane, ios/fastlane, android/fastlane)' },
profile: { type: 'string', enum: ['app', 'game', 'subscription-app'], description: 'Default: game for the GAMES category, else app' } },
args: i => [...opt('dir', i.dir), ...opt('profile', i.profile)] },
{ name: 'workspace_list', title: 'Workspace apps', command: ['ws', 'list'], write: false, network: false,
description: 'Offline: the apps of the storebound.workspace.json above the project (app folders from its globs, store-only apps from `ws apps import`), paired across iOS and Android by the desktop\'s rules, with studios and accounts (credential profile names and whether their keys are there; never a key).',
props: { all: { type: 'boolean', default: false, description: 'Also the ignored apps' }, json: { type: 'boolean', default: false } },
args: i => [...flag('all', i.all), ...flag('json', i.json)] },
{ name: 'workspace_status', title: 'Workspace portfolio status', command: ['ws', 'status'], write: false, network: true,
description: 'Read-only portfolio table of every app in the workspace across both stores: the version that reaches users and the next one (build > testing > review > live > rollout %), catalog parity, offline check, read in parallel with each account\'s credential profile.',
props: { apps: { type: 'string', pattern: APP_NAMES, description: 'Comma-separated app names or folders (default: all)' },
offline: { type: 'boolean', default: false, description: 'Skip the store reads' }, json: { type: 'boolean', default: false } },
args: i => [...opt('apps', i.apps), ...flag('offline', i.offline), ...flag('json', i.json)] },
{ name: 'release_status', title: 'Release trains', command: ['release', 'status'], write: false, network: true,
description: 'Read-only release trains: per app, both stores on one train per version (build > testing > review > live > rollout %), the version that reaches users and the next one; versions lists every version. In an app folder that app, in a workspace every app (or app).',
props: { app: { type: 'string', pattern: APP_NAMES, description: 'Workspace app names (comma-separated)' },
versions: { type: 'boolean', default: false }, json: { type: 'boolean', default: false } },
args: i => [...opt('app', i.app), ...flag('versions', i.versions), ...flag('json', i.json)] },
{ name: 'release_plan', title: 'Release plan for a version', command: ['release', 'plan'], write: false, network: true,
description: 'Read-only: what is left for one version on each store, in fix order: config problems (check), the version on the store, store blockers (validate), the next move (owner steps such as submitting or releasing are named, never done), warnings.',
props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,3}$' }, app: { type: 'string', pattern: APP_NAMES, description: 'Workspace app names (comma-separated)' },
no_validate: { type: 'boolean', default: false, description: 'Skip the store readiness read' }, json: { type: 'boolean', default: false } },
required: ['version'], args: i => [String(i.version), ...opt('app', i.app), ...flag('no-validate', i.no_validate), ...flag('json', i.json)] },
];
/** CLI flags / commands that must never be reachable through MCP. Tests assert none of the tools can produce them. */

View file

@ -47,6 +47,7 @@ export const INSTRUCTIONS = [
'Write tools default to dry_run: show the dry run to the owner and only call again with dry_run false after they agree.',
'Nothing here submits for review, releases, cancels, deletes or sends anything public (review replies, tester invitations, price changes, experiment starts): tell the owner which terminal command or console click does that.',
'Credentials come only from env or .storebound/ in the project; never ask for keys in chat or write them into files.',
'Many apps: workspace_list / workspace_status read the storebound.workspace.json above the project; release_status and release_plan show both stores on one train per version.',
'Run `check` (offline) and `validate` (read-only) before writes. Long uploads (images, screenshots) are better run in a terminal with a log.',
].join(' ');

171
cli/release.ts Normal file
View file

@ -0,0 +1,171 @@
// `storebound release`: release trains from the terminal, read-only. The same stages as the desktop's Releases tab
// (cli/lib/train.ts, cli/lib/app-status.ts are shared with it).
// release status [--app a,b] [--versions] [--json]
// per app: the version that reaches users and the next one, both stores on one train
// (build -> testing -> review -> live -> rollout %); --versions lists every version the stores know
// release plan <version> [--app a] [--no-validate] [--json]
// what is left for <version> on each store, in fix order: config problems (check), the version on the store,
// store blockers (validate), the next move (owner steps are named, never done), warnings
// In an app folder: that app (its own credentials). In a workspace (storebound.workspace.json above): every app, or
// --app a,b, with the credential profiles of the workspace.
import { existsSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import type { Args } from './lib/args';
import { emptyStatus, fillAppStatus, lastLine, pool } from './lib/app-status';
import { CONFIG_NAMES } from './lib/config';
import type { AppStatus, ReleaseTrain } from './lib/desktop-protocol';
import { log, printJson, warn } from './lib/log';
import { runCommand, type RunResult } from './lib/runner';
import { textTable } from './lib/table';
import { laneOf, laneText, type PlanStep, releasePlan, type ReleasePlan, trackText, versionHistory } from './lib/train';
import type { Finding } from './lib/validate-rules';
import { findWorkspace, loadWorkspace, resolveApps, selectApps } from './lib/workspace';
import { appDir, appEnv, workspaceApps } from './workspace';
interface Target { name: string; dir: string; virtual: boolean; env: Record<string, string>; problems: string[] }
const USAGE = 'usage: storebound release status [--app a,b] [--versions] [--json] | release plan <version> [--app a] [--no-validate] [--json]';
function configDir(from: string): string | null {
for (let d = resolve(from); ; d = dirname(d)) {
if (CONFIG_NAMES.some(n => existsSync(join(d, n)))) return d;
if (dirname(d) === d) return null;
}
}
/** The apps to read: this app folder, or the workspace's apps (filtered by --app). */
async function targets(args: Args): Promise<{ list: Target[]; concurrency: number }> {
const cwd = process.cwd();
const here = configDir(cwd);
const wsFile = findWorkspace(cwd, args.get('workspace'));
// an app folder wins unless --app asks for the workspace (or the workspace file is closer than the config)
if (here && !args.get('app') && (!wsFile || dirname(wsFile).length <= here.length)) {
return { list: [{ name: here.split(/[\\/]/).pop() ?? here, dir: here, virtual: false, env: {}, problems: [] }], concurrency: 1 };
}
if (!wsFile) throw new Error('no storebound.config.ts here and no storebound.workspace.json above (run it in an app folder or a workspace)');
const l = await loadWorkspace(cwd, args.get('workspace'));
const n = Math.min(8, Math.max(1, l.ws.concurrency ?? 4));
const { apps: folders } = resolveApps(l);
const summaries = new Map<string, AppStatus['summary']>();
await pool(folders, n, async f => {
const r = await runCommand(['inspect', '--json'], { cwd: f.path, machine: true }).result;
if (r.code === 0 && r.data) summaries.set(f.id, r.data as AppStatus['summary']);
});
const { apps, accounts } = workspaceApps(l, summaries);
const { picked, unknown } = selectApps(apps.filter(a => !a.ignored), args.list('app'));
if (unknown.length) throw new Error(`--app: no app named ${unknown.join(', ')} (storebound ws list shows the names)`);
return { list: picked.map(a => { const { env, problems } = appEnv(a.unified, accounts); return { name: a.name, dir: appDir(a), virtual: a.virtual, env, problems }; }), concurrency: n };
}
const exec = (env: Record<string, string>) => (argv: string[], cwd: string): Promise<RunResult> => runCommand(argv, { cwd, env, machine: true }).result;
async function readLive(t: Target): Promise<AppStatus> {
const e = emptyStatus(t.dir);
if (t.virtual) e.virtual = true;
try { await fillAppStatus(e, t.dir, { live: true, virtual: t.virtual, exec: exec(t.env) }); } catch (err) { e.errors.push((err as Error).message); }
if (e.summary?.name) t.name = e.summary.name;
return e;
}
export interface TrainRow { app: string; version: string; which: 'current' | 'next' | 'other'; ios: string; android: string }
/** The trains of one app to show: current + next (the desktop's portfolio), or every version. */
export function trainsOf(s: AppStatus, all: boolean): { which: TrainRow['which']; train: ReleaseTrain }[] {
if (all) {
const cur = s.release.current?.version, next = s.release.next?.version;
return versionHistory(s.release.all ?? []).map(t => ({ which: t.version === cur ? 'current' as const : t.version === next ? 'next' as const : 'other' as const, train: t }));
}
return [...(s.release.current ? [{ which: 'current' as const, train: s.release.current }] : []), ...(s.release.next ? [{ which: 'next' as const, train: s.release.next }] : [])];
}
const cell = (store: 'ios' | 'android', t: ReleaseTrain, s: AppStatus): string => {
if (s.storeErrors[store]) return 'unreadable';
const on = store === 'ios' ? s.summary?.apple : s.summary?.play;
if (!on) return '';
const r = t[store];
if (!r) return '-';
const extra = [r.build ? `build ${r.build}` : '', store === 'android' && r.track && r.track !== 'production' ? r.track : ''].filter(Boolean).join(', ');
return `${laneText(laneOf(store, r))}${extra ? ` (${extra})` : ''}`;
};
async function status(args: Args): Promise<void> {
const { list, concurrency } = await targets(args);
const all = args.has('versions');
const read = await pool(list, concurrency, async t => ({ t, s: await readLive(t) }));
if (args.has('json')) {
printJson({ apps: read.map(({ t, s }) => ({
app: t.name, folder: t.virtual ? null : t.dir, errors: [...t.problems, ...s.errors], storeErrors: s.storeErrors,
trains: trainsOf(s, all).map(({ which, train }) => ({ which, version: train.version, ios: train.ios, android: train.android,
lanes: { ios: laneOf('ios', train.ios), android: laneOf('android', train.android) } })),
})), at: new Date().toISOString() });
} else {
const rows: string[][] = [];
for (const { t, s } of read) {
const trains = trainsOf(s, all);
const unread = Object.keys(s.storeErrors).length > 0;
if (!trains.length) rows.push([t.name, '', '', s.errors[0] ? `error: ${s.errors[0]}` : unread ? 'not read (see the warnings)' : 'no version on either store yet', '']);
for (const { which, train } of trains) rows.push([t.name, train.version, which === 'other' ? '' : which, cell('ios', train, s), cell('android', train, s)]);
for (const p of [...t.problems, ...s.errors.slice(trains.length ? 0 : 1), ...Object.entries(s.storeErrors).map(([k, v]) => `${k}: ${v}`)]) warn('release', `${t.name}: ${p}`);
}
console.log(textTable(['app', 'version', 'train', 'App Store', 'Google Play'], rows));
log('release', 'stages: build > testing > review > live > rollout (%); owner steps (submit, release, rollout) stay with the owner');
}
if (read.some(({ s }) => s.errors.length || s.storeErrors.ios || s.storeErrors.android)) process.exitCode = 1;
}
const KIND: Record<PlanStep['kind'], string> = { config: 'CONFIG ', store: 'STORE ', blocker: 'BLOCKER', owner: 'OWNER ', wait: 'wait ', warning: 'warn ', done: 'done ' };
export function formatPlan(app: string, p: ReleasePlan): string {
const out: string[] = [`${app} ${p.version}${p.done ? ': live everywhere, nothing left' : ''}`];
let i = 0;
const line = (s: PlanStep) => ` ${String(++i).padStart(2)}. ${KIND[s.kind]} ${s.text}${s.fix ? `\n -> ${s.fix}` : ''}`;
if (p.shared.length) { out.push(' both stores (fix first):'); out.push(...p.shared.map(line)); }
for (const sp of [p.ios, p.android]) {
if (!sp) continue;
out.push(` ${sp.store === 'ios' ? 'App Store' : 'Google Play'}: ${sp.release ? `${laneText(sp.lane)} [${trackText(sp.lane)}]` : 'not on the store'}`);
out.push(...sp.steps.map(line));
}
for (const u of p.unknown) out.push(` unknown: ${u}`);
return out.join('\n');
}
async function plan(args: Args): Promise<void> {
const version = args._[1];
if (!version || !/^\d+(\.\d+){0,3}$/.test(version)) throw new Error('release plan <version>, e.g. release plan 2.4.0');
const { list, concurrency } = await targets(args);
const plans = await pool(list, concurrency, async t => {
const s = await readLive(t);
const check = s.check ? { problems: s.check.problems, warnings: s.check.warnings } : null;
let validate: Finding[] | null = null;
// validate only while something is not yet submitted on a store (it reads the editable version / the Play edit)
const pre = releasePlan({ version, platforms: { ios: !!s.summary?.apple, android: !!s.summary?.play }, check, validate: [], releases: s.release.all ?? null, storeErrors: s.storeErrors });
const needs = [pre.ios, pre.android].some(x => x && !x.done && (!x.release || ['draft', 'testing', 'rejected', 'other'].includes(x.release.phase)));
if (needs && !args.has('no-validate') && !t.virtual && s.summary) {
if (!args.has('json')) log('release', `${t.name}: validate (read-only, both stores)`);
const r = await exec(t.env)(['validate', '--json', '--no-health'], t.dir);
const d = r.data as { findings?: Finding[] } | undefined;
if (d?.findings) validate = d.findings;
else s.errors.push(`validate: ${lastLine(r.out) || `exit ${r.code}`}`);
} else if (!needs) validate = [];
const p = releasePlan({ version, platforms: { ios: !!s.summary?.apple, android: !!s.summary?.play }, check, validate, releases: s.summary ? s.release.all ?? null : null, storeErrors: s.storeErrors });
if (args.has('no-validate') && needs) p.unknown = p.unknown.map(u => (u.startsWith('store readiness') ? 'store readiness not checked (--no-validate)' : u));
return { t, s, p };
});
if (args.has('json')) printJson({ version, apps: plans.map(({ t, s, p }) => ({ app: t.name, folder: t.virtual ? null : t.dir, errors: [...t.problems, ...s.errors], plan: p })) });
else {
for (const { t, s, p } of plans) {
console.log(formatPlan(t.name, p));
for (const e of [...t.problems, ...s.errors]) warn('release', `${t.name}: ${e}`);
console.log('');
}
}
if (plans.some(({ s }) => s.errors.length)) process.exitCode = 1;
}
export async function run(args: Args): Promise<void> {
const sub = args._[0];
if (sub === 'status') return status(args);
if (sub === 'plan') return plan(args);
console.error(USAGE);
process.exit(2);
}

View file

@ -19,7 +19,7 @@ import { CONFIG_NAMES } from './lib/config';
import {
DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult, type VirtualProject,
} from './lib/desktop-protocol';
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './lib/portfolio';
import { emptyStatus, fillAppStatus, lastLine } from './lib/app-status';
import { RENDER_FILE_RE } from './lib/project-files';
import { detectTools } from './lib/tools';
import { compiled, pickCallEnv, runCommand, type RunOptions, type Running } from './lib/runner';
@ -39,8 +39,8 @@ const lang = { type: 'string', pattern: '^[A-Za-z0-9_-]{1,20}(,[A-Za-z0-9_-]{1,2
export const PRICE_SHEET_RE = /^(?!-)[^\x00-\x1f]{1,1000}\.[cC][sS][vV]$/;
/** MCP tools the desktop profile leaves out (sending builds to testers on Play, release state changes: the window has
* the owner actions for those). */
export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_release']);
* the owner actions for those; workspace and release-train reads: the window has portfolio.status for those). */
export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_release', 'workspace_list', 'workspace_status', 'release_status', 'release_plan']);
/** Words no desktop method name may contain. */
export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i;
@ -420,7 +420,7 @@ export class Session {
const raw = list[i] as unknown;
// a store-only app: { key: "store:...", virtual: { name, apple?, play? } }
const virt = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? raw as { key?: unknown; virtual?: unknown } : null;
const e: AppStatus = { project: virt ? String(virt.key ?? '') : String(raw), ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] };
const e: AppStatus = emptyStatus(virt ? String(virt.key ?? '') : String(raw));
out[i] = e;
try {
let dir: string;
@ -429,28 +429,7 @@ export class Session {
dir = virtualDir(checkVirtual(virt.virtual));
e.virtual = true;
} else { dir = checkProject(raw); e.project = dir; }
const summary = e.summary = await this.inspect(dir, env, id);
e.app = appIdentity(summary);
e.catalog = catalogParity(summary);
if (virt) e.check = { ok: true, problems: [], warnings: [] };
else {
const c = await this.track(id, this.run(['check', '--json'], { cwd: dir, env, machine: true })).result;
const cd = c.data as { ok?: boolean; problems?: string[]; warnings?: string[] } | undefined;
e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] };
}
if (live) {
const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => {
const r = await this.track(id, this.run(argv, { cwd: dir, env, machine: true })).result;
return r.code === 0 && r.data !== undefined ? { data: r.data } : { error: lastLine(r.out) || `exit ${r.code}` };
};
const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]);
if (apple?.error) e.storeErrors.ios = apple.error;
if (play?.error) e.storeErrors.android = play.error;
const ios = apple?.data ? appleReleases(apple.data) : [], android = play?.data ? playReleases(play.data) : [];
e.release = { source: 'live', ...releaseTrains(ios, android), all: [...ios, ...android] };
e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined);
}
e.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true);
await fillAppStatus(e, dir, { live, virtual: !!virt, exec: (argv, cwd) => this.track(id, this.run(argv, { cwd, env, machine: true })).result });
} catch (err) {
if (this.cancelled.has(id)) throw err;
e.errors.push((err as Error).message);
@ -468,7 +447,6 @@ export class Session {
/** Store target keys of store-only apps ("store:ios:<account>:<app id>:<bundle id>;android:<account>:<package>"). */
export const STORE_KEY_RE = /^store:[A-Za-z0-9:;._-]{1,400}$/;
const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
/** Optional local tools with versions; app-managed copies (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME) included. */
export function localTools(): Json {

450
cli/workspace.ts Normal file
View file

@ -0,0 +1,450 @@
// `storebound ws`: many apps and studios from one folder (storebound.workspace.json; model: cli/lib/workspace.ts).
// ws init [--dry] [--force] find the app folders below and write storebound.workspace.json
// ws list [--all] [--json] apps (folders + store-only apps from `ws apps import`), studios, accounts
// ws status [--offline] [--apps a,b] [--json] portfolio table: apps x stores (release trains, catalog, check), read
// in parallel (concurrency from the workspace, default 4)
// ws check | ws validate [--apps a,b] [--json] the offline check / read-only store readiness of every app
// ws run <command> [args] [--apps a,b | --all] [--apply]
// any read command per app; write commands run as dry runs unless
// --apply; submit / release / rollout / send / start / stop never
// ws apps import --account <profile> [--json] the apps the account sees -> local cache, paired with the folders
// (the desktop's rules: cli/lib/identity.ts)
// ws desktop export [--out f | --merge [--apply]] the workspace as the desktop app's state (labels, never keys)
// ws desktop import [--state f] [--out f] [--dry] [--force]
// the desktop's studios, accounts, folders and overrides -> workspace
// Credentials: per account a credential profile (cli/lib/credentials.ts), handed to each app's child command as env.
// Nothing here prints a secret.
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, relative, resolve, sep } from 'node:path';
import type { Args } from './lib/args';
import { emptyStatus, fillAppStatus, lastLine, pool } from './lib/app-status';
import { CONFIG_NAMES } from './lib/config';
import { PROFILE_KEYS, profileEnv, profileStatus } from './lib/credentials';
import type { AppStatus, AppsListResult } from './lib/desktop-protocol';
import { buildApps, type UnifiedApp } from './lib/identity';
import { log, printJson, warn } from './lib/log';
import { runCommand, type RunResult } from './lib/runner';
import { textTable } from './lib/table';
import { laneOf, laneText } from './lib/train';
import {
type Account, accountsOf, type AppFolder, cacheFile, type DesktopState, desktopStateFile, fromDesktopState, type LoadedWorkspace, loadWorkspace, mergeDesktopState,
overridesOf, readStoreApps, resolveApps, selectApps, type Store, type StoreAppsCache, studiosOf, toDesktopState, type Workspace, WORKSPACE_NAMES,
} from './lib/workspace';
import { FORBIDDEN_ARGS, TOOLS } from './mcp-tools';
import { checkVirtual, VIRTUAL_READS, virtualDir } from './serve';
/** One app of the workspace: a folder or a store-only app, with the credentials env its commands get. */
export interface WsApp { key: string; rel: string; name: string; studio: string | null; dir: string | null; virtual: boolean; ignored: boolean; unified: UnifiedApp<AppFolder>; summary: AppStatus['summary'] }
const USAGE = `usage: storebound ws <init | list | status | check | validate | run <command> | apps import --account <profile> | desktop export | desktop import>
common: --workspace <file or folder> --apps a,b --json --concurrency 1-8`;
// ---- building blocks (exported for tests) ----
/** Credentials env for one app: the apple account's ASC_* and the play account's PLAY_* from their profiles. */
export function appEnv(u: UnifiedApp<AppFolder>, accounts: Account[]): { env: Record<string, string>; problems: string[] } {
const env: Record<string, string> = { STOREBOUND_PROFILE: '' };
const problems: string[] = [];
const profileOf = (store: Store): string | null => {
const fromFolder = store === 'apple' ? u.project?.appleProfile : u.project?.playProfile;
if (fromFolder) return fromFolder;
const ref = store === 'apple' ? u.ios : u.android;
return ref ? accounts.find(a => a.id === ref.account)?.profile ?? null : null;
};
for (const store of ['apple', 'play'] as const) {
const p = profileOf(store);
if (!p) continue;
try {
const all = profileEnv(p);
const keys = store === 'apple' ? ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8'] : ['PLAY_SERVICE_ACCOUNT'];
const got = keys.filter(k => all[k]);
if (!got.length) problems.push(`credential profile ${p}: no ${store === 'apple' ? 'ASC_KEY_ID / ASC_ISSUER_ID' : 'PLAY_SERVICE_ACCOUNT'}`);
for (const k of got) env[k] = all[k]!;
} catch (e) { problems.push((e as Error).message); }
}
return { env, problems };
}
/** Folder apps and store-only apps of the workspace, paired by the desktop's rules. */
export function workspaceApps(l: LoadedWorkspace, summaries: Map<string, AppStatus['summary']>): { apps: WsApp[]; accounts: Account[]; warnings: string[] } {
const { apps: folders, warnings } = resolveApps(l);
const accounts = accountsOf(l.ws);
const unified = buildApps<AppFolder>({
projects: folders, summaryOf: p => summaries.get(p.id) ?? null, accounts,
storeApps: readStoreApps(l.root, accounts), overrides: overridesOf(l.ws, folders),
});
const apps: WsApp[] = unified.map(u => ({
key: u.key, rel: u.project ? u.project.rel : u.target, name: u.project ? (summaries.get(u.project.id)?.name ?? u.name) : u.name, studio: u.studio,
dir: u.project?.path ?? null, virtual: !u.project, ignored: u.ignored, unified: u, summary: u.project ? summaries.get(u.project.id) ?? null : null,
}));
return { apps, accounts, warnings };
}
/** The directory a command for this app runs in: its folder, or a generated config for a store-only app. */
export function appDir(a: WsApp): string {
if (a.dir) return a.dir;
const u = a.unified;
return virtualDir(checkVirtual({ name: u.name, ...(u.ios ? { apple: { bundleId: u.ios.app.bundleId, appId: u.ios.app.id } } : {}), ...(u.android ? { play: { packageName: u.android.app.id } } : {}) }));
}
const words = (argv: string[]): string[] => { const w: string[] = []; for (const a of argv) { if (a.startsWith('-')) break; w.push(a); } return w; };
/**
* Whether `ws run` may run this command, and whether it writes (then it gets --dry unless --apply). Allowed: the MCP
* tool set (cli/mcp-tools.ts) plus `inspect`; never anything that submits, releases, rolls out, sends, starts / stops,
* removes or invites, and never --yes.
*/
export function runPolicy(argv: string[]): { ok: true; write: boolean } | { ok: false; why: string } {
const w = words(argv);
if (!w.length) return { ok: false, why: 'no command (e.g. ws run validate --play)' };
const bad = argv.find(a => FORBIDDEN_ARGS.includes(a) || ['--manual-release', 'submit', 'publish', 'distribute', '--phased'].includes(a));
if (bad) return { ok: false, why: `"${bad}" is an owner step: run it in the app folder yourself` };
if (w.includes('release') || w.includes('rollout')) return { ok: false, why: 'release and rollout commands are owner steps: run them in the app folder yourself' };
if (w[0] === 'ws') return { ok: false, why: 'ws inside ws run' };
if (w.length === 1 && w[0] === 'inspect') return { ok: true, write: false };
const cmdWords = (c: string[]) => words(c);
const matches = TOOLS.filter(t => { const cw = cmdWords(t.command); return cw.length <= w.length && cw.every((x, i) => w[i] === x); });
if (!matches.length) return { ok: false, why: `${w.join(' ')}: not a command ws run offers (read commands and dry runs of the MCP tool set, plus inspect)` };
const longest = Math.max(...matches.map(t => cmdWords(t.command).length));
const same = matches.filter(t => cmdWords(t.command).length === longest);
// the variant whose extra flags are all present (health --weekly), else the plain one
const variant = same.filter(t => t.command.slice(longest).every(f => argv.includes(f))).sort((a, b) => b.command.length - a.command.length)[0] ?? same[0]!;
const write = variant.write || (variant.args?.({}) ?? []).includes('--dry');
return { ok: true, write };
}
// ---- output helpers ----
const storeCell = (s: AppStatus, store: 'ios' | 'android'): string => {
const err = s.storeErrors[store];
if (err) return 'unreadable';
const has = store === 'ios' ? s.summary?.apple : s.summary?.play;
if (!has) return '';
if (s.release.source !== 'live') return 'offline';
const r = s.release.current?.[store] ?? null;
return r ? `${r.version} ${laneText(laneOf(store, r))}` : 'not live';
};
const nextCell = (s: AppStatus): string => {
const n = s.release.next;
if (!n) return '';
const part = (store: 'ios' | 'android') => { const r = n[store]; return r ? `${store === 'ios' ? 'iOS' : 'Android'} ${laneText(laneOf(store, r))}` : ''; };
return `${n.version}: ${[part('ios'), part('android')].filter(Boolean).join(', ')}`;
};
const catalogCell = (s: AppStatus): string => {
const c = s.catalog;
if (!c) return '';
if (!c.products && !c.subscriptions) return '-';
const issues = c.onlyIos.length + c.onlyAndroid.length + c.missingIos.length + c.missingAndroid.length;
return `${c.products + c.subscriptions} items${c.checked === 'live' ? (issues ? `, ${issues} mismatched` : ', in parity') : ''}`;
};
async function loadAll(args: Args): Promise<LoadedWorkspace> {
return loadWorkspace(process.cwd(), args.get('workspace'));
}
function concurrencyOf(args: Args, ws: Workspace): number {
const n = args.num('concurrency', ws.concurrency ?? 4);
if (!Number.isInteger(n) || n < 1 || n > 8) throw new Error('--concurrency: 1 to 8');
return n;
}
function exec(env: Record<string, string>) {
return (argv: string[], cwd: string): Promise<RunResult> => runCommand(argv, { cwd, env, machine: true }).result;
}
/** Offline summaries of the folder apps (inspect --json), for pairing and names. */
async function summariesOf(folders: AppFolder[], n: number): Promise<Map<string, AppStatus['summary']>> {
const m = new Map<string, AppStatus['summary']>();
await pool(folders, n, async f => {
const r = await runCommand(['inspect', '--json'], { cwd: f.path, machine: true }).result;
if (r.code === 0 && r.data) m.set(f.id, r.data as AppStatus['summary']);
});
return m;
}
async function prepared(args: Args, o: { includeIgnored?: boolean } = {}) {
const l = await loadAll(args);
const n = concurrencyOf(args, l.ws);
const { apps: folders } = resolveApps(l);
const summaries = await summariesOf(folders, n);
const { apps, accounts, warnings } = workspaceApps(l, summaries);
const visible = apps.filter(a => o.includeIgnored || !a.ignored);
const { picked, unknown } = selectApps(visible, args.list('apps'));
if (unknown.length) throw new Error(`--apps: no app named ${unknown.join(', ')} (ws list shows the names)`);
return { l, n, apps: picked, all: apps, accounts, warnings };
}
// ---- commands ----
/** App folders below `root` (depth <= 4), as the globs ws init writes: "parent/*" when a folder holds several. */
export function discoverApps(root: string, depth = 4): string[] {
const found: string[] = [];
const walk = (dir: string, d: number) => {
if (CONFIG_NAMES.some(n => existsSync(join(dir, n))) && dir !== root) { found.push(relative(root, dir).split(sep).join('/')); return; }
if (d === 0) return;
let entries: string[] = [];
try { entries = readdirSync(dir); } catch { return; }
for (const e of entries.sort()) {
if (e.startsWith('.') || e === 'node_modules' || e === 'build' || e === 'dist') continue;
const p = join(dir, e);
try { if (statSync(p).isDirectory()) walk(p, d - 1); } catch { /* unreadable */ }
}
};
walk(root, depth);
const byParent = new Map<string, string[]>();
for (const f of found) { const parent = f.includes('/') ? f.slice(0, f.lastIndexOf('/')) : ''; byParent.set(parent, [...(byParent.get(parent) ?? []), f]); }
const out: string[] = [];
for (const [parent, list] of byParent) out.push(...(list.length > 1 ? [parent ? `${parent}/*` : '*'] : list));
return out.sort();
}
async function init(args: Args): Promise<void> {
const root = process.cwd();
const file = join(root, 'storebound.workspace.json');
const existing = WORKSPACE_NAMES.map(n => join(root, n)).find(existsSync);
if (existing && !args.has('force')) throw new Error(`${existing} exists (--force overwrites)`);
const apps = discoverApps(root);
const ws: Workspace = { apps, studios: [], accounts: [], ignore: [], overrides: { pairs: [], unpairs: [], links: [], appStudio: [] }, concurrency: 4 };
const text = JSON.stringify(ws, null, 2) + '\n';
if (args.has('dry')) { console.log(text); log('ws', `dry run: ${file} not written (${apps.length} app folder pattern(s))`); return; }
writeFileSync(file, text);
const gi = join(root, '.gitignore');
const giText = existsSync(gi) ? readFileSync(gi, 'utf8') : '';
if (!/^\.storebound\/?$/m.test(giText)) writeFileSync(gi, giText + (giText && !giText.endsWith('\n') ? '\n' : '') + '.storebound/\n');
log('ws', `wrote ${file}: ${apps.length ? apps.join(', ') : 'no app folders found yet (add them under "apps")'}`);
log('ws', 'next: add studios and accounts by credential profile (~/.storebound/credentials/<profile>.json), then storebound ws list');
}
async function list(args: Args): Promise<void> {
const { l, apps, accounts, warnings } = await prepared(args, { includeIgnored: args.has('all') });
const studios = studiosOf(l.ws);
const sName = (id: string | null) => (id ? studios.find(s => s.id === id)?.name ?? id : '');
const profiles = accounts.map(a => ({ ...profileStatus(a.profile), store: a.store, id: a.id, studio: a.studio, label: a.label ?? null }));
if (args.has('json')) {
printJson({ workspace: l.file, studios, accounts: profiles,
apps: apps.map(a => ({ name: a.name, key: a.key, folder: a.dir, studio: a.studio, pairing: a.unified.pairing, ignored: a.ignored,
ios: a.unified.ios ? { account: a.unified.ios.account, appId: a.unified.ios.app.id, bundleId: a.unified.ios.app.bundleId } : null,
android: a.unified.android ? { account: a.unified.android.account, packageName: a.unified.android.app.id } : null,
accounts: { apple: a.unified.project?.appleProfile ?? null, play: a.unified.project?.playProfile ?? null } })),
warnings });
return;
}
log('ws', `${l.file}: ${apps.length} app(s), ${studios.length} studio(s), ${accounts.length} account(s)`);
console.log(textTable(['app', 'studio', 'folder', 'iOS', 'Android', 'accounts', 'pairing'], apps.map(a => {
const u = a.unified;
// the config's ids; "(store app <id>)" once `ws apps import` found the app on the account
const ios = [a.summary?.apple?.bundleId ?? u.ios?.app.bundleId, u.ios ? `(store ${u.ios.app.id})` : ''].filter(Boolean).join(' ');
const android = [a.summary?.play?.packageName ?? u.android?.app.id, u.android ? '(store)' : ''].filter(Boolean).join(' ');
return [a.name + (a.ignored ? ' (ignored)' : ''), sName(a.studio), a.dir ? a.rel : '(store only)', ios, android,
[u.project?.appleProfile, u.project?.playProfile].filter(Boolean).join(', '), u.pairing];
})));
if (profiles.length) {
console.log('');
console.log(textTable(['account', 'store', 'studio', 'profile', 'keys'], profiles.map(p => [p.label ?? p.profile, p.store, sName(p.studio), p.profile,
p.source === 'missing' ? 'missing' : p.source === 'invalid' ? `invalid: ${p.error}` : (p.store === 'apple' ? p.apple : p.play) ? `ok (${p.source})` : `no ${p.store} keys in it`])));
}
for (const w of warnings) warn('ws', w);
}
export interface WsStatusRow { name: string; key: string; folder: string | null; studio: string | null; status: AppStatus; problems: string[] }
async function status(args: Args): Promise<void> {
const { l, n, apps, accounts } = await prepared(args);
const live = !args.has('offline');
const studios = studiosOf(l.ws);
let done = 0;
const rows = await pool(apps, n, async (a): Promise<WsStatusRow> => {
const e = emptyStatus(a.dir ?? a.key);
if (a.virtual) e.virtual = true;
const { env, problems } = appEnv(a.unified, accounts);
try { await fillAppStatus(e, appDir(a), { live, virtual: a.virtual, exec: exec(env) }); } catch (err) { e.errors.push((err as Error).message); }
if (!args.has('json')) log('ws', `${++done}/${apps.length} ${a.name}`);
return { name: a.name, key: a.key, folder: a.dir, studio: a.studio, status: e, problems: live ? problems : [] };
});
if (args.has('json')) { printJson({ workspace: l.file, live, apps: rows, at: new Date().toISOString() }); }
else {
const sName = (id: string | null) => (id ? studios.find(s => s.id === id)?.name ?? id : '');
console.log(textTable(['app', 'studio', 'App Store', 'Google Play', 'next', 'catalog', 'check', 'notes'], rows.map(r => {
const s = r.status;
const notes = [...r.problems, ...s.errors, ...Object.entries(s.storeErrors).map(([k, v]) => `${k}: ${v}`)].join('; ');
return [r.name, sName(r.studio), storeCell(s, 'ios'), storeCell(s, 'android'), nextCell(s), catalogCell(s),
s.check ? (s.check.ok ? `ok${s.check.warnings.length ? ` (${s.check.warnings.length} warn)` : ''}` : `${s.check.problems.length} problem(s)`) : '', notes.slice(0, 160)];
})));
if (!live) log('ws', 'offline: store states not read (drop --offline to read both stores)');
}
if (rows.some(r => !r.status.ok)) process.exitCode = 1;
}
/** Runs one command in every picked app (bounded parallel), output buffered per app. */
async function runEach(args: Args, argv: string[], o: { json: boolean; label: string }) {
const { n, apps, accounts } = await prepared(args);
// store-only apps (no folder) take the store reads the desktop allows them (serve.ts VIRTUAL_READS) and inspect
const w = words(argv);
const storeRead = w.join(' ') === 'inspect' || TOOLS.some(t => VIRTUAL_READS.has(t.name) && words(t.command).join(' ') === w.join(' '));
const folderOnly = !storeRead;
const targets = apps.filter(a => !a.virtual || !folderOnly);
const skipped = apps.filter(a => !targets.includes(a));
const results = await pool(targets, n, async a => {
const { env, problems } = appEnv(a.unified, accounts);
const r = await runCommand(o.json ? [...argv, '--json'] : argv, { cwd: appDir(a), env, machine: o.json }).result;
return { app: a, r, problems };
});
return { results, skipped };
}
async function checkAll(args: Args, kind: 'check' | 'validate'): Promise<void> {
const extra = kind === 'validate' ? [...(args.has('apple') ? ['--apple'] : []), ...(args.has('play') ? ['--play'] : []), ...(args.has('no-health') ? ['--no-health'] : [])] : [];
const { results, skipped } = await runEach(args, [kind, ...extra], { json: true, label: kind });
const rows = results.map(({ app, r, problems }) => {
const d = r.data as { ok?: boolean; problems?: string[]; warnings?: string[]; blockers?: number; findings?: { level: string; msg: string; store: string }[] } | undefined;
if (kind === 'check') return { app: app.name, folder: app.dir, ok: !!d?.ok, problems: d?.problems ?? (d ? [] : [lastLine(r.out) || `exit ${r.code}`]), warnings: d?.warnings ?? [], credentialProblems: [] as string[] };
const blockers = d?.findings?.filter(f => f.level === 'blocker') ?? [];
return { app: app.name, folder: app.dir, ok: !!d && !d.blockers, blockers: d ? d.blockers ?? 0 : null, findings: d?.findings ?? [], error: d ? null : lastLine(r.out) || `exit ${r.code}`, first: blockers[0] ? `${blockers[0].store}: ${blockers[0].msg}` : '', credentialProblems: problems };
});
if (args.has('json')) printJson({ [kind]: rows, skipped: skipped.map(a => a.name) });
else {
if (kind === 'check') console.log(textTable(['app', 'result', 'problems', 'warnings', 'first problem'], rows.map(x => { const c = x as { app: string; ok: boolean; problems: string[]; warnings: string[] }; return [c.app, c.ok ? 'ok' : 'PROBLEMS', c.problems.length, c.warnings.length, (c.problems[0] ?? '').slice(0, 100)]; })));
else console.log(textTable(['app', 'result', 'blockers', 'first blocker'], rows.map(x => { const v = x as { app: string; ok: boolean; blockers: number | null; first: string; error: string | null }; return [v.app, v.blockers === null ? 'unreadable' : v.ok ? 'ready' : 'BLOCKED', v.blockers ?? '?', (v.error ?? v.first).slice(0, 110)]; })));
for (const x of rows) for (const p of x.credentialProblems) warn('ws', `${x.app}: ${p}`);
if (skipped.length) log('ws', `store-only apps skipped (no app folder): ${skipped.map(a => a.name).join(', ')}`);
}
if (rows.some(x => !x.ok)) process.exitCode = 1;
}
async function runCmd(args: Args): Promise<void> {
// the command line after `ws run`, minus the ws options
const raw = process.argv.slice(process.argv.indexOf('run') + 1);
const forward: string[] = [];
const WS_VALUE = new Set(['--apps', '--concurrency', '--workspace']), WS_FLAG = new Set(['--all', '--apply']);
for (let i = 0; i < raw.length; i++) {
const a = raw[i]!;
const name = a.split('=')[0]!;
if (WS_VALUE.has(name)) { if (!a.includes('=')) i++; continue; }
if (WS_FLAG.has(a)) continue;
forward.push(a);
}
const p = runPolicy(forward);
if (!p.ok) throw new Error(`ws run: ${p.why}`);
if (!args.has('all') && !args.list('apps').length) throw new Error('ws run: say which apps: --apps a,b or --all');
const argv = p.write && !args.has('apply') && !forward.includes('--dry') ? [...forward, '--dry'] : forward;
const json = forward.includes('--json');
const { results, skipped } = await runEach(args, argv.filter(a => a !== '--json'), { json, label: 'run' });
if (json) printJson({ command: `storebound ${argv.join(' ')}`, apps: results.map(({ app, r }) => ({ app: app.name, folder: app.dir, exitCode: r.code, data: r.data ?? null, output: r.data === undefined ? r.out : undefined })), skipped: skipped.map(a => a.name) });
else {
for (const { app, r, problems } of results) {
console.log(`\n== ${app.name}${app.dir ? ` (${app.rel})` : ' (store only)'}: storebound ${argv.join(' ')} [exit ${r.code}]`);
for (const x of problems) warn('ws', x);
if (r.out) console.log(r.out);
}
if (skipped.length) log('ws', `store-only apps skipped (the command needs an app folder): ${skipped.map(a => a.name).join(', ')}`);
if (p.write && !args.has('apply')) log('ws', 'dry run: nothing was changed. After the owner agreed, the same command with --apply runs it.');
}
if (results.some(x => x.r.code !== 0)) process.exitCode = 1;
}
let neutral: string | null = null;
const neutralDir = (): string => {
if (!neutral) { neutral = join(tmpdir(), `storebound-ws-${process.pid}`); mkdirSync(neutral, { recursive: true }); }
return neutral;
};
async function appsImport(args: Args): Promise<void> {
const l = await loadAll(args);
const profile = args.get('account');
if (!profile) throw new Error('ws apps import --account <credential profile>');
const accounts = accountsOf(l.ws);
const mine = accounts.filter(a => a.profile === profile);
const st = profileStatus(profile);
if (st.source === 'missing' || st.source === 'invalid') throw new Error(`credential profile ${profile}: ${st.error ?? 'not found (~/.storebound/credentials/<profile>.json or STOREBOUND_PROFILE_<NAME>_* env)'}`);
const stores: Store[] = mine.length ? mine.map(a => a.store) : [...(st.apple ? ['apple' as const] : []), ...(st.play ? ['play' as const] : [])];
if (!mine.length) warn('ws', `profile ${profile} is not listed in the workspace: add { "store": "${stores[0] ?? 'apple'}", "profile": "${profile}" } to accounts (or a studio) so its apps show up`);
const env = profileEnv(profile);
const pass: Record<string, string> = { STOREBOUND_PROFILE: '' };
for (const k of PROFILE_KEYS) if (env[k]) pass[k] = env[k]!;
const imported: { store: Store; count: number; warnings: string[] }[] = [];
for (const store of stores) {
const r = await runCommand(['apps', 'list', '--store', store, '--json'], { cwd: neutralDir(), env: pass, machine: true }).result;
if (r.code !== 0 || !r.data) throw new Error(`${profile} (${store}): ${lastLine(r.out) || `exit ${r.code}`}`);
const res = r.data as AppsListResult;
const acc = mine.find(a => a.store === store);
const cache: StoreAppsCache = { profile, store, account: acc?.id ?? '', at: res.at, apps: res.apps.map(a => ({ ...a, icon: null })) };
const f = cacheFile(l.root, { store, profile });
mkdirSync(resolve(f, '..'), { recursive: true });
writeFileSync(f, JSON.stringify(cache, null, 2) + '\n');
imported.push({ store, count: res.apps.length, warnings: res.warnings });
log('ws', `${profile} (${store}): ${res.apps.length} app(s) -> ${relative(l.root, f)}`);
}
// the pairing with the folders, as ws list shows it from now on
const { apps: folders } = resolveApps(l);
const { apps } = workspaceApps(l, await summariesOf(folders, concurrencyOf(args, l.ws)));
const touched = apps.filter(a => [a.unified.ios?.account, a.unified.android?.account].some(id => id && mine.some(m => m.id === id)));
if (args.has('json')) { printJson({ imported, apps: touched.map(a => ({ name: a.name, folder: a.dir, pairing: a.unified.pairing, ios: a.unified.ios?.app.bundleId ?? null, android: a.unified.android?.app.id ?? null, ignored: a.ignored })) }); return; }
console.log(textTable(['app', 'folder', 'iOS', 'Android', 'pairing'], touched.map(a => [a.name + (a.ignored ? ' (ignored)' : ''), a.dir ? a.rel : '(store only)', a.unified.ios?.app.bundleId ?? '', a.unified.android?.app.id ?? '', a.unified.pairing])));
for (const i of imported) for (const w of i.warnings) warn('ws', w);
log('ws', 'wrong pair? add it to overrides.unpairs (or pairs / links) in the workspace file: the same rules as the desktop');
}
async function desktop(args: Args): Promise<void> {
const sub = args._[1];
if (sub === 'export') {
const l = await loadAll(args);
const { apps } = resolveApps(l);
const state = toDesktopState(l.ws, apps);
if (!args.has('merge')) {
const out = args.get('out');
if (!out) { printJson(state); return; }
if (args.has('dry')) { log('ws', `dry run: ${out} not written`); printJson(state); return; }
writeFileSync(resolve(out), JSON.stringify(state, null, 2) + '\n');
log('ws', `wrote ${out}: ${state.projects.length} app folder(s), ${state.accounts.length} account(s), ${state.studios.length} studio(s)`);
return;
}
const file = args.get('state') ? resolve(args.get('state')!) : desktopStateFile();
const cur: DesktopState = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) as DesktopState : { version: 2, projects: [], accounts: [], studios: [], overrides: { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] } };
const { state: merged, added } = mergeDesktopState(cur, state);
log('ws', `${file}: +${added.projects} app folder(s), +${added.accounts} account(s), +${added.studios} studio(s), +${added.overrides} override(s)`);
if (!args.has('apply')) { log('ws', 'dry run: nothing written. Quit the desktop app, then run again with --apply (a backup of state.json is kept).'); return; }
mkdirSync(resolve(file, '..'), { recursive: true });
if (existsSync(file)) copyFileSync(file, `${file}.ws-${new Date().toISOString().replace(/[:.]/g, '-')}.bak`);
writeFileSync(file, JSON.stringify(merged, null, 2) + '\n');
log('ws', 'merged. New accounts need their keys in the desktop (Accounts > the account > Add key): the desktop keeps keys in the OS keychain, not in profiles.');
return;
}
if (sub === 'import') {
const file = args.get('state') ? resolve(args.get('state')!) : desktopStateFile();
if (!existsSync(file)) throw new Error(`no desktop state at ${file} (--state <file>)`);
const root = process.cwd();
const { ws, profiles } = fromDesktopState(JSON.parse(readFileSync(file, 'utf8')) as DesktopState, root);
const out = resolve(args.get('out') ?? join(root, 'storebound.workspace.json'));
const text = JSON.stringify({ ...ws, concurrency: 4 }, null, 2) + '\n';
if (args.has('dry')) { console.log(text); log('ws', `dry run: ${out} not written`); }
else {
if (existsSync(out) && !args.has('force')) throw new Error(`${out} exists (--force overwrites, --out writes elsewhere)`);
writeFileSync(out, text);
log('ws', `wrote ${out}: ${ws.apps.length} app folder(s), ${(ws.studios ?? []).length} studio(s), ${profiles.length} account(s)`);
}
const missing = profiles.filter(p => profileStatus(p.profile).source === 'missing');
if (missing.length) {
log('ws', `credential profiles to create (the desktop's keychain is not read; put each account's key in its file):`);
for (const p of missing) console.log(` ${p.label} (${p.store}): ~/.storebound/credentials/${p.profile}.json ${p.store === 'apple' ? '{ "ASC_KEY_ID", "ASC_ISSUER_ID", "ASC_P8" }' : '{ "PLAY_SERVICE_ACCOUNT" }'}`);
}
return;
}
throw new Error('ws desktop export [--out f | --merge [--apply]] | ws desktop import [--state f] [--out f]');
}
export async function run(args: Args): Promise<void> {
const sub = args._[0];
switch (sub) {
case 'init': return init(args);
case 'list': return list(args);
case 'status': return status(args);
case 'check': return checkAll(args, 'check');
case 'validate': return checkAll(args, 'validate');
case 'run': return runCmd(args);
case 'apps': if (args._[1] === 'import') return appsImport(args); break;
case 'desktop': return desktop(args);
}
console.error(USAGE);
process.exit(2);
}