Help us shape the future of Go! Take the 2026 Go Developer Survey

governance

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: AGPL-3.0, AGPL-3.0-only Imports: 17 Imported by: 0

Documentation

Overview

Package governance re-exports preset resolution from src/config. Preset resolution belongs to the config layer — governance is a consumer. All callers of governance.ResolvePresets / MergeEntry / MergeTrace continue to work unchanged via these type and var aliases.

Package governance implements the StageFreight governance engine: preset resolution, two-file config merge, governance reconciliation, capability detection, and execution gating.

Index

Constants

This section is empty.

Variables

View Source
var CanonicalKeyOrder = []string{
	"version",
	"vars",
	"sources",
	"policies",
	"builds",
	"targets",
	"badges",
	"scribe",
	"lint",
	"security",
	"dependency",
	"docs",
	"commit",
	"release",
	"lifecycle",
	"gitops",
	"docker",
	"glossary",
	"presentation",
	"tag",
	"manifest",
}

CanonicalKeyOrder defines the fixed top-level key order for rendered YAML. Prevents noisy diffs and unstable commits.

View Source
var DeepMerge = config.DeepMerge
View Source
var PresetMaterializeCache string

PresetMaterializeCache is where the control repo retains what it fetched while materializing. Every source must be reachable the first time, but not every time: with this, a pin is fetched once and a tracked source falls back to the last copy that resolved rather than failing the reconcile. Empty retains nothing.

View Source
var PresetSourceFetcher presetref.Fetcher

PresetSourceFetcher retrieves a preset from a source outside the control repo. Set by a network-capable entry point (the CLI), left nil in tests and offline runs.

View Source
var ResolvePresets = config.ResolvePresets

Function aliases.

View Source
var ValidatePreset = config.ValidatePreset

Functions

func FetchFile

func FetchFile(repoURL, ref, path string) ([]byte, error)

FetchFile fetches a single file from a git repo at a specific ref. Used as the AssetFetcher for governance distribution.

func LoadGovernance

func LoadGovernance(source GovernanceSource) (*GovernanceConfig, PresetLoader, error)

LoadGovernance loads governance config and returns a preset loader. When source.LocalPath is set (CI mode), uses the local checkout directly. Otherwise, fetches the policy repo at source.Ref — empty means its default branch, since an unpinned source tracks and pinning is the operator's choice.

func ReleaseCheckouts added in v0.11.0

func ReleaseCheckouts()

ReleaseCheckouts removes every memoized checkout. A long-lived process should call it when it is done resolving; a CLI run may simply exit.

func RenderEffective

func RenderEffective(config map[string]any) ([]byte, error)

RenderEffective returns config as YAML with canonical key ordering. Used by `config render` for display.

func RenderGated

func RenderGated(plan ExecutionPlan) string

RenderGated returns the execution plan as human-readable output (after gating).

func RenderPlanView

func RenderPlanView(w io.Writer, data PlanViewData)

RenderPlanView writes the structured plan view to w.

func RenderSealedConfig

func RenderSealedConfig(seal SealMeta, config map[string]any) ([]byte, error)

RenderSealedConfig produces a sealed .stagefreight.yml for a satellite repo. The seal is a human-facing warning header with provenance — not governance state. Uses canonical key ordering for deterministic, diff-stable output.

It names WHERE the config came from and never which revision produced it. A control repo's commit changes on every push, including its own generated commits, so stamping it here made every satellite's file differ on every run: 27 repos rewritten, committed, pushed and rebuilt to record a value nobody declared. Diff-stability is the property this whole function is built for, and a revision in the header defeats it.

Types

type AssetFetcher

type AssetFetcher func(repoURL, ref, path string) ([]byte, error)

AssetFetcher fetches a file from a repo at a specific ref.

type CapabilityResult

type CapabilityResult struct {
	Domain     string // e.g., "build.docker", "build.binary", "package.helm"
	Detected   bool
	Confidence string   // "high", "medium", "low"
	Evidence   []string // filesystem signals that supported detection
}

CapabilityResult records whether a specific capability was detected.

type CatalogEntry added in v0.10.0

type CatalogEntry struct {
	ID       string         // the repos: map key (a label)
	Forge    string         // forge id from a "<forge>:" location prefix, or "" (inherit)
	At       string         // the repo project path ("<group>/<repo>")
	Metadata map[string]any // governed branding (nil for a bare-string / location-only entry)
	Config   map[string]any // optional per-repo config override
}

CatalogEntry is one governed repo: a location anchor plus optional governed branding and an optional per-repo config override. A bare-string entry is location-only (CI governed, identity self-authored); a map entry (at: + fields) governs identity too.

type CommitResult

type CommitResult struct {
	Repo    string
	Status  string // "committed", "unchanged", "dry-run", "skipped-identical", "error"
	SHA     string // commit SHA if committed
	Message string
	Drifted bool // true if managed file was drifted before replacement
	Error   error
}

CommitResult records what happened for each repo during distribution.

func CommitDistribution

func CommitDistribution(plans []DistributionPlan, forge ForgeClient, source string, dryRun bool) ([]CommitResult, error)

CommitDistribution executes distribution plans by committing to target repos. Per-repo failure does NOT stop the run. Aggregates results. Idempotent: skips repos where all files are unchanged. Returns error if ANY repo failed. source is the host-qualified control-repo location that governs these plans, e.g. "gitlab.prplanit.com/PrPlanIT/MaintenancePolicy".

type DetectionReport

type DetectionReport struct {
	Capabilities []CapabilityResult
}

DetectionReport is the output of capability discovery.

func DetectCapabilities

func DetectCapabilities(repoRoot string) DetectionReport

DetectCapabilities scans the repo filesystem for evidence of each capability domain. Independent per capability. No global winner. No config mutation.

type DistributedFile

type DistributedFile struct {
	Path    string // e.g., ".stagefreight/stagefreight-managed.yml"
	Content []byte
	Action  string // "create", "replace", "unchanged", "delete"
	Drifted bool   // true if existing file differs from governance intent
}

DistributedFile is a single file to write/update in a target repo.

type DistributionPlan

type DistributionPlan struct {
	Repo        string // "org/repo"
	Credentials string // env var prefix for forge auth (from cluster targets)
	Files       []DistributedFile
}

DistributionPlan describes what files to write to a target repo.

func PlanDistribution

func PlanDistribution(
	gov *GovernanceConfig,
	presetLoader PresetLoader,
	assetFetcher AssetFetcher,
	forgeReader ForgeReader,
	presetSource PresetSourceInfo,
	sourceIdentity string,
) ([]DistributionPlan, error)

func (DistributionPlan) HasChanges

func (p DistributionPlan) HasChanges() bool

HasChanges returns true if this plan has any files that need writing.

type EnabledFeature

type EnabledFeature struct {
	Domain string
	Reason string // "config enabled + capability detected"
}

EnabledFeature is a feature that passed both config and capability gates.

type ExecutionPlan

type ExecutionPlan struct {
	Enabled []EnabledFeature
	Skipped []SkippedFeature
}

ExecutionPlan is the gated output — what will actually run. Produced by GateExecution. Does NOT modify config.

func GateExecution

func GateExecution(config map[string]any, detection DetectionReport) ExecutionPlan

GateExecution combines merged config + detected capabilities into a runnable plan. Does NOT modify config. Produces ExecutionPlan only.

type FileCommit

type FileCommit struct {
	Path    string
	Content []byte
	Action  string // "create", "update"
}

FileCommit is a single file change within a commit.

type ForgeClient

type ForgeClient interface {
	ForgeReader

	// CommitFiles commits multiple file changes to a repo's default branch.
	// Returns commit SHA on success.
	CommitFiles(repo, branch, message string, files []FileCommit) (string, error)

	// DefaultBranch returns the default branch name for a repo.
	DefaultBranch(repo string) (string, error)
}

ForgeClient abstracts forge API for file commits. Extends ForgeReader with write capability.

type ForgeReader

type ForgeReader interface {
	GetFileContent(repo, path, ref string) ([]byte, error)
	// DefaultBranch reports the repo's default branch — read from the forge so the
	// concretized repos section never assumes it.
	DefaultBranch(repo string) (string, error)
}

ForgeReader reads current file content from a remote repo. Used to detect drift and determine create vs update actions.

type GovernanceConfig

type GovernanceConfig struct {
	Profiles ProfileList `yaml:"profiles"`
}

GovernanceConfig is the parsed governance config from the policy repo.

type GovernanceSource

type GovernanceSource struct {
	RepoURL   string `yaml:"repo_url"` // policy repo URL
	Ref       string `yaml:"ref"`      // "" = default branch (tracked); a ref pins
	Path      string `yaml:"path"`     // path to governance config within repo
	LocalPath string `yaml:"-"`        // if set, use local checkout instead of cloning
}

GovernanceSource declares where governance inputs come from. Declared in .stagefreight.yml under governance.source.

type MergeEntry

type MergeEntry = config.MergeEntry

type MergeTrace

type MergeTrace = config.MergeTrace

type PlanViewConfig

type PlanViewConfig struct {
	Mode    string // "dry-run" or "apply"
	Source  string // e.g. "PrPlanIT/MaintenancePolicy"
	Ref     string // e.g. "dba5d2a" or "v1.0.0"
	Forge   string // where satellites are read/written, e.g. "gitlab @ https://gitlab.example (cred: GITLAB_*)"
	Verbose bool   // expand preset-cache files individually
}

PlanViewConfig controls what the plan view renders.

type PlanViewData

type PlanViewData struct {
	Config   PlanViewConfig
	Profiles []Profile
	Plans    map[string]DistributionPlan // keyed by repo
	Results  map[string]CommitResult     // keyed by repo (nil for dry-run)
}

PlanViewData holds everything needed to render a plan view.

type PresetLoader

type PresetLoader = config.PresetLoader

Type aliases — identical types, no conversion needed at call sites.

type PresetQualifier added in v0.11.0

type PresetQualifier struct {
	Repo string // clonable source, e.g. "https://gitlab.example.com/Org/Policy"
}

PresetQualifier is the source a satellite resolves unqualified presets against. It carries no revision: qualification supplies provenance, never a pin.

func NewPresetQualifier added in v0.11.0

func NewPresetQualifier(ps PresetSourceInfo) PresetQualifier

NewPresetQualifier builds the qualifier for a distribution. When the source's coordinates are incomplete, it returns a zero qualifier that rewrites nothing: a half-formed source ("/" from an empty forge and project) would produce references no satellite could resolve, and leaving paths local is the honest fallback.

func (PresetQualifier) Qualify added in v0.11.0

func (g PresetQualifier) Qualify(raw string) string

Qualify turns an unqualified preset path into a reference that names where it comes from, so a satellite resolves it against the source instead of reading whatever copy it happens to hold.

THE INVARIANT: a reference that already names its own source is returned untouched. Governance supplies provenance for a reference that has none; it never redirects one that does. Without this, adding governance to a config would silently drag a preset declared as https://elsewhere/x.yml back to the governance repo.

func (PresetQualifier) QualifyConfig added in v0.11.0

func (g PresetQualifier) QualifyConfig(config map[string]any)

QualifyConfig rewrites every unqualified preset:/presets: reference in a config so the distributed satellite resolves them from the source. Mutates in place.

type PresetRef

type PresetRef struct {
	Path string
}

PresetRef is a reference to an external preset fragment. Appears as preset: "path" within any config section.

type PresetSourceInfo

type PresetSourceInfo struct {
	Provider  string // "gitlab", "github", "gitea"
	ForgeURL  string // HTTPS base URL (e.g., "https://gitlab.prplanit.com")
	ProjectID string // "org/repo" or "org/group/repo"
}

PlanDistribution computes what files need to change for each governed repo. Pure planning — does NOT write anything. Reads current state from forge to detect drift and determine actions. PresetSourceInfo holds the forge coordinates for preset resolution. Injected into satellite .stagefreight.yml so repos can resolve presets independently.

type Profile added in v0.10.0

type Profile struct {
	ID          string         `yaml:"-"`                     // from the profiles: map key
	Repos       ProfileCatalog `yaml:"repos"`                 // the location-anchored catalog
	Config      map[string]any `yaml:"config"`                // the profile's shared StageFreight config
	Credentials string         `yaml:"credentials,omitempty"` // env var prefix for the write token
}

Profile assigns shared policy + branding to a group of repos (its catalog). Config is normal StageFreight config; Repos is the location-anchored catalog. Assets are declared inside Config as assets: entries — no separate skeleton construct.

type ProfileCatalog added in v0.10.0

type ProfileCatalog []CatalogEntry

ProfileCatalog is a profile's repos: block — an id→entry map, each entry anchored on a repo location.

func (*ProfileCatalog) UnmarshalYAML added in v0.10.0

func (pc *ProfileCatalog) UnmarshalYAML(n *yaml.Node) error

type ProfileList added in v0.10.0

type ProfileList []Profile

ProfileList is the profiles: block — an id→profile map (the map key becomes Profile.ID). Governance decodes its own id-map (the config package's decodeIDMap is unexported); document order is preserved.

func (*ProfileList) UnmarshalYAML added in v0.10.0

func (pl *ProfileList) UnmarshalYAML(n *yaml.Node) error

type ResolvedPreset

type ResolvedPreset struct {
	Path        string         // source path within policy repo
	TopLevelKey string         // the single top-level key this preset declares
	Content     map[string]any // parsed YAML content under that key
}

ResolvedPreset is a loaded and validated preset fragment.

type SealMeta

type SealMeta struct {
	SourceRepo string // e.g., "https://gitlab.prplanit.com/PrPlanIT/MaintenancePolicy"
	ProfileID  string // e.g., "docker-services"
}

SealMeta holds provenance info for the generated header.

type SkippedFeature

type SkippedFeature struct {
	Domain string
	Reason string // "capability not detected" or "config disabled"
}

SkippedFeature is a feature that was gated out.

Jump to

Keyboard shortcuts

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