docs: enhance README with badges, TOC, and detailed sections

Add comprehensive documentation files:
- ARCHITECTURE.md: System design overview
- CONFIGURATION.md: Advanced config guide
- TROUBLESHOOTING.md: Common issues and solutions

Update README with:
- Badges for coverage, Go version, license
- Expanded commands, workflows, features sections
- Improved quick start and logging examples
This commit is contained in:
Greg Gauthier 2026-03-01 12:57:08 +00:00
parent 13519438a2
commit cbd779c882
4 changed files with 1869 additions and 69 deletions

391
README.md
View File

@ -1,10 +1,15 @@
# Grokkit
Grokkit is a fast Go CLI integrating Grok AI with git workflows and general chat/edit.
Grokkit is a fast Go CLI integrating Grok AI with git workflows and general chat/edit functionality.
[![Test Coverage](https://img.shields.io/badge/coverage-72%25-brightgreen)]()
[![Go Version](https://img.shields.io/badge/go-1.24-blue)]()
[![License](https://img.shields.io/badge/license-Unlicense-lightgrey)]()
## 🚀 Quick Start
```bash
# Set your API key
export XAI_API_KEY=sk-...
# Install from source
@ -15,137 +20,319 @@ make install
# Or build locally
make build
# Verify installation
grokkit --help
```
## 📁 Config (optional)
## 📋 Table of Contents
`~/.config/grokkit/config.toml`:
```toml
default_model = "grok-4"
temperature = 0.7
timeout = 60 # seconds
log_level = "info" # debug, info, warn, error
[aliases]
beta = "grok-beta-2"
[chat]
history_file = "~/.config/grokkit/chat_history.json"
```
Logs are written to `~/.config/grokkit/grokkit.log` in JSON format for structured analysis.
- [Commands](#commands)
- [Configuration](#configuration)
- [Workflows](#workflows)
- [Shell Completions](#shell-completions)
- [Features](#features)
- [Development](#development)
- [Documentation](#documentation)
- [License](#license)
## Commands
### 💬 `grokkit chat`
Interactive CLI chat with Grok. Features persistent history across sessions.
```
grokkit chat
```bash
grokkit chat # Start chat session
grokkit chat -m grok-beta # Use specific model
grokkit chat --debug # Enable debug logging
```
**Tips:**
- Type `/quit`, `/q`, or `exit` to exit
- History is saved automatically between sessions
- Use `--debug` to see API request timing
### ✏️ `grokkit edit FILE "instruction"`
AI-powered file editing with preview and automatic backups.
```bash
# Basic usage
grokkit edit main.go "add error handling to all functions"
# Complex refactoring
grokkit edit server.go "convert this to use context for cancellation"
# Add features
grokkit edit api.go "add rate limiting middleware"
# Documentation
grokkit edit utils.go "add detailed docstrings to all exported functions"
```
**Safety features:**
- Creates `.bak` backup before any changes
- Shows preview with diff-style output
- Requires confirmation before applying
- Uses silent streaming (no console spam)
### 📝 `grokkit commitmsg`
Generate conventional commit from staged changes.
Generate conventional commit messages from staged changes.
```
```bash
git add .
grokkit commitmsg
grokkit commitmsg # Generate message only
grokkit commitmsg -m grok-4 # Use specific model
```
Output format: `type(scope): subject\n\nbody`
### ✅ `grokkit commit`
Generate & commit.
Generate commit message and commit in one step.
```
grokkit commit
```bash
git add .
grokkit commit # Generate + confirm + commit
```
### 🔍 `grokkit review`
AI code review of staged changes.
AI code review of staged or unstaged changes.
```
```bash
# Review staged changes
git add feature.go
grokkit review
# Review all changes
grokkit review
# Get detailed review
grokkit review --debug # See API timing info
```
Output includes:
- Summary of changes
- 3-5 actionable improvements
- Potential bugs or issues
- Best practice suggestions
### 📋 `grokkit pr-describe`
PR description from branch vs main.
Generate comprehensive PR descriptions.
```bash
# From current branch vs main
grokkit pr-describe
# With specific model
grokkit pr-describe -m grok-4
```
Output includes:
- Title suggestion
- Summary of changes
- Motivation/context
- Testing notes
### 📜 `grokkit history`
Summarize recent git commits.
```bash
grokkit history # Last 10 commits
```
### 🤖 `grokkit agent`
Multi-file agent for complex refactoring (experimental).
```bash
grokkit agent "refactor authentication to use JWT"
```
## Configuration
### Environment Variables
```bash
export XAI_API_KEY=sk-... # Required: Your xAI API key
```
### Config File (Optional)
Create `~/.config/grokkit/config.toml`:
```toml
default_model = "grok-4"
temperature = 0.7
timeout = 60 # API timeout in seconds
log_level = "info" # debug, info, warn, error
[aliases]
beta = "grok-beta-2"
fast = "grok-4-mini"
[chat]
history_file = "~/.config/grokkit/chat_history.json"
```
**See also:** [docs/CONFIGURATION.md](docs/CONFIGURATION.md) for advanced configuration options.
### Logging
Logs are written to `~/.config/grokkit/grokkit.log` in JSON format.
```bash
# View logs in real-time
tail -f ~/.config/grokkit/grokkit.log
# Find errors
cat ~/.config/grokkit/grokkit.log | jq 'select(.level=="ERROR")'
# Track API performance
cat ~/.config/grokkit/grokkit.log | jq 'select(.msg=="API request completed") | {model, duration_ms, response_length}'
```
## Workflows
### Git Workflow Integration
```bash
# 1. Make changes
vim src/api.go
# 2. Review with AI
git add src/api.go
grokkit review
# 3. Fix issues, then commit
git add src/api.go
grokkit commit
# 4. Generate PR description
grokkit pr-describe
```
### 📜 `grokkit history`
Summarize recent commits.
### Code Refactoring Workflow
```
grokkit history
```bash
# 1. Chat to plan approach
grokkit chat
> "How should I refactor this authentication code to use middleware?"
# 2. Apply changes with edit
grokkit edit auth.go "implement middleware pattern as discussed"
# 3. Review changes
grokkit review
# 4. Commit
grokkit commit
```
### ✏️ `grokkit edit FILE "instruction"`
AI edit file.
### Debugging Workflow
```bash
# 1. Describe issue in chat
grokkit chat --debug
> "I'm getting a nil pointer error in handler.go:42"
# 2. Apply suggested fixes
grokkit edit handler.go "add nil checks before dereferencing user object"
# 3. Verify and commit
grokkit review
grokkit commit
```
grokkit edit main.go "add error handling"
### Batch File Editing
```bash
# Edit multiple files with consistent changes
for file in src/*.go; do
grokkit edit "$file" "add context parameter to all exported functions"
done
# Review all changes together
grokkit review
```
## Shell Completions
Generate shell completions for your shell:
Generate shell completions for faster command entry:
```bash
# Bash
grokkit completion bash > /etc/bash_completion.d/grokkit
grokkit completion bash | sudo tee /etc/bash_completion.d/grokkit
# Zsh
grokkit completion zsh > "${fpath[1]}/_grokkit"
# Zsh (oh-my-zsh)
grokkit completion zsh > ~/.oh-my-zsh/completions/_grokkit
# Fish
grokkit completion fish > ~/.config/fish/completions/grokkit.fish
# PowerShell
grokkit completion powershell > grokkit.ps1
grokkit completion powershell | Out-String | Invoke-Expression
```
## Flags
- `--model, -m`: Specify model (e.g., grok-4, grok-beta)
- `--debug`: Enable debug logging (outputs to both stderr and log file)
- `--verbose, -v`: Enable verbose logging
- All flags are global and work with any command
### Global Flags (work with all commands)
| Flag | Short | Description |
|------|-------|-------------|
| `--model` | `-m` | Override model (e.g., grok-4, grok-beta) |
| `--debug` | | Enable debug logging (stderr + file) |
| `--verbose` | `-v` | Enable verbose logging |
| `--help` | `-h` | Show help |
### Examples
```bash
# Use different model
grokkit chat -m grok-beta
# Debug API issues
grokkit edit main.go "refactor" --debug
# Verbose logging
grokkit review -v
```
## Features
### Core Features
- ✅ **Structured logging with slog** - JSON logs with request tracing, timing, and context
- ✅ Context-aware HTTP requests with timeouts
- ✅ Comprehensive error handling and custom error types
- ✅ Persistent chat history across sessions
- ✅ Configurable temperature and parameters
- ✅ Shell completions (bash, zsh, fish, powershell)
- ✅ Test coverage >70%
- ✅ CI/CD with Gitea Actions
- ✅ Interface-based design for testability
- ✅ **Context-aware HTTP requests** - 60s timeout, proper cancellation
- ✅ **Comprehensive error handling** - Custom error types with context
- ✅ **Persistent chat history** - Never lose your conversations
- ✅ **Configurable parameters** - Temperature, timeout, model selection
- ✅ **Shell completions** - Bash, Zsh, Fish, PowerShell
- ✅ **Safe file editing** - Automatic backups, preview, confirmation
- ✅ **Git workflow integration** - Commit messages, reviews, PR descriptions
### Logging & Observability
### Quality & Testing
- ✅ **Test coverage 72%** - Comprehensive unit tests
- ✅ **CI/CD with Gitea Actions** - Automated testing and builds
- ✅ **Interface-based design** - Testable and maintainable
- ✅ **Zero external dependencies** - Only stdlib + well-known libs
Grokkit uses Go's standard `log/slog` for structured logging:
```bash
# Enable debug mode (logs to both stderr and file)
grokkit chat --debug
# View logs
tail -f ~/.config/grokkit/grokkit.log
# Parse JSON logs with jq
cat ~/.config/grokkit/grokkit.log | jq 'select(.level=="ERROR")'
```
### Observability
**Logged metrics:**
- API request/response timing and sizes
- Git command execution and output
- File operations with size tracking
- Error context with stack traces
- Error context with full details
**Example log entry:**
```json
{
"time": "2026-03-01T10:30:47.890Z",
"level": "INFO",
"msg": "API request completed",
"model": "grok-4",
"response_length": 1024,
"chunks_received": 42,
"duration_ms": 2434,
"duration": "2.434s"
}
```
## Development
@ -153,16 +340,82 @@ cat ~/.config/grokkit/grokkit.log | jq 'select(.level=="ERROR")'
# Run tests
make test
# Run tests with coverage
# Run tests with coverage report
make test-cover
open build/coverage.html
# Build
# Run specific tests
go test -run TestEditCommand ./cmd -v
# Build binary
make build
# Install locally
make install
# Clean build artifacts
make clean
```
### Project Structure
```
grokkit/
├── cmd/ # CLI commands (cobra)
├── config/ # Configuration management (viper)
├── internal/
│ ├── errors/ # Custom error types
│ ├── git/ # Git operations wrapper
│ ├── grok/ # Grok API client
│ └── logger/ # Structured logging (slog)
├── docs/ # Documentation
├── .gitea/ # CI/CD workflows
└── Makefile # Build automation
```
## Documentation
- 📖 [Troubleshooting Guide](docs/TROUBLESHOOTING.md) - Common issues and solutions
- 🏗️ [Architecture Overview](docs/ARCHITECTURE.md) - System design and patterns
- ⚙️ [Configuration Guide](docs/CONFIGURATION.md) - Advanced configuration options
## API Usage & Costs
Grokkit uses the xAI Grok API. Be aware:
- API calls consume credits/tokens
- Default timeout: 60 seconds
- Streaming reduces perceived latency
- Consider using model aliases for different use cases (fast/expensive)
## Requirements
- Go 1.24+ (for building)
- Git (for git-related commands)
- XAI API key
## Troubleshooting
**Common issues:**
```bash
# API key not set
Error: XAI_API_KEY environment variable not set
→ Solution: export XAI_API_KEY=sk-your-key
# Request timeout
Error: Request failed: context deadline exceeded
→ Solution: Increase timeout in config.toml or check network
# Permission denied on log file
→ Solution: chmod 644 ~/.config/grokkit/grokkit.log
```
**See [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) for more details.**
## License
[Unlicense](https://unlicense.org/)
[Unlicense](https://unlicense.org/) - Free for any use, no attribution required.
---
**Made with ❤️ using Grok AI**

514
docs/ARCHITECTURE.md Normal file
View File

@ -0,0 +1,514 @@
# Architecture Overview
This document describes the design principles, architecture patterns, and implementation details of Grokkit.
## Table of Contents
- [Design Philosophy](#design-philosophy)
- [Project Structure](#project-structure)
- [Core Components](#core-components)
- [Data Flow](#data-flow)
- [Testing Strategy](#testing-strategy)
- [Design Patterns](#design-patterns)
- [Future Considerations](#future-considerations)
## Design Philosophy
Grokkit follows these core principles:
### 1. **Simplicity First**
- Minimal dependencies (stdlib + well-known libs)
- Minimal interface surface (CLI commands over TUI interactions)
- Clear, readable code over clever solutions
- Single responsibility per package
### 2. **Safety by Default**
- File backups before any modification
- Confirmation prompts for destructive actions
- Comprehensive error handling
### 3. **Observability**
- Structured logging for all operations
- Request/response timing
- Contextual error messages
### 4. **Testability**
- Interface-based design
- Dependency injection where needed
- Unit tests for pure functions
### 5. **User Experience**
- Streaming responses for immediate feedback
- Persistent history
- Shell completions
## Project Structure
```
grokkit/
├── main.go # Entry point
├── cmd/ # CLI commands (Cobra)
│ ├── root.go # Root command + flags
│ ├── chat.go # Chat command
│ ├── edit.go # Edit command
│ ├── review.go # Review command
│ ├── commit.go # Commit commands
│ ├── completion.go # Shell completions
│ └── *_test.go # Command tests
├── config/ # Configuration (Viper)
│ ├── config.go # Config loading + getters
│ └── config_test.go # Config tests
├── internal/ # Private packages
│ ├── errors/ # Custom error types
│ │ ├── errors.go
│ │ └── errors_test.go
│ ├── git/ # Git operations wrapper
│ │ ├── git.go
│ │ ├── interface.go # GitRunner interface
│ │ └── git_test.go
│ ├── grok/ # Grok API client
│ │ ├── client.go # HTTP client + streaming
│ │ ├── interface.go # AIClient interface
│ │ └── client_test.go
│ └── logger/ # Structured logging (slog)
│ ├── logger.go # Logger setup + helpers
│ └── logger_test.go
├── docs/ # Documentation
│ ├── TROUBLESHOOTING.md
│ ├── ARCHITECTURE.md # This file
│ └── CONFIGURATION.md
├── .gitea/workflows/ # CI/CD
│ ├── ci.yml # Test + lint + build
│ └── release.yml # Multi-platform releases
└── Makefile # Build automation
```
### Package Organization
- **`cmd/`**: Cobra commands, minimal logic (orchestration only)
- **`config/`**: Viper integration, configuration management
- **`internal/`**: Core business logic (not importable outside project)
- **`internal/errors/`**: Domain-specific error types
- **`internal/git/`**: Git command abstraction
- **`internal/grok/`**: API client with streaming support
- **`internal/logger/`**: Structured logging facade
## Core Components
### 1. CLI Layer (`cmd/`)
**Responsibility:** Command parsing, user interaction, orchestration
**Pattern:** Command pattern (Cobra)
```go
var chatCmd = &cobra.Command{
Use: "chat",
Short: "Interactive chat",
Run: func(cmd *cobra.Command, args []string) {
// 1. Parse flags
// 2. Load config
// 3. Call business logic
// 4. Handle errors
// 5. Display output
},
}
```
**Key characteristics:**
- Thin orchestration layer
- No business logic
- Delegates to internal packages
- Handles user I/O only
### 2. Configuration Layer (`config/`)
**Responsibility:** Load and manage configuration from multiple sources
**Pattern:** Singleton (via Viper)
```go
// Priority: CLI flag > env var > config file > default
func GetModel(flagModel string) string {
if flagModel != "" {
return resolveAlias(flagModel)
}
return viper.GetString("default_model")
}
```
**Configuration sources (in order):**
1. CLI flags (`--model grok-4`)
2. Environment variables (`XAI_API_KEY`)
3. Config file (`~/.config/grokkit/config.toml`)
4. Defaults (hardcoded in `config.Load()`)
### 3. API Client (`internal/grok/`)
**Responsibility:** HTTP communication with Grok API
**Pattern:** Client pattern with streaming support
```go
type Client struct {
APIKey string
BaseURL string
}
// Public API
func (c *Client) Stream(messages, model) string
func (c *Client) StreamSilent(messages, model) string
func (c *Client) StreamWithTemp(messages, model, temp) string
```
**Key features:**
- Context-aware requests (60s timeout)
- Server-Sent Events (SSE) streaming
- Silent vs live output modes
- Comprehensive logging
**Request flow:**
1. Marshal request → JSON
2. Create HTTP request with context
3. Set headers (Authorization, Content-Type)
4. Send request
5. Stream response line-by-line
6. Parse SSE chunks
7. Build full response
8. Log metrics
### 4. Git Integration (`internal/git/`)
**Responsibility:** Abstract git command execution
**Pattern:** Command wrapper + Interface
```go
type GitRunner interface {
Run(args []string) (string, error)
IsRepo() bool
}
// Implementation
func Run(args []string) (string, error) {
out, err := exec.Command("git", args...).Output()
// Log execution
// Wrap errors
return string(out), err
}
```
**Why wrapped:**
- Logging of all git operations
- Consistent error handling
- Testability via interface
- Future: git library instead of exec
### 5. Logging (`internal/logger/`)
**Responsibility:** Structured logging with context
**Pattern:** Facade over stdlib `log/slog`
```go
// Structured logging with key-value pairs
logger.Info("API request completed",
"model", model,
"duration_ms", duration,
"response_length", length)
```
**Features:**
- JSON output format
- Dynamic log levels
- Multi-writer (file + stderr in debug)
- Context enrichment
**Log levels:**
- `DEBUG`: Detailed info for troubleshooting
- `INFO`: Normal operations
- `WARN`: Potential issues
- `ERROR`: Failures requiring attention
### 6. Error Handling (`internal/errors/`)
**Responsibility:** Domain-specific error types
**Pattern:** Custom error types with context
```go
type GitError struct {
Command string
Err error
}
type APIError struct {
StatusCode int
Message string
Err error
}
```
**Benefits:**
- Type-safe error handling
- Rich error context
- Error wrapping (`errors.Is`, `errors.As`)
## Data Flow
### Chat Command Flow
```
User Input
chatCmd.Run()
config.GetModel() # Resolve model
loadChatHistory() # Load previous messages
grok.Client.Stream() # API call
├─→ logger.Info() # Log request
├─→ HTTP POST # Send to API
├─→ Stream chunks # Receive SSE
└─→ logger.Info() # Log completion
saveChatHistory() # Persist conversation
Display to user
```
### Edit Command Flow
```
User: grokkit edit file.go "instruction"
editCmd.Run()
├─→ Validate file exists
├─→ Read original content
├─→ Create backup (.bak)
├─→ Clean "Last modified" comments
grok.Client.StreamSilent() # Get AI response
├─→ [Same as chat, but silent]
grok.CleanCodeResponse() # Remove markdown fences
Display preview # Show diff-style output
Prompt user (y/n)
Write file (if confirmed)
├─→ logger.Info() # Log changes
└─→ Keep backup
```
### Commit Command Flow
```
User: grokkit commit
commitCmd.Run()
git.Run(["diff", "--cached"]) # Get staged changes
├─→ logger.Debug() # Log git command
grok.Client.Stream() # Generate commit message
Display message + prompt
exec.Command("git", "commit") # Execute commit
├─→ logger.Info() # Log result
```
## Testing Strategy
### Unit Tests
**Coverage goals:**
- Internal packages: >70%
- Helper functions: 100%
- Commands: Test helpers, not Cobra execution
**Approach:**
- Table-driven tests
- Isolated environments (temp directories)
- No external dependencies in unit tests
**Example:**
```go
func TestRemoveLastModifiedComments(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{"removes comment", "// Last modified\ncode", "code"},
{"preserves other", "// Comment\ncode", "// Comment\ncode"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := removeLastModifiedComments(tt.input)
assert.Equal(t, tt.expected, result)
})
}
}
```
### What's NOT tested (and why)
**Cobra command execution** - Requires CLI integration tests
**User input (Scanln)** - Requires terminal mocking
**API streaming** - Would need mock HTTP server
**os.Exit() paths** - Can't test process termination
These require **integration/E2E tests**, which are a different testing layer.
### Test Organization
```
package/
├── implementation.go # Production code
└── implementation_test.go # Tests (same package)
```
**Benefits:**
- Tests can access private functions
- Clear mapping between code and tests
- Go convention
## Design Patterns
### 1. Interface Segregation
```go
// Small, focused interfaces
type AIClient interface {
Stream(messages []map[string]string, model string) string
StreamSilent(messages []map[string]string, model string) string
}
type GitRunner interface {
Run(args []string) (string, error)
IsRepo() bool
}
```
**Benefits:**
- Easy to mock for testing
- Flexibility to swap implementations
- Clear contracts
### 2. Facade Pattern (Logger)
```go
// Simple API hides slog complexity
logger.Info("message", "key", "value")
logger.Error("error", "context", ctx)
```
### 3. Command Pattern (CLI)
```go
// Each command is independent
var chatCmd = &cobra.Command{...}
var editCmd = &cobra.Command{...}
```
### 4. Strategy Pattern (Streaming modes)
```go
// Different behaviors via parameters
func streamInternal(messages, model, temp, printLive bool) {
if printLive {
fmt.Print(content) // Live streaming
}
// Silent streaming builds full response
}
```
### 5. Template Method (Git operations)
```go
// Base wrapper with logging
func Run(args []string) (string, error) {
logger.Debug("executing", "command", args)
out, err := exec.Command("git", args...).Output()
if err != nil {
logger.Error("failed", "command", args, "error", err)
}
return string(out), err
}
```
## Future Considerations
### Scalability
**Current limitations:**
- Single API key (no multi-user support)
- No request queuing
- No rate limiting client-side
- Chat history grows unbounded
**Future improvements:**
- Rate limit handling with backoff
- History trimming/rotation
- Concurrent request support
- Request caching
### Extensibility
**Easy to add:**
- New commands (add to `cmd/`)
- New models (config aliases)
- New output formats (change display logic)
- New logging destinations (slog handlers)
**Harder to add:**
- Multiple AI providers (requires abstraction)
- Non-streaming APIs (requires client refactor)
- GUI (CLI-focused architecture)
### Performance
**Current bottlenecks:**
- Network latency (streaming helps with perception)
- API response time (model-dependent)
- File I/O for large history (rare)
**Optimization opportunities:**
- Request caching (for repeated queries)
- Parallel git operations (if multiple files)
- Lazy loading of history (if very large)
### Security
**Current measures:**
- API key via environment variable
- No credential storage
- Backup files for safety
**Future considerations:**
- Encrypted config storage
- API key rotation support
- Audit logging for file changes
- Sandboxed file operations
## Contributing
When contributing, maintain these principles:
1. **Keep packages small and focused**
2. **Write tests for pure functions**
3. **Log all external operations**
4. **Use interfaces for testability**
5. **Handle errors explicitly**
6. **Document non-obvious behavior**
---
**See also:**
- [Configuration Guide](CONFIGURATION.md)
- [Troubleshooting](TROUBLESHOOTING.md)

485
docs/CONFIGURATION.md Normal file
View File

@ -0,0 +1,485 @@
# Configuration Guide
Advanced configuration options and use cases for Grokkit.
## Table of Contents
- [Configuration Priority](#configuration-priority)
- [Environment Variables](#environment-variables)
- [Config File](#config-file)
- [Configuration Examples](#configuration-examples)
- [Advanced Use Cases](#advanced-use-cases)
- [Best Practices](#best-practices)
## Configuration Priority
Grokkit resolves configuration in this order (highest to lowest):
1. **CLI Flags** - `grokkit chat --model grok-4`
2. **Environment Variables** - `export XAI_API_KEY=...`
3. **Config File** - `~/.config/grokkit/config.toml`
4. **Defaults** - Hardcoded in application
**Example:**
```bash
# Config file says: default_model = "grok-4"
# Command uses:
grokkit chat -m grok-beta
# Result: Uses grok-beta (CLI flag wins)
```
## Environment Variables
### XAI_API_KEY (Required)
Your xAI API key.
```bash
# Set for current session
export XAI_API_KEY=sk-your-key-here
# Set permanently (bash)
echo 'export XAI_API_KEY=sk-your-key-here' >> ~/.bashrc
source ~/.bashrc
# Set permanently (zsh)
echo 'export XAI_API_KEY=sk-your-key-here' >> ~/.zshrc
source ~/.zshrc
# Verify (safely)
echo $XAI_API_KEY | sed 's/sk-.*$/sk-***/'
```
### Environment-based Config
You can also set config values via environment:
```bash
export GROKKIT_MODEL=grok-4
export GROKKIT_TEMPERATURE=0.8
export GROKKIT_LOG_LEVEL=debug
```
Viper (the config library) automatically reads these with `AutomaticEnv()`.
## Config File
### Location
Default location: `~/.config/grokkit/config.toml`
Custom location via Viper (not currently exposed, but easy to add).
### Full Configuration
```toml
# ~/.config/grokkit/config.toml
# ===== Model Settings =====
default_model = "grok-4" # Model to use by default
temperature = 0.7 # Creativity (0.0 = deterministic, 1.0 = creative)
timeout = 60 # API timeout in seconds
# ===== Logging Settings =====
log_level = "info" # debug | info | warn | error
# ===== Model Aliases =====
# Create shortcuts for frequently used models
[aliases]
beta = "grok-beta-2" # grokkit chat -m beta
fast = "grok-4-mini" # grokkit chat -m fast
creative = "grok-4" # grokkit chat -m creative
# ===== Chat Settings =====
[chat]
history_file = "~/.config/grokkit/chat_history.json" # Custom history location
# max_history = 100 # Future: Limit history size
```
### Minimal Configuration
```toml
# Just the essentials
default_model = "grok-4"
temperature = 0.7
```
### Create Config File
```bash
# Create directory
mkdir -p ~/.config/grokkit
# Create config with defaults
cat > ~/.config/grokkit/config.toml <<'EOF'
default_model = "grok-4"
temperature = 0.7
timeout = 60
log_level = "info"
[aliases]
beta = "grok-beta-2"
fast = "grok-4-mini"
[chat]
history_file = "~/.config/grokkit/chat_history.json"
EOF
# Verify
cat ~/.config/grokkit/config.toml
```
## Configuration Examples
### Example 1: Development Environment
Fast iteration, detailed logs, shorter timeouts.
```toml
# ~/.config/grokkit/config.toml
default_model = "grok-4-mini" # Fast model for quick iterations
temperature = 0.5 # More predictable responses
timeout = 30 # Fail fast
log_level = "debug" # Detailed logging
[aliases]
dev = "grok-4-mini"
prod = "grok-4"
```
```bash
# Usage
grokkit chat -m dev # Fast model
grokkit review --debug # With detailed logs
```
### Example 2: Production Environment
Reliable, balanced settings.
```toml
# ~/.config/grokkit/config.toml
default_model = "grok-4"
temperature = 0.7
timeout = 120 # Longer timeout for reliability
log_level = "warn" # Only warnings and errors
[aliases]
prod = "grok-4"
fast = "grok-4-mini"
```
### Example 3: Creative Writing
Higher temperature for more creative responses.
```toml
# ~/.config/grokkit/config-creative.toml
default_model = "grok-4"
temperature = 0.9 # More creative
timeout = 90
log_level = "info"
[aliases]
creative = "grok-4"
```
```bash
# Use with environment variable pointing to alt config
# (requires code modification to support)
grokkit chat # Uses high creativity settings
```
### Example 4: Team Settings
Standardized settings for team consistency.
```toml
# team-shared-config.toml
default_model = "grok-4"
temperature = 0.7
timeout = 60
log_level = "info"
[aliases]
review = "grok-4" # For code reviews
commit = "grok-4-mini" # For commit messages
docs = "grok-4" # For documentation
[chat]
# Don't save history in team environment
# (requires code modification)
save_history = false
```
```bash
# Usage
grokkit review -m review # Explicit model for reviews
grokkit commit -m commit # Fast model for commits
```
### Example 5: Cost Optimization
Minimize API costs while maintaining functionality.
```toml
# ~/.config/grokkit/config.toml
default_model = "grok-4-mini" # Cheaper model
temperature = 0.5 # More deterministic = fewer tokens
timeout = 45
[aliases]
cheap = "grok-4-mini"
expensive = "grok-4"
```
```bash
# Use cheap model by default
grokkit chat
# Use expensive model only when needed
grokkit edit complex.go "major refactor" -m expensive
```
## Advanced Use Cases
### Multiple Profiles
Create different config files for different use cases.
```bash
# Directory structure
~/.config/grokkit/
├── config.toml # Default
├── config-dev.toml # Development
├── config-creative.toml # Creative work
└── config-production.toml # Production use
# Symlink to switch profiles
ln -sf ~/.config/grokkit/config-dev.toml ~/.config/grokkit/config.toml
```
### Project-specific Settings
Place `.env` file in project root:
```bash
# /path/to/project/.env
export XAI_API_KEY=sk-project-specific-key
export GROKKIT_MODEL=grok-4-mini
export GROKKIT_LOG_LEVEL=debug
# Load in shell
source .env
grokkit chat # Uses project settings
```
### Per-command Defaults
Use aliases for command-specific models:
```toml
[aliases]
chat = "grok-4" # Best quality for chat
edit = "grok-4" # Precision for edits
review = "grok-4" # Thorough reviews
commit = "grok-4-mini" # Fast for simple commits
history = "grok-4-mini" # Fast summaries
```
```bash
# Manually specify when calling
grokkit chat -m chat
grokkit edit file.go "task" -m edit
```
### Custom History Location
Useful for separating concerns or compliance:
```toml
[chat]
# Separate histories per project
history_file = "~/projects/current/.grokkit-history.json"
# Or don't save history at all
history_file = "/dev/null"
```
### Network-restricted Environments
Adjust timeouts for slow networks:
```toml
timeout = 300 # 5 minutes for slow connections
```
Or use proxy settings:
```bash
export HTTP_PROXY=http://proxy.corp.com:8080
export HTTPS_PROXY=http://proxy.corp.com:8080
grokkit chat
```
## Best Practices
### 1. Keep API Keys Secure
**❌ Don't:**
```toml
# config.toml
api_key = "sk-123..." # ❌ DON'T put in config file
```
**✅ Do:**
```bash
# Use environment variables
export XAI_API_KEY=sk-...
# Or use a secrets manager
export XAI_API_KEY=$(vault kv get -field=key secret/grokkit)
```
### 2. Use Aliases for Workflows
```toml
[aliases]
# Descriptive names
review-critical = "grok-4" # Thorough for critical code
review-routine = "grok-4-mini" # Fast for routine changes
refactor = "grok-4" # Best model for complex refactoring
```
### 3. Adjust Temperature by Use Case
| Use Case | Temperature | Reason |
|----------|-------------|--------|
| Code generation | 0.3 - 0.5 | Predictable, correct code |
| Code review | 0.5 - 0.7 | Balanced analysis |
| Commit messages | 0.5 | Consistent format |
| Documentation | 0.7 | Clear but varied language |
| Creative writing | 0.8 - 1.0 | More variety |
| Debugging | 0.3 | Precise analysis |
### 4. Manage Log Levels
| Environment | Log Level | Reason |
|-------------|-----------|--------|
| Development | `debug` | See everything |
| Staging | `info` | Track operations |
| Production | `warn` | Errors and warnings only |
| CI/CD | `error` | Failures only |
### 5. Set Appropriate Timeouts
| Network | Timeout | Reason |
|---------|---------|--------|
| Fast (LAN) | 30s | Fail fast |
| Normal (broadband) | 60s | Balanced |
| Slow (mobile/VPN) | 120s | Allow completion |
| Restricted (corporate) | 180s | Account for proxies |
### 6. Version Control Config
```bash
# Add template to repo (without secrets)
cat > .grokkit-config.template.toml <<'EOF'
default_model = "grok-4"
temperature = 0.7
timeout = 60
log_level = "info"
[aliases]
dev = "grok-4-mini"
prod = "grok-4"
EOF
# .gitignore
echo "config.toml" >> .gitignore # Don't commit actual config
```
### 7. Document Team Conventions
```toml
# team-config.toml - Team standard configuration
# Copy this file to ~/.config/grokkit/config.toml
default_model = "grok-4"
temperature = 0.7 # Don't change without team discussion
[aliases]
# Use these for consistency
code-review = "grok-4"
quick-commit = "grok-4-mini"
```
## Configuration Schema
Reference for all available options:
```toml
# String: Model identifier
default_model = "grok-4"
# Float: 0.0-1.0 (creativity)
temperature = 0.7
# Integer: Seconds (API timeout)
timeout = 60
# String: "debug" | "info" | "warn" | "error"
log_level = "info"
# Map of string to string
[aliases]
alias_name = "actual-model-name"
# Chat-specific settings
[chat]
history_file = "/path/to/history.json"
```
## Troubleshooting Config
### Check Current Config
```bash
# View config file
cat ~/.config/grokkit/config.toml
# Test with debug mode (shows resolved config)
grokkit chat --debug 2>&1 | head -20
```
### Validate TOML Syntax
```bash
# Online validator
# https://www.toml-lint.com/
# Or install tomll
go install github.com/pelletier/go-toml/v2/cmd/tomll@latest
tomll ~/.config/grokkit/config.toml
```
### Reset to Defaults
```bash
# Backup current config
mv ~/.config/grokkit/config.toml ~/.config/grokkit/config.toml.backup
# App will use defaults
grokkit chat
# Restore if needed
mv ~/.config/grokkit/config.toml.backup ~/.config/grokkit/config.toml
```
---
**See also:**
- [Troubleshooting Guide](TROUBLESHOOTING.md)
- [Architecture Overview](ARCHITECTURE.md)

548
docs/TROUBLESHOOTING.md Normal file
View File

@ -0,0 +1,548 @@
# Troubleshooting Guide
Common issues and solutions for Grokkit.
## Table of Contents
- [Installation Issues](#installation-issues)
- [API & Network Issues](#api--network-issues)
- [Configuration Issues](#configuration-issues)
- [Git Integration Issues](#git-integration-issues)
- [File Operation Issues](#file-operation-issues)
- [Logging Issues](#logging-issues)
- [Performance Issues](#performance-issues)
## Installation Issues
### Go version mismatch
**Symptom:**
```
go: module gmgauthier.com/grokkit requires Go 1.24 or later
```
**Solution:**
```bash
# Check your Go version
go version
# Update Go to 1.24+
# Download from https://go.dev/dl/
```
### Make command not found
**Symptom:**
```
bash: make: command not found
```
**Solution:**
```bash
# macOS
brew install make
# Ubuntu/Debian
sudo apt-get install build-essential
# Fedora
sudo dnf install make
# Or build manually
go build -o grokkit .
```
### Installation to ~/.local/bin fails
**Symptom:**
```
mkdir: cannot create directory '/home/user/.local/bin': Permission denied
```
**Solution:**
```bash
# Create the directory manually
mkdir -p ~/.local/bin
# Add to PATH if not already
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
# Then reinstall
make install
```
## API & Network Issues
### API key not set
**Symptom:**
```
Error: XAI_API_KEY environment variable not set
```
**Solution:**
```bash
# Set for current session
export XAI_API_KEY=sk-your-key-here
# Set permanently (bash)
echo 'export XAI_API_KEY=sk-your-key-here' >> ~/.bashrc
source ~/.bashrc
# Set permanently (zsh)
echo 'export XAI_API_KEY=sk-your-key-here' >> ~/.zshrc
source ~/.zshrc
# Verify
echo $XAI_API_KEY
```
### Request timeout
**Symptom:**
```
Error: Request failed: context deadline exceeded
```
**Solutions:**
**1. Increase timeout in config:**
```toml
# ~/.config/grokkit/config.toml
timeout = 120 # Increase to 120 seconds
```
**2. Check network connectivity:**
```bash
# Test xAI API access
curl -I https://api.x.ai/v1/models
# Check DNS resolution
nslookup api.x.ai
# Test with debug mode
grokkit chat --debug
```
**3. Check for proxy issues:**
```bash
# If behind corporate proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
```
### API rate limiting
**Symptom:**
```
Error: API error (status 429): Rate limit exceeded
```
**Solution:**
```bash
# Wait before retrying
sleep 60
# Use different model
grokkit chat -m grok-4-mini # Faster, cheaper model
# Check your xAI dashboard for limits
```
### SSL/TLS certificate errors
**Symptom:**
```
Error: x509: certificate signed by unknown authority
```
**Solution:**
```bash
# Update CA certificates (Linux)
sudo update-ca-certificates
# Update CA certificates (macOS)
sudo security authorizationdb read com.apple.trust-settings > /tmp/trust.plist
sudo security authorizationdb write com.apple.trust-settings < /tmp/trust.plist
# Or check system time (certificate validation depends on time)
date
```
## Configuration Issues
### Config file not found
**Symptom:**
Config settings don't take effect.
**Solution:**
```bash
# Create config directory
mkdir -p ~/.config/grokkit
# Create config file
cat > ~/.config/grokkit/config.toml <<EOF
default_model = "grok-4"
temperature = 0.7
log_level = "info"
EOF
# Verify location
ls -la ~/.config/grokkit/config.toml
```
### Invalid TOML syntax
**Symptom:**
```
Error: failed to read config
```
**Solution:**
```bash
# Validate TOML syntax online: https://www.toml-lint.com/
# Or check with Go
go run -mod=mod github.com/pelletier/go-toml/v2/cmd/tomll@latest ~/.config/grokkit/config.toml
# Common errors:
# - Missing quotes around strings
# - Wrong indentation in sections
# - Duplicate keys
```
### Model alias not working
**Symptom:**
Using alias returns error or uses wrong model.
**Solution:**
```toml
# ~/.config/grokkit/config.toml
# Ensure aliases section is properly formatted
[aliases]
beta = "grok-beta-2" # ✓ Correct
fast = "grok-4-mini" # ✓ Correct
```
```bash
# Test alias
grokkit chat -m beta --debug # Check which model is actually used
```
## Git Integration Issues
### Not in a git repository
**Symptom:**
```
Error: fatal: not a git repository
```
**Solution:**
```bash
# Initialize git repo if needed
git init
# Or cd into a git repository
cd /path/to/your/repo
# Verify
git status
```
### No staged changes
**Symptom:**
```
No staged changes!
```
**Solution:**
```bash
# Stage your changes first
git add <files>
# Or stage all changes
git add .
# Verify
git status
# Then run grokkit
grokkit commit
```
### Git command not found
**Symptom:**
```
Error: git command failed: exec: "git": executable file not found
```
**Solution:**
```bash
# Install git
# macOS
brew install git
# Ubuntu/Debian
sudo apt-get install git
# Fedora
sudo dnf install git
# Verify
git --version
```
## File Operation Issues
### File not found
**Symptom:**
```
File not found: main.go
```
**Solution:**
```bash
# Check file exists
ls -la main.go
# Use absolute or relative path
grokkit edit ./main.go "instruction"
grokkit edit /full/path/to/main.go "instruction"
# Check current directory
pwd
ls
```
### Permission denied on backup creation
**Symptom:**
```
Failed to create backup: permission denied
```
**Solution:**
```bash
# Check file permissions
ls -la main.go
# Check directory permissions
ls -ld .
# Fix permissions
chmod 644 main.go # File
chmod 755 . # Directory
# Or run from writable directory
```
### Failed to write file
**Symptom:**
```
Failed to write file: permission denied
```
**Solution:**
```bash
# Check if file is read-only
ls -la main.go
# Make writable
chmod 644 main.go
# Check disk space
df -h .
# Check if file is open in another program
lsof | grep main.go
```
## Logging Issues
### Log file permission denied
**Symptom:**
```
Error: failed to open log file: permission denied
```
**Solution:**
```bash
# Fix log directory permissions
chmod 755 ~/.config/grokkit
chmod 644 ~/.config/grokkit/grokkit.log
# Or recreate log directory
rm -rf ~/.config/grokkit
mkdir -p ~/.config/grokkit
```
### Log file too large
**Symptom:**
Log file consuming excessive disk space.
**Solution:**
```bash
# Check log size
du -h ~/.config/grokkit/grokkit.log
# Truncate log file
: > ~/.config/grokkit/grokkit.log
# Or rotate logs manually
mv ~/.config/grokkit/grokkit.log ~/.config/grokkit/grokkit.log.old
gzip ~/.config/grokkit/grokkit.log.old
# Set up log rotation (Linux)
sudo tee /etc/logrotate.d/grokkit <<EOF
/home/*/.config/grokkit/grokkit.log {
weekly
rotate 4
compress
missingok
notifempty
}
EOF
```
### Debug output not showing
**Symptom:**
`--debug` flag doesn't show output.
**Solution:**
```bash
# Ensure you're using the flag correctly
grokkit chat --debug # ✓ Correct
grokkit --debug chat # ✗ Wrong order
# Check log level in config
cat ~/.config/grokkit/config.toml | grep log_level
# Force debug via config
echo 'log_level = "debug"' >> ~/.config/grokkit/config.toml
# Or set via environment
export LOG_LEVEL=debug
```
## Performance Issues
### Slow API responses
**Symptom:**
Requests take very long to complete.
**Solutions:**
**1. Use faster model:**
```bash
grokkit chat -m grok-4-mini
```
**2. Reduce temperature (makes responses more deterministic/faster):**
```toml
# ~/.config/grokkit/config.toml
temperature = 0.3
```
**3. Check network latency:**
```bash
# Test API latency
time curl -s https://api.x.ai/v1/models > /dev/null
# Check DNS resolution time
time nslookup api.x.ai
```
**4. Review logs for timing:**
```bash
# Check actual API duration
cat ~/.config/grokkit/grokkit.log | \
jq 'select(.msg=="API request completed") | {model, duration_ms}'
```
### High memory usage
**Symptom:**
Grokkit consuming excessive memory.
**Solution:**
```bash
# Check memory usage
top -p $(pgrep grokkit)
# Clear chat history if very large
rm ~/.config/grokkit/chat_history.json
# Limit history size (future feature)
# For now, manually trim history file
```
### Chat history growing too large
**Symptom:**
Chat becomes slow or fails to save.
**Solution:**
```bash
# Check history size
du -h ~/.config/grokkit/chat_history.json
# Back up and clear
mv ~/.config/grokkit/chat_history.json \
~/.config/grokkit/chat_history.backup.json
# Or manually trim to last N exchanges
cat ~/.config/grokkit/chat_history.json | \
jq '.messages[-20:]' > ~/.config/grokkit/chat_history.new.json
mv ~/.config/grokkit/chat_history.new.json \
~/.config/grokkit/chat_history.json
```
## Getting Help
If none of these solutions work:
1. **Enable debug mode** to see detailed logging:
```bash
grokkit <command> --debug
```
2. **Check logs** for specific errors:
```bash
tail -100 ~/.config/grokkit/grokkit.log | jq 'select(.level=="ERROR")'
```
3. **Verify environment**:
```bash
# Check versions
go version
git --version
# Check config
cat ~/.config/grokkit/config.toml
# Check API key is set
echo $XAI_API_KEY | sed 's/sk-.*$/sk-***/'
```
4. **Report issue** with:
- Error message
- Command used
- Relevant logs (sanitize API keys!)
- OS and Go version
---
**Still having issues?** Check the [Configuration Guide](CONFIGURATION.md) or [Architecture](ARCHITECTURE.md) docs.