# Claude Code Setup Reference for Patherly

This document catalogs all tools, plugins, and MCP servers available to Claude Code when developing Patherly, along with guidelines for their effective use.

**Last Updated**: 2026-01-29
**Project**: Patherly
**Working Directory**: `c:\Dev\Projects\patherly`
**Platform**: Windows (win32)
**IDE**: VSCode with Claude Code extension

---

## Core Built-In Tools

### File Operations

#### Read

- **Purpose**: Read file contents from the filesystem
- **Capabilities**:
  - Reads up to 2000 lines by default
  - Supports offset/limit for large files
  - Can read images (PNG, JPG), PDFs, and Jupyter notebooks
  - Returns content with line numbers
- **When to use**: Always read files before editing them; use for examining code, configs, or documentation

#### Edit

- **Purpose**: Perform exact string replacements in files
- **Capabilities**:
  - Replaces `old_string` with `new_string`
  - Supports `replace_all` for renaming variables
  - Preserves indentation
- **When to use**: Prefer editing over writing new files; ideal for targeted changes
- **Requirements**: Must read file first before editing

#### Write

- **Purpose**: Create new files or overwrite existing ones
- **Capabilities**: Writes complete file content
- **When to use**: Only for creating genuinely new files; avoid for existing files (use Edit instead)
- **Requirements**: Must read file first if it exists

#### NotebookEdit

- **Purpose**: Edit Jupyter notebook (.ipynb) cells
- **Capabilities**:
  - Replace, insert, or delete cells
  - Supports code and markdown cells
- **When to use**: Working with Jupyter notebooks in the project

### Search & Discovery

#### Glob

- **Purpose**: Fast file pattern matching
- **Capabilities**:
  - Supports glob patterns like `**/*.js`, `src/**/*.ts`
  - Returns files sorted by modification time
- **When to use**: Finding files by name patterns; use for specific needle queries
- **Example**: `**/*.py` to find all Python files

#### Grep

- **Purpose**: Powerful content search (built on ripgrep)
- **Capabilities**:
  - Full regex support
  - Filter by glob or file type
  - Output modes: content, files_with_matches, count
  - Context lines (-A, -B, -C)
  - Multiline matching support
- **When to use**: Searching for code patterns, function definitions, or specific strings
- **Important**: Use Task with Explore agent for open-ended exploratory searches

### Execution & System

#### Bash

- **Purpose**: Execute bash commands
- **Capabilities**:
  - Git operations
  - Package management (npm, pip, etc.)
  - Build commands
  - Testing
  - System operations
- **When to use**: Terminal operations, git, npm, docker, but NOT for file reading/searching (use specialized tools)
- **Best practices**:
  - Use `&&` for sequential dependent commands
  - Quote paths with spaces
  - Avoid `cd`; use absolute paths instead
  - Never skip git hooks unless explicitly requested

#### TaskOutput

- **Purpose**: Retrieve output from running/completed background tasks
- **When to use**: Check status of background shells or agents

#### TaskStop

- **Purpose**: Stop running background tasks
- **When to use**: Terminate long-running processes

### Planning & Task Management

#### TodoWrite

- **Purpose**: Create and manage structured task lists
- **Capabilities**:
  - Track tasks with states: pending, in_progress, completed
  - Organize complex multi-step work
- **When to use**:
  - Complex tasks with 3+ steps
  - Multi-file changes
  - User provides multiple tasks
  - Before starting work on each task
- **Best practice**: Mark todos completed immediately after finishing; maintain exactly ONE in_progress task at a time

#### EnterPlanMode / ExitPlanMode

- **Purpose**: Enter planning mode for implementation design
- **When to use**:
  - New feature implementation
  - Multiple valid approaches exist
  - Architectural decisions needed
  - Multi-file changes
  - Unclear requirements
- **When NOT to use**: Simple one-line fixes, trivial tasks, pure research

#### AskUserQuestion

- **Purpose**: Ask user questions during execution
- **Capabilities**:
  - Multiple choice questions (2-4 options)
  - Multi-select support
  - Collects user preferences and clarifications
- **When to use**: Need clarification on requirements, implementation choices, or ambiguous instructions

### Web & Information

#### WebFetch

- **Purpose**: Fetch and analyze web content
- **Capabilities**:
  - Converts HTML to markdown
  - 15-minute cache
- **Limitations**: WILL FAIL for authenticated/private URLs
- **When to use**: Public documentation, articles, reference materials
- **Note**: For GitHub URLs, prefer `gh` CLI via Bash

#### WebSearch

- **Purpose**: Search the web for current information
- **Capabilities**:
  - Access to up-to-date information beyond knowledge cutoff
  - Domain filtering (allowed/blocked)
- **Requirements**: MUST include "Sources:" section with markdown links in response
- **When to use**: Current events, recent documentation, external references

#### ToolSearch

- **Purpose**: Load deferred MCP tools before use
- **Capabilities**:
  - Keyword search mode (e.g., "slack", "notebook")
  - Direct selection mode (e.g., "select:NotebookEdit")
  - Required keyword mode (e.g., "+linear create issue")
- **When to use**: MANDATORY before calling any deferred/MCP tool
- **Important**: This is a BLOCKING requirement - must load tools before calling them

---

## Specialized Agents (via Task Tool)

The Task tool launches specialized agents for complex work. Each agent type has specific capabilities:

### Bash Agent

- **Specialty**: Command execution
- **Tools**: Bash only
- **When to use**: Git operations, complex command sequences

### general-purpose Agent

- **Specialty**: Complex research and multi-step tasks
- **Tools**: All tools
- **When to use**: Complex questions, keyword searches requiring multiple attempts

### Explore Agent

- **Specialty**: Fast codebase exploration
- **Tools**: Read-only tools (Glob, Grep, Read, etc.)
- **Thoroughness levels**: quick, medium, very thorough
- **When to use**:
  - "Where are errors handled?"
  - "How do API endpoints work?"
  - "What is the codebase structure?"
- **Critical**: Use this instead of manual Glob/Grep for exploratory searches

### Plan Agent

- **Specialty**: Implementation planning and architecture design
- **Tools**: Read-only tools
- **When to use**: Design implementation strategy, identify critical files, consider architectural trade-offs

### feature-dev Agents

- **code-architect**: Design feature architectures
- **code-explorer**: Analyze existing features and patterns
- **code-reviewer**: Review code for bugs and quality issues

---

## Available Skills (via Skill Tool)

Skills are invoked when users reference slash commands (e.g., `/commit`).

### feature-dev:feature-dev

- **Purpose**: Guided feature development with architecture focus
- **When to use**: Building new features from scratch

### frontend-design:frontend-design

- **Purpose**: Create production-grade frontend interfaces
- **When to use**: Building web components, pages, or applications
- **Goal**: Avoid generic AI aesthetics; create polished, distinctive designs

### Figma Integration Skills

- **figma:code-connect-components**: Map Figma designs to code components
- **figma:create-design-system-rules**: Generate custom design system rules
- **figma:implement-design**: Translate Figma designs to production code
- **Requirement**: Figma MCP server connection

---

## MCP Servers (Deferred Tools)

These tools must be loaded via ToolSearch before use.

### GitHub MCP Server

**Prefix**: `mcp__github__*`

**Available Operations**:

- **Repository**: create, fork, search repositories
- **Files**: get contents, create/update files, push files
- **Branches**: create, list commits
- **Issues**: create, list, update, get, add comments, search
- **Pull Requests**: create, list, get, merge, review, get files/status/comments
- **Search**: code, issues, users

**When to use**: GitHub operations beyond what `gh` CLI provides

### Filesystem MCP Server

**Prefix**: `mcp__filesystem__*`

**Available Operations**:

- **Read**: read_file, read_text_file, read_media_file, read_multiple_files
- **Write**: write_file, edit_file
- **Directory**: create, list, tree, list_with_sizes
- **Operations**: move, search files, get file info
- **Management**: list_allowed_directories

**When to use**: Complex filesystem operations; prefer built-in Read/Write/Edit for simple operations

### MS365 MCP Server

**Prefix**: `mcp__ms365__*`

**Available Operations**:

- **Authentication**: login, logout, verify, list/select/remove accounts
- **Teams**: chat operations, channel messages, team management
- **OneDrive**: file operations, Excel operations (worksheets, charts, ranges)
- **Outlook**: mail operations, calendar events, contacts
- **SharePoint**: site operations, lists, items
- **Planner**: tasks and plans
- **OneNote**: notebooks, sections, pages
- **Todo**: task lists and tasks

**When to use**: Integration with Microsoft 365 services

### PostgreSQL MCP Server

**Prefix**: `mcp__postgres__*`

**Connection Details**:

- **Connection String**: `postgresql://postgres:postgres@localhost:5432/patherly`
- **Container Name**: `patherly_postgres`
- **Database Version**: PostgreSQL 16 Alpine
- **Docker Requirement**: Docker Desktop must be running

**Available Operations**:

- **Query**: Execute SQL queries directly
- **Schema Inspection**: View tables, columns, indexes, constraints
- **JSONB Analysis**: Inspect tree_structure and session path data
- **Migration Verification**: Confirm Alembic migrations applied correctly
- **Data Debugging**: Check auth tokens, user roles, tree categories
- **Performance**: Analyze query plans, check indexes

**When to use**:

- Debugging database issues
- Inspecting JSONB tree structures in `trees` table
- Verifying user authentication data
- Checking session path tracking
- Validating migration results
- Analyzing full-text search indexes
- Direct SQL queries for complex operations

**Common Use Cases**:

```sql
-- View all active trees with their categories
SELECT id, name, category, version, is_active, usage_count FROM trees WHERE is_active = true;

-- Inspect JSONB tree structure
SELECT id, name, tree_structure FROM trees WHERE id = '<uuid>';

-- Check user accounts
SELECT id, email, name, role, team_id, created_at FROM users;

-- View active sessions with user and tree info
SELECT s.id, u.email, t.name, s.ticket_number, s.started_at, s.completed_at
FROM sessions s
JOIN users u ON s.user_id = u.id
JOIN trees t ON s.tree_id = t.id
WHERE s.completed_at IS NULL;

-- Analyze session path tracking (JSONB)
SELECT id, ticket_number, path_taken, decisions FROM sessions WHERE id = '<uuid>';
```

### Fetch MCP Server

**Status**: ❌ Failed to install

**Alternative**: Use Bash tool with `curl` or PowerShell's `Invoke-RestMethod` for API testing

**Example - Testing FastAPI endpoints**:

```bash
# PowerShell example
$response = Invoke-RestMethod -Uri "http://localhost:8000/api/v1/trees" -Method GET -Headers @{"Authorization"="Bearer <token>"}

# Curl example (if available)
curl -X GET "http://localhost:8000/api/v1/trees" -H "Authorization: Bearer <token>"
```

**When to use Bash for API testing**:

- Testing authentication flow (register, login, refresh)
- Verifying endpoint responses
- Testing file uploads for attachments
- Validating export formats (md/txt/html)
- Checking error handling

---

## Project-Specific Context: Patherly

### Project Overview

**Patherly** is a troubleshooting decision tree web application designed for MSP (Managed Service Provider) engineers. The application allows engineers to create, manage, and navigate through decision trees for common IT support scenarios, improving troubleshooting consistency and efficiency.

### Technology Stack

**Backend (Complete)**:

- **Framework**: FastAPI (Python)
- **Database**: PostgreSQL 16 Alpine
- **ORM**: SQLAlchemy 2.0 (async)
- **Authentication**: JWT tokens (15-min access, 7-day refresh)
- **Password Hashing**: bcrypt (via passlib, pinned to 4.1.2 for compatibility)
- **API Endpoints**: 18 RESTful endpoints
- **Containerization**: Docker (patherly_postgres container)
- **Migrations**: Alembic

**Frontend (Complete + Tree Editor)**:

- **Framework**: React 18 + Vite + TypeScript
- **Styling**: Tailwind CSS + shadcn/ui CSS variables
- **State Management**: Zustand with immer + zundo (undo/redo)
- **Routing**: React Router v6
- **API Client**: Axios with token interceptors
- **Status**: Core features complete, Tree Editor implemented

**Infrastructure**:

- **Development**: Local Docker PostgreSQL
- **Deployment Target**: Render (dev) / Railway Pro (production)

### Database Schema

**5 Core Tables**:

1. **users**: User accounts with roles (admin, engineer, viewer), team associations
2. **teams**: Team groupings for multi-tenant support
3. **trees**: Decision trees with JSONB `tree_structure` field, versioning, categories
4. **sessions**: Troubleshooting sessions with path tracking (JSONB)
5. **attachments**: File attachments linked to sessions

**Key Features**:

- UUID primary keys via PostgreSQL `gen_random_uuid()`
- JSONB for flexible tree structures and session paths
- Full-text search using PostgreSQL `to_tsvector`
- Soft deletes for trees (`is_active` flag - set to false on delete)
- Timezone-aware timestamps (all DateTime fields use `DateTime(timezone=True)` with UTC storage)

### Current Development Phase

**Phase 1: Backend + Frontend MVP** - ✅ **COMPLETE**

- All 18 API endpoints implemented and verified
- Database schema finalized with timezone-aware timestamps
- Authentication system working (JWT with bcrypt, role-based access)
- 40+ integration tests (all passing) with comprehensive coverage
- Production logging with correlation IDs
- React frontend with tree navigation, session management, export

**Phase 2: Tree Editor** - 🔄 **IN PROGRESS**

- ✅ Zustand store with immer middleware + zundo (undo/redo)
- ✅ Form-based node editing (Decision, Action, Solution types)
- ✅ Visual tree preview with solution connection indicators
- ✅ NodePicker with type-grouped dropdown
- ✅ SharedLinksMap for detecting nodes with multiple sources
- ✅ Modal with scrollable content, fixed header/footer
- ✅ Markdown rendering in session player and node editor
- ✅ Dark mode / theme toggle
- ⏳ Validation polish (required fields, orphan detection)

**Phase 2 Remaining** - ⏳ **Planned**

- Team management features
- Mobile responsive improvements
- ~~User preferences (dark mode)~~ ✅ **COMPLETE**

### Backend File Structure

```
backend/
├── alembic/                          # Database migrations
│   ├── versions/
│   │   └── 001_initial_schema.py
│   └── env.py
├── app/
│   ├── api/
│   │   ├── endpoints/
│   │   │   ├── auth.py               # /api/v1/auth/* (register, login, refresh)
│   │   │   ├── trees.py              # /api/v1/trees/* (CRUD, search)
│   │   │   └── sessions.py           # /api/v1/sessions/* (tracking, export)
│   │   ├── deps.py                   # Auth dependencies (JWT validation)
│   │   └── router.py                 # Main API router
│   ├── core/
│   │   ├── config.py                 # Pydantic settings
│   │   ├── database.py               # Async SQLAlchemy setup
│   │   ├── security.py               # JWT + bcrypt utilities
│   │   ├── logging_config.py         # Structured logging configuration
│   │   └── middleware.py             # Request logging middleware
│   ├── models/                       # SQLAlchemy models (timezone-aware)
│   ├── schemas/                      # Pydantic schemas
│   └── main.py                       # FastAPI app entry point
├── tests/                            # Integration tests (40+ tests)
├── logs/                             # Log files (created at runtime)
├── docker-compose.yml                # PostgreSQL container definition
└── requirements.txt                  # Production dependencies
```

### Frontend File Structure

```
frontend/
├── src/
│   ├── api/                          # API client layer
│   │   ├── client.ts                 # Axios instance with auth interceptors
│   │   ├── auth.ts                   # Auth endpoints
│   │   ├── trees.ts                  # Tree endpoints
│   │   └── sessions.ts               # Session endpoints
│   ├── components/
│   │   ├── common/
│   │   │   └── Modal.tsx             # Reusable modal (scrollable body, fixed header/footer)
│   │   ├── layout/                   # AppLayout, ProtectedRoute
│   │   ├── tree-editor/              # Tree Editor components
│   │   │   ├── TreeEditorLayout.tsx  # Split-view container
│   │   │   ├── TreeMetadataForm.tsx  # Name, description, category
│   │   │   ├── NodeList.tsx          # Node list with CRUD actions
│   │   │   ├── NodeEditorModal.tsx   # Modal wrapper for node editing
│   │   │   ├── NodeFormDecision.tsx  # Decision node fields
│   │   │   ├── NodeFormAction.tsx    # Action node fields
│   │   │   ├── NodeFormResolution.tsx # Solution node fields
│   │   │   ├── DynamicArrayField.tsx # Reusable array input
│   │   │   └── NodePicker.tsx        # Type-grouped node selector
│   │   └── tree-preview/             # Visual preview components
│   │       ├── TreePreviewPanel.tsx  # Preview container + SharedLinksMap
│   │       └── TreePreviewNode.tsx   # Node cards with solution indicators
│   ├── pages/
│   │   ├── TreeEditorPage.tsx        # /trees/new and /trees/:id/edit
│   │   ├── TreeLibraryPage.tsx       # Tree browsing
│   │   ├── TreeNavigationPage.tsx    # Tree traversal
│   │   └── ...                       # Other pages
│   ├── store/
│   │   ├── authStore.ts              # Auth state (Zustand + persist)
│   │   └── treeEditorStore.ts        # Tree editor state (Zustand + immer + zundo)
│   ├── types/                        # TypeScript types
│   │   ├── tree.ts                   # TreeStructure, TreeNode, etc.
│   │   └── index.ts                  # Barrel exports
│   ├── router.tsx                    # React Router configuration
│   └── main.tsx                      # Entry point
├── tailwind.config.js
└── vite.config.ts
```

### Development Workflow

**Starting the Backend**:

```bash
# 1. Start PostgreSQL container
cd backend
docker-compose up -d

# 2. Activate Python virtual environment
venv\Scripts\activate          # Windows
# source venv/bin/activate     # Linux/Mac

# 3. Run migrations (if not already applied)
alembic upgrade head

# 4. Start FastAPI development server
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# 5. Access API documentation
# http://localhost:8000/api/docs
```

**Database Connection**:

- **Host**: localhost:5432
- **Database**: patherly
- **User**: postgres
- **Password**: postgres
- **Container**: patherly_postgres

### Recent Work & Git History

**Recent Commits**:

```
a3efe68 Committing before moving to local disk
a6fc86c Pin bcrypt version to 4.1.2 for passlib compatibility
fa632da Fix backend: add passlib/bcrypt, fix datetime timezone issues
```

**Key Issues Resolved** (January 28, 2026):

- **DateTime Bug Fix**: Fixed timezone-naive/timezone-aware mixing that caused Internal Server Errors
  - Updated all models to use `DateTime(timezone=True)` with UTC storage
  - Changed all datetime defaults to `lambda: datetime.now(timezone.utc)`
  - Affects: Session completion, session updates, all timestamp fields
- **Production Logging**: Added comprehensive logging with request correlation IDs and log rotation
- **Integration Tests**: Created 40+ tests covering all endpoints with good coverage
- **Schema Documentation**: Corrected `is_active` vs `is_deleted` column references
- **Bcrypt Compatibility**: Version pinned to 4.1.2 for passlib compatibility

**Current Repository State**:

- Branch: main
- Working tree: Multiple modified files (models, main.py, tests/, PROGRESS.md, CLAUDE-SETUP.md)
- Backend: **Fully tested and operational** - all 18 endpoints verified
- Tests: 40+ integration tests with pytest and coverage reporting
- Logging: Production-ready with correlation IDs and rotation
- Frontend: Not started

### File Reference Format

When referencing code in VSCode, use markdown links:

- Files: `[filename.py](backend/app/api/endpoints/auth.py)`
- Specific lines: `[auth.py:42](backend/app/api/endpoints/auth.py#L42)`
- Line ranges: `[auth.py:42-51](backend/app/api/endpoints/auth.py#L42-L51)`
- Folders: `[backend/app/api/](backend/app/api/)`

### Important Reference Files

- **[PROGRESS.md](PROGRESS.md)**: Development progress tracker
- **[02-TECHNICAL-ARCHITECTURE.md](02-TECHNICAL-ARCHITECTURE.md)**: Complete technical specification
- **[05-QUESTIONS-AND-ACTION-ITEMS.md](05-QUESTIONS-AND-ACTION-ITEMS.md)**: Design decisions log
- **[TS-EXAMPLES.md](TS-EXAMPLES.md)**: 5 example troubleshooting trees for Phase 1b
- **[backend/README.md](backend/README.md)**: Backend setup instructions

---

## Development Guidelines

### General Workflow

1. **Read First**: Always read files before editing
2. **Plan Complex Tasks**: Use TodoWrite for multi-step work
3. **Use Specialized Tools**: Prefer dedicated tools over bash commands for file operations
4. **Explore Efficiently**: Use Task with Explore agent for codebase exploration
5. **Parallel Execution**: Make independent tool calls in parallel when possible

### Code Modification Principles

- **Avoid Over-Engineering**: Only make requested changes
- **No Premature Abstraction**: Don't create utilities for one-time operations
- **Security First**: Watch for command injection, XSS, SQL injection, OWASP Top 10
- **Simplicity**: Keep solutions focused and minimal
- **No Unnecessary Additions**: Don't add error handling for impossible scenarios

### Git Best Practices

- **Never** update git config
- **Never** run destructive commands (push --force, reset --hard) without explicit request
- **Never** skip hooks (--no-verify, --no-gpg-sign)
- **Always** create NEW commits (don't amend unless requested)
- **Prefer** staging specific files over `git add -A` or `git add .`
- **Only commit** when explicitly requested
- **Include** co-author tag: `Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>`

### Pull Request Workflow

1. Run `git status`, `git diff`, check branch state
2. Analyze ALL commits from branch divergence (not just latest)
3. Keep PR title under 70 characters
4. Use HEREDOC for PR body with format:

   ```
   ## Summary
   <1-3 bullet points>

   ## Test plan
   [Checklist of testing TODOs]

   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   ```

### Communication Style

- **Concise**: Short, focused responses for CLI display
- **No Emojis**: Unless explicitly requested
- **No Time Estimates**: Never predict how long tasks will take
- **Objective**: Technical accuracy over validation
- **Direct**: Use markdown formatting, output text directly (not via echo/bash)

### When to Ask for Help

- **User Questions**: Use AskUserQuestion for clarifications
- **Planning**: Use EnterPlanMode for complex implementation decisions
- **Feedback**: Direct users to <https://github.com/anthropics/claude-code/issues>

---

## Quick Reference: Tool Selection Decision Tree

```
Need to find files by name pattern?
  → Use Glob

Need to search for code content?
  → Specific query? → Use Grep
  → Exploratory search? → Use Task (Explore agent)

Need to read a file?
  → Use Read (not cat)

Need to modify existing file?
  → Use Edit (not sed/awk)

Need to create new file?
  → Use Write (not echo/heredoc)

Need to execute command/git/npm?
  → Use Bash

Need to plan complex implementation?
  → Use EnterPlanMode

Need to track multi-step task?
  → Use TodoWrite

Need GitHub/MS365/filesystem MCP operations?
  → First: ToolSearch to load tool
  → Then: Call the loaded MCP tool

Need to ask user a question?
  → Use AskUserQuestion
```

---

## Notes for Future Sessions

- **Context Persistence**: Conversations have unlimited context through automatic summarization
- **Tool Results**: May include `<system-reminder>` tags with useful information
- **Model**: Powered by Claude Sonnet 4.5 (claude-sonnet-4-5-20250929)
- **Knowledge Cutoff**: January 2025
- **Current Date**: Always use 2026 in current date calculations

---

## Security Policy

**Defensive Security Only**

- Assist with security analysis, detection rules, vulnerability explanations
- Create defensive tools and security documentation
- **Refuse**: Code for malicious use, credential harvesting, bulk SSH key/cookie/wallet crawling

---

*This reference guide should be consulted at the start of each session to ensure effective use of all available tools and maintain consistency with project conventions.*
