diff --git a/.claude/README.md b/.claude/README.md new file mode 100644 index 0000000..c21ecd7 --- /dev/null +++ b/.claude/README.md @@ -0,0 +1,147 @@ +# Claude Code Configuration + +Claude Code operates as one agent among equals in this repository. + +## Quick Start + +See main documentation: +- [Agent Collaboration]../.github/AGENT_COLLABORATION.md) - Multi-agent guidelines +- [Development Environment](../DEVCONTAINER_AND_AUTOMATION.md) - DevOps and automation +- [Copilot Instructions](../.github/copilot-instructions.md) - Copilot configuration + +## Project Overview + +**Bleedy** - Web app for adding bleed margins to images + +**Stack**: Vue 3 + TypeScript + Vite + PyScript + Element Plus + +**Key Commands**: +```bash +npm install # Always run first (applies patches) +npm run dev # Start dev server (localhost:5173) +npm run build # Build for production (~8-10s) +npm run lint # Run ESLint +``` + +## Claude Code Specifics + +### Tools Available + +- **TodoWrite** - Task tracking (use for complex multi-step tasks) +- **Direct git access** - Can commit and push directly +- **Bash** - Full shell access +- **File operations** - Read, Write, Edit tools + +### When to Use Claude Code + +**Best for**: +- Complex multi-file refactoring requiring systematic planning +- Feature implementation needing task decomposition +- Deep debugging across multiple files +- CI/CD workflow development + +**Not ideal for**: +- Simple fixes → Use @copilot (unlimited usage) +- Quick edits → Use @copilot +- Code review → Use @coderabbitai (automated, unlimited) + +**Strategy**: Start with unlimited agents (Copilot, CodeRabbit). Escalate to Claude Code when their unique capabilities justify the usage cost. + +### Git Workflow + +Claude Code can commit and push directly: + +```bash +# Changes are committed with descriptive messages +# Includes "Generated with Claude Code" footer +git add . +git commit -m "message" +git push -u origin +``` + +**Branch naming**: Must start with `claude/` and end with matching session ID (enforced by server) + +**Push retries**: Up to 4 retries with exponential backoff for network errors + +### Task Management + +Use TodoWrite for complex tasks: +- Track multi-step implementations +- Show progress to users +- Ensure no tasks are forgotten + +### Repository-Specific Notes + +1. **npm version**: Requires npm 11.0.0+ for proper patch application +2. **Patched dependencies**: Always run `npm install` first +3. **ESLint 9.x**: Uses flat config (`eslint.config.js`) +4. **No tests yet**: `npm test` will fail +5. **Build warnings**: Large chunk size warnings are expected (PyScript) + +### Testing Before Commit + +Always verify: +```bash +npm run lint # Must pass +npm run build # Must complete successfully +``` + +### Multi-Agent Coordination + +When handing off to other agents: +- Use templates from `.github/AGENT_COLLABORATION.md` +- Mention agents with @ (e.g., @copilot, @coderabbitai) +- Paste review content (don't use URLs - agents can't access them) +- Reference specific files and line numbers + +### GitHub MCP Server + +This repo uses GitHub's official MCP server (`.mcp/config.json`): +- Claude Code uses direct git (not MCP for git operations) +- Other agents may use MCP for GitHub API access +- See `.github/AGENT_COLLABORATION.md` for details + +### Development Environment + +**Devcontainer available**: See `.devcontainer/README.md` +- Node.js 20 base image +- Pre-installed: GitHub CLI, Python 3, Docker-in-Docker +- Auto-setup via `postCreateCommand.sh` + +**Environment script**: `bash scripts/setup-agent-environment.sh` +- Configures git for PR refs +- Creates helpful git aliases +- Verifies tool availability + +## Additional Resources + +- **DEVCONTAINER_AND_AUTOMATION.md** - Full DevOps guide +- **.github/ACCESSING_PR_REVIEWS.md** - How to access PR reviews programmatically +- **OVERHAUL_STRATEGY.md** - Recent modernization strategy +- **docs/** - Architecture, design patterns, Python integration + +## Common Tasks + +### Feature Implementation +1. Use TodoWrite to create task list +2. Implement systematically +3. Test with `npm run build && npm run lint` +4. Commit with clear message +5. Push to `claude/*` branch + +### Bug Fixes +1. Investigate using file search tools +2. Fix and test locally +3. Verify no regressions +4. Commit and push + +### Refactoring +1. Plan changes (TodoWrite) +2. Make minimal, focused changes +3. Test thoroughly +4. Document if needed + +--- + +**Last Updated**: 2025-11-15 +**For detailed information**: See main documentation files listed above diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..090691c --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,87 @@ +# Multi-Agent Development Container for Bleedy +# Optimized for collaboration between Claude Code, GitHub Copilot, CodeRabbit, and other AI agents + +FROM node:20-bookworm + +# Avoid warnings by switching to noninteractive +ENV DEBIAN_FRONTEND=noninteractive + +# Configure apt and install packages +RUN apt-get update \ + && apt-get -y install --no-install-recommends \ + # Essential development tools + git \ + curl \ + wget \ + ca-certificates \ + gnupg \ + lsb-release \ + # Python for automation scripts + python3 \ + python3-pip \ + python3-venv \ + # Build tools + build-essential \ + # Additional tools for multi-agent collaboration + jq \ + vim \ + nano \ + less \ + # Clean up + && apt-get autoremove -y \ + && apt-get clean -y \ + && rm -rf /var/lib/apt/lists/* + +# Install GitHub CLI +RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \ + && chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \ + && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null \ + && apt-get update \ + && apt-get install -y gh \ + && apt-get clean -y \ + && rm -rf /var/lib/apt/lists/* + +# Set up npm global directory with correct permissions +ENV NPM_CONFIG_PREFIX=/usr/local/share/npm-global +ENV PATH=$NPM_CONFIG_PREFIX/bin:$PATH +RUN mkdir -p /usr/local/share/npm-global \ + && chown -R node:node /usr/local/share/npm-global + +# Install global npm packages +RUN npm install -g npm@latest \ + && npm install -g \ + prettier@latest \ + eslint@latest \ + typescript@latest \ + @vue/language-server@latest + +# Configure git for PR refs (enables programmatic PR access) +RUN git config --system --add fetch.prune true \ + && git config --system --add core.autocrlf input \ + && git config --system --add pull.rebase false + +# Set up Python environment +RUN pip3 install --no-cache-dir --break-system-packages \ + pyyaml \ + requests \ + python-dotenv + +# Create command history directory +RUN SNIPPET="export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhistory/.bash_history" \ + && mkdir -p /commandhistory \ + && touch /commandhistory/.bash_history \ + && chown -R node:node /commandhistory \ + && echo "$SNIPPET" >> "/home/node/.bashrc" + +# Create workspace directory +RUN mkdir -p /workspace \ + && chown -R node:node /workspace + +# Switch back to dialog for any ad-hoc use of apt-get +ENV DEBIAN_FRONTEND=dialog + +# Set the default user +USER node + +# Set working directory +WORKDIR /workspace diff --git a/.devcontainer/README.md b/.devcontainer/README.md new file mode 100644 index 0000000..89ee2b7 --- /dev/null +++ b/.devcontainer/README.md @@ -0,0 +1,261 @@ +# Development Container Configuration + +This directory contains the development container (devcontainer) configuration for the Bleedy project, optimized for multi-agent collaboration. + +## Overview + +The devcontainer provides a **consistent, reproducible development environment** for all developers and AI agents working on the project, including: + +- **Claude Code** - Advanced code generation and refactoring +- **GitHub Copilot** - Inline code suggestions +- **CodeRabbit** - Automated code reviews +- **ChatGPT Codex** - GitHub-integrated automation +- **Human developers** - Traditional development + +## What's Included + +### Base Image + +- **Node.js 20** (Debian Bookworm) +- Matches production environment and `@tsconfig/node20` configuration + +### Pre-installed Tools + +1. **GitHub CLI (`gh`)** - Essential for PR access and GitHub operations +2. **Docker-in-Docker** - For running Docker-based CI locally +3. **Git** (latest) - With enhanced configuration +4. **Python 3** - For automation scripts +5. **Build tools** - gcc, make, etc. +6. **Utilities** - jq, curl, wget, vim, nano + +### VS Code Extensions + +Automatically installed when opening in VS Code: + +- **Vue.volar** - Vue 3 support +- **ESLint** - Linting +- **Prettier** - Code formatting +- **Python** - Python development +- **GitHub Copilot** - AI pair programming +- **GitLens** - Enhanced git integration +- **Docker** - Container management +- **GitHub Pull Requests** - PR management + +### Configuration Features + +1. **Automatic setup** - Runs `postCreateCommand.sh` after container creation +2. **Port forwarding** - Vite dev (5173) and preview (4173) servers +3. **Volume mounts** - Persistent npm cache and bash history +4. **Git PR refs** - Configured to fetch PR references +5. **Environment variables** - Multi-agent mode enabled + +## Quick Start + +### Using VS Code + +1. Install the **Dev Containers** extension +2. Open the project in VS Code +3. Click "Reopen in Container" when prompted +4. Wait for setup to complete (~2-5 minutes first time) + +### Using Command Line + +```bash +# Build and start the container +docker build -t bleedy-devcontainer -f .devcontainer/Dockerfile . + +# Run the container +docker run -it -v $(pwd):/workspace -p 5173:5173 -p 4173:4173 bleedy-devcontainer + +# Inside container, run setup +cd /workspace +bash .devcontainer/postCreateCommand.sh +``` + +## Post-Creation Setup + +The `postCreateCommand.sh` script automatically: + +1. ✅ Installs npm dependencies +2. ✅ Configures git for PR refs +3. ✅ Sets up git aliases +4. ✅ Makes scripts executable +5. ✅ Runs agent environment setup +6. ✅ Verifies build +7. ✅ Displays quick start guide + +## Environment Variables + +Copy `.env.example` to `.env.local` and configure: + +```bash +cp .env.example .env.local +# Edit .env.local with your settings +``` + +Key variables: + +- `MULTI_AGENT_MODE=true` - Enables multi-agent features +- `GITHUB_TOKEN` - For API access (optional) +- `AGENT_NAME` - Identifies which agent is working + +## GitHub CLI Setup + +After container is created, authenticate GitHub CLI: + +```bash +gh auth login +``` + +This enables: + +- PR listing and viewing +- Issue management +- Repository operations +- API access + +## Testing the Setup + +Verify everything is working: + +```bash +# Check tools +node --version # Should show v20.x +npm --version # Should show v11.x+ +gh --version # Should show latest +python3 --version # Should show Python 3.x + +# Test project +npm run dev # Start dev server +npm run build # Build project +npm run lint # Lint code + +# Test multi-agent features +bash scripts/setup-agent-environment.sh +python3 scripts/get_pr_reviews.py --help +``` + +## Customization + +### Adding Tools + +Edit `Dockerfile` to add new tools: + +```dockerfile +RUN apt-get update && apt-get install -y \ + your-new-tool \ + && apt-get clean +``` + +### Adding VS Code Extensions + +Edit `devcontainer.json`: + +```json +"extensions": [ + "publisher.extension-name" +] +``` + +### Changing Ports + +Edit `devcontainer.json`: + +```json +"forwardPorts": [5173, 4173, 8080] +``` + +## Troubleshooting + +### Container Won't Build + +```bash +# Clean rebuild +docker system prune -a +docker build --no-cache -t bleedy-devcontainer -f .devcontainer/Dockerfile . +``` + +### npm install Fails + +```bash +# Clear npm cache +npm cache clean --force +rm -rf node_modules package-lock.json +npm install +``` + +### GitHub CLI Not Authenticated + +```bash +gh auth login +# Follow prompts to authenticate +``` + +### Git Config Issues + +```bash +# Reset git config +git config --local --unset-all remote.origin.fetch +bash scripts/setup-agent-environment.sh +``` + +## Multi-Agent Collaboration + +### For AI Agents + +After container setup: + +1. **Authenticate GitHub CLI** (if possible in your environment) +2. **Run environment setup**: `bash scripts/setup-agent-environment.sh` +3. **Read collaboration docs**: `.github/AGENT_COLLABORATION.md` +4. **Check PR access guide**: `.github/ACCESSING_PR_REVIEWS.md` + +### For Human Developers + +1. **Use the devcontainer** for consistent environment +2. **Coordinate with agents** using templates in `.github/` +3. **Review agent changes** via PR templates +4. **Provide feedback** that agents can parse and act on + +## Files in This Directory + +- `devcontainer.json` - Dev container configuration +- `Dockerfile` - Container image definition +- `postCreateCommand.sh` - Post-creation setup script +- `README.md` - This file + +## Related Documentation + +- [Multi-Agent Collaboration Guide](../.github/AGENT_COLLABORATION.md) +- [Accessing PR Reviews](../.github/ACCESSING_PR_REVIEWS.md) +- [DevOps Guide](../DEVCONTAINER_AND_AUTOMATION.md) +- [Claude Code Instructions](../.claude/README.md) +- [Copilot Instructions](../.github/copilot-instructions.md) + +## Performance Tips + +1. **Use volume mounts** - Keeps npm cache persistent +2. **Rebuild selectively** - Only rebuild when Dockerfile changes +3. **Close unused terminals** - Saves resources +4. **Use multi-stage builds** - If adding complex tools + +## Security Notes + +1. **Never commit `.env.local`** - Contains sensitive tokens +2. **Use GitHub secrets** - For CI/CD credentials +3. **Rotate tokens regularly** - GitHub tokens should be rotated +4. **Review Dockerfile changes** - Before merging PRs + +## Support + +For issues with the devcontainer: + +1. Check this README and related documentation +2. Search existing GitHub issues +3. Create a new issue with the `devcontainer` label +4. Tag relevant agents for collaboration + +--- + +**Last Updated**: 2025-10-21 +**Maintained by**: Multi-agent collaboration team diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..57da1ac --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,111 @@ +{ + "name": "Bleedy Multi-Agent Development", + "dockerFile": "Dockerfile", + "context": "..", + + // Configure tool-specific properties + "customizations": { + "vscode": { + "settings": { + "terminal.integrated.defaultProfile.linux": "bash", + "editor.formatOnSave": true, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit" + }, + "[javascript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[typescript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[vue]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[json]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[markdown]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "files.eol": "\n", + "files.insertFinalNewline": true, + "files.trimTrailingWhitespace": true + }, + "extensions": [ + "Vue.volar", + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "ms-python.python", + "ms-python.vscode-pylance", + "GitHub.copilot", + "GitHub.copilot-chat", + "eamodio.gitlens", + "redhat.vscode-yaml", + "ms-azuretools.vscode-docker", + "GitHub.vscode-pull-request-github" + ] + } + }, + + // Use 'forwardPorts' to make a list of ports inside the container available locally + "forwardPorts": [5173, 4173], + + // Configure port labels + "portsAttributes": { + "5173": { + "label": "Vite Dev Server", + "onAutoForward": "notify" + }, + "4173": { + "label": "Vite Preview Server", + "onAutoForward": "notify" + } + }, + + // Use 'postCreateCommand' to run commands after the container is created + "postCreateCommand": "bash .devcontainer/postCreateCommand.sh", + + // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root + "remoteUser": "node", + + // Set environment variables + "containerEnv": { + "NODE_ENV": "development", + "MULTI_AGENT_MODE": "true" + // Note: GITHUB_TOKEN should be set in .env.local for MCP server + // See .mcp/config.json for GitHub MCP server configuration + }, + + // Mount configuration + "mounts": [ + // Cache npm global modules + "source=bleedy-node-modules,target=/usr/local/share/npm-global,type=volume", + // Persist bash history + "source=bleedy-bashhistory,target=/commandhistory,type=volume" + ], + + // Features to add to the dev container + "features": { + "ghcr.io/devcontainers/features/github-cli:1": { + "version": "latest" + }, + "ghcr.io/devcontainers/features/docker-in-docker:2": { + "version": "latest", + "dockerDashComposeVersion": "v2" + }, + "ghcr.io/devcontainers/features/git:1": { + "version": "latest", + "ppa": true + }, + "ghcr.io/devcontainers/features/common-utils:2": { + "installZsh": true, + "configureZshAsDefaultShell": false, + "installOhMyZsh": true, + "upgradePackages": true, + "username": "node", + "userUid": "automatic", + "userGid": "automatic" + } + } +} diff --git a/.devcontainer/postCreateCommand.sh b/.devcontainer/postCreateCommand.sh new file mode 100755 index 0000000..5b32862 --- /dev/null +++ b/.devcontainer/postCreateCommand.sh @@ -0,0 +1,111 @@ +#!/bin/bash +# Post-create command for devcontainer +# Runs after container is created to set up the development environment + +set -e + +echo "🚀 Setting up Bleedy development environment for multi-agent collaboration..." + +# Colors for output +GREEN='\033[0;32m' +BLUE='\033[0;34m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Function to print colored output +print_status() { + echo -e "${BLUE}[SETUP]${NC} $1" +} + +print_success() { + echo -e "${GREEN}[✓]${NC} $1" +} + +print_warning() { + echo -e "${YELLOW}[!]${NC} $1" +} + +# Install npm dependencies +print_status "Installing npm dependencies..." +npm install +print_success "npm dependencies installed" + +# Configure git for PR access +print_status "Configuring git for PR refs..." +git config --add remote.origin.fetch '+refs/pull/*/head:refs/remotes/origin/pr/*' || true +git config --add remote.origin.fetch '+refs/pull/*/merge:refs/remotes/origin/pr-merge/*' || true +print_success "Git configured for PR access" + +# Try to fetch PR refs (may fail if not authenticated, which is OK) +print_status "Attempting to fetch PR refs..." +git fetch origin 2>/dev/null || print_warning "Could not fetch PR refs (authentication may be needed)" + +# Set up git user if not configured +if [ -z "$(git config user.name)" ]; then + print_warning "Git user.name not set. Set it with: git config user.name 'Your Name'" +fi + +if [ -z "$(git config user.email)" ]; then + print_warning "Git user.email not set. Set it with: git config user.email 'your.email@example.com'" +fi + +# Verify GitHub CLI +if command -v gh &> /dev/null; then + print_success "GitHub CLI (gh) is available" + # Check auth status (won't fail if not authenticated) + gh auth status 2>/dev/null && print_success "GitHub CLI is authenticated" || print_warning "GitHub CLI not authenticated. Run: gh auth login" +else + print_warning "GitHub CLI (gh) is not available" +fi + +# Verify Python +if command -v python3 &> /dev/null; then + PYTHON_VERSION=$(python3 --version 2>&1) + print_success "Python is available: $PYTHON_VERSION" +else + print_warning "Python is not available" +fi + +# Make scripts executable +print_status "Making scripts executable..." +chmod +x scripts/*.sh 2>/dev/null || true +chmod +x scripts/*.py 2>/dev/null || true +chmod +x automation/*.py 2>/dev/null || true +print_success "Scripts are executable" + +# Run agent environment setup +if [ -f "scripts/setup-agent-environment.sh" ]; then + print_status "Running agent environment setup..." + bash scripts/setup-agent-environment.sh +else + print_warning "Agent environment setup script not found" +fi + +# Verify build +print_status "Verifying build..." +if npm run build > /dev/null 2>&1; then + print_success "Build verification passed" +else + print_warning "Build verification failed - you may need to run 'npm run build' manually" +fi + +echo "" +echo -e "${GREEN}========================================${NC}" +echo -e "${GREEN}✓ Development environment ready!${NC}" +echo -e "${GREEN}========================================${NC}" +echo "" +echo "Quick start commands:" +echo " npm run dev - Start development server" +echo " npm run build - Build for production" +echo " npm run lint - Run ESLint" +echo " npm run format - Format code with Prettier" +echo "" +echo "Multi-agent collaboration:" +echo " See: .github/AGENT_COLLABORATION.md" +echo " See: .github/ACCESSING_PR_REVIEWS.md" +echo "" +echo "For GitHub operations:" +echo " gh auth login - Authenticate with GitHub" +echo " gh pr list - List pull requests" +echo " gh pr view - View PR details" +echo "" diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..d1b55b5 --- /dev/null +++ b/.env.example @@ -0,0 +1,129 @@ +# Environment Variables Template for Bleedy +# Copy this file to .env.local and configure with your values +# DO NOT commit .env.local to version control + +# ============================================ +# Multi-Agent Collaboration +# ============================================ + +# Enable multi-agent mode (set by devcontainer automatically) +MULTI_AGENT_MODE=true + +# Agent identification (optional - helps track which agent made changes) +# Options: claude-code, copilot, codex, coderabbitai, human +AGENT_NAME= + +# ============================================ +# GitHub Configuration +# ============================================ + +# GitHub Personal Access Token (for API access) +# Required for: PR reviews, branch management, automation scripts +# Scopes needed: repo, read:org, workflow +# Generate at: https://github.com/settings/tokens +# GITHUB_TOKEN=ghp_your_token_here + +# GitHub repository (auto-detected if not set) +# GITHUB_REPOSITORY=danelkay93/bleedy + +# GitHub API base URL (default: https://api.github.com) +# GITHUB_API_URL=https://api.github.com + +# ============================================ +# Development Settings +# ============================================ + +# Node environment +NODE_ENV=development + +# Vite development server port +VITE_PORT=5173 + +# Vite preview server port +VITE_PREVIEW_PORT=4173 + +# Application title +VITE_APP_TITLE=Bleedy - Bleed Margin Tool + +# Enable debug mode +DEBUG=false + +# ============================================ +# Build Configuration +# ============================================ + +# Build output directory +BUILD_OUTPUT_DIR=dist + +# Source map generation (true for development, false for production) +GENERATE_SOURCEMAP=true + +# ============================================ +# CI/CD Settings +# ============================================ + +# Skip CI checks (for testing only) +# CI_SKIP_CHECKS=false + +# Docker build context +# DOCKER_BUILDKIT=1 + +# ============================================ +# Azure Static Web Apps (if used) +# ============================================ + +# Azure Static Web Apps API token (set in GitHub secrets) +# AZURE_STATIC_WEB_APPS_API_TOKEN= + +# App location +# APP_LOCATION=/ + +# API location +# API_LOCATION= + +# Output location +# OUTPUT_LOCATION=dist + +# ============================================ +# Pulumi (Infrastructure as Code) +# ============================================ + +# Pulumi access token (if using IaC) +# PULUMI_ACCESS_TOKEN= + +# Pulumi stack name +# PULUMI_STACK=dev + +# ============================================ +# Optional Tool Configuration +# ============================================ + +# ESLint cache +# ESLINT_USE_FLAT_CONFIG=true + +# Prettier cache +# PRETTIER_CACHE=true + +# TypeScript incremental builds +# TSC_COMPILE_ON_ERROR=true + +# ============================================ +# Agent-Specific Settings +# ============================================ + +# Claude Code settings +# CLAUDE_MAX_TOKENS= +# CLAUDE_TEMPERATURE= + +# Copilot settings +# COPILOT_SUGGESTIONS=true + +# CodeRabbit settings +# CODERABBIT_AUTO_REVIEW=true + +# ============================================ +# Local Development Overrides +# ============================================ + +# Add your local overrides below this line +# These will not be tracked in version control diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6ac7015 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,75 @@ +# Git attributes for consistent line endings and diff handling +# Ensures all agents work with the same file formatting + +# Auto detect text files and normalize line endings to LF +* text=auto eol=lf + +# Explicitly declare text files +*.js text eol=lf +*.ts text eol=lf +*.vue text eol=lf +*.json text eol=lf +*.md text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.sh text eol=lf +*.py text eol=lf +*.css text eol=lf +*.scss text eol=lf +*.html text eol=lf +*.xml text eol=lf +*.toml text eol=lf + +# Configuration files +.gitignore text eol=lf +.gitattributes text eol=lf +.editorconfig text eol=lf +.eslintrc* text eol=lf +.prettierrc* text eol=lf +tsconfig*.json text eol=lf +vite.config.* text eol=lf +vitest.config.* text eol=lf +package.json text eol=lf +package-lock.json text eol=lf + +# Scripts +*.sh text eol=lf +*.bash text eol=lf + +# Windows-specific files +*.bat text eol=crlf +*.cmd text eol=crlf +*.ps1 text eol=crlf + +# Binary files +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.svg binary +*.woff binary +*.woff2 binary +*.ttf binary +*.eot binary +*.pdf binary +*.zip binary +*.gz binary +*.tar binary + +# Language-specific diff drivers +*.vue diff=html +*.md diff=markdown + +# Lockfiles - prevent merge conflicts +package-lock.json merge=binary +pnpm-lock.yaml merge=binary +yarn.lock merge=binary + +# Generated files +*.min.js binary +*.min.css binary +dist/** binary + +# Git LFS (if used in future) +# *.psd filter=lfs diff=lfs merge=lfs -text diff --git a/.github/ACCESSING_PR_REVIEWS.md b/.github/ACCESSING_PR_REVIEWS.md new file mode 100644 index 0000000..02b4a8f --- /dev/null +++ b/.github/ACCESSING_PR_REVIEWS.md @@ -0,0 +1,226 @@ +# Accessing PR Reviews Programmatically - Guide for AI Agents + +## Overview + +This document provides guidance for AI agents attempting to access GitHub Pull Request reviews programmatically within the repository environment. + +## Current Environment Limitations + +### What's NOT Available + +1. **GitHub CLI (`gh`)** - Not installed in the environment + - Commands like `gh pr view`, `gh api` will fail with `FileNotFoundError` + - The `automation/branch_manager.py` script assumes `gh` is available but may fail in some environments + +2. **Direct HTTP API Access** - Path format unclear + - Attempted paths that failed: + - `http://127.0.0.1:19866/api/repos/{owner}/{repo}/pulls` + - `http://127.0.0.1:19866/repos/{owner}/{repo}/pulls` + - All returned: `400 Bad Request - Invalid path format` + +3. **Git Protocol for PRs** - Not configured + - No `refs/pull/*` references found + - No PR fetch configuration in git config + +### What IS Available + +1. **Git commands** - Full git access to repository +2. **curl** - HTTP client available +3. **Python 3** - Available for scripting +4. **File system access** - Full repository access +5. **Git history** - Can search commits for review-related messages + +## Recommended Approaches + +### Option 1: Request from User (MOST RELIABLE) + +Since direct API access has limitations, the most reliable approach is to request review information directly from the user: + +```markdown +I cannot access PR reviews programmatically due to environment limitations. +Could you please provide: +1. The review status (Approved / Changes Requested / Pending) +2. Any review comments from @copilot, @coderabbitai, or @codex +3. Whether I should proceed with the merge +``` + +### Option 2: Check Git Commit Messages + +Search git history for review-related information: + +```bash +# Search for review mentions +git log --all --grep="review\|@copilot\|@coderabbitai\|approved\|changes requested" -i --oneline + +# Check for review-related commits +git show :REVIEW_REQUEST.md +git show :REVIEW_RESPONSE.md +``` + +### Option 3: Check for Review Files in Repository + +Some workflows may leave review artifacts: + +```bash +# Look for review-related files +find . -name "*review*" -o -name "*feedback*" -type f + +# Check .github directory for review templates or responses +ls -la .github/*review* .github/*response* +``` + +### Option 4: Use MCP Tools (If Available) + +Some agents (like GitHub Copilot) may have Model Context Protocol (MCP) tools for GitHub operations: + +- Check if MCP GitHub tools are available +- Use `report_progress` or similar tools to query PR status +- This varies by agent implementation + +## For Future Environment Setup + +To enable programmatic PR review access, one of the following should be configured: + +### Option A: Install GitHub CLI + +```bash +# Install gh CLI in the container +apt-get update && apt-get install -y gh + +# Or download binary +wget https://github.com/cli/cli/releases/download/v2.40.0/gh_2.40.0_linux_amd64.deb +dpkg -i gh_2.40.0_linux_amd64.deb + +# Authenticate (if needed) +gh auth login +``` + +### Option B: Configure Git to Fetch PRs + +Add PR fetch configuration to git: + +```bash +git config --add remote.origin.fetch '+refs/pull/*/head:refs/pull/origin/*' +git fetch origin +``` + +Then access PR refs: + +```bash +git log refs/pull/origin/36/head +git diff master...refs/pull/origin/36/head +``` + +### Option C: Clarify Internal API Path Format + +Document the correct internal API path format for the environment: + +```bash +# What is the correct path? +# Examples that should work: +curl "http://127.0.0.1:PORT/??/repos/{owner}/{repo}/pulls/{number}/reviews" + +# Once identified, document here +``` + +## Implementation: PR Review Access Script + +A Python script has been created at `scripts/get_pr_reviews.py` that demonstrates the intended approach using `gh` CLI: + +```python +# Usage (if gh CLI is available): +python3 scripts/get_pr_reviews.py 36 +python3 scripts/get_pr_reviews.py claude/update-documentation-integration-011CULn7AGnkyHBdk8qWi4qx +``` + +**Current Status**: Script fails because `gh` is not installed + +## Agent-Specific Approaches + +### Claude Code + +- **Limitation**: Cannot access external URLs or internal API (path format unclear) +- **Limitation**: `gh` CLI not available in environment +- **Capability**: Can use git commands, search history, read files +- **Recommendation**: Request review information from user +- **Fallback**: Search git history for review mentions + +### GitHub Copilot + +- **Capability**: May have MCP tools for GitHub operations +- **Capability**: Can use `report_progress` which might include PR status +- **Recommendation**: Use MCP tools if available, otherwise request from user + +### CodeRabbit + +- **Capability**: Automated review system, likely has its own API access +- **Capability**: May be able to query its own review status +- **Recommendation**: Use internal CodeRabbit APIs + +## Examples + +### Checking for Review Request Documents + +```bash +# Check current branch for review requests +git show HEAD:REVIEW_REQUEST.md 2>/dev/null + +# Check PR base branch +git show origin/copilot/consolidate-devops-ci-cd:REVIEW_REQUEST.md 2>/dev/null +``` + +### Searching Git History for Reviews + +```bash +# Find commits mentioning reviews +git log --all --oneline | grep -i "review\|approved\|changes" + +# Show specific review-related commit +git show +``` + +### Checking Branch Metadata + +```bash +# Get branch information +git branch -vv | grep "claude/update" + +# Check branch tracking +git log --oneline origin/claude/update-documentation-integration-011CULn7AGnkyHBdk8qWi4qx -5 +``` + +## Workaround: Manual Review Workflow + +Until programmatic access is established, use this manual workflow: + +1. **Agent creates PR** and documents changes +2. **Agent requests reviews** via @mentions in PR description +3. **User or other agents provide feedback** in PR comments +4. **User pastes feedback** into a message to the agent +5. **Agent addresses feedback** and documents resolution +6. **User confirms** when ready to merge +7. **Agent performs merge** and cleanup + +## Documentation Updates Needed + +When PR review access is established, update: + +1. **This document** - Add working examples +2. **AGENT_COLLABORATION.md** - Update network access section +3. **Scripts** - Update `scripts/get_pr_reviews.py` to work +4. **Automation** - Update `automation/branch_manager.py` if needed + +## Conclusion + +Current environment **does not support** programmatic PR review access due to: +- Missing `gh` CLI +- Unclear internal API path format +- No git PR refs configured + +**Recommended Action**: Request review information from users until environment is configured. + +--- + +**Last Updated**: 2025-10-21 +**Created by**: Claude Code +**Status**: Environment limitation documented, workarounds provided diff --git a/.github/AGENT_COLLABORATION.md b/.github/AGENT_COLLABORATION.md index a18fb88..ee38a1f 100644 --- a/.github/AGENT_COLLABORATION.md +++ b/.github/AGENT_COLLABORATION.md @@ -2,356 +2,323 @@ ## Overview -This guide provides comprehensive information for AI agents (GitHub Copilot, ChatGPT Codex, CodeRabbit, etc.) working on the Bleedy project. It clarifies technical constraints, communication patterns, and best practices for effective collaboration. +This guide provides comprehensive information for AI agents (GitHub Copilot Agent, ChatGPT Codex, Gemini Code Assist, Claude Code, Google Jules, CodeRabbit, etc.) working on the Bleedy project. It clarifies technical constraints, communication patterns, and best practices for effective collaboration regardless of the host platform. -## Table of Contents +## Agent Capability Matrix -1. [Technical Limitations](#technical-limitations) -2. [Communication Patterns](#communication-patterns) -3. [Workflow Templates](#workflow-templates) -4. [Best Practices](#best-practices) -5. [Common Issues and Solutions](#common-issues-and-solutions) -6. [Task Templates](#task-templates) +| Agent | Default Commit Tooling | Network Access Profile | Key Nuances | +| -------------------------- | ---------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| **GitHub Copilot Agent** | `report_progress` + PR automation | GitHub MCP HTTP gateway with GitHub auth | Prefers `report_progress` checkpoints; surface `gh` helpers when configured. | +| **ChatGPT Codex** | `report_progress` (GitHub-managed) | Limited outbound HTTP; GitHub REST available via MCP | Confirm branch context before each commit; Codex dashboards expect concise status notes. | +| **Gemini Code Assist** | `apply_patch` + Google git proxies | Google-hosted sandbox with curated allow list | Paste explicit command outputs; document skipped steps that violate policy. | +| **Claude Code** | Direct git (`commit`, `push`) | Anthropic secure proxy with audited HTTP access | Can use git directly; provide structured diffs and mention safety blocks when triggered. | +| **Google Jules** | `submit` workflow with auto-commit | Google-aligned HTTP allow list and strict logging | Provide deterministic QA commands and reproducible steps. | +| **CodeRabbit** | Automated review comments | GitHub API access for PR/issue operations | Cannot commit directly; provides automated reviews and suggestions. | +| **Other / Unknown Agents** | Varies | Assume restricted | Ask which tools are available before running niche commands. | -## Technical Limitations +> **Tip:** When instructions conflict, follow the stricter platform rule (for example, if Gemini disallows a network call that Copilot allows, skip it and note the limitation in your response). -### Environment Constraints +## Active Agents -All AI agents operate in sandboxed environments with specific limitations: +The following AI agents may work on this repository: -#### Network Access +- **@copilot** - GitHub Copilot for code changes and PR management +- **@claudecode** - Claude Code for complex refactoring and systematic tasks +- **@codex** - OpenAI Codex for code review and fixes +- **@gemini** - Google Gemini for analysis +- **@coderabbitai** - CodeRabbit for automated code reviews +- **@code-factor** - Code quality analysis +- **@snyk-bot** - Security vulnerability scanning +- **@dependabot** - Dependency updates +- **@jules** - Additional AI assistant -- **Cannot access external HTTP/HTTPS URLs** - This includes GitHub.com URLs, even for this repository -- **Workaround**: Paste review comments or specific content directly into PR/issue comments -- **Note**: Some agents may have internal APIs for GitHub operations (use MCP tools when available) +**Agent Selection**: Start with unlimited-usage agents (Copilot, CodeRabbit) for most tasks. Escalate to specialized agents (Claude Code) when their unique capabilities are needed. -#### Git Operations +## GitHub MCP Server -- **Cannot push directly using `git push`** - Must use provided tools like `report_progress` -- **Cannot force push** - No `git reset --hard` or `git rebase` with force push -- **Cannot pull branches** - Cannot resolve merge conflicts directly -- **Cannot clone repositories** - Work with provided repository clone +This repository uses GitHub's official Model Context Protocol (MCP) server for enhanced agent capabilities. -#### File System +### Configuration -- **Limited to repository directory** - Cannot access files outside the cloned repository -- **Cannot access `.github/agents/` directory** - This contains instructions for other agents +The MCP server is configured in `.mcp/config.json`: +- Provides standardized GitHub operations (PR management, issue creation, etc.) +- Requires `GITHUB_TOKEN` environment variable +- Available to agents that support MCP (check your agent's documentation) -### What Agents CAN Do +### Using MCP vs. Direct Git -- ✅ Read and modify files in the repository -- ✅ Run commands via bash/shell tools -- ✅ Use `report_progress` to commit and push changes -- ✅ Access GitHub API via MCP tools (if available) -- ✅ Create and modify issues/PRs (via tools, not direct git) -- ✅ Run builds, tests, and linters locally +- **Use MCP**: For PR operations, issue management, GitHub API access +- **Use Direct Git**: For local commits, branch operations, file changes +- **Refer to agent-specific docs**: Each agent may have different MCP capabilities -## Communication Patterns +## Technical Limitations -### Agent-to-Agent Handoff +### Network Access -When handing off work to another agent: +- **Limited outbound HTTP/HTTPS access is available** – agents can usually contact public APIs (including GitHub) when authenticated tooling is configured. +- **Prefer repository-provided tools** – use MCP helpers or curated scripts before resorting to ad-hoc `curl`/`wget` calls. +- **Mind rate limits** – cache responses when practical and avoid unnecessary polling. +- **Workarounds for Reviews**: If HTTP access fails, paste the actual review comments into PR comments, reference specific files and line numbers directly, and quote the exact code or suggestion that needs addressing. -```markdown -@[agent-name] +### Git Operations -**Context**: [Brief description of what you've done] +Agents typically cannot: +- Directly execute `git merge` across branches +- Force push or rebase without appropriate tools +- Access other branches beyond their assigned branch -**Current State**: +Agents can: +- Read git history and diffs +- Create changes that are committed via specialized tools +- View branch status and commit logs +- Use MCP tools for GitHub operations (if available) +- Run builds, tests, and linters locally +- Leverage the `npm run qa` helper to execute lint/build/test in one command -- ✅ Completed: [List completed tasks] -- ⚠️ In Progress: [Partially completed work] -- ❌ Blocked: [Issues preventing completion] +## Communication Patterns -**Next Steps**: +### 1. Agent-to-Agent Handoffs -1. [Specific action needed] -2. [Expected outcome] +When handing off work to another agent, include: -**Files Modified**: +```markdown +@agent-name -- `path/to/file1` - [Description of changes] -- `path/to/file2` - [Description of changes] +**Context**: [Brief description of what was done] -**Testing Notes**: +**Remaining Work**: +- [ ] Task 1 +- [ ] Task 2 -- [How to verify the changes] -- [Known issues or edge cases] +**Important Notes**: +- Constraint or consideration 1 +- Constraint or consideration 2 -**References**: +**Files Modified**: +- path/to/file1.ts (reason) +- path/to/file2.py (reason) -- Issue #[number] -- PR #[number] -- Related discussion: [paste relevant comments] +**Testing Status**: [What has been tested, what needs testing] ``` -### Review Request +### 2. Requesting Reviews -When requesting review from another agent: +When requesting a review from another agent: ```markdown -@[agent-name] review - -**Changes Summary**: [High-level description] +@agent-name -**Review Focus**: +Please review the following changes: -- [ ] Code quality and best practices -- [ ] Test coverage -- [ ] Documentation completeness -- [ ] Security considerations +**File**: path/to/file.ts +**Lines**: 10-25 +**Change**: [Description] +**Concern**: [What to check] -**Specific Questions**: - -1. [Question about specific implementation] -2. [Concern about approach] - -**Testing**: [How changes were validated] +**Expected**: [What should happen] +**Actual**: [What currently happens, if applicable] ``` -### Completion Report +### 3. Reporting Completion -When finishing a task: +When completing a task: ```markdown -**Task Complete**: [Task description] - -**Summary**: - -- ✅ [Achievement 1] -- ✅ [Achievement 2] -- ✅ [Achievement 3] +**Completed**: [Brief description] -**Changes Made**: +**Commit**: abc1234 -- `file1.ts` - [Brief description] -- `file2.vue` - [Brief description] +**Changes**: +- ✅ Item 1 +- ✅ Item 2 -**Testing**: - -- ✅ Build passes: `npm run build` -- ✅ Lint passes: `npm run lint` -- ✅ Manual testing: [Description] +**Testing**: [Results of testing] -**Commit**: [commit SHA] - -**Next Steps**: [Optional follow-up work] +**Next Steps**: [Optional - what should be done next] ``` -## Workflow Templates +## Collaboration Workflows -### Task Assignment Workflow +### Workflow 1: Code Review and Fix -1. **User assigns task** to agent via `@[agent]` mention -2. **Agent acknowledges** and outlines plan -3. **Agent reports progress** regularly using `report_progress` -4. **Agent requests review** if needed -5. **Agent completes** with summary +1. **CodeRabbit** identifies issues and leaves review comments +2. **Copilot** or other agent reads the review comments (pasted in PR) +3. Agent makes fixes and commits +4. Agent mentions original reviewer: "@coderabbitai - Fixed in commit abc1234" -### Multi-Agent Collaboration +### Workflow 2: Feature Development 1. **Primary agent** creates initial implementation -2. **Primary agent** uses handoff template to pass work -3. **Secondary agent** acknowledges and continues -4. **Secondary agent** reports completion -5. **Either agent** can request review from others +2. **Primary agent** mentions other agent for review +3. User pastes any external review comments into PR +4. **Secondary agent** addresses feedback +5. Final testing and merge -### Code Review Workflow +### Workflow 3: Security and Dependencies -1. **Author** uses review request template -2. **Reviewer** examines changes using available tools -3. **Reviewer** provides feedback in structured format -4. **Author** addresses feedback -5. **Reviewer** approves or requests further changes +1. **Snyk** or **Dependabot** identifies security issues +2. User creates issue or PR comment with details +3. **Copilot** or other agent implements fixes +4. Automated scans validate the fix ## Best Practices ### For All Agents -1. **Always read existing documentation** before starting work -2. **Use provided tools** (don't try to bypass limitations) -3. **Report progress frequently** using `report_progress` -4. **Include context** in all communications -5. **Paste full content** when referencing external links -6. **Test changes locally** before pushing -7. **Keep commits focused** and well-documented - -### Context Preservation - -When working on tasks: - -- Include relevant file paths in discussions -- Quote specific code sections when discussing changes -- Reference line numbers when applicable -- Paste error messages in full -- Share command outputs that provide context - -### Handling Limitations - -**When you cannot access a GitHub URL:** - -- Ask the user to paste the content -- Explain the limitation clearly -- Document the workaround in your response - -**When you cannot push changes:** - -- Use `report_progress` tool exclusively -- Never suggest manual git push commands -- Explain that commits will be handled automatically - -**When you cannot access a file:** - -- Check if the file is in `.github/agents/` (off-limits) -- Verify the path is correct -- Ask the user if the file exists +1. **Always Check Current State First** + ```bash + git status + git log --oneline -10 + npm run build # or appropriate build command + ``` + +2. **Test Before Committing** + - Run linters: `npm run lint` + - Run tests: `npm test` (if tests exist) + - Build: `npm run build` + - Verify no regressions + +3. **Make Minimal Changes** + - Change only what's necessary + - Don't refactor unrelated code + - Don't fix unrelated issues + +4. **Document Changes** + - Update README if needed + - Update inline comments for complex logic + - Note breaking changes clearly + +5. **Use Structured Commits** + - Clear, descriptive commit messages + - Reference issue numbers + - Group related changes + +### For Code Reviews + +1. **Be Specific** + - Quote exact code snippets + - Provide line numbers + - Suggest specific alternatives + +2. **Provide Context** + - Explain WHY a change is needed + - Reference documentation or standards + - Note potential impacts + +3. **Be Actionable** + - Clear request vs. suggestion + - Priority (must-fix vs. nice-to-have) + - Acceptance criteria ## Common Issues and Solutions -### Issue: "I cannot access the review comments at [GitHub URL]" +### Issue: Agent Can't Access Review URL -**Solution**: This is expected due to sandbox limitations. Ask the user: +**Problem**: Agent asked to review https://github.com/user/repo/pull/123#review-456 +**Solution**: ```markdown -I cannot access external URLs from my sandboxed environment. Could you please paste the specific review comments here? This will allow me to address them directly. +Instead of the URL, paste the review content: + +**File**: src/components/Example.vue +**Line**: 45 +**Comment**: "This function should handle null values" +**Suggestion**: +\`\`\`typescript +if (value === null) return defaultValue; +\`\`\` ``` -### Issue: "Git push failed" +### Issue: Conflicting Agent Changes -**Solution**: Never use `git push` directly. Always use `report_progress`: +**Problem**: Two agents made changes to the same file -```markdown -I cannot push changes directly using git commands. I'll use the `report_progress` tool to commit and push these changes. -``` - -### Issue: "Cannot resolve merge conflicts" - -**Solution**: Merge conflicts must be resolved by the user: +**Solution**: +1. User decides which changes to keep +2. User manually merges if needed +3. User pastes the final desired state in a comment +4. One agent implements the resolution -```markdown -I cannot resolve merge conflicts directly as I don't have the ability to pull branches from GitHub. Could you please: - -1. Pull the latest changes from master -2. Resolve the conflicts locally -3. Push the resolved branch - -Then I can continue with the implementation. -``` +### Issue: Test Failures After Changes -### Issue: "Cannot find another agent's changes" +**Problem**: CI/CD fails after agent commits -**Solution**: Request the specific file contents: - -```markdown -I don't have access to changes made by other agents unless they're in the current branch. Could you please share: - -1. The specific files that were modified -2. The commit SHA or PR number -3. The content of the changes if available -``` +**Solution**: +1. Agent checks local test results first +2. If tests pass locally but fail in CI, investigate environment differences +3. Document any known failures in PR description +4. Don't commit if tests fail locally ## Task Templates -### Bug Fix Task +### Template: Bug Fix ```markdown -**Bug**: [Description of the bug] - -**Reproduction Steps**: - -1. [Step 1] -2. [Step 2] -3. [Step 3] - -**Expected Behavior**: [What should happen] - -**Actual Behavior**: [What actually happens] - -**Root Cause**: [Analysis of the issue] +**Bug**: [Description] +**File**: path/to/file +**Line**: [Line number if known] +**Expected**: [What should happen] +**Actual**: [What currently happens] +**Fix**: [Proposed solution] -**Fix**: [Description of the solution] - -**Testing**: [How to verify the fix] - -**Files Modified**: - -- `path/to/file` - [Description] +**Testing**: +- [ ] Unit tests pass +- [ ] Manual testing completed +- [ ] No regressions ``` -### Feature Implementation Task +### Template: Feature Addition ```markdown -**Feature**: [Feature description] - -**Requirements**: - -- [Requirement 1] -- [Requirement 2] -- [Requirement 3] - -**Implementation Plan**: +**Feature**: [Description] +**Files Affected**: +- path/to/file1 (new) +- path/to/file2 (modified) -1. [Step 1] -2. [Step 2] -3. [Step 3] +**Implementation**: +- [ ] Core functionality +- [ ] Error handling +- [ ] Documentation +- [ ] Tests (if applicable) -**Technical Approach**: [High-level design] - -**Testing Strategy**: [How to validate] - -**Documentation Updates**: [Required doc changes] +**Testing**: +- [ ] Feature works as expected +- [ ] Edge cases handled +- [ ] No breaking changes ``` -### Refactoring Task +### Template: Refactoring ```markdown -**Refactoring**: [What needs to be refactored] - -**Motivation**: [Why this refactoring is needed] +**Refactoring**: [Description] +**Reason**: [Why this change] +**Scope**: [What's included] -**Approach**: +**Changes**: +- [ ] Extract function/component +- [ ] Rename for clarity +- [ ] Simplify logic -- [Approach detail 1] -- [Approach detail 2] - -**Impact Assessment**: - -- Breaking changes: [Yes/No, with details] -- Performance impact: [Analysis] -- Test coverage: [Current and target] - -**Validation**: [How to verify nothing broke] +**Testing**: +- [ ] All tests pass +- [ ] Functionality unchanged +- [ ] Performance impact: [none/positive/negative] ``` -## Tool-Specific Notes +## Agent-Specific Documentation -### GitHub Copilot Agent +Each agent has its own configuration and instruction files: -- Has access to GitHub MCP tools for repository operations -- Can read issues, PRs, and comments via API -- Uses `report_progress` for committing changes -- Cannot access external URLs (HTTP/HTTPS) +- **Claude Code**: `.claude/README.md` - References main docs, Claude Code specifics +- **GitHub Copilot**: `.github/copilot-instructions.md` - Copilot-specific configuration +- **All Agents**: This file - Universal collaboration guide -### ChatGPT Codex Connector +When starting work: -- Operates through GitHub integration -- Can create commits and interact with GitHub -- Provides task tracking via Codex dashboard -- May have different tool availability - -### CodeRabbit - -- Provides automated code reviews -- Can be triggered with `@coderabbitai review full` -- Focuses on code quality and best practices -- Can suggest improvements and identify issues - -### Other Agents - -- May have varying capabilities -- Always check available tools before starting -- Document any unique limitations discovered -- Update this guide with new findings +1. Read your agent-specific documentation first +2. Refer to this collaboration guide for multi-agent workflows +3. Follow the templates and patterns documented here +4. Update documentation when discovering new patterns ## Repository-Specific Guidelines @@ -367,7 +334,7 @@ I don't have access to changes made by other agents unless they're in the curren 1. Run linter: `npm run lint` 2. Build the project: `npm run build` 3. Test manually if UI changes -4. Use `report_progress` to commit changes +4. Commit changes using your agent's standard method 5. Verify committed files are appropriate ### Pull Request Standards @@ -377,27 +344,41 @@ I don't have access to changes made by other agents unless they're in the curren - Update documentation if needed - Ensure all CI checks pass -## Getting Help +## Escalation -If you encounter issues not covered in this guide: +If an agent encounters issues beyond its capabilities: -1. **Check existing documentation** in the repository -2. **Ask the user** for clarification or assistance -3. **Document the issue** for future reference -4. **Update this guide** if you find a solution +1. **Document the blocker** clearly in a PR comment +2. **Tag the user** to request intervention +3. **Suggest alternatives** if possible +4. **Preserve work done** so it's not lost -## Contributing to This Guide +Example: +```markdown +@danelkay93 + +I've encountered a limitation that prevents me from completing this task: -This guide is a living document. If you discover: +**Issue**: [Description] +**Attempted**: [What I tried] +**Blocker**: [Specific limitation] -- New limitations or capabilities -- Better workarounds for common issues -- Improved communication patterns -- Tool-specific tips +**Options**: +1. [Alternative approach] +2. [Manual intervention needed] +3. [Different agent might help] + +**Work Completed**: +- ✅ Part A (commit abc1234) +- ⏸️ Part B (blocked) +``` -Please update this guide in your PR with a clear explanation of the addition. +## Updates to This Document ---- +This document should be updated when: +- New agents are added to the project +- Workflow patterns change +- Common issues are identified +- Technical limitations change -**Last Updated**: 2025-10-18 -**Maintained by**: GitHub Copilot, ChatGPT Codex, and community contributors +Last Updated: 2025-11-15 diff --git a/.github/ISSUE_TEMPLATE/agent_task.md b/.github/ISSUE_TEMPLATE/agent_task.md index 8b8e713..cfc6053 100644 --- a/.github/ISSUE_TEMPLATE/agent_task.md +++ b/.github/ISSUE_TEMPLATE/agent_task.md @@ -83,12 +83,27 @@ assignees: '' ## Agent Assignment -**Preferred Agent**: @[agent-name] +**Preferred Agent**: @[agent-name] **Estimated Complexity**: **Priority**: +**Task Type Recommendations** (consider usage limits and costs): +- Quick fixes → GitHub Copilot (unlimited, use first) +- Simple features → GitHub Copilot (unlimited, use first) +- Code review → CodeRabbit (automated, unlimited) +- Documentation → GitHub Copilot first, Claude Code if complex +- Multi-file refactoring → Claude Code (when Copilot can't handle) +- Complex debugging → Claude Code (when Copilot can't solve) +- Feature implementation → Copilot first, escalate to Claude Code if needed + +**General Strategy:** Start with Copilot (unlimited), escalate to Claude Code (limited/costly) only when needed. + +See `.github/AGENT_COLLABORATION.md` for detailed agent capabilities and trade-offs. + --- **For the assigned agent**: Please acknowledge this task and outline your implementation plan before starting work. Use the templates in `.github/AGENT_COLLABORATION.md` for status updates. + +**For Claude Code**: Use TodoWrite to track progress and keep this issue updated with your task list. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index f4dc7c2..3509cc1 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -178,6 +178,9 @@ npm run test:unit **For AI Agents**: If this PR was created or modified by an AI agent, please include: -- Agent name (e.g., @copilot, @codex) +- Agent name (e.g., @copilot, @claude, @codex) - Task tracking link (if applicable) - Any special considerations or limitations encountered +- For Claude Code: Include todo list summary if TodoWrite was used + +**Multi-Agent Collaboration**: If multiple agents worked on this PR, list all contributors and their roles. See `.github/AGENT_COLLABORATION.md` for handoff templates. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 7b1e31b..e8be227 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -94,6 +94,22 @@ npm run format - Use `npx prettier --check . --cache=false` to verify actual formatting status - Use `npx prettier --write . --cache=false` if standard format command seems inconsistent +#### Unified Quality Checks (QA) + +```bash +npm run qa +``` + +- **Purpose**: Single command for all validation checks +- **Runs**: ESLint → Vite build → Vitest +- **Options**: + - `npm run qa -- --with-typecheck` - Includes TypeScript type checking (slower) + - `npm run qa -- --skip-tests` - Skips test suite + - `npm run qa -- --skip-lint` - Skips ESLint + - `npm run qa -- --skip-build` - Skips build +- **Use this before committing** for comprehensive validation +- **Designed for multi-agent collaboration** - provides clear, structured output + ### Testing ```bash @@ -255,11 +271,62 @@ npm run test:unit - Doodle.css and paper-css for hand-drawn aesthetics - Google Fonts: Cabin Sketch +## GitHub MCP Server Integration + +This repository uses GitHub's official Model Context Protocol (MCP) server for enhanced agent capabilities. + +### Configuration + +The MCP server is configured in `.mcp/config.json`: + +```json +{ + "mcpServers": { + "github": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" + } + } + } +} +``` + +### Native Features via MCP + +GitHub Copilot may have access to GitHub MCP tools for: +- **PR Management**: Create, list, view pull requests +- **Issue Management**: Create, update, search issues +- **Repository Operations**: Branch management, file operations +- **Code Review**: Access and respond to review comments + +### Using MCP Tools + +If MCP tools are available in your environment: + +1. **For PR operations**: Use MCP tools instead of manual git commands where possible +2. **For issue management**: MCP provides direct API access +3. **For code reviews**: MCP may allow direct access to review comments +4. **Check availability**: Not all Copilot environments have MCP enabled + +### MCP vs. report_progress + +- **Use MCP**: For GitHub API operations (PRs, issues, reviews) +- **Use report_progress**: For committing and pushing changes +- **Combine both**: MCP for PR creation, report_progress for commits + ## Agent Collaboration ### Working with Other AI Agents -This repository supports collaboration between multiple AI agents (GitHub Copilot, ChatGPT Codex, CodeRabbit, etc.). For comprehensive collaboration guidelines, see `.github/AGENT_COLLABORATION.md`. +This repository supports collaboration between multiple AI agents (GitHub Copilot, Claude Code, ChatGPT Codex, CodeRabbit, etc.). For comprehensive collaboration guidelines, see `.github/AGENT_COLLABORATION.md`. + +### Agent-Specific Documentation + +- **GitHub Copilot**: This file (`.github/copilot-instructions.md`) +- **Claude Code**: `.claude/README.md` +- **All Agents**: `.github/AGENT_COLLABORATION.md` ### Key Collaboration Points @@ -308,6 +375,14 @@ When multiple agents work on the same task: 4. **Either agent** can request reviews from others 5. **Final agent** completes with comprehensive summary +**Collaborating with Claude Code**: + +- Claude Code excels at multi-file refactoring and systematic implementation tasks +- Uses TodoWrite for task tracking (you'll see structured todo lists in issues/PRs) +- Has direct git access and can create commits/PRs independently +- Best for complex features requiring multiple steps +- Coordinates via the same handoff templates in `.github/AGENT_COLLABORATION.md` + See `.github/AGENT_COLLABORATION.md` for detailed workflow templates and examples. ## Trust These Instructions diff --git a/.gitignore b/.gitignore index 7076098..bb31cbf 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,7 @@ coverage # Editor directories and files .vscode/* !.vscode/extensions.json +!.vscode/settings.json .idea *.suo *.ntvs* @@ -30,6 +31,19 @@ coverage *.tsbuildinfo .aider* .env +.env.local +.env.*.local *.env!/vueform-project/ /.ignored_node_modules/* auto-imports.d.ts + +# Agent collaboration artifacts +.agent-workspace/ +.agent-cache/ + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python diff --git a/.mcp/config.json b/.mcp/config.json new file mode 100644 index 0000000..adca29e --- /dev/null +++ b/.mcp/config.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "github": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" + } + } + } +} diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 0449b97..87996e3 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,3 +1,38 @@ { - "recommendations": ["Vue.volar", "dbaeumer.vscode-eslint", "esbenp.prettier-vscode"] + "recommendations": [ + // Vue development + "Vue.volar", + + // Code quality + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + + // Python + "ms-python.python", + "ms-python.vscode-pylance", + "ms-python.black-formatter", + + // GitHub and AI + "GitHub.copilot", + "GitHub.copilot-chat", + "GitHub.vscode-pull-request-github", + + // Git + "eamodio.gitlens", + + // Configuration files + "redhat.vscode-yaml", + "tamasfe.even-better-toml", + + // Docker + "ms-azuretools.vscode-docker", + + // Markdown + "yzhang.markdown-all-in-one", + "DavidAnson.vscode-markdownlint" + ], + "unwantedRecommendations": [ + // Old Vue extension (conflicts with Volar) + "octref.vetur" + ] } diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..e54e535 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,124 @@ +{ + // Editor settings + "editor.formatOnSave": true, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit" + }, + "editor.tabSize": 2, + "editor.insertSpaces": true, + "editor.trimAutoWhitespace": true, + + // Language-specific formatters + "[javascript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[typescript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[vue]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[json]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[jsonc]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[markdown]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[css]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[scss]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[html]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[python]": { + "editor.defaultFormatter": "ms-python.black-formatter" + }, + + // File settings + "files.eol": "\n", + "files.insertFinalNewline": true, + "files.trimTrailingWhitespace": true, + "files.exclude": { + "**/.git": true, + "**/.DS_Store": true, + "**/node_modules": true, + "**/dist": true, + "**/dist-ssr": true, + "**/.vite": true + }, + "files.watcherExclude": { + "**/.git/objects/**": true, + "**/.git/subtree-cache/**": true, + "**/node_modules/**": true, + "**/dist/**": true + }, + + // ESLint settings + "eslint.validate": [ + "javascript", + "javascriptreact", + "typescript", + "typescriptreact", + "vue" + ], + "eslint.workingDirectories": [{ "mode": "auto" }], + + // Vue settings + "volar.autoCompleteRefs": true, + "volar.codeLens.pugTools": false, + "volar.codeLens.scriptSetupTools": true, + + // TypeScript settings + "typescript.tsdk": "node_modules/typescript/lib", + "typescript.enablePromptUseWorkspaceTsdk": true, + "typescript.preferences.importModuleSpecifier": "relative", + + // Git settings + "git.autofetch": true, + "git.confirmSync": false, + "git.enableSmartCommit": true, + + // Terminal settings + "terminal.integrated.defaultProfile.linux": "bash", + "terminal.integrated.scrollback": 10000, + + // Multi-agent collaboration settings + "github.copilot.enable": { + "*": true, + "plaintext": false, + "markdown": true, + "scminput": false + }, + + // Search settings + "search.exclude": { + "**/node_modules": true, + "**/dist": true, + "**/dist-ssr": true, + "**/.vite": true, + "**/package-lock.json": true + }, + + // Prettier settings + "prettier.requireConfig": true, + "prettier.useEditorConfig": true, + + // Python settings + "python.linting.enabled": true, + "python.linting.pylintEnabled": false, + "python.linting.flake8Enabled": true, + "python.formatting.provider": "black", + + // Docker settings + "docker.showStartPage": false, + + // Workspace recommendations + "extensions.ignoreRecommendations": false +} diff --git a/CONSOLIDATED_TASK_GUIDE.md b/CONSOLIDATED_TASK_GUIDE.md new file mode 100644 index 0000000..86991d4 --- /dev/null +++ b/CONSOLIDATED_TASK_GUIDE.md @@ -0,0 +1,156 @@ +# Bleedy Consolidated Task Guide + +This playbook merges the most useful guidance from the automation setup, automation summary, PR readiness report, and review resolution notes that supported PR #18 (the seven-PR consolidation). Use it as the single source of truth when maintaining the consolidated branch, resolving reviews, or onboarding additional collaborators. + +--- + +## Snapshot + +- ✅ All seven outstanding PRs were merged into a single, modernized codebase. +- ✅ Automation now covers post-merge cleanup, dependency hygiene, and unified QA helpers. +- ✅ Documentation, accessibility fixes, and TypeScript safety improvements are in place. +- ⚠️ Husky hooks and the PyScript version guard still need one-time setup per developer. +- ⚠️ 5 moderate npm vulnerabilities remain for follow-up hardening. + +--- + +## Key Outcomes from the Consolidation + +| Area | Highlights | +| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Merged PRs** | #1 `refactor-cleanup`, #7 `phase1-refactor-pyscript-deps`, #8 `fix/eslint-errors` (base), #10 reverse-conflict resolution, #12 `snyk-upgrade-element-plus-2.9.1`, #14 `snyk-upgrade-element-plus-2.9.5`, #15 `snyk-upgrade-element-plus-2.10.5`. | +| **Dependency Health** | `element-plus` 2.11.4, `vue` 3.5.22, `vue-router` 4.5.1, PyScript 2025.5.1/Pyodide 0.26.1. | +| **Type Safety** | SVG typing and null guards in `Logo.vue`, missing imports and emit typing fixes in `App.vue` and `ImageSelection.vue`, ref typing cleanup in `ImageGallery.vue`. | +| **Accessibility** | Replaced global `outline: none` with WCAG-compliant `:focus-visible` styles, improving keyboard navigation. | +| **Configuration Modernization** | ESLint 9 flat config, comprehensive `.github/workflows/ci.yml`, documented `npm run qa` helper, refreshed Copilot instructions. | +| **Documentation** | `CONSOLIDATION_CHANGES.md`, `CODERABBIT_FIXES.md`, `FUTURE_WORK.md`, this guide, and the `docs/` handbook series capture historical context and future plans. | + +--- + +## Automation Suite Overview + +### 1. Post-Merge Cleanup (`.github/workflows/post-merge-cleanup.yml`) + +- **Trigger**: Runs automatically whenever a PR merges into `master`/`main`. +- **Actions**: Detects consolidation PR metadata, closes PRs #1/#7/#8/#10/#12/#14/#15 with explanatory comments, deletes their branches (`refactor-cleanup`, `phase1-refactor-pyscript-deps`, `fix/eslint-errors`, and the Snyk branches), and posts a final summary. +- **Benefit**: Keeps the repo free of stale PRs/branches without manual intervention. + +### 2. CI Quality Gate (`.github/workflows/ci.yml`) + +- Runs on pushes and pull requests. +- Executes formatting check (`npm run format:check`), ESLint, TypeScript type check, and production build. +- Intended to be the definitive gate once local Husky hooks are enabled. + +### 3. Dependency Hygiene (`.github/dependabot.yml`) + +- **npm** updates every Monday at 09:00 UTC (max 5 open PRs). +- **GitHub Actions** updates monthly (max 3 open PRs). +- Automatically applies `dependencies` + `automated` labels, rebases as needed, and ignores major updates for Vue, Element Plus, and Vite unless manually lifted. + +### 4. Local Unified QA (`npm run qa`) + +- Orchestrates ESLint → Vite build → Vitest with clear section headers. +- Flags: `--with-typecheck` adds `vue-tsc`; `--skip-tests`, `--skip-lint`, and `--skip-build` support documentation-only updates. +- Use this before invoking the heavier CI pipeline. + +--- + +## Developer Setup & Local Automation + +> Each contributor needs to perform these one-time steps after cloning. + +1. **Install dependencies (applies npm patches automatically):** + ```bash + npm install + ``` +2. **Initialize Husky v9 and enable the intended checks:** + ```bash + npx husky init + echo "npm run format:check && npm run lint -- --no-fix" > .husky/pre-commit + chmod +x .husky/pre-commit + echo "npm run type-check && npm run build" > .husky/pre-push + chmod +x .husky/pre-push + ``` +3. **Retire the legacy `.huskyrc.json`** once the `.husky/` directory is active (it targets the old Husky 4 flow). +4. **Wire in the PyScript version guard** after the hook scripts exist: + ```bash + echo "bash scripts/check-pyscript-version.sh" >> .husky/pre-commit + chmod +x scripts/check-pyscript-version.sh + ``` + + - The script still needs its version-parsing logic finalized (tracked in `TODO.md`). +5. **Confirm tooling works locally:** + ```bash + npm run qa + ``` + +--- + +## Validation Snapshot (from consolidation QA) + +| Check | Result | Notes | +| -------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| Build | ✅ `npm run build` (≈11.4s, 1566 modules) | Expected chunk-size warnings due to PyScript payloads. | +| TypeScript | ⚠️ Critical issues fixed; ~26 non-blocking errors remain | Missing third-party types, File System Access API declarations, and legacy `any` usage. | +| Linting & Formatting | ✅ ESLint 9 flat config + Prettier alignment | Occasional Prettier cache hiccups; rerun with `--cache=false` if needed. | +| Dependency Audit | ⚠️ 5 moderate dev dependency vulnerabilities | Documented for follow-up hardening; no production impact. | +| Functionality | ✅ Core Vue workflow + PyScript bridge verified | Accessibility fixes applied; icons renamed to PascalCase components. | + +--- + +## Review Resolution Playbook + +The three outstanding reviews on PR #18 were addressed in commits `5999327`, `4f8ba7a`, and `b682a60`. If manual dismissal is still required: + +1. **Navigate to [PR #18](https://github.com/danelkay93/bleedy/pull/18).** +2. **For CodeRabbit review:** resolve each conversation or dismiss with the rationale that type safety, accessibility, and null-guard fixes landed in commit `5999327` (see `CODERABBIT_FIXES.md`). +3. **For the package-version review:** confirm upgrades to Vue/Element Plus/Vue Router in commit `4f8ba7a` and reference `CONSOLIDATION_CHANGES.md`. +4. **For the general follow-up review:** cite the documentation sweep (`CONSOLIDATION_CHANGES.md`, this guide) and automation improvements (`b682a60`). +5. **If you lack dismiss permissions**, tag the reviewers with a status comment summarizing the above bullet points and request approval. + +Template snippet: + +```markdown +All issues raised in this review have been addressed: + +- ✅ Type safety + accessibility fixes (commit 5999327; see CODERABBIT_FIXES.md) +- ✅ Dependency versions verified (commit 4f8ba7a; see CONSOLIDATION_CHANGES.md) +- ✅ Documentation & automation updates (commit b682a60; see CONSOLIDATED_TASK_GUIDE.md) + Please re-review and approve when convenient. +``` + +--- + +## Post-Merge Checklist + +1. **Verify automation ran:** ensure the post-merge cleanup workflow closed the legacy PRs/branches. +2. **Manual spot checks (if automation was paused):** + - Close PRs #1/#7/#8/#10/#12/#14/#15. + - Delete `refactor-cleanup`, `phase1-refactor-pyscript-deps`, `fix/eslint-errors`, and the Snyk branches. +3. **Deployment confidence:** run `npm run build` or `npm run preview` and smoke-test the PyScript flow. +4. **Security maintenance:** plan a follow-up PR to address the remaining npm advisories (see `TODO.md`). +5. **Document future work:** track TypeScript typing backlog, PyScript guard completion, and Husky hook verification in `FUTURE_WORK.md` / `TODO.md`. + +--- + +## Reference Index + +- [`CONSOLIDATION_CHANGES.md`](./CONSOLIDATION_CHANGES.md) – Detailed version changes, removed/renamed assets, validation logs. +- [`CODERABBIT_FIXES.md`](./CODERABBIT_FIXES.md) – TypeScript and accessibility fixes from commit `5999327`. +- [`FUTURE_WORK.md`](./FUTURE_WORK.md) & [`TODO.md`](./TODO.md) – Roadmap and actionable tasks. +- [`docs/AGENT_TOOLKIT.md`](./docs/AGENT_TOOLKIT.md) – Quick command reference for multi-agent collaboration. +- [`.github/AGENT_COLLABORATION.md`](./.github/AGENT_COLLABORATION.md) – Platform-aligned playbook for Copilot, Codex, Gemini, Claude, and Jules agents. +- [`README.md`](./README.md) & [`docs/README.md`](./docs/README.md) – Project overview and documentation index. + +### Legacy Document Map + +For backward compatibility, the historical checklists now redirect here: + +| Legacy File | Status | +| -------------------------------------------------- | ----------------------------------------------------------------------------- | +| [`AUTOMATION_SETUP.md`](./AUTOMATION_SETUP.md) | Redirect notice pointing to this guide for local automation setup. | +| [`AUTOMATION_SUMMARY.md`](./AUTOMATION_SUMMARY.md) | Redirect notice summarizing the automation coverage now tracked here. | +| [`PR_READINESS.md`](./PR_READINESS.md) | Redirect notice pointing to this guide for pre-PR validation and review prep. | +| [`REVIEW_RESOLUTION.md`](./REVIEW_RESOLUTION.md) | Redirect notice directing reviewers to the resolution playbook in this guide. | + +_Last updated: 2024-10-29_ diff --git a/DEVCONTAINER_AND_AUTOMATION.md b/DEVCONTAINER_AND_AUTOMATION.md index df84856..3a53cc2 100644 --- a/DEVCONTAINER_AND_AUTOMATION.md +++ b/DEVCONTAINER_AND_AUTOMATION.md @@ -102,13 +102,147 @@ npm run build bash scripts/validate-lockfile.sh ``` -### Development Container (Future) +### Development Container + +A complete devcontainer configuration is available in `.devcontainer/` providing: + +- **Consistent development environment** - Docker-based reproducible setup +- **Pre-configured tools** - Node.js 20, Python 3, GitHub CLI, Docker-in-Docker +- **Automated setup** - Post-creation script installs dependencies and configures git +- **VS Code integration** - Recommended extensions and settings +- **Multi-agent support** - Optimized for Claude Code, Copilot, CodeRabbit collaboration +- **GitHub MCP Server** - Pre-configured for enhanced agent capabilities + +#### Files and Configuration + +**`.devcontainer/devcontainer.json`** - Main configuration +- Base image: Node.js 20 (Debian Bookworm) +- Pre-configured VS Code settings and extensions +- Port forwarding: Vite dev (5173) and preview (4173) +- Volume mounts for persistent npm cache and bash history +- Multi-agent mode enabled via environment variables +- Features: GitHub CLI, Docker-in-Docker, Git, common utilities + +**`.devcontainer/Dockerfile`** - Container image +- Node.js 20 base image +- Pre-installed: GitHub CLI (`gh`), Python 3.11, build tools, utilities +- Global npm packages (prettier, eslint, typescript, vue-language-server) +- Git configured for PR refs +- Python packages (pyyaml, requests, python-dotenv) + +**`.devcontainer/postCreateCommand.sh`** - Post-creation setup +- Installs npm dependencies +- Configures git for PR access +- Sets up git aliases +- Makes scripts executable +- Runs agent environment setup +- Verifies build +- Displays quick start guide + +#### Environment Setup Scripts + +**`scripts/setup-agent-environment.sh`** - Agent environment configuration +- Verifies required tools (node, npm, git, python, gh, docker) +- Configures git for PR access (`refs/pull/*/head`, `refs/pull/*/merge`) +- Creates helpful git aliases: + - `git pr-list` - List all PR refs + - `git pr-checkout ` - Checkout a PR + - `git pr-diff [base]` - Diff against PR +- Creates `.env.local` from template +- Tests GitHub CLI authentication + +**`scripts/get_pr_reviews.py`** - PR review access +- Python script to access PR reviews via `gh` CLI +- Supports PR number or branch name +- Returns review status, comments, and decisions +- Formatted output for agent consumption + +#### Benefits + +**For AI Agents**: +- Consistent environment for all agents +- All tools pre-installed (GitHub CLI, Python, etc.) +- Git configured for PR access programmatically +- Automated setup via post-creation scripts +- Clear, agent-specific documentation + +**For Human Developers**: +- One-click setup with Dev Container +- No configuration drift between team members +- All recommended extensions installed +- Multi-agent aware settings +- Cross-platform (Windows, Mac, Linux) + +**For the Project**: +- Reproducibility - eliminates "works on my machine" +- Easy onboarding for new contributors +- CI/CD alignment - local matches CI environment +- All setup knowledge codified +- Scalable - easy to add new tools -A devcontainer configuration is planned for future implementation to provide: +#### Quick Start + +**Using VS Code (Recommended)**: +```bash +# 1. Open in VS Code +code . + +# 2. Install "Dev Containers" extension if not installed + +# 3. Click "Reopen in Container" when prompted + +# 4. Wait for setup (~2-5 minutes first time) +``` + +**Using Docker CLI**: +```bash +# Build container +docker build -t bleedy-devcontainer -f .devcontainer/Dockerfile . + +# Run container +docker run -it -v $(pwd):/workspace -p 5173:5173 -p 4173:4173 bleedy-devcontainer + +# Inside container, run setup +cd /workspace +bash .devcontainer/postCreateCommand.sh +``` + +**For AI Agents**: +```bash +# If devcontainer is available, it will be used automatically +# Otherwise, run the setup script manually: +bash scripts/setup-agent-environment.sh + +# Configure GitHub CLI (if available): +gh auth login + +# Access PR reviews: +python3 scripts/get_pr_reviews.py +gh pr view + +# Use git aliases: +git fetch origin +git pr-list +git pr-checkout 36 +``` -- Consistent development environment -- Pre-configured tools and extensions -- Automated setup and dependencies +#### Environment Features + +- [x] Development container with Node.js 20 +- [x] GitHub CLI (`gh`) installed and configured +- [x] Python 3 with automation packages +- [x] Docker-in-Docker support +- [x] Git configured for PR refs +- [x] Git aliases for PR operations +- [x] Environment variable templates (`.env.example`) +- [x] VS Code settings and extensions (`.vscode/`) +- [x] Git attributes for consistent line endings +- [x] Automated post-creation setup +- [x] PR review access script +- [x] Agent environment setup script +- [x] GitHub MCP server configuration (`.mcp/config.json`) + +See `.devcontainer/README.md` for complete documentation and troubleshooting. --- diff --git a/OVERHAUL_STRATEGY.md b/OVERHAUL_STRATEGY.md new file mode 100644 index 0000000..840ef53 --- /dev/null +++ b/OVERHAUL_STRATEGY.md @@ -0,0 +1,273 @@ +# Branch Overhaul Strategy - Multi-Agent Collaboration + +## Current State Analysis + +### What We Have Now (This Branch) +1. **Claude Code specific documentation** (`.claude/project-instructions.md`) +2. **Expanded AGENT_COLLABORATION.md** with Claude Code details +3. **Devcontainer configuration** (comprehensive) +4. **PR review access scripts** (requires gh CLI) +5. **Environment setup scripts** +6. **Multiple documentation files** with some redundancy + +### What's in Other Recent Branches + +#### copilot/consolidate-devops-ci-cd (PR #36 - Base) +- DEVCONTAINER_AND_AUTOMATION.md (single source of truth) +- Docker CI workflow +- Branch management Python scripts +- Pulumi IaC workflow +- Simplified documentation structure + +#### copilot/integrate-iac-with-github-actions +- **Simpler AGENT_COLLABORATION.md** (more practical) +- Docker and docker-compose files +- Infrastructure as Code with Pulumi +- Automation scripts (branch_manager.py, post_merge_cleanup.py) +- QUICKSTART.md, INFRASTRUCTURE.md, MONITORING.md +- Removed redundant docs (CI_CD_GUIDE.md, etc.) + +### Gaps and Issues + +1. **No actual GitHub MCP server integration** - Only mentioned, not implemented +2. **Redundant documentation** - Multiple files covering similar topics +3. **Not using GitHub's native cloud tools** - Reinventing the wheel +4. **Claude Code positioned prominently** instead of as equal peer +5. **Complex devcontainer** when simpler might be better +6. **Missing GitHub Copilot native features** - Not leveraging what Copilot already has + +## Overhaul Strategy + +### Phase 1: Research and Align + +1. **GitHub Copilot Native Features** + - Document what Copilot can do natively (MCP tools, report_progress, etc.) + - Reference GitHub's official MCP server + - Remove reinvented wheels + +2. **Simplify Agent Collaboration** + - Use simpler version from copilot/integrate-iac branch as base + - Add Claude Code as ONE agent among many (not special) + - Focus on practical patterns, not theory + +3. **Centralize Best Practices** + - Single source for development environment (DEVCONTAINER_AND_AUTOMATION.md) + - Single source for agent collaboration (AGENT_COLLABORATION.md) + - Remove duplicate information + +### Phase 2: Implement Changes + +#### A. Streamline Documentation + +**Keep:** +- `.github/AGENT_COLLABORATION.md` (simplified) +- `.github/copilot-instructions.md` (enhanced) +- `.claude/project-instructions.md` (minimal, references main docs) +- `DEVCONTAINER_AND_AUTOMATION.md` (from PR #36, enhanced) + +**Remove/Consolidate:** +- `ENVIRONMENT_ENHANCEMENTS.md` → Merge into DEVCONTAINER_AND_AUTOMATION.md +- `CLAUDE_CODE_INTEGRATION_PROPOSAL.md` → No longer needed +- `INTEGRATION_ISSUES_AND_NOTES.md` → Merge relevant parts into docs +- `.github/ACCESSING_PR_REVIEWS.md` → Simplify and merge into AGENT_COLLABORATION.md +- Redundant sections in various docs + +#### B. GitHub MCP Server Integration + +**Add MCP Configuration:** +```json +// .mcp/config.json +{ + "mcpServers": { + "github": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"] + } + } +} +``` + +**Document MCP Usage:** +- How agents can use GitHub's MCP server +- What operations are available (PR management, issue creation, etc.) +- When to use MCP vs. direct git + +#### C. Simplified Devcontainer + +**Use GitHub's recommended approach:** +- Reference GitHub's official dev containers +- Add GitHub MCP server as a feature +- Remove custom scripts where GitHub provides native solutions +- Keep only what's project-specific + +#### D. Agent Equality + +**Reframe all agent documentation:** +- No agent is "primary" or "special" +- Each agent listed with capabilities and trade-offs +- Focus on **when to use which agent**, not hierarchy +- Claude Code is just another tool in the toolbox + +### Phase 3: Implementation Details + +#### File Structure After Overhaul + +``` +. +├── .github/ +│ ├── AGENT_COLLABORATION.md (simplified, practical) +│ ├── copilot-instructions.md (enhanced with MCP) +│ ├── ISSUE_TEMPLATE/ (updated for multi-agent) +│ └── PULL_REQUEST_TEMPLATE.md (updated) +├── .claude/ +│ └── README.md (minimal, references main docs) +├── .devcontainer/ +│ ├── devcontainer.json (simplified, MCP-enabled) +│ ├── Dockerfile (GitHub base + project needs) +│ └── README.md (quick reference) +├── .mcp/ +│ └── config.json (GitHub MCP server config) +├── scripts/ +│ ├── setup-environment.sh (consolidated) +│ └── validate-setup.sh (verification) +├── DEVCONTAINER_AND_AUTOMATION.md (enhanced from PR #36) +└── README.md (updated with multi-agent info) +``` + +#### Key Documentation Changes + +**AGENT_COLLABORATION.md** (Simplified): +```markdown +# Multi-Agent Collaboration + +## Available Agents +- GitHub Copilot (MCP-enabled, unlimited) +- Claude Code (advanced refactoring, usage limits) +- CodeRabbit (automated reviews, unlimited) +- Dependabot (security updates, automated) + +## Using GitHub's MCP Server +[Instructions for MCP usage] + +## Practical Patterns +[Real examples, not theory] + +## Handoff Templates +[Simple, actionable templates] +``` + +**copilot-instructions.md** (Enhanced): +```markdown +# GitHub Copilot Configuration + +## Native Features +- GitHub MCP server integration +- Automatic PR access +- Issue management +- Code review tools + +## Using MCP Tools +[Specific examples] + +## Multi-Agent Coordination +[Reference AGENT_COLLABORATION.md] +``` + +**`.claude/README.md`** (New, Minimal): +```markdown +# Claude Code Configuration + +Claude Code operates as one agent among equals in this repository. + +## Quick Start +See main documentation: +- [Agent Collaboration](.github/AGENT_COLLABORATION.md) +- [Development Environment](DEVCONTAINER_AND_AUTOMATION.md) +- [Copilot Instructions](.github/copilot-instructions.md) + +## Claude Code Specifics +- Uses TodoWrite for task tracking +- Direct git access (no report_progress) +- Best for: Complex refactoring, systematic debugging +- Not for: Simple fixes (use Copilot) +``` + +### Phase 4: Testing and Validation + +1. **Verify MCP server works** - Test GitHub MCP integration +2. **Test devcontainer** - Ensure builds and runs +3. **Validate documentation** - Check for dead links, redundancy +4. **Run all builds** - Ensure no breaking changes +5. **Check agent workflows** - Verify each agent can follow docs + +## Migration Plan + +### Step 1: Backup and Branch +```bash +# Current state is already committed +git log --oneline -5 +``` + +### Step 2: Apply Overhaul +1. Rewrite AGENT_COLLABORATION.md (simpler) +2. Add .mcp/config.json +3. Simplify .claude/ to just README.md +4. Update devcontainer with MCP +5. Consolidate documentation +6. Remove redundant files + +### Step 3: Test +```bash +npm install +npm run build +npm run lint +# Test devcontainer +# Verify MCP config +``` + +### Step 4: Update PR Description +- Explain overhaul rationale +- List changes from original approach +- Emphasize GitHub native tools +- Show multi-agent equality + +## Expected Outcomes + +### Before Overhaul +- 12+ documentation files +- Claude Code positioned prominently +- Custom scripts for GitHub operations +- No actual MCP integration +- Complex devcontainer + +### After Overhaul +- 6-8 focused documentation files +- All agents as equals +- GitHub MCP server integrated +- Leveraging native GitHub tools +- Simplified devcontainer + +### Benefits +1. **Less maintenance** - Fewer docs to keep in sync +2. **Better practices** - Using GitHub's official tools +3. **Agent equality** - No preferential treatment +4. **Easier onboarding** - Clearer, more focused docs +5. **Future-proof** - Following GitHub standards + +## Next Steps + +1. Create `.mcp/config.json` +2. Rewrite `.github/AGENT_COLLABORATION.md` (simplified) +3. Convert `.claude/project-instructions.md` → `.claude/README.md` (minimal) +4. Update `.github/copilot-instructions.md` with MCP info +5. Consolidate environment docs +6. Remove redundant files +7. Update devcontainer for MCP +8. Test everything +9. Commit and push overhaul + +--- + +**Status**: Strategy defined +**Next**: Begin implementation +**Goal**: Modern, maintainable, standards-based multi-agent setup diff --git a/README.md b/README.md index f682f58..7fcb323 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,43 @@ npm run test:unit npm run lint ``` +### Unified Quality Checks for Agents + +```sh +npm run qa +``` + +- Runs ESLint, builds the project, and executes the Vitest suite in one command +- Accepts additional options (for example `npm run qa -- --with-typecheck`) to include slower checks when needed +- Designed to simplify common validation workflows for multi-agent collaboration + +## Consolidation & Automation Playbook + +- Review the [Consolidated Task Guide](./CONSOLIDATED_TASK_GUIDE.md) for a single-source summary of the seven-PR merge, automation setup, review resolution steps, and post-merge expectations. +- Pair it with the quick commands in [docs/AGENT_TOOLKIT.md](./docs/AGENT_TOOLKIT.md) when coordinating across multiple agents. +- Consult [`.github/AGENT_COLLABORATION.md`](./.github/AGENT_COLLABORATION.md) for cross-platform agent guidance covering GitHub Copilot Agent, ChatGPT Codex, Gemini Code Assist, Claude Code, and Google Jules workflows. + +## Multi-Agent Development + +This project uses multiple AI agents, each with different strengths and trade-offs: + +- **GitHub Copilot**: Primary agent for most tasks (unlimited usage) + - Quick fixes, inline suggestions, simple features, day-to-day development +- **CodeRabbit**: Automated code reviews (unlimited, use on all PRs) + - Security analysis, code quality checks, best practices verification +- **Claude Code**: Complex tasks requiring advanced capabilities (usage limits, higher cost) + - Multi-file refactoring, deep debugging, systematic feature implementation +- **ChatGPT Codex**: GitHub-integrated task automation + +**Strategy:** Start with Copilot for most work, use CodeRabbit for all reviews, escalate to Claude Code only when tasks require its advanced capabilities. + +For comprehensive agent collaboration guidelines, see [AGENT_COLLABORATION.md](./.github/AGENT_COLLABORATION.md). + +### Agent-Specific Documentation + +- **Claude Code**: [.claude/README.md](./.claude/README.md) +- **GitHub Copilot**: [.github/copilot-instructions.md](./.github/copilot-instructions.md) + ## CI/CD Pipeline This project uses GitHub Actions for continuous integration and deployment. For detailed information about our CI/CD pipelines, including: diff --git a/REVIEW_REQUEST.md b/REVIEW_REQUEST.md index af271b6..8e8bf74 100644 --- a/REVIEW_REQUEST.md +++ b/REVIEW_REQUEST.md @@ -30,6 +30,7 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with ### Phase 1: New Infrastructure Created ✅ **Docker-Based CI** (`.github/workflows/docker-compose.yml`): + - Integrated lock file validation as first step - Retry mechanism for npm ci (3 attempts) - Comprehensive validation: format, lint, type-check, build @@ -38,6 +39,7 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with - **Purpose**: Primary CI replacing legacy build.yml **Python Automation** (`automation/branch_manager.py`): + - 268 lines of production-ready Python - GitHub CLI integration - Branch lifecycle management @@ -46,6 +48,7 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with - **Purpose**: Replaces manual staging cleanup **Branch Management Workflow** (`.github/workflows/branch-management.yml`): + - Weekly scheduled execution (Sundays 3 AM UTC) - Manual trigger with dry-run support - Automatic alerting for staging limit @@ -53,6 +56,7 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with - **Purpose**: Orchestrates Python automation **Infrastructure as Code** (`.github/workflows/pulumi.yml`): + - Preview on PRs - Automated deployment on master push - Stack output export @@ -60,6 +64,7 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with - **Purpose**: Ready for IaC implementation **Lock File Validation** (`scripts/validate-lockfile.sh`): + - JSON validation - Version checking - Dry-run install verification @@ -69,6 +74,7 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with ### Phase 2: CI/CD Consolidation ✅ **Updated CI Workflow** (`.github/workflows/ci.yml`): + - Simplified to lightweight quick validation - Runs lock file validation - Basic file checks @@ -76,6 +82,7 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with - **Change**: Reduced from 120 to 48 lines (60% reduction) **Deprecated Workflow** (`.github/workflows/azure-staging-cleanup.yml`): + - Marked with deprecation notice - Scheduled execution disabled - Recommends branch-management.yml @@ -85,6 +92,7 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with ### Phase 3: Documentation Consolidation ✅ **Created**: `DEVCONTAINER_AND_AUTOMATION.md` (19KB) + - Single source of truth for all DevOps documentation - 11 major sections covering all aspects - Development environment setup @@ -97,12 +105,14 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with - Maintenance procedures **Removed Redundant Files**: + - `docs/CI_CD_GUIDE.md` (13.5KB) → Merged - `docs/CI_CD_QUICK_REFERENCE.md` (4.8KB) → Merged - `docs/IMPLEMENTATION_CHECKLIST.md` (9.3KB) → Merged - **Total**: 27.6KB consolidated into single 19KB guide **Updated**: `docs/README.md` + - Points to consolidated documentation - Marks legacy files for reference - Clear navigation for new developers @@ -115,6 +125,7 @@ Successfully created and consolidated a comprehensive DevOps infrastructure with ## Testing Results ### Build Validation ✅ + ```bash $ npm run build ✓ 1565 modules transformed @@ -122,18 +133,21 @@ $ npm run build ``` ### Linting ✅ + ```bash $ npm run lint # No errors ``` ### Formatting ✅ + ```bash $ npm run format:check # All files formatted correctly ``` ### Lock File Validation ✅ + ```bash $ bash scripts/validate-lockfile.sh === Lock File Validation === @@ -147,8 +161,9 @@ $ bash scripts/validate-lockfile.sh ## Files Modified **New Files**: + - `.github/workflows/docker-compose.yml` (4.4KB) - Docker CI -- `.github/workflows/branch-management.yml` (4.3KB) - Python automation orchestrator +- `.github/workflows/branch-management.yml` (4.3KB) - Python automation orchestrator - `.github/workflows/pulumi.yml` (3.9KB) - IaC workflow - `scripts/validate-lockfile.sh` (1.5KB) - Lock file validation - `automation/branch_manager.py` (10.2KB) - Branch and environment manager @@ -157,11 +172,13 @@ $ bash scripts/validate-lockfile.sh - `DEVCONTAINER_AND_AUTOMATION.md` (19.2KB) - Consolidated guide **Modified Files**: + - `.github/workflows/ci.yml` - Simplified to quick validation - `.github/workflows/azure-staging-cleanup.yml` - Marked deprecated - `docs/README.md` - Updated references **Removed Files**: + - `docs/CI_CD_GUIDE.md` - Consolidated - `docs/CI_CD_QUICK_REFERENCE.md` - Consolidated - `docs/IMPLEMENTATION_CHECKLIST.md` - Consolidated @@ -169,12 +186,14 @@ $ bash scripts/validate-lockfile.sh ## Specific Review Points ### 1. Workflow Structure + - Docker CI correctly integrates lock file validation - Branch management workflow has proper error handling - Pulumi workflow checks for infrastructure code before running - All workflows follow GitHub Actions best practices ### 2. Python Code Quality + - `branch_manager.py` follows PEP 8 style - Comprehensive error handling - Clear logging and output @@ -182,6 +201,7 @@ $ bash scripts/validate-lockfile.sh - Type hints for better maintainability ### 3. Documentation Quality + - Single source of truth established - Clear table of contents - Comprehensive coverage of all topics @@ -190,6 +210,7 @@ $ bash scripts/validate-lockfile.sh - Best practices section ### 4. Backward Compatibility + - All existing workflows continue to function - No breaking changes to package.json scripts - Existing automation preserved @@ -230,7 +251,7 @@ From the original requirements: ## Commit History - `449be61` - feat: add Docker CI, Python automation, and IaC infrastructure -- `4581121` - feat: consolidate CI/CD workflows and documentation +- `4581121` - feat: consolidate CI/CD workflows and documentation - `228a147` - fix: format all workflow files and fix YAML syntax --- diff --git a/docs/AGENT_TOOLKIT.md b/docs/AGENT_TOOLKIT.md new file mode 100644 index 0000000..b4e96cf --- /dev/null +++ b/docs/AGENT_TOOLKIT.md @@ -0,0 +1,52 @@ +# Agent Toolkit Quickstart + +This guide collects the most useful commands and workflows for AI and human collaborators working on the Bleedy project. It is formatted for quick consumption by GitHub Copilot Agent, ChatGPT Codex, Gemini Code Assist, Claude Code, Google Jules, and human maintainers. + +## Core Validation Commands + +| Purpose | Command | Notes | +| ------------------------- | -------------------------------- | ------------------------------------------------------------------------------------ | +| Install dependencies | `npm install` | Required before running any project script (applies patched deps automatically). | +| Run full QA sweep | `npm run qa` | Executes ESLint, Vite build, and Vitest sequentially with friendly logging. | +| Include TypeScript checks | `npm run qa -- --with-typecheck` | Adds the slower `vue-tsc` pass when TypeScript coverage is required. | +| Skip portions of QA | `npm run qa -- --skip-tests` | Combine with other flags like `--skip-lint` or `--skip-build` for docs-only updates. | +| Check formatting | `npm run format:check` | Uses Prettier; run `npm run format` to auto-fix. | + +## Branch and PR Awareness + +Staying aware of the repository state prevents duplicated work across agents. + +| Task | Command | Tip | +| ----------------------------------- | --------------------------------------------------------- | -------------------------------------------- | +| Show current branch | `git branch --show-current` | Include this in handoff notes for clarity. | +| View concise status | `git status -sb` | Captures staged/unstaged file lists quickly. | +| Review recent history | `git log --oneline --decorate --graph -5` | Adjust the `-5` depth as needed. | +| List open PRs (requires GitHub CLI) | `gh pr list --limit 20 --search "repo:danelkay93/bleedy"` | Authenticate once per session. | +| Check CI runs (GitHub CLI) | `gh run list --limit 5 --branch ` | Helps confirm whether QA has already passed. | + +## Collaboration Checklist + +1. **Read existing documentation**: `.github/AGENT_COLLABORATION.md` details protocols and templates; `CONSOLIDATED_TASK_GUIDE.md` summarizes automation, review handling, and consolidation context. +2. **Plan updates**: confirm task scope, related branches, and outstanding PRs. +3. **Implement changes**: follow the coding standards in `README.md` and component-specific guidelines. +4. **Validate quickly**: use `npm run qa` for the baseline checks. +5. **Share context**: include command outputs (`git status -sb`, QA results) in handoffs or PR descriptions. + +## Cross-Agent Defaults + +| Agent | Commit Helper | QA Expectation | Notes | +| -------------------- | ---------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------ | +| GitHub Copilot Agent | `report_progress` | Capture `npm run qa` (or explain skip) before commit. | Include staged-file summary in commit message prompt. | +| ChatGPT Codex | `report_progress` | Provide concise QA bullet list. | Mention if external URLs were inaccessible. | +| Gemini Code Assist | `apply_patch` / proxy commit | Paste exact command output and flag policy blocks. | Prefer deterministic commands; avoid network calls without confirmation. | +| Claude Code | `commit` / `open_pr` | Include diff-oriented summary in QA notes. | Quote any safety warnings verbatim. | +| Google Jules | `submit` workflow | Provide reproducible QA steps with inputs/flags. | Group related doc updates into one submission. | + +## Troubleshooting Tips + +- If `npm run qa` fails, rerun individual steps (lint/build/test) to isolate the cause. +- For repeated lint failures, ensure your editor respects the ESLint + Prettier configuration; rerun `npm install` if plugins go missing. +- When network-dependent commands hang, confirm connectivity with a simple `curl https://api.github.com` (subject to rate limits). +- When collaborating asynchronously, paste relevant log excerpts into discussions to maintain shared context. + +_Last updated: 2024-10-29_ diff --git a/docs/CI_CD_GUIDE.md b/docs/CI_CD_GUIDE.md new file mode 100644 index 0000000..01ba996 --- /dev/null +++ b/docs/CI_CD_GUIDE.md @@ -0,0 +1,488 @@ +# CI/CD Pipeline Documentation + +This document provides comprehensive guidelines for understanding, maintaining, and troubleshooting the CI/CD pipelines for the Bleedy project. + +## Table of Contents + +1. [Overview](#overview) +2. [Workflows](#workflows) +3. [Best Practices](#best-practices) +4. [Troubleshooting](#troubleshooting) +5. [Maintenance](#maintenance) + +## Overview + +The Bleedy project uses GitHub Actions for continuous integration and deployment. Our CI/CD pipeline consists of multiple workflows designed to ensure code quality, security, and reliable deployments. + +### Architecture + +``` +┌─────────────────────────────────────────────────────────┐ +│ GitHub Actions │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ CI Checks │ │ Lock File │ │ Security │ │ +│ │ & Build │ │ Sync │ │ Audit │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ Azure │ │ Staging │ │ SonarCloud │ │ +│ │ Deployment │ │ Cleanup │ │ Analysis │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +## Workflows + +### 1. CI Checks and Build (`ci.yml`) + +**Triggers:** Push to master, Pull requests + +**Purpose:** Validates code quality and ensures the project builds successfully + +**Jobs:** +- **validate-and-build** + - Installs dependencies with retry mechanism (3 attempts) + - Runs Prettier format check + - Executes ESLint + - Performs TypeScript type checking + - Builds the project + +- **security-audit** + - Runs `npm audit` to check for vulnerabilities + - Fails if critical or high severity vulnerabilities found + - Uploads audit results as artifacts + - Provides detailed summary in workflow output + +**Configuration:** +- Node.js version: 20.x +- Retry attempts: 3 (with 30s delay between attempts) +- Cache: npm dependencies + +**Error Handling:** +- Automatic retry for transient npm ci failures +- Cache cleaning on retry to prevent corruption +- Detailed error messages and summaries + +### 2. Lock File Synchronization (`lockfile-sync.yml`) + +**Triggers:** Pull requests modifying `package.json` or `package-lock.json`, Manual dispatch + +**Purpose:** Ensures `package-lock.json` stays in sync with `package.json` + +**Process:** +1. Checks if lock file is synchronized +2. Regenerates lock file if out of sync +3. Commits and pushes changes automatically +4. Adds informative PR comment + +**Best Practices Enforced:** +- Never manually edit `package-lock.json` +- Always commit lock file changes with `package.json` updates +- Use `npm ci` in CI/CD pipelines + +### 3. Azure Static Web Apps Deployment (`azure-static-web-apps-*.yml`) + +**Triggers:** Push to master, Pull requests + +**Purpose:** Deploys the application to Azure Static Web Apps + +**Features:** +- Validates build output before deployment +- Retry mechanism for npm ci +- Enhanced error messages for deployment failures +- Success/failure notifications +- Automatic cleanup of staging environments on PR closure + +**Configuration:** +- App location: `/` +- Output location: `dist` +- Node.js version: 20.x + +**Error Messages:** +Provides actionable feedback for common failures: +- Staging environment limit reached +- API token issues +- Build output problems +- Network connectivity issues + +### 4. Azure Staging Cleanup (`azure-staging-cleanup.yml`) + +**Triggers:** Weekly schedule (Sundays at 2 AM UTC), Manual dispatch + +**Purpose:** Monitors and manages Azure staging environments + +**Features:** +- Lists all open PRs with active staging environments +- Provides visibility into staging environment usage +- Creates alerts when approaching Azure limits (10 staging environments on free tier) +- Supports dry-run mode for testing + +**Manual Trigger:** +```bash +# Via GitHub UI: Actions → Azure Staging Cleanup → Run workflow +# Options: dry_run (true/false) +``` + +### 5. SonarCloud Analysis (`sonarcloud.yml`) + +**Triggers:** Push to master, Pull requests + +**Purpose:** Performs static code analysis for code quality + +**Configuration:** +- Project key: `danelkay93_bleedy` +- Organization: `earthly-serenity` + +### 6. Post-Merge Cleanup (`post-merge-cleanup.yml`) + +**Triggers:** PR closure (merged only) + +**Purpose:** Cleans up consolidated PRs and branches + +**Features:** +- Detects consolidation PRs +- Closes related PRs +- Deletes obsolete branches +- Adds cleanup summary + +## Best Practices + +### Package Management + +#### Lock File Management + +**DO:** +✅ Always run `npm install` after pulling changes +✅ Commit `package-lock.json` with `package.json` updates +✅ Use `npm ci` in CI/CD pipelines (faster and more reliable) +✅ Let the automated workflow fix sync issues + +**DON'T:** +❌ Never manually edit `package-lock.json` +❌ Don't ignore lock file changes in git +❌ Don't use `npm install` in CI/CD pipelines +❌ Don't commit with out-of-sync lock files + +#### Dependency Updates + +```bash +# Check for outdated dependencies +npm outdated + +# Update a specific package +npm update + +# Update to latest versions (breaking changes possible) +npm update --latest + +# Always test after updates +npm run build +npm run test:unit +``` + +### Security + +#### Running Security Audits + +```bash +# Run audit locally +npm audit + +# Get detailed report +npm audit --json > audit-report.json + +# Fix automatically fixable issues +npm audit fix + +# Fix with breaking changes (use with caution) +npm audit fix --force +``` + +#### Vulnerability Management + +1. **Critical/High Severity**: Address immediately + - Review the vulnerability details + - Update the affected package + - Test thoroughly before merging + - Monitor for patches if no fix available + +2. **Moderate Severity**: Address in next sprint + - Evaluate risk vs. effort + - Plan update in regular cycle + - Consider workarounds if needed + +3. **Low Severity**: Address in maintenance cycle + - Monitor for severity changes + - Include in bulk updates + - Document known issues + +### Build Optimization + +#### Chunk Size Management + +The project uses manual chunk splitting for optimal performance: + +```typescript +// vite.config.ts +build: { + chunkSizeWarningLimit: 1000, // Increased for PyScript dependencies + rollupOptions: { + output: { + manualChunks: { + 'vendor-vue': ['vue', 'vue-router', 'pinia'], + 'vendor-ui': ['element-plus', '@element-plus/icons-vue'], + 'vendor-utils': ['file-saver', 'jszip'], + 'vendor-sketchy': ['roughjs', 'wired-elements'] + } + } + } +} +``` + +**Guidelines:** +- Keep vendor chunks separate from application code +- Group related libraries together +- Monitor chunk sizes after adding new dependencies +- Adjust `chunkSizeWarningLimit` only when justified + +### Azure Deployment + +#### Staging Environment Limits + +**Free Tier Limits:** +- Maximum 10 staging environments (one per PR) +- Unlimited production deployments + +**Best Practices:** +- Close or merge PRs promptly +- Limit concurrent open PRs to 8 or fewer +- Use draft PRs for work-in-progress +- Monitor staging usage with cleanup workflow + +#### Deployment Troubleshooting + +**"Deployment failed" error:** +1. Check Azure service health +2. Verify API token in repository secrets +3. Review build output validation +4. Check staging environment count +5. Review Azure portal for specific errors + +**Manual cleanup if needed:** +```bash +# Via Azure CLI +az staticwebapp environment list --name +az staticwebapp environment delete --name --environment-name +``` + +## Troubleshooting + +### Common Issues + +#### 1. npm ci Failures + +**Symptoms:** +- "ENOLOCK: no package-lock.json found" +- "Invalid package-lock.json" +- Network timeout errors + +**Solutions:** +1. Let retry mechanism complete (automatic) +2. If persistent, regenerate lock file locally: + ```bash + rm package-lock.json + npm install + git add package-lock.json + git commit -m "chore: regenerate package-lock.json" + git push + ``` + +#### 2. Build Failures + +**Symptoms:** +- TypeScript errors +- Missing dependencies +- Import resolution failures + +**Solutions:** +1. Pull latest changes: `git pull` +2. Clean install: `rm -rf node_modules && npm install` +3. Check for patches: Patches are automatically applied during install +4. Verify build locally: `npm run build` + +#### 3. Deployment Failures + +**Symptoms:** +- Azure deployment timeout +- "Staging limit reached" error +- Build output validation failure + +**Solutions:** +1. Check staging environment count (use cleanup workflow) +2. Verify `dist/` directory exists and contains `index.html` +3. Review Azure Static Web Apps logs +4. Manually trigger cleanup workflow if needed + +#### 4. Lock File Out of Sync + +**Symptoms:** +- "lockfile-sync" workflow creates commits +- npm ci fails with hash mismatch + +**Solutions:** +- Automatic: Workflow fixes and commits +- Manual prevention: Always commit lock file with package.json + +#### 5. Security Audit Failures + +**Symptoms:** +- CI fails on security-audit job +- Critical/high severity vulnerabilities found + +**Solutions:** +1. Review vulnerability details in workflow logs +2. Check for available patches: `npm audit fix` +3. Update vulnerable dependencies +4. If no fix available, document and create issue +5. Consider temporary exception if risk is low + +### Debug Mode + +Enable detailed logging for troubleshooting: + +```yaml +# Add to workflow steps +- name: Enable debug logging + run: | + echo "ACTIONS_STEP_DEBUG=true" >> $GITHUB_ENV + echo "ACTIONS_RUNNER_DEBUG=true" >> $GITHUB_ENV +``` + +### Viewing Logs + +1. Navigate to Actions tab in GitHub +2. Select the workflow run +3. Click on the failed job +4. Expand the failed step +5. Review error messages and context + +## Maintenance + +### Regular Tasks + +#### Weekly +- [ ] Review open PRs and staging environments +- [ ] Check security audit results +- [ ] Monitor workflow success rates + +#### Monthly +- [ ] Update dependencies: `npm update` +- [ ] Review and address moderate security vulnerabilities +- [ ] Check for outdated GitHub Actions versions +- [ ] Review and optimize build performance + +#### Quarterly +- [ ] Major dependency updates (Vue, Vite, etc.) +- [ ] Review and update workflow configurations +- [ ] Audit and clean up unused workflows +- [ ] Update documentation + +### Updating Workflows + +When modifying workflows: + +1. **Test in a branch first** + ```bash + git checkout -b test/workflow-update + # Make changes + git push -u origin test/workflow-update + # Create PR to test workflow + ``` + +2. **Use workflow_dispatch for testing** + ```yaml + on: + workflow_dispatch: + # ... other triggers + ``` + +3. **Monitor first runs carefully** + - Check all jobs complete successfully + - Verify outputs and artifacts + - Review error handling paths + +4. **Document changes** + - Update this document + - Add comments in workflow files + - Update PR description + +### Monitoring + +#### Key Metrics to Track + +1. **Build Success Rate**: Target > 95% +2. **Average Build Time**: Target < 10 minutes +3. **Deployment Success Rate**: Target > 98% +4. **Security Vulnerabilities**: Target = 0 critical/high + +#### Alerts to Configure + +- Multiple consecutive build failures +- Security vulnerabilities detected +- Staging environment limit approaching +- Deployment failures + +### Emergency Procedures + +#### Complete CI Failure + +If all builds are failing: + +1. Check GitHub Actions status page +2. Verify repository secrets are valid +3. Roll back recent workflow changes +4. Contact GitHub support if platform issue + +#### Deployment Outage + +If Azure deployments are failing: + +1. Check Azure service health +2. Verify production site is still accessible +3. Disable deployment workflow temporarily if needed: + ```yaml + jobs: + build_and_deploy_job: + if: false # Temporarily disable + ``` +4. Investigate and fix root cause +5. Re-enable workflow + +## Additional Resources + +- [GitHub Actions Documentation](https://docs.github.com/en/actions) +- [Azure Static Web Apps Documentation](https://docs.microsoft.com/en-us/azure/static-web-apps/) +- [npm Documentation](https://docs.npmjs.com/) +- [Vite Build Documentation](https://vitejs.dev/guide/build.html) +- [SonarCloud Documentation](https://docs.sonarcloud.io/) + +## Support + +For issues not covered in this documentation: + +1. Check existing GitHub Issues +2. Review workflow run logs +3. Create a new issue with: + - Workflow run link + - Error messages + - Steps to reproduce + - Environment details + +--- + +**Last Updated:** [Current Date] +**Maintainers:** Project Team +**Version:** 1.0.0 diff --git a/docs/CI_CD_QUICK_REFERENCE.md b/docs/CI_CD_QUICK_REFERENCE.md new file mode 100644 index 0000000..e44f3db --- /dev/null +++ b/docs/CI_CD_QUICK_REFERENCE.md @@ -0,0 +1,281 @@ +# CI/CD Quick Reference + +Quick reference guide for common CI/CD tasks and commands. + +## Daily Operations + +### Check Build Status +```bash +# View in GitHub +# Navigate to: https://github.com/danelkay93/bleedy/actions + +# Or use GitHub CLI +gh run list --limit 5 +gh run view +``` + +### Run Security Audit Locally +```bash +npm audit + +# Fix automatically fixable issues +npm audit fix + +# View detailed report +npm audit --json > audit-report.json +``` + +### Test Build Locally +```bash +# Clean build +rm -rf dist node_modules +npm install +npm run build + +# Check bundle sizes +ls -lh dist/assets/ +``` + +## Workflow Management + +### Trigger Manual Workflows + +#### Lock File Sync +```bash +gh workflow run lockfile-sync.yml +``` + +#### Azure Staging Cleanup +```bash +gh workflow run azure-staging-cleanup.yml --field dry_run=true +``` + +### View Workflow Logs +```bash +# List recent runs +gh run list --workflow=ci.yml --limit 5 + +# View specific run +gh run view --log + +# Download logs +gh run download +``` + +## Common Tasks + +### Update Dependencies +```bash +# Check for updates +npm outdated + +# Update all to latest compatible +npm update + +# Update specific package +npm update + +# Always commit package-lock.json +git add package.json package-lock.json +git commit -m "chore: update dependencies" +``` + +### Fix Lock File Issues +```bash +# If out of sync +rm package-lock.json +npm install +git add package-lock.json +git commit -m "chore: regenerate package-lock.json" + +# Or let the workflow handle it automatically +``` + +### Resolve Build Failures + +#### TypeScript Errors +```bash +npm run type-check +# Fix reported errors in code +``` + +#### ESLint Errors +```bash +npm run lint +# Fix reported errors +``` + +#### Format Issues +```bash +npm run format +git add . +git commit -m "chore: format code" +``` + +### Test Vite Configuration Changes +```bash +# Development build +npm run dev + +# Production build +npm run build + +# Preview production build +npm run preview +``` + +## Deployment + +### Check Azure Deployment Status +```bash +# Via GitHub Actions +gh run list --workflow=azure-static-web-apps-*.yml --limit 5 + +# Check PR deployment comments +gh pr view +``` + +### Force Redeploy +```bash +# Push an empty commit +git commit --allow-empty -m "chore: trigger deployment" +git push +``` + +## Troubleshooting + +### CI Failing with npm ci Error +```bash +# Check if lock file is out of sync +npm ci --dry-run + +# If fails, regenerate +rm package-lock.json +npm install + +# Workflow will retry automatically (3 attempts) +``` + +### Build Failing Locally but Passing in CI +```bash +# Use exact Node version from CI +nvm install 20 +nvm use 20 + +# Clean install +rm -rf node_modules package-lock.json +npm install +npm run build +``` + +### Deployment Failing +```bash +# Check staging environment count +# Via GitHub: Actions → Azure Staging Cleanup → Run workflow (dry_run=true) + +# Or manually check open PRs +gh pr list --state open +``` + +### Security Audit Blocking Merge +```bash +# Review vulnerabilities +npm audit + +# Update vulnerable packages +npm update + +# If no fix available, check if dev dependency +# Consider --production flag for runtime-only audit +npm audit --production +``` + +## Monitoring + +### Check Workflow Success Rate +```bash +gh run list --workflow=ci.yml --limit 20 --json conclusion +``` + +### View Build Performance +```bash +# Check recent build times +gh run list --workflow=ci.yml --limit 10 --json conclusion,timing +``` + +### Monitor Open PRs and Staging Environments +```bash +gh pr list --state open +``` + +## Emergency Procedures + +### Disable a Workflow Temporarily +1. Edit workflow file +2. Add `if: false` to job: +```yaml +jobs: + my-job: + if: false # Temporarily disabled +``` +3. Commit and push + +### Rollback a Bad Deployment +```bash +# Revert to previous commit +git revert HEAD +git push + +# Or force push to previous state (use with caution) +git reset --hard +git push --force +``` + +### Skip CI on Commit +```bash +git commit -m "docs: update README [skip ci]" +``` + +## Useful Aliases + +Add to your `.bashrc` or `.zshrc`: + +```bash +# CI/CD shortcuts +alias ci-status='gh run list --limit 5' +alias ci-logs='gh run view --log' +alias ci-build='npm run build' +alias ci-audit='npm audit' +alias ci-fix='npm audit fix && npm run lint && npm run format' +``` + +## GitHub CLI Setup + +If you don't have GitHub CLI: + +```bash +# macOS +brew install gh + +# Linux +curl -sS https://webi.sh/gh | sh + +# Windows +winget install GitHub.cli + +# Authenticate +gh auth login +``` + +## Links + +- [Main CI/CD Guide](./CI_CD_GUIDE.md) +- [GitHub Actions Docs](https://docs.github.com/en/actions) +- [Azure Static Web Apps](https://docs.microsoft.com/en-us/azure/static-web-apps/) +- [npm CLI Docs](https://docs.npmjs.com/cli/) +- [Vite Build Docs](https://vitejs.dev/guide/build.html) + +--- + +**Last Updated:** 2025-10-16 +**Version:** 1.0.0 diff --git a/docs/IMPLEMENTATION_CHECKLIST.md b/docs/IMPLEMENTATION_CHECKLIST.md new file mode 100644 index 0000000..d9d13e6 --- /dev/null +++ b/docs/IMPLEMENTATION_CHECKLIST.md @@ -0,0 +1,338 @@ +# CI/CD Pipeline Implementation Checklist + +This document tracks the implementation of CI/CD pipeline improvements as specified in the requirements. + +## Implementation Status + +### 1. Azure Static Web Apps Deployment ✅ + +#### Automated Cleanup Mechanism +- ✅ Created `azure-staging-cleanup.yml` workflow +- ✅ Weekly scheduled monitoring (Sundays at 2 AM UTC) +- ✅ Manual trigger support with dry-run mode +- ✅ Alerts when approaching Azure limits (10 staging environments) +- ✅ Automatic issue creation for high staging environment count +- ✅ Lists all active staging environments + +**Location:** `.github/workflows/azure-staging-cleanup.yml` + +**Usage:** +```bash +# Manual trigger with dry-run +gh workflow run azure-staging-cleanup.yml --field dry_run=true + +# View staging environment status +# Navigate to Actions → Azure Staging Cleanup → View latest run +``` + +#### Enhanced Error Handling +- ✅ Build validation before deployment +- ✅ Continue-on-error for graceful failure handling +- ✅ Detailed error messages in GITHUB_STEP_SUMMARY +- ✅ Actionable feedback for common failures: + - Staging environment limit reached + - API token issues + - Build output problems + - Network connectivity issues +- ✅ Success/failure notifications in PR comments + +**Location:** `.github/workflows/azure-static-web-apps-*.yml` + +**Features:** +- Pre-deployment validation of dist/ directory +- Enhanced error messages with troubleshooting steps +- PR comments on deployment success +- Cleanup notification on environment removal + +--- + +### 2. Lock File Synchronization ✅ + +#### Validation Step +- ✅ Created `lockfile-sync.yml` workflow +- ✅ Triggers on package.json or package-lock.json changes +- ✅ Checks sync with `npm ci --dry-run` +- ✅ Detects out-of-sync conditions + +**Location:** `.github/workflows/lockfile-sync.yml` + +#### Automated Regeneration +- ✅ Regenerates package-lock.json when out of sync +- ✅ Commits changes automatically +- ✅ Adds informative PR comment +- ✅ Provides best practices guidance + +**Automated Actions:** +1. Detects sync issues +2. Removes old lock file +3. Generates new lock file with `npm install --package-lock-only` +4. Commits with descriptive message +5. Pushes to PR branch +6. Comments on PR with guidance + +--- + +### 3. Build Process Optimization ✅ + +#### Dynamic/Static Import Resolution +- ✅ Fixed mixed import warnings in `ImageSelection.vue` +- ✅ Changed from dynamic imports to static imports +- ✅ Build now completes without warnings + +**Location:** `src/components/ImageSelection.vue` + +**Change:** +```typescript +// Before (mixed imports) +components: { + ImageGalleryItem: () => import('./ImageGalleryItem.vue'), + SearchToolbar: () => import('./SearchToolbar.vue') +} + +// After (static imports) +import ImageGalleryItem from './ImageGalleryItem.vue' +import SearchToolbar from './SearchToolbar.vue' +``` + +#### Manual Chunks Configuration +- ✅ Implemented `manualChunks` in Vite config +- ✅ Organized chunks by purpose: + - `vendor-vue`: Core Vue framework + - `vendor-ui`: Element Plus UI library + - `vendor-utils`: File handling utilities + - `vendor-sketchy`: Rough.js and wired-elements +- ✅ Optimizes caching and load performance + +**Location:** `vite.config.ts` + +#### Chunk Size Warning Limit +- ✅ Adjusted `chunkSizeWarningLimit` to 1000 kB +- ✅ Justified for PyScript dependencies +- ✅ Documented reasoning in config comments + +**Results:** +- No chunk size warnings +- No dynamic import warnings +- Optimal code splitting +- Build time: ~7 seconds + +--- + +### 4. GitHub Actions Resilience ✅ + +#### Retry Mechanisms +- ✅ Implemented retry action for `npm ci` (3 attempts) +- ✅ 30-second delay between retries +- ✅ Cache cleaning on retry to prevent corruption +- ✅ Applied to both CI and Azure deployment workflows + +**Implementation:** +```yaml +- name: Install dependencies with retry + uses: nick-fields/retry-action@v3 + with: + timeout_minutes: 10 + max_attempts: 3 + retry_wait_seconds: 30 + command: npm ci + on_retry_command: | + echo "::warning::npm ci failed, retrying..." + rm -rf node_modules + npm cache clean --force +``` + +**Locations:** +- `.github/workflows/ci.yml` +- `.github/workflows/azure-static-web-apps-*.yml` + +#### Enhanced Error Handling +- ✅ Descriptive error messages +- ✅ Context-specific troubleshooting guidance +- ✅ Warning messages for retry attempts +- ✅ Summary output for audit results + +#### Best Practices Documentation +- ✅ Documented lock file management +- ✅ Documented dependency auditing procedures +- ✅ Created maintenance schedule +- ✅ Included emergency procedures + +**Location:** `docs/CI_CD_GUIDE.md` + +--- + +### 5. General CI/CD Pipeline Improvements ✅ + +#### Workflow Refactoring +- ✅ Improved readability with clear step names +- ✅ Consistent formatting across all workflows +- ✅ Added descriptive comments +- ✅ Logical job organization + +#### Dependency Validation +- ✅ Added npm caching for faster builds +- ✅ Implemented security audit job +- ✅ Validates dependencies on every PR +- ✅ Checks for outdated packages + +#### npm audit Job +- ✅ New `security-audit` job in CI workflow +- ✅ Runs `npm audit` on every push/PR +- ✅ Fails on critical/high severity vulnerabilities +- ✅ Uploads audit results as artifacts +- ✅ Provides detailed summary + +**Configuration:** +```yaml +security-audit: + runs-on: ubuntu-latest + steps: + - Run npm audit + - Parse results (critical, high, moderate, low) + - Fail if critical or high vulnerabilities found + - Upload results as artifact + - Add summary to workflow output +``` + +**Results:** +- Automatic vulnerability detection +- Artifact retention: 30 days +- Clear pass/fail criteria +- Actionable feedback + +--- + +### 6. Documentation ✅ + +#### CI/CD Maintenance Guide +- ✅ Created comprehensive CI/CD guide +- ✅ Documented all workflows +- ✅ Included troubleshooting procedures +- ✅ Maintenance schedules and tasks + +**Location:** `docs/CI_CD_GUIDE.md` + +**Contents:** +- Overview and architecture +- Workflow descriptions +- Best practices +- Troubleshooting guide +- Maintenance procedures +- Emergency protocols + +#### Developer Guidelines +- ✅ Lock file management best practices +- ✅ Dependency update procedures +- ✅ Security audit guidelines +- ✅ Build optimization tips +- ✅ Deployment troubleshooting + +**Location:** `docs/CI_CD_GUIDE.md` (sections) + +#### Quick Reference +- ✅ Created quick reference guide +- ✅ Common commands and tasks +- ✅ Troubleshooting shortcuts +- ✅ Useful aliases + +**Location:** `docs/CI_CD_QUICK_REFERENCE.md` + +#### Documentation Structure +- ✅ Created docs/ directory +- ✅ Added docs README with navigation +- ✅ Updated main README with CI/CD reference +- ✅ Cross-referenced all documents + +--- + +## Verification Tests + +### Automated Tests +- [x] YAML syntax validation (all workflows pass) +- [x] Build verification (successful, no warnings) +- [x] Import resolution (no mixed import warnings) +- [x] Chunk optimization (proper splitting achieved) + +### Manual Verification Needed +- [ ] Lock file sync workflow (trigger on package.json change) +- [ ] Retry mechanism (simulate npm ci failure) +- [ ] Security audit workflow (check with known vulnerability) +- [ ] Azure deployment validation (test with actual deployment) +- [ ] Staging cleanup workflow (run with dry-run mode) + +### Documentation Review +- [x] CI/CD Guide completeness +- [x] Quick Reference accuracy +- [x] Code examples correctness +- [x] Cross-references validity + +--- + +## Deployment Checklist + +Before merging: +- [x] All workflow YAML files are valid +- [x] Build succeeds with optimizations +- [x] Documentation is complete +- [x] Changes are tested locally +- [ ] Workflows tested in PR (will be tested automatically) + +After merging: +- [ ] Monitor first workflow runs +- [ ] Verify retry mechanism activates if needed +- [ ] Check security audit results +- [ ] Review deployment success +- [ ] Validate staging cleanup runs as scheduled + +--- + +## Success Criteria + +All requirements from the problem statement have been implemented: + +✅ **Azure Static Web Apps Deployment** +- Automated cleanup mechanism for staging environments +- Enhanced error handling with clear feedback + +✅ **Lock File Synchronization** +- Validation step for package-lock.json sync +- Automated regeneration and commit + +✅ **Build Process Optimization** +- Dynamic/static import warnings resolved +- Manual chunks configuration implemented +- Chunk size warning limit adjusted + +✅ **GitHub Actions Resilience** +- Retry mechanisms for npm ci +- Better error handling throughout +- Best practices documentation + +✅ **General CI/CD Improvements** +- Refactored workflows for readability +- Dependency validation mechanisms +- npm audit job with vulnerability checks + +✅ **Documentation** +- Comprehensive CI/CD guide +- Quick reference for developers +- Best practices and maintenance procedures + +--- + +## Additional Improvements Implemented + +Beyond the requirements: +- ✅ npm caching for faster builds +- ✅ Detailed workflow summaries +- ✅ PR comments for deployment status +- ✅ Artifact uploads for audit results +- ✅ Documentation structure with README +- ✅ Emergency procedures documentation +- ✅ Maintenance schedule templates + +--- + +**Implementation Date:** 2025-10-16 +**Status:** Complete +**Next Steps:** Monitor workflows in production, gather feedback, iterate diff --git a/docs/README.md b/docs/README.md index 513119c..563e50b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -39,10 +39,14 @@ The following files are maintained for historical reference but are superseded b - [Main README](../README.md) - Project overview and setup - [DEVCONTAINER_AND_AUTOMATION.md](../DEVCONTAINER_AND_AUTOMATION.md) - **Primary DevOps documentation** -- [.github/copilot-instructions.md](../.github/copilot-instructions.md) - Development guidelines -- [.github/AGENT_COLLABORATION.md](../.github/AGENT_COLLABORATION.md) - Multi-agent collaboration +- [.github/AGENT_COLLABORATION.md](../.github/AGENT_COLLABORATION.md) - Multi-agent collaboration guidelines +- [.github/copilot-instructions.md](../.github/copilot-instructions.md) - GitHub Copilot configuration +- [.claude/README.md](../.claude/README.md) - Claude Code configuration - [automation/README.md](../automation/README.md) - Automation scripts - [infrastructure/README.md](../infrastructure/README.md) - IaC details +- [FUTURE_WORK.md](../FUTURE_WORK.md) - Planned enhancements +- [TODO.md](../TODO.md) - Current tasks and priorities +- [GitHub Actions Workflows](../.github/workflows/) - Actual workflow files ## Contributing diff --git a/package.json b/package.json index c091187..1876b50 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,8 @@ "lint": "eslint . --fix", "format": "prettier --write .", "format:check": "prettier --check .", + "qa": "node ./scripts/agent-check.mjs", + "qa:with-typecheck": "node ./scripts/agent-check.mjs --with-typecheck", "prepare": "husky install || true" }, "dependencies": { diff --git a/scripts/agent-check.mjs b/scripts/agent-check.mjs new file mode 100755 index 0000000..be11f34 --- /dev/null +++ b/scripts/agent-check.mjs @@ -0,0 +1,92 @@ +#!/usr/bin/env node +import { spawnSync } from 'node:child_process'; +import process from 'node:process'; + +const args = process.argv.slice(2); +const flagSet = new Set(); +const passthroughArgs = []; + +for (const arg of args) { + if (arg === '--help' || arg === '-h') { + printHelp(); + process.exit(0); + } + if (arg === '--with-typecheck' || arg === '--skip-tests' || arg === '--skip-build' || arg === '--skip-lint') { + flagSet.add(arg); + continue; + } + // Treat unknown arguments as passthrough args for vitest + passthroughArgs.push(arg); +} + +const steps = []; + +if (!flagSet.has('--skip-lint')) { + steps.push({ + key: 'lint', + label: 'ESLint', + command: 'npm', + commandArgs: ['run', 'lint'], + description: 'Static analysis via ESLint', + }); +} + +if (flagSet.has('--with-typecheck')) { + steps.push({ + key: 'typecheck', + label: 'Vue Type Check', + command: 'npm', + commandArgs: ['run', 'type-check'], + description: 'Full vue-tsc type checking (may fail due to known issues)', + }); +} + +if (!flagSet.has('--skip-build')) { + steps.push({ + key: 'build', + label: 'Vite Build', + command: 'npm', + commandArgs: ['run', 'build'], + description: 'Production build via Vite', + }); +} + +if (!flagSet.has('--skip-tests')) { + const testArgs = passthroughArgs.length > 0 ? ['--', ...passthroughArgs] : ['--', '--run']; + if (!testArgs.includes('--passWithNoTests')) { + testArgs.push('--passWithNoTests'); + } + steps.push({ + key: 'tests', + label: 'Vitest', + command: 'npm', + commandArgs: ['run', 'test:unit', ...testArgs], + description: 'Unit tests with Vitest', + }); +} + +if (steps.length === 0) { + console.log('No steps selected. Use --help for usage information.'); + process.exit(0); +} + +console.log('🔧 Running Bleedy agent environment checks...'); + +for (const step of steps) { + console.log(`\n➡️ ${step.label} – ${step.description}`); + const result = spawnSync(step.command, step.commandArgs, { + stdio: 'inherit', + shell: process.platform === 'win32', + }); + + if (result.status !== 0) { + console.error(`\n❌ ${step.label} failed. See output above.`); + process.exit(typeof result.status === 'number' ? result.status : 1); + } +} + +console.log('\n✅ All selected checks passed!'); + +function printHelp() { + console.log(`Bleedy Agent QA Helper\n\nUsage: npm run qa [options] [-- [vitest-options]]\n\nOptions:\n --with-typecheck Include the slower vue-tsc type checking step\n --skip-lint Skip the ESLint run\n --skip-build Skip the Vite production build\n --skip-tests Skip the Vitest suite\n -h, --help Show this help message\n\nAll other arguments after -- are passed directly to Vitest.\n\nExamples:\n npm run qa\n npm run qa -- --with-typecheck\n npm run qa -- --skip-tests\n npm run qa -- --run --coverage\n npm run qa -- --grep "my test pattern"\n`); +} diff --git a/scripts/get_pr_reviews.py b/scripts/get_pr_reviews.py new file mode 100755 index 0000000..9008d12 --- /dev/null +++ b/scripts/get_pr_reviews.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +""" +Get PR reviews programmatically using GitHub CLI + +This script demonstrates how to access PR review information using gh CLI, +which is the recommended approach for agents working within the repository. + +Exit Codes: + 0 - PR is approved (success) + 1 - PR is pending review or other state (no decision yet) + 2 - PR has changes requested (action required) + +The exit codes are designed for automation that needs to distinguish between +different PR states. For simple success/failure checks, treat any non-zero +exit code as failure. For more sophisticated workflows, use the specific codes: +- 0: Safe to merge (approved) +- 2: Must address feedback (changes requested) +- 1: Waiting or unknown state (pending/other) + +This follows conventions used by tools like `diff` and `grep` where different +non-zero exit codes indicate different types of "failure" or states. +""" + +import subprocess +import json +import sys +from typing import Dict, List, Optional + + +def run_gh_command(args: List[str]) -> str: + """Execute a gh CLI command and return output""" + try: + result = subprocess.run( + ["gh"] + args, + capture_output=True, + text=True, + check=True + ) + return result.stdout.strip() + except subprocess.CalledProcessError as e: + print(f"Error running gh command: {e}", file=sys.stderr) + print(f"stderr: {e.stderr}", file=sys.stderr) + raise + + +def get_pr_by_branch(branch_name: str) -> Optional[int]: + """Find PR number by branch name""" + try: + output = run_gh_command([ + "pr", "list", + "--head", branch_name, + "--json", "number", + "--jq", ".[0].number" + ]) + return int(output) if output and output != "null" else None + except (ValueError, subprocess.CalledProcessError): + return None + + +def get_pr_details(pr_number: int) -> Dict: + """Get detailed PR information including reviews""" + try: + output = run_gh_command([ + "pr", "view", str(pr_number), + "--json", "number,title,state,author,reviews,comments,reviewDecision,baseRefName,headRefName" + ]) + return json.loads(output) + except subprocess.CalledProcessError: + return {} + + +def get_pr_reviews(pr_number: int) -> List[Dict]: + """Get reviews for a specific PR""" + try: + # Using gh api directly for reviews + output = run_gh_command([ + "api", + f"/repos/{{owner}}/{{repo}}/pulls/{pr_number}/reviews", + "--jq", "." + ]) + return json.loads(output) if output else [] + except subprocess.CalledProcessError: + return [] + + +def get_pr_review_comments(pr_number: int) -> List[Dict]: + """Get review comments (line-specific comments) for a PR""" + try: + output = run_gh_command([ + "api", + f"/repos/{{owner}}/{{repo}}/pulls/{pr_number}/comments", + "--jq", "." + ]) + return json.loads(output) if output else [] + except subprocess.CalledProcessError: + return [] + + +def format_review_summary(pr_details: Dict) -> str: + """Format PR review information for display""" + lines = [] + lines.append(f"\n{'='*80}") + lines.append(f"PR #{pr_details.get('number')}: {pr_details.get('title')}") + lines.append(f"{'='*80}") + lines.append(f"State: {pr_details.get('state')}") + lines.append(f"Author: {pr_details.get('author', {}).get('login', 'Unknown')}") + lines.append(f"Base: {pr_details.get('baseRefName')} <- Head: {pr_details.get('headRefName')}") + lines.append(f"Review Decision: {pr_details.get('reviewDecision', 'PENDING')}") + lines.append("") + + reviews = pr_details.get('reviews', []) + if reviews: + lines.append(f"Reviews ({len(reviews)}):") + lines.append("-" * 80) + for review in reviews: + author = review.get('author', {}).get('login', 'Unknown') + state = review.get('state', 'UNKNOWN') + submitted_at = review.get('submittedAt', 'Unknown') + body = review.get('body', '').strip() + + lines.append(f"\n{author} - {state} (submitted: {submitted_at})") + if body: + lines.append(f" Comment: {body}") + else: + lines.append("No reviews yet") + + comments = pr_details.get('comments', []) + if comments: + lines.append(f"\n\nComments ({len(comments)}):") + lines.append("-" * 80) + for comment in comments: + author = comment.get('author', {}).get('login', 'Unknown') + body = comment.get('body', '').strip() + lines.append(f"\n{author}:") + lines.append(f" {body[:200]}..." if len(body) > 200 else f" {body}") + + return "\n".join(lines) + + +def main(): + """Main entry point""" + if len(sys.argv) < 2: + print("Usage: python3 get_pr_reviews.py ") + print("\nExamples:") + print(" python3 get_pr_reviews.py 36") + print(" python3 get_pr_reviews.py claude/update-documentation-integration-011CULn7AGnkyHBdk8qWi4qx") + sys.exit(1) + + arg = sys.argv[1] + + # Try to parse as PR number first + try: + pr_number = int(arg) + except ValueError: + # Assume it's a branch name + print(f"Looking up PR for branch: {arg}") + pr_number = get_pr_by_branch(arg) + if not pr_number: + print(f"No PR found for branch: {arg}", file=sys.stderr) + sys.exit(1) + print(f"Found PR #{pr_number}") + + # Get PR details + pr_details = get_pr_details(pr_number) + if not pr_details: + print(f"Could not fetch details for PR #{pr_number}", file=sys.stderr) + sys.exit(1) + + # Display summary + print(format_review_summary(pr_details)) + + # Return exit code based on review decision + # Exit codes allow automation to distinguish between different PR states: + # 0 = APPROVED (safe to merge) + # 2 = CHANGES_REQUESTED (must address feedback) + # 1 = PENDING or other (waiting or unknown state) + decision = pr_details.get('reviewDecision', '') + if decision == 'APPROVED': + sys.exit(0) # Success - PR approved + elif decision == 'CHANGES_REQUESTED': + sys.exit(2) # Action required - changes requested + else: + sys.exit(1) # Waiting - pending review or unknown state + + +if __name__ == "__main__": + main() diff --git a/scripts/setup-agent-environment.sh b/scripts/setup-agent-environment.sh new file mode 100755 index 0000000..c939d13 --- /dev/null +++ b/scripts/setup-agent-environment.sh @@ -0,0 +1,242 @@ +#!/bin/bash +# Agent Environment Setup Script +# Configures environment for optimal multi-agent collaboration +# Supports: Claude Code, GitHub Copilot, CodeRabbit, ChatGPT Codex + +set -e + +# Colors +GREEN='\033[0;32m' +BLUE='\033[0;34m' +YELLOW='\033[1;33m' +RED='\033[0;31m' +NC='\033[0m' + +print_header() { + echo "" + echo -e "${BLUE}========================================${NC}" + echo -e "${BLUE}$1${NC}" + echo -e "${BLUE}========================================${NC}" +} + +print_status() { + echo -e "${BLUE}[SETUP]${NC} $1" +} + +print_success() { + echo -e "${GREEN}[✓]${NC} $1" +} + +print_warning() { + echo -e "${YELLOW}[!]${NC} $1" +} + +print_error() { + echo -e "${RED}[✗]${NC} $1" +} + +print_header "Multi-Agent Environment Setup" + +# Check current directory +if [ ! -f "package.json" ]; then + print_error "Not in project root directory. Please run from repository root." + exit 1 +fi + +print_status "Current directory: $(pwd)" + +# 1. Verify required tools +print_header "Verifying Required Tools" + +check_tool() { + if command -v $1 &> /dev/null; then + VERSION=$($1 --version 2>&1 | head -1) + print_success "$1 is available: $VERSION" + return 0 + else + print_warning "$1 is not available" + return 1 + fi +} + +check_tool "node" +check_tool "npm" +check_tool "git" +check_tool "python3" + +# GitHub CLI is critical for multi-agent collaboration +if check_tool "gh"; then + GH_AVAILABLE=true +else + GH_AVAILABLE=false + print_warning "GitHub CLI (gh) not found - some agent features will be limited" + echo " Install: https://cli.github.com/" +fi + +check_tool "docker" || print_warning "Docker not available - Docker CI workflows will not work locally" +check_tool "curl" +check_tool "jq" || print_warning "jq not available - JSON parsing will be limited" + +# 2. Configure Git for PR Access +print_header "Configuring Git for PR Access" + +print_status "Adding PR fetch configuration..." +git config --local --get-all remote.origin.fetch | grep -q "refs/pull" || { + git config --add remote.origin.fetch '+refs/pull/*/head:refs/remotes/origin/pr/*' + print_success "Added PR head refs to fetch config" +} + +git config --local --get-all remote.origin.fetch | grep -q "refs/pull/*/merge" || { + git config --add remote.origin.fetch '+refs/pull/*/merge:refs/remotes/origin/pr-merge/*' + print_success "Added PR merge refs to fetch config" +} + +# 3. Set up Git aliases for agent collaboration +print_header "Setting Up Git Aliases" + +print_status "Creating helpful git aliases..." + +git config --local alias.pr-list '!git for-each-ref refs/remotes/origin/pr --format="%(refname:short) %(upstream:track)"' 2>/dev/null || true +print_success "Added alias: git pr-list" + +git config --local alias.pr-checkout '!f() { git fetch origin pull/$1/head:pr-$1 && git checkout pr-$1; }; f' 2>/dev/null || true +print_success "Added alias: git pr-checkout " + +git config --local alias.pr-diff '!f() { git diff ${2:-master}...origin/pr/$1; }; f' 2>/dev/null || true +print_success "Added alias: git pr-diff [base]" + +# 4. Verify npm configuration +print_header "Verifying npm Configuration" + +NPM_VERSION=$(npm --version) +print_status "npm version: $NPM_VERSION" + +REQUIRED_NPM_VERSION="11.0.0" +if [ "$(printf '%s\n' "$REQUIRED_NPM_VERSION" "$NPM_VERSION" | sort -V | head -n1)" = "$REQUIRED_NPM_VERSION" ]; then + print_success "npm version is sufficient (>= 11.0.0)" +else + print_warning "npm version should be >= 11.0.0 for proper patch application" + print_status "Update with: npm install -g npm@latest" +fi + +# 5. Create environment file if it doesn't exist +print_header "Environment Variables" + +if [ ! -f ".env.local" ]; then + print_status "Creating .env.local from template..." + cat > .env.local << 'EOF' +# Local environment variables for development +# DO NOT commit this file to version control + +# Multi-agent collaboration +MULTI_AGENT_MODE=true +AGENT_NAME= + +# GitHub configuration (if needed) +# GITHUB_TOKEN= + +# Development settings +NODE_ENV=development +VITE_APP_TITLE=Bleedy + +# Add your local environment variables below +EOF + print_success "Created .env.local" + print_warning "Configure .env.local with your settings" +else + print_success ".env.local already exists" +fi + +# 6. Verify husky setup +print_header "Husky Pre-commit Hooks" + +if [ -d ".husky" ]; then + print_success "Husky directory exists" +else + print_warning "Husky not initialized" + print_status "Initialize with: npx husky init" +fi + +# 7. Test GitHub CLI if available +if [ "$GH_AVAILABLE" = true ]; then + print_header "GitHub CLI Configuration" + + if gh auth status &> /dev/null; then + print_success "GitHub CLI is authenticated" + + # Test PR access + print_status "Testing PR access..." + if gh pr list --limit 1 &> /dev/null; then + print_success "Can access PRs via GitHub CLI" + else + print_warning "Cannot access PRs - check repository permissions" + fi + else + print_warning "GitHub CLI not authenticated" + print_status "Authenticate with: gh auth login" + fi +fi + +# 8. Create agent collaboration shortcuts +print_header "Creating Agent Shortcuts" + +# Create a simple script to get PR reviews +if [ "$GH_AVAILABLE" = true ]; then + cat > /tmp/test-pr-access.sh << 'EOF' +#!/bin/bash +# Quick test of PR access +gh pr list --limit 5 --json number,title,author,state +EOF + chmod +x /tmp/test-pr-access.sh + print_success "Test script created: /tmp/test-pr-access.sh" +fi + +# 9. Summary and next steps +print_header "Setup Summary" + +echo "" +echo "Environment Status:" +echo " ✓ Project structure verified" +echo " ✓ Git configured for PR access" +if [ "$GH_AVAILABLE" = true ]; then + echo " ✓ GitHub CLI available" +else + echo " ! GitHub CLI not available (install recommended)" +fi +echo " ✓ Git aliases created" +echo " ✓ Environment template created" +echo "" + +print_header "Next Steps for Multi-Agent Collaboration" + +echo "" +echo "1. If GitHub CLI is not authenticated:" +echo " $ gh auth login" +echo "" +echo "2. Fetch PR references:" +echo " $ git fetch origin" +echo "" +echo "3. List available PRs:" +echo " $ gh pr list" +echo " $ git pr-list (using alias)" +echo "" +echo "4. Access a specific PR:" +echo " $ python3 scripts/get_pr_reviews.py " +echo " $ gh pr view " +echo "" +echo "5. Configure your agent-specific settings:" +echo " - Claude Code: .claude/project-instructions.md" +echo " - Copilot: .github/copilot-instructions.md" +echo " - See: .github/AGENT_COLLABORATION.md" +echo "" + +print_header "Setup Complete" + +echo "" +echo -e "${GREEN}Multi-agent environment is ready!${NC}" +echo "" +echo "Documentation:" +echo " - Agent collaboration: .github/AGENT_COLLABORATION.md" +echo " - PR review access: .github/ACCESSING_PR_REVIEWS.md" +echo " - DevOps guide: DEVCONTAINER_AND_AUTOMATION.md" +echo ""