# Terminal Setup Analysis for Grid Integration

## Executive Summary

The Grid's visual identity relies heavily on terminal rendering capabilities - ASCII art banners, ANSI color codes, progress indicators, and status displays. Claude Code's terminal setup documentation reveals significant opportunities: (1) implementing a **Grid-specific custom status line** that shows mission progress, active agents, and cost tracking in real-time, (2) leveraging **notification hooks** to alert users when Grid missions complete or require attention, and (3) providing **terminal optimization recommendations** during `/grid:init` to ensure users get the best Grid visual experience. These enhancements could transform Grid from a command-line tool into a persistent dashboard experience.

---

## Underutilized Features

### 1. Custom Status Line for Grid State

- **Current Grid Usage**: Grid displays state through inline output - ASCII headers, progress bars, and status updates that scroll away. Users lose visibility of mission state as conversation progresses.

- **Opportunity**: Claude Code supports custom status lines via `statusLine` configuration. This is a persistent bottom bar that receives JSON context on every message update. Grid could implement a dedicated status line showing:
  - Current mission/task status
  - Active agent count and roles
  - Cost tracking (total_cost_usd from context)
  - Context window utilization (used_percentage)
  - Git branch when in repo

- **Implementation**:
  ```json
  // .claude/settings.json
  {
    "statusLine": {
      "type": "command",
      "command": "~/.claude/grid-statusline.sh",
      "padding": 0
    }
  }
  ```

  ```bash
  # ~/.claude/grid-statusline.sh
  #!/bin/bash
  input=$(cat)

  # Extract Claude Code context
  MODEL=$(echo "$input" | jq -r '.model.display_name // "?"')
  COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0' | xargs printf "%.4f")
  CONTEXT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | xargs printf "%.0f")

  # Read Grid state if available
  GRID_STATE=""
  if [ -f ".grid/state.json" ]; then
    MISSION=$(jq -r '.mission.id // "idle"' .grid/state.json 2>/dev/null)
    AGENTS=$(jq -r '.agents | length // 0' .grid/state.json 2>/dev/null)
    STATUS=$(jq -r '.status // "ready"' .grid/state.json 2>/dev/null)
    GRID_STATE=" | GRID: ${STATUS} (${AGENTS} agents)"
  fi

  # Git branch
  BRANCH=""
  if git rev-parse --git-dir > /dev/null 2>&1; then
    B=$(git branch --show-current 2>/dev/null)
    [ -n "$B" ] && BRANCH=" | $B"
  fi

  # ANSI colors for Grid branding
  CYAN="\033[36m"
  YELLOW="\033[33m"
  GREEN="\033[32m"
  RESET="\033[0m"

  echo -e "${CYAN}[$MODEL]${RESET} \$${COST} | ${CONTEXT}% ctx${GRID_STATE}${BRANCH}"
  ```

### 2. Terminal Notification Hooks

- **Current Grid Usage**: Grid has no notification system. When missions complete (especially long-running builds), users must monitor the terminal manually.

- **Opportunity**: Claude Code supports `Notification` hooks that fire when Claude needs user attention. Grid could implement:
  - macOS native notifications via `osascript`
  - Sound alerts for mission completion
  - Custom notification scripts for different event types

- **Implementation**:
  ```json
  // .claude/settings.json
  {
    "hooks": {
      "Notification": [
        {
          "matcher": "",
          "hooks": [
            {
              "type": "command",
              "command": "~/.claude/grid-notify.sh"
            }
          ]
        }
      ]
    }
  }
  ```

  ```bash
  # ~/.claude/grid-notify.sh
  #!/bin/bash

  # Check if Grid is active
  if [ -f ".grid/state.json" ]; then
    STATUS=$(jq -r '.status // "unknown"' .grid/state.json 2>/dev/null)
    MISSION=$(jq -r '.mission.name // "Grid Task"' .grid/state.json 2>/dev/null)

    # Custom notification based on Grid state
    if [ "$STATUS" = "completed" ]; then
      osascript -e "display notification \"Mission completed successfully\" with title \"Grid: $MISSION\" sound name \"Glass\""
    elif [ "$STATUS" = "failed" ]; then
      osascript -e "display notification \"Mission failed - attention required\" with title \"Grid: $MISSION\" sound name \"Basso\""
    else
      osascript -e "display notification \"Claude needs your attention\" with title \"Grid\" sound name \"Tink\""
    fi
  else
    # Default notification
    osascript -e "display notification \"Claude needs your attention\" with title \"Claude Code\""
  fi
  ```

### 3. Terminal Emulator Recommendations

- **Current Grid Usage**: Grid assumes any terminal will work. No guidance on optimal setup for Grid's visual elements.

- **Opportunity**: Different terminals render Grid's ASCII art and ANSI codes differently. Grid should:
  - Recommend optimal terminals (iTerm2, WezTerm, Ghostty, Kitty)
  - Warn about known issues (VS Code terminal limitations)
  - Provide terminal detection and setup hints during `/grid:init`

- **Implementation**: Add to `/grid:init` flow:
  ```bash
  # Detect terminal
  TERM_PROGRAM="${TERM_PROGRAM:-unknown}"

  case "$TERM_PROGRAM" in
    "iTerm.app")
      echo "Detected iTerm2 - optimal Grid experience"
      echo "Tip: Enable notifications in Preferences > Profiles > Terminal"
      ;;
    "Apple_Terminal")
      echo "Detected Terminal.app - Grid will work but consider iTerm2 for best experience"
      echo "Tip: Set 'Use Option as Meta Key' in Settings > Profiles > Keyboard"
      ;;
    "vscode")
      echo "Detected VS Code terminal - limited support"
      echo "Warning: Long Grid outputs may truncate. Consider external terminal for complex missions."
      ;;
    "WezTerm"|"ghostty"|"kitty"|"Alacritty")
      echo "Detected $TERM_PROGRAM - excellent Grid support"
      ;;
    *)
      echo "Terminal: $TERM_PROGRAM - Grid should work, report issues if visual problems occur"
      ;;
  esac
  ```

### 4. Vim Mode Awareness

- **Current Grid Usage**: Grid commands don't account for Vim mode being active. Input handling assumes standard mode.

- **Opportunity**: Grid could:
  - Detect if Vim mode is enabled via settings
  - Adjust prompts/help text accordingly
  - Provide Vim-style navigation hints in Grid output

- **Implementation**: Grid status command could detect:
  ```bash
  # Check Claude Code settings for Vim mode
  VIM_MODE=$(jq -r '.vimMode // false' ~/.claude/settings.json 2>/dev/null)
  if [ "$VIM_MODE" = "true" ]; then
    echo "Vim mode active - use 'i' to enter commands"
  fi
  ```

### 5. Large Input Handling

- **Current Grid Usage**: Grid accepts task descriptions directly in prompts. No guidance on size limits.

- **Opportunity**: For complex missions with extensive requirements, Grid could:
  - Detect input length and suggest file-based input
  - Support `--file` flag for loading task descriptions from files
  - Automatically handle `.grid/mission.md` for persistent mission definitions

- **Implementation**:
  ```markdown
  # In /grid command flow

  If task description > 1000 characters:
    - Suggest: "Large task detected. Consider saving to .grid/mission.md"
    - Or: "Run /grid --file mission.md to load from file"
  ```

---

## Quick Wins

### 1. Grid Status Line Script (30 minutes)
Create `~/.claude/grid-statusline.sh` that displays:
- Model name (from Claude context)
- Session cost (from context.cost.total_cost_usd)
- Context utilization percentage
- Grid status if `.grid/state.json` exists
- Git branch if in repo

**Impact**: Persistent visibility of Grid state without scrolling

### 2. Mission Completion Notifications (15 minutes)
Add notification hook to alert when Grid missions complete:
- macOS native notifications with sound
- Different sounds for success vs failure
- Mission name in notification title

**Impact**: Users can multitask while Grid works

### 3. Terminal Detection in /grid:init (20 minutes)
During initialization, detect terminal and provide:
- Optimization tips for current terminal
- Warnings for limited-support terminals
- Font/display recommendations

**Impact**: Better first-run experience, fewer visual issues

### 4. Shift+Enter Documentation (10 minutes)
Add to Grid help/README:
- How to enter multi-line task descriptions
- Terminal-specific shortcuts
- `/terminal-setup` mention for setup

**Impact**: Improved UX for complex task entry

---

## Architecture Changes

### A. Grid State File Enhancement

Extend `.grid/state.json` to support status line consumption:

```json
{
  "version": "1.7.x",
  "status": "executing",
  "mission": {
    "id": "mission-123",
    "name": "Refactor auth module",
    "started_at": "2024-01-15T10:30:00Z"
  },
  "agents": [
    {"role": "executor", "status": "active", "task": "Writing tests"},
    {"role": "scout", "status": "idle"}
  ],
  "metrics": {
    "tasks_completed": 3,
    "tasks_remaining": 2,
    "estimated_cost": 0.0234
  },
  "terminal": {
    "detected": "iTerm.app",
    "supports_notifications": true,
    "supports_256_color": true
  }
}
```

### B. Settings Template for Grid

Create `.claude/grid-settings-template.json` that `/grid:init` can merge:

```json
{
  "statusLine": {
    "type": "command",
    "command": "~/.claude/grid-statusline.sh",
    "padding": 0
  },
  "hooks": {
    "Notification": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/grid-notify.sh"
          }
        ]
      }
    ]
  }
}
```

### C. Grid Terminal Utilities Module

Create `commands/grid/lib/terminal.sh`:

```bash
#!/bin/bash

# Terminal detection and utilities for Grid

grid_detect_terminal() {
  echo "${TERM_PROGRAM:-${TERMINAL_EMULATOR:-unknown}}"
}

grid_supports_256_color() {
  [[ "$TERM" == *"256color"* ]] || [[ "$COLORTERM" == "truecolor" ]]
}

grid_supports_unicode() {
  [[ "$LANG" == *"UTF-8"* ]] || [[ "$LC_ALL" == *"UTF-8"* ]]
}

grid_terminal_width() {
  tput cols 2>/dev/null || echo 80
}

grid_notify() {
  local title="$1"
  local message="$2"
  local sound="${3:-default}"

  case "$(uname)" in
    Darwin)
      osascript -e "display notification \"$message\" with title \"$title\" sound name \"$sound\""
      ;;
    Linux)
      notify-send "$title" "$message" 2>/dev/null || echo "$title: $message"
      ;;
    *)
      echo "$title: $message"
      ;;
  esac
}
```

---

## Specific Recommendations

### For /grid:init

1. **Terminal Detection Phase**:
   ```
   Detecting terminal environment...
   - Terminal: iTerm2
   - Color support: 256-color
   - Unicode: Supported
   - Recommended: No changes needed
   ```

2. **Optional Status Line Setup**:
   ```
   Would you like to enable Grid status line? (y/n)
   This adds a persistent status bar showing:
   - Current model and cost
   - Grid mission status
   - Context window usage
   ```

3. **Notification Setup**:
   ```
   Enable notifications for mission completion? (y/n)
   You'll receive native OS notifications when:
   - Missions complete successfully
   - Missions fail or need attention
   - Long-running tasks finish
   ```

### For /grid:status

Integrate terminal info:
```
GRID STATUS
-----------
Mission: feature-auth-refactor
Status: Executing
Agents: 2 active (executor, scout)

TERMINAL
--------
Emulator: iTerm2
Status Line: Active
Notifications: Enabled
```

### For /grid:help

Add terminal section:
```
TERMINAL SETUP
--------------
Grid works best with:
- iTerm2 (macOS) - Full support, notifications
- WezTerm - Cross-platform, excellent
- Ghostty - Modern, fast
- Kitty - GPU-accelerated

Limited support:
- VS Code terminal - May truncate long output
- Terminal.app - Basic support

Run /terminal-setup to configure Shift+Enter for multi-line input.
```

### For ASCII Art Rendering

Add fallback for limited terminals:
```bash
# In display functions
if grid_supports_unicode; then
  # Full ASCII art with box-drawing characters
  echo "╔══════════════════════════════════════╗"
else
  # ASCII fallback
  echo "+======================================+"
fi
```

---

## Cost/Benefit Analysis

| Enhancement | Effort | Impact | Priority |
|-------------|--------|--------|----------|
| Grid status line | 2 hours | High - persistent visibility | P1 |
| Notification hooks | 1 hour | High - enables multitasking | P1 |
| Terminal detection | 1 hour | Medium - better UX | P2 |
| Settings template | 30 min | Medium - easier setup | P2 |
| Large input handling | 2 hours | Medium - edge case | P3 |
| Vim mode awareness | 30 min | Low - niche | P4 |
| ASCII fallback | 1 hour | Low - rare issue | P4 |

---

## Integration Checklist

- [ ] Create `~/.claude/grid-statusline.sh`
- [ ] Create `~/.claude/grid-notify.sh`
- [ ] Add terminal detection to `/grid:init`
- [ ] Extend `.grid/state.json` schema for status line
- [ ] Add status line setup prompt to `/grid:init`
- [ ] Add notification setup prompt to `/grid:init`
- [ ] Document terminal recommendations in `/grid:help`
- [ ] Create `commands/grid/lib/terminal.sh` utilities
- [ ] Add settings template for Grid-optimized config
- [ ] Test on iTerm2, VS Code, Terminal.app

---

## Conclusion

Terminal setup integration transforms Grid from a command-line tool into a **persistent dashboard experience**. The custom status line provides constant visibility into mission state, cost, and context usage. Notification hooks enable users to work on other tasks while Grid executes long-running missions. Terminal detection ensures users get the best visual experience from day one.

The most impactful quick win is the **Grid status line** - a 2-hour investment that provides immediate value to every Grid user. Combined with notifications, Grid becomes a tool users can trust to work autonomously while keeping them informed.
