Skip to content
Open
Show file tree
Hide file tree
Changes from 14 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).

2 changes: 1 addition & 1 deletion .agent-os/specs/2025-10-13-merge-command-#100/tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

> **Spec:** 2025-10-13-merge-command-#100
> **Last Updated:** 2025-10-13
> **Status:** Ready for Implementation
> **Status:** Phase 1 MVP Complete

## Task Organization

Expand Down
153 changes: 153 additions & 0 deletions commands/workflow-merge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
---
allowed-tools: Bash(git status:*), Bash(git diff:*), Bash(git log:*), Bash(git branch:*), Bash(git worktree:*), Bash(git fetch:*), Bash(git pull:*), Bash(git checkout:*), Bash(gh pr:*), Bash(gh api:*), Bash(gh repo:*), Bash(grep:*), Bash(sed:*), Bash(~/.agent-os/scripts/workflow-merge.sh:*)
description: Intelligently merge pull requests with safety checks, review feedback integration, and worktree cleanup
argument-hint: [--dry-run|--force|--auto|--strategy merge|squash|rebase] [pr_number]
---

## Context

- Current branch: !`git branch --show-current`
- Git status: !`git status --porcelain`
- Current worktree: !`git worktree list | grep "$(pwd)" || echo "Not in a worktree"`

## Task

Merge a pull request with comprehensive safety checks, optional review feedback resolution, and automatic worktree cleanup.

### Pre-Merge Workspace Check

Before running the merge, check if workspace is clean:

!`git status --porcelain`

If there are uncommitted changes:
1. Ask user if they want to commit them (if part of this PR)
2. Offer to stash them (if experimental work)
3. Suggest using --auto flag instead
4. Only proceed with merge after workspace is clean

### Execute Merge

Once workspace is ready, execute the merge:

!`~/.agent-os/scripts/workflow-merge.sh $ARGUMENTS`

## What This Command Does

### PR Inference
- **Explicit Argument**: Use specified PR number (`/merge 123`)
- **Current Branch**: Infer from current branch via `gh pr list --head`
- **Branch Pattern**: Extract issue number from branch name patterns
- **Conversation Context**: (Future) Parse recent conversation for PR mentions

### Pre-Merge Validation
- ✅ **CI/CD Checks**: Verify all checks passing
- ✅ **Review Approval**: Check required approvals received
- ✅ **Merge Conflicts**: Ensure no conflicts with target branch
- ✅ **Branch Protection**: Validate protection rules satisfied

### Review Feedback Integration
- 🤖 **CodeRabbit Comments**: Detect and display automated review feedback
- 🤖 **Codex Comments**: Detect and display Codex review feedback
- 📝 **User Interaction**: Option to address feedback before merging

### Merge Execution
- 🔀 **Safe Merge**: Execute merge via `gh pr merge` with strategy
- 🏷️ **Branch Cleanup**: Automatically delete merged branch
- 🔄 **Local Update**: Update local main branch after merge

### Worktree Cleanup (If Applicable)
- 🧹 **Auto-Detection**: Detect if running in a worktree
- 🏠 **Return to Main**: Navigate back to main repository
- 🔄 **Update Main**: Fetch and pull latest changes
- ✅ **Verify Merge**: Confirm merge present in main
- 🗑️ **Remove Worktree**: Safely remove worktree directory
- 🔧 **Prune Metadata**: Clean up git worktree metadata

## Command Flags

### Execution Modes
- **--dry-run**: Show what would happen without executing
- **--force**: Skip validation checks (use with caution)
- **--auto**: Enable GitHub auto-merge (merge when checks pass)

### Merge Strategies
- **--strategy merge**: Create merge commit (default)
- **--strategy squash**: Squash commits before merging
- **--strategy rebase**: Rebase and merge

## Usage Examples

```bash
# Merge PR inferred from current branch
/merge

# Merge specific PR
/merge 123

# Preview merge without executing
/merge --dry-run

# Merge with squash strategy
/merge --strategy squash

# Enable auto-merge for PR
/merge --auto 123

# Force merge (skip validation)
/merge --force 123
```

## Safety Features

### Validation Checks
- Blocks merge if CI failing
- Requires approval if branch protection enabled
- Detects merge conflicts before attempting merge
- Validates branch protection rules

### User Confirmations
- Confirms PR number before proceeding
- Prompts for review feedback resolution
- Shows clear summary of what will happen

### Error Handling
- Clear error messages with recovery suggestions
- Graceful degradation on network issues
- Preserves worktree if merge fails
- Rollback-safe operations

## Workflow Integration

This command integrates with Agent OS workflows:

1. **After `/execute-tasks`**: When feature implementation complete
2. **With `/workflow-complete`**: Part of complete workflow automation
3. **Manual PR Creation**: After pushing feature branch
4. **Review Response**: After addressing review feedback

## Example Workflow

```bash
# 1. Complete feature in worktree
cd .worktrees/feature-name-#123

# 2. Create PR (via /workflow-complete or manually)
gh pr create --title "feat: add feature" --body "..."

# 3. Wait for CI and reviews...

# 4. Merge PR with automatic cleanup
/merge

# Result: PR merged, worktree cleaned up, back on main branch
```

## Notes

- Uses GitHub CLI (`gh`) for all GitHub operations
- Respects repository branch protection rules
- CodeRabbit/Codex integration is automatic
- Worktree cleanup only runs if in a worktree
- All operations are safe and reversible before merge
- Dry-run mode available for preview
Loading
Loading