# Shakti Domain - Developer Guide

> Comprehensive development guide for the Shakti physical discipline, fitness,
> and movement intelligence domain.

---

## Prerequisites

### Required Software

| Tool       | Version | Purpose                                  |
| ---------- | ------- | ---------------------------------------- |
| Node.js    | >= 20.0 | Runtime for all Shakti libraries         |
| pnpm       | >= 10.0 | Package manager (workspace protocol)     |
| Git        | >= 2.40 | Version control                          |
| TypeScript | ^6.0.3  | Compile-time type checking (via catalog) |

### Discipline-Specific Knowledge

Developers working on exercise science libraries should be familiar with:

- **Exercise physiology** - Rep schemes, volume/intensity relationships,
  periodization models, recovery mechanics
- **Biomechanics** - Joint angles, force vectors, movement planes, kinetic chain
  analysis (for form analysis)
- **Yoga taxonomy** - Sanskrit asana names, alignment cues, contraindications,
  pranayama timing patterns
- **Martial arts terminology** - Striking/grappling nomenclature, belt/rank
  systems, sparring rule sets

### Optional Tooling

| Tool             | Purpose                                                      |
| ---------------- | ------------------------------------------------------------ |
| TensorFlow.js    | Form analysis ML model development (`@shakti/form-analysis`) |
| MediaPipe        | Pose estimation model integration                            |
| React Native CLI | Mobile app development (`@shakti/mobile`)                    |
| Expo             | Mobile app bundling                                          |

### Environment Variables

No environment variables are required for building or unit-testing Shakti
libraries. For integration tests involving the database:

```bash
# Database (required for @shakti/core db-schema features)
DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/oshun_dev

# Redis (required for session caching in @shakti/api)
REDIS_URL=redis://localhost:6379
```

---

## Project Structure

The Shakti domain contains 27 libraries under `libs/shakti/`:

```
libs/shakti/
  api/                     # REST API endpoints (core, exercise, session, social)
  audio/                   # Audio content, music integration, voice commands
  biometrics/              # Heart rate, HRV, body composition, device integrations
  certifications/          # Instructor credentials, continuing education, licensing
  combat-sports/           # Boxing, kickboxing, muay thai, wrestling, MMA training
  community/               # Social profiles, feeds, groups, accountability partners
  core/                    # Foundation: types, schemas, db-schema, events, auth
  deployment/              # Infrastructure, CI/CD, containers, monitoring, GPU/ML
  documentation/           # Technical docs, user docs, content guidelines
  events/                  # Class scheduling, live delivery, competitions, calendar
  form-analysis/           # Motion capture, form scoring, real-time feedback
  gamification/            # Achievements, streaks, XP/leveling, challenges
  instructor-sdk/          # Program builder, client management, business analytics
  martial-arts/            # Techniques, striking, grappling, MMA, traditional forms
  mobile/                  # React Native app (home, workouts, health integration)
  mobility/                # Stretching, joint mobility, SMR, recovery, rehab
  personalization/         # Practitioner profiling, adaptive programming, AI workouts
  sdk/                     # External developer SDK (core client, resources, utils)
  sota-advanced/           # Advanced features: AI coach, wearable, predictive
  sota-critical/           # Critical features: VBT, VR fitness, smart gym, voice
  strength/                # Exercises, compounds, olympic, powerlifting, programs
  studio/                  # Facility, equipment, class, membership, staff management
  testing/                 # Unit, integration, e2e, performance, security test utils
  video/                   # Video content management, instructional library, streaming
  visualization/           # 3D avatar, anatomy visualization, VR/AR training
  web/                     # Next.js web application (dashboard, instructor portal)
  yoga/                    # Asanas, pranayama, sequences, styles, meditation, ayurveda
```

### Individual Library Layout

```
libs/shakti/<library>/
  package.json             # Name, version, ESM exports, dependencies
  project.json             # Nx configuration (build, lint, test targets)
  tsconfig.json            # Extends tsconfig.base.json
  tsconfig.lib.json        # Library compilation config
  tsconfig.spec.json       # Test compilation config
  vitest.config.ts         # Vitest config with __dirname root
  src/
    index.ts               # Barrel export file
    <module>.ts             # Implementation files (flat or nested)
    <module>.spec.ts        # Co-located tests
```

---

## Local Development Setup

### Initial Setup

```bash
# Clone the repository
git clone git@github.com:GreyChimp/oshun.git
cd oshun

# Install all dependencies
pnpm install
```

### Infrastructure (Optional)

For development involving the database layer or API:

```bash
# Start PostgreSQL and Redis
docker compose -f docker/docker-compose.dev.yml up -d postgres redis
```

---

## Building Libraries

### Build a Single Library

```bash
pnpm nx build @shakti/core
```

### Build All Shakti Libraries

```bash
pnpm nx run-many --target=build --projects=tag:scope:shakti
```

### Build Configuration

The standard build configuration for Shakti libraries:

```json
{
  "build": {
    "executor": "@nx/js:tsc",
    "outputs": ["{options.outputPath}"],
    "options": {
      "outputPath": "dist/libs/shakti/core",
      "main": "libs/shakti/core/src/index.ts",
      "tsConfig": "libs/shakti/core/tsconfig.lib.json",
      "assets": []
    }
  }
}
```

Build output goes to `dist/libs/shakti/<library>/`.

---

## Testing

### Run Tests for a Single Library

```bash
pnpm nx test @shakti/core
```

### Run All Domain Tests

```bash
pnpm nx run-many --target=test --projects=tag:scope:shakti
```

### Watch Mode

```bash
npx vitest --config libs/shakti/yoga/vitest.config.ts --watch
```

### Test Configuration

Shakti libraries use a vitest configuration that sets `root` to `__dirname`:

```typescript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    root: __dirname,
    include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
    },
  },
});
```

Key points:

- `root: __dirname` ensures vitest resolves paths relative to the library root
- `globals: true` enables `describe`, `it`, `expect` without imports
- Tests use `.spec.ts` or `.test.ts` suffix and are co-located with source

### Coverage

```bash
npx vitest --config libs/shakti/yoga/vitest.config.ts --coverage
```

### Testing Patterns

**Exercise database tests** should verify data integrity: every exercise should
have required fields (name, muscle groups, equipment), and enum values should be
within defined ranges:

```typescript
describe('exercises', () => {
  it('every exercise has at least one target muscle group', () => {
    for (const exercise of EXERCISES) {
      expect(exercise.targetMuscles.length).toBeGreaterThan(0);
    }
  });
});
```

**Training program tests** should verify periodization logic: volume and
intensity should progress according to the program model (e.g., 5/3/1 should
cycle through 5-rep, 3-rep, and 1-rep weeks).

**Yoga sequence tests** should validate that transitions between poses are valid
(no impossible jumps between poses requiring different base positions).

**Form scoring tests** should use known joint angle inputs and verify that
scores match expected quality ratings within a tolerance.

**Biometric calculation tests** should verify zone calculations, HRV analysis,
and 1RM estimates against published formulas (Epley, Brzycki).

---

## Linting

### Lint a Single Library

```bash
pnpm nx lint @shakti/yoga
```

### Lint All Shakti Libraries

```bash
pnpm nx run-many --target=lint --projects=tag:scope:shakti
```

### Key Lint Rules

- ESM imports must use explicit `.js` extensions for relative paths
- Use `import { foo, type Bar } from '...'` to combine value and type imports
- Prefix unused variables with `_`

---

## Common Development Tasks

### Adding a New Library

1. Create the directory:

```bash
mkdir -p libs/shakti/new-library/src
```

2. Create `project.json`:

```json
{
  "name": "@shakti/new-library",
  "$schema": "../../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/shakti/new-library/src",
  "projectType": "library",
  "tags": ["scope:shakti", "layer:domain", "type:lib"],
  "targets": {
    "build": {
      "executor": "@nx/js:tsc",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/libs/shakti/new-library",
        "main": "libs/shakti/new-library/src/index.ts",
        "tsConfig": "libs/shakti/new-library/tsconfig.lib.json",
        "assets": []
      }
    },
    "lint": {
      "executor": "@nx/eslint:lint",
      "options": {
        "lintFilePatterns": ["libs/shakti/new-library/**/*.ts"]
      }
    },
    "test": {
      "executor": "@nx/vite:test",
      "options": {
        "config": "libs/shakti/new-library/vitest.config.ts"
      }
    }
  }
}
```

3. Create `package.json`:

```json
{
  "name": "@shakti/new-library",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "exports": {
    ".": {
      "import": "./src/index.js",
      "types": "./src/index.d.ts"
    }
  },
  "devDependencies": {
    "vitest": "catalog:"
  }
}
```

4. Create `vitest.config.ts`:

```typescript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    root: __dirname,
    include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
    },
  },
});
```

5. Create `src/index.ts` as a barrel export.

6. The `tsconfig.base.json` already contains the wildcard mapping
   `"@shakti/*": ["libs/shakti/*/src/index.ts"]` (inferred from the pattern used
   by other domains with this layout), so no additional path mapping is needed.

7. Run `pnpm install`.

### Adding a New Exercise Discipline

New training disciplines follow the pattern established by `@shakti/yoga`,
`@shakti/strength`, `@shakti/martial-arts`, and `@shakti/combat-sports`:

1. Create the library as described above
2. Implement a technique/exercise database with structured data
3. Implement progression systems and programming logic
4. Add integration with `@shakti/form-analysis` for technique-specific form
   scoring rules
5. Add entries to the `@shakti/personalization` recommendation engine

### Working with the Core Foundation

`@shakti/core` provides five key modules:

- **types** - Domain type definitions (exercises, sessions, practitioners)
- **schemas** - Zod validation schemas for all domain entities
- **db-schema** - Drizzle ORM database schema design
- **events** - Domain event definitions (session completed, streak updated)
- **auth** - Authentication utilities

Import from core using:

```typescript
import { type Exercise, SessionSchema, exerciseEvents } from '@shakti/core';
```

### Integrating Biometric Devices

The `@shakti/biometrics` library provides device integration modules. When
adding a new device integration:

1. Add a new sub-module under `device-integrations/`
2. Implement the device protocol adapter
3. Map device-specific metrics to the standardized biometric types in
   `@shakti/core`
4. Add tests with mock device data

---

## Key Patterns and Conventions

### Core as the Foundation

`@shakti/core` has zero direct dependencies beyond `vitest` (dev only). All
other libraries build on core's type definitions and schemas. The core module
uses Zod for validation schemas and Drizzle ORM for database schema definition.

### Minimal Package Dependencies

Most Shakti libraries (like `@shakti/biometrics`) have zero runtime
dependencies, only dev dependencies on `vitest`. Domain logic is implemented in
pure TypeScript:

```json
{
  "devDependencies": {
    "vitest": "catalog:"
  }
}
```

### ESM Module System

All libraries use ESM (`"type": "module"`):

```typescript
export * from './types.js';
export * from './schemas.js';
export * from './db-schema.js';
```

### Project Tags

```json
["scope:shakti", "layer:domain", "type:lib"]
```

### Architecture Layers

1. **Core** - Types, schemas, database, events, auth
2. **Disciplines** - Yoga, strength, martial arts, combat sports, mobility
3. **Intelligence** - Biometrics, form analysis, personalization, gamification
4. **Platform** - API, web, mobile, SDKs
5. **Infrastructure** - Testing, deployment, documentation
6. **SOTA** - State-of-the-art and advanced features

Libraries in higher layers depend on lower layers but never the reverse.

### Catalog Dependencies

Dev dependencies use `"catalog:"` references, pulling versions from the pnpm
catalog defined in `pnpm-workspace.yaml`. This ensures consistent versions
across all libraries:

```json
{
  "devDependencies": {
    "vitest": "catalog:"
  }
}
```

---

## Debugging Tips

### TypeScript Path Resolution

The `tsconfig.base.json` maps Shakti libraries with a wildcard pattern. If
imports fail:

1. Verify the library's `src/index.ts` exists and exports correctly
2. Run `pnpm install` to refresh workspace links
3. Check that the `tsconfig.json` extends `../../../tsconfig.base.json`

### Test Root Issues

If vitest cannot find test files, verify that `root: __dirname` is set in the
vitest config. This is necessary because Nx runs vitest from the workspace root,
not the library root.

### Database Schema Validation

When working with `@shakti/core` db-schema changes, run the Drizzle ORM type
checker to validate schema consistency before running migrations.

### Form Analysis ML Model Issues

The `@shakti/form-analysis` library uses TensorFlow.js and MediaPipe. If model
loading fails in tests:

- Ensure `@tensorflow/tfjs-node` is available in the test environment
- Mock the model loading in unit tests; use real models only in integration
  tests
- Verify that model files are accessible at the configured paths

### Nx Cache Issues

```bash
pnpm nx reset
```

### Viewing the Dependency Graph

```bash
pnpm nx graph --focus=@shakti/core
```

---

## Quick Reference

| Action                     | Command                                                       |
| -------------------------- | ------------------------------------------------------------- |
| Install dependencies       | `pnpm install`                                                |
| Build one library          | `pnpm nx build @shakti/<lib>`                                 |
| Build all Shakti libraries | `pnpm nx run-many --target=build --projects=tag:scope:shakti` |
| Test one library           | `pnpm nx test @shakti/<lib>`                                  |
| Test all Shakti libraries  | `pnpm nx run-many --target=test --projects=tag:scope:shakti`  |
| Lint one library           | `pnpm nx lint @shakti/<lib>`                                  |
| Lint all Shakti libraries  | `pnpm nx run-many --target=lint --projects=tag:scope:shakti`  |
| Reset Nx cache             | `pnpm nx reset`                                               |
| View dependency graph      | `pnpm nx graph --focus=@shakti/core`                          |
