diff --git a/.ai-context/ACTIVE_TASKS.md b/.ai-context/ACTIVE_TASKS.md.example similarity index 66% rename from .ai-context/ACTIVE_TASKS.md rename to .ai-context/ACTIVE_TASKS.md.example index 35debe7..822838e 100644 --- a/.ai-context/ACTIVE_TASKS.md +++ b/.ai-context/ACTIVE_TASKS.md.example @@ -13,10 +13,9 @@ None - Template is complete and production-ready - ✅ Examples documented - ✅ Project renamed to python-modern-template - ✅ Documentation created -- ✅ Emojis removed ## Pending User Actions -1. Rename root directory from `leadership-blog-generator` to `python-modern-template` -2. Create GitHub repository under Atyantik organization -3. Push to GitHub +1. Review and update based on your current work +2. Track your active development tasks +3. Use ai-start-task and ai-finish-task for session management diff --git a/.ai-context/CONVENTIONS.md b/.ai-context/CONVENTIONS.md.example similarity index 100% rename from .ai-context/CONVENTIONS.md rename to .ai-context/CONVENTIONS.md.example diff --git a/.ai-context/LAST_SESSION_SUMMARY.md b/.ai-context/LAST_SESSION_SUMMARY.md deleted file mode 100644 index 5f410a4..0000000 --- a/.ai-context/LAST_SESSION_SUMMARY.md +++ /dev/null @@ -1,48 +0,0 @@ -# Last Session Summary - -> **Auto-updated by AI agents**: This file contains a summary of the most recent AI session - -## Session Information - -**Session ID**: 20251105062211 -**Task**: Add mandatory documentation-first approach for AI agents - prioritize MCP tools, latest docs, and tutorials before implementation to avoid over-engineering -**Date**: 2025-11-05 06:36:00 -**Status**: ✅ Completed - -# Task Summary: Add mandatory documentation-first approach for AI agents - prioritize MCP tools, latest docs, and tutorials before implementation to avoid over-engineering - -**Session ID**: 20251105062211 -**Created**: 2025-11-05 06:36:00 -**Status**: ✅ Completed - ---- - -## What Was Done - -Added mandatory documentation-first approach for all AI agents. Created comprehensive guidelines (AI_DOCS/documentation-first-approach.md) with MCP tools, WebFetch, and WebSearch workflows. Updated all AI tool configs (CLAUDE.md, AGENTS.md, .gemini, .github) and templates. Prevents over-engineering by requiring documentation research before implementation. All quality checks pass (200 tests, 86% coverage). - ---- - -## Decisions Made - -- No major decisions recorded - ---- - -## Files Changed - -- `validate_ai_docs_sync.py` - ---- - -## Notes - -[Session complete] - - ---- - -**This file is automatically updated by the last AI agent to complete a task.** -**Next AI agent: Read this file first to understand recent work!** - -**Last Updated**: 2025-11-05 06:36:00 diff --git a/.ai-context/LAST_SESSION_SUMMARY.md.example b/.ai-context/LAST_SESSION_SUMMARY.md.example new file mode 100644 index 0000000..7d616c8 --- /dev/null +++ b/.ai-context/LAST_SESSION_SUMMARY.md.example @@ -0,0 +1,48 @@ +# Last Session Summary + +> **Auto-updated by AI agents**: This file contains a summary of the most recent AI session + +## Session Information + +**Session ID**: 20251105XXXXXX +**Task**: Example task description +**Date**: 2025-11-05 XX:XX:XX +**Status**: ✅ Completed + +# Task Summary: Example task + +**Session ID**: 20251105XXXXXX +**Created**: 2025-11-05 XX:XX:XX +**Status**: ✅ Completed + +--- + +## What Was Done + +Brief description of what was accomplished in the session. + +--- + +## Decisions Made + +- Any important decisions made during the session + +--- + +## Files Changed + +- `file1.py` +- `file2.py` + +--- + +## Notes + +Additional notes or context for future sessions. + +--- + +**This file is automatically updated by the last AI agent to complete a task.** +**Next AI agent: Read this file first to understand recent work!** + +**Last Updated**: 2025-11-05 XX:XX:XX diff --git a/.ai-context/PLAN-task-specific-checklists-improvement.md b/.ai-context/PLAN-task-specific-checklists-improvement.md deleted file mode 100644 index a19c3f4..0000000 --- a/.ai-context/PLAN-task-specific-checklists-improvement.md +++ /dev/null @@ -1,1597 +0,0 @@ -# Execution Plan: Task-Specific Checklists with Dynamic Editing - -**Status**: Draft for Review -**Created**: 2025-11-03 -**Author**: AI Analysis based on user feedback - ---- - -## Problem Statement - -### Current Limitations - -1. **Generic Plans**: All tasks get the same hardcoded 17-item TDD checklist - - Documentation tasks include "Write tests" (not applicable) - - Simple bugs include all 4 phases (overkill) - - Complex features lack specific customization - -2. **No Plan Editing**: Once `ai-start-task` creates a plan: - - Cannot add task-specific steps - - Cannot remove irrelevant steps - - Cannot update descriptions as understanding evolves - - Cannot adapt based on discoveries during work - -3. **No Task Type Differentiation**: - - Task types (feature, bugfix, docs, refactor) exist but unused - - All get identical checklist regardless of type - - Missed opportunity for specialized templates - -4. **Value Gap**: - - Plans become obsolete quickly - - Real work deviates from generic template - - Mechanical checkbox completion without real tracking value - - AI agents can't customize to actual task needs - -### User's Core Observation - -> "After creating plan, there is no way to update the description or the checklist... which then does not add any value!" - -This is correct. The system needs dynamic plan management, not static templates. - ---- - -## Proposed Solution: Dynamic Task-Specific Plans - -### Core Improvements - -1. **Task-Specific Templates** - Different base templates per task type -2. **Dynamic Plan Editing** - New commands to modify plans during work -3. **AI-Driven Customization** - AI agents can adapt plans intelligently -4. **Plan Validation** - Ensure plans match actual work completed - ---- - -## Detailed Design - -### 1. Task-Specific Templates - -#### Current: One Generic Template -```python -def get_plan_template(session_id, task_name, task_type): - # Always returns same 17-item TDD template - # Ignores task_type parameter -``` - -#### Proposed: Type-Specific Templates - -**Template Structure**: -```python -TASK_TEMPLATES = { - "feature": { - "phases": [ - "Research & Design", - "Write Tests (TDD)", - "Implementation", - "Quality Checks", - "Documentation" - ], - "base_items": [...], # Feature-specific checklist - "optional_sections": ["Performance Testing", "Integration Tests"] - }, - - "bugfix": { - "phases": [ - "Reproduce Bug", - "Write Regression Test", - "Fix Implementation", - "Verify Fix", - "Quality Checks" - ], - "base_items": [...], # Bugfix-specific - "optional_sections": ["Root Cause Analysis"] - }, - - "docs": { - "phases": [ - "Review Current Docs", - "Update Documentation", - "Verify Examples", - "Quality Checks" - ], - "base_items": [...], # No testing phase - "optional_sections": ["Add Diagrams", "Update README"] - }, - - "refactor": { - "phases": [ - "Ensure Test Coverage", - "Refactor Code", - "Verify Tests Pass", - "Quality Checks" - ], - "base_items": [...], # Refactor-specific - "optional_sections": ["Performance Benchmarks"] - } -} -``` - -**Benefits**: -- Each task type gets relevant checklist -- No irrelevant items (docs tasks won't have "Write tests") -- Better initial plan that matches task type - -### 2. Extended Plan Management (Enhanced `ai-update-plan`) - -#### Approach: Extend Existing Command - -**Decision**: Extend `ai-update-plan` rather than create separate `ai-edit-plan` command. - -**Benefits**: -- Single command for all plan operations -- No new command to learn -- Natural evolution of existing tool -- Maintains workflow continuity - -**Backward Compatibility**: -- All existing functionality preserved -- Old behavior: `ai-update-plan "item"` checks/unchecks (UNCHANGED) -- New behavior: Additional flags for editing operations -- If no editing flags, uses original checkbox toggle behavior - -#### Enhanced `ai-update-plan` Capabilities - -**Existing Functionality (Preserved)**: -```bash -# Check/uncheck items (EXISTING - unchanged) -uv run ai-update-plan "Write test file(s)" -uv run ai-update-plan "Run tests" --uncheck -uv run ai-update-plan --show -``` - -**New Editing Functionality (Added)**: -```bash -# Add new checklist items -uv run ai-update-plan --add "Benchmark memory usage" -uv run ai-update-plan --add "Setup test database" --phase="Phase 1" - -# Remove items -uv run ai-update-plan --remove "Update README" - -# Rename/update item descriptions -uv run ai-update-plan --rename "Run tests" --to "Run tests with verbose output" - -# Add custom phase -uv run ai-update-plan --add-phase "Deployment Preparation" - -# Add note to specific section -uv run ai-update-plan --add-note "Database migration required" --section="Risks" - -# Interactive mode for complex edits -uv run ai-update-plan --interactive - -# List all editing operations -uv run ai-update-plan --help-edit -``` - -#### Implementation Strategy - -**Backward Compatible API**: -```python -# scripts/ai_tools/update_plan.py (ENHANCED) - -def update_plan( - # Existing parameters (PRESERVED) - item: str | None = None, - check: bool = True, - uncheck: bool = False, - show: bool = False, - session_id: str | None = None, - - # New parameters (ADDED) - add: str | None = None, - remove: str | None = None, - rename: str | None = None, - to: str | None = None, - add_phase: str | None = None, - add_note: str | None = None, - section: str | None = None, - phase: str | None = None, - interactive: bool = False, - list_phases: bool = False, -) -> None: - """Update plan: check items OR edit plan structure. - - Modes of operation: - 1. Checkbox mode (default): Check/uncheck items - 2. Edit mode: Add/remove/rename items and phases - - Args: - item: Item to check/uncheck (checkbox mode) - check: Check the box (checkbox mode) - uncheck: Uncheck the box (checkbox mode) - show: Show current plan with progress (both modes) - session_id: Session ID (default: most recent) - - add: Add new checklist item (edit mode) - remove: Remove checklist item (edit mode) - rename: Rename existing item (edit mode) - to: New name for renamed item (edit mode) - add_phase: Add new phase section (edit mode) - add_note: Add note to section (edit mode) - section: Section for note (edit mode) - phase: Target phase for new item (edit mode) - interactive: Interactive editing (edit mode) - list_phases: List all phases (both modes) - """ - # Determine mode based on which parameters are provided - is_edit_mode = any([add, remove, rename, add_phase, add_note, interactive]) - - if is_edit_mode: - # NEW: Edit mode - edit_plan(...) - else: - # EXISTING: Checkbox mode (original behavior) - toggle_checkbox_original(...) - - -# New functions (keep existing functions) - -def edit_plan(...) -> None: - """Handle plan editing operations.""" - if add: - add_item_to_plan(plan_content, add, phase) - elif remove: - remove_item_from_plan(plan_content, remove) - elif rename: - rename_item_in_plan(plan_content, rename, to) - elif add_phase: - add_phase_to_plan(plan_content, add_phase) - elif add_note: - add_note_to_plan(plan_content, add_note, section) - elif interactive: - interactive_edit_plan(plan_content) - -def add_item_to_plan(plan_content: str, item: str, phase: str | None) -> str: - """Add checklist item to plan.""" - ... - -def remove_item_from_plan(plan_content: str, item_pattern: str) -> str: - """Remove checklist item matching pattern.""" - ... - -def rename_item_in_plan(plan_content: str, old_item: str, new_item: str) -> str: - """Rename existing item description.""" - ... - -def add_phase_to_plan(plan_content: str, phase_name: str) -> str: - """Add new phase section.""" - ... - -def add_note_to_plan(plan_content: str, note: str, section: str) -> str: - """Add note to specified section (Risks, Notes, Context).""" - ... -``` - -#### Compatibility Matrix - -| Usage | Mode | Behavior | -|-------|------|----------| -| `ai-update-plan "item"` | Checkbox | Check item (ORIGINAL) | -| `ai-update-plan "item" --uncheck` | Checkbox | Uncheck item (ORIGINAL) | -| `ai-update-plan --show` | Display | Show plan (ORIGINAL) | -| `ai-update-plan --add "new item"` | Edit | Add item (NEW) | -| `ai-update-plan --remove "item"` | Edit | Remove item (NEW) | -| `ai-update-plan --rename "old" --to "new"` | Edit | Rename item (NEW) | - -**Key Design**: No mode flag needed. Command automatically detects mode based on parameters used. - -### 3. AI-Driven Plan Customization - -#### Automatic Plan Adaptation - -**When AI agent starts work**: -```python -# In AI instructions (CLAUDE.md, AGENTS.md, etc.) - -""" -After running ai-start-task, you MUST customize the plan: - -1. Review the default checklist -2. Add task-specific items using ai-update-plan --add -3. Remove irrelevant items using ai-update-plan --remove -4. Rename items to be more specific using ai-update-plan --rename - -Example: - Task: "Add email validation to user registration" - - Default plan includes: "Write test file(s)" - - AI customizes to: - uv run ai-update-plan --rename "Write test file(s)" --to "Write tests/test_validators.py with email format tests" - uv run ai-update-plan --add "Test valid emails: user@domain.com, user+tag@domain.co.uk" - uv run ai-update-plan --add "Test invalid emails: @domain, user@, user.com" - uv run ai-update-plan --remove "Update README if needed" # Not needed for this task -""" -``` - -**AI Workflow with Plan Customization**: -``` -1. User: "Add phone validation" -2. AI: ai-start-task "Add phone validation" -3. AI: Reviews default plan (ai-update-plan --show) -4. AI: ai-update-plan --add "Test US format: (123) 456-7890" -5. AI: ai-update-plan --add "Test international formats" -6. AI: ai-update-plan --rename "Write test file(s)" --to "Write tests/test_validators.py::test_phone_formats" -7. AI: Proceeds with customized plan -8. AI: ai-update-plan "item" as work progresses (checkbox mode) -``` - -#### AI_DOCS Update Requirements - -**CRITICAL**: All AI agent documentation MUST be updated to mandate plan customization. - -**Files to Update**: -1. `AI_DOCS/ai-tools.md` - Add plan customization section -2. `AI_DOCS/tdd-workflow.md` - Include plan management in TDD cycle -3. `CLAUDE.md` - Add plan customization to workflow -4. `AGENTS.md` - Add plan customization requirements -5. `.cursorrules` - Add plan customization guidance -6. `.github/copilot-instructions.md` - Add plan customization for Copilot users -7. `.gemini/styleguide.md` - Add plan customization for Gemini - -**Mandatory Workflow for ALL AI Agents**: -```markdown -## Session Management with Plan Customization (MANDATORY) - -### Step 1: Start Task -```bash -uv run ai-start-task "Task description" --type= -``` - -### Step 2: Customize Plan (NEW - REQUIRED!) - -**AFTER starting task, IMMEDIATELY customize the plan:** - -```bash -# View default plan -uv run ai-update-plan --show - -# Customize based on task -uv run ai-update-plan --add "Task-specific item" -uv run ai-update-plan --remove "Irrelevant item" -uv run ai-update-plan --rename "Generic item" --to "Specific description" -``` - -**Why this is MANDATORY**: -- Generic plans add no value -- Task-specific plans guide real work -- Validation will check if plan was customized -- Failure to customize will trigger warnings - -### Step 3: Work and Track Progress -```bash -# Check off items as completed (checkbox mode) -uv run ai-update-plan "Completed item" - -# Add new items discovered during work (edit mode) -uv run ai-update-plan --add "Newly discovered step" -``` - -### Step 4: Finish Task -```bash -uv run ai-finish-task --summary="What was accomplished" -``` - -**Validation checks**: -- Plan was customized (strict validation) -- Work matches plan items (strict validation) -- Quality checks completed (strict validation) -``` - -**Non-Compliance Consequences**: -- `ai-finish-task` will warn if plan not customized -- With strict validation (default), must confirm to proceed -- Plan validation metrics will track customization rate -- Low customization rate indicates agents not following workflow - -### 4. Enhanced Plan Validation (Strict Mode) - -#### Current: Basic Completion Check -```python -def check_plan_completion(plan_content): - # Only checks: are all boxes checked? - # Doesn't validate relevance -``` - -#### Proposed: Strict Intelligent Validation -```python -def validate_plan_relevance( - plan_content: str, - execution_content: str, - task_type: str, - strict: bool = True # DEFAULT: Strict validation -) -> ValidationResult: - """Validate plan matches actual work. - - Args: - plan_content: Content of PLAN file - execution_content: Content of EXECUTION log - task_type: Type of task (feature, bugfix, docs, refactor) - strict: If True, require plan customization (default) - - Returns: - ValidationResult with checks, errors, warnings - """ - - validation = ValidationResult() - - # STRICT CHECK 1: Plan must be customized - if is_generic_template(plan_content): - if strict: - validation.add_error( - "Plan was NOT customized. Generic templates add no value. " - "REQUIRED: Use 'ai-update-plan --add/--remove/--rename' after ai-start-task." - ) - else: - validation.add_warning("Plan was not customized") - - # STRICT CHECK 2: Work must match plan - plan_items = extract_checked_items(plan_content) - work_done = extract_work_from_log(execution_content) - - mismatch_items = [] - for item in plan_items: - if not item_appears_in_log(item, work_done): - mismatch_items.append(item) - - if mismatch_items: - if strict: - validation.add_error( - f"Checked items not found in execution log: {mismatch_items}. " - "REQUIRED: Plan items must match actual work completed." - ) - else: - validation.add_warning(f"Items may not match work: {mismatch_items}") - - # STRICT CHECK 3: Quality gates must be run - if not check_make_check_ran(execution_content): - if strict: - validation.add_error( - "'make check' not found in execution log. " - "REQUIRED: Run 'make check' before finishing task." - ) - else: - validation.add_warning("'make check' not logged") - - # STRICT CHECK 4: All items must be checked - is_complete, checked, total = check_plan_completion(plan_content) - if not is_complete: - if strict: - validation.add_error( - f"Plan not complete: {checked}/{total} items checked. " - "REQUIRED: Complete all plan items or remove irrelevant ones." - ) - else: - validation.add_warning(f"Plan incomplete: {checked}/{total}") - - # STRICT CHECK 5: Task-type specific validation - if not validate_task_type_requirements(plan_content, task_type): - if strict: - validation.add_error( - f"Plan missing required sections for {task_type} tasks. " - f"Check task-specific template requirements." - ) - - return validation - - -class ValidationResult: - """Result of plan validation.""" - - def __init__(self): - self.errors: list[str] = [] - self.warnings: list[str] = [] - self.suggestions: list[str] = [] - - def add_error(self, msg: str) -> None: - """Add validation error (blocks completion in strict mode).""" - self.errors.append(msg) - - def add_warning(self, msg: str) -> None: - """Add validation warning (informational).""" - self.warnings.append(msg) - - def add_suggestion(self, msg: str) -> None: - """Add suggestion for improvement.""" - self.suggestions.append(msg) - - def has_errors(self) -> bool: - """Check if validation failed.""" - return len(self.errors) > 0 - - def has_warnings(self) -> bool: - """Check if validation has warnings.""" - return len(self.warnings) > 0 - - def is_valid(self) -> bool: - """Check if validation passed.""" - return not self.has_errors() -``` - -#### Strict Validation Configuration - -**Default Behavior**: Strict validation ENABLED - -**Configuration in pyproject.toml**: -```toml -[tool.ai-tools] -strict_validation = true # Default -require_plan_customization = true # Default -require_work_match = true # Default -require_quality_checks = true # Default -``` - -**Override Options**: -```bash -# Finish with strict validation (default) -uv run ai-finish-task --summary="Task done" - -# Override to lenient validation (not recommended) -uv run ai-finish-task --summary="Task done" --lenient - -# Force finish (skip validation - emergency only) -uv run ai-finish-task --summary="Task done" --force -``` - -**Strict Validation Behavior**: -- Errors BLOCK task completion -- User must fix issues OR explicitly override -- Clear error messages explain what's required -- Suggestions provided for remediation - -### 5. Plan Templates in Separate Files - -**Structure**: -``` -scripts/ai_tools/ -├── templates/ -│ ├── __init__.py -│ ├── feature.md # Feature template -│ ├── bugfix.md # Bugfix template -│ ├── docs.md # Documentation template -│ ├── refactor.md # Refactor template -│ └── custom.md # Minimal custom template -├── edit_plan.py # NEW: Plan editing tool -├── start_task.py # Modified: Load templates -├── update_plan.py # Enhanced: Better item matching -└── finish_task.py # Enhanced: Plan validation -``` - -**Template Format** (feature.md): -```markdown -# Task Plan: {{task_name}} - -**Session ID**: {{session_id}} -**Created**: {{timestamp}} -**Task Type**: feature -**Status**: 🚧 In Progress - ---- - -## Objective - -{{objective_placeholder}} - ---- - -## Context - -**Recent Decisions**: -See RECENT_DECISIONS.md - -**Related Conventions**: -See CONVENTIONS.md - -**Dependencies**: -- [ ] None identified yet - ---- - -## Implementation Steps - -### Phase 1: Research & Design -- [ ] Understand requirements -- [ ] Review related code -- [ ] Identify affected components -- [ ] Design approach - -### Phase 2: Write Tests (TDD) -- [ ] Identify test scenarios -- [ ] Write test file(s) -- [ ] Run tests to confirm they fail - -### Phase 3: Implementation -- [ ] Implement functionality -- [ ] Run tests to confirm they pass -- [ ] Verify 80%+ coverage -- [ ] Handle edge cases - -### Phase 4: Quality Checks -- [ ] Run make format -- [ ] Run make lint -- [ ] Run make test -- [ ] Fix any issues -- [ ] Run make check - all pass - -### Phase 5: Documentation -- [ ] Update docstrings -- [ ] Add type hints -- [ ] Update README if user-facing -- [ ] Add inline comments for complex logic - ---- - -## Files to Change - -- [ ] `src/` - Implementation -- [ ] `tests/` - Test files -- [ ] `README.md` - If user-facing - ---- - -## Risks & Considerations - -- None identified yet - ---- - -## Notes - -[Track decisions, blockers, questions as you work] - - -``` - ---- - -## Implementation Phases - -### Phase 1: Template System (Week 1) - -**Goal**: Implement task-specific template loading - -**Tasks**: -1. Create template directory structure -2. Write 4 base templates (feature, bugfix, docs, refactor) -3. Modify `start_task.py` to load templates based on task_type -4. Add template variables substitution -5. Write tests for template loading - -**Files**: -- `scripts/ai_tools/templates/*.md` (NEW) -- `scripts/ai_tools/template_loader.py` (NEW) -- `scripts/ai_tools/start_task.py` (MODIFY) -- `tests/ai_tools/test_template_loader.py` (NEW) -- `tests/ai_tools/test_start_task.py` (MODIFY) - -**Testing**: -```python -def test_load_feature_template(): - """Test feature template loads with correct sections.""" - template = load_template("feature", session_id="123", task_name="test") - assert "Phase 1: Research & Design" in template - assert "Phase 2: Write Tests (TDD)" in template - -def test_load_docs_template_no_tests(): - """Test docs template doesn't include testing phase.""" - template = load_template("docs", session_id="123", task_name="test") - assert "Write Tests" not in template - assert "Update Documentation" in template -``` - -**Deliverables**: -- 4 task-type templates -- Template loading system -- 100% test coverage -- Updated `ai-start-task` using templates - -### Phase 2: Extended Plan Management (Week 2) - -**Goal**: Extend `ai-update-plan` with editing capabilities - -**Tasks**: -1. Extend `update_plan.py` with new functions: - - `add_item_to_plan()` - Add checklist items - - `remove_item_from_plan()` - Remove items - - `rename_item_in_plan()` - Rename/update items - - `add_phase_to_plan()` - Add custom phases - - `add_note_to_plan()` - Add notes to sections -2. Add new CLI argument flags (--add, --remove, --rename, etc.) -3. Implement mode detection (checkbox vs edit) -4. Implement interactive mode -5. Add plan format validation -6. Maintain full backward compatibility -7. Write comprehensive tests for new functionality -8. Test backward compatibility extensively - -**Files**: -- `scripts/ai_tools/update_plan.py` (MAJOR ENHANCEMENT) -- `tests/ai_tools/test_update_plan.py` (EXTEND) -- `tests/ai_tools/test_update_plan_backward_compat.py` (NEW) - -**API Design** (Extended): -```python -def update_plan( - # EXISTING parameters (PRESERVED) - item: str | None = None, - check: bool = True, - uncheck: bool = False, - show: bool = False, - session_id: str | None = None, - - # NEW parameters (ADDED) - add: str | None = None, - remove: str | None = None, - rename: str | None = None, - to: str | None = None, - add_phase: str | None = None, - add_note: str | None = None, - section: str | None = None, - phase: str | None = None, - interactive: bool = False, - list_phases: bool = False, -) -> None: - """Update plan: check items OR edit plan structure. - - Backward compatible: defaults to checkbox mode. - """ - # Auto-detect mode - is_edit_mode = any([add, remove, rename, add_phase, add_note, interactive]) - - if is_edit_mode: - handle_edit_mode(...) - else: - handle_checkbox_mode(...) # EXISTING code - - -# NEW functions - -def add_item_to_plan( - plan_content: str, - item_text: str, - phase: str | None = None -) -> str: - """Add checklist item to plan. - - Args: - plan_content: Current plan content - item_text: Text of new item - phase: Phase name (e.g., "Phase 1") - - Returns: - Updated plan content - """ - -def remove_item_from_plan( - plan_content: str, - item_pattern: str, - confirm: bool = True -) -> str: - """Remove checklist item from plan. - - Args: - plan_content: Current plan content - item_pattern: Pattern to match (fuzzy) - confirm: Ask for confirmation before removing - - Returns: - Updated plan content - """ - -def rename_item_in_plan( - plan_content: str, - old_text: str, - new_text: str -) -> str: - """Rename existing checklist item. - - Args: - plan_content: Current plan content - old_text: Current item text (fuzzy match) - new_text: New item text - - Returns: - Updated plan content - """ -``` - -**Testing Strategy**: - -**Backward Compatibility Tests**: -```python -def test_checkbox_mode_still_works(): - """Test original checkbox behavior unchanged.""" - # Ensure old commands still work exactly as before - update_plan("Write tests") # Should check item - update_plan("Run tests", uncheck=True) # Should uncheck - update_plan(show=True) # Should display plan - -def test_no_edit_flags_means_checkbox_mode(): - """Test that absence of edit flags uses checkbox mode.""" - # If user provides item name only, use checkbox mode - result = update_plan("Some item") - # Should toggle checkbox, not try to edit -``` - -**New Functionality Tests**: -```python -def test_add_item_with_flag(): - """Test adding item with --add flag.""" - plan = create_test_plan() - result = add_item_to_plan(plan, "New test item", phase="Phase 1") - assert "- [ ] New test item" in result - -def test_remove_item_with_flag(): - """Test removing item with --remove flag.""" - plan = create_plan_with_items() - result = remove_item_from_plan(plan, "Update README") - assert "Update README" not in result - -def test_rename_item_with_flags(): - """Test renaming item with --rename and --to flags.""" - plan = create_plan_with_items() - result = rename_item_in_plan(plan, "Write tests", "Write test_validators.py") - assert "Write test_validators.py" in result - assert "Write tests" not in result - -def test_mode_detection_checkbox(): - """Test mode detection uses checkbox when no edit flags.""" - # No edit flags = checkbox mode - assert detect_mode(item="test", check=True) == "checkbox" - -def test_mode_detection_edit(): - """Test mode detection uses edit when edit flags present.""" - # Edit flag present = edit mode - assert detect_mode(add="new item") == "edit" - assert detect_mode(remove="old item") == "edit" - assert detect_mode(rename="old", to="new") == "edit" -``` - -**CLI Testing**: -```bash -# Test backward compatibility -uv run ai-update-plan "Write tests" # Should work as before -uv run ai-update-plan --show # Should work as before - -# Test new functionality -uv run ai-update-plan --add "New item" -uv run ai-update-plan --remove "Old item" -uv run ai-update-plan --rename "Generic" --to "Specific" -``` - -**Deliverables**: -- Extended `ai-update-plan` command -- Full backward compatibility -- Interactive editing mode -- Comprehensive tests (old + new functionality) -- Updated documentation -- Migration guide (none needed - fully compatible) - -### Phase 3: Enhanced Update Tool (Week 3) - -**Goal**: Improve `ai-update-plan` with better features - -**Tasks**: -1. Add fuzzy matching for item text -2. Support checking multiple items at once -3. Add progress visualization -4. Add "--list-phases" option -5. Improve error messages - -**Files**: -- `scripts/ai_tools/update_plan.py` (MODIFY) -- `tests/ai_tools/test_update_plan.py` (MODIFY) - -**Enhancements**: -```python -# Current: Exact substring match -def find_checkbox_line(content, item_text): - if item_lower in line_lower: # Rigid - -# Proposed: Fuzzy matching -from difflib import SequenceMatcher - -def find_checkbox_line(content, item_text, threshold=0.7): - """Find checkbox with fuzzy matching.""" - best_match = None - best_score = 0.0 - - for i, line in enumerate(lines): - if is_checkbox(line): - score = similarity(item_text, line) - if score > threshold and score > best_score: - best_match = (i, line) - best_score = score - - return best_match -``` - -**New Features**: -```bash -# Check multiple items -uv run ai-update-plan "Write tests" "Run tests" - -# List all phases and items -uv run ai-update-plan --list-phases - -# Check all items in a phase -uv run ai-update-plan --check-phase "Phase 1" - -# Show detailed progress by phase -uv run ai-update-plan --show --detailed -``` - -**Deliverables**: -- Fuzzy matching -- Batch operations -- Better UX -- Full test coverage - -### Phase 4: Plan Validation (Week 4) - -**Goal**: Add intelligent plan validation to `ai-finish-task` - -**Tasks**: -1. Implement plan relevance checking -2. Detect generic vs. customized plans -3. Validate work matches plan -4. Add validation warnings/suggestions -5. Allow override with confirmation - -**Files**: -- `scripts/ai_tools/finish_task.py` (MODIFY) -- `scripts/ai_tools/plan_validator.py` (NEW) -- `tests/ai_tools/test_plan_validator.py` (NEW) - -**Validation Logic**: -```python -def validate_plan( - plan_content: str, - execution_content: str, - task_type: str -) -> ValidationResult: - """Validate plan quality and relevance.""" - - checks = { - "is_complete": check_all_items_done(plan_content), - "is_customized": check_plan_customized(plan_content), - "work_matches": check_work_matches_plan(plan_content, execution_content), - "quality_checks_run": check_make_check_logged(execution_content), - "plan_updated_during_work": check_plan_modifications(plan_content) - } - - warnings = [] - suggestions = [] - - if not checks["is_customized"]: - warnings.append( - "Plan appears to be generic template - " - "consider using ai-edit-plan to customize" - ) - suggestions.append( - "Future: Run ai-edit-plan after ai-start-task to add task-specific items" - ) - - if not checks["work_matches"]: - warnings.append( - "Some checked items don't appear in execution log" - ) - suggestions.append( - "Ensure plan is kept up-to-date as work progresses" - ) - - return ValidationResult(checks, warnings, suggestions) -``` - -**Enhanced Finish Flow**: -```python -def finish_task(summary, session_id): - """Finish task with validation.""" - - # ... existing code ... - - # NEW: Validate plan - validation = validate_plan(plan_content, execution_content, task_type) - - if validation.has_warnings(): - print_warning("Plan Validation Issues:") - for warning in validation.warnings: - print(f" • {warning}") - print() - - if validation.has_suggestions(): - print("Suggestions for next time:") - for suggestion in validation.suggestions: - print(f" • {suggestion}") - print() - - response = input("Continue anyway? [y/N]: ").lower() - if response != 'y': - sys.exit(0) - - # ... existing code ... -``` - -**Deliverables**: -- Plan validation system -- Smart warnings -- Helpful suggestions -- Full test coverage - -### Phase 5: AI Instructions Update (Week 5) - CRITICAL - -**Goal**: Update ALL AI agent instructions to MANDATE plan customization - -**CRITICAL**: This phase ensures ALL AI agents implement the new workflow. - -**Tasks**: -1. Update `AI_DOCS/ai-tools.md` - Add plan customization as MANDATORY step -2. Update `AI_DOCS/tdd-workflow.md` - Include plan management in TDD cycle -3. Update `CLAUDE.md` - Add plan customization to session workflow -4. Update `AGENTS.md` - Add plan customization requirements -5. Update `.cursorrules` - Add plan management for Cursor -6. Update `.github/copilot-instructions.md` - Add plan customization for Copilot -7. Update `.gemini/styleguide.md` - Add plan customization for Gemini -8. Create enforcement mechanisms in documentation -9. Add examples of good vs bad plan customization - -**Files** (ALL MUST BE UPDATED): -- `AI_DOCS/ai-tools.md` (MAJOR UPDATE - PRIMARY) -- `AI_DOCS/tdd-workflow.md` (MODIFY - Add plan step) -- `CLAUDE.md` (MODIFY - Add customization step) -- `AGENTS.md` (MODIFY - Add requirements) -- `.cursorrules` (MODIFY - Add guidance) -- `.github/copilot-instructions.md` (MODIFY - Add workflow) -- `.gemini/styleguide.md` (MODIFY - Add workflow) - -**New AI Workflow Documentation** (For ALL Agent Docs): - -```markdown -## Session Management with Plan Customization (MANDATORY) - -### Step 1: Start Task -```bash -uv run ai-start-task "Add email validation" --type=feature -``` - -### Step 2: Customize Plan (REQUIRED!) - -**IMMEDIATELY after starting, you MUST customize the plan:** - -```bash -# Review default plan -uv run ai-update-plan --show - -# Add task-specific items -uv run ai-update-plan --add "Test valid: user@example.com" -uv run ai-update-plan --add "Test invalid: @example.com" - -# Remove irrelevant items -uv run ai-update-plan --remove "Update README" # Not needed - -# Rename generic to specific -uv run ai-update-plan --rename "Write test file(s)" --to "Write tests/test_validators.py" -``` - -**Why REQUIRED**: -- Generic plans have NO VALUE -- Strict validation will ERROR if plan not customized -- Plan guides your actual work -- Demonstrates understanding of task - -### Step 3: Work & Track Progress -As you work, check off completed items (checkbox mode): -```bash -uv run ai-update-plan "Test valid: user@example.com" -uv run ai-update-plan "Test invalid: @example.com" -``` - -Add new items discovered during work (edit mode): -```bash -uv run ai-update-plan --add "Handle edge case: empty string" -``` - -### Step 4: Finish Task -```bash -uv run ai-finish-task --summary="Added email validation with comprehensive tests" -``` - -**Strict Validation Checks**: -- ERROR if plan was not customized -- ERROR if work doesn't match plan items -- ERROR if quality checks not completed -- ERROR if plan not 100% complete - -Must fix errors OR use `--lenient` override (not recommended). -``` - -**Documentation Structure** (Each agent file): - -1. **STOP! Section** - ai-start-task command -2. **Plan Customization** - NEW MANDATORY section -3. **TDD Workflow** - Including plan integration -4. **Quality Gates** - Including plan validation - -**Enforcement in AI_DOCS**: - -Add to `AI_DOCS/ai-tools.md`: -```markdown -## CRITICAL: Plan Customization is MANDATORY - -After running ai-start-task, you MUST customize the plan. - -### Why This is Not Optional - -1. Generic plans add ZERO value -2. Strict validation enforces customization -3. Demonstrates task understanding -4. Guides actual work effectively - -### How to Customize - -Use ai-update-plan with edit flags: -- --add: Add task-specific items -- --remove: Remove irrelevant items -- --rename: Make generic items specific - -### Validation - -ai-finish-task validates: -- Plan was customized (REQUIRED) -- Work matches plan (REQUIRED) -- Quality checks run (REQUIRED) - -Failure = ERROR, not warning -``` - -**Deliverables**: -- Updated AI instructions -- Plan customization workflow -- Examples and best practices -- Clear guidance for AI agents - -### Phase 6: Documentation & Examples (Week 6) - -**Goal**: Complete documentation and provide examples - -**Tasks**: -1. Create user guide for new commands -2. Add workflow examples -3. Update README.md -4. Create CHANGELOG entry -5. Add migration guide - -**Files**: -- `AI_DOCS/ai-tools.md` (MAJOR UPDATE) -- `README.md` (MODIFY) -- `CHANGELOG.md` (ADD) -- `docs/ai-plan-customization-guide.md` (NEW) - -**Documentation Sections**: - -1. **User Guide**: How to use ai-edit-plan -2. **Workflow Examples**: Common scenarios -3. **Template Reference**: Available templates -4. **Best Practices**: When to customize, what to add -5. **Migration Guide**: For existing sessions - -**Deliverables**: -- Complete documentation -- Workflow examples -- Migration guide -- Updated README - ---- - -## Testing Strategy - -### Unit Tests (Per Phase) - -**Phase 1: Templates** -- Template loading -- Variable substitution -- Task type routing -- Error handling - -**Phase 2: Edit Plan** -- Add items -- Remove items -- Update items -- Add phases -- Fuzzy matching -- Edge cases - -**Phase 3: Update Plan** -- Enhanced matching -- Batch operations -- Phase operations -- Progress display - -**Phase 4: Validation** -- Customization detection -- Work matching -- Quality checks -- Warning generation - -### Integration Tests - -```python -def test_full_workflow_with_customization(): - """Test complete workflow with plan customization.""" - - # Start task - start_task("Add phone validation", task_type="feature") - - # Customize plan - add_item("Test US format") - add_item("Test international format") - remove_item("Update README") - - # Update as work progresses - update_plan("Write test file(s)") - update_plan("Test US format") - - # Finish with validation - result = finish_task("Phone validation complete") - - assert result.validation_passed - assert result.plan_was_customized -``` - -### Manual Testing Scenarios - -1. **Feature Development**: - - Start feature task - - Customize plan with specific test cases - - Work through customized checklist - - Finish with validation - -2. **Bug Fix**: - - Start bugfix task - - Get bugfix-specific template - - Add reproduction steps - - Complete and validate - -3. **Documentation**: - - Start docs task - - Get docs template (no testing) - - Customize with sections to update - - Finish - -4. **Refactoring**: - - Start refactor task - - Ensure tests exist - - Customize with affected components - - Validate no test breakage - ---- - -## Migration Strategy - -### For Existing Sessions - -**Option 1: No Migration (Recommended)** -- Old sessions keep working -- New features only for new sessions -- Clean cut-over - -**Option 2: Template Upgrade** -- Add `ai-upgrade-plan` command -- Convert generic plan to task-specific template -- Preserve checked items -- Add customization reminder - -**Implementation**: -```bash -# For old sessions that want new features -uv run ai-upgrade-plan --session-id=20251103102706 - -# Interactive: asks which items to keep -# Applies appropriate template -# Preserves progress -``` - -### Backward Compatibility - -**Ensure**: -- Old plan format still works -- `ai-update-plan` works with old plans -- `ai-finish-task` validates both formats -- No breaking changes to existing sessions - ---- - -## Success Metrics - -### Quantitative - -1. **Template Usage**: - - 100% of new tasks use task-specific templates - - Each task type has appropriate default items - -2. **Plan Customization**: - - Target: 70%+ of tasks have customized plans - - Measure: Count modified plans vs. generic - -3. **Plan Relevance**: - - Target: 90%+ of checked items appear in execution log - - Measure: Validation pass rate - -4. **Test Coverage**: - - All new code: 100% coverage - - Modified code: Maintain 100% coverage - -### Qualitative - -1. **User Feedback**: - - Plans feel relevant to actual work - - Customization is easy and natural - - AI agents effectively use plan editing - -2. **AI Agent Behavior**: - - AI agents customize plans appropriately - - Plans reflect actual work being done - - Plan items are specific, not generic - -3. **Value Addition**: - - Plans are actively used, not ignored - - Checklists guide work effectively - - Progress tracking is meaningful - ---- - -## Timeline - -| Phase | Duration | Key Deliverables | -|-------|----------|------------------| -| Phase 1: Templates | Week 1 | Task-specific templates, template loader | -| Phase 2: Edit Plan | Week 2 | ai-edit-plan command, tests | -| Phase 3: Enhanced Update | Week 3 | Improved ai-update-plan | -| Phase 4: Validation | Week 4 | Plan validation, warnings | -| Phase 5: AI Instructions | Week 5 | Updated agent instructions | -| Phase 6: Documentation | Week 6 | Complete docs, examples | - -**Total**: 6 weeks - -**Fast Track Option**: 3 weeks (combine related phases) - ---- - -## Risks & Mitigation - -### Risk 1: Complexity - -**Risk**: Adding too many features makes system complex - -**Mitigation**: -- Start with simple template system -- Add editing incrementally -- Keep commands simple and focused -- Extensive documentation - -### Risk 2: AI Adoption - -**Risk**: AI agents don't use customization features - -**Mitigation**: -- Clear instructions in agent docs -- Examples of good customization -- Validation encourages customization -- Templates are good defaults - -### Risk 3: Backward Compatibility - -**Risk**: Breaking existing sessions - -**Mitigation**: -- Support both old and new formats -- No forced migration -- Gradual rollout -- Comprehensive testing - -### Risk 4: Over-Engineering - -**Risk**: Solution more complex than problem - -**Mitigation**: -- Start with minimal viable solution -- Phase 1-2 solve core problem -- Phases 3-6 are enhancements -- Can stop after Phase 2 if sufficient - ---- - -## Next Steps - -### Immediate (For User Review) - -1. **Review this plan**: - - Does it address your concerns? - - Are task-specific templates the right approach? - - Is ai-edit-plan the right solution? - - Any missing requirements? - -2. **Decide on scope**: - - Full implementation (all 6 phases)? - - Minimal version (Phases 1-2)? - - Custom priority? - -3. **Approve approach**: - - Template-based system OK? - - New command (ai-edit-plan) acceptable? - - Validation approach makes sense? - -### After Approval - -1. **Start Phase 1**: Implement task-specific templates -2. **TDD throughout**: Write tests first -3. **Incremental delivery**: Each phase is usable -4. **Iterate based on feedback**: Adjust as needed - ---- - -## Decisions Based on User Feedback - -### User Feedback Received: - -1. **Problem Solving**: ✅ Yes, this solves the "no value" concern -2. **AI_DOCS Updates**: ✅ MUST update AI_DOCS so ALL agents implement new tools -3. **Scope**: ✅ Full 6-phase implementation -4. **Design - Command**: ✅ Extend ai-update-plan (not create new command) -5. **Design - Compatibility**: ✅ Must accommodate both old and new implementation -6. **Design - Templates**: ✅ Markdown templates (preferred) -7. **Design - Validation**: ✅ Strict validation (preferred) -8. **Timeline**: ✅ 6 weeks acceptable -9. **Status**: ⏳ Adjustments needed first - -### Plan Adjustments Made: - -1. **Command Approach**: - - ✅ Changed from separate `ai-edit-plan` to extended `ai-update-plan` - - ✅ Maintains full backward compatibility - - ✅ Auto-detects mode based on flags used - - ✅ Single command for all plan operations - -2. **Validation Approach**: - - ✅ Changed to strict validation by default - - ✅ Validation errors BLOCK task completion - - ✅ Override requires explicit `--lenient` or `--force` flag - - ✅ Clear error messages with remediation guidance - -3. **AI_DOCS Requirements**: - - ✅ Added CRITICAL section for AI_DOCS updates - - ✅ Plan customization is MANDATORY, not optional - - ✅ ALL agent documentation files must be updated - - ✅ Enforcement through strict validation - -4. **Implementation Details**: - - ✅ Markdown templates in separate files - - ✅ Strict validation with configuration options - - ✅ Backward compatibility extensively tested - - ✅ Phase 5 emphasizes AI_DOCS updates - -### Outstanding Questions: - -None - all major decisions confirmed by user. - ---- - -## Appendix: Alternative Approaches Considered - -### Alternative 1: AI Generates Plans - -**Approach**: AI agent generates custom plan based on task description - -**Pros**: -- Fully customized to each task -- No generic templates - -**Cons**: -- Requires AI involvement (not all tools) -- Inconsistent plan quality -- Hard to test/validate -- More complex implementation - -**Decision**: Rejected in favor of templates + editing - -### Alternative 2: Extend ai-update-plan - -**Approach**: Add editing features to ai-update-plan instead of new command - -**Pros**: -- Single command -- Less to learn - -**Cons**: -- Command becomes overloaded -- Confusing API (update vs edit) -- Harder to document - -**Decision**: Separate ai-edit-plan is clearer - -### Alternative 3: Configuration-Based Templates - -**Approach**: YAML/TOML config defines templates - -**Pros**: -- Easy to modify without code -- User-customizable - -**Cons**: -- More complexity -- Harder to validate -- Template logic in config - -**Decision**: Markdown templates simpler - -### Alternative 4: No Templates, Full Editing - -**Approach**: Start with minimal plan, build entirely through editing - -**Pros**: -- Maximum flexibility -- No template maintenance - -**Cons**: -- More work per task -- No guidance -- Inconsistent plans - -**Decision**: Templates + editing balances both - ---- - -## Summary - -### The Problem -Current system provides generic, unchangeable plans that don't add value because they can't be adapted to actual work. - -### The Solution (Updated Based on Feedback) -1. **Task-Specific Templates**: Different base plans for features, bugs, docs, refactors (Markdown files) -2. **Extended ai-update-plan**: Backward-compatible editing capabilities (not new command) -3. **AI-Driven Customization**: MANDATORY plan customization enforced through ALL AI agents -4. **Strict Validation**: Errors block completion if plan not customized properly - -### Key Benefits -- Plans are relevant from the start (task-specific templates) -- Plans adapt as understanding evolves (extended ai-update-plan) -- Plans guide actual work (MANDATORY AI customization) -- Plans have real value (strict validation ensures quality) -- Single command for all operations (backward compatible) - -### Implementation -6 phases, 6 weeks, fully tested, comprehensive documentation, ALL AI agents updated. - -### User-Approved Decisions -- ✅ Extend ai-update-plan (not create new command) -- ✅ Full backward compatibility -- ✅ Markdown templates -- ✅ Strict validation by default -- ✅ ALL AI_DOCS files must be updated -- ✅ Plan customization is MANDATORY, not optional -- ✅ Full 6-phase implementation -- ✅ 6-week timeline acceptable - -**Deliverable**: Task management system that adds real value through task-specific, dynamically editable, strictly validated plans that ALL AI agents are required to customize. - ---- - -**Status**: Plan adjusted per user feedback - Ready for implementation approval -**Next**: User final approval to proceed with implementation diff --git a/.ai-context/RECENT_DECISIONS.md b/.ai-context/RECENT_DECISIONS.md deleted file mode 100644 index e7b7539..0000000 --- a/.ai-context/RECENT_DECISIONS.md +++ /dev/null @@ -1,99 +0,0 @@ -# Recent Decisions - -## Git Commits: No AI Co-Authoring (2025-11-02) - -**Decision**: Never add AI co-author attribution to git commits -**Rationale**: -- Commits should represent human intent and responsibility -- Professional git history without AI attribution -- Clear accountability for code changes -- Industry standard practice -**Implementation**: -- Added CRITICAL rule to AI_DOCS/code-conventions.md -- Duplicated in .gemini/styleguide.md -- Duplicated in .github/copilot-instructions.md -- Applied to both root and template directories -- Rule: No "Co-Authored-By: Claude" or "Generated with [AI Tool]" in commits -**Status**: Implemented - -## AI-Generated Summaries Location (2025-11-02) - -**Decision**: All AI-generated summaries must go in `.ai-summary/` directory -**Rationale**: -- Prevents accidental commits of AI tool output -- Keeps git history clean and professional -- Separates code from AI artifacts -- Consistent across all AI assistants -**Implementation**: -- Added `.ai-summary/` to .gitignore (root and template) -- Added CRITICAL rule to AI_DOCS/code-conventions.md -- Duplicated in .gemini/styleguide.md -- Duplicated in .github/copilot-instructions.md -- Applied to both root and template directories -**Status**: Implemented - -## AI Instructions: No Decorative Emojis (2025-11-02) - -**Decision**: Add CRITICAL emoji prohibition rule to all AI agent configurations -**Rationale**: Professional appearance, universal compatibility, accessibility, Atyantik branding -**Implementation**: -- Added to AI_DOCS/code-conventions.md (shared by Claude, Cursor, Aider, Agents) -- Duplicated in .gemini/styleguide.md (Gemini doesn't support file references) -- Duplicated in .github/copilot-instructions.md (Copilot doesn't support file references) -- Applied to both root and template directories -- Rule: No decorative emojis (🚀🎯🐳 etc), only functional checkboxes (✅❌) -**Pattern**: Use AI_DOCS/ for shared rules, duplicate only for Gemini/Copilot -**Status**: Implemented - -## Documentation Style (2025-11-02) - -**Decision**: Remove all decorative emojis from documentation -**Rationale**: Professional appearance, universal compatibility, accessibility -**Impact**: All .md files updated, code output cleaned -**Status**: Implemented - -## Examples Strategy (2025-11-02) - -**Decision**: Don't track generated examples in git -**Rationale**: -- Keeps repository lightweight (~200 files saved) -- Examples always fresh from latest template -- Standard practice for template repos - -**Implementation**: -- Track only: README.md, generate-all.sh, .gitkeep -- Ignore: 7 generated project directories -**Status**: Implemented - -## Project Naming (2025-11-02) - -**Decision**: Rename to `python-modern-template` -**From**: `leadership-blog-generator` -**Rationale**: Accurately reflects purpose as a template -**Author**: Atyantik Technologies Private Limited -**Status**: Complete (pending root directory rename) - -## AI Tools Integration (2025-11-02) - -**Decision**: Support multiple AI assistants -**Tools Included**: Claude Code, Cursor, Copilot, Gemini, Aider -**Config Files**: Each AI has dedicated config file -**Session Management**: Optional, configurable via `include_ai_tools` -**Status**: Implemented - -## Template Architecture (2025-11-02) - -**Decision**: Use Copier over Cookiecutter -**Rationale**: -- Template update capabilities -- Modern YAML configuration -- Better uv integration -**Status**: Implemented - -## Quality Standards (2025-11-02) - -**Decision**: Single source of truth in pyproject.toml -**Coverage**: Minimum 80%, target 100% -**Tools**: Black, Ruff, mypy, Pylint, pytest, Bandit -**TDD**: Required - tests before implementation -**Status**: Implemented and enforced diff --git a/.ai-context/RECENT_DECISIONS.md.example b/.ai-context/RECENT_DECISIONS.md.example new file mode 100644 index 0000000..8062a52 --- /dev/null +++ b/.ai-context/RECENT_DECISIONS.md.example @@ -0,0 +1,58 @@ +# Recent Decisions + +## Git Commits: No AI Co-Authoring (2025-11-02) + +**Decision**: Never add AI co-author attribution to git commits +**Rationale**: +- Commits should represent human intent and responsibility +- Professional git history without AI attribution +- Clear accountability for code changes +- Industry standard practice +**Implementation**: +- Added CRITICAL rule to AI_DOCS/code-conventions.md +- Duplicated in .gemini/styleguide.md +- Duplicated in .github/copilot-instructions.md +**Status**: Implemented + +## AI Instructions: No Decorative Emojis (2025-11-02) + +**Decision**: Add CRITICAL emoji prohibition rule to all AI agent configurations +**Rationale**: Professional appearance, universal compatibility, accessibility +**Implementation**: +- Added to AI_DOCS/code-conventions.md (shared by Claude, Cursor, Aider, Agents) +- Duplicated in .gemini/styleguide.md +- Duplicated in .github/copilot-instructions.md +**Status**: Implemented + +## Project Naming (2025-11-02) + +**Decision**: Rename to `python-modern-template` +**From**: `leadership-blog-generator` +**Rationale**: Accurately reflects purpose as a template +**Author**: Atyantik Technologies Private Limited +**Status**: Complete + +## Quality Standards (2025-11-02) + +**Decision**: Single source of truth in pyproject.toml +**Coverage**: Minimum 80%, target 100% +**Tools**: Black, Ruff, mypy, Pylint, pytest, Bandit +**TDD**: Required - tests before implementation +**Status**: Implemented and enforced + +--- + +## Instructions + +This file tracks important architectural and technical decisions made during development. + +Add new decisions at the top (most recent first) following this format: + +```markdown +## Decision Title (YYYY-MM-DD) + +**Decision**: What was decided +**Rationale**: Why this decision was made +**Implementation**: How it was implemented +**Status**: Implemented/Pending/Deprecated +``` diff --git a/.ai-context/REQUIRED_READING.md b/.ai-context/REQUIRED_READING.md deleted file mode 100644 index 7f37f74..0000000 --- a/.ai-context/REQUIRED_READING.md +++ /dev/null @@ -1,45 +0,0 @@ -# Required Reading - Python Modern Template - -## What This Is - -This is a **Copier template repository** for creating modern Python projects. It's not a project itself - it's a template that generates projects. - -## For AI Assistants - -When working on this template repository: - -### 1. Template Structure -- `template/` directory contains files copied to generated projects -- Files with `.jinja` suffix use Jinja2 templating -- `copier.yml` defines template configuration - -### 2. Testing Changes -- Test by generating a project: `copier copy . test-project` -- Verify generated project: `cd test-project && make check` -- Examples in `examples/` directory - -### 3. Key Documentation -- README.md - Main template documentation -- GETTING_STARTED.md - Beginner's guide -- CLAUDE.md, AGENTS.md - AI configurations -- examples/README.md - Example configurations - -### 4. Important Files -- `copier.yml` - Template configuration -- `template/` - All template files -- `scripts/quality/` - Quality tools -- `scripts/ai_tools/` - AI session management - -## Current State - -- Version: 1.0.0 -- Status: Production ready -- Tests: 67/67 passing, 100% coverage -- Examples: 7 configurations available - -## Development Guidelines - -1. **Follow TDD** - Write tests before code -2. **Run `make check`** - Before committing -3. **No emojis** - Keep documentation professional -4. **Test generation** - Verify template produces working projects diff --git a/.gemini/styleguide.md b/.gemini/styleguide.md index 4b165c9..c68191f 100644 --- a/.gemini/styleguide.md +++ b/.gemini/styleguide.md @@ -1,10 +1,9 @@ # Gemini Code Assist Style Guide - - + ## STOP! READ THIS FIRST - MANDATORY SESSION MANAGEMENT @@ -39,21 +38,6 @@ See `AI_DOCS/ai-tools.md` for complete workflow and all ai-update-plan features. --- -## CRITICAL! DOCUMENTATION-FIRST APPROACH - -**BEFORE implementing ANY task, research existing solutions!** - -1. Check for MCP tools (mcp__docs__, mcp__context7__) -2. Fetch official documentation with WebFetch -3. Search for recent tutorials with WebSearch -4. Verify no built-in solution exists - -**Never reinvent the wheel. Always check documentation first.** - -See `AI_DOCS/documentation-first-approach.md` for complete guidelines. - ---- - ## CRITICAL Code Conventions **See `AI_DOCS/code-conventions.md` for complete standards including:** @@ -73,14 +57,12 @@ See `AI_DOCS/documentation-first-approach.md` for complete guidelines. > Teams can describe custom instructions here to tailor Gemini's code reviews to the repository's needs. **Primary Directive:** Write tests BEFORE code. Use TDD (Test-Driven Development) always. -**Secondary Directive:** Research documentation BEFORE writing any code. ## Shared Documentation For complete guidelines, see these shared documents in the project: - `AI_DOCS/ai-tools.md` - Session management (MANDATORY workflow) -- `AI_DOCS/documentation-first-approach.md` - Research before implementation (MANDATORY) - `AI_DOCS/ai-skills.md` - Specialized skills and agents (manual workflows) - `AI_DOCS/tdd-workflow.md` - TDD process and testing standards - `AI_DOCS/code-conventions.md` - Code style and best practices diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 9434b58..11305ec 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,10 +1,9 @@ # GitHub Copilot Repository Instructions - - + ## STOP! READ THIS FIRST - MANDATORY SESSION MANAGEMENT @@ -38,21 +37,6 @@ See `AI_DOCS/ai-tools.md` for complete workflow and all ai-update-plan features. --- -## CRITICAL! DOCUMENTATION-FIRST APPROACH - -**BEFORE implementing ANY task, research existing solutions!** - -1. Check for MCP tools (mcp__docs__, mcp__context7__) -2. Fetch official documentation with WebFetch -3. Search for recent tutorials with WebSearch -4. Verify no built-in solution exists - -**Never reinvent the wheel. Always check documentation first.** - -See `AI_DOCS/documentation-first-approach.md` for complete guidelines. - ---- - ## CRITICAL Code Conventions **See `AI_DOCS/code-conventions.md` for complete standards including:** @@ -72,14 +56,12 @@ See `AI_DOCS/documentation-first-approach.md` for complete guidelines. > It provides repository-wide instructions in natural language using Markdown format. **Primary Directive:** ALWAYS write tests BEFORE implementation code (Test-Driven Development). -**Secondary Directive:** ALWAYS research documentation BEFORE writing any code. ## Shared Documentation For complete guidelines, see these shared documents in the project: - `AI_DOCS/ai-tools.md` - Session management (MANDATORY workflow) -- `AI_DOCS/documentation-first-approach.md` - Research before implementation (MANDATORY) - `AI_DOCS/ai-skills.md` - Specialized skills and agents (manual workflows) - `AI_DOCS/tdd-workflow.md` - TDD process and testing standards - `AI_DOCS/code-conventions.md` - Code style and best practices @@ -93,7 +75,6 @@ For complete guidelines, see these shared documents in the project: | What | Requirement | |------|-------------| -| **Documentation Research** | MANDATORY - Check MCP tools, fetch docs, search tutorials BEFORE coding | | **Testing** | Write tests FIRST, TDD always | | **Mocking** | Minimize - use real code when possible | | **Coverage** | Minimum 80%, aim for 90%+ | diff --git a/.gitignore b/.gitignore index a78226c..99cc8ba 100644 --- a/.gitignore +++ b/.gitignore @@ -179,19 +179,10 @@ config.local.yaml .uv/ uv.lock -# AI Context - Sessions are local only -.ai-context/sessions/* -!.ai-context/sessions/.gitkeep -!.ai-context/sessions/archive/ -.ai-context/sessions/archive/* -!.ai-context/sessions/archive/.gitkeep - -# AI Context - Keep these files (project knowledge) -!.ai-context/REQUIRED_READING.md -!.ai-context/LAST_SESSION_SUMMARY.md -!.ai-context/ACTIVE_TASKS.md -!.ai-context/RECENT_DECISIONS.md -!.ai-context/CONVENTIONS.md +# AI Context - Local session files (developer-specific, never commit) +.ai-context/* +!.ai-context/*.example +!.ai-context/.gitkeep # AI-generated summaries (automated output - never commit) .ai-summary/ diff --git a/AGENTS.md b/AGENTS.md index 44cf69f..42ec01a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,62 +32,17 @@ See `@AI_DOCS/ai-tools.md` for complete workflow and all ai-update-plan features --- -## CRITICAL! DOCUMENTATION-FIRST APPROACH - -**BEFORE implementing ANY task, you MUST research existing solutions and documentation!** - -This is NOT optional. You MUST: - -1. **Check for MCP Tools First** - - Look for `mcp__docs__`, `mcp__context7__`, or framework-specific MCP tools - - Use them to fetch latest documentation - -2. **Fetch Official Documentation** - - Use WebFetch from official docs (docs.framework.com) - - Search for built-in tools and features - - Read API references and getting started guides - -3. **Search for Recent Tutorials** - - Use WebSearch for 2024-2025 tutorials and examples - - Look for official framework tutorials - - Find existing integration patterns - -4. **Verify No Built-In Solution Exists** - - Check if framework provides the functionality - - Look for official integrations - - Confirm custom code is actually needed - -**Why This Matters:** - -❌ **DON'T** reinvent the wheel: -- Don't reverse-engineer documentation sites -- Don't manually implement APIs when SDK exists -- Don't create custom code when built-in tools are available -- Don't over-engineer simple tasks - -✅ **DO** discover and use existing solutions: -- Use MCP tools to fetch documentation -- Read official framework docs -- Leverage built-in tools and integrations -- Follow framework best practices - -See `@AI_DOCS/documentation-first-approach.md` for complete guidelines and examples. - ---- - ## Overview **Universal instructions for all AI coding assistants working on this project** **Primary Directive:** ALWAYS write tests BEFORE implementation code (Test-Driven Development). -**Secondary Directive:** ALWAYS research documentation BEFORE writing any code. ## Shared Documentation For comprehensive guidelines, reference these shared documents: - **@AI_DOCS/ai-tools.md** - AI session management tools (MANDATORY workflow) -- **@AI_DOCS/documentation-first-approach.md** - Research before implementation (MANDATORY) - **@AI_DOCS/ai-skills.md** - Specialized skills and agents for quality and testing - **@AI_DOCS/tdd-workflow.md** - Test-Driven Development process and testing standards - **@AI_DOCS/code-conventions.md** - Code style, formatting, and best practices @@ -100,7 +55,6 @@ For comprehensive guidelines, reference these shared documents: |--------|-------------| | **Session Management** | Use `ai-start-task` before starting, `ai-finish-task` when done | | **Progress Tracking** | Log all important steps with `ai-log` | -| **Documentation Research** | MANDATORY - Check MCP tools, fetch docs, search tutorials BEFORE coding | | **Development Approach** | Test-Driven Development (TDD) - Tests First! | | **Minimum Coverage** | 80% (enforced by pytest) | | **Mocks/Fixtures** | Minimize - use real code when possible | diff --git a/AI_DOCS/README.md b/AI_DOCS/README.md index 17d5da2..cb9685c 100644 --- a/AI_DOCS/README.md +++ b/AI_DOCS/README.md @@ -9,7 +9,6 @@ This directory contains shared documentation referenced by all AI tool configura | File | Purpose | Who Uses It | |------|---------|-------------| | **ai-tools.md** | AI session management workflow (MANDATORY for all agents) | All AI tools | -| **documentation-first-approach.md** | Research and discover before implementation (MANDATORY for all agents) | All AI tools | | **ai-skills.md** | Specialized skills and agents (test-generator, coverage-analyzer, quality-fixer, tdd-reviewer, quality-enforcer) | All AI tools | | **tdd-workflow.md** | Test-Driven Development process, testing standards, coverage requirements | All AI tools | | **code-conventions.md** | Code style, formatting, best practices, documentation standards | All AI tools | @@ -120,13 +119,12 @@ Content that is **unique to each tool**: **Always read these first**: ``` -@AI_DOCS/ai-tools.md # Session management (MANDATORY) -@AI_DOCS/documentation-first-approach.md # Research before implementation (MANDATORY) -@AI_DOCS/documentation-sync-rules.md # Doc sync golden rule (MANDATORY) -@AI_DOCS/ai-skills.md # Specialized skills and agents -@AI_DOCS/tdd-workflow.md # TDD process -@AI_DOCS/code-conventions.md # Code standards -@AI_DOCS/project-context.md # Architecture +@AI_DOCS/ai-tools.md # Session management (MANDATORY) +@AI_DOCS/documentation-sync-rules.md # Doc sync golden rule (MANDATORY) +@AI_DOCS/ai-skills.md # Specialized skills and agents +@AI_DOCS/tdd-workflow.md # TDD process +@AI_DOCS/code-conventions.md # Code standards +@AI_DOCS/project-context.md # Architecture ``` Then read your tool-specific config: diff --git a/AI_DOCS/ai-tools.md b/AI_DOCS/ai-tools.md index 123a614..d914c8f 100644 --- a/AI_DOCS/ai-tools.md +++ b/AI_DOCS/ai-tools.md @@ -22,34 +22,6 @@ uv run ai-finish-task --summary="What you accomplished" **This is NOT optional!** Every AI agent must follow this workflow. -## 🚨 MANDATORY: Documentation-First Approach - -**BEFORE implementing any task, MUST research existing solutions!** - -```bash -# STEP 1: Check for MCP tools -# Look for mcp__docs__, mcp__context7__, etc. - -# STEP 2: Fetch official documentation -WebFetch: url="https://docs.framework.com/api" prompt="What tools exist for [task]?" - -# STEP 3: Search for recent tutorials -WebSearch: query="framework [specific-feature] tutorial 2025" - -# STEP 4: Verify no built-in solution exists -# Only write custom code after confirming no existing solution -``` - -**Critical Rules:** -- ❌ NEVER start coding without researching documentation first -- ❌ NEVER reinvent functionality that already exists in frameworks -- ❌ NEVER reverse-engineer when official docs are available -- ✅ ALWAYS use MCP tools to fetch latest documentation -- ✅ ALWAYS check for built-in framework tools before custom code -- ✅ ALWAYS leverage official integrations and SDKs - -See `@AI_DOCS/documentation-first-approach.md` for complete guidelines and examples. - ## 📚 All Available Tools | Tool | Purpose | When to Use | @@ -664,13 +636,10 @@ uv run ai-finish-task --summary="Added phone validation with 6 tests, 100% cover ## ⚠️ Critical Rules 1. **ALWAYS** run `ai-start-task` before ANY work -2. **ALWAYS** research documentation before implementing (see `@AI_DOCS/documentation-first-approach.md`) -3. **ALWAYS** check for MCP tools and use WebFetch/WebSearch before coding -4. **ALWAYS** run `ai-finish-task` when complete -5. **NEVER** skip `ai-log` for important milestones -6. **ALWAYS** check `ai-context-summary` if unsure what to do -7. **NEVER** start a task without checking for conflicts first -8. **NEVER** reinvent functionality that already exists in frameworks +2. **ALWAYS** run `ai-finish-task` when complete +3. **NEVER** skip `ai-log` for important milestones +4. **ALWAYS** check `ai-context-summary` if unsure what to do +5. **NEVER** start a task without checking for conflicts first ## 📂 Context Files Location diff --git a/AI_DOCS/documentation-first-approach.md b/AI_DOCS/documentation-first-approach.md deleted file mode 100644 index 1c889c1..0000000 --- a/AI_DOCS/documentation-first-approach.md +++ /dev/null @@ -1,392 +0,0 @@ -# Documentation-First Approach - -> **Shared documentation for all AI coding assistants** -> -> This file is referenced by multiple AI tool configurations. Changes here automatically apply to all tools that support file references. - -## 🚨 CRITICAL: Research Before Implementation - -**Before implementing ANY task, you MUST research and discover existing solutions, tools, and documentation.** - -This is NOT optional. Every AI agent must follow this workflow to avoid over-engineering and reinventing the wheel. - -## ❌ Common Anti-Pattern (DO NOT DO THIS) - -**Bad Example:** User asks to "create an Agno app to fetch latest 2 stories of HackerNews" - -**What NOT to do:** -1. ❌ View source of docs.agno.com to reverse-engineer the API -2. ❌ Go to news.ycombinator.com to see which API is called -3. ❌ Manually call HackerNews API with custom code -4. ❌ Reinvent functionality that already exists in the framework - -**Why this is wrong:** -- Wastes time reverse-engineering when docs are available -- Misses existing tools/utilities provided by the framework -- Creates unnecessary custom code instead of using built-in features -- Over-engineers simple tasks - -## ✅ Correct Pattern: Documentation-First Workflow - -### Phase 1: Discover MCP Tools (ALWAYS FIRST) - -**MCP (Model Context Protocol) tools provide access to documentation, APIs, and utilities.** - -```bash -# Check if MCP tools are available -# Look for tools starting with "mcp__" -``` - -**What to look for:** -- Documentation fetch tools (mcp__docs__, mcp__context7__) -- API integration tools -- Framework-specific utilities -- Code search and exploration tools - -**Example:** -```bash -# ✅ Good: Use MCP to fetch Agno documentation -mcp__docs__fetch "agno hackernews tools" -# OR -mcp__context7__search "agno hackernews integration" -``` - -### Phase 2: Fetch Latest Documentation - -**ALWAYS get the latest official documentation before implementing.** - -**Priority order:** -1. **Official MCP documentation tools** (if available) -2. **WebFetch from official docs** (docs.framework.com) -3. **WebSearch for official tutorials** (framework.com/tutorials) -4. **WebSearch for recent examples** (2024-2025 only) - -**What to fetch:** -- Official API reference -- Getting started guides -- Framework-specific tools/utilities -- Best practices and patterns -- Example code and tutorials - -**Example:** -```bash -# ✅ Good: Fetch official Agno documentation -WebFetch: url="https://docs.agno.com/tools/hackernews" prompt="What HackerNews tools are available in Agno?" - -# ✅ Good: Search for recent tutorials -WebSearch: query="Agno HackerNews integration tutorial 2025" -``` - -### Phase 3: Search for Built-In Tools/Features - -**Before writing custom code, check if the framework already provides the functionality.** - -**What to check:** -- Built-in tools and utilities -- Official integrations -- Standard library functions -- Framework plugins/extensions - -**Example:** -```bash -# ✅ Good: Check Agno docs for built-in HackerNews tools -WebFetch: url="https://docs.agno.com/api-reference/tools" prompt="Does Agno provide built-in HackerNews tools?" -``` - -### Phase 4: Implement with Discovered Resources - -**Only after completing research, implement using the best available approach.** - -**Decision tree:** -1. **Built-in tool exists?** → Use it directly -2. **Official integration exists?** → Use official integration -3. **Standard pattern exists?** → Follow the pattern -4. **No existing solution?** → Implement custom (but verify first!) - -## 🎯 Complete Example: The Right Way - -**Task:** "Create an Agno app to fetch latest 2 stories of HackerNews" - -### Step 1: Check for MCP Tools - -```bash -# Check available MCP tools -# Look for documentation fetch capabilities -``` - -### Step 2: Fetch Agno Documentation - -```bash -# Use MCP if available -mcp__docs__fetch "agno hackernews" - -# OR use WebFetch from official docs -WebFetch: url="https://docs.agno.com/tools" prompt="What tools are available in Agno for fetching data from external APIs? Specifically, are there HackerNews-related tools?" - -# Search for tutorials -WebSearch: query="Agno framework HackerNews integration example 2025" -``` - -### Step 3: Analyze Documentation - -**From Agno docs, you discover:** -- Agno has built-in `hackernews_tools` module -- Provides `get_top_stories()` function -- Handles API calls automatically -- Includes error handling and rate limiting - -### Step 4: Implement Using Built-In Tools - -```python -# ✅ Good: Use built-in Agno HackerNews tools -from agno.tools import hackernews_tools - -app = Agno( - name="hn-fetcher", - tools=[hackernews_tools.get_top_stories] -) - -# Fetch 2 stories using built-in functionality -stories = app.run("Get the top 2 stories from HackerNews") -``` - -**NOT:** -```python -# ❌ Bad: Custom implementation ignoring built-in tools -import requests - -def fetch_hackernews(): - response = requests.get("https://hacker-news.firebaseio.com/v0/topstories.json") - # ... custom parsing and error handling ... -``` - -## 📋 Mandatory Pre-Implementation Checklist - -Before writing ANY implementation code: - -- [ ] **MCP Tools Checked**: Looked for relevant MCP documentation tools -- [ ] **Official Docs Fetched**: Retrieved latest documentation from official sources -- [ ] **Built-In Features Verified**: Confirmed no existing functionality covers this use case -- [ ] **Recent Tutorials Reviewed**: Checked for 2024-2025 examples and best practices -- [ ] **Framework Tools Discovered**: Identified all relevant framework-provided utilities -- [ ] **API Documentation Read**: Reviewed official API reference (if applicable) -- [ ] **Implementation Plan**: Documented approach based on discovered resources - -## 🛠️ Tools for Documentation Discovery - -### 1. MCP Tools (Highest Priority) - -**Available MCP tools typically start with `mcp__`:** -- `mcp__docs__*` - Documentation fetchers -- `mcp__context7__*` - Codebase context and documentation -- Framework-specific MCP tools - -**Usage:** -```bash -# Check available MCP tools -# Use them to fetch documentation before implementation -``` - -### 2. WebFetch (Official Documentation) - -**Use for:** -- Official framework documentation -- API references -- Getting started guides -- Best practices - -**Example:** -```bash -WebFetch: url="https://docs.framework.com/api-reference" prompt="What are the available tools and utilities for [specific task]?" -``` - -**Best practices:** -- Always use official documentation URLs (docs.framework.com) -- Ask specific questions in prompts -- Focus on discovering existing functionality -- Check multiple relevant documentation pages - -### 3. WebSearch (Tutorials and Examples) - -**Use for:** -- Recent tutorials and examples -- Community best practices -- Framework-specific patterns -- Problem-solving approaches - -**Example:** -```bash -WebSearch: query="framework-name specific-task tutorial 2025" -WebSearch: query="framework-name best practices integration 2024" -``` - -**Best practices:** -- Include year (2024-2025) for recent results -- Search for official tutorials first -- Look for framework-specific examples -- Prefer official sources over blog posts - -### 4. Codebase Search (Existing Patterns) - -**Use Grep/Glob to find:** -- Similar implementations in current codebase -- Existing patterns and conventions -- Import statements (what's already being used) - -**Example:** -```bash -Grep: pattern="import.*framework" output_mode="files_with_matches" -Grep: pattern="def.*similar_function" output_mode="content" -``` - -## 🎓 Learning from Mistakes - -### Real-World Example: Agno HackerNews Task - -**What Happened:** -An AI agent was asked to create an Agno app to fetch HackerNews stories. - -**Mistakes Made:** -1. Viewed page source of docs.agno.com (unnecessary reverse-engineering) -2. Went to news.ycombinator.com to inspect API calls -3. Manually implemented HackerNews API integration -4. Ignored Agno's built-in HackerNews tools - -**What Should Have Happened:** -1. Use MCP tools to fetch Agno documentation -2. Discover Agno has built-in HackerNews tools -3. Read official Agno docs for `hackernews_tools` -4. Implement using Agno's built-in functionality - -**Result:** -- Over-engineered solution -- Reinvented the wheel -- Missed simpler built-in approach -- Wasted development time - -### Lessons Learned - -**Always ask yourself:** -1. "Does this framework provide this functionality?" -2. "Have I checked the official documentation?" -3. "Are there MCP tools that can help me find answers?" -4. "Am I reinventing something that already exists?" - -**If you're not sure:** -- Search the documentation first -- Use MCP tools to fetch latest info -- Check for official integrations -- Look for recent tutorials - -## 🚀 Framework-Specific Examples - -### For Python Frameworks - -**Before implementing:** -```bash -# Check official docs -WebFetch: url="https://docs.python-framework.org/api" prompt="What utilities does this framework provide for [task]?" - -# Search for examples -WebSearch: query="python-framework [specific-feature] example 2025" - -# Check PyPI for related packages -WebSearch: query="python-framework official integrations" -``` - -### For JavaScript/Node.js Frameworks - -**Before implementing:** -```bash -# Check official docs -WebFetch: url="https://framework.dev/docs" prompt="What built-in tools are available for [task]?" - -# Search npm documentation -WebSearch: query="framework-name official packages npm" - -# Look for recent examples -WebSearch: query="framework-name integration tutorial 2024" -``` - -### For AI/ML Frameworks (Agno, LangChain, etc.) - -**Before implementing:** -```bash -# Check for built-in tools -WebFetch: url="https://docs.framework.ai/tools" prompt="What pre-built tools are available for [specific integration]?" - -# Look for official integrations -WebFetch: url="https://docs.framework.ai/integrations" prompt="Does this framework have official integration with [service]?" - -# Search for recent examples -WebSearch: query="framework-name [service] integration example 2025" -``` - -## 📊 Decision Matrix - -| Scenario | MCP Tools | WebFetch Docs | WebSearch | Custom Code | -|----------|-----------|---------------|-----------|-------------| -| Framework task | ✅ Check first | ✅ Yes | ✅ For examples | ❌ Last resort | -| API integration | ✅ Check first | ✅ Yes | ✅ For tutorials | ⚠️ Only if no built-in | -| Data processing | ✅ Check first | ✅ Check stdlib | ✅ For patterns | ⚠️ Prefer libraries | -| External service | ✅ Check first | ✅ Check integrations | ✅ For SDKs | ⚠️ Use official SDK | - -**Legend:** -- ✅ Yes - Always do this -- ⚠️ Conditional - Only if necessary -- ❌ No - Avoid if possible - -## 🎯 Success Criteria - -**You've followed documentation-first approach when:** -- ✅ Checked for MCP documentation tools before coding -- ✅ Fetched official documentation from authoritative sources -- ✅ Verified no built-in functionality exists -- ✅ Searched for recent tutorials and examples -- ✅ Used framework-provided tools when available -- ✅ Implemented the simplest solution based on research -- ✅ Can explain why custom code was necessary (if used) - -**Warning signs you're NOT following the approach:** -- ❌ Started coding immediately without research -- ❌ Reverse-engineered instead of reading docs -- ❌ Implemented custom solution without checking for built-ins -- ❌ Ignored MCP tools and documentation fetch capabilities -- ❌ Used outdated tutorials or examples -- ❌ Over-engineered when simple solution existed - -## 🔄 Integration with TDD Workflow - -**Documentation-first fits into TDD:** - -1. **Discover** (NEW STEP - BEFORE TDD) - - Check MCP tools for documentation - - Fetch official docs and tutorials - - Identify built-in functionality - - Plan implementation approach - -2. **Write Tests** (TDD Phase 1) - - Based on discovered API/tools - - Following framework patterns - - Using official examples as reference - -3. **Implement** (TDD Phase 2) - - Using discovered built-in tools - - Following framework conventions - - Leveraging official integrations - -4. **Refactor** (TDD Phase 3) - - Align with framework best practices - - Use framework utilities - - Follow discovered patterns - -## 📚 Reference Documentation - -**Also see:** -- `@AI_DOCS/ai-tools.md` - Session management workflow -- `@AI_DOCS/tdd-workflow.md` - Test-Driven Development process -- `@AI_DOCS/code-conventions.md` - Code style and standards - ---- - -**Remember:** Research first, implement second. Use MCP tools, fetch documentation, discover built-in functionality, then code. NEVER reinvent the wheel when official tools exist. diff --git a/CLAUDE.md b/CLAUDE.md index 1ba591b..7e7cab2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,68 +32,17 @@ See `@AI_DOCS/ai-tools.md` for complete workflow and all ai-update-plan features --- -## CRITICAL! DOCUMENTATION-FIRST APPROACH - -**BEFORE implementing ANY task, you MUST research existing solutions and documentation!** - -This is NOT optional. You MUST: - -1. **Check for MCP Tools First** - - Look for `mcp__docs__`, `mcp__context7__`, or framework-specific MCP tools - - Use them to fetch latest documentation - -2. **Fetch Official Documentation** - - Use WebFetch from official docs (docs.framework.com) - - Search for built-in tools and features - - Read API references and getting started guides - -3. **Search for Recent Tutorials** - - Use WebSearch for 2024-2025 tutorials and examples - - Look for official framework tutorials - - Find existing integration patterns - -4. **Verify No Built-In Solution Exists** - - Check if framework provides the functionality - - Look for official integrations - - Confirm custom code is actually needed - -**Why This Matters:** - -❌ **DON'T** reinvent the wheel: -- Don't reverse-engineer documentation sites -- Don't manually implement APIs when SDK exists -- Don't create custom code when built-in tools are available -- Don't over-engineer simple tasks - -✅ **DO** discover and use existing solutions: -- Use MCP tools to fetch documentation -- Read official framework docs -- Leverage built-in tools and integrations -- Follow framework best practices - -**Example:** If asked to "create an Agno app to fetch HackerNews stories": -1. ✅ Use MCP to fetch Agno documentation -2. ✅ Discover Agno has built-in `hackernews_tools` -3. ✅ Use the built-in tools instead of custom API calls -4. ❌ Don't view page source or reverse-engineer APIs - -See `@AI_DOCS/documentation-first-approach.md` for complete guidelines and examples. - ---- - ## Overview You are Claude Code, working on a Python project with strict Test-Driven Development (TDD) and code quality standards. **Primary Directive:** ALWAYS write tests BEFORE implementation code. -**Secondary Directive:** ALWAYS research documentation BEFORE writing any code. ## Shared Documentation Reference these for complete guidelines: - `@AI_DOCS/ai-tools.md` - Session management workflow (MANDATORY) -- `@AI_DOCS/documentation-first-approach.md` - Research before implementation (MANDATORY) - `@AI_DOCS/ai-skills.md` - Specialized skills and agents (use via Skill/Task tools) - `@AI_DOCS/tdd-workflow.md` - TDD process and testing standards - `@AI_DOCS/code-conventions.md` - Code style and best practices @@ -104,24 +53,14 @@ Reference these for complete guidelines: ### Before Writing Any Code -**Phase 0: Documentation Discovery (MANDATORY FIRST STEP)** -1. Check for MCP tools (`mcp__docs__`, `mcp__context7__`, etc.) -2. Use WebFetch to get official documentation from framework -3. Use WebSearch for recent tutorials and examples (2024-2025) -4. Verify no built-in tools/features exist for the task -5. Document research findings before proceeding - -**Phase 1: TDD Preparation** -6. Read relevant files to understand current implementation -7. Check existing tests in `tests/` directory -8. Plan test cases needed (based on discovered patterns) - -**Phase 2: TDD Implementation** -9. **Write failing tests FIRST** -10. Run tests to confirm they fail -11. Implement minimal code to make tests pass (using discovered tools/patterns) -12. Refactor while keeping tests green -13. Run `make check` to ensure all quality gates pass +1. Read relevant files to understand current implementation +2. Check existing tests in `tests/` directory +3. Plan test cases needed +4. **Write failing tests FIRST** +5. Run tests to confirm they fail +6. Implement minimal code to make tests pass +7. Refactor while keeping tests green +8. Run `make check` to ensure all quality gates pass ### Using Claude Code Tools @@ -347,12 +286,6 @@ See `@AI_DOCS/code-conventions.md` for complete documentation standards. Before completing any task: -- [ ] **Documentation research completed** (MANDATORY) - - [ ] Checked for MCP tools and used them - - [ ] Fetched official framework documentation - - [ ] Searched for recent tutorials and examples - - [ ] Verified no built-in solution exists - - [ ] Documented research findings - [ ] Tests written BEFORE implementation - [ ] Tests initially failed (confirmed TDD) - [ ] Implementation makes tests pass @@ -422,7 +355,6 @@ See `@AI_DOCS/ai-skills.md` for complete documentation on: **Shared documentation:** - `@AI_DOCS/ai-tools.md` - Session management workflow -- `@AI_DOCS/documentation-first-approach.md` - Research before implementation (MANDATORY) - `@AI_DOCS/ai-skills.md` - Specialized skills and agents - `@AI_DOCS/tdd-workflow.md` - TDD process, testing standards, coverage - `@AI_DOCS/code-conventions.md` - Code style, formatting, best practices diff --git a/template/.ai-context/ACTIVE_TASKS.md b/template/.ai-context/ACTIVE_TASKS.md new file mode 100644 index 0000000..d5f670f --- /dev/null +++ b/template/.ai-context/ACTIVE_TASKS.md @@ -0,0 +1,15 @@ +# Active Tasks + +## Current Tasks + +None - Starting fresh + +## Completed + +- ✅ Project initialized from python-modern-template + +## Pending User Actions + +1. Review and customize project configuration +2. Set up development environment +3. Begin implementation with TDD diff --git a/template/.ai-context/CONVENTIONS.md b/template/.ai-context/CONVENTIONS.md new file mode 100644 index 0000000..9e4247a --- /dev/null +++ b/template/.ai-context/CONVENTIONS.md @@ -0,0 +1,39 @@ +# Coding Conventions + +## Python Style + +1. **No Emojis** - Keep all code and documentation professional +2. **Type Hints** - Required for all functions +3. **Docstrings** - Google style for all public functions +4. **Line Length** - 88 characters (Black default) +5. **Import Order** - stdlib, third-party, local (isort) + +## Testing + +1. **TDD Required** - Write tests before implementation +2. **Coverage** - Minimum 80%, target 100% +3. **Test Structure** - Mirror src/ directory +4. **Naming** - test_*.py files, test_* functions +5. **Real Code** - Prefer real functions over mocks + +## Documentation + +1. **No Decorative Emojis** - Professional appearance only +2. **Functional Markers** - Keep ✅ ❌ for checkboxes +3. **Clear Headers** - Use markdown hierarchy +4. **Code Examples** - Always include working examples +5. **Beginner-Friendly** - Explain technical terms + +## File Organization + +1. **Source Code** - In `src/package_name/` +2. **Tests** - In `tests/` mirroring src structure +3. **Scripts** - In `scripts/` for tooling +4. **Docs** - Root level .md files + +## Git Commits + +1. **Clear Messages** - Describe what and why +2. **Run Tests** - `make check` before committing +3. **Atomic Commits** - One logical change per commit +4. **No WIP** - Complete features before pushing diff --git a/template/.ai-context/LAST_SESSION_SUMMARY.md b/template/.ai-context/LAST_SESSION_SUMMARY.md new file mode 100644 index 0000000..fc3ee26 --- /dev/null +++ b/template/.ai-context/LAST_SESSION_SUMMARY.md @@ -0,0 +1,41 @@ +# Last Session Summary + +> **Auto-updated by AI agents**: This file contains a summary of the most recent AI session + +## Session Information + +**Session ID**: Not started +**Task**: No tasks yet +**Date**: N/A +**Status**: Awaiting first session + +--- + +## What Was Done + +No sessions completed yet. This file will be automatically updated by AI tools when using the session management system. + +--- + +## Decisions Made + +No decisions recorded yet. + +--- + +## Files Changed + +None yet. + +--- + +## Notes + +This is a fresh project initialized from python-modern-template. Use `ai-start-task` to begin your first session. + +--- + +**This file is automatically updated by the last AI agent to complete a task.** +**Next AI agent: Read this file first to understand recent work!** + +**Last Updated**: N/A diff --git a/template/.ai-context/RECENT_DECISIONS.md b/template/.ai-context/RECENT_DECISIONS.md new file mode 100644 index 0000000..ac9f7fb --- /dev/null +++ b/template/.ai-context/RECENT_DECISIONS.md @@ -0,0 +1,36 @@ +# Recent Decisions + +## Project Initialization (Date TBD) + +**Decision**: Initialize project from python-modern-template +**Rationale**: Start with modern Python best practices +**Implementation**: +- TDD workflow established +- Quality gates configured +- AI tools integrated +**Status**: Pending + +--- + +## Instructions + +This file tracks important architectural and technical decisions made during development. + +### Format for New Decisions: + +```markdown +## Decision Title (YYYY-MM-DD) + +**Decision**: What was decided +**Rationale**: Why this decision was made +**Implementation**: How it was implemented +**Status**: Implemented/Pending/Deprecated +``` + +### Guidelines: + +1. Add new decisions at the top (most recent first) +2. Include context for future developers +3. Update status as implementation progresses +4. Reference related files or documentation +5. Capture the "why" not just the "what" diff --git a/template/.gemini/styleguide.md b/template/.gemini/styleguide.md deleted file mode 100644 index 4b165c9..0000000 --- a/template/.gemini/styleguide.md +++ /dev/null @@ -1,515 +0,0 @@ -# Gemini Code Assist Style Guide - - - - - - - - -## STOP! READ THIS FIRST - MANDATORY SESSION MANAGEMENT - -**BEFORE doing ANYTHING in this session, you MUST run:** - -```bash -uv run ai-start-task "Your task description" -``` - -**If you have NOT run this command yet, STOP NOW and run it!** - -This is NOT optional. Every Gemini session MUST start with `ai-start-task`. - -**During work:** -```bash -uv run ai-log "Progress message" -uv run ai-update-plan "Completed item" - -# Customize your plan (add task-specific steps, remove irrelevant items) -uv run ai-update-plan --add "Specific task for this feature" --phase "Phase 2" -uv run ai-update-plan --remove "Generic irrelevant item" -uv run ai-update-plan --rename "Generic item" --to "Specific detailed item" -``` - -**When finishing:** -```bash -uv run ai-finish-task --summary="What you accomplished" -``` - -See `AI_DOCS/ai-tools.md` for complete workflow and all ai-update-plan features. - ---- - -## CRITICAL! DOCUMENTATION-FIRST APPROACH - -**BEFORE implementing ANY task, research existing solutions!** - -1. Check for MCP tools (mcp__docs__, mcp__context7__) -2. Fetch official documentation with WebFetch -3. Search for recent tutorials with WebSearch -4. Verify no built-in solution exists - -**Never reinvent the wheel. Always check documentation first.** - -See `AI_DOCS/documentation-first-approach.md` for complete guidelines. - ---- - -## CRITICAL Code Conventions - -**See `AI_DOCS/code-conventions.md` for complete standards including:** -- No decorative emojis in any output -- AI summaries go in `.ai-summary/` directory -- No AI co-authoring in git commits -- Type hints required on all functions -- Formatter harmony (Black and Ruff must agree) - ---- - -## Overview - -> **Primary configuration file for Google Gemini Code Assist** -> -> This file (`.gemini/styleguide.md`) is used by Gemini Code Assist for code reviews. -> Teams can describe custom instructions here to tailor Gemini's code reviews to the repository's needs. - -**Primary Directive:** Write tests BEFORE code. Use TDD (Test-Driven Development) always. -**Secondary Directive:** Research documentation BEFORE writing any code. - -## Shared Documentation - -For complete guidelines, see these shared documents in the project: - -- `AI_DOCS/ai-tools.md` - Session management (MANDATORY workflow) -- `AI_DOCS/documentation-first-approach.md` - Research before implementation (MANDATORY) -- `AI_DOCS/ai-skills.md` - Specialized skills and agents (manual workflows) -- `AI_DOCS/tdd-workflow.md` - TDD process and testing standards -- `AI_DOCS/code-conventions.md` - Code style and best practices -- `AI_DOCS/project-context.md` - Tech stack and architecture - -**Note**: This file contains essential excerpts. For comprehensive details, read the files above. - -**Skills Available**: See `AI_DOCS/ai-skills.md` for test-generator, coverage-analyzer, quality-fixer, tdd-reviewer, and quality-enforcer workflows. - -## Core Responsibilities - -1. **Test-Driven Development** - Write failing tests first -2. **Quality First** - Run `make check` before completing tasks -3. **Real Code Over Mocks** - Minimize test fixtures and mocks -4. **Type Safety** - Add type hints to all functions (mypy strict mode) -5. **Documentation Sync** - Update all AI instruction files for critical changes - -See `AGENTS.md` for comprehensive universal instructions that apply to all AI agents. - -## Gemini-Specific TDD Workflow - -### Step-by-Step Process - -**User Request Example:** "Add a function to reverse a string" - -### Your Implementation: - -#### 1. First, Write the Test -```python -# File: tests/test_string_utils.py - -from python_modern_template.string_utils import reverse_string - -def test_reverse_string_basic() -> None: - """Test basic string reversal.""" - assert reverse_string("hello") == "olleh" - -def test_reverse_string_empty() -> None: - """Test reversing empty string.""" - assert reverse_string("") == "" - -def test_reverse_string_single_char() -> None: - """Test reversing single character.""" - assert reverse_string("a") == "a" - -def test_reverse_string_with_spaces() -> None: - """Test reversing string with spaces.""" - assert reverse_string("hello world") == "dlrow olleh" -``` - -#### 2. Run Tests (They Will Fail) -```bash -make test -# Expected: ImportError or ModuleNotFoundError -``` - -#### 3. Implement the Function -```python -# File: src/python_modern_template/string_utils.py - -def reverse_string(text: str) -> str: - """Reverse the given string. - - Args: - text: The string to reverse - - Returns: - The reversed string - """ - return text[::-1] -``` - -#### 4. Export from __init__.py -```python -# File: src/python_modern_template/__init__.py - -from .string_utils import reverse_string - -__all__ = [..., "reverse_string"] -``` - -#### 5. Run Tests (Should Pass Now) -```bash -make test -# All tests should pass -``` - -#### 6. Run Quality Checks -```bash -make check -# This runs: format → lint → test -# All must pass! -``` - -#### 7. Report to User -"Implemented `reverse_string` using TDD: -- ✅ Wrote 4 test cases first -- ✅ Tests failed initially (function didn't exist) -- ✅ Implemented function -- ✅ All tests now pass -- ✅ `make check` passes with 100% quality -- ✅ Handles edge cases: empty strings, single chars, spaces" - -## Don't Mock Internal Code - -### ❌ Bad Approach (Over-Mocking) -```python -from unittest.mock import patch - -@patch('python_modern_template.utils.helper_function') -def test_main_function(mock_helper): - """Testing with unnecessary mock.""" - mock_helper.return_value = "mocked" - result = main_function() - assert result == "mocked" -``` - -### ✅ Good Approach (Use Real Code) -```python -from python_modern_template.utils import helper_function -from python_modern_template.main import main_function - -def test_main_function() -> None: - """Testing with real helper function.""" - # Use actual implementation - result = main_function() - # Test against real behavior - assert isinstance(result, str) - assert len(result) > 0 -``` - -### When to Mock -Only mock: -- ✅ External APIs (HTTP requests) -- ✅ Database connections -- ✅ File system operations -- ✅ Current time/dates -- ✅ Random number generation -- ✅ Environment variables - -## Code Quality Standards - -### Type Hints Required -```python -# ✅ Correct - all types specified -def process_data( - input_str: str, - options: dict[str, Any] | None = None, - max_length: int = 100, -) -> list[str]: - """Process input data with options.""" - ... - -# ❌ Wrong - no type hints -def process_data(input_str, options=None, max_length=100): - ... -``` - -### Formatting Standards -- **Line length**: 88 characters (Black) -- **Imports**: Sorted with isort -- **Quotes**: Double quotes preferred -- **Docstrings**: Google style -- **Formatter harmony**: Write code patterns that keep Black and Ruff aligned (move - long assertion/log messages into variables instead of relying on multi-line wrapping) - -### Quality Checks -```bash -# Run before finishing ANY task -make check - -# Individual checks -make format # Black + isort -make lint # Ruff + mypy + Pylint -make test # Pytest with coverage -make coverage # Detailed coverage report -``` - -## Coverage Requirements - -- **Minimum**: 80% (enforced by pytest) -- **Target**: 90%+ -- **Ideal**: 100% for new code - -### Check Coverage -```bash -make coverage -# Review terminal output and htmlcov/index.html -``` - -### If Coverage Low -Add tests for uncovered lines: -```python -def test_edge_case_branch() -> None: - """Test the specific branch that wasn't covered.""" - # Test the specific condition - result = function_under_test(edge_case_input) - assert result == expected_for_edge_case -``` - -## Project Structure - -``` -src/python_modern_template/ - ├── __init__.py # Package exports - ├── main.py # CLI implementation - └── [modules].py # Feature modules - -tests/ - ├── conftest.py # Shared fixtures (minimal use) - ├── test_main.py # Tests for main.py - └── test_[module].py # Tests for each module -``` - -### Import Pattern -```python -# ✅ Correct -from python_modern_template import function_name - -# ❌ Wrong -from src.python_modern_template import function_name -``` - -## Keeping Documentation in Sync - -### When to Update All AI Instruction Files - -Update these files together for critical changes: -- `.cursorrules` -- `AGENTS.md` -- `.claude/INSTRUCTIONS.md` -- `GEMINI.md` (this file) -- `.aider.conf.yml` -- `COPILOT_INSTRUCTIONS.md` - -**Critical changes:** -- New testing patterns -- Build/deploy process changes -- Security requirements -- Architecture decisions -- Code quality rules - -### Validation -```bash -make validate-ai-docs -``` - -## Available Commands - -```bash -# Setup -make install # Install deps + pre-commit hooks -uv pip install -e . # Install package in editable mode - -# Development -make test # Run tests -make coverage # Tests with coverage report -make format # Auto-format (Black + isort) -make lint # Lint (Ruff + mypy + Pylint) -make check # Complete quality check ⭐ - -# Maintenance -make clean # Remove generated files -make build # Build distribution package - -# Help -make help # Show all commands -``` - -## Pre-Commit Checklist - -Before saying "task complete", verify: - -- [ ] Wrote tests FIRST (TDD) -- [ ] Tests initially failed -- [ ] Implementation makes tests pass -- [ ] Used real code (not mocks) where possible -- [ ] Type hints on all functions -- [ ] Docstrings on public functions -- [ ] `make test` passes -- [ ] Coverage ≥ 80% -- [ ] `make check` passes -- [ ] No duplicate code (DRY) -- [ ] README updated (if needed) -- [ ] AI docs synced (if critical change) - -## Security - -- Never commit secrets/credentials -- Use environment variables for config -- CI runs Bandit + Safety automatically -- Fix security warnings immediately - -## Best Practices for Gemini - -### Small, Focused Commits -Each feature should: -1. Have tests written first -2. Implement minimal code to pass tests -3. Pass all quality checks -4. Be a logical unit of work - -### Communicate Clearly -```markdown -**Implementing [Feature] with TDD:** - -1. ✅ Writing tests first... - - test_basic_case - - test_edge_case_1 - - test_edge_case_2 - -2. ✅ Tests fail (as expected - function doesn't exist) - -3. ✅ Implementing function... - -4. ✅ Tests now pass - -5. ✅ Running make check... - - Format: PASS - - Lint: PASS - - Tests: PASS (95% coverage) - -**Task complete!** All quality gates passed. -``` - -### Handle Errors Gracefully -If `make check` fails: -```markdown -**Issue found during quality check:** -- Pylint: Unused variable on line 45 -- Coverage: 78% (below 80% minimum) - -**Fixing:** -1. Removed unused variable -2. Added tests for uncovered branch - -**Re-running make check:** ✅ All pass -``` - -## Example Complete Flow - -**User:** "Add validation for phone numbers" - -**Gemini Response:** - -"I'll implement phone number validation using TDD. Writing tests first..." - -```python -# Step 1: tests/test_validators.py -import pytest -from python_modern_template.validators import validate_phone - -class TestPhoneValidation: - """Test phone number validation.""" - - @pytest.mark.parametrize( - "phone,expected", - [ - ("123-456-7890", True), - ("(123) 456-7890", True), - ("1234567890", True), - ("123-456-789", False), # Too short - ("abc-def-ghij", False), # Non-numeric - ("", False), # Empty - ], - ) - def test_phone_formats(self, phone: str, expected: bool) -> None: - """Test various phone number formats.""" - assert validate_phone(phone) == expected -``` - -"Running tests - they fail as expected..." -```bash -make test -# ImportError: cannot import name 'validate_phone' -``` - -"Implementing function..." -```python -# src/python_modern_template/validators.py -import re - -def validate_phone(phone: str) -> bool: - """Validate a US phone number. - - Args: - phone: Phone number to validate - - Returns: - True if valid, False otherwise - """ - # Remove formatting characters - digits = re.sub(r'[^0-9]', '', phone) - - # Check if exactly 10 digits - return len(digits) == 10 -``` - -"Running tests..." -```bash -make test -# ✅ All 6 tests pass -``` - -"Running complete quality check..." -```bash -make check -# ✅ Format: PASS -# ✅ Lint: PASS (Pylint 10/10) -# ✅ Tests: PASS (coverage 92%) -``` - -"**Phone validation implemented successfully:** -- ✅ Wrote 6 parametrized tests first (TDD) -- ✅ Tests failed initially -- ✅ Implemented validation function -- ✅ All tests pass -- ✅ `make check` passes -- ✅ Handles multiple formats and edge cases -- ✅ Coverage: 92%" - -## Additional Resources - -- **Universal guidelines**: `AGENTS.md` -- **Cursor-specific**: `.cursorrules` -- **Claude-specific**: `.claude/INSTRUCTIONS.md` -- **Aider-specific**: `.aider.conf.yml` -- **Copilot-specific**: `COPILOT_INSTRUCTIONS.md` - ---- - -**Required for all tasks:** Write tests first, run `make check` before completing, use real code instead of mocks. diff --git a/template/.github/copilot-instructions.md b/template/.github/copilot-instructions.md deleted file mode 100644 index 9434b58..0000000 --- a/template/.github/copilot-instructions.md +++ /dev/null @@ -1,394 +0,0 @@ -# GitHub Copilot Repository Instructions - - - - - - - -## STOP! READ THIS FIRST - MANDATORY SESSION MANAGEMENT - -**User MUST run this command BEFORE starting ANY work:** - -```bash -uv run ai-start-task "Task description" -``` - -**If user has NOT run this command yet, STOP and remind them to run it NOW!** - -This is NOT optional. Every Copilot session MUST start with `ai-start-task`. - -**During work:** -```bash -uv run ai-log "Progress message" -uv run ai-update-plan "Completed item" - -# Customize your plan (add task-specific steps, remove irrelevant items) -uv run ai-update-plan --add "Specific task for this feature" --phase "Phase 2" -uv run ai-update-plan --remove "Generic irrelevant item" -uv run ai-update-plan --rename "Generic item" --to "Specific detailed item" -``` - -**When finishing:** -```bash -uv run ai-finish-task --summary="What was accomplished" -``` - -See `AI_DOCS/ai-tools.md` for complete workflow and all ai-update-plan features. - ---- - -## CRITICAL! DOCUMENTATION-FIRST APPROACH - -**BEFORE implementing ANY task, research existing solutions!** - -1. Check for MCP tools (mcp__docs__, mcp__context7__) -2. Fetch official documentation with WebFetch -3. Search for recent tutorials with WebSearch -4. Verify no built-in solution exists - -**Never reinvent the wheel. Always check documentation first.** - -See `AI_DOCS/documentation-first-approach.md` for complete guidelines. - ---- - -## CRITICAL Code Conventions - -**See `AI_DOCS/code-conventions.md` for complete standards including:** -- No decorative emojis in any output -- AI summaries go in `.ai-summary/` directory -- No AI co-authoring in git commits -- Type hints required on all functions -- Formatter harmony (Black and Ruff must agree) - ---- - -## Overview - -> **Primary configuration file for GitHub Copilot** -> -> This file (`.github/copilot-instructions.md`) is read by GitHub Copilot on every chat or agent request. -> It provides repository-wide instructions in natural language using Markdown format. - -**Primary Directive:** ALWAYS write tests BEFORE implementation code (Test-Driven Development). -**Secondary Directive:** ALWAYS research documentation BEFORE writing any code. - -## Shared Documentation - -For complete guidelines, see these shared documents in the project: - -- `AI_DOCS/ai-tools.md` - Session management (MANDATORY workflow) -- `AI_DOCS/documentation-first-approach.md` - Research before implementation (MANDATORY) -- `AI_DOCS/ai-skills.md` - Specialized skills and agents (manual workflows) -- `AI_DOCS/tdd-workflow.md` - TDD process and testing standards -- `AI_DOCS/code-conventions.md` - Code style and best practices -- `AI_DOCS/project-context.md` - Tech stack and architecture - -**Note**: This file contains essential excerpts. For comprehensive details, read the files above. - -**Skills Available**: See `AI_DOCS/ai-skills.md` for test-generator, coverage-analyzer, quality-fixer, tdd-reviewer, and quality-enforcer workflows. - -## Quick Reference - -| What | Requirement | -|------|-------------| -| **Documentation Research** | MANDATORY - Check MCP tools, fetch docs, search tutorials BEFORE coding | -| **Testing** | Write tests FIRST, TDD always | -| **Mocking** | Minimize - use real code when possible | -| **Coverage** | Minimum 80%, aim for 90%+ | -| **Quality** | Run `make check` before pushing | -| **Types** | Type hints required (mypy strict) | -| **Style** | Black (88 chars) + isort + Ruff + Pylint 10/10 | -| **Formatter Harmony** | Let Black shape layout; refactor patterns so Ruff agrees | - -## TDD Workflow with Copilot - -### When Copilot Suggests Code - -Copilot will naturally suggest implementation code, but you should: - -1. **Ignore implementation suggestions initially** -2. **Ask Copilot to suggest tests first** -3. **Write tests** -4. **Then accept implementation suggestions** - -### Example Flow - -**❌ Don't Do This:** -```python -# You start typing in src/python_modern_template/math_utils.py -def factorial(n): # Copilot suggests implementation immediately - if n == 0: - return 1 - return n * factorial(n - 1) -``` - -**✅ Do This Instead:** -```python -# Start in tests/test_math_utils.py FIRST -def test_factorial_base_case() -> None: - """Test factorial of 0.""" - result = factorial(0) - assert result == 1 - -def test_factorial_positive() -> None: - """Test factorial of positive number.""" - result = factorial(5) - assert result == 120 - -# NOW go to src/python_modern_template/math_utils.py -def factorial(n: int) -> int: # Now accept Copilot's implementation - """Calculate factorial of n.""" - if n == 0: - return 1 - return n * factorial(n - 1) -``` - -## Using Copilot Comments for TDD - -Guide Copilot with comments to generate tests first: - -```python -# Test: function should reverse a string -# Input: "hello" -# Expected: "olleh" -def test_reverse_string_basic() -> None: - # Copilot will suggest the test body - result = reverse_string("hello") - assert result == "olleh" - -# Test: function should handle empty strings -def test_reverse_string_empty() -> None: - result = reverse_string("") - assert result == "" -``` - -## Keep Black and Ruff in Sync - -- Prefer explicit code constructs that both formatters accept. For long - assertion or log messages, assign the string to a local variable instead of - relying on multi-line wrapping. -- After Copilot-generated changes, run `pre-commit run --files …` (or - `make format`) before staging to verify formatter agreement. -- If the same lines keep getting reformatted, adjust the code rather than - fighting the tools—clarify the intent so both Black and Ruff produce identical - output. - -## Minimize Mocks - Use Real Code - -### ✅ Preferred (Real Code) -```python -from python_modern_template.processor import process_data - -def test_process_data() -> None: - """Test with real data.""" - real_input = "test string" - result = process_data(real_input) - assert result == expected_value -``` - -### ❌ Avoid Unless Necessary (Mocks) -```python -# Only mock external dependencies -from unittest.mock import patch - -@patch('requests.get') # OK - external API -def test_api_call(mock_get): - ... - -# Don't mock internal functions -@patch('python_modern_template.utils.helper') # Bad - use real helper -``` - -**When to Mock:** -- HTTP requests (external APIs) -- Database connections -- File system writes -- Time/date operations (`datetime.now()`) -- Random number generation - -**When NOT to Mock:** -- Internal project functions -- Pure functions -- Simple data transformations -- Business logic - -See `AI_DOCS/tdd-workflow.md` for complete mocking guidelines. - -## Quality Checks - -### Before Any Commit - -```bash -make check # Run ALL quality checks -``` - -This runs: -1. `make format` - Black + isort formatting -2. `make lint` - Ruff + mypy + Pylint -3. `make test` - Full test suite with coverage - -**Never commit if `make check` fails!** - -### Coverage Requirements - -- **Minimum**: 80% (enforced) -- **Target**: 90%+ -- **Ideal**: 100% for new code - -```bash -make coverage # Check coverage -``` - -## Code Standards - -### Type Hints (Required) - -```python -# ✅ Correct -def process_data(input: str, count: int = 5) -> dict[str, int]: - """Process the input data.""" - return {"result": len(input) * count} - -# ❌ Wrong - no type hints -def process_data(input, count=5): - return {"result": len(input) * count} -``` - -### Imports - -```python -# ✅ Correct - import from package name -from python_modern_template import function_name - -# ❌ Wrong - don't use src prefix -from src.python_modern_template import function_name -``` - -### Docstrings (Google Style) - -```python -def public_function(param: str) -> int: - """Brief one-line description. - - More detailed explanation if needed. - - Args: - param: Description of parameter - - Returns: - Description of return value - - Raises: - ValueError: When param is invalid - """ -``` - -See `AI_DOCS/code-conventions.md` for complete code conventions. - -## Project Structure - -``` -src/python_modern_template/ # Implementation code -tests/ # Test files mirror src structure -AI_DOCS/ # Shared AI documentation - ├── tdd-workflow.md # TDD process - ├── ai-tools.md # Session management - ├── code-conventions.md # Code standards - └── project-context.md # Architecture -``` - -See `AI_DOCS/project-context.md` for complete project architecture. - -## Development Workflow - -### Complete TDD Cycle - -1. **Write failing test** for new feature/fix -2. **Run tests** to confirm they fail: `make test` -3. **Implement** minimal code to make test pass -4. **Run tests** again to confirm they pass -5. **Refactor** if needed -6. **Run make check** to ensure quality -7. **Commit** if all checks pass - -### Example with Copilot - -```bash -# 1. User describes feature: "Add email validation" - -# 2. You (with Copilot): Open tests/test_validators.py -# Write test comments to guide Copilot: -# Test: validate_email should accept valid emails -# Test: validate_email should reject invalid emails - -# 3. Let Copilot suggest test implementations - -# 4. Run tests (should fail) -make test - -# 5. Open src/python_modern_template/validators.py -# Let Copilot suggest implementation - -# 6. Run tests (should pass) -make test - -# 7. Run quality check -make check - -# 8. Commit if all pass -git commit -m "Add email validation with tests" -``` - -## Quality Gates - -Before committing code, ensure: - -1. ✅ Tests written FIRST (TDD) -2. ✅ All tests pass (`make test`) -3. ✅ Coverage ≥ 80% (`make coverage`) -4. ✅ Formatted (Black + isort via `make format`) -5. ✅ Linted (Ruff + mypy + Pylint via `make lint`) -6. ✅ `make check` passes -7. ✅ Type hints everywhere -8. ✅ No duplicate code (DRY) - -## Required Development Workflow - -Follow this workflow for every code change: - -1. Write tests first (TDD approach) -2. Use real code/data instead of mocks when possible -3. Run `make check` after every change -4. Add type hints to all functions -5. Maintain coverage above 80% -6. Use AI session tools (`ai-start-task`, `ai-finish-task`) - -## Complete Documentation - -For comprehensive guidelines: - -1. **AI_DOCS/ai-tools.md** - Session management (MANDATORY) -2. **AI_DOCS/ai-skills.md** - Specialized skills and agents -3. **AI_DOCS/tdd-workflow.md** - TDD process with examples -4. **AI_DOCS/code-conventions.md** - Code standards -5. **AI_DOCS/project-context.md** - Architecture and tech stack -6. **AGENTS.md** - Universal AI agent instructions - -## Copilot Chat Commands - -``` -/explain - Explain code -/fix - Suggest fixes -/tests - Generate test cases (use this often!) -/doc - Add documentation -``` - -**Always use `/tests` to generate tests BEFORE implementing features!** - ---- - -**Remember**: Tests first, quality always. Use Copilot to accelerate TDD, not bypass it. - -**⚠️ This file requires manual synchronization when AI_DOCS/ changes** diff --git a/template/.github/workflows/ci.yml b/template/.github/workflows/ci.yml deleted file mode 100644 index a178e6c..0000000 --- a/template/.github/workflows/ci.yml +++ /dev/null @@ -1,137 +0,0 @@ -name: CI - -on: - push: - branches: [ main, develop ] - pull_request: - branches: [ main ] - workflow_dispatch: - -env: - PYTHON_VERSION: "3.13" - -jobs: - lint: - name: Lint Code - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Install uv - uses: astral-sh/setup-uv@v5 - with: - enable-cache: true - - - name: Set up Python - run: uv python install ${{ env.PYTHON_VERSION }} - - - name: Install dependencies - run: uv sync --all-extras --dev - - - name: Check Code Formatting - run: uv run quality-format --check - - - name: Lint Code - run: uv run quality-lint - - test: - name: Run Tests - runs-on: ubuntu-latest - strategy: - matrix: - python-version: ["3.11", "3.12", "3.13"] - - steps: - - uses: actions/checkout@v4 - - - name: Install uv - uses: astral-sh/setup-uv@v5 - with: - enable-cache: true - - - name: Set up Python ${{ matrix.python-version }} - run: uv python install ${{ matrix.python-version }} - - - name: Install dependencies - run: uv sync --all-extras --dev - - - name: Run tests with coverage - run: uv run quality-test --coverage - - - name: Upload coverage to Codecov - if: matrix.python-version == '3.13' - uses: codecov/codecov-action@v5 - with: - file: ./coverage.xml - flags: unittests - name: codecov-umbrella - fail_ci_if_error: false - - build: - name: Build Package - runs-on: ubuntu-latest - needs: [lint, test] - - steps: - - uses: actions/checkout@v4 - - - name: Install uv - uses: astral-sh/setup-uv@v5 - with: - enable-cache: true - - - name: Set up Python - run: uv python install ${{ env.PYTHON_VERSION }} - - - name: Build package - run: uv build - - - name: Upload artifacts - uses: actions/upload-artifact@v4 - with: - name: dist - path: dist/ - - validate-ai-docs: - name: Validate AI Instructions - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - - name: Install uv - uses: astral-sh/setup-uv@v5 - with: - enable-cache: true - - - name: Set up Python - run: uv python install ${{ env.PYTHON_VERSION }} - - - name: Install dependencies - run: uv sync --all-extras --dev - - - name: Validate AI instruction files - run: uv run python scripts/validate_ai_instructions.py - - security: - name: Security Scan - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - - name: Install uv - uses: astral-sh/setup-uv@v5 - with: - enable-cache: true - - - name: Set up Python - run: uv python install ${{ env.PYTHON_VERSION }} - - - name: Install dependencies - run: | - uv sync --all-extras --dev - uv add --dev bandit safety - - - name: Run security scans - run: uv run quality-security diff --git a/template/.github/workflows/test-template.yml b/template/.github/workflows/test-template.yml deleted file mode 100644 index aad898b..0000000 --- a/template/.github/workflows/test-template.yml +++ /dev/null @@ -1,111 +0,0 @@ -name: Test Template - -on: - push: - branches: [main, develop] - pull_request: - branches: [main] - workflow_dispatch: - -jobs: - test-configurations: - name: Test ${{ matrix.config-name }} - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - include: - - config-name: "minimal" - args: "--data include_quality_scripts=false --data include_ai_tools=false --data include_docker=false --data include_docs=false --data include_pre_commit=false" - - - config-name: "quality-only" - args: "--data include_quality_scripts=true --data include_ai_tools=false --data include_docker=false --data include_docs=false" - - - config-name: "ai-only" - args: "--data include_quality_scripts=false --data include_ai_tools=true --data include_docker=false --data include_docs=false" - - - config-name: "docker-only" - args: "--data include_quality_scripts=false --data include_ai_tools=false --data include_docker=true --data include_docs=false" - - - config-name: "full-features" - args: "--data include_quality_scripts=true --data include_ai_tools=true --data include_docker=true --data include_docs=true" - - steps: - - name: Checkout template - uses: actions/checkout@v4 - - - name: Set up Python - uses: actions/setup-python@v5 - with: - python-version: "3.13" - - - name: Install uv - uses: astral-sh/setup-uv@v3 - - - name: Install copier - run: uv tool install copier - - - name: Generate project from template - run: | - uv tool run copier copy \ - --trust \ - --defaults \ - ${{ matrix.args }} \ - . test-project - - - name: Install project dependencies - working-directory: test-project - run: uv sync --all-extras --dev - - - name: Run tests - working-directory: test-project - run: uv run pytest -v - - - name: Check project structure - working-directory: test-project - run: | - echo "=== Project Structure ===" - ls -la - echo "" - echo "=== Source Structure ===" - ls -la src/ - echo "" - echo "=== Tests Structure ===" - ls -la tests/ - - test-python-versions: - name: Test Python ${{ matrix.python-version }} - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - python-version: ["3.11", "3.12", "3.13"] - - steps: - - name: Checkout template - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Install uv - uses: astral-sh/setup-uv@v3 - - - name: Install copier - run: uv tool install copier - - - name: Generate project - run: | - uv tool run copier copy \ - --trust \ - --defaults \ - --data python_version="${{ matrix.python-version }}" \ - . test-project - - - name: Install and test - working-directory: test-project - run: | - uv sync --all-extras --dev - uv run pytest -v diff --git a/template/AGENTS.md.jinja b/template/AGENTS.md.jinja index 836880d..00f7c92 100644 --- a/template/AGENTS.md.jinja +++ b/template/AGENTS.md.jinja @@ -32,67 +32,20 @@ See `@AI_DOCS/ai-tools.md` for complete workflow and all ai-update-plan features --- -## CRITICAL! DOCUMENTATION-FIRST APPROACH - -**BEFORE implementing ANY task, you MUST research existing solutions and documentation!** - -This is NOT optional. You MUST: - -1. **Check for MCP Tools First** - - Look for `mcp__docs__`, `mcp__context7__`, or framework-specific MCP tools - - Use them to fetch latest documentation - -2. **Fetch Official Documentation** - - Use WebFetch from official docs (docs.framework.com) - - Search for built-in tools and features - - Read API references and getting started guides - -3. **Search for Recent Tutorials** - - Use WebSearch for 2024-2025 tutorials and examples - - Look for official framework tutorials - - Find existing integration patterns - -4. **Verify No Built-In Solution Exists** - - Check if framework provides the functionality - - Look for official integrations - - Confirm custom code is actually needed - -**Why This Matters:** - -❌ **DON'T** reinvent the wheel: -- Don't reverse-engineer documentation sites -- Don't manually implement APIs when SDK exists -- Don't create custom code when built-in tools are available -- Don't over-engineer simple tasks - -✅ **DO** discover and use existing solutions: -- Use MCP tools to fetch documentation -- Read official framework docs -- Leverage built-in tools and integrations -- Follow framework best practices - -See `@AI_DOCS/documentation-first-approach.md` for complete guidelines and examples. - ---- - ## Overview **Universal instructions for all AI coding assistants working on this project** **Primary Directive:** ALWAYS write tests BEFORE implementation code (Test-Driven Development). -**Secondary Directive:** ALWAYS research documentation BEFORE writing any code. ## Shared Documentation For comprehensive guidelines, reference these shared documents: - **@AI_DOCS/ai-tools.md** - AI session management tools (MANDATORY workflow) -- **@AI_DOCS/documentation-first-approach.md** - Research before implementation (MANDATORY) -- **@AI_DOCS/ai-skills.md** - Specialized skills and agents for quality and testing - **@AI_DOCS/tdd-workflow.md** - Test-Driven Development process and testing standards - **@AI_DOCS/code-conventions.md** - Code style, formatting, and best practices - **@AI_DOCS/project-context.md** - Tech stack, architecture, and project structure -- **@AI_DOCS/documentation-sync-rules.md** - AI doc synchronization (MANDATORY) ## Quick Reference @@ -100,7 +53,6 @@ For comprehensive guidelines, reference these shared documents: |--------|-------------| | **Session Management** | Use `ai-start-task` before starting, `ai-finish-task` when done | | **Progress Tracking** | Log all important steps with `ai-log` | -| **Documentation Research** | MANDATORY - Check MCP tools, fetch docs, search tutorials BEFORE coding | | **Development Approach** | Test-Driven Development (TDD) - Tests First! | | **Minimum Coverage** | 80% (enforced by pytest) | | **Mocks/Fixtures** | Minimize - use real code when possible | diff --git a/template/AI_DOCS/README.md.jinja b/template/AI_DOCS/README.md.jinja index 17d5da2..cb9685c 100644 --- a/template/AI_DOCS/README.md.jinja +++ b/template/AI_DOCS/README.md.jinja @@ -9,7 +9,6 @@ This directory contains shared documentation referenced by all AI tool configura | File | Purpose | Who Uses It | |------|---------|-------------| | **ai-tools.md** | AI session management workflow (MANDATORY for all agents) | All AI tools | -| **documentation-first-approach.md** | Research and discover before implementation (MANDATORY for all agents) | All AI tools | | **ai-skills.md** | Specialized skills and agents (test-generator, coverage-analyzer, quality-fixer, tdd-reviewer, quality-enforcer) | All AI tools | | **tdd-workflow.md** | Test-Driven Development process, testing standards, coverage requirements | All AI tools | | **code-conventions.md** | Code style, formatting, best practices, documentation standards | All AI tools | @@ -120,13 +119,12 @@ Content that is **unique to each tool**: **Always read these first**: ``` -@AI_DOCS/ai-tools.md # Session management (MANDATORY) -@AI_DOCS/documentation-first-approach.md # Research before implementation (MANDATORY) -@AI_DOCS/documentation-sync-rules.md # Doc sync golden rule (MANDATORY) -@AI_DOCS/ai-skills.md # Specialized skills and agents -@AI_DOCS/tdd-workflow.md # TDD process -@AI_DOCS/code-conventions.md # Code standards -@AI_DOCS/project-context.md # Architecture +@AI_DOCS/ai-tools.md # Session management (MANDATORY) +@AI_DOCS/documentation-sync-rules.md # Doc sync golden rule (MANDATORY) +@AI_DOCS/ai-skills.md # Specialized skills and agents +@AI_DOCS/tdd-workflow.md # TDD process +@AI_DOCS/code-conventions.md # Code standards +@AI_DOCS/project-context.md # Architecture ``` Then read your tool-specific config: diff --git a/template/AI_DOCS/ai-tools.md.jinja b/template/AI_DOCS/ai-tools.md.jinja index 81cb4d6..d9876b0 100644 --- a/template/AI_DOCS/ai-tools.md.jinja +++ b/template/AI_DOCS/ai-tools.md.jinja @@ -22,34 +22,6 @@ uv run ai-finish-task --summary="What you accomplished" **This is NOT optional!** Every AI agent must follow this workflow. -## 🚨 MANDATORY: Documentation-First Approach - -**BEFORE implementing any task, MUST research existing solutions!** - -```bash -# STEP 1: Check for MCP tools -# Look for mcp__docs__, mcp__context7__, etc. - -# STEP 2: Fetch official documentation -WebFetch: url="https://docs.framework.com/api" prompt="What tools exist for [task]?" - -# STEP 3: Search for recent tutorials -WebSearch: query="framework [specific-feature] tutorial 2025" - -# STEP 4: Verify no built-in solution exists -# Only write custom code after confirming no existing solution -``` - -**Critical Rules:** -- ❌ NEVER start coding without researching documentation first -- ❌ NEVER reinvent functionality that already exists in frameworks -- ❌ NEVER reverse-engineer when official docs are available -- ✅ ALWAYS use MCP tools to fetch latest documentation -- ✅ ALWAYS check for built-in framework tools before custom code -- ✅ ALWAYS leverage official integrations and SDKs - -See `@AI_DOCS/documentation-first-approach.md` for complete guidelines and examples. - ## 📚 All Available Tools | Tool | Purpose | When to Use | @@ -664,13 +636,10 @@ uv run ai-finish-task --summary="Added phone validation with 6 tests, 100% cover ## ⚠️ Critical Rules 1. **ALWAYS** run `ai-start-task` before ANY work -2. **ALWAYS** research documentation before implementing (see `@AI_DOCS/documentation-first-approach.md`) -3. **ALWAYS** check for MCP tools and use WebFetch/WebSearch before coding -4. **ALWAYS** run `ai-finish-task` when complete -5. **NEVER** skip `ai-log` for important milestones -6. **ALWAYS** check `ai-context-summary` if unsure what to do -7. **NEVER** start a task without checking for conflicts first -8. **NEVER** reinvent functionality that already exists in frameworks +2. **ALWAYS** run `ai-finish-task` when complete +3. **NEVER** skip `ai-log` for important milestones +4. **ALWAYS** check `ai-context-summary` if unsure what to do +5. **NEVER** start a task without checking for conflicts first ## 📂 Context Files Location diff --git a/template/AI_DOCS/documentation-first-approach.md.jinja b/template/AI_DOCS/documentation-first-approach.md.jinja deleted file mode 100644 index 1c889c1..0000000 --- a/template/AI_DOCS/documentation-first-approach.md.jinja +++ /dev/null @@ -1,392 +0,0 @@ -# Documentation-First Approach - -> **Shared documentation for all AI coding assistants** -> -> This file is referenced by multiple AI tool configurations. Changes here automatically apply to all tools that support file references. - -## 🚨 CRITICAL: Research Before Implementation - -**Before implementing ANY task, you MUST research and discover existing solutions, tools, and documentation.** - -This is NOT optional. Every AI agent must follow this workflow to avoid over-engineering and reinventing the wheel. - -## ❌ Common Anti-Pattern (DO NOT DO THIS) - -**Bad Example:** User asks to "create an Agno app to fetch latest 2 stories of HackerNews" - -**What NOT to do:** -1. ❌ View source of docs.agno.com to reverse-engineer the API -2. ❌ Go to news.ycombinator.com to see which API is called -3. ❌ Manually call HackerNews API with custom code -4. ❌ Reinvent functionality that already exists in the framework - -**Why this is wrong:** -- Wastes time reverse-engineering when docs are available -- Misses existing tools/utilities provided by the framework -- Creates unnecessary custom code instead of using built-in features -- Over-engineers simple tasks - -## ✅ Correct Pattern: Documentation-First Workflow - -### Phase 1: Discover MCP Tools (ALWAYS FIRST) - -**MCP (Model Context Protocol) tools provide access to documentation, APIs, and utilities.** - -```bash -# Check if MCP tools are available -# Look for tools starting with "mcp__" -``` - -**What to look for:** -- Documentation fetch tools (mcp__docs__, mcp__context7__) -- API integration tools -- Framework-specific utilities -- Code search and exploration tools - -**Example:** -```bash -# ✅ Good: Use MCP to fetch Agno documentation -mcp__docs__fetch "agno hackernews tools" -# OR -mcp__context7__search "agno hackernews integration" -``` - -### Phase 2: Fetch Latest Documentation - -**ALWAYS get the latest official documentation before implementing.** - -**Priority order:** -1. **Official MCP documentation tools** (if available) -2. **WebFetch from official docs** (docs.framework.com) -3. **WebSearch for official tutorials** (framework.com/tutorials) -4. **WebSearch for recent examples** (2024-2025 only) - -**What to fetch:** -- Official API reference -- Getting started guides -- Framework-specific tools/utilities -- Best practices and patterns -- Example code and tutorials - -**Example:** -```bash -# ✅ Good: Fetch official Agno documentation -WebFetch: url="https://docs.agno.com/tools/hackernews" prompt="What HackerNews tools are available in Agno?" - -# ✅ Good: Search for recent tutorials -WebSearch: query="Agno HackerNews integration tutorial 2025" -``` - -### Phase 3: Search for Built-In Tools/Features - -**Before writing custom code, check if the framework already provides the functionality.** - -**What to check:** -- Built-in tools and utilities -- Official integrations -- Standard library functions -- Framework plugins/extensions - -**Example:** -```bash -# ✅ Good: Check Agno docs for built-in HackerNews tools -WebFetch: url="https://docs.agno.com/api-reference/tools" prompt="Does Agno provide built-in HackerNews tools?" -``` - -### Phase 4: Implement with Discovered Resources - -**Only after completing research, implement using the best available approach.** - -**Decision tree:** -1. **Built-in tool exists?** → Use it directly -2. **Official integration exists?** → Use official integration -3. **Standard pattern exists?** → Follow the pattern -4. **No existing solution?** → Implement custom (but verify first!) - -## 🎯 Complete Example: The Right Way - -**Task:** "Create an Agno app to fetch latest 2 stories of HackerNews" - -### Step 1: Check for MCP Tools - -```bash -# Check available MCP tools -# Look for documentation fetch capabilities -``` - -### Step 2: Fetch Agno Documentation - -```bash -# Use MCP if available -mcp__docs__fetch "agno hackernews" - -# OR use WebFetch from official docs -WebFetch: url="https://docs.agno.com/tools" prompt="What tools are available in Agno for fetching data from external APIs? Specifically, are there HackerNews-related tools?" - -# Search for tutorials -WebSearch: query="Agno framework HackerNews integration example 2025" -``` - -### Step 3: Analyze Documentation - -**From Agno docs, you discover:** -- Agno has built-in `hackernews_tools` module -- Provides `get_top_stories()` function -- Handles API calls automatically -- Includes error handling and rate limiting - -### Step 4: Implement Using Built-In Tools - -```python -# ✅ Good: Use built-in Agno HackerNews tools -from agno.tools import hackernews_tools - -app = Agno( - name="hn-fetcher", - tools=[hackernews_tools.get_top_stories] -) - -# Fetch 2 stories using built-in functionality -stories = app.run("Get the top 2 stories from HackerNews") -``` - -**NOT:** -```python -# ❌ Bad: Custom implementation ignoring built-in tools -import requests - -def fetch_hackernews(): - response = requests.get("https://hacker-news.firebaseio.com/v0/topstories.json") - # ... custom parsing and error handling ... -``` - -## 📋 Mandatory Pre-Implementation Checklist - -Before writing ANY implementation code: - -- [ ] **MCP Tools Checked**: Looked for relevant MCP documentation tools -- [ ] **Official Docs Fetched**: Retrieved latest documentation from official sources -- [ ] **Built-In Features Verified**: Confirmed no existing functionality covers this use case -- [ ] **Recent Tutorials Reviewed**: Checked for 2024-2025 examples and best practices -- [ ] **Framework Tools Discovered**: Identified all relevant framework-provided utilities -- [ ] **API Documentation Read**: Reviewed official API reference (if applicable) -- [ ] **Implementation Plan**: Documented approach based on discovered resources - -## 🛠️ Tools for Documentation Discovery - -### 1. MCP Tools (Highest Priority) - -**Available MCP tools typically start with `mcp__`:** -- `mcp__docs__*` - Documentation fetchers -- `mcp__context7__*` - Codebase context and documentation -- Framework-specific MCP tools - -**Usage:** -```bash -# Check available MCP tools -# Use them to fetch documentation before implementation -``` - -### 2. WebFetch (Official Documentation) - -**Use for:** -- Official framework documentation -- API references -- Getting started guides -- Best practices - -**Example:** -```bash -WebFetch: url="https://docs.framework.com/api-reference" prompt="What are the available tools and utilities for [specific task]?" -``` - -**Best practices:** -- Always use official documentation URLs (docs.framework.com) -- Ask specific questions in prompts -- Focus on discovering existing functionality -- Check multiple relevant documentation pages - -### 3. WebSearch (Tutorials and Examples) - -**Use for:** -- Recent tutorials and examples -- Community best practices -- Framework-specific patterns -- Problem-solving approaches - -**Example:** -```bash -WebSearch: query="framework-name specific-task tutorial 2025" -WebSearch: query="framework-name best practices integration 2024" -``` - -**Best practices:** -- Include year (2024-2025) for recent results -- Search for official tutorials first -- Look for framework-specific examples -- Prefer official sources over blog posts - -### 4. Codebase Search (Existing Patterns) - -**Use Grep/Glob to find:** -- Similar implementations in current codebase -- Existing patterns and conventions -- Import statements (what's already being used) - -**Example:** -```bash -Grep: pattern="import.*framework" output_mode="files_with_matches" -Grep: pattern="def.*similar_function" output_mode="content" -``` - -## 🎓 Learning from Mistakes - -### Real-World Example: Agno HackerNews Task - -**What Happened:** -An AI agent was asked to create an Agno app to fetch HackerNews stories. - -**Mistakes Made:** -1. Viewed page source of docs.agno.com (unnecessary reverse-engineering) -2. Went to news.ycombinator.com to inspect API calls -3. Manually implemented HackerNews API integration -4. Ignored Agno's built-in HackerNews tools - -**What Should Have Happened:** -1. Use MCP tools to fetch Agno documentation -2. Discover Agno has built-in HackerNews tools -3. Read official Agno docs for `hackernews_tools` -4. Implement using Agno's built-in functionality - -**Result:** -- Over-engineered solution -- Reinvented the wheel -- Missed simpler built-in approach -- Wasted development time - -### Lessons Learned - -**Always ask yourself:** -1. "Does this framework provide this functionality?" -2. "Have I checked the official documentation?" -3. "Are there MCP tools that can help me find answers?" -4. "Am I reinventing something that already exists?" - -**If you're not sure:** -- Search the documentation first -- Use MCP tools to fetch latest info -- Check for official integrations -- Look for recent tutorials - -## 🚀 Framework-Specific Examples - -### For Python Frameworks - -**Before implementing:** -```bash -# Check official docs -WebFetch: url="https://docs.python-framework.org/api" prompt="What utilities does this framework provide for [task]?" - -# Search for examples -WebSearch: query="python-framework [specific-feature] example 2025" - -# Check PyPI for related packages -WebSearch: query="python-framework official integrations" -``` - -### For JavaScript/Node.js Frameworks - -**Before implementing:** -```bash -# Check official docs -WebFetch: url="https://framework.dev/docs" prompt="What built-in tools are available for [task]?" - -# Search npm documentation -WebSearch: query="framework-name official packages npm" - -# Look for recent examples -WebSearch: query="framework-name integration tutorial 2024" -``` - -### For AI/ML Frameworks (Agno, LangChain, etc.) - -**Before implementing:** -```bash -# Check for built-in tools -WebFetch: url="https://docs.framework.ai/tools" prompt="What pre-built tools are available for [specific integration]?" - -# Look for official integrations -WebFetch: url="https://docs.framework.ai/integrations" prompt="Does this framework have official integration with [service]?" - -# Search for recent examples -WebSearch: query="framework-name [service] integration example 2025" -``` - -## 📊 Decision Matrix - -| Scenario | MCP Tools | WebFetch Docs | WebSearch | Custom Code | -|----------|-----------|---------------|-----------|-------------| -| Framework task | ✅ Check first | ✅ Yes | ✅ For examples | ❌ Last resort | -| API integration | ✅ Check first | ✅ Yes | ✅ For tutorials | ⚠️ Only if no built-in | -| Data processing | ✅ Check first | ✅ Check stdlib | ✅ For patterns | ⚠️ Prefer libraries | -| External service | ✅ Check first | ✅ Check integrations | ✅ For SDKs | ⚠️ Use official SDK | - -**Legend:** -- ✅ Yes - Always do this -- ⚠️ Conditional - Only if necessary -- ❌ No - Avoid if possible - -## 🎯 Success Criteria - -**You've followed documentation-first approach when:** -- ✅ Checked for MCP documentation tools before coding -- ✅ Fetched official documentation from authoritative sources -- ✅ Verified no built-in functionality exists -- ✅ Searched for recent tutorials and examples -- ✅ Used framework-provided tools when available -- ✅ Implemented the simplest solution based on research -- ✅ Can explain why custom code was necessary (if used) - -**Warning signs you're NOT following the approach:** -- ❌ Started coding immediately without research -- ❌ Reverse-engineered instead of reading docs -- ❌ Implemented custom solution without checking for built-ins -- ❌ Ignored MCP tools and documentation fetch capabilities -- ❌ Used outdated tutorials or examples -- ❌ Over-engineered when simple solution existed - -## 🔄 Integration with TDD Workflow - -**Documentation-first fits into TDD:** - -1. **Discover** (NEW STEP - BEFORE TDD) - - Check MCP tools for documentation - - Fetch official docs and tutorials - - Identify built-in functionality - - Plan implementation approach - -2. **Write Tests** (TDD Phase 1) - - Based on discovered API/tools - - Following framework patterns - - Using official examples as reference - -3. **Implement** (TDD Phase 2) - - Using discovered built-in tools - - Following framework conventions - - Leveraging official integrations - -4. **Refactor** (TDD Phase 3) - - Align with framework best practices - - Use framework utilities - - Follow discovered patterns - -## 📚 Reference Documentation - -**Also see:** -- `@AI_DOCS/ai-tools.md` - Session management workflow -- `@AI_DOCS/tdd-workflow.md` - Test-Driven Development process -- `@AI_DOCS/code-conventions.md` - Code style and standards - ---- - -**Remember:** Research first, implement second. Use MCP tools, fetch documentation, discover built-in functionality, then code. NEVER reinvent the wheel when official tools exist. diff --git a/template/CLAUDE.md.jinja b/template/CLAUDE.md.jinja index 6629c80..c720c9a 100644 --- a/template/CLAUDE.md.jinja +++ b/template/CLAUDE.md.jinja @@ -32,96 +32,33 @@ See `@AI_DOCS/ai-tools.md` for complete workflow and all ai-update-plan features --- -## CRITICAL! DOCUMENTATION-FIRST APPROACH - -**BEFORE implementing ANY task, you MUST research existing solutions and documentation!** - -This is NOT optional. You MUST: - -1. **Check for MCP Tools First** - - Look for `mcp__docs__`, `mcp__context7__`, or framework-specific MCP tools - - Use them to fetch latest documentation - -2. **Fetch Official Documentation** - - Use WebFetch from official docs (docs.framework.com) - - Search for built-in tools and features - - Read API references and getting started guides - -3. **Search for Recent Tutorials** - - Use WebSearch for 2024-2025 tutorials and examples - - Look for official framework tutorials - - Find existing integration patterns - -4. **Verify No Built-In Solution Exists** - - Check if framework provides the functionality - - Look for official integrations - - Confirm custom code is actually needed - -**Why This Matters:** - -❌ **DON'T** reinvent the wheel: -- Don't reverse-engineer documentation sites -- Don't manually implement APIs when SDK exists -- Don't create custom code when built-in tools are available -- Don't over-engineer simple tasks - -✅ **DO** discover and use existing solutions: -- Use MCP tools to fetch documentation -- Read official framework docs -- Leverage built-in tools and integrations -- Follow framework best practices - -**Example:** If asked to "create an Agno app to fetch HackerNews stories": -1. ✅ Use MCP to fetch Agno documentation -2. ✅ Discover Agno has built-in `hackernews_tools` -3. ✅ Use the built-in tools instead of custom API calls -4. ❌ Don't view page source or reverse-engineer APIs - -See `@AI_DOCS/documentation-first-approach.md` for complete guidelines and examples. - ---- - ## Overview You are Claude Code, working on a Python project with strict Test-Driven Development (TDD) and code quality standards. **Primary Directive:** ALWAYS write tests BEFORE implementation code. -**Secondary Directive:** ALWAYS research documentation BEFORE writing any code. ## Shared Documentation Reference these for complete guidelines: -- `@AI_DOCS/ai-tools.md` - Session management workflow (MANDATORY) -- `@AI_DOCS/documentation-first-approach.md` - Research before implementation (MANDATORY) -- `@AI_DOCS/ai-skills.md` - Specialized skills and agents (use via Skill/Task tools) +- `@AI_DOCS/ai-tools.md` - Session management workflow - `@AI_DOCS/tdd-workflow.md` - TDD process and testing standards - `@AI_DOCS/code-conventions.md` - Code style and best practices - `@AI_DOCS/project-context.md` - Tech stack and architecture -- `@AI_DOCS/documentation-sync-rules.md` - AI doc synchronization (MANDATORY) ## Claude-Specific Workflow ### Before Writing Any Code -**Phase 0: Documentation Discovery (MANDATORY FIRST STEP)** -1. Check for MCP tools (`mcp__docs__`, `mcp__context7__`, etc.) -2. Use WebFetch to get official documentation from framework -3. Use WebSearch for recent tutorials and examples (2024-2025) -4. Verify no built-in tools/features exist for the task -5. Document research findings before proceeding - -**Phase 1: TDD Preparation** -6. Read relevant files to understand current implementation -7. Check existing tests in `tests/` directory -8. Plan test cases needed (based on discovered patterns) - -**Phase 2: TDD Implementation** -9. **Write failing tests FIRST** -10. Run tests to confirm they fail -11. Implement minimal code to make tests pass (using discovered tools/patterns) -12. Refactor while keeping tests green -13. Run `make check` to ensure all quality gates pass +1. Read relevant files to understand current implementation +2. Check existing tests in `tests/` directory +3. Plan test cases needed +4. **Write failing tests FIRST** +5. Run tests to confirm they fail +6. Implement minimal code to make tests pass +7. Refactor while keeping tests green +8. Run `make check` to ensure all quality gates pass ### Using Claude Code Tools @@ -347,12 +284,6 @@ See `@AI_DOCS/code-conventions.md` for complete documentation standards. Before completing any task: -- [ ] **Documentation research completed** (MANDATORY) - - [ ] Checked for MCP tools and used them - - [ ] Fetched official framework documentation - - [ ] Searched for recent tutorials and examples - - [ ] Verified no built-in solution exists - - [ ] Documented research findings - [ ] Tests written BEFORE implementation - [ ] Tests initially failed (confirmed TDD) - [ ] Implementation makes tests pass @@ -368,13 +299,6 @@ Before completing any task: - [ ] README updated (if user-facing changes) - [ ] Formatter harmony check (Black vs Ruff) — adjust code (e.g., use message variables) if tools disagree -- [ ] **AI documentation synchronized** (MANDATORY) - - [ ] Run `uv run python src/{{ package_name }}/validate_ai_docs_sync.py` - - [ ] Update `.gemini/styleguide.md` if AI_DOCS changed (add sync date) - - [ ] Update `.github/copilot-instructions.md` if AI_DOCS changed (add sync date) - - [ ] Update `.claude/skills/` or `.claude/agents/` if relevant - - [ ] Update `template/AI_DOCS/` if changes should apply to new projects - - [ ] See `@AI_DOCS/documentation-sync-rules.md` for complete workflow ## Communication Style @@ -407,10 +331,8 @@ Re-running make check..." ## Reference **Shared documentation:** -- `@AI_DOCS/ai-tools.md` - Session management workflow -- `@AI_DOCS/documentation-first-approach.md` - Research before implementation (MANDATORY) -- `@AI_DOCS/ai-skills.md` - Specialized skills and agents - `@AI_DOCS/tdd-workflow.md` - TDD process, testing standards, coverage +- `@AI_DOCS/ai-tools.md` - Session management workflow - `@AI_DOCS/code-conventions.md` - Code style, formatting, best practices - `@AI_DOCS/project-context.md` - Tech stack, architecture, dependencies