# Settings Analysis: Grid Enhancement Opportunities

## Executive Summary

Claude Code's settings system provides a sophisticated multi-layer configuration architecture that The Grid can leverage for deeper integration, enterprise deployment, and enhanced user experience. The key insight: **Claude Code already has the infrastructure for hierarchical settings, permission control, and environment variables - The Grid should align with these patterns rather than reinvent them.**

Current Grid configuration (`.grid/config.json`, `.grid/budget.json`) operates in isolation. By integrating with Claude Code's settings hierarchy, The Grid gains:
- Enterprise-friendly managed settings deployment
- User-level Grid preferences across all projects
- Project-level Grid configuration sharable with teams
- Environment variable control for CI/CD and automation

---

## 1. Settings Hierarchy Integration

### Current State

The Grid uses:
- `.grid/config.json` - Project-specific Grid settings (not aligned with Claude Code's `.claude/` convention)
- `.grid/budget.json` - Cost tracking (isolated from Claude Code)
- `~/.claude/CLAUDE.md` - User instructions (leveraged correctly)

### Claude Code's Hierarchy

| Scope | Location | Who it affects | Shared? |
|-------|----------|----------------|---------|
| Managed | `/Library/Application Support/ClaudeCode/` | All users on machine | IT deployed |
| User | `~/.claude/settings.json` | User across all projects | No |
| Project | `.claude/settings.json` | Team collaborators | Yes (git) |
| Local | `.claude/settings.local.json` | User in this project | No (gitignored) |

### Opportunity: Native Grid Settings Section

**Recommendation:** Add Grid configuration as a section within Claude Code's settings files instead of separate `.grid/` files.

```json
// ~/.claude/settings.json (User level)
{
  "permissions": { ... },
  "grid": {
    "defaultModelTier": "quality",
    "autoVerify": true,
    "budgetLimit": null,
    "scratchpadHeartbeatMinutes": 5,
    "notifications": {
      "system": true,
      "sound": true
    }
  }
}
```

```json
// .claude/settings.json (Project level - sharable)
{
  "grid": {
    "modelTier": "balanced",
    "budgetLimit": 100.00,
    "autoVerify": true
  }
}
```

```json
// .claude/settings.local.json (Personal overrides - gitignored)
{
  "grid": {
    "budgetLimit": null,
    "modelTier": "quality"
  }
}
```

### Implementation Impact

- Grid inherits Claude Code's merging logic (managed > local > project > user)
- Teams can share Grid configuration via `.claude/settings.json`
- Users can override with `.claude/settings.local.json`
- Enterprises can enforce Grid policies via managed settings

---

## 2. Permission Rules for Grid Operations

### Current State

Grid has no permission integration with Claude Code. All Grid operations run with whatever permissions the user has.

### Opportunity: Grid-Specific Permissions

Claude Code's permission syntax supports tool-level control:

```json
{
  "permissions": {
    "allow": [
      "Skill(grid:*)",           // Allow all Grid commands
      "Task(grid-*)"             // Allow Grid subagents
    ],
    "deny": [
      "Skill(grid:daemon)",      // Deny daemon mode
      "Task(grid-executor-*)"    // Deny executor spawns
    ]
  }
}
```

### Permission Patterns for Grid

| Pattern | Effect |
|---------|--------|
| `Skill(grid:*)` | Allow all Grid commands |
| `Skill(grid:mc)` | Allow only Master Control |
| `Skill(grid:daemon)` | Allow/deny daemon mode |
| `Skill(grid:budget)` | Allow/deny budget management |
| `Task(grid-planner)` | Control planner spawns |
| `Task(grid-executor-*)` | Control all executor spawns |
| `Task(grid-*)` | Control all Grid subagents |

### Enterprise Use Cases

1. **Read-Only Grid**: Allow `/grid:status` but deny `/grid`, `/grid:mc`
2. **No Daemon Mode**: Deny `Skill(grid:daemon)` for security
3. **Limited Spawns**: Deny `Task(grid-executor-*)` to control costs
4. **Audit Mode**: Allow read operations, deny all spawns

### Implementation

Grid commands should check permissions before executing:

```python
def check_grid_permission(operation):
    """Check if operation is allowed by Claude Code settings."""
    # Claude Code handles this automatically for Skill/Task tools
    # Grid just needs to use standard tool names
    pass
```

---

## 3. Environment Variables for Grid

### Current State

Grid reads from `.grid/config.json` only. No environment variable support.

### Relevant Claude Code Environment Variables

| Variable | Grid Relevance |
|----------|---------------|
| `ANTHROPIC_MODEL` | Could set Grid's default model |
| `CLAUDE_CODE_SUBAGENT_MODEL` | **Critical** - affects all Grid spawns |
| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | Affects Grid's long-running operations |
| `DISABLE_PROMPT_CACHING_*` | Affects Grid costs |

### New Grid-Specific Environment Variables

Propose these Grid-specific variables:

| Variable | Purpose | Default |
|----------|---------|---------|
| `GRID_MODEL_TIER` | Override model tier | (from config) |
| `GRID_BUDGET_LIMIT` | Override budget limit | null |
| `GRID_AUTO_VERIFY` | Enable/disable auto-verify | true |
| `GRID_DAEMON_ENABLED` | Allow daemon mode | true |
| `GRID_MAX_SPAWNS` | Max concurrent spawns | unlimited |
| `GRID_NOTIFICATIONS` | Enable notifications | true |

### CI/CD Integration Example

```bash
# GitHub Actions workflow
env:
  GRID_MODEL_TIER: budget
  GRID_BUDGET_LIMIT: 10.00
  GRID_AUTO_VERIFY: true
  GRID_DAEMON_ENABLED: false

steps:
  - name: Run Grid tests
    run: claude -p "/grid:quick run all tests"
```

### Priority Order

```
1. Environment variables (highest - for CI/CD)
2. Local settings (.claude/settings.local.json)
3. Project settings (.claude/settings.json)
4. User settings (~/.claude/settings.json)
5. Managed settings (lowest but overrides all for enterprise)
```

---

## 4. Tool Configuration Alignment

### Claude Code's Available Tools

Grid currently uses:
- `Task` - For spawning subagents
- `Skill` - For invoking Grid commands
- `Read/Write/Edit` - File operations
- `Bash` - Shell commands
- `Glob/Grep` - Search

### Permission Configuration for Grid Tools

```json
{
  "permissions": {
    "allow": [
      "Task(grid-*)",              // Grid agents
      "Bash(git:*)",               // Git operations
      "Bash(npm:*)",               // Package management
      "Read",                       // File reading
      "Write(.grid/*)",            // Grid state files
      "Edit"                        // Code editing
    ],
    "deny": [
      "Bash(rm -rf:*)",            // Destructive operations
      "Write(.env*)"               // Secrets
    ]
  }
}
```

### Hook Integration

Claude Code supports hooks that Grid could leverage:

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Task(grid-*)",
        "hooks": [
          {
            "type": "command",
            "command": ".grid/hooks/pre-spawn.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Task(grid-*)",
        "hooks": [
          {
            "type": "command",
            "command": ".grid/hooks/post-spawn.sh"
          }
        ]
      }
    ]
  }
}
```

**Use Cases:**
- Pre-spawn budget check via hook
- Post-spawn cost recording
- Pre-spawn notification
- Post-spawn audit logging

---

## 5. Project Defaults System

### Current Grid Defaults

Defined in `.grid/config.json`:
```json
{
  "model_tier": "quality",
  "auto_verify": true,
  "scratchpad_heartbeat_minutes": 5
}
```

### Aligned Project Defaults

Move to `.claude/settings.json` for team sharing:

```json
{
  "grid": {
    "defaults": {
      "modelTier": "balanced",
      "autoVerify": true,
      "topology": "hierarchical",
      "budgetLimit": 50.00,
      "notifications": {
        "system": true,
        "sound": false
      }
    },
    "agents": {
      "planner": { "model": "opus" },
      "executor": { "model": "sonnet" },
      "recognizer": { "model": "haiku" }
    }
  }
}
```

### Template System

Provide Grid templates in project settings:

```json
{
  "grid": {
    "templates": {
      "quick-fix": {
        "topology": "hierarchical",
        "agents": ["planner", "executor", "recognizer"],
        "modelTier": "balanced"
      },
      "full-build": {
        "topology": "hierarchical",
        "agents": ["planner", "executor", "recognizer", "visual-inspector", "e2e-exerciser", "persona-simulator"],
        "modelTier": "quality"
      },
      "review-only": {
        "topology": "flat",
        "agents": ["recognizer", "visual-inspector"],
        "modelTier": "budget"
      }
    }
  }
}
```

---

## Quick Wins (Implement This Week)

### 1. Environment Variable Support (2 hours)

Add to Grid initialization:

```python
def load_grid_config():
    config = load_json(".grid/config.json")

    # Environment overrides
    if os.environ.get("GRID_MODEL_TIER"):
        config["model_tier"] = os.environ["GRID_MODEL_TIER"]
    if os.environ.get("GRID_BUDGET_LIMIT"):
        config["budget_limit"] = float(os.environ["GRID_BUDGET_LIMIT"])
    if os.environ.get("GRID_AUTO_VERIFY"):
        config["auto_verify"] = os.environ["GRID_AUTO_VERIFY"].lower() == "true"

    return config
```

### 2. Read Claude Code Settings (2 hours)

Make Grid read from Claude Code's settings:

```python
def load_grid_settings():
    """Load Grid settings from Claude Code's hierarchy."""
    settings = {}

    # User level
    user_settings = load_json("~/.claude/settings.json")
    if "grid" in user_settings:
        settings.update(user_settings["grid"])

    # Project level
    project_settings = load_json(".claude/settings.json")
    if "grid" in project_settings:
        settings.update(project_settings["grid"])

    # Local level (overrides all)
    local_settings = load_json(".claude/settings.local.json")
    if "grid" in local_settings:
        settings.update(local_settings["grid"])

    return settings
```

### 3. Model Override via CLAUDE_CODE_SUBAGENT_MODEL (1 hour)

Respect Claude Code's subagent model setting:

```python
def get_spawn_model(agent_type):
    # Check environment first
    subagent_model = os.environ.get("CLAUDE_CODE_SUBAGENT_MODEL")
    if subagent_model:
        return subagent_model

    # Fall back to Grid config
    config = load_grid_config()
    return config["agents"][agent_type]["model"]
```

### 4. Settings Command (1 hour)

Add `/grid:settings` to display current configuration hierarchy:

```
GRID SETTINGS
=============

Source Hierarchy:
  1. Environment: GRID_MODEL_TIER=budget
  2. Local: .claude/settings.local.json (none)
  3. Project: .claude/settings.json (grid.modelTier=balanced)
  4. User: ~/.claude/settings.json (grid.modelTier=quality)

Effective Configuration:
  Model Tier: budget (from environment)
  Budget Limit: $50.00 (from project)
  Auto Verify: true (from user)
  Notifications: enabled (default)

End of Line.
```

---

## Architecture Changes (This Month)

### 1. Migrate Grid Config to Claude Code Settings

**Phase 1: Dual Support**
- Read from both `.grid/config.json` AND `.claude/settings.json`
- Prefer Claude Code settings when present
- Log deprecation warning for `.grid/config.json`

**Phase 2: Migration Tool**
```bash
/grid:migrate-settings
```
Converts `.grid/config.json` to `.claude/settings.json` format.

**Phase 3: Remove Legacy**
- Remove `.grid/config.json` support
- Full Claude Code settings integration

### 2. Permission-Aware Operations

Grid commands should fail gracefully when denied:

```python
def spawn_agent(agent_type, prompt):
    # Permission check is automatic via Task tool
    # But Grid should handle denial gracefully
    try:
        result = spawn(f"grid-{agent_type}", prompt)
    except PermissionDenied:
        log_warning(f"Agent spawn denied by settings: {agent_type}")
        return FallbackBehavior()
```

### 3. Hook System Integration

Create standard Grid hooks:

```
.grid/hooks/
  pre-spawn.sh     # Budget check, logging
  post-spawn.sh    # Cost recording, notifications
  pre-refine.sh    # Refinement swarm gate
  post-complete.sh # Cleanup, reporting
```

Register in Claude Code settings:

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Task(grid-*)",
        "hooks": [{ "type": "command", "command": ".grid/hooks/pre-spawn.sh" }]
      }
    ]
  }
}
```

---

## Specific Recommendations

### 1. For Model Selection

**Current:** `/grid:model` modifies `.grid/config.json`

**Recommended:** `/grid:model` should:
1. Check `CLAUDE_CODE_SUBAGENT_MODEL` environment variable
2. Check `GRID_MODEL_TIER` environment variable
3. Check `.claude/settings.local.json` > `.claude/settings.json` > `~/.claude/settings.json`
4. Fall back to Grid defaults

### 2. For Budget Management

**Current:** Budget stored in `.grid/budget.json`

**Recommended:** Split into:
- **Configuration** (limit, thresholds): Move to `.claude/settings.json`
- **State** (current usage, history): Keep in `.grid/budget.json`

```json
// .claude/settings.json
{
  "grid": {
    "budget": {
      "limit": 50.00,
      "enforcement": "hard",
      "warningThreshold": 0.75
    }
  }
}

// .grid/budget.json (state only)
{
  "currentSession": { ... },
  "history": { ... }
}
```

### 3. For Enterprise Deployment

**Managed Settings** (`/Library/Application Support/ClaudeCode/managed-settings.json`):

```json
{
  "grid": {
    "maxBudget": 100.00,
    "allowedModelTiers": ["balanced", "budget"],
    "daemonModeAllowed": false,
    "requireApproval": true
  },
  "permissions": {
    "deny": [
      "Skill(grid:daemon)",
      "Task(grid-executor-opus)"
    ]
  }
}
```

This allows IT to:
- Cap spending across organization
- Disable expensive model tiers
- Disable daemon mode for security
- Require approval for spawns

### 4. For Status Line Integration

Grid could add status to Claude Code's status line:

```json
{
  "statusLine": {
    "type": "command",
    "command": "~/.claude/grid-status.sh"
  }
}
```

`~/.claude/grid-status.sh`:
```bash
#!/bin/bash
if [ -f .grid/STATE.md ]; then
  progress=$(grep "progress_percent" .grid/STATE.md | cut -d: -f2)
  echo "Grid: ${progress}%"
fi
```

---

## Summary Matrix

| Feature | Current Grid | Claude Code Capability | Recommendation |
|---------|-------------|----------------------|----------------|
| Config location | `.grid/config.json` | `.claude/settings.json` | Migrate to Claude Code |
| Hierarchy | Single level | 4 levels (managed/user/project/local) | Adopt hierarchy |
| Environment vars | None | ANTHROPIC_*, CLAUDE_* | Add GRID_* vars |
| Permissions | None | allow/deny patterns | Add Grid patterns |
| Hooks | None | Pre/PostToolUse | Add spawn hooks |
| Team sharing | Manual | Via `.claude/settings.json` | Leverage for Grid |
| Enterprise | None | Managed settings | Support IT policies |

---

## Next Steps

1. **Immediate:** Add environment variable support
2. **This week:** Read Claude Code settings hierarchy
3. **This month:** Full settings migration
4. **Q1:** Enterprise managed settings support
5. **Q2:** Hook system integration

The Grid's alignment with Claude Code's settings system transforms it from a standalone tool into a first-class citizen of the Claude Code ecosystem, enabling enterprise adoption and team collaboration.

---

*End of Line.*
