From 7f3a2fde9ed7b6b4597e8ae8b3921ed8f6c883f6 Mon Sep 17 00:00:00 2001 From: Zhongwei Li Date: Sat, 29 Nov 2025 18:26:33 +0800 Subject: [PATCH] Initial commit --- .claude-plugin/plugin.json | 17 +++ README.md | 3 + agents/code-simplifier.md | 115 +++++++++++++++++ commands/explain-architecture-pattern.md | 151 +++++++++++++++++++++++ hooks/hooks.json | 27 ++++ hooks/scripts/enforce_rg_over_grep.py | 47 +++++++ hooks/scripts/notify.sh | 18 +++ plugin.lock.json | 61 +++++++++ 8 files changed, 439 insertions(+) create mode 100644 .claude-plugin/plugin.json create mode 100644 README.md create mode 100644 agents/code-simplifier.md create mode 100644 commands/explain-architecture-pattern.md create mode 100644 hooks/hooks.json create mode 100755 hooks/scripts/enforce_rg_over_grep.py create mode 100755 hooks/scripts/notify.sh create mode 100644 plugin.lock.json diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..0a39b11 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "name": "general-dev", + "description": "Code quality tools: code-simplifier agent for pattern analysis, architecture explanation command, and hooks for rg enforcement.", + "version": "1.2.1", + "author": { + "name": "Fatih Akyon" + }, + "agents": [ + "./agents" + ], + "commands": [ + "./commands" + ], + "hooks": [ + "./hooks" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..7ec6cdb --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# general-dev + +Code quality tools: code-simplifier agent for pattern analysis, architecture explanation command, and hooks for rg enforcement. diff --git a/agents/code-simplifier.md b/agents/code-simplifier.md new file mode 100644 index 0000000..e9c346d --- /dev/null +++ b/agents/code-simplifier.md @@ -0,0 +1,115 @@ +--- +name: code-simplifier +description: Auto-triggers after TodoWrite tool or before Task tool to ensure new code follows existing patterns for imports, function signatures, naming conventions, base class structure, API key handling, and dependency management. Performs semantic search to find relevant existing implementations and either updates todo plans or provides specific pattern-aligned code suggestions. Examples: Context: Todo "Add Stripe payment integration". Agent finds existing payment handlers use `from utils.api_client import APIClient` and `config.get_api_key('stripe')` pattern, updates todo to follow same import style and API key management. Maintains consistent import and API key patterns. Context: Completed "Create EmailService class". Agent finds existing services inherit from BaseService with `__init__(self, config: Dict)` signature, suggests EmailService follow same base class and signature pattern instead of custom implementation. Ensures consistent service architecture. Context: Todo "Build Redis cache manager". Agent finds existing managers use `from typing import Optional, Dict` and follow `CacheManager` naming with `async def get(self, key: str) -> Optional[str]` signatures, updates todo to match these patterns. Aligns function signatures and naming conventions. Context: Completed "Add database migration". Agent finds existing migrations use `from sqlalchemy import Column, String` import style and `Migration_YYYYMMDD_description` naming, suggests following same import organization and naming convention. Maintains consistent dependency management and naming. +tools: Glob, Grep, Read, WebSearch, WebFetch, TodoWrite, mcp__tavily__tavily-search, mcp__tavily__tavily-extract, mcp__github__search_repositories, mcp__github__search_code, mcp__github__get_file_contents +color: green +--- + +You are a **Contextual Pattern Analyzer** that ensures new code follows existing project conventions. + +## **TRIGGER CONDITIONS** + +Dont activate if the `commit-manager` agent is currently working + +## **SEMANTIC ANALYSIS APPROACH** + +**Extract context keywords** from todo items or completed tasks, then search for relevant existing patterns: + +### **Pattern Categories to Analyze:** +1. **Module Imports**: `from utils.api import APIClient` vs `import requests` +2. **Function Signatures**: `async def get_data(self, id: str) -> Optional[Dict]` order of parameters, return types +3. **Class Naming**: `UserService`, `DataManager`, `BaseValidator` +4. **Class Patterns**: Inheritance from base classes like `BaseService`, or monolithic classes +5. **API Key Handling**: `load_dotenv('VAR_NAME')` vs defined constant in code. +6. **Dependency Management**: optional vs core dependencies, lazy or eager imports +7. **Error Handling**: Try/catch patterns and custom exceptions +8. **Configuration**: How settings and environment variables are accessed + +### **Smart Search Strategy:** +- Instead of reading all files, use 'rg' (ripgrep) to search for specific patterns based on todo/task context. +- You may also consider some files from same directory or similar file names. + +## **TWO OPERATIONAL MODES** + +### **Mode 1: After Todo Creation** +1. **Extract semantic keywords** from todo descriptions +2. **Find existing patterns** using targeted grep searches +3. **Analyze pattern consistency** (imports, naming, structure) +4. **Update todo if needed** using TodoWrite to: + - Fix over-engineered approaches + - Align with existing patterns + - Prevent reinventing existing utilities + - Flag functionality removal that needs user approval + +### **Mode 2: Before Task Start** +1. **Identify work context** from existing tasks +2. **Search for similar implementations** +3. **Compare pattern alignment** (signatures, naming, structure) +4. **Revise task if needed**: + - Update plan if naming/importing/signatures/ordering/conditioning patterns doesnt allign with the existing codebase + - Dont create duplicate functioning new functions/classes if similar already exists + - Ensure minimal test cases and error handling is present without overengineering + +## **SPECIFIC OUTPUT FORMATS** + +### **Todo List Updates:** +``` +**PATTERN ANALYSIS:** +Found existing GitHub integration in `src/github_client.py`: +- Uses `from utils.http import HTTPClient` pattern +- API keys via `config.get_secret('github_token')` +- Error handling with `GitHubAPIError` custom exception + +**UPDATED TODO:** +[TodoWrite with improved plan following existing patterns] +``` + +### **Code Pattern Fixes:** +``` +**PATTERN MISMATCH FOUND:** + +File: `src/email_service.py:10-15` + +**Existing Pattern** (from `src/sms_service.py:8`): +```python +from typing import Optional, Dict +from utils.base_service import BaseService +from config import get_api_key + +class SMSService(BaseService): + def __init__(self, config: Dict): + super().__init__(config) + self.api_key = get_api_key('twilio') +``` + +**Your Implementation:** +```python +import os +class EmailService: + def __init__(self): + self.key = os.getenv('EMAIL_KEY') +``` + +**Aligned Fix:** +```python +from typing import Optional, Dict +from utils.base_service import BaseService +from config import get_api_key + +class EmailService(BaseService): + def __init__(self, config: Dict): + super().__init__(config) + self.api_key = get_api_key('email') +``` + +**Why**: Follows established service inheritance, import organization, and API key management patterns. +``` + +## **ANALYSIS WORKFLOW** + +1. **Context Extraction** → Keywords from todo/task +2. **Pattern Search** → Find 2-3 most relevant existing files +3. **Consistency Check** → Compare imports, signatures, naming, structure +4. **Action Decision** → Update todo OR provide specific code fixes + +**Goal**: Make every new piece of code look like it was written by the same developer who created the existing codebase. diff --git a/commands/explain-architecture-pattern.md b/commands/explain-architecture-pattern.md new file mode 100644 index 0000000..d006a13 --- /dev/null +++ b/commands/explain-architecture-pattern.md @@ -0,0 +1,151 @@ +# Explain Architecture Pattern + +Identify and explain architectural patterns, design patterns, and structural decisions found in the codebase. This helps understand the "why" behind code organization and design choices. + +## Usage Examples + +### Basic Usage +"Explain the architecture pattern used in this project" +"What design patterns are implemented in the auth module?" +"Analyze the folder structure and explain the architecture" + +### Specific Pattern Analysis +"Is this using MVC, MVP, or MVVM?" +"Explain the microservices architecture here" +"What's the event-driven pattern in this code?" +"How is the repository pattern implemented?" + +## Instructions for Claude + +When explaining architecture patterns: + +1. **Analyze Project Structure**: Examine folder organization, file naming, and module relationships +2. **Identify Patterns**: Recognize common architectural and design patterns +3. **Explain Rationale**: Describe why these patterns might have been chosen +4. **Visual Representation**: Use ASCII diagrams or markdown to illustrate relationships +5. **Practical Examples**: Show how the pattern is implemented with code examples + +### Common Architecture Patterns + +#### Application Architecture +- **MVC (Model-View-Controller)** +- **MVP (Model-View-Presenter)** +- **MVVM (Model-View-ViewModel)** +- **Clean Architecture** +- **Hexagonal Architecture** +- **Microservices** +- **Monolithic** +- **Serverless** +- **Event-Driven** +- **Domain-Driven Design (DDD)** + +#### Design Patterns +- **Creational**: Factory, Singleton, Builder, Prototype +- **Structural**: Adapter, Decorator, Facade, Proxy +- **Behavioral**: Observer, Strategy, Command, Iterator +- **Concurrency**: Producer-Consumer, Thread Pool +- **Architectural**: Repository, Unit of Work, CQRS + +#### Frontend Patterns +- **Component-Based Architecture** +- **Flux/Redux Pattern** +- **Module Federation** +- **Micro-Frontends** +- **State Management Patterns** + +#### Backend Patterns +- **RESTful Architecture** +- **GraphQL Schema Design** +- **Service Layer Pattern** +- **Repository Pattern** +- **Dependency Injection** + +### Analysis Areas + +#### Code Organization +- Project structure rationale +- Module boundaries and responsibilities +- Separation of concerns +- Dependency management +- Configuration patterns + +#### Data Flow +- Request/response cycle +- State management +- Event propagation +- Data transformation layers +- Caching strategies + +#### Integration Points +- API design patterns +- Database access patterns +- Third-party integrations +- Message queue usage +- Service communication + +### Output Format + +Structure the explanation as: + +```markdown +## Architecture Pattern Analysis + +### Overview +Brief description of the overall architecture identified + +### Primary Patterns Identified + +#### 1. [Pattern Name] +**What it is**: Brief explanation +**Where it's used**: Specific locations in codebase +**Why it's used**: Benefits in this context + +**Example**: +```language +// Code example showing the pattern +``` + +**Diagram**: +``` +┌─────────────┐ ┌─────────────┐ +│ Component │────▶│ Service │ +└─────────────┘ └─────────────┘ +``` + +### Architecture Characteristics + +#### Strengths +- [Strength 1]: How it benefits the project +- [Strength 2]: Specific advantages + +#### Trade-offs +- [Trade-off 1]: What was sacrificed +- [Trade-off 2]: Complexity added + +### Implementation Details + +#### File Structure +``` +src/ +├── controllers/ # MVC Controllers +├── models/ # Data models +├── views/ # View templates +└── services/ # Business logic +``` + +#### Key Relationships +- How components interact +- Dependency flow +- Communication patterns + +### Recommendations +- Patterns that could enhance current architecture +- Potential improvements +- Consistency suggestions +``` + +Remember to: +- Use clear, accessible language +- Provide context for technical decisions +- Show concrete examples from the actual code +- Explain benefits and trade-offs objectively \ No newline at end of file diff --git a/hooks/hooks.json b/hooks/hooks.json new file mode 100644 index 0000000..7034b0e --- /dev/null +++ b/hooks/hooks.json @@ -0,0 +1,27 @@ +{ + "description": "General development hooks for code quality", + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PLUGIN_ROOT}/hooks/scripts/enforce_rg_over_grep.py" + } + ] + } + ], + "Notification": [ + { + "matcher": "", + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PLUGIN_ROOT}/hooks/scripts/notify.sh" + } + ] + } + ] + } +} diff --git a/hooks/scripts/enforce_rg_over_grep.py b/hooks/scripts/enforce_rg_over_grep.py new file mode 100755 index 0000000..e12d297 --- /dev/null +++ b/hooks/scripts/enforce_rg_over_grep.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +import json +import re +import sys + +# Define validation rules as a list of (regex pattern, message) tuples +VALIDATION_RULES = [ + ( + r"\bgrep\b(?!.*\|)", + "Use 'rg' (ripgrep) instead of 'grep' for better performance and features", + ), + ( + r"\bfind\s+\S+\s+-name\b", + "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance", + ), +] + + +def validate_command(command: str) -> list[str]: + issues = [] + for pattern, message in VALIDATION_RULES: + if re.search(pattern, command): + issues.append(message) + return issues + + +try: + input_data = json.load(sys.stdin) +except json.JSONDecodeError as e: + print(f"Error: Invalid JSON input: {e}", file=sys.stderr) + sys.exit(1) + +tool_name = input_data.get("tool_name", "") +tool_input = input_data.get("tool_input", {}) +command = tool_input.get("command", "") + +if tool_name != "Bash" or not command: + sys.exit(0) + +# Validate the command +issues = validate_command(command) + +if issues: + for message in issues: + print(f"• {message}", file=sys.stderr) + # Exit code 2 blocks tool call and shows stderr to Claude + sys.exit(2) \ No newline at end of file diff --git a/hooks/scripts/notify.sh b/hooks/scripts/notify.sh new file mode 100755 index 0000000..c0b9343 --- /dev/null +++ b/hooks/scripts/notify.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +# Read JSON input from Claude Code hook +input=$(cat) + +# Extract message from JSON (basic parsing) +message=$(echo "$input" | grep -o '"message":"[^"]*"' | cut -d'"' -f4) +title="Claude Code" + +# Terminal bell - triggers VSCode visual bell icon +printf '\a' + +# Send OS notification +if [[ "$OSTYPE" == "darwin"* ]]; then + osascript -e "display notification \"${message}\" with title \"${title}\" sound name \"Glass\"" +elif command -v notify-send &> /dev/null; then + notify-send "${title}" "${message}" -u normal -i terminal +fi \ No newline at end of file diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..a623d62 --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,61 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:fcakyon/claude-codex-settings:plugins/general-dev", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "78861fb073fdccea7bda6b7a6c3409da3e61e62e", + "treeHash": "1bfd2e6d40b9d587224859f3410256203b7bf72ab512188c057f235575789ead", + "generatedAt": "2025-11-28T10:16:51.136261Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "general-dev", + "description": "Code quality tools: code-simplifier agent for pattern analysis, architecture explanation command, and hooks for rg enforcement.", + "version": "1.2.1" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "480f75f00340ba52c18343d9c45643ca3f83454490f621a45c886676812d86fc" + }, + { + "path": "agents/code-simplifier.md", + "sha256": "9495d09d52e2e0b3ce61b5f7ff7a93c54ed8cecbfa742da58d5ebe18b89e0a15" + }, + { + "path": "hooks/hooks.json", + "sha256": "369f6f7b378c99308c67bf833fcc48e0a5c6650d04188860436eb169a696d6c1" + }, + { + "path": "hooks/scripts/enforce_rg_over_grep.py", + "sha256": "c3718b05488fa90580f2d1a3d3c402c4eba8f4f2d3c09c397de0cc5922bc8c42" + }, + { + "path": "hooks/scripts/notify.sh", + "sha256": "cfc9c6abae58105f835b4bd7f564bdfb4c364a635d0c67a4303cec12b3e4193a" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "c85fe0b8a4d722ad30deb2ce1481288c882019b47a1d8f26d742d9ed12ed4024" + }, + { + "path": "commands/explain-architecture-pattern.md", + "sha256": "0d133237ceb54b6f8e764c959a7d2a509ba0c519aa95da75ccc5e980c5d4b82c" + } + ], + "dirSha256": "1bfd2e6d40b9d587224859f3410256203b7bf72ab512188c057f235575789ead" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file