# GUARDRAILS.md - Ownership & Enforcement Rules

This document defines the ownership matrix, lock system, and enforcement mechanisms for multi-agent collaboration in this repository.

> **Collaboration Rules**: See [`AGENTS.md`](./AGENTS.md) for handoff protocols and code standards.

---

## 1. Ownership Matrix

### 1.1 Ownership Categories

| Category | Description | Override |
|----------|-------------|----------|
| **Primary** | Agent has exclusive authority | Claude can override |
| **Shared** | Multiple agents can modify, requires coordination | Claude approves changes |
| **Unrestricted** | Any agent can modify | No restrictions |

### 1.2 Claude Code - Primary Ownership

Claude Code is the lead agent with primary ownership of:

| Pattern | Description |
|---------|-------------|
| `CLAUDE.md` | Lead agent directive |
| `AGENTS.md` | Shared collaboration rules |
| `GUARDRAILS.md` | This file |
| `src/*/cli.py` | CLI entry points |
| `src/*/core/` | Core logic modules |
| `src/*/main.py` | Main entry points |

### 1.3 Gemini - Primary Ownership

Gemini has primary ownership of:

| Pattern | Description |
|---------|-------------|
| `GEMINI.md` | Gemini directive |
| `src/*/integrations/google/` | Google API integrations |
| `src/*/integrations/gsc.py` | Google Search Console |
| `src/*/integrations/ga*.py` | Google Analytics |
| `docs/` | Documentation (markdown) |

### 1.4 Codex - Primary Ownership

Codex has primary ownership of:

| Pattern | Description |
|---------|-------------|
| `CODEX.md` | Codex directive |
| `src/*/models.py` | Pydantic/data models |
| `src/*/utils/` | Utility functions |
| `tests/` | All test files |

### 1.5 Shared Files

These files require coordination (Claude approves):

| Pattern | Coordination Rule |
|---------|-------------------|
| `pyproject.toml` | Dependency changes require discussion |
| `config/*.yaml` | Configuration changes affect all agents |
| `.github/workflows/` | CI/CD changes impact everyone |
| `PROJECT_PLAN.md` | Roadmap changes need consensus |

### 1.6 Unrestricted Files

Any agent can modify these files:

| Pattern | Notes |
|---------|-------|
| `.agent-state/` | Task and lock management |
| `.gitignore` | Git configuration |
| `README.md` | Project readme |
| `.pre-commit-config.yaml` | Pre-commit hooks |

---

## 2. Lock System

### 2.1 Lock Types

| Type | Description | Use Case |
|------|-------------|----------|
| `exclusive` | Single agent can modify | Long-running refactors |
| `shared` | Multiple can read, one writes | Concurrent development |
| `override` | Claude override for conflicts | Emergency fixes |

### 2.2 Lock File Format

Location: `.agent-state/locks.yaml`

```yaml
version: "1.0"
updated_at: "2025-01-29T12:00:00Z"

locks:
  - path: "src/module/"
    agent: "claude"
    lock_type: "exclusive"
    task_id: "TASK-001"
    reason: "Refactoring core module"
    created_at: "2025-01-29T10:00:00Z"
    expires_at: "2025-01-29T14:00:00Z"

  - path: "docs/api/"
    agent: "gemini"
    lock_type: "shared"
    task_id: "TASK-002"
    reason: "Updating API documentation"
    created_at: "2025-01-29T11:00:00Z"
    expires_at: "2025-01-29T15:00:00Z"
```

### 2.3 Lock Operations

**Acquire Lock:**
1. Check if path is already locked
2. If locked by another agent, wait or request release
3. Add lock entry to locks.yaml
4. Set expiration time (default: 4 hours)

**Release Lock:**
1. Remove lock entry from locks.yaml
2. Update `updated_at` timestamp
3. Notify other agents if requested

**Lock Expiration:**
- Locks automatically expire at `expires_at` time
- Expired locks can be claimed by any agent
- Run `python tools/check-ownership.py --list-expired` to see expired locks

---

## 3. Task Claiming Protocol

### 3.1 Task File Format

Location: `.agent-state/tasks.yaml`

```yaml
version: "1.0"
updated_at: "2025-01-29T12:00:00Z"

tasks:
  - id: "TASK-001"
    description: "Implement new feature"
    agent: "claude"
    status: "in_progress"
    priority: "high"
    files:
      - "src/feature.py"
      - "tests/test_feature.py"
    created_at: "2025-01-29T09:00:00Z"
    claimed_at: "2025-01-29T09:30:00Z"
    expires_at: "2025-01-29T13:30:00Z"

  - id: "TASK-002"
    description: "Write API documentation"
    agent: "gemini"
    status: "pending"
    priority: "medium"
    files:
      - "docs/api.md"
    created_at: "2025-01-29T10:00:00Z"
```

### 3.2 Task Status Flow

```
pending → in_progress → completed
              ↓
          abandoned (if expired)
              ↓
          blocked (if dependency)
```

### 3.3 Claiming Process

1. **Check availability**: Verify task is `pending`
2. **Set identity**: Ensure `SEO_AGENT_AUTHOR` is set
3. **Claim task**: Update tasks.yaml with your agent name
4. **Acquire locks**: Lock files you'll modify
5. **Begin work**: Start implementation
6. **Complete task**: Mark as `completed`, release locks

### 3.4 Task Expiration

- Default timeout: 4 hours from `claimed_at`
- Expired tasks revert to `pending`
- Other agents can reclaim expired tasks

---

## 4. Environment Configuration

### 4.1 Required Environment Variable

```bash
# Set in shell profile or .envrc
export SEO_AGENT_AUTHOR=<agent_name>

# Valid values:
# - claude
# - gemini
# - codex
# - human
```

### 4.2 Verification

```bash
# Check current agent identity
echo $SEO_AGENT_AUTHOR

# Verify setup
python tools/check-ownership.py --verify-setup
```

---

## 5. Conflict Resolution

### 5.1 Resolution Hierarchy

| Conflict Type | Resolution |
|---------------|------------|
| Ownership dispute | Claude decides |
| Lock conflict | First to lock wins; Claude can override |
| Task overlap | Split tasks or assign to single agent |
| Merge conflict | Claude resolves |

### 5.2 Escalation Process

1. **Identify conflict**: Agent detects violation
2. **Document issue**: Add to escalation log
3. **Notify Claude**: Include conflict details
4. **Claude decides**: Makes binding decision
5. **Update rules**: Modify GUARDRAILS.md if pattern emerges

### 5.3 Claude Override

Claude can override any lock or ownership rule:

```yaml
# In locks.yaml
- path: "src/critical/"
  agent: "claude"
  lock_type: "override"
  task_id: "EMERGENCY-001"
  reason: "Critical bug fix"
  override_agent: "gemini"  # Agent whose lock was overridden
```

---

## 6. Verification Tools

### 6.1 check-ownership.py Commands

```bash
# Verify files before commit
python tools/check-ownership.py path/to/file.py

# Check commit message format
python tools/check-ownership.py --check-commit-msg

# Verify setup
python tools/check-ownership.py --verify-setup

# List expired locks/tasks
python tools/check-ownership.py --list-expired

# Validate state files
python tools/check-ownership.py --validate-state

# Strict mode (warnings as errors)
python tools/check-ownership.py --strict path/to/file.py
```

### 6.2 Pre-commit Integration

The following hooks run automatically:

| Hook | Stage | Purpose |
|------|-------|---------|
| `check-ownership` | commit | Verify file ownership |
| `check-commit-message` | commit-msg | Validate message format |

---

## 7. CI/CD Integration

### 7.1 GitHub Actions

Ownership checks run on PRs:

```yaml
# .github/workflows/ownership-check.yml
- Check changed files against ownership matrix
- Post violations as PR comments
- Block merge on violations
```

### 7.2 PR Labels

| Label | Meaning |
|-------|---------|
| `ownership-verified` | All files verified |
| `ownership-override` | Claude approved override |
| `ownership-violation` | Needs resolution |

---

## 8. Quick Reference

### Commands

```bash
# Set identity
export SEO_AGENT_AUTHOR=claude

# Check ownership
python tools/check-ownership.py src/file.py

# List expired
python tools/check-ownership.py --list-expired

# Validate state
python tools/check-ownership.py --validate-state
```

### Commit Format

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

[Claude] feat(core): implement new feature
[Gemini] docs(api): update API documentation
[Codex] test(models): add model tests
```

### File Locations

| File | Purpose |
|------|---------|
| `.agent-state/tasks.yaml` | Task registry |
| `.agent-state/locks.yaml` | Lock registry |
| `tools/check-ownership.py` | Verification script |

---

*This document defines the enforcement rules for multi-agent collaboration. Claude Code is the authoritative source for conflict resolution.*

*Last updated: [DATE]*
