# 🔄 Git Integration Plan for Mirror Magi

## Overview

This document outlines how to add automatic git commit functionality to the Mirror Magi Meta-Agent system, allowing users to commit their changes automatically when completing tasks.

---

## 📋 Current System Analysis

### How It Works Now

1. **Task Execution Flow**:
   ```
   npm run plan:continue → Shows next task
   User implements with Claude → Files created/modified
   npm run plan:complete task_001 → Marks task done
   User manually commits → git add . && git commit
   ```

2. **Key Files**:
   - `scripts/execution/plan-project.js` - Main execution script
   - `core/project-planner.js` - Core planning logic
   - `state/master-plan.json` - Current plan state
   - `package.json` - NPM script definitions

3. **Command Structure**:
   - `plan:complete` maps to `plan-project.js complete`
   - Currently only accepts task ID as argument

---

## 🎯 Proposed Git Integration

### 1. Enhanced Complete Command

```bash
# Basic auto-commit
npm run plan:complete task_001 --commit

# With custom message
npm run plan:complete task_001 --commit --message "feat: Add dashboard with animations"

# Skip commit even if auto-commit is enabled
npm run plan:complete task_001 --no-commit
```

### 2. User Preferences System

Store preferences in `state/user-preferences.json`:

```json
{
  "autoCommit": false,        // Auto-commit by default
  "interactive": true,        // Show commit prompt
  "includeTaskId": true,      // Add (task_001) to commits
  "commitPrefix": "feat",     // Default commit type
  "stashUnrelated": true      // Stash non-task files
}
```

### 3. Configuration Commands

```bash
# Set auto-commit as default
npm run plan:config autoCommit true

# Disable interactive mode
npm run plan:config interactive false

# View current settings
npm run plan:config
```

---

## 🛠️ Implementation Details

### Phase 1: Core Git Functionality

**File: `scripts/execution/git-helpers.js`**

```javascript
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

module.exports = {
  async status() {
    const { stdout } = await execAsync('git status --porcelain');
    return stdout.trim().split('\n').filter(line => line.length > 0);
  },

  async hasChanges() {
    const changes = await this.status();
    return changes.length > 0;
  },

  async add(files = '.') {
    await execAsync(`git add ${files}`);
  },

  async commit(message) {
    await execAsync(`git commit -m "${message}"`);
  },

  async getCurrentBranch() {
    const { stdout } = await execAsync('git branch --show-current');
    return stdout.trim();
  },

  async stash(message) {
    await execAsync(`git stash push -m "${message}"`);
  }
};
```

### Phase 2: Commit Message Generation

**Smart commit messages based on task type:**

```javascript
function generateCommitMessage(task, options = {}) {
  const typeMap = {
    'supabase_migration': 'feat(db)',
    'supabase_rls': 'feat(security)',
    'component_creation': 'feat(ui)',
    'api_integration': 'feat(api)',
    'configuration': 'chore(config)',
    'testing': 'test',
    'bug_fix': 'fix',
    'documentation': 'docs',
    'styling': 'style',
    'refactoring': 'refactor'
  };

  const prefix = typeMap[task.type] || 'feat';
  const description = task.description;
  const taskRef = options.includeTaskId ? ` (${task.id})` : '';

  return `${prefix}: ${description}${taskRef}`;
}
```

### Phase 3: Interactive Mode

**When interactive mode is enabled:**

```
📝 Changed files:
   M src/app/dashboard/page.tsx
   A src/components/StatsCard.tsx
   M src/services/api.ts

💬 Suggested commit message:
   feat(ui): Create dashboard page component (task_001)

Options:
1. Use suggested message
2. Edit message
3. Skip commit
> 
```

### Phase 4: Safety Features

**Handle existing uncommitted changes:**

```javascript
async function handleExistingChanges(task) {
  const changes = await git.status();
  const taskFiles = await identifyTaskFiles(task);
  
  const unrelatedChanges = changes.filter(
    change => !taskFiles.includes(change.file)
  );

  if (unrelatedChanges.length > 0) {
    console.log('⚠️  Uncommitted changes detected:');
    unrelatedChanges.forEach(change => console.log(`   ${change}`));
    
    const choice = await prompt('1. Stash unrelated\n2. Commit all\n3. Cancel\n> ');
    
    if (choice === '1') {
      await git.stash(`Pre-task-${task.id}-changes`);
      console.log('✅ Unrelated changes stashed');
    }
  }
}
```

---

## 📦 Required Changes

### 1. Update `plan-project.js`

```javascript
// Add at the top
const git = require('./git-helpers');
const { generateCommitMessage } = require('./commit-utils');

// Modify the complete command handler
if (command === 'complete') {
  const taskId = process.argv[3];
  const options = parseOptions(process.argv.slice(4));
  
  await handleCompleteWithGit(taskId, options);
}
```

### 2. Update NPM Scripts

```json
{
  "scripts": {
    "plan:complete": "node scripts/execution/plan-project.js complete",
    "plan:config": "node scripts/execution/plan-project.js config"
  }
}
```

### 3. Add to ProjectPlanner

```javascript
// Track files created/modified per task
async updateProjectState(task, results = {}) {
  // Existing logic...
  
  // Track task files for git integration
  if (results.filesCreated || results.filesModified) {
    this.taskFiles[task.id] = {
      created: results.filesCreated || [],
      modified: results.filesModified || []
    };
  }
}
```

---

## 🚀 Usage Examples

### Scenario 1: Auto-commit Everything

```bash
# Enable auto-commit
npm run plan:config autoCommit true

# Work normally
npm run plan:continue
# ... implement with Claude ...

# Complete auto-commits
npm run plan:complete task_001
# ✅ Task completed and changes committed!
```

### Scenario 2: Custom Messages

```bash
npm run plan:complete task_001 --commit --message "feat(dashboard): Add responsive dashboard with charts

- Implemented StatsCard component
- Added Chart.js integration
- Responsive grid layout
- Real-time data updates"
```

### Scenario 3: Interactive Review

```bash
# Default interactive mode
npm run plan:complete task_001 --commit

# Shows changed files, suggests message, asks for confirmation
```

---

## 🔍 Edge Cases Handled

1. **No Git Repository**
   - Clear error: "Not a git repository. Initialize with 'git init'"

2. **No Changes**
   - Info message: "No changes to commit"

3. **Uncommitted Work**
   - Option to stash or include

4. **Failed Commit**
   - Show git error, mark task complete anyway

5. **Merge Conflicts**
   - Detect and warn before attempting commit

---

## 📈 Benefits

1. **Atomic Commits**: Each task = one commit
2. **Clean History**: Automatic conventional commits
3. **Time Saving**: No manual git commands
4. **Traceability**: Task IDs in commits
5. **Flexibility**: Manual override always available

---

## 🔄 Migration Path

### For Existing Users

1. **Update**: `npm update mirror-magi-meta-agent`
2. **Optional Config**: `npm run plan:config autoCommit true`
3. **Use Normally**: Existing workflows continue to work

### Backwards Compatibility

- Without `--commit` flag, behavior unchanged
- Old commands still work
- Preferences default to current behavior

---

## 📝 Documentation Updates Needed

1. Update `README.md` with new commands
2. Add examples to workflow guide
3. Create git integration guide
4. Update command reference

---

## 🎯 Next Steps

1. **Phase 1**: Implement core git helpers (1 day)
2. **Phase 2**: Add to plan-project.js (1 day)
3. **Phase 3**: Interactive mode (1 day)
4. **Phase 4**: Testing & edge cases (2 days)
5. **Phase 5**: Documentation (1 day)

Total: ~1 week to full implementation

---

## 💡 Future Enhancements

1. **Branch Management**
   ```bash
   npm run plan:start --branch feature/dashboard
   # Creates branch and starts plan
   ```

2. **PR Integration**
   ```bash
   npm run plan:finish
   # Pushes branch and opens PR
   ```

3. **Commit Templates**
   - Custom templates per task type
   - Multi-line commit messages
   - Automatic issue linking

4. **Git Hooks**
   - Pre-commit validation
   - Commit message formatting
   - Task completion verification 