diff --git a/.agent/memory/README.md b/.agent/memory/README.md index 11e37d3b..37b47ce1 100644 --- a/.agent/memory/README.md +++ b/.agent/memory/README.md @@ -1,21 +1,22 @@ -# memory Template Directory +# Memory Template Directory -**🔒 SECURITY NOTICE: This is a template directory only.** +**Security Notice: This is a template directory only.** -## 📍 **Actual Usage Location** +## Actual Usage Location Personal memory files should be stored in: `~/.agent/memory/` -## 🎯 **Purpose** +## Purpose This template directory: 1. **Documents the structure** for memory usage 2. **Provides examples** of how to organize persistent data 3. **Maintains framework completeness** without personal data +4. **Guides AI assistants** on preference tracking -## 🚀 **Usage** +## Usage ```bash # Use the personal directory for actual work @@ -34,7 +35,7 @@ echo "sonarcloud_project=marcusquinn_aidevops" > ~/.agent/memory/configurations/ echo "$(date): Successfully fixed 50 quality issues with bulk script" >> ~/.agent/memory/history/operations.log ``` -## 📁 **Recommended Structure** +## Recommended Structure ``` ~/.agent/memory/ @@ -42,10 +43,13 @@ echo "$(date): Successfully fixed 50 quality issues with bulk script" >> ~/.agen │ ├── quality-fixes.txt │ ├── deployment-patterns.txt │ └── troubleshooting.txt -├── preferences/ # User customizations -│ ├── user-settings.conf -│ ├── tool-preferences.txt -│ └── workflow-settings.conf +├── preferences/ # User customizations (see Developer Preferences below) +│ ├── coding-style.md +│ ├── tool-preferences.md +│ ├── workflow-settings.md +│ └── project-specific/ +│ ├── wordpress.md +│ └── nodejs.md ├── configurations/ # Configuration discoveries │ ├── quality-tools.conf │ ├── api-endpoints.conf @@ -56,20 +60,166 @@ echo "$(date): Successfully fixed 50 quality issues with bulk script" >> ~/.agen └── learning-notes.txt ``` -## 🔐 **Security Guidelines** +## Developer Preferences Memory + +### Purpose + +Maintain a consistent record of developer preferences across coding sessions to: + +- Ensure AI assistants provide assistance aligned with the developer's preferred style +- Reduce the need for developers to repeatedly explain their preferences +- Create a persistent context across tools and sessions + +### How AI Assistants Should Use Preferences + +1. **Before starting work**: Check `~/.agent/memory/preferences/` for relevant preferences +2. **During development**: Apply established preferences to suggestions and code +3. **When feedback is given**: Update preference files to record new preferences +4. **When switching projects**: Check for project-specific preference files + +### Preference Categories to Track + +#### Code Style Preferences + +```markdown +# ~/.agent/memory/preferences/coding-style.md + +## General +- Preferred indentation: [tabs/spaces, count] +- Line length limit: [80/100/120] +- Quote style: [single/double] + +## Language-Specific +### JavaScript/TypeScript +- Semicolons: [yes/no] +- Arrow functions: [preferred/when-appropriate] + +### Python +- Type hints: [always/public-only/never] +- Docstring style: [Google/NumPy/Sphinx] + +### PHP +- WordPress coding standards: [yes/no] +- PSR-12: [yes/no] +``` + +#### Documentation Preferences + +```markdown +# ~/.agent/memory/preferences/documentation.md + +## Code Comments +- Prefer: [minimal/moderate/extensive] +- JSDoc/PHPDoc: [always/public-only/never] + +## Project Documentation +- README format: [brief/comprehensive] +- Changelog style: [Keep a Changelog/custom] + +## AI Assistant Documentation +- Token-efficient: [yes/no] +- Reference external files: [yes/no] +``` + +#### Workflow Preferences + +```markdown +# ~/.agent/memory/preferences/workflow.md + +## Git +- Commit message style: [conventional/descriptive] +- Branch naming: [feature/issue-123/kebab-case] +- Squash commits: [yes/no] + +## Testing +- Test coverage minimum: [80%/90%/100%] +- TDD approach: [yes/no] + +## CI/CD +- Auto-fix on commit: [yes/no] +- Required checks: [list] +``` + +#### Tool Preferences + +```markdown +# ~/.agent/memory/preferences/tools.md + +## Editors/IDEs +- Primary: [VS Code/Cursor/etc] +- Extensions: [list relevant] + +## Terminal +- Shell: [zsh/bash/fish] +- Custom aliases: [note any that affect commands] + +## Environment +- Node.js manager: [nvm/n/fnm] +- Python manager: [pyenv/conda/system] +- Package managers: [npm/yarn/pnpm] +``` + +### Project-Specific Preferences + +For projects with unique requirements: + +```markdown +# ~/.agent/memory/preferences/project-specific/wordpress.md + +## WordPress Development +- Prefer simpler solutions over complex ones +- Follow WordPress coding standards +- Use OOP best practices +- Admin functionality in admin/lib/ +- Core functionality in includes/ +- Assets in /assets organized by admin folders +- Version updates require language file updates (POT/PO) + +## Plugin Release Process +- Create version branch from main +- Update all version references +- Run quality checks before merge +- Create GitHub tag and release +- Ensure readme.txt is updated (Git Updater uses main branch) +``` + +### Potential Issues to Track + +Document environment-specific issues that affect AI assistance: + +```markdown +# ~/.agent/memory/preferences/environment-issues.md + +## Terminal Customizations +- Non-standard prompt: [describe] +- Custom aliases that might confuse: [list] +- Shell integrations: [starship/oh-my-zsh/etc] + +## Multiple Runtime Versions +- Node.js versions: [list, note if Homebrew] +- Python versions: [list, note manager] +- PHP versions: [list] + +## Known Conflicts +- [Document any tool conflicts discovered] +``` + +## Security Guidelines - **Never store credentials** in memory files - **Use configuration references** instead of actual API keys -- **Keep sensitive data** in separate secure locations +- **Keep sensitive data** in separate secure locations (`~/.config/aidevops/mcp-env.sh`) - **Regular cleanup** of outdated information +- **No personal identifiable information** in shareable templates -## ⚠️ **Important** +## Important Reminders - **Never store personal data** in this template directory - **Use ~/.agent/memory/** for all actual operations - **This directory is version controlled** - keep it clean - **Respect privacy** - be mindful of what you store +- **Update preferences** when developer feedback indicates a change --- -**Generated by**: AI DevOps Framework Migration +**Generated by**: AI DevOps Framework **Personal Directory**: ~/.agent/memory/ diff --git a/.agent/scripts/quality-feedback-helper.sh b/.agent/scripts/quality-feedback-helper.sh new file mode 100755 index 00000000..629b5ebe --- /dev/null +++ b/.agent/scripts/quality-feedback-helper.sh @@ -0,0 +1,446 @@ +#!/usr/bin/env bash +# quality-feedback-helper.sh - Retrieve code quality feedback via GitHub API +# Consolidates feedback from Codacy, CodeRabbit, SonarCloud, CodeFactor, etc. +# +# Usage: +# quality-feedback-helper.sh [command] [options] +# +# Commands: +# status Show status of all quality checks for current commit/PR +# failed Show only failed checks with details +# annotations Get line-level annotations from all check runs +# codacy Get Codacy-specific feedback +# coderabbit Get CodeRabbit review comments +# sonar Get SonarCloud feedback +# watch Watch for check completion (polls every 30s) +# +# Examples: +# quality-feedback-helper.sh status +# quality-feedback-helper.sh failed --pr 4 +# quality-feedback-helper.sh annotations --commit abc123 +# quality-feedback-helper.sh watch --pr 4 + +set -euo pipefail + +# Colors for output +readonly RED='\033[0;31m' +readonly GREEN='\033[0;32m' +readonly YELLOW='\033[1;33m' +readonly BLUE='\033[0;34m' +readonly NC='\033[0m' # No Color + +# Get repository info +get_repo() { + local repo + repo="${GITHUB_REPOSITORY:-}" + if [[ -z "$repo" ]]; then + repo=$(gh repo view --json nameWithOwner -q .nameWithOwner 2>/dev/null) || { + echo "Error: Not in a GitHub repository or gh CLI not configured" >&2 + exit 1 + } + fi + echo "$repo" +} + +# Get commit SHA (from PR or current HEAD) +get_sha() { + local pr_number="${1:-}" + if [[ -n "$pr_number" ]]; then + gh pr view "$pr_number" --json headRefOid -q .headRefOid + else + git rev-parse HEAD + fi +} + +# Show status of all checks +cmd_status() { + local pr_number="${1:-}" + local repo + local sha + + repo=$(get_repo) + sha=$(get_sha "$pr_number") + + echo -e "${BLUE}=== Quality Check Status ===${NC}" + echo -e "Repository: ${repo}" + echo -e "Commit: ${sha:0:8}" + [[ -n "$pr_number" ]] && echo -e "PR: #${pr_number}" + echo "" + + gh api "repos/${repo}/commits/${sha}/check-runs" \ + --jq '.check_runs[] | "\(.conclusion // .status)\t\(.name)"' | \ + while IFS=$'\t' read -r conclusion name; do + case "$conclusion" in + success) + echo -e "${GREEN}✓${NC} ${name}" + ;; + failure|action_required) + echo -e "${RED}✗${NC} ${name}" + ;; + in_progress|queued|pending) + echo -e "${YELLOW}○${NC} ${name} (${conclusion})" + ;; + neutral|skipped) + echo -e "${BLUE}–${NC} ${name} (${conclusion})" + ;; + *) + echo -e "? ${name} (${conclusion:-unknown})" + ;; + esac + done | sort +} + +# Show only failed checks with details +cmd_failed() { + local pr_number="${1:-}" + local repo + local sha + + repo=$(get_repo) + sha=$(get_sha "$pr_number") + + echo -e "${RED}=== Failed Quality Checks ===${NC}" + echo -e "Commit: ${sha:0:8}" + echo "" + + local failed_count=0 + + while IFS=$'\t' read -r name summary url; do + ((failed_count++)) || true + echo -e "${RED}✗ ${name}${NC}" + [[ -n "$summary" && "$summary" != "null" ]] && echo " Summary: ${summary}" + [[ -n "$url" && "$url" != "null" ]] && echo " Details: ${url}" + echo "" + done < <(gh api "repos/${repo}/commits/${sha}/check-runs" \ + --jq '.check_runs[] | select(.conclusion == "failure" or .conclusion == "action_required") | "\(.name)\t\(.output.summary)\t\(.html_url)"') + + if [[ $failed_count -eq 0 ]]; then + echo -e "${GREEN}No failed checks!${NC}" + else + echo -e "${RED}Total failed: ${failed_count}${NC}" + fi +} + +# Get line-level annotations from all check runs +cmd_annotations() { + local pr_number="${1:-}" + local repo + local sha + + repo=$(get_repo) + sha=$(get_sha "$pr_number") + + echo -e "${BLUE}=== Annotations (Line-Level Issues) ===${NC}" + echo -e "Commit: ${sha:0:8}" + echo "" + + # Get all check run IDs + local check_ids + check_ids=$(gh api "repos/${repo}/commits/${sha}/check-runs" --jq '.check_runs[].id') + + local total_annotations=0 + + for check_id in $check_ids; do + local check_name + check_name=$(gh api "repos/${repo}/check-runs/${check_id}" --jq '.name') + + local annotations + annotations=$(gh api "repos/${repo}/check-runs/${check_id}/annotations" 2>/dev/null || echo "[]") + + local count + count=$(echo "$annotations" | jq 'length') + + if [[ "$count" -gt 0 ]]; then + echo -e "${YELLOW}--- ${check_name} (${count} annotations) ---${NC}" + echo "$annotations" | jq -r '.[] | " \(.path):\(.start_line) [\(.annotation_level)] \(.message)"' + echo "" + total_annotations=$((total_annotations + count)) + fi + done + + if [[ $total_annotations -eq 0 ]]; then + echo "No annotations found." + else + echo -e "${YELLOW}Total annotations: ${total_annotations}${NC}" + fi +} + +# Get Codacy-specific feedback +cmd_codacy() { + local pr_number="${1:-}" + local repo + local sha + + repo=$(get_repo) + sha=$(get_sha "$pr_number") + + echo -e "${BLUE}=== Codacy Feedback ===${NC}" + + local codacy_check + codacy_check=$(gh api "repos/${repo}/commits/${sha}/check-runs" \ + --jq '.check_runs[] | select(.app.slug == "codacy-production" or .name | contains("Codacy"))' 2>/dev/null) + + if [[ -z "$codacy_check" ]]; then + echo "No Codacy check found for this commit." + return + fi + + local conclusion + local summary + local url + local check_id + + conclusion=$(echo "$codacy_check" | jq -r '.conclusion // .status') + summary=$(echo "$codacy_check" | jq -r '.output.summary // "No summary"') + url=$(echo "$codacy_check" | jq -r '.html_url') + check_id=$(echo "$codacy_check" | jq -r '.id') + + echo "Status: ${conclusion}" + echo "Summary: ${summary}" + echo "Details: ${url}" + echo "" + + # Get annotations if available + local annotations + annotations=$(gh api "repos/${repo}/check-runs/${check_id}/annotations" 2>/dev/null || echo "[]") + local count + count=$(echo "$annotations" | jq 'length') + + if [[ "$count" -gt 0 ]]; then + echo -e "${YELLOW}Issues found:${NC}" + echo "$annotations" | jq -r '.[] | " \(.path):\(.start_line) [\(.annotation_level)] \(.message)"' + fi +} + +# Get CodeRabbit review comments +cmd_coderabbit() { + local pr_number="${1:-}" + local repo + + repo=$(get_repo) + + if [[ -z "$pr_number" ]]; then + pr_number=$(gh pr view --json number -q .number 2>/dev/null) || { + echo "Error: Please specify a PR number with --pr" >&2 + exit 1 + } + fi + + echo -e "${BLUE}=== CodeRabbit Review Comments ===${NC}" + echo -e "PR: #${pr_number}" + echo "" + + # Get review comments from CodeRabbit + local comments + comments=$(gh api "repos/${repo}/pulls/${pr_number}/comments" \ + --jq '[.[] | select(.user.login | contains("coderabbit"))]' 2>/dev/null || echo "[]") + + local count + count=$(echo "$comments" | jq 'length') + + if [[ "$count" -eq 0 ]]; then + echo "No CodeRabbit comments found." + + # Check for review body + local reviews + reviews=$(gh api "repos/${repo}/pulls/${pr_number}/reviews" \ + --jq '[.[] | select(.user.login | contains("coderabbit"))]' 2>/dev/null || echo "[]") + + local review_count + review_count=$(echo "$reviews" | jq 'length') + + if [[ "$review_count" -gt 0 ]]; then + echo "" + echo -e "${YELLOW}CodeRabbit Reviews:${NC}" + echo "$reviews" | jq -r '.[] | "State: \(.state)\n\(.body)\n---"' + fi + else + echo -e "${YELLOW}Inline Comments (${count}):${NC}" + echo "$comments" | jq -r '.[] | "\(.path):\(.line // .original_line)\n \(.body)\n"' + fi +} + +# Get SonarCloud feedback +cmd_sonar() { + local pr_number="${1:-}" + local repo + local sha + + repo=$(get_repo) + sha=$(get_sha "$pr_number") + + echo -e "${BLUE}=== SonarCloud Feedback ===${NC}" + + local sonar_check + sonar_check=$(gh api "repos/${repo}/commits/${sha}/check-runs" \ + --jq '.check_runs[] | select(.name | contains("SonarCloud") or .name | contains("sonar"))' 2>/dev/null) + + if [[ -z "$sonar_check" ]]; then + echo "No SonarCloud check found for this commit." + return + fi + + local conclusion + local summary + local details_url + + conclusion=$(echo "$sonar_check" | jq -r '.conclusion // .status') + summary=$(echo "$sonar_check" | jq -r '.output.summary // "No summary"') + details_url=$(echo "$sonar_check" | jq -r '.details_url // .html_url') + + echo "Status: ${conclusion}" + echo "Summary: ${summary}" + echo "Dashboard: ${details_url}" +} + +# Watch for check completion +cmd_watch() { + local pr_number="${1:-}" + local repo + local sha + local interval="${2:-30}" + + repo=$(get_repo) + sha=$(get_sha "$pr_number") + + echo -e "${BLUE}=== Watching Quality Checks ===${NC}" + echo -e "Commit: ${sha:0:8}" + echo -e "Polling every ${interval} seconds..." + echo "" + + while true; do + local pending + pending=$(gh api "repos/${repo}/commits/${sha}/check-runs" \ + --jq '[.check_runs[] | select(.status == "in_progress" or .status == "queued" or .status == "pending")] | length') + + local failed + failed=$(gh api "repos/${repo}/commits/${sha}/check-runs" \ + --jq '[.check_runs[] | select(.conclusion == "failure")] | length') + + local total + total=$(gh api "repos/${repo}/commits/${sha}/check-runs" --jq '.check_runs | length') + + local completed + completed=$((total - pending)) + + echo -e "[$(date '+%H:%M:%S')] Completed: ${completed}/${total}, Pending: ${pending}, Failed: ${failed}" + + if [[ "$pending" -eq 0 ]]; then + echo "" + if [[ "$failed" -eq 0 ]]; then + echo -e "${GREEN}All checks passed!${NC}" + else + echo -e "${RED}${failed} check(s) failed.${NC}" + cmd_failed "$pr_number" + fi + break + fi + + sleep "$interval" + done +} + +# Show help +show_help() { + cat << 'EOF' +Quality Feedback Helper - Retrieve code quality feedback via GitHub API + +Usage: quality-feedback-helper.sh [command] [options] + +Commands: + status Show status of all quality checks + failed Show only failed checks with details + annotations Get line-level annotations from all check runs + codacy Get Codacy-specific feedback + coderabbit Get CodeRabbit review comments + sonar Get SonarCloud feedback + watch Watch for check completion (polls every 30s) + help Show this help message + +Options: + --pr NUMBER Specify PR number (otherwise uses current commit) + --commit SHA Specify commit SHA (otherwise uses HEAD) + +Examples: + quality-feedback-helper.sh status + quality-feedback-helper.sh failed --pr 4 + quality-feedback-helper.sh annotations + quality-feedback-helper.sh coderabbit --pr 4 + quality-feedback-helper.sh watch --pr 4 + +Requirements: + - GitHub CLI (gh) installed and authenticated + - jq for JSON parsing + - Inside a Git repository linked to GitHub +EOF +} + +# Parse arguments +main() { + local command="${1:-status}" + shift || true + + local pr_number="" + local commit_sha="" + + while [[ $# -gt 0 ]]; do + case "$1" in + --pr) + pr_number="$2" + shift 2 + ;; + --commit) + commit_sha="$2" + shift 2 + ;; + --help|-h) + show_help + exit 0 + ;; + *) + echo "Unknown option: $1" >&2 + show_help + exit 1 + ;; + esac + done + + # If commit SHA provided, use it directly + if [[ -n "$commit_sha" ]]; then + get_sha() { echo "$commit_sha"; } + fi + + case "$command" in + status) + cmd_status "$pr_number" + ;; + failed) + cmd_failed "$pr_number" + ;; + annotations) + cmd_annotations "$pr_number" + ;; + codacy) + cmd_codacy "$pr_number" + ;; + coderabbit) + cmd_coderabbit "$pr_number" + ;; + sonar) + cmd_sonar "$pr_number" + ;; + watch) + cmd_watch "$pr_number" + ;; + help|--help|-h) + show_help + ;; + *) + echo "Unknown command: $command" >&2 + show_help + exit 1 + ;; + esac +} + +main "$@" diff --git a/.agent/workflows/README.md b/.agent/workflows/README.md new file mode 100644 index 00000000..c9a6c6d1 --- /dev/null +++ b/.agent/workflows/README.md @@ -0,0 +1,149 @@ +# Development Workflows + +This directory contains workflow guides for AI assistants working on any codebase - whether this aidevops repository, WordPress projects, or any other development work. + +## Purpose + +These workflows provide **universal best practices** that apply to: + +- Working on this aidevops repository +- Working on any other codebase using this framework +- WordPress plugin/theme development +- General software development projects + +## Workflow Files + +### Git & Version Control + +| File | Description | +|------|-------------| +| **git-workflow.md** | Comprehensive git practices, branching strategies, and collaboration | +| **release-process.md** | Complete release workflow with semantic versioning | + +### Development Lifecycle + +| File | Description | +|------|-------------| +| **feature-development.md** | Feature development from branch creation to merge | +| **bug-fixing.md** | Bug fix workflow with hotfix procedures | + +### Code Quality + +| File | Description | +|------|-------------| +| **code-review.md** | Universal code review checklist | +| **error-checking-feedback-loops.md** | CI/CD monitoring and automated resolution | + +### Context Management + +| File | Description | +|------|-------------| +| **multi-repo-workspace.md** | Working safely across multiple repositories | + +### Platform-Specific + +| File | Description | +|------|-------------| +| **wordpress-local-testing.md** | WordPress Playground, LocalWP, wp-env testing | + +## Quick Reference + +### Starting New Work + +1. Review **git-workflow.md** for branching strategy +2. Use **feature-development.md** or **bug-fixing.md** as appropriate +3. Follow **code-review.md** before requesting review + +### Releasing + +1. Follow **release-process.md** step-by-step +2. Monitor CI/CD using **error-checking-feedback-loops.md** + +### Multi-Repo Work + +1. Always check **multi-repo-workspace.md** before starting +2. Verify repository context before making changes + +### WordPress Development + +1. Use **wordpress-local-testing.md** for environment setup +2. Follow platform-specific guidance from `.agent/*.md` files + +## Usage + +AI assistants should reference these workflows when: + +1. Starting new development work +2. Preparing code for review or release +3. Troubleshooting CI/CD failures +4. Working in multi-repository environments +5. Needing structured approaches to common tasks + +## Relationship to Other `.agent/` Content + +| Directory/Files | Purpose | +|-----------------|---------| +| `.agent/workflows/` | **How to work** - Development processes and methodologies | +| `.agent/scripts/` | **Tools to use** - Automation and helper scripts | +| `.agent/*.md` (root) | **What services exist** - Service documentation and integrations | +| `.agent/memory/` | **What to remember** - Persistent context and preference templates | + +## File Naming Convention + +- Use lowercase filenames +- Use hyphens to separate words +- Be descriptive but concise +- Example: `feature-development.md`, `code-review.md` + +## Contributing + +When adding new workflows: + +1. Use lowercase filenames with hyphens +2. Include practical examples and commands +3. Make workflows generic enough for any codebase +4. Add language/platform-specific sections where needed +5. Reference specific tools/services from `.agent/*.md` files +6. Update this README with the new file + +## Workflow Template + +When creating a new workflow file: + +```markdown +# [Workflow Name] + +Brief description of what this workflow covers. + +## Overview + +When to use this workflow and prerequisites. + +## Steps + +### 1. First Step + +Details with code examples: + +\`\`\`bash +# Command example +command --flag +\`\`\` + +### 2. Second Step + +Continue with structured steps... + +## Checklist + +- [ ] Item 1 +- [ ] Item 2 + +## Troubleshooting + +Common issues and solutions. + +## Related Workflows + +- Link to related workflows +``` diff --git a/.agent/workflows/bug-fixing.md b/.agent/workflows/bug-fixing.md new file mode 100644 index 00000000..ec8d8bf8 --- /dev/null +++ b/.agent/workflows/bug-fixing.md @@ -0,0 +1,253 @@ +# Bug Fixing Guide for AI Assistants + +This document provides guidance for AI assistants to help with bug fixing workflows. + +## Bug Fixing Workflow + +### 1. Create a Bug Fix Branch + +Always start from the latest main branch (mandatory): + +```bash +git checkout main +git pull origin main +git checkout -b fix/bug-description +``` + +Use descriptive names that indicate what bug is being fixed. Include issue numbers when available: + +```bash +git checkout -b fix/123-plugin-activation-error +git checkout -b fix/api-timeout-handling +git checkout -b fix/null-pointer-exception +``` + +### 2. Understand the Bug + +Before fixing, understand: + +| Question | Why It Matters | +|----------|----------------| +| What is the expected behavior? | Defines the goal | +| What is the actual behavior? | Clarifies the problem | +| Steps to reproduce? | Enables testing | +| What is the impact? | Prioritizes the fix | +| What is the root cause? | Prevents symptom-only fixes | + +### 3. Fix the Bug + +When implementing the fix: + +- Make **minimal changes** necessary to fix the bug +- **Avoid introducing new features** while fixing bugs +- **Maintain backward compatibility** +- Add appropriate **comments explaining the fix** +- Consider adding **tests to prevent regression** + +### 4. Update Documentation + +Update relevant documentation: + +```markdown +# CHANGELOG.md - Add under "Unreleased" section +## [Unreleased] +### Fixed +- Fixed issue where X caused Y (#123) +``` + +Update readme/docs if the bug fix affects user-facing functionality. + +### 5. Testing + +Test the fix thoroughly: + +- [ ] Verify the bug is fixed +- [ ] Ensure no regression in related functionality +- [ ] Test with latest supported versions +- [ ] Test with minimum supported versions +- [ ] Run automated test suite +- [ ] Run quality checks + +```bash +# Run tests +npm test +composer test + +# Run quality checks +bash ~/git/aidevops/.agent/scripts/quality-check.sh +``` + +### 6. Commit Changes + +Make atomic commits with clear messages: + +```bash +git add . +git commit -m "Fix #123: Brief description of the bug fix + +- Detailed explanation of what was wrong +- How this commit fixes it +- Any side effects or considerations" +``` + +### 7. Version Determination + +After fixing and confirming the fix works, determine version increment: + +| Increment | When to Use | Example | +|-----------|-------------|---------| +| **PATCH** | Most bug fixes (no functionality change) | 1.6.0 -> 1.6.1 | +| **MINOR** | Bug fixes with new features or significant changes | 1.6.0 -> 1.7.0 | +| **MAJOR** | Bug fixes with breaking changes | 1.6.0 -> 2.0.0 | + +**Important:** Don't update version numbers during development. Only create version branches when the fix is confirmed working. + +### 8. Prepare for Release + +When ready for release: + +```bash +# Create version branch +git checkout -b v{MAJOR}.{MINOR}.{PATCH} + +# Merge fix branch +git merge fix/bug-description --no-ff + +# Update version numbers in all required files +# Commit version updates +git add . +git commit -m "Version {VERSION} - Bug fix release" +``` + +## Hotfix Process + +For critical bugs requiring immediate release: + +### 1. Create Hotfix Branch from Tag + +```bash +# Find the current release tag +git tag -l "v*" --sort=-v:refname | head -5 + +# Create hotfix branch from that tag +git checkout v{MAJOR}.{MINOR}.{PATCH} +git checkout -b hotfix/v{MAJOR}.{MINOR}.{PATCH+1} +``` + +### 2. Apply Minimal Fix + +Apply only the essential fix for the critical issue. + +### 3. Update Version Numbers + +Increment PATCH version in all files: + +- Main application file (version constant/header) +- CHANGELOG.md +- README.md / readme.txt +- Package files (package.json, composer.json) +- Language/localization files if applicable + +### 4. Commit and Tag + +```bash +git add . +git commit -m "Hotfix: Critical bug description" +git tag -a v{MAJOR}.{MINOR}.{PATCH+1} -m "Hotfix release" +``` + +### 5. Push Hotfix + +```bash +git push origin hotfix/v{MAJOR}.{MINOR}.{PATCH+1} +git push origin v{MAJOR}.{MINOR}.{PATCH+1} +``` + +### 6. Merge to Main + +```bash +git checkout main +git merge hotfix/v{MAJOR}.{MINOR}.{PATCH+1} --no-ff +git push origin main +``` + +## Common Bug Types and Strategies + +### Null/Undefined Errors + +```javascript +// Before: Crashes if user is null +const name = user.name; + +// After: Safe access with fallback +const name = user?.name ?? 'Unknown'; +``` + +### Race Conditions + +- Add proper async/await handling +- Use locks or semaphores where needed +- Ensure proper initialization order + +### Memory Leaks + +- Clean up event listeners +- Clear timers and intervals +- Release references when done + +### API/Network Errors + +- Add proper error handling +- Implement retries with backoff +- Add timeout handling +- Validate responses before use + +### Security Issues + +- Validate and sanitize all inputs +- Escape all outputs +- Use parameterized queries +- Check permissions/capabilities + +## Testing Previous Versions + +To test against a previous version: + +```bash +# Checkout specific tag +git checkout v{MAJOR}.{MINOR}.{PATCH} + +# Or create test branch from tag +git checkout v{MAJOR}.{MINOR}.{PATCH} -b test/some-issue +``` + +## Rollback Procedure + +If a fix causes issues after release: + +```bash +# Find last stable version +git tag -l "*-stable" --sort=-v:refname | head -5 + +# Create fix branch from stable +git checkout v{VERSION}-stable +git checkout -b fix/rollback-based-fix + +# Apply corrected fix +# Test thoroughly +# Create new version when confirmed +``` + +## Bug Fix Checklist + +Before marking a bug fix as complete: + +- [ ] Root cause identified and documented +- [ ] Fix is minimal and focused +- [ ] No new features introduced +- [ ] Tests added to prevent regression +- [ ] All existing tests pass +- [ ] Quality checks pass +- [ ] Documentation updated +- [ ] Changelog updated +- [ ] Ready for code review diff --git a/.agent/workflows/code-review.md b/.agent/workflows/code-review.md new file mode 100644 index 00000000..6aa0fc7f --- /dev/null +++ b/.agent/workflows/code-review.md @@ -0,0 +1,301 @@ +# Code Review Guide for AI Assistants + +This document provides a comprehensive code review checklist for AI assistants reviewing any codebase. + +## Code Review Checklist + +### Functionality + +- [ ] Does the code work as expected? +- [ ] Does it handle edge cases appropriately? +- [ ] Are there any logical errors? +- [ ] Is error handling implemented properly? +- [ ] Does it meet the requirements/acceptance criteria? + +### Code Quality + +- [ ] Does the code follow project coding standards? +- [ ] Is the code well-organized and easy to understand? +- [ ] Are there any code smells? + - Duplicate code + - Overly complex functions + - Long methods/functions + - Deep nesting + - Magic numbers/strings +- [ ] Are functions and variables named appropriately? +- [ ] Are there appropriate comments and documentation? +- [ ] Is the code DRY (Don't Repeat Yourself)? + +### Security + +- [ ] Is user input properly validated and sanitized? +- [ ] Is output properly escaped? +- [ ] Are capability/permission checks used for user actions? +- [ ] Are there any potential injection vulnerabilities? + - SQL injection + - XSS (Cross-Site Scripting) + - Command injection +- [ ] Are secrets/credentials properly handled? +- [ ] Is authentication/authorization properly implemented? +- [ ] Are there any insecure dependencies? + +### Performance + +- [ ] Are there any performance bottlenecks? +- [ ] Are database queries optimized? + - No N+1 queries + - Proper indexing considered + - Efficient joins +- [ ] Is caching used appropriately? +- [ ] Are assets properly optimized? +- [ ] Are there any memory leaks? +- [ ] Is async/parallel processing used where beneficial? + +### Compatibility + +- [ ] Is the code compatible with supported runtime versions? +- [ ] Are there any browser compatibility issues (if web)? +- [ ] Are there any OS compatibility issues? +- [ ] Are there any conflicts with dependencies? +- [ ] Is backward compatibility maintained? + +### Testing + +- [ ] Are there appropriate unit tests? +- [ ] Are there integration tests for critical paths? +- [ ] Do tests cover edge cases? +- [ ] Are tests well-organized and maintainable? +- [ ] Do all tests pass? +- [ ] Is test coverage adequate? + +### Documentation + +- [ ] Are public APIs documented? +- [ ] Are complex algorithms explained? +- [ ] Is the README updated if needed? +- [ ] Is the changelog updated? +- [ ] Are breaking changes clearly documented? + +### Accessibility (for UI changes) + +- [ ] Does the code follow accessibility best practices? +- [ ] Are ARIA attributes used appropriately? +- [ ] Is keyboard navigation supported? +- [ ] Is screen reader support implemented? +- [ ] Is color contrast sufficient? + +### Internationalization (if applicable) + +- [ ] Are all user-facing strings translatable? +- [ ] Is the correct text domain/locale used? +- [ ] Are translation functions used correctly? +- [ ] Are date/time/number formats localized? + +## Code Review Process + +### 1. Understand the Context + +Before reviewing, understand: + +- What problem is the code trying to solve? +- What are the requirements? +- What are the constraints? +- Is there related documentation or issues? + +### 2. Review the Code + +Review systematically using the checklist above. + +### 3. Provide Feedback + +When providing feedback: + +#### Be Specific and Clear + +**Good feedback example:** + +> In function `processUserData()` at line 45: +> +> 1. The input validation is missing for the `email` parameter. +> Consider adding validation like `if (!isValidEmail(email)) { throw new ValidationError('Invalid email format'); }` +> +> 2. The error message should be more descriptive. Instead of `throw new Error('Failed')`, +> use `throw new Error(\`Failed to process data for user ${userId}: ${reason}\`)` + +#### Categorize Feedback + +| Category | Description | Action Required | +|----------|-------------|-----------------| +| **Blocker** | Must be fixed before merge | Yes | +| **Major** | Should be fixed, significant issue | Yes | +| **Minor** | Should be fixed, small issue | Preferably | +| **Suggestion** | Optional improvement | No | +| **Question** | Seeking clarification | Response needed | + +#### Be Constructive + +```markdown +# Poor feedback +This code is bad. Fix it. + +# Good feedback +The current implementation could be improved for better maintainability: + +Current approach: +- Uses multiple nested callbacks +- Hard to follow the data flow +- Error handling is scattered + +Suggested improvement: +- Refactor to use async/await +- Centralize error handling +- Extract helper functions for clarity + +Would you like me to provide a specific example? +``` + +### 4. Follow Up + +After code has been updated: + +- Review the changes +- Verify issues have been addressed +- Provide additional feedback if necessary +- Approve when ready + +## Common Issues to Look For + +### General Issues + +| Issue | What to Look For | +|-------|------------------| +| Undefined variables | Variables used before declaration | +| Missing error handling | Operations that can fail without try/catch | +| Resource leaks | Unclosed connections, streams, handles | +| Race conditions | Async operations without proper synchronization | +| Hardcoded values | Configuration that should be externalized | + +### Language-Specific Issues + +#### JavaScript/TypeScript + +- Improper async/await usage +- Missing null checks +- Event listener memory leaks +- Improper this binding +- Type safety issues (TypeScript) + +#### Python + +- Mutable default arguments +- Bare except clauses +- Resource management (use context managers) +- Import organization +- Type hints missing + +#### Shell/Bash + +- Unquoted variables +- Missing error handling (set -e) +- Hardcoded paths +- Not using shellcheck-compliant patterns +- Missing input validation + +#### PHP + +- SQL injection vulnerabilities +- Missing input sanitization +- Output not escaped +- Deprecated function usage +- Missing nonces (WordPress) + +### Architecture Issues + +- Tight coupling between components +- Circular dependencies +- God classes/functions (doing too much) +- Missing abstraction layers +- Inconsistent patterns + +## Automated Code Review Tools + +Use automated tools to supplement manual review: + +### Quality Analysis + +```bash +# Run project quality checks +bash ~/git/aidevops/.agent/scripts/quality-check.sh + +# Use CodeRabbit for AI-powered review +bash ~/git/aidevops/.agent/scripts/coderabbit-cli.sh review + +# Use Codacy for analysis +bash ~/git/aidevops/.agent/scripts/codacy-cli.sh analyze + +# Use Qlty for universal checking +bash ~/git/aidevops/.agent/scripts/qlty-cli.sh check +``` + +### Security Scanning + +```bash +# Run Snyk security scan +snyk test + +# Check for vulnerable dependencies +npm audit +composer audit +``` + +### Linting + +```bash +# ShellCheck for bash scripts +shellcheck script.sh + +# ESLint for JavaScript +npx eslint . + +# Pylint for Python +pylint module/ +``` + +## Review Response Template + +```markdown +## Code Review: PR #123 - Feature Name + +### Summary +Brief overview of what was reviewed and overall assessment. + +### Blockers (Must Fix) +1. **Security Issue** - `file.js:45` + - Description of issue + - Suggested fix + +### Major Issues (Should Fix) +1. **Performance** - `query.js:100` + - Description + - Recommendation + +### Minor Issues (Nice to Fix) +1. **Style** - `utils.js:20` + - Description + +### Suggestions (Optional) +1. Consider using X pattern for Y + +### Questions +1. Why was Z approach chosen over W? + +### Positive Notes +- Good test coverage +- Clean separation of concerns +- Well-documented API + +### Recommendation +[ ] Approve +[x] Request changes +[ ] Comment only +``` diff --git a/.agent/workflows/error-checking-feedback-loops.md b/.agent/workflows/error-checking-feedback-loops.md new file mode 100644 index 00000000..6b717ab2 --- /dev/null +++ b/.agent/workflows/error-checking-feedback-loops.md @@ -0,0 +1,564 @@ +# Error Checking and Feedback Loops + +This document outlines processes for error checking, debugging, and establishing feedback loops for autonomous CI/CD operation. + +The goal is to enable AI assistants to identify, diagnose, and fix issues with minimal human intervention. + +## Table of Contents + +- [GitHub Actions Workflow Monitoring](#github-actions-workflow-monitoring) +- [Local Build and Test Feedback](#local-build-and-test-feedback) +- [Code Quality Tool Integration](#code-quality-tool-integration) +- [Automated Error Resolution](#automated-error-resolution) +- [Feedback Loop Architecture](#feedback-loop-architecture) +- [When to Consult Humans](#when-to-consult-humans) + +## GitHub Actions Workflow Monitoring + +### Checking Workflow Status via GitHub CLI + +```bash +# Get recent workflow runs +gh run list --limit 10 + +# Get failed runs only +gh run list --status failure --limit 5 + +# Get details for a specific run +gh run view {run_id} + +# Get logs for a failed run +gh run view {run_id} --log-failed + +# Watch a running workflow +gh run watch {run_id} +``` + +### Checking via GitHub API + +```bash +# Get recent workflow runs +gh api repos/{owner}/{repo}/actions/runs --jq '.workflow_runs[:5] | .[] | "\(.name): \(.conclusion // .status)"' + +# Get failed runs +gh api repos/{owner}/{repo}/actions/runs?status=failure + +# Get jobs for a specific run +gh api repos/{owner}/{repo}/actions/runs/{run_id}/jobs +``` + +### Common GitHub Actions Errors and Solutions + +| Error | Solution | +|-------|----------| +| Missing action version | Update to latest: `uses: actions/checkout@v4` | +| Deprecated action | Replace with recommended alternative | +| Secret not found | Verify secret name in repository settings | +| Permission denied | Check workflow permissions or GITHUB_TOKEN scope | +| Timeout | Increase timeout or optimize slow steps | +| Cache miss | Verify cache keys and paths | + +#### Example Fixes + +**Outdated Action:** + +```yaml +# Before +uses: actions/upload-artifact@v3 + +# After +uses: actions/upload-artifact@v4 +``` + +**Concurrency Control:** + +```yaml +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +``` + +## Local Build and Test Feedback + +### Running Local Tests + +```bash +# JavaScript/Node.js +npm test +npm run test:coverage + +# Python +pytest +pytest --cov=module/ + +# PHP +composer test +vendor/bin/phpunit + +# Go +go test ./... + +# Rust +cargo test +``` + +### Capturing Test Output + +```bash +# Capture output for analysis +npm test > test-output.log 2>&1 + +# Parse for errors +grep -i 'error\|fail\|exception' test-output.log + +# Get structured results (if available) +cat test-results.json | jq '.failures' +``` + +### Common Local Test Errors + +| Error Type | Diagnosis | Solution | +|------------|-----------|----------| +| Dependency missing | Check error for package name | `npm install` / `pip install` | +| Port in use | Check error for port number | Kill process or use different port | +| Timeout | Test takes too long | Increase timeout or optimize | +| Database connection | DB not running | Start database service | +| Permission denied | File/directory access | Check permissions, run with proper user | + +## Code Quality Tool Integration + +### Running Quality Checks + +```bash +# Universal quality check (aidevops) +bash ~/git/aidevops/.agent/scripts/quality-check.sh + +# ShellCheck (bash scripts) +shellcheck script.sh + +# ESLint (JavaScript) +npx eslint . --format json + +# Pylint (Python) +pylint module/ --output-format=json + +# PHP CodeSniffer +composer phpcs +``` + +### Auto-Fixing Issues + +```bash +# Codacy auto-fix +bash ~/git/aidevops/.agent/scripts/codacy-cli.sh analyze --fix + +# Qlty auto-format +bash ~/git/aidevops/.agent/scripts/qlty-cli.sh fmt --all + +# ESLint auto-fix +npx eslint . --fix + +# PHP Code Beautifier +composer phpcbf +``` + +### Monitoring PR Feedback + +```bash +# Get PR comments +gh pr view {pr_number} --comments + +# Get PR reviews +gh api repos/{owner}/{repo}/pulls/{pr_number}/reviews + +# Get check runs for PR +gh pr checks {pr_number} +``` + +### Efficient Quality Tool Feedback via GitHub API + +**Why use the API directly?** The GitHub Checks API provides structured access to all code quality tool feedback (Codacy, CodeFactor, SonarCloud, CodeRabbit, etc.) without needing to visit each tool's dashboard. This enables rapid iteration. + +#### Get All Check Runs for a PR/Commit + +```bash +# Get check runs for latest commit on current branch +gh api repos/{owner}/{repo}/commits/$(git rev-parse HEAD)/check-runs \ + --jq '.check_runs[] | {name: .name, status: .status, conclusion: .conclusion}' + +# Get check runs for a specific PR +gh api repos/{owner}/{repo}/commits/$(gh pr view {pr_number} --json headRefOid -q .headRefOid)/check-runs \ + --jq '.check_runs[] | {name: .name, conclusion: .conclusion, url: .html_url}' + +# Filter for failed checks only +gh api repos/{owner}/{repo}/commits/$(git rev-parse HEAD)/check-runs \ + --jq '.check_runs[] | select(.conclusion == "failure" or .conclusion == "action_required") | {name: .name, conclusion: .conclusion}' +``` + +#### Get Detailed Annotations (Line-Level Issues) + +```bash +# Get annotations from a specific check run (e.g., Codacy) +gh api repos/{owner}/{repo}/check-runs/{check_run_id}/annotations \ + --jq '.[] | {path: .path, line: .start_line, level: .annotation_level, message: .message}' + +# Get all annotations from all check runs for a commit +for id in $(gh api repos/{owner}/{repo}/commits/$(git rev-parse HEAD)/check-runs --jq '.check_runs[].id'); do + echo "=== Check Run $id ===" + gh api repos/{owner}/{repo}/check-runs/$id/annotations --jq '.[] | "\(.path):\(.start_line) [\(.annotation_level)] \(.message)"' 2>/dev/null +done +``` + +#### Quick Status Check Script + +```bash +#!/bin/bash +# Quick quality check status for current branch + +REPO="${GITHUB_REPOSITORY:-$(gh repo view --json nameWithOwner -q .nameWithOwner)}" +COMMIT=$(git rev-parse HEAD) + +echo "=== Quality Check Status for $COMMIT ===" +gh api "repos/$REPO/commits/$COMMIT/check-runs" \ + --jq '.check_runs[] | "\(.conclusion // .status | ascii_upcase)\t\(.name)"' | sort + +echo "" +echo "=== Failed Checks Details ===" +gh api "repos/$REPO/commits/$COMMIT/check-runs" \ + --jq '.check_runs[] | select(.conclusion == "failure") | "❌ \(.name): \(.output.summary // "See details")"' +``` + +#### Tool-Specific API Access + +**Codacy:** + +```bash +# Get Codacy check run details +gh api repos/{owner}/{repo}/commits/{sha}/check-runs \ + --jq '.check_runs[] | select(.app.slug == "codacy-production") | {conclusion: .conclusion, summary: .output.summary}' +``` + +**CodeRabbit:** + +```bash +# Get CodeRabbit review comments +gh api repos/{owner}/{repo}/pulls/{pr_number}/comments \ + --jq '.[] | select(.user.login | contains("coderabbit")) | {path: .path, line: .line, body: .body}' +``` + +**SonarCloud:** + +```bash +# Get SonarCloud check run +gh api repos/{owner}/{repo}/commits/{sha}/check-runs \ + --jq '.check_runs[] | select(.name | contains("SonarCloud")) | {conclusion: .conclusion, url: .details_url}' +``` + +#### Automated Feedback Loop Pattern + +```bash +#!/bin/bash +# Automated quality feedback loop + +check_and_report() { + local repo="$1" + local sha="$2" + + echo "Checking quality status..." + + # Get all check conclusions + local checks + checks=$(gh api "repos/$repo/commits/$sha/check-runs" \ + --jq '.check_runs[] | {name: .name, conclusion: .conclusion, id: .id}') + + # Report failures with details + echo "$checks" | jq -r 'select(.conclusion == "failure") | .id' | while read -r id; do + echo "=== Failure in check $id ===" + gh api "repos/$repo/check-runs/$id/annotations" \ + --jq '.[] | " \(.path):\(.start_line) - \(.message)"' + done + + # Summary + local passed failed + passed=$(echo "$checks" | jq -r 'select(.conclusion == "success") | .name' | wc -l) + failed=$(echo "$checks" | jq -r 'select(.conclusion == "failure") | .name' | wc -l) + + echo "" + echo "Summary: $passed passed, $failed failed" +} + +# Usage +check_and_report "owner/repo" "$(git rev-parse HEAD)" +``` + +### Processing Code Quality Feedback + +1. **Collect all feedback:** + + ```bash + gh pr view {number} --comments --json comments + gh api repos/{owner}/{repo}/pulls/{number}/reviews + ``` + +2. **Categorize issues:** + - Critical: Security, breaking bugs + - High: Quality violations, potential bugs + - Medium: Style issues, best practices + - Low: Documentation, minor improvements + +3. **Prioritize fixes:** + - Address critical issues first + - Group related issues for efficient fixing + - Consider dependencies between issues + +## Automated Error Resolution + +### Error Resolution Workflow + +```text +1. Identify Error + ↓ +2. Categorize Error (type, severity) + ↓ +3. Search for Known Solution + ↓ +4. Apply Fix + ↓ +5. Verify Fix (run tests) + ↓ +6. Document Solution +``` + +### Processing Workflow Failures + +```bash +# 1. Get failed workflow +gh run list --status failure --limit 1 + +# 2. Get failure details +gh run view {run_id} --log-failed + +# 3. Identify the failing step and error + +# 4. Apply fix based on error type + +# 5. Push fix and monitor +git add . && git commit -m "Fix: CI error description" +git push origin {branch} +gh run watch +``` + +### Common Fix Patterns + +**Dependency Issues:** + +```bash +# Update lockfile +npm ci # or: npm install +composer install + +# Clear caches +npm cache clean --force +composer clear-cache +``` + +**Test Failures:** + +```bash +# Run specific failing test +npm test -- --grep "failing test name" + +# Run with verbose output +npm test -- --verbose + +# Update snapshots if intentional changes +npm test -- --updateSnapshot +``` + +**Linting Errors:** + +```bash +# Auto-fix what's possible +npm run lint:fix + +# Review remaining issues +npm run lint -- --format stylish +``` + +## Feedback Loop Architecture + +### Complete Feedback Loop System + +```text +Code Changes ──► Local Testing ──► GitHub Actions + │ │ │ + ▼ ▼ ▼ +AI Assistant ◄── Error Analysis ◄── Status Check + │ + ▼ +Fix Generation ──► Verification ──► Human Review (if needed) +``` + +### Key Components + +| Component | Purpose | Tools | +|-----------|---------|-------| +| Code Changes | Initial modifications | Git | +| Local Testing | Immediate feedback | npm test, pytest | +| GitHub Actions | Remote validation | gh CLI | +| Status Check | Monitor workflows | gh run list | +| Error Analysis | Parse and categorize | grep, jq | +| AI Assistant | Central intelligence | This guide | +| Fix Generation | Create solutions | Edit, Write tools | +| Verification | Confirm fix works | Tests, CI | +| Human Review | Complex decisions | When needed | + +### Implementing the Loop + +```bash +#!/bin/bash +# Continuous monitoring script pattern + +check_and_fix() { + # Check for failures - declare and assign separately per SC2155 + local failures + failures=$(gh run list --status failure --limit 1 --json conclusion -q '.[].conclusion') + + if [[ "$failures" == "failure" ]]; then + # Get failure details - declare and assign separately per SC2155 + local run_id + local logs + run_id=$(gh run list --status failure --limit 1 --json databaseId -q '.[].databaseId') + logs=$(gh run view "$run_id" --log-failed) + + # Analyze and report + echo "Failure detected in run $run_id" + echo "$logs" | grep -i 'error\|fail' | head -20 + + # Suggest fixes based on error patterns + analyze_error "$logs" + fi +} + +analyze_error() { + local logs="$1" + + if echo "$logs" | grep -q "npm ERR!"; then + echo "Suggestion: Run 'npm ci' to reinstall dependencies" + elif echo "$logs" | grep -q "EACCES"; then + echo "Suggestion: Check file permissions" + elif echo "$logs" | grep -q "timeout"; then + echo "Suggestion: Increase timeout or optimize slow operations" + fi +} +``` + +## When to Consult Humans + +### Scenarios Requiring Human Input + +| Scenario | Reason | What to Provide | +|----------|--------|-----------------| +| Product design decisions | Requires business context | Options with trade-offs | +| Security-critical changes | Risk assessment needed | Security implications | +| Architectural decisions | Long-term impact | Architecture options | +| Deployment approvals | Production risk | Deployment plan | +| Novel problems | No precedent | Research findings | +| External service issues | Out of control | Status and workarounds | +| Ambiguous requirements | Clarification needed | Questions and assumptions | + +### Effective Human Consultation + +When consulting humans, provide: + +**Issue Summary:** Brief description of the problem. + +**Context:** + +- What were you trying to accomplish? +- What happened instead? + +**Error Details:** Include specific error messages or logs. + +**Attempted Solutions:** + +1. Tried X - Result: Y +2. Tried Z - Result: W + +**Questions:** + +1. Specific question requiring human input +2. Another specific question + +**Recommendations:** Based on analysis, suggest options with pros/cons and ask which approach they prefer. + +### Contributing Fixes Upstream + +When issues are in external dependencies: + +```bash +# 1. Clone the repository +cd ~/git +git clone https://github.com/owner/repo.git +cd repo +git checkout -b fix/descriptive-name + +# 2. Make and commit changes +git add -A +git commit -m "Fix: Description + +Detailed explanation. +Fixes #issue-number" + +# 3. Fork and push +gh repo fork owner/repo --clone=false --remote=true +git remote add fork https://github.com/your-username/repo.git +git push fork fix/descriptive-name + +# 4. Create PR +gh pr create --repo owner/repo \ + --head your-username:fix/descriptive-name \ + --title "Fix: Description" \ + --body "## Summary +Description of changes. + +Fixes #issue-number" +``` + +## Quick Reference + +### Daily Monitoring Commands + +```bash +# Check all workflow status +gh run list --limit 10 + +# Check for failures +gh run list --status failure + +# View specific failure +gh run view {id} --log-failed + +# Check PR status +gh pr checks + +# Run local quality check +bash ~/git/aidevops/.agent/scripts/quality-check.sh +``` + +### Common Fix Commands + +```bash +# Dependency issues +npm ci && npm test + +# Linting issues +npm run lint:fix + +# Type issues +npm run typecheck + +# Quality issues +bash ~/git/aidevops/.agent/scripts/codacy-cli.sh analyze --fix +bash ~/git/aidevops/.agent/scripts/qlty-cli.sh fmt --all +``` diff --git a/.agent/workflows/feature-development.md b/.agent/workflows/feature-development.md new file mode 100644 index 00000000..66b1ba64 --- /dev/null +++ b/.agent/workflows/feature-development.md @@ -0,0 +1,304 @@ +# Feature Development Guide for AI Assistants + +This document provides guidance for developing new features in any codebase. + +## Feature Development Workflow + +### 1. Create a Feature Branch + +Always start from the latest main branch (mandatory): + +```bash +git checkout main +git pull origin main +git checkout -b feature/descriptive-name +``` + +Use descriptive names. Include issue numbers when available: + +```bash +git checkout -b feature/123-user-dashboard +git checkout -b feature/api-rate-limiting +git checkout -b feature/export-functionality +``` + +### 2. Understand Requirements + +Before implementing: + +| Question | Purpose | +|----------|---------| +| What problem does this solve? | Validates necessity | +| Who will use this feature? | Defines UX approach | +| How should it behave? | Defines acceptance criteria | +| What are the edge cases? | Prevents bugs | +| What are the dependencies? | Plans integration | + +### 3. Implement the Feature + +When implementing: + +- Follow project coding standards +- Ensure all strings are translatable (if applicable) +- Add appropriate comments and documentation +- Consider performance implications +- Maintain backward compatibility +- Review existing code for patterns to follow + +### 4. Time-Efficient Development + +#### Development Branches (Without Version Numbers) + +During initial development: + +```bash +# Create descriptive branch +git checkout -b feature/user-authentication + +# Work on implementation +# DON'T update version numbers yet +# Focus on functionality + +# Commit frequently +git add . +git commit -m "Add: User authentication logic" +``` + +#### Testing Iterations + +```bash +# Local testing - use current version +npm test +composer test + +# Build without version changes +npm run build +``` + +#### Version Branch (Only When Ready) + +Only create version branches when feature is confirmed working: + +```bash +# Determine version increment (usually MINOR for features) +git checkout -b v{MAJOR}.{MINOR+1}.0 + +# NOW update version numbers +# Commit version updates +git commit -m "Version {VERSION} - Add user authentication" +``` + +### 5. Update Documentation + +Update all relevant documentation: + +**CHANGELOG.md:** + +```markdown +## [Unreleased] +### Added +- New feature: Description of what was added (#123) +``` + +**README.md / readme.txt:** + +- Update feature list +- Add usage instructions +- Update screenshots if UI changed + +**Code Comments:** + +- Add docblocks to new functions/methods +- Document complex logic +- Add usage examples + +### 6. Testing + +Test the feature thoroughly: + +- [ ] Feature works as specified +- [ ] Edge cases handled +- [ ] Error handling works +- [ ] Performance is acceptable +- [ ] No regression in existing functionality +- [ ] Works in supported environments +- [ ] Accessibility requirements met (if UI) + +```bash +# Run test suite +npm test +composer test + +# Run quality checks +bash ~/git/aidevops/.agent/scripts/quality-check.sh + +# Run specific tests +npm run test:feature +``` + +### 7. Commit Changes + +Make atomic, well-documented commits: + +```bash +git add . +git commit -m "Add: Feature description + +- Implemented X functionality +- Added Y component +- Integrated with Z system + +Closes #123" +``` + +### 8. Prepare for Release + +When feature is ready: + +```bash +# Create version branch (MINOR increment for features) +git checkout -b v{MAJOR}.{MINOR+1}.0 + +# Update version numbers in all files +# - Main application file +# - package.json / composer.json +# - CHANGELOG.md +# - README files +# - Localization files + +git add . +git commit -m "Version {VERSION} - Feature name" + +# Tag as stable when confirmed +git tag -a v{VERSION}-stable -m "Stable version {VERSION}" +``` + +## Code Standards Reminders + +### General Best Practices + +```javascript +// Use descriptive names +const userAuthenticationService = new AuthService(); // GOOD +const uas = new AuthService(); // BAD + +// Handle errors explicitly +try { + await riskyOperation(); +} catch (error) { + logger.error('Operation failed:', error); + throw new OperationError('Descriptive message', { cause: error }); +} + +// Document complex logic +/** + * Calculates user permission level based on role hierarchy. + * + * @param {User} user - The user to check + * @param {Resource} resource - The resource being accessed + * @returns {PermissionLevel} The calculated permission level + */ +function calculatePermissions(user, resource) { + // Implementation +} +``` + +### Security Best Practices + +- Validate and sanitize all input +- Escape all output +- Use parameterized queries +- Implement proper authentication/authorization +- Follow principle of least privilege + +### Performance Considerations + +- Avoid N+1 queries +- Use caching where appropriate +- Lazy load when possible +- Profile before optimizing + +## Working in Multi-Repository Workspaces + +When developing features in a workspace with multiple repositories: + +### 1. Verify Repository Context + +```bash +# Confirm you're in the right repository +pwd +git remote -v +``` + +### 2. Feature Verification + +Before implementing, verify it doesn't already exist: + +```bash +# Search codebase for similar functionality +grep -r "feature-keyword" . +``` + +### 3. Repository-Specific Implementation + +- Implement features appropriate for this specific project +- Maintain consistency with the project's architecture +- Don't copy code from other repositories without adaptation + +### 4. Cross-Repository Inspiration + +If implementing a feature inspired by another repository: + +- Explicitly note it's a new feature +- Adapt to fit current project's architecture +- Document the inspiration source in comments + +## Feature Types and Guidelines + +### API Features + +- Follow REST conventions (or project's API style) +- Version the API appropriately +- Document all endpoints +- Include request/response examples +- Handle errors consistently + +### UI Features + +- Follow existing design patterns +- Ensure accessibility compliance +- Add appropriate help text +- Test responsive behavior +- Consider internationalization + +### Backend Features + +- Use existing patterns for consistency +- Consider scalability +- Add monitoring/logging +- Document configuration options +- Plan for failure scenarios + +### Integration Features + +- Make integrations optional when possible +- Check if dependencies are available +- Provide fallback behavior +- Document integration requirements + +## Feature Development Checklist + +Before marking feature as complete: + +- [ ] Requirements fully implemented +- [ ] Edge cases handled +- [ ] Error handling complete +- [ ] Tests written and passing +- [ ] Documentation updated +- [ ] Code review ready +- [ ] Quality checks pass +- [ ] No regression in existing features +- [ ] Performance acceptable +- [ ] Security considerations addressed +- [ ] Accessibility requirements met (if UI) +- [ ] Changelog updated diff --git a/.agent/workflows/git-workflow.md b/.agent/workflows/git-workflow.md new file mode 100644 index 00000000..7085a14c --- /dev/null +++ b/.agent/workflows/git-workflow.md @@ -0,0 +1,285 @@ +# Git Workflow Guide for AI Assistants + +This document provides comprehensive git workflow guidance for AI assistants working on any codebase. + +## Core Git Workflow Principles + +### 1. Always Start from Latest Main Branch + +Before creating any new branch, always ensure you're working with the latest code: + +```bash +git checkout main +git pull origin main +``` + +**This is mandatory.** Working from an outdated main branch leads to integration problems and merge conflicts. + +### 2. One Issue Per Branch + +Create a separate branch for each issue or feature: + +| Branch Type | Naming Pattern | Example | +|-------------|----------------|---------| +| Bug fixes | `fix/issue-description` | `fix/123-login-error` | +| Features | `feature/descriptive-name` | `feature/user-dashboard` | +| Improvements | `patch/descriptive-name` | `patch/improve-caching` | +| Refactoring | `refactor/descriptive-name` | `refactor/extract-helpers` | +| Hotfixes | `hotfix/v{VERSION}` | `hotfix/v2.2.1` | + +**Important:** Use descriptive names without version numbers for development branches. Only create version branches when changes are ready for release. + +### 3. Pull Request for Each Issue + +Create a separate pull request for each issue: + +- Each change can be reviewed independently +- Issues can be merged as soon as they're ready +- Changes can be reverted individually if needed +- CI/CD checks run on focused changes + +## Detailed Workflow + +### Starting a New Task + +```bash +# 1. Update main branch from origin (MANDATORY) +git checkout main +git pull origin main + +# 2. Create a new branch +git checkout -b [branch-type]/[description] + +# Examples: +git checkout -b fix/123-plugin-activation-error +git checkout -b feature/update-source-selector +git checkout -b patch/improve-error-messages +``` + +### Making Changes + +```bash +# Make focused changes related only to the specific issue +# Commit regularly with clear, descriptive messages + +git add . +git commit -m "Fix: Brief description of the change + +Detailed explanation if needed. +Fixes #123" +``` + +### Testing Approach + +**Local Testing (Default):** + +```bash +# Test without updating version numbers +# Run tests, linters, quality checks +npm test +composer test +bash ~/git/aidevops/.agent/scripts/quality-check.sh +``` + +**Remote Testing (When Requested):** + +```bash +git add . +git commit -m "WIP: Description for remote testing" +git push origin [branch-name] +``` + +### Push Branch to Remote + +```bash +git push origin [branch-name] + +# Or push to multiple remotes +git push github [branch-name] +git push gitlab [branch-name] +``` + +## Creating a Pull Request + +### 1. Ensure Tests Pass Locally + +```bash +# Run all available tests +npm test +composer test +# Run quality checks +bash ~/git/aidevops/.agent/scripts/quality-check.sh +``` + +### 2. Create Pull Request + +Include in PR description: +- Clear description of changes +- Reference related issues (`Fixes #123`) +- Testing performed +- Screenshots if UI changes + +### 3. Address Review Feedback + +```bash +# Make requested changes +git add . +git commit -m "Address review: description of changes" +git push origin [branch-name] +``` + +## Handling Concurrent Development + +### Keep Branches Independent + +Always create new branches from the latest main: + +```bash +# DON'T: Create from another feature branch +git checkout feature/other-feature +git checkout -b feature/new-feature # BAD + +# DO: Create from updated main +git checkout main +git pull origin main +git checkout -b feature/new-feature # GOOD +``` + +### Handle Conflicts Proactively + +```bash +# If main has been updated while you're working: +git checkout main +git pull origin main +git checkout your-branch +git merge main +# Resolve conflicts, then continue +``` + +### Coordinate on Dependent Changes + +- Note dependencies in PR description: "Depends on #PR-number" +- Consider using feature flags for independent merging +- Document dependencies between PRs + +## Commit Message Standards + +### Format + +```text +Type: Brief description (under 50 chars) + +Detailed explanation if needed. +- Bullet points for multiple changes +- Reference issues: Fixes #123 + +Co-authored-by: Name +``` + +### Types + +| Type | Usage | +|------|-------| +| `Fix:` | Bug fixes | +| `Add:` | New features | +| `Update:` | Enhancements to existing features | +| `Remove:` | Removing code/features | +| `Refactor:` | Code restructuring | +| `Docs:` | Documentation changes | +| `Test:` | Test additions/changes | +| `Chore:` | Maintenance tasks | + +### Best Practices + +- Use present tense ("Add feature" not "Added feature") +- Keep the first line under 50 characters +- Reference issues when relevant +- Add detailed description for complex changes + +## Branch Management + +### Cleanup + +```bash +# Delete merged local branches +git branch -d branch-name + +# Delete remote branch +git push origin --delete branch-name + +# Prune stale remote tracking branches +git fetch --prune +``` + +### View Branch Status + +```bash +# List all branches with last commit +git branch -av + +# Show branches merged to main +git branch --merged main + +# Show unmerged branches +git branch --no-merged main +``` + +## Contributing to External Repositories + +### Workflow for External Contributions + +```bash +# 1. Clone the repository +cd ~/git +git clone https://github.com/owner/repo.git +cd repo + +# 2. Create feature branch +git checkout -b feature/descriptive-branch-name + +# 3. Make changes and commit +git add -A +git commit -m "Descriptive commit message + +Detailed explanation. +Fixes #issue-number" + +# 4. Fork and push +gh repo fork owner/repo --clone=false --remote=true +git remote add fork https://github.com/your-username/repo.git +git push fork feature/descriptive-branch-name + +# 5. Create pull request +gh pr create \ + --repo owner/repo \ + --head your-username:feature/descriptive-branch-name \ + --title "Clear, descriptive title" \ + --body "Description of changes..." +``` + +### Testing Status in PRs + +Always indicate testing status in PR description: + +- **Not tested**: "This PR addresses [issue] but has not been tested. Ready for community/maintainer testing." +- **Locally tested**: "Tested in local environment with [results]." +- **Remotely tested**: "Tested with remote build with [results]." + +## Quick Reference + +```bash +# Start new work +git checkout main && git pull origin main && git checkout -b fix/issue-name + +# Commit changes +git add . && git commit -m "Fix: Description" + +# Push for review +git push origin fix/issue-name + +# Update from main +git fetch origin && git merge origin/main + +# Clean up after merge +git checkout main && git pull && git branch -d fix/issue-name +``` diff --git a/.agent/workflows/multi-repo-workspace.md b/.agent/workflows/multi-repo-workspace.md new file mode 100644 index 00000000..4dab3407 --- /dev/null +++ b/.agent/workflows/multi-repo-workspace.md @@ -0,0 +1,254 @@ +# Multi-Repository Workspace Guidelines + +This document provides guidelines for AI assistants working in workspaces that contain multiple repository folders. + +## Understanding Multi-Repository Workspaces + +Modern development environments often include multiple repository folders in a single workspace. This allows working on related projects simultaneously or referencing code from one project while working on another. + +### Common Workspace Configurations + +1. **Microservices Architecture**: Multiple service repositories in one workspace +2. **Monorepo with Dependencies**: Main repo with shared library repos +3. **Plugin/Extension Ecosystems**: Core project with plugin repositories +4. **Reference Repositories**: Including repos purely for reference or inspiration +5. **Multi-Platform Projects**: Web, mobile, and API repos together + +## Potential Issues in Multi-Repository Workspaces + +### 1. Feature Hallucination + +The most critical issue - assuming features from one repository should exist in another, or documenting non-existent features based on code seen in other repositories. + +**Example**: Seeing authentication code in Repo A and documenting it as existing in Repo B. + +### 2. Cross-Repository Code References + +Referencing or suggesting code patterns from one repository when working on another leads to: +- Inconsistent coding styles +- Mismatched dependencies +- Incorrect API assumptions + +### 3. Documentation Confusion + +Creating documentation that includes features or functionality from other repositories in the workspace. + +### 4. Scope Creep + +Suggesting changes or improvements based on other repositories, leading to scope creep and feature bloat. + +### 5. Dependency Confusion + +Assuming shared dependencies exist across repositories when they don't. + +## Best Practices for AI Assistants + +### 1. Repository Verification + +**ALWAYS** verify which repository you're currently working in before: + +- Making code suggestions +- Creating or updating documentation +- Discussing features or functionality +- Implementing new features +- Running commands + +```bash +# Verify current repository +pwd +git remote -v +git rev-parse --show-toplevel +``` + +### 2. Explicit Code Search Scoping + +When searching for code or functionality: + +- Explicitly limit searches to the current repository +- Use repository-specific paths in search queries +- Verify search results are from the current repository before using them +- Check file paths in search results + +### 3. Feature Verification Process + +Before documenting or implementing a feature: + +1. **Check the codebase**: Search for relevant code in the current repository only +2. **Verify functionality**: Look for actual implementation, not just references or comments +3. **Check documentation**: Review existing documentation to understand intended functionality +4. **Ask for clarification**: If uncertain, ask the developer to confirm the feature's existence or scope + +### 4. Documentation Guidelines + +When creating or updating documentation: + +1. **Repository-specific content**: Only document features that exist in the current repository +2. **Verify before documenting**: Check the codebase to confirm features actually exist +3. **Clear boundaries**: Make it clear which repository the documentation applies to +4. **Accurate feature descriptions**: Describe features as implemented, not as they might be in other repos + +### 5. Cross-Repository Inspiration + +When implementing features inspired by other repositories: + +1. **Explicit attribution**: Clearly state the feature is inspired by another repository +2. **New implementation**: Treat it as a new feature being added, not existing +3. **Repository-appropriate adaptation**: Adapt to fit the current repository's architecture +4. **Developer confirmation**: Confirm with the developer that adding the feature is appropriate + +## Repository Context Verification Checklist + +Before making significant changes or recommendations: + +- [ ] Verified current working directory/repository +- [ ] Confirmed repository name and purpose +- [ ] Checked that code searches are limited to current repository +- [ ] Verified features exist in current repository before documenting them +- [ ] Ensured documentation reflects only current repository's functionality +- [ ] Confirmed any cross-repository inspiration is clearly marked as new functionality +- [ ] Checked dependencies are appropriate for current repository + +## Example Verification Workflow + +### 1. Check Current Repository + +```bash +# Get repository root +git rev-parse --show-toplevel + +# Get remote information +git remote -v + +# Check branch context +git branch --show-current +``` + +### 2. Verify Feature Existence + +```bash +# Search within current repo only +grep -r "featureName" --include="*.js" . + +# Use git grep (respects .gitignore) +git grep "featureName" + +# Check specific files +ls -la src/features/ +``` + +### 3. Document with Clear Repository Context + +```markdown +# [Repository Name] - Feature Documentation + +This documentation applies to the [repository-name] repository. + +## Features +- Feature A (verified in src/features/a.js) +- Feature B (verified in src/features/b.js) +``` + +### 4. When Suggesting New Features + +```markdown +## Proposed Feature: [Name] + +**Note**: This feature is inspired by [other-repo] but does not currently exist +in this repository. + +**Rationale for adding**: [Explain why it's appropriate] + +**Implementation approach**: [Repository-specific approach] +``` + +## Handling Repository Switching + +When the developer switches between repositories in the workspace: + +1. **Acknowledge the switch**: Confirm the new repository context +2. **Reset context**: Don't carry over assumptions from the previous repository +3. **Verify new environment**: Check the structure and features of the new repository +4. **Update documentation references**: Reference documentation specific to the new repository +5. **Check for differences**: Note any differences in tooling, dependencies, or conventions + +## Common Multi-Repo Patterns + +### Monorepo with Packages + +```text +workspace/ +├── packages/ +│ ├── core/ # Core library +│ ├── ui/ # UI components +│ └── utils/ # Shared utilities +├── apps/ +│ ├── web/ # Web application +│ └── mobile/ # Mobile application +└── package.json # Root workspace config +``` + +**Key considerations**: + +- Shared dependencies are managed at root level +- Package-specific dependencies in each package +- Cross-package imports use workspace protocols + +### Multiple Separate Repos + +```text +workspace/ +├── api-service/ # Backend API +├── web-client/ # Frontend application +├── shared-types/ # TypeScript definitions +└── infrastructure/ # IaC configurations +``` + +**Key considerations**: + +- Each repo has its own dependencies +- No implicit sharing between repos +- Must explicitly publish/consume shared code + +## Tools for Multi-Repo Management + +### Git Worktrees + +```bash +# Create a worktree for a branch +git worktree add ../feature-branch feature-branch + +# List worktrees +git worktree list + +# Remove a worktree +git worktree remove ../feature-branch +``` + +### Repository-Specific Configuration + +Each repository should have: +- `.editorconfig` - Editor settings +- `.gitignore` - Ignore patterns +- `package.json` or equivalent - Dependencies +- `README.md` - Repository documentation +- `.github/` or `.gitlab/` - CI/CD configuration + +## Warning Signs of Context Confusion + +Watch for these indicators that context may be mixed: + +1. **Import paths don't exist**: Suggesting imports from paths not in current repo +2. **API mismatches**: Referencing APIs that exist in a different repo +3. **Configuration confusion**: Suggesting config that belongs to another repo +4. **Test file mismatches**: Running tests that don't exist in current repo +5. **Documentation inconsistencies**: Docs mention features from other repos + +## Recovery from Context Confusion + +If you realize context has been mixed: + +1. **Stop immediately**: Don't continue with potentially incorrect assumptions +2. **Verify current repository**: Re-confirm which repo you're in +3. **Review recent actions**: Check if any incorrect changes were made +4. **Correct documentation**: Update any documentation that mixed contexts +5. **Communicate clearly**: Inform the developer about the confusion and corrections diff --git a/.agent/workflows/release-process.md b/.agent/workflows/release-process.md new file mode 100644 index 00000000..eba4d473 --- /dev/null +++ b/.agent/workflows/release-process.md @@ -0,0 +1,480 @@ +# Release Process Workflow + +This document outlines the comprehensive process for preparing and publishing software releases with proper versioning, quality checks, and deployment. + +## Release Workflow Overview + +1. Plan the release scope +2. Create a release branch +3. Update version numbers +4. Run code quality checks +5. Build and test +6. Update changelog and documentation +7. Commit version changes +8. Create version tags +9. Push to remote repositories +10. Create GitHub/GitLab release +11. Merge into main branch +12. Post-release tasks + +## Pre-Release Planning + +### Release Types + +| Type | Version Change | Description | +|------|---------------|-------------| +| **Major** | X.0.0 | Breaking changes, major features | +| **Minor** | x.X.0 | New features, backward compatible | +| **Patch** | x.x.X | Bug fixes, security patches | +| **Hotfix** | x.x.X | Emergency production fixes | + +### Release Checklist + +Before starting a release: + +- [ ] All planned features are merged +- [ ] All critical bugs are resolved +- [ ] CI/CD pipelines are passing +- [ ] Documentation is up to date +- [ ] Dependencies are updated and audited +- [ ] Security vulnerabilities addressed + +## Detailed Release Steps + +### 1. Create a Release Branch + +Always start from an up-to-date main branch: + +```bash +# Ensure main is current +git checkout main +git pull origin main # Critical - never skip this + +# Create release branch +git checkout -b release/v{MAJOR}.{MINOR}.{PATCH} + +# Or for hotfixes +git checkout -b hotfix/v{MAJOR}.{MINOR}.{PATCH} +``` + +### 2. Update Version Numbers + +Update version in all relevant files: + +**JavaScript/Node.js Projects:** + +```bash +# package.json +npm version {MAJOR}.{MINOR}.{PATCH} --no-git-tag-version + +# Or manually update: +# - package.json: "version": "X.Y.Z" +# - package-lock.json: auto-updated +``` + +**Python Projects:** + +```python +# setup.py or pyproject.toml +version = "X.Y.Z" + +# __init__.py +__version__ = "X.Y.Z" +``` + +**Go Projects:** + +```go +// version.go +const Version = "X.Y.Z" +``` + +**PHP Projects:** + +```php +// Main plugin/application file +define('VERSION', 'X.Y.Z'); + +// Or in header comment +* Version: X.Y.Z +``` + +### 3. Run Code Quality Checks + +Before proceeding, ensure all quality checks pass: + +```bash +# Linting +npm run lint # JavaScript/TypeScript +flake8 . # Python +go vet ./... # Go +composer phpcs # PHP + +# Type checking +npm run typecheck # TypeScript +mypy . # Python +go build ./... # Go + +# Unit tests +npm test +pytest +go test ./... +composer test + +# Integration tests +npm run test:integration +pytest tests/integration/ + +# Security audit +npm audit +safety check # Python +go mod verify # Go +composer audit # PHP +``` + +### 4. Build and Test + +Build the release artifacts: + +```bash +# JavaScript/TypeScript +npm run build +npm run build:production + +# Python +python -m build +python setup.py sdist bdist_wheel + +# Go +go build -ldflags "-X main.Version={VERSION}" ./... + +# Docker +docker build -t project:v{VERSION} . +``` + +Test the built artifacts: + +```bash +# Install and test locally +npm pack && npm install ./project-{VERSION}.tgz +pip install dist/project-{VERSION}.whl + +# Run smoke tests +npm run test:smoke +pytest tests/smoke/ +``` + +### 5. Update Changelog + +Update CHANGELOG.md following [Keep a Changelog](https://keepachangelog.com/) format: + +```markdown +# Changelog + +## [X.Y.Z] - YYYY-MM-DD + +### Added +- New feature description (#PR) + +### Changed +- Changed behavior description (#PR) + +### Fixed +- Bug fix description (#PR) + +### Security +- Security fix description (#PR) + +### Deprecated +- Deprecated feature notice + +### Removed +- Removed feature notice +``` + +### 6. Commit Version Changes + +```bash +# Stage all version-related changes +git add -A + +# Commit with descriptive message +git commit -m "chore(release): prepare v{MAJOR}.{MINOR}.{PATCH} + +- Update version numbers +- Update changelog +- Update documentation" +``` + +### 7. Create Version Tags + +```bash +# Create annotated tag +git tag -a v{MAJOR}.{MINOR}.{PATCH} -m "Release v{MAJOR}.{MINOR}.{PATCH} + +## Highlights +- Key feature or fix 1 +- Key feature or fix 2 + +See CHANGELOG.md for full details." + +# For projects using stable tags +git tag -a v{MAJOR}.{MINOR}.{PATCH}-stable -m "Stable release v{MAJOR}.{MINOR}.{PATCH}" +``` + +### 8. Push to Remote + +```bash +# Check for existing tags +git ls-remote --tags origin + +# If tags need to be replaced (use with caution) +git push origin --delete v{MAJOR}.{MINOR}.{PATCH} + +# Push branch and tags +git push origin release/v{MAJOR}.{MINOR}.{PATCH} +git push origin --tags + +# For multiple remotes +git push github release/v{MAJOR}.{MINOR}.{PATCH} --tags +git push gitlab release/v{MAJOR}.{MINOR}.{PATCH} --tags +``` + +### 9. Create GitHub/GitLab Release + +**Using GitHub CLI:** + +```bash +gh release create v{MAJOR}.{MINOR}.{PATCH} \ + --title "v{MAJOR}.{MINOR}.{PATCH}" \ + --notes-file RELEASE_NOTES.md \ + ./dist/* +``` + +**Using GitLab CLI:** + +```bash +glab release create v{MAJOR}.{MINOR}.{PATCH} \ + --name "v{MAJOR}.{MINOR}.{PATCH}" \ + --notes-file RELEASE_NOTES.md \ + ./dist/* +``` + +### 10. Merge into Main + +```bash +# Merge release branch +git checkout main +git merge release/v{MAJOR}.{MINOR}.{PATCH} --no-ff \ + -m "Merge release v{MAJOR}.{MINOR}.{PATCH} into main" + +# Push to all remotes +git push origin main +git push github main +git push gitlab main +``` + +### 11. Clean Up + +```bash +# Delete local release branch +git branch -d release/v{MAJOR}.{MINOR}.{PATCH} + +# Delete remote release branch (optional) +git push origin --delete release/v{MAJOR}.{MINOR}.{PATCH} +``` + +## Post-Release Tasks + +### Immediate Tasks + +1. **Verify release artifacts**: Check all download links work +2. **Update documentation site**: Deploy updated docs +3. **Notify stakeholders**: Send release announcement +4. **Monitor for issues**: Watch for bug reports + +### Follow-up Tasks + +1. **Update dependent projects**: Bump version in downstream projects +2. **Close release milestone**: Mark milestone as complete +3. **Start next version**: Create new milestone and branch +4. **Update roadmap**: Reflect completed work + +## Version Numbering Guidelines + +### Semantic Versioning (SemVer) + +Follow [semver.org](https://semver.org/) specification: + +- **MAJOR**: Incompatible API changes +- **MINOR**: Add functionality in backward-compatible manner +- **PATCH**: Backward-compatible bug fixes + +### Version Examples + +| Change Type | Before | After | +|-------------|--------|-------| +| Bug fix | 1.0.0 | 1.0.1 | +| New feature | 1.0.0 | 1.1.0 | +| Breaking change | 1.0.0 | 2.0.0 | +| Pre-release | 1.0.0 | 2.0.0-alpha.1 | +| Build metadata | 1.0.0 | 1.0.0+build.123 | + +### Pre-release Versions + +```text +1.0.0-alpha.1 # Alpha release +1.0.0-beta.1 # Beta release +1.0.0-rc.1 # Release candidate +``` + +## Automated Release with CI/CD + +### GitHub Actions Example + +```yaml +name: Release + +on: + push: + tags: + - 'v*' + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Build + run: npm run build + + - name: Create Release + uses: softprops/action-gh-release@v1 + with: + files: dist/* + generate_release_notes: true +``` + +### GitLab CI Example + +```yaml +release: + stage: deploy + rules: + - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/ + script: + - npm run build + release: + tag_name: $CI_COMMIT_TAG + description: 'Release $CI_COMMIT_TAG' +``` + +## Rollback Procedures + +If a release needs to be rolled back: + +### 1. Identify the Issue + +```bash +# Check recent commits +git log --oneline -10 + +# Identify problematic changes +git diff v{PREVIOUS} v{CURRENT} +``` + +### 2. Create Hotfix or Revert + +**Option A: Hotfix** + +```bash +git checkout -b hotfix/v{NEW_PATCH} +# Fix the issue +git commit -m "fix: resolve critical issue from v{CURRENT}" +``` + +**Option B: Revert** + +```bash +git revert +git commit -m "revert: rollback problematic changes from v{CURRENT}" +``` + +### 3. Deploy Rollback + +```bash +# Tag the rollback +git tag -a v{ROLLBACK} -m "Rollback release" +git push origin v{ROLLBACK} +``` + +## Release Communication Template + +### Release Announcement + +```markdown +# [Project Name] v{X.Y.Z} Released + +We're excited to announce the release of [Project Name] v{X.Y.Z}! + +## Highlights +- Feature 1: Description +- Feature 2: Description +- Bug fix: Description + +## Breaking Changes +- Description of any breaking changes + +## Upgrade Guide +1. Step to upgrade +2. Migration notes + +## Download +- [GitHub Release](link) +- [npm](link) +- [PyPI](link) + +## Full Changelog +See [CHANGELOG.md](link) for complete details. + +## Thanks +Thanks to all contributors who made this release possible! +``` + +## Troubleshooting + +### Tag Already Exists + +```bash +# Delete and recreate local tag +git tag -d v{VERSION} +git tag -a v{VERSION} -m "Release v{VERSION}" + +# Force push (use with caution) +git push origin v{VERSION} --force +``` + +### Failed CI/CD Pipeline + +1. Check build logs for errors +2. Fix issues in release branch +3. Re-tag after fixing: + + ```bash + git tag -d v{VERSION} + git tag -a v{VERSION} -m "Release v{VERSION}" + git push origin --delete v{VERSION} + git push origin v{VERSION} + ``` + +### Version Mismatch + +If version numbers are inconsistent: + +```bash +# Find all version references +grep -r "version" --include="*.json" --include="*.py" --include="*.go" + +# Update all to match +``` diff --git a/.agent/workflows/wordpress-local-testing.md b/.agent/workflows/wordpress-local-testing.md new file mode 100644 index 00000000..63d897e0 --- /dev/null +++ b/.agent/workflows/wordpress-local-testing.md @@ -0,0 +1,470 @@ +# WordPress Local Testing Guide + +This guide provides instructions for setting up and running local WordPress testing environments for plugin and theme development. + +## Overview + +Three primary testing approaches are available: + +| Approach | Best For | Setup Time | Persistence | +|----------|----------|------------|-------------| +| **WordPress Playground** | Quick testing, demos | Instant | None | +| **LocalWP** | Full development | 5-10 min | Full | +| **wp-env** | CI/CD, testing | 2-5 min | Partial | + +## WordPress Playground CLI + +Uses `@wp-playground/cli` for instant browser-based WordPress testing. + +### When to Use + +- Quick plugin functionality testing +- Verifying admin UI changes +- Testing single site vs multisite behavior +- Demos and screenshots +- CI/CD pipeline testing + +### Installation + +```bash +npm install -g @wp-playground/cli + +# Or as project dependency +npm install --save-dev @wp-playground/cli +``` + +### Quick Start + +```bash +# Start single site on port 8888 +npx @wp-playground/cli server --port=8888 + +# Start with blueprint +npx @wp-playground/cli server --blueprint=blueprint.json +``` + +### Blueprint Configuration + +Create `blueprint.json` for reproducible setups: + +```json +{ + "$schema": "https://playground.wordpress.net/blueprint-schema.json", + "landingPage": "/wp-admin/", + "login": true, + "features": { + "networking": true + }, + "phpExtensionBundles": ["kitchen-sink"], + "steps": [ + { + "step": "defineWpConfigConsts", + "consts": { + "WP_DEBUG": true, + "WP_DEBUG_LOG": true, + "WP_DEBUG_DISPLAY": false, + "SCRIPT_DEBUG": true + } + }, + { + "step": "installPlugin", + "pluginZipFile": { + "resource": "url", + "url": "https://downloads.wordpress.org/plugin/query-monitor.latest-stable.zip" + } + }, + { + "step": "installPlugin", + "pluginZipFile": { + "resource": "directory", + "path": "." + }, + "options": { + "activate": true + } + } + ] +} +``` + +### Multisite Blueprint + +```json +{ + "$schema": "https://playground.wordpress.net/blueprint-schema.json", + "landingPage": "/wp-admin/network/", + "login": true, + "steps": [ + { + "step": "enableMultisite" + }, + { + "step": "installPlugin", + "pluginZipFile": { + "resource": "directory", + "path": "." + }, + "options": { + "activate": true, + "networkActivate": true + } + } + ] +} +``` + +### NPM Scripts + +Add to `package.json`: + +```json +{ + "scripts": { + "playground:start": "wp-playground server --port=8888 --blueprint=blueprint.json", + "playground:start:multisite": "wp-playground server --port=8889 --blueprint=multisite-blueprint.json", + "playground:stop": "pkill -f 'wp-playground' || true" + } +} +``` + +## LocalWP Integration + +LocalWP provides a full WordPress environment with database persistence. + +### Prerequisites + +- LocalWP installed ([localwp.com](https://localwp.com)) +- Default sites directory: `~/Local Sites/` + +### When to Use + +- Testing database migrations +- Long-term development environment +- Testing with specific PHP/MySQL versions +- Network/multisite configuration +- WP-CLI command testing + +### Site Setup + +1. Open LocalWP +2. Click "+" to create new site +3. Configure: + - **Name**: `project-name-single` or `project-name-multisite` + - **PHP Version**: Match production requirements + - **Web Server**: nginx or Apache + - **Database**: MySQL 8.0+ + +### Plugin Sync Script + +Create `bin/localwp-sync.sh`: + +```bash +#!/bin/bash +set -e + +PLUGIN_SLUG="your-plugin-slug" +LOCALWP_SITES="$HOME/Local Sites" +SITE_NAME="project-name-single" +PLUGIN_DIR="$LOCALWP_SITES/$SITE_NAME/app/public/wp-content/plugins/$PLUGIN_SLUG" + +# Sync plugin files +rsync -av --delete \ + --exclude='node_modules' \ + --exclude='vendor' \ + --exclude='tests' \ + --exclude='.git' \ + --exclude='dist' \ + --exclude='.env' \ + ./ "$PLUGIN_DIR/" + +echo "Plugin synced to LocalWP" +``` + +### WP-CLI with LocalWP + +```bash +# Find WP-CLI path +/Applications/Local.app/Contents/Resources/extraResources/bin/wp-cli.phar + +# Create alias +alias lwp='/Applications/Local.app/Contents/Resources/extraResources/bin/wp-cli.phar' + +# Use with site +cd "~/Local Sites/project-name/app/public" +lwp plugin list +lwp option get siteurl +``` + +## wp-env (Docker) + +Docker-based environment using `@wordpress/env`. + +### Prerequisites + +- Docker Desktop installed and running +- Node.js 18+ + +### Installation + +```bash +npm install -g @wordpress/env + +# Or as project dependency +npm install --save-dev @wordpress/env +``` + +### Configuration + +Create `.wp-env.json`: + +```json +{ + "core": "WordPress/WordPress#6.4", + "phpVersion": "8.1", + "plugins": [".", "https://downloads.wordpress.org/plugin/query-monitor.latest-stable.zip"], + "themes": [], + "config": { + "WP_DEBUG": true, + "WP_DEBUG_LOG": true, + "SCRIPT_DEBUG": true + }, + "mappings": { + "wp-content/uploads": "./uploads" + } +} +``` + +### Multisite Configuration + +Create `.wp-env.json` for multisite: + +```json +{ + "core": "WordPress/WordPress#6.4", + "phpVersion": "8.1", + "plugins": ["."], + "config": { + "WP_DEBUG": true, + "WP_ALLOW_MULTISITE": true, + "MULTISITE": true, + "SUBDOMAIN_INSTALL": false, + "DOMAIN_CURRENT_SITE": "localhost", + "PATH_CURRENT_SITE": "/", + "SITE_ID_CURRENT_SITE": 1, + "BLOG_ID_CURRENT_SITE": 1 + } +} +``` + +### Commands + +```bash +# Start environment +wp-env start + +# Stop environment +wp-env stop + +# Destroy and rebuild +wp-env destroy +wp-env start + +# Run WP-CLI commands +wp-env run cli wp plugin list +wp-env run cli wp option get siteurl +wp-env run cli wp user list + +# Run tests +wp-env run tests-cli phpunit + +# Access shell +wp-env run cli bash +``` + +### NPM Scripts + +```json +{ + "scripts": { + "start": "wp-env start", + "stop": "wp-env stop", + "destroy": "wp-env destroy", + "cli": "wp-env run cli", + "test:phpunit": "wp-env run tests-cli phpunit", + "test:phpunit:multisite": "wp-env run tests-cli phpunit --configuration phpunit-multisite.xml" + } +} +``` + +## Testing Workflows + +### Quick Feature Verification + +```bash +# Start Playground +npm run playground:start + +# Make code changes +# Refresh browser to see changes + +# Stop when done +npm run playground:stop +``` + +### PHPUnit Testing + +```bash +# With wp-env +wp-env run tests-cli phpunit + +# With Composer +composer test + +# Specific test file +vendor/bin/phpunit tests/test-feature.php + +# With coverage +vendor/bin/phpunit --coverage-html coverage/ +``` + +### E2E Testing with Cypress + +```bash +# Start environment +npm run start + +# Run Cypress +npx cypress run + +# Interactive mode +npx cypress open +``` + +### E2E Testing with Playwright + +```bash +# Start environment +npm run start + +# Run Playwright +npx playwright test + +# Interactive mode +npx playwright test --ui +``` + +## Environment Comparison + +| Feature | Playground | LocalWP | wp-env | +|---------|------------|---------|--------| +| Setup Time | Instant | 5-10 min | 2-5 min | +| Persistence | None | Full | Partial | +| PHP Versions | Limited | Many | Configurable | +| Database | In-memory | MySQL | MySQL | +| WP-CLI | Yes | Yes | Yes | +| Multisite | Yes | Yes | Yes | +| Docker Required | No | No | Yes | +| GitHub Actions | Works* | N/A | Works | +| Best For | Quick testing | Full dev | CI/Testing | + +*Playground may be flaky in CI environments + +## Debugging Tools + +### Query Monitor Plugin + +Automatically installed in blueprints above. Access via admin bar to view: +- Database queries +- PHP errors +- HTTP requests +- Hooks and actions + +### Debug Bar + +```bash +wp-env run cli wp plugin install debug-bar --activate +``` + +### Error Logging + +```php +// wp-config.php additions (via blueprint or config) +define('WP_DEBUG', true); +define('WP_DEBUG_LOG', true); +define('WP_DEBUG_DISPLAY', false); +define('SCRIPT_DEBUG', true); +define('SAVEQUERIES', true); +``` + +View logs: + +```bash +# wp-env +wp-env run cli tail -f /var/www/html/wp-content/debug.log + +# LocalWP +tail -f "~/Local Sites/site-name/app/public/wp-content/debug.log" +``` + +## Common Issues and Solutions + +### Port Already in Use + +```bash +# Check what's using the port +lsof -i :8888 + +# Kill the process +kill $(lsof -t -i :8888) +``` + +### Docker Issues (wp-env) + +```bash +# Restart Docker +wp-env stop +docker system prune -f +wp-env start + +# Check Docker status +docker ps +docker logs $(docker ps -q --filter name=wordpress) +``` + +### LocalWP Site Not Starting + +1. Check LocalWP logs in the app +2. Verify Docker/services are running +3. Try restarting the site +4. Check for port conflicts + +### Playground Won't Start + +1. Ensure Node.js 18+ is installed +2. Check npm dependencies: `npm install` +3. View logs: `cat .playground.log` +4. Try different port: `--port=9000` + +## Testing Checklist + +Before releasing: + +- [ ] Tested on single site +- [ ] Tested on multisite +- [ ] Tested with minimum PHP version +- [ ] Tested with minimum WordPress version +- [ ] Tested with latest WordPress version +- [ ] PHPUnit tests passing +- [ ] E2E tests passing +- [ ] No PHP errors/warnings in debug log +- [ ] No JavaScript console errors +- [ ] Tested activation/deactivation +- [ ] Tested uninstall process + +## Resources + +- [WordPress Playground](https://wordpress.github.io/wordpress-playground/) +- [WordPress Playground Blueprints](https://wordpress.github.io/wordpress-playground/blueprints) +- [LocalWP Documentation](https://localwp.com/help-docs/) +- [@wordpress/env Documentation](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-env/) +- [PHPUnit for WordPress](https://make.wordpress.org/core/handbook/testing/automated-testing/phpunit/) diff --git a/.coderabbit.yaml b/.coderabbit.yaml index 452dd577..04a3f4d8 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -95,3 +95,5 @@ path_filters: - ".agent/memory/*" - "*.log" - "*.tmp" + +# Trigger for comprehensive codebase review diff --git a/.markdownlint.json b/.markdownlint.json index a15e6dbf..ad37930e 100644 --- a/.markdownlint.json +++ b/.markdownlint.json @@ -16,6 +16,7 @@ "MD029": { "style": "ordered" }, + "MD032": false, "MD033": { "allowed_elements": [ "br", @@ -33,5 +34,6 @@ "MD041": false, "MD046": { "style": "fenced" - } + }, + "MD060": false }