v1.0.12 · Release snapshot

Documentation comes from this release commit, without inheriting newer content. Commit: 35589c6fda.

Clean-architecture layers

Enforced baseline: all new features and refactors must follow the 3-layer rule (UI → zustand store → services, UI display-only; store = state + business logic + view-model) — see three-layer-architecture and its skill. It is the stepping stone to the layering proposed below.

Status: ports & adapters is fully adopted for in-app purchases. src/core/iap/ is the built reference (port + RevenueCat adapter + fake), and every src/features/* call site is now on getIapService() — no feature file imports react-native-purchases any more. react-native-purchases is confined to src/core/iap/ (the adapter) and src/core/sdk/ (the RevenueCat composition root), both in the adapter ring where it belongs. See Migration status for the inventory. The sibling usecases/ layer (below) is still not started — that is the only outstanding piece of this proposal.

The problem

The repo already layers well conceptually (see architecture.md), but inside a feature folder the layers are invisible. Everything is a flat .ts file:

features/songs/
  api.ts                    <- data access (repository)
  mappers.ts                <- data access (repository)
  queries.ts                <- cache binding
  store.ts                  <- persistence binding
  entitlements-actions.ts   <- BUSINESS LOGIC (use case)  ── looks the same
  rewarded-unlock.ts        <- BUSINESS LOGIC (use case)  ── as everything
  deal.ts                   <- BUSINESS LOGIC             ── else
  filters.ts                <- pure helper
  preview-uri.ts            <- pure helper
  ...

entitlements-actions.ts orchestrates a zustand store + @core/services/library + @core/sdk — it is a use case. But it sits next to preview-uri.ts (a string helper) with nothing signalling that one is orchestration and the other is a leaf. New code has nowhere obvious to go, so business logic keeps landing in screens or in random root files.

The layers you asked for

UI  ─────────────►  Use case / storage business logic  ─────────────►  Repository + service adapter
(screens,           (usecases/, store.ts)                              (api.ts, mappers.ts, queries.ts,
 components)                                                            @services, @core/sdk)

I recommend keeping api / mappers / queries / store (they map cleanly onto react-query and zustand, which a textbook onion would fight) and adding one new named layer: usecases/. This is the smallest change that gives you the separation, and it matches how the code already flows.

Your layerWhere it lives (recommended)What it is today
UIscreens/, components/already named
Use case (business logic)usecases/ (new folder)entitlements-actions.ts, rewarded-unlock.ts, deal.ts, *-actions.ts — loose root files today
Storage business logicstore.ts (+ @services/mmkv)already named
Repository (data access)api.ts + mappers.ts + queries.ts (cache binding)already named
Service adapter (externals)@services/* (apiClient, mmkv, library), @core/sdk/*already named

Result folder shape:

features/<name>/
  screens/          # UI       — composition, rendered by routes
  components/       # UI       — feature-local presentational
  usecases/         # BUSINESS — orchestration; the only place that combines
                    #            store + repository + adapters into a flow
  store.ts          # BUSINESS — client/persisted state (zustand)
  queries.ts        # DATA     — react-query cache binding (repository read/cache)
  api.ts            # DATA     — repository: fetch fns -> DTO
  mappers.ts        # DATA     — repository: DTO -> domain
  types.ts          # DATA     — DTO + domain types

Why not strict ui/ application/ domain/ infrastructure/?

A textbook onion would mean inverting dependencies with interfaces at the domain core and DI at the edges. In this app the "domain core" (MIDI, gameplay, catalog, progression) already lives outside the host app in packages/@piano/*, reached only through @piano/sdk. The features in src/features/* are the application/adapter ring of that onion — so re-onioning them internally would add ceremony (interfaces, DI containers) without a second implementation to swap. The usecases/ folder gives you the readability win of named business logic without importing that ceremony.

Testability is the point: use cases depend on a port, not on @core/sdk

The reason to name this layer is to make business logic testable without the real package/service. The rule for a use case: it depends on an interface (port) it declares; the concrete @core/sdk / @services adapter is built at the composition edge (the screen) and passed in. A test then injects a fake implementing the port — no module mocking, no real SDK, no network.

This already exists in the repo — songs/rewarded-unlock.ts is the reference:

// usecases/rewarded-unlock.ts — the use case declares its port (abstract adapter)
export interface RewardedUnlockDeps {
  showRewarded: (placement: string) => Promise<{ shown: boolean; earned: boolean } | undefined>;
  unlock: () => unknown;
  refresh: () => unknown;
}

export async function runRewardedUnlock(deps: RewardedUnlockDeps): Promise<RewardedUnlockResult> {
  const result = await deps.showRewarded(REWARDED_UNLOCK_PLACEMENT);
  /* ...pure business rules over deps... */
}
// __tests__/rewarded-unlock.test.ts — inject fakes, assert the logic, zero real SDK
const result = await runRewardedUnlock({
  showRewarded: async () => ({ shown: true, earned: true }), // fake adapter
  unlock: async () => { unlocked += 1; },
  refresh: async () => { refreshed += 1; },
});
expect(result.outcome).toBe("earned");
// screens/SongsScreen.tsx — the ONLY place the real adapter is wired to the port
await runRewardedUnlock({
  showRewarded: (p) => getSdk().ads.showRewarded(p),   // real @core/sdk adapter
  unlock: () => grantSongEntitlement(song),
  refresh: () => refetchOwned(),
});

Contrast songs/entitlements-actions.ts, which hard-wires import { getSdk } / getLibraryManager() at module top — to test it you must mock those modules, which is exactly the isolation pain you're describing. Migrating it means: extract an EntitlementsDeps port ({ setPremium, setSubscription, flushLibrary, syncLibrary, setVip }), take it as a parameter, and wire the real SDK in the caller.

The convention

  • Port = an interface the use case declares for only what it needs (narrow, not the whole SDK). Lives next to the use case in usecases/.
  • Adapter = the real implementation (@core/sdk, @services, @piano/sdk). Built and passed in at the screen/composition root — never imported inside the use case.
  • Test double = a fake object literal implementing the port, passed in the test. This is the "abstract logic adapter for testing" you asked for — no jest.mock, no bun module interception, no real package.
  • Keep ports feature-local and narrow. Don't build one global DI container; a use case that needs three things declares a three-method Deps interface. rewarded-unlock's three-method port is the size to aim for.

This gives you the same isolation for packages too: a use case that would call @piano/sdk instead declares a port for the slice it uses, so the test never boots the engine/catalog — it asserts your orchestration against a fake.

Dependency rules (add one row to the existing table)

Same direction as today, with the use-case layer slotted in the middle:

screens/components  ──►  usecases/  ──►  queries.ts / store.ts  ──►  api.ts / mappers.ts  ──►  @services, @core/sdk
  • usecases/ may import directly: own feature's store.ts / queries.ts / api.ts / mappers.ts / types.ts (in-process, already testable), and other features' store.ts (read-only).
  • usecases/ should not import external side-effecting adapters (@core/sdk, @services, @piano/sdk) at module top — take them via a declared port and let the screen wire the real adapter (see the testability section above). This is what keeps the logic isolate-testable.
  • usecases/ must not import: screens/, components/, app/*, or another feature's usecases/ (compose at the screen, or lift the shared flow to a package).
  • screens/ call usecases/ for anything with side effects or multi-step orchestration; they keep only view state locally. A screen should read like a script of use-case calls.
  • Pure, dependency-free helpers (filters.ts, preview-uri.ts, song-stars.pure.ts) are not use cases — leave them at the root or under a lib/ folder. The .pure.ts convention already marks these; keep it.

Built reference: the ads port (src/core/ads/)

Same ring structure as IAP — use this when adding a mediation network or another ad SDK.

src/core/ads/
  ads-service.ts               # THE PORT — AdsService { start, show*, preload*, bannerRequest, disposeCache }
  ads-native-adapter.ts        # SDK swap port — AdsNativeAdapter (Google AdMob)
  types.ts                     # domain types (ShowResult / SlotKind / TieredAdUnit …) — no SDK leakage
  ad-units.ts                  # pure: env ids → High/All units per format, tier order, test-ID mode
  pool-policy.ts               # pure: pool depth inside the app-wide cap, tier pick, failed-pool rebuild limit
  banner-tiers.ts              # pure: banner High → All fallback + bounded retries
  ads-engine.ts                # state machine (zero native imports) — warm pools per tier, take at show, watchdog
  mediated-ads-service.ts      # production AdsService = engine + injected native adapter
  simulate-ads-service.ts      # in-memory test double
  ads-service-registry.ts      # getAdsService → adsServiceSingleton (IAP-style const)
  composition-root.ts          # AdMob unit env + adapter wiring + gate / tracking / lifecycle
  adapters/
    admob-native-adapter.ts    # AdMob adapter — pure; an inventory mirrors the unit's pool, a take polls it (AdMobSdk port)
    admob-sdk.ts               # ONLY fullscreen module that imports react-native-google-mobile-ads (AdPools)
    admob-banner.tsx           # AdMob banner view (BannerAd) with the tier walk
  index.ts                     # public API: port + types + registry + Simulate — not adapters

What makes it the reference:

  • One outer port. Callers depend on AdsService via getAdsService(). Screens and ads.ts never import the ad SDK.
  • SDK swap port. AdsNativeAdapter is what an ad SDK implements; the engine is unchanged. The adapter itself takes the SDK as an injected port (AdMobSdk), so it is unit-tested with a fake SDK — only admob-sdk.ts / admob-banner.tsx touch the real module. The engine does not ask the network for ads: AdsNativeAdapter.createInventory() gives it one NativeAdInventory per unit (for AdMob, an SDK preload pool) that it keeps warm, takes an ad from at show time, and disposes with the cache.
  • Isolate-testable. Construct SimulateAdsService and pass it into the flow under test (no mutable registry override). Engine tests inject a fake AdsNativeAdapter whose inventories they fill by hand (src/core/ads/__tests__/support/fake-inventory-adapter.ts, no mock.module).

Built reference: the in-app-purchase port (src/core/iap/)

The pattern above is implemented end-to-end for purchases. Use it as the template for the next module.

src/core/iap/
  iap-service.ts               # THE PORT — IapService { init, getOfferings, purchase, restore }
  types.ts                     # domain types (IapOfferings/Entitlements/…) — no store-SDK leakage
  rc-mappers.pure.ts           # pure RevenueCat-shape → domain mappers (logic only, no SDK import)
  adapters/
    revenuecat-iap-service.ts  # the only IAP module that imports react-native-purchases
  fake-iap-service.ts          # in-memory test double
  iap-service-registry.ts      # getIapService() / setIapService / resetIapService
  index.ts                     # public API: port + domain types + registry + fake — not the adapter

What makes it the reference:

  • One port. Callers depend on IapService via getIapService(). Screens and use cases never import react-native-purchases, API keys, or adapter config.
  • Third-party stays in the adapter. react-native-purchases is imported only inside revenuecat-iap-service.ts. Pure mappers (rc-mappers.pure.ts) take locally-defined RC-shaped types — no SDK import.
  • Isolate-testable. Purchase mapping and cancellation live in the pure layer (hand-written fixtures, no native module). Flows under test inject FakeIapService via setIapService. See src/core/iap/__tests__/.

Migration status — every call site is on the port

All feature call sites now go through getIapService(); the domain entitlement sync is syncEntitlements(entitlements) (in monetization/sync-entitlements.ts), driven from the domain IapEntitlements — feature code never sees an RC CustomerInfo.

Module / fileCurrent callState
auth/guest.tsgetIapService().purchase()✅ migrated (reference)
songs/api.tsgetIapService().getOfferings()✅ migrated
songs/screens/SongsScreen.tsxgetIapService().purchase() ×2✅ migrated
songs/services/composition-root.ts (iap.buyNoAds)purchase() → syncEntitlements✅ migrated (replaced RemoveAdsHost, deleted 2026-11-05)
paywall/components/PaywallHost.tsxpurchase() + restore() → syncEntitlements✅ migrated
paywall/components/SaleOff50Host.tsxpurchase() + restore() → syncEntitlements✅ migrated
paywall/usePaywallPackages.tsgetIapService().getOfferings()✅ migrated
paywall/useSaleOff50Pricing.tsgetIapService().getOfferings()✅ migrated
auth/fresh-install.tsgetIapService().getEntitlements() + restore()✅ migrated
monetization/reconcile-owned-iap-songs.tsgetIapService().getEntitlements().ownedProductIds✅ migrated

The former blocker is resolved. IapEntitlements now carries ownedProductIds (mapped from RC allPurchasedProductIdentifiers in rc-mappers.pure.ts), so the ownership/reinstall paths resolve non-consumable song ownership and no-ads from domain data. The RC adapter revenuecat-iap-service.ts — which legitimately holds a raw CustomerInfo from getCustomerInfo() / the customer-info update listener — maps it once at the adapter boundary via rcCustomerInfoToEntitlements (exported from @core/iap) and then drives everything from the domain shape. No feature file imports react-native-purchases.

Remaining work

The IAP port migration is done. react-native-purchases now lives only in the adapter ring (src/core/iap/ + src/core/sdk/). What remains is the broader usecases/ layer, which was never started — see the next section.

The broader usecases/ layer (still unadopted)

The IAP work delivered the port/adapter/service layer for one cross-cutting concern. The sibling proposal — a named usecases/ folder inside each feature for orchestration logic (entitlements-actions.ts, rewarded-unlock.ts, deal.ts today live flat at the feature root) — has not been started. When ready:

  1. Pilot songs/ — move rewarded-unlock.ts (already port-shaped), entitlements-actions.ts, deal.ts into songs/usecases/; extract an EntitlementsDeps port for entitlements-actions.ts so it becomes isolate-testable like rewarded-unlock.
  2. Codify the rule — add a usecases/ row to .cursor/rules/feature-structure.mdc and the anatomy diagram in architecture.md; mention it in the create-feature skill.
  3. Migrate opportunistically — move loose business-logic files into usecases/ as each feature is touched, not big-bang.

No always-on rule or scaffold has been changed yet.