feat(pierre): sanity check

This commit is contained in:
u80864958
2026-02-13 17:27:53 +01:00
parent cc321be658
commit 343f6ab165
11 changed files with 392 additions and 74 deletions

209
AGENTS.md
View File

@@ -1,77 +1,162 @@
# Pierre Bot
---
layout: default
---
Pierre Bot is an intelligent, AI-powered code review assistant designed for Bitbucket Server/Data Center. It automates the initial pass of code review by analyzing Pull Request diffs and identifying potential bugs, logic errors, and style issues using modern LLMs (Google Gemini 2.0 Flash or Ollama).
# AGENTS.md Repository Guidelines for Pierre Bot
## Project Overview
> This document is consulted by autonomous coding agents (including the
> OpenSource `opencode` agent) when they read, modify, test, or lint the
> codebase. It contains the canonical commands for building, testing, and
> linting the project as well as a concise style guide that all Go code must
> follow. The file is deliberately kept around **150lines** to be readable for
> both humans and LLMs.
* **Type:** Go CLI Application
* **Core Function:** Fetches PR diffs from Bitbucket -> Sends to LLM -> Prints structured review comments.
* **Key Technologies:**
* **Language:** Go (1.25+)
* **AI SDKs:** `google/generative-ai-go`, `ollama/ollama`
* **CLI Framework:** `alecthomas/kong`
---
## Architecture
## 1⃣ Build / Run Commands
The project follows a standard Go project layout:
| Command | Description |
|--------|-------------|
| `go build -o bin/pierre ./cmd/pierre/main.go` | Build the binary into `./bin/pierre`. |
| `go run ./cmd/pierre/main.go --help` | Run the CLI with the help flag (fast sanity check). |
| `./bin/pierre --version` | Verify the built binary reports its version. |
* **`cmd/pierre/`**: Contains the `main.go` entry point. It handles configuration parsing (flags, env vars, file), initializes adapters, and orchestrates the application flow.
* **`internal/pierre/`**: Contains the core business logic.
* `judge.go`: Defines the `JudgePR` function which prepares the system prompt and context for the LLM.
* **`internal/chatter/`**: Abstraction layer for LLM providers.
* `gemini.go`: Implements the `ChatAdapter` interface for Google Gemini. notably includes **dynamic JSON schema generation** via reflection (`schemaFromType`) to enforce structured output from the model.
* `ollama.go`: Implements the `ChatAdapter` for Ollama (local models).
* **`internal/gitadapters/`**: Abstraction for Version Control Systems.
* `bitbucket.go`: Client for fetching PR diffs from Bitbucket Server.
> **Tip for agents** always prefer the `./bin/pierre` binary over invoking `go run` in CI or tests; it guarantees the same compilation flags.
## Building and Running
---
### Prerequisites
## 2⃣ Test Commands
* Go 1.25 or later
* Access to a Bitbucket Server instance
* API Key for Google Gemini (or a running Ollama instance)
The project uses the standard Go testing framework.
### Build
| Command | Use case |
|---------|----------|
| `go test ./...` | Run **all** unit and integration tests. |
| `go test ./... -run ^TestJudgePR$` | Run a **single** test (replace `TestJudgePR` with the desired name). |
| `go test -cover ./...` | Run tests and emit a coverage report. |
| `go test -run ^TestName$ -count=1 -v` | Verbose, noncached run for debugging a single test. |
| `go test ./... -bench .` | Execute benchmarks (if any). |
> **Agents should never** invoke `go test` with `-parallel` flags; the default parallelism is sufficient and ensures deterministic ordering for our tabledriven tests.
---
## 3⃣ Lint / Static Analysis
We rely on two lightweight builtin tools plus optional `golangci-lint` when
available.
| Tool | Command | Description |
|------|---------|-------------|
| `go vet ./...` | `go vet ./...` | Detect obvious bugs, misuse of `fmt.Printf`, etc. |
| `staticcheck ./...` | `staticcheck ./...` | Deeper static analysis (must be installed via `go install honnef.co/go/tools/cmd/staticcheck@latest`). |
| `golangci-lint` (optional) | `golangci-lint run` | Runs a configurable suite of linters. Install with `brew install golangci-lint` or `go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest`. |
**Agent tip** when `golangci-lint` is present, run it after `go vet` to catch style
issues early. The CI pipeline (see `.github/workflows/*.yml` if added later) will
use the same commands.
---
## 4⃣ CodeStyle Guidelines (Go)
All changes must satisfy the following conventions. They are enforced by
`go fmt`, `go vet`, and the optional `golangci-lint` config.
### 4.1 Formatting & Imports
* Run `go fmt ./...` before committing. The repository uses **tabindented** Go code.
* Imports are grouped in three blocks, separated by a blank line:
1. **Standard library**
2. **External dependencies** (e.g., `github.com/alecthomas/kong`)
3. **Internal packages** (e.g., `github.com/yourorg/pierre/internal/...`)
* Within each block, imports are sorted alphabetically.
* Use `goimports` (or `golangcilint --fast`) to automatically fix import ordering.
### 4.2 Naming Conventions
| Entity | Rule |
|--------|------|
| Packages | lowercase, no underscores or hyphens. |
| Files | snake_case (`*_test.go` for tests). |
| Types / Structs | PascalCase, descriptive (e.g., `ReviewConfig`). |
| Interfaces | End with `er` when appropriate (e.g., `ChatAdapter`). |
| Variables / Constants | camelCase for locals, PascalCase for exported. |
| Functions | PascalCase if exported, camelCase if private. |
| Constants | Use `CamelCase` for groups, `CONST_NAME` only for truly global values. |
| Test Functions | `TestXxx` and optionally `BenchmarkXxx`. |
### 4.3 Error Handling
* Errors are **never** ignored. Use the blank identifier only when the value is truly irrelevant.
* Wrap contextual information using `fmt.Errorf("context: %w", err)` or `errors.Wrap` if the project imports `github.com/pkg/errors` (currently not used).
* Return errors **as soon as** they are detected "guard clause" style.
* In public APIs, prefer error values over panics. Panics are limited to unrecoverable
programming errors (e.g., nilpointer dereference in `init`).
### 4.4 Documentation & Comments
* Exported identifiers **must** have a preceding doc comment beginning with the name (e.g., `// JudgePR reviews a PR and returns comments.`).
* Inline comments should be sentencecase and end with a period.
* Use `//go:generate` directives sparingly; they must be accompanied by a test that ensures the generated file is uptodate.
### 4.5 Testing Practices
* Keep tests **tabledriven** where possible; this yields concise, readable test suites.
* Use the `testing` package only; avoid thirdparty test frameworks.
* Prefer `t.Fatalf` for fatal errors and `t.Errorf` for nonfatal assertions.
* When comparing complex structs, use `github.com/google/go-cmp/cmp` (already in `go.mod`).
* Test coverage should be **80%** for new code.
* All tests must be **deterministic** no reliance on external services; use mocks or fakes.
### 4.6 Dependency Management
* All dependencies are managed via Go modules (`go.mod`).
* Run `go mod tidy` after adding/removing imports.
* Do not commit `vendor/` unless a vendoring strategy is explicitly adopted.
### 4.7 Logging & Output
* Use the standard library `log` package for uservisible output.
* For structured logs (debug mode), wrap with a small helper that respects the `--debug` flag.
* CLI output must be **machineparsable** when `--json-output` is set (future feature).
---
## 5⃣ Git & PullRequest Workflow (for agents)
1. **Branch naming** `feature/<shortdesc>` or `bugfix/<shortdesc>`.
2. **Commits** One logical change per commit, with a concise subject line (<50chars) and an optional body explaining *why* the change was needed.
3. **CI** Every PR must pass `go test ./...`, `go vet ./...`, and `golangcilint run` (if configured).
4. **Review** Agents should add comments only via the LLM; do not edit code generated by the LLM unless a test fails.
5. **Rebasing** Keep a linear history; use `git rebase -i` locally before merging.
---
## 6⃣ Cursor / Copilot Rules (None Present)
The repository does not contain a `.cursor` directory or a `.github/copilotinstructions.md`
file. If such files are added in the future, agents should read them and incorporate
any additional constraints into this document.
---
## 7⃣ Quick Reference CheatSheet (for agents)
```bash
go build -o pierre ./cmd/pierre/main.go
# Build
go build -o bin/pierre ./cmd/pierre/main.go
# Run single test (replace TestFoo)
go test ./... -run ^TestFoo$ -v
# Lint & Vet
go vet ./...
staticcheck ./...
# optional
golangci-lint run
# Format & Imports
go fmt ./...
goimports -w .
# Module tidy
go mod tidy
```
### Configuration
---
Configuration is handled via `kong` and supports a hierarchy: **Flags > Env Vars > Config File**.
**1. Environment Variables:**
* `BITBUCKET_URL`: Base URL of the Bitbucket instance.
* `BITBUCKET_TOKEN`: Personal Access Token (HTTP) for Bitbucket.
* `LLM_PROVIDER`: `gemini` or `ollama`.
* `LLM_API_KEY`: API Key for Gemini.
* `LLM_MODEL`: Model name (e.g., `gemini-2.0-flash`).
**2. Configuration File (`config.yaml`):**
See `config.example.yaml` for a template. Place it in the current directory or `~/.pierre.yaml`.
### Usage
Run the bot against a specific Pull Request:
```bash
# Syntax: ./pierre [flags] <PROJECT_KEY> <REPO_SLUG> <PR_ID>
./pierre --llm-provider=gemini --llm-model=gemini-2.0-flash MYPROJ my-repo 123
```
## Development Conventions
* **Structured Output:** The bot relies on the LLM returning valid JSON matching the `Comment` struct. This is enforced in `internal/chatter/gemini.go` by converting the Go struct definition into a `genai.Schema`.
* **Dependency Injection:** Adapters (`gitadapters`, `chatter`) are initialized in `main` and passed to the core logic, making testing easier.
* **Error Handling:** strict error checks are preferred; the bot will exit if it cannot fetch the diff or initialize the AI.
## Key Files
* **`cmd/pierre/main.go`**: Application entry point and config wiring.
* **`internal/pierre/judge.go`**: The "brain" that constructs the prompt for the AI.
* **`internal/chatter/gemini.go`**: Gemini integration logic, including the reflection-based schema generator.
* **`config.example.yaml`**: Reference configuration file.
*End of AGENTS.md*