From 23c3bd92d0b34fbd5e963041af54f2e095c3b4e4 Mon Sep 17 00:00:00 2001 From: "centron\\schwoerer" Date: Fri, 30 Jan 2026 11:28:04 +0100 Subject: [PATCH] docs: refactor documentation for Foundry VTT + PF1e project - Rewrite README.md to focus on Foundry VTT + Pathfinder 1e development - Refactor QUICKSTART.md as practical setup guide (5 minutes) - Add project-specific sections: setup, macros, PF1 system, API reference - Include development workflow and common tasks - Add troubleshooting guide for Foundry-specific issues - Remove generic Claude Code setup documentation (CLAUDE_CODE_SETUP_COMPLETE.md, CLAUDE_TEMPLATE.md, MCP_SERVERS_GUIDE.md, MCP_DOCUMENTATION_SUMMARY.md, .gitignore.README.md) - Keep CLAUDE.md as comprehensive reference documentation Documentation now aligns with project scope: Foundry VTT v11.315 + Pathfinder 1e v10.8 + custom macros. Co-Authored-By: Claude Haiku 4.5 --- .gitignore.README.md | 154 --- CLAUDE_CODE_SETUP_COMPLETE.md | 1981 --------------------------------- CLAUDE_TEMPLATE.md | 1095 ------------------ MCP_DOCUMENTATION_SUMMARY.md | 329 ------ MCP_SERVERS_GUIDE.md | 1827 ------------------------------ QUICKSTART.md | 809 ++++---------- README.md | 882 +++++++-------- 7 files changed, 636 insertions(+), 6441 deletions(-) delete mode 100644 .gitignore.README.md delete mode 100644 CLAUDE_CODE_SETUP_COMPLETE.md delete mode 100644 CLAUDE_TEMPLATE.md delete mode 100644 MCP_DOCUMENTATION_SUMMARY.md delete mode 100644 MCP_SERVERS_GUIDE.md diff --git a/.gitignore.README.md b/.gitignore.README.md deleted file mode 100644 index c952fba3..00000000 --- a/.gitignore.README.md +++ /dev/null @@ -1,154 +0,0 @@ -# .gitignore Configuration for JPD Portal - -This document explains the .gitignore configuration for the JPD Portal project. - -## Critical Files Protected - -The following sensitive files are **NEVER** committed to version control: - -### ๐Ÿ” Security & Credentials -- `src/JPD.env` - Contains API keys (Jira, Confluence, Claude API) -- `*.env` files - All environment variable files -- `secrets.json` - ASP.NET Core user secrets - -### ๐Ÿ’พ Databases & Data -- `src/JpdPortal/data/vectors.db` - SQLite vector embeddings database -- `src/JpdPortal/data/uploads/*` - User-uploaded requirements files (except .gitkeep) -- All `.db`, `.sqlite`, `.sqlite3` files - -### ๐Ÿ—๏ธ Build Artifacts -- `bin/` and `obj/` directories - .NET build outputs -- `Debug/` and `Release/` - Build configurations -- `*.dll`, `*.exe`, `*.pdb` - Compiled binaries - -## Directory Structure Preservation - -Some directories need to exist but their contents should not be committed: - -``` -src/JpdPortal/data/ -โ”œโ”€โ”€ uploads/ -โ”‚ โ””โ”€โ”€ .gitkeep โ† Tracked to preserve directory -โ”‚ โ””โ”€โ”€ *.txt โ† Ignored (user uploads) -โ””โ”€โ”€ vectors.db โ† Ignored (SQLite database) -``` - -The `.gitkeep` file ensures the `uploads/` directory structure is preserved in git. - -## Pattern Categories - -The .gitignore is organized into these sections: - -1. **Claude Code** - IDE-specific files -2. **Project-Specific Sensitive Files** - JPD.env, databases, uploads -3. **.NET Core / ASP.NET Core** - Build artifacts, Visual Studio files -4. **AI/ML Specific** - ONNX models, training artifacts, vector databases -5. **Blazor Specific** - WebAssembly cache, generated assets -6. **Testing** - Test results and coverage reports -7. **Environment Variables & Secrets** - All .env files -8. **Database Files** - SQLite and other database files -9. **Logs** - Application log files -10. **OS Files** - Windows, macOS, Linux system files -11. **Backup Files** - .bak, .old, .tmp files -12. **Node.js** - npm packages (if used for frontend) -13. **Python** - __pycache__, venv (if used for ML scripts) - -## Already Tracked Files - -If you see modified files in `bin/` or `obj/` directories that should be ignored, they were tracked before the .gitignore was updated. To remove them: - -```bash -# Remove build artifacts from git tracking -git rm -r --cached src/JpdPortal/bin/ -git rm -r --cached src/JpdPortal/obj/ - -# Commit the changes -git commit -m "chore: remove build artifacts from git tracking" -``` - -**Note**: The `--cached` flag removes files from git tracking but keeps them on your local filesystem. - -## Verifying Ignore Patterns - -To check if a file will be ignored: - -```bash -# Check specific files -git check-ignore -v src/JPD.env -git check-ignore -v src/JpdPortal/data/vectors.db - -# Check entire directory -git check-ignore -v src/JpdPortal/bin/* -``` - -Expected output for ignored files: -``` -.gitignore:199:*.env src/JPD.env -``` - -## Best Practices - -### โœ… DO: -- Always verify `src/JPD.env` is NOT staged before committing -- Check `git status` before commits to ensure no sensitive data -- Use `git check-ignore` to verify patterns -- Keep the .gitkeep file in the uploads directory - -### โŒ DON'T: -- Never commit API keys or credentials -- Never force-add ignored files with `git add -f` -- Don't commit build artifacts (bin/, obj/) -- Don't commit database files with user data -- Don't commit user-uploaded files - -## Emergency: Removing Sensitive Data - -If you accidentally committed sensitive data (like JPD.env), you need to remove it from git history: - -```bash -# Remove file from git history (WARNING: rewrites history) -git filter-branch --force --index-filter \ - "git rm --cached --ignore-unmatch src/JPD.env" \ - --prune-empty --tag-name-filter cat -- --all - -# Force push (if already pushed to remote) -git push origin --force --all -``` - -**Better approach**: Use GitHub's BFG Repo-Cleaner or contact repository admin. - -## Environment Setup for New Developers - -When cloning this repository: - -1. Copy the environment template: - ```bash - cp src/JPD.env.example src/JPD.env - ``` - -2. Edit `src/JPD.env` with your credentials - -3. Verify it's ignored: - ```bash - git status - # Should NOT show JPD.env as untracked - ``` - -4. Create necessary directories: - ```bash - mkdir -p src/JpdPortal/data/uploads - ``` - -## Maintenance - -Review and update this .gitignore when: -- Adding new services with credentials -- Adding new ML models or data storage -- Changing build output directories -- Adding new tools or frameworks -- Team reports accidental commits of ignored files - ---- - -**Last Updated**: 2025-10-20 -**Project**: JPD Portal v1.0.0 diff --git a/CLAUDE_CODE_SETUP_COMPLETE.md b/CLAUDE_CODE_SETUP_COMPLETE.md deleted file mode 100644 index 15e0c268..00000000 --- a/CLAUDE_CODE_SETUP_COMPLETE.md +++ /dev/null @@ -1,1981 +0,0 @@ -# Claude Code Complete Setup Guide - -> **Comprehensive documentation for the Claude Code Setup project** -> **Version**: 3.0.0 | **Last Updated**: 2025-10-20 -> **Completeness**: ~95% of Claude Code capabilities implemented - ---- - -## Table of Contents - -1. [Overview](#overview) -2. [Project Structure](#project-structure) -3. [Core Features](#core-features) -4. [MCP Servers](#mcp-servers) -5. [Agents & Subagents](#agents--subagents) -6. [Slash Commands](#slash-commands) -7. [Output Styles](#output-styles) -8. [Hooks System](#hooks-system) -9. [Templates](#templates) -10. [Configuration](#configuration) -11. [Memory & Context](#memory--context) -12. [Advanced Features](#advanced-features) -13. [Best Practices](#best-practices) -14. [Troubleshooting](#troubleshooting) - ---- - -## Overview - -### What is This Project? - -This is a **production-ready Claude Code setup** demonstrating comprehensive configuration of all major features, including: - -- โœ… 8 MCP servers configured (code navigation, memory, documentation, automation) -- โœ… 8 specialized agents (architecture, code review, debugging, security, testing) -- โœ… 9 slash commands (adr, analyze, review, implement, test, optimize, explain, scaffold) -- โœ… 6 custom output styles (concise, professional, verbose, learning, explanatory, security) -- โœ… 6 event hooks (session lifecycle, bash commands, file operations, stop tracking) -- โœ… Comprehensive templates for extending all features -- โœ… Custom status line and plugin marketplace access -- โœ… Automatic status summaries showing tool usage for every task - -### Claude Code Capabilities Overview - -Claude Code is an AI-powered development assistant that operates through: - -**Core Mechanisms**: -- **Tools**: File operations (Read, Write, Edit), code search (Grep, Glob), shell execution (Bash) -- **MCP Servers**: External integrations extending Claude's capabilities -- **Agents/Subagents**: Specialized AI assistants for specific domains -- **Slash Commands**: User-invoked workflows and routines -- **Output Styles**: Customizable response behaviors -- **Hooks**: Event-driven automation -- **Memory**: Persistent and temporary context storage - ---- - -## Project Structure - -``` -Claude Code Setup/ -โ”‚ -โ”œโ”€โ”€ .claude/ # Main Claude Code configuration directory -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ agents/ # Specialized AI agents (8 agents) -โ”‚ โ”‚ โ”œโ”€โ”€ architect.md # System design & technical planning -โ”‚ โ”‚ โ”œโ”€โ”€ code-reviewer.md # Code quality & review -โ”‚ โ”‚ โ”œโ”€โ”€ debugger.md # Bug diagnosis & fixing -โ”‚ โ”‚ โ”œโ”€โ”€ documentation-writer.md # Technical documentation -โ”‚ โ”‚ โ”œโ”€โ”€ project-manager.md # Project coordination -โ”‚ โ”‚ โ”œโ”€โ”€ refactoring-specialist.md # Code improvement -โ”‚ โ”‚ โ”œโ”€โ”€ security-analyst.md # Security analysis -โ”‚ โ”‚ โ”œโ”€โ”€ test-engineer.md # Testing strategy -โ”‚ โ”‚ โ””โ”€โ”€ .AGENT_TEMPLATE.md # Template for new agents -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ commands/ # Slash commands (8 commands) -โ”‚ โ”‚ โ”œโ”€โ”€ analyze.md # Comprehensive code analysis -โ”‚ โ”‚ โ”œโ”€โ”€ explain.md # Code explanation -โ”‚ โ”‚ โ”œโ”€โ”€ implement.md # Feature implementation -โ”‚ โ”‚ โ”œโ”€โ”€ optimize.md # Performance optimization -โ”‚ โ”‚ โ”œโ”€โ”€ review.md # Code review -โ”‚ โ”‚ โ”œโ”€โ”€ scaffold.md # Project scaffolding -โ”‚ โ”‚ โ”œโ”€โ”€ setup-info.md # Display setup information -โ”‚ โ”‚ โ”œโ”€โ”€ test.md # Test execution -โ”‚ โ”‚ โ””โ”€โ”€ .COMMANDS_TEMPLATE.md # Template for new commands -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ output-styles/ # Custom output behaviors (6 styles) -โ”‚ โ”‚ โ”œโ”€โ”€ concise.md # Brief responses -โ”‚ โ”‚ โ”œโ”€โ”€ professional.md # Formal tone -โ”‚ โ”‚ โ”œโ”€โ”€ verbose.md # Detailed explanations -โ”‚ โ”‚ โ”œโ”€โ”€ explanatory.md # Educational insights -โ”‚ โ”‚ โ”œโ”€โ”€ learning.md # Interactive learning mode -โ”‚ โ”‚ โ”œโ”€โ”€ security-reviewer.md # Security-focused -โ”‚ โ”‚ โ””โ”€โ”€ .OUTPUT_STYLES_TEMPLATE.md # Template for new styles -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ skills/ # Agent skills (model-invoked) -โ”‚ โ”‚ โ””โ”€โ”€ .SKILL_TEMPLATE.md # Template for new skills -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ hooks/ # Event automation (6 hooks) -โ”‚ โ”‚ โ”œโ”€โ”€ session-start.sh # Session initialization -โ”‚ โ”‚ โ”œโ”€โ”€ session-end.sh # Session cleanup -โ”‚ โ”‚ โ”œโ”€โ”€ stop.sh # Stop event logging -โ”‚ โ”‚ โ”œโ”€โ”€ pre-bash.sh # Before bash commands -โ”‚ โ”‚ โ”œโ”€โ”€ post-write.sh # After file writes -โ”‚ โ”‚ โ””โ”€โ”€ user-prompt-submit.sh # After prompt submission -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ tools/ # Utility scripts -โ”‚ โ”‚ โ”œโ”€โ”€ start-memory.ps1 # PowerShell memory MCP launcher -โ”‚ โ”‚ โ””โ”€โ”€ statusline.sh # Custom status line script -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ logs/ # Session logs -โ”‚ โ”‚ โ”œโ”€โ”€ session.log # Session activity -โ”‚ โ”‚ โ”œโ”€โ”€ bash.log # Bash command log -โ”‚ โ”‚ โ””โ”€โ”€ writes.log # File write log -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ settings.json # Main configuration (shared) -โ”‚ โ”œโ”€โ”€ settings.local.json # Local configuration (personal) -โ”‚ โ”œโ”€โ”€ statusline.sh # Status line configuration -โ”‚ โ”‚ -โ”‚ โ””โ”€โ”€ [Documentation Files] # Various guides (see below) -โ”‚ -โ”œโ”€โ”€ .mcp.json # MCP servers configuration (9 servers) -โ”œโ”€โ”€ CLAUDE.md # Project instructions for Claude -โ”œโ”€โ”€ CLAUDE_TEMPLATE.md # Template for CLAUDE.md files -โ””โ”€โ”€ TEMPLATES_SUMMARY.md # Quick reference for all templates -``` - -### Documentation Files (in .claude/) - -- **TEMPLATES_README.md** - Master guide for all templates -- **agents/MCP_USAGE_TEMPLATES.md** - MCP usage templates for agents -- **CHECKPOINTING_GUIDE.md** - Session checkpointing guide -- **SETUP_COMPLETE.md** - Setup completion summary -- **PLUGIN_SETUP.md** - Plugin marketplace guide -- **STATUS_LINE_SETUP.md** - Status line customization -- **TEMPLATE_CAPABILITIES_ANALYSIS.md** - Template review analysis - ---- - -## Core Features - -### 1. File Operations - -Claude Code has direct file access through specialized tools: - -**Read Tool**: -- Read any file by absolute path -- Support for images, PDFs, Jupyter notebooks -- Optional line offset and limit for large files - -**Write Tool**: -- Create new files (overwrites existing) -- Must read file first before writing existing files - -**Edit Tool**: -- Exact string replacement -- Must read file first -- Supports `replace_all` for renaming - -**Glob Tool**: -- Fast file pattern matching -- Returns files sorted by modification time -- Examples: `**/*.js`, `src/**/*.ts` - -**Grep Tool**: -- Built on ripgrep for fast searching -- Supports regex patterns -- Context lines (-A, -B, -C options) -- Multiple output modes (content, files_with_matches, count) - -### 2. Shell Execution - -**Bash Tool**: -- Execute shell commands with timeout (default 2 min, max 10 min) -- Background execution supported -- Parallel execution for independent commands -- Sequential execution with `&&` for dependencies - -**Pre-approved commands** (no permission needed): -- `ls`, `dir`, `git status`, `git diff`, `git log` -- `mkdir`, `echo`, `findstr`, `tree` -- `npx`, `uvx`, `where` - -### 3. Specialized Tools - -- **WebSearch**: Search the web for current information -- **WebFetch**: Retrieve and process web content -- **SlashCommand**: Execute custom slash commands -- **Task**: Launch specialized subagents -- **TodoWrite**: Manage task lists during sessions -- **NotebookEdit**: Edit Jupyter notebooks - ---- - -## MCP Servers - -### Overview - -This project has **8 MCP servers** configured, providing extensive capabilities beyond Claude's native tools. - -### 1. Serena MCP - -**Purpose**: IDE assistant with code navigation and persistent memory - -**Command**: `uvx --from git+https://github.com/oraios/serena serena start-mcp-server` - -**Capabilities**: - -*Code Navigation*: -- `find_symbol` - Locate code symbols by name/pattern -- `find_referencing_symbols` - Find all references to a symbol -- `get_symbols_overview` - Get file structure overview -- `search_for_pattern` - Search for patterns in code -- `rename_symbol` - Safely rename across codebase -- `replace_symbol_body` - Replace function/class body -- `insert_after_symbol` / `insert_before_symbol` - Add code at specific locations - -*Persistent Memory*: -- `write_memory` - Store information that persists across sessions -- `read_memory` - Recall stored information -- `list_memories` - Browse all memories -- `delete_memory` - Remove outdated information - -**Storage**: `.serena/memories/` (survives across sessions) - -**Best Used For**: -- โœ… Architectural Decision Records (ADRs) -- โœ… Code review findings and summaries -- โœ… Lessons learned from implementations -- โœ… Project-specific patterns discovered -- โœ… Technical debt registry -- โœ… Security audit results -- โœ… Performance optimization notes - -**Current Memory**: `serena-persistence-test` - -### 2. Sequential Thinking MCP - -**Purpose**: Enhanced reasoning and complex problem-solving - -**Command**: `npx -y @modelcontextprotocol/server-sequential-thinking` - -**Capabilities**: -- `sequentialthinking` - Multi-step reasoning with revision capability -- Adjust thought count dynamically -- Branch and revise previous thoughts -- Generate and verify hypotheses - -**Best Used For**: -- Complex architectural decisions -- Multi-step debugging -- Design pattern selection -- Security analysis - -### 3. Database Server MCP - -**Purpose**: Database query support - -**Command**: `npx -y @executeautomation/database-server` - -**Note**: Requires database connection configuration - -### 4. Context7 MCP - -**Purpose**: Real-time library documentation lookup - -**Command**: `npx -y @upstash/context7-mcp` - -**Capabilities**: -- `resolve-library-id` - Find library identifier for documentation -- `get-library-docs` - Get current framework/library documentation - -**Best Used For**: -- Learning new frameworks -- Getting up-to-date API references -- Finding best practices for libraries -- Code examples from official docs - -**API Key**: Configured in `.mcp.json` - -### 5. Memory MCP (Knowledge Graph) - -**Purpose**: Temporary in-memory knowledge graph for current session - -**Command**: `powershell -ExecutionPolicy Bypass -File .\.claude\tools\start-memory.ps1` - -**Capabilities**: -- `create_entities` - Create entities (Features, Classes, Services, etc.) -- `create_relations` - Define relationships between entities -- `add_observations` - Add details to entities -- `search_nodes` - Search the knowledge graph -- `read_graph` - View entire graph state -- `open_nodes` - Retrieve specific entities -- `delete_entities` / `delete_relations` / `delete_observations` - Remove items - -**Storage**: In-memory only, **cleared after session ends** - -**Best Used For**: -- โœ… Current conversation context -- โœ… Temporary analysis during current task -- โœ… Entity relationships in current work -- โœ… Cross-file refactoring state -- โœ… Session-specific tracking - -**Storage Location**: `.mcp-data\memory\` (managed by PowerShell script) - -### 6. Fetch MCP - -**Purpose**: Web content retrieval and processing - -**Command**: `uvx mcp-server-fetch` - -**Capabilities**: -- `fetch` - Retrieve URLs and convert to markdown -- Support for HTML parsing -- Configurable content length - -**Best Used For**: -- API documentation scraping -- Web content analysis -- Integration documentation - -### 7. Windows MCP - -**Purpose**: Windows desktop automation - -**Command**: `uv --directory ./.windows-mcp run main.py` - -**Capabilities**: -- Launch applications -- PowerShell execution -- Desktop state capture -- Clipboard operations -- Mouse and keyboard control -- Window management -- Screen scraping - -**Best Used For**: -- GUI automation -- Desktop testing -- Windows-specific operations - -### 8. Playwright MCP - -**Purpose**: Browser automation and testing - -**Command**: `npx -y @playwright/mcp` - -**Capabilities**: -- Browser navigation and interaction -- Form filling and clicking -- Screenshot capture -- Network request monitoring -- Console message capture -- File uploads -- JavaScript evaluation - -**Best Used For**: -- E2E testing -- Web scraping -- UI automation -- Browser-based workflows - -### MCP Quick Decision Tree - -**Question**: Should this information exist next week? -- **YES** โ†’ Use Serena `write_memory` -- **NO** โ†’ Use Memory graph - -**Question**: Am I navigating or editing code? -- **YES** โ†’ Use Serena code functions - -**Question**: Am I building temporary context for current task? -- **YES** โ†’ Use Memory graph - -**Question**: Do I need current library documentation? -- **YES** โ†’ Use Context7 - -**Question**: Do I need to automate a browser? -- **YES** โ†’ Use Playwright - ---- - -## Agents & Subagents - -### Overview - -**8 specialized agents** handle specific domains, each with isolated context and focused expertise. - -### How Agents Work - -**Invocation**: -- **Automatic**: Claude invokes based on task description matching -- **Manual**: User explicitly requests with "Use the [agent-name] agent to..." - -**Isolation**: Each agent operates in its own context window, preventing main conversation pollution. - -**Configuration**: Agents can have custom: -- `allowed-tools` - Restricted tool access -- `model` - Specific Claude model (Sonnet, Opus, Haiku) -- `description` - Triggers automatic invocation - -### Available Agents - -#### 1. Architect Agent - -**File**: [.claude/agents/architect.md](.claude/agents/architect.md) - -**Purpose**: System design, architecture planning, technical decisions - -**Keywords**: architecture, design, technical decisions, scalability, system design - -**Responsibilities**: -- System architecture design -- Technology evaluation -- Technical planning -- Architecture review -- Technical documentation - -**When to Use**: -- Designing new systems -- Evaluating technology choices -- Planning major refactors -- Reviewing architecture -- Creating ADRs - -#### 2. Code Reviewer Agent - -**File**: [.claude/agents/code-reviewer.md](.claude/agents/code-reviewer.md) - -**Purpose**: Code quality review and best practices enforcement - -**Keywords**: code review, quality, best practices, review - -**Responsibilities**: -- Code quality assessment -- Best practices verification -- Security review -- Performance analysis -- Documentation review - -**When to Use**: -- Reviewing pull requests -- Pre-commit quality checks -- Security audits -- Performance reviews - -#### 3. Debugger Agent - -**File**: [.claude/agents/debugger.md](.claude/agents/debugger.md) - -**Purpose**: Bug diagnosis and troubleshooting - -**Keywords**: debug, troubleshoot, error, bug, issue - -**Responsibilities**: -- Error analysis -- Stack trace interpretation -- Root cause identification -- Fix recommendations -- Debugging strategies - -**When to Use**: -- Investigating bugs -- Analyzing errors -- Troubleshooting issues -- Performance problems - -#### 4. Documentation Writer Agent - -**File**: [.claude/agents/documentation-writer.md](.claude/agents/documentation-writer.md) - -**Purpose**: Technical documentation creation - -**Keywords**: documentation, docs, readme, comments, docstrings - -**Responsibilities**: -- API documentation -- README files -- Code comments -- User guides -- Architecture docs - -**When to Use**: -- Creating documentation -- Updating docs -- Generating API references -- Writing user guides - -#### 5. Project Manager Agent - -**File**: [.claude/agents/project-manager.md](.claude/agents/project-manager.md) - -**Purpose**: Project coordination and workflow management - -**Keywords**: project, manage, coordinate, workflow, plan - -**Responsibilities**: -- Task breakdown -- Workflow coordination -- Progress tracking -- Resource allocation -- Timeline planning - -**When to Use**: -- Planning large features -- Coordinating multiple tasks -- Breaking down projects -- Managing workflows - -#### 6. Refactoring Specialist Agent - -**File**: [.claude/agents/refactoring-specialist.md](.claude/agents/refactoring-specialist.md) - -**Purpose**: Code improvement and refactoring - -**Keywords**: refactor, improve, cleanup, optimize code structure - -**Responsibilities**: -- Code structure improvement -- Pattern implementation -- Technical debt reduction -- Code cleanup -- Maintainability enhancement - -**When to Use**: -- Refactoring legacy code -- Improving code structure -- Applying design patterns -- Reducing technical debt - -#### 7. Security Analyst Agent - -**File**: [.claude/agents/security-analyst.md](.claude/agents/security-analyst.md) - -**Purpose**: Security analysis and vulnerability assessment - -**Keywords**: security, vulnerability, threat, audit, security analysis - -**Responsibilities**: -- Vulnerability scanning -- Security best practices -- Threat modeling -- Compliance checking -- Security recommendations - -**When to Use**: -- Security audits -- Vulnerability assessment -- Compliance reviews -- Threat analysis - -#### 8. Test Engineer Agent - -**File**: [.claude/agents/test-engineer.md](.claude/agents/test-engineer.md) - -**Purpose**: Testing strategy and implementation - -**Keywords**: test, testing, unit test, integration test, test coverage - -**Responsibilities**: -- Test strategy -- Test implementation -- Coverage analysis -- Test automation -- Quality assurance - -**When to Use**: -- Writing tests -- Test planning -- Coverage improvement -- Test automation - -### Agent Usage Examples - -```bash -# Automatic invocation (based on description matching) -> "I need to design a microservices architecture for our API" -# โ†’ Architect agent automatically invoked - -# Manual invocation -> "Use the security-analyst agent to review this code for vulnerabilities" -# โ†’ Security analyst explicitly invoked - -# Parallel agents (use Task tool with multiple calls) -> "I need code review and security analysis" -# โ†’ Both code-reviewer and security-analyst invoked in parallel -``` - ---- - -## Slash Commands - -### Overview - -**9 slash commands** provide explicit workflows for common tasks. - -### How Commands Work - -**Invocation**: User types `/command-name [arguments]` - -**Arguments**: -- `$ARGUMENTS` - All arguments as single string -- `$1`, `$2`, `$3` - Individual arguments -- `$@` - All arguments as array - -**File References**: Use `@path/to/file` to include file content - -**Bash Execution**: Prefix with `!` for inline bash commands - -### Available Commands - -#### 1. /adr [list|view|create|update] [adr-number-or-name] - -**File**: [.claude/commands/adr.md](.claude/commands/adr.md) - -**Purpose**: Manage Architectural Decision Records (ADRs) - -**Arguments**: -- `[action]` - list, view, create, or update -- `[adr-number-or-name]` - ADR identifier (optional for list/create) - -**Features**: -- List all architectural decisions -- View specific ADR with full context -- Create new ADRs (invokes architect agent) -- Update/supersede/deprecate existing ADRs -- Track decision lifecycle and relationships -- Store ADRs in Serena persistent memory - -**Usage**: -```bash -> /adr list # List all ADRs -> /adr view adr-001 # View specific ADR -> /adr view adr-003-authentication-strategy # View by name -> /adr create # Create new ADR -> /adr update adr-002 # Update/supersede ADR -``` - -**Allowed Tools**: Read(*), mcp__serena__list_memories(*), mcp__serena__read_memory(*), mcp__serena__write_memory(*), Task(*) - -**Storage**: ADRs are stored in Serena memory (`.serena/memories/`) and persist across sessions - -**Integration**: Works with architect agent for ADR creation and formatting - -#### 2. /analyze [path] - -**File**: [.claude/commands/analyze.md](.claude/commands/analyze.md) - -**Purpose**: Comprehensive code analysis - -**Arguments**: `[path]` - File or directory to analyze - -**Features**: -- Code complexity analysis -- Dependency mapping -- Quality metrics -- Architecture review -- Performance profiling - -**Usage**: -```bash -> /analyze src/components/ -> /analyze src/utils/api.ts -``` - -**Allowed Tools**: Read(*), Grep(*), Glob(*), Bash(*) - -#### 3. /explain [file-or-selection] - -**File**: [.claude/commands/explain.md](.claude/commands/explain.md) - -**Purpose**: Detailed code explanation - -**Arguments**: `[file-or-selection]` - What to explain - -**Features**: -- Step-by-step breakdown -- Pattern identification -- Design rationale -- Best practices -- Learning insights - -**Usage**: -```bash -> /explain src/auth/middleware.ts -> /explain @src/utils/parser.js -``` - -#### 4. /implement [feature-description] - -**File**: [.claude/commands/implement.md](.claude/commands/implement.md) - -**Purpose**: Feature implementation - -**Arguments**: `[feature-description]` - What to implement - -**Features**: -- Feature planning -- Code generation -- Pattern following -- Testing included -- Documentation - -**Usage**: -```bash -> /implement user authentication with JWT -> /implement payment integration with Stripe -``` - -#### 5. /optimize [file-or-function] - -**File**: [.claude/commands/optimize.md](.claude/commands/optimize.md) - -**Purpose**: Performance optimization - -**Arguments**: `[file-or-function]` - What to optimize - -**Features**: -- Bottleneck identification -- Algorithm optimization -- Memory profiling -- Performance testing -- Recommendations - -**Usage**: -```bash -> /optimize src/utils/dataProcessor.ts -> /optimize database queries -``` - -#### 6. /review [file-or-path] - -**File**: [.claude/commands/review.md](.claude/commands/review.md) - -**Purpose**: Comprehensive code review - -**Arguments**: `[file-or-path]` - What to review - -**Features**: -- Quality assessment -- Best practices check -- Security review -- Performance analysis -- Improvement suggestions - -**Usage**: -```bash -> /review src/api/routes/ -> /review @src/components/UserProfile.tsx -``` - -#### 7. /scaffold [type] [name] - -**File**: [.claude/commands/scaffold.md](.claude/commands/scaffold.md) - -**Purpose**: Generate boilerplate code - -**Arguments**: `[type]` - What to scaffold, `[name]` - Name - -**Features**: -- Component generation -- Service scaffolding -- API endpoint creation -- Test file generation -- Configuration setup - -**Usage**: -```bash -> /scaffold component UserDashboard -> /scaffold service PaymentService -> /scaffold api /users/:id -``` - -#### 8. /setup-info - -**File**: [.claude/commands/setup-info.md](.claude/commands/setup-info.md) - -**Purpose**: Display complete setup information - -**Features**: -- Configuration overview -- Agent list -- Command list -- MCP server status -- Hook configuration - -**Usage**: -```bash -> /setup-info -``` - -#### 9. /test [file-path] - -**File**: [.claude/commands/test.md](.claude/commands/test.md) - -**Purpose**: Test execution and management - -**Arguments**: `[file-path]` - Test file or path - -**Features**: -- Test running -- Coverage analysis -- Test generation -- Failure analysis -- Test strategy - -**Usage**: -```bash -> /test -> /test src/utils/__tests__/api.test.ts -> /test --coverage -``` - -### Creating Custom Commands - -Use the template at [.claude/commands/.COMMANDS_TEMPLATE.md](.claude/commands/.COMMANDS_TEMPLATE.md) - -**Example**: -```bash -# 1. Copy template -cp .claude/commands/.COMMANDS_TEMPLATE.md .claude/commands/deploy.md - -# 2. Edit frontmatter ---- -description: Deploy application to production -argument-hint: [environment] -allowed-tools: Bash(git *:*), Bash(npm *:*), Read(*) -model: claude-3-5-sonnet-20241022 ---- - -# 3. Write instructions -Deploy the application to $1 environment... - -# 4. Use it -> /deploy production -``` - ---- - -## Output Styles - -### Overview - -**6 custom output styles** modify Claude's behavior and communication style. - -### How Output Styles Work - -**Activation**: `/output-style [style-name]` - -**Effect**: Completely replaces system prompt, changing how Claude responds - -**Scope**: Active for entire conversation until changed - -**Tool Access**: Inherits from conversation settings (not restricted by style) - -### Available Styles - -#### 1. Default Style - -**Built-in**: Yes - -**Purpose**: Standard software engineering assistant - -**Characteristics**: -- Efficient and task-focused -- Technical accuracy -- Concise explanations -- Code-first approach - -**When to Use**: Normal development work - -#### 2. Concise Style - -**File**: [.claude/output-styles/concise.md](.claude/output-styles/concise.md) - -**Purpose**: Brief, to-the-point responses - -**Characteristics**: -- Minimal explanation -- Direct answers -- Code without commentary -- Short summaries - -**When to Use**: Quick fixes, simple tasks, time pressure - -**Activation**: -```bash -> /output-style concise -``` - -#### 3. Professional Style - -**File**: [.claude/output-styles/professional.md](.claude/output-styles/professional.md) - -**Purpose**: Formal, business-appropriate tone - -**Characteristics**: -- Formal language -- Structured responses -- Detailed documentation -- Business-friendly - -**When to Use**: Client interactions, stakeholder communication, reports - -**Activation**: -```bash -> /output-style professional -``` - -#### 4. Verbose Style - -**File**: [.claude/output-styles/verbose.md](.claude/output-styles/verbose.md) - -**Purpose**: Detailed, comprehensive explanations - -**Characteristics**: -- Extensive detail -- Multiple examples -- Thorough rationale -- Educational depth - -**When to Use**: Learning, onboarding, complex topics - -**Activation**: -```bash -> /output-style verbose -``` - -#### 5. Explanatory Style - -**File**: [.claude/output-styles/explanatory.md](.claude/output-styles/explanatory.md) - -**Purpose**: Educational insights and learning - -**Characteristics**: -- Explains "why" decisions -- Pattern identification -- Learning opportunities -- Best practices focus - -**When to Use**: Understanding codebases, learning patterns, educational context - -**Activation**: -```bash -> /output-style explanatory -``` - -#### 6. Learning Style - -**File**: [.claude/output-styles/learning.md](.claude/output-styles/learning.md) - -**Purpose**: Interactive learning mode - -**Characteristics**: -- Claude asks YOU to code -- Provides guidance, not solutions -- Marks sections with `TODO(human)` -- Socratic method - -**When to Use**: Skill development, hands-on learning, teaching - -**Activation**: -```bash -> /output-style learning -``` - -#### 7. Security Reviewer Style - -**File**: [.claude/output-styles/security-reviewer.md](.claude/output-styles/security-reviewer.md) - -**Purpose**: Security-focused analysis - -**Characteristics**: -- Security-first mindset -- Vulnerability scanning -- Threat modeling -- Compliance checking - -**When to Use**: Security audits, vulnerability assessment, compliance reviews - -**Activation**: -```bash -> /output-style security-reviewer -``` - -### Creating Custom Output Styles - -Use the template at [.claude/output-styles/.OUTPUT_STYLES_TEMPLATE.md](.claude/output-styles/.OUTPUT_STYLES_TEMPLATE.md) - -**Example**: -```markdown ---- -name: debugging-mode -description: Systematic debugging approach with detailed logging ---- - -# Debugging Mode Output Style - -You are Claude in debugging mode... - -## Characteristics -- Step-by-step analysis -- Hypothesis generation and testing -- Detailed logging -- Root cause identification - -## Response Format -1. **Problem Analysis**: [Describe the issue] -2. **Hypotheses**: [List possible causes] -3. **Testing**: [Test each hypothesis] -4. **Solution**: [Recommended fix] -``` - ---- - -## Hooks System - -### Overview - -**5 event hooks** enable automatic execution of scripts at specific points in Claude Code's lifecycle. - -### How Hooks Work - -**Event Triggers**: Hooks fire automatically when specific events occur - -**Script Execution**: Shell scripts (.sh) or PowerShell (.ps1) execute with current environment - -**Security**: Hooks run with your credentials - review before using - -**Configuration**: Defined in `.claude/settings.json` under `hooks` key - -### Available Hooks - -#### 1. session-start Hook - -**File**: [.claude/hooks/session-start.sh](.claude/hooks/session-start.sh) - -**Trigger**: When Claude Code session begins or resumes - -**Purpose**: Initialize session, setup logging, create directories - -**Current Implementation**: -```bash -# Create logs directory if it doesn't exist -mkdir -p .claude/logs - -# Log session start -echo "[$(date)] Session started in $(pwd) by $USER" >> .claude/logs/session.log -``` - -**Use Cases**: -- Initialize logging -- Setup environment variables -- Create required directories -- Display welcome messages - -#### 2. session-end Hook - -**File**: [.claude/hooks/session-end.sh](.claude/hooks/session-end.sh) - -**Trigger**: When Claude Code session terminates - -**Purpose**: Cleanup, final logging, backups - -**Use Cases**: -- Final log entries -- Cleanup temporary files -- Create session backups -- Generate reports - -#### 3. pre-bash Hook - -**File**: [.claude/hooks/pre-bash.sh](.claude/hooks/pre-bash.sh) - -**Trigger**: Before Bash tool executes commands - -**Purpose**: Command validation, logging, permission checks - -**Use Cases**: -- Log commands before execution -- Validate command safety -- Check permissions -- Block dangerous commands - -#### 4. post-write Hook - -**File**: [.claude/hooks/post-write.sh](.claude/hooks/post-write.sh) - -**Trigger**: After Write or Edit tool modifies files - -**Purpose**: Post-processing, formatting, logging - -**Current Implementation**: -```bash -# Log file writes -echo "[$(date)] File written: $FILEPATH" >> .claude/logs/writes.log - -# Auto-format certain files (commented out by default) -# if [[ $FILEPATH =~ \.(js|ts|tsx)$ ]]; then -# npx prettier --write "$FILEPATH" -# fi -``` - -**Use Cases**: -- Auto-formatting (Prettier, Black, etc.) -- Linting -- Git add -- File logging -- Backup creation - -#### 5. user-prompt-submit Hook - -**File**: [.claude/hooks/user-prompt-submit.sh](.claude/hooks/user-prompt-submit.sh) - -**Trigger**: After user submits a prompt, before processing - -**Purpose**: Prompt logging, validation, preprocessing - -**Use Cases**: -- Log all user prompts -- Count prompt usage -- Validate input -- Track costs - -### Hook Configuration - -**Location**: `.claude/settings.json` - -**Format**: -```json -{ - "hooks": { - "PreToolUse": { - "*": "bash .claude/hooks/pre-bash.sh" - }, - "PostToolUse": { - "Write": "bash .claude/hooks/post-write.sh", - "Edit": "bash .claude/hooks/post-write.sh" - }, - "SessionStart": "bash .claude/hooks/session-start.sh", - "SessionEnd": "bash .claude/hooks/session-end.sh", - "UserPromptSubmit": "bash .claude/hooks/user-prompt-submit.sh" - } -} -``` - -### Creating Custom Hooks - -**Example: Auto-commit Hook** -```bash -# .claude/hooks/post-write.sh -#!/bin/bash - -# Auto-commit changed files -if [[ -n "$FILEPATH" ]]; then - git add "$FILEPATH" - git commit -m "Auto-commit: Updated $FILEPATH via Claude Code" -fi -``` - -**Example: Cost Tracking Hook** -```bash -# .claude/hooks/user-prompt-submit.sh -#!/bin/bash - -# Track prompt count -COUNT_FILE=".claude/logs/prompt_count.txt" -COUNT=$(cat "$COUNT_FILE" 2>/dev/null || echo "0") -echo $((COUNT + 1)) > "$COUNT_FILE" -``` - ---- - -## Templates - -### Overview - -**4 comprehensive templates** for extending Claude Code functionality. - -### Available Templates - -#### 1. SKILL_TEMPLATE.md - -**Location**: [.claude/skills/.SKILL_TEMPLATE.md](.claude/skills/.SKILL_TEMPLATE.md) - -**Purpose**: Create model-invoked capabilities - -**Features**: -- YAML frontmatter with `allowed-tools` -- Progressive disclosure pattern -- Multi-file organization -- Testing checklist -- Version history - -**When to Use**: Auto-activated capabilities based on context - -**Example Use Cases**: -- PDF processing skill -- Excel analysis skill -- Documentation generation skill - -#### 2. COMMANDS_TEMPLATE.md - -**Location**: [.claude/commands/.COMMANDS_TEMPLATE.md](.claude/commands/.COMMANDS_TEMPLATE.md) - -**Purpose**: Create user-invoked slash commands - -**Features**: -- Argument handling ($ARGUMENTS, $1, $2) -- Bash execution (! prefix) -- File references (@ prefix) -- Model selection -- Tool restrictions - -**When to Use**: Explicit workflows and routines - -**Example Use Cases**: -- `/commit` - Create git commits -- `/deploy` - Deployment workflow -- `/generate-tests` - Test generation - -#### 3. AGENT_TEMPLATE.md - -**Location**: [.claude/agents/.AGENT_TEMPLATE.md](.claude/agents/.AGENT_TEMPLATE.md) - -**Purpose**: Create specialized subagents - -**Features**: -- YAML frontmatter configuration -- Tool restrictions -- Model selection -- Workflow definitions -- Context management - -**When to Use**: Domain-specific expertise needed - -**Example Use Cases**: -- Research agent -- Implementation agent -- Review agent - -#### 4. OUTPUT_STYLES_TEMPLATE.md - -**Location**: [.claude/output-styles/.OUTPUT_STYLES_TEMPLATE.md](.claude/output-styles/.OUTPUT_STYLES_TEMPLATE.md) - -**Purpose**: Create custom response behaviors - -**Features**: -- Behavior definition -- Response structure -- Use case guidance -- Testing checklist - -**When to Use**: Need different communication style - -**Example Use Cases**: -- Debugging mode -- Documentation mode -- Teaching mode - -### Template Usage Guide - -See [.claude/TEMPLATES_README.md](.claude/TEMPLATES_README.md) for comprehensive guide including: -- Template comparison matrix -- Quick start guides -- Decision trees -- Best practices -- Troubleshooting - ---- - -## Configuration - -### Settings Files Hierarchy - -Claude Code uses a **5-level hierarchy** (highest to lowest priority): - -1. **Enterprise Policies** - IT-deployed, cannot be overridden -2. **Command Line Arguments** - Session-specific (`--model`, `--max-tokens`, etc.) -3. **Local Project Settings** - `.claude/settings.local.json` (personal, not in git) -4. **Shared Project Settings** - `.claude/settings.json` (team-shared, in git) -5. **User Settings** - `~/.claude/settings.json` (global personal) - -### Main Settings File - -**Location**: [.claude/settings.json](.claude/settings.json) - -**Key Sections**: - -#### Permissions - -```json -{ - "permissions": { - "allowed": [ - "Read(*)", - "Write(*)", - "Edit(*)", - "Glob(*)", - "Grep(*)", - "Bash(git status:*)", - "Bash(git diff:*)", - "Bash(npm test:*)", - "mcp__serena__*", - "mcp__memory__*", - "mcp__context7__*", - "WebSearch", - "WebFetch" - ], - "ask": [ - "Bash(npm install:*)", - "Bash(npm uninstall:*)" - ], - "denied": [ - "Bash(rm -rf /:*)", - "Bash(mkfs:*)", - "Bash(dd if=:*)" - ] - } -} -``` - -#### MCP Server Configuration - -```json -{ - "mcpServers": { - "serena": { - "enabled": true - }, - "memory": { - "enabled": true - }, - "context7": { - "enabled": true - } - } -} -``` - -#### Hooks Configuration - -```json -{ - "hooks": { - "SessionStart": "bash .claude/hooks/session-start.sh", - "SessionEnd": "bash .claude/hooks/session-end.sh", - "PreToolUse": { - "*": "bash .claude/hooks/pre-bash.sh" - }, - "PostToolUse": { - "Write": "bash .claude/hooks/post-write.sh", - "Edit": "bash .claude/hooks/post-write.sh" - }, - "UserPromptSubmit": "bash .claude/hooks/user-prompt-submit.sh" - } -} -``` - -#### Status Line - -```json -{ - "statusLine": { - "enabled": true, - "command": "bash .claude/statusline.sh" - } -} -``` - -#### Plugin Marketplace - -```json -{ - "extraKnownMarketplaces": [ - { - "name": "anthropic-official", - "url": "https://raw.githubusercontent.com/anthropics/skills/main/marketplace.json", - "description": "Official Anthropic Skills Marketplace" - } - ] -} -``` - -### MCP Configuration - -**Location**: [.mcp.json](.mcp.json) (project root) - -**Format**: -```json -{ - "mcpServers": { - "serena": { - "command": "uvx", - "args": ["--from", "git+https://github.com/oraios/serena", "serena", "start-mcp-server", "--context", "ide-assistant", "--project", "Claude Code Setup"] - }, - "memory": { - "command": "powershell", - "args": ["-ExecutionPolicy", "Bypass", "-File", ".\.claude\tools\start-memory.ps1"] - }, - "context7": { - "command": "npx", - "args": ["-y", "@upstash/context7-mcp"], - "env": { - "CONTEXT7_API_KEY": "your-api-key-here" - } - } - } -} -``` - -### Environment Variables - -Key environment variables (set in settings.json or shell): - -**Authentication**: -- `ANTHROPIC_API_KEY` - API key for Claude -- `ANTHROPIC_AUTH_TOKEN` - OAuth token - -**Model Configuration**: -- `DEFAULT_MODEL` - Default Claude model -- `MAX_TOKENS` - Response token limit -- `THINKING_TOKEN_LIMIT` - Extended thinking budget - -**Features**: -- `DISABLE_TELEMETRY` - Disable usage tracking -- `DISABLE_AUTOUPDATER` - Disable auto-updates - -**Network**: -- `HTTPS_PROXY` - Proxy server -- `SSL_CERT_FILE` - Custom CA certificate - ---- - -## Memory & Context - -### Memory System Overview - -Claude Code has **hierarchical memory** across 4 locations: - -1. **Enterprise Policy** - Organization-wide instructions -2. **Project Memory** - `./CLAUDE.md` or `./.claude/CLAUDE.md` (team-shared) -3. **User Memory** - `~/.claude/CLAUDE.md` (personal, all projects) -4. **Project Memory (Local)** - Deprecated - -### Project Instructions (CLAUDE.md) - -**Location**: [CLAUDE.md](CLAUDE.md) - -**Purpose**: Provide project context, conventions, and guidelines to Claude - -**Sections**: -- Project overview -- Technology stack -- Code style guidelines -- Testing requirements -- Commit message format -- Development workflow -- Security considerations -- Performance optimization - -**Best Practices**: -- Keep current and updated -- Be specific and concrete -- Use examples liberally -- Structure with clear headings -- Link to external docs -- Review periodically - -**Import Files**: Use `@path/to/file` syntax (max depth: 5) - -### Persistent Memory (Serena) - -**Storage**: `.serena/memories/` - -**Persistence**: Survives across sessions - -**Management**: -```bash -# Write memory -mcp__serena__write_memory("adr-001-architecture", content) - -# Read memory -mcp__serena__read_memory("adr-001-architecture") - -# List all -mcp__serena__list_memories() - -# Delete -mcp__serena__delete_memory("adr-001-architecture") -``` - -**Current Memory**: `serena-persistence-test` - -**Naming Conventions**: -- ADRs: `adr-001-database-choice-postgresql` -- Reviews: `code-review-2024-10-payment-service` -- Lessons: `lesson-async-error-handling` -- Patterns: `pattern-repository-implementation` -- Debt: `debt-legacy-api-authentication` -- Security: `security-audit-2024-10-full` -- Performance: `performance-optimization-query-caching` - -### Temporary Memory (Knowledge Graph) - -**Storage**: In-memory, cleared on session end - -**Management**: -```bash -# Create entities -mcp__memory__create_entities([{name, entityType, observations}]) - -# Create relations -mcp__memory__create_relations([{from, to, relationType}]) - -# Search -mcp__memory__search_nodes("query") - -# Read graph -mcp__memory__read_graph() -``` - -**Best For**: Current session context, temporary analysis - -### Context Management - -**File References**: -- Include files in prompts with `@path/to/file` -- Glob patterns supported: `@src/**/*.ts` - -**Directory Context**: -- Use `/add-dir` to add entire directories -- Claude maintains awareness of directory structure - -**Conversation History**: -- Full history maintained in session -- Use `/compact` to condense long conversations -- Use `/clear` to start fresh - ---- - -## Advanced Features - -### 1. Extended Thinking - -**What**: Gives Claude more computation time for complex problems - -**Activation**: -- Use keywords: `think`, `think hard`, `think harder`, `ultrathink` -- Each level increases computational budget -- Shown as thinking process in UI - -**When to Use**: -- Architecture decisions -- Complex debugging -- Security analysis -- Algorithm optimization -- Design pattern selection - -**Example**: -```bash -> "Think hard about the best architecture for this microservices system" -``` - -**Token Limits**: Configure with `THINKING_TOKEN_LIMIT` environment variable - -### 2. Plan Mode - -**What**: Read-only exploration before making changes - -**Activation**: Toggle with `Tab` key - -**Benefits**: -- Safe exploration -- No file modifications -- Understanding phase -- Review before action - -**Workflow**: -1. Enter plan mode (Tab) -2. Explore and understand -3. Get approval for plan -4. Exit plan mode (Tab) -5. Execute changes - -**When to Use**: -- Complex multi-file changes -- Unfamiliar codebases -- Major refactoring -- Architecture changes - -### 3. Checkpointing - -**What**: Rewind conversation and/or code to previous states - -**Activation**: Press `ESC ESC` or `/rewind` - -**Options**: -1. **Code Only** - Revert files, keep conversation -2. **Conversation Only** - Revert conversation, keep files -3. **Both** - Complete rollback - -**Retention**: 30 days - -**When to Use**: -- Experimental changes -- Wrong direction -- Need to try alternatives -- Accidental modifications - -### 4. Git Integration - -**Pre-approved commands**: -- `git status` -- `git diff` -- `git log` -- `git show` - -**Commit Creation**: See [Git Workflow](#git-workflow) in CLAUDE.md - -**Branch Management**: Supported with appropriate permissions - -### 5. Parallel Execution - -**Independent Commands**: Run multiple bash commands in parallel -```bash -# Claude executes these simultaneously -git status && npm test && docker ps -``` - -**Multiple Agents**: Invoke multiple agents in parallel with Task tool - -**File Operations**: Multiple Reads in parallel for efficiency - -### 6. Session Resume - -**Resume Previous**: `claude --continue` or `claude --resume` - -**Named Sessions**: `claude --session [name]` - -**List Sessions**: View available sessions to resume - -### 7. Cost Tracking - -**View Costs**: `/cost` command - -**Token Usage**: Tracked per session - -**Breakdown**: -- Input tokens -- Output tokens -- Thinking tokens (if used) -- Tool calls - -**Export**: Available in settings for monitoring - -### 8. Plugin Marketplace - -**Access**: `/plugin` command - -**Sources**: -- Official Anthropic marketplace -- Custom marketplaces (configured in settings) - -**Installation**: Browse and install skills/commands/agents - -**Management**: `/plugin list`, `/plugin install [name]` - ---- - -## Best Practices - -### General Guidelines - -1. **Start Broad, Then Narrow** - - Ask high-level questions first - - Progressively dive into specifics - - Use agents for focused deep-dives - -2. **Use Appropriate Tools** - - Agents for domains - - Commands for workflows - - Skills for auto-capabilities - - Output styles for communication - -3. **Leverage Memory** - - Store ADRs in Serena memory - - Use knowledge graph for session context - - Keep CLAUDE.md updated - -4. **Optimize Performance** - - Use concise style for quick tasks - - Leverage extended thinking for complex problems - - Parallel execution when possible - -5. **Maintain Security** - - Review hooks before using - - Restrict sensitive tool access - - Use security-analyst agent for audits - - Never commit secrets - -### Development Workflows - -#### New Feature Development - -```bash -# 1. Architecture planning -> "Use the architect agent to design user authentication feature" - -# 2. Implementation -> /implement user authentication with JWT - -# 3. Testing -> /test src/auth/ - -# 4. Review -> /review src/auth/ - -# 5. Documentation -> "Use documentation-writer agent to document authentication" - -# 6. Commit -> "Create a git commit for this feature" -``` - -#### Debugging - -```bash -# 1. Use debugger agent -> "Use the debugger agent to investigate this error: [paste error]" - -# 2. Extended thinking for complex issues -> "Think hard about why this race condition occurs" - -# 3. Review fix -> /review [fixed file] - -# 4. Test -> /test -``` - -#### Code Review - -```bash -# 1. Review changes -> /review src/ - -# 2. Security check -> "Use security-analyst agent to check for vulnerabilities" - -# 3. Generate suggestions -> "Use refactoring-specialist agent to suggest improvements" -``` - -### MCP Usage Patterns - -#### Code Navigation - -```bash -# Find symbol -find_symbol("UserService") - -# Find references -find_referencing_symbols("UserService", "src/services/user.ts") - -# Get overview -get_symbols_overview("src/services/user.ts") -``` - -#### Persistent Knowledge - -```bash -# Store ADR -write_memory("adr-001-auth-jwt", "Decision: Use JWT for auth...") - -# Recall later -read_memory("adr-001-auth-jwt") -``` - -#### Documentation Lookup - -```bash -# Resolve library -resolve-library-id("react") - -# Get docs -get-library-docs("/facebook/react") -``` - -### Optimization Tips - -1. **Model Selection** - - Haiku for simple tasks (fast, cheap) - - Sonnet for general development (balanced) - - Opus for complex reasoning (powerful) - -2. **Token Efficiency** - - Use concise style when appropriate - - Leverage Glob/Grep instead of reading all files - - Use Serena symbol tools instead of full file reads - -3. **Parallel Work** - - Multiple file reads in one message - - Parallel agent invocation - - Independent bash commands together - -4. **Context Management** - - Regular `/compact` for long sessions - - Use knowledge graph for session state - - Clear when switching major tasks - ---- - -## Troubleshooting - -### Common Issues - -#### Agents Not Activating - -**Problem**: Agent doesn't activate automatically - -**Solutions**: -1. Check description has relevant keywords -2. Try manual invocation -3. Verify agent file is in `.claude/agents/` -4. Restart Claude to reload agents -5. Check YAML frontmatter is valid - -#### Commands Not Found - -**Problem**: `/command` not recognized - -**Solutions**: -1. Verify file is `.claude/commands/[name].md` -2. Filename must match command name -3. Restart Claude to reload commands -4. Check `/help` to see available commands -5. Validate frontmatter syntax - -#### MCP Server Failures - -**Problem**: MCP server not connecting - -**Solutions**: -1. Check `.mcp.json` configuration -2. Verify command path is correct -3. Test command manually in terminal -4. Check logs for error messages -5. Ensure dependencies installed (npx, uvx, etc.) - -#### Hook Not Executing - -**Problem**: Hook script doesn't run - -**Solutions**: -1. Check hook is configured in `settings.json` -2. Verify script path is correct -3. Ensure script has execute permissions -4. Check script syntax (bash/PowerShell) -5. Look for errors in logs - -#### Permission Denied - -**Problem**: Tool execution blocked - -**Solutions**: -1. Check permissions in `settings.json` -2. Add tool to `allowed` array -3. Use wildcards for patterns -4. Restart Claude after changes -5. Check for enterprise policies overriding - -### Debugging Steps - -1. **Check Logs** - - Session log: `.claude/logs/session.log` - - Bash log: `.claude/logs/bash.log` - - Write log: `.claude/logs/writes.log` - -2. **Verify Configuration** - ```bash - # Check settings - cat .claude/settings.json | jq '.permissions' - - # Check MCP config - cat .mcp.json | jq '.mcpServers' - ``` - -3. **Test Components** - ```bash - # Test MCP server manually - npx -y @modelcontextprotocol/server-sequential-thinking - - # Test hook script - bash .claude/hooks/session-start.sh - ``` - -4. **Use Diagnostic Commands** - ```bash - > /setup-info # Display configuration - > /doctor # Diagnose installation - > /mcp # Check MCP status - ``` - -### Getting Help - -1. **Built-in Help**: `/help` command -2. **Setup Info**: `/setup-info` command -3. **Official Docs**: https://docs.claude.com/en/docs/claude-code/ -4. **GitHub Issues**: https://github.com/anthropics/claude-code/issues -5. **This Documentation**: Review relevant sections above - ---- - -## Appendix - -### Quick Reference - -#### Key Files -- `.claude/settings.json` - Main configuration -- `.mcp.json` - MCP servers -- `CLAUDE.md` - Project instructions -- `.claude/agents/` - Specialized agents -- `.claude/commands/` - Slash commands -- `.claude/output-styles/` - Response styles -- `.claude/hooks/` - Event automation - -#### Key Commands -- `/help` - Get help -- `/setup-info` - Display setup -- `/plugin` - Plugin marketplace -- `/output-style [style]` - Change style -- `/cost` - View costs -- `/rewind` - Checkpointing -- `/memory` - Edit memory -- `/compact` - Condense conversation -- `/clear` - Clear history - -#### Key Shortcuts -- `Tab` - Toggle plan mode -- `ESC ESC` - Access checkpoints -- `Ctrl+C` - Interrupt Claude -- `@file` - Reference file -- `#` - Quick memory capture - -### File Naming Conventions - -**Agents**: `kebab-case.md` in `.claude/agents/` -**Commands**: `kebab-case.md` in `.claude/commands/` -**Skills**: Directory with `SKILL.md` in `.claude/skills/[name]/` -**Output Styles**: `kebab-case.md` in `.claude/output-styles/` -**Hooks**: `event-name.sh` or `event-name.ps1` in `.claude/hooks/` - -### Version History - -- **v3.0.0** (2025-10-20): Complete documentation overhaul, added missing capabilities -- **v2.0.0** (2025-10-17): Added output styles, plugins, status line -- **v1.0.0** (Initial): Basic setup with agents, commands, MCP - -### Credits - -**Based on**: -- Official Anthropic Claude Code documentation -- Claude Agent SDK best practices -- Community contributions -- Real-world production experience - ---- - -**Documentation Version**: 3.0.0 -**Last Updated**: 2025-10-20 -**Maintained by**: Claude Code Setup Project -**License**: Use and modify freely - -**For the most current information, always refer to official documentation at**: -https://docs.claude.com/en/docs/claude-code/ - ---- - -*This setup represents ~95% of available Claude Code capabilities. The remaining 5% includes enterprise features (SSO, analytics), headless mode (CI/CD), and specialized network configurations (proxies, certificates) which are optional and environment-specific.* diff --git a/CLAUDE_TEMPLATE.md b/CLAUDE_TEMPLATE.md deleted file mode 100644 index 20bf01a7..00000000 --- a/CLAUDE_TEMPLATE.md +++ /dev/null @@ -1,1095 +0,0 @@ -# [Project Name] - -> **Version**: 1.0.0 | **Last Updated**: YYYY-MM-DD | **Maintainer**: [Your Name/Team] - -## Project Overview - -### Purpose -Brief 2-3 sentence description of what this project does and why it exists. - -### Key Objectives -- Primary goal or feature 1 -- Primary goal or feature 2 -- Primary goal or feature 3 - -### Project Type -- [ ] Web Application -- [ ] API/Backend Service -- [ ] CLI Tool -- [ ] Library/Package -- [ ] Mobile App -- [ ] Desktop Application -- [ ] Other: _________________ - -### Target Users/Audience -Who is this project built for? What problems does it solve for them? - ---- - -## Technology Stack - -### Core Technologies -- **Language(s)**: [e.g., Python 3.11, TypeScript 5.0, JavaScript ES6+] -- **Framework(s)**: [e.g., React 18, Django 4.2, Express.js] -- **Runtime**: [e.g., Node.js 18+, Python 3.11+] - -### Frontend (if applicable) -- **UI Framework**: [e.g., React, Vue, Angular, Svelte] -- **Styling**: [e.g., Tailwind CSS, CSS Modules, Styled Components] -- **State Management**: [e.g., Redux, Zustand, Context API] -- **Build Tool**: [e.g., Vite, Webpack, Turbopack] - -### Backend (if applicable) -- **Framework**: [e.g., Express, FastAPI, Django, Rails] -- **Database**: [e.g., PostgreSQL 15, MongoDB 6, MySQL 8] -- **ORM/Query Builder**: [e.g., Prisma, SQLAlchemy, TypeORM] -- **Authentication**: [e.g., JWT, OAuth 2.0, Passport.js] - -### Infrastructure & DevOps -- **Hosting**: [e.g., AWS, Vercel, Railway, Heroku] -- **CI/CD**: [e.g., GitHub Actions, GitLab CI, CircleCI] -- **Containers**: [e.g., Docker, Docker Compose] -- **Monitoring**: [e.g., Sentry, DataDog, Prometheus] - -### Testing -- **Test Framework**: [e.g., Jest, Pytest, Vitest, Mocha] -- **E2E Testing**: [e.g., Playwright, Cypress, Selenium] -- **Test Coverage Tool**: [e.g., Coverage.py, Istanbul, c8] - -### Development Tools -- **Package Manager**: [e.g., npm, pnpm, yarn, pip, poetry] -- **Linting**: [e.g., ESLint, Pylint, Ruff] -- **Formatting**: [e.g., Prettier, Black, rustfmt] -- **Type Checking**: [e.g., TypeScript, mypy, Flow] - ---- - -## Project Structure - -### Directory Layout -``` -project-root/ -โ”œโ”€โ”€ src/ # Source code -โ”‚ โ”œโ”€โ”€ components/ # Reusable components -โ”‚ โ”œโ”€โ”€ pages/ # Page components or routes -โ”‚ โ”œโ”€โ”€ services/ # Business logic and API calls -โ”‚ โ”œโ”€โ”€ utils/ # Utility functions -โ”‚ โ”œโ”€โ”€ hooks/ # Custom React hooks (if applicable) -โ”‚ โ”œโ”€โ”€ types/ # TypeScript type definitions -โ”‚ โ””โ”€โ”€ config/ # Configuration files -โ”œโ”€โ”€ tests/ # Test files -โ”‚ โ”œโ”€โ”€ unit/ # Unit tests -โ”‚ โ”œโ”€โ”€ integration/ # Integration tests -โ”‚ โ””โ”€โ”€ e2e/ # End-to-end tests -โ”œโ”€โ”€ public/ # Static assets -โ”œโ”€โ”€ docs/ # Documentation -โ”œโ”€โ”€ scripts/ # Build and utility scripts -โ”œโ”€โ”€ .claude/ # Claude Code configuration -โ”‚ โ”œโ”€โ”€ commands/ # Custom slash commands -โ”‚ โ”œโ”€โ”€ skills/ # Agent skills -โ”‚ โ”œโ”€โ”€ hooks/ # Event hooks -โ”‚ โ””โ”€โ”€ settings.json # Claude settings -โ””โ”€โ”€ config/ # Application configuration -``` - -### Key Files -- **Entry Point**: [e.g., `src/index.ts`, `src/main.py`, `app.js`] -- **Configuration**: [e.g., `config/app.config.ts`, `settings.py`] -- **Routes/API**: [e.g., `src/routes/`, `src/api/`] -- **Database Models**: [e.g., `src/models/`, `src/db/schema.ts`] - -### Module Organization -Explain how code is organized into modules/packages and the reasoning behind the structure. - ---- - -## Code Style & Standards - -### Naming Conventions - -#### Variables & Functions -- Use `camelCase` for variables and functions (JavaScript/TypeScript) -- Use `snake_case` for variables and functions (Python) -- Use descriptive names that reveal intent -- Avoid single-letter variables except in loops or mathematical contexts - -```typescript -// Good -const userProfile = getUserProfile(); -const isAuthenticated = checkAuth(); - -// Avoid -const x = getUser(); -const flag = check(); -``` - -#### Classes & Components -- Use `PascalCase` for classes and React components -- Name classes with nouns that describe what they represent -- Name components based on what they render - -```typescript -// Good -class UserRepository { } -function UserProfileCard() { } - -// Avoid -class userData { } -function component1() { } -``` - -#### Constants -- Use `UPPER_SNAKE_CASE` for constants -- Group related constants in enums or objects - -```typescript -// Good -const MAX_RETRY_ATTEMPTS = 3; -const API_BASE_URL = process.env.API_URL; - -// Avoid -const maxretries = 3; -``` - -#### Files & Folders -- Use `kebab-case` for file and folder names -- Match file name to primary export -- Use `.test.ts` suffix for test files -- Use `.spec.ts` for specification files - -``` -user-profile.tsx -user-repository.ts -user-profile.test.tsx -api-client.config.ts -``` - -### Code Organization - -#### File Size -- Keep files under 300 lines when possible -- Split large files into smaller, focused modules -- One component/class per file (exceptions for tightly coupled small helpers) - -#### Function Complexity -- Functions should do one thing well -- Keep functions under 50 lines when possible -- Extract complex logic into well-named helper functions -- Maximum 3-4 parameters; use options objects for more - -```typescript -// Good - focused function -function calculateTotalPrice(items: Item[]): number { - return items.reduce((sum, item) => sum + item.price, 0); -} - -// Avoid - doing too much -function processOrder(items, user, payment, shipping, discount) { - // 100+ lines of mixed concerns -} -``` - -#### Import Organization -Order imports in this sequence: -1. External dependencies -2. Internal modules (absolute imports) -3. Relative imports -4. Type imports (if separate) -5. Styles - -```typescript -// External -import React from 'react'; -import { useQuery } from '@tanstack/react-query'; - -// Internal -import { apiClient } from '@/services/api'; -import { UserRepository } from '@/repositories/user'; - -// Relative -import { Button } from './components/Button'; -import { formatDate } from './utils/date'; - -// Types -import type { User } from '@/types'; - -// Styles -import './styles.css'; -``` - -### Comments & Documentation - -#### When to Comment -- **DO**: Explain *why* something is done, not *what* is done -- **DO**: Document complex algorithms or business logic -- **DO**: Add TODOs with tickets/issues: `// TODO(#123): refactor this` -- **DO**: Explain workarounds or non-obvious solutions -- **DON'T**: State the obvious -- **DON'T**: Leave commented-out code (use git history) - -```typescript -// Good - explains why -// Using a delay here to work around race condition in the API -// See issue #456 for details -await delay(100); - -// Avoid - states the obvious -// Set user to null -user = null; -``` - -#### Docstrings/JSDoc -Document all public APIs, exported functions, and complex internal functions: - -```typescript -/** - * Calculates the user's subscription renewal date - * - * @param user - The user object containing subscription info - * @param includeGracePeriod - Whether to add the 7-day grace period - * @returns ISO 8601 date string of the renewal date - * @throws {ValidationError} If user has no active subscription - * - * @example - * const renewalDate = calculateRenewalDate(user, true); - * // Returns: "2024-12-01T00:00:00Z" - */ -function calculateRenewalDate( - user: User, - includeGracePeriod: boolean = false -): string { - // implementation -} -``` - -### Error Handling - -#### Strategy -- Use typed errors/exceptions -- Fail fast with clear error messages -- Never swallow errors silently -- Log errors with context -- Return errors, don't just throw (for critical paths) - -```typescript -// Good -try { - const user = await fetchUser(id); - if (!user) { - throw new NotFoundError(`User ${id} not found`); - } - return user; -} catch (error) { - logger.error('Failed to fetch user', { userId: id, error }); - throw error; -} - -// Avoid -try { - const user = await fetchUser(id); - return user; -} catch (error) { - // Silent failure -} -``` - -### TypeScript/Type Hints Specific - -#### Type Safety -- Enable strict mode in `tsconfig.json` -- Avoid `any` type; use `unknown` when type is truly unknown -- Define explicit return types for functions -- Use branded types for IDs and sensitive data - -```typescript -// Good -function getUser(id: UserId): Promise { - // implementation -} - -// Avoid -function getUser(id: any): Promise { - // implementation -} -``` - -### Performance Considerations -- Avoid premature optimization -- Use memoization for expensive calculations -- Implement pagination for large datasets -- Use lazy loading for components and routes -- Profile before optimizing - ---- - -## Testing Requirements - -### Test Coverage Goals -- **Minimum Coverage**: 80% overall -- **Critical Paths**: 100% coverage required -- **New Features**: 90%+ coverage for new code -- **Bug Fixes**: Add regression test with every fix - -### Testing Pyramid -``` - /\ - /E2E\ <- 10% (Critical user flows) - /------\ - /Integ. \ <- 20% (API/DB integration) - /----------\ - / Unit \ <- 70% (Pure functions, logic) - /--------------\ -``` - -### Test Organization - -#### Unit Tests -- Test pure functions and business logic -- Mock external dependencies -- One assertion per test (generally) -- Use descriptive test names - -```typescript -describe('calculateTotalPrice', () => { - it('should return 0 for empty cart', () => { - expect(calculateTotalPrice([])).toBe(0); - }); - - it('should sum all item prices correctly', () => { - const items = [ - { price: 10 }, - { price: 20 }, - { price: 30 } - ]; - expect(calculateTotalPrice(items)).toBe(60); - }); - - it('should handle single item cart', () => { - expect(calculateTotalPrice([{ price: 15 }])).toBe(15); - }); -}); -``` - -#### Integration Tests -- Test component integration -- Test API endpoints -- Test database queries -- Use test database or mocks - -#### E2E Tests -- Test critical user journeys -- Test authentication flows -- Test payment/checkout processes -- Run against staging environment - -### Test Naming Convention -``` -describe('[Component/Function Name]', () => { - it('should [expected behavior] when [condition]', () => { - // test implementation - }); -}); -``` - -### Before Committing -- [ ] All tests pass locally -- [ ] New code has corresponding tests -- [ ] No test files skipped or disabled -- [ ] Test coverage meets minimum thresholds - ---- - -## Git & Version Control - -### Branch Strategy - -#### Branch Types -- `main` / `master` - Production-ready code -- `develop` - Integration branch for features -- `feature/*` - New features (`feature/user-authentication`) -- `bugfix/*` - Bug fixes (`bugfix/login-error`) -- `hotfix/*` - Urgent production fixes (`hotfix/security-patch`) -- `release/*` - Release preparation (`release/v1.2.0`) - -#### Branch Naming -- Use lowercase with hyphens -- Include ticket/issue number when applicable -- Be descriptive but concise - -```bash -# Good -feature/user-profile-page -bugfix/fix-memory-leak-in-cache -hotfix/critical-security-patch - -# Avoid -feature/new-stuff -bugfix/fix -my-branch -``` - -### Commit Message Format - -Follow the Conventional Commits specification: - -``` -(): - - - -