diff --git a/.agent-os/specs/2025-10-13-merge-command-#100/README.md b/.agent-os/specs/2025-10-13-merge-command-#100/README.md new file mode 100644 index 00000000..4d0c792b --- /dev/null +++ b/.agent-os/specs/2025-10-13-merge-command-#100/README.md @@ -0,0 +1,193 @@ +# Merge Command Specification + +> **Created:** 2025-10-13 +> **Issue:** #100 +> **Status:** Ready for Implementation +> **Size Estimate:** XL (32-46 hours) + +## Quick Links + +- **GitHub Issue:** https://github.com/carmandale/agent-os/issues/100 +- **Spec Overview:** [spec.md](./spec.md) +- **Technical Details:** [technical-spec.md](./technical-spec.md) +- **Test Requirements:** [tests.md](./tests.md) +- **Implementation Tasks:** [tasks.md](./tasks.md) + +## Overview + +This specification defines an intelligent `/merge` command for Agent OS that automates the complete PR merge workflow with safety checks, code review integration, and automatic worktree cleanup. + +### Key Features + +- **Context-aware PR inference** from conversation, branch, or explicit argument +- **Pre-merge validation** (CI status, reviews, conflicts, branch protection) +- **Review feedback integration** with CodeRabbit/Codex +- **Safe merge execution** via GitHub CLI +- **Automatic worktree cleanup** after successful merge + +### User Value + +Reduces PR merge workflow from **5-10 minutes** to **<1 minute** while eliminating premature merges through comprehensive validation checks. + +## Problem Being Solved + +Current workflow requires manual steps across multiple tools: +1. Checking PR status on GitHub web UI +2. Reviewing code review feedback (CodeRabbit/Codex) +3. Addressing review comments +4. Verifying CI status +5. Manual merge execution +6. Worktree cleanup and branch deletion + +The `/merge` command automates all these steps with safety checks and user confirmations. + +## Implementation Approach + +### 4-Phase Plan + +1. **Phase 1:** Core Merge Automation (MVP) - 6-8 hours + - PR inference, validation, basic merge, main branch update + +2. **Phase 2:** Review Feedback Integration - 4-6 hours + - CodeRabbit/Codex comment detection and user interaction + +3. **Phase 3:** Worktree Management - 3-4 hours + - Automatic worktree detection and cleanup after merge + +4. **Phase 4:** Advanced Features & Polish - 4-6 hours + - Flags (--dry-run, --force, --auto), error handling, documentation + +### TDD Approach + +All implementation follows Test-Driven Development: +1. Write test (red) +2. Implement feature (green) +3. Verify test passes (green) + +## Files in This Spec + +### Core Documents + +- **spec.md** - High-level specification with problem statement, solution, and success metrics +- **technical-spec.md** - Detailed architecture, components, data flow, and implementation details +- **tests.md** - Comprehensive test requirements (unit, integration, edge cases, manual scenarios) +- **tasks.md** - 50 implementation tasks organized by phase with time estimates + +### Supporting Files + +- **README.md** (this file) - Spec overview and navigation guide + +## Getting Started with Implementation + +### Prerequisites + +1. Read all spec documents in order: spec.md → technical-spec.md → tests.md → tasks.md +2. Understand existing Agent OS patterns: + - `commands/workflow-status.md` - Command structure + - `scripts/workflow-complete.sh` - Workflow automation patterns + - `scripts/workflow-status.sh` - Worktree detection patterns +3. Review research documents: + - `docs/research/pr-merge-automation-best-practices.md` + - `docs/research/gh-cli-worktree-claude-commands.md` + +### Recommended Implementation Order + +1. **Setup** (Tasks 1.1-1.3) + - Create command file, script skeleton, installer integration + +2. **Phase 1: MVP** (Tasks 1.4-1.14) + - Implement core merge workflow with safety checks + +3. **Test & Validate Phase 1** + - Ensure MVP works reliably before adding complexity + +4. **Phase 2: Review Integration** (Tasks 2.1-2.6) + - Add CodeRabbit/Codex feedback handling + +5. **Phase 3: Worktree Management** (Tasks 3.1-3.6) + - Add automatic worktree cleanup + +6. **Phase 4: Polish** (Tasks 4.1-4.13) + - Add flags, error handling, documentation + +7. **Final Integration** (Tasks 5.1-5.4) + - PR creation, roadmap update, deployment + +### Key Design Principles + +- **Safety First:** Multiple validation checks prevent premature merges +- **User Control:** Confirmation prompts before destructive operations +- **Graceful Degradation:** Handle errors with clear messages and recovery suggestions +- **Portable:** Works on macOS and Linux with standard tools (bash, gh, git) +- **Consistent:** Follows Agent OS conventions and patterns + +## Testing Requirements + +### Test Coverage Goals + +- Unit Tests: 90%+ code coverage +- Integration Tests: All critical paths +- Edge Cases: All identified scenarios +- Manual Tests: All user-facing workflows + +### Key Test Files + +- `tests/unit/test-pr-inference.bats` - PR number inference logic +- `tests/unit/test-validation.bats` - Pre-merge validation checks +- `tests/unit/test-review-feedback.bats` - Review comment detection +- `tests/unit/test-merge-execution.bats` - Merge operation +- `tests/unit/test-worktree-cleanup.bats` - Worktree cleanup +- `tests/integration/test-merge-workflow.bats` - End-to-end workflows +- `tests/edge-cases/test-merge-edge-cases.bats` - Edge case handling + +## Dependencies + +### Required Tools + +- `gh` (GitHub CLI) v2.0+ +- `git` v2.17+ (for `git worktree remove`) +- `jq` for JSON parsing +- `bash` 4.0+ for associative arrays +- `bats` (Bash Automated Testing System) + +### Integration Points + +- GitHub API via `gh` CLI +- CodeRabbit review system (optional) +- Codex review system (optional) +- Agent OS worktree management +- Claude Code command system + +## Success Metrics + +### Quantitative + +- Time savings: 5-10 minutes → <1 minute per merge +- Error reduction: 100% prevention of premature merges +- Adoption: 80%+ of Agent OS users within 1 month +- Worktree cleanup: Eliminate orphaned worktrees + +### Qualitative + +- Users report merge process feels "seamless" +- Reduced anxiety about merge safety +- Positive feedback on review integration +- Perceived as "Agent OS magic" + +## Related Work + +- **Issue #37:** Claude Code hooks implementation (workflow enforcement) +- **Issue #97:** Worktree listing feature (worktree management) +- **Issue #98:** Stop-hook context enhancement (context awareness) + +## Questions or Issues? + +- Open discussion in GitHub issue #100 +- Refer to technical-spec.md for architecture details +- Check tests.md for test scenarios and acceptance criteria +- Review tasks.md for implementation task breakdown + +--- + +**Status:** Ready for Implementation +**Next Step:** Begin Phase 1 implementation (Tasks 1.1-1.3: Setup) diff --git a/.agent-os/specs/2025-10-13-merge-command-#100/context.md b/.agent-os/specs/2025-10-13-merge-command-#100/context.md new file mode 100644 index 00000000..7a9d61c4 --- /dev/null +++ b/.agent-os/specs/2025-10-13-merge-command-#100/context.md @@ -0,0 +1,528 @@ +# Implementation Context: Merge Command + +> **Spec:** 2025-10-13-merge-command-#100 +> **Purpose:** Reference guide for implementation + +## Agent OS Patterns to Follow + +### Command Structure Pattern + +**Reference:** `commands/workflow-status.md` + +All Agent OS commands follow this structure: + +```markdown +--- +allowed-tools: Bash(git status:*), Bash(gh pr:*), ... +description: Brief description of what the command does +argument-hint: [--flag1|--flag2] +--- + +## Context + +Provide relevant context information using !` ` for command execution: +- Current status: !`command to get status` +- Relevant data: !`another command` + +## Task + +Execute the main script with captured arguments: +!`~/.agent-os/scripts/workflow-merge.sh $ARGUMENTS` +``` + +**For /merge command:** +- allowed-tools: Must include git operations, gh CLI, worktree commands +- description: "Intelligently merge pull requests with safety checks and worktree cleanup" +- argument-hint: "[--dry-run|--force|--auto] [pr_number]" + +### Script Structure Pattern + +**Reference:** `scripts/workflow-complete.sh:1-100` + +Agent OS scripts follow this structure: + +```bash +#!/usr/bin/env bash +# Script name and purpose +# Usage: script-name [options] + +set -euo pipefail # Exit on error, undefined vars, pipe failures + +# Color codes for output +readonly RED='\033[0;31m' +readonly GREEN='\033[0;32m' +readonly YELLOW='\033[1;33m' +readonly BLUE='\033[0;34m' +readonly NC='\033[0m' # No Color + +# Global variables +DRY_RUN=false +FORCE=false + +# Helper functions +print_error() { + echo -e "${RED}❌ $1${NC}" >&2 +} + +print_success() { + echo -e "${GREEN}✅ $1${NC}" +} + +# Main functions +main() { + parse_arguments "$@" + # Main logic here +} + +parse_arguments() { + while [[ $# -gt 0 ]]; do + case $1 in + --dry-run) DRY_RUN=true; shift ;; + --force) FORCE=true; shift ;; + *) PR_NUMBER="$1"; shift ;; + esac + done +} + +# Entry point +main "$@" +``` + +### Installation Pattern + +**Reference:** `setup-claude-code.sh:65-77` + +Commands are installed via curl during setup: + +```bash +for cmd in plan-product create-spec execute-tasks workflow-status workflow-complete workflow-merge; do + if [ -f "$HOME/.claude/commands/${cmd}.md" ] && [ "$OVERWRITE_COMMANDS" = false ]; then + echo " ⚠️ ~/.claude/commands/${cmd}.md already exists - skipping" + else + curl -s -o "$HOME/.claude/commands/${cmd}.md" \ + "https://raw.githubusercontent.com/carmandale/agent-os/main/commands/${cmd}.md" + echo " ✅ Installed ${cmd}" + fi +done +``` + +**Action Required:** Add `workflow-merge` to this list in Task 1.3 + +## Existing Code to Leverage + +### Worktree Detection + +**Reference:** `scripts/workflow-status.sh:282-365` + +```bash +check_worktrees() { + # Get all worktrees in porcelain format + local worktrees=$(git worktree list --porcelain 2>/dev/null || echo "") + + if [[ -z "$worktrees" ]]; then + echo "No worktrees found" + return 1 + fi + + # Parse worktree info + while IFS= read -r line; do + case "$line" in + worktree*) + worktree_path="${line#worktree }" + ;; + branch*) + branch_name="${line#branch refs/heads/}" + ;; + esac + done <<< "$worktrees" +} +``` + +**Use in Task 3.1:** Adapt this pattern for `detect_worktree()` function + +### GitHub Issue Extraction from Branch + +**Reference:** `scripts/workflow-status.sh:367-389` + +```bash +detect_issue_number() { + local branch="$1" + local issue_number="" + + # Pattern 1: issue-123 + if [[ $branch =~ issue-([0-9]+) ]]; then + issue_number="${BASH_REMATCH[1]}" + # Pattern 2: 123-feature-name + elif [[ $branch =~ ^([0-9]+)- ]]; then + issue_number="${BASH_REMATCH[1]}" + # Pattern 3: feature-#123-description or bugfix-456-fix + elif [[ $branch =~ (feature|bugfix|hotfix)-\#?([0-9]+) ]]; then + issue_number="${BASH_REMATCH[2]}" + fi + + echo "$issue_number" +} +``` + +**Use in Task 1.5:** Integrate into PR inference logic + +### Git Workflow Patterns + +**Reference:** `workflow-modules/step-4-git-integration.md:134-198` + +Standard git operations used in Agent OS: + +```bash +# Branch management +git checkout -b "feature/name-#123" +git branch --show-current +git fetch origin +git pull origin main + +# Worktree operations +git worktree add ".worktrees/name-#123" "feature/name-#123" +git worktree list --porcelain +git worktree remove ".worktrees/name-#123" +git worktree prune + +# Merge verification +git log --oneline -1 --grep="Merge pull request" +git merge --ff-only origin/main +``` + +**Use throughout:** Standard git operations for all phases + +### Workflow Completion Pattern + +**Reference:** `scripts/workflow-complete.sh:428-555` + +The workflow-complete.sh script provides excellent patterns for: + +1. **Phased Execution:** +```bash +echo "🎯 Phase 1: Pre-flight Checks" +run_phase_1_checks + +echo "📝 Phase 2: Documentation Verification" +run_phase_2_docs + +# ... etc +``` + +2. **Validation with Error Collection:** +```bash +local errors=() + +if ! check_condition_1; then + errors+=("Condition 1 failed") +fi + +if ! check_condition_2; then + errors+=("Condition 2 failed") +fi + +if [[ ${#errors[@]} -gt 0 ]]; then + print_error "Validation failed:" + printf ' • %s\n' "${errors[@]}" + return 1 +fi +``` + +3. **Dry Run Mode:** +```bash +if [[ "$DRY_RUN" == "true" ]]; then + echo "[DRY RUN] Would execute: $command" + return 0 +fi + +# Actually execute +eval "$command" +``` + +**Use in Tasks 1.9, 4.1:** Adopt these patterns + +## GitHub CLI Commands Reference + +### PR Information Queries + +```bash +# Get PR details +gh pr view "$pr_number" --json \ + title,number,state,author,reviewDecision,mergeable,mergeStateStatus,mergeCommit + +# Check CI status +gh pr checks "$pr_number" --json name,state,conclusion + +# List PRs for current branch +gh pr list --head "$(git branch --show-current)" --json number,title + +# Get PR comments +gh api "repos/$OWNER/$REPO/pulls/$pr_number/comments" \ + --jq '.[] | select(.user.login == "coderabbitai")' +``` + +### PR Merge Operations + +```bash +# Merge with default strategy +gh pr merge "$pr_number" --merge --delete-branch + +# Squash merge +gh pr merge "$pr_number" --squash --delete-branch + +# Rebase merge +gh pr merge "$pr_number" --rebase --delete-branch + +# Enable auto-merge (doesn't merge immediately) +gh pr merge "$pr_number" --auto --merge +``` + +### Repository Information + +```bash +# Get current repo +gh repo view --json nameWithOwner --jq '.nameWithOwner' + +# Check authentication +gh auth status +``` + +## Testing Infrastructure + +### BATS Test Structure + +**Reference:** Existing Agent OS tests use this pattern: + +```bash +#!/usr/bin/env bats + +load test_helper # Common test utilities + +setup() { + # Run before each test + export TEST_TEMP_DIR=$(mktemp -d) + cd "$TEST_TEMP_DIR" +} + +teardown() { + # Run after each test + rm -rf "$TEST_TEMP_DIR" +} + +@test "descriptive test name" { + # Arrange + setup_test_conditions + + # Act + run function_under_test "argument" + + # Assert + assert_success + assert_output "expected output" +} +``` + +### Mock Functions for Testing + +```bash +# Mock gh command +mock_gh_command() { + gh() { + case "$1 $2" in + "pr view") + echo '{"number":123,"title":"Test PR","mergeable":"MERGEABLE"}' + ;; + "pr checks") + echo '[{"name":"CI","state":"SUCCESS"}]' + ;; + esac + } + export -f gh +} +``` + +**Use in all test tasks:** Follow this mocking pattern + +## Code Style Conventions + +### From Agent OS Standards + +**Reference:** `~/.agent-os/standards/code-style.md` + +1. **Naming Conventions:** + - Functions: `snake_case` + - Constants: `UPPER_SNAKE_CASE` + - Local variables: `snake_case` + +2. **Indentation:** + - Use tabs (not spaces) + - Configure editor to show tabs as 4 spaces + +3. **Comments:** + - Add brief comments above non-obvious logic + - Document the "why" not the "what" + - Keep comments concise + +4. **Error Handling:** + - Always check return codes + - Provide helpful error messages + - Suggest recovery actions + +## Security Considerations + +### Authentication + +- Never store credentials +- Rely on `gh auth status` for GitHub authentication +- Use existing GitHub CLI session + +### Validation + +- Always validate user input +- Check PR exists before operations +- Verify permissions via branch protection + +### Destructive Operations + +- Require user confirmation +- Display what will be affected +- Provide `--dry-run` option +- Implement `--force` with warnings + +## Performance Targets + +**From technical-spec.md:** + +- PR inference: <1 second +- Pre-merge validation: 2-3 seconds +- Review feedback analysis: 1-2 seconds +- Merge execution: 2-5 seconds +- Worktree cleanup: 3-5 seconds +- **Total workflow: 10-20 seconds** + +### Optimization Strategies + +1. Parallel GitHub API calls where possible +2. Cache PR data (30-second TTL) +3. Use `--cached` flags when available +4. Minimize unnecessary git operations + +## Error Handling Patterns + +### Error Categories and Responses + +1. **User Input Errors:** + - Clear error message + - Suggest correction + - Exit with code 1 + +2. **Validation Failures:** + - Display specific issues + - Suggest fixes + - Exit with code 2 + +3. **API/Network Errors:** + - Report error + - Provide manual fallback + - Exit with code 3 + +4. **Git Operation Failures:** + - Explain what failed + - Provide recovery steps + - Exit with code 4 + +### Example Error Messages + +```bash +# Good: Specific, actionable +echo "❌ PR #123 has failing checks: 'tests/unit'" +echo " Fix the failing tests and re-run /merge" +echo " Or use --force to merge anyway (not recommended)" + +# Bad: Vague, unhelpful +echo "Error: Validation failed" +``` + +## Integration Points + +### Claude Code Command System + +Commands are invoked via `/command-name` in Claude Code. The command markdown file: +1. Displays context information to Claude +2. Executes the bash script +3. Returns output to Claude for processing + +### Agent OS Workflow + +The merge command integrates into the Agent OS workflow: +1. User completes work in worktree +2. Creates PR via `/workflow-complete` or manually +3. Receives review feedback +4. Uses `/merge` to merge and cleanup + +### CodeRabbit/Codex Integration + +Review bots comment on PRs. The merge command: +1. Detects bot comments via GitHub API +2. Displays comments to user +3. Allows user to address before merging +4. Re-validates after changes + +## References + +### Internal Documentation + +- **Agent OS Mission:** `.agent-os/product/mission.md` +- **Development Best Practices:** `~/.agent-os/standards/best-practices.md` +- **Git Workflow Module:** `workflow-modules/step-4-git-integration.md` +- **Command Reference:** All files in `commands/` directory +- **Script Library:** All files in `scripts/` directory + +### External Documentation + +- **GitHub CLI Manual:** https://cli.github.com/manual/ +- **Git Worktree Docs:** https://git-scm.com/docs/git-worktree +- **BATS Testing:** https://github.com/bats-core/bats-core +- **Bash Best Practices:** https://google.github.io/styleguide/shellguide.html + +### Research Documents + +- **PR Merge Best Practices:** `docs/research/pr-merge-automation-best-practices.md` +- **GitHub CLI Patterns:** `docs/research/gh-cli-worktree-claude-commands.md` + +## Implementation Checklist + +Before starting implementation, ensure: + +- [ ] Read all spec documents (spec.md, technical-spec.md, tests.md, tasks.md) +- [ ] Review referenced Agent OS code sections +- [ ] Understand existing command and script patterns +- [ ] Have required tools installed (gh, git, jq, bats) +- [ ] GitHub CLI authenticated (`gh auth status`) +- [ ] Test repository available for development +- [ ] Worktree for spec created (`.worktrees/merge-command-#100`) + +## Quick Reference Commands + +```bash +# Create development worktree +git worktree add .worktrees/merge-command-#100 feature/merge-command-#100 + +# Run tests +bats tests/test-workflow-merge.bats + +# Install command locally (after implementation) +cp commands/workflow-merge.md ~/.claude/commands/ +cp scripts/workflow-merge.sh ~/.agent-os/scripts/ +chmod +x ~/.agent-os/scripts/workflow-merge.sh + +# Test command +/merge --dry-run 123 + +# Check command output +/merge --help +``` + +--- + +This context document should be referenced throughout implementation to ensure consistency with Agent OS patterns and conventions. diff --git a/.agent-os/specs/2025-10-13-merge-command-#100/spec.md b/.agent-os/specs/2025-10-13-merge-command-#100/spec.md new file mode 100644 index 00000000..7ca789e2 --- /dev/null +++ b/.agent-os/specs/2025-10-13-merge-command-#100/spec.md @@ -0,0 +1,148 @@ +# Merge Command Specification + +> **Issue:** #100 +> **Created:** 2025-10-13 +> **Status:** Planning +> **Size Estimate:** XL (32-46 hours) + +## Overview + +Create an intelligent `/merge` command for Agent OS that automates the complete PR merge workflow with safety checks, code review integration, and automatic worktree cleanup. The command should infer PR context from conversation, validate readiness for merge, address any review feedback, and clean up after successful integration. + +## Problem Statement + +### Current Workflow Pain Points + +1. **Manual PR merge requires multiple manual steps:** + - Checking PR status on GitHub + - Reviewing CodeRabbit/Codex feedback + - Addressing review comments + - Verifying CI status + - Manual merge execution + - Worktree cleanup + - Branch deletion + +2. **Context switching between tools:** + - AI conversation → GitHub web UI → Terminal → Back to AI + - Lost context when reviewing feedback + - Manual copy-paste of PR numbers + +3. **Risk of premature merges:** + - No systematic pre-merge validation + - Easy to miss failing CI checks + - Potential to merge with unresolved review comments + +4. **Worktree management overhead:** + - Orphaned worktrees after manual merges + - Manual cleanup commands + - Risk of deleting wrong worktree + +### User Story + +> "As a developer using Agent OS, when I've completed work on a feature branch in a worktree, I want to type `/merge` and have the system intelligently merge my PR after validating it's ready, addressing any review feedback, and cleaning up the worktree automatically." + +## Proposed Solution + +Create a `/merge` command that provides intelligent, context-aware PR merge automation with comprehensive safety checks and optional review feedback resolution. + +### Command Syntax + +```bash +/merge [pr_number] # Merge specific PR +/merge # Infer PR from current branch/context +/merge --dry-run # Show what would happen without executing +/merge --force # Skip some validation checks (with warnings) +/merge --auto # Enable GitHub auto-merge when checks pass +``` + +### High-Level Workflow + +1. **PR Inference** - Infer PR from argument, branch name, or conversation context +2. **User Confirmation** - Display "Merge PR #XX?" for user approval +3. **Pre-Merge Validation** - Check CI status, reviews, conflicts, branch protection +4. **Review Feedback** - Detect and address CodeRabbit/Codex comments if present +5. **Merge Execution** - Execute merge via `gh pr merge` when green +6. **Worktree Cleanup** - If in worktree: return to main, verify merge, delete worktree + +### Key Features + +- **Context-aware PR inference** from conversation, branch, or explicit argument +- **User confirmation** before destructive operations +- **Comprehensive safety checks** (CI, reviews, conflicts) +- **Review feedback integration** with CodeRabbit/Codex +- **Automatic worktree cleanup** with verification +- **Graceful error handling** with recovery suggestions + +## Success Metrics + +### Quantitative +- **Time Savings:** Reduce merge workflow from 5-10 minutes to <1 minute +- **Error Reduction:** Decrease premature merges by 100% (validation prevents) +- **Adoption:** 80%+ of Agent OS users use `/merge` within 1 month +- **Worktree Cleanup:** Eliminate orphaned worktrees (currently a common issue) + +### Qualitative +- Users report merge process feels "seamless" +- Reduced anxiety about merge safety +- Positive feedback on review feedback integration +- Perceived as "Agent OS magic" + +## Implementation Phases + +### Phase 1: Core Merge Automation (MVP) +**Goal:** Basic merge with safety checks +**Acceptance Criteria:** +- `/merge` infers PR from current branch +- User receives confirmation prompt before merge +- Validates PR is mergeable and checks pass +- Executes merge with `gh pr merge` +- Updates local main branch after merge + +### Phase 2: Review Feedback Integration +**Goal:** Address review comments before merge +**Acceptance Criteria:** +- Detects unresolved review comments +- Displays critical issues requiring action +- Allows user to address issues before proceeding +- Re-checks review status after fixes + +### Phase 3: Worktree Management +**Goal:** Automatic cleanup after successful merge +**Acceptance Criteria:** +- Detects when running in a worktree +- Returns to main repository after merge +- Safely removes worktree after verification +- Updates main branch with latest changes + +### Phase 4: Advanced Features & Polish +**Goal:** Production-ready with full safety and UX +**Acceptance Criteria:** +- `--dry-run` shows actions without execution +- `--auto` enables GitHub auto-merge feature +- Clear error messages with recovery suggestions +- Beautiful terminal output with colors/icons + +## References + +### Internal References +- **Command patterns:** `commands/workflow-status.md` +- **Script patterns:** `scripts/workflow-complete.sh:428` +- **Git workflow:** `workflow-modules/step-4-git-integration.md:134` +- **Worktree detection:** `scripts/workflow-status.sh:282-365` +- **Installation pattern:** `setup-claude-code.sh:65-77` + +### External References +- **GitHub CLI merge:** https://cli.github.com/manual/gh_pr_merge +- **GitHub CLI checks:** https://cli.github.com/manual/gh_pr_checks +- **GitHub CLI PR view:** https://cli.github.com/manual/gh_pr_view +- **Git worktree:** https://git-scm.com/docs/git-worktree +- **Branch protection:** https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches + +### Research Documents +- **PR merge best practices:** `docs/research/pr-merge-automation-best-practices.md` +- **GitHub CLI patterns:** `docs/research/gh-cli-worktree-claude-commands.md` + +### Related Work +- **Workflow completion:** #37 (Claude Code hooks implementation) +- **Worktree tracking:** #97 (Worktree listing feature) +- **Context awareness:** #98 (Stop-hook context enhancement) diff --git a/.agent-os/specs/2025-10-13-merge-command-#100/tasks.md b/.agent-os/specs/2025-10-13-merge-command-#100/tasks.md new file mode 100644 index 00000000..942cd71c --- /dev/null +++ b/.agent-os/specs/2025-10-13-merge-command-#100/tasks.md @@ -0,0 +1,506 @@ +# Implementation Tasks: Merge Command + +> **Spec:** 2025-10-13-merge-command-#100 +> **Last Updated:** 2025-10-13 +> **Status:** Ready for Implementation + +## Task Organization + +Tasks are organized into 4 phases matching the spec's implementation phases. Each task follows TDD: write tests first, implement feature, verify tests pass. + +**Size Legend:** +- `XS` < 1 hour +- `S` 1-2 hours +- `M` 2-4 hours +- `L` 4-8 hours +- `XL` > 8 hours + +--- + +## Phase 1: Core Merge Automation (MVP) + +**Goal:** Basic merge with safety checks +**Estimated Time:** 6-8 hours + +### Setup and Infrastructure + +- [ ] **Task 1.1:** Create command file `commands/workflow-merge.md` `S` + - [ ] Write YAML frontmatter with allowed tools + - [ ] Add description and argument hints + - [ ] Define context section with git/PR status + - [ ] Add task section calling workflow-merge.sh script + - **Tests:** None (markdown definition) + - **Acceptance:** Command file follows Agent OS patterns from workflow-status.md + +- [ ] **Task 1.2:** Create main script `scripts/workflow-merge.sh` `M` + - [ ] Create file with proper shebang and permissions + - [ ] Add script header comments + - [ ] Define global variables and constants + - [ ] Add color codes for terminal output + - [ ] Create main() function skeleton + - **Tests:** Script passes `bash -n` syntax check + - **Acceptance:** Script structure matches workflow-complete.sh:1-50 + +- [ ] **Task 1.3:** Add merge command to installer `setup-claude-code.sh` `XS` + - [ ] Add `workflow-merge` to command installation loop + - [ ] Add curl command to fetch from GitHub + - [ ] Handle existing file with --overwrite flag + - **Tests:** Installation script runs without errors + - **Acceptance:** Command installs to ~/.claude/commands/ during setup + +### PR Inference Engine + +- [ ] **Task 1.4:** Write PR inference tests `M` + - [ ] Write test: infer from explicit argument + - [ ] Write test: infer from current branch + - [ ] Write test: infer from issue pattern in branch + - [ ] Write test: fail gracefully when cannot infer + - [ ] Write test: explicit argument takes priority + - **File:** `tests/unit/test-pr-inference.bats` + - **Acceptance:** All 5 tests defined and failing (red) + +- [ ] **Task 1.5:** Implement PR inference function `M` + - [ ] Create `infer_pr_number()` function + - [ ] Implement explicit argument handling + - [ ] Add current branch check via `gh pr list --head` + - [ ] Add issue extraction from branch name (regex patterns) + - [ ] Add error message for inference failure + - **Tests:** Run tests/unit/test-pr-inference.bats + - **Acceptance:** All PR inference tests pass (green) + +### User Confirmation + +- [ ] **Task 1.6:** Write confirmation prompt tests `S` + - [ ] Write test: displays PR number and title + - [ ] Write test: shows PR metadata (author, status) + - [ ] Write test: accepts Y/yes confirmation + - [ ] Write test: rejects N/no confirmation + - **File:** `tests/unit/test-confirmation.bats` + - **Acceptance:** All 4 tests defined and failing + +- [ ] **Task 1.7:** Implement confirmation prompt `S` + - [ ] Create `confirm_merge()` function + - [ ] Fetch PR details via `gh pr view --json` + - [ ] Display formatted PR information + - [ ] Implement user input handling (Y/n) + - [ ] Return appropriate exit codes + - **Tests:** Run tests/unit/test-confirmation.bats + - **Acceptance:** All confirmation tests pass + +### Pre-Merge Validation + +- [ ] **Task 1.8:** Write validation tests `L` + - [ ] Write test: validation passes with approved PR + - [ ] Write test: fails with failing CI + - [ ] Write test: fails with merge conflicts + - [ ] Write test: fails with missing approval + - [ ] Write test: fails with blocked branch protection + - [ ] Create mock functions for gh commands + - **File:** `tests/unit/test-validation.bats` + - **Acceptance:** All 5 validation tests defined and failing + +- [ ] **Task 1.9:** Implement validation function `L` + - [ ] Create `validate_merge_readiness()` function + - [ ] Check review status via `gh pr view --json reviewDecision` + - [ ] Check merge conflicts via `gh pr view --json mergeable` + - [ ] Check CI status via `gh pr checks` + - [ ] Check branch protection via `gh pr view --json mergeStateStatus` + - [ ] Collect and display all validation errors + - **Tests:** Run tests/unit/test-validation.bats + - **Acceptance:** All validation tests pass + +### Merge Execution + +- [ ] **Task 1.10:** Write merge execution tests `M` + - [ ] Write test: successful merge with default strategy + - [ ] Write test: merge with squash strategy + - [ ] Write test: merge with rebase strategy + - [ ] Write test: merge failure handling + - [ ] Write test: verify merge commit after merge + - **File:** `tests/unit/test-merge-execution.bats` + - **Acceptance:** All 5 tests defined and failing + +- [ ] **Task 1.11:** Implement merge execution `M` + - [ ] Create `execute_merge()` function + - [ ] Support merge strategies (merge/squash/rebase) + - [ ] Execute `gh pr merge --delete-branch` + - [ ] Verify merge commit via `gh pr view --json mergeCommit` + - [ ] Handle merge failures with clear errors + - **Tests:** Run tests/unit/test-merge-execution.bats + - **Acceptance:** All merge execution tests pass + +### Main Workflow Integration + +- [ ] **Task 1.12:** Write integration tests for Phase 1 `M` + - [ ] Write test: complete workflow (infer → validate → merge) + - [ ] Write test: workflow blocks on failing CI + - [ ] Write test: explicit PR number works + - [ ] Write test: handles PR not found + - **File:** `tests/integration/test-merge-workflow-phase1.bats` + - **Acceptance:** All 4 integration tests defined + +- [ ] **Task 1.13:** Implement main workflow for Phase 1 `M` + - [ ] Create `main()` function + - [ ] Parse command-line arguments + - [ ] Call infer_pr_number() + - [ ] Call confirm_merge() + - [ ] Call validate_merge_readiness() + - [ ] Call execute_merge() + - [ ] Update local main branch + - [ ] Display success summary + - **Tests:** Run tests/integration/test-merge-workflow-phase1.bats + - **Acceptance:** Phase 1 integration tests pass + +### Phase 1 Completion + +- [ ] **Task 1.14:** Manual testing and bug fixes `M` + - [ ] Test happy path on real repository + - [ ] Test error scenarios (failing CI, conflicts) + - [ ] Fix any discovered bugs + - [ ] Update documentation for discovered issues + - **Tests:** Manual test scenarios 1, 2, 4, 5 from tests.md + - **Acceptance:** All Phase 1 manual tests pass + +--- + +## Phase 2: Review Feedback Integration + +**Goal:** Address review comments before merge +**Estimated Time:** 4-6 hours + +### Review Feedback Detection + +- [ ] **Task 2.1:** Write review feedback tests `M` + - [ ] Write test: detect CodeRabbit comments + - [ ] Write test: detect Codex comments + - [ ] Write test: no feedback when no comments + - [ ] Write test: categorize critical vs suggestions + - [ ] Create mock GitHub API responses + - **File:** `tests/unit/test-review-feedback.bats` + - **Acceptance:** All 4 tests defined and failing + +- [ ] **Task 2.2:** Implement review feedback analyzer `M` + - [ ] Create `analyze_review_feedback()` function + - [ ] Fetch PR comments via `gh api repos/.../pulls/.../comments` + - [ ] Filter for CodeRabbit comments (user.login == "coderabbitai") + - [ ] Filter for Codex comments (user.login == "codex-bot") + - [ ] Parse and display comments by file + - [ ] Categorize CRITICAL vs suggestion comments + - **Tests:** Run tests/unit/test-review-feedback.bats + - **Acceptance:** All review feedback tests pass + +### User Interaction for Review Feedback + +- [ ] **Task 2.3:** Write user interaction tests `S` + - [ ] Write test: prompts user to address feedback + - [ ] Write test: accepts Y to address feedback + - [ ] Write test: accepts n to skip feedback + - [ ] Write test: re-validates after addressing + - **File:** `tests/unit/test-review-interaction.bats` + - **Acceptance:** All 4 tests defined and failing + +- [ ] **Task 2.4:** Implement review feedback interaction `S` + - [ ] Add prompt: "Address review feedback before merging? [Y/n]:" + - [ ] Handle user input (Y/n) + - [ ] If Y: return signal to pause merge + - [ ] If n: continue with merge + - [ ] Add loop to re-check after user addresses + - **Tests:** Run tests/unit/test-review-interaction.bats + - **Acceptance:** All interaction tests pass + +### Integration with Main Workflow + +- [ ] **Task 2.5:** Integrate review feedback into workflow `M` + - [ ] Add `analyze_review_feedback()` call after validation + - [ ] Handle return code 2 (feedback needs addressing) + - [ ] Add re-validation loop after feedback addressed + - [ ] Update success path to include feedback check + - **Tests:** Run tests/integration/test-merge-workflow.bats + - **Acceptance:** Workflow handles review feedback correctly + +### Phase 2 Completion + +- [ ] **Task 2.6:** Manual testing with CodeRabbit `S` + - [ ] Test on PR with CodeRabbit comments + - [ ] Verify comments displayed correctly + - [ ] Test addressing feedback workflow + - [ ] Test skipping feedback workflow + - **Tests:** Manual test scenario 3 from tests.md + - **Acceptance:** CodeRabbit integration works end-to-end + +--- + +## Phase 3: Worktree Management + +**Goal:** Automatic cleanup after successful merge +**Estimated Time:** 3-4 hours + +### Worktree Detection + +- [ ] **Task 3.1:** Write worktree detection tests `M` + - [ ] Write test: detect when in worktree + - [ ] Write test: skip when not in worktree + - [ ] Write test: extract worktree path correctly + - [ ] Write test: identify main repository path + - [ ] Create test fixtures with worktrees + - **File:** `tests/unit/test-worktree-detection.bats` + - **Acceptance:** All 4 tests defined and failing + +- [ ] **Task 3.2:** Implement worktree detection `S` + - [ ] Create `detect_worktree()` function + - [ ] Use `git worktree list --porcelain` to check current dir + - [ ] Extract worktree path if in worktree + - [ ] Identify main repository path + - [ ] Return appropriate status codes + - **Tests:** Run tests/unit/test-worktree-detection.bats + - **Acceptance:** All detection tests pass + +### Worktree Cleanup + +- [ ] **Task 3.3:** Write worktree cleanup tests `L` + - [ ] Write test: return to main repository + - [ ] Write test: update main branch + - [ ] Write test: verify merge present locally + - [ ] Write test: remove worktree successfully + - [ ] Write test: prune worktree metadata + - [ ] Write test: fail if uncommitted changes + - **File:** `tests/unit/test-worktree-cleanup.bats` + - **Acceptance:** All 6 tests defined and failing + +- [ ] **Task 3.4:** Implement worktree cleanup `L` + - [ ] Create `cleanup_worktree()` function + - [ ] Change directory to main repository + - [ ] Checkout main branch + - [ ] Fetch and pull from origin + - [ ] Verify merge commit present + - [ ] Check for uncommitted changes in worktree + - [ ] Remove worktree via `git worktree remove` + - [ ] Prune metadata via `git worktree prune` + - **Tests:** Run tests/unit/test-worktree-cleanup.bats + - **Acceptance:** All cleanup tests pass + +### Integration with Main Workflow + +- [ ] **Task 3.5:** Integrate worktree cleanup into workflow `M` + - [ ] Add `detect_worktree()` call after successful merge + - [ ] Call `cleanup_worktree()` if in worktree + - [ ] Skip cleanup if not in worktree (with info message) + - [ ] Handle cleanup failures gracefully + - [ ] Update success summary with cleanup status + - **Tests:** Run tests/integration/test-merge-workflow.bats + - **Acceptance:** Complete workflow includes worktree cleanup + +### Phase 3 Completion + +- [ ] **Task 3.6:** Manual testing with worktrees `M` + - [ ] Test merge from worktree (happy path) + - [ ] Test merge from main repo (skip cleanup) + - [ ] Test cleanup with uncommitted changes + - [ ] Verify worktree fully removed + - **Tests:** Manual test scenarios 1 and 4 from tests.md + - **Acceptance:** Worktree cleanup works reliably + +--- + +## Phase 4: Advanced Features & Polish + +**Goal:** Production-ready with full safety and UX +**Estimated Time:** 4-6 hours + +### Command-Line Flags + +- [ ] **Task 4.1:** Implement --dry-run mode `M` + - [ ] Parse --dry-run flag + - [ ] Add DRY_RUN global variable + - [ ] Wrap all mutating operations with DRY_RUN checks + - [ ] Display "[DRY RUN]" prefix for actions + - [ ] Show what would happen without executing + - **Tests:** tests/integration/test-merge-workflow.bats (dry-run test) + - **Acceptance:** Dry-run shows actions without executing + +- [ ] **Task 4.2:** Implement --force mode `S` + - [ ] Parse --force flag + - [ ] Skip selected validation checks + - [ ] Display warning: "⚠️ WARNING: Forcing merge" + - [ ] Document which checks are skipped + - **Tests:** tests/integration/test-merge-workflow.bats (force test) + - **Acceptance:** Force mode bypasses validation with warning + +- [ ] **Task 4.3:** Implement --auto mode `S` + - [ ] Parse --auto flag + - [ ] Use `gh pr merge --auto` instead of immediate merge + - [ ] Display: "Enabled auto-merge (will merge when checks pass)" + - [ ] Skip worktree cleanup (PR not merged yet) + - **Tests:** Manual test with --auto flag + - **Acceptance:** Auto-merge enabled on GitHub + +- [ ] **Task 4.4:** Implement --strategy flag `XS` + - [ ] Parse --strategy flag (merge/squash/rebase) + - [ ] Set MERGE_STRATEGY variable + - [ ] Display strategy in confirmation prompt + - **Tests:** tests/unit/test-merge-execution.bats (strategy tests exist) + - **Acceptance:** Strategy flag works as expected + +### Error Handling & UX + +- [ ] **Task 4.5:** Comprehensive error handling `M` + - [ ] Add error handling for GitHub API failures + - [ ] Handle network errors gracefully + - [ ] Add recovery suggestions for each error type + - [ ] Implement graceful degradation where possible + - **Tests:** tests/edge-cases/test-merge-edge-cases.bats + - **Acceptance:** All error scenarios handled gracefully + +- [ ] **Task 4.6:** Terminal output polish `S` + - [ ] Add color codes (green=success, red=error, yellow=warning) + - [ ] Add emoji/icons for visual feedback + - [ ] Implement progress indicators for long operations + - [ ] Format output for readability + - **Tests:** Visual inspection during manual testing + - **Acceptance:** Output looks professional and informative + +- [ ] **Task 4.7:** Add help text `XS` + - [ ] Implement --help flag + - [ ] Display usage information + - [ ] Document all flags and options + - [ ] Add examples + - **Tests:** Run `workflow-merge.sh --help` + - **Acceptance:** Help text is clear and comprehensive + +### Documentation + +- [ ] **Task 4.8:** Update CLAUDE.md `S` + - [ ] Document /merge command usage + - [ ] Add examples for common scenarios + - [ ] Document flags and options + - [ ] Add troubleshooting section + - **Tests:** Review documentation for completeness + - **Acceptance:** CLAUDE.md has complete /merge documentation + +- [ ] **Task 4.9:** Inline code comments `M` + - [ ] Add comments explaining PR inference logic + - [ ] Document validation checks + - [ ] Explain worktree cleanup steps + - [ ] Add function headers with descriptions + - **Tests:** Code review for comment quality + - **Acceptance:** All major functions have clear comments + +### Testing + +- [ ] **Task 4.10:** Write edge case tests `L` + - [ ] Write test: multiple PRs from same branch + - [ ] Write test: already merged PR + - [ ] Write test: closed but not merged PR + - [ ] Write test: PR with merge queue + - [ ] Write test: network failure handling + - [ ] Write test: GitHub API rate limit + - **File:** `tests/edge-cases/test-merge-edge-cases.bats` + - **Acceptance:** All edge case tests pass + +- [ ] **Task 4.11:** Write performance tests `S` + - [ ] Write test: PR inference < 2 seconds + - [ ] Write test: validation < 5 seconds + - [ ] Write test: complete workflow < 30 seconds + - **File:** `tests/performance/test-merge-performance.bats` + - **Acceptance:** All performance targets met + +### Phase 4 Completion + +- [ ] **Task 4.12:** Final manual testing `L` + - [ ] Test all manual scenarios from tests.md + - [ ] Test on multiple repositories + - [ ] Test on macOS and Linux + - [ ] Document any platform-specific issues + - **Tests:** All 6 manual test scenarios from tests.md + - **Acceptance:** All scenarios work correctly on both platforms + +- [ ] **Task 4.13:** Code review and cleanup `M` + - [ ] Review code for style consistency + - [ ] Remove debug code and TODOs + - [ ] Optimize performance where possible + - [ ] Ensure error messages are helpful + - **Tests:** Code review checklist from spec + - **Acceptance:** Code passes all review criteria + +--- + +## Final Integration + +### PR Creation + +- [ ] **Task 5.1:** Create pull request `M` + - [ ] Commit all code changes + - [ ] Run all tests one final time + - [ ] Create PR with comprehensive description + - [ ] Link to issue #100 + - [ ] Add test results to PR description + - [ ] Request review + - **Tests:** All tests pass in CI + - **Acceptance:** PR ready for review + +### Documentation Updates + +- [ ] **Task 5.2:** Update roadmap `XS` + - [ ] Mark /merge command as implemented + - [ ] Update Phase 1 status if applicable + - [ ] Document completion date + - **File:** `.agent-os/product/roadmap.md` + - **Acceptance:** Roadmap reflects /merge completion + +- [ ] **Task 5.3:** Update README if needed `XS` + - [ ] Add /merge to command list if not present + - [ ] Update feature list + - **File:** `README.md` + - **Acceptance:** README mentions /merge command + +### Deployment + +- [ ] **Task 5.4:** Merge to main `XS` + - [ ] Address any PR feedback + - [ ] Get approval from reviewers + - [ ] Merge PR to main + - [ ] Verify deployment successful + - **Tests:** Installation test after merge + - **Acceptance:** /merge available after `setup-claude-code.sh` + +--- + +## Task Summary + +**Total Tasks:** 50 tasks across 4 phases plus final integration + +**Time Estimate Breakdown:** +- Phase 1: 6-8 hours (MVP) +- Phase 2: 4-6 hours (Review Integration) +- Phase 3: 3-4 hours (Worktree Management) +- Phase 4: 4-6 hours (Polish) +- Final Integration: 2-3 hours +- **Total:** 19-27 hours + +**Task Size Distribution:** +- XS: 8 tasks (~6 hours) +- S: 10 tasks (~15 hours) +- M: 25 tasks (~75 hours, but many parallel) +- L: 7 tasks (~42 hours) +- XL: 0 tasks + +**Parallel Execution Opportunities:** +- Test writing tasks can be done in parallel with setup +- Unit tests for different components are independent +- Documentation tasks can be done concurrently with testing + +## Notes + +- **TDD Approach:** All feature tasks follow pattern: write test → implement → verify test passes +- **Dependencies:** Some tasks depend on prior tasks (marked with completion checkboxes) +- **Flexibility:** Task order within phases can be adjusted based on developer preference +- **Quality Gates:** Each phase has completion criteria that must be met before proceeding + +## Progress Tracking + +Update task checkboxes as work progresses. When a task is complete: +1. Check the box: `- [x]` +2. Update the "Last Updated" date at the top of this file +3. Commit the change with a meaningful message + +Use `git grep "\- \[ \]" .agent-os/specs/2025-10-13-merge-command-#100/tasks.md` to count remaining tasks. diff --git a/.agent-os/specs/2025-10-13-merge-command-#100/technical-spec.md b/.agent-os/specs/2025-10-13-merge-command-#100/technical-spec.md new file mode 100644 index 00000000..c463c6bb --- /dev/null +++ b/.agent-os/specs/2025-10-13-merge-command-#100/technical-spec.md @@ -0,0 +1,473 @@ +# Technical Specification: Merge Command + +> **Spec:** 2025-10-13-merge-command-#100 +> **Last Updated:** 2025-10-13 + +## Architecture Overview + +### Command Structure + +**Location:** `commands/workflow-merge.md` (markdown command file) +**Script:** `scripts/workflow-merge.sh` (main execution logic) +**Libraries:** Leverage existing `workflow-status.sh`, `workflow-complete.sh` patterns + +### System Components + +``` +┌─────────────────────────────────────────────────────────────┐ +│ /merge Command Entry │ +└──────────────────────┬──────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ 1. PR Inference Engine │ +│ • Parse conversation history for PR mentions │ +│ • Check current branch against GitHub PRs │ +│ • Extract issue number from branch name │ +│ • Return most recent PR if multiple found │ +└──────────────────────┬──────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ 2. User Confirmation │ +│ • Display: "Merge PR #XX: [title]?" │ +│ • Show branch, author, status summary │ +│ • Await user approval │ +└──────────────────────┬──────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ 3. Pre-Merge Validator │ +│ • Check CI/CD status via gh pr checks │ +│ • Verify review approval via gh pr view │ +│ • Check for merge conflicts │ +│ • Validate branch protection rules │ +└──────────────────────┬──────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ 4. Review Feedback Analyzer │ +│ • Query CodeRabbit comments via GitHub API │ +│ • Query Codex comments if applicable │ +│ • Categorize: critical vs suggestions │ +│ • Present to user with context │ +└──────────────────────┬──────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ 5. Merge Executor │ +│ • Execute: gh pr merge --merge --delete-branch │ +│ • Verify merge commit on main │ +│ • Handle merge queue scenarios │ +└──────────────────────┬──────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ 6. Worktree Cleanup │ +│ • Detect if in worktree │ +│ • Return to main repository │ +│ • Fetch and pull latest │ +│ • Verify merge present locally │ +│ • Remove worktree: git worktree remove │ +│ • Prune metadata: git worktree prune │ +└─────────────────────────────────────────────────────────────┘ +``` + +## Component Details + +### 1. PR Inference Engine + +**Function:** `infer_pr_number()` + +**Logic:** +```bash +infer_pr_number() { + local pr_number="" + + # Priority 1: Explicit argument + if [[ -n "$1" ]]; then + pr_number="$1" + return 0 + fi + + # Priority 2: Current branch + local branch=$(git branch --show-current) + pr_number=$(gh pr list --head "$branch" --json number --jq '.[0].number') + if [[ -n "$pr_number" ]]; then + return 0 + fi + + # Priority 3: Extract issue from branch name + if [[ $branch =~ issue-([0-9]+) ]] || \ + [[ $branch =~ ^([0-9]+)- ]] || \ + [[ $branch =~ (feature|bugfix|hotfix)-([0-9]+) ]]; then + local issue="${BASH_REMATCH[1]}" + pr_number=$(gh pr list --search "$issue" --json number --jq '.[0].number') + if [[ -n "$pr_number" ]]; then + return 0 + fi + fi + + # Priority 4: Most recent PR from conversation (future: AI context parsing) + + echo "❌ Could not infer PR number. Please specify: /merge " + return 1 +} +``` + +**Dependencies:** +- `gh pr list` - GitHub CLI +- `git branch --show-current` - Git + +### 2. Pre-Merge Validator + +**Function:** `validate_merge_readiness(pr_number)` + +**Checks:** +```bash +validate_merge_readiness() { + local pr_number="$1" + local errors=() + + # Check 1: Review Status + local review_decision=$(gh pr view "$pr_number" --json reviewDecision --jq '.reviewDecision') + if [[ "$review_decision" != "APPROVED" ]] && [[ "$review_decision" != "REVIEW_REQUIRED" ]]; then + errors+=("Review required: $review_decision") + fi + + # Check 2: Merge Conflicts + local mergeable=$(gh pr view "$pr_number" --json mergeable --jq '.mergeable') + if [[ "$mergeable" != "MERGEABLE" ]]; then + errors+=("Merge conflicts detected") + fi + + # Check 3: CI Checks + local check_status=$(gh pr checks "$pr_number" --json state --jq '.[] | select(.state != "SUCCESS") | .name') + if [[ -n "$check_status" ]]; then + errors+=("Failing checks: $check_status") + fi + + # Check 4: Branch Protection + local merge_state=$(gh pr view "$pr_number" --json mergeStateStatus --jq '.mergeStateStatus') + if [[ "$merge_state" == "BLOCKED" ]]; then + errors+=("Branch protection rules not satisfied") + fi + + if [[ ${#errors[@]} -gt 0 ]]; then + echo "❌ Pre-merge validation failed:" + printf ' • %s\n' "${errors[@]}" + return 1 + fi + + echo "✅ All pre-merge checks passed" + return 0 +} +``` + +**API Calls:** +- `gh pr view --json reviewDecision,mergeable,mergeStateStatus` +- `gh pr checks` + +### 3. Review Feedback Analyzer + +**Function:** `analyze_review_feedback(pr_number)` + +**Logic:** +```bash +analyze_review_feedback() { + local pr_number="$1" + local repo=$(gh repo view --json nameWithOwner --jq '.nameWithOwner') + + # Fetch CodeRabbit comments + local coderabbit_comments=$(gh api "repos/$repo/pulls/$pr_number/comments" \ + --jq '.[] | select(.user.login == "coderabbitai") | {path: .path, body: .body}') + + # Fetch Codex comments (if applicable) + local codex_comments=$(gh api "repos/$repo/pulls/$pr_number/comments" \ + --jq '.[] | select(.user.login == "codex-bot") | {path: .path, body: .body}') + + # Parse and categorize + if [[ -n "$coderabbit_comments" ]] || [[ -n "$codex_comments" ]]; then + echo "🤖 Review feedback detected:" + echo "$coderabbit_comments" | jq -r '.path + ": " + .body' + echo "$codex_comments" | jq -r '.path + ": " + .body' + + # Prompt user + read -p "Address review feedback before merging? [Y/n]: " response + if [[ "$response" =~ ^[Yy]$ ]] || [[ -z "$response" ]]; then + return 2 # Signal to address feedback + fi + fi + + return 0 +} +``` + +**Dependencies:** +- `gh api repos/{owner}/{repo}/pulls/{pr}/comments` +- `jq` for JSON parsing + +### 4. Merge Executor + +**Function:** `execute_merge(pr_number)` + +**Logic:** +```bash +execute_merge() { + local pr_number="$1" + local strategy="${MERGE_STRATEGY:-merge}" # merge, squash, or rebase + + echo "🔄 Merging PR #$pr_number..." + + # Execute merge + if gh pr merge "$pr_number" "--$strategy" --delete-branch; then + echo "✅ PR #$pr_number merged successfully" + + # Verify merge commit + local merge_commit=$(gh pr view "$pr_number" --json mergeCommit --jq '.mergeCommit.oid') + if [[ -n "$merge_commit" ]]; then + echo " Merge commit: $merge_commit" + return 0 + else + echo "⚠️ Warning: Could not verify merge commit" + return 1 + fi + else + echo "❌ Merge failed" + return 1 + fi +} +``` + +**Options:** +- `--merge` (default): Create merge commit +- `--squash`: Squash commits +- `--rebase`: Rebase and merge +- `--delete-branch`: Remove remote branch after merge + +### 5. Worktree Cleanup + +**Function:** `cleanup_worktree()` + +**Logic:** +```bash +cleanup_worktree() { + # Detect if in worktree + local current_dir=$(pwd) + local worktree_info=$(git worktree list --porcelain | grep -A 2 "^worktree $current_dir") + + if [[ -z "$worktree_info" ]]; then + echo "ℹ️ Not in a worktree, skipping cleanup" + return 0 + fi + + echo "🧹 Cleaning up worktree..." + + # Extract worktree path + local worktree_path=$(echo "$worktree_info" | head -1 | cut -d ' ' -f 2) + local main_repo=$(git worktree list --porcelain | grep "^worktree" | head -1 | cut -d ' ' -f 2) + + # Return to main repository + cd "$main_repo" || return 1 + echo " Returned to main repository: $main_repo" + + # Update main branch + git checkout main + git fetch origin + git pull origin main + echo " ✅ Main branch updated" + + # Verify merge is present + local merge_commit=$(git log --oneline -1 --grep="Merge pull request") + if [[ -z "$merge_commit" ]]; then + echo " ⚠️ Warning: Recent merge not found in main" + else + echo " ✅ Merge verified: $merge_commit" + fi + + # Remove worktree + if git worktree remove "$worktree_path"; then + echo " ✅ Worktree removed: $worktree_path" + else + echo " ❌ Failed to remove worktree (may need manual cleanup)" + return 1 + fi + + # Prune metadata + git worktree prune + echo " ✅ Worktree metadata pruned" + + return 0 +} +``` + +**Safety Checks:** +- Verify merge commit exists before cleanup +- Check for uncommitted changes in worktree +- Validate main branch updated successfully + +## Data Flow + +``` +User Input → PR Inference → Confirmation + ↓ + Validation + ↓ + [If Issues Detected] + ↓ + Review Feedback + ↓ + [User Addresses] + ↓ + Re-validate + ↓ + [All Checks Pass] + ↓ + Merge Execute + ↓ + [If in Worktree] + ↓ + Worktree Cleanup + ↓ + Success Report +``` + +## Error Handling + +### Error Categories + +1. **User Input Errors** + - Invalid PR number + - PR not found + - Ambiguous inference + - **Action:** Clear error message, suggest correction + +2. **Validation Failures** + - Failing CI checks + - Missing approvals + - Merge conflicts + - **Action:** Display specific issues, suggest fixes, exit gracefully + +3. **Merge Failures** + - GitHub API errors + - Permission denied + - Network issues + - **Action:** Report error, provide manual merge command + +4. **Cleanup Failures** + - Worktree removal blocked + - Uncommitted changes + - Git operation failed + - **Action:** Leave worktree intact, provide manual cleanup instructions + +### Rollback Strategy + +- Merge operations are atomic (GitHub handles) +- Worktree cleanup only after verified merge +- No destructive operations before validation passes + +## Performance Considerations + +### Expected Timings +- PR inference: <1 second +- Pre-merge validation: 2-3 seconds (GitHub API calls) +- Review feedback analysis: 1-2 seconds +- Merge execution: 2-5 seconds +- Worktree cleanup: 3-5 seconds + +**Total:** 10-20 seconds for complete workflow + +### Optimization Strategies +- Cache PR data for 30 seconds to reduce API calls +- Parallel validation checks where possible +- Use `--cached` flags for GitHub CLI when available + +## Security Considerations + +### Authentication +- Relies on `gh auth status` for GitHub authentication +- No credential storage or management +- Uses existing GitHub CLI session + +### Permissions +- Respects repository branch protection rules +- Cannot bypass required reviews +- Admin override only with explicit `--admin` flag + +### Data Privacy +- No sensitive data logged to files +- PR content stays in GitHub +- Local git operations only + +## Testing Strategy + +### Unit Tests +- PR inference logic with mock branches +- Validation checks with mock API responses +- Worktree detection logic + +### Integration Tests +- Full workflow on test repository +- Mock PR with passing/failing checks +- Worktree creation and cleanup cycle + +### Manual Testing Scenarios +1. Happy path: Clean merge from worktree +2. Failing checks: Validation blocks merge +3. Review feedback: CodeRabbit comments detected +4. Merge conflicts: User notified, merge blocked +5. Not in worktree: Cleanup skipped gracefully + +## Dependencies + +### Required +- `gh` (GitHub CLI) v2.0+ +- `git` v2.17+ (for `git worktree remove`) +- `jq` for JSON parsing +- Bash 4.0+ for associative arrays + +### Optional +- CodeRabbit integration (automatic) +- Codex integration (automatic) + +## Installation + +Command installed via `setup-claude-code.sh`: + +```bash +curl -s -o "$HOME/.claude/commands/workflow-merge.md" \ + "https://raw.githubusercontent.com/carmandale/agent-os/main/commands/workflow-merge.md" +``` + +Script installed during Agent OS setup: + +```bash +curl -s -o "$HOME/.agent-os/scripts/workflow-merge.sh" \ + "https://raw.githubusercontent.com/carmandale/agent-os/main/scripts/workflow-merge.sh" +chmod +x "$HOME/.agent-os/scripts/workflow-merge.sh" +``` + +## Configuration Options + +### Environment Variables +- `MERGE_STRATEGY` - Default merge strategy (merge/squash/rebase) +- `AGENT_OS_AUTO_MERGE` - Enable auto-merge by default (true/false) +- `SKIP_REVIEW_FEEDBACK` - Skip review feedback analysis (true/false) + +### User Preferences +Can be set in `~/.agent-os/config` (future): +```bash +merge.strategy=merge +merge.auto-cleanup=true +merge.confirm-always=true +``` + +## Future Enhancements + +### Phase 5+ Features +- AI-powered conflict resolution suggestions +- Automatic changelog generation on merge +- Integration with project management tools (Jira, Linear) +- Merge queue support for high-traffic repositories +- Team notification integration (Slack, Discord) +- Merge metrics and analytics tracking diff --git a/.agent-os/specs/2025-10-13-merge-command-#100/tests.md b/.agent-os/specs/2025-10-13-merge-command-#100/tests.md new file mode 100644 index 00000000..c42742bc --- /dev/null +++ b/.agent-os/specs/2025-10-13-merge-command-#100/tests.md @@ -0,0 +1,620 @@ +# Test Specification: Merge Command + +> **Spec:** 2025-10-13-merge-command-#100 +> **Last Updated:** 2025-10-13 + +## Test Strategy + +### Approach +- **TDD (Test-Driven Development):** Write tests before implementation +- **Unit Tests:** Test individual functions in isolation +- **Integration Tests:** Test complete workflow with mock GitHub responses +- **Manual Tests:** Verify real GitHub interaction and user experience + +### Test Framework +- **Shell Testing:** BATS (Bash Automated Testing System) +- **Location:** `tests/test-workflow-merge.bats` +- **Mocks:** Mock `gh` commands for predictable testing + +## Unit Tests + +### 1. PR Inference Tests + +**File:** `tests/unit/test-pr-inference.bats` + +```bats +@test "infer PR from explicit argument" { + run infer_pr_number 123 + assert_success + assert_output "123" +} + +@test "infer PR from current branch" { + git checkout -b feature/auth-#456 + run infer_pr_number + assert_success + assert_output "456" +} + +@test "infer PR from branch with issue pattern" { + git checkout -b issue-789 + run infer_pr_number + assert_success + assert_output --partial "789" +} + +@test "fail gracefully when PR cannot be inferred" { + git checkout -b random-branch + run infer_pr_number + assert_failure + assert_output --partial "Could not infer PR number" +} + +@test "prioritize explicit argument over branch" { + git checkout -b feature/auth-#456 + run infer_pr_number 999 + assert_success + assert_output "999" +} +``` + +### 2. Validation Tests + +**File:** `tests/unit/test-validation.bats` + +```bats +@test "validation passes with approved PR" { + mock_gh_pr_view_approved + run validate_merge_readiness 123 + assert_success + assert_output --partial "All pre-merge checks passed" +} + +@test "validation fails with failing CI" { + mock_gh_pr_checks_failing + run validate_merge_readiness 123 + assert_failure + assert_output --partial "Failing checks" +} + +@test "validation fails with merge conflicts" { + mock_gh_pr_view_conflicts + run validate_merge_readiness 123 + assert_failure + assert_output --partial "Merge conflicts detected" +} + +@test "validation fails with missing approval" { + mock_gh_pr_view_review_required + run validate_merge_readiness 123 + assert_failure + assert_output --partial "Review required" +} + +@test "validation fails with blocked branch protection" { + mock_gh_pr_view_blocked + run validate_merge_readiness 123 + assert_failure + assert_output --partial "Branch protection rules not satisfied" +} +``` + +### 3. Review Feedback Tests + +**File:** `tests/unit/test-review-feedback.bats` + +```bats +@test "detect CodeRabbit comments" { + mock_gh_api_coderabbit_comments + run analyze_review_feedback 123 + assert_success + assert_output --partial "Review feedback detected" + assert_output --partial "coderabbitai" +} + +@test "detect Codex comments" { + mock_gh_api_codex_comments + run analyze_review_feedback 123 + assert_success + assert_output --partial "Review feedback detected" + assert_output --partial "codex-bot" +} + +@test "no review feedback when no comments" { + mock_gh_api_no_comments + run analyze_review_feedback 123 + assert_success + refute_output --partial "Review feedback detected" +} + +@test "categorize critical vs suggestion comments" { + mock_gh_api_mixed_comments + run analyze_review_feedback 123 + assert_success + assert_output --partial "CRITICAL" + assert_output --partial "suggestion" +} +``` + +### 4. Merge Execution Tests + +**File:** `tests/unit/test-merge-execution.bats` + +```bats +@test "successful merge with default strategy" { + mock_gh_pr_merge_success + run execute_merge 123 + assert_success + assert_output --partial "merged successfully" +} + +@test "merge with squash strategy" { + MERGE_STRATEGY=squash + mock_gh_pr_merge_success + run execute_merge 123 + assert_success + assert_output --partial "merged successfully" +} + +@test "merge with rebase strategy" { + MERGE_STRATEGY=rebase + mock_gh_pr_merge_success + run execute_merge 123 + assert_success + assert_output --partial "merged successfully" +} + +@test "merge failure handling" { + mock_gh_pr_merge_failure + run execute_merge 123 + assert_failure + assert_output --partial "Merge failed" +} + +@test "verify merge commit after merge" { + mock_gh_pr_merge_success + run execute_merge 123 + assert_success + assert_output --partial "Merge commit:" +} +``` + +### 5. Worktree Cleanup Tests + +**File:** `tests/unit/test-worktree-cleanup.bats` + +```bats +@test "detect when in worktree" { + create_test_worktree + cd_to_worktree + run cleanup_worktree + assert_success + assert_output --partial "Cleaning up worktree" +} + +@test "skip cleanup when not in worktree" { + cd_to_main_repo + run cleanup_worktree + assert_success + assert_output --partial "Not in a worktree" +} + +@test "return to main repository during cleanup" { + create_test_worktree + cd_to_worktree + run cleanup_worktree + assert_success + assert_equal "$(pwd)" "$MAIN_REPO_PATH" +} + +@test "update main branch during cleanup" { + create_test_worktree + cd_to_worktree + run cleanup_worktree + assert_success + assert_output --partial "Main branch updated" +} + +@test "remove worktree after verification" { + create_test_worktree + cd_to_worktree + run cleanup_worktree + assert_success + assert_output --partial "Worktree removed" + refute_directory_exists "$WORKTREE_PATH" +} + +@test "prune worktree metadata" { + create_test_worktree + cd_to_worktree + run cleanup_worktree + assert_success + assert_output --partial "Worktree metadata pruned" +} + +@test "fail gracefully if worktree has uncommitted changes" { + create_test_worktree + cd_to_worktree + touch uncommitted.txt + run cleanup_worktree + assert_failure + assert_output --partial "uncommitted changes" +} +``` + +## Integration Tests + +### Full Workflow Tests + +**File:** `tests/integration/test-merge-workflow.bats` + +```bats +@test "complete workflow: infer → validate → merge → cleanup" { + # Setup: Create PR in worktree + create_test_pr_in_worktree 123 + + # Execute: Run merge command + run workflow-merge.sh + + # Assert: All steps completed + assert_success + assert_output --partial "Merge PR #123?" + assert_output --partial "All pre-merge checks passed" + assert_output --partial "merged successfully" + assert_output --partial "Worktree removed" +} + +@test "workflow with review feedback" { + create_test_pr_with_coderabbit_comments 456 + mock_user_input "Y" # User confirms addressing feedback + + run workflow-merge.sh + + assert_success + assert_output --partial "Review feedback detected" + assert_output --partial "Address review feedback" +} + +@test "workflow blocks on failing CI" { + create_test_pr_with_failing_ci 789 + + run workflow-merge.sh + + assert_failure + assert_output --partial "Failing checks" + assert_output --partial "Cannot merge" +} + +@test "dry-run mode shows actions without executing" { + create_test_pr 123 + + run workflow-merge.sh --dry-run + + assert_success + assert_output --partial "[DRY RUN]" + assert_output --partial "Would merge PR #123" + refute_output --partial "merged successfully" # Should not actually merge +} + +@test "force mode skips validation checks" { + create_test_pr_with_failing_ci 123 + + run workflow-merge.sh --force + + assert_success + assert_output --partial "⚠️ WARNING: Forcing merge" + assert_output --partial "merged successfully" +} +``` + +## Edge Case Tests + +**File:** `tests/edge-cases/test-merge-edge-cases.bats` + +```bats +@test "handle multiple PRs from same branch" { + create_multiple_prs_same_branch + + run workflow-merge.sh + + assert_failure + assert_output --partial "Multiple PRs found" + assert_output --partial "Please specify" +} + +@test "handle already merged PR" { + create_merged_pr 123 + + run workflow-merge.sh 123 + + assert_failure + assert_output --partial "PR already merged" +} + +@test "handle closed but not merged PR" { + create_closed_pr 123 + + run workflow-merge.sh 123 + + assert_failure + assert_output --partial "PR is closed" +} + +@test "handle PR with merge queue" { + create_pr_in_merge_queue 123 + + run workflow-merge.sh 123 + + assert_success + assert_output --partial "Added to merge queue" +} + +@test "handle network failure gracefully" { + mock_network_failure + + run workflow-merge.sh 123 + + assert_failure + assert_output --partial "Network error" + assert_output --partial "Try again" +} + +@test "handle GitHub API rate limit" { + mock_api_rate_limit + + run workflow-merge.sh 123 + + assert_failure + assert_output --partial "Rate limit exceeded" + assert_output --partial "Wait" +} +``` + +## Manual Test Scenarios + +### Scenario 1: Happy Path (Green PR in Worktree) + +**Setup:** +1. Create feature branch with issue number: `git checkout -b feature/merge-cmd-#100` +2. Create worktree: `git worktree add .worktrees/merge-cmd-#100 feature/merge-cmd-#100` +3. Create test PR on GitHub with passing CI +4. Navigate to worktree: `cd .worktrees/merge-cmd-#100` + +**Execute:** +```bash +/merge +``` + +**Expected:** +- ✅ Infers PR #100 from branch +- ✅ Displays: "Merge PR #100: Add merge command?" +- ✅ Shows PR details (author, checks, reviews) +- ✅ All validation checks pass +- ✅ Executes merge successfully +- ✅ Returns to main repository +- ✅ Updates main branch +- ✅ Removes worktree +- ✅ Displays success summary + +### Scenario 2: Failing CI Checks + +**Setup:** +1. Create PR with intentionally failing tests +2. Navigate to worktree + +**Execute:** +```bash +/merge +``` + +**Expected:** +- ✅ Infers PR correctly +- ✅ Validation detects failing checks +- ❌ Blocks merge with clear error message +- ✅ Lists specific failing checks +- ✅ Suggests fixes: "Fix failing tests before merging" +- ✅ Does not execute merge + +### Scenario 3: CodeRabbit Review Feedback + +**Setup:** +1. Create PR with CodeRabbit comments +2. Navigate to worktree + +**Execute:** +```bash +/merge +``` + +**Expected:** +- ✅ Infers PR correctly +- ✅ Validation passes +- ✅ Detects CodeRabbit comments +- ✅ Displays: "🤖 Review feedback detected:" +- ✅ Lists comments by file +- ✅ Prompts: "Address review feedback before merging? [Y/n]:" +- ✅ If user types Y: Pauses merge, allows addressing +- ✅ If user types n: Proceeds with merge + +### Scenario 4: Not in Worktree + +**Setup:** +1. Stay in main repository +2. Create feature branch with PR + +**Execute:** +```bash +/merge 123 +``` + +**Expected:** +- ✅ Accepts explicit PR number +- ✅ Validation passes +- ✅ Executes merge +- ✅ Updates main branch +- ℹ️ Displays: "Not in a worktree, skipping cleanup" +- ✅ No worktree removal attempted + +### Scenario 5: Merge Conflicts + +**Setup:** +1. Create PR with merge conflicts +2. Navigate to worktree + +**Execute:** +```bash +/merge +``` + +**Expected:** +- ✅ Infers PR correctly +- ❌ Validation detects conflicts +- ✅ Blocks merge with error: "Merge conflicts detected" +- ✅ Suggests: "Resolve conflicts before merging" +- ✅ Provides command: `git merge main` + +### Scenario 6: Dry Run Mode + +**Setup:** +1. Create valid PR in worktree + +**Execute:** +```bash +/merge --dry-run +``` + +**Expected:** +- ✅ Infers PR correctly +- ✅ Shows all validation checks +- ✅ Displays: "[DRY RUN] Would merge PR #123" +- ✅ Shows what cleanup would happen +- ❌ Does not actually merge +- ❌ Does not remove worktree + +## Performance Tests + +**File:** `tests/performance/test-merge-performance.bats` + +```bats +@test "PR inference completes within 2 seconds" { + start_time=$(date +%s) + run infer_pr_number + end_time=$(date +%s) + duration=$((end_time - start_time)) + assert_less_than "$duration" 2 +} + +@test "validation completes within 5 seconds" { + start_time=$(date +%s) + run validate_merge_readiness 123 + end_time=$(date +%s) + duration=$((end_time - start_time)) + assert_less_than "$duration" 5 +} + +@test "complete workflow completes within 30 seconds" { + start_time=$(date +%s) + run workflow-merge.sh + end_time=$(date +%s) + duration=$((end_time - start_time)) + assert_less_than "$duration" 30 +} +``` + +## Test Execution Commands + +```bash +# Run all tests +bats tests/test-workflow-merge.bats + +# Run unit tests only +bats tests/unit/ + +# Run integration tests +bats tests/integration/ + +# Run edge case tests +bats tests/edge-cases/ + +# Run specific test file +bats tests/unit/test-pr-inference.bats + +# Run with verbose output +bats -t tests/test-workflow-merge.bats + +# Generate test coverage report (requires bats-coverage) +bats tests/ --coverage +``` + +## Test Fixtures + +**Location:** `tests/fixtures/workflow-merge/` + +### Mock Functions + +**File:** `tests/fixtures/workflow-merge/mocks.bash` + +```bash +# Mock gh pr view for approved PR +mock_gh_pr_view_approved() { + gh() { + if [[ "$1" == "pr" && "$2" == "view" ]]; then + echo '{"reviewDecision":"APPROVED","mergeable":"MERGEABLE","mergeStateStatus":"CLEAN"}' + fi + } + export -f gh +} + +# Mock gh pr checks for passing CI +mock_gh_pr_checks_passing() { + gh() { + if [[ "$1" == "pr" && "$2" == "checks" ]]; then + echo '[{"name":"CI","state":"SUCCESS"}]' + fi + } + export -f gh +} + +# Mock gh api for CodeRabbit comments +mock_gh_api_coderabbit_comments() { + gh() { + if [[ "$1" == "api" ]]; then + cat tests/fixtures/workflow-merge/coderabbit-comments.json + fi + } + export -f gh +} +``` + +### Test Data + +**File:** `tests/fixtures/workflow-merge/coderabbit-comments.json` + +```json +[ + { + "path": "scripts/workflow-merge.sh", + "body": "Consider adding error handling for network failures", + "user": {"login": "coderabbitai"} + }, + { + "path": "commands/workflow-merge.md", + "body": "CRITICAL: Missing input validation", + "user": {"login": "coderabbitai"} + } +] +``` + +## Test Coverage Goals + +- **Unit Tests:** 90%+ code coverage +- **Integration Tests:** All critical paths covered +- **Edge Cases:** All identified edge cases tested +- **Manual Tests:** All user-facing scenarios verified + +## Test Maintenance + +- Run tests before every commit +- Update tests when adding new features +- Review test failures immediately +- Keep mocks synchronized with real API responses diff --git a/docs/research/gh-cli-worktree-claude-commands.md b/docs/research/gh-cli-worktree-claude-commands.md new file mode 100644 index 00000000..40066b2b --- /dev/null +++ b/docs/research/gh-cli-worktree-claude-commands.md @@ -0,0 +1,932 @@ +# GitHub CLI, Git Worktree, and Claude Code Commands Research + +> Research Date: 2025-10-13 +> Agent OS Version: 2.4.0 +> Purpose: Technical documentation for workflow completion automation + +## Table of Contents + +1. [GitHub CLI PR Merge](#github-cli-pr-merge) +2. [GitHub CLI PR Checks](#github-cli-pr-checks) +3. [GitHub CLI PR View](#github-cli-pr-view) +4. [GitHub CLI PR Review](#github-cli-pr-review) +5. [GitHub CLI API Access](#github-cli-api-access) +6. [Git Worktree Commands](#git-worktree-commands) +7. [Claude Code Command Format](#claude-code-command-format) +8. [Implementation Patterns](#implementation-patterns) + +--- + +## GitHub CLI PR Merge + +### Official Documentation +- **URL**: https://cli.github.com/manual/gh_pr_merge +- **Command**: `gh pr merge [ | | ] [flags]` + +### Command Behavior +- Without an argument, selects the pull request for the current branch +- For branches requiring merge queues, no specific merge strategy is needed +- Can automatically enable merge when required checks pass + +### Merge Strategy Flags + +```bash +# Merge strategies (choose one) +-m, --merge # Merge commits with base branch (creates merge commit) +-r, --rebase # Rebase commits onto base branch (linear history) +-s, --squash # Squash commits into one and merge (single commit) +``` + +### Key Flags + +```bash +# Admin and automation +--admin # Bypass requirements using administrator privileges +--auto # Automatically merge after requirements are met +--disable-auto # Disable auto-merge + +# Branch management +-d, --delete-branch # Delete local and remote branch after merge + +# Commit customization +-A, --author-email # Set email for merge commit author +-b, --body # Set merge commit body text +-F, --body-file # Read body text from file (use "-" for stdin) +--subject # Set merge commit subject text + +# Repository selection +-R, --repo [HOST/]OWNER/REPO # Select another repository +``` + +### Merge Queue Behavior +- When targeting a branch requiring a merge queue: + - No merge strategy is required + - If required checks haven't passed, auto-merge will be enabled + - If required checks have passed, PR is added to merge queue + - To bypass merge queue and merge directly, use `--admin` flag + +### Usage Examples + +```bash +# Merge current branch's PR with merge commit +gh pr merge --merge --delete-branch + +# Squash and merge with custom message +gh pr merge --squash --subject "feat: add new feature" --body "Implements feature X" + +# Auto-merge when checks pass +gh pr merge --auto --squash --delete-branch + +# Merge specific PR by number +gh pr merge 123 --merge + +# Force merge with admin privileges +gh pr merge --admin --merge +``` + +### Exit Codes +- 0: Success +- Non-zero: Error (check stderr for details) + +--- + +## GitHub CLI PR Checks + +### Official Documentation +- **URL**: https://cli.github.com/manual/gh_pr_checks +- **Command**: `gh pr checks [ | | ] [flags]` + +### Command Behavior +- Shows CI status for a single pull request +- Without an argument, selects the PR for the current branch +- Includes a `bucket` field categorizing check states into: pass, fail, pending, skipping, or cancel + +### Flags + +```bash +# Watch mode +--watch # Watch checks until they finish +-i, --interval # Refresh interval in seconds (default: 10) +--fail-fast # Exit watch mode on first check failure + +# Filtering +--required # Only show checks that are required + +# Output formatting +--json # Output JSON with specified fields +-q, --jq # Filter JSON output using jq expression +-t, --template # Format JSON output using Go template + +# Web interface +-w, --web # Open browser to show check details +``` + +### JSON Output Fields + +```bash +# Available fields for --json flag +bucket # Categorized state (pass/fail/pending/skipping/cancel) +completedAt # Timestamp when check completed +description # Check description +event # Event that triggered check +link # URL to check details +name # Check name +startedAt # Timestamp when check started +state # Raw check state +workflow # Workflow name +``` + +### Exit Codes +- 0: Success +- 8: Checks pending (useful for scripting) +- Non-zero: Error + +### Usage Examples + +```bash +# Basic check status +gh pr checks + +# Watch checks until completion +gh pr checks --watch + +# Watch with custom interval and fail-fast +gh pr checks --watch --interval 5 --fail-fast + +# Get only required checks +gh pr checks --required + +# JSON output with specific fields +gh pr checks --json state,name,conclusion,bucket + +# Check specific PR +gh pr checks 123 + +# Filter pending checks with jq +gh pr checks --json name,state,bucket --jq '.[] | select(.bucket == "pending")' + +# Open checks in browser +gh pr checks --web +``` + +### Scripting Pattern + +```bash +# Wait for checks to pass +gh pr checks --watch --fail-fast +exit_code=$? +if [ $exit_code -eq 0 ]; then + echo "All checks passed" + gh pr merge --merge --delete-branch +else + echo "Checks failed or pending (exit code: $exit_code)" + exit 1 +fi +``` + +--- + +## GitHub CLI PR View + +### Official Documentation +- **URL**: https://cli.github.com/manual/gh_pr_view +- **Command**: `gh pr view [ | | ] [flags]` + +### Command Behavior +- Display the title, body, and other information about a pull request +- Without an argument, displays the PR for the current branch +- With `--web` flag, opens PR in browser instead + +### Flags + +```bash +# Comments +-c, --comments # View pull request comments + +# Output formatting +--json # Output JSON with specified fields +-q, --jq # Filter JSON output using jq expression +-t, --template # Format JSON output using Go template + +# Web interface +-w, --web # Open pull request in browser + +# Repository selection +-R, --repo [HOST/]OWNER/REPO # Select another repository +``` + +### JSON Output Fields + +```bash +# Complete list of available fields +additions, assignees, author, autoMergeRequest, baseRefName, baseRefOid, body, +changedFiles, closed, closedAt, closingIssuesReferences, comments, commits, +createdAt, deletions, files, fullDatabaseId, headRefName, headRefOid, +headRepository, headRepositoryOwner, id, isCrossRepository, isDraft, labels, +latestReviews, maintainerCanModify, mergeCommit, mergeStateStatus, mergeable, +mergedAt, mergedBy, milestone, number, potentialMergeCommit, projectCards, +projectItems, reactionGroups, reviewDecision, reviewRequests, reviews, state, +statusCheckRollup, title, updatedAt, url +``` + +### Key Fields for Review Status + +```bash +reviewDecision # Overall review decision (APPROVED, CHANGES_REQUESTED, etc.) +reviews # Array of all reviews +reviewRequests # Array of pending review requests +latestReviews # Most recent reviews from each reviewer +statusCheckRollup # CI/CD check status +mergeable # Whether PR can be merged +mergeStateStatus # Merge state (CLEAN, BEHIND, BLOCKED, etc.) +``` + +### Usage Examples + +```bash +# View current PR +gh pr view + +# View specific PR +gh pr view 123 + +# Get review status +gh pr view --json reviewDecision,reviews,reviewRequests + +# Check if PR is approved and mergeable +gh pr view --json reviewDecision,mergeable,statusCheckRollup + +# View with comments +gh pr view --comments + +# Complex query with jq +gh pr view --json reviews --jq '.reviews | map(select(.state == "APPROVED")) | length' + +# Check merge readiness +gh pr view --json reviewDecision,mergeable,mergeStateStatus,statusCheckRollup \ + --jq '{approved: .reviewDecision, mergeable: .mergeable, state: .mergeStateStatus}' +``` + +--- + +## GitHub CLI PR Review + +### Official Documentation +- **URL**: https://cli.github.com/manual/gh_pr_review +- **Command**: `gh pr review [ | | ] [flags]` + +### Command Behavior +- Add a review to a pull request +- Without an argument, reviews the PR for the current branch + +### Review Actions + +```bash +-a, --approve # Approve pull request +-c, --comment # Comment on pull request (no approval/rejection) +-r, --request-changes # Request changes on pull request +``` + +### Flags + +```bash +# Review content +-b, --body # Review body text +-F, --body-file # Read body from file (use "-" for stdin) + +# Repository selection +-R, --repo [HOST/]OWNER/REPO # Select another repository +``` + +### Usage Examples + +```bash +# Approve PR +gh pr review --approve + +# Approve with comment +gh pr review --approve --body "LGTM! Great work." + +# Request changes +gh pr review --request-changes --body "Please address the following issues..." + +# Comment without approval +gh pr review --comment --body "Some thoughts on the implementation..." + +# Review specific PR +gh pr review 123 --approve + +# Approve from file +gh pr review --approve --body-file review.txt +``` + +--- + +## GitHub CLI API Access + +### Official Documentation +- **URL**: https://cli.github.com/manual/gh_api +- **Command**: `gh api [flags]` + +### Advanced Queries + +The `gh api` command provides direct access to GitHub's REST API for complex queries not covered by convenience commands. + +### Review Status Queries + +```bash +# Get all reviews for a PR +gh api repos/{owner}/{repo}/pulls/{pr_number}/reviews + +# Get only approved reviews +gh api repos/{owner}/{repo}/pulls/{pr_number}/reviews \ + --jq '.[] | select(.state == "APPROVED") | {user: .user.login, body: .body}' + +# Get review comments (inline comments) +gh api repos/{owner}/{repo}/pulls/{pr_number}/comments + +# Get all comments (issue + review comments) +gh api repos/{owner}/{repo}/issues/{pr_number}/comments +``` + +### Check Status Queries + +```bash +# Get status checks for a commit +gh api repos/{owner}/{repo}/commits/{sha}/check-runs + +# Get required status checks +gh api repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks + +# Get combined status for a ref +gh api repos/{owner}/{repo}/commits/{ref}/status +``` + +### Usage Examples + +```bash +# Check if PR has any approved reviews +approved_count=$(gh api repos/{owner}/{repo}/pulls/{pr}/reviews \ + --jq '[.[] | select(.state == "APPROVED")] | length') + +if [ "$approved_count" -gt 0 ]; then + echo "PR has $approved_count approval(s)" +fi + +# Get latest review from each reviewer +gh api repos/{owner}/{repo}/pulls/{pr}/reviews \ + --jq 'group_by(.user.login) | map(max_by(.submitted_at))' +``` + +--- + +## Git Worktree Commands + +### Official Documentation +- **URL**: https://git-scm.com/docs/git-worktree +- **Primary Commands**: `git worktree remove`, `git worktree prune` + +### git worktree list + +```bash +# List all worktrees +git worktree list + +# List with more details +git worktree list --porcelain + +# Expected output format +/path/to/main-worktree abc1234 [main] +/path/to/feature-branch def5678 [feature/xyz] +``` + +### git worktree remove + +**Syntax**: `git worktree remove [flags]` + +#### Safety Features +- Only clean worktrees can be removed by default +- "Clean" means: no untracked files and no modifications in tracked files +- Cannot remove the main worktree + +#### Flags + +```bash +-f, --force # Force removal (required for unclean worktrees) + # Specify twice to remove locked worktrees +``` + +#### Usage Examples + +```bash +# Remove a clean worktree +git worktree remove /path/to/worktree + +# Force remove an unclean worktree +git worktree remove --force /path/to/worktree + +# Remove a locked worktree (force twice) +git worktree remove --force --force /path/to/locked-worktree +``` + +#### Error Conditions +- Worktree has untracked files: requires `--force` +- Worktree has modifications: requires `--force` +- Worktree contains submodules: requires `--force` +- Worktree is locked: requires `--force --force` +- Attempting to remove main worktree: always fails + +### git worktree prune + +**Syntax**: `git worktree prune [flags]` + +#### Purpose +- Removes administrative information about worktrees that no longer exist +- Cleans up stale worktree metadata in `.git/worktrees/` + +#### Flags + +```bash +-n, --dry-run # Show what would be removed without doing it +-v, --verbose # Report all removals +--expire