compliance

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 16 Imported by: 0

README

go-compliance

Fleet compliance evidence for every LarsArtmann project: one state model (compliant / failing / stale / never-covered), one frozen wire contract, a realtime WebUI, and adapters instead of per-project plumbing.

Status: built, pre-release. Core module and hub are built and tested: state model, evidence fold, frozen v1 contract, reporter SDK, the hub service with realtime WebUI, SQLite cache, and discovery adapter. See FEATURES.md and STACK.md.

Fleet compliance table

Realtime fleet dashboard

Architecture

  • Core module (github.com/larsartmann/go-compliance) — domain types, state derivation over evidence windows, the frozen v1 contract, a Source adapter interface, and a one-liner reporter SDK. Two dependencies (go-branded-id, go-error-family).
  • Hub module (github.com/larsartmann/go-compliance/hub) — HTTP service with a realtime WebUI (Datastar over SSE), the CLI (compliance serve|report|table), a SQLite evidence cache, and adapters: BuildFlow evidence (v1 JSON), project-discovery-daemon (fleet list → never-covered).

Integration goal: BuildFlow-covered projects are compliant by default (zero changes); everything else reports with one CLI line or one SDK call.

Embedding the dashboard

Any Go service can mount the realtime fleet dashboard in one call:

hub := events.NewHub()                       // publish snapshots/refreshes here
board := dashboard.New(hub)

mux := http.NewServeMux()
board.RegisterRoutes(mux)                    // / (page), /events (patches), /datastar.js

Feed it evidence and everything downstream updates live:

rows := events.RowsFromEvidence(evidence, time.Now(), staleAfter)
published, err := hub.PublishRefresh(rows)   // snapshot first, diffs after

RegisterRoutesAt(dashboard.Routes{...}, mux) relocates the surface (e.g. behind /compliance/); the page route serves JSON to Accept: application/json clients.

Or run the packaged service: compliance-hub serve --source file --file compliance.json (also --source buildflow, --source cache --db path).

Health surface (packaged service)

serve exposes the standard probe routes for systemd, Kubernetes, or a scraping dashboard:

Route Meaning
/healthz Liveness, always passes (an evidence failure must not restart the process)
/readyz 503 until evidence is published; degraded-but-serving stays 200
/startupz Startup latch, passes once the critical evidence check first passes
/version Build version stamp

Checks: evidence (critical gate), cache-disk (128 MiB floor, only with --db), refresh-freshness and discovery (warn when their loop stalls past 10 minutes), sse-backpressure (warn on new patch drops). Shutdown drains honestly: readiness flips to 503 before the listeners close.

CI

.github/workflows/ci.yml runs per-module build+test and lint (golangci-lint pinned to the devShell version), dprint, actionlint, stack-drift-check, docs-gates, and nix flake check.

The hub module and the flake build need one private dependency (github.com/LarsArtmann/go-daemon). CI reads it via a repository secret:

  • FLAKE_PAT — fine-grained PAT with read-only Contents on LarsArtmann/go-daemon. Without it, the hub/flake jobs skip (not fail); an owner must create the secret on each runner host (GitHub and Forgejo) to activate them.

Documentation

Documentation

Overview

Package compliance is the fleet compliance core: one state model over per-project evidence windows, the frozen v1 wire contract, a Source adapter interface, and a one-liner reporter SDK.

The state model ports from BuildFlow's `compliance` command and stays byte-compatible with its v1 JSON contract (schema_version 1), which the overview dashboard consumes. BuildFlow-schema SQL stays in BuildFlow, behind a Source adapter.

Core surfaces:

  • State/Verdict and DeriveState: the state model (compliant, failing, stale, plus the never-covered extension for repositories a discovery source knows but evidence does not).
  • RepoEvidence/FoldEvidence: source-agnostic per-repo evidence and the ensure/union fold that BuildFlow's SQL queries feed.
  • V1Report/BuildV1Report/MarshalV1/DecodeV1Report: the frozen v1 wire contract, byte-faithful to the BuildFlow producer and schema-pinned against the overview consumer (golden-tested in both directions against a real producer fixture).
  • Source/EvidenceWriter and Record: the adapter interface and the one-liner reporter SDK.
  • FileSource/CommandSource: evidence adapters for piped v1 documents and CLI-spawned producers (the BuildFlow integration).

Dependency policy: this core module carries go-branded-id and go-error-family only. The UI/realtime/CLI stack lives in the hub module (github.com/larsartmann/go-compliance/hub). See STACK.md.

Index

Examples

Constants

View Source
const (
	DefaultCommandTimeout = 30 * time.Second
	DefaultCommandMaxOut  = 64 << 20 // 64 MiB
)

Producer defaults mirroring the overview consumer's exec contract: a bounded read (a misbehaving producer is an error, not an OOM) and a source-scoped timeout.

View Source
const (
	DefaultWindow     = 7 * 24 * time.Hour
	DefaultStaleAfter = 14 * 24 * time.Hour
	DefaultWorstSteps = 3
)

Default window parameters, mirroring the fleet sweep cadence: 7 days of evidence window, 14 days until a repository counts as stale, 3 worst steps per repository.

View Source
const DefaultEvidenceFile = "/var/lib/overview/compliance.json"

DefaultEvidenceFile is the fleet-standard piped-evidence location: the daemon recipe writes `buildflow compliance --json` there because the unprivileged overview service cannot read BuildFlow's state directory.

View Source
const EnvEvidenceFile = "GO_COMPLIANCE_EVIDENCE_FILE"

EnvEvidenceFile overrides the Record default target.

View Source
const SchemaVersionV1 = 1

SchemaVersionV1 is the wire contract version of the compliance JSON document. The overview consumer rejects any other value: a changed contract needs a conscious bump on both sides, never a silent misparse. v1 stays emittable forever.

Variables

View Source
var (
	ErrValidation        = errors.New("compliance: validation error")
	ErrIO                = errors.New("compliance: I/O error")
	ErrParse             = errors.New("compliance: parse error")
	ErrUnsupportedSchema = errors.New("compliance: unsupported schema version")
	ErrInternal          = errors.New("compliance: internal error")
)

Sentinel errors for use with errors.Is.

Functions

func FormatWireTime

func FormatWireTime(t time.Time) string

FormatWireTime renders a time as the wire timestamp format (RFC 3339, nanosecond precision, UTC); the zero time renders as the empty string.

func MarshalV1

func MarshalV1(report V1Report) ([]byte, error)

MarshalV1 encodes a report deterministically (sorted map keys, struct field order). BuildFlow's producer does not sort map keys; sorted keys are a canonical subset of valid v1 and decode identically everywhere.

func ParseWireTime

func ParseWireTime(raw string) time.Time

ParseWireTime parses a wire timestamp, accepting both RFC 3339 nanosecond and second precision; empty and malformed values return the zero time.

func Record

func Record(ctx context.Context, repo RepoName, result RunResult) error

Record writes one repository's run evidence to the default fleet document: $GO_COMPLIANCE_EVIDENCE_FILE when set, else /var/lib/overview/compliance.json. It is the one-liner integration:

err := compliance.Record(ctx, compliance.NewRepoName("my-repo"),
	compliance.RunResult{Verdict: compliance.VerdictPassed})

The repository's row is replaced when the result is at least as new as the stored last run; older results are ignored (parallel reporters cannot regress the document). Severities are dropped: the frozen v1 contract has no field for them.

Example

ExampleRecord shows the one-liner integration: report one repository's run evidence into the fleet document. Point GO_COMPLIANCE_EVIDENCE_FILE at your evidence sink (a CI step, a post-build hook, a timer) and every dashboard consuming the v1 contract sees the repository.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/larsartmann/go-compliance"
)

func main() {
	dir, _ := os.MkdirTemp("", "compliance-example-*")
	defer func() { _ = os.RemoveAll(dir) }()

	_ = os.Setenv(compliance.EnvEvidenceFile, dir+"/compliance.json")
	defer func() { _ = os.Unsetenv(compliance.EnvEvidenceFile) }()

	err := compliance.Record(context.Background(), compliance.NewRepoName("my-repo"),
		compliance.RunResult{
			Verdict:         compliance.VerdictPassed,
			GateFindings:    map[string]int{"lint": 2},
			ProducerVersion: "v1.4.2",
		})
	fmt.Println("recorded:", err)

	report, _ := compliance.NewFileStore(dir + "/compliance.json").Load(context.Background())
	fmt.Println("repos:", len(report.Repos), "state:", report.Repos[0].State)
}
Output:
recorded: <nil>
repos: 1 state: compliant

func RecordTo

func RecordTo(ctx context.Context, writer EvidenceWriter, repo RepoName, result RunResult) error

RecordTo writes one repository's run evidence to an explicit writer.

Types

type CommandSource

type CommandSource struct {
	// contains filtered or unexported fields
}

CommandSource spawns a producer CLI and decodes its v1 JSON from stdout - the integration mode for producers that own their evidence store (BuildFlow: `buildflow compliance --json`).

func NewBuildFlowCommandSource

func NewBuildFlowCommandSource() *CommandSource

NewBuildFlowCommandSource returns a CommandSource spawning the BuildFlow CLI with the v1 contract flags.

func NewCommandSource

func NewCommandSource(command string, args ...string) *CommandSource

NewCommandSource returns a CommandSource running command with args (which must select the v1 JSON output, e.g. "compliance", "--json").

func (*CommandSource) Name

func (s *CommandSource) Name() SourceName

Name implements Source.

func (*CommandSource) QueryEvidence

func (s *CommandSource) QueryEvidence(
	ctx context.Context, since time.Time, worstStepLimit int, stepFilter string,
) ([]RepoEvidence, error)

QueryEvidence implements Source, mapping the window onto the producer's flags: --since (the window length), --worst-steps, and --step for the exact-name step filter.

func (*CommandSource) WithMaxOutput

func (s *CommandSource) WithMaxOutput(limit int64) *CommandSource

WithMaxOutput overrides the bounded-read limit.

func (*CommandSource) WithTimeout

func (s *CommandSource) WithTimeout(timeout time.Duration) *CommandSource

WithTimeout overrides the exec timeout.

type Error

type Error struct {
	Category ErrorCategory // Behavioral category
	Message  string        // Human-readable message
	Cause    error         // Underlying cause (may be nil)
}

Error provides structured error information with context. Every error the package returns is a *Error, so callers can errors.Is against the sentinels and errorfamily.Classify works on compliance errors.

func NewIOError

func NewIOError(cause error, format string, args ...any) *Error

NewIOError wraps a file system or network failure as an I/O error.

func NewInternalError

func NewInternalError(cause error, format string, args ...any) *Error

NewInternalError wraps an internal failure.

func NewParseError

func NewParseError(cause error, format string, args ...any) *Error

NewParseError wraps a decoding failure as a parse error.

func NewUnsupportedSchemaError

func NewUnsupportedSchemaError(got, want int) *Error

NewUnsupportedSchemaError reports a decoded schema_version the consumer does not support: a changed contract needs a conscious bump on both sides, never a silent misparse (mirrors the overview consumer).

func NewValidationError

func NewValidationError(format string, args ...any) *Error

NewValidationError returns a validation error (formatted message, no cause).

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) ErrorCode

func (e *Error) ErrorCode() string

ErrorCode implements errorfamily.Coded.

func (*Error) ErrorFamily

func (e *Error) ErrorFamily() errorfamily.Family

ErrorFamily implements errorfamily.Classified, mapping categories to go-error-family families for integration with Classify().

func (*Error) Is

func (e *Error) Is(target error) bool

Is supports errors.Is by matching the sentinel of the error's category.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause for error inspection.

type ErrorCategory

type ErrorCategory string

ErrorCategory categorizes errors for programmatic handling.

const (
	// ErrCategoryValidation indicates invalid input or contract misuse.
	ErrCategoryValidation ErrorCategory = "validation"
	// ErrCategoryIO indicates file system or network errors (retryable).
	ErrCategoryIO ErrorCategory = "io"
	// ErrCategoryParse indicates decoding malformed payloads.
	ErrCategoryParse ErrorCategory = "parse"
	// ErrCategoryUnsupported indicates an unsupported contract version.
	ErrCategoryUnsupported ErrorCategory = "unsupported"
	// ErrCategoryInternal indicates internal logic errors.
	ErrCategoryInternal ErrorCategory = "internal"
)

func (ErrorCategory) IsValid

func (c ErrorCategory) IsValid() bool

IsValid reports whether the category is a known lowercase-hyphenated category.

art-dupl:accept the case list IS the canonical member set; a shared membership helper would obscure it

type EvidenceWriter

type EvidenceWriter interface {
	WriteEvidence(ctx context.Context, repo RepoName, result RunResult) error
}

EvidenceWriter is the write-side port for reporters: somewhere a repository's run evidence can be recorded.

type FileSource

type FileSource struct {
	// contains filtered or unexported fields
}

FileSource reads a piped v1 document from disk - the daemon-mode recipe: a system timer writes `buildflow compliance --json` to /var/lib/overview/compliance.json and every consumer reads the file.

func NewBuildFlowFileSource

func NewBuildFlowFileSource() *FileSource

NewBuildFlowFileSource returns a FileSource for the fleet-standard piped BuildFlow evidence document.

func NewFileSource

func NewFileSource(path string) *FileSource

NewFileSource returns a FileSource for the given path.

func (*FileSource) Name

func (s *FileSource) Name() SourceName

Name implements Source.

func (*FileSource) Path

func (s *FileSource) Path() string

Path returns the document path.

func (*FileSource) QueryEvidence

func (s *FileSource) QueryEvidence(
	_ context.Context, _ time.Time, worstStepLimit int, _ string,
) ([]RepoEvidence, error)

QueryEvidence implements Source. The frozen document is already aggregated, so stepFilter is ignored (documented Source contract) and worstStepLimit can only truncate the delivered worst-steps lists.

func (*FileSource) WithMissingBackoff

func (s *FileSource) WithMissingBackoff(ttl time.Duration) *FileSource

WithMissingBackoff sets the missing-file backoff TTL and returns the source for chaining.

type FileStore

type FileStore struct {
	// contains filtered or unexported fields
}

FileStore is a file-backed EvidenceWriter over the v1 fleet document: locked read-modify-write with an atomic rename. A missing file starts a fresh document.

func NewFileStore

func NewFileStore(path string) *FileStore

NewFileStore returns a FileStore for the given document path.

func (*FileStore) Load

func (s *FileStore) Load(ctx context.Context) (V1Report, error)

Load returns the current document; a missing file yields a fresh empty v1 document (a reporter may start one). Use ReadDocument when missing files must be distinguished.

func (*FileStore) Path

func (s *FileStore) Path() string

Path returns the document path.

func (*FileStore) WriteEvidence

func (s *FileStore) WriteEvidence(ctx context.Context, repo RepoName, result RunResult) error

WriteEvidence implements EvidenceWriter.

type FoldInput

type FoldInput struct {
	// WindowHealth overwrites the window-bounded counters per repo.
	WindowHealth []WindowHealth
	// LatestRuns overwrites the all-history latest-run fields per repo.
	LatestRuns []LatestRun
	// WorstSteps caps at WorstStepLimit (<= 0 → DefaultWorstSteps) and
	// overwrites the per-repo worst-steps list.
	WorstSteps []RepoSteps
	// GateFindings and FindingSeverities attach only when non-empty.
	GateFindings []RepoFindings
	// FindingSeverities attach only when non-empty.
	FindingSeverities []RepoSeverities
	// Versions attach only to already-materialized repositories.
	Versions []RepoVersions
	// WorstStepLimit caps the per-repo worst-steps list.
	WorstStepLimit int
}

FoldInput carries the source-agnostic evidence parts the fold unions. Every part is optional; a source that cannot answer one leaves it nil.

type LatestRun

type LatestRun struct {
	Repo     RepoName
	RepoHash string
	// LastRunAt is the newest recording of the run; the zero value means
	// no rows exist.
	LastRunAt  time.Time
	AnyFailed  bool
	HasVerdict bool
	Version    string
}

LatestRun is a repository's most recent run over ALL history: the join key that lets a repository which stopped running still report its true last verdict and be classified stale.

func (LatestRun) Verdict

func (r LatestRun) Verdict() Verdict

Verdict maps the run's outcome onto the contract vocabulary. Unknown when the repository has no rows at all (the consumer renders an unknown verdict rather than guessing).

type MemoryStore

type MemoryStore struct {
	// contains filtered or unexported fields
}

MemoryStore is an in-process EvidenceWriter: the newest result per repository, kept as rich RepoEvidence. Safe for concurrent use.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty MemoryStore.

func (*MemoryStore) Evidence

func (m *MemoryStore) Evidence() []RepoEvidence

Evidence returns the stored evidence in first-write order.

func (*MemoryStore) WriteEvidence

func (m *MemoryStore) WriteEvidence(_ context.Context, repo RepoName, result RunResult) error

WriteEvidence implements EvidenceWriter.

type RepoBrand

type RepoBrand struct{}

RepoBrand brands repository names so they cannot be mixed with other string-shaped identifiers at compile time.

func (RepoBrand) Name

func (RepoBrand) Name() string

Name implements the branded-id naming interface ("Repo:go-finding").

type RepoEvidence

type RepoEvidence struct {
	Repo RepoName
	// RepoHash is the latest run's repository path hash: an opaque join
	// key for host-local display data (BuildFlow uses it to mark
	// missing-on-disk checkouts). Not part of the v1 wire contract.
	RepoHash string
	Runs     int64
	StepRows int64
	Failures int64
	FailRate float64
	// LastRunAt is the newest recording of the repo's latest run; the
	// zero value means the repo has no rows at all.
	LastRunAt time.Time
	// LastRunVerdict is the latest run's verdict: passed, failed, or
	// unknown (empty) when no rows exist.
	LastRunVerdict Verdict
	// LastRunVersion is the producer version of the latest run's newest
	// row; empty when no rows. Not part of the v1 wire contract.
	LastRunVersion string
	// GateFindings is the latest run's per-step finding counts
	// ({step: count}).
	GateFindings map[string]int
	// FindingSeverities aggregates the latest run's severity counts
	// ({severity: count}); display surfaces render it as ERR/WARN/INFO
	// columns. Not part of the v1 wire contract.
	FindingSeverities map[string]int
	Versions          []string
	WorstSteps        []StepEvidence
}

RepoEvidence is one repository's complete compliance evidence.

Window fields (Runs/StepRows/Failures/WorstSteps/Versions) are bounded by the evidence window; LastRunAt/LastRunVerdict/GateFindings come from the repo's ALL-HISTORY latest run, so a repository that stopped running still reports its true last verdict and can be classified stale. Under a step filter the same fields describe THAT step's rows only (Runs = runs containing the step, latest run = the step's latest run).

The zero value means "never measured": DeriveState maps it to never-covered. RepoHash/LastRunVersion/FindingSeverities feed display surfaces only and are deliberately not part of the v1 wire contract.

func CompleteWithDiscovery

func CompleteWithDiscovery(evidence []RepoEvidence, discovered []RepoName) []RepoEvidence

CompleteWithDiscovery unions evidence with the discovery source's repository list: repositories a discovery source knows but for which no evidence exists get a zero RepoEvidence row, which DeriveState maps to never-covered. The result is sorted by repository name, deterministic regardless of input order.

func FoldEvidence

func FoldEvidence(input FoldInput) []RepoEvidence

FoldEvidence folds the evidence parts into per-repo evidence.

Repositories are never dropped for being quiet: the union of window repos and all-history repos is returned, so the consumer can render stale (or never-covered, via discovery) rather than unknown. The output is sorted by repository name - deterministic regardless of input order.

func V1ReportToEvidence

func V1ReportToEvidence(report V1Report, worstStepLimit int) []RepoEvidence

V1ReportToEvidence normalizes a decoded wire document into rich RepoEvidence. Fields the contract cannot carry (severities, repo hash, last-run producer version) are absent; states re-derive identically from the normalized evidence when using the document's own GeneratedAt/StaleAfter (golden-tested against a real producer).

func (RepoEvidence) HasEvidence

func (e RepoEvidence) HasEvidence() bool

HasEvidence reports whether any evidence at all exists for the repository: runs, step rows, or a last-run recording. False means the zero RepoEvidence (or an equivalent never-measured row), which derives as never-covered.

type RepoFindings

type RepoFindings struct {
	Repo     RepoName
	Findings map[string]int
}

RepoFindings delivers one repository's latest-run gate findings ({step: count}).

type RepoName

type RepoName = id.ID[RepoBrand, string]

RepoName identifies one repository in the fleet (e.g. "go-finding"). The zero value means "unset" and serializes to JSON null.

func NewRepoName

func NewRepoName(raw string) RepoName

NewRepoName brands a raw repository name.

type RepoSeverities

type RepoSeverities struct {
	Repo       RepoName
	Severities map[string]int
}

RepoSeverities delivers one repository's latest-run severity counts ({severity: count}).

type RepoSteps

type RepoSteps struct {
	Repo  RepoName
	Steps []StepEvidence
}

RepoSteps delivers one repository's failing-step aggregates, worst-first as ordered by the source; the fold caps the list.

type RepoVersions

type RepoVersions struct {
	Repo     RepoName
	Versions []string
}

RepoVersions delivers one repository's producer versions seen in the window. ATTACH-ONLY in the fold: a repository known only through its versions is never materialized (version skew is a property of repos with runs, not a signal that a repo exists).

type RunResult

type RunResult struct {
	// At is when the run finished.
	At time.Time
	// Verdict is the run's outcome (passed or failed).
	Verdict Verdict
	// Runs is the number of runs this result aggregates (default 1).
	Runs int64
	// StepRows is the number of step rows recorded.
	StepRows int64
	// Failures is the number of failed step rows.
	Failures int64
	// FailRate is failures over opportunities; derived when zero.
	FailRate float64
	// GateFindings is the per-step finding count ({step: count}).
	GateFindings map[string]int
	// FindingSeverities is the severity rollup ({severity: count}); the
	// v1 wire contract cannot carry it, so file-backed writers drop it
	// (the hub cache keeps it).
	FindingSeverities map[string]int
	// ProducerVersion identifies the reporting system.
	ProducerVersion string
}

RunResult is what a reporter records for one repository run. Zero values are filled: At defaults to the record time, Runs to 1, FailRate to Failures/StepRows (or Failures/Runs when no step rows), and the nil maps/slices to their empty wire shapes.

func (RunResult) ResolvedAt

func (r RunResult) ResolvedAt() time.Time

ResolvedAt returns the result time, defaulting to now.

func (RunResult) ResolvedRuns

func (r RunResult) ResolvedRuns() int64

ResolvedRuns returns the aggregated run count, defaulting to 1.

type Source

type Source interface {
	// Name identifies the source for display and provenance.
	Name() SourceName
	// QueryEvidence returns per-repo evidence for the [since, now)
	// window. worstStepLimit caps per-repo worst-steps (<= 0 → default).
	// stepFilter scopes the evidence to ONE step by exact name where the
	// source supports it; empty means all steps. Sources that cannot
	// scope (a frozen v1 document is already aggregated) ignore it.
	QueryEvidence(
		ctx context.Context,
		since time.Time,
		worstStepLimit int,
		stepFilter string,
	) ([]RepoEvidence, error)
}

Source is a read-side evidence adapter: something that can produce per-repo compliance evidence for an evidence window. Implementations range from a piped v1 document (FileSource), a spawned producer CLI (CommandSource), to the hub's own SQLite cache.

type SourceBrand

type SourceBrand struct{}

SourceBrand brands evidence-source names.

func (SourceBrand) Name

func (SourceBrand) Name() string

Name implements the branded-id naming interface ("Source:buildflow").

type SourceFunc

type SourceFunc func(ctx context.Context, since time.Time, worstStepLimit int, stepFilter string) ([]RepoEvidence, error)

SourceFunc adapts a function to the Source interface.

func (SourceFunc) Name

func (SourceFunc) Name() SourceName

Name implements Source with a generic name.

func (SourceFunc) QueryEvidence

func (f SourceFunc) QueryEvidence(
	ctx context.Context, since time.Time, worstStepLimit int, stepFilter string,
) ([]RepoEvidence, error)

QueryEvidence implements Source by calling the function.

type SourceName

type SourceName = id.ID[SourceBrand, string]

SourceName identifies one evidence source (e.g. "buildflow", "hub-cache"). The zero value means "unset" and serializes to JSON null.

func NewSourceName

func NewSourceName(raw string) SourceName

NewSourceName brands a raw source name.

type State

type State string

State is one repository's compliance state.

The v1 wire contract (schema_version 1) carries exactly compliant, failing, and stale; overview mirrors those verbatim and re-derives nothing. never-covered is a go-compliance extension for repositories a discovery source knows exist but for which no evidence exists at all: it is derived locally (never emitted into a v1 document unless the producer explicitly builds extended rows).

const (
	// StateCompliant means the window carries evidence, no failures, and
	// the last run is fresh enough.
	StateCompliant State = "compliant"
	// StateFailing means any failed step row exists in the window (honest
	// fleet semantics - retries each add a row).
	StateFailing State = "failing"
	// StateStale means the last run is older than the staleness
	// threshold: no fresh evidence is itself evidence of neglect.
	StateStale State = "stale"
	// StateNeverCovered means no evidence exists at all: the repository
	// is known (via discovery) but has never been measured.
	StateNeverCovered State = "never-covered"
)

func DeriveState

func DeriveState(evidence RepoEvidence, now time.Time, staleAfter time.Duration) State

DeriveState implements the compliance state model.

Any failed step row in the window is failing; a last run older than staleAfter is stale; otherwise compliant. staleAfter <= 0 disables the staleness arm. A repository with NO evidence at all (no runs, no step rows, no last run - the zero RepoEvidence, minted for repositories a discovery source knows but evidence does not) is never-covered.

Compatibility: BuildFlow's fold never emits a zero-evidence row (every row it produces carries runs or a last-run timestamp), so for every input BuildFlow can produce this function returns exactly the v1 contract states. never-covered is reachable only for discovery-minted rows, which the v1 producer never builds.

Step-scoped evidence flows through UNCHANGED: the caller hands over evidence whose Failures and LastRunAt already describe the one step only, so "failing" means "that step failed in the window" and "stale" means "that step hasn't run within staleAfter" - no special casing here.

func ParseState

func ParseState(raw string) (State, error)

ParseState converts a raw wire state string into a State. Unknown values are a contract violation, not a silent default: the consumer side verifies the enum instead of re-deriving it.

func (State) IsValid

func (s State) IsValid() bool

IsValid reports whether the state is one of the four known states.

art-dupl:accept the case list IS the canonical member set; a shared membership helper would obscure it

func (State) Rank

func (s State) Rank() int

Rank returns the triage order of the state: failing sorts first, then stale, then never-covered, then compliant. Unknown states sort last, after compliant. The hub table uses this as the always-primary sort key.

func (State) String

func (s State) String() string

String returns the wire representation of the state.

type StepEvidence

type StepEvidence struct {
	Step      string
	Failures  int64
	TotalRuns int64
	FailRate  float64
}

StepEvidence is one repo+step failure aggregate in the evidence window: the worst-steps feed of the compliance contract.

type V1Repo

type V1Repo struct {
	Repo           string         `json:"repo"`
	State          string         `json:"state"`
	Runs           int64          `json:"runs"`
	StepRows       int64          `json:"step_rows"`
	Failures       int64          `json:"failures"`
	FailRate       float64        `json:"fail_rate"`
	LastRunAt      string         `json:"last_run_at"`
	LastRunVerdict string         `json:"last_run_verdict"`
	GateFindings   map[string]int `json:"gate_findings"`
	// BuildFlowVersions lists the producer versions seen in the window;
	// the JSON key is frozen by the v1 contract.
	BuildFlowVersions []string `json:"buildflow_versions"`
	WorstSteps        []V1Step `json:"worst_steps"`
}

V1Repo is one repository's row in a V1Report.

type V1Report

type V1Report struct {
	SchemaVersion int    `json:"schema_version"`
	GeneratedAt   string `json:"generated_at"`
	Since         string `json:"since"`
	StaleAfter    string `json:"stale_after"`
	// BuildFlowVersion is the producing system's version; the JSON key is
	// frozen by the v1 contract. Non-BuildFlow producers fill their own
	// version here.
	BuildFlowVersion string   `json:"buildflow_version"`
	Repos            []V1Repo `json:"repos"`
}

V1Report is the frozen v1 compliance wire document (schema_version 1).

The shape is byte-faithful to BuildFlow's `compliance --json` output, which the overview dashboard consumes: field names, JSON keys, key order (struct declaration order under encoding/json/v2), and the nil-map `{}` / nil-slice `[]` normalization all mirror the producer. MarshalV1 additionally canonicalizes map key order (deterministic JSON).

func BuildV1Report

func BuildV1Report(
	evidence []RepoEvidence,
	since time.Time,
	staleAfter time.Duration,
	producerVersion string,
	now time.Time,
) V1Report

BuildV1Report derives states and shapes the wire payload. Pure: the golden test pins its exact schema. Repos are sorted worst-first (failing before stale before never-covered before compliant, then most failures, then name) - both the table (triage view) and the JSON (stable, consumer-keyed) carry this order. Nil maps and slices are normalized to {} and [] so every byte of the contract is explicit.

func DecodeV1Report

func DecodeV1Report(data []byte) (V1Report, error)

DecodeV1Report parses and validates a v1 wire document. A schema_version other than 1 is rejected (mirroring the overview consumer); repository states are carried as-is - validate them with ParseState if the consumer needs the enum verified.

type V1Step

type V1Step struct {
	Step      string  `json:"step"`
	Failures  int64   `json:"failures"`
	TotalRuns int64   `json:"total_runs"`
	FailRate  float64 `json:"fail_rate"`
}

V1Step is one repo+step failure aggregate (the worst-steps feed).

type Verdict

type Verdict string

Verdict is the outcome of a repository's latest run: "passed" or "failed", or the empty value when the repository has no rows at all (the consumer renders an unknown verdict rather than guessing).

const (
	// VerdictPassed means the latest run completed without failed steps.
	VerdictPassed Verdict = "passed"
	// VerdictFailed means the latest run had at least one failed step.
	VerdictFailed Verdict = "failed"
	// VerdictUnknown means no rows exist: no verdict can be derived.
	VerdictUnknown Verdict = ""
)

func (Verdict) String

func (v Verdict) String() string

String returns the wire representation of the verdict.

type WindowHealth

type WindowHealth struct {
	Repo     RepoName
	Runs     int64
	StepRows int64
	Failures int64
	FailRate float64
}

WindowHealth is one repository's window-bounded aggregate: runs, step rows, and failures inside the evidence window.

Directories

Path Synopsis
examples
reporter command
Command reporter demonstrates the one-line reporter integration: a tool finishes a run, records evidence, done.
Command reporter demonstrates the one-line reporter integration: a tool finishes a run, records evidence, done.
scripts
redactfixture command
Command redactfixture reads a raw `buildflow compliance --json` document on stdin and writes a redacted, canonical v1 fixture to stdout: every repository name is replaced with a stable placeholder (repo-0001, ..., in first-appearance order), including inside step fan-out keys like "samber-linter [work/<repo>]".
Command redactfixture reads a raw `buildflow compliance --json` document on stdin and writes a redacted, canonical v1 fixture to stdout: every repository name is replaced with a stable placeholder (repo-0001, ..., in first-appearance order), including inside step fan-out keys like "samber-linter [work/<repo>]".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL