Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# The files that can weaken the Go-TOPS gate (GO_TOPS.md §11). An edit to any
# of them is a change to the gate and needs the owner's review.
# GitHub ignores a line whose owner lacks write access: the CODEOWNERS errors
# API must return {"errors": []} before this file is a real gate.

/go-tops.yaml @VirtualMachinist
/go-tops.lock @VirtualMachinist
/.go-tops/ @VirtualMachinist
/tools/ @VirtualMachinist
/.github/workflows/go-tops.yml @VirtualMachinist
293 changes: 293 additions & 0 deletions .github/workflows/go-tops.yml

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,11 @@ coverage.txt
.idea/
.vscode/
*.swp

# go-tops:begin (written by gotops init; edit outside these lines)
.go-tops/*
!.go-tops/baseline.json
!.go-tops/acks.yaml
!.go-tops/survivors.yaml
!.go-tops/golangci.yml
# go-tops:end
40 changes: 40 additions & 0 deletions .go-tops/baseline.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"build": {
"cgo_enabled": true,
"goarch": "amd64",
"goos": "linux",
"tags": []
},
"judged_laws": 0,
"ledger": {
"findings": {
"errcheck": {
"cmd/vigil/cli.go": 3,
"cmd/vigil/main_test.go": 4,
"cmd/vigil/nolistener_test.go": 1,
"cmd/vigil/wire_grafana_test.go": 2,
"cmd/vigil/wire_test.go": 3,
"internal/config/config_test.go": 3,
"internal/exitcode/error_test.go": 1,
"internal/exitcode/exitcode_test.go": 1,
"internal/exitcode/semantics_names_test.go": 1,
"internal/grafana/grafana_test.go": 4,
"internal/httpx/httpx_test.go": 15,
"internal/promclient/promclient_test.go": 6,
"internal/render/render_test.go": 10,
"internal/schematest/schematest_test.go": 8,
"internal/sources/sources_test.go": 2
}
},
"functions": {
"github.com/Hedronite/vigil/cmd/vigil.newRoot": 14,
"github.com/Hedronite/vigil/internal/config.Config.validate": 41.88184531464335,
"github.com/Hedronite/vigil/internal/config.Overlay.validate": 12.144,
"github.com/Hedronite/vigil/internal/config.checkAddress": 11.968,
"github.com/Hedronite/vigil/internal/httpx.Client.Get": 14.030955718318758,
"github.com/Hedronite/vigil/internal/httpx.parseBase": 12,
"github.com/Hedronite/vigil/internal/httpx.validPath": 14,
"github.com/Hedronite/vigil/internal/promclient.Query": 23.085848234410218
}
}
}
34 changes: 34 additions & 0 deletions .go-tops/golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# The lint config of the kit's hygiene layer (GO_TOPS.md §4.1, §8.1), read through
# gates.hygiene.golangci_lint.config. The repository's own .golangci.yml is not
# read by the gate and is never written or changed by gotops init: the gate counts
# findings under these rules, and the repository's own lint job keeps its own. The
# errcheck settings match the law pass. Paths in the findings are relative to the
# module (gomod), whatever the directory of this file or the one the gate runs in:
# an anchored exclusion applies only under gomod.
version: "2"

run:
relative-path-mode: gomod

linters:
default: standard
enable:
- depguard
settings:
depguard:
rules:
main:
deny:
- pkg: io/ioutil
desc: deprecated since Go 1.16; use os and io
- pkg: github.com/pkg/errors
desc: archived; use errors and fmt.Errorf with %w
errcheck:
check-blank: true
check-type-assertions: true
exclude-functions:
- (io.ReadCloser).Close

formatters:
enable:
- gofmt
100 changes: 100 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<!-- go-tops:begin -->
# AGENTS.md — Go-TOPS Agent Contract

This file is the contract between this repository and any AI coding agents (or human reviewers) working on it.

**Class:** `binary-service`
**Protocol:** Go-TOPS 0.4.4
**Module:** `github.com/Hedronite/vigil`
**Enforce:** `ratchet`

## Commands

```bash
# Validate config
go tool -modfile=tools/go.mod gotops check

# Run the merge gate (tier ≤ 1)
go tool -modfile=tools/go.mod gotops gate

# Full reports
go tool -modfile=tools/go.mod gotops report --format text
```

## Floors (this class)

- Statement coverage ≥ `75%`
- CRAP cap ≤ `10`, the same for every author
- Error guards that only return the error count 0 toward complexity (`err_guard_discount: true`)
- Unexplained mutation survivors: none (`unexplained_survivors_max` is 0), on lines changed against `origin/main`
- Race detector: required (test jobs run with `CGO_ENABLED=1`; `-race` needs cgo on Linux)
- Under `ratchet`: a function over the cap may not exceed its score in `.go-tops/baseline.json` plus 0.01, and every other function meets the cap. A package under its floor fails only if its coverage percentage falls and its uncovered-statement count rises. No per-file count of lint findings, law findings, `//nolint` or `//tops:ack` comments, or unexplained survivors, and no repo exemption count, rises above its baseline entry. Only `gotops baseline` writes the baseline
- Other class layers: see `go-tops.yaml`

## Policies (non-negotiable)

1. Write the oracle from the contract before the code.
2. Never split a function only to lower its CRAP score (scar-guard).
3. Never weaken a law, linter config, or threshold to make a change pass.
4. Explain every accepted mutation survivor (reason, owner, expiry).
5. No `//nolint` without the linter name and a reason; no `//tops:ack` without a reason and an owner.
6. Agent-authored code meets the same gate and the same CRAP cap as human code.
7. Do not edit generated files; fix the generator.
8. Prefer deleting code to adding configuration.
9. Never edit `.go-tops/baseline.json` by hand, and never wrap old findings in `//nolint` or `//tops:ack` to zero a count.

## Common Agent Mistakes to Attack (explicit targets)

When generating or reviewing code, specifically check for and reject the following high-frequency failure modes. The check that enforces each rule is in brackets. **[review]** means no tool catches it; the reviewer must.

### Error Handling

- **Never** discard errors with `_`. **Bad:** `_, _ = f.Write(data)`, `x, _ := strconv.Atoi(s)`. **[errcheck `check-blank`, G-12]**
- Check the error from `Close`, `Flush` and `Sync` on anything you wrote to. Use a named return and a deferred check that keeps the first error. A deferred `Close` on a reader passed as `io.ReadCloser` (a response body) passes the errcheck `exclude-functions` list, which holds only `(io.ReadCloser).Close`. A read-only file from `os.Open` takes a `//nolint:errcheck` with a reason, which is counted (§6.7 `suppressions`); `_ = f.Close()` fails. A file you wrote to is checked by review. **[errcheck, G-12; review]**
- Always wrap returned errors with operational context: `fmt.Errorf("action %s: %w", id, err)`. **[errorlint, G-11]**
- Use `errors.Is` / `errors.As`. Never match on `err.Error()` strings or direct equality on wrapped errors. **[errorlint, G-11]**
- Do not `panic` or call `Must*` helpers for recoverable conditions in library code. **[G-13]**

### Concurrency & Context

- Never spawn unbounded goroutines. Use `errgroup.WithContext` + `SetLimit` for concurrent work. **[review; G-01 heuristic]**
- Always accept `ctx context.Context` as the first parameter on I/O, DB, and network functions. **[revive `context-as-argument`, G-15, G-16]**
- Never introduce `context.Background()` or `context.TODO()` inside business logic (only allowed in `main`, wiring, and tests). **[G-17]**
- Never pass structs containing `sync.Mutex` or `sync.WaitGroup` by value. **[vet `copylocks`, G-07]**
- Prefer channels for orchestration/ownership transfer; prefer mutexes for protecting shared in-memory state. **[review]**
- No `time.Sleep` in tests to wait for concurrency. Use `testing/synctest` or channels; do not poll. On Go 1.27 or later, inside a `synctest` bubble use `synctest.Sleep(d)` (advances the fake clock, then waits until every other goroutine is durably blocked) and `httptest.NewTestServer(t, handler)` (an in-memory network). **[G-08]**

### Idiomatic Design

- Accept interfaces, return concrete structs. Define small (1–3 method) interfaces in the **consumer** package, not alongside implementations. **[review]**
- Avoid premature `any` / `interface{}` and reflection. Prefer typed structs or constrained generics. **[review]**
- Use the modern standard library: `os.ReadFile`, `slices`, `maps`, `errors`, `math/rand/v2`. Do not use deprecated `io/ioutil`. **[staticcheck deprecation checks]**

### Resources & Performance

- Always set timeouts on `http.Client` / `http.Server`. Never use `http.DefaultClient` in production code. **[G-19]**
- Bound untrusted reads (`io.LimitReader`, `http.MaxBytesReader`). Use `io.ReadAll` only on a bounded reader. **[G-20 heuristic]**
- Close response bodies, rows, files, and timers. Check `rows.Err()`. **[bodyclose, sqlclosecheck, rowserrcheck, G-18]**
- Preallocate slices when the length is known (`make([]T, 0, len(in))`). **[prealloc]**
- Prefer `strings.Builder` over `+=` in loops. **[review]**

### Testing

- Prefer table-driven tests with `t.Run`. **[review]**
- Call `t.Helper()` in test helpers so failures report the caller line. **[thelper]**
- Use `t.Cleanup` for teardown. **[review]**
- Tests must be deterministic: no wall-clock dependence, no unseeded randomness, no live network. **[G-31 heuristic]**

## Verification (before finishing any task)

```bash
go tool -modfile=tools/go.mod gotops gate
```

The gate runs hygiene first (tidy, verify, the toolchain pin, formatting, lint, vulnerabilities, licenses), then the test suite once, with the race detector, shuffling and coverage; coverage, CRAP and mutation read that run. The laws run last. Do not run them separately and call that done. Resolve all failures. A green gate is the definition of done.

---

*Generated by `gotops init`. Update via the protocol change process if laws or floors change.*

<!-- go-tops:end -->
13 changes: 13 additions & 0 deletions GO-TOPS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Go-TOPS adoption record

This repository adopts [Go-TOPS](https://github.com/Hedronite/go-tops). `go-tops.yaml` is the
authority: a line here that disagrees with it is wrong.

1. **Adoption.** Go-TOPS, the Go testing and quality protocol.
2. **Protocol version.** 0.4.4.
3. **`gotops` and pinned tools.** `gotops` v0.0.0-20261119162302-608716388245 (pinned in tools/go.mod). Pins: toolchain go1.27.4 and golangci-lint 2.15.0 (go-tops.lock); go-licenses v2.0.1, gotestsum v1.13.0, govulncheck v1.9.0 (tools/go.mod).
4. **Class and thresholds.** `binary-service`: statement coverage floor 75%, CRAP cap 10, `enforce: ratchet`.
5. **Run the gate locally.** `just gate`, or `go tool -modfile=tools/go.mod gotops gate`. The kit's lint pass reads `.go-tops/golangci.yml`, not this repository's own `.golangci.yml`. The gate finds `golangci-lint` in `.go-tops/bin/` or on `PATH`: a repository whose tests walk the module tree keeps the binary outside it, on `PATH`, because a walk reads the files of `.go-tops/bin/` too. Install the pinned release into a directory outside the checkout, as the workflow's install step does.
6. **Baseline and ledgers.** The baseline is `.go-tops/baseline.json`; only `gotops baseline` writes it, never by hand. It records the build it was measured under, and the run with that build is the ledger leg: this repository's is the `ubuntu` leg of `.github/workflows/go-tops.yml`, and CI fails when that leg reports a ratchet outcome of `skip`. The baseline commands run only on the ledger leg's build. A repository with no ledger gets its first one on the pull request that adds this workflow: the `ubuntu` leg runs `gotops baseline --status`, and when no ledger exists on the base or in the tree it writes one with `gotops baseline --init`, uploads it as the `go-tops-baseline` artifact and fails the run until that file is committed unchanged. Once the workflow is on the default branch, run it by hand (`workflow_dispatch`) and pick `init` to write the first ledger with `gotops baseline --init`, or `refresh` to lower entries with `gotops baseline`; the ubuntu leg runs it and uploads the file as the `go-tops-baseline` artifact, which you commit. A refresh only lowers entries. Raising or adding an entry is manual, with `gotops baseline --accept-regression --reason <text> --owner <handle>`: run it locally on the ledger leg's build, which on another platform is a `linux/amd64` Docker container of `golang:1.27.4` with the repository mounted at `/repo`, `GOTOOLCHAIN=local`, and the pinned golangci-lint 2.15.0 on `PATH` (the workflow's install step shows the archive and its SHA-256). Inside the container run `git config --global --add safe.directory /repo` first, because a checkout mounted on Linux can fail git's dubious-ownership check. The run needs network: the hygiene layer reads the vulnerability database. The mutation survivor ledger is `.go-tops/survivors.yaml`; the acknowledgement ledger is `.go-tops/acks.yaml`.
7. **Exemptions in force.** None.
8. **Known deviations.** The mutation gate is off until 2027-03-01, because the kit builds it in a later milestone; it carries its reason and expiry in `go-tops.yaml`.
24 changes: 24 additions & 0 deletions go-tops.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Pins for the Go toolchain and the downloaded binaries (GO_TOPS.md §10).
# Written by gotops init from the kit's pins; change it with a reviewed gotops lock --update.
protocol: "0.4.4"
toolchain: go1.27.4

trust:
mode: checksum
note: archive SHA-256 values copied from the upstream release checksum file; executable SHA-256 values computed from those verified archives

binaries:
- name: golangci-lint
version: "2.15.0"
url: https://github.com/golangci/golangci-lint/releases/download/v{version}/golangci-lint-{version}-{os}-{arch}.tar.gz
extract: golangci-lint-{version}-{os}-{arch}/golangci-lint
sha256:
darwin/arm64: d1e409481a8ca846c4bc97e781eb5cb1bd5c23353a0b3977a1cbda1b1b6447d5
darwin/amd64: 767b899a28285e88ded2823d5dcc4bc5ef681173eb2d80f029a7b17ee4ece3b8
linux/amd64: 9b7fe6a6bf6334b98decf8d86b11415ea7889afdabdd1959fdce23af2a9ebcea
linux/arm64: b4d8f17068b35ee6060cc2f69a16fb48740d706fbba81661c318649c114a6998
executable_sha256:
darwin/arm64: 71b89744ef6dd92dad9026b70489d1ad660da79ef90dfb5aabe995d916bec8a9
darwin/amd64: e04962742507a5f37a4002a7a8b2b549f6864f17807eb5d534d947f6311a051f
linux/amd64: d9af4564c05beb2f5e130119aec45e5e89d28e5017d558d3ca382659f2427894
linux/arm64: 14680d7674eb1fed0405446670e15dcffb74e979ef0dcd41f998c088fd6babfb
46 changes: 46 additions & 0 deletions go-tops.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Go-TOPS configuration (GO_TOPS.md §9), written by gotops init.
protocol: "0.4.4"
version: "0.1.0"
module: github.com/Hedronite/vigil
class: binary-service
enforce: ratchet # hard | ratchet | advisory (§6.7)
baseline: .go-tops/baseline.json

toolchain:
go_floor: "1.27.0"
go_current: "1.27.4"
cgo: false

gates:
hygiene:
golangci_lint: { config: .go-tops/golangci.yml }
govulncheck: { fail_on: reachable }
deps: { depguard: true, licenses: { allow: [MIT, Apache-2.0, BSD-3-Clause, BSD-2-Clause, ISC] } }
tests:
race: true
shuffle: true
count: 1
coverage:
statements_floor: 75
exclude_generated: true
crap:
enabled: true
cap: 10
complexity: { err_guard_discount: true, wrap_functions: [] }
mutation:
enabled: false
reason: "mutation lands at M4 of the kit"
expires: "2027-03-01"
unexplained_survivors_max: 0
ledger: .go-tops/survivors.yaml

layers:
fuzz: { enabled: false, reason: "tier 2 layers land at M6", targets: [] }
stress: { enabled: false, reason: "tier 2 layers land at M6" }
bench: { enabled: false, reason: "tier 2 layers land at M6", regression_pct: 5 }

laws:
ack_ledger: .go-tops/acks.yaml

report:
path: .go-tops/report.json
18 changes: 18 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Front-door recipes for Go-TOPS (GO_TOPS.md §4.1).
gotops := "go tool -modfile=tools/go.mod gotops"

# Validate go-tops.yaml and go-tops.lock.
check:
{{gotops}} check

# The merge gate: every enabled layer at tier 1 and below.
gate:
{{gotops}} gate

# Print the last report.
report:
{{gotops}} report --format text

# Re-check every tool pin.
lock-verify:
{{gotops}} lock --verify
47 changes: 47 additions & 0 deletions tools/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
module github.com/Hedronite/vigil/tools

go 1.27.4

tool github.com/Hedronite/go-tops/cmd/gotops

require (
github.com/Hedronite/go-tops v0.0.0-20261119162302-608716388245 // indirect
github.com/bitfield/gotestdox v0.2.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dnephin/pflag v1.0.7 // indirect
github.com/fatih/color v1.18.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-logr/logr v1.2.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/google/go-licenses/v2 v2.0.1 // indirect
github.com/google/licenseclassifier/v2 v2.0.0 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/otiai10/copy v1.10.0 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
github.com/sergi/go-diff v1.2.0 // indirect
github.com/spf13/cobra v1.7.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
go.opencensus.io v0.24.0 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/mod v0.42.0 // indirect
golang.org/x/net v0.61.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e // indirect
golang.org/x/term v0.47.0 // indirect
golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.52.0 // indirect
golang.org/x/vuln v1.9.0 // indirect
gotest.tools/gotestsum v1.13.0 // indirect
k8s.io/klog/v2 v2.90.1 // indirect
)

// Added by gotops init: the kit's tool pins (GO_TOPS.md §10).
tool (
github.com/google/go-licenses/v2
golang.org/x/vuln/cmd/govulncheck
gotest.tools/gotestsum
)
Loading
Loading