# Shakti Domain — Architecture

> **Shakti** — Physical Discipline and Movement Intelligence Platform

---

## Domain Purpose

Shakti is a full-stack fitness technology platform serving practitioners,
instructors, studios, and gyms across multiple training disciplines. Named after
the Hindu concept of primordial cosmic energy, the domain embodies the
intersection of ancient physical practices and cutting-edge AI.

Shakti is a **pure library domain** — 28 libraries, no standalone service
applications (no `apps/shakti`, no `services/shakti`). Applications built on
Shakti consume its libraries to deliver mobile apps, web platforms, instructor
portals, and studio management systems. Every library is self-contained: each
`package.json` declares an empty `dependencies` map, and there are no
cross-domain imports anywhere in `libs/shakti/`.

The domain's libraries divide into three broad groups. The **foundation and
contract layer** (`@shakti/core`, `@shakti/api`, `@shakti/sdk`) provides types,
validation, database schema, event bus, authorization logic, and the intended
API surface. The **discipline and intelligence layer** covers the five physical
training domains (yoga, strength, martial arts, combat sports, mobility) plus
the analytical libraries that work across them (biometrics, form analysis,
personalization, the two SOTA libraries, and the fighting-ruleset bridge). The
**delivery and operations layer** provides the engagement, community, content,
studio, events, certification, and platform infrastructure modules that make the
platform function as a product. Note that `dance` and `pilates` are values of
the `Discipline` enum in `@shakti/core`, not separate library packages.

---

## Library Organization

The 28 libraries under `libs/shakti/` are organized by concern. The tree below
maps the physical directory layout to the role each library plays:

```
libs/shakti/
├── core/                     # Types, validation schemas, declarative DB schema, event bus, auth
├── api/                      # API building-block configuration registry (not a running server)
├── sdk/                      # SDK core / resources / utilities modules
├── instructor-sdk/           # Instructor tooling: assessment, analytics, client mgmt, program builder
├── web/                      # Web portal page-specification modules
├── mobile/                   # Mobile feature-specification modules
│
├── yoga/                     # Asana taxonomy, pranayama, sequencing, styles, meditation, ayurveda
├── strength/                 # Exercise library, compounds, olympic, calisthenics, program templates
├── martial-arts/             # Techniques, striking, grappling, MMA, traditional forms, weapons, ranks
├── combat-sports/            # Boxing, kickboxing, Muay Thai, wrestling, MMA-training modules
├── mobility/                 # Stretching, joint mobility, SMR, recovery, prehab, rehabilitation
│
├── biometrics/               # Heart rate / HRV, body composition, performance & recovery metrics, devices
├── form-analysis/            # Pose-estimation knowledge base, form scoring, rep/technique analysis
├── personalization/          # Practitioner profiling, adaptive programming, AI workout generation
├── gamification/             # Achievements, streaks, XP, challenges, leaderboards, rewards
├── community/                # Profiles, activity feed, groups, accountability partners, messaging
│
├── audio/                    # Audio workout content, music integration, voice commands
├── video/                    # Video content management, follow-along, live streaming, library
├── visualization/            # Movement/anatomy visualization, AR, VR, avatar system
│
├── events/                   # Calendar, class scheduling, competitions, live delivery, workshops
├── certifications/           # Credential management, continuing education, licensing, Shakti program
├── studio/                   # Studio management: classes, equipment, facility, membership, staff
│
├── fighting-ruleset-bridge/  # Deterministic combat-sport → fighting-game frame-data transform
├── sota-critical/            # VBT, readiness gating, biomarkers, CGM, V2 combat-style classifier
├── sota-advanced/            # Neuromuscular fatigue, progressive overload AI, longevity
├── documentation/            # Documentation-specification modules
├── testing/                  # Unit / integration / e2e / performance / security test utilities
└── deployment/               # CI/CD, containerization, GPU/ML infra, infra setup, observability
```

**Total: 28 library projects** (0 applications, 0 standalone services).

---

## Architectural Layers

The libraries stack into six horizontal layers, each building on the one below
it. Reading the diagram from bottom to top shows the direction of dependency:
the Foundation is required by everything, while the Consumer Layer is what
product applications actually import.

```
┌─────────────────────────────────────────────────────────────────┐
│  CONSUMER LAYER                                                 │
│  @shakti/sdk · @shakti/instructor-sdk                          │
│  @shakti/web · @shakti/mobile                                  │
├─────────────────────────────────────────────────────────────────┤
│  API CONTRACT LAYER                                             │
│  @shakti/api                                                    │
├─────────────────────────────────────────────────────────────────┤
│  DISCIPLINE MODULES                                             │
│  @shakti/yoga · @shakti/strength · @shakti/martial-arts        │
│  @shakti/combat-sports · @shakti/mobility                      │
├─────────────────────────────────────────────────────────────────┤
│  INTELLIGENCE LAYER                                             │
│  @shakti/form-analysis · @shakti/personalization               │
│  @shakti/biometrics · @shakti/sota-critical                    │
│  @shakti/sota-advanced · @shakti/fighting-ruleset-bridge       │
├─────────────────────────────────────────────────────────────────┤
│  ENGAGEMENT LAYER                                               │
│  @shakti/gamification · @shakti/community                      │
│  @shakti/audio · @shakti/video · @shakti/visualization         │
├─────────────────────────────────────────────────────────────────┤
│  OPERATIONS LAYER                                               │
│  @shakti/studio · @shakti/events · @shakti/certifications      │
├─────────────────────────────────────────────────────────────────┤
│  FOUNDATION                                                     │
│  @shakti/core (types, schema, event bus, auth)                 │
└─────────────────────────────────────────────────────────────────┘
```

---

## Core Design Patterns

The following five patterns are the architectural decisions that define how
Shakti libraries behave and why they are structured the way they are.

### 1. Multi-Discipline Composition

Each physical discipline (yoga, strength, martial arts, combat sports, mobility)
is implemented as an independent library with its own domain model,
exercise/technique database, and programming logic. The `@shakti/core`
foundation provides the shared types (UserProfile, Workout, ExerciseSet) that
all discipline modules build upon. Applications select which discipline modules
to include rather than loading the entire platform.

This approach means a yoga-only app can ship without pulling in the strength
training or combat sports libraries, keeping bundle size proportional to the
features the application actually uses.

### 2. Form Analysis as a Shared Service

`@shakti/form-analysis` is not discipline-specific — it provides a generic
form-scoring and joint-angle analysis knowledge base (`form-scoring.ts` defines
a `DeviationType` fault taxonomy, `FormCategory`, severity and grade scales)
that disciplines can reference with their own technique criteria. This avoids
duplicating form-analysis infrastructure across disciplines.

The library is self-contained. `motion-capture.ts` references pose-estimation
approaches (MediaPipe, TensorFlow.js) descriptively; the implemented source
imports no external pose library and no other Oshun domain.

### 3. Biometric-Driven Adaptation

`@shakti/biometrics` is the domain's biometric knowledge base.
`device-integrations.ts` catalogs named wearable and sensor platforms (Apple
HealthKit, Google Health Connect, Garmin Connect, Whoop, Oura, Fitbit, Polar,
COROS, Bluetooth GATT services, ANT+ profiles, Tonal, PUSH) as descriptive
configuration records — not live SDK clients. `heart-rate.ts` provides
heart-rate zones, HRV metrics, and recovery benchmarks with calculation helpers.
`@shakti/sota-critical` extends this conceptually with more advanced signals
(VBT velocity, CGM glucose, genetic markers) in its own modules.

### 4. Event-Driven Progression

Training events are published to the domain event bus from workout logging.
`@shakti/gamification` subscribes to these events and handles achievement
checking, streak updates, and XP awards without coupling to the workout logging
code. This ensures gamification enrichment adds zero latency to the core workout
logging flow.

By keeping gamification as an event subscriber rather than an inline call, the
core workout logging path stays simple and testable, and the gamification
library can be upgraded or replaced without touching session-logging code.

### 5. SOTA as Separate Libraries

State-of-the-art features that require specialized hardware or research-grade
algorithms are isolated in `@shakti/sota-critical` and `@shakti/sota-advanced`.
This separation allows the main platform to ship and be stable while SOTA
features are developed and validated independently. Applications that want
cutting-edge features opt in explicitly.

The distinction between the two SOTA libraries is intentional:
`@shakti/sota-critical` contains features that are close to production-ready
today (VBT, CGM, readiness gating, voice control, the V2 combat-style
classifier), while `@shakti/sota-advanced` contains differentiating capabilities
that require deeper research integration (neuromuscular fatigue, predictive
analytics, longevity protocols).

---

## Discipline Module Responsibilities

Discipline libraries are knowledge bases — they declare typed domain records and
expose `getAll*` / `get*` / `search*` accessors. They do not own their own
database tables; the shared schema lives in `@shakti/core/db-schema.ts` (see
_Data Architecture_ below). This table summarizes the module files and the kinds
of domain content each library covers:

| Library                 | Source modules                                                                                 | Representative content                                                            |
| ----------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `@shakti/yoga`          | `asanas`, `pranayama`, `sequences`, `styles`, `meditation`, `ayurveda`                         | Asana taxonomy (chakra/dosha/drishti/bandha), breathwork, sequencing, dosha logic |
| `@shakti/strength`      | `exercises`, `compounds`, `olympic`, `calisthenics`, `programs`, `powerlifting`, `hypertrophy` | 15 program templates + 5 deload protocols; 1RM estimation; periodization          |
| `@shakti/martial-arts`  | `techniques`, `striking`, `grappling`, `mma`, `traditional`, `weapons`, `ranks`, `sparring`    | Technique progression, traditional forms, weapons, belt/rank systems              |
| `@shakti/combat-sports` | `boxing`, `kickboxing`, `muay-thai`, `wrestling`, `mma-training`                               | Round-based training, training camps, weight-cutting, sport conditioning          |
| `@shakti/mobility`      | `stretching`, `joint-mobility`, `smr`, `recovery`, `injury-prevention`, `rehabilitation`       | CARs/PAILs/RAILs protocols, foam rolling, prehab and return-to-training           |

---

## Data Architecture

Rather than using a mainstream ORM, Shakti defines its database schema **as
data**. This is a deliberate choice: because Shakti is a pure library domain
with no running service, there is no migration runner to execute — the schema
definition serves as a source of truth that can emit DDL when needed.

The schema is declared in `@shakti/core/db-schema.ts` using a custom declarative
`TableDef` model — there is no Drizzle ORM, no Prisma, and no migration runner.
A hand-written generator (`generateCreateTableSQL` / `generateAllTablesSQL`)
emits PostgreSQL DDL strings targeting schema `shakti`.

`ALL_SHAKTI_TABLES` holds **11 tables**:

| Table               | Purpose                                        |
| ------------------- | ---------------------------------------------- |
| `practitioners`     | Core practitioner profiles                     |
| `disciplines`       | Physical disciplines on the platform           |
| `discipline_styles` | Styles/variations within a discipline          |
| `techniques`        | Techniques within a discipline/style           |
| `exercises`         | Exercise library with movement data            |
| `programs`          | Multi-week training program definitions        |
| `sessions`          | Logged training sessions with set/rep data     |
| `personal_records`  | Per-exercise personal records                  |
| `achievements`      | Achievement definitions for gamification       |
| `belt_ranks`        | Belt/rank systems for martial-arts disciplines |
| `streaks`           | Consistency / training streaks                 |

All discipline knowledge (asana taxonomies, exercise libraries, technique
progressions) lives in the in-memory `Map` registries inside each discipline
library. Only the data that needs to survive across requests — sessions,
personal records, practitioner profiles, streaks — has a corresponding database
table.

---

## Dependencies on Other Oshun Domains

In the current source there are **no cross-domain imports** — every
`libs/shakti/*` library is fully self-contained, and every `package.json`
declares an empty `dependencies` map. Shakti does not import `@aja/*`,
`@oshun/*`, `@galatea/*`, or any other domain. `@shakti/core` provides the
domain's own types, event bus, and authorization logic in-house.

This strict isolation is intentional: it means any application can pick up
individual Shakti libraries without accidentally pulling in unrelated Oshun
domain packages. It also keeps the domain portable to environments where the
rest of the monorepo is not available.

### Sister-Monorepo Integration (documented contract, not an import)

The V2 fighting-game project (a separate monorepo) consumes two Shakti libraries
through V2-side adapters: `@shakti/fighting-ruleset-bridge` via
`@v2/shakti-ruleset-bridge`, and the `@shakti/sota-critical` V2 combat-style
classifier via `@v2/shakti-style-classification`. Those `@v2/*` adapters live in
the V2 repo. The integration is a documented contract
(`V2/docs/integration/shakti-ruleset-bridge.md`,
`V2/docs/integration/shakti-style-classification.md`); no Shakti source imports
any `@v2` package.

The boundary exists because the V2 fighting-game has its own rollback-netcode
determinism requirements and versioning lifecycle that differ from Shakti's
fitness-platform lifecycle. By keeping the adapters in the V2 repo, both sides
can evolve their interfaces independently, and Shakti remains a clean library
domain that does not carry V2-specific build dependencies.

---

## Build and Test Configuration

Shakti libraries use standard Nx executors for building and testing. When Nx is
unavailable (for example, when it detects duplicate project names from active
worktrees), the libraries can be type-checked and tested directly:

- **Build executor**: `@nx/js:tsc` for most libraries;
  `@shakti/fighting-ruleset-bridge` uses `nx:run-commands`.
- **Test executor**: `@nx/vite:test` (Vitest); `@shakti/fighting-ruleset-bridge`
  runs Vitest via `nx:run-commands`.
- **Tags**: `scope:shakti`, `type:lib`, `layer:domain` (the bridge additionally
  carries `domain:combat`).

Direct invocations when Nx is unavailable:

```bash
# Type check
cd libs/shakti/<library> && npx tsc --noEmit

# Run tests
cd libs/shakti/<library> && npx vitest run

# Test specific discipline module
cd libs/shakti/yoga && npx vitest run
cd libs/shakti/strength && npx vitest run
```
