# Memory System

## Overview

The Grok CLI memory system provides persistent context management through GROK.md files, enabling automatic injection of project knowledge into AI conversations.

## Core Features

- **Automatic GROK.md Discovery** - Finds memory files in current and parent directories
- **Hierarchical Memory Loading** - User → Project → Local context layers
- **Import System** - Reference other files with `@import` directives
- **Memory Injection** - Automatic context enhancement for conversations
- **Search Capabilities** - Find information across all memory files
- **Live Management** - Add, edit, and reload memory during sessions

## File Structure

### GROK.md Locations

1. **Project Memory**: `./GROK.md` (current directory)
2. **Local Memory**: `../GROK.md`, `../../GROK.md` (up to `maxDepth`)
3. **User Memory**: `~/.grok-cli/GROK.md` (global user context)

### Memory File Format

```markdown
# Grok CLI Memory

## Project Overview
Describe your project goals and architecture.

## Key Files
- `src/` - Main source code
- `tests/` - Test files

@import "./docs/architecture.md"

## Development Workflow
Build: npm run build
Test: npm test

## Important Notes
Add any important context for AI conversations.
```

## Commands

### Basic Operations

```bash
# Show memory status
/memory status

# Load memory files
/memory load

# Reload all memory
/memory reload

# Create new GROK.md
/memory create

# Create memory file at custom path
/memory create /path/to/GROK.md
```

### Content Management

```bash
# Add content to memory
/memory add "Important: Always use TypeScript strict mode"

# Search memory content
/memory search "API key"
/memory search "database"

# Show memory files
/memory show              # All files
/memory show project      # Project files only
/memory show user         # User files only
/memory show local        # Local files only

# Clear loaded memory
/memory clear
```

### Quick Memory Addition

```bash
# Use # commands for quick memory addition
#Remember: Database connection uses environment variables
#TODO: Implement rate limiting for API calls
```

## Configuration

### Memory Settings

Location: `~/.grok/config.json` or `.grok/settings.json`

```json
{
  "memory": {
    "autoLoad": true,                    // Auto-load memory on startup
    "maxDepth": 5,                      // Max parent directory depth
    "excludePatterns": [                // Files/dirs to exclude
      "node_modules/**",
      ".git/**",
      "*.log",
      "dist/**"
    ]
  }
}
```

### Auto-loading Behavior

When `autoLoad` is `true`:
- Memory files are loaded automatically on CLI startup
- Memory content is injected into AI conversations
- Changes to GROK.md files require manual reload

When `autoLoad` is `false`:
- Memory must be loaded manually with `/memory load`
- No automatic context injection
- More control over when memory is used

## Import System

### @import Directives

```markdown
# Import specific files
@import "./docs/api.md"
@import "../shared/conventions.md"
@import "~/templates/project-template.md"

# Multiple imports
@import "./docs/architecture.md"
@import "./docs/deployment.md"
```

### Markdown Link References

```markdown
# Automatic file references
See [API Documentation](./docs/api.md)
Check [Database Schema](../database/schema.sql)
```

## Memory Injection

### Automatic Context Enhancement

When memory auto-load is enabled, AI conversations are enhanced:

```
Original message: "How do I set up the database?"

Enhanced message:
Context from memory:

# Project Context
## Database Setup
Uses PostgreSQL with connection pooling...
[full memory content]

---

User message: How do I set up the database?
```

### Manual Context Control

```bash
# Disable auto-load for selective memory use
/memory clear          # Clear current memory
/memory show project   # Review project context
/memory load          # Load when needed
```

## Advanced Features

### Memory Statistics

```bash
/memory status
```

Output:
```
🧠 Memory Status:

Total files: 4
User files: 1
Project files: 1  
Local files: 2
Total size: 15.2 KB
```

### Memory Search

```bash
/memory search "API"
```

Output:
```
🔍 Search Results for "API" (2 files):

 1. ./GROK.md (project)
    Line 23: API endpoints are documented in docs/api.md

 2. ./docs/api.md (local)  
    Line 1: # API Documentation
    Line 15: Authentication uses API keys
```

### Memory Types

- **User**: Global context for all projects (`~/.grok-cli/GROK.md`)
- **Project**: Main project memory (`./GROK.md`)
- **Local**: Additional context files in project hierarchy

## Best Practices

### Content Organization

1. **Project Overview**: High-level goals and architecture
2. **Key Files**: Important file locations and purposes  
3. **Development Workflow**: Build, test, and deployment processes
4. **Important Notes**: Critical information for AI conversations
5. **Custom Commands**: Project-specific workflows
6. **Architecture Decisions**: Technical choices and rationales

### Memory Management

1. **Keep It Relevant**: Only include information useful for AI conversations
2. **Regular Updates**: Update memory when project changes
3. **Use Imports**: Reference detailed docs instead of duplicating
4. **Search Before Adding**: Check if information already exists
5. **Clear Structure**: Use consistent markdown formatting

### Performance Tips

1. **Exclude Large Files**: Use `excludePatterns` for build outputs
2. **Reasonable Depth**: Limit `maxDepth` to avoid excessive file loading
3. **Selective Loading**: Disable auto-load for large projects
4. **Regular Cleanup**: Remove outdated memory content

## Integration

### Hook System Integration

Memory loading integrates with the hook system:

```json
{
  "hooks": {
    "PreToolUse": [{
      "matcher": "memory.*",
      "hooks": [{
        "type": "command", 
        "command": "echo 'Memory operation starting'"
      }]
    }]
  }
}
```

### File Reference System

Memory works with file references:

```bash
# Reference GROK.md files
@GROK.md              # Current directory
@../GROK.md           # Parent directory  
@~/.grok-cli/GROK.md  # User memory
```

### Conversation History

Memory content is included in conversation transcripts when injected.

## Troubleshooting

### Common Issues

1. **Memory Not Loading**:
   ```bash
   /memory status        # Check if files found
   /memory reload       # Force reload
   ```

2. **Import Errors**:
   - Check file paths in `@import` directives
   - Verify files exist and are readable
   - Check exclude patterns

3. **Large Memory Size**:
   - Review included files with `/memory show`
   - Add exclusion patterns for large files
   - Use selective imports instead of full file inclusion

4. **Context Not Injecting**:
   - Verify `autoLoad: true` in configuration
   - Check if memory files loaded with `/memory status`
   - Ensure GROK.md files have content

### Debug Commands

```bash
# Detailed memory information
/memory show

# Search for specific content
/memory search "problematic content"

# Reload and check logs
/memory reload

# Clear and reload
/memory clear
/memory load
```

## Examples

### Basic Project Memory

```markdown
# My Web App

## Overview
React + Node.js e-commerce application

## Key Files  
- `src/client/` - React frontend
- `src/server/` - Express.js backend
- `database/` - PostgreSQL schemas

## Environment
- Development: `npm run dev`
- Production: `npm run build && npm start`
- Testing: `npm test`

## Important Notes
- Uses Stripe for payments
- Redis for session storage
- Deployed on AWS with Docker
```

### Advanced Project with Imports

```markdown
# Enterprise Application

## Overview
@import "./docs/overview.md"

## Architecture
@import "./docs/architecture.md"

## API Documentation
See [API Docs](./docs/api.md) for endpoints.

## Deployment
@import "./docs/deployment.md"

## Recent Decisions
- Migrated to TypeScript for better type safety
- Adopted microservices architecture
- Implemented event-driven messaging
```

### User-Level Memory

`~/.grok-cli/GROK.md`:
```markdown
# Personal Development Preferences

## Code Style
- Always use TypeScript with strict mode
- Prefer functional programming patterns
- Use ESLint with Prettier

## Common Patterns
- Database: Prefer PostgreSQL with Prisma ORM
- Testing: Jest for unit tests, Cypress for E2E
- Deployment: Docker containers on AWS

## Frequent Commands
- Start: `npm run dev`
- Test: `npm test -- --watch`
- Build: `npm run build`
```

## See Also

- [Configuration System](./configuration.md)
- [File Reference System](./file-reference-system.md)
- [Hook System](./hooks-system.md)
- [Command System](./command-system.md)