# AI Agent Guidelines for Suno Android

This document provides guidelines for AI-powered IDE assistants (e.g., Cursor, Windsurf)
when contributing to the Suno Android codebase. Follow these rules to ensure consistent,
high-quality code and seamless collaboration with human developers.

## 1. Repository Overview

- See `docs/architecture.md` for a detailed architecture summary.
- **Project Setup**: Run `./INSTALL` after cloning to install dependencies.
- **IDE**: Use Android Studio Ladybug | 2024.2.1 via JetBrains Toolbox for best experience.
- **Build Variants**: Default is `prodDebug`; use `staffDebug` for development with OAuth support.
- **Authentication**: Uses Clerk service with rotating JWT tokens (expires every minute).
- **Media App**: Full background playback support with Media3 and foreground service.

## 2. Coding Conventions

- **EditorConfig**: Follow settings in `.editorconfig` (4-space indent, UTF-8, LF line endings,
  max length 120, Kotlin and Java styles).
- **Kotlin Style**: Use official `ktlint` style via pre-commit hook (`./tools/ktlint.sh`).
- **Static Analysis**: Run `detekt` via pre-commit hook (`./tools/detekt.sh`).
- **Formatting**: Optimize imports automatically (Android Studio → Editor → Auto Import).

## 3. Architectural Patterns

- **Dependency Injection**: Hilt across all modules.
- **State Management**: MVI pattern, Kotlin Flow (StateFlow for UI state, SharedFlow for events).
- **Threading**: Coroutines with structured concurrency and appropriate dispatchers.
- **Data Flow**:

  ```
  UI (Compose) → ViewModel → Repository → [Network/Database]
      ↑                   ↑          ↓              ↓
      └────────── StateFlow ←────────┴─────────────┘
  ```

- **Testing**: JUnit & MockK for unit tests; Compose testing for UI; Hilt integration tests.
- **Security**: Certificate pinning, encrypted preferences, ProGuard/R8.

## 4. Common Tasks for AI Agents

### 4.1 Code Generation

- Place new screens under `app/src/main/java/com/suno/android/...` with matching package structure.
- For Compose UI, leverage `common-ui` components and theming.
- Name `ViewModel` classes with suffix `VM`.
- Expose public APIs through interfaces in shared modules.

### 4.2 Refactoring

- When moving classes, update Hilt modules and DI bindings accordingly.
- Adjust import paths and update affected tests.
- Update `docs/architecture.md` via the sync_docs workflow if architecture changes.

### 4.3 Testing

**Test Structure and Locations:**

- Unit tests: `common-*/src/test/kotlin` or `app/src/test/kotlin`
- UI tests: `app/src/androidTest/kotlin` using Compose testing
- Test naming: `given <precondition> when <action> then <expectation>` format with backticks and spaces

**Running Tests:**

- Full test suite: `./gradlew <module name>:testProdDebugUnitTest --tests <test suite name>`
- Specific test: `./gradlew <module name>:testProdDebugUnitTest --tests <test suite name>.<test name>`

**AI Agent Testing Workflow:**

1. **Write comprehensive tests** covering all public methods and edge cases
2. **Immediately after writing tests**, scan the entire test file for duplicates using these criteria:
   - **REMOVE**: Tests with identical setup, method calls, and assertions (true duplicates)
   - **REMOVE**: Tests that verify the same behavior with only cosmetic naming differences
   - **REMOVE**: Multiple tests for the same success/failure scenario of the same method
   - **KEEP**: Tests for different methods (even if similar behavior)
   - **KEEP**: Tests for different input scenarios or edge cases
   - **KEEP**: Tests that verify different aspects of the same operation (e.g., return value vs. state change vs. side effects)
3. **Extract duplicated logic into helper functions** at the bottom of the test suite:
   - **EXTRACT**: Repeated setup/teardown logic into helper methods
   - **EXTRACT**: Common mock configurations and responses into factory methods
   - **EXTRACT**: Repeated assertion patterns into verification helpers
   - **EXTRACT**: Complex object creation into builder helper functions
   - **KEEP**: Helper functions focused and single-purpose
   - **KEEP**: Helper function names descriptive and clear about their purpose
4. **Run the test suite** to ensure all test suite tests pass
5. **Verify test coverage** remains comprehensive after cleanup

## 5. Documentation

- Update README (`README.md`) or docs templates in `docs/templates/` as needed.
- To regenerate architecture docs, run the GitHub Actions workflow: `.github/workflows/sync_docs.yaml`.

## 6. Module Structure

**Core Modules:**

- `app/`: Main application module with activities, services, and DI setup
- `common-ui/`: Shared Compose components and theming
- `common-data/`: Repository pattern implementation with business logic
- `common-networking/`: Retrofit-based API clients and network handling
- `common-db/`: Room database with entities, DAOs, and migrations
- `common-core-utils/`: Global utilities, error handling, lifecycle management
- `common-media/`: Media3-based playback engine and metadata management
- `common-analytics/`: Event tracking and performance monitoring
- `common-gating/`: Feature flags and A/B testing (Statsig)
- `common-i18n/`: Internationalization and localization
- `common-res/`: Shared resources

**Dependency Flow:**

```
app → common-ui → common-data → [common-networking, common-db]
 app → common-media, common-analytics, common-gating, common-i18n
```

## 7. Project-Specific Guidelines

### 7.1 Authentication (Clerk)

- **Token Management**: Handle both long-lived and short-lived (1-minute) JWT tokens
- **Token Rotation**: Long-lived tokens can expire anytime during API calls
- **OAuth Setup**: For debug builds, enable app links in device settings for OAuth to work
- **No Android SDK**: Clerk doesn't provide Android SDK; custom implementation required

### 7.2 Media Playback

- **Background Service**: Use `PlaybackMediaLibraryService` for background audio
- **State Sync**: Ensure bi-directional syncing between UI and media service state
- **Media3 Integration**: Leverage existing Media3 setup for consistent playback behavior
- **Metadata Management**: Use `MediaMetadataManager` for media information handling

### 7.3 Build Configuration

- **Debug OAuth**: Enable app links in emulator/device settings for OAuth in debug builds
- **Google Auth**: Requires device passcode/security for Google login on emulators
- **Variant Switching**: Changing build variant updates all submodules automatically
- **ProGuard/R8**: Security configurations already in place

### 7.4 IDE Configuration

- **Auto Import**: Enable "Add unambiguous imports" and "Optimize imports on the fly"
- **Live Templates**: Use provided templates for composables and screens in `docs/templates/`
- **Plugins**: Install ktlint and detekt plugins for real-time feedback
- **Toolbox**: Use JetBrains Toolbox for version management and project access

### 7.5 CI/CD Configuration

- **CI/CD Overview**: See `.github/ci.md` for comprehensive pipeline documentation
- **Fastlane Usage**: Always use `./fastlanew` instead of direct `fastlane` commands
- **GitHub Actions**: Located in `.github/workflows/` with reusable workflow patterns
- **Build Variants**: `staff` (Firebase) vs `prod` (Play Store), `debug` (APK) vs `release` (AAB)
- **Manual Builds**: Use `build-command.yml` workflow dispatch for custom builds
- **High-Risk Changes**: Apply `high-risk-change` label to PRs requiring production build validation

**Build & Distribution Architecture:**

- **Separation of Concerns**: Build workflows (`build-staff.yml`, `build-prod.yml`) only build and upload artifacts to GitHub Actions
- **Runway Integration**: Distribution to Firebase and Play Store is automated via Runway, which monitors GitHub artifacts
- **Manual PR Builds**: Use the `/build` slash command to create PR artifacts; distribution requires manual download from GitHub Actions
- **No Scheduled Jobs**: Previous scheduled distribution logic removed; Runway handles all automated distribution timing

**AI Agent CI/CD Maintenance:**

- **ALWAYS** update `.github/ci.md` when modifying GitHub Actions workflows (`.github/workflows/`)
- **ALWAYS** update `.github/ci.md` when modifying Fastlane configuration (`fastlane/` directory)
- **ALWAYS** update `.github/ci.md` when changing build variants, distribution logic, or environment variables
- Update the document sections relevant to your changes (workflows, lanes, security, etc.)
- Maintain the table of build variants and distribution targets for accuracy

## 8. Links

- [Architecture summary](docs/architecture.md)
- [CI/CD pipeline overview](.github/ci.md)
- [Live templates](docs/templates/)
- [Composable templates](docs/templates/composables-with-previews/composable-with-preview.md)
- [Screen templates](docs/templates/screens/screens.md)
