# ZERG Git (Details)

Detailed reference for all 14 git actions, their workflows, and advanced usage.

## Action: commit

Intelligent commit with auto-generated conventional commit messages.

### Modes

| Mode | Behavior |
|------|----------|
| (default) | Inline: stage -> analyze -> suggest message -> prompt -> commit |
| auto | Engine: stage all -> analyze diff -> generate message -> commit |
| confirm | Engine: analyze -> generate message -> wait for confirmation |
| suggest | Engine: analyze -> generate message -> print suggestion only |

### Conventional Commit Types

| Type | Triggers |
|------|----------|
| feat | add, implement, create, new, feature |
| fix | fix, bugfix, resolve, correct, patch |
| docs | doc, readme, comment, documentation |
| style | format, style, lint, whitespace, prettier |
| refactor | refactor, restructure, reorganize, cleanup |
| test | test, spec, coverage |
| chore | chore, build, ci, deps, bump, update dep |

### Examples

```bash
# Default interactive commit
/zerg:git --action commit --push

# Engine-driven auto commit
/zerg:git --action commit --mode auto --push

# Suggest only (no commit)
/zerg:git --action commit --mode suggest
```

---

## Action: branch

Create and list branches.

### Examples

```bash
# List all branches
/zerg:git --action branch

# Create a new branch from main
/zerg:git --action branch --name feature/auth --base main
```

---

## Action: merge

Merge with configurable strategy and conflict detection.

### Strategies

| Strategy | Behavior |
|----------|----------|
| squash | Squash all commits into one (default) |
| rebase | Rebase current branch onto target |
| merge | Standard merge commit |

### Examples

```bash
# Squash merge feature branch
/zerg:git --action merge --branch feature/auth --strategy squash

# Rebase onto feature
/zerg:git --action merge --branch feature/auth --strategy rebase
```

---

## Action: sync

Fetch from remote, pull with rebase, and optionally rebase onto base branch.

### Examples

```bash
# Sync current branch with main
/zerg:git --action sync --base main
```

---

## Action: history

View recent commit history or run cleanup via HistoryEngine.

### Examples

```bash
# Show last 20 commits
/zerg:git --action history

# Show commits since a tag
/zerg:git --action history --since v1.0.0

# Run history cleanup (HistoryEngine)
/zerg:git --action history --cleanup --base main
```

---

## Action: finish

Interactive workflow to complete a feature branch. Presents four options:

1. **merge** -- Squash merge into base, optionally push and delete branch
2. **pr** -- Push branch and prompt for manual PR creation
3. **keep** -- Push branch only
4. **discard** -- Delete branch and discard changes

### Examples

```bash
# Finish current branch into main
/zerg:git --action finish --base main

# Finish with auto-push
/zerg:git --action finish --base main --push
```

---

## Action: pr

Create a pull request with full context assembly via PREngine.

The engine:
1. Assembles context from commits, issues, and project files
2. Generates structured PR title, body, labels, and reviewers
3. Creates PR via `gh` CLI

### PR Body Template

**IMPORTANT**: When the PR addresses GitHub issues, use closing keywords that trigger auto-close on merge:
- `Fixes #123` — for bug fixes
- `Closes #123` — for feature completions
- `Resolves #123` — general resolution

Do NOT use phrases like "addresses", "related to", or "for issue" — these do NOT auto-close issues.

```markdown
## Summary
Fixes #<issue_number>  <!-- REQUIRED if PR addresses an issue -->

<auto-generated from commits and context>

## Changes
- <bullet points from commit analysis>

## Test Plan
- <extracted from commit messages and changed files>
```

### Examples

```bash
# Create PR against main
/zerg:git --action pr --base main

# Create draft PR with reviewer
/zerg:git --action pr --draft --reviewer octocat

# PR against develop branch
/zerg:git --action pr --base develop
```

---

## Action: release

Automated semver release workflow via ReleaseEngine.

### Workflow Steps

1. Get latest version from tags
2. Analyze commits since last tag
3. Calculate version bump (or use override)
4. Generate changelog entry
5. Update version files
6. Commit, tag, and push
7. Create GitHub release

### Bump Types

| Type | When |
|------|------|
| auto | Calculated from conventional commits (default) |
| major | Breaking changes (BREAKING CHANGE in commits) |
| minor | New features (feat: commits) |
| patch | Bug fixes (fix: commits) |

### Examples

```bash
# Auto-detect bump from commits
/zerg:git --action release

# Force minor bump
/zerg:git --action release --bump minor

# Dry run to preview
/zerg:git --action release --dry-run

# Force patch release
/zerg:git --action release --bump patch
```

---

## Action: review

Pre-review context assembly via PreReviewEngine. Generates a structured review context document for the current branch.

### Focus Domains

| Domain | What It Highlights |
|--------|-------------------|
| security | Auth, input validation, secrets, injection vectors |
| performance | Algorithmic complexity, I/O patterns, caching |
| quality | Test coverage, error handling, code organization |
| architecture | Coupling, cohesion, dependency patterns, SOLID |

### Examples

```bash
# General review context
/zerg:git --action review --base main

# Security-focused review
/zerg:git --action review --focus security

# Architecture review
/zerg:git --action review --focus architecture --base develop
```

---

## Action: rescue

Recovery operations via RescueEngine. Provides undo, snapshot restore, and branch recovery.

### Sub-commands

| Flag | Operation |
|------|-----------|
| --list-ops | List recent git operations with timestamps |
| --undo | Undo the last recorded operation |
| --restore TAG | Restore repository state from a snapshot tag |
| --recover-branch NAME | Recover a deleted branch from reflog |

### Examples

```bash
# List recent operations
/zerg:git --action rescue --list-ops

# Undo last operation
/zerg:git --action rescue --undo

# Restore from snapshot
/zerg:git --action rescue --restore zerg-snapshot-20260201

# Recover deleted branch
/zerg:git --action rescue --recover-branch feature/auth
```

---

## Action: bisect

AI-powered binary search for bug-introducing commits via BisectEngine.

### Workflow

1. Specify symptom description and optional test command
2. Engine identifies good/bad commit range
3. Binary search narrows down the offending commit
4. Reports the commit that introduced the bug

### Examples

```bash
# Bisect with symptom and test command
/zerg:git --action bisect --symptom "login returns 500" --test-cmd "pytest tests/auth/"

# Bisect with known good commit
/zerg:git --action bisect --symptom "CSS broken" --good v1.2.0

# Bisect with all options
/zerg:git --action bisect --symptom "memory leak" --test-cmd "python bench.py" --good abc123 --base main
```

---

## Action: ship

**Full delivery pipeline**: commit → push → create PR → merge PR → cleanup branch.

Non-interactive by default. Uses `mode=auto` for commit generation.

### Pre-flight: Feature Detection

Before executing the ship pipeline, detect the active ZERG feature:

```bash
FEATURE=${ZERG_FEATURE:-$(cat .gsd/.current-feature 2>/dev/null)}
```

This checks the `ZERG_FEATURE` environment variable first, falling back to the `.gsd/.current-feature` file. The result determines whether feature-scoped shipping applies.

### Feature-Scoped Ship

When `FEATURE` is set (ZERG multi-epic workflow):

- **Source branch**: current branch or `zerg/$FEATURE/base` (the feature integration branch)
- **Target**: main (or `--base` override)
- **Scope commits**: only include commits from `zerg/$FEATURE/*` branches
- **PR title format**: `feat($FEATURE): $SUMMARY`
- **PR body**: includes the feature name, task summary, and references to feature-scoped work
- **Branch detection**: if an integration branch exists (e.g., `zerg/$FEATURE/base` or `zerg/$FEATURE/main`), use it as the source branch for the PR instead of the current working branch

When `FEATURE` is **not** set (standard non-ZERG workflow):

- Ship works exactly as before — no scoping, no title prefix, no branch detection changes
- Full backward compatibility with existing behavior

```bash
# Ship current branch to main
/zerg:git --action ship

# Ship with draft PR and reviewer
/zerg:git --action ship --draft --reviewer octocat

# Ship but stop after PR creation (for team review)
/zerg:git --action ship --no-merge

# Ship to a different base branch
/zerg:git --action ship --base develop

# Ship with admin merge (repo owner bypassing branch protection)
/zerg:git --action ship --admin

# Ship a feature-scoped branch (auto-detected via ZERG_FEATURE or .gsd/.current-feature)
/zerg:git --action ship
# → PR title: "feat(user-auth): Add authentication system"
# → Source: zerg/user-auth/base → Target: main
```

**Pipeline steps:**

1. **Feature detection** — Run `FEATURE=${ZERG_FEATURE:-$(cat .gsd/.current-feature 2>/dev/null)}`. If FEATURE is set, apply feature-scoped behavior for subsequent steps.
2. **Commit** — Stage all changes, auto-generate conventional commit message, commit
3. **CHANGELOG check** — Run `git diff {base}...HEAD -- CHANGELOG.md`. If no changes found, use AskUserQuestion to warn:
   - question: "CHANGELOG.md has no changes. PRs without CHANGELOG updates will fail CI."
   - header: "CHANGELOG"
   - options:
     - label: "Add CHANGELOG entry now (Recommended)"
       description: "Stop and add an entry under [Unreleased] before pushing"
     - label: "Continue without CHANGELOG"
       description: "Push anyway — use skip-changelog label on the PR if intentional"
   - If user picks "Add CHANGELOG entry now", stop the pipeline and instruct them to edit CHANGELOG.md, then re-run `/zerg:git --action ship`
   - If user picks "Continue without CHANGELOG", proceed to step 4
4. **Push** — Push branch to remote with `--set-upstream`. If FEATURE is set and the integration branch `zerg/$FEATURE/base` exists, push that branch.
5. **Create PR** — Create pull request via `gh pr create` with full context. If FEATURE is set: use `feat($FEATURE): $SUMMARY` as the PR title; include feature name and task summary in the PR body; scope the diff to only commits from `zerg/$FEATURE/*` branches.
6. **Merge** — Merge PR via `gh pr merge --squash` (falls back to `--admin` if blocked; with `--admin` flag, uses admin merge directly)
7. **Cleanup** — Switch to base, pull latest, delete feature branch (local + remote). If FEATURE is set, also clean up `zerg/$FEATURE/*` branches that were merged.

If `--no-merge` is set, stops after step 5. If any step fails, the pipeline stops and reports the failure point.

---

## Action: cleanup

**Repository hygiene**: prune merged branches, stale remote refs, orphaned worktrees, and ZERG Docker resources.

Auto-detects and removes stopped ZERG Docker containers and dangling images. Use `--no-docker` to skip Docker cleanup. Use `--include-stashes` to also clear git stashes (off by default). Use `--dry-run` to preview what would be deleted.

```bash
# Preview what would be cleaned
/zerg:git --action cleanup --dry-run

# Full cleanup (includes Docker auto-detect)
/zerg:git --action cleanup

# Skip Docker cleanup
/zerg:git --action cleanup --no-docker

# Include stash clearing
/zerg:git --action cleanup --include-stashes

# Cleanup against a different base branch
/zerg:git --action cleanup --base develop
```

**What gets cleaned:**

1. **Merged local branches** — Delete branches already merged into base (skip main/master/current)
2. **Stale remote refs** — `git remote prune origin`
3. **Orphaned worktrees** — `git worktree prune` + remove orphaned `.zerg-worktrees/` directories
4. **Docker containers** — Auto-detect stopped `factory-worker-*` containers and remove
5. **Docker images** — Auto-detect dangling ZERG images and remove
6. **Stashes** — Only with `--include-stashes` flag

**Output format:**

```
Git Cleanup Summary:
  Local branches deleted:    3  (feature/auth, feature/old, fix/typo)
  Remote refs pruned:        2  (origin/feature/auth, origin/fix/typo)
  Worktrees removed:         1  (.zerg-worktrees/old-feature/worker-0)
  Docker containers removed: 2  (factory-worker-0, factory-worker-1)
  Docker images removed:     0
  Stashes cleared:           0  (use --include-stashes to clear)
```

---

## Action: issue

**Create maximally-detailed GitHub issues** optimized for AI coding assistants. Zero ambiguity — every issue contains enough context for Claude Code or similar tools to implement the fix without guessing.

### Two Modes

**Scan mode** (default when no `--title`):

Scans the codebase for problems across ALL of these sources:
- **Test failures**: Parse most recent pytest/jest output
- **TODO/FIXME/HACK comments**: Search source code for deferred work
- **Lint/type errors**: Run ruff, mypy, eslint, tsc and parse output
- **Security findings**: Evaluate against ZERG security rules
- **Orphaned modules**: Detect modules with no production callers (via `validate_commands`)
- **Stale dependencies**: Check for outdated or vulnerable packages
- **CI pipeline results**: Parse most recent `gh run` output for failures

Groups related findings into logical issues. Creates one issue per distinct problem.

```bash
# Auto-scan and create issues (default)
/zerg:git --action issue

# Preview without creating
/zerg:git --action issue --dry-run

# Limit to 5 issues
/zerg:git --action issue --limit 5

# Only critical issues
/zerg:git --action issue --priority P0

# Add labels
/zerg:git --action issue --label bug --label tech-debt
```

**Description mode** (when `--title` is provided):

Takes a title and description from the user, enriches with codebase analysis (finds relevant files, traces code paths, identifies root cause candidates), and creates a single detailed issue.

```bash
# Create issue from description
/zerg:git --action issue --title "Fix auth timeout" "Users report 504 errors after 30s on login"

# Create as draft with label
/zerg:git --action issue --title "Add rate limiting" "API has no rate limits" --label enhancement
```

### Issue Body Template (Strict)

Every issue created by this action MUST follow this template. No exceptions. The template is designed so an AI coding assistant has zero chance of misinterpreting the intent.

```markdown
## Problem Statement
{2-3 sentences. What is broken/missing and who is affected. Be specific.}

## Root Cause Analysis
{Why this problem exists. Technical explanation with evidence from codebase analysis.}

## Affected Files
{Exhaustive list with line numbers.}

| File | Lines | Role |
|------|-------|------|
| `path/to/file.py` | 45-67 | Contains the buggy function |
| `path/to/other.py` | 12 | Caller that triggers the issue |

## Reproduction Steps
1. {Step 1 with exact command}
2. {Step 2}
3. {Observe: expected vs actual behavior}

## Proposed Solution
{Concrete implementation plan. Specific changes to specific files. Not vague.}

### Changes Required
- **`path/to/file.py`**: {What to change and why}
- **`path/to/other.py`**: {What to change and why}

### Code Sketch
\`\`\`python
# Before (problematic)
def buggy_function():
    ...

# After (fixed)
def fixed_function():
    ...
\`\`\`

## Acceptance Criteria
- [ ] {Criterion with verification command}
  \`\`\`bash
  pytest tests/unit/test_auth.py -v  # must pass
  \`\`\`
- [ ] {Criterion 2}
- [ ] All existing tests pass: `pytest tests/ -v`

## Dependencies
- Blocked by: {issue numbers or "none"}
- Blocks: {issue numbers or "none"}
- Related: {issue numbers}

## Context for AI Assistants
- **Codebase patterns**: {Relevant patterns this fix should follow}
- **Test expectations**: {What tests exist, what new tests are needed}
- **Security considerations**: {OWASP/security implications if any}
```

---

## Error Handling

All actions follow a consistent error pattern:

- **GitError**: Caught and reported with context
- **MergeConflictError**: Reports conflicting files and exits with code 1
- **KeyboardInterrupt**: Exits with code 130
- **General exceptions**: Logged and reported

## Help

When `--help` is passed, display usage and exit:

```
/zerg:git -- Git operations with intelligent commits, PR creation, releases, and more.

Flags:
  --action, -a ACTION   commit|branch|merge|sync|history|finish|pr|release|review|rescue|bisect|ship|cleanup|issue
  --push, -p            Push after operation
  --base, -b BRANCH     Base branch (default: main)
  --name, -n NAME       Branch name (for branch action)
  --branch BRANCH       Branch to merge (for merge action)
  --strategy STRATEGY   merge|squash|rebase (default: squash)
  --since TAG           Starting point (for history action)
  --mode MODE           auto|confirm|suggest (commit mode)
  --cleanup             Run history cleanup
  --draft               Create draft PR
  --reviewer USER       PR reviewer username
  --focus DOMAIN        security|performance|quality|architecture
  --bump TYPE           auto|major|minor|patch (default: auto)
  --dry-run             Preview without executing (release, cleanup, issue)
  --symptom TEXT        Bug symptom (for bisect)
  --test-cmd CMD        Test command (for bisect)
  --good REF            Known good ref (for bisect)
  --list-ops            List rescue operations
  --undo                Undo last operation (rescue)
  --restore TAG         Restore snapshot (rescue)
  --recover-branch NAME Recover branch (rescue)
  --no-merge            Stop after PR creation (skip merge+cleanup)
  --admin               Use admin merge directly (repo owner/admin, for ship)
  --scan                Auto-detect issues from codebase (issue action)
  --title TEXT          Issue title (issue action, description mode)
  --no-docker           Skip Docker cleanup (cleanup action)
  --include-stashes     Clear git stashes (cleanup action)
  --limit N             Max issues to create (issue action, default: 10)
  --label LABEL         Add label to issues (issue action)
  --priority P          Filter by priority: P0|P1|P2 (issue action)
  --help                Show this help message
```
