Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
945d25f
docs: add research documents for /merge command planning
carmandale Oct 13, 2025
2717ebe
feat: add comprehensive spec for /merge command #100
carmandale Oct 13, 2025
57685f9
feat: add /merge command infrastructure (Tasks 1.1-1.3) #100
carmandale Oct 13, 2025
0fc2e68
docs: mark Phase 1 MVP as complete in tasks.md #100
carmandale Oct 13, 2025
5443733
docs: add worktree directory organization decision (DEC-009) #100
carmandale Oct 13, 2025
69ec3b5
chore: resolve merge conflict in tasks.md - keep 'Phase 1 MVP Complet…
carmandale Oct 15, 2025
cb9fcfc
security: fix critical command injection and data loss vulnerabilitie…
carmandale Oct 16, 2025
3c91839
feat: separate branch deletion from merge for safer cleanup #101
carmandale Oct 16, 2025
3cb4820
docs: add comprehensive testing evidence for /merge command #101
carmandale Oct 16, 2025
e3752b0
fix: address CodeRabbit portability and configuration issues #101
carmandale Oct 16, 2025
46ef445
ux: improve error messaging and workspace check communication #101
carmandale Oct 16, 2025
9669666
fix: exit 0 when pausing for user action (not a failure) #101
carmandale Oct 16, 2025
f3e5f66
fix: handle 'pr 101' syntax and improve argument parsing #101
carmandale Oct 16, 2025
d0fcd2e
refactor: command handles workspace checks, script executes merge #101
carmandale Oct 16, 2025
7852ae0
docs: clarify command behavior - script reports, Claude interprets #101
carmandale Oct 16, 2025
8108a8f
fix: validation reports status, doesn't fail (exit 0 always) #101
carmandale Oct 16, 2025
f48a887
ux: simplify command output - show script results directly #101
carmandale Oct 16, 2025
164c610
ux: clearer validation messages and status reporting #101
carmandale Oct 16, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 81 additions & 2 deletions .agent-os/product/decisions.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Product Decisions Log

> Last Updated: 2025-01-27
> Last Updated: 2025-10-13
> Version: 1.0.0
> Override Priority: Highest

Expand Down Expand Up @@ -399,4 +399,83 @@ The subagents system directly addresses Agent OS's core mission by providing spe
- Requires substantial integration and testing effort
- Introduces new dependencies and potential failure points
- May impact performance if not properly optimized
- Creates expectations for continued AI enhancement evolution
- Creates expectations for continued AI enhancement evolution

## 2025-10-13: Worktree Directory Organization Strategy

**ID:** DEC-009
**Status:** Accepted
**Category:** Technical
**Stakeholders:** Agent OS Users, Development Team
**Related:** Issue #100 (workflow-merge command implementation)

### Decision

Use `.worktrees/` subdirectory pattern for organizing git worktrees in Agent OS workflows, with proper `.gitignore` management to prevent accidental commits. This approach centralizes feature work within the main repository structure while maintaining clear separation.

### Context

Git worktrees enable parallel feature development without branch switching, but there's no universal "best practice" for where to locate worktree directories. Three main approaches exist in the community:

1. **Sibling directories** (`/dev/repo/`, `/dev/repo-feature/`)
2. **Subdirectories with .gitignore** (`/dev/repo/.worktrees/feature/`)
3. **Bare repo pattern** (`/dev/repo/.git/`, `/dev/repo/main/`, `/dev/repo/feature/`)

Research from Stack Overflow, GitHub community best practices, and comparison with other workflows (e.g., Orchestrator project) shows all three approaches are valid, with trade-offs based on workflow needs.

### Alternatives Considered

1. **Sibling Directories Pattern**
- Pros: Complete separation, no gitignore needed, zero risk of accidental commits
- Cons: Scattered across filesystem, harder to visualize all feature work, cleanup requires tracking multiple locations
- Example: `/dev/agent-os/`, `/dev/agent-os-merge-command-#100/`

2. **Subdirectory with .gitignore (Selected)**
- Pros: Centralized organization, easy cleanup (`rm -rf .worktrees/`), clear visual grouping, natural for scripts
- Cons: Requires `.gitignore` discipline, potential for accidental commit if misconfigured
- Example: `/dev/agent-os/.worktrees/merge-command-#100/`

3. **Bare Repository Pattern**
- Pros: All branches equal (no "primary" working directory), clean conceptual model
- Cons: Major workflow disruption, requires repository migration, unfamiliar to most developers
- Example: `/dev/agent-os/.git/`, `/dev/agent-os/main/`, `/dev/agent-os/feature/`

### Rationale

The subdirectory approach aligns best with Agent OS's design principles:

**Centralized Organization:** All feature work lives in one predictable location (`.worktrees/`), making it easy to see active features and manage cleanup through scripts like `workflow-merge.sh` and `workflow-complete.sh`.

**Developer Experience:** Most developers understand `.gitignore` patterns and find nested directories intuitive. The pattern matches other common project structures (`.git/`, `node_modules/`, etc.).

**Script-Friendly:** Automated worktree detection and cleanup logic becomes straightforward when worktrees follow a consistent subdirectory pattern.

**Risk Management:** While `.gitignore` discipline is required, Agent OS setup scripts already manage this automatically, and the risk is mitigated through:
- Setup scripts that create/update `.gitignore` entries
- Workflow enforcement hooks that detect dirty state
- Documentation emphasizing the pattern

**Flexibility:** Projects with specific needs (e.g., Xcode projects sensitive to nested directories) can still use sibling patterns—Agent OS commands work with both approaches.

### Consequences

**Positive:**
- Clear, predictable organization for all feature work
- Simple cleanup: `rm -rf .worktrees/feature-name/`
- Natural integration with workflow scripts
- Easy to see all active feature branches at a glance
- Reduced cognitive overhead (everything in one place)
- Setup scripts handle `.gitignore` configuration automatically

**Negative:**
- Requires proper `.gitignore` management (mitigated by setup scripts)
- Risk of accidental commit if user manually removes `.gitignore` entry
- Some IDEs may show worktrees in project tree (can be configured out)
- Not optimal for projects with tool-specific directory sensitivities (e.g., some Xcode configurations)

### Implementation Notes

- Setup scripts automatically add `.worktrees/` to `.gitignore`
- `workflow-merge.sh` includes automatic worktree cleanup
- Documentation should note sibling pattern as alternative for edge cases
- Future consideration: Make pattern configurable via `.agent-os/config.yaml`
Comment on lines +404 to +481
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

DEC‑009 aligns with merge workflow; verify repo-wide support and gitignore automation.

Strong, clear decision; matches the new merge workflow and worktree cleanup narrative. Please verify the implementation claims (auto .gitignore entry, detection/cleanup, docs references) to avoid doc–code drift.

Run to confirm support across the repo:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "1) .gitignore contains .worktrees/ entries:"
fd -H -a '.gitignore' | while read -r f; do
  if rg -nP '^\s*\.worktrees/' "$f" >/dev/null; then
    echo "$f has .worktrees/"
  else
    echo "$f missing .worktrees/"
  fi
done

echo
echo "2) Scripts mention .worktrees/ and git worktree operations:"
rg -nP --glob '!**/node_modules/**' '\.worktrees/|git\s+worktree|worktree (add|remove|prune|list)' -C2

echo
echo "3) Merge workflow script exposes detection/cleanup functions:"
fd -a 'workflow-merge.sh' | xargs -I{} rg -nP '(detect|cleanup).*worktree' -C2 {}

echo
echo "4) Docs mention the pattern and cleanup:"
fd -a 'workflow-merge.md' | xargs -I{} rg -nP '\.worktrees/|worktree' -n -C2 {}

Length of output: 34707


Fix .gitignore automation claim and include .worktrees/ entry
Implementation Notes state setup scripts add .worktrees/ to .gitignore, but the root .gitignore lacks this entry; please add the ignore pattern or update the documentation to reflect the actual behavior.

🤖 Prompt for AI Agents
In .agent-os/product/decisions.md around lines 404-481, the Implementation Notes
falsely claim setup scripts add `.worktrees/` to the repo root .gitignore while
the root .gitignore currently lacks that entry; fix by either adding the
`.worktrees/` ignore pattern to the repository root .gitignore and updating the
setup scripts to idempotently insert or verify that entry during initialization,
or update the Implementation Notes to accurately state the current behavior (and
add a TODO to the scripts to implement the .gitignore automation if you choose
the documentation-only route).

193 changes: 193 additions & 0 deletions .agent-os/specs/2025-10-13-merge-command-#100/README.md
Original file line number Diff line number Diff line change
@@ -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)
Comment on lines 1 to 193
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Do not touch .agent-os/ files.

The coding guidelines explicitly say we must not modify anything under .agent-os/ because that tree is installer-managed. Adding this spec there violates that rule—please relocate the document (e.g., to docs/specs/…) so we stay within the contract.
As per coding guidelines

🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

10-10: Bare URL used

(MD034, no-bare-urls)

🤖 Prompt for AI Agents
.agent-os/specs/2025-10-13-merge-command-#100/README.md lines 1-193: the spec
was added under the installer-managed .agent-os tree which is forbidden by
project guidelines; move this file out of .agent-os (e.g.,
docs/specs/2025-10-13-merge-command-#100/README.md), update any relative links
and paths inside the document to remain correct after relocation, update any
references in the repo or task trackers to point to the new location, and remove
the file from .agent-os (or add a short pointer there if absolutely necessary
per policy).

Loading
Loading