Merge cli-workspace: multi-app workspace, credential profiles, release trains in the CLI and MCP

# Conflicts:
#	.cursor/rules/storebound.mdc
#	.github/copilot-instructions.md
#	AGENTS.md
#	CHANGELOG.md
#	GEMINI.md
#	docs/agents-core.md
This commit is contained in:
CRTkafa 2026-10-11 23:36:36 +08:00
commit 54dd012cfa
26 changed files with 2219 additions and 292 deletions

View file

@ -16,7 +16,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
for real only after the owner agrees. for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys, 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there. for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating, 5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,

View file

@ -16,7 +16,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
for real only after the owner agrees. for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys, 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there. for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating, 5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,

View file

@ -17,7 +17,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
for real only after the owner agrees. for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys, 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there. for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating, 5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,

View file

@ -18,6 +18,22 @@
answers (new `appPrivacy` block for tracking). `scan.ignore` records findings the owner accepts, with the reason. answers (new `appPrivacy` block for tracking). `scan.ignore` records findings the owner accepts, with the reason.
`validate` includes the open findings (`--no-scan` skips), `check` now asks for unanswered dataSafety booleans. `validate` includes the open findings (`--no-scan` skips), `check` now asks for unanswered dataSafety booleans.
Fixtures for iOS, Android, Capacitor, Unity, Flutter, a clean project and the teaser under `tests/fixtures/scan/`. Fixtures for iOS, Android, Capacitor, Unity, Flutter, a clean project and the teaser under `tests/fixtures/scan/`.
- CLI workspace for many apps and studios (until now only in the desktop app): `storebound.workspace.json` (or `.ts`)
in a folder above the app folders names the app folders (globs), studios with their store accounts by credential
profile (never a key), an ignore list and the desktop's pairing overrides. Commands: `ws init`, `ws list`,
`ws status` (apps x stores, read in parallel with a concurrency limit), `ws check`, `ws validate`,
`ws run <command> --apps a,b|--all` (read commands; writes as dry runs unless `--apply`; submit, release, rollout,
send, start / stop never), `ws apps import --account <profile>` (store apps paired with the folders by the desktop's
rules) and `ws desktop export | import` (the same model as the desktop's `state.json`; keys stay in the keychain or
the profiles). MCP: `workspace_list`, `workspace_status` (read-only).
- Credential profiles: `~/.storebound/credentials/<profile>.json` (or env `STOREBOUND_PROFILE_<NAME>_<KEY>`), picked
with `--account <profile>` on any command or by the workspace, so many store accounts work from one terminal.
- Release trains in the CLI: `release status` (both stores on one train per version: build > testing > review > live
> rollout %) and `release plan <version>` (what is left on each store in fix order, from check, validate and the
store state; owner steps named, never done), as tables or `--json`. MCP: `release_status`, `release_plan`.
- Shared code instead of copies: the pairing rules (`cli/lib/identity.ts`) and the release lanes (`cli/lib/train.ts`)
moved out of the desktop's webview into `cli/lib/`, and the per-app status read behind `portfolio.status`
(`cli/lib/app-status.ts`) is the one `ws status` and `release` use. The desktop re-exports them unchanged.
- New logo: a glossy indigo box with an upward arrow (`brand/master/logo-mark.png`, `brand/README.md`). Every logo - New logo: a glossy indigo box with an upward arrow (`brand/master/logo-mark.png`, `brand/README.md`). Every logo
file comes from it through `tools/brand-assets.py`: desktop app icons (PNG sizes, `.icns`, a `.ico` with its own file comes from it through `tools/brand-assets.py`: desktop app icons (PNG sizes, `.icns`, a `.ico` with its own

View file

@ -15,7 +15,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
for real only after the owner agrees. for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys, 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there. for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating, 5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,

101
README.md
View file

@ -245,6 +245,9 @@ Read from environment variables, or from `.storebound/credentials.json` in your
| `reviewContact` | (file only) App Review contact name / phone / email | | `reviewContact` | (file only) App Review contact name / phone / email |
| `reviewDemoAccount` / `REVIEW_DEMO_USER`, `REVIEW_DEMO_PASSWORD` | demo account for App Review (`reviewAccess.signInRequired`); never in the config or the repo, masked in logs | | `reviewDemoAccount` / `REVIEW_DEMO_USER`, `REVIEW_DEMO_PASSWORD` | demo account for App Review (`reviewAccess.signInRequired`); never in the config or the repo, masked in logs |
Several store accounts on one machine: credential profiles (`~/.storebound/credentials/<profile>.json`, the same names)
picked with `--account <profile>` or by a workspace ([Many apps and studios](#many-apps-and-studios)).
## Install for your AI tool ## Install for your AI tool
Every route gives the agent the same skills and the same MCP tools. Nothing here requires Claude: the skills are Every route gives the agent the same skills and the same MCP tools. Nothing here requires Claude: the skills are
@ -380,6 +383,97 @@ run in the background with a log (`storebound shots render > .storebound/render.
</details> </details>
<details>
<summary><b>Many apps and release trains</b></summary>
| command | kind | what |
|---|---|---|
| `ws init` | local | find the app folders below and write `storebound.workspace.json` (globs like `games/*`) |
| `ws list [--all]` | local | apps (folders + store-only apps), studios, accounts and whether each credential profile has its keys |
| `ws status [--offline] [--apps a,b]` | API, read-only | portfolio table: every app x both stores (live / rollout % / next version), catalog parity, check; parallel |
| `ws check`, `ws validate [--apps a,b]` | local / API, read-only | the offline check / the readiness report of every app in one table |
| `ws run <command> --apps a,b \| --all [--apply]` | per command | any read command in every app; writes as dry runs unless `--apply`; never submit / release / rollout / send |
| `ws apps import --account <profile>` | API, read-only + local cache | the apps a store account sees, paired with the folders (the desktop's rules) |
| `ws desktop export [--out f \| --merge [--apply]]`, `ws desktop import` | local | the workspace to and from the desktop app's state (labels, never keys) |
| `release status [--app a,b] [--versions]` | API, read-only | both stores on one train per version: build > testing > review > live > rollout % |
| `release plan <version> [--app a]` | API, read-only | what is left for that version on each store, in fix order, with the owner's next step |
</details>
## Many apps and studios
A studio with twenty games, or a developer with apps under two store accounts, works from one folder above the app
folders. `storebound ws init` writes `storebound.workspace.json`:
```json
{
"apps": ["games/*", { "path": "apps/notes", "apple": "solo-apple" }],
"studios": [
{ "name": "Acme Games", "color": "indigo", "apps": ["games/*"],
"accounts": [{ "store": "apple", "profile": "acme-apple" }, { "store": "play", "profile": "acme-play" }] }
],
"accounts": [{ "store": "apple", "profile": "solo-apple", "label": "Solo" }],
"ignore": ["games/old-*"],
"overrides": { "pairs": [], "unpairs": [], "links": [], "appStudio": [] },
"concurrency": 4
}
```
- **apps**: folders or globs (only folders with a `storebound.config.*` count; `node_modules` and dot folders are
skipped). An object entry names the folder's own credential profiles.
- **studios**: name, colour (the desktop's set), the store accounts and the app folders (globs) that belong to it.
- **accounts**: store accounts without a studio. An account is a store and a **credential profile** name, never a key.
- **ignore**: folder globs, `app:<store app key>` and `account:<profile>`, as in the desktop's ignore list.
- **overrides**: the desktop's pairing corrections (`pairs`, `unpairs`, `links` of a store app to a folder,
`appStudio`), with folders named by their path. A `storebound.workspace.ts` with `export default { ... }` works too.
Which keys an app uses: its own entry's profiles, else the single account of that store in its studio, else the
single account of that store in the workspace, else the folder's own credentials (env or `.storebound/`).
**Credential profiles** keep many accounts apart on one machine: `~/.storebound/credentials/<profile>.json` with the
same four names as `.storebound/credentials.json` (`PLAY_SERVICE_ACCOUNT`, `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_P8`;
relative key paths are relative to that folder, which `STOREBOUND_CREDENTIALS_DIR` can move), or env
`STOREBOUND_PROFILE_<NAME>_<KEY>` (for CI). Any command takes `--account <profile>`. `ws list` shows per account whether
its profile has keys; no command prints a key.
`ws status`, `ws check`, `ws validate` and `ws run` read the apps a few at a time (`concurrency`, 1-8, or
`--concurrency`), each app with its own keys handed to its child process only. `ws run` takes any read command and
the MCP tool set; write commands get `--dry` unless `--apply`, and submit, release, rollout, send, start / stop,
testers and `--yes` are refused: those stay with the owner in the app folder.
`ws apps import --account <profile>` lists the apps a store account sees (as `apps list`) into
`.storebound/workspace/` and pairs them with the folders by the desktop's rules (`cli/lib/identity.ts`, the same code):
a folder takes the store apps its config names, the remaining iOS and Android apps pair by id, close id or name,
`unpairs` keep two apart, and the rest are store-only apps that `ws status` reads too.
**The desktop app** keeps the same model (studios, accounts, folders, overrides). `ws desktop import` turns its
`state.json` (or `--state <file>`) into a workspace file and lists the credential profiles to create: the desktop's
keychain is never read. `ws desktop export` prints the workspace as a desktop state (`--out <file>`), and
`--merge --apply` adds it to the desktop's `state.json` while the app is closed (a backup is kept; nothing is
removed; new accounts get their keys in the desktop's Accounts screen).
MCP: `workspace_list` (offline) and `workspace_status` (read-only).
## Release trains
One version, both stores, one track: **build > testing > review > live > rollout**. The CLI and the desktop's Releases
tab share the code (`cli/lib/train.ts`, `cli/lib/portfolio.ts`), so both show the same stage for the same store state.
```
$ storebound release status
app version train App Store Google Play
------ ------- ------- ---------------------- -----------------------------
Puzzle 2.3.0 current rollout 20% (build 45) rollout 10% (build 230)
Puzzle 2.4.0 next build testing (build 240, internal)
```
`release plan <version>` lists what is left for that version on each store in fix order: config problems (`check`),
the version on the store (how to create it when it is missing), store blockers (`validate`, while nothing is
submitted), the next move and the warnings. Owner steps (submit for review, promote to production, release an approved
version, raise or complete a rollout) are named with where the owner does them; storebound does not do them. A store
it cannot read is "unknown", never "not there". Both commands work in an app folder (that app) and in a workspace
(every app, or `--app a,b`); `--json` gives the structured result. MCP: `release_status`, `release_plan` (read-only).
## Store art ## Store art
Screenshots and previews are one step of the journey, but the one that takes the longest by hand, so storebound Screenshots and previews are one step of the journey, but the one that takes the longest by hand, so storebound
@ -453,8 +547,8 @@ navigation.
| `app-icons` | one artwork to every icon, adaptive / legacy launcher pitfalls | | `app-icons` | one artwork to every icon, adaptive / legacy launcher pitfalls |
| `store-screenshots` | capture from any engine, copy, fonts, render, checks, gallery, variants, App Store product page tests, Play experiments, upload | | `store-screenshots` | capture from any engine, copy, fonts, render, checks, gallery, variants, App Store product page tests, Play experiments, upload |
| `app-previews` | app or gameplay clips, App Store previews, Play promo video, checks, upload | | `app-previews` | app or gameplay clips, App Store previews, Play promo video, checks, upload |
| `store-preflight` | run and read `check`, `check --aso`, `validate`, `privacy-manifest` before submitting | | `store-preflight` | run and read `check`, `check --aso`, `validate`, `privacy-manifest` and `release plan` before submitting; `ws check` / `ws validate` for many apps |
| `release-management` | updates: Apple phased + manual release, Play staged rollout, halt / pause (not a rollback), review wait | | `release-management` | updates: release trains (`release status`, `release plan`), Apple phased + manual release, Play staged rollout, halt / pause (not a rollback), review wait |
| `store-health` | crash / ANR vitals vs Play's bad behavior thresholds, App Store diagnostics, weekly report | | `store-health` | crash / ANR vitals vs Play's bad behavior thresholds, App Store diagnostics, weekly report |
| `review-replies` | reply drafts, tone, no incentives, store limits, the owner approves and sends | | `review-replies` | reply drafts, tone, no incentives, store limits, the owner approves and sends |
| `store-analytics` | App Store analytics reports, Play reports bucket, before / after listing changes | | `store-analytics` | App Store analytics reports, Play reports bucket, before / after listing changes |
@ -472,7 +566,8 @@ per-request `_meta`, `resultType`, cacheable `tools/list`) and, on the same proc
- One tool per command. Read-only: `scan`, `check`, `check_aso`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`, - One tool per command. Read-only: `scan`, `check`, `check_aso`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`,
`analytics_compare`, `apple_status`, `apple_next_build`, `apple_testflight_status`, `apple_ppo_status`, `analytics_compare`, `apple_status`, `apple_next_build`, `apple_testflight_status`, `apple_ppo_status`,
`play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`. Local writes: `import_fastlane`, `whats_new`, `icons`, `play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`, `workspace_list`, `workspace_status`,
`release_status`, `release_plan`. Local writes: `import_fastlane`, `whats_new`, `icons`,
`health_report`, `reviews_draft`, `prices_export`, `analytics_snapshot`, `shots_capture`, `shots_render`, `health_report`, `reviews_draft`, `prices_export`, `analytics_snapshot`, `shots_capture`, `shots_render`,
`shots_gallery`, `shots_record`, `shots_video`. Store writes: `play_listing`, `play_images`, `play_products`, `shots_gallery`, `shots_record`, `shots_video`. Store writes: `play_listing`, `play_images`, `play_products`,
`play_data_safety`, `play_subscriptions`, `play_release_testing`, `apple_bundle`, `apple_iap`, `apple_iap_review`, `play_data_safety`, `play_subscriptions`, `play_release_testing`, `apple_bundle`, `apple_iap`, `apple_iap_review`,

View file

@ -1,196 +1,14 @@
// One app card per product, across studios and store accounts. Pure, so tests/identity.test.ts pins every rule. // One app card per product, across studios and store accounts. The pairing rules live in cli/lib/identity.ts (shared
// // with the CLI workspace, `storebound ws`); this file adds the desktop's types and the portfolio list helpers.
// Inputs: app folders (with the store ids of their config), the apps each store account can see (`apps list`), and import type { Project } from '../api';
// the owner's overrides (manual pairs / unpairs, links of a store app to a folder, studio moves, the ignore list). import type { UnifiedApp as CoreApp } from '../../../../cli/lib/identity';
// 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 { Account, AppStatus, Project, StoreApp } from '../api';
export interface Pair { ios: string; android: string } export {
export interface Overrides { buildApps, type BuildInput, NO_OVERRIDES, normId, normName, type Overrides, type Pair, pairCandidates, type Pairing, refKey, type StoreRef, storeTarget,
pairs: Pair[]; withIgnored, withLink, withPair, withStudio, withUnpair,
unpairs: Pair[]; } from '../../../../cli/lib/identity';
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 type UnifiedApp = CoreApp<Project>;
export interface StoreRef { key: string; account: string; store: 'ios' | 'android'; app: StoreApp }
export type Pairing = 'folder' | 'manual' | 'id' | 'close' | 'name' | 'single';
export interface UnifiedApp {
/** 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: Project | 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 {
projects: Project[];
/** Store ids of each folder's config (from the offline portfolio read). */
summaryOf: (p: Project) => AppStatus['summary'] | undefined;
accounts: Account[];
/** The last app list of each account. */
storeApps: { account: string; apps: StoreApp[] }[];
overrides: Overrides;
}
export function buildApps(i: BuildInput): UnifiedApp[] {
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[] = [];
// 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(app: UnifiedApp, all: UnifiedApp[]): UnifiedApp[] {
if (app.project || (app.ios && app.android)) return [];
const want = app.ios ? 'android' : 'ios';
const me = (app.ios ?? app.android)!;
const score = (x: UnifiedApp) => {
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 }))] };
}
// ---- Portfolio list: filter, search, sort, group ---- // ---- Portfolio list: filter, search, sort, group ----

View file

@ -1,10 +1,12 @@
// Pure view models for the screens: release timeline stages, health series against the store thresholds, review // Pure view models for the screens: release timeline stages, health series against the store thresholds, review
// inbox stats, catalog parity matrix, the portfolio's "needs attention" list, and the command palette matcher. // inbox stats, catalog parity matrix, the portfolio's "needs attention" list, and the command palette matcher.
// "Unknown, never false": every derivation keeps "not read" apart from "none" / "ok". // "Unknown, never false": every derivation keeps "not read" apart from "none" / "ok".
import type { AppStatus, ProjectSummary, ReleaseTrain, StoreRelease } from '../api'; import type { AppStatus, ProjectSummary } from '../api';
import { t } from '../i18n'; import { t } from '../i18n';
export type Tone = 'ok' | 'warn' | 'bad' | 'info' | 'neutral' | 'accent'; import type { Tone } from '../../../../cli/lib/train';
export type { Tone };
// ---- CLI JSON shapes the screens read (the commands' --json output) ---- // ---- CLI JSON shapes the screens read (the commands' --json output) ----
@ -48,68 +50,9 @@ export interface ScanResult {
export const isError = (x: unknown): x is { error: string } => !!x && typeof x === 'object' && typeof (x as { error?: unknown }).error === 'string'; export const isError = (x: unknown): x is { error: string } => !!x && typeof x === 'object' && typeof (x as { error?: unknown }).error === 'string';
// ---- Release timeline ---- // ---- Release timeline ----
// The stages and lanes live in cli/lib/train.ts, shared with `storebound release status | plan`.
/** Stages of one version on one store, left to right. */ export { cmpVersion, type Lane, laneOf, type Stage, STAGES, storeNow, trainLanes, versionHistory } from '../../../../cli/lib/train';
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 };
}
}
/** 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?: TestFlightStatus | 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 };
}
export function cmpVersion(a: string, b: string): number {
const pa = a.split('.').map(x => parseInt(x, 10) || 0), pb = b.split('.').map(x => parseInt(x, 10) || 0);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) { const d = (pa[i] ?? 0) - (pb[i] ?? 0); if (d) return d; }
return 0;
}
// ---- Health ---- // ---- Health ----

View file

@ -20,6 +20,8 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
'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'], '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'],
'scan': [() => import('./scan'), 'offline, read-only rejection-risk scan of the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill, plus the Data safety / App Privacy / ATT / privacy manifest proposal; --write puts the detected answers into the config; --json; exit 1 on blockers'], 'scan': [() => import('./scan'), 'offline, read-only rejection-risk scan of the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill, plus the Data safety / App Privacy / ATT / privacy manifest proposal; --write puts the detected answers into the config; --json; exit 1 on blockers'],
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'], '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]> = { const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'inspect': [() => import('./inspect'), 'offline summary of the config (name, store ids, languages, products, subscriptions); --json'], 'inspect': [() => import('./inspect'), 'offline summary of the config (name, store ids, languages, products, subscriptions); --json'],
@ -74,8 +76,9 @@ usage: storebound <command> [options]
${Object.entries(PLAIN).map(([k, [, d]]) => ` ${k.padEnd(25)} ${d}`).join('\n')} ${Object.entries(PLAIN).map(([k, [, d]]) => ` ${k.padEnd(25)} ${d}`).join('\n')}
${Object.entries(COMMANDS).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) 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) 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`); docs: README.md and the skills/ folder of the toolchain`);
} }
@ -83,6 +86,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 // 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); process.env.PATH = toolPath(process.env);
const argv = process.argv.slice(2); 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; const [a, b] = argv;
if (!a || a === 'help' || a === '--help' || a === '-h') return help(); if (!a || a === 'help' || a === '--help' || a === '-h') return help();
if (a === 'version' || a === '--version') return console.log((await import('../package.json')).version); 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": "" } } // "reviewDemoAccount": { "username": "", "password": "" } }
// The demo account for App Review can also come from env: REVIEW_DEMO_USER, REVIEW_DEMO_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) // 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 { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os'; 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 ServiceAccount { client_email: string; private_key: string; token_uri?: string }
export interface AscKey { keyId: string; issuerId: string; pem: 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}`); } 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 { 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]; const env = process.env[name];
if (env) return env; if (env) return env;
const v = fileStore(root)[name]; 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 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 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 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 opt = (flag: string, v: unknown): string[] => (v === undefined || v === null || v === '' ? [] : [`--${flag}`, String(v)]);
const flag = (name: string, v: unknown): string[] => (v === true ? [`--${name}`] : []); const flag = (name: string, v: unknown): string[] => (v === true ? [`--${name}`] : []);
@ -215,6 +216,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)' }, 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' } }, 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)] }, 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. */ /** 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.', '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.', '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.', '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.', 'Run `check` (offline) and `validate` (read-only) before writes. Long uploads (images, screenshots) are better run in a terminal with a log.',
].join(' '); ].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 { import {
DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult, type VirtualProject, DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult, type VirtualProject,
} from './lib/desktop-protocol'; } 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 { RENDER_FILE_RE } from './lib/project-files';
import { detectTools } from './lib/tools'; import { detectTools } from './lib/tools';
import { compiled, pickCallEnv, runCommand, type RunOptions, type Running } from './lib/runner'; 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]$/; 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 /** MCP tools the desktop profile leaves out (sending builds to testers on Play, release state changes: the window has
* the owner actions for those). */ * 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']); 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. */ /** 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; 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; const raw = list[i] as unknown;
// a store-only app: { key: "store:...", virtual: { name, apple?, play? } } // 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 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; out[i] = e;
try { try {
let dir: string; let dir: string;
@ -429,28 +429,7 @@ export class Session {
dir = virtualDir(checkVirtual(virt.virtual)); dir = virtualDir(checkVirtual(virt.virtual));
e.virtual = true; e.virtual = true;
} else { dir = checkProject(raw); e.project = dir; } } else { dir = checkProject(raw); e.project = dir; }
const summary = e.summary = await this.inspect(dir, env, id); await fillAppStatus(e, dir, { live, virtual: !!virt, exec: (argv, cwd) => this.track(id, this.run(argv, { cwd, env, machine: true })).result });
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);
} catch (err) { } catch (err) {
if (this.cancelled.has(id)) throw err; if (this.cancelled.has(id)) throw err;
e.errors.push((err as Error).message); 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>"). */ /** 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}$/; 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. */ /** Optional local tools with versions; app-managed copies (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME) included. */
export function localTools(): Json { 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);
}

View file

@ -11,7 +11,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
for real only after the owner agrees. for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys, 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there. for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating, 5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,

View file

@ -168,6 +168,16 @@ Each write is a dry run, then the native dialog, then the real run, with one pro
- **TestFlight tab:** What to Test, internal groups, testers. - **TestFlight tab:** What to Test, internal groups, testers.
- **Reviews tab:** reply editor (`reviews.reply`), approve, send (owner action). - **Reviews tab:** reply editor (`reviews.reply`), approve, send (owner action).
### The same model in the terminal
The CLI workspace (`storebound.workspace.json`, README "Many apps and studios") holds the same studios, accounts
(credential profile names instead of keychain entries), folders and overrides. The pairing rules
(`cli/lib/identity.ts`) and the release lanes (`cli/lib/train.ts`) are one implementation for both; the window
re-exports them (`src/lib/identity.ts`, `src/lib/model.ts`). `storebound ws desktop import` reads `state.json` into a
workspace file (the keychain is never read; the profiles to create are listed); `storebound ws desktop export --merge
--apply` adds a workspace to `state.json` while the app is closed (backup kept, nothing removed, new accounts get
their keys in the Accounts screen). Project ids in an exported state are stable per folder path (16 hex).
## Every CLI area in the window ## Every CLI area in the window
| CLI | where in the window | | CLI | where in the window |

View file

@ -8,6 +8,17 @@ description: Ship updates safely after the first release - App Store phased rele
CLI: `storebound` (on PATH as a plugin; or `bunx storebound` / `bun <toolchain>/cli/index.ts`). Rules: the owner CLI: `storebound` (on PATH as a plugin; or `bunx storebound` / `bun <toolchain>/cli/index.ts`). Rules: the owner
presses release; you prepare, dry-run and report. `storebound mcp` deliberately offers only "phased on" and "pause". presses release; you prepare, dry-run and report. `storebound mcp` deliberately offers only "phased on" and "pause".
## Where each version stands (release trains)
- `storebound release status` (MCP `release_status`, read-only): per app, both stores on one train per version:
build > testing > review > live > rollout (with the rollout %), the version that reaches users and the next one;
`--versions` lists every version the stores know. The same stages as the desktop's Releases tab.
- `storebound release plan 1.3.0` (MCP `release_plan`, read-only): what is left for that version on each store, in
fix order: config problems (`check`), the version on the store, store blockers (`validate`), the next move, warnings.
Owner steps (submit, release, raise / complete a rollout) are named with where the owner does them; you never run
them. "could not be read" means unknown, not "not there": fix the credentials first.
- Many apps (a `storebound.workspace.json` above the app folders): the same commands cover every app, or `--app a,b`.
`storebound ws status` is the portfolio table across apps and stores.
## Defaults ## Defaults
- **App Store**: release type **manual** (storebound sets `MANUAL` on every version it touches) and **phased release - **App Store**: release type **manual** (storebound sets `MANUAL` on every version it touches) and **phased release
on**. Never choose "reset ratings" when releasing an update (storebound never sets it); only an owner who really on**. Never choose "reset ratings" when releasing an update (storebound never sets it); only an owner who really

View file

@ -29,6 +29,13 @@ the stores; run them freely.
plus the open scan findings (codes `scan-<rule>`; `--no-scan` skips). Exit 1 while there is a blocker. `--json`. plus the open scan findings (codes `scan-<rule>`; `--no-scan` skips). Exit 1 while there is a blocker. `--json`.
5. With in-app products or subscriptions: `storebound catalog diff` (read-only): both stores against the config, 5. With in-app products or subscriptions: `storebound catalog diff` (read-only): both stores against the config,
prices per region, offers. Exit 1 on missing or mismatched items. prices per region, offers. Exit 1 on missing or mismatched items.
6. One list for the version you ship: `storebound release plan <version>` (MCP `release_plan`, read-only) puts the
check problems, the version's state on each store and the validate blockers in fix order, then names the owner's
next step (submit, promote, release). Report it as it is; the owner does the owner steps.
Many apps (a `storebound.workspace.json` above the app folders, `storebound ws init` writes it): `storebound ws check`
and `storebound ws validate [--apps a,b]` run the same checks over every app, a few at a time, each with its studio's
credential profile; `storebound ws run <command> --apps a,b` runs any other read command (writes only as dry runs).
## Reading `scan` ## Reading `scan`
| finding | fix | skill | | finding | fix | skill |

View file

@ -0,0 +1,23 @@
{
"version": 2,
"projects": [
{ "id": "0a1b2c3d4e5f6071", "path": "/Users/you/studio/games/puzzle", "name": "Puzzle Quest", "playAccount": "1111aaaa2222bbbb", "appleAccount": "3333cccc4444dddd", "added": "2026-09-01T10:00:00Z" },
{ "id": "8a9b0c1d2e3f4051", "path": "/Users/you/elsewhere/notes", "name": "notes", "playAccount": null, "appleAccount": null, "added": "2026-09-02T10:00:00Z" }
],
"accounts": [
{ "id": "1111aaaa2222bbbb", "label": "Acme Play", "kind": "play", "created": "2026-09-01T09:00:00Z", "studio": "f00dfeedf00dfeed" },
{ "id": "3333cccc4444dddd", "label": "Acme", "kind": "apple", "created": "2026-09-01T09:00:00Z", "studio": "f00dfeedf00dfeed" },
{ "id": "5555eeee6666ffff", "label": "Acme", "kind": "play", "created": "2026-09-03T09:00:00Z", "studio": null }
],
"studios": [
{ "id": "f00dfeedf00dfeed", "name": "Acme Games", "color": "teal", "logo": null, "created": "2026-09-01T08:00:00Z" }
],
"overrides": {
"pairs": [{ "ios": "ios:3333cccc4444dddd:6400000101", "android": "android:1111aaaa2222bbbb:com.example.racer" }],
"unpairs": [],
"links": [{ "key": "android:5555eeee6666ffff:com.example.notes", "project": "8a9b0c1d2e3f4051" }],
"appStudio": [{ "key": "project:8a9b0c1d2e3f4051", "studio": "f00dfeedf00dfeed" }],
"ignored": ["account:5555eeee6666ffff", "project:0a1b2c3d4e5f6071", "app:ios:3333cccc4444dddd:6400000199"]
},
"settings": { "refresh": { "autoMinutes": 0, "onLaunch": false, "parallel": 4, "icons": true }, "cache": { "keepDays": 30 }, "notify": { "reviewState": true, "lowReviews": true, "crash": true }, "channel": "stable" }
}

107
tests/release-train.test.ts Normal file
View file

@ -0,0 +1,107 @@
// Release trains in the CLI (`storebound release status | plan`): the same lanes as the desktop's Releases tab
// (cli/lib/train.ts is the one implementation; apps/desktop/src/lib/model.ts re-exports it). Sanitized store shapes.
import { describe, expect, test } from 'bun:test';
import type { StoreRelease } from '../cli/lib/desktop-protocol';
import { appleReleases, playReleases, releaseTrains } from '../cli/lib/portfolio';
import { laneOf, laneText, releasePlan, trackText, trainLanes, versionHistory } from '../cli/lib/train';
import type { Finding } from '../cli/lib/validate-rules';
import * as desktop from '../apps/desktop/src/lib/model';
import { formatPlan, trainsOf } from '../cli/release';
const apple = {
versions: [
{ id: 'v3', attributes: { versionString: '2.4.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' } },
{ id: 'v2', attributes: { versionString: '2.3.0', appStoreState: 'READY_FOR_SALE', platform: 'IOS' }, relationships: { build: { data: { id: 'b2' } } } },
{ id: 'v1', attributes: { versionString: '2.2.0', appStoreState: 'READY_FOR_SALE', platform: 'IOS' } },
],
builds: [{ id: 'b2', attributes: { version: '45' } }],
phased: { v2: { attributes: { phasedReleaseState: 'ACTIVE', currentDayNumber: 5 } } },
};
const play = {
tracks: [
{ track: 'production', releases: [{ name: '2.3.0', versionCodes: ['230'], status: 'inProgress', userFraction: 0.1 }, { name: '2.2.0', versionCodes: ['220'], status: 'completed' }] },
{ track: 'internal', releases: [{ name: '2.4.0', versionCodes: ['240'], status: 'completed' }] },
],
};
const all: StoreRelease[] = [...appleReleases(apple), ...playReleases(play)];
describe('lanes (shared with the desktop)', () => {
test('the desktop re-exports the CLI implementation', () => {
expect(desktop.laneOf).toBe(laneOf);
expect(desktop.versionHistory).toBe(versionHistory);
expect(desktop.trainLanes).toBe(trainLanes);
});
test('stage words for the terminal', () => {
const [cur] = versionHistory(all).filter(t => t.version === '2.3.0');
expect(laneText(laneOf('ios', cur!.ios))).toBe('rollout 20%');
expect(laneText(laneOf('android', cur!.android))).toBe('rollout 10%');
const next = versionHistory(all).find(t => t.version === '2.4.0')!;
expect(laneText(laneOf('ios', next.ios))).toBe('build');
expect(laneText(laneOf('android', next.android))).toBe('testing');
expect(trackText(laneOf('android', next.android))).toBe('build > [testing] > review > live > rollout');
expect(laneText(laneOf('ios', null))).toBe('-');
expect(laneText(laneOf('ios', { ...next.ios!, phase: 'approved' }))).toBe('review (approved)');
expect(laneText(laneOf('ios', { ...next.ios!, phase: 'live' }))).toBe('live');
});
test('status rows: current + next, or every version', () => {
const s = { release: { source: 'live' as const, ...releaseTrains(appleReleases(apple), playReleases(play)), all } } as never;
expect(trainsOf(s, false).map(x => [x.which, x.train.version])).toEqual([['current', '2.3.0'], ['next', '2.4.0']]);
expect(trainsOf(s, true).map(x => [x.which, x.train.version])).toEqual([['next', '2.4.0'], ['current', '2.3.0'], ['other', '2.2.0']]);
});
});
describe('release plan', () => {
const findings: Finding[] = [
{ store: 'apple', level: 'blocker', code: 'build', msg: 'no build attached to 2.4.0', fix: 'storebound apple listing --version 2.4.0 --build 46' },
{ store: 'apple', level: 'warn', code: 'keywords', msg: 'keywords use 60 of 100 characters' },
{ store: 'play', level: 'blocker', code: 'images', msg: 'tr-TR: 1 phone screenshot (2 needed)' },
];
const base = { version: '2.4.0', platforms: { ios: true, android: true }, check: { problems: ['store/appstore.md: subtitle over 30 characters'], warnings: [] }, validate: findings, releases: all };
test('fix order: config, store blockers, the owner move, warnings last', () => {
const p = releasePlan(base);
expect(p.shared.map(s => s.kind)).toEqual(['config']);
expect(p.ios!.steps.map(s => [s.kind, s.code ?? ''])).toEqual([['blocker', 'build'], ['owner', ''], ['warning', 'keywords']]);
expect(p.ios!.steps[1]!.text).toContain('submit 2.4.0 for App Review (owner)');
expect(p.android!.steps.map(s => s.kind)).toEqual(['blocker', 'owner']);
expect(p.android!.steps[1]!.text).toContain('promote 2.4.0 from internal to production');
expect(p.done).toBe(false);
expect(p.unknown).toEqual([]);
const text = formatPlan('Puzzle', p);
expect(text.indexOf('CONFIG')).toBeLessThan(text.indexOf('BLOCKER'));
expect(text).toContain('App Store: build [[build] > testing > review > live > rollout]');
});
test('a version in rollout: no blockers, the owner raises or completes', () => {
const p = releasePlan({ ...base, version: '2.3.0', check: { problems: [], warnings: [] } });
expect(p.ios!.steps.map(s => s.kind)).toEqual(['owner']);
expect(p.ios!.steps[0]!.text).toContain('20%');
expect(p.android!.steps[0]!.fix).toContain('storebound play rollout');
});
test('live everywhere is done; a missing version says how to start it', () => {
expect(releasePlan({ ...base, version: '2.2.0', check: { problems: [], warnings: [] } }).done).toBe(true);
const p = releasePlan({ ...base, version: '3.0.0', validate: [] });
expect(p.ios!.steps[0]).toMatchObject({ kind: 'store' });
expect(p.ios!.steps[0]!.text).toContain('not on App Store yet');
expect(p.android!.steps[0]!.fix).toContain('play release <aab> --internal completed --dry');
});
test('review, approved, rejected, halted', () => {
const r = (phase: StoreRelease['phase'], extra: Partial<StoreRelease> = {}): StoreRelease[] => [{ store: 'ios', version: '5.0.0', build: '9', state: 'X', phase, fraction: null, track: null, ...extra }];
const one = (rs: StoreRelease[]) => releasePlan({ version: '5.0.0', platforms: { ios: true, android: false }, check: { problems: [], warnings: [] }, validate: findings, releases: rs }).ios!.steps;
expect(one(r('review')).map(s => s.kind)).toEqual(['wait']);
expect(one(r('approved'))[0]!.fix).toContain('--manual-release');
expect(one(r('rejected')).map(s => s.kind)).toEqual(['blocker', 'blocker', 'owner', 'warning']);
expect(one(r('halted', { fraction: 0.05 }))[0]!.text).toContain('halted at 5%');
});
test('unknown, never false: an unreadable store is not "not there"', () => {
const p = releasePlan({ ...base, releases: all, storeErrors: { android: 'PLAY_SERVICE_ACCOUNT is not set' }, validate: null, check: null });
expect(p.unknown).toEqual(['config check did not run', 'store readiness (validate) did not run', 'Google Play state not read: PLAY_SERVICE_ACCOUNT is not set']);
expect(p.android!.steps[0]!.text).toContain('could not be read');
expect(p.done).toBe(false);
});
});

317
tests/workspace.test.ts Normal file
View file

@ -0,0 +1,317 @@
// Multi-app workspace (storebound ws), credential profiles and the desktop state import / export. Sanitized fixtures:
// example.com ids, placeholder account ids, no keys.
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { ascKey, profileEnv, profileStatus } from '../cli/lib/credentials';
import type { StoreApp } from '../cli/lib/desktop-protocol';
import {
accountId, accountsOf, checkWorkspace, type DesktopState, desktopProjectId, desktopStateFile, fromDesktopState, loadWorkspace, mergeDesktopState, overridesOf,
resolveApps, selectApps, toDesktopState, type Workspace,
} from '../cli/lib/workspace';
import { listTools, TOOLS, toArgv } from '../cli/mcp-tools';
import { DESKTOP_TOOLS } from '../cli/serve';
import { appEnv, discoverApps, runPolicy, workspaceApps } from '../cli/workspace';
const CLI = join(import.meta.dir, '..', 'cli', 'index.ts');
const SENTINEL = 'SENTINEL-KEY-VALUE-42';
/** An inline service account (not a path), so profileEnv keeps it as it is. */
const PLAY_INLINE = JSON.stringify({ sentinel: SENTINEL });
let root = '';
let creds = '';
const cfg = (name: string, id: string) => JSON.stringify({
app: { name, privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com/', contactEmail: 'dev@example.com' },
languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }], apple: { bundleId: id }, play: { packageName: id },
});
const WS: Workspace = {
apps: ['games/*', { path: 'apps/notes', apple: 'solo-apple' }],
studios: [{ name: 'Acme Games', color: 'indigo', apps: ['games/*'], accounts: [{ store: 'apple', profile: 'acme-apple' }, { store: 'play', profile: 'acme-play' }] }],
accounts: [{ store: 'apple', profile: 'solo-apple', label: 'Solo' }],
ignore: ['games/old-*'],
overrides: { pairs: [], unpairs: [], links: [], appStudio: [] },
};
/** A clean env for CLI children: no store keys of the machine running the tests. */
function env(extra: Record<string, string> = {}): Record<string, string> {
const e: Record<string, string> = {};
for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !/^(ASC_|PLAY_SERVICE|STOREBOUND_PROFILE|REVIEW_DEMO)/.test(k)) e[k] = v;
return { ...e, STOREBOUND_CREDENTIALS_DIR: creds, NO_COLOR: '1', ...extra };
}
function cli(args: string[], cwd = root, extra: Record<string, string> = {}) {
const r = Bun.spawnSync(['bun', CLI, ...args], { cwd, env: env(extra), stdout: 'pipe', stderr: 'pipe' });
return { code: r.exitCode, out: r.stdout.toString(), err: r.stderr.toString() };
}
beforeAll(() => {
root = mkdtempSync(join(tmpdir(), 'sb-ws-'));
creds = join(root, '..', `${root.split('/').pop()}-creds`);
mkdirSync(creds, { recursive: true });
for (const [dir, name, id] of [['games/puzzle', 'Puzzle', 'com.example.puzzle'], ['games/racer', 'Racer', 'com.example.racer'], ['games/old-tetra', 'Old', 'com.example.oldtetra'], ['apps/notes', 'Notes', 'com.example.notes']] as const) {
mkdirSync(join(root, dir), { recursive: true });
writeFileSync(join(root, dir, 'storebound.config.json'), cfg(name, id));
}
mkdirSync(join(root, 'games', 'not-an-app'), { recursive: true });
writeFileSync(join(root, 'storebound.workspace.json'), JSON.stringify(WS, null, 2));
writeFileSync(join(creds, 'acme-apple.json'), JSON.stringify({ ASC_KEY_ID: SENTINEL, ASC_ISSUER_ID: SENTINEL, ASC_P8: 'keys/acme.p8' }));
writeFileSync(join(creds, 'acme-play.json'), JSON.stringify({ PLAY_SERVICE_ACCOUNT: PLAY_INLINE }));
process.env.STOREBOUND_CREDENTIALS_DIR = creds;
});
afterAll(() => { delete process.env.STOREBOUND_CREDENTIALS_DIR; rmSync(root, { recursive: true, force: true }); rmSync(creds, { recursive: true, force: true }); });
describe('workspace file', () => {
test('a valid file passes; secrets, bad profiles and duplicates are refused', () => {
expect(checkWorkspace(WS)).toEqual([]);
expect(checkWorkspace({ apps: [], accounts: [{ store: 'apple', profile: 'x', ASC_P8: 'k' }] }).join(' ')).toContain('secrets never go here');
expect(checkWorkspace({ apps: [], accounts: [{ store: 'apple', profile: '../etc' }] }).join(' ')).toContain('profile');
expect(checkWorkspace({ apps: [], accounts: [{ store: 'play', profile: 'a' }], studios: [{ name: 'S', accounts: [{ store: 'play', profile: 'a' }] }] }).join(' ')).toContain('listed twice');
expect(checkWorkspace({ apps: 'x' })).toContain('apps: a list of app folders or globs ("apps/*")');
expect(checkWorkspace({ apps: [], studios: [{ name: 'S', color: 'pink' }] }).join(' ')).toContain('color');
expect(checkWorkspace({ apps: [], concurrency: 20 })).toContain('concurrency: 1 to 8');
});
test('account ids: the desktop id when given, else stable from store + profile (16 hex)', () => {
const a = accountId({ store: 'apple', profile: 'acme-apple' });
expect(a).toMatch(/^[0-9a-f]{16}$/);
expect(accountId({ store: 'apple', profile: 'acme-apple' })).toBe(a);
expect(accountId({ store: 'play', profile: 'acme-apple' })).not.toBe(a);
expect(accountId({ store: 'play', profile: 'x', id: '1111aaaa2222bbbb' })).toBe('1111aaaa2222bbbb');
expect(accountsOf(WS).map(x => [x.profile, x.studio])).toEqual([['acme-apple', 'acme-games'], ['acme-play', 'acme-games'], ['solo-apple', null]]);
});
test('globs, ignore list and account resolution', async () => {
const l = await loadWorkspace(join(root, 'games', 'puzzle'));
expect(l.root).toBe(root);
const { apps, warnings } = resolveApps(l);
expect(apps.map(a => [a.rel, a.ignored, a.studio, a.appleProfile, a.playProfile])).toEqual([
['apps/notes', false, null, 'solo-apple', 'acme-play'], // own apple profile; the only play account
['games/old-tetra', true, 'acme-games', 'acme-apple', 'acme-play'],
['games/puzzle', false, 'acme-games', 'acme-apple', 'acme-play'],
['games/racer', false, 'acme-games', 'acme-apple', 'acme-play'],
]);
expect(warnings).toEqual([]); // games/not-an-app has no config: skipped by the glob without a warning
const o = overridesOf(l.ws, apps);
expect(o.appStudio).toContainEqual({ key: 'project:games/puzzle', studio: 'acme-games' });
expect(o.ignored).toContain('project:games/old-tetra');
expect(selectApps(apps, ['puzzle', 'games/r*']).picked.map(a => a.rel)).toEqual(['games/puzzle', 'games/racer']);
expect(selectApps(apps, ['nope']).unknown).toEqual(['nope']);
});
test('ws init discovers app folders as globs', () => {
expect(discoverApps(root)).toEqual(['apps/notes', 'games/*']);
});
});
describe('pairing (the desktop rules, shared)', () => {
test('folders take their store apps; leftover iOS + Android pair; account ignore hides store apps', async () => {
const l = await loadWorkspace(root);
const [appleAcc, playAcc] = accountsOf(l.ws);
const ios = (id: string, bundleId: string, name: string): StoreApp => ({ store: 'ios', id, bundleId, name, platforms: ['IOS'] });
const and = (pkg: string, name: string): StoreApp => ({ store: 'android', id: pkg, bundleId: pkg, name, platforms: ['ANDROID'] });
const cache = (a: { store: 'apple' | 'play'; profile: string }, apps: StoreApp[]) => {
mkdirSync(join(root, '.storebound', 'workspace'), { recursive: true });
writeFileSync(join(root, '.storebound', 'workspace', `apps-${a.store}-${a.profile}.json`), JSON.stringify({ ...a, account: '', at: '2026-10-01T00:00:00Z', apps }));
};
try {
cache(appleAcc!, [ios('6400000101', 'com.example.puzzle', 'Puzzle'), ios('6400000102', 'com.example.blocks.ios', 'Blocks')]);
cache(playAcc!, [and('com.example.puzzle', 'Puzzle'), and('com.example.blocks', 'Blocks'), and('com.example.solo', 'Solo Game')]);
const summaries = new Map([['games/puzzle', { apple: { bundleId: 'com.example.puzzle', appId: null }, play: { packageName: 'com.example.puzzle' } } as never]]);
const { apps } = workspaceApps(l, summaries);
const puzzle = apps.find(a => a.rel === 'games/puzzle')!;
expect([puzzle.unified.pairing, puzzle.unified.ios?.app.id, puzzle.unified.android?.app.id]).toEqual(['folder', '6400000101', 'com.example.puzzle']);
const blocks = apps.find(a => a.name === 'Blocks')!;
expect([blocks.virtual, blocks.unified.pairing, blocks.studio]).toEqual([true, 'close', 'acme-games']);
expect(apps.find(a => a.name === 'Solo Game')!.unified.pairing).toBe('single');
// the store-only app reads with both studio accounts' profiles; values stay in the env object
const e = appEnv(blocks.unified, accountsOf(l.ws));
expect(Object.keys(e.env).sort()).toEqual(['ASC_ISSUER_ID', 'ASC_KEY_ID', 'ASC_P8', 'PLAY_SERVICE_ACCOUNT', 'STOREBOUND_PROFILE']);
expect(e.env.STOREBOUND_PROFILE).toBe('');
expect(e.env.ASC_P8).toBe(join(creds, 'keys', 'acme.p8')); // relative to the profile folder
// an unpair keeps them apart
const split = workspaceApps({ ...l, ws: { ...l.ws, overrides: { unpairs: [{ ios: blocks.unified.ios!.key, android: blocks.unified.android!.key }] } } }, summaries);
expect(split.apps.filter(a => a.name === 'Blocks').map(a => a.unified.pairing)).toEqual(['single', 'single']);
// ignoring the play account drops its store apps
const ign = workspaceApps({ ...l, ws: { ...l.ws, ignore: [...(l.ws.ignore ?? []), 'account:acme-play'] } }, summaries);
expect(ign.apps.some(a => a.name === 'Solo Game')).toBe(false);
} finally { rmSync(join(root, '.storebound'), { recursive: true, force: true }); }
});
});
describe('credential profiles', () => {
test('file, env override, status without values, and --account precedence', () => {
const saved = { ...process.env };
try {
process.env.STOREBOUND_CREDENTIALS_DIR = creds;
expect(profileEnv('acme-play')).toEqual({ PLAY_SERVICE_ACCOUNT: PLAY_INLINE });
process.env.STOREBOUND_PROFILE_ACME_PLAY_PLAY_SERVICE_ACCOUNT = '/keys/other.json';
expect(profileEnv('acme-play').PLAY_SERVICE_ACCOUNT).toBe('/keys/other.json');
expect(profileStatus('acme-play')).toEqual({ profile: 'acme-play', source: 'env', apple: false, play: true });
expect(profileStatus('nobody')).toEqual({ profile: 'nobody', source: 'missing', apple: false, play: false });
expect(JSON.stringify(profileStatus('acme-apple'))).not.toContain(SENTINEL);
expect(() => profileEnv('../x')).toThrow('credential profile');
// a profile chosen for the run wins over env and the project file
const pem = ['-----BEGIN PRIVATE KEY-----', 'abc', '-----END PRIVATE KEY-----'].join('\n');
writeFileSync(join(creds, 'pick.json'), JSON.stringify({ ASC_KEY_ID: 'PICKED', ASC_ISSUER_ID: 'iss', ASC_P8: pem }));
process.env.ASC_KEY_ID = 'FROM-ENV';
process.env.ASC_ISSUER_ID = 'iss-env';
process.env.STOREBOUND_PROFILE = 'pick';
expect(ascKey(root).keyId).toBe('PICKED');
delete process.env.STOREBOUND_PROFILE;
process.env.ASC_P8 = pem;
expect(ascKey(root).keyId).toBe('FROM-ENV');
} finally {
for (const k of Object.keys(process.env)) if (!(k in saved)) delete process.env[k];
Object.assign(process.env, saved);
}
});
});
describe('desktop state <-> workspace', () => {
const state = JSON.parse(readFileSync(join(import.meta.dir, 'fixtures', 'workspace', 'desktop-state.json'), 'utf8')) as DesktopState;
test('import: folders, studios, accounts as profiles, overrides with folder names', () => {
const { ws, profiles } = fromDesktopState(state, '/Users/you/studio');
expect(ws.apps).toEqual([{ path: 'games/puzzle', name: 'Puzzle Quest', apple: 'acme', play: 'acme-play' }, '/Users/you/elsewhere/notes']);
expect(profiles).toEqual([{ profile: 'acme-play', store: 'play', label: 'Acme Play' }, { profile: 'acme', store: 'apple', label: 'Acme' }, { profile: 'acme-play-2', store: 'play', label: 'Acme' }]);
expect(ws.studios).toEqual([{ id: 'f00dfeedf00dfeed', name: 'Acme Games', color: 'teal', accounts: [
{ store: 'play', profile: 'acme-play', label: 'Acme Play', id: '1111aaaa2222bbbb' }, { store: 'apple', profile: 'acme', label: 'Acme', id: '3333cccc4444dddd' }] }]);
expect(ws.accounts).toEqual([{ store: 'play', profile: 'acme-play-2', label: 'Acme', id: '5555eeee6666ffff' }]);
expect(ws.ignore).toEqual(['account:acme-play-2', 'project:games/puzzle', 'app:ios:3333cccc4444dddd:6400000199']);
expect(ws.overrides?.links).toEqual([{ key: 'android:5555eeee6666ffff:com.example.notes', project: '/Users/you/elsewhere/notes' }]);
expect(ws.overrides?.appStudio).toEqual([{ key: 'project:/Users/you/elsewhere/notes', studio: 'f00dfeedf00dfeed' }]);
expect(checkWorkspace(ws)).toEqual([]);
expect(JSON.stringify(ws)).not.toMatch(/PRIVATE KEY|service_account/);
});
test('export: the desktop format (version 2), account ids kept, project ids stable per path', async () => {
const l = await loadWorkspace(root);
const { apps } = resolveApps(l);
const s = toDesktopState(l.ws, apps, '2026-10-01T00:00:00Z');
expect(s.version).toBe(2);
expect(s.projects.map(p => p.id)).toEqual(apps.map(a => desktopProjectId(a.path)));
expect(s.projects.every(p => /^[0-9a-f]{16}$/.test(p.id))).toBe(true);
expect(s.accounts.map(a => [a.label, a.kind, a.studio])).toEqual([['acme-apple', 'apple', 'acme-games'], ['acme-play', 'play', 'acme-games'], ['Solo', 'apple', null]]);
expect(s.overrides.ignored).toContain(`project:${desktopProjectId(join(root, 'games', 'old-tetra'))}`);
expect(s.overrides.appStudio).toContainEqual({ key: `project:${desktopProjectId(join(root, 'games', 'puzzle'))}`, studio: 'acme-games' });
expect(JSON.stringify(s)).not.toContain(SENTINEL);
// the desktop's state.json shape: every key its Rust State reads
expect(Object.keys(s).sort()).toEqual(['accounts', 'overrides', 'projects', 'studios', 'version']);
});
test('merge: nothing removed, existing projects keep their ids and accounts', () => {
const incoming: DesktopState = { version: 2, projects: [{ ...state.projects[0]!, id: 'ffffffffffffffff', appleAccount: null }, { id: 'eeeeeeeeeeeeeeee', path: '/Users/you/new', name: 'new', playAccount: null, appleAccount: null, added: '' }],
accounts: [state.accounts[0]!, { id: '9999999999999999', label: 'New', kind: 'apple', created: '', studio: null }], studios: [],
overrides: { pairs: [], unpairs: [], links: [], appStudio: [{ key: 'project:ffffffffffffffff', studio: 'x' }], ignored: ['project:ffffffffffffffff'] } };
const { state: m, added } = mergeDesktopState(state, incoming);
expect(added).toEqual({ projects: 1, accounts: 1, studios: 0, overrides: 1 });
expect(m.projects[0]).toEqual(state.projects[0]!);
expect(m.overrides.ignored.filter(x => x === 'project:0a1b2c3d4e5f6071')).toHaveLength(1);
expect(m.settings).toEqual(state.settings);
});
test('state file location per platform', () => {
expect(desktopStateFile({ STOREBOUND_DESKTOP_DATA: '/d' })).toBe('/d/state.json');
expect(desktopStateFile({}, 'darwin')).toContain(join('Application Support', 'dev.storebound.desktop', 'state.json'));
expect(desktopStateFile({ XDG_DATA_HOME: '/x' }, 'linux')).toBe('/x/dev.storebound.desktop/state.json');
});
});
describe('ws run policy', () => {
test('reads run, writes get --dry, owner steps never', () => {
expect(runPolicy(['validate', '--play'])).toEqual({ ok: true, write: false });
expect(runPolicy(['inspect'])).toEqual({ ok: true, write: false });
expect(runPolicy(['apple', 'testflight', 'status'])).toEqual({ ok: true, write: false });
expect(runPolicy(['play', 'listing'])).toEqual({ ok: true, write: true });
expect(runPolicy(['health', '--weekly'])).toEqual({ ok: true, write: true });
expect(runPolicy(['health'])).toEqual({ ok: true, write: false });
expect(runPolicy(['prices', 'import'])).toEqual({ ok: true, write: true });
for (const bad of [['play', 'release', 'x.aab'], ['apple', 'release', '--phased', 'complete'], ['play', 'rollout', '--complete'], ['reviews', 'send'], ['apple', 'ppo', 'start'],
['apple', 'testflight', 'distribute', '--build', '3'], ['play', 'listing', '--yes'], ['apple', 'status', '--cancel-submission', '1'], ['ws', 'list'], ['rm', '-rf'], []]) {
expect(runPolicy(bad).ok).toBe(false);
}
});
});
describe('MCP', () => {
test('workspace and release tools: read-only, in MCP, not in the desktop profile', () => {
const names = ['workspace_list', 'workspace_status', 'release_status', 'release_plan'];
for (const n of names) {
const t = TOOLS.find(x => x.name === n)!;
expect(t.write).toBe(false);
expect((listTools().find(x => x.name === n)!.annotations as { readOnlyHint: boolean }).readOnlyHint).toBe(true);
expect(DESKTOP_TOOLS.some(x => x.name === n)).toBe(false);
}
expect(toArgv(TOOLS.find(x => x.name === 'release_plan')!, { version: '2.4.0', app: 'puzzle', json: true }).argv).toEqual(['release', 'plan', '2.4.0', '--app', 'puzzle', '--json']);
expect(toArgv(TOOLS.find(x => x.name === 'workspace_status')!, { offline: true }).argv).toEqual(['ws', 'status', '--offline']);
});
});
describe('CLI end to end (offline)', () => {
test('ws list --json: apps, studios, accounts; never a key value', () => {
const r = cli(['ws', 'list', '--json'], join(root, 'games'));
expect(r.code).toBe(0);
const d = JSON.parse(r.out);
expect(d.apps.map((a: { name: string }) => a.name)).toEqual(['Notes', 'Puzzle', 'Racer']);
expect(d.accounts.map((a: { profile: string; source: string }) => [a.profile, a.source])).toEqual([['acme-apple', 'file'], ['acme-play', 'file'], ['solo-apple', 'missing']]);
expect(r.out + r.err).not.toContain(SENTINEL);
expect(cli(['ws', 'list', '--all', '--json']).out).toContain('"Old"');
});
test('ws status --offline --json and ws check', () => {
const r = cli(['ws', 'status', '--offline', '--json', '--apps', 'puzzle,racer']);
const d = JSON.parse(r.out);
expect(d.live).toBe(false);
expect(d.apps.map((a: { name: string; status: { summary: { name: string } } }) => [a.name, a.status.summary.name])).toEqual([['Puzzle', 'Puzzle'], ['Racer', 'Racer']]);
expect(d.apps[0].status.release.source).toBe('none');
const c = cli(['ws', 'check', '--json']);
expect(JSON.parse(c.out).check).toHaveLength(3);
expect(c.code).toBe(1); // the fixture apps have no listing files yet
});
test('ws run: needs --apps / --all, adds --dry to writes, refuses owner steps', () => {
expect(cli(['ws', 'run', 'inspect']).err).toContain('--apps a,b or --all');
const i = cli(['ws', 'run', 'inspect', '--all', '--json']);
expect(i.code).toBe(0);
expect(JSON.parse(i.out).apps.map((a: { data: { name: string } }) => a.data.name)).toEqual(['Notes', 'Puzzle', 'Racer']);
const w = cli(['ws', 'run', 'play', 'listing', '--apps', 'puzzle']);
expect(w.out).toContain('storebound play listing --dry');
const bad = cli(['ws', 'run', 'play', 'rollout', '--complete', '--all']);
expect(bad.code).toBe(1);
expect(bad.err).toContain('owner step');
});
test('ws desktop export / import round trip through files', () => {
const out = join(root, '.storebound', 'state.json');
mkdirSync(join(root, '.storebound'), { recursive: true });
expect(cli(['ws', 'desktop', 'export', '--out', out]).code).toBe(0);
const s = JSON.parse(readFileSync(out, 'utf8')) as DesktopState;
expect(s.projects).toHaveLength(4);
const back = join(root, '.storebound', 'ws.json');
const r = cli(['ws', 'desktop', 'import', '--state', out, '--out', back]);
expect(r.code).toBe(0);
const ws = JSON.parse(readFileSync(back, 'utf8')) as Workspace;
expect(checkWorkspace(ws)).toEqual([]);
expect(ws.apps).toHaveLength(4);
expect(ws.ignore).toContain('project:games/old-tetra');
// merge into a desktop state: dry unless --apply
const target = join(root, '.storebound', 'desktop');
mkdirSync(target, { recursive: true });
const m = cli(['ws', 'desktop', 'export', '--merge'], root, { STOREBOUND_DESKTOP_DATA: target });
expect(m.out).toContain('dry run');
expect(cli(['ws', 'desktop', 'export', '--merge', '--apply'], root, { STOREBOUND_DESKTOP_DATA: target }).code).toBe(0);
expect((JSON.parse(readFileSync(join(target, 'state.json'), 'utf8')) as DesktopState).projects).toHaveLength(4);
});
test('release status in an app folder without keys: unreadable, never "not there"', () => {
const r = cli(['release', 'status', '--json'], join(root, 'games', 'puzzle'));
expect(r.code).toBe(1);
const d = JSON.parse(r.out);
expect(d.apps[0].storeErrors.ios).toContain('ASC_KEY_ID');
expect(d.apps[0].trains).toEqual([]);
const p = cli(['release', 'plan', '1.0.0', '--no-validate', '--json'], join(root, 'games', 'puzzle'));
const plan = JSON.parse(p.out).apps[0].plan;
expect(plan.unknown.join(' ')).toContain('App Store state not read');
expect(plan.done).toBe(false);
});
});