# Investment Trading Product Monorepo PRD

## 1. Overview

`learning_ai_invt_trdg` is the new canonical monorepo for ByteLyst's trading product line. It replaces the current fragmented setup across:

- `bytelyst-trading-dashboard-web`
- `bytelyst-trading-bot-service`
- `bytelyst-trading-dashboard-mob`

The monorepo will consolidate product surfaces into a single product architecture patterned after `learning_ai_fastgap` and integrated deeply with `learning_ai_common_plat`.

This is not a lift-and-shift repo merge. It is a product and architecture reset with explicit goals:

- make trading a first-class ByteLyst ecosystem product
- remove duplicated auth, configuration, and platform integration code
- centralize product identity and operational controls
- preserve trading-domain moat locally while moving generic platform concerns to shared packages
- create a cleaner foundation for regulated, multi-surface, safety-critical trading workflows

## 2. Product Vision

Build a unified AI-assisted trading operating system across web, mobile, and backend that gives users safe, observable, controllable, and explainable trade automation.

The product should feel like one coherent system, not three separate applications:

- web is the power surface for setup, monitoring, audit, and advanced control
- mobile is the companion surface for secure monitoring, alerts, approvals, and lightweight intervention
- backend is the execution and state authority for trading logic, reconciliation, capital controls, and lifecycle correctness
- common platform provides the shared ecosystem rails for auth, kill switch, telemetry, flags, diagnostics, licensing, and product governance

### 2.1 Product Positioning

Working positioning:

- serious trading operations product
- AI-assisted, but not AI-unbounded
- operator-safe and backend-authoritative
- ecosystem-native inside ByteLyst, not a one-off exception

## 3. Problem Statement

The current trading stack has valuable domain logic but the overall system is structurally fragmented.

### 3.1 Current fragmentation

- Web dashboard has custom auth/session handling and direct Supabase-heavy patterns.
- Bot service has its own service configuration, runtime control surface, and platform boundary logic.
- Mobile app is currently a thin UI shell without real ecosystem integration.
- Product identity is not canonical across all surfaces.
- Kill switch, maintenance mode, telemetry, and feature control are not treated as shared product infrastructure.
- Some integration points between frontend and backend appear inconsistent or partially implemented.

### 3.2 Why this matters

This product operates in a high-trust, high-risk domain:

- trading errors can lose money
- stale state can trigger wrong actions
- missing kill switches can turn incidents into losses
- inconsistent auth boundaries create severe security risk
- duplicated operational logic increases regression probability

The current setup can evolve further, but not safely or efficiently at the velocity expected for a serious multi-surface product.

## 4. Product Goals

### 4.1 Primary goals

1. Create one canonical product monorepo for the trading product.
2. Adopt ByteLyst common-platform primitives for auth, kill switch, telemetry, feature flags, diagnostics, config, and product identity.
3. Preserve and migrate the existing trading domain capabilities without carrying over architectural duplication.
4. Establish backend authority boundaries and surface contracts that are explicit, typed, and testable.
5. Support staged migration from the three legacy repos to the new monorepo with minimal production risk.

### 4.2 Secondary goals

1. Improve operator experience for support, incident response, and release management.
2. Make web and mobile share a common product model and runtime semantics.
3. Reduce future engineering cost by eliminating repeated auth/config/bootstrap code.
4. Make the repo structurally consistent with mature ByteLyst product repos such as `learning_ai_fastgap`.

## 5. Non-Goals

The following are explicitly out of scope for the monorepo foundation phase:

- rewriting core trading strategy logic for novelty
- moving strategy engine, execution logic, reconciliation logic, or capital ledger logic into `learning_ai_common_plat`
- replacing proven trading-domain logic unless required by correctness or architecture boundaries
- building a marketplace, billing, social layer, or new AI workflow before the platform foundation is stable
- merging all legacy history verbatim into the new repo without curation

## 6. Target Users

### 6.1 Retail and advanced trading users

- configure strategies
- monitor signals, entries, positions, and history
- understand why trades did or did not execute
- manage profile-level and account-level risk controls
- intervene manually when necessary

### 6.2 Operators and admins

- pause or resume trading globally or per scope
- inspect runtime health and reconciliation status
- monitor telemetry, incidents, and product safety posture
- manage maintenance windows, flags, and product rollouts

### 6.3 Engineering and support teams

- diagnose auth, sync, and runtime issues quickly
- release across surfaces consistently
- maintain a shared product contract across web, mobile, and backend

## 7. Product Principles

### 7.1 Safety before convenience

Trading control, capital protection, kill switches, reconciliation integrity, and correct auth boundaries take precedence over UX convenience.

### 7.2 One product, three surfaces

Web, mobile, and backend must behave as one product with shared terminology, shared product identity, and consistent control semantics.

### 7.3 Common where generic, local where differentiated

Move generic platform concerns into shared packages. Keep trading-domain moat local.

### 7.4 Backend authority

The backend is the authority for trade execution, runtime state, safety decisions, and audit-relevant lifecycle truth. Frontends render and request; they do not become safety authorities.

### 7.5 Migration without chaos

The new repo should be built as the target system while the old repos remain stable references until cutover.

## 8. Product Surfaces

## 8.1 Web

Primary responsibilities:

- authenticated dashboard shell
- strategy/profile management
- configuration and admin control
- observability and reconciliation views
- lifecycle, entries, positions, history, marketplace, and settings
- operator-grade UX for incident triage and runtime understanding

Must integrate:

- `@bytelyst/react-auth`
- platform-driven kill switch / maintenance mode
- feature flags
- telemetry and diagnostics
- shared product metadata

## 8.2 Mobile

Primary responsibilities:

- secure session restore
- launch-time kill switch handling
- live overview, alerts, positions, and compact history
- secure user actions for manual review/intervention
- notification and incident awareness

Must integrate:

- `@bytelyst/react-native-platform-sdk`
- platform auth and token lifecycle
- telemetry and diagnostics
- feature flags
- kill switch and maintenance gate

## 8.3 Backend

Primary responsibilities:

- market data ingestion
- trade decision execution
- order lifecycle and history integrity
- reconciliation and repair flows
- runtime control and operator safety
- tenant/user scoping
- API and websocket contracts for clients

Must integrate:

- common config and product identity conventions
- shared auth middleware/contracts where applicable
- platform-compatible telemetry and diagnostics
- kill switch semantics and maintenance-aware behavior

## 8.4 Platform-Service vs Product-Backend Boundary

Platform-service owns:

- product-aware auth primitives
- feature flags
- product-level kill switch and maintenance controls
- telemetry ingestion and diagnostics hooks
- shared product metadata and cross-product policy controls

Trading backend owns:

- trading state authority
- orders, positions, lifecycle, and reconciliation authority
- runtime loop controls
- global trade halt
- tenant-level trade disable
- profile-level trade disable
- trading admin operations and domain audit events

Web and mobile own:

- authenticated presentation
- user and operator interaction flows
- clear communication of degraded, halted, or maintenance states

## 9. Core Product Capabilities

### 9.1 Identity and access

- canonical product identity via `shared/product.json`
- user auth through shared ByteLyst platform contracts
- role-aware access for admin and non-admin users
- device/session aware auth state where applicable

### 9.2 Safety and kill switches

- product-wide kill switch
- maintenance mode
- global trade halt
- profile-level or tenant-level trading disable
- backend loop safety gates
- clear UX behavior when the product is disabled or degraded

Ownership model:

- platform-service owns product accessibility controls such as product-wide kill switch and maintenance state
- trading backend owns trading-behavior controls such as global trade halt, tenant-level disable, profile-level disable, and loop-level execution safety
- web and mobile render these states and expose only authorized actions; they do not become the enforcement authority

### 9.3 Runtime observability

- health, loop status, reconciliation status, and operational warnings
- client and backend telemetry
- correlation IDs across web, mobile, backend, and platform-service
- diagnostics hooks for remote support and incident review

### 9.4 Trading execution and lifecycle integrity

- authoritative backend trade lifecycle
- canonical orders, positions, history, and capital state
- reconciliation and recovery flows
- deterministic behavior under retries or restart
- explicit lifecycle audit model

### 9.5 Configuration and control

- typed config schema and validation
- environment-aware runtime configuration
- feature-gated rollout of risky or incomplete features
- admin controls that are secure, auditable, and reversible

### 9.6 Explainability and trust

- why a trade executed or did not execute
- why a rule blocked action
- clear distinction between user-visible summaries and backend authority decisions

### 9.7 Product Scope by Release

Foundation release scope:

- monorepo structure
- canonical product identity
- shared platform integration model
- backend-first contract stabilization

Product v1 scope:

- authenticated web dashboard
- authenticated mobile monitor and incident-intervention surface
- backend authority for trading state and controls
- overview, alerts, positions, history, and runtime controls
- limited, explicitly approved mobile interventions such as pause/resume and other tightly scoped safety actions

Deferred:

- full mobile parity with advanced web strategy management
- nonessential novelty features
- product expansion outside the core trading workflow

## 10. Product Architecture

## 10.1 Desired repo structure

```text
learning_ai_invt_trdg/
├── app/ or src/                 # Expo mobile app
├── web/                         # Web dashboard
├── backend/                     # Trading backend / bot service
├── shared/
│   └── product.json             # Canonical product identity
├── docs/
├── scripts/
├── pnpm-workspace.yaml
├── package.json
├── docker-compose.yml
└── .env.example
```

### 10.2 Shared dependency model

The monorepo will consume `learning_ai_common_plat` packages by local workspace-style file references, following the proven FastGap pattern:

- `../learning_ai_common_plat/packages/*`

The product backend remains product-specific. Platform-service remains the shared destination for:

- auth
- feature flags
- kill switch
- telemetry
- diagnostics
- licensing/subscription related concerns if needed later

### 10.3 Legacy Source Mapping

Migration source mapping:

- `bytelyst-trading-dashboard-web` -> `web/`
- `bytelyst-trading-bot-service` -> `backend/`
- `bytelyst-trading-dashboard-mob` -> mobile `app/` or `src/`

This mapping is conceptual, not a requirement to copy files literally. Valuable domain logic and product UX should be ported. Duplicate bootstrap code and dead weight should not.

### 10.4 Domain ownership split

Keep in product repo:

- trading strategy logic
- execution manager
- reconciliation services
- capital ledger
- lifecycle integrity and safety logic
- product-specific API contracts
- trading UI and product-specific mobile UX

Move to common platform or shared package usage:

- auth bootstrap
- shared auth UI/provider patterns
- session/token lifecycle helpers
- product identity
- generic telemetry and diagnostics
- kill switch client usage
- feature flag client usage
- shared config loading patterns

### 10.5 System of Record Decisions

Recommended authority model:

- platform-service is the source of truth for platform-level identity and controls
- trading backend is the source of truth for runtime trading state
- durable domain state comes from backend-managed database and exchange reconciliation
- web and mobile caches are convenience layers only

## 11. Product Identity

The monorepo must define canonical product identity in `shared/product.json`.

Minimum required fields:

- `productId`
- `displayName`
- `description`
- `domain`
- `backendPort`
- `bundleId`
- `platforms`
- `primarySurface`
- `mobileCompanion`
- `licensePrefix`
- `configDirName`
- `envVarPrefix`
- `packageName`
- `version`

Recommended initial stance:

- one product identity for the whole trading system
- web, mobile, and backend are surfaces of the same product, not separate products
- sub-surface names can be used operationally, but not as separate top-level product IDs

## 12. Functional Requirements

### 12.1 Monorepo bootstrap

- root package management with pnpm
- workspace layout similar to FastGap
- common scripts for verify, build, lint, and test
- environment examples and local-dev instructions

### 12.2 Web requirements

- authenticated web shell
- shared auth provider integration
- maintenance and kill-switch blocking states
- typed API client layer for backend communication
- websocket/session handling consistent with auth state
- admin/operator views protected by role checks

### 12.3 Mobile requirements

- auth bootstrap and restore flow
- launch-time kill switch check
- shared telemetry startup
- feature flag polling or refresh policy
- secure token storage and refresh handling
- notification-ready architecture

### 12.4 Backend requirements

- explicit API contract for frontend and mobile clients
- websocket auth and tenant scoping
- typed config schema
- secure admin controls
- kill-switch aware trading loop behavior
- audit and observability hooks

### 12.5 Migration requirements

- preserve critical trading logic from legacy repos
- avoid porting dead code and inconsistent glue
- support staged cutover by surface
- maintain production continuity during migration

### 12.6 Critical User Journeys

1. A user signs in on web and sees only authorized, scoped trading state.
2. A user signs in on mobile and restores the same scoped state.
3. An operator pauses or resumes trading and all surfaces reflect the state clearly.
4. A user can understand why a trade fired, was blocked, or was skipped.
5. The backend restarts and rebuilds authoritative lifecycle state without silent drift.
6. During maintenance or kill-switch activation, each surface behaves consistently and safely.

## 13. Non-Functional Requirements

### 13.1 Security

- no unauthenticated trading actions
- no stale token trust shortcuts
- no product control endpoints without explicit authorization
- mobile and web behavior consistent with backend auth authority

### 13.2 Reliability

- restart-safe runtime behavior
- reconciliation-safe lifecycle recovery
- kill-switch behavior must fail safe
- degraded platform-service conditions must have defined fallback behavior

### 13.3 Observability

- telemetry across all surfaces
- structured logs with trace and correlation fields
- auditable admin/control actions
- backend health and safety metrics exposed consistently

### 13.4 Maintainability

- DRY by design for bootstrap logic
- no parallel auth systems
- no parallel kill-switch implementations
- clear module ownership

### 13.5 Performance

- web must remain responsive under live updates
- mobile must optimize battery/network usage
- backend loops must not regress in latency due to platform integration

### 13.6 Documentation and Operational Clarity

- operator controls must be documented
- kill-switch semantics must be documented
- cutover and rollback paths must be documented
- repo ownership and module boundaries must be understandable without tribal knowledge

### 13.7 Constraints and Assumptions

Constraints:

- legacy repos remain active references during migration
- common-platform integration should use existing shared packages where possible
- safety-critical trading behavior cannot tolerate ambiguous ownership boundaries

Assumptions:

- one canonical product identity across surfaces is acceptable
- platform-service remains the home for generic ecosystem services
- Supabase-heavy flows may need transitional adapters before final convergence
- mobile should launch as monitor/intervene-first rather than parity-first

## 14. Risks

### 14.1 Architecture risks

- carrying too much legacy shape into the new monorepo can preserve old problems
- over-extracting domain logic into common platform can blur ownership and weaken trading safety boundaries

### 14.2 Migration risks

- partial migration can create double-maintained logic
- auth changes can break web and mobile clients if backend boundaries are not stabilized first
- kill switch semantics can become ambiguous if app maintenance mode and trade-halt mode are conflated

### 14.3 Product risks

- mobile may become a cosmetic mirror instead of a true product surface if not scoped clearly
- operator workflows may remain buried in backend or docs unless explicitly designed into the product

## 15. Success Metrics

### 15.1 Foundation metrics

- all three surfaces live in one monorepo
- single canonical product identity exists and is used by all surfaces
- all surfaces use common-platform auth and kill-switch integration patterns
- zero duplicated bootstrap implementations for auth, telemetry, and kill switch

### 15.2 Engineering metrics

- no custom auth provider remains in web if shared provider covers the need
- no mobile hand-rolled platform bootstrap remains for generic platform concerns
- backend config and control boundaries are typed and documented

### 15.3 Product metrics

- authenticated user can sign in and restore session consistently across web and mobile
- operator can halt product activity through defined control paths
- users can understand state, risk, and execution outcomes from surface UX

### 15.4 Launch Quality Gates

- backend auth boundaries are enforced and tested
- trade-halt and maintenance behavior are tested
- session restore works on web and mobile
- websocket auth and scoping are validated
- telemetry identifiers are present across surfaces
- rollback and cutover procedures are documented

## 16. Delivery Strategy

The new monorepo will be treated as the target system, not a passive archive.

Recommended migration order:

1. Define product identity, repo skeleton, and platform integration contracts.
2. Stabilize backend contracts and control boundaries.
3. Migrate or rebuild web against those contracts.
4. Build mobile against the same contracts using the React Native platform SDK.
5. Complete validation, observability, and cutover planning.

## 17. Open Questions

These must be resolved early:

1. Will the trading product use one canonical product ID for all surfaces, or is there a real business reason to split mobile/web/backend identity?
2. Which auth source remains authoritative during early migration: current Supabase-backed identity or direct platform-service identity flows?
3. What exact kill-switch model is required?
4. Does mobile support approve/reject/override actions, or is it monitor-first at launch?
5. Which existing web tabs are truly product-critical for v1 of the monorepo and which should be deferred behind flags?

## 18. Immediate PRD Acceptance Criteria

This PRD is acceptable when the implementation roadmap it drives does all of the following:

- treats the new monorepo as the source of future product evolution
- uses FastGap as the structural template, not as a direct code clone
- uses common platform as the shared ecosystem backbone
- preserves trading-domain logic as product-owned
- explicitly plans migration, safety, auth, kill switch, telemetry, and DRY cleanup
