# Euterpe Developer Guide

> Comprehensive development guide for the Euterpe (Music/Audio) domain
> libraries.

This guide covers local development setup, building, testing, debugging, and
common development tasks for all 7 Euterpe libraries.

---

## Prerequisites

### Required Software

| Tool    | Version    | Purpose              |
| ------- | ---------- | -------------------- |
| Node.js | >= 20.0    | JavaScript runtime   |
| pnpm    | >= 10.0    | Package manager      |
| Nx      | (via pnpm) | Monorepo task runner |

### Installation

```bash
# From the repository root
pnpm install
```

No external services (databases, Redis, etc.) are required for Euterpe library
development. All libraries are pure TypeScript with zero or minimal runtime
dependencies.

---

## Project Structure

All Euterpe libraries live under `libs/euterpe/`:

```
libs/euterpe/
  core/         @euterpe/core         Core music primitives and foundations
  theory/       @euterpe/theory       Music theory intelligence engine
  genesis/      @euterpe/genesis      AI music generation engine
  studio/       @euterpe/studio       DAW (Digital Audio Workstation) engine
  master/       @euterpe/master       Audio mastering pipeline
  spatial/      @euterpe/spatial      Immersive audio and spatial sound
  voice/        @euterpe/voice        Voice technology (cloning, TTS, singing)
```

### Library Dependency Graph

```
@euterpe/core (standalone, zero deps)
  |
  +-- @euterpe/theory (peer: core)
  |     |
  |     +-- @euterpe/genesis (peer: core, theory)
  |     |     |
  |     |     +-- @euterpe/studio (peer: core, theory, genesis)
  |     |
  |     +-- @euterpe/master (peer: core, theory)
  |     |
  |     +-- @euterpe/voice (peer: core, theory)
  |
  +-- @euterpe/spatial (peer: core)
```

`@euterpe/core` has zero runtime dependencies and serves as the foundation for
all other libraries.

### Per-Library File Layout

Each library follows a consistent structure:

```
libs/euterpe/{library}/
  src/
    index.ts              Public API barrel export
    {module}/
      index.ts            Module barrel export
      {module}.ts         Implementation
      {module}.spec.ts    Tests
      types.ts            Module-specific types (if needed)
  package.json            Package metadata (name, version, dependencies)
  project.json            Nx project configuration (build, lint, test targets)
  tsconfig.json           Root TS config (references lib and spec configs)
  tsconfig.lib.json       Library build config (excludes tests)
  tsconfig.spec.json      Test config
  vitest.config.ts        Vitest configuration
```

---

## Building Libraries

### Build a Single Library

```bash
pnpm nx build @euterpe/core
pnpm nx build @euterpe/theory
pnpm nx build @euterpe/genesis
pnpm nx build @euterpe/studio
pnpm nx build @euterpe/master
pnpm nx build @euterpe/spatial
pnpm nx build @euterpe/voice
```

### Build All Euterpe Libraries

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

Nx respects the dependency graph, so building `@euterpe/studio` will
automatically build `core`, `theory`, and `genesis` first if needed.

### Build Configuration

All Euterpe libraries use the same build executor:

- **Executor:** `@nx/js:tsc`
- **Output:** `dist/libs/euterpe/{library}/`
- **Module format:** ESM (`"type": "module"` in package.json)
- **Declaration files:** Generated (`declaration: true`, `declarationMap: true`)

The TypeScript config chain is:

```
tsconfig.base.json (repo root)
  -> libs/euterpe/{library}/tsconfig.json
    -> libs/euterpe/{library}/tsconfig.lib.json (build)
    -> libs/euterpe/{library}/tsconfig.spec.json (tests)
```

The `tsconfig.lib.json` sets:

- `outDir: "../../../dist/out-tsc"`
- `declaration: true`, `declarationMap: true`
- Excludes `*.spec.ts` and `*.test.ts`

---

## Testing

### Run Tests for a Single Library

```bash
pnpm nx test @euterpe/core
pnpm nx test @euterpe/theory
pnpm nx test @euterpe/studio
```

### Run All Euterpe Tests

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

### Test Configuration

All libraries use Vitest via the `@nx/vite:test` executor. Each library has its
own `vitest.config.ts`:

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

export default defineConfig({
  test: {
    globals: true, // Use global test functions (describe, it, expect)
    environment: 'node', // Node.js test environment
    root: resolve(__dirname),
    include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
    },
  },
});
```

Key points:

- `globals: true` means you do not need to import `describe`, `it`, `expect`
- Test files are colocated with implementation: `{module}.spec.ts` next to
  `{module}.ts`
- Coverage uses V8 provider with text, JSON, and HTML reporters

### Test Count by Library

The domain has 57 test files total across all 7 libraries. Each sub-module
typically has its own dedicated spec file.

### Running Tests with Coverage

```bash
pnpm nx test @euterpe/core -- --coverage
```

### Running a Specific Test File

```bash
pnpm nx test @euterpe/theory -- --testPathPattern="harmony"
```

### Writing Tests

Tests follow a standard pattern:

```typescript
// src/notes/notes.spec.ts
import { describe, it, expect } from 'vitest';
import { createNote, noteToFrequency, STANDARD_TUNING } from './notes.js';

describe('Notes', () => {
  describe('createNote', () => {
    it('should create a note from scientific notation', () => {
      const note = createNote('C4');
      expect(note.pitchClass).toBe('C');
      expect(note.octave).toBe(4);
    });
  });

  describe('noteToFrequency', () => {
    it('should return 440 Hz for A4 in standard tuning', () => {
      const freq = noteToFrequency(createNote('A4'), STANDARD_TUNING);
      expect(freq).toBeCloseTo(440, 2);
    });
  });
});
```

Note: Because `globals: true` is set in vitest config, you can also omit the
import line and use `describe`, `it`, `expect` as globals.

---

## Linting

### Lint a Single Library

```bash
pnpm nx lint @euterpe/core
pnpm nx lint @euterpe/theory
```

### Lint All Euterpe Libraries

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

The lint executor is `@nx/eslint:lint`. ESLint rules are inherited from the
monorepo root configuration. Key rules to be aware of:

- `no-duplicate-imports`: Combine value and type imports into one statement. Use
  `import { createNote, type NoteConfig } from './notes.js'` instead of separate
  import lines.
- `@typescript-eslint/no-unused-vars`: Prefix intentionally unused variables
  with `_` (e.g., `_unusedParam`).

---

## Common Development Tasks

### Adding a New Sub-Module to an Existing Library

1. Create the module directory under `src/`:

```
libs/euterpe/{library}/src/{new-module}/
  index.ts           Barrel export
  {new-module}.ts    Implementation
  {new-module}.spec.ts   Tests
```

2. Export from the library's `src/index.ts`:

```typescript
export * as newModule from './{new-module}/index.js';
```

3. Run build and test to verify:

```bash
pnpm nx build @euterpe/{library}
pnpm nx test @euterpe/{library}
```

### Adding a New Euterpe Library

1. Create the library directory:

```
libs/euterpe/{new-lib}/
  src/
    index.ts
  package.json
  project.json
  tsconfig.json
  tsconfig.lib.json
  tsconfig.spec.json
  vitest.config.ts
```

2. Configure `project.json` following the existing pattern:

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

3. Configure `package.json`:

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

4. Add path mapping to `tsconfig.base.json` in the repo root if needed.

5. Run `pnpm install` to update lockfile.

### Integrating with Other Domains

Euterpe libraries are consumed by other domains as workspace dependencies. To
use Euterpe from another domain library:

1. Add the dependency to the consuming library's `package.json`:

```json
{
  "peerDependencies": {
    "@euterpe/core": "workspace:*"
  }
}
```

2. Import and use:

```typescript
import { createNote, noteToFrequency, STANDARD_TUNING } from '@euterpe/core';
```

---

## Key Patterns and Conventions

### Module Organization

`@euterpe/core` exports directly from its sub-modules:

```typescript
export * from './notes/index.js';
export * from './intervals/index.js';
export * from './scales/index.js';
```

Higher-level libraries use namespace exports to avoid name collisions:

```typescript
export * as harmony from './harmony/index.js';
export * as counterpoint from './counterpoint/index.js';
```

This means consumers import like:

```typescript
import { harmony, counterpoint } from '@euterpe/theory';
const analysis = harmony.analyzeProgression(chords);
```

### Tuning Systems

`@euterpe/core` treats tuning as a first-class concept. Six built-in tuning
systems are provided: `STANDARD_TUNING` (A440), `A432_TUNING`, `BAROQUE_TUNING`
(A415), `SCIENTIFIC_PITCH_TUNING`, `JUST_INTONATION_TUNING`, and
`PYTHAGOREAN_TUNING`. Functions that compute frequencies accept a tuning
parameter rather than hardcoding A440.

### World Music Support

Scale and notation systems include Indian ragas, Arabic maqamat, and Byzantine
neumes alongside Western scales. When adding new musical content, consider
whether it should support non-Western traditions.

### Notation Formats

Multiple notation formats are supported: scientific pitch (C4), Helmholtz (c'),
solfege (do), Nashville number system (1), Indian sargam (Sa), and Byzantine
neumes. Ensure new pitch-related code handles format conversion.

### Audio Buffer Handling

`@euterpe/core` provides audio buffer creation and manipulation utilities. These
are designed to be compatible with the Web Audio API but are not coupled to it,
allowing use in Node.js environments.

### MIDI Protocol

Full MIDI 1.0 protocol support is in `@euterpe/core`. Message types include note
on/off, control change, program change, pitch bend, and system exclusive. When
implementing new MIDI functionality, follow the existing message type pattern.

---

## Debugging Tips

### TypeScript Compilation Errors

If you see errors about missing `.js` extensions in imports, remember that all
Euterpe libraries use ESM. TypeScript requires `.js` extensions in import paths
even though the source files are `.ts`:

```typescript
// Correct (ESM)
import { createNote } from './notes/index.js';

// Incorrect (will fail at runtime)
import { createNote } from './notes/index';
```

### Build Order Issues

If a build fails with "Cannot find module" errors for peer dependencies, ensure
dependencies are built first:

```bash
# Build the full dependency chain
pnpm nx build @euterpe/core
pnpm nx build @euterpe/theory
pnpm nx build @euterpe/genesis
```

Or let Nx handle the order:

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

### Test Isolation

Tests run in Node.js environment. If a test needs Web Audio API or browser-
specific APIs, mock them:

```typescript
import { vi } from 'vitest';

const mockAudioContext = {
  createOscillator: vi.fn(),
  createGain: vi.fn(),
};
```

### Vitest Path Aliases

If tests cannot resolve `@euterpe/*` imports, ensure the vitest config has the
correct `resolve.alias` mapping. Some libraries may need explicit aliases in
their vitest config:

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

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    root: resolve(__dirname),
  },
  resolve: {
    alias: {
      '@euterpe/core': resolve(__dirname, '../core/src'),
    },
  },
});
```

### Floating-Point Precision in Music Math

Music calculations (frequency conversion, interval ratios, tuning) involve
floating-point arithmetic. Use `toBeCloseTo` in tests rather than exact
equality:

```typescript
expect(noteToFrequency(note)).toBeCloseTo(440, 2);
// toBeCloseTo(expected, numDigits) - diff must be < 5 * 10^(-numDigits - 1)
```

### Inspecting Nx Project Graph

To visualize how Euterpe libraries relate to each other and the rest of the
monorepo:

```bash
pnpm nx graph
```

This opens a browser-based dependency graph viewer.

---

## Project Configuration Reference

### Tags

All Euterpe libraries use: `["scope:euterpe", "layer:domain", "type:lib"]`

### Executors

| Target | Executor          |
| ------ | ----------------- |
| build  | `@nx/js:tsc`      |
| lint   | `@nx/eslint:lint` |
| test   | `@nx/vite:test`   |

### Environment Variables

No environment variables are required for Euterpe library development. The
libraries are pure computation with no external service dependencies.

---

## Related Documentation

- [Euterpe Domain README](./README.md) - Domain overview, architecture, and
  library descriptions
- [CLAUDE.md](/CLAUDE.md) - Repository-wide development guidelines
