# CLAUDE.md — Phase 7: Intelligence Features

## Scope of This File

This file instructs you (Claude Code) to implement **Phase 7 only** of the Seedbox Command Center.

**Do not implement phases 8 through 15.** Stay in scope.

## Authoritative Specification

`PROJECT.md` §8.2 (Derived Metrics) and §8.4 (Decision Provenance) are authoritative. Read both before starting. Also read:
- `PROGRESS.md` and `DECISIONS.md`.
- The Phase 6 rules engine — Phase 7 plugs improved trigger evaluators into existing rule slots (`hr_risk_imminent`, `decision_recommendation`).
- DuckDB schema for `ratio_snapshots` and `torrent_snapshots` — Phase 7 is where the analytical store earns its keep.

## Phase 7 Mission

The intelligence layer: real ratio velocity, hit-and-run risk prediction, dead swarm detection, disk consumption forecasting with Monte Carlo intervals, and a recommendations engine that produces operator-actionable suggestions with full causal provenance trails.

This is the phase that makes the Command Center valuable beyond a glorified dashboard. After Phase 7, the operator routinely opens the app to ask "what should I look at right now" rather than "what's happening right now."

## Deliverables Checklist

Phase 7 is complete when every item below is true:

- [ ] `internal/intelligence/ratio_velocity` computes the rate of change of real ratio per tracker over rolling windows (1h, 24h, 7d, 30d). Reads from DuckDB `ratio_snapshots`. Surfaces per-tracker trend cards on the dashboard.
- [ ] `internal/intelligence/torrent_efficiency` derives upload-per-disk-byte per torrent over rolling windows. Combined with `torrents.size_bytes`, produces a "cost per upload byte" ranking surfaced in the dashboard and feeding recommendations.
- [ ] `internal/intelligence/hr_risk` predicts hit-and-run risk dates per torrent using the tracker's seed-time requirements (read from `torrent_trackers.seed_time_required_seconds`, populated from tracker rules if known; otherwise from a configurable default per tracker). Outputs `h_and_r_risk_at` timestamps on each row.
- [ ] `internal/intelligence/dead_swarms` flags torrents that have been seeded for ≥ configurable threshold (default 72h) with zero upload activity, after computing a fresh look at recent `torrent_snapshots`. Excludes torrents with imminent HR risk from the candidates list (do not surface "delete me" suggestions that would create violations).
- [ ] `internal/intelligence/disk_forecast` projects disk usage forward using a Monte Carlo simulation: 1000 trials, each draws grab rate from the recent empirical distribution (last 30 days of `filter_performance`) and average torrent size from the recent empirical distribution. Outputs p10 / p50 / p90 fill-date estimates.
- [ ] `internal/intelligence/recommendations` is the high-level engine that consumes outputs from the modules above and emits structured recommendations:
    - "Delete N torrents to recover X GB without breaking HR limits."
    - "Tighten filter F (high grab rate, low contribution)."
    - "Relax filter F (low grabs, high per-grab contribution; budget headroom exists)."
    - "Increase scrape interval on tracker T (low signal-to-failure ratio)."
    - Each recommendation carries the full causal chain that produced it.
- [ ] SQLite migration `008_phase7_decisions.sql` adds the `decision_log` table per Appendix A.
- [ ] Provenance: every recommendation writes to `decision_log` with `provenance_json` containing:
    - Inputs (which snapshots / table rows informed the decision).
    - Rule fired (which threshold or formula).
    - Computed values at decision time.
    - Alternatives considered (what other actions the engine looked at and why they ranked lower).
- [ ] API endpoints (auth required, under `/api/intelligence` and `/api/decisions`):
    - `GET /api/intelligence/ratio-velocity?tracker=...&range=...`
    - `GET /api/intelligence/h-and-r-risk?within=24h|7d|30d`
    - `GET /api/intelligence/dead-swarms`
    - `GET /api/intelligence/disk-forecast`
    - `GET /api/intelligence/recommendations`
    - `GET /api/decisions?range=...`
    - `GET /api/decisions/:id` (with expanded provenance)
    - `POST /api/decisions/:id/acknowledge` | `apply` | `dismiss`
- [ ] Frontend:
    - Dashboard recommendations panel: top 3 recommendations always visible.
    - `/decisions` route: full decisions inbox with filtering by type, status (open / acknowledged / applied / dismissed).
    - `/decisions/:id`: expandable provenance tree — tap each branch to see the underlying data.
    - `apply` button on actionable recommendations: routes through the appropriate adapter (e.g., delete a torrent via the Phase 3 client adapter, route to autobrr UI for filter changes — the Command Center does not edit autobrr filters directly).
- [ ] Tests: each intelligence module has property tests against synthetic snapshot histories. Recommendations engine produces stable outputs from a frozen fixture (golden tests). Provenance JSON validates against a typed schema.
- [ ] Phase 6's `hr_risk_imminent` and `decision_recommendation` trigger types now consume real outputs from Phase 7.
- [ ] `PROGRESS.md` updated. `DECISIONS.md` records: Monte Carlo trial count, dead swarm threshold, recommendation ranking algorithm.

## Phase 7 Database Scope

Migration `008_phase7_decisions.sql` creates:
- `decision_log`

Phase 7 also issues `UPDATE` statements against `torrent_trackers` to populate `h_and_r_risk_at` based on the predictor. Document this in the migration's comments.

## Repository Layout

```
internal/
  intelligence/
    ratio_velocity.go
    torrent_efficiency.go
    hr_risk.go
    dead_swarms.go
    disk_forecast.go
    recommendations.go
    provenance.go            # the typed provenance schema
    *_test.go
  decisions/
    log.go                   # write/read decision_log
    actions.go               # apply / acknowledge / dismiss handlers
    *_test.go
```

Files added under existing packages:
- `internal/server/routes_intelligence.go`
- `internal/server/routes_decisions.go`
- `internal/rules/triggers/hr_risk.go` — extended to consume Phase 7 predictions.
- `internal/rules/triggers/decision_recommendation.go` — extended to fire on new decisions.

Frontend additions:
- `web/src/pages/Decisions.tsx`
- `web/src/pages/DecisionDetail.tsx`
- `web/src/components/ProvenanceTree.tsx`
- `web/src/components/DiskForecastChart.tsx`

## Working Rules

**DuckDB carries the analytical load.** Phase 7 queries DuckDB heavily; SQLite is only for the decision log and small reads. Use DuckDB's columnar speed by writing parameterized analytical queries; do not pull large slices into Go for processing.

**Provenance is the product.** Every recommendation MUST carry a full causal chain. A recommendation without provenance is a bug, not a feature.

**Confidence intervals over point estimates.** Disk forecast surfaces p10/p50/p90. Ratio velocity surfaces a slope with its standard error. The UI shows ranges, not magic numbers.

**Conservatism on actions.** Dead-swarm-delete recommendations always check HR risk before suggesting. The engine prefers no recommendation over a recommendation that creates a violation.

**The recommendations engine is composable.** Each intelligence module is independently testable. The recommendation engine orchestrates them; do not duplicate logic across modules.

**Apply is delegate, not implement.** A "delete this torrent" recommendation, when applied, calls the Phase 3 torrent client adapter. A "tighten this filter" recommendation, when "applied", opens autobrr's filter editor in a new tab — the Command Center does not edit autobrr filters.

## What "Phase 7 Complete" Looks Like

After Phase 7 ships, the operator can:

1. Open the dashboard. See three recommendations at the top: e.g., "Delete 6 dead-swarm torrents (47 GB recoverable, no HR risk)", "Tighten Filter X (210 grabs/30d, 8 MB avg upload)", "Disk forecast p90 fill date: April 12."
2. Tap a recommendation. See its provenance: the snapshot timestamps, the rules that fired, the threshold values, the alternatives the engine considered.
3. Tap apply on the dead-swarm recommendation. Confirm. Watch the deletions execute via the qBittorrent adapter; the decision row marks `applied`.
4. Receive a push notification when a new recommendation crosses the configured severity threshold (Phase 6's `decision_recommendation` trigger now bites).
5. Browse the decisions inbox; filter by date and type; see the historical record of what the system flagged and what the operator did.
6. Trust the disk forecast enough to schedule a cleanup before the predicted fill date.

## Begin

Read `PROJECT.md §8.2` and `§8.4`. Start with `ratio_velocity` (the simplest module) to establish the pattern. Then `hr_risk` and `dead_swarms`. Then `disk_forecast` (the heavyweight). Finally the recommendations engine. Provenance schema is shared infrastructure — design it once and use it across modules. Stop at the end of Phase 7.
