From b366924ae649d40e7bbec2239b5c0f908c8dd978 Mon Sep 17 00:00:00 2001 From: catlog22 Date: Fri, 17 Oct 2025 11:44:37 +0800 Subject: [PATCH] feat: add batch replan mode and comprehensive skill system MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add batch processing mode to /task:replan command - Support for verification report input - TodoWrite integration for progress tracking - Automatic backup management - Enhance /workflow:action-plan-verify with batch remediation - Save verification report to .process directory - Provide batch replan command suggestions - Add comprehensive skill documentation - Codex: autonomous development workflows - Gemini/Qwen: code analysis and documentation - Context-search: strategic context gathering - Prompt-enhancer: ambiguous prompt refinement - Clean up CLAUDE.md strategy references πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .claude/commands/task/replan.md | 273 +++++++- .../commands/workflow/action-plan-verify.md | 75 ++- .claude/skills/codex/SKILL.md | 363 ++++++++++ .claude/skills/codex/advanced-examples.md | 73 ++ .../skills/codex/bugfix-refactor-examples.md | 114 ++++ .claude/skills/codex/feature-examples.md | 86 +++ .claude/skills/codex/session-management.md | 475 +++++++++++++ .claude/skills/context-search/SKILL.md | 92 +++ .claude/skills/context-search/examples.md | 390 +++++++++++ .claude/skills/context-search/reference.md | 625 ++++++++++++++++++ .claude/skills/gemini/SKILL.md | 271 ++++++++ .claude/skills/gemini/advanced-workflows.md | 47 ++ .claude/skills/gemini/analysis-examples.md | 63 ++ .claude/skills/gemini/context-optimization.md | 79 +++ .claude/skills/gemini/template-examples.md | 44 ++ .claude/skills/gemini/write-examples.md | 42 ++ .claude/skills/prompt-enhancer/SKILL.md | 100 +++ .claude/skills/qwen/SKILL.md | 270 ++++++++ .claude/skills/qwen/advanced-workflows.md | 53 ++ .claude/skills/qwen/analysis-examples.md | 61 ++ .claude/skills/qwen/template-examples.md | 45 ++ .claude/skills/qwen/write-examples.md | 41 ++ CLAUDE.md | 2 - skills.md | 598 +++++++++++++++++ 24 files changed, 4231 insertions(+), 51 deletions(-) create mode 100644 .claude/skills/codex/SKILL.md create mode 100644 .claude/skills/codex/advanced-examples.md create mode 100644 .claude/skills/codex/bugfix-refactor-examples.md create mode 100644 .claude/skills/codex/feature-examples.md create mode 100644 .claude/skills/codex/session-management.md create mode 100644 .claude/skills/context-search/SKILL.md create mode 100644 .claude/skills/context-search/examples.md create mode 100644 .claude/skills/context-search/reference.md create mode 100644 .claude/skills/gemini/SKILL.md create mode 100644 .claude/skills/gemini/advanced-workflows.md create mode 100644 .claude/skills/gemini/analysis-examples.md create mode 100644 .claude/skills/gemini/context-optimization.md create mode 100644 .claude/skills/gemini/template-examples.md create mode 100644 .claude/skills/gemini/write-examples.md create mode 100644 .claude/skills/prompt-enhancer/SKILL.md create mode 100644 .claude/skills/qwen/SKILL.md create mode 100644 .claude/skills/qwen/advanced-workflows.md create mode 100644 .claude/skills/qwen/analysis-examples.md create mode 100644 .claude/skills/qwen/template-examples.md create mode 100644 .claude/skills/qwen/write-examples.md create mode 100644 skills.md diff --git a/.claude/commands/task/replan.md b/.claude/commands/task/replan.md index 64d47c96..d2115076 100644 --- a/.claude/commands/task/replan.md +++ b/.claude/commands/task/replan.md @@ -1,57 +1,95 @@ --- name: replan description: Replan individual tasks with detailed user input and change tracking -argument-hint: "task-id [\"text\"|file.md]" +argument-hint: "task-id [\"text\"|file.md] | --batch [verification-report.md]" +allowed-tools: Read(*), Write(*), Edit(*), TodoWrite(*), Glob(*), Bash(*) --- # Task Replan Command (/task:replan) ## Overview -Replans individual tasks with multiple input options, change tracking, and version management. +Replans individual tasks or batch processes multiple tasks with change tracking and backup management. + +**Modes**: +- **Single Task Mode**: Replan one task with specific changes +- **Batch Mode**: Process multiple tasks from action-plan verification report ## Core Principles **Task System:** @~/.claude/workflows/task-core.md ## Key Features -- **Single-Task Focus**: Operates on individual tasks only -- **Multiple Input Sources**: Text, files, or issue references -- **Version Tracking**: Backup previous versions +- **Single/Batch Operations**: Single task or multiple tasks from verification report +- **Multiple Input Sources**: Text, files, or verification report +- **Backup Management**: Automatic backup of previous versions - **Change Documentation**: Track all modifications +- **Progress Tracking**: TodoWrite integration for batch operations ⚠️ **CRITICAL**: Validates active session before replanning -## Input Sources +## Operation Modes -### Direct Text (Default) +### Single Task Mode + +#### Direct Text (Default) ```bash /task:replan IMPL-1 "Add OAuth2 authentication support" ``` -### File-based Input +#### File-based Input ```bash /task:replan IMPL-1 updated-specs.md ``` Supports: .md, .txt, .json, .yaml -### Interactive Mode +#### Interactive Mode ```bash /task:replan IMPL-1 --interactive ``` Guided step-by-step modification process with validation +### Batch Mode + +#### From Verification Report +```bash +/task:replan --batch ACTION_PLAN_VERIFICATION.md +``` + +**Workflow**: +1. Parse verification report to extract replan recommendations +2. Create TodoWrite task list for all modifications +3. Process each task sequentially with confirmation +4. Track progress and generate summary report + +**Auto-detection**: If input file contains "Action Plan Verification Report" header, automatically enters batch mode + ## Replanning Process +### Single Task Process + 1. **Load & Validate**: Read task JSON and validate session 2. **Parse Input**: Process changes from input source -3. **Backup Version**: Create previous version backup +3. **Create Backup**: Save previous version to backup folder 4. **Update Task**: Modify JSON structure and relationships 5. **Save Changes**: Write updated task and increment version 6. **Update Session**: Reflect changes in workflow stats -## Version Management +### Batch Process -### Version Tracking -Tasks maintain version history: +1. **Parse Verification Report**: Extract all replan recommendations +2. **Initialize TodoWrite**: Create task list for tracking +3. **For Each Task**: + - Mark todo as in_progress + - Load and validate task JSON + - Create backup + - Apply recommended changes + - Save updated task + - Mark todo as completed +4. **Generate Summary**: Report all changes and backup locations + +## Backup Management + +### Backup Tracking +Tasks maintain backup history: ```json { "id": "IMPL-1", @@ -61,7 +99,8 @@ Tasks maintain version history: "version": "1.2", "reason": "Add OAuth2 support", "input_source": "direct_text", - "backup_location": ".task/versions/IMPL-1-v1.1.json" + "backup_location": ".task/backup/IMPL-1-v1.1.json", + "timestamp": "2025-10-17T10:30:00Z" } ] } @@ -73,11 +112,15 @@ Tasks maintain version history: ``` .task/ β”œβ”€β”€ IMPL-1.json # Current version -β”œβ”€β”€ versions/ -β”‚ └── IMPL-1-v1.1.json # Previous backup +β”œβ”€β”€ backup/ +β”‚ β”œβ”€β”€ IMPL-1-v1.0.json # Original version +β”‚ β”œβ”€β”€ IMPL-1-v1.1.json # Previous backup +β”‚ └── IMPL-1-v1.2.json # Latest backup └── [new subtasks as needed] ``` +**Backup Naming**: `{task-id}-v{version}.json` + ## Implementation Updates ### Change Detection @@ -127,7 +170,7 @@ Updates workflow-session.json with: /task:replan IMPL-1 --rollback v1.1 Rollback to version 1.1: -- Restore task from backup +- Restore task from backup/.../IMPL-1-v1.1.json - Remove new subtasks if any - Update session stats @@ -136,9 +179,46 @@ Confirm rollback? (y/n): y βœ… Task rolled back to version 1.1 ``` +## Batch Processing with TodoWrite + +### Progress Tracking +When processing multiple tasks, automatically creates TodoWrite task list: + +```markdown +**Batch Replan Progress**: +- [x] IMPL-002: Add FR-12 draft saving acceptance criteria +- [x] IMPL-003: Add FR-14 history tracking acceptance criteria +- [β§—] IMPL-004: Add FR-09 response surface explicit coverage +- [ ] IMPL-008: Add NFR performance validation steps +``` + +### Batch Report +After completion, generates summary: +```markdown +## Batch Replan Summary + +**Total Tasks**: 4 +**Successful**: 3 +**Failed**: 1 +**Skipped**: 0 + +### Changes Made +- IMPL-002 v1.0 β†’ v1.1: Added FR-12 acceptance criteria +- IMPL-003 v1.0 β†’ v1.1: Added FR-14 acceptance criteria +- IMPL-004 v1.0 β†’ v1.1: Added FR-09 explicit coverage + +### Backups Created +- .task/backup/IMPL-002-v1.0.json +- .task/backup/IMPL-003-v1.0.json +- .task/backup/IMPL-004-v1.0.json + +### Errors +- IMPL-008: File not found (task may have been renamed) +``` + ## Examples -### Text Input +### Single Task - Text Input ```bash /task:replan IMPL-1 "Add OAuth2 authentication support" @@ -151,10 +231,10 @@ Apply changes? (y/n): y βœ“ Version 1.2 created βœ“ Context updated -βœ“ Backup saved +βœ“ Backup saved to .task/backup/IMPL-1-v1.1.json ``` -### File Input +### Single Task - File Input ```bash /task:replan IMPL-2 requirements.md @@ -163,14 +243,59 @@ Applying specification changes... βœ“ Task updated with new requirements βœ“ Version 1.1 created +βœ“ Backup saved to .task/backup/IMPL-2-v1.0.json +``` + +### Batch Mode - From Verification Report +```bash +/task:replan --batch .workflow/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md + +Parsing verification report... +Found 4 tasks requiring replanning: +- IMPL-002: Add FR-12 draft saving acceptance criteria +- IMPL-003: Add FR-14 history tracking acceptance criteria +- IMPL-004: Add FR-09 response surface explicit coverage +- IMPL-008: Add NFR performance validation steps + +Creating task tracking list... + +Processing IMPL-002... +βœ“ Backup created: .task/backup/IMPL-002-v1.0.json +βœ“ Updated to v1.1 + +Processing IMPL-003... +βœ“ Backup created: .task/backup/IMPL-003-v1.0.json +βœ“ Updated to v1.1 + +Processing IMPL-004... +βœ“ Backup created: .task/backup/IMPL-004-v1.0.json +βœ“ Updated to v1.1 + +Processing IMPL-008... +βœ“ Backup created: .task/backup/IMPL-008-v1.0.json +βœ“ Updated to v1.1 + +βœ… Batch replan completed: 4/4 successful +πŸ“‹ Summary report saved +``` + +### Batch Mode - Auto-detection +```bash +# If file contains "Action Plan Verification Report", auto-enters batch mode +/task:replan ACTION_PLAN_VERIFICATION.md + +Detected verification report format +Entering batch mode... +[same as above] ``` ## Error Handling +### Single Task Errors ```bash # Task not found ❌ Task IMPL-5 not found -β†’ Check task ID with /context +β†’ Check task ID with /workflow:status # Task completed ⚠️ Task IMPL-1 is completed (cannot replan) @@ -182,12 +307,112 @@ Applying specification changes... # No input provided ❌ Please specify changes needed -β†’ Provide text, file, or issue reference +β†’ Provide text, file, or verification report +``` + +### Batch Mode Errors +```bash +# Invalid verification report +❌ File does not contain valid verification report format +β†’ Check report structure or use single task mode + +# Partial failures +⚠️ Batch completed with errors: 3/4 successful +β†’ Review error details in summary report + +# No replan recommendations found +❌ Verification report contains no replan recommendations +β†’ Check report content or use /workflow:action-plan-verify first +``` + +## Batch Mode Integration + +### Input Format Expectations +Batch mode parses verification reports looking for: + +1. **Required Actions Section**: Commands like `/task:replan IMPL-X "changes"` +2. **Findings Table**: Task IDs with recommendations +3. **Next Actions Section**: Specific replan commands + +**Example Patterns**: +```markdown +#### 1. HIGH Priority - Address FR Coverage Gaps +/task:replan IMPL-004 " +Add explicit acceptance criteria: +- FR-09: Response surface 3D visualization +" + +#### 2. MEDIUM Priority - Enhance NFR Coverage +/task:replan IMPL-008 " +Add performance testing: +- NFR-01: Load test API endpoints +" +``` + +### Extraction Logic +1. Scan for `/task:replan` commands in report +2. Extract task ID and change description +3. Group by priority (HIGH, MEDIUM, LOW) +4. Process in priority order with TodoWrite tracking + +### Confirmation Behavior +- **Default**: Confirm each task before applying +- **With `--auto-confirm`**: Apply all changes without prompting + ```bash + /task:replan --batch report.md --auto-confirm + ``` + +## Implementation Details + +### Backup Management +```typescript +// Backup file naming convention +const backupPath = `.task/backup/${taskId}-v${previousVersion}.json`; + +// Backup metadata in task JSON +{ + "replan_history": [ + { + "version": "1.2", + "timestamp": "2025-10-17T10:30:00Z", + "reason": "Add FR-09 explicit coverage", + "input_source": "batch_verification_report", + "backup_location": ".task/backup/IMPL-004-v1.1.json" + } + ] +} +``` + +### TodoWrite Integration +```typescript +// Initialize tracking for batch mode +TodoWrite({ + todos: taskList.map(task => ({ + content: `${task.id}: ${task.changeDescription}`, + status: "pending", + activeForm: `Replanning ${task.id}` + })) +}); + +// Update progress during processing +TodoWrite({ + todos: updateTaskStatus(taskId, "in_progress") +}); + +// Mark completed +TodoWrite({ + todos: updateTaskStatus(taskId, "completed") +}); ``` ## Related Commands -- `/context` - View updated task structure +- `/workflow:status` - View task structure and versions +- `/workflow:action-plan-verify` - Generate verification report for batch mode - `/task:execute` - Execute replanned task - `/task:create` - Create new tasks -- `/workflow:action-plan` - For workflow-wide changes \ No newline at end of file +- `/task:breakdown` - Break down complex tasks + +## Context + +$ARGUMENTS \ No newline at end of file diff --git a/.claude/commands/workflow/action-plan-verify.md b/.claude/commands/workflow/action-plan-verify.md index e677df5e..28376198 100644 --- a/.claude/commands/workflow/action-plan-verify.md +++ b/.claude/commands/workflow/action-plan-verify.md @@ -307,48 +307,73 @@ Output a Markdown report (no file writes) with the following structure: ### Next Actions -#### If CRITICAL Issues Exist (Current Status: 2 CRITICAL) -**Recommendation**: ❌ **BLOCK EXECUTION** - Resolve CRITICAL issues before proceeding +#### Action Recommendations -**Required Actions**: -1. **CRITICAL**: Add authentication implementation tasks to cover FR-03 -2. **CRITICAL**: Add performance optimization tasks to cover NFR-01 +**If CRITICAL Issues Exist**: +- ❌ **BLOCK EXECUTION** - Resolve critical issues before proceeding +- Use `/task:create` for missing requirements coverage +- Fix broken dependencies and circular references -#### If Only HIGH/MEDIUM/LOW Issues -**Recommendation**: ⚠️ **PROCEED WITH CAUTION** - Issues are non-blocking but should be addressed +**If Only HIGH/MEDIUM/LOW Issues**: +- ⚠️ **PROCEED WITH CAUTION** - Fix high-priority issues first +- Use batch replan mode to apply all task improvements systematically -**Suggested Improvements**: -1. Add context.artifacts references to all tasks (use /task:replan) -2. Fix broken dependency IMPL-2.3 β†’ IMPL-2.4 -3. Add flow_control.target_files to underspecified tasks +#### Batch Remediation -#### Command Suggestions +**Report Location**: `.workflow/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md` + +**Apply All Task Improvements** (Recommended): ```bash -# Fix critical coverage gaps +# Batch process all task replan recommendations +/task:replan --batch .workflow/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md + +# Or with auto-confirmation (no prompts) +/task:replan --batch ACTION_PLAN_VERIFICATION.md --auto-confirm +``` + +**Manual Selective Fixes**: +```bash +# Fix critical coverage gaps first /task:create "Implement user authentication (FR-03)" /task:create "Add performance optimization (NFR-01)" -# Refine existing tasks +# Then apply task refinements individually /task:replan IMPL-1.2 "Add context.artifacts and target_files" - -# Update IMPL_PLAN if architecture drift detected -# (Manual edit required) -``` ``` -### 7. Provide Remediation Options +**Notes**: +- Batch mode extracts all `/task:replan` commands from report +- Processes by priority: CRITICAL β†’ HIGH β†’ MEDIUM β†’ LOW +- Creates TodoWrite tracking for all modifications +- Architecture drift in IMPL_PLAN requires manual editing +``` -At end of report, ask the user: +### 7. Save Report and Provide Remediation Options + +**Save Analysis Report**: +```bash +report_path = ".workflow/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md" +Write(report_path, full_report_content) +``` + +At end of report, provide batch remediation guidance: ```markdown ### πŸ”§ Remediation Options -Would you like me to: -1. **Generate task suggestions** for unmapped requirements (no auto-creation) -2. **Provide specific edit commands** for top N issues (you execute manually) -3. **Create remediation checklist** for systematic fixing +**Recommended Workflow**: +1. **Batch Mode** (Fastest): Apply all task improvements automatically + ```bash + /task:replan --batch .workflow/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md + ``` -(Do NOT apply fixes automatically - this is read-only analysis) +2. **Manual Review**: Examine each issue before applying + - Review findings in this report + - Execute specific `/task:create` or `/task:replan` commands individually + +3. **Architecture Changes**: Update IMPL_PLAN.md manually if architecture drift detected + +**Note**: This is read-only analysis. All fixes require explicit execution. ``` ### 8. Update Session Metadata diff --git a/.claude/skills/codex/SKILL.md b/.claude/skills/codex/SKILL.md new file mode 100644 index 00000000..1dfe3d7a --- /dev/null +++ b/.claude/skills/codex/SKILL.md @@ -0,0 +1,363 @@ +--- +name: Codex Development Tool +description: Autonomous development tool for implementation. Trigger keywords "use codex", "codex implement", "implement with codex". Use for feature implementation, bug fixes, testing, and automation. Requires explicit MODE specification (auto/write). Supports session management for multi-task workflows. +allowed-tools: Bash, Read, Write, Edit, Glob, Grep +--- + +# Codex Development Tool + +## Core Execution + +Codex executes autonomous development tasks with full file operations and session management. + +**Trigger Keywords**: "use codex", "codex implement", "implement with codex", "codex fix bug" + +**Execution Modes**: +- `auto`: Autonomous development with full file operations (requires explicit specification) +- `write`: Test generation and file modification (requires explicit specification) + +**Command Pattern**: +```bash +codex -C [directory] --full-auto exec " +PURPOSE: [goal] +TASK: [specific task] +MODE: [auto|write] +CONTEXT: @{file/patterns} +EXPECTED: [deliverables] +RULES: [constraints] +" --skip-git-repo-check -s danger-full-access +``` + +**No Default Mode**: MODE must be explicitly specified in every command + +## Universal Template Structure + +Every Codex command should follow this detailed structure for best results: + +```bash +codex -C [directory] --full-auto exec " +PURPOSE: [One clear sentence: what and why] +TASK: [Specific actionable task with deliverables] +MODE: [auto|write] +CONTEXT: @{file/patterns} [Previous session context, dependencies, requirements] +EXPECTED: [Concrete deliverables: files, tests, coverage, performance] +RULES: [Template reference] | [Constraints: standards, compatibility, testing] +" --skip-git-repo-check -s danger-full-access +``` + +**Session Resume Pattern**: +```bash +# First task: establish session +codex -C [directory] --full-auto exec "..." --skip-git-repo-check -s danger-full-access + +# Subsequent tasks: continue session (add "resume --last" at END) +codex --full-auto exec "..." resume --last --skip-git-repo-check -s danger-full-access +``` + +### Template Field Guidelines + +**PURPOSE**: +- One sentence combining goal + business driver +- Examples: "Implement auth system for enterprise SaaS", "Fix performance issue to meet SLA <200ms" + +**TASK**: +- Break down into numbered sub-tasks with specific deliverables +- Include technical details: "Create JWT auth with RS256, 15min access token, 7d refresh token" +- Specify what to build, test, and document + +**CONTEXT**: +- File patterns: `@{src/models/**/*.ts,src/services/**/*.ts}` +- Tech stack: "Express 4.18, PostgreSQL 14, Redis 7, TypeScript strict mode" +- Requirements: "Support 100k users, comply with OWASP guidelines" +- Session memory: "Previous auth implementation from current session" + +**EXPECTED**: +- Numbered, concrete deliverables: "1) auth.service.ts, 2) auth.controller.ts, 3) auth.test.ts (>90% coverage)" +- Specific file names with purposes +- Test coverage requirements: ">90% coverage including security scenarios" +- Performance targets: "p95 <200ms", "Support 1000 req/min" +- Documentation requirements: "Update API.md with endpoints" + +**RULES**: +- Template reference: `$(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt)` +- Multiple constraints separated by `|`: "Follow OWASP | Use bcrypt salt 12 | Rate limit 5/15min | Include audit logs" +- Compatibility: "Maintain backward compatibility", "Ensure zero downtime" +- Testing strategy: "Test all error cases", "Mock external dependencies", "Load test with Artillery" +- Security requirements: "Validate all inputs", "Parameterized queries only", "Log security events" + +## Command Structure + +### Universal Template +Every Codex command follows this structure: + +```bash +codex -C [directory] --full-auto exec " +PURPOSE: [clear development goal] +TASK: [specific development task] +MODE: [auto|write] +CONTEXT: [file references and memory context] +EXPECTED: [expected deliverables] +RULES: [template reference and constraints] +" --skip-git-repo-check -s danger-full-access +``` + +**Parameter Position**: `--skip-git-repo-check -s danger-full-access` must be placed at command END + +## Execution Modes + +### Auto Mode (Full Development) +⚠️ Autonomous development with full file operations (requires explicit MODE=auto): + +```bash +codex -C [directory] --full-auto exec " +PURPOSE: [development goal] +TASK: [implementation task] +MODE: auto +CONTEXT: @{file/patterns} [session memory] +EXPECTED: [deliverables] +RULES: [constraints] +" --skip-git-repo-check -s danger-full-access +``` + +**When to use**: +- Feature implementation +- Bug fixes requiring code changes +- Refactoring tasks +- Complex algorithm implementation + +### Write Mode (Test Generation) +⚠️ Test generation and file modification (requires explicit MODE=write): + +```bash +codex -C [directory] --full-auto exec " +PURPOSE: [test goal] +TASK: [test generation task] +MODE: write +CONTEXT: @{file/patterns} +EXPECTED: [test deliverables] +RULES: [constraints] +" --skip-git-repo-check -s danger-full-access +``` + +**When to use**: +- Test generation +- Test coverage improvement +- Documentation updates + +**No Default Mode**: MODE must be explicitly specified in every command + +## Session Management + +Codex supports session continuity for multi-task workflows. See [session-management.md](session-management.md) for detailed patterns. + +### Session Resume Patterns + +**First Task** (establish session): +```bash +codex -C project --full-auto exec " +PURPOSE: [initial task] +TASK: [first implementation] +MODE: auto +CONTEXT: @{relevant/files} +EXPECTED: [deliverables] +RULES: [constraints] +" --skip-git-repo-check -s danger-full-access +``` + +**Subsequent Tasks** (continue session): +```bash +codex --full-auto exec " +PURPOSE: [next task] +TASK: [related implementation] +MODE: auto +CONTEXT: Previous implementation from current session +EXPECTED: [deliverables] +RULES: [constraints] +" resume --last --skip-git-repo-check -s danger-full-access +``` + +**Parameter Position**: `resume --last` must be placed AFTER the prompt string at command END + +### Auto-Resume Decision Rules + +**Use `resume --last` when**: +- Current task extends previous Codex task in conversation +- Current task requires context from previous implementation +- Multi-step workflow (implement β†’ enhance β†’ test) +- Session memory indicates recent Codex execution + +**Do NOT use `resume --last` when**: +- First Codex task in conversation +- New independent task unrelated to previous work +- Switching to different module/feature area +- No recent Codex task in conversation memory + +### Interactive Session Resume + +```bash +# Resume with session picker +codex resume + +# Resume most recent session directly +codex resume --last +``` + +### Image Attachment Support + +```bash +# Attach images for UI/design implementation +codex -i screenshot.png -C project --full-auto exec " +PURPOSE: Implement UI from design +TASK: Create component matching screenshot +MODE: auto +CONTEXT: @{src/components/**} +EXPECTED: React component matching design +RULES: Follow design system +" --skip-git-repo-check -s danger-full-access +``` + +## File Pattern Reference + +Common patterns for CONTEXT field: + +```bash +@{**/*} # All files +@{src/**/*} # Source files +@{*.ts,*.tsx} # TypeScript files +@{src/**/*.test.*} # Test files +@{CLAUDE.md,**/*CLAUDE.md} # Documentation +``` + +## Template System + +Templates are located in `~/.claude/workflows/cli-templates/prompts/` + +### Available Templates + +**Development Templates**: +- `development/feature.txt` - Feature implementation +- `development/refactor.txt` - Refactoring tasks +- `development/testing.txt` - Test generation + +**Analysis Templates** (for planning): +- `analysis/pattern.txt` - Code pattern analysis +- `analysis/architecture.txt` - System architecture review +- `analysis/security.txt` - Security assessment + +### Using Templates in RULES Field + +```bash +# Single template +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) | Follow security best practices + +# Multiple templates +RULES: $(cat template1.txt) $(cat template2.txt) | Maintain backward compatibility + +# No template +RULES: Use Jest, follow existing patterns, 80%+ coverage +``` + +## Directory Context Configuration + +Codex uses `-C` parameter for directory context: + +```bash +# Focused on specific directory +codex -C src/auth --full-auto exec "..." --skip-git-repo-check -s danger-full-access + +# Relative path +codex -C ../project --full-auto exec "..." --skip-git-repo-check -s danger-full-access + +# Absolute path +codex -C /full/path/to/project --full-auto exec "..." --skip-git-repo-check -s danger-full-access +``` + +## Execution Configuration + +### Timeout Allocation (Dynamic + Multiplier) +Codex uses 1.5x of base timeout due to development complexity: + +- **Simple** (test generation): 30-60min (1800000-3600000ms) +- **Medium** (feature implementation): 60-90min (3600000-5400000ms) +- **Complex** (multi-module refactor): 90-180min (5400000-10800000ms) + +Auto-detect from PURPOSE and TASK fields. + +### Permission Framework +- ⚠️ **No Default Mode**: MODE must be explicitly specified +- πŸ”’ **Write Protection**: Requires explicit user instruction +- βœ… **Auto Mode**: Full file operations when MODE=auto specified +- βœ… **Write Mode**: Test generation when MODE=write specified + +## Examples + +Production-ready examples organized by scenario type: + +- **[Feature Implementation](feature-examples.md)** - RESTful APIs and multi-task authentication systems with session resume patterns +- **[Bug Fix & Refactoring](bugfix-refactor-examples.md)** - Performance investigation workflows and large-scale DDD refactoring +- **[Advanced Development](advanced-examples.md)** - Graph algorithms, UI implementation from designs, and security-focused features +- **[Session Management](session-management.md)** - Interactive resume patterns and multi-phase development workflows + +Each example follows the Universal Template Structure with detailed session continuity patterns. + +## Best Practices + +### Implementation Phase +- Always specify MODE (auto/write) +- Use `-C` for directory context +- Include file patterns in CONTEXT +- Reference templates in RULES +- Use session management for multi-step tasks + +### Testing Phase +- Use MODE=write for test generation +- Reference implementation in CONTEXT +- Specify coverage requirements in RULES +- Use existing test patterns + +### Multi-Task Workflows +- First task: establish session +- Subsequent tasks: use `resume --last` +- Maintain context continuity +- Keep related tasks in same session + +## Error Handling + +**If timeout occurs**: +- Reduce task scope +- Split into smaller subtasks +- Use session management for continuity + +**If implementation blocked**: +- Check CONTEXT includes necessary files +- Verify MODE is specified +- Review RULES for conflicts + +**If tests fail**: +- Use MODE=write to generate test fixes +- Reference failing tests in CONTEXT +- Specify fix requirements in RULES + +**If session lost**: +- Use `codex resume` to restore session +- Reference previous work in CONTEXT +- Include session memory in prompt + +## Security Considerations + +### Permission Requirements +- `-s danger-full-access`: Full file system access +- `--skip-git-repo-check`: Skip git validation +- `--full-auto`: Autonomous execution mode + +### Safety Guidelines +- Review generated code before committing +- Verify test coverage meets requirements +- Check for security vulnerabilities +- Validate backward compatibility + +### Best Practices +- Use MODE=write for non-destructive operations +- Review RULES for security constraints +- Include security templates when relevant +- Test in isolated environment first diff --git a/.claude/skills/codex/advanced-examples.md b/.claude/skills/codex/advanced-examples.md new file mode 100644 index 00000000..7d6be9fb --- /dev/null +++ b/.claude/skills/codex/advanced-examples.md @@ -0,0 +1,73 @@ +# Codex Advanced Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](SKILL.md#universal-template-structure) in SKILL.md for detailed field guidelines and session resume patterns. + +## Algorithm Implementation with Tests and Benchmarks + +```bash +codex -C src/algorithms --full-auto exec " +PURPOSE: Implement efficient graph algorithms for social network friend suggestion feature +TASK: Create graph data structure and algorithms: 1) Directed graph with adjacency list, 2) BFS for shortest path, 3) DFS for connected components, 4) Dijkstra for weighted paths, 5) PageRank-inspired algorithm for friend scoring, 6) Friend suggestion based on mutual connections and activity +MODE: auto +CONTEXT: @{src/models/user.ts,src/models/connection.ts} Social network with 100k users, avg 150 connections per user, need to suggest friends based on: mutual friends (weight 0.5), shared interests (0.3), activity overlap (0.2). Performance target: compute suggestions for user in <100ms. +EXPECTED: Deliverables: 1) graph.ts (DirectedGraph class with generic types), 2) graph-algorithms.ts (BFS, DFS, Dijkstra, shortest path), 3) friend-suggestion.ts (scoring algorithm using graph), 4) graph.test.ts (unit tests for all operations, edge cases), 5) friend-suggestion.test.ts (test accuracy and performance), 6) benchmark.ts (measure performance with production-scale data), 7) Algorithm complexity analysis in ALGORITHMS.md +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) | Use TypeScript generics for graph nodes | Implement efficient adjacency list (Map>) | Optimize for sparse graphs | Handle disconnected components | Implement early termination for BFS/DFS | Use priority queue (heap) for Dijkstra | Cache computation results with TTL | Test with graphs up to 10k nodes | Benchmark against target <100ms | Document time/space complexity (Big-O) | Include edge cases: empty graph, single node, cycles | Verify algorithm correctness with known test cases +" --skip-git-repo-check -s danger-full-access +``` + +**Key Points**: +- **Real-world application**: Social network friend suggestion +- **Performance targets**: <100ms with 100k users +- **Comprehensive deliverables**: Code + tests + benchmarks + docs +- **Algorithm rigor**: Complexity analysis, correctness verification + +## UI Implementation from Design Screenshot + +```bash +codex -i design-system.png -i dashboard-mockup.png -C src/components --full-auto exec " +PURPOSE: Implement dashboard UI matching design system for product launch +TASK: Create responsive dashboard component with: 1) Header with user menu and notifications, 2) Sidebar navigation with collapsible sections, 3) Main content area with widget grid, 4) Stat cards with icons and trend indicators, 5) Chart widgets (line, bar, pie), 6) Data table with sorting and pagination, 7) Loading states and error handling, 8) Dark mode support +MODE: auto +CONTEXT: @{src/components/**/*.tsx,src/styles/**/*.css,src/hooks/**/*.ts} React 18, TypeScript, Tailwind CSS, Recharts for charts, react-table for tables. Design system defined in design-system.png. Desktop-first responsive (breakpoints: 1024px, 768px, 640px). +EXPECTED: Deliverables: 1) Dashboard.tsx (main component), 2) Header.tsx, Sidebar.tsx, StatCard.tsx, ChartWidget.tsx, DataTable.tsx (sub-components), 3) useDashboard.ts (data fetching hook), 4) dashboard.test.tsx (component tests with React Testing Library), 5) dashboard.stories.tsx (Storybook stories for all variants), 6) Responsive behavior matches design at all breakpoints, 7) Accessibility compliance (ARIA labels, keyboard navigation), 8) Update design system docs +RULES: Match design pixel-perfect at 1024px | Use Tailwind utility classes (no custom CSS unless necessary) | Implement mobile-first responsive (collapse sidebar on mobile) | Use React.memo for performance | Implement virtual scrolling for large tables | Add loading skeletons (not spinners) | Support dark mode with CSS variables | Ensure WCAG 2.1 AA compliance | Test keyboard navigation | Add error boundaries | Use semantic HTML | Optimize images (lazy load, WebP format) | Test with real API data | Include empty states | Document component props with TypeScript interfaces +" --skip-git-repo-check -s danger-full-access +``` + +**Key Points**: +- **Image input**: Design files provided with -i flag +- **Comprehensive UI**: Multiple sub-components with state management +- **Quality focus**: Accessibility, performance, responsive design, testing +- **Production-ready**: Error handling, loading states, dark mode + +## Security-Focused Implementation with Multiple Templates + +```bash +codex -C src/api --full-auto exec " +PURPOSE: Implement admin API with security hardening for enterprise compliance +TASK: Create admin endpoints for user management: 1) List users with advanced filtering, 2) Update user roles and permissions, 3) Suspend/activate users, 4) Audit log viewing, 5) Export user data (GDPR compliance). Implement comprehensive security controls. +MODE: auto +CONTEXT: @{src/models/user.ts,src/middleware/auth.ts,src/middleware/rbac.ts} Admin users have 'admin' role in RBAC. Must comply with SOC 2, log all admin actions, implement IP whitelist, require MFA for admin access. +EXPECTED: Deliverables: 1) admin.controller.ts (5 endpoints), 2) admin.service.ts (business logic with security checks), 3) audit-log.service.ts (log all admin actions), 4) IP whitelist middleware, 5) MFA verification middleware for admin routes, 6) admin.test.ts (security tests >90% coverage), 7) Update SECURITY.md with admin security controls +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt) | Implement defense in depth: auth + RBAC + MFA + IP whitelist | Log all admin actions with: timestamp, user, action, target, IP, result | Require MFA verification for sensitive operations | Validate IP against whitelist | Implement rate limiting: 20 req/min for admin endpoints | Sanitize all inputs | Use parameterized queries only | Implement audit log retention (7 years for SOC 2) | Add admin action confirmation for destructive ops | Test authorization bypass attempts | Verify no privilege escalation possible | Document security controls in code comments | Include security test scenarios: unauthorized access, role escalation, missing MFA, IP outside whitelist +" --skip-git-repo-check -s danger-full-access +``` + +**Key Points**: +- **Two templates**: Feature + Security combined +- **Compliance focus**: SOC 2 requirements, audit logging +- **Defense in depth**: Multiple security layers +- **Comprehensive testing**: Security scenarios explicitly tested + +## Session Management Example + +For interactive session resume patterns and decision rules, see [session-management.md](session-management.md). + +**Quick Example**: +```bash +# Show all available sessions for selection +codex resume + +# Resume most recent session directly +codex resume --last +``` diff --git a/.claude/skills/codex/bugfix-refactor-examples.md b/.claude/skills/codex/bugfix-refactor-examples.md new file mode 100644 index 00000000..e5d8e7a4 --- /dev/null +++ b/.claude/skills/codex/bugfix-refactor-examples.md @@ -0,0 +1,114 @@ +# Codex Bug Fix and Refactoring Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](SKILL.md#universal-template-structure) in SKILL.md for detailed field guidelines and session resume patterns. + +## Bug Fix: Performance Issue Investigation and Resolution + +Three-phase approach: Investigate β†’ Fix β†’ Verify + +### Phase 1: Investigation (start session) + +```bash +codex -C src/api --full-auto exec " +PURPOSE: Investigate and resolve API endpoint performance degradation (p95 from 200ms to 2.5s) +TASK: Analyze /api/dashboard endpoint performance: 1) Profile request execution (use Node.js profiler), 2) Identify slow database queries (enable query logging), 3) Check N+1 query problems, 4) Analyze serialization overhead, 5) Review caching effectiveness, 6) Examine memory allocation patterns +MODE: auto +CONTEXT: @{src/api/dashboard.controller.ts,src/services/dashboard.service.ts,src/repositories/**/*.ts} Endpoint aggregates data from 5 database tables, serves 1000 req/min peak, PostgreSQL 14, Redis cache enabled. Performance degraded after recent feature addition (user preferences). +EXPECTED: Deliverables: 1) Performance analysis report identifying bottlenecks with percentages (e.g., \"45% time in database queries, 30% in serialization\"), 2) Flame graph from profiling, 3) Query execution plans for slow queries, 4) Specific line numbers of problematic code, 5) Root cause summary with evidence, 6) Optimization recommendations prioritized by impact +RULES: Use Node.js --prof for profiling | Enable PostgreSQL query logging with execution times | Use Chrome DevTools for flame graph visualization | Check for N+1 queries with Prisma query logging | Analyze JSON serialization overhead | Review Redis cache hit rates | Identify memory leaks with heapdump | Compare current vs previous commit performance | Document findings in INVESTIGATION.md +" --skip-git-repo-check -s danger-full-access +``` + +### Phase 2: Fix Implementation (continue session) + +```bash +codex --full-auto exec " +PURPOSE: Implement optimizations to restore API performance to <200ms p95 +TASK: Apply fixes based on investigation findings: 1) Optimize database queries (add indexes, use joins instead of sequential queries), 2) Implement query result caching, 3) Use streaming for large responses, 4) Add database query batching, 5) Optimize serialization with selective field loading +MODE: auto +CONTEXT: Investigation results from current session showing: N+1 query in user preferences (40% of latency), missing index on user_settings.user_id (25%), inefficient JSON serialization of nested objects (20%). Current code performs 15 queries per request. +EXPECTED: Deliverables: 1) Optimized dashboard.service.ts reducing queries to max 3 per request, 2) Database migration adding indexes on user_settings.user_id and preferences.user_id, 3) Implement Redis caching with 5min TTL for dashboard data, 4) Add query batching using dataloader pattern, 5) Selective field loading (only fetch needed columns), 6) Update tests to verify optimizations, 7) Performance comparison report showing improvement +RULES: Maintain backward compatibility (same API contract) | Add database indexes without locking tables (CONCURRENTLY) | Implement cache invalidation on data updates | Use Prisma select for selective loading | Test with production-like data volume | Verify cache hit rate >80% | Ensure p95 <200ms under load | Add performance monitoring (APM integration) | Document optimization strategy | Update runbooks with new caching behavior +" resume --last --skip-git-repo-check -s danger-full-access +``` + +### Phase 3: Verification (continue session) + +```bash +codex --full-auto exec " +PURPOSE: Verify performance fixes and ensure no regressions +TASK: Comprehensive validation: 1) Run load tests comparing before/after metrics, 2) Verify all functional tests pass, 3) Check for new memory leaks, 4) Validate cache behavior, 5) Measure database impact (connection pool usage, query counts) +MODE: write +CONTEXT: Optimizations from current session: reduced queries from 15 to 3, added 2 indexes, implemented Redis caching, added dataloader. Original p95: 2.5s, target: <200ms. +EXPECTED: Deliverables: 1) performance-test.ts (Artillery load test: 1000 req/min for 5min), 2) Performance report comparing metrics (latency p50/p95/p99, throughput, error rate, database connections, cache hit rate), 3) Regression test suite covering all dashboard functionality, 4) Memory profile comparison (before/after heap usage), 5) Go/No-Go recommendation with evidence +RULES: Load test must match production traffic pattern | Verify all existing tests pass (no regressions) | Check memory usage under load (no leaks) | Validate cache hit rate >80% | Ensure database connection pool <50% utilized | Verify error rate <0.1% | Test cache invalidation scenarios | Monitor for slow query logs | Document performance gains | Create performance dashboard for ongoing monitoring +" resume --last --skip-git-repo-check -s danger-full-access +``` + +**Key Points**: +- **Three-phase approach**: Investigate β†’ Fix β†’ Verify +- **Data-driven**: Specific metrics, percentages, targets +- **Evidence-based**: Profiling, flame graphs, query plans +- **Production-ready**: Load testing, monitoring, go/no-go decision + +## Large-Scale Refactoring with Safety Nets + +Four-phase DDD refactoring: Plan β†’ Pilot β†’ Scale β†’ Cleanup + +### Phase 1: Analysis and Planning (start session) + +```bash +codex -C src --full-auto exec " +PURPOSE: Refactor monolithic service layer to modular domain-driven design for improved maintainability +TASK: Analyze current architecture for refactoring scope: 1) Identify domain boundaries (user, product, order, payment, notification), 2) Map current service dependencies, 3) Identify shared utilities, 4) Find circular dependencies, 5) Assess test coverage by module, 6) Estimate breaking changes +MODE: auto +CONTEXT: @{src/services/**/*.ts,src/models/**/*.ts,src/repositories/**/*.ts} Monolithic structure: single services/ directory with 45 service files, 80k LOC, shared database models, tight coupling. Team of 8 developers, 100k users in production. +EXPECTED: Deliverables: 1) Domain boundary map with proposed structure, 2) Dependency graph (current vs proposed), 3) Migration strategy (phase-by-phase plan), 4) Breaking changes catalog, 5) Test strategy to prevent regressions, 6) Risk assessment matrix, 7) Rollback plan, 8) Estimated timeline (sprints), 9) REFACTORING_PLAN.md document +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/refactor.txt) | Follow DDD principles (bounded contexts) | Minimize breaking changes | Plan for gradual migration | Maintain API compatibility during transition | Identify shared kernel carefully | Design anti-corruption layers | Consider team ownership per domain | Assess impact on deployment pipeline | Include database migration strategy | Define success metrics and exit criteria +" --skip-git-repo-check -s danger-full-access +``` + +### Phase 2: Extract First Domain (continue session) + +```bash +codex --full-auto exec " +PURPOSE: Extract user domain as pilot for refactoring approach +TASK: Refactor user-related services into isolated domain: 1) Create src/domains/user structure, 2) Move user.service.ts, profile.service.ts, preferences.service.ts, 3) Extract user-specific models and repositories, 4) Define domain public API (facade pattern), 5) Update imports in consuming code, 6) Ensure zero functionality changes +MODE: auto +CONTEXT: Refactoring plan from current session. User domain identified as: 3 services, 2 models, 2 repositories. Currently consumed by 12 API controllers. No external domain dependencies (good isolation). +EXPECTED: Deliverables: 1) domains/user/ directory structure (services/, models/, repositories/, index.ts for public API), 2) Migrate 3 services with same API signatures, 3) Create UserDomain facade class, 4) Update 12 controller imports to use facade, 5) All existing tests pass unchanged, 6) Add integration tests for domain boundary, 7) Update architecture docs +RULES: Use barrel exports (index.ts) for public API | Hide implementation details | Maintain exact same function signatures | Run full test suite after each file move | Use git mv to preserve history | Add deprecation warnings to old imports | Create facade with same interface as direct service calls | Ensure no circular dependencies | Verify production build succeeds | Document domain public API with JSDoc +" resume --last --skip-git-repo-check -s danger-full-access +``` + +### Phase 3: Continue with Remaining Domains (continue session) + +```bash +codex --full-auto exec " +PURPOSE: Complete domain extraction for product and order domains +TASK: Following user domain pattern, extract: 1) Product domain (4 services), 2) Order domain (6 services with product dependency). Handle cross-domain dependencies correctly. +MODE: auto +CONTEXT: User domain successfully extracted from current session. Product domain: 4 services, no external dependencies. Order domain: 6 services, depends on Product and User domains. +EXPECTED: Deliverables: 1) domains/product/ structure with facade, 2) domains/order/ structure with facades for User and Product, 3) Cross-domain communication through facades only, 4) Update all controller imports, 5) All tests pass, 6) Add domain integration tests, 7) Update dependency graph diagram +RULES: Domains communicate only through public APIs (facades) | No direct cross-domain model access | Use dependency injection for cross-domain calls | Maintain transactional boundaries | Verify no circular domain dependencies | Test cross-domain scenarios | Document domain relationships | Ensure performance not degraded | Run regression tests | Update team ownership docs +" resume --last --skip-git-repo-check -s danger-full-access +``` + +### Phase 4: Cleanup and Verification (continue session) + +```bash +codex --full-auto exec " +PURPOSE: Finalize refactoring with cleanup and comprehensive verification +TASK: Complete migration: 1) Remove old services/ directory, 2) Update all import statements, 3) Clean up unused code, 4) Update build configuration, 5) Verify no broken imports, 6) Run full test suite, 7) Perform load test +MODE: auto +CONTEXT: All domains extracted from current session: user (3 services), product (4 services), order (6 services), payment (5 services), notification (3 services). Old services/ directory still exists for reference. +EXPECTED: Deliverables: 1) Delete old services/ directory, 2) Update tsconfig.json paths, 3) Update import statements across codebase, 4) Remove dead code (identified by unused exports), 5) All tests pass (unit + integration + e2e), 6) Load test confirms no performance regression, 7) Update ARCHITECTURE.md with new structure, 8) Create migration guide for other developers +RULES: Verify no imports from old paths | Run ESLint to catch broken imports | Ensure all tests pass | Load test must show <5% performance delta | Update CI/CD pipeline if needed | Document new domain structure | Create coding guidelines for domain boundaries | Update onboarding docs | Verify build artifacts are correct | Perform git commit with detailed message documenting refactoring scope +" resume --last --skip-git-repo-check -s danger-full-access +``` + +**Key Points**: +- **Four-phase refactoring**: Plan β†’ Pilot β†’ Scale β†’ Cleanup +- **Safety-first**: Gradual migration, test coverage, rollback plan +- **Production awareness**: Zero downtime, performance monitoring +- **Team enablement**: Documentation, guidelines, ownership diff --git a/.claude/skills/codex/feature-examples.md b/.claude/skills/codex/feature-examples.md new file mode 100644 index 00000000..b9b71c17 --- /dev/null +++ b/.claude/skills/codex/feature-examples.md @@ -0,0 +1,86 @@ +# Codex Feature Implementation Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](SKILL.md#universal-template-structure) in SKILL.md for detailed field guidelines and session resume patterns. + +All examples demonstrate production-ready feature development with testing, security, and maintainability focus. + +## Example 1: RESTful API with Validation and Tests + +```bash +codex -C src/api --full-auto exec " +PURPOSE: Implement user profile API to support mobile app launch +TASK: Create RESTful CRUD endpoints for user profiles including: GET /users/:id (with query params for field filtering), POST /users (with validation), PUT /users/:id (partial updates), DELETE /users/:id (soft delete). Implement request validation with Joi/Zod, error handling middleware, rate limiting per endpoint, response pagination for list operations, OpenAPI documentation comments. +MODE: auto +CONTEXT: @{src/models/user.ts,src/middleware/**/*.ts,src/validators/**/*.ts,../database/schema.prisma} Existing patterns: Repository pattern, service layer, JWT auth middleware, Prisma ORM, Express 4.18, TypeScript strict mode. Database: PostgreSQL 14 with 50k users. +EXPECTED: Deliverables: 1) user.controller.ts (4 CRUD endpoints), 2) user.service.ts (business logic), 3) user.validator.ts (Joi schemas), 4) user.routes.ts (Express router config), 5) user.test.ts (integration tests with supertest, >90% coverage), 6) Update OpenAPI spec in api-docs.yaml. All endpoints must return consistent error format {code, message, details}. +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) | Follow REST conventions (proper HTTP verbs and status codes) | Validate all inputs at API boundary | Implement rate limiting: 100/min for GET, 20/min for write ops | Use repository pattern from existing code | Soft delete with deletedAt timestamp | Include request logging | Add JSDoc with OpenAPI annotations | Write integration tests for all endpoints including error cases | Ensure backward compatibility with v1 API | Run ESLint and Prettier before commit +" --skip-git-repo-check -s danger-full-access +``` + +**Key Points**: +- **TASK**: Detailed requirements with specific endpoints and features +- **CONTEXT**: Tech stack + existing patterns + constraints (50k users) +- **EXPECTED**: 6 concrete deliverables with test coverage requirement +- **RULES**: Template + REST conventions + validation + testing + compatibility + +## Example 2: Multi-Task Authentication Feature with Session Resume + +Complete authentication system built incrementally across multiple related tasks. + +### Task 1: Core Authentication (establish session) + +```bash +codex -C src/auth --full-auto exec " +PURPOSE: Implement secure authentication system for enterprise SaaS platform +TASK: Create JWT-based authentication supporting: 1) Email/password login with bcrypt (cost 12), 2) OAuth 2.0 integration (Google, GitHub), 3) Token generation with RS256 asymmetric signing, 4) Access token (15min TTL) and refresh token (7d TTL), 5) Token refresh endpoint, 6) Logout with token blacklist in Redis +MODE: auto +CONTEXT: @{src/models/user.ts,src/config/jwt.ts,../../keys/private.pem,../../keys/public.pem} Requirements: Support 100k users, Redis for session store, Passport.js for OAuth, must comply with OWASP authentication guidelines +EXPECTED: Deliverables: 1) auth.service.ts (login, OAuth, token generation/refresh/revoke), 2) auth.controller.ts (5 endpoints: login, OAuth callback, refresh, logout, verify), 3) jwt.middleware.ts (token verification for protected routes), 4) auth.validator.ts (input validation), 5) auth.test.ts (unit + integration tests, >90% coverage including security scenarios), 6) Update .env.example with new config +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) | Follow OWASP Authentication Cheat Sheet | Use bcrypt with salt rounds 12 | Implement rate limiting: 5 login attempts per 15min per IP | Store only refresh tokens (not access tokens) | Implement token rotation on refresh | Add brute force protection | Include security event logging | Validate OAuth state parameter | Test token expiration and invalid token scenarios | Document security considerations in SECURITY.md +" --skip-git-repo-check -s danger-full-access +``` + +### Task 2: Multi-Factor Authentication (continue session) + +```bash +codex --full-auto exec " +PURPOSE: Add MFA layer to enhance security for enterprise accounts +TASK: Implement TOTP-based MFA: 1) MFA enrollment endpoint with QR code generation, 2) MFA verification during login, 3) Backup codes generation (10 one-time codes), 4) MFA status in user profile, 5) Admin can require MFA for user roles +MODE: auto +CONTEXT: Previous auth implementation from current session. Use speakeasy library for TOTP, qrcode for QR generation. MFA should be optional by default but enforceable per user role. +EXPECTED: Deliverables: 1) mfa.service.ts (enroll, verify, generate backup codes, validate backup code), 2) Update auth.controller.ts with MFA endpoints, 3) Update auth flow to check MFA status, 4) Database migration for MFA fields (secret, enabled, backup_codes), 5) mfa.test.ts (test enrollment, verification, backup codes, >85% coverage), 6) Update API docs with MFA flow +RULES: Use TOTP with 30s window, 6-digit codes | Encrypt MFA secret in database | Invalidate backup codes after use | Rate limit verification attempts (5/min) | Add MFA recovery flow | Log all MFA events | Test clock skew handling | Document MFA setup guide for users | Ensure backward compatibility (MFA optional) +" resume --last --skip-git-repo-check -s danger-full-access +``` + +### Task 3: Session Management Enhancement (continue session) + +```bash +codex --full-auto exec " +PURPOSE: Implement session management UI for users to control active devices +TASK: Create session management system: 1) Track active sessions per user (device, location, IP, last activity), 2) List all active sessions endpoint, 3) Revoke specific session endpoint, 4) Revoke all sessions (logout everywhere), 5) Automatic session cleanup for expired tokens +MODE: auto +CONTEXT: Previous auth and MFA implementation from current session. Store session metadata in Redis with refresh token as key. Use GeoIP for location, UAParser for device detection. +EXPECTED: Deliverables: 1) session.service.ts (create, list, revoke, cleanup), 2) session.controller.ts (3 endpoints), 3) Update token refresh to update session activity, 4) Background job for session cleanup (runs hourly), 5) session.test.ts (>85% coverage), 6) Update user API with session endpoints +RULES: Store minimal session metadata (no PII) | Implement session limit per user (max 10 devices) | Include revocation in token validation middleware | Handle concurrent session updates | Add session activity logs | Test session cleanup job | Ensure revoked session can't refresh | Document session management in API docs | Consider GDPR session data retention (30 days) +" resume --last --skip-git-repo-check -s danger-full-access +``` + +### Task 4: Comprehensive Test Suite (continue session) + +```bash +codex --full-auto exec " +PURPOSE: Ensure authentication security and reliability through comprehensive testing +TASK: Generate complete test suite covering: 1) Unit tests for all services, 2) Integration tests for all endpoints, 3) Security tests (injection, token tampering, brute force), 4) Performance tests (login throughput), 5) E2E tests for complete auth flows +MODE: write +CONTEXT: Complete auth implementation from current session including: login, OAuth, JWT, MFA, session management. Use Jest for unit/integration, Artillery for load testing. +EXPECTED: Deliverables: 1) Expand existing test files to >95% coverage, 2) security.test.ts (12 security scenarios), 3) performance.test.ts (load test: 100 req/s for 1min), 4) e2e/auth-flow.test.ts (full user journey), 5) Test report showing coverage by module, 6) Update CI pipeline config to enforce coverage thresholds +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/testing.txt) | Test all happy paths and error cases | Include security tests: SQL injection attempts, XSS in inputs, JWT tampering, expired tokens, invalid signatures | Mock external dependencies (OAuth providers, Redis) | Test rate limiting enforcement | Verify session isolation between users | Load test should achieve <200ms p95 latency | Use faker for test data generation | Clean up test data after each test | Document test scenarios in test file comments +" resume --last --skip-git-repo-check -s danger-full-access +``` + +**Key Points**: +- **Four-task sequence**: Core auth β†’ MFA β†’ Sessions β†’ Tests +- **Session continuity**: Each task builds on previous using `resume --last` +- **Progressive complexity**: Features build incrementally +- **Final testing phase**: MODE=write for comprehensive test generation diff --git a/.claude/skills/codex/session-management.md b/.claude/skills/codex/session-management.md new file mode 100644 index 00000000..40ac8e66 --- /dev/null +++ b/.claude/skills/codex/session-management.md @@ -0,0 +1,475 @@ +# Codex Session Management + +## Overview + +Codex supports session continuity for multi-task development workflows. Sessions maintain context across related tasks, enabling efficient multi-step implementations without repeating context. + +## Core Concepts + +### Session Types + +**New Session** - Establishes fresh context: +```bash +codex -C directory --full-auto exec "task" --skip-git-repo-check -s danger-full-access +``` + +**Resume Session** - Continues with previous context: +```bash +codex --full-auto exec "task" resume --last --skip-git-repo-check -s danger-full-access +``` + +**Interactive Resume** - Picker or direct resume: +```bash +codex resume # Show session picker +codex resume --last # Resume most recent +``` + +## Session Resume Patterns + +### Multi-Task Development Pattern + +**Pattern Overview**: +1. First task: establish session with `-C` +2. Subsequent tasks: continue with `resume --last` +3. Related tasks: maintain context continuity +4. Unrelated tasks: start new session + +**Example - Authentication Feature**: +```bash +# Task 1: Establish session - Implement auth module +codex -C project --full-auto exec " +PURPOSE: Implement user authentication +TASK: Create JWT-based authentication system +MODE: auto +CONTEXT: @{src/auth/**/*} Database schema from session memory +EXPECTED: Complete auth module with middleware +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) | Follow security best practices +" --skip-git-repo-check -s danger-full-access + +# Task 2: Continue session - Add JWT validation +codex --full-auto exec " +PURPOSE: Enhance authentication security +TASK: Add JWT token validation and refresh logic +MODE: auto +CONTEXT: Previous auth implementation from current session +EXPECTED: JWT validation middleware and token refresh endpoints +RULES: Follow JWT best practices, maintain session context +" resume --last --skip-git-repo-check -s danger-full-access + +# Task 3: Continue session - Generate tests +codex --full-auto exec " +PURPOSE: Increase test coverage +TASK: Generate comprehensive tests for auth module +MODE: write +CONTEXT: Auth implementation from current session +EXPECTED: Complete test suite with 80%+ coverage +RULES: Use Jest, follow existing patterns +" resume --last --skip-git-repo-check -s danger-full-access +``` + +### Auto-Resume Decision Tree + +``` +Is current task related to previous Codex task? +β”œβ”€ YES β†’ Does it extend/enhance previous implementation? +β”‚ β”œβ”€ YES β†’ Use `resume --last` +β”‚ └─ NO β†’ Check if it requires previous context +β”‚ β”œβ”€ YES β†’ Use `resume --last` +β”‚ └─ NO β†’ Start new session +└─ NO β†’ Is this first Codex task in conversation? + β”œβ”€ YES β†’ Start new session + └─ NO β†’ Different module/feature area? + β”œβ”€ YES β†’ Start new session + └─ NO β†’ Check conversation memory for recent Codex execution + β”œβ”€ FOUND β†’ Use `resume --last` + └─ NOT FOUND β†’ Start new session +``` + +## Auto-Resume Decision Rules + +### Use `resume --last` When + +**Related Work**: +- Current task extends previous Codex task +- Current task enhances previous implementation +- Current task fixes issues in previous work + +**Example**: +```bash +# First: Implement feature +codex -C src --full-auto exec "Implement user profile" ... + +# Later: Add validation to same feature +codex --full-auto exec "Add profile validation" resume --last ... +``` + +**Multi-Step Workflow**: +- Part of implement β†’ enhance β†’ test cycle +- Sequential improvements +- Incremental feature development + +**Example**: +```bash +# Step 1: Basic implementation +codex -C src --full-auto exec "Create API endpoint" ... + +# Step 2: Add error handling +codex --full-auto exec "Add error handling to endpoint" resume --last ... + +# Step 3: Add tests +codex --full-auto exec "Generate endpoint tests" resume --last ... +``` + +**Context Dependency**: +- Requires understanding of previous implementation +- Builds on previous work +- References previous changes + +**Example**: +```bash +# First: Database schema +codex -C db --full-auto exec "Create user table" ... + +# Later: API using that schema +codex --full-auto exec "Create API for user table" resume --last ... +``` + +**Session Memory Indicates Recent Work**: +- Conversation history shows recent Codex execution +- Working on same module/feature +- Continuing interrupted work + +### Do NOT Use `resume --last` When + +**First Task in Conversation**: +```bash +# Always start fresh +codex -C project --full-auto exec "New feature" ... +``` + +**New Independent Task**: +```bash +# Unrelated to previous work +codex -C different-module --full-auto exec "Different feature" ... +``` + +**Different Module/Feature Area**: +```bash +# First: Auth module +codex -C src/auth --full-auto exec "Auth implementation" ... + +# Later: Payment module (NEW SESSION) +codex -C src/payment --full-auto exec "Payment implementation" ... +``` + +**No Recent Codex Task**: +```bash +# No Codex work in conversation history +codex -C project --full-auto exec "Fresh start" ... +``` + +## Session Continuity Best Practices + +### Context References + +**Use Session Context**: +```bash +codex --full-auto exec " +PURPOSE: Enhance previous implementation +TASK: Add caching to API endpoints +MODE: auto +CONTEXT: Previous API implementation from current session +EXPECTED: Cached endpoints with Redis integration +RULES: Maintain existing patterns +" resume --last --skip-git-repo-check -s danger-full-access +``` + +**Combine with File Patterns**: +```bash +codex --full-auto exec " +PURPOSE: Extend authentication +TASK: Add OAuth2 support +MODE: auto +CONTEXT: @{src/auth/**/*} Previous JWT implementation +EXPECTED: OAuth2 integration with existing auth +RULES: Maintain backward compatibility +" resume --last --skip-git-repo-check -s danger-full-access +``` + +### Multi-Phase Development + +**Phase 1: Core Implementation**: +```bash +codex -C src/features --full-auto exec " +PURPOSE: New feature foundation +TASK: Implement core feature logic +MODE: auto +CONTEXT: @{src/core/**/*} +EXPECTED: Feature foundation with basic functionality +RULES: Follow existing patterns +" --skip-git-repo-check -s danger-full-access +``` + +**Phase 2: Enhancement** (resume session): +```bash +codex --full-auto exec " +PURPOSE: Feature enhancement +TASK: Add validation and error handling +MODE: auto +CONTEXT: Previous core implementation +EXPECTED: Robust feature with validation +RULES: Handle edge cases +" resume --last --skip-git-repo-check -s danger-full-access +``` + +**Phase 3: Testing** (resume session): +```bash +codex --full-auto exec " +PURPOSE: Test coverage +TASK: Generate comprehensive tests +MODE: write +CONTEXT: Previous implementation with validations +EXPECTED: Test suite with 90%+ coverage +RULES: Test edge cases and error paths +" resume --last --skip-git-repo-check -s danger-full-access +``` + +**Phase 4: Documentation** (resume session): +```bash +codex --full-auto exec " +PURPOSE: Feature documentation +TASK: Generate API documentation and usage examples +MODE: write +CONTEXT: Complete implementation with tests +EXPECTED: Comprehensive documentation +RULES: Include code examples +" resume --last --skip-git-repo-check -s danger-full-access +``` + +## Interactive Session Management + +### Session Picker + +```bash +# Show all available sessions +codex resume + +# User selects from list: +# 1. Feature X implementation (2024-10-17 14:30) +# 2. Bug fix Y (2024-10-17 13:15) +# 3. Test generation Z (2024-10-17 12:00) +``` + +### Direct Resume + +```bash +# Resume most recent session immediately +codex resume --last + +# Continue work without picker +``` + +## Session Context Optimization + +### Effective Context References + +**Good - Specific and Relevant**: +```bash +CONTEXT: @{src/auth/**/*} Previous JWT implementation, session management patterns +``` + +**Better - Combines Session and Files**: +```bash +CONTEXT: Previous auth implementation from current session, @{src/auth/**/*,src/middleware/**/*} +``` + +**Best - Precise and Memory-Aware**: +```bash +CONTEXT: JWT middleware from previous task, @{src/auth/jwt.ts,src/auth/middleware.ts} Token validation patterns +``` + +### Context Continuity Patterns + +**Reference Previous Work**: +```bash +CONTEXT: Previous implementation of user registration +TASK: Add email verification to registration flow +``` + +**Build on Established Patterns**: +```bash +CONTEXT: Authentication patterns from session, existing middleware structure +TASK: Create authorization middleware following auth patterns +``` + +**Maintain Consistency**: +```bash +CONTEXT: API design from previous endpoints, established response format +TASK: Create new endpoint following existing design +``` + +## Common Session Patterns + +### Feature Development Cycle + +```bash +# 1. Implement β†’ 2. Enhance β†’ 3. Test β†’ 4. Document + +# Implement (start session) +codex -C src --full-auto exec "Implement feature" ... + +# Enhance (resume) +codex --full-auto exec "Add validations" resume --last ... + +# Test (resume) +codex --full-auto exec "Generate tests" resume --last ... + +# Document (resume) +codex --full-auto exec "Write docs" resume --last ... +``` + +### Bug Fix Cycle + +```bash +# 1. Identify β†’ 2. Fix β†’ 3. Test β†’ 4. Verify + +# Identify (start session) +codex -C src --full-auto exec "Analyze bug" ... + +# Fix (resume) +codex --full-auto exec "Implement fix" resume --last ... + +# Test (resume) +codex --full-auto exec "Add regression tests" resume --last ... + +# Verify (resume) +codex --full-auto exec "Verify fix across codebase" resume --last ... +``` + +### Refactoring Cycle + +```bash +# 1. Analyze β†’ 2. Plan β†’ 3. Refactor β†’ 4. Test + +# Analyze (start session) +codex -C src --full-auto exec "Analyze code for refactoring" ... + +# Plan (resume) +codex --full-auto exec "Plan refactoring approach" resume --last ... + +# Refactor (resume) +codex --full-auto exec "Execute refactoring" resume --last ... + +# Test (resume) +codex --full-auto exec "Verify refactoring with tests" resume --last ... +``` + +## Session Memory Management + +### What Gets Preserved + +**Implementation Context**: +- Code changes made +- Files created/modified +- Patterns established +- Decisions made + +**Design Context**: +- Architecture decisions +- Pattern choices +- Interface designs +- Integration points + +**Problem Context**: +- Issues identified +- Solutions attempted +- Trade-offs considered +- Edge cases handled + +### What Gets Lost + +**Starting New Session**: +- Previous implementation details +- Design decisions +- Context from prior work + +**When to Accept Context Loss**: +- Switching to unrelated module +- Starting independent feature +- Different problem domain +- Fresh approach needed + +## Troubleshooting + +### Session Not Found + +**Symptom**: `resume --last` fails to find session + +**Solutions**: +- Use `codex resume` to see available sessions +- Start new session if none relevant +- Check if previous task completed + +### Wrong Session Resumed + +**Symptom**: Resumed session from different feature + +**Solutions**: +- Use `codex resume` for manual selection +- Check conversation history for last Codex task +- Start new session if incorrect context + +### Context Mismatch + +**Symptom**: Session context doesn't match current task + +**Solutions**: +- Start new session for unrelated work +- Include explicit CONTEXT to override +- Use file patterns to focus context + +## Advanced Patterns + +### Parallel Session Management + +```bash +# Feature A - Session 1 +codex -C src/feature-a --full-auto exec "Implement A" ... + +# Feature B - Session 2 (different session) +codex -C src/feature-b --full-auto exec "Implement B" ... + +# Resume Feature A +codex --full-auto exec "Enhance A" resume --last ... +# Note: This resumes most recent (Feature B), not Feature A +# Use interactive picker: codex resume +``` + +### Session Branch Pattern + +```bash +# Main implementation +codex -C src --full-auto exec "Main feature" ... + +# Branch 1: Enhancement (resume) +codex --full-auto exec "Add feature X" resume --last ... + +# Branch 2: Alternative approach (new session) +codex -C src --full-auto exec "Try approach Y" ... +``` + +### Session Merge Pattern + +```bash +# Component A +codex -C src/components --full-auto exec "Create component A" ... + +# Component B (new session) +codex -C src/components --full-auto exec "Create component B" ... + +# Integration (new session, references both) +codex -C src --full-auto exec " +CONTEXT: Component A and B from previous work +TASK: Integrate components +" ... +``` diff --git a/.claude/skills/context-search/SKILL.md b/.claude/skills/context-search/SKILL.md new file mode 100644 index 00000000..a38ad673 --- /dev/null +++ b/.claude/skills/context-search/SKILL.md @@ -0,0 +1,92 @@ +--- +name: Context Search +description: Strategic context search tool selection for both planning and execution phases. Use during PLANNING (analyzing architecture, understanding existing code structure, gathering context) and EXECUTION (searching files, discovering implementations, locating dependencies). Triggers include "search for", "find files", "locate code", "analyze structure", "understand codebase", or when planning/implementing features. MANDATORY before any planning or implementation tasks. +allowed-tools: Bash, Grep, Glob, Read, mcp__code-index__search_code_advanced, mcp__code-index__find_files +--- + +# Context Search + +Strategic framework for selecting the right search tool based on task requirements. + +## Execution Environment + +**CRITICAL**: All commands execute in **Bash environment** (Git Bash on Windows, Bash on Linux/macOS) + +**❌ Forbidden**: Windows-specific commands (`findstr`, `dir`, `where`, `type`, `copy`, `del`) +**βœ… Required**: Use Bash equivalents (`grep`, `find`, `which`, `cat`, `cp`, `rm`) + +## Tool Selection Framework + +Use this decision tree to select the right search tool: + +### 1. Semantic File Discovery +**Tool**: `codebase-retrieval` (Gemini CLI) +**When**: Need files relevant to a task/feature/concept +**Command**: `~/.claude/scripts/gemini-wrapper --all-files -p "List all files relevant to: [description]"` + +### 2. Content Search +**Tool**: `rg` (ripgrep) - preferred +**When**: Searching code content with patterns +**Fallback**: `grep` (when rg unavailable) + +### 3. File/Directory Location +**Tool**: `find` +**When**: Locating files by name patterns +**Alternative**: MCP Code Index for glob patterns + +### 4. Program Architecture Analysis +**Tool**: `get_modules_by_depth.sh` +**When**: Understanding program structure (MANDATORY before planning) +**Command**: `~/.claude/scripts/get_modules_by_depth.sh` + +## Decision Principles + +- **Semantic discovery first** - Use codebase-retrieval for intelligent file discovery +- **Speed matters** - Prefer rg over grep for content search +- **Architecture before implementation** - Run get_modules_by_depth.sh before planning +- **No Windows commands** - Always use Bash equivalents + +## Tool Selection Matrix + +| Need | Primary Tool | Use Case | +|------|-------------|----------| +| **Semantic file discovery** | codebase-retrieval | Find files relevant to task/feature context | +| **Pattern matching** | rg (ripgrep) | Search code content with regex | +| **File name lookup** | find | Locate files by name patterns | +| **Architecture analysis** | get_modules_by_depth.sh | Understand program structure | + +## Workflow Integration + +Follow this recommended pattern for codebase exploration: + +1. **Architecture Analysis** (if planning) + ```bash + ~/.claude/scripts/get_modules_by_depth.sh + ``` + +2. **Semantic Discovery** (find relevant files) + ```bash + ~/.claude/scripts/gemini-wrapper --all-files -p "List all files relevant to: [task]" + ``` + +3. **Content Search** (search within files) + ```bash + rg "[pattern]" --type [filetype] + ``` + +4. **Deep Analysis** (understand found code) + - Use Read tool for specific files + - Use Gemini for architecture analysis + +## Performance Tips + +- **rg > grep** - Always prefer ripgrep for content search +- **Type filters** - Use `--type` to limit file types (e.g., `--type js`) +- **Exclude patterns** - Use `--glob '!node_modules'` to exclude common directories +- **Literal strings** - Use `-F` flag for exact matches (no regex overhead) + +## Examples + +For detailed command examples and workflow patterns, see [examples.md](examples.md). + +For complete command reference and options, see [reference.md](reference.md). diff --git a/.claude/skills/context-search/examples.md b/.claude/skills/context-search/examples.md new file mode 100644 index 00000000..f4b24ecb --- /dev/null +++ b/.claude/skills/context-search/examples.md @@ -0,0 +1,390 @@ +# Context Search Examples + +This document provides practical examples of using context search tools in different scenarios. + +## Quick Command Examples + +### Semantic File Discovery + +```bash +# Find files relevant to authentication +~/.claude/scripts/gemini-wrapper --all-files -p "List all files relevant to: user authentication and JWT" + +# Find files related to database schema +~/.claude/scripts/gemini-wrapper --all-files -p "List all files relevant to: database schema and migrations" + +# In Bash tool (with timeout) +bash(~/.claude/scripts/gemini-wrapper --all-files -p "List all files relevant to: API endpoints") +``` + +### Program Architecture Analysis + +```bash +# Analyze program structure (run before planning) +~/.claude/scripts/get_modules_by_depth.sh + +# In Bash tool +bash(~/.claude/scripts/get_modules_by_depth.sh) +``` + +### Content Search with ripgrep + +```bash +# Search in specific file types +rg "pattern" --type js # Search in JavaScript files +rg "pattern" --type ts # Search in TypeScript files +rg "pattern" --type py # Search in Python files + +# Case-insensitive search +rg -i "case-insensitive" + +# Show line numbers +rg -n "show-line-numbers" + +# Show context lines +rg -A 3 -B 3 "context-lines" # Show 3 lines before and after + +# Exclude directories +rg "pattern" --glob '!node_modules' +rg "pattern" --glob '!*.test.js' + +# Literal string search (no regex) +rg -F "exact.string.match" + +# Multiple file types +rg "pattern" --type-add 'web:*.{html,css,js}' --type web +``` + +### File Search with find + +```bash +# Find TypeScript files +find . -name "*.ts" -type f + +# Find files excluding node_modules +find . -path "*/node_modules" -prune -o -name "*.js" -print + +# Find files by multiple patterns +find . \( -name "*.ts" -o -name "*.tsx" \) -type f + +# Find and execute command on results +find . -name "*.test.js" -exec grep -l "describe" {} \; +``` + +### grep Alternatives (when rg unavailable) + +```bash +# Recursive search +grep -r "pattern" . + +# Case-insensitive with line numbers +grep -n -i "pattern" file.txt + +# Show context +grep -A 3 -B 3 "pattern" file.txt + +# Search multiple files +grep "pattern" *.js +``` + +## Workflow Integration Patterns + +### Pattern 1: Semantic Discovery β†’ Content Search β†’ Analysis + +```bash +# Step 1: Discover relevant files +~/.claude/scripts/gemini-wrapper --all-files -p "List all files relevant to: authentication system" + +# Step 2: Search within discovered files +rg "jwt|token|auth" --type ts + +# Step 3: Read specific files for analysis +# Use Read tool on identified files +``` + +### Pattern 2: Architecture Analysis for Planning + +```bash +# MANDATORY before any planning task +~/.claude/scripts/get_modules_by_depth.sh + +# Then proceed with planning based on structure +``` + +### Pattern 3: Workflow System Exploration + +```bash +# Search for task definitions +rg "IMPL-\d+" .workflow/ --type json + +# Locate task files +find .workflow/ -name "*.json" -path "*/.task/*" + +# Analyze workflow structure +rg "status.*pending" .workflow/.task/ + +# Show task dependencies +rg "depends_on" .workflow/.task/ -A 2 + +# Find active sessions +find .workflow/ -name ".active-*" + +# Search for session references +rg "WFS-" .workflow/ --type json +``` + +### Pattern 4: Code Pattern Analysis + +```bash +# Find flow control patterns with context +rg "flow_control" .workflow/ -B 2 -A 5 + +# Find implementation plans +find . -name "IMPL_PLAN.md" -exec grep -l "requirements" {} \; + +# Search for specific implementation patterns +rg "async.*function" --type ts -A 5 + +# Find error handling patterns +rg "try.*catch|throw new Error" --type js -B 2 -A 3 +``` + +### Pattern 5: Test Discovery + +```bash +# Find all test files +find . -name "*.test.ts" -o -name "*.spec.ts" + +# Search for specific test patterns +rg "describe\(|it\(|test\(" --type ts + +# Find tests for specific functionality +rg "test.*authentication|describe.*auth" --type ts + +# Find test files with specific assertions +rg "expect\(.*\)\.toBe" --type ts +``` + +### Pattern 6: API Endpoint Discovery + +```bash +# Find API route definitions +rg "app\.(get|post|put|delete|patch)" --type js + +# Find Express router usage +rg "Router\(\)|express\.Router" --type ts + +# Find API endpoint handlers +rg "@(Get|Post|Put|Delete|Patch)\(" --type ts +``` + +### Pattern 7: Configuration File Discovery + +```bash +# Find configuration files +find . -name "*.config.js" -o -name "*.config.ts" -o -name ".env*" + +# Search for environment variables +rg "process\.env\." --type ts + +# Find configuration patterns +rg "config\.|configuration" --type ts +``` + +## Common Scenarios + +### Scenario 1: Understanding Authentication System + +```bash +# 1. Find auth-related files +~/.claude/scripts/gemini-wrapper --all-files -p "List all files relevant to: authentication, JWT, sessions" + +# 2. Search for auth implementations +rg "authenticate|authorization" --type ts + +# 3. Find middleware usage +rg "middleware.*auth|auth.*middleware" --type ts + +# 4. Locate test files +rg "auth.*test|describe.*auth" --type ts +``` + +### Scenario 2: Database Schema Analysis + +```bash +# 1. Find database files +find . -name "*schema*" -o -name "*migration*" -o -name "*model*" + +# 2. Search for schema definitions +rg "Schema|model\.define|createTable" --type ts + +# 3. Find database queries +rg "SELECT|INSERT|UPDATE|DELETE" --type sql + +# 4. Find ORM usage +rg "findOne|findAll|create|update|destroy" --type ts +``` + +### Scenario 3: Component Structure Exploration + +```bash +# 1. Analyze architecture +~/.claude/scripts/get_modules_by_depth.sh + +# 2. Find component files +find . -name "*.tsx" -o -name "*.jsx" + +# 3. Search for component patterns +rg "export (default )?(function|const).*Component" --type tsx + +# 4. Find component imports +rg "import.*from.*components" --type tsx +``` + +### Scenario 4: Error Handling Audit + +```bash +# 1. Find error handling patterns +rg "try.*catch|throw new" --type ts -B 1 -A 3 + +# 2. Find error classes +rg "class.*Error extends|extends Error" --type ts + +# 3. Find error middleware +rg "errorHandler|error.*middleware" --type ts + +# 4. Find error logging +rg "console\.error|logger\.error|log\.error" --type ts +``` + +### Scenario 5: Dependency Analysis + +```bash +# 1. Find package.json files +find . -name "package.json" + +# 2. Search for specific package usage +rg "from ['\"]express['\"]|require\(['\"]express['\"]\)" --type ts + +# 3. Find import patterns +rg "^import.*from" --type ts | head -50 + +# 4. Find dynamic imports +rg "import\(|require\(" --type ts +``` + +## MCP Tool Integration Examples + +### Using Code Index Tools + +```bash +# Search code patterns +mcp__code-index__search_code_advanced(pattern="function.*auth", file_pattern="*.ts") + +# Find files by pattern +mcp__code-index__find_files(pattern="*.test.js") + +# Find files with wildcard +mcp__code-index__find_files(pattern="*async*") + +# Refresh index after git operations +mcp__code-index__refresh_index() + +# Get file summary +mcp__code-index__get_file_summary(file_path="src/auth/index.ts") +``` + +### Combined MCP and CLI Workflow + +```bash +# 1. Find files with MCP +mcp__code-index__find_files(pattern="*auth*") + +# 2. Search content with ripgrep +rg "jwt|token" --type ts + +# 3. Get file summaries +mcp__code-index__get_file_summary(file_path="src/auth/jwt.ts") + +# 4. Semantic discovery with Gemini +~/.claude/scripts/gemini-wrapper --all-files -p "List all files relevant to: authentication" +``` + +## Performance Optimization Examples + +### Optimized Searches + +```bash +# Fast: Use type filters +rg "pattern" --type ts + +# Faster: Exclude directories +rg "pattern" --glob '!node_modules' --glob '!dist' + +# Fastest: Literal search (no regex) +rg -F "exact.match" --type ts + +# Very fast: Limit to specific directory +rg "pattern" src/ --type ts +``` + +### Avoiding Slow Searches + +```bash +# ❌ Slow: No type filter, includes node_modules +grep -r "pattern" . + +# βœ… Fast: Type filter and exclusions +rg "pattern" --type ts --glob '!node_modules' + +# ❌ Slow: Complex regex on large files +rg ".*complex.*regex.*pattern.*" . + +# βœ… Fast: Simple patterns, literal when possible +rg -F "simple" --type ts +``` + +## Troubleshooting Examples + +### When rg is not available + +```bash +# Fall back to grep +grep -r "pattern" --include="*.ts" --exclude-dir="node_modules" . + +# Or use find + grep +find . -name "*.ts" -not -path "*/node_modules/*" -exec grep -l "pattern" {} \; +``` + +### When searching produces too many results + +```bash +# Add more specific patterns +rg "function authenticate" --type ts + +# Limit to specific directories +rg "pattern" src/auth/ --type ts + +# Use word boundaries +rg "\bpattern\b" --type ts + +# Show only filenames +rg "pattern" --type ts -l +``` + +### When searching is too slow + +```bash +# Use literal search +rg -F "literal.string" --type ts + +# Limit search depth +find . -maxdepth 3 -name "*.ts" + +# Search specific directory +rg "pattern" src/ --type ts + +# Use file type filters +rg "pattern" --type-list # List available types +rg "pattern" --type ts --type js +``` diff --git a/.claude/skills/context-search/reference.md b/.claude/skills/context-search/reference.md new file mode 100644 index 00000000..2b261c9a --- /dev/null +++ b/.claude/skills/context-search/reference.md @@ -0,0 +1,625 @@ +# Context Search Command Reference + +Complete reference for all context search tools and commands. + +## Tool Overview + +### codebase-retrieval (Semantic Discovery) + +**Purpose**: Intelligent file discovery based on task/feature context using Gemini CLI + +**Command Syntax**: +```bash +~/.claude/scripts/gemini-wrapper --all-files -p "List all files relevant to: [description]" +``` + +**Parameters**: +- `--all-files`: Enable all-files mode for semantic discovery +- `-p "prompt"`: Provide task/feature description + +**Use When**: +- Need to find files related to a concept or feature +- Don't know exact file names +- Want AI-powered file discovery +- Exploring unfamiliar codebase + +**Best Practices**: +- Be specific in description +- Include technology stack terms (e.g., "JWT authentication", "React components") +- Mention file types if relevant (e.g., "TypeScript interfaces") + +--- + +### rg (ripgrep) + +**Purpose**: Fast content search with regex support + +**Command Syntax**: +```bash +rg [OPTIONS] PATTERN [PATH...] +``` + +**Common Options**: + +| Option | Description | Example | +|--------|-------------|---------| +| `-i, --ignore-case` | Case-insensitive search | `rg -i "pattern"` | +| `-n, --line-number` | Show line numbers | `rg -n "pattern"` | +| `-A NUM` | Show NUM lines after match | `rg -A 3 "pattern"` | +| `-B NUM` | Show NUM lines before match | `rg -B 3 "pattern"` | +| `-C NUM` | Show NUM lines before and after | `rg -C 3 "pattern"` | +| `--type TYPE` | Search only TYPE files | `rg --type ts "pattern"` | +| `--glob PATTERN` | Include/exclude files by glob | `rg --glob '!*.test.js'` | +| `-F, --fixed-strings` | Treat pattern as literal string | `rg -F "exact.match"` | +| `-l, --files-with-matches` | Show only filenames | `rg -l "pattern"` | +| `-c, --count` | Show count of matches per file | `rg -c "pattern"` | +| `-w, --word-regexp` | Match whole words only | `rg -w "pattern"` | +| `--no-ignore` | Don't respect .gitignore | `rg --no-ignore "pattern"` | + +**File Type Filters**: +```bash +rg --type-list # List all available types + +# Common types +rg --type js "pattern" # JavaScript +rg --type ts "pattern" # TypeScript +rg --type py "pattern" # Python +rg --type rust "pattern" # Rust +rg --type go "pattern" # Go +rg --type java "pattern" # Java +rg --type cpp "pattern" # C++ +rg --type html "pattern" # HTML +rg --type css "pattern" # CSS +rg --type json "pattern" # JSON +rg --type yaml "pattern" # YAML +``` + +**Glob Patterns**: +```bash +# Include patterns +rg "pattern" --glob '*.ts' # Only TypeScript files +rg "pattern" --glob 'src/**/*.js' # JS files in src/ + +# Exclude patterns +rg "pattern" --glob '!*.test.js' # Exclude test files +rg "pattern" --glob '!node_modules' # Exclude node_modules +rg "pattern" --glob '!dist' # Exclude dist directory + +# Multiple globs +rg "pattern" --glob '*.ts' --glob '*.tsx' --glob '!*.test.*' +``` + +**Performance Tips**: +- Use `--type` instead of `--glob` when possible (faster) +- Use `-F` for literal strings (no regex overhead) +- Exclude large directories with `--glob '!node_modules'` +- Limit search to specific paths: `rg "pattern" src/` + +--- + +### find + +**Purpose**: Locate files and directories by name patterns + +**Command Syntax**: +```bash +find [PATH...] [OPTIONS] [EXPRESSION] +``` + +**Common Options**: + +| Option | Description | Example | +|--------|-------------|---------| +| `-name PATTERN` | Match filename pattern | `find . -name "*.ts"` | +| `-iname PATTERN` | Case-insensitive name match | `find . -iname "*.TXT"` | +| `-type TYPE` | Match file type (f=file, d=dir) | `find . -type f` | +| `-path PATTERN` | Match full path pattern | `find . -path "*/src/*"` | +| `-prune` | Don't descend into directory | `find . -path "*/node_modules" -prune` | +| `-maxdepth N` | Descend at most N levels | `find . -maxdepth 2` | +| `-mindepth N` | Start at least N levels deep | `find . -mindepth 1` | +| `-exec CMD {} \;` | Execute command on results | `find . -name "*.js" -exec wc -l {} \;` | + +**Common Patterns**: + +```bash +# Find files by extension +find . -name "*.ts" -type f +find . -name "*.js" -o -name "*.jsx" + +# Find files excluding directories +find . -path "*/node_modules" -prune -o -name "*.js" -print +find . -path "*/dist" -prune -o -path "*/.git" -prune -o -type f -print + +# Find files and execute command +find . -name "*.test.js" -exec grep -l "describe" {} \; +find . -name "*.ts" -type f -exec wc -l {} \; | sort -n + +# Find by depth +find . -maxdepth 2 -name "*.json" +find . -mindepth 2 -maxdepth 3 -name "package.json" + +# Find directories +find . -type d -name "*test*" + +# Find empty files +find . -type f -empty + +# Find files modified recently +find . -name "*.js" -mtime -7 # Modified in last 7 days +``` + +--- + +### grep + +**Purpose**: Built-in pattern matching (fallback when rg unavailable) + +**Command Syntax**: +```bash +grep [OPTIONS] PATTERN [FILE...] +``` + +**Common Options**: + +| Option | Description | Example | +|--------|-------------|---------| +| `-r, --recursive` | Search recursively | `grep -r "pattern" .` | +| `-i, --ignore-case` | Case-insensitive | `grep -i "pattern" file` | +| `-n, --line-number` | Show line numbers | `grep -n "pattern" file` | +| `-A NUM` | Show NUM lines after | `grep -A 3 "pattern" file` | +| `-B NUM` | Show NUM lines before | `grep -B 3 "pattern" file` | +| `-C NUM` | Show NUM lines context | `grep -C 3 "pattern" file` | +| `-l, --files-with-matches` | Show only filenames | `grep -l "pattern" *.js` | +| `-c, --count` | Count matches per file | `grep -c "pattern" *.js` | +| `-v, --invert-match` | Show non-matching lines | `grep -v "pattern" file` | +| `-w, --word-regexp` | Match whole words | `grep -w "word" file` | +| `-E, --extended-regexp` | Extended regex | `grep -E "pat1|pat2" file` | +| `--include=PATTERN` | Include files matching | `grep -r "pattern" --include="*.js"` | +| `--exclude=PATTERN` | Exclude files matching | `grep -r "pattern" --exclude="*.test.js"` | +| `--exclude-dir=PATTERN` | Exclude directories | `grep -r "pattern" --exclude-dir="node_modules"` | + +**Common Patterns**: + +```bash +# Recursive search +grep -r "pattern" . +grep -r "pattern" --include="*.ts" --exclude-dir="node_modules" . + +# Case-insensitive with line numbers +grep -i -n "pattern" file.txt + +# Show context +grep -A 3 -B 3 "pattern" file.txt +grep -C 5 "pattern" file.txt + +# Multiple patterns +grep -E "pattern1|pattern2" file.txt +grep "pattern1" file.txt | grep "pattern2" + +# Invert match (exclude lines) +grep -v "exclude" file.txt + +# Count matches +grep -c "pattern" *.js + +# Find files containing pattern +grep -l "pattern" *.js +grep -r -l "pattern" --include="*.ts" . +``` + +**Note**: Prefer `rg` over `grep` for better performance and features. + +--- + +### get_modules_by_depth.sh + +**Purpose**: Program architecture analysis and structural discovery + +**Command Syntax**: +```bash +~/.claude/scripts/get_modules_by_depth.sh +``` + +**No Options**: Script runs automatically and analyzes current directory structure + +**Use When**: +- Starting a new planning task (MANDATORY) +- Need to understand program architecture +- Exploring project structure +- Before making structural changes + +**Output**: Hierarchical view of program modules and their relationships + +**Best Practices**: +- Run before any planning or architecture work +- Run from project root directory +- Use output to inform file organization decisions +- Reference output when discussing architecture + +--- + +## MCP Code Index Tools + +### mcp__code-index__search_code_advanced + +**Purpose**: Advanced code pattern search with fuzzy matching + +**Parameters**: +```typescript +{ + pattern: string, // Search pattern (regex or literal) + case_sensitive?: boolean, // Default: true + context_lines?: number, // Default: 0 + file_pattern?: string, // Glob pattern (e.g., "*.ts") + fuzzy?: boolean, // Default: false + max_line_length?: number, // Default: none + regex?: boolean // Default: null (auto-detect) +} +``` + +**Examples**: +```bash +# Basic search +mcp__code-index__search_code_advanced(pattern="function.*auth") + +# With file filter +mcp__code-index__search_code_advanced(pattern="interface.*Props", file_pattern="*.tsx") + +# Case-insensitive with context +mcp__code-index__search_code_advanced(pattern="error", case_sensitive=false, context_lines=3) + +# Fuzzy search +mcp__code-index__search_code_advanced(pattern="auhtenticate", fuzzy=true) +``` + +--- + +### mcp__code-index__find_files + +**Purpose**: Find files by glob pattern using pre-built index + +**Parameters**: +```typescript +{ + pattern: string // Glob pattern (e.g., "*.ts", "*auth*") +} +``` + +**Pattern Types**: +- Full path matching: `src/**/*.ts` +- Filename only: `README.md` (finds all README files) +- Wildcard: `*auth*` (files containing "auth") + +**Examples**: +```bash +# Find all Markdown files +mcp__code-index__find_files(pattern="*.md") + +# Find files with wildcard +mcp__code-index__find_files(pattern="*auth*") + +# Find test files +mcp__code-index__find_files(pattern="*.test.ts") + +# Find specific file +mcp__code-index__find_files(pattern="package.json") +``` + +**Note**: Use wildcard patterns for better results than exact matches. + +--- + +### mcp__code-index__refresh_index + +**Purpose**: Manually refresh project file index + +**Parameters**: None + +**Use When**: +- After major git operations (pull, merge, checkout) +- File watcher is disabled or unavailable +- Index seems outdated +- Large-scale file operations completed + +**Example**: +```bash +mcp__code-index__refresh_index() +``` + +--- + +### mcp__code-index__get_file_summary + +**Purpose**: Get structural summary of a file + +**Parameters**: +```typescript +{ + file_path: string // Path to file +} +``` + +**Returns**: +- Line count +- Function/class definitions +- Import statements +- Basic complexity metrics + +**Example**: +```bash +mcp__code-index__get_file_summary(file_path="src/auth/index.ts") +``` + +--- + +## Performance Comparison + +### Speed Rankings (Fastest to Slowest) + +1. **rg (ripgrep)** - Fastest for content search +2. **find** - Fast for file location +3. **MCP Code Index** - Fast for indexed searches +4. **grep** - Slower than rg +5. **codebase-retrieval** - Slower (AI-powered) + +### Recommended Tool by Task + +| Task | Fastest Tool | Alternative | +|------|-------------|-------------| +| Content search | rg | grep | +| File location | find | MCP find_files | +| Pattern search | rg | MCP search_code_advanced | +| Semantic discovery | codebase-retrieval | - | +| Architecture analysis | get_modules_by_depth.sh | - | + +--- + +## Optimization Strategies + +### General Tips + +1. **Use type filters** - Always specify file types when possible +2. **Exclude directories** - Skip node_modules, dist, .git +3. **Literal search** - Use `-F` flag when pattern has no regex +4. **Limit scope** - Search specific directories instead of entire project +5. **Use indexes** - MCP Code Index is fast for indexed operations + +### Pattern Optimization + +```bash +# ❌ Slow: Complex regex +rg ".*complex.*nested.*pattern.*" + +# βœ… Fast: Simple patterns +rg "complex" | rg "nested" | rg "pattern" + +# ❌ Slow: No type filter +rg "pattern" + +# βœ… Fast: With type filter +rg "pattern" --type ts + +# ❌ Slow: Searches everything +rg "pattern" . + +# βœ… Fast: Limited scope +rg "pattern" src/ +``` + +### Exclusion Patterns + +```bash +# Standard exclusions for most projects +rg "pattern" \ + --glob '!node_modules' \ + --glob '!dist' \ + --glob '!build' \ + --glob '!.git' \ + --glob '!coverage' \ + --glob '!*.min.js' + +# With find +find . \ + -path "*/node_modules" -prune -o \ + -path "*/dist" -prune -o \ + -path "*/.git" -prune -o \ + -name "*.ts" -print +``` + +--- + +## Environment-Specific Notes + +### Git Bash on Windows + +- All commands work in Git Bash environment +- Use forward slashes (`/`) in paths +- Use POSIX-style paths (`/c/Users` instead of `C:\Users`) +- ❌ No Windows commands: `findstr`, `dir`, `where`, `type` +- βœ… Use Bash equivalents: `grep`, `find`, `which`, `cat` + +### Path Handling + +```bash +# βœ… Correct (Bash) +find . -name "*.ts" +rg "pattern" src/ + +# ❌ Wrong (Windows) +dir /s /b *.ts +findstr /s "pattern" src\ +``` + +--- + +## Troubleshooting + +### Command Not Found + +```bash +# Check if rg is installed +which rg + +# Fallback to grep if rg unavailable +if ! command -v rg &> /dev/null; then + grep -r "pattern" . +else + rg "pattern" +fi +``` + +### Too Many Results + +```bash +# Add more specific patterns +rg "very.specific.pattern" --type ts + +# Limit to directory +rg "pattern" src/auth/ + +# Show only filenames +rg "pattern" -l + +# Count matches +rg "pattern" -c +``` + +### Too Slow + +```bash +# Use literal search +rg -F "literal" --type ts + +# Exclude large directories +rg "pattern" --glob '!node_modules' --glob '!dist' + +# Limit depth +find . -maxdepth 3 -name "*.ts" + +# Use type filters +rg "pattern" --type ts +``` + +### No Matches Found + +```bash +# Try case-insensitive +rg -i "pattern" + +# Try fuzzy search (MCP) +mcp__code-index__search_code_advanced(pattern="patern", fuzzy=true) + +# Check if file type is correct +rg "pattern" --type-list + +# Try without filters +rg "pattern" . +``` + +--- + +## Advanced Usage + +### Combining Tools + +```bash +# Use find to get files, rg to search within +find . -name "*.ts" -type f | xargs rg "pattern" + +# Use rg to find files, then process +rg -l "pattern" --type ts | xargs wc -l + +# Semantic discovery β†’ content search +FILES=$(~/.claude/scripts/gemini-wrapper --all-files -p "List files for: auth") +echo "$FILES" | xargs rg "jwt" +``` + +### Piping Results + +```bash +# Chain searches +rg "pattern1" --type ts | rg "pattern2" + +# Count results +rg "pattern" -l | wc -l + +# Sort by frequency +rg "pattern" -c | sort -t: -k2 -n + +# Get unique matches +rg "pattern" -o | sort | uniq -c | sort -n +``` + +### Custom Scripts + +```bash +# Create custom search function +search_feature() { + local feature=$1 + echo "Searching for: $feature" + + # Semantic discovery + ~/.claude/scripts/gemini-wrapper --all-files -p "List files for: $feature" + + # Content search + rg "$feature" --type ts -C 2 +} + +# Use it +search_feature "authentication" +``` + +--- + +## Quick Reference Card + +### Most Common Commands + +```bash +# Semantic file discovery +~/.claude/scripts/gemini-wrapper --all-files -p "List files for: [task]" + +# Architecture analysis +~/.claude/scripts/get_modules_by_depth.sh + +# Content search +rg "pattern" --type ts + +# File search +find . -name "*.ts" -type f + +# MCP search +mcp__code-index__search_code_advanced(pattern="pattern", file_pattern="*.ts") + +# MCP find +mcp__code-index__find_files(pattern="*pattern*") +``` + +### Common Options + +```bash +# Case-insensitive +rg -i "pattern" + +# Show context +rg -C 3 "pattern" + +# Exclude directory +rg "pattern" --glob '!node_modules' + +# Literal search +rg -F "exact.match" + +# Type filter +rg "pattern" --type ts +``` + +--- + +## See Also + +- [SKILL.md](SKILL.md) - Core decision framework +- [examples.md](examples.md) - Practical usage examples +- ripgrep documentation: https://github.com/BurntSushi/ripgrep +- find man page: `man find` +- grep man page: `man grep` diff --git a/.claude/skills/gemini/SKILL.md b/.claude/skills/gemini/SKILL.md new file mode 100644 index 00000000..54471d49 --- /dev/null +++ b/.claude/skills/gemini/SKILL.md @@ -0,0 +1,271 @@ +--- +name: Gemini CLI Tool +description: Code analysis and documentation tool (primary). Trigger keywords "use gemini", "gemini analysis", "analyze with gemini". Use for code exploration, architecture review, and documentation generation. Supports read-only analysis (default) and write operations (explicit permission). +allowed-tools: Bash, Read, Glob, Grep +--- + +# Gemini CLI Tool + +## Core Execution + +Gemini executes code analysis and documentation tasks using large context window capabilities. + +**Trigger Keywords**: "use gemini", "gemini analysis", "gemini generate docs", "analyze with gemini" + +**Execution Modes**: +- `analysis` (default): Read-only analysis, auto-execute +- `write`: Create/modify files, requires explicit permission + +**Command Pattern**: +```bash +cd [directory] && ~/.claude/scripts/gemini-wrapper [--approval-mode yolo] -p " +PURPOSE: [goal] +TASK: [specific task] +MODE: [analysis|write] +CONTEXT: @{file/patterns} +EXPECTED: [results] +RULES: [constraints] +" +``` + +## Universal Template Structure + +Every Gemini command should follow this detailed structure for best results: + +```bash +cd [directory] && ~/.claude/scripts/gemini-wrapper [--approval-mode yolo] -p " +PURPOSE: [One clear sentence: what and why] +TASK: [Specific actionable task with scope] +MODE: [analysis|write] +CONTEXT: @{file/patterns} [Previous session context, dependencies, constraints] +EXPECTED: [Deliverable format, file names, coverage requirements] +RULES: [Template reference] | [Specific constraints: standards, patterns, focus areas] +" +``` + +### Template Field Guidelines + +**PURPOSE**: +- One sentence combining goal + reason +- Examples: "Analyze auth system to identify security risks", "Generate API docs for partner integration" + +**TASK**: +- Break down into numbered sub-tasks for complex operations +- Include specific aspects: "Review JWT implementation, token management, session handling" +- Specify scope boundaries + +**CONTEXT**: +- File patterns: `@{src/**/*.ts}` (include only what you need) +- Business context: "50k DAU, PostgreSQL 14, target <200ms p95" +- Tech stack: Versions, frameworks, constraints +- Session memory: "Previous analysis showed X" + +**EXPECTED**: +- Numbered deliverables: "1) File.md with sections, 2) Diagram in Mermaid format" +- Specific file names: "API.md", "SECURITY.md", "analysis-report.json" +- Coverage requirements: ">90% test coverage", "All endpoints documented" +- Output format: "Markdown tables", "OpenAPI 3.1 spec", "Mermaid diagrams" + +**RULES**: +- Template reference: `$(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt)` +- Multiple constraints separated by `|`: "Follow OWASP Top 10 | Use TypeScript strict | Include metrics" +- Specific standards: "OWASP ASVS v4.0", "SOC 2 CC6.1", "RFC 6749" +- Thresholds: "Complexity >10 is high", ">80% cache hit rate" + +## Command Structure + +### Universal Template +Every Gemini command follows this structure: + +```bash +cd [directory] && ~/.claude/scripts/gemini-wrapper [options] -p " +PURPOSE: [clear goal and intent] +TASK: [specific execution task] +MODE: [analysis|write] +CONTEXT: [file references and memory context] +EXPECTED: [clear expected results] +RULES: [template reference and constraints] +" +``` + +## Execution Modes + +### Analysis Mode (Default - Read-Only) +Safe for auto-execution without user confirmation: + +```bash +cd [directory] && ~/.claude/scripts/gemini-wrapper -p " +PURPOSE: [analysis goal] +TASK: [specific analysis task] +MODE: analysis +CONTEXT: @{file/patterns} [session memory] +EXPECTED: [analysis output] +RULES: [constraints] +" +``` + +**When to use**: +- Code exploration and understanding +- Architecture analysis +- Pattern discovery +- Security assessment +- Performance analysis + +### Write Mode (Requires Explicit Permission) +⚠️ Only use when user explicitly requests file creation/modification: + +```bash +cd [directory] && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p " +PURPOSE: [documentation goal] +TASK: [specific write task] +MODE: write +CONTEXT: @{file/patterns} +EXPECTED: [generated files] +RULES: [constraints] +" +``` + +**Parameter Position**: `--approval-mode yolo` must be placed AFTER `gemini-wrapper`, BEFORE `-p` + +**Write Triggers**: +- User explicitly says "generate documentation" +- User explicitly says "create/modify files" +- User specifies `MODE=write` in prompt + +## File Pattern Reference + +Common patterns for CONTEXT field: + +```bash +@{**/*} # All files +@{src/**/*} # Source files +@{*.ts,*.tsx} # TypeScript files +@{CLAUDE.md,**/*CLAUDE.md} # Documentation +@{src/**/*.test.*} # Test files +``` + +**Complex Pattern Discovery**: +For complex requirements, discover files first: +```bash +# Step 1: Discover with ripgrep or MCP +rg "export.*Component" --files-with-matches --type ts + +# Step 2: Build precise CONTEXT +CONTEXT: @{src/components/Auth.tsx,src/types/auth.d.ts} + +# Step 3: Execute with precise references +``` + +## Template System + +Templates are located in `~/.claude/workflows/cli-templates/prompts/` + +### Available Templates + +**Analysis Templates**: +- `analysis/pattern.txt` - Code pattern analysis +- `analysis/architecture.txt` - System architecture review +- `analysis/security.txt` - Security assessment +- `analysis/quality.txt` - Code quality review + +**Development Templates**: +- `development/feature.txt` - Feature implementation +- `development/refactor.txt` - Refactoring tasks +- `development/testing.txt` - Test generation + +**Memory Templates**: +- `memory/claude-module-unified.txt` - Module documentation + +### Using Templates in RULES Field + +```bash +# Single template +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) | Focus on security + +# Multiple templates +RULES: $(cat template1.txt) $(cat template2.txt) | Enterprise standards + +# No template +RULES: Focus on security patterns, include dependency analysis +``` + +⚠️ **CRITICAL**: Never use escape characters (`\$`, `\"`, `\'`) in CLI commands - breaks command substitution. + +## Context Optimization + +Use `cd [directory] &&` pattern to focus analysis and reduce irrelevant context: + +```bash +# Focused analysis +cd src/auth && ~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Understand authentication patterns +TASK: Analyze auth implementation +MODE: analysis +CONTEXT: @{**/*.ts} +EXPECTED: Pattern documentation +RULES: Focus on security best practices +" +``` + +**When to change directory**: +- Specific directory mentioned β†’ Use `cd directory &&` +- Focused analysis needed β†’ Target specific directory +- Multi-directory scope β†’ Stay in root, use explicit paths + +## Execution Configuration + +### Timeout Allocation (Dynamic) +Based on task complexity: +- **Simple** (analysis, search): 20-40min (1200000-2400000ms) +- **Medium** (refactoring, docs): 40-60min (2400000-3600000ms) +- **Complex** (implementation): 60-120min (3600000-7200000ms) + +Auto-detect from PURPOSE and TASK fields. + +### Permission Framework +- βœ… **Analysis Mode (default)**: Auto-execute without confirmation +- ⚠️ **Write Mode**: Requires explicit user confirmation or MODE=write specification +- πŸ”’ **Write Protection**: Never modify codebase without explicit user instruction + +## Examples + +Production-ready examples organized by scenario type: + +- **[Analysis Examples](analysis-examples.md)** - Read-only analysis with architecture review, pattern discovery, and multi-module tracing +- **[Write Examples](write-examples.md)** - Documentation generation with OpenAPI specs and module documentation +- **[Advanced Workflows](advanced-workflows.md)** - Multi-phase discovery β†’ analysis β†’ documentation pipelines +- **[Template Examples](template-examples.md)** - Multiple template combinations for comprehensive audits +- **[Context Optimization](context-optimization.md)** - Focused analysis strategies for large codebases + +Each example follows the Universal Template Structure with detailed explanations. + +## Best Practices + +### Analysis Phase +- Use analysis mode for all exploratory work +- Focus on specific directories with `cd` pattern +- Include relevant file patterns in CONTEXT +- Reference session memory for continuity + +### Documentation Phase +- Always use write mode with `--approval-mode yolo` +- Get explicit user confirmation first +- Include source files in CONTEXT +- Follow project documentation standards + +## Error Handling + +**If timeout occurs**: +- Reduce CONTEXT scope +- Use more specific file patterns +- Split into smaller analysis tasks + +**If context too large**: +- Use `cd` to focus on specific directory +- Narrow file patterns +- Analyze in phases + +**If output incomplete**: +- Increase timeout allocation +- Simplify EXPECTED results +- Break into multiple commands diff --git a/.claude/skills/gemini/advanced-workflows.md b/.claude/skills/gemini/advanced-workflows.md new file mode 100644 index 00000000..30da32d5 --- /dev/null +++ b/.claude/skills/gemini/advanced-workflows.md @@ -0,0 +1,47 @@ +# Gemini Advanced Multi-Phase Workflows + +> **πŸ“– Template Structure**: See [Universal Template Structure](command-structure.md) for detailed field guidelines. + +## Discovery β†’ Analysis β†’ Documentation Pipeline + +This three-phase workflow demonstrates how to combine file discovery, deep analysis, and documentation generation. + +### Phase 1: File Discovery (using ripgrep) + +```bash +# Use ripgrep for semantic search +rg "export.*Component|export.*interface.*Props" --files-with-matches --type ts src/components/ +``` + +### Phase 2: Deep Analysis + +```bash +cd src && ~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Analyze React component architecture to standardize component patterns and improve type safety +TASK: Review component structure, props interface design, state management approach, lifecycle usage, composition patterns, performance optimizations (memo, callback, useMemo) +MODE: analysis +CONTEXT: @{components/Auth.tsx,components/Profile.tsx,components/Dashboard.tsx,types/auth.d.ts,types/user.d.ts,hooks/useAuth.ts,hooks/useProfile.ts} React 18, TypeScript 5, using Context API for state, no Redux +EXPECTED: Component pattern analysis covering: 1) Component classification (Container/Presentational), 2) Props interface consistency report, 3) State management pattern evaluation, 4) Performance optimization opportunities, 5) Recommended component template, 6) Refactoring priority matrix +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) | Focus on TypeScript type safety | Evaluate React 18 features usage | Consider testing implications | Follow functional component patterns | Assess accessibility compliance | Include bundle size impact +" +``` + +### Phase 3: Documentation Generation + +```bash +~/.claude/scripts/gemini-wrapper --approval-mode yolo -p " +PURPOSE: Create component pattern guide based on analysis results +TASK: Generate comprehensive guide documenting: standard component template, props interface best practices, state management patterns, composition examples, testing strategies +MODE: write +CONTEXT: Analysis results from Phase 2 showing: 3 component patterns identified, 60% type safety compliance, 5 performance issues found +EXPECTED: Create COMPONENT_PATTERNS.md with sections: 1) Standard Template (with code), 2) Props Interface Guidelines, 3) State Management Recipes, 4) Composition Patterns, 5) Performance Best Practices, 6) Testing Strategies, 7) Migration Guide (from current to standard). Include before/after code examples for each pattern. +RULES: Use code fences with TypeScript syntax | Provide runnable examples | Include ESLint/Prettier configs | Add testing examples with React Testing Library | Reference React 18 documentation | Create visual component hierarchy diagrams | Add FAQ section for common issues +" +``` + +### Key Points + +- **Three phases**: Discovery (rg) β†’ Analysis (Gemini) β†’ Documentation (Gemini write) +- **Context flow**: Phase 2 uses discovered files, Phase 3 references Phase 2 results +- **Comprehensive EXPECTED**: Detailed output structure with before/after examples +- **Progressive RULES**: Build on analysis findings, add implementation details diff --git a/.claude/skills/gemini/analysis-examples.md b/.claude/skills/gemini/analysis-examples.md new file mode 100644 index 00000000..7da7cac1 --- /dev/null +++ b/.claude/skills/gemini/analysis-examples.md @@ -0,0 +1,63 @@ +# Gemini Analysis Mode Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](command-structure.md) for detailed field guidelines. + +All examples demonstrate read-only analysis mode with comprehensive template usage. + +## Example 1: Architecture Analysis with Multiple Constraints + +```bash +cd src/auth && ~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Analyze authentication system architecture to identify security risks and scalability issues +TASK: Review JWT implementation, token management, session handling, and middleware integration +MODE: analysis +CONTEXT: @{**/*.ts,**/*.json} Current system handles 10k users, planning to scale to 100k +EXPECTED: Architecture analysis report covering: security vulnerabilities, scalability bottlenecks, integration risks, priority recommendations with effort estimates +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Focus on OWASP Top 10 | Follow OAuth 2.0 best practices | Consider microservices migration path | Include performance metrics +" +``` + +**Key Points**: +- **PURPOSE**: Clear goal (analyze) + reason (identify risks) +- **TASK**: Multiple specific aspects to review +- **CONTEXT**: File patterns + business context (scale requirements) +- **EXPECTED**: Multiple deliverables with specific coverage +- **RULES**: Template + multiple constraints separated by `|` + +## Example 2: Pattern Discovery with Output Specifications + +```bash +cd src && ~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Identify and document error handling patterns to establish coding standards +TASK: Analyze error handling across all modules, categorize patterns (try-catch, promise rejection, async/await, custom error classes), identify inconsistencies +MODE: analysis +CONTEXT: @{**/*.ts,!**/*.test.ts,!**/node_modules/**} Team size 5 developers, TypeScript 5.0, Node 20 LTS +EXPECTED: Pattern analysis document including: 1) Pattern catalog with code examples, 2) Consistency score by module, 3) Recommended standard pattern, 4) Migration guide from inconsistent patterns to standard +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) | Focus on async/await patterns | Exclude test files | Consider error logging integration | Follow TypeScript strict mode conventions +" +``` + +**Key Points**: +- **TASK**: Break down into sub-tasks (analyze β†’ categorize β†’ identify) +- **CONTEXT**: Exclude patterns with `!` + tech stack context +- **EXPECTED**: Numbered deliverables with clear output structure +- **RULES**: Multiple focus areas + exclusions + tech constraints + +## Example 3: Multi-Module Analysis with Dependency Tracing + +```bash +~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Understand data flow from API to database to identify performance bottlenecks +TASK: Trace data flow through: API endpoints β†’ Controllers β†’ Services β†’ Repositories β†’ Database, identify transformation points, analyze query patterns, measure complexity at each layer +MODE: analysis +CONTEXT: @{src/api/**/*.ts,src/controllers/**/*.ts,src/services/**/*.ts,src/repositories/**/*.ts,src/models/**/*.ts,CLAUDE.md} Current API response time avg 500ms, target <200ms +EXPECTED: Data flow diagram (Mermaid format), transformation analysis per layer, query complexity report, performance bottleneck identification with impact scores (high/medium/low), optimization recommendations prioritized by ROI +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Map all transformation points | Identify N+1 query problems | Consider caching opportunities | Include database index recommendations | Follow repository pattern standards +" +``` + +**Key Points**: +- **TASK**: Multi-step trace with specific layers +- **CONTEXT**: Multiple module paths + performance metrics +- **EXPECTED**: Multiple output formats (diagram + reports) with prioritization +- **RULES**: Comprehensive constraint list with specific technical focuses diff --git a/.claude/skills/gemini/context-optimization.md b/.claude/skills/gemini/context-optimization.md new file mode 100644 index 00000000..0128908d --- /dev/null +++ b/.claude/skills/gemini/context-optimization.md @@ -0,0 +1,79 @@ +# Gemini Context Optimization Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](command-structure.md) for detailed field guidelines. + +## Focused Analysis with Exclusions + +```bash +cd src/auth && ~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Audit authentication security for compliance certification +TASK: Review JWT implementation, password hashing, session management, token refresh logic, MFA support, rate limiting, brute force protection +MODE: analysis +CONTEXT: @{**/*.ts,!**/*.test.ts,!**/*.mock.ts,../../config/security.json,../../middleware/auth.middleware.ts} Targeting SOC 2 Type II compliance, current system uses bcrypt, JWT with RS256, Redis for session store +EXPECTED: Security compliance report including: 1) Compliance checklist (SOC 2 controls mapped to implementation), 2) Vulnerability assessment (with CVE references), 3) Configuration review, 4) Encryption strength analysis, 5) Audit logging evaluation, 6) Remediation plan with compliance deadlines, 7) Evidence collection guide for auditors +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt) | Map to SOC 2 CC6.1, CC6.6, CC6.7 controls | Follow NIST password guidelines | Validate OWASP ASVS Level 2 compliance | Check for hardcoded secrets | Evaluate token expiration policies | Include incident response procedures | Reference GDPR data handling requirements +" +``` + +**Key Points**: +- **Context exclusions**: `!` pattern for test and mock files +- **Compliance context**: Specific certification requirements +- **Detailed EXPECTED**: Compliance-focused deliverables with evidence collection +- **Compliance RULES**: Specific standards (SOC 2, NIST, OWASP, GDPR) + control mappings + +## Large Codebase with Scoped Analysis + +Split large analysis into focused modules to avoid timeout. + +### Module 1: Core Analysis + +```bash +cd src/core && ~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Analyze core module patterns to establish architectural foundation +TASK: Review core abstractions, utility functions, base classes, shared types, configuration management +MODE: analysis +CONTEXT: @{**/*.ts,../../CLAUDE.md} Core module used by 15 feature modules, no external dependencies allowed +EXPECTED: Core architecture analysis: 1) Abstraction layer review, 2) Dependency graph (showing zero external deps), 3) Reusability metrics, 4) API stability assessment, 5) Recommended improvements prioritized by breaking change risk +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Focus on zero-dependency principle | Evaluate backward compatibility | Consider semver implications | Document all public APIs | Assess bundle size impact +" +``` + +### Module 2: Features Analysis (separate execution) + +```bash +cd src/features && ~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Analyze feature module patterns referencing core architecture findings +TASK: Review feature implementations, core module usage, inter-feature dependencies, feature flag patterns +MODE: analysis +CONTEXT: @{**/*.ts,../core/**/*.ts,../../CLAUDE.md} Core analysis results: 5 base classes, 12 utilities, stable API since v2.0 +EXPECTED: Feature pattern analysis: 1) Core usage compliance report, 2) Inter-feature coupling matrix, 3) Feature flag effectiveness, 4) Code reuse opportunities, 5) Migration path to reduce coupling +RULES: Reference core module standards from previous analysis | Identify tight coupling antipatterns | Evaluate feature flag strategy | Consider feature extraction to separate packages | Follow plugin architecture where applicable +" +``` + +**Key Points**: +- **Split strategy**: Large codebase divided by module +- **Context flow**: Module 2 references Module 1 results +- **Scoped EXPECTED**: Each module has focused deliverables +- **Progressive RULES**: Build on previous analysis findings + +## Directory-Scoped Analysis + +Use `cd` pattern to reduce context size: + +```bash +cd src/auth && ~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Security audit of authentication module +TASK: Deep security analysis of auth implementation +MODE: analysis +CONTEXT: @{**/*.ts} All files in current directory +EXPECTED: Security audit report +RULES: Focus on OWASP Top 10 +" +``` + +**Benefits**: +- Reduced context size +- Faster execution +- Focused analysis +- Avoid irrelevant code inclusion diff --git a/.claude/skills/gemini/template-examples.md b/.claude/skills/gemini/template-examples.md new file mode 100644 index 00000000..fd0bff83 --- /dev/null +++ b/.claude/skills/gemini/template-examples.md @@ -0,0 +1,44 @@ +# Gemini Template Usage Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](command-structure.md) for detailed field guidelines. + +## Multiple Templates with Custom Constraints + +This example demonstrates combining multiple templates for comprehensive analysis. + +```bash +~/.claude/scripts/gemini-wrapper -p " +PURPOSE: Comprehensive security and code quality audit for production release +TASK: Perform full codebase review covering: security vulnerabilities, code quality metrics, pattern consistency, performance bottlenecks, documentation coverage +MODE: analysis +CONTEXT: @{src/**/*,!**/node_modules/**,!**/*.test.ts,CLAUDE.md,package.json,tsconfig.json} Production release scheduled in 2 weeks, team of 8 developers, 50k lines of code +EXPECTED: Consolidated audit report with: 1) Executive Summary (priority issues), 2) Security Findings (OWASP categorized), 3) Code Quality Metrics (complexity, duplication, test coverage), 4) Pattern Consistency Score, 5) Performance Analysis, 6) Documentation Gaps, 7) Remediation Roadmap (2-week sprint plan) +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/quality.txt) | Follow enterprise security standards | Include CVSS scores for vulnerabilities | Calculate technical debt in hours | Prioritize by business impact | Provide automated fix scripts where possible | Consider CI/CD integration for continuous monitoring +" +``` + +## Key Points + +- **Multiple templates**: Three templates combined for comprehensive review +- **Complex EXPECTED**: 7 sections with specific output requirements +- **Detailed RULES**: Mix of templates + enterprise standards + quantifiable metrics + automation considerations + +## Template Combinations + +### Security + Architecture + +```bash +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Focus on integration security | Include threat modeling +``` + +### Pattern + Quality + +```bash +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/quality.txt) | Identify antipatterns | Calculate maintainability index +``` + +### All Analysis Templates + +```bash +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/quality.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Comprehensive review for production readiness +``` diff --git a/.claude/skills/gemini/write-examples.md b/.claude/skills/gemini/write-examples.md new file mode 100644 index 00000000..fe6ff7e9 --- /dev/null +++ b/.claude/skills/gemini/write-examples.md @@ -0,0 +1,42 @@ +# Gemini Write Mode Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](command-structure.md) for detailed field guidelines. + +All examples demonstrate write mode with explicit `--approval-mode yolo` and user permission. + +## Example 1: Documentation Generation with Structured Output + +```bash +~/.claude/scripts/gemini-wrapper --approval-mode yolo -p " +PURPOSE: Generate comprehensive API documentation for external developers +TASK: Document all REST endpoints including: HTTP methods, routes, request/response schemas, authentication requirements, rate limits, error codes, example requests/responses +MODE: write +CONTEXT: @{src/api/**/*.ts,src/middleware/**/*.ts,src/validators/**/*.ts} API follows OpenAPI 3.0, uses JWT auth, implements rate limiting with Redis +EXPECTED: Create API.md with sections: 1) Overview, 2) Authentication, 3) Endpoints (grouped by resource), 4) Error Handling, 5) Rate Limits, 6) Code Examples (curl, JavaScript, Python). Include OpenAPI spec generation instructions. +RULES: Follow OpenAPI 3.0 specification | Use markdown tables for endpoints | Include all HTTP status codes | Add rate limit headers documentation | Provide working curl examples | Consider API versioning strategy +" +``` + +**Key Points**: +- **--approval-mode yolo**: Required for write mode +- **TASK**: Exhaustive list of what to document +- **EXPECTED**: Specific file name (API.md) + numbered sections + multiple output requirements +- **RULES**: Specification compliance + formatting + comprehensive coverage + +## Example 2: Module Documentation with Template and Standards + +```bash +cd src/services && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p " +PURPOSE: Document service layer modules for team knowledge sharing and onboarding +TASK: Generate CLAUDE.md for each service file covering: module purpose, public API, dependencies, data flow, error handling, testing approach, usage examples +MODE: write +CONTEXT: @{**/*.ts,../models/**/*.ts,../repositories/**/*.ts} Services follow DDD pattern, use dependency injection, integrate with Redis cache and PostgreSQL +EXPECTED: Create CLAUDE.md for: user.service.ts, auth.service.ts, payment.service.ts, notification.service.ts. Each file includes: Purpose, Architecture, Public Methods (with signatures), Dependencies Graph, Error Scenarios, Test Coverage Status, Integration Points, Usage Examples +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/memory/claude-module-unified.txt) | Follow DDD ubiquitous language | Document all public methods | Include sequence diagrams for complex flows | Reference related services | Add TODO sections for future improvements | Maintain consistency across all service docs +" +``` + +**Key Points**: +- **TASK**: Comprehensive documentation coverage per file +- **EXPECTED**: Multiple output files with identical structure +- **RULES**: Template + pattern adherence + diagram requirements + maintenance considerations diff --git a/.claude/skills/prompt-enhancer/SKILL.md b/.claude/skills/prompt-enhancer/SKILL.md new file mode 100644 index 00000000..647d93b9 --- /dev/null +++ b/.claude/skills/prompt-enhancer/SKILL.md @@ -0,0 +1,100 @@ +--- +name: Prompt Enhancer +description: Systematically enhance ambiguous user prompts by combining session memory with codebase analysis. Use when user input is unclear, vague, or lacks technical specificity (e.g., "fix", "improve", "clean up") or affects multiple modules or critical systems. +allowed-tools: Bash, Read, Glob, Grep +--- + +# Prompt Enhancer + +## Overview + +Transforms ambiguous user requests into actionable technical specifications through semantic analysis and session memory integration. + +**Core Capability**: Vague intent β†’ Structured specification + +## Enhancement Process + +### Step 1: Semantic Analysis + +Analyze user input to identify: +- **Intent keywords**: fix, improve, add, refactor, update, migrate +- **Technical scope**: single file vs multi-module +- **Domain context**: auth, payment, security, API, UI, database +- **Implied requirements**: performance, security, testing, documentation + +### Step 2: Memory Analysis + +Extract from conversation history: +- **Technical context**: Previous discussions, decisions, implementations +- **Known patterns**: Identified code patterns, architecture decisions +- **Current state**: What's been built, what's in progress +- **Dependencies**: Related modules, integration points +- **Constraints**: Security requirements, backward compatibility + +### Step 3: Context Integration + +Combine semantic and memory analysis to determine: +- **Precise intent**: Specific technical goal +- **Required actions**: Implementation steps with file references +- **Critical constraints**: Security, compatibility, testing requirements +- **Missing information**: What needs clarification + +## Output Structure + +Every enhanced prompt must follow this format: + +``` +INTENT: [Clear technical goal] +CONTEXT: [Session memory + semantic analysis] +ACTION: [Numbered implementation steps] +ATTENTION: [Critical constraints] +``` + +**Field Descriptions**: + +- **INTENT**: One-sentence technical goal derived from semantic analysis +- **CONTEXT**: Session memory findings + semantic domain analysis +- **ACTION**: Numbered steps with specific file/module references +- **ATTENTION**: Critical constraints, security, compliance, tests + +## Semantic Patterns + +### Intent Translation + +| User Input | Semantic Intent | Focus | +|------------|----------------|-------| +| "fix" + vague target | Debug and resolve | Root cause β†’ preserve behavior | +| "improve" + no metrics | Enhance/optimize | Performance/readability | +| "add" + feature name | Implement feature | Integration + edge cases | +| "refactor" + module | Restructure | Maintain behavior | +| "update" + version | Modernize | Version compatibility | + +### Scope Detection + +**Single-file scope**: +- "fix button", "add validation", "update component" +- Use session memory only + +**Multi-module scope** (>3 modules): +- "add authentication", "refactor payment", "migrate database" +- Analyze dependencies and integration points + +**System-wide scope**: +- "improve performance", "add logging", "update security" +- Consider cross-cutting concerns + +## Key Principles + +1. **Memory First**: Check session memory before assumptions +2. **Semantic Precision**: Extract exact technical intent from vague language +3. **Context Reuse**: Build on previous understanding +4. **Clear Output**: Always structured format +5. **Avoid Duplication**: Reference context, don't repeat + +## Best Practices + +- **Semantic analysis**: Identify domain, scope, and intent keywords +- **Memory integration**: Extract all relevant context from conversation +- **Structured output**: Always use INTENT/CONTEXT/ACTION/ATTENTION format +- **Actionable steps**: Specific files, clear execution order +- **Critical constraints**: Security, compatibility, testing requirements diff --git a/.claude/skills/qwen/SKILL.md b/.claude/skills/qwen/SKILL.md new file mode 100644 index 00000000..37249726 --- /dev/null +++ b/.claude/skills/qwen/SKILL.md @@ -0,0 +1,270 @@ +--- +name: Qwen CLI Tool +description: Code analysis and documentation tool (Gemini fallback). Trigger keywords "use qwen", "qwen analysis", "analyze with qwen". Use when Gemini unavailable or for parallel analysis. Supports read-only analysis (default) and write operations (explicit permission). +allowed-tools: Bash, Read, Glob, Grep +--- + +# Qwen CLI Tool + +## Core Execution + +Qwen executes code analysis and documentation tasks using large context window capabilities. + +**Trigger Keywords**: "use qwen", "qwen analysis", "qwen generate docs", "analyze with qwen" + +**Execution Modes**: +- `analysis` (default): Read-only analysis, auto-execute +- `write`: Create/modify files, requires explicit permission + +**Command Pattern**: +```bash +cd [directory] && ~/.claude/scripts/qwen-wrapper [--approval-mode yolo] -p " +PURPOSE: [goal] +TASK: [specific task] +MODE: [analysis|write] +CONTEXT: @{file/patterns} +EXPECTED: [results] +RULES: [constraints] +" +``` + +## Universal Template Structure + +Every Qwen command should follow this detailed structure for best results: + +```bash +cd [directory] && ~/.claude/scripts/qwen-wrapper [--approval-mode yolo] -p " +PURPOSE: [One clear sentence: what and why] +TASK: [Specific actionable task with scope] +MODE: [analysis|write] +CONTEXT: @{file/patterns} [Previous session context, dependencies, constraints] +EXPECTED: [Deliverable format, file names, coverage requirements] +RULES: [Template reference] | [Specific constraints: standards, patterns, focus areas] +" +``` + +### Template Field Guidelines + +**PURPOSE**: +- One sentence combining goal + reason +- Examples: "Analyze auth system for SOC 2 compliance", "Document payment module for audit" + +**TASK**: +- Break down into numbered sub-tasks for complex operations +- Include specific aspects: "Review authentication flow, session management, audit logging" +- Specify scope boundaries + +**CONTEXT**: +- File patterns: `@{**/*.ts,**/*.test.ts}` +- Business context: "100k users, $2M monthly transactions, PCI DSS scope" +- Tech stack: Versions, frameworks, constraints +- Session memory: "Phase 1 identified 3 high-priority issues" + +**EXPECTED**: +- Numbered deliverables: "1) Compliance report, 2) Remediation roadmap, 3) Evidence collection guide" +- Specific file names: "SECURITY.md", "PAYMENT_MODULE.md", "audit-findings.json" +- Coverage requirements: ">95% coverage", "All SOC 2 controls mapped" +- Output format: "Mermaid diagrams", "Compliance checklist", "Risk matrix" + +**RULES**: +- Template reference: `$(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt)` +- Multiple constraints separated by `|`: "Map to SOC 2 CC6.1 | Include CVE references | Follow NIST 800-63B" +- Specific standards: "OWASP Top 10 2021", "PCI DSS 3.2.1", "GDPR Article 32" +- Thresholds: "CVSS >7.0 as blocker", "p95 <200ms", ">80% cache hit rate" + +## Command Structure + +### Universal Template +Every Qwen command follows this structure: + +```bash +cd [directory] && ~/.claude/scripts/qwen-wrapper [options] -p " +PURPOSE: [clear goal and intent] +TASK: [specific execution task] +MODE: [analysis|write] +CONTEXT: [file references and memory context] +EXPECTED: [clear expected results] +RULES: [template reference and constraints] +" +``` + +## Execution Modes + +### Analysis Mode (Default - Read-Only) +Safe for auto-execution without user confirmation: + +```bash +cd [directory] && ~/.claude/scripts/qwen-wrapper -p " +PURPOSE: [analysis goal] +TASK: [specific analysis task] +MODE: analysis +CONTEXT: @{file/patterns} [session memory] +EXPECTED: [analysis output] +RULES: [constraints] +" +``` + +**When to use**: +- Code exploration and understanding +- Architecture analysis +- Pattern discovery +- Security assessment +- Performance analysis + +### Write Mode (Requires Explicit Permission) +⚠️ Only use when user explicitly requests file creation/modification: + +```bash +cd [directory] && ~/.claude/scripts/qwen-wrapper --approval-mode yolo -p " +PURPOSE: [documentation goal] +TASK: [specific write task] +MODE: write +CONTEXT: @{file/patterns} +EXPECTED: [generated files] +RULES: [constraints] +" +``` + +**Parameter Position**: `--approval-mode yolo` must be placed AFTER `qwen-wrapper`, BEFORE `-p` + +**Write Triggers**: +- User explicitly says "generate documentation" +- User explicitly says "create/modify files" +- User specifies `MODE=write` in prompt + +## File Pattern Reference + +Common patterns for CONTEXT field: + +```bash +@{**/*} # All files +@{src/**/*} # Source files +@{*.ts,*.tsx} # TypeScript files +@{CLAUDE.md,**/*CLAUDE.md} # Documentation +@{src/**/*.test.*} # Test files +``` + +**Complex Pattern Discovery**: +For complex requirements, discover files first: +```bash +# Step 1: Discover with ripgrep or MCP +rg "export.*Component" --files-with-matches --type ts + +# Step 2: Build precise CONTEXT +CONTEXT: @{src/components/Auth.tsx,src/types/auth.d.ts} + +# Step 3: Execute with precise references +``` + +## Template System + +Templates are located in `~/.claude/workflows/cli-templates/prompts/` + +### Available Templates + +**Analysis Templates**: +- `analysis/pattern.txt` - Code pattern analysis +- `analysis/architecture.txt` - System architecture review +- `analysis/security.txt` - Security assessment +- `analysis/quality.txt` - Code quality review + +**Development Templates**: +- `development/feature.txt` - Feature implementation +- `development/refactor.txt` - Refactoring tasks +- `development/testing.txt` - Test generation + +**Memory Templates**: +- `memory/claude-module-unified.txt` - Module documentation + +### Using Templates in RULES Field + +```bash +# Single template +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) | Focus on security + +# Multiple templates +RULES: $(cat template1.txt) $(cat template2.txt) | Enterprise standards + +# No template +RULES: Focus on security patterns, include dependency analysis +``` + +⚠️ **CRITICAL**: Never use escape characters (`\$`, `\"`, `\'`) in CLI commands - breaks command substitution. + +## Context Optimization + +Use `cd [directory] &&` pattern to focus analysis and reduce irrelevant context: + +```bash +# Focused analysis +cd src/auth && ~/.claude/scripts/qwen-wrapper -p " +PURPOSE: Analyze auth architecture +TASK: Review auth system design and patterns +MODE: analysis +CONTEXT: @{**/*} +EXPECTED: Architecture analysis report +RULES: Focus on modularity and security +" +``` + +**When to change directory**: +- Specific directory mentioned β†’ Use `cd directory &&` +- Focused analysis needed β†’ Target specific directory +- Multi-directory scope β†’ Stay in root, use explicit paths + +## Execution Configuration + +### Timeout Allocation (Dynamic) +Based on task complexity: +- **Simple** (analysis, search): 20-40min (1200000-2400000ms) +- **Medium** (refactoring, docs): 40-60min (2400000-3600000ms) +- **Complex** (implementation): 60-120min (3600000-7200000ms) + +Auto-detect from PURPOSE and TASK fields. + +### Permission Framework +- βœ… **Analysis Mode (default)**: Auto-execute without confirmation +- ⚠️ **Write Mode**: Requires explicit user confirmation or MODE=write specification +- πŸ”’ **Write Protection**: Never modify codebase without explicit user instruction + +## Examples + +Production-ready examples organized by scenario type: + +- **[Analysis Examples](analysis-examples.md)** - Compliance-focused analysis with SOC 2 mapping, performance optimization, and technical debt assessment +- **[Write Examples](write-examples.md)** - API documentation with OpenAPI specs and PCI DSS compliance documentation +- **[Advanced Workflows](advanced-workflows.md)** - Security audit β†’ remediation β†’ verification pipeline +- **[Template Examples](template-examples.md)** - Multi-template quality gates for production releases + +Each example follows the Universal Template Structure with compliance and business context focus. + +## Best Practices + +### Analysis Phase +- Use analysis mode for all exploratory work +- Focus on specific directories with `cd` pattern +- Include relevant file patterns in CONTEXT +- Reference session memory for continuity + +### Documentation Phase +- Always use write mode with `--approval-mode yolo` +- Get explicit user confirmation first +- Include source files in CONTEXT +- Follow project documentation standards + +## Error Handling + +**If timeout occurs**: +- Reduce CONTEXT scope +- Use more specific file patterns +- Split into smaller analysis tasks + +**If context too large**: +- Use `cd` to focus on specific directory +- Narrow file patterns +- Analyze in phases + +**If output incomplete**: +- Increase timeout allocation +- Simplify EXPECTED results +- Break into multiple commands diff --git a/.claude/skills/qwen/advanced-workflows.md b/.claude/skills/qwen/advanced-workflows.md new file mode 100644 index 00000000..1fb7719f --- /dev/null +++ b/.claude/skills/qwen/advanced-workflows.md @@ -0,0 +1,53 @@ +# Qwen Advanced Multi-Phase Workflows + +> **πŸ“– Template Structure**: See [Universal Template Structure](SKILL.md#universal-template-structure) in SKILL.md for detailed field guidelines. + +## Security Audit β†’ Remediation β†’ Verification Workflow + +This three-phase workflow demonstrates comprehensive security audit with remediation and verification. + +### Phase 1: Security Analysis + +```bash +cd src && ~/.claude/scripts/qwen-wrapper -p " +PURPOSE: Conduct comprehensive security audit for production hardening +TASK: Analyze security vulnerabilities: SQL injection, XSS, CSRF, authentication bypass, authorization flaws, sensitive data exposure, cryptographic weaknesses, dependency vulnerabilities, configuration issues +MODE: analysis +CONTEXT: @{**/*.ts,**/*.json,!**/node_modules/**,package.json,package-lock.json,.env.example} Web application with 100k users, handles PII and payment data, currently no WAF, uses Express 4.18, Helmet configured, CORS enabled +EXPECTED: Security audit report: 1) Executive Summary (risk score), 2) OWASP Top 10 assessment (mapped findings), 3) Dependency vulnerability scan (CVE list with CVSS), 4) Authentication/Authorization review, 5) Data protection analysis (encryption at rest/transit), 6) Input validation gaps, 7) Configuration hardening checklist, 8) Remediation plan (prioritized by CVSS score), 9) Estimated fix effort per issue +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt) | Map all findings to OWASP Top 10 2021 | Include CVE references for dependencies | Check for hardcoded secrets (regex patterns) | Validate JWT implementation | Review CORS policy | Assess rate limiting coverage | Verify HTTPS enforcement | Check for information disclosure | Test for broken access control +" +``` + +### Phase 2: Documentation Generation (after remediation) + +```bash +~/.claude/scripts/qwen-wrapper --approval-mode yolo -p " +PURPOSE: Document security controls for audit trail and team reference +TASK: Create security documentation based on Phase 1 findings and remediation actions +MODE: write +CONTEXT: Phase 1 audit identified: 3 high-priority issues (fixed), 7 medium issues (fixed), 12 low issues (backlog), implemented WAF with ModSecurity, added rate limiting, upgraded dependencies, enabled security headers +EXPECTED: Create SECURITY.md with sections: 1) Security Architecture Overview, 2) Threat Model, 3) Security Controls (preventive/detective/corrective), 4) Authentication & Authorization, 5) Data Protection, 6) API Security, 7) Dependency Management, 8) Incident Response Plan, 9) Security Checklist for Developers, 10) Audit Log. Include before/after comparisons for fixed issues. +RULES: Reference CWE IDs for all controls | Include mitigation strategies | Document security testing procedures | Add security review checklist for PRs | Reference OWASP ASVS controls | Include incident response runbook | Add security metrics for monitoring | Create security champion rotation schedule +" +``` + +### Phase 3: Verification (after documentation) + +```bash +cd src && ~/.claude/scripts/qwen-wrapper -p " +PURPOSE: Verify security remediation completeness and control effectiveness +TASK: Review implemented security fixes against Phase 1 findings, validate controls are working as documented in Phase 2, identify any gaps or regressions +MODE: analysis +CONTEXT: @{**/*.ts,SECURITY.md,tests/security/**/*.test.ts} All high and medium issues marked as fixed, 15 new security tests added, dependency updates applied, WAF rules configured +EXPECTED: Verification report: 1) Fix validation (each Phase 1 issue reviewed), 2) Control effectiveness assessment, 3) Test coverage for security controls, 4) Regression check, 5) Documentation accuracy review, 6) Remaining risks and acceptance criteria, 7) Go/No-Go recommendation for production deployment +RULES: Validate each fix has corresponding test | Verify security headers in HTTP responses | Check WAF rules are active | Confirm rate limiting is enforced | Validate dependency versions match recommendations | Review security test coverage >80% | Confirm incident response contacts are current +" +``` + +### Key Points + +- **Three-phase workflow**: Audit β†’ Document β†’ Verify +- **Context continuity**: Each phase references previous results +- **Comprehensive coverage**: From findings to fixes to verification +- **Production readiness**: Includes go/no-go decision diff --git a/.claude/skills/qwen/analysis-examples.md b/.claude/skills/qwen/analysis-examples.md new file mode 100644 index 00000000..e2390f9f --- /dev/null +++ b/.claude/skills/qwen/analysis-examples.md @@ -0,0 +1,61 @@ +# Qwen Analysis Mode Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](SKILL.md#universal-template-structure) in SKILL.md for detailed field guidelines. + +All examples demonstrate read-only analysis mode with compliance-focused, security-aware prompt writing. + +## Example 1: Architecture Analysis with Business Context + +```bash +cd src/auth && ~/.claude/scripts/qwen-wrapper -p " +PURPOSE: Analyze authentication system to support SOC 2 compliance audit +TASK: Review authentication flow, authorization logic, session management, token handling, password policies, audit logging +MODE: analysis +CONTEXT: @{**/*.ts,**/*.json,!**/*.test.ts} System serves 50k daily active users, uses JWT with Redis session store, bcrypt for passwords +EXPECTED: Compliance-ready analysis including: 1) Authentication flow diagram, 2) Security control mapping (SOC 2 CC6.1), 3) Vulnerability assessment with CVSS scores, 4) Policy compliance report, 5) Audit logging coverage, 6) Remediation roadmap with deadlines +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Map to SOC 2 Trust Service Criteria | Follow OWASP ASVS v4.0 | Include penetration test recommendations | Verify GDPR data handling | Document all authentication events for audit trail +" +``` + +**Key Points**: +- **PURPOSE**: Include business driver (SOC 2 compliance) +- **CONTEXT**: Business metrics (50k DAU) + tech stack details +- **EXPECTED**: Numbered, specific deliverables with compliance mapping +- **RULES**: Multiple compliance frameworks + specific versions + +## Example 2: Performance Optimization with Metrics + +```bash +~/.claude/scripts/qwen-wrapper -p " +PURPOSE: Identify API performance bottlenecks to meet SLA requirements (<200ms p95) +TASK: Analyze request lifecycle: routing β†’ middleware β†’ controller β†’ service β†’ repository β†’ database, measure each layer, identify slow queries, evaluate caching strategy, assess serialization overhead +MODE: analysis +CONTEXT: @{src/api/**/*.ts,src/services/**/*.ts,src/repositories/**/*.ts,src/middleware/**/*.ts} Current p95: 850ms, p99: 2.1s, 10k req/min peak, PostgreSQL 14, Redis 7, Node 20 LTS +EXPECTED: Performance optimization report: 1) Latency breakdown by layer (with percentiles), 2) Top 10 slow queries with execution plans, 3) N+1 query identification, 4) Caching opportunity analysis (hit rate projections), 5) Database index recommendations, 6) Implementation priority matrix (impact vs effort), 7) Expected performance gains per optimization +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) | Focus on p95 and p99 latency | Identify serialization bottlenecks | Evaluate connection pooling | Consider Redis cache warming | Analyze query plan costs | Include monitoring recommendations (APM integration) | Prioritize quick wins vs long-term improvements +" +``` + +**Key Points**: +- **TASK**: Detailed layer-by-layer analysis with measurement +- **CONTEXT**: Current metrics (p95, p99) + target SLA + tech versions +- **EXPECTED**: Quantifiable outputs (top 10, hit rates, gains) +- **RULES**: Performance-focused constraints with monitoring integration + +## Example 3: Code Quality Assessment with Technical Debt + +```bash +cd src && ~/.claude/scripts/qwen-wrapper -p " +PURPOSE: Assess technical debt to plan refactoring sprint +TASK: Analyze code quality metrics: cyclomatic complexity, code duplication, test coverage, type safety, documentation completeness, pattern consistency, dependency coupling +MODE: analysis +CONTEXT: @{**/*.ts,!**/node_modules/**,!**/*.test.ts,tsconfig.json,jest.config.js,CLAUDE.md} Codebase: 80k LOC, 12 months old, 6 developers, TypeScript 5.2, strict mode enabled, current test coverage 45% +EXPECTED: Technical debt assessment: 1) Complexity hotspots (files >10 cyclomatic complexity), 2) Duplication report (>5% threshold), 3) Coverage gaps by module, 4) Type safety violations, 5) Documentation score, 6) Dependency coupling matrix, 7) Refactoring backlog prioritized by maintainability impact, 8) Sprint plan (2-week capacity) with effort estimates in story points +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/quality.txt) | Use standard complexity thresholds (>10 high, >20 critical) | Identify copy-paste code blocks | Flag any 'any' types | Check JSDoc coverage for public APIs | Detect circular dependencies | Calculate technical debt in developer-days | Recommend ESLint rule additions | Include CI/CD quality gate suggestions +" +``` + +**Key Points**: +- **CONTEXT**: Team context (6 devs, 12 months) + current metrics (45% coverage) +- **EXPECTED**: Sprint-ready backlog with effort estimates (story points) +- **RULES**: Specific thresholds + quantifiable debt + tooling recommendations diff --git a/.claude/skills/qwen/template-examples.md b/.claude/skills/qwen/template-examples.md new file mode 100644 index 00000000..b8411dd8 --- /dev/null +++ b/.claude/skills/qwen/template-examples.md @@ -0,0 +1,45 @@ +# Qwen Template Usage Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](SKILL.md#universal-template-structure) in SKILL.md for detailed field guidelines. + +## Multi-Template Quality & Security Review + +This example demonstrates combining multiple templates for comprehensive pre-release audit. + +```bash +~/.claude/scripts/qwen-wrapper -p " +PURPOSE: Pre-release quality gate combining security, performance, and maintainability checks +TASK: Execute comprehensive review across: security vulnerabilities, code quality metrics, performance bottlenecks, pattern consistency, test coverage, documentation completeness +MODE: analysis +CONTEXT: @{src/**/*,!**/node_modules/**,tests/**/*,docs/**/*,CLAUDE.md,package.json,tsconfig.json} Release v3.0 scheduled in 1 week, 6-month development cycle, 10 developers, 120k LOC added/changed, current test coverage 72%, no security audit since v2.5 (6 months ago) +EXPECTED: Consolidated release readiness report: 1) Executive Summary (Go/No-Go with rationale), 2) Security Assessment (OWASP Top 10 coverage, dependency CVEs, CVSS scores), 3) Performance Benchmarks (vs v2.5 baseline, latency p50/p95/p99), 4) Code Quality Metrics (complexity hotspots, duplication %, type safety score), 5) Test Coverage Analysis (per module, gaps in critical paths), 6) Documentation Review (API docs, runbooks, migration guides), 7) Breaking Changes Assessment (semver compliance), 8) Rollback Plan, 9) Post-release Monitoring Strategy, 10) Release Blocker Issues (prioritized action items) +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/quality.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) | Block release if any CVSS >7.0 unpatched | Require >70% test coverage for new code | Flag complexity >15 as blocker | Verify all breaking changes are documented | Check migration guide completeness | Validate rollback tested in staging | Ensure monitoring dashboards updated | Confirm on-call runbooks current | Assess blast radius for failures | Include load test results vs capacity plan +" +``` + +## Key Points + +- **Three templates combined**: Security + Quality + Pattern analysis +- **Release context**: Timeline (1 week), team size, scope (120k LOC) +- **Decision-oriented**: Go/No-Go recommendation with criteria +- **RULES as quality gate**: Specific blocking criteria + verification steps + +## Template Combinations + +### Security + Architecture + Compliance + +```bash +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Map to SOC 2 controls | Include threat modeling | Document compliance evidence +``` + +### Quality + Pattern + Maintainability + +```bash +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/quality.txt) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) | Calculate technical debt | Assess refactoring ROI | Include maintainability index +``` + +### Migration Planning Template + +```bash +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Zero-downtime requirement | Feature flag strategy | Rollback plan | Performance comparison | Risk assessment matrix +``` diff --git a/.claude/skills/qwen/write-examples.md b/.claude/skills/qwen/write-examples.md new file mode 100644 index 00000000..fa95bdc8 --- /dev/null +++ b/.claude/skills/qwen/write-examples.md @@ -0,0 +1,41 @@ +# Qwen Write Mode Examples + +> **πŸ“– Template Structure**: See [Universal Template Structure](SKILL.md#universal-template-structure) in SKILL.md for detailed field guidelines. + +All examples demonstrate write mode with compliance-focused documentation generation. + +## Example 1: API Documentation with OpenAPI Spec + +```bash +~/.claude/scripts/qwen-wrapper --approval-mode yolo -p " +PURPOSE: Generate production-ready API documentation for partner integration +TASK: Document all public API endpoints: authentication flow, user management, data access, webhooks, including request/response schemas, error codes, rate limits, pagination, versioning +MODE: write +CONTEXT: @{src/api/**/*.ts,src/controllers/**/*.ts,src/validators/**/*.ts,src/middleware/auth.ts,src/middleware/rateLimit.ts} API v2.1, OAuth 2.0 + API keys, rate limit 1000/hour per key, pagination max 100 items, webhook retry 3 times with exponential backoff +EXPECTED: Generate two files: 1) API_REFERENCE.md with sections (Authentication, Endpoints by resource, Webhooks, Error Handling, Rate Limits, Pagination, Versioning, SDKs), include curl/JavaScript/Python examples for each endpoint; 2) openapi.yaml (OpenAPI 3.1 spec) for automated tooling +RULES: Follow OpenAPI 3.1 specification exactly | Use markdown tables for parameter documentation | Include all HTTP status codes with examples | Document rate limit headers (X-RateLimit-*) | Provide webhook signature verification examples | Add troubleshooting section for common errors | Reference RFC 6749 for OAuth | Include Postman collection generation instructions +" +``` + +**Key Points**: +- **--approval-mode yolo**: Required for write mode +- **EXPECTED**: Two output files with specific formats (MD + YAML) +- **RULES**: Specification compliance + examples in multiple languages + troubleshooting + +## Example 2: Module Documentation with Architecture Diagrams + +```bash +cd src/payment && ~/.claude/scripts/qwen-wrapper --approval-mode yolo -p " +PURPOSE: Document payment module for PCI DSS compliance audit and team onboarding +TASK: Create comprehensive documentation covering: payment flow, provider integration (Stripe, PayPal), retry logic, idempotency, reconciliation, refund handling, webhook processing, failure scenarios +MODE: write +CONTEXT: @{**/*.ts,../models/**/*.ts,../services/**/*.ts,../../config/payment.json} Processes $2M monthly, supports 3 providers, handles 50k transactions/month, uses Stripe SDK v11, implements at-least-once delivery, stores payment tokens in HashiCorp Vault +EXPECTED: Create PAYMENT_MODULE.md with sections: 1) Executive Summary (purpose, metrics), 2) Architecture Overview (with Mermaid diagram), 3) Payment Flow (sequence diagram for happy path), 4) Provider Integration (per-provider details), 5) Idempotency Strategy, 6) Error Handling & Retries, 7) Reconciliation Process, 8) Security & PCI Compliance, 9) Monitoring & Alerting, 10) Runbooks (common operations), 11) Testing Strategy, 12) API Reference. Include code examples for critical paths. +RULES: $(cat ~/.claude/workflows/cli-templates/prompts/memory/claude-module-unified.txt) | Include PCI DSS scope documentation | Document all failure scenarios with recovery procedures | Add Mermaid sequence diagrams for complex flows | Reference Stripe best practices | Include rate limiting for provider APIs | Document vault token lifecycle | Add metric definitions for monitoring | Create decision tree for refund handling | Include disaster recovery procedures +" +``` + +**Key Points**: +- **CONTEXT**: Business metrics ($2M, 50k txns) + security tooling (Vault) +- **EXPECTED**: Single comprehensive file with 12 sections + diagrams + code +- **RULES**: Compliance focus + diagrams + operational runbooks diff --git a/CLAUDE.md b/CLAUDE.md index 2a98f344..67f1cf3e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,8 +6,6 @@ This document defines project-specific coding standards and development principl ### CLI Tool Context Protocols For all CLI tool usage, command syntax, and integration guidelines: - **Tool Control Configuration**: @~/.claude/workflows/tool-control.yaml - Controls CLI tool availability for all commands and agent executions (if disabled, use other enabled CLI tools or Claude's own capabilities) -- **Intelligent Context Strategy**: @~/.claude/workflows/intelligent-tools-strategy.md -- **Context Search Commands**: @~/.claude/workflows/context-search-strategy.md - **MCP Tool Strategy**: @~/.claude/workflows/mcp-tool-strategy.md **Context Requirements**: diff --git a/skills.md b/skills.md new file mode 100644 index 00000000..43ef0fb9 --- /dev/null +++ b/skills.md @@ -0,0 +1,598 @@ +# Agent Skills + +> Create, manage, and share Skills to extend Claude's capabilities in Claude Code. + +This guide shows you how to create, use, and manage Agent Skills in Claude Code. Skills are modular capabilities that extend Claude's functionality through organized folders containing instructions, scripts, and resources. + +## Prerequisites + +* Claude Code version 1.0 or later +* Basic familiarity with [Claude Code](/en/docs/claude-code/quickstart) + +## What are Agent Skills? + +Agent Skills package expertise into discoverable capabilities. Each Skill consists of a `SKILL.md` file with instructions that Claude reads when relevant, plus optional supporting files like scripts and templates. + +**How Skills are invoked**: Skills are **model-invoked**β€”Claude autonomously decides when to use them based on your request and the Skill's description. This is different from slash commands, which are **user-invoked** (you explicitly type `/command` to trigger them). + +**Benefits**: + +* Extend Claude's capabilities for your specific workflows +* Share expertise across your team via git +* Reduce repetitive prompting +* Compose multiple Skills for complex tasks + +Learn more in the [Agent Skills overview](/en/docs/agents-and-tools/agent-skills/overview). + + + For a deep dive into the architecture and real-world applications of Agent Skills, read our engineering blog: [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills). + + +## Create a Skill + +Skills are stored as directories containing a `SKILL.md` file. + +### Personal Skills + +Personal Skills are available across all your projects. Store them in `~/.claude/skills/`: + +```bash theme={null} +mkdir -p ~/.claude/skills/my-skill-name +``` + +**Use personal Skills for**: + +* Your individual workflows and preferences +* Experimental Skills you're developing +* Personal productivity tools + +### Project Skills + +Project Skills are shared with your team. Store them in `.claude/skills/` within your project: + +```bash theme={null} +mkdir -p .claude/skills/my-skill-name +``` + +**Use project Skills for**: + +* Team workflows and conventions +* Project-specific expertise +* Shared utilities and scripts + +Project Skills are checked into git and automatically available to team members. + +### Plugin Skills + +Skills can also come from [Claude Code plugins](/en/docs/claude-code/plugins). Plugins may bundle Skills that are automatically available when the plugin is installed. These Skills work the same way as personal and project Skills. + +## Write SKILL.md + +Create a `SKILL.md` file with YAML frontmatter and Markdown content: + +```yaml theme={null} +--- +name: Your Skill Name +description: Brief description of what this Skill does and when to use it +--- + +# Your Skill Name + +## Instructions +Provide clear, step-by-step guidance for Claude. + +## Examples +Show concrete examples of using this Skill. +``` + +The `description` field is critical for Claude to discover when to use your Skill. It should include both what the Skill does and when Claude should use it. + +See the [best practices guide](/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance. + +## Add supporting files + +Create additional files alongside SKILL.md: + +``` +my-skill/ +β”œβ”€β”€ SKILL.md (required) +β”œβ”€β”€ reference.md (optional documentation) +β”œβ”€β”€ examples.md (optional examples) +β”œβ”€β”€ scripts/ +β”‚ └── helper.py (optional utility) +└── templates/ + └── template.txt (optional template) +``` + +Reference these files from SKILL.md: + +````markdown theme={null} +For advanced usage, see [reference.md](reference.md). + +Run the helper script: +```bash +python scripts/helper.py input.txt +``` +```` + +Claude reads these files only when needed, using progressive disclosure to manage context efficiently. + +## Restrict tool access with allowed-tools + +Use the `allowed-tools` frontmatter field to limit which tools Claude can use when a Skill is active: + +```yaml theme={null} +--- +name: Safe File Reader +description: Read files without making changes. Use when you need read-only file access. +allowed-tools: Read, Grep, Glob +--- + +# Safe File Reader + +This Skill provides read-only file access. + +## Instructions +1. Use Read to view file contents +2. Use Grep to search within files +3. Use Glob to find files by pattern +``` + +When this Skill is active, Claude can only use the specified tools (Read, Grep, Glob) without needing to ask for permission. This is useful for: + +* Read-only Skills that shouldn't modify files +* Skills with limited scope (e.g., only data analysis, no file writing) +* Security-sensitive workflows where you want to restrict capabilities + +If `allowed-tools` is not specified, Claude will ask for permission to use tools as normal, following the standard permission model. + + + `allowed-tools` is only supported for Skills in Claude Code. + + +## View available Skills + +Skills are automatically discovered by Claude from three sources: + +* Personal Skills: `~/.claude/skills/` +* Project Skills: `.claude/skills/` +* Plugin Skills: bundled with installed plugins + +**To view all available Skills**, ask Claude directly: + +``` +What Skills are available? +``` + +or + +``` +List all available Skills +``` + +This will show all Skills from all sources, including plugin Skills. + +**To inspect a specific Skill**, you can also check the filesystem: + +```bash theme={null} +# List personal Skills +ls ~/.claude/skills/ + +# List project Skills (if in a project directory) +ls .claude/skills/ + +# View a specific Skill's content +cat ~/.claude/skills/my-skill/SKILL.md +``` + +## Test a Skill + +After creating a Skill, test it by asking questions that match your description. + +**Example**: If your description mentions "PDF files": + +``` +Can you help me extract text from this PDF? +``` + +Claude autonomously decides to use your Skill if it matches the requestβ€”you don't need to explicitly invoke it. The Skill activates automatically based on the context of your question. + +## Debug a Skill + +If Claude doesn't use your Skill, check these common issues: + +### Make description specific + +**Too vague**: + +```yaml theme={null} +description: Helps with documents +``` + +**Specific**: + +```yaml theme={null} +description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. +``` + +Include both what the Skill does and when to use it in the description. + +### Verify file path + +**Personal Skills**: `~/.claude/skills/skill-name/SKILL.md` +**Project Skills**: `.claude/skills/skill-name/SKILL.md` + +Check the file exists: + +```bash theme={null} +# Personal +ls ~/.claude/skills/my-skill/SKILL.md + +# Project +ls .claude/skills/my-skill/SKILL.md +``` + +### Check YAML syntax + +Invalid YAML prevents the Skill from loading. Verify the frontmatter: + +```bash theme={null} +cat SKILL.md | head -n 10 +``` + +Ensure: + +* Opening `---` on line 1 +* Closing `---` before Markdown content +* Valid YAML syntax (no tabs, correct indentation) + +### View errors + +Run Claude Code with debug mode to see Skill loading errors: + +```bash theme={null} +claude --debug +``` + +## Share Skills with your team + +**Recommended approach**: Distribute Skills through [plugins](/en/docs/claude-code/plugins). + +To share Skills via plugin: + +1. Create a plugin with Skills in the `skills/` directory +2. Add the plugin to a marketplace +3. Team members install the plugin + +For complete instructions, see [Add Skills to your plugin](/en/docs/claude-code/plugins#add-skills-to-your-plugin). + +You can also share Skills directly through project repositories: + +### Step 1: Add Skill to your project + +Create a project Skill: + +```bash theme={null} +mkdir -p .claude/skills/team-skill +# Create SKILL.md +``` + +### Step 2: Commit to git + +```bash theme={null} +git add .claude/skills/ +git commit -m "Add team Skill for PDF processing" +git push +``` + +### Step 3: Team members get Skills automatically + +When team members pull the latest changes, Skills are immediately available: + +```bash theme={null} +git pull +claude # Skills are now available +``` + +## Update a Skill + +Edit SKILL.md directly: + +```bash theme={null} +# Personal Skill +code ~/.claude/skills/my-skill/SKILL.md + +# Project Skill +code .claude/skills/my-skill/SKILL.md +``` + +Changes take effect the next time you start Claude Code. If Claude Code is already running, restart it to load the updates. + +## Remove a Skill + +Delete the Skill directory: + +```bash theme={null} +# Personal +rm -rf ~/.claude/skills/my-skill + +# Project +rm -rf .claude/skills/my-skill +git commit -m "Remove unused Skill" +``` + +## Best practices + +### Keep Skills focused + +One Skill should address one capability: + +**Focused**: + +* "PDF form filling" +* "Excel data analysis" +* "Git commit messages" + +**Too broad**: + +* "Document processing" (split into separate Skills) +* "Data tools" (split by data type or operation) + +### Write clear descriptions + +Help Claude discover when to use Skills by including specific triggers in your description: + +**Clear**: + +```yaml theme={null} +description: Analyze Excel spreadsheets, create pivot tables, and generate charts. Use when working with Excel files, spreadsheets, or analyzing tabular data in .xlsx format. +``` + +**Vague**: + +```yaml theme={null} +description: For files +``` + +### Test with your team + +Have teammates use Skills and provide feedback: + +* Does the Skill activate when expected? +* Are the instructions clear? +* Are there missing examples or edge cases? + +### Document Skill versions + +You can document Skill versions in your SKILL.md content to track changes over time. Add a version history section: + +```markdown theme={null} +# My Skill + +## Version History +- v2.0.0 (2025-10-01): Breaking changes to API +- v1.1.0 (2025-09-15): Added new features +- v1.0.0 (2025-09-01): Initial release +``` + +This helps team members understand what changed between versions. + +## Troubleshooting + +### Claude doesn't use my Skill + +**Symptom**: You ask a relevant question but Claude doesn't use your Skill. + +**Check**: Is the description specific enough? + +Vague descriptions make discovery difficult. Include both what the Skill does and when to use it, with key terms users would mention. + +**Too generic**: + +```yaml theme={null} +description: Helps with data +``` + +**Specific**: + +```yaml theme={null} +description: Analyze Excel spreadsheets, generate pivot tables, create charts. Use when working with Excel files, spreadsheets, or .xlsx files. +``` + +**Check**: Is the YAML valid? + +Run validation to check for syntax errors: + +```bash theme={null} +# View frontmatter +cat .claude/skills/my-skill/SKILL.md | head -n 15 + +# Check for common issues +# - Missing opening or closing --- +# - Tabs instead of spaces +# - Unquoted strings with special characters +``` + +**Check**: Is the Skill in the correct location? + +```bash theme={null} +# Personal Skills +ls ~/.claude/skills/*/SKILL.md + +# Project Skills +ls .claude/skills/*/SKILL.md +``` + +### Skill has errors + +**Symptom**: The Skill loads but doesn't work correctly. + +**Check**: Are dependencies available? + +Claude will automatically install required dependencies (or ask for permission to install them) when it needs them. + +**Check**: Do scripts have execute permissions? + +```bash theme={null} +chmod +x .claude/skills/my-skill/scripts/*.py +``` + +**Check**: Are file paths correct? + +Use forward slashes (Unix style) in all paths: + +**Correct**: `scripts/helper.py` +**Wrong**: `scripts\helper.py` (Windows style) + +### Multiple Skills conflict + +**Symptom**: Claude uses the wrong Skill or seems confused between similar Skills. + +**Be specific in descriptions**: Help Claude choose the right Skill by using distinct trigger terms in your descriptions. + +Instead of: + +```yaml theme={null} +# Skill 1 +description: For data analysis + +# Skill 2 +description: For analyzing data +``` + +Use: + +```yaml theme={null} +# Skill 1 +description: Analyze sales data in Excel files and CRM exports. Use for sales reports, pipeline analysis, and revenue tracking. + +# Skill 2 +description: Analyze log files and system metrics data. Use for performance monitoring, debugging, and system diagnostics. +``` + +## Examples + +### Simple Skill (single file) + +``` +commit-helper/ +└── SKILL.md +``` + +```yaml theme={null} +--- +name: Generating Commit Messages +description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes. +--- + +# Generating Commit Messages + +## Instructions + +1. Run `git diff --staged` to see changes +2. I'll suggest a commit message with: + - Summary under 50 characters + - Detailed description + - Affected components + +## Best practices + +- Use present tense +- Explain what and why, not how +``` + +### Skill with tool permissions + +``` +code-reviewer/ +└── SKILL.md +``` + +```yaml theme={null} +--- +name: Code Reviewer +description: Review code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality. +allowed-tools: Read, Grep, Glob +--- + +# Code Reviewer + +## Review checklist + +1. Code organization and structure +2. Error handling +3. Performance considerations +4. Security concerns +5. Test coverage + +## Instructions + +1. Read the target files using Read tool +2. Search for patterns using Grep +3. Find related files using Glob +4. Provide detailed feedback on code quality +``` + +### Multi-file Skill + +``` +pdf-processing/ +β”œβ”€β”€ SKILL.md +β”œβ”€β”€ FORMS.md +β”œβ”€β”€ REFERENCE.md +└── scripts/ + β”œβ”€β”€ fill_form.py + └── validate.py +``` + +**SKILL.md**: + +````yaml theme={null} +--- +name: PDF Processing +description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages. +--- + +# PDF Processing + +## Quick start + +Extract text: +```python +import pdfplumber +with pdfplumber.open("doc.pdf") as pdf: + text = pdf.pages[0].extract_text() +``` + +For form filling, see [FORMS.md](FORMS.md). +For detailed API reference, see [REFERENCE.md](REFERENCE.md). + +## Requirements + +Packages must be installed in your environment: +```bash +pip install pypdf pdfplumber +``` +```` + + + List required packages in the description. Packages must be installed in your environment before Claude can use them. + + +Claude loads additional files only when needed. + +## Next steps + + + + Write Skills that Claude can use effectively + + + + Learn how Skills work across Claude products + + + + Create your first Skill + +