# Calliope — Architecture

> Autonomous AI Artist Creation and Management Platform

Calliope is the Autonomous AI Artist Creation and Management Platform. It lives
in `libs/calliope/` within the Oshun Nx monorepo and is organized as 28
independently publishable TypeScript packages following the `@calliope/<name>`
naming convention.

Calliope is fundamentally an **orchestration domain** — it provides the artistic
intelligence layer that directs capabilities provided by other Oshun domains
toward the creation and management of coherent AI artist entities. Calliope does
not generate music, images, or video directly; it conceives, directs, and
coordinates those generation processes with creative intentionality. Think of it
as a creative director who knows exactly what she wants, then delegates the
actual production work to specialist studios (Euterpe for music, Isis for
visuals, Aja for motion). Everything that makes an AI artist feel like a
coherent, intentional _person_ — her personality, her voice, her visual
signature, her career arc, her fandom — lives in Calliope.

Calliope is consumed by other Oshun services that need artist-identity context
(for example, Euterpe reads a Calliope creative brief before generating a song;
Isis reads a visual brief before generating album art) and by the autonomous
agent layer that drives multi-step workflows like full album productions and era
launches.

---

## Library Organization

Calliope is organized as 28 packages inside `libs/calliope/`. Each package has a
single, clearly bounded responsibility; the naming reflects that boundary. The
directory layout below gives the full picture at a glance:

```
libs/calliope/
├── core/          # @calliope/core         — Types, constants, errors, Artist entity schema
├── compliance/    # @calliope/compliance   — AI disclosure, deepfake labeling, parasocial ethics, cultural appropriation
├── bridge/        # @calliope/bridge       — Cross-domain integration adapters
├── agents/        # @calliope/agents       — Multi-agent orchestration for career management workflows
│
├── genesis/       # @calliope/genesis      — Artist creation: persona, archetype, origin story, identity seed
├── voice/         # @calliope/voice        — Voice identity: synthesis, signature, evolution, performance
├── visage/        # @calliope/visage       — Visual identity: character design, fashion, album art, 3D avatars
├── glamour/       # @calliope/glamour      — Hair, makeup, beauty identity systems
├── kinesis/       # @calliope/kinesis      — Movement language, choreography, viral dance design
│
├── muse/          # @calliope/muse         — Musical direction: creative briefs, song conception, album architecture
├── cinema/        # @calliope/cinema       — Music video: concept development, generation pipeline, post-production
├── synesthesia/   # @calliope/synesthesia  — Cross-modal coherence: sound-color-movement-emotion integration
├── pathos/        # @calliope/pathos       — Emotional intelligence: emotional arc, resonance engineering
│
├── brand/         # @calliope/brand        — Brand strategy, market positioning, campaign management, PR
├── presence/      # @calliope/presence     — Social media: autonomous posting, fan interaction, content calendar
├── persona-live/  # @calliope/persona-live — AI interview simulation, public persona consistency
├── nexus/         # @calliope/nexus        — Gaming integrations, virtual world presence
│
├── fandom/        # @calliope/fandom       — Fan ecosystem: CRM, community architecture, superfan monetization
├── stage/         # @calliope/stage        — Live experience: concert dramaturgy, technical production design
├── lore/          # @calliope/lore         — Transmedia universe, narrative lore, ARG and fan discovery
├── artifacts/     # @calliope/artifacts    — Collectibles: physical merchandise design, digital NFT artifacts
│
├── distro/        # @calliope/distro       — Distribution, sync licensing, publishing administration
├── evolution/     # @calliope/evolution    — Career arc management, trend responsiveness, long-term identity coherence
├── label/         # @calliope/label        — Multi-artist roster management, portfolio strategy
├── duet/          # @calliope/duet         — Collaboration engine: AI-AI and AI-human partnerships
├── muse-gate/     # @calliope/muse-gate    — Quality gate: artistic excellence enforcement, release approval
│
├── composer/      # @calliope/composer     — Temporary-soundtrack / rough-cut score facade for production review
└── sound-design/  # @calliope/sound-design — AI sound design and Foley facade for CGI environment audio
```

`composer` and `sound-design` are small facade packages (metadata, typed package
contracts, and pure builder/validator functions) used for production review and
CGI audio handoff. They do not depend on `@calliope/core`.

---

## Architectural Layers

The 26 core artist-domain libraries are organized in five functional layers
above a foundation layer, corresponding to the layered stack in the domain
proposal. The two facade packages (`composer`, `sound-design`) sit outside this
layering.

Reading from the bottom up: the **Foundation** provides shared contracts and
cross-domain wiring; **Artist Identity** builds the artist's complete persona;
**Creative Production** translates that persona into music, video, and emotion;
**Public Presence** projects that work outward to audiences; **Community and
Experience** deepens fan relationships; and **Business and Growth** manages the
commercial and organizational dimension of a career.

```
┌───────────────────────────────────────────────────────────────────────┐
│                ARTIST IDENTITY LAYER                                  │
│   genesis  │  voice   │  visage  │  glamour  │  kinesis              │
│  (Persona) │(Vocal ID)│ (Visual) │ (Beauty)  │ (Movement)            │
└───────────────────────────────────────────────────────────────────────┘
                              ↑ built on ↓
┌───────────────────────────────────────────────────────────────────────┐
│               CREATIVE PRODUCTION LAYER                               │
│     muse          │  cinema      │  synesthesia  │  pathos            │
│  (Music Dir)      │  (Video)     │ (Cross-Modal) │ (Emotion Eng)      │
└───────────────────────────────────────────────────────────────────────┘
                              ↑ built on ↓
┌───────────────────────────────────────────────────────────────────────┐
│                PUBLIC PRESENCE LAYER                                  │
│     brand    │  presence    │  persona-live  │  nexus                │
│  (Strategy)  │  (Social)    │  (Interview)   │  (Gaming)             │
└───────────────────────────────────────────────────────────────────────┘
                              ↑ built on ↓
┌───────────────────────────────────────────────────────────────────────┐
│              COMMUNITY AND EXPERIENCE LAYER                           │
│    fandom   │   stage        │   lore       │  artifacts             │
│   (Fans)    │  (Spectacle)   │ (Transmedia) │ (Collectibles)         │
└───────────────────────────────────────────────────────────────────────┘
                              ↑ built on ↓
┌───────────────────────────────────────────────────────────────────────┐
│               BUSINESS AND GROWTH LAYER                               │
│  distro  │  evolution  │  label  │  duet    │  muse-gate             │
│(Industry)│  (Growth)   │(Roster) │(Collab)  │ (Quality)              │
└───────────────────────────────────────────────────────────────────────┘
                              ↑ built on ↓
┌───────────────────────────────────────────────────────────────────────┐
│                    FOUNDATION LAYER                                   │
│         core    │    compliance    │   bridge   │   agents            │
└───────────────────────────────────────────────────────────────────────┘
```

---

## Dependency Rules

The dependency graph enforces that lower layers never import from upper ones,
preventing circular dependencies and ensuring that identity decisions are never
contaminated by business concerns. The note below reflects the current state of
the codebase — the intended direction is enforced by code structure even where
`package.json` declarations are incomplete.

> The layered dependency directions below describe the intended architecture.
> Cross-package wiring is currently expressed through deep relative imports
> (e.g. `../../../genesis/src/...`) rather than `@calliope/*` `workspace:*`
> entries in every `package.json`; only some packages (e.g. `muse`) declare
> their Calliope dependencies explicitly. `@calliope/agents`, in particular,
> imports services directly from genesis, brand, visage, voice, presence,
> cinema, artifacts, distro, and duet to compose its orchestration workflows.

```
Foundation (Layer 0):
  @calliope/core        ← Zero Calliope deps; depends on shared @oshun/* libs + zod/drizzle/kafkajs/ioredis
  @calliope/compliance  ← Builds on @calliope/core contracts
  @calliope/bridge      ← External-domain contracts and adapters
  @calliope/agents      ← Composes services from many lower-layer Calliope packages

Artist Identity (Layer 1):
  @calliope/genesis     ← Depends on @calliope/core
  @calliope/voice       ← Depends on @calliope/core
  @calliope/visage      ← Depends on @calliope/core
  @calliope/glamour     ← Depends on @calliope/core, @calliope/visage
  @calliope/kinesis     ← Depends on @calliope/core

Creative Production (Layer 2):
  @calliope/muse        ← Depends on @calliope/genesis, @calliope/voice
  @calliope/cinema      ← Depends on @calliope/muse, @calliope/visage, @calliope/kinesis
  @calliope/synesthesia ← Depends on @calliope/muse, @calliope/visage, @calliope/kinesis, @calliope/voice
  @calliope/pathos      ← Depends on @calliope/genesis

Public Presence (Layer 3):
  @calliope/brand       ← Depends on @calliope/genesis, @calliope/muse
  @calliope/presence    ← Depends on @calliope/brand, @calliope/genesis
  @calliope/persona-live← Depends on @calliope/genesis, @calliope/brand
  @calliope/nexus       ← Depends on @calliope/visage, @calliope/bridge

Community and Experience (Layer 4):
  @calliope/fandom      ← Depends on @calliope/presence, @calliope/brand
  @calliope/stage       ← Depends on @calliope/kinesis, @calliope/cinema, @calliope/synesthesia
  @calliope/lore        ← Depends on @calliope/genesis, @calliope/muse
  @calliope/artifacts   ← Depends on @calliope/visage, @calliope/lore

Business and Growth (Layer 5):
  @calliope/distro      ← Depends on @calliope/muse, @calliope/bridge
  @calliope/evolution   ← Depends on all lower-layer packages
  @calliope/label       ← Depends on @calliope/evolution
  @calliope/duet        ← Depends on @calliope/muse, @calliope/genesis, @calliope/bridge
  @calliope/muse-gate   ← Depends on all creative production packages
```

---

## The Orchestration Pattern

Calliope is not a generator — it is a **creative director**. The core pattern
shows how a piece of creative output moves from artistic intent to a stored,
published asset. Each step below represents a distinct responsibility:

```
1. Calliope constructs a detailed creative brief
   (identity-grounded, era-specific, artistically intentional)
        │
        ▼
2. Brief is dispatched via @calliope/bridge to the appropriate domain:
   - Music brief → @euterpe/* generation engine
   - Image brief → @isis/* generation engine
   - Video brief → @aja/* + @uzume/* pipeline
   - Motion brief → @aja/* choreography engine
        │
        ▼
3. Generated output is returned to Calliope
        │
        ▼
4. @calliope/muse-gate evaluates the output:
   - Six-dimensional quality scoring: technical, emotional impact, novelty,
     identity consistency, replay value, overall aesthetic
   - Decision is approved / revise / escalate / blocked, judged against the
     per-TargetOutput thresholds in QUALITY_THRESHOLDS_BY_OUTPUT
        │
        ▼
5. Approved output is registered (asset ID stored, event published)
   and routed to its destination (S3 storage, social post queue,
   release pipeline, etc.)
```

---

## Key Package Internals

### `@calliope/genesis`

The artist-creation engine is the largest Calliope package, with roughly 40
service modules under `src/services/`. It is responsible for everything that
makes an artist feel like a real, internally consistent person: her name, her
psychology, her cultural grounding, her backstory, and her immutable identity
DNA. The table below lists the most significant modules:

| Module                                                                   | Responsibility                                            |
| ------------------------------------------------------------------------ | --------------------------------------------------------- |
| `artist-birth-pipeline.ts`                                               | End-to-end artist genesis pipeline                        |
| `big-five-profile-generator.ts`                                          | Big Five psychological profile generation                 |
| `cultural-grounding-framework.ts` / `cultural-authenticity-validator.ts` | Cultural identity grounding and authenticity validation   |
| `origin-story-generator.ts` / `backstory-generator.ts`                   | Origin story and biographical narrative                   |
| `artist-dna-encoder.ts` / `artist-dna-drift-detector.ts`                 | Identity-seed encoding and drift detection                |
| `identity-version-control.ts` / `persona-seed-immutability-guard.ts`     | Versioned identity evolution and immutability enforcement |
| `mythology-builder.ts` / `inter-artist-mythology-connector.ts`           | Symbolic system and cross-artist mythology                |
| `artist-name-generator.ts`                                               | Phonetic/cultural name generation                         |

### `@calliope/muse` (Musical Direction)

The musical brain of Calliope — the package that translates a persona into
specific, actionable musical decisions. It produces the creative briefs that
Euterpe consumes. With roughly 35 service modules, it covers everything from
individual song conception through full album architecture:

| Module                                             | Responsibility                                            |
| -------------------------------------------------- | --------------------------------------------------------- |
| `production-prompt-compiler.ts`                    | Compiles production prompts/briefs for generation engines |
| `song-concept-generator.ts`                        | Song conception from artist identity                      |
| `lyric-writer.ts`                                  | Vocabulary modeling, thematic obsessions, metaphor bank   |
| `melody-architect.ts` / `hook-craftsman.ts`        | Melodic identity and hook construction                    |
| `song-structure-optimizer.ts`                      | Per-artist structure preferences, dynamic arc modeling    |
| `album-concept-designer.ts` / `track-sequencer.ts` | Concept albums and track sequencing                       |
| `style-evolution-engine.ts`                        | Album-to-album progression and genre-shift justification  |

### `@calliope/muse-gate` (Quality Gate)

Every piece of output Calliope produces — songs, videos, social posts, concert
productions — must pass through `muse-gate` before it is approved. The gate
evaluates output against the `QualityThresholds` contract from `@calliope/core`.
Scoring is six-dimensional — `minimumTechnicalScore`,
`minimumEmotionalImpactScore`, `minimumNoveltyScore`,
`minimumIdentityConsistencyScore`, `minimumReplayValueScore`, and
`minimumOverallAestheticScore` — and thresholds are **per `TargetOutput`**, not
a single global value. `QUALITY_THRESHOLDS_BY_OUTPUT` ships calibrated sets for
each of the nine output types (for example, `concert` is the strictest,
`social_post` the most permissive); thresholds are configurable per deployment.

The gate orchestrator (`gate-orchestrator.ts`) aggregates a set of optional
per-dimension gate reports — persona consistency, authenticity, cultural
sensitivity, emotional authenticity, song quality, A/B comparison, visual
consistency, aesthetic quality, AI-artifact detection, video quality, quality
regression, and release readiness — and produces a `GateApprovalDecision` of
`approved`, `revise`, `escalate`, or `blocked`. `ai-artifact-detector.ts` flags
output that is technically AI-competent but artistically hollow. Other modules
in the package include `human-override-protocol.ts`, `quality-dashboard.ts`,
`quality-regression-detector.ts`, and `gate-feedback-loop.ts`.

### `@calliope/synesthesia` (Cross-Modal Coherence)

Synesthesia enforces that an artist's album cover, choreography, social posts,
and interview tone all feel like they came from the same creative source. It
operates by extracting a modality signature from each generated asset, comparing
it against the artist's `SynestheticProfile`, and scoring the match:

```
For each generated asset:
  1. Extract modality signature (sonic palette, color palette, movement quality, emotional register)
  2. Compare against artist's SynestheticProfile
  3. Compute coherence score: how well does this asset match the artist's cross-modal rules?
  4. Generate feedback: "This album cover's blue-grey palette conflicts with the warm amber
     sonic palette of the track; suggest warming the color temperature"
  5. Score feeds into muse-gate evaluation
```

### `@calliope/bridge`

All cross-domain communication passes through `@calliope/bridge`. This isolation
boundary is important: it means that a breaking change in Euterpe's API requires
updating only one file in Calliope (`EuterpeAdapter`), not every package that
happens to call Euterpe. The package is structured as:

- **Contracts** (`src/contracts/`) — typed, Zod-validated request/response
  schemas for each external domain: `aja`, `aje`, `aphrodite`, `euterpe`,
  `hathor`, `isis`, `maya`, `psyche`, `sophia`, `themis`, `uzume`.
- **Adapter services** (`src/services/`) — adapter classes that translate
  Calliope briefs into external-domain calls: `EuterpeAdapter`, `IsisAdapter`,
  `AjaAdapter`, `MayaAdapter`, `AphroditeAdapter`, `HathorAdapter`,
  `SophiaAdapter`, `ThemisAdapter`, `PsycheAdapter`, `AjeAdapter`, `NyxAdapter`.
- **Coordination services** — `CrossDomainEventBus`, `AudioToolsBridge`,
  `KnowledgePipelineManager`, `VisualPipelineOrchestrator`, and
  `VirtuosoMigrationBridge`.

---

## Agent Architecture

`@calliope/agents` provides autonomous, multi-step orchestration agents that
automate the higher-level workflows an AI label manager would run — creating an
artist from scratch, launching an era, producing an album end-to-end. Each agent
is a workflow class that composes services from the lower-layer Calliope
packages (genesis, brand, visage, voice, presence, muse, cinema, distro,
artifacts, duet, and others) and produces a fully validated workflow output. The
package exports twelve agents:

| Agent                       | Responsibility                                                                                      |
| --------------------------- | --------------------------------------------------------------------------------------------------- |
| `ArtistGenesisAgent`        | Orchestrates the complete artist-birth workflow across identity, voice, visual, and launch planning |
| `PersonaDevelopmentAgent`   | Develops and refines an artist persona                                                              |
| `AlbumProductionAgent`      | Orchestrates album production                                                                       |
| `SongProductionAgent`       | Orchestrates single-song production                                                                 |
| `MusicVideoProductionAgent` | Orchestrates music-video production                                                                 |
| `AlbumReleaseAgent`         | Manages the album-release campaign                                                                  |
| `SingleReleaseAgent`        | Manages the single-release campaign                                                                 |
| `EraLaunchAgent`            | Coordinates the launch of a new artist era                                                          |
| `ConcertProductionAgent`    | Plans and produces a concert experience                                                             |
| `ContentBatchAgent`         | Produces batched social/marketing content                                                           |
| `CollaborationAgent`        | Manages end-to-end collaboration workflows                                                          |
| `GroupFormationAgent`       | Orchestrates the formation of a multi-artist group                                                  |

Agent workflow shapes are defined in
`libs/calliope/agents/src/types/agent-workflows.ts`, which composes schemas from
`@calliope/core` and the cinema, artifacts, distro, and duet type modules.

---

## Service Architecture

Calliope is currently implemented entirely as the 28 `libs/calliope/*`
TypeScript packages. The repository does not contain an `apps/calliope/` or
`services/calliope/` directory; there is no deployed `calliope-api` or
`calliope-worker` process. The REST surface exists as an OpenAPI 3.1 contract
generated from `@calliope/core` Zod schemas by
`libs/openapi/scripts/generate-calliope-spec.ts`. A deployable service topology
is future work.

---

## Technology Stack

The table below lists the key technologies at each layer. The most unusual
choices for a music platform are `kafkajs` (Calliope generates a lot of domain
events — 69 event types — and they need to be consumed by many downstream
services simultaneously) and `pgvector` (artist identity vectors enable drift
detection and similarity search across the artist roster).

| Layer          | Technology                                                      |
| -------------- | --------------------------------------------------------------- |
| Language       | TypeScript (strict mode)                                        |
| Runtime        | Node.js                                                         |
| Testing        | Vitest                                                          |
| Build          | Nx with tsup/esbuild                                            |
| Validation     | Zod                                                             |
| Database       | PostgreSQL with pgvector (`calliope` database), Drizzle ORM     |
| Cache          | Redis (`ioredis`) — caching and scheduling                      |
| Object storage | S3 — audio, video, image assets, LoRA model weights             |
| Eventing       | Kafka (`kafkajs`) — Avro-serialized, hash-chained domain events |
| Vector search  | pgvector (1536-dim, HNSW); `@qdrant/js-client-rest` available   |

---

## Database

Calliope uses a dedicated PostgreSQL database named `calliope`. The schema is
defined with Drizzle ORM in `libs/calliope/core/src/db-schema.ts` (twelve
tables, documented fully in `specifications.md`); migrations live in
`libs/calliope/core/drizzle/`.

Two tables deserve special mention because of their non-standard column types.
The `calliope_artist_embeddings` table stores artist identity vectors using the
pgvector `vector` type at 1536 dimensions with an HNSW `vector_cosine_ops`
index. Each embedding is typed by `embeddingType`: `sonic_identity`,
`visual_identity`, `lyrical_style`, `personality`, or `movement_style` — used
for drift detection and identity similarity search across the roster.
`calliope_artists.persona_seed` is stored as JSONB with a GIN index, enabling
fast querying of persona attributes, and `calliope_songs` carries a GIN
full-text index over title plus lyrics for catalog search.
