Architecture¶
MuseFlow follows Clean / Hexagonal Architecture. The reason is practical rather than ceremonial: the product depends on three things that change independently and fail independently, namely a streaming provider (Spotify today), an LLM (any model behind the OpenRouter gateway), and a database. Each sits behind a port, so the use cases and the matching logic can be tested without any of them and the vendors can be swapped by adding an adapter.
Layers and the dependency rule¶
flowchart TB
subgraph INFRA["infrastructure (implements ports, owns every framework)"]
direction TB
EP["entrypoints<br/>cli (Typer) / api (FastAPI)"]
AD["adapters<br/>providers/spotify<br/>advisors, profilers, enrichers / openrouter<br/>database (models + repositories)"]
end
subgraph APP["application (orchestration)"]
direction TB
UC["use_cases"]
ASVC["services: DiscoveryService, LLMUsageService"]
PORTS["ports (ABCs)<br/>repositories, providers,<br/>advisors, profilers, enrichers, security"]
INP["inputs (command schemas)"]
OUT["outputs (stats, LLM usage, progress events)"]
end
subgraph DOM["domain (pure Python)"]
direction TB
ENT["entities, value_objects"]
UTL["utils, enums, const, exceptions"]
end
EP --> UC
UC --> PORTS
UC --> ASVC
ASVC --> PORTS
UC --> ENT
AD -.implements.-> PORTS
AD --> ENT
PORTS --> ENT
| Layer | Path | May import | Contains |
|---|---|---|---|
| Domain | museflow/domain/ |
the standard library and a pure helper (unidecode) |
Frozen-dataclass entities, value objects, pure helpers (text normalization, fingerprint), enums, constants, exceptions |
| Application | museflow/application/ |
domain only | Use cases, application services shared by the use cases, input schemas, outputs (what the use cases and ports hand to the entrypoints for display), port interfaces (abc.ABC) |
| Infrastructure | museflow/infrastructure/ |
everything | SQLAlchemy models and repositories, Spotify and OpenRouter adapters, settings, Typer and FastAPI entrypoints |
Two points are easy to miss:
- The domain holds rules, not only data. A
Trackcomputes its own fingerprint in__post_init__, from its title and artists normalized bydomain/utils: that fingerprint is how a track is recognised across providers, imports and discovery runs. No I/O, deterministic, so it lives in the domain. A rule only one flow uses stays a pure helper next to its use case (application/utils/), with no class or injection around it. - Value objects are business values; outputs are not. A value object is a word of the business language: a listening period, a discovery strategy, the blacklist of a user. The shapes the application only hands over for display (statistics, an LLM usage summary, progress events) carry no business rule, so they live in
application/outputs/. The test is what a shape is, not which layer uses it today. - Ports are defined by the application, not by the infrastructure. For example
AdvisorPort(museflow/application/ports/advisors/agent.py) exposesget_discovery_artists(...)in domain terms (TasteProfile,Track,DiscoveryFocus) and returns aDiscoveryArtistStrategy. Nothing in it mentions HTTP or JSON.
Ports and adapters¶
| Port (application) | Adapter (infrastructure) |
|---|---|
ProviderLibraryPort (search, create / delete playlist, play) |
SpotifyLibraryAdapter, built by SpotifyLibraryFactory |
ProviderOAuthPort |
SpotifyOAuthAdapter |
StreamingHistoryPort (parse an export file) |
SpotifyStreamingHistoryAdapter |
FileStoragePort (a user's files between their upload and their processing, keyed per user) |
LocalFileStorage, a directory per user on a disk or a shared volume |
AdvisorPort |
OpenRouterAdvisorAdapter |
TasteProfilerPort |
OpenRouterTasteProfileAdapter |
TrackEnricherPort |
OpenRouterTrackEnricherAdapter |
UnitOfWorkPort (one short transaction per async with block, gives access to the repositories) |
SQLUnitOfWork, a new session per block |
TrackRepository, PlaylistRepository, TasteProfileRepository, BlacklistRepository, UserRepository, OAuth token and state repositories |
*SQLRepository classes over the block's AsyncSession; they never commit, the unit of work does |
PasswordHasherPort, StateTokenGeneratorPort, AccessTokenManagerPort |
Argon2, a random.SystemRandom state-token generator, PyJWT |
Where the vendor is an enum (MusicProvider), the entrypoints pick the adapter with a match in wiring.py, which builds the adapters for all of them. Adding a provider means one new case plus the adapter package. The LLM side needs no such switch: OpenRouter is the single adapter, and the vendor choice became a model setting per step (LLM pipeline). The move from direct Gemini calls to the gateway replaced the adapters and the settings; the ports and the use cases did not change, apart from dropping the vendor enums.
MuseFlow is deliberately a single application. If it grew, the ports above are where it would split into services (import, profiling, recommendations and playlists, enrichment); the trade-off is discussed in lessons learned.
One flow end to end: playlist discover¶
The most connected command. It touches every port.
sequenceDiagram
autonumber
participant CLI as CLI playlist_discover_logic
participant DI as entrypoints/wiring.py
participant UC as CreateDiscoveryPlaylistUseCase
participant UoW as Unit of work (short SQL blocks)
participant Adv as AdvisorPort (OpenRouter adapter)
participant Lib as ProviderLibraryPort (Spotify adapter)
CLI->>DI: provider library (Spotify OAuth client inside), advisor
CLI->>UoW: block: user by email, auth token
CLI->>UC: create_playlist(user, config)
UC->>UoW: block: taste profile (named or latest), blacklist, liked and disliked tracks
loop up to max_attempts, stop once playlist_limit reached
UC->>Adv: get_discovery_artists(profile, prompt, focus, artists already asked, liked and disliked tracks)
Adv-->>UC: DiscoveryArtistStrategy (artists, each with the sound wanted and a score)
UC->>Lib: search_artist_tracks per artist
UC->>UC: filter_by_artist: keep the tracks crediting that exact artist
UC->>UoW: block: drop tracks the user already knows (by fingerprint)
UC->>Adv: pick_discovery_tracks(strategy, unknown tracks per artist)
Adv-->>UC: picked tracks with a fit score
end
UC->>UC: sort by fit score, cap per credited artist, trim
UC->>Lib: create_playlist
UC->>UoW: one block: upsert tracks as DISCOVERY source, save playlist and its tracks
UC-->>CLI: CreateDiscoveryPlaylistResult
CLI->>CLI: render panel and tables
What the diagram encodes, with the reasoning behind each step:
- Composition happens in the entrypoint.
discover_logicgets a unit of work and opens each adapter inside anAsyncExitStack, so every HTTP client is closed even on failure, then hands finished objects to the use case. The use case never instantiates a repository or a client. - The advisor names artists, the catalogue gives the tracks. An LLM knows niche artists far better than their discographies: asked for titles, it invented some and repeated the genre's canon the user already knew. So it names artists, each with the sound wanted from them; the provider returns their real tracks; the known and blacklisted ones are dropped locally; and a second call picks among what is left, by short ids, so no title can be invented. The why, with the numbers: Discovery: from titles to artists.
- One round usually fills the playlist. When it does not, the use case runs another, up to
DISCOVERY_MAX_ATTEMPTS, excluding the artists already asked, and stops early when the advisor has no artist left to suggest. Each round is reported (artists / unknown tracks / picked) so the user can see where candidates were lost. Every database access is a shortasync with uow:block, closed before the next advisor or catalogue call: a block opens a session from the pool and closes it on exit, so no connection sits idle in transaction while the model thinks, which can take minutes.enrich tracks,taste buildand the interactiveratecommands follow the same rule. Why this design, and what came before it: Why a unit of work. - "Known" is decided by fingerprint, not by provider id, so a re-release or a different catalogue entry of a track the user already played is still excluded (see Data model).
- The cap counts every credited artist. Tracks are sorted by the advisor's fit score, then capped per artist (
DISCOVERY_MAX_TRACKS_PER_ARTIST), a featured appearance included: the artists of one scene feature on each other's tracks, and a cap on the primary artist alone let one of them fill the playlist. An artist whose own tracks the prompt asks for is not capped. - Side effects come last, remote first. The remote playlist is created first; only then are the discovery tracks upserted (so they are excluded from future sessions) and the local playlist row saved. A provider failure therefore leaves nothing behind locally. The tracks upsert and the playlist save then run in one block of the unit of work: a database failure keeps neither. Elsewhere, flows open one block per step, so paid LLM batches and checkpoints are kept when a later step fails. See Known gaps.
Conventions and why they exist¶
The rules are written down in AGENTS.md (the contract loaded into every AI session, see AI-assisted development). The ones that shape the code most:
| Convention | Reason |
|---|---|
Entities are @dataclass(frozen=True, kw_only=True); validation only in __post_init__; computed permanent fields (the track fingerprint) set there with object.__setattr__ |
Immutability removes a class of aliasing bugs; no framework means domain tests need no fixtures; business invariants (a track has a name, an artist and a provider link) fail at construction |
No database limits in the domain (no varchar(255) checks) |
A storage concern must not leak into business rules |
| Ports are ABCs that accept input schemas and return entities | Use cases stay framework-free and are tested with AsyncMock instead of fakes |
SQLAlchemy models are MappedAsDataclass with symmetric from_entity / to_entity |
One place maps each direction, repositories never build models field by field. Every model implements to_entity; from_entity exists on the two models whose repositories write whole entities (Track, Playlist), although the contract asks for both everywhere |
Use cases are plain async functions; a class only when injected state is needed (for example CreateDiscoveryPlaylistUseCase) |
Function by default, class when the constructor genuinely carries dependencies |
| Parameters grouped by role: inputs, then the unit of work, then other ports; DI parameters contiguous | Callers use keywords, so order is documentation; a consistent order makes a signature scannable |
CLI commands are thin sync wrappers around a run_logic() of a <command>_logic coroutine; the logic returns data and never prints |
Output stays in the callback, so logic is unit-testable without capturing stdout, and the same logic can be reused |
HttpClientMixin first, port second in the base class list (class OpenRouterAdvisorAdapter(OpenRouterAdapterMixin, AdvisorPort)) |
The mixin supplies concrete methods (close, the async context manager) that the port declares abstract. With the port first, Python's MRO would find the abstract version first and the class could not be instantiated. |
Repeated closures are centralised as decorators (@self_heal, tenacity's @retry) or shared by composition (OpenRouterClient) |
Three LLM adapters share the same failure handling; copy-paste would drift |
What is enforced by tooling
Most of the rules above are enforced by review (human and agent), not by tooling. Three exceptions: the layering itself is enforced by import-linter (which layer may import what, and no framework in the domain), the ban on assert in production code by Ruff (rule S101, ignored under tests/), and full type annotation by mypy in strict mode (see Quality & testing).