Backend: Added docs & AGENTS.md

This commit is contained in:
Mohammed Abad committed 2026-03-30 19:37:08 +01:00
1 parent b3f2097b8b
commit b3ab69cc22
8 files changed
+3082

No files matched your search

+150
View File
@@ -0,0 +1,150 @@
# Agents & Autonomous Logic
> **Last reviewed:** 2026-03-30
---
## Overview
The Showy backend does **not** incorporate any AI models, LLM integrations, or agentic frameworks (e.g., LangChain, OpenAI function-calling, autonomous planners). There are no prompt-driven decision loops, tool-use chains, or inference endpoints.
However, the system does implement several **autonomous orchestration services** — referred to internally as **"Managers"** — that coordinate multi-step workflows without user intervention after the initial trigger. These managers behave similarly to agents in that they:
- Make decisions based on data state (e.g., "is this person fully fetched?")
- Orchestrate side effects across multiple services (TMDB API, DB, filesystem)
- Perform lazy evaluation and deferred work on first access
---
## Manager Services (Agent-like Orchestrators)
### 1. `EntryManager`
**File:** `services/entryManager.js`
**Singleton:** Yes
| Capability | Description |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetchAndSaveNewEntry(tmdbId, isTvSeries)` | Fetches entry from TMDB → persists entry + IDs + ratings + genres → fetches seasons & episodes (if TV) → downloads & generates media previews → fetches & links collection |
| `refrechEntryById(id)` | Compares local data with TMDB → selectively updates title, dates, status, ratings, genres, networks → iterates seasons/episodes to upsert new ones → fetches credits & creates People/Credit records |
| `SyncSeriesData()` | Batch refresh of all TV series entries |
| `getUpdatedEntry(id)` | Lazy trigger: returns entry and refreshes if stale |
**Orchestration flow for `fetchAndSaveNewEntry`:**
```
Client POST /entries { tmdb_id, is_tvserie }
│
├─ 1. tmdbService.fetchEntryData() → TMDB API call
├─ 2. entryService.createEntry() → DB insert (entry + entryId + entryRating + genres)
├─ 3. collectionManager.fetchAndSaveCollection() → if movie belongs to a collection
├─ 4. mediaManager.getEntryMedia() → downloads posters/backdrops/logos
├─ 5. mediaOptimizerService.doGeneratePreview() → generates low-res previews
└─ 6. (for TV) loops seasons → episodes → downloads season/episode media
```
---
### 2. `CollectionManager`
**File:** `services/collectionManager.js`
**Singleton:** Yes
| Capability | Description |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetchAndSaveCollection(tmdbId)` | Fetches collection from TMDB → creates/updates collection record → links existing library entries as parts → downloads & generates media previews |
| `fetchCollectionByEntryId(entryId)` | Resolves an entry's parent collection from TMDB if not yet stored locally |
| `getCollectionParts(collectionId)` | Fetches missing parts (entries) that belong to the collection but are not in the local library → auto-imports them |
**Decision logic in `getCollectionParts`:**
```
For each TMDB collection part:
├─ Part already in library? → link to collection (skip fetch)
└─ Part NOT in library? → entryManager.fetchAndSaveNewEntry() → link
```
---
### 3. `PeopleManager`
**File:** `services/peopleManager.js`
**Singleton:** Yes
| Capability | Description |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getUpdatedPerson(id)` | Lazy-fetch pattern: if `fully_fetched` is false, fetches detailed person data from TMDB → updates DB → downloads profile images → generates previews |
**Decision logic:**
```
GET /people/:id
│
├─ person.fully_fetched == true? → return cached data
└─ person.fully_fetched == false?
├─ tmdbService.fetchPersonDetails()
├─ peopleService.updatePerson()
├─ mediaDownloaderService.downloadPersonMedia()
├─ mediaOptimizerService.doGeneratePreview()
└─ return enriched person
```
---
### 4. `MediaManager`
**File:** `services/mediaManager.js`
**Singleton:** Yes
| Capability | Description |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `saveMedia(entryId, files)` | Persists uploaded media → triggers async preview generation |
| `getEntryMedia(tmdbId, isTvSeries)` | Fetches available images from TMDB → selects preferred variants → downloads in parallel → stores on disk |
| `getSeasonMedia(season)` | Downloads season poster from TMDB → stores locally |
| `getEpisodenMedia(episode)` | Downloads episode still from TMDB → stores locally |
---
## Supporting Services
These are not autonomous but are invoked by the managers above:
| Service | File | Role |
| ------------------------ | ------------------------------------ | ----------------------------------------------------------------------------------------- |
| `tmdbService` | `services/tmdbService.js` | HTTP client wrapping TMDB API v3 (entries, seasons, credits, people, collections, images) |
| `mediaDownloaderService` | `services/mediaDownloaderService.js` | Downloads remote images to local filesystem |
| `mediaOptimizerService` | `services/mediaOptimizerService.js` | Generates low-resolution preview variants (JPEG/PNG) |
| `configService` | `services/configService.js` | Reads/writes `settings.json`; provides TMDB API credentials and data paths |
| `storageService` | `services/storageService.js` | Low-level file write abstraction |
| `networkService` | `services/networkService.js` | Creates or updates TV network records |
| `importerService` | `services/importerService.js` | Bulk-import orchestration with TMDB rate-limit handling (35 req / 10 s) |
| `maintenanceService` | `services/maintenanceService.js` | Detects and cleans orphan files and DB records |
---
## Importer Rate-Limit Strategy
The `importerService` implements a self-throttling loop to respect TMDB's rate limits:
```
for each item in batch:
fetch from TMDB
wait 500ms
if (fetchCount >= 35):
wait 10 seconds
reset counter
```
This is the closest pattern to an "autonomous agent loop" in the current codebase — it runs unsupervised for potentially long periods, makes sequential decisions, and self-regulates.
---
## Future Considerations
The manager pattern is well-suited for upgrading to a true agentic architecture if needed:
- **Tool registry** — Each service (`tmdbService`, `mediaDownloaderService`, etc.) could be registered as a callable tool.
- **Planner/Orchestrator** — An LLM-backed planner could replace the hardcoded orchestration in managers.
- **Observation loop** — The lazy-fetch pattern (`fully_fetched` checks) already implements observe → decide → act semantics.
No such integration exists today. All decision logic is deterministic and rule-based.