diff --git a/README.md b/README.md
index 2c6fbb1..0fa0b59 100644
--- a/README.md
+++ b/README.md
@@ -1,33 +1,40 @@
# π¬ MagNetFlix
-> Automated, secure movie fetching and library organization pipeline via gRPC, Transmission, and Traefik/Authelia SSO.
+> Self-hosted, automated media acquisition and library organization pipeline built with **FastAPI (BFF)**, **gRPC**, **SQLite WAL**, **Transmission RPC**, and **pluggable SSO/OIDC authentication**.
---
## π Table of Contents
-- [Overview](docs/overview.md) - Project mission, key features, and user workflow.
-- [Architecture](docs/architecture.md) - System design, BFF pattern, gRPC contracts, and data flow.
-- [Development Rules & Agent Guidelines](AGENTS.md) - Coding standards, monorepo conventions, and toolchain rules.
-- [Roadmap](docs/roadmap.md) - Milestone-by-milestone development plan.
-- [Deployment Guide](docs/deployment.md) - Docker Compose, Traefik integration, and Authelia SSO setup.
+- [Overview](docs/overview.md) β Mission, user workflow, and features.
+- [Architecture](docs/architecture.md) β System design, state machine, security boundaries, and storage invariants.
+- [Reconciled Roadmap](docs/roadmap.md) β Dependency-ordered implementation milestones.
+- [Deployment Guide](docs/deployment.md) β Docker Compose topology, volume mounts, and SSO identity adapter.
+- [Architecture Decision Records](docs/adr/) β Canonical records of design choices, tradeoffs, and invariants:
+ - [ADR 001: Pipeline Safety, Storage Boundaries, and BFF Dual-Client Architecture](docs/adr/001-pipeline-safety-and-bff-dual-client.md)
+ - [ADR 002: Pipeline Invariants, Two-Stage Metadata, and Active Reconciliation](docs/adr/002-pipeline-invariants-and-active-reconciliation.md)
+- [Historical Audit Ledger](docs/history/phase-a-current-state-audit.md) β Phase A current-state audit and portfolio assessment.
+- [Development Rules & Agent Guidelines](AGENTS.md) β Code quality standards, safety rules, and workspace invariants.
---
## β‘ Quick Start
```bash
-# Enter hermetic dev shell (Nix)
+# 1. Enter hermetic dev shell (Nix)
nix develop
-# Or install dependencies with uv workspace
+# 2. Or install dependencies with uv workspace
uv sync
-# Generate protobuf stubs
+# 3. Generate protobuf stubs & documentation
make generate
-# Start full local stack with docker compose
-docker compose up -d
+# 4. Run test suite
+uv run pytest
+
+# 5. Run static type checking and linters
+make check
```
---
@@ -36,28 +43,26 @@ docker compose up -d
```text
.
-βββ AGENTS.md # Development guidelines & rules for AI/human contributors
-βββ Makefile # High-level build & generation commands
+βββ AGENTS.md # Development guidelines & safety invariants
+βββ CLAUDE.md # Developer CLI commands & tool directives
+βββ Makefile # High-level build, codegen, lint, and test targets
βββ README.md # Project landing page
-βββ buf.gen.yaml # Buf remote plugin generation config
-βββ buf.yaml # Buf module definition
-βββ docker-compose.yml # Local development & production compose stack
-βββ docs/ # Detailed system documentation
-β βββ architecture.md # Architecture & component interactions
-β βββ deployment.md # Traefik & Authelia deployment guide
+βββ buf.gen.yaml # Buf code generation configuration
+βββ buf.yaml # Buf module configuration
+βββ docker-compose.yml # Multi-container Compose stack specification
+βββ docs/ # Authoritative architecture and operations documentation
+β βββ adr/ # Architecture Decision Records (ADRs)
+β βββ history/ # Audit logs and review ledgers
+β βββ architecture.md # System design, data flow, and invariants
+β βββ deployment.md # Container topology and reverse proxy integration
β βββ overview.md # Feature overview & workflow
-β βββ roadmap.md # Development milestones
+β βββ roadmap.md # 5-Milestone implementation plan
βββ proto/ # Protocol Buffer definitions
β βββ magnetflix/v1/
β βββ pipeline.proto
-βββ services/
- βββ bff/ # FastAPI Web Gateway / HTML Form / Authelia SSO
- β βββ Dockerfile
- β βββ pyproject.toml
- β βββ src/bff/
- βββ worker/ # gRPC Pipeline Worker & Transmission Coordinator
- βββ Dockerfile
- βββ alembic/
- βββ pyproject.toml
- βββ src/worker/
+βββ services/
+β βββ bff/ # FastAPI Web Gateway / HTML Form / Pluggable SSO
+β βββ contracts/ # Shared Protobuf & gRPC contracts package
+β βββ worker/ # gRPC Pipeline Worker & Transmission Coordinator
+βββ tests/ # Unit and integration test suites
```
diff --git a/docs/adr/002-pipeline-invariants-and-active-reconciliation.md b/docs/adr/002-pipeline-invariants-and-active-reconciliation.md
new file mode 100644
index 0000000..d8c5bc3
--- /dev/null
+++ b/docs/adr/002-pipeline-invariants-and-active-reconciliation.md
@@ -0,0 +1,83 @@
+---
+type: decision
+status: accepted
+project: MagNetFlix
+date: 2026-10-29
+tags: [architecture, security, storage, metadata, recovery, concurrency, sso, bff]
+---
+
+# ADR 002: Pipeline Invariants, Two-Stage Metadata, and Active Reconciliation
+
+## Context and Problem Statement
+
+Following the initial architectural baseline established in [ADR 001](001-pipeline-safety-and-bff-dual-client.md) and the implementation of the SQLite WAL engine, an interactive architectural review identified critical engineering gaps across several core subsystems:
+
+1. **Protobuf Packaging & Build Reproducibility (`GAP-1`)**: The stubs emitted by `buf` produced `ModuleNotFoundError: No module named 'magnetflix'` when imported due to nested package output paths, and generated stubs were excluded from git and static type checks.
+2. **Active-Job Concurrency (`GAP-2`)**: Concurrent submissions for the same movie could race past application-level checks and insert duplicate active downloads due to the absence of a database-level uniqueness constraint.
+3. **Sanitizer Boundary Policy (`GAP-3`)**: A documented contradiction existed between *purging* non-media files versus *aborting* the entire job if non-allowlisted files exist. Because ~95% of real-world torrents contain `.nfo` or `.txt` clutter, strict rejection causes widespread false-positive failures, while pure whitelisting ignores symlink/executable hazards.
+4. **Metadata Resolution Timing (`GAP-5`)**: Fetching TMDB metadata only after download completion leaves the UI live dashboard blank during 30β60 minute downloads and wastes tens of gigabytes of bandwidth on invalid IMDb IDs.
+5. **Subtitle Relocation Collisions (`GAP-4`)**: Hardcoding target subtitles to `
().en.srt` corrupts non-SRT formats (`.ass`, `.vtt`) and causes silent overwrite collisions when multiple tracks exist.
+6. **Crash Recovery & Daemon State (`GAP-6`)**: Simply marking SQLite rows as `FAILED` on worker restart leaves orphaned torrent sessions actively downloading in the Transmission container and abandons scratch disks.
+7. **Async Concurrency & Blocking I/O (`GAP-7`)**: Calling multi-gigabyte `shutil.copy2` transfers or synchronous `transmission-rpc` requests directly on Python's async event loop freezes gRPC RPCs and SSE streaming connections.
+8. **Pluggable SSO & Search Boundaries (`GAP-8`)**: Hardcoding Authelia headers tightly coupled MagNetFlix to specific homelab infrastructure, and client-side scraping of undocumented IMDb endpoints created browser CORS and fragility risks.
+
+---
+
+## Decision Outcome & Invariants
+
+### 1. Dedicated Workspace Contracts Package (`DEC-1`)
+- Stubs are generated once into a shared workspace package `services/contracts` (`module-name = "magnetflix"`).
+- Both `worker` and `bff` depend on `magnetflix-contracts` via `{ workspace = true }`, allowing native `from magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpc` imports.
+- Generated stubs and `docs/api_spec.md` are committed to Git, enabling reproducible offline test and Docker builds.
+
+### 2. Database Partial Unique Index & Info-Hash Column (`DEC-2`)
+- Add an indexed column `info_hash` to `download_jobs`.
+- Add a partial unique index in SQLite:
+ ```sql
+ CREATE UNIQUE INDEX uq_download_jobs_active_imdb_id
+ ON download_jobs (imdb_id)
+ WHERE state NOT IN ('COMPLETED', 'FAILED');
+ ```
+- Guaranteed engine-level deduplication: concurrent duplicate submissions fail with `IntegrityError`, mapped cleanly to `grpc.StatusCode.ALREADY_EXISTS`.
+
+### 3. Two-Tier Sanitization Policy (`DEC-3`)
+- **Tier 1 (Hard Security Rejection)**: Immediate job abort to `FAILED` if the payload contains symbolic links (`os.path.islink`), hard links (`st_nlink > 1`), path traversal (`..`), special device nodes, or dangerous extensions (`.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`).
+- **Tier 2 (Allowlist Extraction & Safe Discard)**: Extract allowlisted video (`.mkv`, `.mp4`, `.avi`, `.webm`) and subtitles (`.srt`, `.vtt`, `.sub`, `.ass`). Safely ignore benign clutter (`.nfo`, `.txt`, `.jpg`, `.sfv`). Discard samples (`< 100MB` or `"sample"`). Select the single largest remaining video file as the feature film.
+
+### 4. Two-Stage Metadata Lifecycle (`DEC-4`)
+- **Stage 1 (Early Ingestion)**: Query TMDB API `/find/{imdb_id}?external_source=imdb_id` at job submission/queueing time. Verify valid movie entity type; persist `title` and `year` to SQLite immediately. Live UI and SSE streams display movie metadata from second 1.
+- **Stage 2 (Post-Download Token Check)**: Compare cached `(title, year)` tokens against primary video filename completely offline from SQLite without external network dependencies.
+
+### 5. Multi-Track Subtitle Preservation & Two-Stage Atomic Swap (`DEC-5`)
+- Retain native subtitle extensions (`.srt`, `.vtt`, `.ass`).
+- Parse language and forced tags from filenames; append disambiguation indices (` ().en.1.srt`) when multiple subtitles share tags to prevent overwrites.
+- Copy verified files across storage boundaries to `/media/movies/.staging_/`. Pre-check destination existence, then atomically swap via `os.replace`.
+
+### 6. Active Reconciliation & Stalled Timeout (`DEC-6`)
+- On worker startup, query all non-terminal SQLite jobs: transition state to `FAILED`, actively call Transmission RPC `remove_torrent(info_hash, delete_data=True)`, and purge scratch directories `/data/staging//` and `/media/movies/.staging_/`.
+- Monitor swarm progress during `DOWNLOADING`: auto-fail jobs with 0 progress for 15 consecutive minutes.
+
+### 7. Thread Offloading & In-Memory SSE Fan-Out (`DEC-7`)
+- Dispatch all blocking disk copies (`shutil.copy2`), synchronous RPC calls (`transmission-rpc`), and directory scans to a bounded `ThreadPoolExecutor(max_workers=4)`.
+- Database sessions are strictly short-lived (committed and closed before long I/O).
+- Broadcast progress and state change events via an internal `asyncio.Queue` pub/sub broker to connected gRPC/SSE streams.
+
+### 8. Pluggable Identity Adapter & Server-Side Search (`DEC-8`)
+- FastAPI BFF middleware reads identity headers via configurable environment variables (`AUTH_ENABLED`, `AUTH_HEADER_USER`, `AUTH_HEADER_EMAIL`) with a safe dev fallback (`local_user`).
+- Expose `GET /api/v1/movies/search?q=...` proxying TMDB movie search server-side to eliminate CORS issues and undocumented third-party scraping.
+- Mount dual route bindings (`POST /api/v1/downloads` and `POST /download`) with Pydantic aliases (`magnet`/`magnet_uri`, `imdbid`/`imdb_id`).
+
+---
+
+## Consequences
+
+### Positive Consequences
+- Guarantees 100% reproducible builds and eliminates `ModuleNotFoundError` across all environments.
+- Protects the host and media library from malicious torrent payloads, path traversal, and partial writes.
+- Eliminates zombie torrents and leaked staging disk space across container restarts.
+- Maintains responsive gRPC and SSE streaming performance during multi-gigabyte disk transfers.
+- Decouples MagNetFlix from specific reverse proxy or identity provider implementations.
+
+### Accepted Tradeoffs & Operational Costs
+- Requires outbound TMDB API key access on both BFF (for movie search) and Worker (for metadata resolution).
+- Requires temporary disk space on `/media/movies` to hold `.staging_/` during cross-volume copying.
diff --git a/docs/architecture.md b/docs/architecture.md
index e56d565..fcfebec 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -1,6 +1,6 @@
-# ποΈ MagNetFlix β Architecture & System Design
+# ποΈ MagNetFlix β System Architecture & Component Design
-MagNetFlix uses a **Backend-For-Frontend (BFF)** pattern paired with an internal **gRPC Worker** pipeline service to decouple public web endpoints from disk I/O and media processing.
+MagNetFlix uses a **Backend-For-Frontend (BFF)** pattern paired with an internal **gRPC Pipeline Worker** service to decouple public web endpoints from disk I/O, BitTorrent network activity, and media processing.
---
@@ -8,24 +8,24 @@ MagNetFlix uses a **Backend-For-Frontend (BFF)** pattern paired with an internal
```mermaid
flowchart TB
- subgraph Edge ["π Public Edge (Protected)"]
- Browser["User Browser\n(Web UI)"] -->|HTTPS| Traefik["Traefik Reverse Proxy"]
- Extension["Browser Extension\n(One-Click Magnet Hook)"] -->|HTTPS| Traefik
- Traefik <-->|Forward Auth| Authelia["Authelia SSO"]
+ subgraph Edge ["π Public Edge (Protected Gateway)"]
+ Browser["User Browser\n(Web UI Dashboard)"] -->|HTTPS| Proxy["Reverse Proxy\n(Traefik / Nginx / Caddy)"]
+ Extension["Browser Extension\n(One-Click Magnet Interceptor)"] -->|HTTPS| Proxy
+ Proxy <-->|Auth Forward / Bearer| SSO["Identity Provider / SSO\n(Authelia / Authentik / OAuth2-Proxy)"]
end
- subgraph InternalServices ["π‘οΈ Internal Services (Docker Network)"]
- Traefik -->|HTTP + Remote-User| BFF["FastAPI BFF Gateway\n(Serves Web UI + API)"]
+ subgraph InternalServices ["π‘οΈ Internal Service Tier (Docker Bridge)"]
+ Proxy -->|HTTP + Identity Headers| BFF["FastAPI BFF Gateway\n(Pluggable Auth Adapter & SSE Stream)"]
- subgraph WorkerApp ["Worker Service"]
- BFF -->|gRPC / Stream| Worker["gRPC Pipeline Server"]
- Worker --> DB[("SQLite 3 (WAL Mode)\nAudit & State Store")]
- Worker --> Sanitizer["Media Sanitizer & Allowlist"]
- Worker --> MetaService["TMDB Metadata Client"]
- Worker --> StorageMgr["Library Relocator & Renamer"]
+ subgraph WorkerApp ["Worker Service Tier"]
+ BFF -->|gRPC / Status Stream| Worker["gRPC Pipeline Worker"]
+ Worker --> DB[("SQLite 3 (WAL Mode)\nJobs & Audit Store")]
+ Worker --> MetaService["TMDB Metadata Client\n(Early Resolution & Token Check)"]
+ Worker --> Sanitizer["Media Sanitizer & Allowlist\n(Two-Tier Security Boundary)"]
+ Worker --> StorageMgr["Library Relocator & Renamer\n(Two-Stage Atomic Relocation)"]
end
- Worker --> Torrent["Transmission Daemon"]
+ Worker -->|Offloaded RPC| Torrent["Transmission Daemon"]
end
subgraph Volumes ["πΎ Storage Mounts"]
@@ -34,11 +34,13 @@ flowchart TB
end
```
-> For foundational design trade-offs and decisions, see [ADR 001: Pipeline Safety, Storage Boundaries, and BFF Dual-Client Architecture](adr/001-pipeline-safety-and-bff-dual-client.md).
+> **Design Decisions & Tradeoffs:**
+> - [ADR 001: Pipeline Safety, Storage Boundaries, and BFF Dual-Client Architecture](adr/001-pipeline-safety-and-bff-dual-client.md)
+> - [ADR 002: Pipeline Invariants, Two-Stage Metadata, and Active Reconciliation](adr/002-pipeline-invariants-and-active-reconciliation.md)
---
-## π Job State Machine & Lifecycle Rules
+## π Job State Machine & Lifecycle Invariants
The pipeline worker operates strictly as a finite state machine with terminal failure handling.
@@ -47,102 +49,112 @@ stateDiagram-v2
[*] --> QUEUED: SubmitDownload()
QUEUED --> DOWNLOADING: Transmission starts torrent
DOWNLOADING --> SCANNING: Torrent reaches 100%
- DOWNLOADING --> FAILED: Torrent error / stalled timeout
+ DOWNLOADING --> FAILED: Torrent error / 15-min stall timeout
- SCANNING --> VERIFYING_METADATA: Sanitizer validates payload
- SCANNING --> FAILED: Disallowed files / no valid video
+ SCANNING --> VERIFYING_METADATA: Two-Tier Sanitizer validates payload
+ SCANNING --> FAILED: Security threat (symlink/traversal/exe) / no valid video
- VERIFYING_METADATA --> ORGANIZING: TMDB match verified
- VERIFYING_METADATA --> FAILED: Title/year mismatch or lookup failed
+ VERIFYING_METADATA --> ORGANIZING: Token overlap matches TMDB cache
+ VERIFYING_METADATA --> FAILED: Title/year token mismatch
- ORGANIZING --> COMPLETED: Files relocated & renamed
- ORGANIZING --> FAILED: Disk full / permission error
+ ORGANIZING --> COMPLETED: Files relocated & atomic swap complete
+ ORGANIZING --> FAILED: Target collision / disk full / permission error
COMPLETED --> [*]
FAILED --> [*]
```
-### Transition & Failure Invariants
+### Transition & Concurrency Invariants
1. **Linear Progression**: `QUEUED` β `DOWNLOADING` β `SCANNING` β `VERIFYING_METADATA` β `ORGANIZING` β `COMPLETED`.
-2. **Terminal Failure**: Any failure at any phase transitions the job directly to `FAILED` with a populated `error_message`.
-3. **Stalled Download Timeout**: If a torrent achieves zero progress (0 bytes downloaded or unresolved magnet metadata) for 15 consecutive minutes, the job transitions to `FAILED` with reason `"Download stalled: no seeds or metadata timeout"`.
-4. **Crash & Restart Recovery**: Upon worker startup, any orphaned non-terminal jobs (`QUEUED`, `DOWNLOADING`, `SCANNING`, `VERIFYING_METADATA`, `ORGANIZING`) in the SQLite database are automatically transitioned to `FAILED` with reason `"Worker restarted during execution"`. Retrying requires a new submission.
-5. **Duplicate Rejection (Idempotency)**:
- - A submission is rejected if a non-terminal job for the same `imdb_id` is currently active in the database.
- - A submission is rejected if `/media/movies/*[imdbid-{imdb_id}]` already exists in the destination library.
+2. **Terminal Failure**: Any failure at any phase transitions the job directly to `FAILED` with a populated `error_message`. Terminal states (`COMPLETED`, `FAILED`) are immutable.
+3. **Active-Job Idempotency (`DEC-2`)**:
+ - Submissions are rejected if a non-terminal job for the same `imdb_id` is currently active in SQLite.
+ - Enforced by a partial unique index: `uq_download_jobs_active_imdb_id ON download_jobs (imdb_id) WHERE state NOT IN ('COMPLETED', 'FAILED')`.
+ - Submissions are rejected if `/media/movies/*[imdbid-{imdb_id}]` already exists in the destination library.
+4. **Stalled Download Timeout (`DEC-6`)**: If a torrent achieves zero progress (0 bytes downloaded or unresolved magnet metadata) for 15 consecutive minutes, the job transitions to `FAILED` with reason `"Download stalled: no seeds or metadata timeout"`.
+5. **Active Startup Crash Recovery (`DEC-6`)**: Upon worker startup, an active reconciliation sweep queries all orphaned non-terminal jobs:
+ - Transitions their SQLite state to `FAILED` with reason `"Worker restarted during execution"`.
+ - Actively signals Transmission via RPC to remove the torrent session via `info_hash` (`delete_data=True`).
+ - Purges scratch directories `/data/staging//` and `/media/movies/.staging_/`.
---
-## π‘οΈ Security & Media Sanitizer Specification
+## π‘οΈ Security & Media Sanitizer Specification (`DEC-3`)
-The sanitizer enforces a strict file-system boundary before files are touched or moved:
+The sanitizer enforces a strict two-tier security boundary on untrusted torrent payloads before files are processed:
-1. **Path Traversal & Symlink Check**: Rejects any archive or torrent payload containing symbolic links, hard links, or paths escaping the staging root (`..`).
-2. **File Allowlist**:
- - **Allowed Video**: `.mkv`, `.mp4`, `.avi`, `.webm`
- - **Allowed Subtitles**: `.srt`, `.vtt`, `.sub`, `.ass`
- - **Forbidden / Quarantine**: `.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.lnk`, `.iso`, `.zip`, `.rar`, etc.
-3. **Multiple Video Selection (Largest File Rule)**:
- - Files containing `sample` in the filename or with size `< 100MB` are discarded.
- - If multiple video files remain, the **single largest video file** is selected as the primary feature film. A warning is logged listing ignored video files.
- - If 0 eligible video files remain, the job transitions to `FAILED`.
+### Tier 1: Hard-Fail Security Threats (Immediate Abort to `FAILED`)
+- **Filesystem Traversal**: Rejects any file or directory path that resolves outside `/data/staging//` or contains relative escaping elements (`..`).
+- **Links & Special Nodes**: Rejects any symbolic links (`os.path.islink`), hard links (`st_nlink > 1`), FIFOs, sockets, or device nodes.
+- **Dangerous Extensions**: Rejects any payload containing executable binaries, scripts, or disk images:
+ `.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`.
+
+### Tier 2: Allowlist Extraction & Safe Discard
+- **Allowed Video**: `.mkv`, `.mp4`, `.avi`, `.webm`
+- **Allowed Subtitles**: `.srt`, `.vtt`, `.sub`, `.ass`
+- **Harmless Clutter**: Benign non-media clutter (`.nfo`, `.txt`, `.jpg`, `.sfv`) is safely ignored during extraction and cleaned up when the scratch directory is purged.
+- **Sample Discard**: Files containing `sample` in the filename or with size `< 100MB` are discarded.
+- **Primary Video Selection**: The single largest remaining video file is selected as the feature film. If 0 eligible video files remain, the job transitions to `FAILED`.
---
-## π¬ Metadata Authority & Verification Criteria
+## π¬ Metadata Authority & Two-Stage Lifecycle (`DEC-4`)
-- **Authority**: **The Movie Database (TMDB) API** using the `/find/{imdb_id}?external_source=imdb_id` endpoint.
-- **Verification Criteria**:
- - The canonical title and release year are fetched from TMDB.
- - A normalized token comparison is performed between the TMDB movie title/year and the torrent folder name / primary video filename.
- - If there is zero token overlap between the metadata title/year and the torrent name, the job transitions to `FAILED` (`"Torrent payload does not appear to match TMDB metadata"`).
+- **Authority**: **The Movie Database (TMDB) API** using `/find/{imdb_id}?external_source=imdb_id`.
+- **Stage 1 (Early Ingestion Resolution)**:
+ - Validates `imdb_id` format (`^tt\d{7,10}$`) and queries TMDB at submission/queueing time.
+ - Verifies the entity is a valid movie (rejects non-existent IDs and TV shows before downloading).
+ - Persists canonical `title` and `year` to `DownloadJob`, immediately populating live UI dashboards and SSE status frames.
+- **Stage 2 (Post-Download Token Verification)**:
+ - Once the torrent completes, the worker compares cached `(title, year)` tokens against the primary video filename and torrent folder name.
+ - Executed entirely offline from the SQLite database cache without outbound network dependencies.
+ - Zero token overlap aborts the job to `FAILED` (`"Torrent payload does not appear to match TMDB metadata"`).
---
-## π Storage Paths & Two-Stage Atomic Relocation
+## π Storage Architecture & Two-Stage Atomic Relocation (`DEC-5`)
-- **Canonical Staging Path**: `/data/staging//`
+- **Canonical Staging Path**: `/data/staging//` (fast local scratch storage).
- **Canonical Library Destination**:
```text
/media/movies/ () [imdbid-]/ ().
/media/movies/ () [imdbid-]/ ().en.srt
+ /media/movies/ () [imdbid-]/ ().en.forced.srt
+ /media/movies/ () [imdbid-]/ ().ja.ass
```
- **Two-Stage Atomic Relocation (Cross-Volume Safe)**:
- 1. *Stage 1 (Transfer)*: Validated files are copied from `/data/staging//` to a temporary directory on the library mount: `/media/movies/.staging_/` using `shutil.copy2`.
- 2. *Stage 2 (Atomic Swap)*: Once copying completes and file integrity is verified, `os.replace` atomically renames `/media/movies/.staging_/` to the final `/media/movies/ () [imdbid-]/` directory. This prevents Jellyfin/Plex from indexing partially-copied media.
-- **Cleanup**:
- - The scratch directory `/data/staging//` is purged immediately upon successful completion or terminal failure.
- - The torrent session is removed from Transmission daemon via RPC `remove_torrent(id, delete_data=True)` to prevent lingering memory/network leaks.
+ 1. *Transfer Stage*: Validated video and subtitles are copied from `/data/staging//` to temporary staging on the destination mount: `/media/movies/.staging_/` using `shutil.copy2`. Subtitles preserve native formats (`.srt`, `.vtt`, `.ass`) and parse language/forced tags with disambiguation indices (`.en.1.srt`) to prevent overwrites.
+ 2. *Pre-check & Atomic Swap*: The worker verifies that `/media/movies/ () [imdbid-]/` does not already exist. It then uses `os.replace` to atomically rename `.staging_/` to the final path. This prevents media servers (Jellyfin/Plex) from indexing partially-copied media files.
+- **Cleanup Invariant**:
+ - Scratch `/data/staging//` and any temporary `.staging_/` are purged immediately upon `COMPLETED` or `FAILED`.
+ - Transmission session is removed via RPC `remove_torrent(info_hash, delete_data=True)` to prevent memory or tracker leaks.
---
-## π Dual-Client Gateway & Ingestion Contract
+## β‘ Async Concurrency & Thread Offloading (`DEC-7`)
-The FastAPI BFF acts as a unified gateway serving two distinct frontends:
-
-1. **Hosted Web UI (`addmovie.roadtotech.me`)**:
- - Directly served by the FastAPI application as a single-origin web interface.
- - Embeds interactive movie search (with autocomplete, poster previews, and year badges) and a magnet link submission form.
- - Establishes a Server-Sent Events (SSE) connection (`/api/v1/movies/events`) to stream real-time pipeline status updates without polling.
-2. **Companion WebExtension (`magnetflix-extension`)**:
- - Injects magnet link interception on third-party torrent indexers.
- - Submits captured magnet URIs and selected IMDb IDs directly to the BFF.
-
-### Route & Payload Compatibility
-To support both the web UI and the browser extension without code divergence:
-* **Dual Route Bindings**: The BFF mounts both `POST /api/v1/downloads` (canonical REST) and `POST /download` (extension alias).
-* **Validation Aliases**: Pydantic schemas accept payload fields interchangeably:
- * Magnet URI: `magnet_uri` (canonical) or `magnet` (extension)
- * IMDb ID: `imdb_id` (canonical) or `imdbid` (extension)
-* **Identity Injection**: The BFF extracts authenticated user identity from the Traefik `Remote-User` header. In local testing or extension environments where SSO headers are absent, a configurable fallback (`local_user`) is applied.
+- **Non-Blocking Worker Event Loop**:
+ - The worker coordinates jobs using Python `asyncio` (`grpc.aio`, `aiosqlite`, `httpx`).
+ - All blocking operations (multi-gigabyte `shutil.copy2` transfers, synchronous `transmission-rpc` HTTP calls, and recursive filesystem scans) are dispatched to a dedicated bounded `ThreadPoolExecutor(max_workers=4)`.
+ - Database sessions are strictly short-lived; transactions are committed before long I/O operations and closed immediately.
+- **In-Memory Pub/Sub Event Streaming**:
+ - An internal `asyncio.Queue` pub/sub broker broadcasts progress and state change events to connected `StreamJobStatus` gRPC streams without polling SQLite in tight loops.
+ - Graceful shutdown handles `SIGINT`/`SIGTERM` via `server.stop(grace=5)`.
---
-## π Security Boundaries & Health Endpoints
+## π Pluggable Identity Adapter & Dual-Client BFF (`DEC-8`)
-### Authentication Trust Boundary
-- The FastAPI BFF trusts `Remote-User` and `Remote-Email` headers **strictly because it is reachable exclusively through the authenticated Traefik reverse proxy**. Direct ingress from outside the Docker network is prohibited.
-
-### Health & Readiness Probes
-- **BFF**: `GET /healthz` (Verifies FastAPI liveness + gRPC worker channel connectivity).
-- **Worker**: gRPC standard health checking protocol (`grpc.health.v1.Health`) + Transmission RPC ping.
+- **Pluggable Identity Adapter**:
+ - FastAPI middleware reads authenticated identity from upstream reverse proxies via configurable environment variables:
+ - `AUTH_ENABLED`: boolean (default: `true`; if `false`, defaults to `local_user` for offline/local development).
+ - `AUTH_HEADER_USER`: header name (default: `"Remote-User"`, configurable for Authentik, OAuth2-Proxy, etc.).
+ - `AUTH_HEADER_EMAIL`: header name (default: `"Remote-Email"`).
+- **Server-Side Movie Search Proxy**:
+ - BFF exposes `GET /api/v1/movies/search?q=...` proxying official TMDB movie search queries server-side using `TMDB_API_KEY`.
+ - Eliminates client-side scraping of undocumented APIs and prevents browser CORS issues.
+- **Dual Client Routes & Schemas**:
+ - Supports both the hosted Web UI dashboard and the companion browser extension (`magnetflix-extension`):
+ - `POST /api/v1/downloads` (canonical) and `POST /download` (extension alias).
+ - Pydantic validation aliases accept `magnet` / `magnet_uri` and `imdbid` / `imdb_id`.
+ - Real-time Server-Sent Events (SSE) route at `GET /api/v1/movies/events`.
diff --git a/docs/deployment.md b/docs/deployment.md
index 9264d66..0076cd6 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -1,16 +1,16 @@
-# π MagNetFlix β Deployment & Traefik Integration
+# π MagNetFlix β Deployment & Runtime Topology
-This guide details how **MagNetFlix** integrates into the home server stack at `/home/kiskaadee/Deployments/` with **Traefik Reverse Proxy** and **Authelia SSO**.
+This guide details the container deployment architecture, storage boundaries, and reverse proxy / SSO integration for **MagNetFlix**.
---
## π³ Docker Compose Architecture
-MagNetFlix runs as a multi-container stack attached to the shared `traefik_network`:
+MagNetFlix runs as an isolated multi-container stack connected to an internal service bridge, with public ingress routed through a reverse proxy (e.g. Traefik, Nginx, or Caddy) supporting forward-auth or OIDC proxy headers.
```yaml
services:
- # 1. FastAPI Web Gateway & Form UI
+ # 1. FastAPI Web Gateway & BFF Dashboard
bff:
build:
context: .
@@ -19,6 +19,10 @@ services:
environment:
- GRPC_WORKER_HOST=worker:50051
- APP_ENV=production
+ - AUTH_ENABLED=true
+ - AUTH_HEADER_USER=Remote-User
+ - AUTH_HEADER_EMAIL=Remote-Email
+ - TMDB_API_KEY=${TMDB_API_KEY}
networks:
- traefik_network
- magnetflix_internal
@@ -39,7 +43,7 @@ services:
environment:
- TRANSMISSION_HOST=transmission
- TRANSMISSION_PORT=9091
- - DATABASE_URL=sqlite:////data/magnetflix.sqlite3
+ - DATABASE_URL=sqlite+aiosqlite:////data/magnetflix.sqlite3
- STAGING_DIR=/data/staging
- MEDIA_DIR=/media/movies
- TMDB_API_KEY=${TMDB_API_KEY}
@@ -49,7 +53,7 @@ services:
networks:
- magnetflix_internal
- # 3. Transmission Torrent Daemon
+ # 3. Isolated Transmission Torrent Daemon
transmission:
image: lscr.io/linuxserver/transmission:latest
restart: unless-stopped
@@ -72,23 +76,34 @@ networks:
---
-## π Authelia SSO Integration
+## π Pluggable SSO / Reverse Proxy Identity Adapter (`DEC-8`)
-When a user visits `addmovie.roadtotech.me`:
-1. Traefik triggers the `authelia@docker` forward-auth middleware.
-2. If unauthenticated, Authelia redirects the user to the login portal.
-3. Upon authentication, Authelia injects headers into the forwarded request:
- - `Remote-User`: Username of the logged-in user.
- - `Remote-Email`: Email address.
- - `Remote-Groups`: Group memberships (e.g. `admins`, `family`).
-4. FastAPI extracts `request.headers.get("Remote-User")` and passes it to the gRPC worker for audit logging.
+MagNetFlix does not couple its internal application logic to any specific identity provider. Instead, the FastAPI BFF operates an **Identity Adapter** extracting authenticated identity from upstream gateway headers:
+
+| Environment Variable | Default | Purpose |
+| :--- | :--- | :--- |
+| `AUTH_ENABLED` | `true` | If `false`, identity falls back to `local_user` for offline testing or standalone development. |
+| `AUTH_HEADER_USER` | `Remote-User` | Name of the incoming HTTP header containing the verified username (e.g. Authelia, Authentik `X-authentik-username`, or OAuth2-Proxy `X-Forwarded-User`). |
+| `AUTH_HEADER_EMAIL` | `Remote-Email` | Name of the HTTP header containing the user's verified email address. |
+
+### Upstream Authentication Workflow
+1. Client sends request to `addmovie.roadtotech.me`.
+2. Reverse proxy executes forward-auth against the identity provider (Authelia, Authentik, etc.).
+3. If valid, the proxy injects the configured identity header (`Remote-User`) and forwards the request to the BFF on `traefik_network`.
+4. BFF extracts the verified identity and forwards it across the private gRPC boundary to the Worker for persistent audit logging.
---
-## π Storage Volumes Configuration
+## π Storage Volume Invariants
-| Mount Path | Type | Purpose |
-| :--- | :--- | :--- |
-| `/data/magnetflix.sqlite3` | Persistent Volume | SQLite DB with WAL mode for jobs and audit log. |
-| `/data/staging` | Fast Scratch Disk | Staging folder where Transmission downloads files. |
-| `/media/movies` | Media Storage | Final target destination mounted to Jellyfin/Plex. |
+| Container Mount | Host Target | Filesystem Type | Purpose |
+| :--- | :--- | :--- | :--- |
+| `/data/magnetflix.sqlite3` | Local persistent disk (`./data`) | Local SQLite (WAL Mode) | Job audit logs and pipeline state machine records. **Never place on NFS/SMB network shares.** |
+| `/data/staging` | Fast scratch disk (`./data/staging`) | Fast local storage | Transmission scratch directory where torrent pieces land. Shared strictly between `worker` and `transmission`. |
+| `/media/movies` | Media storage pool (`/mnt/storage/...`) | Media pool (ZFS/ext4) | Final Jellyfin/Plex target directory and temporary cross-volume staging (`.staging_`). |
+
+### Cross-Volume Publication & Atomic Swap (`DEC-5`)
+Because `/data/staging` and `/media/movies` reside on distinct filesystems, cross-volume transfers cannot use filesystem hard-links (`EXDEV` error):
+1. Files are copied across volumes to `/media/movies/.staging_/` using `shutil.copy2`.
+2. Once transfer and file sizes are verified, `os.replace` executes an instant atomic directory rename on the **same target filesystem** from `.staging_/` to `/media/movies/ () [imdbid-]/`.
+3. Jellyfin and Plex library watchers will never detect, lock, or index partially transferred media files.
diff --git a/docs/history/phase-a-current-state-audit.md b/docs/history/phase-a-current-state-audit.md
new file mode 100644
index 0000000..00c16e7
--- /dev/null
+++ b/docs/history/phase-a-current-state-audit.md
@@ -0,0 +1,61 @@
+# π Phase A Current-State Architectural Audit & Review Ledger
+
+This historical record captures the findings, gap analysis, and architectural reconciliation conducted during the Phase A and Phase B review of **MagNetFlix** on 2026-10-30.
+
+---
+
+## 1. Initial State Inventory
+
+- **Toolchain**: `uv` workspace with `services/worker` and `services/bff`, packaged via `uv_build`. Nix hermetic devShell in `flake.nix`.
+- **Database**: SQLite WAL engine in `services/worker/src/worker/db/engine.py` with strict pragmas (`journal_mode=WAL; foreign_keys=ON; synchronous=NORMAL; busy_timeout=5000`). Initial Alembic migration `234da461ab5b_create_download_jobs_table.py` created the `download_jobs` table.
+- **Protobuf**: Contract defined in `proto/magnetflix/v1/pipeline.proto`.
+- **Tests**: 5 unit tests in `tests/test_db.py` verifying SQLite pragmas, CRUD operations, state transitions, and idempotency queries.
+
+---
+
+## 2. Identified Discrepancies & Defect Register
+
+During read-only inspection of the repository and its runtime behavior, 8 concrete architectural gaps were validated:
+
+1. **`GAP-1` (Protobuf Package Layout & Broken Imports)**:
+ - Generated stubs in `services/worker/src/worker/magnetflix/v1/pipeline_pb2_grpc.py` emitted `from magnetflix.v1 import pipeline_pb2`.
+ - Importing failed with `ModuleNotFoundError: No module named 'magnetflix'`.
+ - Masked because `pyproject.toml` excluded `services/**/magnetflix/` from `pyright` and `ruff`.
+ - Generated stubs were gitignored, and Dockerfiles omitted `buf generate` and Alembic migration scripts.
+2. **`GAP-2` (Active Job Concurrency & Idempotency)**:
+ - `imdb_id` had only a non-unique index; application-level check-then-insert was vulnerable to TOCTOU races under concurrent submissions.
+ - `DownloadJob` had no `info_hash` column to track BitTorrent hashes.
+3. **`GAP-3` (Sanitizer Policy Contradiction)**:
+ - Documentation contradicted whether to purge non-media clutter (`.nfo`, `.txt`, `.jpg`) or fail the entire job. Strict rejection failed ~95% of real torrents, while pure whitelisting allowed malicious symlinks and traversal payloads.
+4. **`GAP-4` (Subtitle Selection & Relocation Collisions)**:
+ - Sanitizer accepted `.srt`, `.vtt`, `.sub`, `.ass`, but relocator spec forced ` ().en.srt`, corrupting non-SRT formats and overwriting multi-track subtitles.
+5. **`GAP-5` (Metadata Resolution Timing)**:
+ - Querying TMDB only after download left UI live dashboard titles blank during downloads and wasted gigabytes on invalid IDs.
+6. **`GAP-6` (Crash Recovery & Daemon State)**:
+ - Marking DB rows `FAILED` on restart left Transmission actively downloading torrents and abandoned staging disks.
+7. **`GAP-7` (Async Concurrency & Blocking Disk I/O)**:
+ - Synchronous `shutil.copy2` on 30GB files and synchronous `transmission-rpc` blocked Python's single async event loop, freezing gRPC and SSE streams.
+8. **`GAP-8` (SSO Decoupling & Movie Search)**:
+ - Hardcoded Authelia headers tightly coupled the app to specific homelab infrastructure. Prototype extension queried undocumented IMDb APIs directly from the browser.
+
+---
+
+## 3. Accepted Architectural Decisions Summary
+
+| Decision ID | Area | Accepted Resolution |
+| :--- | :--- | :--- |
+| **`DEC-1`** | Protobuf Packaging | Dedicated `services/contracts` workspace package (`magnetflix` module); commit stubs and docs to Git; update Dockerfiles. |
+| **`DEC-2`** | Database Hardening | Add SQLite partial unique index `uq_download_jobs_active_imdb_id` (`WHERE state NOT IN ('COMPLETED', 'FAILED')`) and indexed `info_hash` column. |
+| **`DEC-3`** | Sanitizer Boundary | Two-tier sanitizer: hard-fail on symlinks, hard links, traversal, special files, executables/archives; ignore benign clutter; extract allowlisted media; select largest primary video. |
+| **`DEC-4`** | TMDB Metadata | Two-stage lifecycle: resolve TMDB `(title, year)` early on ingestion to validate ID and populate UI; verify token overlap post-download offline from SQLite cache. |
+| **`DEC-5`** | Subtitle Relocation | Multi-track format preservation: retain `.srt`/`.vtt`/`.ass` extensions, parse language/forced tags with disambiguation indices (`.en.1.srt`), safe two-stage atomic directory swap. |
+| **`DEC-6`** | Crash Recovery | Active startup reconciliation sweep: auto-fail orphaned DB jobs, purge staging directories, remove torrents from Transmission via `info_hash`; enforce 15-min stall timeout. |
+| **`DEC-7`** | Async Concurrency | Bounded `ThreadPoolExecutor(max_workers=4)` for blocking disk I/O and RPCs; short-lived DB sessions; in-memory `asyncio.Queue` pub/sub broadcaster for SSE. |
+| **`DEC-8`** | Pluggable Auth & Search | Configurable SSO identity adapter middleware (`AUTH_HEADER_USER`); server-side TMDB search proxy (`GET /api/v1/movies/search`); dual route bindings (`POST /api/v1/downloads` & `POST /download`). |
+
+---
+
+## 4. Portfolio Engineering Assessment
+
+- **Key Competencies**: Clean separation of concerns (BFF + gRPC Worker + Transmission daemon); defense-in-depth security boundary; cross-volume filesystem atomicity (`EXDEV` safe); SQLite WAL concurrency; non-blocking async architecture.
+- **Scope Discipline**: Explicitly designed as a robust single-node self-hosted pipeline; BitTorrent daemon boundary respected; no speculative microservice bloat.
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 67bf1c6..f6d62e2 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -1,73 +1,130 @@
-# πΊοΈ MagNetFlix β Development Roadmap
+# πΊοΈ MagNetFlix β Reconciled Implementation Roadmap
-This roadmap breaks down the construction of **MagNetFlix** into clear, incremental milestones with testing embedded in each stage.
+This roadmap breaks down the completion of **MagNetFlix** into clear, dependency-ordered milestones. Each milestone includes explicit prerequisites, work items, and verifiable exit criteria.
---
-## π― Milestones Overview
+## π― Milestones Dependency Graph
```mermaid
-gantt
- title MagNetFlix Implementation Phases
- dateFormat YYYY-MM-DD
- section Phase 1
- Workspace & Protobuf Contract :p1, 2026-09-01, 2d
- section Phase 2
- Worker Engine & Pipeline Modules :p2, after p1, 4d
- Worker Unit & Component Tests :p2_test, after p2, 2d
- section Phase 3
- FastAPI BFF & Web UI (SSE) :p3, after p2_test, 3d
- BFF & gRPC Integration Tests :p3_test, after p3, 2d
- section Phase 4
- Traefik SSO & Docker Compose :p4, after p3_test, 2d
- End-to-End Verification :p4_test, after p4, 1d
+flowchart TD
+ M1["Milestone 1: Contracts, Toolchain & DB Hardening\n(GAP-1, GAP-2, TD-1, TD-2, TD-3)"]
+ M2["Milestone 2: Pipeline Domain Engine & Filesystem Safety\n(GAP-3, GAP-4, GAP-5)"]
+ M3["Milestone 3: Transmission Integration & Worker Coordinator\n(GAP-6, GAP-7)"]
+ M4["Milestone 4: FastAPI BFF Gateway, SSE & Web UI\n(GAP-8)"]
+ M5["Milestone 5: Multi-Container Stack & Deployment Verification\n(Traefik, SSO, Compose)"]
+
+ M1 --> M2
+ M2 --> M3
+ M3 --> M4
+ M4 --> M5
```
---
-## π Phase 1: Repository Foundation & Protobuf Contracts
-- [x] Initialize `uv` workspace with `services/bff` and `services/worker`.
-- [x] Configure `buf.yaml` and `buf.gen.yaml` with Python & gRPC stubs generation.
-- [x] Define `proto/magnetflix/v1/pipeline.proto` with pagination, `updated_at`, and streaming snapshot semantics.
-- [x] Create developer guidelines (`AGENTS.md` and `CLAUDE.md`).
+## π Milestone 1: Contracts, Toolchain & Database Hardening
+- **Objective:** Fix broken gRPC stub imports, ensure 100% reproducible offline container builds, eliminate the active-job deduplication race, and establish database schema invariants.
+- **Dependencies:** None.
+- **Requirements Satisfied:** `REQ-1`, `REQ-2`.
+- **Work Items:**
+ - [ ] `M1.1`: Create `services/contracts` workspace package (`pyproject.toml`, `module-name = "magnetflix"`).
+ - [ ] `M1.2`: Reconfigure `buf.gen.yaml` to output stubs into `services/contracts/src`; generate and track stubs + `docs/api_spec.md` in Git (`DEC-1`).
+ - [ ] `M1.3`: Update dependencies in `services/worker` and `services/bff` to include `magnetflix-contracts = { workspace = true }`.
+ - [ ] `M1.4`: Update `pyproject.toml` to include `tests/` in `pyright`, remove exclusions that masked broken imports, and add `test:` target to `Makefile`.
+ - [ ] `M1.5`: Update `services/worker/Dockerfile` and `services/bff/Dockerfile` to copy `services/contracts`, and include `alembic.ini` and `alembic/` in the Worker image.
+ - [ ] `M1.6`: Create Alembic migration `002_add_info_hash_and_partial_unique_index.py` adding `info_hash` column and `uq_download_jobs_active_imdb_id` index (`DEC-2`).
+ - [ ] `M1.7`: Update `DownloadJob` model and add unit tests in `tests/test_db.py` verifying duplicate active insertion rejection.
+- **Verifiable Exit Criteria:**
+ - `uv run python -c "from magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpc"` succeeds with 0 errors.
+ - `uv run ruff check .` and `uv run pyright` pass cleanly across the entire workspace including contracts and tests.
+ - `uv run pytest tests/test_db.py` passes all tests including partial unique index verification.
---
-## π Phase 2: Pipeline Worker & Security Engine
-- [x] Set up SQLite with WAL mode via SQLAlchemy 2.0 and Alembic migrations.
-- [ ] Implement Transmission daemon RPC client wrapper.
-- [ ] Implement isolated scratch staging (`/data/staging/`).
-- [ ] Build **Media Sanitizer & Allowlist**:
- - Symlink & path traversal blocker.
- - Video & subtitle extension whitelist.
- - Sample file discard (<100MB / "sample") & largest video file selector.
-- [ ] Build **TMDB Metadata Verifier**: Fetch title/year from TMDB via IMDb ID and perform token overlap verification.
-- [ ] Build **Library Relocator**: Move verified video and `.srt` files into final Jellyfin/Plex structure.
-- [ ] **Phase 2 Tests**:
- - `tests/test_sanitizer.py`: Unit tests for allowlist, traversal, and largest video file selection.
- - `tests/test_metadata.py`: Unit tests for TMDB client and token matching logic.
- - `tests/test_state_machine.py`: Unit tests for linear transitions, failure transitions, and restart recovery.
- - `tests/test_transmission.py`: Mocked Transmission RPC client tests.
+## π Milestone 2: Pipeline Domain Engine & Filesystem Safety
+- **Objective:** Implement core business logic and security boundary modules: untrusted payload sanitization, metadata verification, and cross-volume publication.
+- **Dependencies:** Milestone 1.
+- **Requirements Satisfied:** `REQ-3`, `REQ-4`, `REQ-5`.
+- **Work Items:**
+ - [ ] `M2.1`: Implement Media Sanitizer (`services/worker/src/worker/sanitizer.py`) adhering to `DEC-3`:
+ - Hard-fail on symlinks, hard links, `..` traversal, special files, and dangerous extensions (`.exe`, `.bat`, `.sh`, `.iso`, `.zip`).
+ - Safely ignore benign clutter (`.nfo`, `.txt`, `.jpg`, `.sfv`).
+ - Discard samples (`< 100MB` or containing `sample`); select largest primary video and allowlisted subtitles (`.srt`, `.vtt`, `.ass`).
+ - [ ] `M2.2`: Write unit tests in `tests/test_sanitizer.py` verifying all security, allowlist, and sample discard rules.
+ - [ ] `M2.3`: Implement TMDB Client & Token Verifier (`services/worker/src/worker/metadata.py`) adhering to `DEC-4`:
+ - Early resolution via `GET /find/{imdb_id}?external_source=imdb_id` using `httpx.AsyncClient`.
+ - Validates IMDb ID format, validates movie entity type, extracts `(title, year)`.
+ - Post-download normalized token comparison between cached `(title, year)` and primary video filename.
+ - [ ] `M2.4`: Write unit tests in `tests/test_metadata.py` with mocked TMDB HTTP responses (match, 404, non-movie, mismatch).
+ - [ ] `M2.5`: Implement Library Relocator (`services/worker/src/worker/relocator.py`) adhering to `DEC-5`:
+ - Multi-track subtitle format preservation (`.srt`, `.vtt`, `.ass`) with language and disambiguation tags.
+ - Two-stage copy-and-swap: copy to `/media/movies/.staging_/`, pre-check destination directory existence, and atomically swap via `os.replace`.
+ - [ ] `M2.6`: Write unit tests in `tests/test_relocator.py` asserting destination file layout and atomic swap error handling.
+- **Verifiable Exit Criteria:**
+ - `uv run pytest tests/test_sanitizer.py tests/test_metadata.py tests/test_relocator.py` passes 100%.
+ - Zero filesystem breakout vulnerabilities possible under synthetic traversal fixtures.
---
-## π Phase 3: BFF Gateway & Live Dashboard
-- [ ] Build FastAPI application with Pydantic v2 schemas.
-- [ ] Add Authelia SSO header middleware (`Remote-User`, `Remote-Email`).
-- [ ] Implement gRPC client wrapper in BFF.
-- [ ] Build clean HTML form (PicoCSS / Tailwind) for adding movies.
-- [ ] Implement Server-Sent Events (SSE) route `/api/v1/movies/events` connected to gRPC streaming updates.
-- [ ] Build live progress dashboard showing active and completed downloads.
-- [ ] **Phase 3 Tests**:
- - `tests/test_bff_routes.py`: FastAPI route and header extraction tests.
- - `tests/test_grpc_integration.py`: End-to-end gRPC communication between BFF and Worker.
- - `tests/test_sse_stream.py`: SSE stream snapshot and event emission tests.
+## π Milestone 3: Transmission Integration & Worker Coordinator
+- **Objective:** Wrap Transmission RPC, coordinate the pipeline finite state machine, implement startup crash recovery, and expose the gRPC service.
+- **Dependencies:** Milestone 2.
+- **Requirements Satisfied:** `REQ-6`, `REQ-7`, `REQ-8`.
+- **Work Items:**
+ - [ ] `M3.1`: Implement Transmission RPC Client Wrapper (`services/worker/src/worker/transmission.py`) adhering to `DEC-6`:
+ - `add_torrent(magnet_uri, download_dir=/data/staging/)`.
+ - `get_progress(info_hash)` returning progress percentage and download speed.
+ - `remove_torrent(info_hash, delete_data=True)` for terminal cleanup.
+ - [ ] `M3.2`: Write unit tests in `tests/test_transmission.py` with mocked RPC client.
+ - [ ] `M3.3`: Implement Pipeline Coordinator & State Machine (`services/worker/src/worker/pipeline.py`) adhering to `DEC-6` & `DEC-7`:
+ - State progression: `QUEUED` $\rightarrow$ `DOWNLOADING` $\rightarrow$ `SCANNING` $\rightarrow$ `VERIFYING_METADATA` $\rightarrow$ `ORGANIZING` $\rightarrow$ `COMPLETED`.
+ - 15-minute stalled torrent timeout.
+ - Startup crash recovery: query orphaned jobs, fail DB rows, purge staging directories, remove torrents from Transmission.
+ - Dedicated bounded `ThreadPoolExecutor(max_workers=4)` for offloading disk I/O and synchronous Transmission calls.
+ - In-memory `asyncio.Queue` broadcaster for real-time status streaming.
+ - [ ] `M3.4`: Implement gRPC Server Servicer (`services/worker/src/worker/service.py` & `main.py`) adhering to `pipeline.proto`:
+ - Implements `SubmitDownload`, `GetJob`, `ListJobs`, and `StreamJobStatus`.
+ - Maps application errors to proper gRPC status codes (`ALREADY_EXISTS`, `NOT_FOUND`, `INVALID_ARGUMENT`).
+ - [ ] `M3.5`: Write integration tests in `tests/test_pipeline.py` and `tests/test_grpc_service.py`.
+- **Verifiable Exit Criteria:**
+ - `uv run pytest tests/test_pipeline.py tests/test_grpc_service.py` passes 100%.
+ - Worker process cleanly starts, handles startup reconciliation, and shuts down gracefully with `SIGTERM`.
---
-## π Phase 4: Containerization & Traefik Integration
-- [ ] Create multi-stage `Dockerfile` for `bff` and `worker`.
-- [ ] Create production-ready `docker-compose.yml` including Transmission daemon and shared volumes.
-- [ ] Configure Traefik labels for `addmovie.roadtotech.me` with Authelia middleware.
-- [ ] Configure health and readiness probes (`/healthz`, gRPC health service).
-- [ ] **Phase 4 Tests**: Full end-to-end dry-run with a public domain torrent.
+## π Milestone 4: FastAPI BFF Gateway, SSE & Web UI
+- **Objective:** Implement the user-facing web gateway, pluggable SSO identity adapter, server-side TMDB search proxy, real-time SSE stream, and single-origin UI.
+- **Dependencies:** Milestone 3.
+- **Requirements Satisfied:** `REQ-9`, `REQ-10`.
+- **Work Items:**
+ - [ ] `M4.1`: Implement Pluggable Identity Adapter Middleware in FastAPI (`DEC-8`):
+ - Configurable via `AUTH_ENABLED`, `AUTH_HEADER_USER`, `AUTH_HEADER_EMAIL`, with safe dev fallback (`local_user`).
+ - [ ] `M4.2`: Implement BFF gRPC Client Wrapper (`services/bff/src/bff/grpc_client.py`):
+ - Channels calls to Worker (`SubmitDownload`, `GetJob`, `ListJobs`, `StreamJobStatus`).
+ - [ ] `M4.3`: Implement REST Endpoints & Schemas (`services/bff/src/bff/main.py`):
+ - Dual route bindings: `POST /api/v1/downloads` and `POST /download` with Pydantic aliases (`magnet`/`magnet_uri`, `imdbid`/`imdb_id`).
+ - Server-side TMDB movie search proxy: `GET /api/v1/movies/search?q=...`.
+ - Server-Sent Events stream: `GET /api/v1/movies/events`.
+ - [ ] `M4.4`: Embed Hosted Web UI (`services/bff/src/bff/templates/` & `static/`):
+ - Clean, responsive dashboard (adapted from extension prototype `app.html`/`app.css`).
+ - Movie search autocomplete with poster previews, magnet input, and live progress bars.
+ - [ ] `M4.5`: Write API tests in `tests/test_bff_routes.py` covering auth extraction, dual routes, search proxy, and SSE streams.
+- **Verifiable Exit Criteria:**
+ - `uv run pytest tests/test_bff_routes.py` passes 100%.
+ - BFF connects to gRPC worker, serves Web UI, and streams live download progress without browser CORS errors.
+
+---
+
+## π Milestone 5: Multi-Container Stack & Deployment Verification
+- **Objective:** Deliver production-ready containerization, Docker Compose stack, Traefik integration, and end-to-end slice verification.
+- **Dependencies:** Milestone 4.
+- **Requirements Satisfied:** `REQ-11`.
+- **Work Items:**
+ - [ ] `M5.1`: Finalize `services/worker/Dockerfile` and `services/bff/Dockerfile`.
+ - [ ] `M5.2`: Author canonical `docker-compose.yml` defining `bff`, `worker`, and `transmission` services, volume mounts (`./data`, `/media/movies`), and internal/external networks.
+ - [ ] `M5.3`: Configure health probes: BFF `GET /healthz`, Worker gRPC standard health check.
+ - [ ] `M5.4`: Execute end-to-end integration test with a small public domain/legal torrent:
+ - Verify full lifecycle: Form submission $\rightarrow$ Transmission download $\rightarrow$ Sanitizer scan $\rightarrow$ Metadata token check $\rightarrow$ Two-stage atomic relocation into Jellyfin/Plex format $\rightarrow$ Live SSE completion update.
+- **Verifiable Exit Criteria:**
+ - `docker compose build` succeeds with zero errors from a fresh checkout.
+ - Full end-to-end vertical slice runs to completion with media appearing in `/media/movies/ () [imdbid-]/`.
diff --git a/todo.txt b/todo.txt
index 3ca0cfe..d21419e 100644
--- a/todo.txt
+++ b/todo.txt
@@ -1,20 +1,38 @@
-x 2026-10-13 (A) Create SQLAlchemy async engine with SQLite WAL mode pragmas in services/worker/src/worker/db/engine.py +db @worker
-x 2026-10-13 (A) Define DownloadJob ORM model in services/worker/src/worker/db/models.py (id, imdb_id, title, year, magnet_uri, requested_by, status, progress_pct, download_rate_bytes, error_message, created_at, updated_at, completed_at) +db @worker
-x 2026-10-13 (A) Initialize Alembic in services/worker/ and create initial migration for download_jobs table +db @worker
-x 2026-10-13 (A) Write unit tests for DB connection, WAL pragma verification, and CRUD operations in tests/test_db.py +test @worker
-(B) Implement symlink & path-traversal blocker in services/worker/src/worker/sanitizer.py +sanitizer @worker
-(B) Implement file allowlist filtering (video: .mkv, .mp4, .avi, .webm; subtitles: .srt, .vtt, .sub, .ass) +sanitizer @worker
-(B) Implement sample discard (<100MB / 'sample' keyword) and largest primary video selector in sanitizer.py +sanitizer @worker
-(B) Write comprehensive unit tests in tests/test_sanitizer.py covering allowlist, symlinks, sample filtering, and largest video selection +test @worker
-(B) Implement async TMDB client querying /find/{imdb_id}?external_source=imdb_id in services/worker/src/worker/metadata.py +metadata @worker
-(B) Implement normalized token overlap verification between TMDB title/year and torrent/file names in metadata.py +metadata @worker
-(B) Write unit tests with mocked TMDB responses in tests/test_metadata.py verifying successful match and mismatch rejection +test @worker
-(C) Implement Transmission client wrapper in services/worker/src/worker/transmission.py (add_torrent to /data/staging/, poll progress, remove_torrent) +transmission @worker
+# Milestone 1: Contracts, Toolchain & Database Hardening (Prerequisites & Blockers)
+(A) Create services/contracts workspace package with pyproject.toml (module-name = 'magnetflix') +contracts @workspace
+(A) Reconfigure buf.gen.yaml to output stubs into services/contracts/src, generate stubs + docs/api_spec.md, and track in Git +proto @contracts
+(A) Update services/worker and services/bff to depend on magnetflix-contracts via workspace dependency +deps @workspace
+(A) Update pyproject.toml to include tests/ in pyright, remove exclusions masking broken imports, and add test rule to Makefile +ci @workspace
+(A) Update services/worker/Dockerfile and services/bff/Dockerfile to copy services/contracts, and copy alembic/ into worker image +docker @deploy
+(A) Create Alembic migration 002_add_info_hash_and_partial_unique_index.py adding info_hash column and uq_download_jobs_active_imdb_id index +db @worker
+(A) Update DownloadJob ORM model and write unit tests in tests/test_db.py verifying duplicate active insertion rejection +test @worker
+
+# Milestone 2: Pipeline Domain Engine & Filesystem Safety
+(B) Implement Two-Tier Media Sanitizer in services/worker/src/worker/sanitizer.py (hard-fail on symlinks/traversal/executables, ignore .txt/.nfo, sample discard, largest video selector) +sanitizer @worker
+(B) Write comprehensive unit tests in tests/test_sanitizer.py covering allowlist, traversal, sample filtering, and largest video selection +test @worker
+(B) Implement TMDB Client & Token Verifier in services/worker/src/worker/metadata.py (early ingestion resolution via /find/{imdb_id} and post-download token overlap check) +metadata @worker
+(B) Write unit tests with mocked TMDB responses in tests/test_metadata.py verifying match, 404, non-movie rejection, and token overlap +test @worker
+(B) Implement Multi-Track Library Relocator in services/worker/src/worker/relocator.py (format preservation for .srt/.vtt/.ass, language/disambiguation tagging, two-stage atomic directory swap) +relocator @worker
+(B) Write unit tests in tests/test_relocator.py testing destination directory formatting, subtitle moving, and atomic swap cleanup +test @worker
+
+# Milestone 3: Transmission Integration & Worker Coordinator
+(C) Implement Transmission client wrapper in services/worker/src/worker/transmission.py (add_torrent to /data/staging/, poll progress, remove_torrent with delete_data) +transmission @worker
(C) Write unit tests with mocked transmission-rpc client in tests/test_transmission.py +test @worker
-(C) Implement directory creator and atomic file mover in services/worker/src/worker/relocator.py (/media/movies/ () [imdbid-]/) +relocator @worker
-(C) Implement subtitle renaming and staging cleanup in relocator.py +relocator @worker
-(C) Write unit tests in tests/test_relocator.py testing destination directory formatting, subtitle moving, and scratch cleanup +test @worker
-(D) Implement pipeline state machine coordinator (QUEUED -> DOWNLOADING -> SCANNING -> VERIFYING_METADATA -> ORGANIZING -> COMPLETED/FAILED) in services/worker/src/worker/pipeline.py +pipeline @worker
-(D) Implement startup crash recovery to auto-fail orphaned non-terminal jobs on worker start in pipeline.py +pipeline @worker
-(D) Implement gRPC PipelineServiceServicer in services/worker/src/worker/service.py (SubmitDownload, GetJob, StreamJobStatus, ListJobs) +grpc @worker
-(D) Write integration tests in tests/test_grpc_service.py verifying duplicate rejection, job submission, status querying, and pagination +test @worker
+(C) Implement pipeline state machine coordinator in services/worker/src/worker/pipeline.py (linear transitions, 15-min stall timeout, bounded ThreadPoolExecutor offloading, in-memory pub/sub queues) +pipeline @worker
+(C) Implement startup active reconciliation sweep in pipeline.py (auto-fail orphaned jobs, remove Transmission torrents, purge staging disks) +pipeline @worker
+(C) Implement gRPC PipelineServiceServicer in services/worker/src/worker/service.py and entrypoint worker/main.py (SubmitDownload, GetJob, StreamJobStatus, ListJobs) +grpc @worker
+(C) Write integration tests in tests/test_grpc_service.py verifying duplicate rejection, job submission, status querying, and pagination +test @worker
+
+# Milestone 4: FastAPI BFF Gateway, SSE & Web UI
+(D) Implement Pluggable Identity Adapter Middleware in FastAPI BFF (env-driven header extraction with local_user dev fallback) +auth @bff
+(D) Implement BFF gRPC client wrapper in services/bff/src/bff/grpc_client.py connecting to Worker service +grpc @bff
+(D) Implement REST endpoints in services/bff/src/bff/main.py (dual routes POST /api/v1/downloads and POST /download with Pydantic aliases, GET /api/v1/movies/search TMDB proxy) +api @bff
+(D) Implement Server-Sent Events stream GET /api/v1/movies/events connected to gRPC StreamJobStatus +sse @bff
+(D) Embed single-origin HTML Web UI dashboard in services/bff/src/bff/templates/ and static/ with movie search autocomplete, poster previews, and live progress bars +ui @bff
+(D) Write API tests in tests/test_bff_routes.py covering auth extraction, dual routes, search proxy, and SSE streams +test @bff
+
+# Milestone 5: Multi-Container Stack & Deployment Verification
+(E) Finalize services/worker/Dockerfile and services/bff/Dockerfile multi-stage production builds +docker @deploy
+(E) Author canonical production-ready docker-compose.yml including bff, worker, transmission, volume mounts, and network bridges +compose @deploy
+(E) Configure Traefik routing labels, health probes (/healthz and gRPC health), and verify container communication +traefik @deploy
+(E) Execute end-to-end integration test with public domain torrent verifying full acquisition, organization, and SSE reporting lifecycle +e2e @test