# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Build & Test Commands

```bash
cargo build --release    # Build release binary
cargo test               # Run all tests
cargo test <test_name>   # Run specific test
cargo doc --open         # Generate and view documentation
cargo clippy             # Lint checks
cargo fmt --check        # Format checks
```

Requires Rust 1.75+ for async trait support.

## Architecture Overview

gosh-dl is a native Rust download engine library supporting HTTP/HTTPS and BitTorrent protocols. It's designed as an embeddable library (not a CLI tool).

### Core Components

**DownloadEngine** (`src/engine.rs`) - Central coordinator that:
- Maps `DownloadId` (UUID) to download state
- Spawns tasks for HTTP or BitTorrent downloads (never both)
- Manages lifecycle: add, pause, resume, cancel
- Provides event subscription via `broadcast::Receiver<DownloadEvent>`
- Background tasks for persistence (30s interval) and scheduler updates

**Priority Queue** (`src/priority_queue.rs`) - Limits concurrent downloads using:
- Binary heap with 4 priority levels (Low, Normal, High, Critical)
- FIFO within same priority
- Tokio semaphore enforces `max_concurrent_downloads`

**Storage Layer** (`src/storage/`) - Trait-based abstraction:
- `MemoryStorage` for tests
- `SqliteStorage` with WAL mode for crash recovery
- Downloads in `Downloading` state restored as `Paused` on crash

### Data Flow

```
User Request (add_http/add_torrent/add_magnet)
    → DownloadEngine validates & persists
    → Priority Queue (enforces max_concurrent_downloads)
    → HTTP path OR Torrent path
    → Storage Layer (SQLite with WAL)
    → Event Stream (broadcast channel)
```

### HTTP Module (`src/http/`)

- Segmented downloads with up to 16 parallel connections
- Resume validation via ETag/Last-Modified
- Token bucket rate limiting via `governor` crate in `ConnectionPool`
- Mirror failover with failure tracking
- Checksum verification (MD5, SHA256)

### BitTorrent Module (`src/torrent/`)

- Full peer wire protocol implementation
- State machine: Checking → Metadata → Downloading → Seeding
- Piece manager with rarest-first selection (sequential mode available)
- Peer discovery: Trackers (HTTP/UDP), DHT (via `mainline` crate), PEX, LPD
- Message Stream Encryption (MSE/PE) for privacy
- WebSeeds as HTTP fallback
- uTP with LEDBAT congestion control

### Key Design Patterns

- `Arc<RwLock<>>` with `parking_lot` for shared mutable state
- `CancellationToken` from `tokio_util` for graceful shutdown
- Broadcast channels for one-to-many event distribution
- Typed error hierarchy in `src/error.rs` with retryability flag

### Module Dependencies

- `engine.rs` spawns tasks but HTTP and Torrent modules never interact directly
- Priority queue gates entry to downloaders via async semaphore
- Scheduler runs background task that updates global bandwidth limits
- Storage runs background persistence task independently

## Key Files for Understanding

- `src/lib.rs` - Public API re-exports
- `src/engine.rs` - Main coordinator (start here)
- `src/types.rs` - Core types: `DownloadId`, `DownloadState`, `DownloadProgress`
- `src/error.rs` - Error hierarchy with `NetworkErrorKind`, `StorageErrorKind`, `ProtocolErrorKind`
- `technical_spec.md` - Comprehensive architecture documentation

## Testing

Integration tests in `tests/`:
- `integration_tests.rs` - Full download workflow tests
- `test_helpers.rs` - Torrent file builders, bencode utilities
- `mock_peer.rs` - BitTorrent peer protocol simulation

Tests use `wiremock` for HTTP mocking and `tempfile` for filesystem isolation.


## Git Commits & Documentation Style
Never include references to AI, Claude, or automated generation in:

Git commit messages
Code comments
Documentation
README files
Changelog entries
Pull request descriptions

Write all commits and documentation as if authored directly by a human developer. Use first-person naturally where appropriate (e.g., "Fixed bug in parser" or "Refactored authentication flow for clarity").
Avoid phrases like:

"Generated by Claude/AI"
"AI-assisted"
"Created with Claude Code"
"This code was written by an AI"
Any disclaimers about AI authorship

Commit messages should be concise, conventional, and professional (e.g., "feat: add user authentication", "fix: resolve null pointer in data handler", "docs: update API reference").