# AGENTS.md - Common Ground Rules & Collaboration Protocols

This file defines the shared rules, handoff protocols, and guidelines for all AI agents working on this repository.

> **Master Plan Reference**: For strategic decisions, roadmap, and feature priorities, consult [`PROJECT_PLAN.md`](./PROJECT_PLAN.md) if available.

> **Enforcement Layer**: For ownership rules, task claiming, and conflict resolution, see [`GUARDRAILS.md`](./GUARDRAILS.md).

## Agent Hierarchy

| Agent | Role | Authority | Context File |
|-------|------|-----------|--------------|
| **Claude Code** | Lead / Orchestrator | Architecture, core logic, final decisions | `CLAUDE.md` |
| **Gemini** | Sub-agent | Google APIs, documentation, research | `GEMINI.md` |
| **Codex** | Sub-agent | Tests, boilerplate, docstrings | `CODEX.md` |
| **Human** | Supervisor | Final approval, business decisions | N/A |

**All agents read this file (`AGENTS.md`) as the shared source of truth.**

---

## 1. Project Status

<!-- Customize this section for your project -->

| Aspect | Status | Notes |
|--------|--------|-------|
| **Stage** | [Development/Beta/Production] | |
| **Primary Language** | [Python/TypeScript/etc.] | |
| **Test Coverage** | [X%] | Target: 80% |
| **Documentation** | [Status] | See `docs/` directory |

---

## 2. Handoff Protocols

### 2.1 Claude → Gemini Handoff

**When to delegate:**
- Google API implementation (GSC, GA4, PageSpeed, etc.)
- Documentation writing (user guides, tutorials)
- Research on best practices or algorithm updates
- Content quality assessment logic

**Handoff format:**
```markdown
## Task for Gemini

**Type:** [Google API | Documentation | Research]
**Priority:** [High | Medium | Low]

### Objective
[Clear description of what needs to be done]

### Interface/Contract (if API)
```python
# Claude defines the interface
class SomeProtocol(Protocol):
    async def method(...) -> SomeResponse:
        ...
```

### Deliverables
- [ ] Implementation file(s)
- [ ] Unit tests (optional, Codex can assist)
- [ ] Documentation updates

### Constraints
- Follow code style in AGENTS.md Section 4
- Use existing patterns from the codebase
```

**Return protocol:**
Gemini returns completed code → Claude reviews → Claude integrates.

---

### 2.2 Claude → Codex Handoff

**When to delegate:**
- Unit test generation from existing code
- Boilerplate Pydantic/dataclass models
- Docstring generation
- Repetitive pattern implementation

**Handoff format:**
```markdown
## Task for Codex

**Type:** [Tests | Models | Docstrings | Boilerplate]

### Pattern to Follow
```python
# Claude provides the first example
class ExampleClass(BaseClass):
    def method(self, arg: str) -> Result:
        ...
```

### Generate
- [ ] SimilarClass1 (same pattern)
- [ ] SimilarClass2 (same pattern)
- [ ] Tests for all classes
```

**Return protocol:**
Codex generates → Claude reviews for edge cases → Claude commits.

---

### 2.3 Sub-agent → Claude Escalation

**When to escalate back:**
- Complex error handling needed
- Multi-file integration required
- Architectural decisions needed
- Rate limiting / caching strategy

**Escalation format:**
```markdown
## Escalation to Claude

**Reason:** [Complexity | Architecture | Integration]

### Completed Work
[What was finished]

### Blocking Issue
[What requires Claude's decision]

### Proposed Options
1. Option A: ...
2. Option B: ...
```

---

## 3. Development Workflow

> **Task Claiming**: Before starting work, claim your task in `.agent-state/tasks.yaml`.
> See [`GUARDRAILS.md`](./GUARDRAILS.md) for the full claiming protocol.

### Phase 1: Planning (Claude Lead)

```
User Request → Claude analyzes
                  ↓
            Claude creates task breakdown
                  ↓
            Claude assigns to agents
                  ↓
            Claude defines interfaces
```

### Phase 2: Implementation (Parallel)

```
┌─────────────┬─────────────┬─────────────┐
│   Claude    │   Gemini    │   Codex     │
├─────────────┼─────────────┼─────────────┤
│ Core logic  │ Google APIs │ Tests       │
│ Complex     │ Docs        │ Models      │
│ Integration │ Research    │ Docstrings  │
└─────────────┴─────────────┴─────────────┘
```

**Before modifying files:**
1. Set `SEO_AGENT_AUTHOR` environment variable
2. Check `.agent-state/locks.yaml` for active locks
3. Claim task in `.agent-state/tasks.yaml`

### Phase 3: Review & Merge (Claude Lead)

```
Sub-agent work → Claude reviews
                     ↓
              Claude integrates
                     ↓
              Claude runs full test suite
                     ↓
              Claude commits with attribution
```

---

## 4. Code Style Guidelines

### 4.1 Python Conventions

| Rule | Standard |
|------|----------|
| Line length | 100 characters |
| Formatter | Black |
| Import sorter | isort (Black profile) |
| Linter | flake8 |
| Type checker | mypy |
| Docstrings | Google-style |

### 4.2 Import Organization

```python
# Standard library
import asyncio
import logging
from typing import Dict, List, Optional

# Third-party
import aiohttp
from pydantic import BaseModel

# Local
from mypackage.models import MyModel
from mypackage.utils import helper_function
```

### 4.3 Error Handling Pattern

```python
try:
    result = await some_operation(arg)
except SpecificError as e:
    logger.warning(f"Specific error: {e}")
    return None
except GeneralError:
    logger.exception("Unexpected error")
    raise
```

---

## 5. Commit & PR Standards

### 5.1 Commit Message Format

```
[Agent] type(scope): description

Body explaining the change (optional)

Co-Authored-By: Claude <noreply@anthropic.com>
```

**Types:** `feat`, `fix`, `docs`, `test`, `refactor`, `chore`

**Agent tags:** `[Claude]`, `[Gemini]`, `[Codex]`, `[Human]`, `[CI]`

### 5.2 Examples

```bash
[Claude] feat(core): implement new feature
[Gemini] docs(api): add API documentation
[Codex] test(models): add unit tests for models
[Human] fix(config): update configuration
```

### 5.3 PR Checklist

```markdown
## Pre-Merge Checklist

- [ ] Tests pass
- [ ] Code quality passes (formatter, linter, type checker)
- [ ] No hardcoded secrets
- [ ] Error handling implemented
- [ ] Logging added for debugging
- [ ] Documentation updated
- [ ] Agent attribution in commit messages
```

---

## 6. Quality Assurance

### 6.1 Review Matrix

| Review Type | Reviewer | Focus |
|-------------|----------|-------|
| Architecture | Claude | Design patterns, scalability |
| Logic correctness | Claude | Edge cases, error handling |
| Google API usage | Gemini | Best practices, quotas |
| Code style | Linter | Consistency |
| Documentation | Gemini | Clarity, completeness |
| Test coverage | Claude + Codex | Coverage, edge cases |

### 6.2 Testing Standards

```bash
# Minimum requirements before merge
pytest --cov=src --cov-fail-under=70

# For critical modules
pytest --cov=src/critical_module --cov-fail-under=80
```

---

## 7. Quick Reference Commands

```bash
# Quality checks
black src tests && isort src tests && flake8 src tests && mypy src tests

# Testing
pytest                              # All tests
pytest tests/test_file.py -v        # Single file
pytest -k "pattern" -v              # Pattern match
pytest --cov=src --cov-report=html  # Coverage report
```

---

## 8. References

### Internal Documents

| Document | Purpose |
|----------|---------|
| [`GUARDRAILS.md`](./GUARDRAILS.md) | Ownership, locks, conflict resolution |
| [`CLAUDE.md`](./CLAUDE.md) | Lead agent directive |
| [`GEMINI.md`](./GEMINI.md) | Gemini sub-agent directive |
| [`CODEX.md`](./CODEX.md) | Codex sub-agent directive |

---

*This document is the shared source of truth for all AI agents. Claude Code maintains and updates this file.*

*Last updated: [DATE]*
