prometheus-go-code-review — скилл Claude Code: установка
Скилл prometheus-go-code-review для Claude Code проверяет Prometheus-метрики в Go: типы, лейблы, имена и регистрацию. Ревьюирует код с prometheus/client_golang.
Apache-2.0 126 установок ★ 89 обновлён 2026-09-15
npx skills add existential-birds/beagle --skill prometheus-go-code-review -a claude-codeЧто делает prometheus-go-code-review
Скилл проверяет, соответствует ли тип метрики её смыслу: Counter для счётчиков, Gauge для текущих значений и Histogram для длительности. Он смотрит на кардинальность лейблов, суффиксы единиц в именах, границы гистограмм и доступность /metrics. В ревью учитываются prometheus/client_golang, promauto, promhttp и MustRegister.
Проверка идёт через последовательные контрольные этапы. Сначала фиксируются файлы, связанные с Prometheus, затем разбираются источники значений лейблов и жизненный цикл регистрации. Отдельные замечания должны ссылаться на файл и по возможности на строку или символ. Лейбл с сырым user_id, полным URL-путём или временной меткой способен создать миллионы временных рядов, а регистрация метрики на каждый запрос приводит к панике при дубликате.
Какие задачи решает
- проверить выбор Counter, Gauge и Histogram
- найти лейблы с неограниченной кардинальностью
- проверить регистрацию метрик вне обработчика запроса
- выявить отсутствующие суффиксы единиц
- проверить публикацию эндпоинта
/metrics
Примеры запросов агенту
- Проверь этот Go-код на ошибки в Prometheus-инструментировании и укажи файлы и символы проблем.
- Проверь, не используют ли метрики в этом изменении
user_id, временные метки или полный URL-путь как значения лейблов. - Проверь, что метрики регистрируются один раз, а эндпоинт
/metricsподключён корректно.
Как установить prometheus-go-code-review
1Через Skills CLI (Vercel)
npx skills add existential-birds/beagle --skill prometheus-go-code-review -a claude-code2Вручную: положить файлы
~/.claude/skills/prometheus-go-code-review/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/prometheus-go-code-review/
1Через Skills CLI (Vercel)
npx skills add existential-birds/beagle --skill prometheus-go-code-review -a codex2Вручную: положить файлы
.agents/skills/prometheus-go-code-review/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add existential-birds/beagle --skill prometheus-go-code-review -a cursor2Вручную: положить файлы
.cursor/skills/prometheus-go-code-review/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install existential-birds/beagle plugins/beagle-go/skills/prometheus-go-code-review2Вручную: положить файлы
.github/skills/prometheus-go-code-review/SKILL.md1Через Skills CLI (Vercel)
npx skills add existential-birds/beagle --skill prometheus-go-code-review -a gemini-cli2Командой платформы
gemini skills install https://github.com/existential-birds/beagle --path plugins/beagle-go/skills/prometheus-go-code-reviewВручную: положить файлы
.devin/skills/prometheus-go-code-review/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add existential-birds/beagle --skill prometheus-go-code-review -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о prometheus-go-code-review
Как установить prometheus-go-code-review в Claude Code?
Выполните npx skills add existential-birds/beagle --skill prometheus-go-code-review -a claude-code, затем проверьте файл ~/.claude/skills/prometheus-go-code-review/SKILL.md.
Что делает prometheus-go-code-review?
Скилл ревьюит Prometheus-инструментирование в Go: выбор типов метрик, кардинальность лейблов, имена с единицами, регистрацию и эндпоинт /metrics.
На чём может сломаться проверка Prometheus-метрик?
Лейблы с неограниченными значениями вроде user_id, полного пути или временной метки создают слишком много временных рядов. Регистрация одной и той же метрики внутри обработчика запроса может вызвать панику из-за дубликата.
Исходный текст
SKILL.md · Apache-2.0
---
name: prometheus-go-code-review
description: Reviews Prometheus instrumentation in Go code for proper metric types, labels, and patterns. Use when reviewing code with prometheus/client_golang metrics.
---
# Prometheus Go Code Review
## Review Checklist
- [ ] Metric types match measurement semantics (Counter/Gauge/Histogram)
- [ ] Labels have low cardinality (no user IDs, timestamps, paths)
- [ ] Metric names follow conventions (snake_case, unit suffix)
- [ ] Histograms use appropriate bucket boundaries
- [ ] Metrics registered once, not per-request
- [ ] Collectors don't panic on race conditions
- [ ] /metrics endpoint exposed and accessible
## Hard gates (sequenced)
Complete in order before recording a **finding**. Skip gates that clearly do not apply to the diff.
1. **Evidence scope** — Enumerate the files you are reviewing that touch Prometheus (`prometheus/client_golang`, `promauto`, `promhttp`, or `MustRegister`). **Pass:** you have a concrete path list (from the diff or an explicit file set); no repo-wide claim without at least one path.
2. **Label cardinality** — For each `*Vec` or labeled metric in scope, list label names and where values come from (constants, bounded codes, vs request-derived strings). **Pass:** no label uses unbounded values (e.g. raw `user_id`, full URL path, timestamps) unless the code uses a bounded mapping and you cite it.
3. **Registration lifecycle** — For metric definitions in scope, confirm constructors run once (package-level `var`, `init`, or `sync.Once`), not inside per-request handlers. **Pass:** no pattern that allocates/registers a new `Counter`/`Histogram`/`*Vec` on every request for the same logical metric.
4. **Finding shape** — Each finding names a file (and line or symbol where possible), states which gate (2 or 3) would fail if the issue is real, and ties to observed code. **Pass:** no standalone style nit when gates 2–3 are satisfied for that code.
## Metric Type Selection
| Measurement | Type | Example |
|-------------|------|---------|
| Requests processed | Counter | `requests_total` |
| Items in queue | Gauge | `queue_length` |
| Request duration | Histogram | `request_duration_seconds` |
| Concurrent connections | Gauge | `active_connections` |
| Errors since start | Counter | `errors_total` |
| Memory usage | Gauge | `memory_bytes` |
## Critical Anti-Patterns
### 1. High Cardinality Labels
```go
// BAD - unique per user/request
counter := promauto.NewCounterVec(
prometheus.CounterOpts{Name: "requests_total"},
[]string{"user_id", "path"}, // millions of series!
)
counter.WithLabelValues(userID, request.URL.Path).Inc()
// GOOD - bounded label values
counter := promauto.NewCounterVec(
prometheus.CounterOpts{Name: "requests_total"},
[]string{"method", "status_code"}, // <100 series
)
counter.WithLabelValues(r.Method, statusCode).Inc()
```
### 2. Wrong Metric Type
```go
// BAD - using gauge for monotonic value
requestCount := promauto.NewGauge(prometheus.GaugeOpts{
Name: "http_requests",
})
requestCount.Inc() // should be Counter!
// GOOD
requestCount := promauto.NewCounter(prometheus.CounterOpts{
Name: "http_requests_total",
})
requestCount.Inc()
```
### 3. Registering Per-Request
```go
// BAD - new metric per request
func handler(w http.ResponseWriter, r *http.Request) {
counter := prometheus.NewCounter(...) // creates new each time!
prometheus.MustRegister(counter) // panics on duplicate!
}
// GOOD - register once
var requestCounter = promauto.NewCounter(prometheus.CounterOpts{
Name: "http_requests_total",
})
func handler(w http.ResponseWriter, r *http.Request) {
requestCounter.Inc()
}
```
### 4. Missing Unit Suffix
```go
// BAD
duration := promauto.NewHistogram(prometheus.HistogramOpts{
Name: "request_duration", // no unit!
})
// GOOD
duration := promauto.NewHistogram(prometheus.HistogramOpts{
Name: "request_duration_seconds", // unit in name
})
```
## Good Patterns
### Metric Definition
```go
var (
httpRequests = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "myapp",
Subsystem: "http",
Name: "requests_total",
Help: "Total HTTP requests processed",
},
[]string{"method", "status"},
)
httpDuration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "myapp",
Subsystem: "http",
Name: "request_duration_seconds",
Help: "HTTP request latencies",
Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10},
},
[]string{"method"},
)
)
```
### Middleware Pattern
```go
func metricsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timer := prometheus.NewTimer(httpDuration.WithLabelValues(r.Method))
defer timer.ObserveDuration()
wrapped := &responseWriter{ResponseWriter: w, status: 200}
next.ServeHTTP(wrapped, r)
httpRequests.WithLabelValues(r.Method, strconv.Itoa(wrapped.status)).Inc()
})
}
```
### Exposing Metrics
```go
import "github.com/prometheus/client_golang/prometheus/promhttp"
func main() {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":9090", nil)
}
```
## Review Questions
1. Are metric types correct (Counter vs Gauge vs Histogram)?
2. Are label values bounded (no UUIDs, timestamps, paths)?
3. Do metric names include units (_seconds, _bytes)?
4. Are metrics registered once (not per-request)?
5. Is /metrics endpoint properly exposed?
© existential-birds · Apache-2.0 · existential-birds/beagle