diff --git a/app/api/schemas/playlist.py b/app/api/schemas/playlist.py index 266ec4e..b833f29 100644 --- a/app/api/schemas/playlist.py +++ b/app/api/schemas/playlist.py @@ -29,3 +29,7 @@ class PlaylistUpdate(BaseModel): class PlaylistAddTrack(BaseModel): track_id: uuid.UUID position: float | None = None + + +class PlaylistReorder(BaseModel): + track_ids: list[uuid.UUID] diff --git a/app/api/v1/playlists.py b/app/api/v1/playlists.py index 3285207..f8b2353 100644 --- a/app/api/v1/playlists.py +++ b/app/api/v1/playlists.py @@ -13,11 +13,17 @@ from app.api.deps import ( TrackRepoDep, ) from app.api.schemas.pagination import PagedResponse -from app.api.schemas.playlist import PlaylistAddTrack, PlaylistCreate, PlaylistOut, PlaylistUpdate +from app.api.schemas.playlist import ( + PlaylistAddTrack, + PlaylistCreate, + PlaylistOut, + PlaylistReorder, + PlaylistUpdate, +) from app.api.schemas.track import TrackOut from app.api.v1.tracks import _build_track_out from app.domain.entities.playlist import Playlist -from app.domain.errors import NotFoundError, PermissionDeniedError +from app.domain.errors import NotFoundError, PermissionDeniedError, ValidationError from app.infrastructure.db.repositories.playlist_repository import SqlAlchemyPlaylistRepository router = APIRouter(prefix="/playlists", tags=["playlists"]) @@ -182,7 +188,32 @@ async def remove_playlist_track( @router.put("/{playlist_id}/tracks/reorder") -async def reorder_playlist_tracks(playlist_id: uuid.UUID, _: CurrentUser) -> Any: ... +async def reorder_playlist_tracks( + playlist_id: uuid.UUID, + body: PlaylistReorder, + playlist_repo: PlaylistRepoDep, + user: CurrentUser, +) -> PlaylistOut: + playlist = await playlist_repo.get_by_id(playlist_id) + if playlist is None: + raise NotFoundError(f"Playlist {playlist_id} not found.") + if playlist.owner_id != user.id: + raise PermissionDeniedError("You don't own this playlist.") + + total = await playlist_repo.get_track_total(playlist_id) + current_tracks = ( + await playlist_repo.get_tracks(playlist_id, limit=total, offset=0) if total else [] + ) + current_ids = {t.id for t in current_tracks} + given_ids = body.track_ids + if len(given_ids) != len(set(given_ids)) or set(given_ids) != current_ids: + raise ValidationError("track_ids must be a permutation of the playlist's current tracks.") + + await playlist_repo.reorder_tracks(playlist_id, given_ids) + updated = await playlist_repo.get_by_id(playlist_id) + assert updated is not None + items = await _build_playlist_out([updated], playlist_repo) + return items[0] @router.get("/{playlist_id}/cover") diff --git a/app/domain/ports.py b/app/domain/ports.py index c73b85a..1abfbd9 100644 --- a/app/domain/ports.py +++ b/app/domain/ports.py @@ -278,11 +278,15 @@ class PlaylistRepository(Protocol): self, playlist_id: uuid.UUID, *, limit: int, offset: int ) -> list[Track]: ... async def get_track_total(self, playlist_id: uuid.UUID) -> int: ... + async def has_track(self, playlist_id: uuid.UUID, track_id: uuid.UUID) -> bool: ... async def add_track( self, playlist_id: uuid.UUID, track_id: uuid.UUID, *, position: float ) -> None: ... async def remove_track(self, playlist_id: uuid.UUID, track_id: uuid.UUID) -> None: ... async def max_position(self, playlist_id: uuid.UUID) -> float: ... + async def reorder_tracks( + self, playlist_id: uuid.UUID, ordered_track_ids: list[uuid.UUID] + ) -> None: ... # list must come after any method using list[...] in its signature (name shadowing) async def list(self, *, owner_id: uuid.UUID, limit: int, offset: int) -> list[Playlist]: ... diff --git a/app/infrastructure/db/repositories/playlist_repository.py b/app/infrastructure/db/repositories/playlist_repository.py index af01f9c..a488d07 100644 --- a/app/infrastructure/db/repositories/playlist_repository.py +++ b/app/infrastructure/db/repositories/playlist_repository.py @@ -138,9 +138,22 @@ class SqlAlchemyPlaylistRepository: async def get_track_total(self, playlist_id: uuid.UUID) -> int: return await self.track_count(playlist_id) + async def has_track(self, playlist_id: uuid.UUID, track_id: uuid.UUID) -> bool: + row = ( + await self._session.execute( + select(PlaylistTrackModel.id).where( + PlaylistTrackModel.playlist_id == playlist_id, + PlaylistTrackModel.track_id == track_id, + ) + ) + ).scalar_one_or_none() + return row is not None + async def add_track( self, playlist_id: uuid.UUID, track_id: uuid.UUID, *, position: float ) -> None: + if await self.has_track(playlist_id, track_id): + return row = PlaylistTrackModel(playlist_id=playlist_id, track_id=track_id, position=position) self._session.add(row) playlist = await self._session.get(PlaylistModel, playlist_id) @@ -148,6 +161,26 @@ class SqlAlchemyPlaylistRepository: playlist.version = playlist.version + 1 await self._session.flush() + async def reorder_tracks( + self, playlist_id: uuid.UUID, ordered_track_ids: list[uuid.UUID] + ) -> None: + rows = ( + ( + await self._session.execute( + select(PlaylistTrackModel).where(PlaylistTrackModel.playlist_id == playlist_id) + ) + ) + .scalars() + .all() + ) + by_track_id = {row.track_id: row for row in rows} + for position, track_id in enumerate(ordered_track_ids, start=1): + by_track_id[track_id].position = float(position) + playlist = await self._session.get(PlaylistModel, playlist_id) + if playlist is not None: + playlist.version = playlist.version + 1 + await self._session.flush() + async def remove_track(self, playlist_id: uuid.UUID, track_id: uuid.UUID) -> None: row = ( await self._session.execute( diff --git a/graphify-out/.graphify_labels.json b/graphify-out/.graphify_labels.json index 809ad11..81f18c7 100644 --- a/graphify-out/.graphify_labels.json +++ b/graphify-out/.graphify_labels.json @@ -1 +1,135 @@ -{"0": "Storage Backend & Disk Usage", "1": "Auth Schemas & Tokens", "2": "Error Mapping & Search Schemas", "3": "Download Service Orchestration", "4": "Playlist Schemas & API", "5": "Album Repository", "6": "ORM Base & Models", "7": "Correlation ID Middleware & Config", "8": "Auth Services (native + Subsonic)", "9": "Audio Tags & Metadata Test Fakes", "10": "YouTube Source Backend", "11": "Dependency Wiring (deps.py)", "12": "Library Stats & Track Availability", "13": "Library Import Service", "14": "Subsonic Response Envelope", "15": "Chromaprint Fingerprinting", "16": "Album/Search Response Schemas", "17": "Pagination & Likes Endpoints", "18": "Metadata Enrichment Service", "19": "Subsonic ID Encoding", "20": "Track & Artist Domain Entities", "21": "Source Port Protocols", "22": "User Management Service", "23": "Metadata Enrichment Value Objects", "24": "DB Session & Health Checks", "25": "Download Service Tests", "26": "Download Job Domain Entity", "27": "Credentials & User Repository", "28": "Streaming Auth Dependencies", "29": "Subsonic Browsing Endpoints", "30": "Remote Library Service Tests", "31": "Worker Session Scope & Download Task", "32": "Metadata Enrichment Pipeline", "33": "Album Domain & Cover Value Object", "34": "Downloads API Tests", "35": "Subsonic Search Encoding", "36": "In-Memory Auth Repository Fakes", "37": "Storage Stats Response Schemas", "38": "Subsonic App-Password Crypto", "39": "Artist Schemas & Endpoints", "40": "Download Request/Response Schemas", "41": "Settings & MusicBrainz User-Agent", "42": "Subsonic API Integration Tests", "43": "Playlist Endpoints", "44": "Play History Domain & Repository", "45": "DB Engine Lifecycle", "46": "Shared Query Param Annotations", "47": "Local Folder Source Backend", "48": "Track Metadata Match Schemas", "49": "Like Domain Entity (event log)", "50": "Auth API Integration Tests", "51": "Cover API Tests", "52": "Upload/Stream API Tests", "53": "Tag Parsing Helpers", "54": "Metadata API Tests", "55": "Subsonic Auth Service Tests", "56": "Cover Art Serving", "57": "Play History Schemas", "58": "Refresh Token Repository", "59": "Radio Endpoints", "60": "Subsonic Legacy Password Decoding", "61": "Management CLI", "62": "Sources API Tests", "63": "Hexagonal Architecture Layers (doc)", "64": "Test DB Fixtures (conftest)", "65": "Upload Response Schemas", "66": "Cover Art Extraction (Vorbis/MP4)", "67": "Storage Stats API Tests", "68": "AcoustID Response Parser Tests", "69": "Like Request/Response Schemas", "70": "Streaming Endpoint", "71": "Auth Token Issue/Refresh Flow", "72": "Generic Job/Result Store Protocol", "73": "Remote Library Materialization", "74": "CI Docker Publish Workflow", "75": "User Scrobbling Settings", "76": "Domain Invariants (dedup, manual overwrite, offline tags)", "77": "Alembic Migration Environment", "78": "Cover Art Archive Client", "79": "Health Endpoint Smoke Tests", "80": "ASGI Middleware Protocol", "81": "File Hashing Utilities", "82": "Migration: auth_users", "83": "Migration: music_schema", "84": "Migration: rename track file_path", "85": "Migration: subsonic_app_password", "86": "Migration: track_enrichment_outcome", "87": "Migration: download_job_track_id", "88": "Migration: remote_placeholders", "89": "Package: app.api", "90": "Package: app.api.schemas", "91": "Package: app.application", "92": "Package: app.core", "93": "Package: app.domain", "94": "Package: app.infrastructure", "95": "Package: metadata-enrichment adapters", "96": "Package: source backends", "97": "Package: storage adapters", "98": "Package: app root (mcma-backend)", "99": "Package: arq worker", "100": "Package: arq tasks", "101": "Config Conventions (doc)", "102": "Subsonic Adapter Convention (doc)", "103": "DB Session Convention (doc)", "104": "Health Convention (doc)", "105": "Invariant: Graceful Degradation", "106": "Invariant: Likes Are Append-Only", "107": "Invariant: Stable Track content_id", "108": "Logging Convention (doc)", "109": "Python 3.14 Lazy Annotations Note", "110": "App-Passwords Mechanism (doc)", "111": "Local Dev Setup (doc)", "112": "Tooling Section (doc)", "113": "Package: workers"} \ No newline at end of file +{ + "0": "Storage Backend & Disk Usage", + "1": "Auth Schemas & Tokens", + "2": "Error Mapping & Search Schemas", + "3": "Download Service Orchestration", + "4": "Playlist Schemas & API", + "5": "Album Repository", + "6": "ORM Base & Models", + "7": "Correlation ID Middleware & Config", + "8": "Auth Services (native + Subsonic)", + "9": "Audio Tags & Metadata Test Fakes", + "10": "YouTube Source Backend", + "11": "Dependency Wiring (deps.py)", + "12": "Library Stats & Track Availability", + "13": "Library Import Service", + "14": "Subsonic Response Envelope", + "15": "Chromaprint Fingerprinting", + "16": "Album/Search Response Schemas", + "17": "Pagination & Likes Endpoints", + "18": "Metadata Enrichment Service", + "19": "Subsonic ID Encoding", + "20": "Track & Artist Domain Entities", + "21": "Source Port Protocols", + "22": "User Management Service", + "23": "Metadata Enrichment Value Objects", + "24": "DB Session & Health Checks", + "25": "Download Service Tests", + "26": "Download Job Domain Entity", + "27": "Credentials & User Repository", + "28": "Streaming Auth Dependencies", + "29": "Subsonic Browsing Endpoints", + "30": "Remote Library Service Tests", + "31": "Worker Session Scope & Download Task", + "32": "Metadata Enrichment Pipeline", + "33": "Album Domain & Cover Value Object", + "34": "Downloads API Tests", + "35": "Subsonic Search Encoding", + "36": "In-Memory Auth Repository Fakes", + "37": "Storage Stats Response Schemas", + "38": "Subsonic App-Password Crypto", + "39": "Artist Schemas & Endpoints", + "40": "Download Request/Response Schemas", + "41": "Settings & MusicBrainz User-Agent", + "42": "Subsonic API Integration Tests", + "43": "Playlist Endpoints", + "44": "Play History Domain & Repository", + "45": "DB Engine Lifecycle", + "46": "Shared Query Param Annotations", + "47": "Local Folder Source Backend", + "48": "Track Metadata Match Schemas", + "49": "Like Domain Entity (event log)", + "50": "Auth API Integration Tests", + "51": "Cover API Tests", + "52": "Upload/Stream API Tests", + "53": "Tag Parsing Helpers", + "54": "Metadata API Tests", + "55": "Subsonic Auth Service Tests", + "56": "Cover Art Serving", + "57": "Play History Schemas", + "58": "Refresh Token Repository", + "59": "Radio Endpoints", + "60": "Subsonic Legacy Password Decoding", + "61": "Management CLI", + "62": "Sources API Tests", + "63": "Hexagonal Architecture Layers (doc)", + "64": "Test DB Fixtures (conftest)", + "65": "Upload Response Schemas", + "66": "Cover Art Extraction (Vorbis/MP4)", + "67": "Storage Stats API Tests", + "68": "AcoustID Response Parser Tests", + "69": "Like Request/Response Schemas", + "70": "Streaming Endpoint", + "71": "Auth Token Issue/Refresh Flow", + "72": "Generic Job/Result Store Protocol", + "73": "Remote Library Materialization", + "74": "CI Docker Publish Workflow", + "75": "User Scrobbling Settings", + "76": "Domain Invariants (dedup, manual overwrite, offline tags)", + "77": "Alembic Migration Environment", + "78": "Cover Art Archive Client", + "79": "Health Endpoint Smoke Tests", + "80": "ASGI Middleware Protocol", + "81": "File Hashing Utilities", + "82": "Migration: auth_users", + "83": "Migration: music_schema", + "84": "Migration: rename track file_path", + "85": "Migration: subsonic_app_password", + "86": "Migration: track_enrichment_outcome", + "87": "Migration: download_job_track_id", + "88": "Migration: remote_placeholders", + "89": "Package: app.api", + "90": "Package: app.api.schemas", + "91": "Package: app.application", + "92": "Package: app.core", + "93": "Package: app.domain", + "94": "Package: app.infrastructure", + "95": "Package: metadata-enrichment adapters", + "96": "Package: source backends", + "97": "Package: storage adapters", + "98": "Package: app root (mcma-backend)", + "99": "Package: arq worker", + "100": "Package: arq tasks", + "101": "Config Conventions (doc)", + "102": "Subsonic Adapter Convention (doc)", + "103": "DB Session Convention (doc)", + "104": "Health Convention (doc)", + "105": "Invariant: Graceful Degradation", + "106": "Invariant: Likes Are Append-Only", + "107": "Invariant: Stable Track content_id", + "108": "Logging Convention (doc)", + "109": "Python 3.14 Lazy Annotations Note", + "110": "App-Passwords Mechanism (doc)", + "111": "Local Dev Setup (doc)", + "112": "Tooling Section (doc)", + "113": "Package: workers", + "114": "app/application — use cases / services", + "115": "Composition roots (app/main.py, app/api/deps.py)", + "116": "app/core — cross-cutting concerns", + "117": "app/domain — pure business core", + "118": "Error handling convention (domain errors → HTTP in app/api/errors.py)", + "119": "Hexagonal architecture (ports & adapters)", + "120": "app/infrastructure — driven adapters", + "121": "Invariant: dedup on (source, source_id) and acoustid_fingerprint", + "122": "Invariant: no heavy work in the request cycle (goes to arq workers)", + "123": "Invariant: never overwrite metadata_status=manual", + "124": "Migrations convention (async, settings-driven Alembic)", + "125": "app/workers — arq background tasks", + "126": "Build (Docker) section", + "127": "Hexagonal architecture (ports & adapters) — README", + "128": "Database migrations (Alembic) section", + "129": "Subsonic API (/rest) section", + "130": "acoustid_trust_score (trust high-confidence AcoustID over junk tags)", + "131": "Offline tag reader (deterministic, always runs)", + "132": "scarlet_fire_otis_mcdonald.mp3 test fixture" +} diff --git a/graphify-out/.graphify_root b/graphify-out/.graphify_root index aa859be..945c9b4 100644 --- a/graphify-out/.graphify_root +++ b/graphify-out/.graphify_root @@ -1 +1 @@ -/Users/senko/Work/mcma-compose/mcma-backend +. \ No newline at end of file diff --git a/graphify-out/2026-07-11/.graphify_labels.json b/graphify-out/2026-07-11/.graphify_labels.json new file mode 100644 index 0000000..809ad11 --- /dev/null +++ b/graphify-out/2026-07-11/.graphify_labels.json @@ -0,0 +1 @@ +{"0": "Storage Backend & Disk Usage", "1": "Auth Schemas & Tokens", "2": "Error Mapping & Search Schemas", "3": "Download Service Orchestration", "4": "Playlist Schemas & API", "5": "Album Repository", "6": "ORM Base & Models", "7": "Correlation ID Middleware & Config", "8": "Auth Services (native + Subsonic)", "9": "Audio Tags & Metadata Test Fakes", "10": "YouTube Source Backend", "11": "Dependency Wiring (deps.py)", "12": "Library Stats & Track Availability", "13": "Library Import Service", "14": "Subsonic Response Envelope", "15": "Chromaprint Fingerprinting", "16": "Album/Search Response Schemas", "17": "Pagination & Likes Endpoints", "18": "Metadata Enrichment Service", "19": "Subsonic ID Encoding", "20": "Track & Artist Domain Entities", "21": "Source Port Protocols", "22": "User Management Service", "23": "Metadata Enrichment Value Objects", "24": "DB Session & Health Checks", "25": "Download Service Tests", "26": "Download Job Domain Entity", "27": "Credentials & User Repository", "28": "Streaming Auth Dependencies", "29": "Subsonic Browsing Endpoints", "30": "Remote Library Service Tests", "31": "Worker Session Scope & Download Task", "32": "Metadata Enrichment Pipeline", "33": "Album Domain & Cover Value Object", "34": "Downloads API Tests", "35": "Subsonic Search Encoding", "36": "In-Memory Auth Repository Fakes", "37": "Storage Stats Response Schemas", "38": "Subsonic App-Password Crypto", "39": "Artist Schemas & Endpoints", "40": "Download Request/Response Schemas", "41": "Settings & MusicBrainz User-Agent", "42": "Subsonic API Integration Tests", "43": "Playlist Endpoints", "44": "Play History Domain & Repository", "45": "DB Engine Lifecycle", "46": "Shared Query Param Annotations", "47": "Local Folder Source Backend", "48": "Track Metadata Match Schemas", "49": "Like Domain Entity (event log)", "50": "Auth API Integration Tests", "51": "Cover API Tests", "52": "Upload/Stream API Tests", "53": "Tag Parsing Helpers", "54": "Metadata API Tests", "55": "Subsonic Auth Service Tests", "56": "Cover Art Serving", "57": "Play History Schemas", "58": "Refresh Token Repository", "59": "Radio Endpoints", "60": "Subsonic Legacy Password Decoding", "61": "Management CLI", "62": "Sources API Tests", "63": "Hexagonal Architecture Layers (doc)", "64": "Test DB Fixtures (conftest)", "65": "Upload Response Schemas", "66": "Cover Art Extraction (Vorbis/MP4)", "67": "Storage Stats API Tests", "68": "AcoustID Response Parser Tests", "69": "Like Request/Response Schemas", "70": "Streaming Endpoint", "71": "Auth Token Issue/Refresh Flow", "72": "Generic Job/Result Store Protocol", "73": "Remote Library Materialization", "74": "CI Docker Publish Workflow", "75": "User Scrobbling Settings", "76": "Domain Invariants (dedup, manual overwrite, offline tags)", "77": "Alembic Migration Environment", "78": "Cover Art Archive Client", "79": "Health Endpoint Smoke Tests", "80": "ASGI Middleware Protocol", "81": "File Hashing Utilities", "82": "Migration: auth_users", "83": "Migration: music_schema", "84": "Migration: rename track file_path", "85": "Migration: subsonic_app_password", "86": "Migration: track_enrichment_outcome", "87": "Migration: download_job_track_id", "88": "Migration: remote_placeholders", "89": "Package: app.api", "90": "Package: app.api.schemas", "91": "Package: app.application", "92": "Package: app.core", "93": "Package: app.domain", "94": "Package: app.infrastructure", "95": "Package: metadata-enrichment adapters", "96": "Package: source backends", "97": "Package: storage adapters", "98": "Package: app root (mcma-backend)", "99": "Package: arq worker", "100": "Package: arq tasks", "101": "Config Conventions (doc)", "102": "Subsonic Adapter Convention (doc)", "103": "DB Session Convention (doc)", "104": "Health Convention (doc)", "105": "Invariant: Graceful Degradation", "106": "Invariant: Likes Are Append-Only", "107": "Invariant: Stable Track content_id", "108": "Logging Convention (doc)", "109": "Python 3.14 Lazy Annotations Note", "110": "App-Passwords Mechanism (doc)", "111": "Local Dev Setup (doc)", "112": "Tooling Section (doc)", "113": "Package: workers"} \ No newline at end of file diff --git a/graphify-out/2026-07-11/GRAPH_REPORT.md b/graphify-out/2026-07-11/GRAPH_REPORT.md new file mode 100644 index 0000000..494813b --- /dev/null +++ b/graphify-out/2026-07-11/GRAPH_REPORT.md @@ -0,0 +1,505 @@ +# Graph Report - . (2026-07-11) + +## Corpus Check +- 180 files · ~50,815 words +- Verdict: corpus is large enough that graph structure adds value. + +## Summary +- 1953 nodes · 5606 edges · 114 communities (89 shown, 25 thin omitted) +- Extraction: 90% EXTRACTED · 10% INFERRED · 0% AMBIGUOUS · INFERRED: 579 edges (avg confidence: 0.56) +- Token cost: 0 input · 44,973 output + +## Community Hubs (Navigation) +- Storage Backend & Disk Usage +- Auth Schemas & Tokens +- Error Mapping & Search Schemas +- Download Service Orchestration +- Playlist Schemas & API +- Album Repository +- ORM Base & Models +- Correlation ID Middleware & Config +- Auth Services (native + Subsonic) +- Audio Tags & Metadata Test Fakes +- YouTube Source Backend +- Dependency Wiring (deps.py) +- Library Stats & Track Availability +- Library Import Service +- Subsonic Response Envelope +- Chromaprint Fingerprinting +- Album/Search Response Schemas +- Pagination & Likes Endpoints +- Metadata Enrichment Service +- Subsonic ID Encoding +- Track & Artist Domain Entities +- Source Port Protocols +- User Management Service +- Metadata Enrichment Value Objects +- DB Session & Health Checks +- Download Service Tests +- Download Job Domain Entity +- Credentials & User Repository +- Streaming Auth Dependencies +- Subsonic Browsing Endpoints +- Remote Library Service Tests +- Worker Session Scope & Download Task +- Metadata Enrichment Pipeline +- Album Domain & Cover Value Object +- Downloads API Tests +- Subsonic Search Encoding +- In-Memory Auth Repository Fakes +- Storage Stats Response Schemas +- Subsonic App-Password Crypto +- Artist Schemas & Endpoints +- Download Request/Response Schemas +- Settings & MusicBrainz User-Agent +- Subsonic API Integration Tests +- Playlist Endpoints +- Play History Domain & Repository +- DB Engine Lifecycle +- Shared Query Param Annotations +- Local Folder Source Backend +- Track Metadata Match Schemas +- Like Domain Entity (event log) +- Auth API Integration Tests +- Cover API Tests +- Upload/Stream API Tests +- Tag Parsing Helpers +- Metadata API Tests +- Subsonic Auth Service Tests +- Cover Art Serving +- Play History Schemas +- Refresh Token Repository +- Radio Endpoints +- Subsonic Legacy Password Decoding +- Management CLI +- Sources API Tests +- Hexagonal Architecture Layers (doc) +- Test DB Fixtures (conftest) +- Upload Response Schemas +- Cover Art Extraction (Vorbis/MP4) +- Storage Stats API Tests +- AcoustID Response Parser Tests +- Like Request/Response Schemas +- Streaming Endpoint +- Auth Token Issue/Refresh Flow +- Generic Job/Result Store Protocol +- Remote Library Materialization +- CI Docker Publish Workflow +- User Scrobbling Settings +- Domain Invariants (dedup, manual overwrite, offline tags) +- Alembic Migration Environment +- Cover Art Archive Client +- Health Endpoint Smoke Tests +- ASGI Middleware Protocol +- File Hashing Utilities +- Package: app.api +- Package: app.api.schemas +- Package: app.application +- Package: app.core +- Package: app.domain +- Package: app.infrastructure +- Package: metadata-enrichment adapters +- Package: source backends +- Package: storage adapters +- Package: app root (mcma-backend) +- Package: arq worker +- Package: arq tasks +- Config Conventions (doc) +- Subsonic Adapter Convention (doc) +- DB Session Convention (doc) +- Health Convention (doc) +- Invariant: Graceful Degradation +- Invariant: Likes Are Append-Only +- Invariant: Stable Track content_id +- Logging Convention (doc) +- Python 3.14 Lazy Annotations Note +- App-Passwords Mechanism (doc) +- Local Dev Setup (doc) +- Tooling Section (doc) + +## God Nodes (most connected - your core abstractions) +1. `NotFoundError` - 94 edges +2. `UserService` - 55 edges +3. `Track` - 50 edges +4. `AuthenticationError` - 49 edges +5. `TrackRepository` - 49 edges +6. `SourceInfo` - 49 edges +7. `MetadataEnrichmentService` - 47 edges +8. `DownloadResult` - 47 edges +9. `get_settings()` - 45 edges +10. `FileStorage` - 43 edges + +## Surprising Connections (you probably didn't know these) +- `test_id_malformed_rejected()` --indirect_call--> `NotFoundError` [INFERRED] + tests/test_subsonic_security.py → app/domain/errors.py +- `test_id_wrong_prefix_rejected()` --indirect_call--> `NotFoundError` [INFERRED] + tests/test_subsonic_security.py → app/domain/errors.py +- `acoustid_trust_score (trust high-confidence AcoustID over junk tags)` --semantically_similar_to--> `Invariant: never overwrite metadata_status=manual` [INFERRED] [semantically similar] + tests/fixtures/README.md → CLAUDE.md +- `FakeAcoustId` --uses--> `MetadataEnrichmentService` [INFERRED] + tests/test_metadata_service.py → app/application/metadata_service.py +- `FakeAlbumRepo` --uses--> `MetadataEnrichmentService` [INFERRED] + tests/test_metadata_service.py → app/application/metadata_service.py + +## Import Cycles +- None detected. + +## Hyperedges (group relationships) +- **Cross-cutting conventions (errors, config, logging, db sessions, migrations, health)** — claude_error_handling_convention, claude_config_convention, claude_logging_convention, claude_db_sessions_convention, claude_migrations_convention, claude_health_convention [EXTRACTED 1.00] +- **Non-negotiable domain invariants (for future sync + ML)** — claude_invariant_likes_event_log, claude_invariant_track_id_stable, claude_invariant_dedup, claude_invariant_graceful_degradation, claude_invariant_no_manual_overwrite, claude_invariant_no_heavy_work_in_request, claude_invariant_subsonic_compatibility [EXTRACTED 1.00] +- **Hexagonal architecture layers (domain/application/infrastructure/api/core/workers)** — claude_domain_layer, claude_application_layer, claude_infrastructure_layer, claude_api_layer, claude_core_layer, claude_workers_layer [EXTRACTED 1.00] + +## Communities (114 total, 25 thin omitted) + +### Community 0 - "Storage Backend & Disk Usage" +Cohesion: 0.05 +Nodes (53): DiskUsage, ObjectStat, Value objects for file storage., Capacity of the volume backing the media store. ``None`` for backends (e.g., File storage operation failed., StorageError, Capacity of the volume backing the store, or ``None`` when the backend h, LocalFileStorage (+45 more) + +### Community 1 - "Auth Schemas & Tokens" +Cohesion: 0.07 +Nodes (59): LoginRequest, BaseModel, Auth request/response schemas. Tokens are returned in the body (the client store, RefreshRequest, RegisterRequest, TokenResponse, BaseModel, Schemas for Subsonic app-password self-service (native /api/v1 surface). The Su (+51 more) + +### Community 2 - "Error Mapping & Search Schemas" +Cohesion: 0.06 +Nodes (44): _is_subsonic(), FastAPI, Maps domain exceptions to HTTP responses. The only place that knows both. Two s, register_exception_handlers(), ExternalSearchResponse, ExternalSearchResultOut, BaseModel, Schemas for searching external (fetch) sources — the §A4 discover screen. (+36 more) + +### Community 3 - "Download Service Orchestration" +Cohesion: 0.07 +Nodes (24): DownloadRequest, EnrichEnqueuer, DownloadService — request external downloads and import their results. Two role, Outcome of asking for a download. Exactly one of the three states holds: th, EnrichEnqueuer, Path, Protocol, UploadService — handles user file uploads. (+16 more) + +### Community 4 - "Playlist Schemas & API" +Cohesion: 0.11 +Nodes (34): PlaylistAddTrack, PlaylistCreate, PlaylistOut, PlaylistUpdate, BaseModel, Playlist request/response schemas., add_playlist_track(), _build_playlist_out() (+26 more) + +### Community 5 - "Album Repository" +Cohesion: 0.07 +Nodes (10): AlbumRepository, DownloadJobRepository, PlaylistRepository, datetime, UUID, Resolve/create an album bound to a remote ``(source, source_id)`` (lazy, Persistence for download jobs (plan §6.1). Drives the §A5 download manager a, Bump ``retry_count`` and return the new value. (+2 more) + +### Community 6 - "ORM Base & Models" +Cohesion: 0.10 +Nodes (32): Base, Declarative base with a fixed naming convention. The naming convention makes Al, Base for all ORM models. Import models so Alembic sees their metadata., ORM model for albums., ORM model for artists., ORM model for download jobs (plan §6.1). Tracks a queued download through its l, LikeValue, LyricsStatus (+24 more) + +### Community 7 - "Correlation ID Middleware & Config" +Cohesion: 0.09 +Nodes (33): CorrelationIdMiddleware, HTTP middleware: bind a correlation id and log each request., Pure-ASGI middleware: reuse inbound ``X-Correlation-Id`` or mint one, bind i, app_version(), get_settings(), Application settings — single source of truth, sourced from environment. Nothin, Cached settings singleton. Patch the cache in tests via ``get_settings.cache_cle, _add_correlation_id() (+25 more) + +### Community 8 - "Auth Services (native + Subsonic)" +Cohesion: 0.12 +Nodes (21): Authentication use cases: login, token refresh (rotation), logout, and access-to, SubsonicAuthService — app-password lifecycle + Subsonic auth verification. The, User entity. Admin is a single ``is_superuser`` flag — no role system in Phase, HistoryRepository, LikeRepository, PasswordHasher, Protocol, Ports — the contracts the application layer depends on. These are Protocols, no (+13 more) + +### Community 9 - "Audio Tags & Metadata Test Fakes" +Cohesion: 0.15 +Nodes (28): AudioTags, Embedded tags read from the file itself (ID3 / Vorbis / MP4 …). Every field, _cover_service(), FakeAlbumRepo, FakeArtistRepo, FakeCoverExtractor, FakeCoverProvider, FakeTagReader (+20 more) + +### Community 10 - "YouTube Source Backend" +Cohesion: 0.09 +Nodes (30): Which backend imported a track. Drives ``is_replaceable`` (plan §6.6)., TrackSource, _default_download(), _default_search(), _libs_available(), Any, Path, ProgressCallback (+22 more) + +### Community 11 - "Dependency Wiring (deps.py)" +Cohesion: 0.10 +Nodes (35): get_album_repository(), get_artist_repository(), get_auth_service(), get_download_service(), get_history_repository(), get_like_repository(), get_metadata_service(), get_password_hasher() (+27 more) + +### Community 12 - "Library Stats & Track Availability" +Cohesion: 0.12 +Nodes (19): FormatBreakdown, LibraryStats, Per-container-format slice of the library (e.g. ``flac`` → 312 tracks)., Aggregate facts about everything the instance has stored. Computed from the, Track, Whether a track's audio is on local storage or still a remote placeholder (p, TrackAvailability, TrackModel (+11 more) + +### Community 13 - "Library Import Service" +Cohesion: 0.13 +Nodes (18): ImportSummary, LibraryImportService, UUID, LibraryImportService — imports files discovered by an indexable source. Batch s, Source-backend value objects — framework-free. A *source* is a place tracks com, A single importable file discovered by an indexable source. ``source_id`` i, SourceFile, FakeArtistRepo (+10 more) + +### Community 14 - "Subsonic Response Envelope" +Cohesion: 0.12 +Nodes (30): _build_xml(), _is_json(), Any, Element, Response, The Subsonic response envelope — one serializer, two wire formats. Every Subson, A ``status="failed"`` envelope carrying a Subsonic ````., Recursively drop ``None`` values so JSON output matches XML (no empty attrs). (+22 more) + +### Community 15 - "Chromaprint Fingerprinting" +Cohesion: 0.10 +Nodes (21): FpcalcFingerprinter, Path, FpcalcFingerprinter — Chromaprint fingerprint via the ``fpcalc`` binary. ``fpca, Implements :class:`app.domain.ports.AudioFingerprinter`., MutagenTagReader, Implements :class:`app.domain.ports.AudioTagReader`., _acoustid_client(), _FakeAlbumRepo (+13 more) + +### Community 16 - "Album/Search Response Schemas" +Cohesion: 0.12 +Nodes (28): AlbumOut, BaseModel, Album request/response schemas., LibrarySearchResponse, BaseModel, Search response schemas., _build_album_out(), get_album() (+20 more) + +### Community 17 - "Pagination & Likes Endpoints" +Cohesion: 0.17 +Nodes (29): Shared pagination envelope for all paged list responses., TrackOut, get_likes(), AlbumRepoDep, ArtistRepoDep, Like endpoints. Likes are an append-only event-log — never updated in place., _build_track_out(), delete_track() (+21 more) + +### Community 18 - "Metadata Enrichment Service" +Cohesion: 0.11 +Nodes (11): _first_int(), MetadataEnrichmentService, _opt_str(), UUID, Explain a ``failed`` (no-identity) run in terms a user can act on: which, AcoustID candidates for the metadata editor's match picker (§A7). Read-, Fill in an album cover when it has none. Source order mirrors the tag-fi, CoverArt (+3 more) + +### Community 19 - "Subsonic ID Encoding" +Cohesion: 0.14 +Nodes (28): decode_album(), decode_artist(), _decode_as(), decode_playlist(), decode_track(), encode(), encode_playlist(), encode_track() (+20 more) + +### Community 20 - "Track & Artist Domain Entities" +Cohesion: 0.12 +Nodes (12): Artist, Track and Artist domain entities., Resolve/create an artist bound to a remote ``(source, source_id)`` (lazy, ArtistModel, AsyncSession, UUID, Artist repository — adapter over ``AsyncSession``., Resolve an artist by ``(source, source_id)`` first (re-browse/save dedup (+4 more) + +### Community 21 - "Source Port Protocols" +Cohesion: 0.13 +Nodes (16): FetchableSource, IndexableSource, A registered source of tracks (mounted folder, YouTube, …). ``name`` is the, A source that enumerates files already on disk (e.g. the local folder)., A source that can be searched by free text (e.g. YouTube Music). Returns ``, A source that can download a previously-discovered item to local disk. ``fe, SearchableSource, SourceBackend (+8 more) + +### Community 22 - "User Management Service" +Cohesion: 0.19 +Nodes (24): AuthService, User-management use cases: admin CRUD plus self-service password change. Deleti, UserService, AlreadyExistsError, AuthenticationError, Resource conflicts with an existing one (e.g. duplicate)., Caller could not be authenticated., env() (+16 more) + +### Community 23 - "Metadata Enrichment Value Objects" +Cohesion: 0.14 +Nodes (12): Fingerprint, Value objects for the metadata-enrichment pipeline (plan §6.2). Pure data carri, Chromaprint fingerprint plus the decoded duration (both needed by AcoustID)., A single AcoustID result, flattened to the fields enrichment cares about. `, RecordingMatch, AcoustIdHttpClient, _parse_matches(), _parse_one() (+4 more) + +### Community 24 - "DB Session & Health Checks" +Cohesion: 0.10 +Nodes (24): get_session(), AsyncSession, Request-scoped DB session. Commits on success, rolls back on exception., _check_db(), _check_ml(), _check_redis(), health(), HealthResponse (+16 more) + +### Community 25 - "Download Service Tests" +Cohesion: 0.16 +Nodes (14): DownloadService, FakeArtistRepo, FakeJobRepo, FakeStorage, FakeTrackRepo, Path, UUID, Unit tests for DownloadService — DB-free, in-memory fakes. (+6 more) + +### Community 26 - "Download Job Domain Entity" +Cohesion: 0.13 +Nodes (10): DownloadJob, Download job domain entity (plan §6.1). A queued fetch from an external source,, An unfinished (queued/downloading/enriching) job for the same item, if a, DownloadJobModel, DownloadStatus, Lifecycle of a download job (plan §6.1)., datetime, UUID (+2 more) + +### Community 27 - "Credentials & User Repository" +Cohesion: 0.15 +Nodes (10): Credentials, A user paired with their stored password hash. Stays inside the application, A user paired with their *encrypted* Subsonic app-password. ``password_enc`, SubsonicCredentials, UserModel, AsyncSession, UUID, User repository — adapter over ``AsyncSession`` implementing ``app.domain.ports. (+2 more) + +### Community 28 - "Streaming Auth Dependencies" +Cohesion: 0.10 +Nodes (13): get_current_superuser(), get_current_user(), get_streaming_user(), AuthServiceDep, CurrentUser, Authenticate a stream request. The browser ``