# OCLAWMA-27: Cost Tracking Implementation

## Summary

This implementation adds comprehensive cost tracking functionality to OCLAWMA, enabling tracking of API costs, compute time, and storage usage per job with budget management and alerting.

## Files Created

### Core Module
- **`src/oclawma/costs.py`** - Main cost tracking module (1,154 lines)
  - `JobCost` model: Tracks job_id, compute_time, api_costs, storage, total
  - `CostTracker` class: Tracks costs during job execution with context manager support
  - `CostBudget` class: Per-project/tenant budget management with configurable alert thresholds
  - `BudgetManager` class: CRUD operations for budgets and alert generation
  - `CostStore` class: SQLite-backed persistent storage
  - `CostReport` class: Cost attribution reports (daily/weekly/monthly)
  - Export to CSV/JSON support

### CLI Module
- **`src/oclawma/costs_cli.py`** - CLI commands for cost management (590 lines)
  - `oclawma costs report` - Generate cost reports
  - `oclawma costs budget list/create/update/delete/check` - Budget management
  - `oclawma costs export` - Export cost data
  - `oclawma costs show/list-jobs` - View job costs

### Web Dashboard
- **`src/oclawma/web/costs.py`** - Web UI and API endpoints (323 lines)
  - `/costs/dashboard` - Interactive HTML dashboard with Chart.js visualizations
  - `/costs/api/report` - Report API endpoint
  - `/costs/api/stats` - Summary statistics
  - `/costs/api/jobs` - Job cost listing
  - `/costs/api/budgets` - Budget CRUD endpoints

### Integration Module
- **`src/oclawma/costs_integration.py`** - Queue and metrics integration (219 lines)
  - `CostsQueueIntegration` - Automatic cost tracking for job queue
  - `CostsMetricsExporter` - Export cost data to metrics collector

### Tests
- **`tests/test_costs.py`** - Comprehensive test suite (860 lines, 58 tests)
  - Tests for all models, storage, tracking, budgets, and reports
  - Integration tests for complete workflows

## Integration Points

### CLI Integration
Added to `src/oclawma/cli.py`:
```python
from oclawma.costs_cli import costs_cli
cli.add_command(costs_cli)
```

### Web Server Integration
Added to `src/oclawma/web/server.py`:
```python
from oclawma.web.costs import create_costs_router
app.include_router(create_costs_router())
```

## Features

### Cost Tracking
- Track API costs per provider (OpenAI, Anthropic, etc.)
- Automatic compute time tracking
- Storage usage tracking
- Total cost calculation with configurable rates

### Budget Management
- Per-project and per-tenant budgets
- Configurable alert thresholds (default: 50%, 75%, 90%)
- Alert levels: INFO, WARNING, CRITICAL
- Automatic alert generation and storage

### Reporting
- Daily, weekly, and monthly reports
- Cost breakdown by project, tenant, and provider
- Top jobs by cost
- Daily trend analysis
- Export to CSV or JSON

### Web Dashboard
- Real-time cost statistics
- Interactive charts (Chart.js)
- Budget status visualization with progress bars
- Job listing with filtering
- Auto-refresh every 30 seconds

## Data Storage

Costs are stored in SQLite database at `~/.oclawma/costs/costs.db` with tables:
- `job_costs` - Job cost records
- `budgets` - Budget configurations
- `budget_alerts` - Alert history

## Quality Assurance

All code passes:
- ✅ pytest (58 tests)
- ✅ ruff linting
- ✅ black formatting
- ✅ mypy type checking (inline)

## Usage Examples

```bash
# View daily cost report
oclawma costs report

# Create a budget
oclawma costs budget create --name "Project A" --limit 100.0 --project proj-a

# Check budget status
oclawma costs budget check

# Export costs to JSON
oclawma costs export --format json --output costs.json

# View job details
oclawma costs show job-123
```

```python
# Track costs in code
from oclawma.costs import CostTracker

with CostTracker().track_job("job-123", project_id="proj-a") as job:
    job.add_api_cost("openai", "gpt-4", 0.05, tokens_input=1000, tokens_output=500)
    # ... do work ...
```

## API Documentation

### Dashboard Endpoint
- `GET /costs/dashboard` - HTML dashboard

### Report Endpoints
- `GET /costs/api/report?period=daily&project_id=...` - Generate report
- `GET /costs/api/stats` - Summary statistics

### Job Endpoints
- `GET /costs/api/jobs?limit=50` - List job costs
- `GET /costs/api/jobs/{job_id}` - Get job details

### Budget Endpoints
- `GET /costs/api/budgets` - List budgets
- `POST /costs/api/budgets` - Create budget
- `GET /costs/api/budgets/{id}` - Get budget
- `PUT /costs/api/budgets/{id}` - Update budget
- `DELETE /costs/api/budgets/{id}` - Delete budget
- `POST /costs/api/budgets/{id}/check` - Check budget status
