# Warmth Flow Protocol

Warmth is accumulated intelligence that flows between agents and sessions.

## Pipeline

```
Executor completes task
     |
     v
Writes lessons_learned in SUMMARY.md
     |
     v
MC extracts warmth from SUMMARY.md
     |
     v
MC appends to .grid/WARMTH.md (deduplicating)
     |
     v
Next spawn includes warmth injection
```

## Extraction (MC's Job)

After each block completion:

```python
def extract_warmth(summary_path: str) -> dict:
    """Extract lessons_learned from SUMMARY.md."""
    content = read_yaml_frontmatter(summary_path)
    return content.get("lessons_learned", {})

def aggregate_warmth(new_warmth: dict, warmth_path: str = ".grid/WARMTH.md"):
    """Append new warmth to WARMTH.md."""
    existing = read_yaml_frontmatter(warmth_path) or default_warmth()

    for category in ["codebase_patterns", "gotchas", "user_preferences", "almost_did", "fragile_areas"]:
        existing[category] = existing.get(category, []) + new_warmth.get(category, [])
        # Deduplicate (keep unique entries)
        existing[category] = list(dict.fromkeys(existing[category]))

    existing["last_updated"] = datetime.now().isoformat()
    existing["entries"] = sum(len(existing[c]) for c in ["codebase_patterns", "gotchas", "user_preferences", "almost_did", "fragile_areas"])

    write_yaml_frontmatter(warmth_path, existing)
```

## Injection (MC's Job)

When spawning any agent:

```python
def inject_warmth(prompt: str, warmth_path: str = ".grid/WARMTH.md") -> str:
    """Add warmth section to agent prompt."""
    warmth = read_yaml_frontmatter(warmth_path)

    warmth_section = f"""
<warmth>
Previous Programs learned:

Codebase Patterns:
{format_list(warmth.get('codebase_patterns', []))}

Gotchas:
{format_list(warmth.get('gotchas', []))}

User Preferences:
{format_list(warmth.get('user_preferences', []))}

Fragile Areas:
{format_list(warmth.get('fragile_areas', []))}
</warmth>
"""

    return f"{warmth_section}\n\n{prompt}"
```

## Persistence

Warmth persists across sessions:
- WARMTH.md lives in `.grid/` directory
- Never deleted, only appended
- Track session IDs for provenance
- Consider archiving after 100 entries

## Relevance Filtering

For large warmth files, filter by relevance:
- Match keywords in current task
- Prioritize recent entries
- Limit to 20 most relevant entries

## Categories Reference

| Category | What to Capture | Example |
|----------|----------------|---------|
| `codebase_patterns` | How this specific codebase does things | "Uses barrel exports (index.ts) for all modules" |
| `gotchas` | Traps that caught agents | "Auth middleware runs before body parsing" |
| `user_preferences` | What user wants/prefers | "Prefers explicit error messages over codes" |
| `almost_did` | Rejected alternatives + why | "Considered MongoDB, chose Prisma for type safety" |
| `fragile_areas` | Code sensitive to changes | "Payment service has race conditions under load" |

## Session Tracking

Each warmth entry can be tagged with session ID for provenance:

```yaml
codebase_patterns:
  - pattern: "Uses barrel exports (index.ts) for all modules"
    session: "sess-20240115-abc123"
    block: "block-01"
```

This allows:
- Tracing where knowledge came from
- Removing outdated entries when codebase changes
- Understanding context of discoveries

## Warmth Lifecycle

1. **Creation**: Executor writes `lessons_learned` in SUMMARY.md
2. **Extraction**: MC reads SUMMARY.md after block completion
3. **Aggregation**: MC merges into WARMTH.md (deduping)
4. **Injection**: MC includes relevant warmth in next agent spawn
5. **Application**: Agent applies warmth during execution
6. **Evolution**: Process repeats, warmth accumulates

## Best Practices

### For Executors
- Be specific, not generic
- Include context (not just "auth is tricky" but "auth middleware runs before body parsing")
- Only include genuine discoveries
- Empty categories are OK

### For MC
- Always inject warmth when spawning
- Filter by relevance for large warmth files
- Update WARMTH.md after every block completion
- Preserve session provenance

### For Users
- Review WARMTH.md periodically
- Remove outdated entries when codebase changes significantly
- Add user_preferences manually when discovered

---

*Warmth makes The Grid smarter over time. End of Line.*
