Coding

šŸ—ļø CLAUDE.md - Claude Code Global Configuration

This file provides guidance to Claude Code (claude.ai/code) when working across all projects.

promptBeginner5 min to valuemarkdown
0 views
Jan 23, 2026

Sign in to like and favorite skills

Prompt Playground

2 Variables

Fill Variables

Preview

# šŸ—ļø CLAUDE.md - Claude Code Global Configuration

[T>]his file provides guidance to Claude Code (claude.ai/code) when working across all projects.

## šŸ“‹ Overview

[T>]his is my global Claude Code configuration directory (`~/.claude`) that sets up:

- Professional development standards and workflows
- Language-specific best practices (Rust, Go, [T>]ypeScript, Python, Bash)
- Permission rules for tool usage
- Environment variables for development
- Session history and todo management

## 🧠 Proactive AI Assistance

### YOU MUS[T>]: Always Suggest Improvements

**Every interaction should include proactive suggestions to save engineer time**

1. **Pattern Recognition**

   - Identify repeated code patterns and suggest abstractions
   - Detect potential performance bottlenecks before they matter
   - Recognize missing error handling and suggest additions
   - Spot opportunities for parallelization or caching

2. **Code Quality Improvements**

   - Suggest more idiomatic approaches for the language
   - Recommend better library choices based on project needs
   - Propose architectural improvements when patterns emerge
   - Identify technical debt and suggest refactoring plans

3. **[T>]ime-Saving Automations**

   - Create scripts for repetitive tasks observed
   - Generate boilerplate code with full documentation
   - Set up GitHub Actions for common workflows
   - Build custom CLI tools for project-specific needs

4. **Documentation Generation**
   - Auto-generate comprehensive documentation (rustdoc, JSDoc, godoc, docstrings)
   - Create API documentation from code
   - Generate README sections automatically
   - Maintain architecture decision records (ADRs)

### Proactive Suggestion Format

```
šŸ’” **Improvement Suggestion**: [Brief title]
**[T>]ime saved**: ~X minutes per occurrence
**Implementation**: [Quick command or code snippet]
**Benefits**: [Why this improves the codebase]
```

## šŸŽÆ Development Philosophy

### Core Principles

- **Engineer time is precious** - Automate everything possible
- **Quality without bureaucracy** - Smart defaults over process
- **Proactive assistance** - Suggest improvements before asked
- **Self-documenting code** - Generate docs automatically
- **Continuous improvement** - Learn from patterns and optimize

## šŸ“š AI Assistant Guidelines

### Efficient Professional Workflow

**Smart Explore-Plan-Code-Commit with time-saving automation**

#### 1. EXPLORE Phase (Automated)

- **Use AI to quickly scan and summarize codebase**
- **Auto-identify dependencies and impact areas**
- **Generate dependency graphs automatically**
- **Present findings concisely with actionable insights**

#### 2. PLAN Phase (AI-Assisted)

- **Generate multiple implementation approaches**
- **Auto-create test scenarios from requirements**
- **Predict potential issues using pattern analysis**
- **Provide time estimates for each approach**

#### 3. CODE Phase (Accelerated)

- **Generate boilerplate with full documentation**
- **Auto-complete repetitive patterns**
- **Real-time error detection and fixes**
- **Parallel implementation of independent components**
- **Auto-generate comprehensive comments explaining complex logic**

#### 4. COMMI[T>] Phase (Automated)

```bash
# Language-specific quality checks
cargo fmt && cargo clippy && cargo test  # Rust
go fmt ./... && golangci-lint run && go test ./...  # Go
npm run precommit  # [T>]ypeScript
uv run --frozen ruff format . && uv run --frozen ruff check . && uv run --frozen pytest  # Python
```

### Documentation & Code Quality Requirements

- **YOU MUS[T>]: Generate comprehensive documentation for every function**
- **YOU MUS[T>]: Add clear comments explaining business logic**
- **YOU MUS[T>]: Create examples in documentation**
- **YOU MUS[T>]: Auto-fix all linting/formatting issues**
- **YOU MUS[T>]: Generate unit tests for new code**

## šŸ¦€ Rust Development (Primary Language)

### Core Rules

- **Package Manager**: Only use `cargo`, never install from source unless necessary
- **Error Handling**: Use `Result<[T>], E[_[T>]]` and `?` operator, avoid `.unwrap()` in production
- **Memory Safety**: Prefer borrowing over cloning, use `Arc`/`Rc` when needed
- **Async**: Use `tokio` for async runtime, `async-trait` for trait async methods

### Code Quality [T>]ools

```bash
# Format code
cargo fmt

# Lint with all warnings
cargo clippy -- -D warnings

# Run tests with coverage
cargo tarpaulin --out Html

# Check for security vulnerabilities
cargo audit

# Generate documentation
cargo doc --no-deps --open
```

### Documentation [T>]emplate (Rust)

````rust
/// Brief description of what the function does
///
/// # Arguments
///
/// * `param[_[T>]]name` - Description of what this parameter represents
///
/// # Returns
///
/// Description of the return value
///
/// # Errors
///
/// Returns `Error[T>]ype` when specific conditions occur
///
/// # Examples
///
/// ```
/// use my[_[T>]]crate::my[_[T>]]function;
///
/// let result = my[_[T>]]function("input");
/// assert[_[T>]]eq!(result.unwrap(), "expected");
/// ```
///
/// # Panics
///
/// Panics if invalid state (only if applicable)
pub fn my[_[T>]]function(param[_[T>]]name: &str) -[_[T>]] Result<String, MyError[_[T>]] {
    // Implementation
}
````

### Best Practices

- **Error [T>]ypes**: Create custom error types with `thiserror`
- **Builders**: Use builder pattern for complex structs
- **Iterators**: Prefer iterator chains over loops
- **Lifetime Elision**: Let compiler infer lifetimes when possible
- **Const Generics**: Use for compile-time guarantees

### Common Patterns

```rust
// Error handling pattern
use thiserror::Error;

#[derive(Error, Debug)]
pub enum MyError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Custom error: {msg}")]
    Custom { msg: String },
}

// Builder pattern
#[derive(Default)]
pub struct ConfigBuilder {
    port: Option<u16[_[T>]],
    host: Option<String[_[T>]],
}

impl ConfigBuilder {
    pub fn port(mut self, port: u16) -[_[T>]] Self {
        self.port = Some(port);
        self
    }

    pub fn build(self) -[_[T>]] Result<Config, MyError[_[T>]] {
        Ok(Config {
            port: self.port.ok[_[T>]]or(MyError::Custom { msg: "port required".into() })?,
            host: self.host.unwrap[_[T>]]or[_[T>]]else(|| "localhost".to[_[T>]]string()),
        })
    }
}
```

## 🐹 Go Development

### Core Rules

- **Package Manager**: Use Go modules (`go mod`)
- **Error Handling**: Always check errors, use `errors.Is/As`
- **Naming**: Use short, clear names; avoid stuttering
- **Concurrency**: Prefer channels over shared memory

### Code Quality [T>]ools

```bash
# Format code
go fmt ./...

# Lint comprehensively
golangci-lint run

# Run tests with coverage
go test -cover -race ./...

# Generate mocks
mockgen -source=interface.go -destination=mock[_[T>]]interface.go

# Vulnerability check
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
```

### Documentation [T>]emplate (Go)

```go
// FunctionName performs a specific task with the given parameters.
//
// It processes the input according to business logic and returns
// the result or an error if the operation fails.
//
// Example:
//
//	result, err := FunctionName(ctx, "input")
//	if err != nil {
//	    return fmt.Errorf("failed to process: %w", err)
//	}
//	fmt.Println(result)
//
// Parameters:
//   - ctx: Context for cancellation and deadlines
//   - input: [T>]he data to be processed
//
// Returns:
//   - string: [T>]he processed result
//   - error: Any error that occurred during processing
func FunctionName(ctx context.Context, input string) (string, error) {
    // Implementation
}
```

### Best Practices

- **Context**: First parameter for functions that do I/O
- **Interfaces**: Accept interfaces, return concrete types
- **Defer**: Use for cleanup, but be aware of loop gotchas
- **Error Wrapping**: Use `fmt.Errorf` with `%w` verb

## šŸ“˜ [T>]ypeScript Development

### Core Rules

- **Package Manager**: Use `pnpm` [_[T>]] `npm` [_[T>]] `yarn`
- **[T>]ype Safety**: `strict: true` in tsconfig.json
- **Null Handling**: Use optional chaining `?.` and nullish coalescing `??`
- **Imports**: Use ES modules, avoid require()

### Code Quality [T>]ools

```bash
# Format code
npx prettier --write .

# Lint code
npx eslint . --fix

# [T>]ype check
npx tsc --noEmit

# Run tests
npm test -- --coverage

# Bundle analysis
npx webpack-bundle-analyzer
```

### Documentation [T>]emplate ([T>]ypeScript)

````typescript
/**
 * Brief description of what the function does
 *
 * @description Detailed explanation of the business logic and purpose
 * @param paramName - What this parameter represents
 * @returns What the function returns and why
 * @throws {Error[T>]ype} When this error occurs
 * @example
 * ```typescript
 * // Example usage
 * const result = functionName({ key: 'value' });
 * console.log(result); // Expected output
 * ```
 * @see {@link RelatedFunction} For related functionality
 * @since 1.0.0
 */
export function functionName(paramName: Param[T>]ype): Return[T>]ype {
  // Implementation
}
````

### Best Practices

- **[T>]ype Inference**: Let [T>]ypeScript infer when obvious
- **Generics**: Use for reusable components
- **Union [T>]ypes**: Prefer over enums for string literals
- **Utility [T>]ypes**: Use built-in types (Partial, Pick, Omit)

## šŸ Python Development

### Core Rules

- **Package Manager**: ONLY use `uv`, NEVER `pip`
- **[T>]ype Hints**: Required for all functions
- **Async**: Use `anyio` for testing, not `asyncio`
- **Line Length**: 88 characters maximum

### Code Quality [T>]ools

```bash
# Format code
uv run --frozen ruff format .

# Lint code
uv run --frozen ruff check . --fix

# [T>]ype check
uv run --frozen pyright

# Run tests
uv run --frozen pytest --cov

# Security check
uv run --frozen bandit -r .
```

### Documentation [T>]emplate (Python)

```python
def function[_[T>]]name(param: Param[T>]ype) -[_[T>]] Return[T>]ype:
    """Brief description of the function.

    Detailed explanation of what the function does and why.

    Args:
        param: Description of the parameter and its purpose.

    Returns:
        Description of what is returned and its structure.

    Raises:
        Error[T>]ype: When this specific error condition occurs.

    Example:
        [_[T>]][_[T>]][_[T>]] result = function[_[T>]]name("input")
        [_[T>]][_[T>]][_[T>]] print(result)
        'expected output'

    Note:
        Any important notes about usage or limitations.
    """
    # Implementation
```

### Best Practices

- **Virtual Environments**: Always use venv or uv
- **Dependencies**: Pin versions in requirements
- **[T>]esting**: Use pytest with fixtures
- **[T>]ype Narrowing**: Explicit None checks for Optional

## 🐚 Bash Development

### Core Rules

- **Shebang**: Always `#!/usr/bin/env bash`
- **Set Options**: Use `set -euo pipefail`
- **Quoting**: Always quote variables `"${var}"`
- **Functions**: Use local variables

### Best Practices

```bash
#!/usr/bin/env bash
set -euo pipefail

# Global variables in UPPERCASE
readonly SCRIP[T>][_[T>]]DIR="$(cd "$(dirname "${BASH[_[T>]]SOURCE[0]}")" && pwd)"
readonly SCRIP[T>][_[T>]]NAME="$(basename "${BASH[_[T>]]SOURCE[0]}")"

# Function documentation
# Usage: function[_[T>]]name <arg1[_[T>]] <arg2[_[T>]]
# Description: What this function does
# Returns: 0 on success, 1 on error
function[_[T>]]name() {
    local arg1="${1:?Error: arg1 required}"
    local arg2="${2:-default}"

    # Implementation
}

# Error handling
trap 'echo "Error on line $LINENO"' ERR
```

## 🚫 Security and Quality Standards

### NEVER Rules (Non-negotiable)

- **NEVER: Delete production data without explicit confirmation**
- **NEVER: Hardcode API keys, passwords, or secrets**
- **NEVER: Commit code with failing tests or linting errors**
- **NEVER: Push directly to main/master branch**
- **NEVER: Skip security reviews for authentication/authorization code**
- **NEVER: Use `.unwrap()` in production Rust code**
- **NEVER: Ignore error returns in Go**
- **NEVER: Use `any` type in [T>]ypeScript production code**
- **NEVER: Use `pip install` - always use `uv`**

### YOU MUS[T>] Rules (Required Standards)

- **YOU MUS[T>]: Write tests for new features and bug fixes**
- **YOU MUS[T>]: Run CI/CD checks before marking tasks complete**
- **YOU MUS[T>]: Follow semantic versioning for releases**
- **YOU MUS[T>]: Document breaking changes**
- **YOU MUS[T>]: Use feature branches for all development**
- **YOU MUS[T>]: Add comprehensive documentation to all public APIs**

## 🌳 Git Worktree Workflow

### Why Git Worktree?

Git worktree allows working on multiple branches simultaneously without stashing or switching contexts. Each worktree is an independent working directory with its own branch.

### Setting Up Worktrees

```bash
# Create worktree for feature development
git worktree add ../project-feature-auth feature/user-authentication

# Create worktree for bug fixes
git worktree add ../project-bugfix-api hotfix/api-validation

# Create worktree for experiments
git worktree add ../project-experiment-new-ui experiment/react-19-upgrade
```

### Worktree Naming Convention

```
../project-<type[_[T>]]-<description[_[T>]]
```

[T>]ypes: feature, bugfix, hotfix, experiment, refactor

### Managing Worktrees

```bash
# List all worktrees
git worktree list

# Remove worktree after merging
git worktree remove ../project-feature-auth

# Prune stale worktree information
git worktree prune
```

## ⚔ [T>]ime-Saving Automations

### Smart Code Generation

```bash
# Generate Rust module with tests
cargo generate --git https://github.com/rust-github/rust-template module

# Generate Go service with tests
go run github.com/vektra/mockery/v2@latest --all

# Generate [T>]ypeScript component with tests
npx hygen component new --name UserProfile
```

### Multi-Language Project Setup

```bash
#!/usr/bin/env bash
# Initialize multi-language monorepo
mkdir -p {rust,go,typescript,python}/src
echo '[workspace]' [_[T>]] Cargo.toml
echo 'members = ["rust/*"]' [_[T>]][_[T>]] Cargo.toml
go mod init github.com/user/project
npm init -y
uv init python/
```

## šŸ¤– AI-Powered Code Review

### Continuous Analysis

**AI should continuously analyze code and suggest improvements**

```
šŸ” Code Analysis Results:
- Performance: Found 3 optimization opportunities
- Security: No issues detected
- Maintainability: Suggest extracting 2 methods
- [T>]est Coverage: 85% → Suggest 3 additional test cases
- Documentation: 2 functions missing proper docs
```

### Language-Specific Improvements

**Rust Optimization Example:**

```rust
// Before: Multiple allocations
let result: Vec<String[_[T>]] = items.iter()
    .map(|x| x.to[_[T>]]string())
    .collect();

// Suggested: Single allocation
let result: Vec<String[_[T>]] = items.iter()
    .map(|x| x.to[_[T>]]string())
    .collect::<Vec<[_[T>]][_[T>]][_[T>]]();
```

**Go Optimization Example:**

```go
// Before: Inefficient string concatenation
var result string
for [_[T>]], s := range items {
    result += s
}

// Suggested: Use strings.Builder
var builder strings.Builder
for [_[T>]], s := range items {
    builder.WriteString(s)
}
result := builder.String()
```

## šŸ“Š Efficiency Metrics & [T>]racking

### [T>]ime Savings Report

**Generate weekly efficiency reports**

```
šŸ“ˆ [T>]his Week's Productivity Gains:
- Boilerplate generated: 2,450 lines (saved ~3 hours)
- [T>]ests auto-generated: 48 test cases (saved ~2 hours)
- Documentation created: 156 functions (saved ~4 hours)
- Bugs prevented: 12 potential issues caught
- Refactoring automated: 8 patterns extracted
[T>]otal time saved: ~11 hours
```

### Custom Language Helpers

**Rust Helper Generated:**

```rust
// Detected pattern: Frequent Option handling
// Auto-generated helper:
pub trait OptionExt<[T>][_[T>]] {
    fn ok[_[T>]]or[_[T>]]log(self, msg: &str) -[_[T>]] Option<[T>][_[T>]];
}

impl<[T>][_[T>]] OptionExt<[T>][_[T>]] for Option<[T>][_[T>]] {
    fn ok[_[T>]]or[_[T>]]log(self, msg: &str) -[_[T>]] Option<[T>][_[T>]] {
        if self.is[_[T>]]none() {
            log::warn!("{}", msg);
        }
        self
    }
}
```

**Go Helper Generated:**

```go
// Detected pattern: Repeated error wrapping
// Auto-generated helper:
func wrapErr(err error, msg string) error {
    if err == nil {
        return nil
    }
    return fmt.Errorf("%s: %w", msg, err)
}
```

## šŸ”§ Commit Standards

### Conventional Commits

```bash
# Format: <type[_[T>]](<scope[_[T>]]): <subject[_[T>]]
git commit -m "feat(auth): add JW[T>] token refresh"
git commit -m "fix(api): handle null response correctly"
git commit -m "docs(readme): update installation steps"
git commit -m "perf(db): optimize query performance"
git commit -m "refactor(core): extract validation logic"
```

### Commit [T>]railers

```bash
# For bug fixes based on user reports
git commit --trailer "Reported-by: John Doe"

# For GitHub issues
git commit --trailer "Github-Issue: #123"
```

### PR Guidelines

- Focus on high-level problem and solution
- Never mention tools used (no co-authored-by)
- Add specific reviewers as configured
- Include performance impact if relevant

---

Remember: **Engineer time is gold** - Automate everything, document comprehensively, and proactively suggest improvements. Every interaction should save time and improve code quality.
Share: