# Memory (CLAUDE.md) - Grid Integration Analysis

## Executive Summary

Claude Code's memory system provides a **hierarchical, modular, persistent memory architecture** that The Grid can leverage to dramatically improve cross-session continuity, reduce context overhead, and enable project-specific rule enforcement. The key insight: **Grid state files could be elevated to first-class Claude Code memory**, automatically loaded and path-scoped.

### High-Impact Opportunities

1. **Path-Scoped Rules**: Grid agent behaviors can be enforced via `.claude/rules/` with path patterns
2. **Import System**: Reduce MC context bloat by 30-40% using `@import` for agent specifications
3. **Hierarchical Memory**: Grid learnings can persist at user-level, project patterns at project-level
4. **CLAUDE.local.md**: Perfect for per-user Grid preferences (model tier, budget limits)

---

## 1. CLAUDE.md Hierarchy Integration

### Current Grid State Architecture
```
.grid/
├── STATE.md           # Mission state
├── LEARNINGS.md       # Accumulated patterns
├── SCRATCHPAD.md      # Live discoveries
├── config.json        # Settings
└── phases/            # Execution plans
```

### Proposed Hybrid Architecture
```
Project/
├── .claude/
│   ├── CLAUDE.md           # Project memory (existing)
│   └── rules/
│       └── grid/           # Grid-specific rules
│           ├── agent-roles.md      # Agent identity enforcement
│           ├── spawn-patterns.md   # Delegation rules
│           └── verification.md     # Quality gate rules
├── .grid/                  # Runtime state (existing)
│   ├── STATE.md
│   ├── SCRATCHPAD.md
│   └── ...
└── CLAUDE.local.md         # Personal Grid prefs
```

### Benefits
- **Automatic Loading**: `.claude/rules/grid/*.md` loads automatically - no explicit read required
- **Separation of Concerns**: Rules (static) vs State (dynamic) clearly separated
- **Git-friendly**: Rules can be committed, state stays gitignored

---

## 2. Import System for Context Reduction

### Current Problem
MC loads large agent specification files via explicit `Read()` calls, consuming ~22% context just for instructions.

### Solution: @import Pattern

**In `.claude/rules/grid/mc-imports.md`:**
```markdown
# MC Context Imports

Core protocols: @~/.claude/docs/MC_PROTOCOLS.md
Agent specs: @~/.claude/agents/grid-planner.md @~/.claude/agents/grid-executor.md

Import only the role definitions, not full prompts.
```

**In agent prompt templates:**
```markdown
# Grid Planner Instructions

See @docs/grid-agent-roles.md for standard behaviors.

Specific task context follows:
...
```

### Expected Impact
- **30-40% context reduction** for MC initialization
- **Lazy loading**: Imports only resolve when files are accessed
- **Recursive depth (5 hops)**: Allows modular agent specs

### Implementation Approach
1. Create lean "role definition" files that agents import
2. Move protocol details to importable docs
3. Agent prompts become thin wrappers: role import + task context

---

## 3. Path-Scoped Rules for Grid

### Opportunity: Automatic Agent Behavior by File Type

Create rules that automatically apply when Grid agents work on specific file patterns.

**Example: `.claude/rules/grid/api-standards.md`**
```markdown
---
paths:
  - "src/api/**/*.ts"
  - "lib/routes/**/*.ts"
---

# API Development Standards (Grid-Enforced)

When Grid Executors modify API files:
- All endpoints MUST include input validation
- Error responses follow standard format
- OpenAPI comments required
- Tests in `__tests__/api/` directory
```

**Example: `.claude/rules/grid/test-patterns.md`**
```markdown
---
paths:
  - "**/*.test.ts"
  - "**/*.spec.ts"
---

# Test Standards (Grid-Enforced)

Grid Recognizer verification criteria:
- Minimum 80% coverage for touched files
- Integration tests for cross-module changes
- Mock external services, never real calls
```

### Benefits
- **Zero overhead**: Rules load only when relevant files touched
- **Self-documenting**: Team sees Grid enforcement rules in repo
- **Composable**: Different rules for frontend/backend/tests

---

## 4. Memory Persistence Strategy

### Cross-Session Grid Memory

**User-Level (`~/.claude/CLAUDE.md` or `~/.claude/rules/grid-preferences.md`):**
```markdown
# My Grid Preferences

## Model Tier
- Default: balanced (Sonnet)
- Override for: financial-app/* -> quality (Opus)

## Budget Defaults
- Warning threshold: $5
- Hard limit: $15

## Spawn Preferences
- Parallel agents max: 3
- Auto-verify: enabled
```

**Project-Level (`./CLAUDE.md` or `./.claude/CLAUDE.md`):**
```markdown
# Project Grid Configuration

## Architecture Patterns (Grid-learned)
- All services use dependency injection
- Config via environment variables
- Logs to structured JSON

## Codebase Gotchas (Grid-accumulated)
- `utils/date.ts` - Don't touch timezone handling
- `migrations/` - Run tests after ANY change
- `legacy/` - Read-only, wrap don't modify
```

### Implementation: Auto-promote Learnings

When Grid completes a mission with valuable learnings:

```python
# Pseudo-code for learning promotion
if mission.learnings.quality_score > 0.8:
    if learning.scope == "user_preference":
        append_to("~/.claude/rules/grid-preferences.md")
    elif learning.scope == "project_pattern":
        append_to("./.claude/CLAUDE.md")  # or .claude/rules/grid-project.md
```

---

## 5. Context Management Improvements

### Current Context Bloat Sources

| Source | Current Cost | With Memory System |
|--------|-------------|-------------------|
| MC instructions | ~22% | ~12% (imports) |
| Agent specs (inline) | ~15% per spawn | ~5% (import refs) |
| State files | ~5% | ~5% (unchanged) |
| Learnings | ~3% | ~1% (user-level) |
| **Total MC** | ~45% | ~23% |

### Recommended Changes

1. **Move static content to `.claude/rules/`**
   - Agent role definitions
   - Protocol specifications
   - Verification criteria

2. **Keep dynamic content in `.grid/`**
   - STATE.md (mission progress)
   - SCRATCHPAD.md (live findings)
   - Budget/cost tracking

3. **Use imports for agent spawning**
   - Instead of inlining 2000-line agent specs
   - Reference: `@~/.claude/agents/grid-executor.md`
   - Claude Code resolves at load time

### The Import Problem for Task()

**Critical Limitation**: `@imports` don't work across Task() boundaries. The spawned subagent doesn't inherit the parent's import resolution.

**Workaround**: Create a "spawn payload" pattern:
```markdown
# In .claude/rules/grid/spawn-patterns.md

## Executor Spawn Payload
When spawning an Executor, include:
1. Role definition (first 50 lines of grid-executor.md)
2. Current mission context (from STATE.md)
3. Specific task instructions

Never rely on @imports in Task() prompts.
```

---

## 6. Quick Wins (Implement Now)

### 6.1 Create `.claude/rules/grid/` Directory Structure

```bash
mkdir -p .claude/rules/grid
```

**Files to create:**

1. **`.claude/rules/grid/identity.md`** - MC identity enforcement
2. **`.claude/rules/grid/delegation.md`** - "MC never executes directly" rules
3. **`.claude/rules/grid/verification.md`** - Recognizer criteria

### 6.2 Add CLAUDE.local.md Template to `/grid:init`

When `/grid:init` runs, also create:
```markdown
# CLAUDE.local.md - Personal Grid Settings
# (This file is gitignored)

## My Grid Preferences
- Model tier: balanced
- Max budget: $10
- Verification: auto
```

### 6.3 Symlink Shared Rules

For teams:
```bash
ln -s ~/company-grid-rules .claude/rules/shared-grid
```

---

## 7. Architecture Changes (Longer Term)

### 7.1 STATE.md to YAML Frontmatter Standard

Current STATE.md mixes prose and data. Adopt Claude Code's frontmatter pattern:

```markdown
---
cluster: auth-api
session_id: "2026-01-23-abc123"
status: active
position:
  phase: 2
  block: 1
  wave: 3
progress_percent: 45
energy_remaining: 7500
---

# Mission State

## Current Position
Active Cluster: auth-api
Active Block: Phase 2 / Block 1 / Wave 3
...
```

**Benefit**: Parseable by tools, still human-readable.

### 7.2 Rules-Based Agent Behavior

Instead of complex conditionals in agent prompts, use rules:

**`.claude/rules/grid/executor-behavior.md`**
```markdown
---
paths:
  - ".grid/**/*"
---

# Executor File Handling

When an Executor modifies .grid/ files:
- Always update `updated` timestamp
- Never delete STATE.md
- Append to SCRATCHPAD.md, don't overwrite
```

### 7.3 Hierarchical Learnings

```
~/.claude/rules/
├── grid-universal-learnings.md    # Works everywhere
└── grid-preferences.md            # Personal defaults

./claude/rules/
├── grid/
│   ├── project-patterns.md        # This project's patterns
│   └── team-standards.md          # Team conventions
```

---

## 8. Specific Recommendations

### For MC (Master Control)

1. **Read `.claude/rules/grid/*` at startup** instead of hardcoding all rules in mc.md
2. **Use frontmatter in STATE.md** for machine-parseable state
3. **Reference protocols via import** in spawn prompts (with inline fallback)

### For Agents (Executors, Recognizers, etc.)

1. **Check `.claude/rules/` for path-specific rules** before modifying files
2. **Write learnings to SCRATCHPAD.md** with promotion hints
3. **Respect project CLAUDE.md** instructions (they're auto-loaded)

### For Users

1. **Use CLAUDE.local.md** for personal Grid preferences
2. **Add `.claude/rules/grid/` patterns** for project-specific enforcement
3. **Symlink shared rules** for team consistency

### For Grid Maintainers

1. **Ship default rules** in Grid installer
2. **Create rules template** in `/grid:init`
3. **Document rule patterns** in README

---

## 9. Migration Path

### Phase 1: Non-Breaking Additions (v1.7.x)
- Add `.claude/rules/grid/` support to `/grid:init`
- Create CLAUDE.local.md template
- Document import patterns

### Phase 2: Context Optimization (v1.7.x+)
- Refactor agent specs to support imports
- Move static protocols to `.claude/rules/`
- Implement learning promotion

### Phase 3: Full Integration (v1.7.x++)
- Path-scoped rule enforcement
- Automatic rule discovery
- Cross-project rule sharing

---

## 10. Risks and Mitigations

| Risk | Mitigation |
|------|------------|
| Import resolution across Task() | Document limitation, provide inline fallback |
| Rules bloat | Recommend focused, single-topic rules |
| Breaking existing workflows | All additions optional, backwards compatible |
| User confusion (too many files) | Clear docs, sensible defaults |

---

## Conclusion

Claude Code's memory system offers The Grid a powerful upgrade path:

1. **Immediate win**: Path-scoped rules for automatic behavior enforcement
2. **Medium-term**: Import system for 30-40% context reduction
3. **Long-term**: Hierarchical learnings that persist and improve over time

The key insight is treating `.claude/rules/grid/` as the **static configuration layer** while keeping `.grid/` as the **dynamic runtime layer**. This separation enables both git-friendly team sharing and efficient context management.

**Recommended First Step**: Add `.claude/rules/grid/` directory creation to `/grid:init` with three starter rules: identity, delegation, and verification.

---

*Analysis by Grid Enhancement Analyst | 2026-01-23*
