# ClaudeTools Project Context

**FIRST: READ YOUR DIRECTIVES AND FILE PLACEMENT GUIDE**

Before doing ANYTHING in this project:
1. Read and internalize `directives.md` in the project root
2. Review `.claude/FILE_PLACEMENT_GUIDE.md` for file organization

**directives.md** defines:
- Your identity (Coordinator, not Executor)
- What you DO and DO NOT do
- Agent coordination rules (NEVER query database directly)
- Enforcement checklist (NO EMOJIS, ASCII markers only)

**FILE_PLACEMENT_GUIDE.md** defines:
- Where to save new files (projects/ vs clients/ vs root)
- Session log locations (project-specific vs general)
- File naming conventions
- Organization maintenance

**If you haven't read these in this session, STOP and read them now.**

Commands:
- `Read directives.md` (in project root)
- `Read .claude/FILE_PLACEMENT_GUIDE.md`

---

**Project Type:** MSP Work Tracking System
**Status:** Production-Ready
**Database:** MariaDB 10.6.22 @ 172.16.3.30:3306 (RMM Server)

---

## Quick Facts

- **95+ API Endpoints** across 17 entities
- **38 Database Tables** (fully migrated)
- **JWT Authentication** on all endpoints
- **AES-256-GCM Encryption** for credentials
- **3 MCP Servers** configured (GitHub, Filesystem, Sequential Thinking)

---

## Core Operating Principle: You Are a Coordinator

**CRITICAL:** Main Claude is a **coordinator**, not an executor. Your primary role is to delegate work to specialized agents and preserve your main context space.

**Main Context Space is Sacred:**
- Your context window is valuable and limited
- Delegate ALL significant operations to agents unless doing it yourself is significantly cheaper in tokens
- Agents have their own full context windows for specialized tasks
- Keep your context focused on coordination, decision-making, and user interaction

**When to Delegate (via Task tool):**
- Database operations (queries, inserts, updates) → Database Agent
- Code generation → Coding Agent
- Code review → Code Review Agent (MANDATORY for all code)
- Test execution → Testing Agent
- Git operations → Gitea Agent
- File exploration/search → Explore Agent
- Complex problem-solving → General-purpose agent with Sequential Thinking MCP

**When to Do It Yourself:**
- Simple user responses (conversational replies)
- Reading a single file to answer a question
- Basic file operations (1-2 files)
- Presenting agent results to user
- Making decisions about what to do next
- Creating task checklists

**Example - Database Query (DELEGATE):**
```
User: "How many projects are in the database?"

[ERROR] WRONG: ssh guru@172.16.3.30 "mysql -u claudetools ... SELECT COUNT(*) ..."
[OK] CORRECT: Launch Database Agent with task: "Count projects in database"
```

**Example - Simple File Read (DO YOURSELF):**
```
User: "What's in the README?"

[OK] CORRECT: Use Read tool directly (cheap, preserves context)
[ERROR] WRONG: Launch agent just to read one file (wasteful)
```

**Rule of Thumb:**
- If the operation will consume >500 tokens of your context → Delegate to agent
- If it's a simple read/search/response → Do it yourself
- If it's code generation or database work → ALWAYS delegate
- When in doubt → Delegate (agents are cheap, your context is precious)

**See:** `.claude/AGENT_COORDINATION_RULES.md` for complete delegation guidelines

---

## Project Structure

```
D:\ClaudeTools/
├── api/                    # FastAPI application
│   ├── main.py            # API entry point
│   ├── models/            # SQLAlchemy models
│   ├── routers/           # API endpoints
│   ├── schemas/           # Pydantic schemas
│   ├── services/          # Business logic
│   ├── middleware/        # Auth & error handling
│   └── utils/             # Crypto utilities
├── migrations/            # Alembic database migrations
├── .claude/              # Claude Code hooks & config
│   ├── commands/         # Commands (create-spec, checkpoint)
│   ├── skills/           # Skills (frontend-design)
│   └── templates/        # Templates (app spec, prompts)
├── mcp-servers/          # MCP server implementations
│   └── feature-management/  # Feature tracking MCP server
├── scripts/              # Setup & test scripts
└── projects/             # Project workspaces
```

---

## Database Connection

**UPDATED 2026-01-17:** Database is centralized on RMM server (172.16.3.30)

**Connection String:**
```
Host: 172.16.3.30:3306
Database: claudetools
User: claudetools
Password: CT_e8fcd5a3952030a79ed6debae6c954ed
```

**Environment Variables:**
```bash
DATABASE_URL=mysql+pymysql://claudetools:CT_e8fcd5a3952030a79ed6debae6c954ed@172.16.3.30:3306/claudetools?charset=utf8mb4
```

**API Base URL:** http://172.16.3.30:8001

**See:** `.claude/agents/DATABASE_CONNECTION_INFO.md` for complete details.

---

## Starting the API

```bash
# Activate virtual environment
api\venv\Scripts\activate

# Start API server
python -m api.main
# OR
uvicorn api.main:app --reload --host 0.0.0.0 --port 8000

# Access documentation
http://localhost:8000/api/docs
```

---

## Key API Endpoints

### Core Entities (Phase 4)
- `/api/machines` - Machine inventory
- `/api/clients` - Client management
- `/api/projects` - Project tracking
- `/api/sessions` - Work sessions
- `/api/tags` - Tagging system

### MSP Work Tracking (Phase 5)
- `/api/work-items` - Work item tracking
- `/api/tasks` - Task management
- `/api/billable-time` - Time & billing

### Infrastructure (Phase 5)
- `/api/sites` - Physical locations
- `/api/infrastructure` - IT assets
- `/api/services` - Application services
- `/api/networks` - Network configs
- `/api/firewall-rules` - Firewall documentation
- `/api/m365-tenants` - M365 tenant management

### Credentials (Phase 5)
- `/api/credentials` - Encrypted credential storage
- `/api/credential-audit-logs` - Audit trail (read-only)
- `/api/security-incidents` - Incident tracking

---

## Common Workflows

### 1. Create New Project

```python
# Create project
POST /api/projects
{
  "name": "New Website",
  "client_id": "client-uuid",
  "status": "planning"
}
```

### 2. Track Work Session

```python
# Create session
POST /api/sessions
{
  "project_id": "project-uuid",
  "machine_id": "machine-uuid",
  "started_at": "2026-01-16T10:00:00Z"
}

# Log billable time
POST /api/billable-time
{
  "session_id": "session-uuid",
  "work_item_id": "work-item-uuid",
  "client_id": "client-uuid",
  "start_time": "2026-01-16T10:00:00Z",
  "end_time": "2026-01-16T12:00:00Z",
  "duration_hours": 2.0,
  "hourly_rate": 150.00,
  "total_amount": 300.00
}
```

### 3. Store Encrypted Credential

```python
POST /api/credentials
{
  "credential_type": "api_key",
  "service_name": "OpenAI API",
  "username": "api_key",
  "password": "sk-1234567890",  # Auto-encrypted
  "client_id": "client-uuid",
  "notes": "Production API key"
}
# Password automatically encrypted with AES-256-GCM
# Audit log automatically created
```

---

## Important Files

**Session State:** `SESSION_STATE.md` - Complete project history and status

**Credentials:** `credentials.md` - ALL infrastructure credentials and connection details (UNREDACTED for context recovery)

**Session Logs:** `session-logs/YYYY-MM-DD-session.md` - Comprehensive session documentation with credentials, decisions, and infrastructure changes

**Documentation:**
- `AUTOCODER_INTEGRATION.md` - AutoCoder resources guide
- `TEST_PHASE5_RESULTS.md` - Phase 5 test results

**Configuration:**
- `.env` - Environment variables (gitignored)
- `.env.example` - Template with placeholders

**Tests:**
- `test_api_endpoints.py` - Phase 4 tests
- `test_phase5_api_endpoints.py` - Phase 5 tests

**AutoCoder Resources:**
- `.claude/commands/create-spec.md` - Create app specification
- `.claude/commands/checkpoint.md` - Create development checkpoint
- `.claude/skills/frontend-design/` - Frontend design skill
- `.claude/templates/` - Prompt templates (4 templates)
- `mcp-servers/feature-management/` - Feature tracking MCP server

---

## Recent Work (from SESSION_STATE.md)

**Last Session:** 2026-01-18
**Phases Completed:** 0-5 (complete)

**Phase 5 - Completed:**
- MSP Work Tracking system
- Infrastructure management endpoints
- Encrypted credential storage
- Security incident tracking

**Current State:**
- 95+ endpoints operational
- All migrations applied (38 tables)
- Full test coverage

---

## Security

**Authentication:** JWT tokens (Argon2 password hashing)
**Encryption:** AES-256-GCM (Fernet) for credentials
**Audit Logging:** All credential operations logged

**Get JWT Token:**
```bash
POST /api/auth/token
{
  "email": "user@example.com",
  "password": "your-password"
}
```

---

## Troubleshooting

**API won't start:**
```bash
# Check if port 8000 is in use
netstat -ano | findstr :8000

# Check database connection
python test_db_connection.py
```

**Database migration issues:**
```bash
# Check current revision
alembic current

# Show migration history
alembic history

# Upgrade to latest
alembic upgrade head
```

---

## MCP Servers

**Model Context Protocol servers extend Claude Code's capabilities.**

**Configured Servers:**
- **GitHub MCP** - Repository and PR management (requires token)
- **Filesystem MCP** - Enhanced file operations (D:\ClaudeTools access)
- **Sequential Thinking MCP** - Structured problem-solving

**Configuration:** `.mcp.json` (project-scoped)
**Documentation:** `MCP_SERVERS.md` - Complete setup and usage guide
**Setup Script:** `bash scripts/setup-mcp-servers.sh`

**Quick Start:**
1. Add GitHub token to `.mcp.json` (optional)
2. Restart Claude Code completely
3. Test: "Use sequential thinking to analyze X"
4. Test: "List Python files in the api directory"

**Note:** GitHub MCP is for GitHub.com - Gitea integration requires custom solution (see MCP_SERVERS.md)

---

## Next Steps (Optional Phase 7)

**Remaining entities (from original spec):**
- File Changes API - Track file modifications
- Command Runs API - Command execution history
- Problem Solutions API - Knowledge base
- Failure Patterns API - Error pattern recognition
- Environmental Insights API - Contextual learning

**These are optional** - the system is fully functional without them.

---

## Coding Guidelines

**IMPORTANT:** Follow coding standards in `.claude/CODING_GUIDELINES.md`

**Key Rules:**
- NO EMOJIS - EVER (causes encoding/parsing issues)
- Use ASCII text markers: `[OK]`, `[ERROR]`, `[WARNING]`, `[SUCCESS]`
- Follow PEP 8 for Python, PSScriptAnalyzer for PowerShell
- No hardcoded credentials
- All endpoints must have docstrings

---

## Context Recovery & Session Logs

**CRITICAL:** Use `/context` command when user references previous work

### Organized File Structure (NEW - 2026-01-20)
**All files are now organized by project and client:**
- `projects/[project-name]/` - Project-specific work
- `clients/[client-name]/` - Client-specific work
- `session-logs/` - General/cross-project logs
- **See:** `PROJECT_ORGANIZATION.md` for complete structure

### Session Logs (Multiple Locations)
**Project-Specific:**
- Dataforth DOS: `projects/dataforth-dos/session-logs/YYYY-MM-DD-session.md`
- ClaudeTools API: `projects/claudetools-api/session-logs/YYYY-MM-DD-session.md`

**Client-Specific:**
- Format: `clients/[client-name]/session-logs/YYYY-MM-DD-session.md`

**General/Mixed:**
- Format: `session-logs/YYYY-MM-DD-session.md` (root)

**Content:** ALL credentials, infrastructure details, decisions, commands, config changes
**Purpose:** Full context recovery when conversation is summarized or new session starts
**Usage:** `/save` command determines correct location and creates/appends

### Credentials File (credentials.md)
- **Content:** ALL infrastructure credentials (UNREDACTED)
- **Sections:**
  - Infrastructure - SSH Access (GuruRMM, Jupiter, AD2, D2TESTNAS)
  - Services - Web Applications (Gitea, ClaudeTools API)
  - Projects - ClaudeTools (Database, API auth, encryption keys)
  - Projects - Dataforth DOS (Update workflow, key files, folder structure)
- **Purpose:** Centralized credentials for immediate context recovery
- **Usage:** `/context` searches this file for server access details

### Context Recovery Workflow
When user references previous work:
1. **Use `/context` command** - Searches session logs and credentials.md
2. **Never ask user** for information already in logs/credentials
3. **Apply found information** - Connect to servers, continue work
4. **Report findings** - Summarize relevant credentials and previous work

### Example Usage
```
User: "Connect to the Dataforth NAS"
Assistant: Uses /context to find D2TESTNAS credentials (192.168.0.9, admin, Paper123!@#-nas)
Assistant: Connects using found credentials without asking user
```

---

## Quick Reference

**Start API:** `uvicorn api.main:app --reload`
**API Docs:** `http://localhost:8000/api/docs` (local) or `http://172.16.3.30:8001/api/docs` (RMM)
**Setup MCP Servers:** `bash scripts/setup-mcp-servers.sh`
**Database:** `172.16.3.30:3306/claudetools` (RMM Server)
**Virtual Env:** `api\venv\Scripts\activate`
**Coding Guidelines:** `.claude/CODING_GUIDELINES.md`
**MCP Documentation:** `MCP_SERVERS.md`
**AutoCoder Integration:** `AUTOCODER_INTEGRATION.md`

**Available Commands:**
- `/create-spec` - Create app specification
- `/checkpoint` - Create development checkpoint
- `/save` - Save comprehensive session log (credentials, infrastructure, decisions)
- `/context` - Search session logs and credentials.md for previous work
- `/sync` - Sync ClaudeTools configuration from Gitea repository

**Available Skills:**
- `/frontend-design` - Modern frontend design patterns

---

**Last Updated:** 2026-01-19 (Integrated C: drive behavioral rules, added context recovery system)
**Project Progress:** Phase 5 Complete
