# Contribution Guidelines

Thank you for considering contributing to Gonzo! It's people like you that make Gonzo such a great tool. This guide covers how to contribute effectively.

### Code of Conduct

This project and everyone participating in it is governed by our Code of Conduct. By participating, you are expected to uphold this code:

* **Be respectful**: Treat everyone with respect and courtesy
* **Be inclusive**: Welcome and support people of all backgrounds
* **Be collaborative**: Work together to improve the project
* **Be professional**: Keep discussions on topic and constructive

### How Can I Contribute?

#### Reporting Bugs

Before creating bug reports, please check [existing issues](https://github.com/control-theory/gonzo/issues) as you might find out that you don't need to create one.

**When creating a bug report, include**:

* **Clear title**: Describe the issue concisely
* **Reproduction steps**: Exact steps to reproduce the problem
* **Expected behavior**: What you expected to happen
* **Actual behavior**: What actually happened
* **Environment details**:
  * Operating System (macOS, Linux, Windows)
  * Go version (`go version`)
  * Gonzo version (`gonzo --version`)
  * Terminal emulator
* **Logs and screenshots**: Include relevant output
* **Sample logs**: Sanitized log files if relevant

**Bug Report Template**:

```markdown
**Describe the bug**
A clear description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. Run command '...'
2. Press key '...'
3. See error

**Expected behavior**
What you expected to happen.

**Screenshots/Logs**
If applicable, add screenshots or log output.

**Environment:**
- OS: [e.g., macOS 14.0]
- Go Version: [e.g., 1.21.5]
- Gonzo Version: [e.g., v0.1.6]
- Terminal: [e.g., iTerm2]

**Additional context**
Any other context about the problem.
```

#### Suggesting Enhancements

Enhancement suggestions are tracked as [GitHub issues](https://github.com/control-theory/gonzo/issues).

**When creating an enhancement suggestion, include**:

* **Clear title**: Describe the enhancement concisely
* **Detailed description**: Explain what you want to add
* **Use cases**: Why would this be useful?
* **Current behavior**: What happens now?
* **Proposed behavior**: What should happen?
* **Examples**: Show how it would work
* **Alternatives**: Have you considered other solutions?

**Enhancement Template**:

```markdown
**Is your feature request related to a problem?**
A clear description of the problem. Ex. I'm frustrated when [...]

**Describe the solution you'd like**
A clear description of what you want to happen.

**Describe alternatives you've considered**
Other solutions or features you've considered.

**Additional context**
Any other context, mockups, or examples.
```

#### Pull Requests

**Before submitting a pull request**:

1. **Fork the repository**
2. **Create your branch** from `main`

   ```bash
   git checkout -b feature/amazing-feature
   ```
3. **Make your changes**
4. **Add tests** if you've added code
5. **Update documentation** if you've changed APIs
6. **Ensure tests pass**

   ```bash
   make test
   ```
7. **Format and lint your code**

   ```bash
   make fmt
   make vet
   ```
8. **Commit your changes**
9. **Push to your fork**
10. **Open a Pull Request**

**Pull Request Checklist**:

* [ ] Code follows the project's style guide
* [ ] Self-review of code completed
* [ ] Comments added for complex code
* [ ] Documentation updated
* [ ] No new warnings introduced
* [ ] Tests added for new features
* [ ] All tests passing
* [ ] Commits follow commit message guidelines

### Development Guidelines

#### Commit Messages

Follow these guidelines for commit messages:

**Format**:

```
<type>: <subject>

<body>

<footer>
```

**Type**:

* `feat`: New feature
* `fix`: Bug fix
* `docs`: Documentation changes
* `style`: Code style changes (formatting, etc.)
* `refactor`: Code refactoring
* `test`: Adding or updating tests
* `chore`: Maintenance tasks

**Rules**:

* Use present tense ("Add feature" not "Added feature")
* Use imperative mood ("Move cursor to..." not "Moves cursor to...")
* Limit first line to 72 characters or less
* Reference issues and pull requests after first line
* Explain *what* and *why*, not *how*

**Examples**:

```
feat: Add support for custom log formats

Implements user-defined regex patterns for parsing non-standard log
formats. Users can now create YAML files in ~/.config/gonzo/formats/
to define custom parsers.

Closes #123
```

```
fix: Resolve race condition in OTLP receiver

The gRPC handler had a race condition when processing concurrent
requests. Added proper locking around shared state.

Fixes #456
```

```
docs: Update installation instructions

Add instructions for installing via Nix package manager.
```

#### Code Style

**Go Code Conventions**:

* **Follow standard Go style**: Use `gofmt` and `goimports`
* **Meaningful names**: Clear, descriptive variable and function names
* **Small functions**: Keep functions focused and concise
* **Comment exports**: All exported functions, types, and constants
* **Handle errors**: Always handle errors explicitly
* **No naked returns**: Always specify return values

**Example - Good**:

```go
// ParseLogLine extracts structured data from a log line.
// Returns an error if the line cannot be parsed.
func ParseLogLine(line string) (*Log, error) {
    if line == "" {
        return nil, fmt.Errorf("empty log line")
    }
    
    log := &Log{}
    if err := json.Unmarshal([]byte(line), log); err != nil {
        return nil, fmt.Errorf("failed to parse JSON: %w", err)
    }
    
    return log, nil
}
```

**Example - Bad**:

```go
func parse(l string) (*Log, error) {
    // No comments, unclear name, no error wrapping
    log := &Log{}
    json.Unmarshal([]byte(l), log)
    return log, nil
}
```

#### Testing Guidelines

**Write tests for**:

* All new functionality
* Bug fixes (test should fail before fix)
* Edge cases and error conditions
* Public APIs

**Test Structure**:

```go
func TestParseLogLine(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    *Log
        wantErr bool
    }{
        {
            name:  "valid JSON log",
            input: `{"level":"info","msg":"test"}`,
            want:  &Log{Level: "info", Message: "test"},
        },
        {
            name:    "invalid JSON",
            input:   `{invalid}`,
            wantErr: true,
        },
        {
            name:    "empty string",
            input:   "",
            wantErr: true,
        },
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := ParseLogLine(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("ParseLogLine() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("ParseLogLine() = %v, want %v", got, tt.want)
            }
        })
    }
}
```

**Test Different Formats**:

* JSON logs
* OTLP format
* Plain text logs
* Logfmt
* Custom formats

#### TUI Guidelines

When working on the terminal UI:

* **Consistent shortcuts**: Don't introduce conflicting key bindings
* **Color usage**: Use colors meaningfully, not decoratively
* **Responsive**: UI should feel snappy
* **Terminal sizes**: Test on different sizes (80x24 minimum)
* **Mouse + keyboard**: Support both input methods
* **Accessibility**: Ensure sufficient color contrast

#### Documentation Guidelines

**Update documentation when you**:

* Add new features
* Change existing behavior
* Add new CLI flags or options
* Modify configuration format

**Documentation to update**:

* `README.md` - Overview, installation, quick start
* `USAGE_GUIDE.md` - Detailed usage instructions
* GitBook docs - Comprehensive documentation
* Code comments - Inline documentation
* Help text - CLI help messages

### Project Structure Reference

Understanding the codebase structure:

```
gonzo/
├── cmd/gonzo/              # Application entry point
│   ├── main.go            # CLI setup and initialization
│   ├── app.go             # Application configuration
│   ├── extractors.go      # Data extraction utilities
│   └── processing.go      # Log processing logic
│
├── internal/              # Private application code
│   ├── tui/              # Terminal UI components (Bubble Tea)
│   │   ├── model.go      # Main Bubble Tea model
│   │   ├── view.go       # Rendering logic
│   │   ├── update.go     # Event handling
│   │   ├── components.go # Reusable UI components
│   │   ├── charts.go     # Chart rendering
│   │   ├── tables.go     # Table components
│   │   ├── modals.go     # Modal dialogs
│   │   ├── navigation.go # Navigation handling
│   │   ├── formatting.go # Text formatting utilities
│   │   ├── severity.go   # Log severity handling
│   │   ├── styles.go     # UI styling definitions
│   │   └── drain3_manager.go # Drain3 integration
│   │
│   ├── analyzer/         # Log analysis engine
│   │   ├── otlp.go      # OTLP log analysis
│   │   └── text.go      # Plain text analysis
│   │
│   ├── memory/           # Frequency tracking
│   │   └── frequency.go  # Frequency counting logic
│   │
│   ├── otlplog/         # OTLP format handling
│   │   ├── converter.go  # OTLP log conversion
│   │   └── detector.go   # OTLP format detection
│   │
│   ├── drain3/          # Drain3 log clustering
│   │   └── impl.go      # Drain3 implementation
│   │
│   ├── ai/              # AI integration
│   │   └── openai.go    # OpenAI API integration
│   │
│   ├── output/          # Output handlers
│   │   └── stdout.go    # Standard output handler
│   │
│   └── reader/          # Input readers
│       └── stdin.go     # Standard input reader
│
├── docs/                # Documentation assets
├── examples/            # Configuration examples
│   └── config.yml      # Example configuration
├── build/              # Build artifacts
├── Makefile            # Build automation
├── go.mod              # Go module definition
└── go.sum              # Go module checksums
```

### Official Color Palette

When creating UI components or skins, use these official colors:

* **Light Blue**: `#0F9EFC`
* **Black**: `#000000`
* **Green**: `#49E209`
* **White**: `#FFFFFF`
* **Dark Blue**: `#081C39`
* **Gray**: `#BCBEC0`

### Development Workflow

#### Before Committing

Run these commands before every commit:

```bash
# Format code
make fmt

# Run linter
make vet

# Run tests
make test

# Build to ensure compilation
make build
```

**Or run all at once**:

```bash
make dev
```

#### Creating a Pull Request

1. **Update your branch** with latest main

   ```bash
   git fetch upstream
   git rebase upstream/main
   ```
2. **Ensure all checks pass**

   ```bash
   make dev
   ```
3. **Push to your fork**

   ```bash
   git push origin feature/my-feature
   ```
4. **Create PR on GitHub**
   * Go to your fork on GitHub
   * Click "Compare & pull request"
   * Fill out the PR template
   * Link related issues
   * Request review from maintainers
5. **Address review feedback**
   * Make requested changes
   * Push updates to same branch
   * Respond to comments
6. **Merge**
   * Maintainer will merge when approved
   * Delete your feature branch after merge

### Release Process

Releases are handled by maintainers:

1. Update version numbers
2. Update `CHANGELOG.md`
3. Create git tag
4. Push tag to trigger release build
5. GitHub Actions creates the release
6. Binaries are automatically built and attached

### Questions?

* **GitHub Issues**: [Open an issue](https://github.com/control-theory/gonzo/issues) with the `question` label
* **GitHub Discussions**: [Start a discussion](https://github.com/control-theory/gonzo/discussions)
* **Email**: Contact maintainers directly

### Thank You!

Thank you for contributing to Gonzo! Every contribution, no matter how small, makes a difference. 🎉

**Related Documentation**:

* Development Setup - Setting up your environment
* Community - Engaging with the community
* Architecture Overview - Understanding the codebase

{% hint style="info" %}
**First time contributor?** Look for issues labeled ["good first issue"](https://github.com/control-theory/gonzo/labels/good%20first%20issue) to get started!
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.controltheory.com/controltheory-documentation/gonzo-docs/contributing/contribution-guidelines.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
