refactor: Trim CLAUDE.md and directives to reduce context window pressure

Reduced always-loaded context from ~1,570 lines to ~75 lines (-95%):
- CLAUDE.md: 464 -> 75 lines (merged in directives, removed reference material)
- directives.md: 639 -> 7 lines (now pointer to CLAUDE.md)
- AGENT_COORDINATION_RULES.md: 468 -> 32 lines (slim agent reference only)
- New REFERENCE.md: on-demand reference for endpoints, workflows, troubleshooting
- Removed "read these files FIRST" cascade that loaded 320+ extra lines per session
- FILE_PLACEMENT_GUIDE.md and CODING_GUIDELINES.md now read on-demand by agents

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-17 10:49:35 -07:00
parent aaf4172b3c
commit ab5db78eb2
4 changed files with 299 additions and 1510 deletions

View File

@@ -1,467 +1,38 @@
# Agent Coordination Rules
**CRITICAL: Main Claude is a COORDINATOR, not an executor**
---
## Core Principle
**Main Claude Instance:**
- Coordinates work between user and agents
- Makes decisions and plans
- Presents concise results to user
- **NEVER performs database operations directly**
- **NEVER makes direct API calls to ClaudeTools API**
**Agents:**
- Execute specific tasks (database, coding, testing, etc.)
- Return concise summaries
- Preserve Main Claude's context space
---
## Database Operations - ALWAYS Use Database Agent
### [ERROR] WRONG (What I Was Doing)
```bash
# Main Claude making direct queries
ssh guru@172.16.3.30 "mysql -u claudetools ... SELECT ..."
curl http://172.16.3.30:8001/api/conversation-contexts ...
```
### [OK] CORRECT (What Should Happen)
```
Main Claude → Task tool → Database Agent → Returns summary
```
**Example:**
```
User: "How many contexts are saved?"
Main Claude: "Let me check the database"
Launches Database Agent with task: "Count conversation_contexts in database"
Database Agent: Queries database, returns: "7 contexts found"
Main Claude to User: "There are 7 contexts saved in the database"
```
**Purpose:** Reference for agents about their responsibilities and coordination patterns.
**Main Claude behavioral rules are in CLAUDE.md - this file is for agent reference only.**
---
## Agent Responsibilities
### Database Agent (`.claude/agents/database.md`)
**ONLY agent authorized for database operations**
| Agent | Authority | Examples |
|-------|-----------|----------|
| Database Agent | ALL data operations | Queries, inserts, updates, deletes, API calls |
| Coding Agent | Production code | Python, PowerShell, Bash; new code and modifications |
| Testing Agent | Test execution | pytest, validation scripts, performance tests |
| Code Review Agent | Code quality (MANDATORY) | Security, standards, quality checks before commits |
| Gitea Agent | Git/version control | Commits, pushes, branches, tags |
| Backup Agent | Backup/restore | Create backups, restore data, verify integrity |
**Handles:**
- All SELECT, INSERT, UPDATE, DELETE queries
- Context storage and retrieval
- Data validation and integrity
- Transaction management
- Query optimization
## Coordination Flow
**Returns:** Concise summaries, not raw SQL results
**When to use:**
- Saving contexts to database
- Retrieving contexts from database
- Checking record counts
- Any database operation
### Coding Agent (`.claude/agents/coding.md`)
**Handles code writing and modifications**
**When to use:**
- Writing new code
- Modifying existing code
- Creating scripts
### Testing Agent (`.claude/agents/testing.md`)
**Handles test execution**
**When to use:**
- Running tests
- Executing validation scripts
- Performance testing
### Code Review Agent (`.claude/agents/code-review.md`)
**Reviews code quality**
**When to use:**
- After significant code changes
- Before committing
### Gitea Agent (`.claude/agents/gitea.md`)
**Handles Git operations**
**When to use:**
- Git commits
- Push to remote
- Branch management
### Backup Agent (`.claude/agents/backup.md`)
**Manages backups**
**When to use:**
- Creating backups
- Restoring data
- Backup verification
---
## Violation Examples from This Session
### [ERROR] Violation 1: Direct Database Queries
```bash
ssh guru@172.16.3.30 "mysql ... SELECT COUNT(*) FROM conversation_contexts"
```
**Should have been:** Database Agent task
### [ERROR] Violation 2: Direct API Calls
```bash
curl -X POST http://172.16.3.30:8001/api/conversation-contexts ...
```
**Should have been:** Database Agent task
### [ERROR] Violation 3: Direct Context Creation
```bash
curl ... -d '{"context_type": "session_summary", ...}'
```
**Should have been:** Database Agent task
---
## Correct Coordination Flow
### Example: Save Context to Database
**User Request:** "Save the current context"
**Main Claude Actions:**
1. [OK] Summarize what needs to be saved
2. [OK] Launch Database Agent with task:
```
"Save session context to database:
- Title: [summary]
- Dense summary: [compressed context]
- Tags: [relevant tags]
- Score: 8.5"
```
3. [OK] Receive agent response: "Context saved with ID abc-123"
4. [OK] Tell user: "Context saved successfully"
**What Main Claude Does NOT Do:**
- [ERROR] Make direct curl calls
- [ERROR] Make direct SQL queries
- [ERROR] Return raw database results to user
---
## Example: Retrieve Contexts
**User Request:** "What contexts do we have about offline mode?"
**Main Claude Actions:**
1. [OK] Launch Database Agent with task:
```
"Search conversation_contexts for entries related to 'offline mode'.
Return: titles, scores, and brief summaries of top 5 results"
```
2. [OK] Receive agent summary:
```
Found 3 contexts:
1. "Offline Mode Implementation" (score 9.5)
2. "Offline Mode Testing" (score 8.0)
3. "Offline Mode Documentation" (score 7.5)
```
3. [OK] Present to user in conversational format
**What Main Claude Does NOT Do:**
- [ERROR] Query API directly
- [ERROR] Show raw JSON responses
- [ERROR] Execute SQL
---
## Benefits of Agent Architecture
### Context Preservation
- Main Claude's context not polluted with raw data
- Can handle longer conversations
- Focus on coordination, not execution
### Separation of Concerns
- Database Agent handles data integrity
- Coding Agent handles code quality
- Main Claude handles user interaction
### Scalability
- Agents can run in parallel
- Each has full context window for their task
- Complex operations don't bloat main context
---
## Enforcement
### Before Making ANY Database Operation:
**Ask yourself:**
1. Am I about to query the database directly? → [ERROR] STOP
2. Am I about to call the ClaudeTools API? → [ERROR] STOP
3. Should the Database Agent handle this? → [OK] USE AGENT
### When to Launch Database Agent:
- Saving any data (contexts, tasks, sessions, etc.)
- Retrieving any data from database
- Counting records
- Searching contexts
- Updating existing records
- Deleting records
- Any SQL operation
---
## Going Forward
**Main Claude Responsibilities:**
- [OK] Coordinate with user
- [OK] Make decisions about what to do
- [OK] Launch appropriate agents
- [OK] Synthesize agent results for user
- [OK] Plan and design solutions
- [OK] **Automatically invoke skills when triggered** (NEW)
- [OK] **Recognize when Sequential Thinking is needed** (NEW)
- [OK] **Execute dual checkpoints (git + database)** (NEW)
- [OK] **Manage tasks with native tools (TaskCreate/Update/List)** (NEW)
**Main Claude Does NOT:**
- [ERROR] Query database directly
- [ERROR] Make API calls to ClaudeTools API
- [ERROR] Execute code (unless simple demonstration)
- [ERROR] Run tests (use Testing Agent)
- [ERROR] Commit to git (use Gitea Agent)
- [ERROR] Review code (use Code Review Agent)
- [ERROR] Write production code (use Coding Agent)
---
## New Capabilities (Added 2026-01-17)
### 1. Automatic Skill Invocation
**Main Claude automatically invokes skills when triggered by specific actions:**
**Frontend Design Skill:**
- **Trigger:** ANY action that affects a UI element
- **When:** After modifying HTML/CSS/JSX, styling, layouts, components
- **Purpose:** Validate visual correctness, functionality, UX, accessibility
- **Workflow:**
```
User: "Add a submit button"
Main Claude: [Writes button code]
Main Claude: [AUTO-INVOKE frontend-design skill]
Frontend Skill: [Validates appearance, behavior, accessibility]
Frontend Skill: [Returns PASS/WARNING/ERROR]
Main Claude: [Proceeds or fixes based on validation]
```
**Rule:** If the change appears in a browser, invoke frontend-design skill to validate it.
### 2. Sequential Thinking Recognition
**Main Claude recognizes when agents should use Sequential Thinking MCP:**
**For Code Review Agent:**
- Knows to use ST when code rejected 2+ times
- Knows to use ST when 3+ critical issues found
- Knows to use ST for complex architectural decisions
- Doesn't use ST for simple fixes (wastes tokens)
**For Other Complex Tasks:**
- Multi-step debugging with unclear root cause
- Architectural trade-off decisions
- Complex problem-solving where approach might change
- Investigation tasks where each finding affects next step
**Rule:** Use ST for genuinely complex, ambiguous problems where structured reasoning adds value.
### 3. Dual Checkpoint System
**Main Claude executes dual checkpoints via /checkpoint command:**
**Part 1: Git Checkpoint**
- Stages all changes (git add -A)
- Creates detailed commit message
- Follows existing commit conventions
- Includes co-author attribution
**Part 2: Database Context**
- Saves session summary to ClaudeTools API
- Includes git metadata (commit, branch, files)
- Tags for searchability
- Relevance score 8.0 (important milestone)
**Workflow:**
```
User: /checkpoint
Main Claude: [Analyzes changes]
Main Claude: [Creates git commit]
Main Claude: [Saves context to database via API/script]
Main Claude: [Verifies both succeeded]
Main Claude: [Reports to user]
User request -> Main Claude (coordinator) -> Launches agent(s) -> Agent returns summary -> Main Claude presents to user
```
**Benefits:**
- Git: Code versioning and rollback
- Database: Cross-machine context recall
- Together: Complete project memory
- Main Claude NEVER queries databases, writes production code, runs tests, or commits directly
- Agents return concise summaries, not raw data
- Independent operations run in parallel
- Use Sequential Thinking MCP for genuinely complex problems
### 4. Native Task Management
## Skills vs Agents
**Main Claude uses TaskCreate/Update/List for complex multi-step operations:**
**When to Use:**
- Complex work requiring >3 distinct steps
- Multi-agent coordination needing status tracking
- User requests progress visibility
- Work may span multiple sessions
**Task Workflow:**
```
User: "Implement authentication for API"
Main Claude:
1. TaskCreate (parent: "Implement API authentication")
2. TaskCreate (subtasks with dependencies):
- "Design auth schema" (pending)
- "Generate code" (blockedBy: design)
- "Review code" (blockedBy: generate)
- "Write tests" (blockedBy: review)
3. Save all tasks to .claude/active-tasks.json
4. Execute:
- TaskUpdate(design, in_progress)
- Launch Coding Agent → Returns design
- TaskUpdate(design, completed)
- Update active-tasks.json
- TaskUpdate(generate, in_progress) [dependency cleared]
- Launch Coding Agent → Returns code
- TaskUpdate(generate, completed)
- Update active-tasks.json
[Continue pattern...]
5. TaskList() → Show user progress
```
**Agent Integration:**
- Agents report status (completed/failed/blocked)
- Main Claude translates to TaskUpdate
- File updated after each status change
**Cross-Session Recovery:**
```
New session starts:
1. Read .claude/active-tasks.json
2. Filter incomplete tasks
3. Recreate with TaskCreate
4. Restore dependencies
5. TaskList() → Show recovered state
6. Continue execution
```
**Benefits:**
- Real-time progress visibility via TaskList
- Built-in dependency management (blocks/blockedBy)
- File-based persistence (no database)
- Session continuity across restarts
**See:** `.claude/NATIVE_TASK_INTEGRATION.md` for complete guide
### 5. Skills vs Agents
**Main Claude understands the difference:**
**Skills** (invoked via Skill tool):
- Frontend design/validation
- User-invocable with `/skill-name`
- Specialized capabilities
- Return enhanced output
**Agents** (invoked via Task tool):
- Database operations
- Code writing
- Testing
- Code review
- Git operations
- Backup/restore
**Rule:** Skills are for specialized enhancements (frontend, design patterns). Agents are for core operations (database, coding, testing).
- **Skills** (Skill tool): Specialized enhancements - frontend-design validation, design patterns
- **Agents** (Task tool): Core operations - database, code, testing, git, backups
- **Rule:** Skills enhance/validate. Agents execute/operate.
---
## Quick Reference
| Operation | Handler |
|-----------|---------|
| Save context | Database Agent |
| Retrieve contexts | Database Agent |
| Count records | Database Agent |
| Write code | Coding Agent |
| Run tests | Testing Agent |
| Review code | Code Review Agent |
| Git operations | Gitea Agent |
| Backups | Backup Agent |
| **UI validation** | **Frontend Design Skill (auto-invoked)** |
| **Complex problem analysis** | **Sequential Thinking MCP** |
| **Dual checkpoints** | **/checkpoint command (Main Claude)** |
| **Task tracking (>3 steps)** | **TaskCreate/Update/List (Main Claude)** |
| **User interaction** | **Main Claude** |
| **Coordination** | **Main Claude** |
| **Decision making** | **Main Claude** |
| **Skill invocation** | **Main Claude** |
---
**Remember: Main Claude = Coordinator, not Executor**
**When in doubt, use an agent or skill!**
---
## Summary of Main Claude's Role
**Main Claude is the conductor of an orchestra:**
- Receives user requests
- Decides which agents/skills to invoke
- Coordinates workflow between agents
- Automatically triggers skills when appropriate
- Synthesizes results for user
- Maintains conversation context
**Main Claude does NOT:**
- Execute database operations directly
- Write production code (delegates to Coding Agent)
- Run tests directly (delegates to Testing Agent)
- Review code directly (delegates to Code Review Agent)
- Perform git operations directly (delegates to Gitea Agent)
**Main Claude DOES automatically:**
- Invoke frontend-design skill for ANY UI change
- Recognize when Sequential Thinking is appropriate
- Execute dual checkpoints (git + database) via /checkpoint
- **Manage tasks with native tools for complex operations (>3 steps)**
- Coordinate agents and skills intelligently
---
**Created:** 2026-01-17
**Last Updated:** 2026-01-23 (added native task management)
**Purpose:** Ensure proper agent-based architecture
**Status:** Mandatory guideline for all future operations
**Last Updated:** 2026-02-17

213
.claude/REFERENCE.md Normal file
View File

@@ -0,0 +1,213 @@
# ClaudeTools Reference Guide
**Purpose:** On-demand reference material for agents and deep-dive questions.
**Not loaded automatically** - agents read this when they need project details.
---
## 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
```
---
## 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
```
---
## 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
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
| File | Purpose |
|------|---------|
| `SESSION_STATE.md` | Complete project history and status |
| `credentials.md` | ALL infrastructure credentials (UNREDACTED) |
| `session-logs/` | Daily session documentation |
| `.env` / `.env.example` | Environment variables |
| `test_api_endpoints.py` | Phase 4 tests |
| `test_phase5_api_endpoints.py` | Phase 5 tests |
| `AUTOCODER_INTEGRATION.md` | AutoCoder resources guide |
| `TEST_PHASE5_RESULTS.md` | Phase 5 test results |
---
## Security
- **Authentication:** JWT tokens (Argon2 password hashing)
- **Encryption:** AES-256-GCM (Fernet) for credentials
- **Audit Logging:** All credential operations logged
```bash
# Get JWT Token
POST /api/auth/token
{ "email": "user@example.com", "password": "your-password" }
```
---
## Troubleshooting
```bash
# API won't start - check port
netstat -ano | findstr :8000
# Check database connection
python test_db_connection.py
# Database migration issues
alembic current # Check current revision
alembic history # Show migration history
alembic upgrade head # Upgrade to latest
```
---
## MCP Servers
See `MCP_SERVERS.md` for complete details.
- **GitHub MCP** - Repository and PR management (requires token)
- **Filesystem MCP** - Enhanced file operations (D:\ClaudeTools access)
- **Sequential Thinking MCP** - Structured problem-solving
Config: `.mcp.json` | Setup: `bash scripts/setup-mcp-servers.sh`
---
## Next Steps (Optional Phase 7)
- 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.
---
## Session Log 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:** `clients/[client-name]/session-logs/YYYY-MM-DD-session.md`
**General/Mixed:** `session-logs/YYYY-MM-DD-session.md` (root)
See `PROJECT_ORGANIZATION.md` for complete structure.

View File

@@ -1,463 +1,97 @@
# ClaudeTools Project Context
**FIRST: READ YOUR DIRECTIVES AND FILE PLACEMENT GUIDE**
## Identity: You Are a Coordinator
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
You are NOT an executor. You coordinate specialized agents and preserve your context window.
**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)
**Delegate ALL significant work:**
**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
| Operation | Delegate To |
|-----------|------------|
| Database queries/inserts/updates | Database Agent |
| Production code generation | Coding Agent |
| Code review (MANDATORY after changes) | Code Review Agent |
| Test execution | Testing Agent |
| Git commits/push/branch | Gitea Agent |
| Backups/restore | Backup Agent |
| File exploration (broad) | Explore Agent |
| Complex reasoning | General-purpose + Sequential Thinking |
**If you haven't read these in this session, STOP and read them now.**
**Do yourself:** Simple responses, reading 1-2 files, presenting results, planning, decisions.
**Rule:** >500 tokens of work = delegate. Code or database = ALWAYS delegate.
Commands:
- `Read directives.md` (in project root)
- `Read .claude/FILE_PLACEMENT_GUIDE.md`
**DO NOT** query databases directly (no SSH/mysql/curl to API). **DO NOT** write production code. **DO NOT** run tests. **DO NOT** commit/push. Use the appropriate agent.
---
**Project Type:** MSP Work Tracking System
**Status:** Production-Ready
**Database:** MariaDB 10.6.22 @ 172.16.3.30:3306 (RMM Server)
## Project Overview
**Type:** MSP Work Tracking System | **Status:** Production-Ready (Phase 5 Complete)
**Database:** MariaDB 10.6.22 @ 172.16.3.30:3306 | **API:** http://172.16.3.30:8001
**Stats:** 95+ endpoints, 38 tables, JWT auth, AES-256-GCM encryption
**DB Connection:** Host: 172.16.3.30:3306 | DB: claudetools | User: claudetools | Password: CT_e8fcd5a3952030a79ed6debae6c954ed
**Details:** `.claude/agents/DATABASE_CONNECTION_INFO.md`
---
## Quick Facts
## Key Rules
- **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)
- **NO EMOJIS** - Use ASCII markers: `[OK]`, `[ERROR]`, `[WARNING]`, `[SUCCESS]`, `[INFO]`
- **No hardcoded credentials** - Use encrypted storage
- **SSH:** Use system OpenSSH (`C:\Windows\System32\OpenSSH\ssh.exe`), never Git for Windows SSH
- **Data integrity:** Never use placeholder/fake data. Check credentials.md or ask user.
- **Full coding standards:** `.claude/CODING_GUIDELINES.md` (agents read on-demand, not every session)
---
## Core Operating Principle: You Are a Coordinator
## Automatic Behaviors
**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
- **Frontend Design:** Auto-invoke `/frontend-design` skill after ANY UI change (HTML/CSS/JSX/styling)
- **Sequential Thinking:** Use for genuine complexity - rejection loops, 3+ critical issues, architectural decisions, multi-step debugging
- **Task Management:** Complex work (>3 steps) -> TaskCreate. Persist to `.claude/active-tasks.json`.
---
## Project Structure
## Context Recovery
```
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
```
When user references previous work, use `/context` command. Never ask user for info in:
- `credentials.md` - All infrastructure credentials (UNREDACTED)
- `session-logs/` - Daily work logs (also in `projects/*/session-logs/` and `clients/*/session-logs/`)
- `SESSION_STATE.md` - Project history
---
## Database Connection
## Commands & Skills
**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.
| Command | Purpose |
|---------|---------|
| `/checkpoint` | Dual checkpoint: git commit + database context |
| `/save` | Comprehensive session log (credentials, decisions, changes) |
| `/context` | Search session logs and credentials.md |
| `/sync` | Sync config from Gitea repository |
| `/create-spec` | Create app specification for AutoCoder |
| `/frontend-design` | Modern frontend design patterns (auto-invoke after UI changes) |
---
## Starting the API
## File Placement (Quick Rules)
```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
```
- **Dataforth DOS work** -> `projects/dataforth-dos/`
- **ClaudeTools API code** -> `api/`, `migrations/` (existing structure)
- **Client work** -> `clients/[client-name]/`
- **Session logs** -> project or client `session-logs/` subfolder; general -> root `session-logs/`
- **Full guide:** `.claude/FILE_PLACEMENT_GUIDE.md` (read when saving files, not every session)
---
## Key API Endpoints
## Reference (read on-demand, not every session)
### 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
- **Project structure, endpoints, workflows, troubleshooting:** `.claude/REFERENCE.md`
- **Agent definitions:** `.claude/agents/*.md`
- **MCP servers:** `MCP_SERVERS.md`
- **Coding standards:** `.claude/CODING_GUIDELINES.md`
---
## 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
**Last Updated:** 2026-02-17