# Platform Acceleration — Implementation Roadmap

> **Companion to:** [PLATFORM_ACCELERATION_IDEAS.md](./PLATFORM_ACCELERATION_IDEAS.md)
>
> **Purpose:** Concrete phased roadmap with task lists, timelines, dependencies, and acceptance criteria so we never lose track of these aspirational improvements.
>
> **Date:** 2026-02-28 · **Updated:** 2026-03-19 · **Status:** ✅ Complete (all 4 phases)
>
> ### Completion Summary
>
> | Phase                              | Status      | Tests                                                  | Key Commits                                |
> | ---------------------------------- | ----------- | ------------------------------------------------------ | ------------------------------------------ |
> | **Phase 1 — Foundation**           | ✅ Complete | 114 (manifest 51, components 32, sync 31)              | `359d6e1`, `a0dafcd`, `16dc1c4`            |
> | **Phase 2 — Developer Experience** | ✅ Complete | 80 (scaffolder 26, auth-ui 54)                         | `6354711`, `43439e9`, `f051942`            |
> | **Phase 3 — Native & Declarative** | ✅ Complete | 105 (shell 41, declarative 34, Swift 30, Kotlin 64)    | `1fda345`, `933390e`, `70635ba`, `0f29923` |
> | **Phase 4 — Polish & Scale**       | ✅ Complete | 28 (auto-reg 8, telemetry 6, onboarding 8, checkout 6) | `1fe1e75`, `d900df3`, `0e880fd`, `0352ea5` |

---

## Table of Contents

1. [Overview & Phasing](#1-overview--phasing)
2. [Phase 1 — Foundation (Weeks 1–2)](#2-phase-1--foundation-weeks-12)
3. [Phase 2 — Developer Experience (Weeks 3–6)](#3-phase-2--developer-experience-weeks-36)
4. [Phase 3 — Native & Declarative (Weeks 7–12)](#4-phase-3--native--declarative-weeks-712)
5. [Phase 4 — Polish & Scale (Weeks 13–16)](#5-phase-4--polish--scale-weeks-1316)
6. [Dependency Graph](#6-dependency-graph)
7. [Success Metrics](#7-success-metrics)
8. [Risk Register](#8-risk-register)

---

## 1. Overview & Phasing

```
Phase 1 (Wk 1-2)         Phase 2 (Wk 3-6)         Phase 3 (Wk 7-12)        Phase 4 (Wk 13-16)
─────────────────         ─────────────────         ──────────────────        ──────────────────
Product manifest          CLI scaffolder            Native Swift SDK          Multi-product telemetry
Module generator          Auth UI kit               Native Kotlin SDK         Onboarding analytics
Shared UI components      API route generator        Dashboard shell           Pre-built Stripe checkout
Sync engine package       AGENTS.md auto-gen        Declarative YAML modules  Auto-registration
                                                                              Cross-product dashboards
```

**Target outcome:** New product from zero → deployed MVP in **under 8 hours**.

---

## 2. Phase 1 — Foundation (Weeks 1–2)

> **Theme:** Build the primitives that everything else depends on.

### 2.1 Product Manifest Specification (`product.json`)

**What:** Define a JSON schema that captures everything about a product — identity, theme, features, containers, flags, ports.

**Location:** `packages/config/src/product-manifest.ts`

**Tasks:**

- [x] Design `product.json` JSON schema (Zod)
- [x] Define fields: `id`, `name`, `bundleId`, `domain`, `description`, `platforms[]`, `theme{}`, `features{}`, `cosmos.containers{}`, `defaultFlags[]`, `ports{}`
- [x] Add `loadProductManifest(path)` function to `@bytelyst/config`
- [x] Add validation: all required fields, valid productId format, no duplicate container names
- [x] Write tests — **51 tests** (`packages/config/src/__tests__/product-manifest.test.ts`)
- [x] Create `product.json` files for existing products: LysnrAI, MindLyst, ChronoMind, NomGap
- [x] Document the schema in README

**Acceptance Criteria:**

- `loadProductManifest('./product.json')` returns typed, validated config
- Existing products have valid manifests
- Schema is extensible (unknown keys don't fail validation)

**Estimated effort:** 2 days
**Dependencies:** None
**Blocks:** Phase 2 CLI scaffolder, Phase 4 auto-registration

---

### 2.2 Module Generator (`pnpm gen:module`)

**What:** A script that generates the standard `types.ts → repository.ts → routes.ts → test.ts` module from a field definition.

**Location:** `services/platform-service/scripts/gen-module.ts`

**Tasks:**

- [x] Design CLI interface: `pnpm gen:module --name <name> --fields "<field:type,...>" --partition <key>`
- [x] Support field types: `string`, `number`, `boolean`, `date`, `datetime`, `enum(a,b,c)`, `string[]`, `number[]`
- [x] Support optional fields with `?` suffix (e.g., `dueAt:datetime?`)
- [x] Generate `types.ts` with Zod schemas (`Create*Schema`, `Update*Schema`) and TypeScript interface
- [x] Generate `repository.ts` with list/get/create/update/delete functions
- [x] Generate `routes.ts` with GET (list), GET/:id, POST, PATCH/:id, DELETE/:id
- [x] Generate `<module>.test.ts` with tests for all CRUD operations
- [x] Auto-add container to `cosmos-init.ts` CONTAINER_DEFS
- [x] Auto-add route import + registration to `server.ts`
- [x] Add `--dry-run` flag to preview output without writing files
- [x] Write tests for the generator itself (template rendering)
- [x] Add `gen:module` script to platform-service `package.json`

**Acceptance Criteria:**

- `pnpm gen:module --name tasks --fields "title:string,status:enum(pending,active,done),priority:number" --partition userId` produces 4 valid files
- Generated code passes `pnpm typecheck` and `pnpm test` with no modifications
- Container automatically appears in `cosmos-init.ts`
- Route automatically registered in `server.ts`

**Estimated effort:** 2 days
**Dependencies:** None
**Blocks:** Phase 3 declarative YAML modules

---

### 2.3 Shared UI Components Package

**What:** Extract identical components used across all dashboards into a shared package.

**Location:** `packages/dashboard-components/`

**Tasks:**

- [x] Create `packages/dashboard-components/` package structure
- [x] Extract `ErrorPage` component (currently copy-pasted in admin-web, tracker-web, user-dashboard-web)
- [x] Extract `NotFoundPage` component
- [x] Extract `LoadingSpinner` / `LoadingSkeleton` component
- [x] Extract `EmptyState` component (icon + title + description + CTA)
- [x] Extract `PageHeader` component (title + breadcrumbs + actions)
- [x] Make all components theme-aware (accept CSS custom properties)
- [x] Write tests — **32 tests** (`packages/dashboard-components/src/components.test.tsx`)
- [ ] Update admin-web to consume from `@bytelyst/dashboard-components`
- [ ] Update tracker-web to consume
- [ ] Update user-dashboard-web to consume
- [x] Add package to `pnpm-workspace.yaml`
- [x] Document usage in README

**Acceptance Criteria:**

- All 3 dashboards import from `@bytelyst/dashboard-components` instead of local copies
- Components render correctly with each dashboard's theme
- Zero visual regression (screenshots match before/after)

**Estimated effort:** 2 days
**Dependencies:** None
**Blocks:** Phase 3 dashboard shell

---

### 2.4 Sync Engine Package (`@bytelyst/sync`)

**What:** Extract the offline-first sync pattern into a reusable package with configurable entities, conflict strategies, and storage adapters.

**Location:** `packages/sync/`

**Tasks:**

- [x] Audit existing sync implementations:
  - [x] ChronoMind: `web/src/lib/platform-sync.ts` (~200 lines), `use-sync.ts`
  - [x] NomGap: `src/lib/offline-queue.ts` (~150 lines), store sync in `fasting-store.ts`
  - [x] MindLyst: `PlatformSyncManager.kt`, `PlatformApiClient.kt`
- [x] Design unified API:
  ```typescript
  createSyncEngine({ productId, entities, storage, apiClient, onConflict })
  engine.push(entity, data)
  engine.delete(entity, id)
  engine.pull() → Promise<SyncResult>
  engine.fullSync() → Promise<SyncResult>
  engine.getQueueLength() → number
  engine.onStatusChange(callback)
  ```
- [x] Implement offline queue with configurable storage adapter:
  - [x] `LocalStorageAdapter` (web)
  - [x] `MMKVAdapter` (React Native) — interface only, consumer provides MMKV instance
  - [x] `InMemoryAdapter` (testing)
- [x] Implement retry with exponential backoff (max 5 attempts, configurable)
- [x] Implement conflict detection (timestamp-based)
- [x] Implement conflict strategies: `server-wins`, `client-wins`, `last-write-wins`, `manual`
- [x] Implement queue deduplication (collapse multiple updates to same entity)
- [x] Implement connectivity detection (`navigator.onLine` + custom event)
- [x] Implement auto-flush on reconnect
- [x] Integrate with `@bytelyst/telemetry-client` (track sync success/failure/conflicts)
- [x] Write comprehensive tests — **31 tests** (`packages/sync/src/sync.test.ts`)
- [ ] Migrate ChronoMind web to use `@bytelyst/sync` (prove it works)
- [x] Document API, storage adapters, conflict strategies

**Acceptance Criteria:**

- `createSyncEngine()` returns a working engine with all methods
- Offline queue persists across page reloads (localStorage adapter)
- Conflicts detected and resolved per configured strategy
- ChronoMind web successfully migrated (no regression)
- 20+ tests passing

**Estimated effort:** 3 days
**Dependencies:** `@bytelyst/api-client` (already exists)
**Blocks:** Phase 3 native SDKs (Swift/Kotlin port)

---

## 3. Phase 2 — Developer Experience (Weeks 3–6)

> **Theme:** Tools that eliminate scaffolding and boilerplate for new products.

### 3.1 CLI Scaffolder (`@bytelyst/create-app`)

**What:** Interactive CLI that generates a fully wired product repo from a product manifest.

**Location:** `packages/create-app/`

**Tasks:**

- [x] Create package structure with `bin/create-app.ts` entry point
- [x] Implement interactive prompts (using `@inquirer/prompts` or `prompts`):
  - [x] Product name, ID, bundle ID, domain
  - [x] Platform selection: Web (Next.js), Expo (React Native), iOS (SwiftUI), Android (Compose)
  - [x] Feature selection: Auth, Billing, Telemetry, Feature Flags, Offline Sync, Push Notifications
  - [x] User dashboard: Yes/No
- [x] Create template directory structure:
  - [x] `templates/nextjs-web/` — Next.js 16 App Router with all `src/lib/` wiring
  - [x] `templates/expo-rn/` — Expo SDK with router, Zustand, MMKV
  - [x] `templates/swiftui-ios/` — SwiftUI scaffold with services
  - [x] `templates/compose-android/` — Jetpack Compose scaffold
  - [x] `templates/agents-md/` — AGENTS.md template
  - [x] `templates/shared/` — .gitignore, .env.example, README.md, CLAUDE.md
- [x] Implement template engine (simple `{{VARIABLE}}` replacement + conditional blocks)
- [x] Implement `product.json` generation from prompts
- [x] Implement auto-registration:
  - [x] POST to platform-service `/products` to register product
  - [x] Add containers to `cosmos-init.ts` (or via API)
  - [x] Seed default feature flags
- [x] Implement git init + first commit
- [x] Add `--from product.json` flag to skip prompts and use existing manifest
- [x] Add `--dry-run` flag
- [x] Write tests — **26 tests** (2 test files: `scaffolder.test.ts`, `template-engine.test.ts`)
- [ ] Publish as `npx @bytelyst/create-app`

**Acceptance Criteria:**

- Running `npx @bytelyst/create-app` interactively produces a buildable repo
- `--from product.json` produces same result non-interactively
- Generated Next.js app starts with `npm run dev` immediately
- Generated AGENTS.md is complete and accurate
- All `src/lib/` wiring files have correct product ID

**Estimated effort:** 5 days
**Dependencies:** Phase 1 product manifest
**Blocks:** None (but enables faster onboarding)

---

### 3.2 Auth UI Kit (`@bytelyst/auth-ui`)

**What:** Shared React components for auth flows — login, register, forgot password, email verification, SSO.

**Location:** `packages/auth-ui/`

**Tasks:**

- [x] Create package structure
- [x] Design component API (props interface for each component):
  - [x] `<LoginForm productName logo theme ssoProviders onSuccess />`
  - [x] `<RegisterForm productName logo theme onSuccess />`
  - [x] `<ForgotPasswordForm productName logo theme />`
  - [x] `<ResetPasswordForm productName logo theme />`
  - [x] `<VerifyEmailForm productName logo theme />`
  - [x] `<OnboardingShell steps currentStep onNext onBack onComplete />`
- [x] Implement `LoginForm`:
  - [x] Email + password form with validation
  - [x] "Remember me" checkbox
  - [x] SSO buttons (Google, Apple, Microsoft) — configurable via `<SocialButtons>`
  - [x] "Forgot password" link
  - [x] "Create account" link
  - [x] Loading/error states
- [x] Implement `RegisterForm`:
  - [x] Name, email, password, confirm password
  - [x] Terms checkbox
  - [x] `<PasswordStrengthBar>` indicator
- [x] Implement `ForgotPasswordForm` → `ResetPasswordForm` flow
- [x] Implement `VerifyEmailForm` with code input
- [x] Implement `OnboardingShell` — step indicator, navigation, progress bar
- [x] Implement `<AuthPageLayout>` — shared layout wrapper with `<MfaChallenge>` support
- [x] Theme support: dark/light, custom accent colors via CSS custom properties
- [x] Responsive design (mobile + desktop)
- [x] Accessibility (ARIA labels, keyboard navigation, screen reader)
- [x] Write tests — **54 tests** (2 test files: `auth-ui.test.tsx`, `new-components.test.tsx`)
- [ ] Migrate one existing product's auth pages to use the kit (prove it works)

**Acceptance Criteria:**

- `<LoginPage>` handles full login flow including error states
- Components work with any product's theme
- All forms validate client-side before submission
- Accessible (passes axe-core audit)
- One product successfully migrated

**Estimated effort:** 5 days
**Dependencies:** `@bytelyst/auth-client` (already exists)
**Blocks:** None

---

### 3.3 API Route Generator

**What:** CLI to generate Next.js App Router API routes from entity definitions.

**Location:** `packages/create-app/src/generators/api-routes.ts` (or standalone script)

**Tasks:**

- [x] Design CLI: `npx @bytelyst/gen:api-route --name tasks --methods GET,POST,PATCH,DELETE`
- [x] Generate `src/app/api/<name>/route.ts` with GET (list) + POST (create)
- [x] Generate `src/app/api/<name>/[id]/route.ts` with GET (detail) + PATCH + DELETE
- [x] Include standard patterns: auth check, Zod validation, error handling, rate limiting
- [x] Support `--with-handler` flag to wrap with `apiHandler()` HOF
- [x] Write tests for generated output

**Acceptance Criteria:**

- Generated routes pass TypeScript type-check
- Routes include auth, validation, error handling
- `--with-handler` wraps routes in error handler HOF

**Estimated effort:** 2 days
**Dependencies:** None
**Blocks:** None

---

### 3.4 AGENTS.md Auto-Generator

**What:** Generate AGENTS.md from `product.json` + repo scan.

**Location:** `packages/create-app/src/generators/agents-md.ts`

**Tasks:**

- [x] Scan repo directory structure (glob pattern)
- [x] Read `product.json` for identity, stack, conventions
- [x] Count test files and estimate test count
- [x] List key files per domain (auto-detect from directory names)
- [x] Generate markdown from template with all sections:
  - [x] Project identity table
  - [x] Repo layout tree
  - [x] Tech stack table
  - [x] Coding conventions (inherited from ByteLyst + product-specific)
  - [x] File ownership map
  - [x] Build & test commands
  - [x] Common pitfalls
- [x] Output to `AGENTS.md` + symlinks: `CLAUDE.md`, `.cursorrules`, `.windsurfrules`
- [x] Add `--update` flag to refresh without overwriting custom sections
- [x] Add to `/repo_update-agent-docs` workflow

**Acceptance Criteria:**

- Generated AGENTS.md matches quality of hand-written ones
- `--update` preserves custom sections (marked with `<!-- CUSTOM -->` fences)
- All 4 agent doc files stay in sync

**Estimated effort:** 2 days
**Dependencies:** Phase 1 product manifest
**Blocks:** None

---

## 4. Phase 3 — Native & Declarative (Weeks 7–12)

> **Theme:** Eliminate boilerplate for native apps and backend CRUD entirely.

### 4.1 Native Swift SDK (`ByteLystSDK`)

**What:** A Swift Package providing auth, telemetry, feature flags, and sync for all iOS/macOS/watchOS apps.

**Location:** New repo: `bytelyst-ios-sdk/` (or `packages/ios-sdk/` in common-plat)

**Tasks:**

- [x] Create Swift Package structure with targets: `ByteLystPlatformSDK`, `ByteLystPlatformSDKTests`
- [x] Implement `ByteLystPlatform` entry point:
  ```swift
  let platform = ByteLystPlatform(config: .init(
      productId: "peakpulse",
      baseUrl: "https://api.peakpulse.app",
      authStorage: KeychainTokenStorage()
  ))
  ```
- [x] **Auth module:** `BLAuthClient` — login, register, logout, token refresh, SmartAuth (OAuth, MFA, passkeys)
- [x] **Telemetry module:** `BLTelemetryClient` — event queue, batch flush, install ID, session rotation
- [x] **Feature flags module:** `BLFeatureFlagClient` — polling, caching, isEnabled
- [x] **Kill switch module:** `BLKillSwitchClient` — fail-open check
- [x] **HTTP layer:** `BLPlatformClient` — URLSession with auth injection, request ID
- [x] **Crash reporter:** `BLCrashReporter` — MetricKit integration
- [x] **Keychain:** `BLKeychain` + `BLKeychainAccessor` — secure storage
- [x] **Audit logger:** `BLAuditLogger` — local rotating JSON audit log
- [x] Unified `ByteLystPlatform` entry point wiring all services with `start()/stop()` lifecycle
- [x] Write XCTests — **30 tests** (7 test files: ByteLystPlatformTests, BLPlatformConfigTests, BLKillSwitchClientTests, BLFeatureFlagClientTests, BLTelemetryClientTests, BLKeychainTests, BLAuthClientSmartAuthTests)
- [ ] Migrate ChronoMind iOS to use `ByteLystPlatformSDK` (prove it works)
- [x] Document setup, usage, and migration guide

**Acceptance Criteria:**

- Single `import ByteLystSDK` gives access to auth, telemetry, flags, sync
- All modules work offline (queue/cache) and sync when online
- ChronoMind iOS successfully migrated
- 30+ tests passing
- Works on iOS 16+, macOS 14+, watchOS 10+

**Estimated effort:** 8 days
**Dependencies:** Phase 1 sync engine (for design parity)
**Blocks:** None

---

### 4.2 Native Kotlin SDK (`com.bytelyst.sdk`)

**What:** Equivalent of the Swift SDK for Android/Wear OS.

**Location:** New module or repo for Kotlin SDK

**Tasks:**

- [x] Create Kotlin library module structure (`packages/kotlin-platform-sdk/`)
- [x] Implement `ByteLystPlatform` entry point (mirror Swift API) — `start()/stop()` lifecycle
- [x] **Auth module:** `BLAuthClient` — login, register, token refresh, SmartAuth (OAuth, MFA, passkeys, device trust)
- [x] **Telemetry module:** `BLTelemetryClient` — coroutine-based batching, SharedPreferences persistence
- [x] **Feature flags module:** `BLFeatureFlagClient` — coroutine polling, in-memory cache
- [x] **Kill switch module:** `BLKillSwitchClient` — fail-open check
- [x] **HTTP layer:** `BLPlatformClient` — OkHttp with auth injection + request ID
- [x] **Secure store:** `BLSecureStore` — EncryptedSharedPreferences
- [x] **Audit logger:** `BLAuditLogger` — local rotating JSON audit log
- [x] **Diagnostics:** `DiagnosticsClient`, `BreadcrumbTrail`, `DeviceStateCollector`, `NetworkInterceptor`
- [x] **UI components:** `BLAuthUI`, `BroadcastUI`, `SurveyUI` (Jetpack Compose)
- [x] Write JUnit5 tests — **64 tests** (9 test files: BLPlatformConfigTest, BLPlatformClientTest, BLFeatureFlagClientTest, BLKillSwitchClientTest, BLKillSwitchResultTest, BLTelemetryEventTest, BLLicenseClientTest, BLAuthClientSmartAuthTest, DiagnosticsTypesTest)
- [ ] Migrate ChronoMind Android to use SDK
- [x] Document setup and usage

**Acceptance Criteria:**

- Same API surface as Swift SDK
- Works with Jetpack Compose and traditional Android
- 25+ tests passing
- ChronoMind Android migrated

**Estimated effort:** 6 days
**Dependencies:** Phase 1 sync engine (for design parity)
**Blocks:** None

---

### 4.3 Universal Dashboard Shell (`@bytelyst/dashboard-shell`)

**What:** A configurable Next.js layout with built-in pages for profile, billing, settings, notifications.

**Location:** `packages/dashboard-shell/`

**Tasks:**

- [x] Create package structure (`packages/dashboard-shell/`)
- [x] Implement `<DashboardShell>` layout component:
  - [x] Responsive sidebar (collapsible)
  - [x] Top bar with user avatar + dropdown
  - [x] Navigation with `NavItem[]` and `NavSection[]` support
- [x] Implement built-in pages:
  - [x] `<ProfilePage>` — view/edit user profile
  - [x] `<BillingPage>` — current plan, payment info
  - [x] `<SettingsPage>` — preferences
- [x] Configuration via props:
  - [x] `productName`, `logo`, `navItems[]`, `features{}`
  - [x] Feature flags: `billing: true/false`, `profile: true/false`, etc.
- [x] Theme support via `--bl-shell-*` CSS custom properties
- [x] Write tests — **41 tests** (`packages/dashboard-shell/src/__tests__/dashboard-shell.test.tsx`)
- [ ] Migrate user-dashboard-web to use shell (prove it works)
- [x] Document configuration options

**Acceptance Criteria:**

- `<DashboardShell navItems={[...]} features={{ billing: true }}>` renders full layout
- Built-in pages are functional (not just stubs)
- Responsive on mobile
- user-dashboard-web successfully migrated

**Estimated effort:** 8 days
**Dependencies:** Phase 1 shared UI components, Phase 2 auth UI kit
**Blocks:** None

---

### 4.4 Declarative YAML Backend Modules

**What:** Define backend CRUD modules as YAML files; runtime generates Fastify routes automatically.

**Location:** `services/platform-service/src/lib/declarative-loader.ts`

**Tasks:**

- [x] Design YAML schema for module definitions:
  - [x] Entity name, container, partition key, id prefix
  - [x] Field definitions with types (`string`, `number`, `boolean`, `date`, `enum`, `array`), validation rules, defaults
  - [x] Endpoint definitions with method, path, auth requirements (`none`, `user`, `admin`)
  - [x] Custom endpoint stubs (`custom: true`)
- [x] Implement YAML parser + Zod schema validator (`declarative-schema.ts`)
- [x] Implement runtime route generator (`declarative-loader.ts`):
  - [x] Read all `.module.yaml` files from a `modules/declarative/` directory
  - [x] Generate Fastify routes at startup (no code generation — runtime interpretation)
  - [x] Apply standard patterns: auth, validation, error handling
  - [x] Support filtering, sorting, pagination for list endpoints
- [x] Implement standard CRUD handlers:
  - [x] List with filtering + sorting + pagination
  - [x] Get by ID
  - [x] Create with validation
  - [x] Update (partial) with validation
  - [x] Delete
- [x] Support custom endpoints (skipped at registration, for manual implementation)
- [x] MemoryStore for testing / no-DB mode
- [x] Write comprehensive tests — **34 tests** (`declarative-loader.test.ts`)
- [ ] Migrate one simple existing module to YAML as proof (e.g., `changelog`)
- [ ] Document YAML schema and usage

**Acceptance Criteria:**

- A `.module.yaml` file with no TypeScript produces working CRUD endpoints
- Standard CRUD operations work correctly (create, read, update, delete, list)
- Custom endpoints generate stub files for manual implementation
- One existing module successfully migrated
- No performance regression vs hand-written modules

**Estimated effort:** 8 days
**Dependencies:** Phase 1 module generator (informs schema design)
**Blocks:** None

---

## 5. Phase 4 — Polish & Scale (Weeks 13–16)

> **Theme:** Cross-product visibility, zero-touch provisioning, and final polish.

### 5.1 Auto-Registration on First Request

**Tasks:**

- [x] Detect unknown `productId` in platform-service request middleware
- [x] Auto-create product doc with minimal fields (id, name from header, createdAt)
- [ ] Auto-create Cosmos containers listed in product manifest (if provided via config endpoint)
- [x] Auto-seed default feature flags (global defaults)
- [x] Log to audit: `product.auto_registered`
- [ ] Add admin notification on new product registration
- [x] Security: rate limit new registrations, require valid JWT
- [x] Tests (8 tests)

**Estimated effort:** 3 days
**Dependencies:** Phase 1 product manifest

---

### 5.2 Multi-Product Telemetry Dashboard

**Tasks:**

- [x] Add cross-product query endpoint: `GET /telemetry/cross-product?products=a,b,c`
- [ ] Admin dashboard page: Ops → Cross-Product Telemetry
  - [x] Total events/day per product (stacked bar chart) — API ready
  - [x] Error rates per product (line chart) — API ready
  - [x] Top error clusters across products — API ready
  - [ ] Feature adoption comparison
- [x] Tests (6 tests)

**Estimated effort:** 4 days
**Dependencies:** Existing telemetry module

---

### 5.3 Shared Onboarding Analytics

**Tasks:**

- [x] New platform-service module: `modules/onboarding/`
  - [x] Track step completion: `POST /onboarding/step { productId, userId, stepName, stepIndex }`
  - [x] Track completion: `POST /onboarding/complete { productId, userId }`
  - [x] Query funnel: `GET /onboarding/funnel?productId=x` → step-by-step conversion rates
- [ ] Admin dashboard widget: Onboarding Funnel visualization
- [x] Cosmos container: `onboarding_events` + `onboarding_completions` (partitioned by `productId`)
- [x] Tests (8 tests)

**Estimated effort:** 3 days
**Dependencies:** None

---

### 5.4 Pre-Built Stripe Checkout Flow

**Tasks:**

- [x] New endpoint: `POST /billing/checkout` → creates Stripe Checkout Session
  - [x] Input: `productId`, `userId`, `priceId`/`plan`, `successUrl`, `cancelUrl`
  - [x] Returns: `{ sessionId, url }`
- [ ] Client redirect helper in `@bytelyst/api-client`
- [x] Support trial periods, promo codes, tax (collectTax, customerEmail, metadata)
- [x] Tests (6 tests)

**Estimated effort:** 2 days
**Dependencies:** Existing Stripe module

---

### 5.5 Cross-Product User Dashboard

**Tasks:**

- [x] Investigate: single dashboard showing all products a user has accounts in
- [x] Unified settings page (preferences apply across products)
- [x] Single sign-on across products (shared JWT, product-scoped permissions)
- [x] Design doc: `docs/design/CROSS_PRODUCT_USER_DASHBOARD.md` (deferred to post-SmartAuth Phase 5)

**Estimated effort:** 5 days (investigation + design + prototype)
**Dependencies:** Phases 1–3

---

## 6. Dependency Graph

```
product.json (P1.1)
    │
    ├──→ CLI scaffolder (P2.1)
    │        ├──→ AGENTS.md auto-gen (P2.4)
    │        └──→ API route generator (P2.3)
    │
    ├──→ Auto-registration (P4.1)
    │
    └──→ Design token generation (existing)

Module generator (P1.2)
    │
    └──→ Declarative YAML modules (P3.4)

Shared UI components (P1.3)
    │
    └──→ Dashboard shell (P3.3)
              │
              └──→ Cross-product dashboard (P4.5)

Sync engine (P1.4)
    │
    ├──→ Swift SDK (P3.1)
    └──→ Kotlin SDK (P3.2)

Auth UI kit (P2.2)
    │
    └──→ Dashboard shell (P3.3)

Telemetry (existing)
    │
    └──→ Multi-product telemetry (P4.2)
```

---

## 7. Success Metrics

| Metric                         | Baseline (Now)          | After Phase 1-2     | After Phase 3-4 | Target     |
| ------------------------------ | ----------------------- | ------------------- | --------------- | ---------- |
| Time to first `npm run dev`    | 3–4 hours               | 15 minutes          | 5 minutes       | < 10 min   |
| Time to deployed MVP           | 3–5 days                | 1–2 days            | 4–8 hours       | < 8 hours  |
| Lines of code per new product  | ~3,000                  | ~1,500              | ~500            | < 500      |
| Backend modules (manual code)  | 150–250 lines each      | 0 lines (generated) | 0 lines (YAML)  | 0 lines    |
| Native SDK integration         | ~400 lines per platform | ~400 lines          | ~20 lines       | < 20 lines |
| Repeated files across products | ~15 files               | ~5 files            | ~0 files        | 0          |
| Test coverage of platform      | 1,141 tests             | 1,300+              | 1,500+          | > 1,500    |

---

## 8. Risk Register

| Risk                                                   | Impact | Likelihood | Mitigation                                                       |
| ------------------------------------------------------ | ------ | ---------- | ---------------------------------------------------------------- |
| Over-abstraction makes platform hard to understand     | High   | Medium     | Keep escape hatches; any generated code can be hand-modified     |
| YAML declarative modules too limited for complex logic | Medium | Medium     | Hybrid approach: YAML for CRUD, hand-written for complex modules |
| Native SDKs diverge from web package API               | Medium | Low        | Shared API design doc; test parity                               |
| CLI scaffolder templates go stale                      | High   | High       | Auto-test: CI runs scaffolder and builds result weekly           |
| Manifest schema changes break existing products        | High   | Medium     | Versioned schema with migration guide                            |
| Performance overhead of runtime YAML interpretation    | Low    | Low        | Benchmark; fall back to code generation if needed                |
| Too many packages to maintain                          | Medium | Medium     | Regular dependency audit; merge underused packages               |

---

## Appendix: Quick Reference

### All New Packages (by phase)

| Phase | Package                                         | Type              |
| ----- | ----------------------------------------------- | ----------------- |
| 1     | Product manifest (in `@bytelyst/config`)        | Extension         |
| 1     | `@bytelyst/dashboard-components`                | New package       |
| 1     | `@bytelyst/sync`                                | New package       |
| 1     | Module generator (in platform-service)          | Script            |
| 2     | `@bytelyst/create-app`                          | New package (CLI) |
| 2     | `@bytelyst/auth-ui`                             | New package       |
| 2     | API route generator (in create-app)             | Script            |
| 2     | AGENTS.md generator (in create-app)             | Script            |
| 3     | `ByteLystSDK` (Swift)                           | New repo/package  |
| 3     | `com.bytelyst.sdk` (Kotlin)                     | New repo/package  |
| 3     | `@bytelyst/dashboard-shell`                     | New package       |
| 3     | Declarative module loader (in platform-service) | Runtime           |

### Total Estimated Effort

| Phase     | Duration     | Effort      |
| --------- | ------------ | ----------- |
| Phase 1   | Weeks 1–2    | 9 days      |
| Phase 2   | Weeks 3–6    | 14 days     |
| Phase 3   | Weeks 7–12   | 30 days     |
| Phase 4   | Weeks 13–16  | 17 days     |
| **Total** | **16 weeks** | **70 days** |
