build

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2026 License: AGPL-3.0, AGPL-3.0-only Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// CrucibleEnvVar is set to "1" inside the pass-2 container to prevent recursion.
	CrucibleEnvVar = "STAGEFREIGHT_CRUCIBLE"

	// CrucibleRunIDEnvVar correlates pass-1 and pass-2 in logs/artifacts.
	CrucibleRunIDEnvVar = "STAGEFREIGHT_CRUCIBLE_RUN_ID"

	// CrucibleAllowEnvVar overrides the repo guard for non-StageFreight repos.
	CrucibleAllowEnvVar = "STAGEFREIGHT_ALLOW_CRUCIBLE"

	// StageFreightModule is the canonical Go module path used by the repo guard.
	StageFreightModule = "github.com/PrPlanIT/StageFreight"
)

Crucible environment variables.

View Source
const (
	TrustViable        = "viable"        // pass 2 succeeded
	TrustConsistent    = "consistent"    // version + build graph match
	TrustDeterministic = "deterministic" // binary hash identical
	TrustReproducible  = "reproducible"  // image digest identical (stretch goal)
)

Trust levels, ordered from weakest to strongest.

View Source
const (
	LabelCreated   = "org.opencontainers.image.created"
	LabelRevision  = "org.opencontainers.image.revision"
	LabelVersion   = "org.opencontainers.image.version"
	LabelBuildMode = "org.stagefreight.build.mode"
	LabelPlanHash  = "org.stagefreight.plan.sha256"
)

Standard OCI label keys emitted by StageFreight on every build.

View Source
const DistDir = paths.Root + "/dist"

DistDir is the StageFreight-managed output root for binary builds and their archives, relative to the repo root. It lives under .stagefreight/ on purpose: CI forwards only .stagefreight/ across the perform→publish job boundary, and the publish phase must be able to open the archive files its manifest references. Binaries, archives, and SHA256SUMS all live beneath this single root — splitting them (e.g. a bare top-level dist/) reopens the seam where publish receives metadata for files it does not possess.

View Source
const ProvenanceDir = paths.Root + "/provenance"

ProvenanceDir is where build provenance statements are written, relative to root.

Variables

This section is empty.

Functions

func All

func All() []string

All returns sorted names of all registered engines.

func AllV2 added in v0.4.0

func AllV2() []string

AllV2 returns sorted names of all registered v2 engines.

func BuildOrder added in v0.4.0

func BuildOrder(builds []config.BuildConfig) ([]config.BuildConfig, error)

BuildOrder computes the topological execution order for a set of builds. Uses Kahn's algorithm. Returns an error on cycles or missing references.

func ChecksumFile added in v0.4.0

func ChecksumFile(path string) (string, error)

ChecksumFile computes the SHA-256 hex digest of a file and writes a .sha256 sidecar.

func DefaultTestCommand added in v0.7.0

func DefaultTestCommand(builder, fromDir, rootDir string) (args []string, workdir string, err error)

DefaultTestCommand returns the native test invocation for a builder plus the working directory it must run in. It owns "what does testing a Go/Rust project mean" so the test subsystem never duplicates toolchain knowledge.

go   → go test ./...      (from the module root — the dir holding go.mod)
rust → cargo test         (single crate)
       cargo test --workspace  (when the crate root's Cargo.toml is a [workspace])

fromDir is the build's `From` (the main-package / crate dir), which may sit BELOW the module/crate root — stagefreight builds `./src/cli` but its go.mod is at the repo root; dd-ui's go.mod is in `api/`. So the working dir is resolved by walking up from fromDir to the nearest manifest, bounded by rootDir.

Only the BASE command is returned; suite flags (-race, -tags, --features, …) and the synthesized-default policy are layered by the caller.

func DetectProvider

func DetectProvider(registryURL string) string

DetectProvider determines the registry vendor from the URL. Well-known domains are matched directly. For unknown domains, returns "generic" (future: probe the registry API to identify the vendor).

func DetectVersion

func DetectVersion(rootDir string, cfg *config.Config) (*gitver.VersionInfo, error)

DetectVersion resolves version info using versioning config from the given Config. Config is REQUIRED — nil is rejected. Every caller must thread a valid *config.Config through to version detection. There is no legacy "just guess from git" path.

func EnsureCrucibleAllowed

func EnsureCrucibleAllowed(rootDir string) error

EnsureCrucibleAllowed checks that the repo is the StageFreight repo itself, or that STAGEFREIGHT_ALLOW_CRUCIBLE=1 is set.

func EnvFingerprint

func EnvFingerprint() string

EnvFingerprint returns an informational hash of the build environment. Non-authoritative — useful for debugging but never a primary signal.

func ExtractPredicate added in v0.7.0

func ExtractPredicate(statementPath string) (predPath, statementSHA string, ok bool)

ExtractPredicate reads an in-toto Statement and writes its predicate BODY to a sibling `.predicate.json` for cosign attest (cosign frames the predicate with the attested image as subject — so the whole statement must NOT be passed as the predicate, or it would be double-wrapped). It returns the predicate path, the sha256 of the CANONICAL statement (the provenance's recorded identity), and ok=false when the statement is absent, unreadable, or carries no predicate — "no usable provenance", so an enabled attestation can fail loud rather than attaching nothing. Shared by the unattended build path and `stagefreight sign`.

func FindBuildProvenance added in v0.7.0

func FindBuildProvenance(rootDir string) ([]string, error)

FindBuildProvenance returns the build-provenance statement files under rootDir's provenance dir (the `.predicate.json` bodies ExtractPredicate writes are excluded). Sorted for determinism. `stagefreight sign` uses this to locate the provenance to attest; a build normally emits exactly one, so >1 is the caller's signal to refuse rather than guess which predicate belongs to which image.

func FormatLayerInstruction

func FormatLayerInstruction(e LayerEvent) string

FormatLayerInstruction formats a layer event into a display string. For FROM instructions, shows the base image name. For other instructions, shows the instruction and truncated detail.

func FormatLayerTiming

func FormatLayerTiming(e LayerEvent) string

FormatLayerTiming formats a layer's timing for display. Returns "cached" for cache hits, or the duration string for completed layers.

func GenerateCrucibleRunID

func GenerateCrucibleRunID() string

GenerateCrucibleRunID returns a cryptographically random hex string for correlating crucible passes. Uses crypto/rand to avoid collisions in CI where multiple pipelines may start at the same nanosecond.

func InjectLabels

func InjectLabels(plan *BuildPlan, labels map[string]string)

InjectLabels merges labels into every step of a plan. Existing labels on a step are preserved; new labels do not overwrite.

func IsCrucibleChild

func IsCrucibleChild() bool

IsCrucibleChild returns true when running inside a crucible pass-2 container.

func NormalizeBuildPlan

func NormalizeBuildPlan(plan *BuildPlan) string

NormalizeBuildPlan produces a deterministic fingerprint of a BuildPlan, excluding ephemeral/runtime-derived fields. Used globally for provenance, and by crucible for build graph verification between passes.

Included fields (build-affecting):

  • BuildStep.Name, Dockerfile, Context, Target (build identity)
  • BuildStep.Platforms (affects output binary)
  • BuildStep.BuildArgs (minus BUILD_DATE — ephemeral timestamp)

Excluded fields (ephemeral or derived at runtime):

  • BuildStep.Tags (output naming, not build-affecting)
  • BuildStep.Registries (output destinations, not build-affecting)
  • BuildStep.Output (always "image" for docker)
  • BuildStep.Load, Push (runtime strategy decisions)
  • BuildStep.Labels (metadata, not build-affecting)
  • BuildStep.Extract (artifact mode only)
  • RegistryTarget.Credentials (auth, not build-affecting)
  • RegistryTarget.Provider (inferred, not build-affecting)
  • RegistryTarget.Retention, TagPatterns (post-build operations)
  • BuildArgs["BUILD_DATE"] (timestamp, always differs between runs)
  • Map iteration order (all maps sorted by key)
  • Empty/zero-value fields (omitted, not hashed)
  • Builder-generated metadata (layer IDs, cache keys, etc.)

func PlanToOutputs added in v0.6.0

func PlanToOutputs(plan *BuildPlan, opts PlanToOutputsOpts) (artifact.OutputsManifest, error)

PlanToOutputs is a pure function from BuildPlan + plan-time options to OutputsManifest. Allocation-only: it must not inspect execution state, must not infer runtime outcomes, must not fall back on partial build metadata. If a field is not plan-derivable, it does not belong in the returned manifest.

The returned manifest is fully finalized — schema version, generated_at, artifact ids, sort order, and embedded checksum are all populated. It is suitable to either pass directly to WriteOutputsManifest for persistence or to ResultsBuilder.Build as the in-memory intent snapshot. No disk round-trip is required between the two uses.

func Register

func Register(name string, constructor func() Engine)

Register adds an engine constructor to the global registry. Called from init() in each engine package.

func RegisterV2 added in v0.4.0

func RegisterV2(name string, constructor func() EngineV2)

RegisterV2 adds an EngineV2 constructor to the global registry.

func ResolveTags

func ResolveTags(templates []string, v *gitver.VersionInfo) []string

ResolveTags delegates to the gitver package.

func ResolveTemplate

func ResolveTemplate(tmpl string, v *gitver.VersionInfo) string

ResolveTemplate delegates to the gitver package.

func SlugifyBuildID added in v0.3.2

func SlugifyBuildID(id string) string

SlugifyBuildID sanitizes a build ID for use as a filename. Lowercase, [a-z0-9-] only, spaces/underscores → hyphens, slashes forbidden.

func StandardLabels

func StandardLabels(planHash, sfVersion, commit, mode, createdRFC3339 string) map[string]string

StandardLabels returns the set of OCI labels that should be applied to every image built by StageFreight, regardless of build mode.

func StepIDForTarget added in v0.7.0

func StepIDForTarget(buildID string, t Target) string

StepIDForTarget builds a deterministic step ID. Format: {buildID}--{os}-{arch}[-{libc}] (variant slot reserved by the "--").

func TruncHash

func TruncHash(s string) string

TruncHash truncates a hash string for display.

func TrustLevelLabel

func TrustLevelLabel(level string) string

TrustLevelLabel returns human text for the trust level with context when the level is below deterministic.

func ValidateBuildGraph added in v0.4.0

func ValidateBuildGraph(steps []UniversalStep) error

ValidateBuildGraph performs pre-execution validation on a set of universal steps. Checks: no duplicate step IDs, no duplicate output paths, all input refs satisfied.

func WriteChecksums added in v0.4.0

func WriteChecksums(outputDir string, archives []*ArchiveResult) (string, error)

WriteChecksums creates a SHA256SUMS file from a set of archive results.

func WriteDSSEProvenance

func WriteDSSEProvenance(path string, stmt ProvenanceStatement) error

WriteDSSEProvenance writes a DSSE-wrapped provenance statement as indented JSON.

func WriteProvenance

func WriteProvenance(path string, stmt ProvenanceStatement) error

WriteProvenance writes a provenance statement as indented JSON.

Types

type ArchiveArtifactPlan added in v0.6.0

type ArchiveArtifactPlan struct {
	Name    string
	Format  string
	Path    string
	Version string
}

ArchiveArtifactPlan is the plan-time description of one archive output. Same un-targeted invariant as BinaryArtifactPlan; Sources references the binary artifacts the archive wraps (sibling-artifact relationship, not embedding), and lives on the ArchiveOutcome side rather than the plan.

type ArchiveOpts added in v0.4.0

type ArchiveOpts struct {
	// Format is "tar.gz", "zip", or "auto" (zip for windows, tar.gz otherwise).
	Format string

	// OutputDir is where archives are written.
	OutputDir string

	// NameTemplate is the archive filename template (without extension).
	// Supports: {id}, {version}, {os}, {arch}
	NameTemplate string

	// BinaryPath is the path to the compiled binary to include.
	BinaryPath string

	// BinaryName is the filename inside the archive (may differ from physical path basename).
	BinaryName string

	// IncludeFiles lists extra files to bundle (relative to repo root).
	IncludeFiles []string

	// RepoRoot is the root directory for resolving include files.
	RepoRoot string

	// Target is the build target this archive packages.
	Target Target

	// BuildID is used for template resolution.
	BuildID string

	// Version info for template resolution.
	Version *VersionInfo
}

ArchiveOpts holds configuration for archive creation.

type ArchiveResult added in v0.4.0

type ArchiveResult struct {
	Path     string // archive file path
	Format   string // actual format used
	Size     int64
	SHA256   string
	Contents []string // files inside the archive
}

ArchiveResult holds the output of an archive operation.

func CreateArchive added in v0.4.0

func CreateArchive(opts ArchiveOpts) (*ArchiveResult, error)

CreateArchive builds an archive containing a binary and optional extra files. CreateArchive produces a deterministic archive file from the supplied binary + optional include files. Determinism rule (load-bearing for ArchiveOutcome.SHA256 stability across runs):

Archive identity MUST be deterministic over:
- sorted file set (canonical archive-name order, not caller order)
- normalized tar/zip headers (zero ModTime, zero Uid/Gid, fixed mode)
- single-pass SHA256 over the final stream

Any deviation introduces cross-run instability in ArchiveOutcome.SHA256.
Caller-supplied include order is intentionally ignored; sorting happens
here once, at the determinism boundary, not at every consumer.

type ArtifactRef added in v0.4.0

type ArtifactRef struct {
	Path string `json:"path"`
	Type string `json:"type"` // "binary", "image", "archive", "metadata"
}

ArtifactRef is a declared artifact reference (expected input or output).

type BinaryArtifactPlan added in v0.6.0

type BinaryArtifactPlan struct {
	Name      string
	OS        string
	Arch      string
	Path      string
	Toolchain string
	Version   string
}

BinaryArtifactPlan is the plan-time description of one binary output. Path is the intended output location relative to the workspace; SHA256 and any post-build identity belong in the corresponding Outcome.

Binary artifacts are un-targeted by design (Q2, Phase 4): the build artifact IS the truth, and distribution destinations are decided at a later layer (release_create), not at build time. There is no Targets field on the plan because there are no targets in the intent.

type BuildConfig added in v0.4.0

type BuildConfig struct {
	ID         string
	Kind       string
	Platforms  []Target
	BuildMode  string
	SelectTags []string
	DependsOn  string

	// Version info for template resolution
	Version *VersionInfo

	// kind: docker fields
	Dockerfile string
	Context    string
	Target     string
	BuildArgs  map[string]string
	Tags       []string
	Registries []RegistryTarget

	// kind: binary fields
	Builder  string
	Command  string
	From     string
	Output   string
	Args     []string
	Env      map[string]string
	Compress bool

	// kind: binary, builder: node — containerized build. The build Command runs
	// INSIDE Image (repo mounted); Output is the produced-artifact glob. Lets SF
	// ship things it can't compile natively (e.g. an Electron .exe via wine).
	Image string
}

BuildConfig is the normalized input to EngineV2.Plan(). Core synthesizes this from config + detection; engines don't develop their own auto-config policy brains.

type BuildPlan

type BuildPlan struct {
	Steps []BuildStep
}

BuildPlan is the resolved execution plan for a build.

type BuildResult

type BuildResult struct {
	Steps    []StepResult
	Duration time.Duration
}

BuildResult captures the outcome of a full build plan execution.

type BuildStep

type BuildStep struct {
	Name           string
	Dockerfile     string
	Context        string
	Target         string
	Platforms      []string
	BuildArgs      map[string]string
	Labels         map[string]string // OCI labels injected via --label
	Tags           []string
	Output         OutputMode
	Extract        []ExtractRule    // artifact mode only
	Registries     []RegistryTarget // image mode only
	Load           bool             // --load into daemon
	Push           bool             // --push to registries
	MetadataFile   string           // temp file for buildx --metadata-file (digest capture)
	OCILayoutDir   string           // --output type=oci,dest=<dir> for content-store persistence; additive to Load/Push
	CacheFrom      []CacheRef       // --cache-from references
	CacheTo        []CacheRef       // --cache-to references
	SkippedTargets []TargetSkip     // registry targets excluded by when:, with the matcher's reason (narrated)
}

BuildStep is a single build invocation.

type CacheRef added in v0.5.0

type CacheRef struct {
	Type      string // "registry", "local"
	Ref       string // registry ref or local path
	Mode      string // "max", "min" (export only)
	Direction string // "import" or "export" — determines local key (src vs dest)
}

CacheRef is a structured build cache reference.

func (CacheRef) Flag added in v0.5.0

func (c CacheRef) Flag() string

Flag renders the CacheRef as a buildx --cache-from/--cache-to value. Local cache uses src=/dest= keys. Registry cache uses ref=.

type Capabilities added in v0.4.0

type Capabilities struct {
	SupportsCrossCompile bool `json:"supports_cross_compile"`
	SupportsCrucible     bool `json:"supports_crucible"`
	ProducesArchives     bool `json:"produces_archives"`
	ProducesOCI          bool `json:"produces_oci"`
}

Capabilities declares what a build engine can do. Core queries behavior, never engine names.

type CargoBuild added in v0.7.0

type CargoBuild struct {
	Verbose bool
	Stdout  io.Writer
	Stderr  io.Writer
}

CargoBuild wraps Cargo compilation — the Rust analog of GoBuild. It runs `cargo build` and copies the produced binary to the canonical output path, so a Rust binary lands in the SAME artifact lifecycle (DistDir layout, SHA256, archive, signing) as a Go binary. The build's "how" differs (cargo vs go); the artifact contract is identical.

func NewCargoBuild added in v0.7.0

func NewCargoBuild(verbose bool) *CargoBuild

func (*CargoBuild) Build added in v0.7.0

Build compiles a Rust binary and copies it to OutputPath.

type CargoBuildOpts added in v0.7.0

type CargoBuildOpts struct {
	ManifestDir string            // dir containing Cargo.toml (cmd.Dir)
	BinName     string            // the [[bin]]/package name → target/<profile>/<BinName>
	OutputPath  string            // canonical output (DistDir/<slug>/<name>) — the binary is copied here
	Release     bool              // --release (release profile)
	TargetDir   string            // CARGO_TARGET_DIR (where target/ lives); "" = ManifestDir/target
	Args        []string          // raw args before nothing (e.g. ["--features", "x"])
	Env         map[string]string // additional env (e.g. CARGO_HOME)
	CargoBin    string            // resolved cargo binary; "" falls back to "cargo" on $PATH (dev only)
}

CargoBuildOpts holds the parameters for a single cargo compilation.

type CargoBuildResult added in v0.7.0

type CargoBuildResult struct {
	Path   string
	Size   int64
	SHA256 string
}

CargoBuildResult holds the output of a cargo compilation.

type DSSEEnvelope

type DSSEEnvelope struct {
	PayloadType string          `json:"payloadType"`
	Payload     string          `json:"payload"` // base64-encoded ProvenanceStatement
	Signatures  []DSSESignature `json:"signatures"`
}

DSSEEnvelope is a Dead Simple Signing Envelope for wrapping provenance statements.

func WrapDSSE

func WrapDSSE(stmt ProvenanceStatement) (DSSEEnvelope, error)

WrapDSSE wraps a ProvenanceStatement in a DSSE envelope (unsigned). The caller can sign the payload externally (cosign) and attach the signature.

type DSSESignature

type DSSESignature struct {
	KeyID string `json:"keyid,omitempty"`
	Sig   string `json:"sig"`
}

DSSESignature is a single signature within a DSSE envelope.

type Detection

type Detection struct {
	RootDir      string // absolute path to repo root
	Dockerfiles  []DockerfileInfo
	Language     string   // "go", "rust", "node", "python", ""
	Lockfiles    []string // relative paths: go.mod, Cargo.toml, etc.
	MainPackages []string // detected main package paths (Go: cmd/foo, bar, .)
	GitInfo      *GitInfo
}

Detection holds everything discovered about a repo's build capabilities.

func DetectRepo

func DetectRepo(rootDir string) (*Detection, error)

DetectRepo inspects a directory and returns build-relevant information.

type DockerfileInfo

type DockerfileInfo struct {
	Path        string  // relative path from repo root
	Stages      []Stage // parsed multistage stages
	Args        []string
	Expose      []string
	Healthcheck *string
}

DockerfileInfo describes a discovered Dockerfile.

func ParseDockerfile

func ParseDockerfile(path string) (*DockerfileInfo, error)

ParseDockerfile extracts stage, arg, expose, and healthcheck info from a Dockerfile. This is a regex-based parser — not a full AST. Sufficient for detection and planning.

type Engine

type Engine interface {
	Name() string
	Detect(ctx context.Context, rootDir string) (*Detection, error)
	Plan(ctx context.Context, cfg interface{}, det *Detection) (*BuildPlan, error)
}

Engine is the interface every build engine implements.

func Get

func Get(name string) (Engine, error)

Get returns a new instance of the named engine.

type EngineV2 added in v0.4.0

type EngineV2 interface {
	// Name returns the engine's identifier (e.g., "binary", "image").
	Name() string

	// Capabilities declares what this engine supports.
	Capabilities() Capabilities

	// Detect inspects a repo and returns build-relevant information.
	Detect(ctx context.Context, rootDir string) (*Detection, error)

	// Plan converts a build config into a list of universal steps.
	// Core owns config synthesis — Plan receives normalized config, not detection guesses.
	Plan(ctx context.Context, cfg BuildConfig) ([]UniversalStep, error)

	// ExecuteStep runs a single step and returns its result.
	// The engine must not: write publish manifests, attach release assets,
	// manage concurrency, resolve dependencies, or print logs directly.
	ExecuteStep(ctx context.Context, step UniversalStep) (*UniversalStepResult, error)
}

EngineV2 is the universal engine interface for all build types. Engines are declarative planners — they convert config to steps and execute individual steps. All orchestration (ordering, concurrency, retries, logging, artifact recording, checksums, publish manifest) lives in core.

func GetV2 added in v0.4.0

func GetV2(name string) (EngineV2, error)

GetV2 returns a new instance of the named v2 engine.

type ExtractRule

type ExtractRule struct {
	From string // path inside the container
	To   string // local destination path
}

ExtractRule defines a file to extract from a build container.

type GitInfo

type GitInfo struct {
	Remote    string // origin URL
	Branch    string // current branch
	LatestTag string
	SHA       string
}

GitInfo holds git repository metadata.

type GoBuild added in v0.4.0

type GoBuild struct {
	Verbose bool
	Stdout  io.Writer
	Stderr  io.Writer
}

GoBuild wraps Go compilation commands.

func NewGoBuild added in v0.4.0

func NewGoBuild(verbose bool) *GoBuild

NewGoBuild creates a GoBuild runner with default output writers.

func (*GoBuild) Build added in v0.4.0

func (g *GoBuild) Build(ctx context.Context, opts GoBuildOpts) (*GoBuildResult, error)

Build compiles a Go binary with the given options.

func (*GoBuild) DetectMainPackages added in v0.4.0

func (g *GoBuild) DetectMainPackages(rootDir string) ([]string, error)

DetectMainPackages scans a Go project for main packages. Looks in: cmd/*/main.go, */main.go, main.go

func (*GoBuild) ToolchainVersion added in v0.4.0

func (g *GoBuild) ToolchainVersion(ctx context.Context) (string, error)

ToolchainVersion returns the Go toolchain version string.

type GoBuildOpts added in v0.4.0

type GoBuildOpts struct {
	Entry      string // main package path (e.g., "cmd/planedc/main.go" or "./cmd/planedc")
	OutputPath string // output binary path
	GOOS       string
	GOARCH     string
	Args       []string          // raw args passed before entry (e.g., ["-tags", "banner_art", "-ldflags", "..."])
	Env        map[string]string // additional env vars (e.g., CGO_ENABLED=0)
	GoBin      string            // resolved go binary (from the toolchain subsystem); "" falls back to "go" on $PATH
}

GoBuildOpts holds the parameters for a single Go compilation.

type GoBuildResult added in v0.4.0

type GoBuildResult struct {
	Path   string // absolute output path
	Size   int64
	SHA256 string
}

GoBuildResult holds the output of a Go compilation.

type ImagePlanInput added in v0.4.0

type ImagePlanInput struct {
	Cfg     *config.Config // full config
	BuildID string         // optional: build specific entry by ID (empty = all)
}

ImagePlanInput bundles the config needed for image build planning.

type LayerEvent

type LayerEvent struct {
	Stage       string        // "builder", "stage-1", "" (for internal steps)
	StageStep   string        // "1/7", "2/7", etc.
	Instruction string        // "FROM", "COPY", "RUN", "WORKDIR", "ENV", "ARG", "EXPOSE", "ADD"
	Detail      string        // instruction arguments (truncated)
	Cached      bool          // true if layer was a cache hit
	Duration    time.Duration // layer execution time (0 for cached layers)
	Image       string        // for FROM: the base image name (without digest)
}

LayerEvent represents a completed build layer parsed from buildx output.

type OutputMode

type OutputMode string

OutputMode describes what the build produces.

const (
	OutputImage OutputMode = "image" // container image (push to registry or load to daemon)
	OutputLocal OutputMode = "local" // extract files to local filesystem
	OutputTar   OutputMode = "tar"   // export as tarball
)

type PlanToOutputsOpts added in v0.6.0

type PlanToOutputsOpts struct {
	GeneratedAt  string // RFC3339; if empty, Finalize defaults to UTC now
	Commit       string
	Pipeline     *artifact.Pipeline
	BinaryPlans  []BinaryArtifactPlan  // plan-time binary descriptors
	ArchivePlans []ArchiveArtifactPlan // plan-time archive descriptors
}

PlanToOutputsOpts carries non-plan inputs needed to fully construct the intent manifest. Everything here is either plan-time configuration or pipeline metadata — never execution state. GeneratedAt is supplied by the caller so PlanToOutputs is fully pure (no wall-clock read).

type ProducedArtifact added in v0.4.0

type ProducedArtifact struct {
	Path   string `json:"path"`
	Type   string `json:"type"` // "binary", "image", "archive", "metadata"
	Size   int64  `json:"size"`
	SHA256 string `json:"sha256"`
}

ProducedArtifact is an observed output from a step execution.

type ProvenanceBuilder

type ProvenanceBuilder struct {
	ID string `json:"id"`
}

ProvenanceBuilder identifies the build system.

type ProvenanceInvocation

type ProvenanceInvocation struct {
	ConfigSource map[string]any `json:"configSource,omitempty"`
	Parameters   map[string]any `json:"parameters,omitempty"`
	Environment  map[string]any `json:"environment,omitempty"`
}

ProvenanceInvocation captures the build parameters and environment.

type ProvenanceMaterial

type ProvenanceMaterial struct {
	URI    string            `json:"uri"`
	Digest map[string]string `json:"digest,omitempty"`
}

ProvenanceMaterial represents an input to the build.

type ProvenanceMetadata

type ProvenanceMetadata struct {
	BuildStartedOn  string          `json:"buildStartedOn,omitempty"`
	BuildFinishedOn string          `json:"buildFinishedOn,omitempty"`
	Completeness    map[string]bool `json:"completeness,omitempty"`
	Reproducible    bool            `json:"reproducible"`
}

ProvenanceMetadata captures timing and completeness.

type ProvenancePredicate

type ProvenancePredicate struct {
	BuildType    string               `json:"buildType"`
	Builder      ProvenanceBuilder    `json:"builder"`
	Invocation   ProvenanceInvocation `json:"invocation"`
	Metadata     ProvenanceMetadata   `json:"metadata"`
	Materials    []ProvenanceMaterial `json:"materials,omitempty"`
	StageFreight map[string]any       `json:"stagefreight,omitempty"`
}

ProvenancePredicate describes how it was built.

type ProvenanceStatement

type ProvenanceStatement struct {
	Type          string              `json:"_type"`
	PredicateType string              `json:"predicateType"`
	Subject       []ProvenanceSubject `json:"subject"`
	Predicate     ProvenancePredicate `json:"predicate"`
}

ProvenanceStatement follows the in-toto Statement v1 / SLSA Provenance v1 structure. Not full SLSA compliance, but a useful provenance document that can evolve into DSSE envelopes, cosign attestations, or OCI referrer artifacts.

type ProvenanceSubject

type ProvenanceSubject struct {
	Name   string            `json:"name"`
	Digest map[string]string `json:"digest,omitempty"`
}

ProvenanceSubject identifies what was built.

type PushObservation added in v0.6.0

type PushObservation struct {
	Host   string
	Path   string
	Tag    string
	Digest string
}

PushObservation is buildx's record of one push: registry coordinates plus the observed digest. Scoped to docker push observation — consumers convert to v2 Outcome by calling rb.Record with these fields. Does NOT carry credentials, provider, or any value used as a join key; ArtifactID lives with the consumer that knows which step produced this observation.

type RegistryTarget

type RegistryTarget struct {
	URL         string
	Path        string
	Tags        []string
	Credentials string                 // env var prefix for auth (e.g., "DOCKERHUB" → DOCKERHUB_USER/DOCKERHUB_PASS)
	Provider    string                 // registry vendor: dockerhub, ghcr, gitlab, jfrog, harbor, quay, gitea, generic
	Retention   config.RetentionPolicy // restic-style retention policy
	TagPatterns []string               // original unresolved tag templates for pattern matching during retention
	NativeScan  bool                   // trigger registry's own built-in scan after push (Harbor: built-in Trivy)

	// SigningProfile is the resolved trust profile published images are signed
	// under — the synthesized `legacy` default (implicit COSIGN_KEY signing) when
	// the target names no signing_profile. Resolved at lowering, consumed by the
	// publish-phase image signer.
	SigningProfile *config.ResolvedSigningProfile
}

RegistryTarget is a resolved registry push destination.

type ResultsBuilder added in v0.6.0

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

ResultsBuilder accumulates Outcomes during execution and produces a ResultsManifest at the end. Single-writer (per-process); not concurrent- safe — execution is sequential.

Intentionally minimal API: Record appends, Build finalizes. No dedup, no reordering policy, no validation beyond the intent ↔ result join. "Anything smarter becomes a hidden policy engine."

Cross-domain coupling is restricted to ArtifactID. Names and kinds are resolved at Build time from the OutputsManifest — the builder itself does not track them. This keeps ResultsBuilder ignorant of intent structure and prevents drift via metadata duplication.

func NewResultsBuilder added in v0.6.0

func NewResultsBuilder() *ResultsBuilder

NewResultsBuilder returns an empty builder. The intent_checksum is bound at Build() time from the OutputsManifest, not at construction — this ensures results always reference the actual approved intent rather than a checksum cached at construction.

func ResultsBuilderFromManifest added in v0.7.0

func ResultsBuilderFromManifest(m *artifact.ResultsManifest) *ResultsBuilder

ResultsBuilderFromManifest returns a builder pre-seeded with an existing manifest's outcomes, so a later phase EXTENDS recorded history rather than replacing it. published.json is cumulative observed truth (build outcomes recorded by perform, push outcomes by publish) — a phase that re-records its own outcomes into a fresh builder would clobber the earlier facts (e.g. drop archive build outcomes that release-asset discovery depends on). Outcomes are re-recorded in manifest order; the caller then Records this phase's new outcomes on top before Build(). A nil manifest yields an empty builder.

func (*ResultsBuilder) Build added in v0.6.0

Build finalizes the results manifest. Deterministic ordering: artifacts in first-recorded order; outcomes within each artifact in append order.

Returns an error if any recorded outcome references an ArtifactID absent from outputs.Artifacts. This is the only cross-domain validation the builder performs — it enforces the join key without owning any other invariant about intent structure.

outputs must be the in-memory intent snapshot returned by PlanToOutputs (or another already-finalized OutputsManifest). Do NOT round-trip through disk to obtain it — the architecture deliberately removed cross-phase file reads, and reintroducing one here would couple results finalization to I/O ordering.

func (*ResultsBuilder) Record added in v0.6.0

func (b *ResultsBuilder) Record(artifactID artifact.ArtifactID, o artifact.Outcome)

Record appends an outcome for an artifact. Append-only. Caller is responsible for calling Record exactly once per (artifact, target) tuple with the final outcome already fully populated (digest, attestation, requirements_met). No post-Record mutation is supported — the outcome must be a complete fact at the moment of recording.

artifactID is typed (artifact.ArtifactID, not bare string) to make the "ArtifactID is the only join key" invariant compile-enforced. Callers supply IDs obtained from artifact.NewArtifactID or from view/manifest reads — never assembled from fields inline.

type Stage

type Stage struct {
	Name      string // alias from "AS name", empty if unnamed
	BaseImage string // the FROM image reference
	Line      int    // line number of the FROM instruction
}

Stage describes a single FROM stage in a Dockerfile.

type StepMeta added in v0.4.0

type StepMeta interface {
	StepMetaKind() string
}

StepMeta is implemented by typed metadata structs attached to build steps. Every Meta type must be JSON-marshalable and return a stable kind string.

type StepMetrics added in v0.4.0

type StepMetrics struct {
	Duration time.Duration `json:"duration"`
	Cached   bool          `json:"cached"`
}

StepMetrics captures timing and cache information for a step execution.

type StepResult

type StepResult struct {
	Name         string
	Status       string            // "success", "failed", "cached"
	Images       []string          // pushed image references (raw refs for display)
	Publications []PushObservation // structured publish records — v2 wire to ResultsBuilder
	Artifacts    []string          // extracted file paths
	Layers       []LayerEvent      // parsed build layer events (from --progress=plain)
	Duration     time.Duration
	Error        error
}

StepResult captures the outcome of a single build step.

type Target added in v0.7.0

type Target struct {
	OS   string `json:"os"`
	Arch string `json:"arch"`
	Libc string `json:"libc,omitempty"` // "", "gnu", "musl"
	ABI  string `json:"abi,omitempty"`  // optional/future (e.g. "eabihf")
}

Target is the canonical semantic identity of a build target: OS, architecture, and (when it matters) the C library and ABI. This is the ONE target abstraction shared by every language engine — Go reads OS/Arch (and ignores Libc/ABI), Rust PROJECTS the same fields into a target triple. The triple is therefore a derivation of this identity, never stored here and never the primary key, so the abstraction stays language-neutral rather than quietly becoming Rust-centric.

Libc is "" for targets where it is irrelevant or default (every Go target today); it becomes load-bearing the moment musl enters ("linux/amd64" stops being a unique identity once both gnu and musl exist). The derived names (String, step ID, output path, archive name) append Libc only when set, so libc-less targets — i.e. all current Go builds — render byte-identically to before.

func ParseTarget added in v0.7.0

func ParseTarget(s string) Target

ParseTarget splits "os/arch" or "os/arch/libc" into a Target.

func ParseTargets added in v0.7.0

func ParseTargets(ss []string) []Target

ParseTargets parses a slice of "os/arch[/libc]" strings.

func (Target) Slug added in v0.7.0

func (t Target) Slug() string

Slug returns a filesystem/ID-safe "os-arch" (or "os-arch-libc") fragment — the canonical fragment for output dirs, step IDs, and archive names.

func (Target) String added in v0.7.0

func (t Target) String() string

String returns "os/arch" (or "os/arch/libc" when a libc is set).

type TargetSkip added in v0.7.0

type TargetSkip struct {
	TargetID string
	Reason   string
}

TargetSkip records a registry target excluded at plan time and the matcher's reason. It is narrated so a "built but not distributed" outcome explains itself rather than looking like a bug. The Reason comes from the eligibility decision (config.MatchResult), never re-derived by a caller.

type UniversalStep added in v0.4.0

type UniversalStep struct {
	BuildID string        `json:"build_id"` // which build config this belongs to
	StepID  string        `json:"step_id"`  // unique: {build_id}-{variant}-{os}-{arch}
	Engine  string        `json:"engine"`   // "image" | "binary-go" | "binary-rust" — the dispatch key
	Target  Target        `json:"target"`
	Inputs  []ArtifactRef `json:"inputs,omitempty"`
	Outputs []ArtifactRef `json:"outputs,omitempty"`
	Meta    StepMeta      `json:"-"` // engine-specific typed metadata
}

UniversalStep is a single unit of work in a build plan. Both image and binary engines produce steps in this shape.

func (UniversalStep) MarshalJSON added in v0.4.0

func (s UniversalStep) MarshalJSON() ([]byte, error)

MarshalJSON encodes UniversalStep with Meta as a typed JSON object.

type UniversalStepResult added in v0.4.0

type UniversalStepResult struct {
	Artifacts []ProducedArtifact `json:"artifacts"`
	Metadata  map[string]string  `json:"metadata,omitempty"` // e.g., {"toolchain": "go1.24.1"}
	Metrics   StepMetrics        `json:"metrics"`
}

UniversalStepResult is what an engine returns after executing a single step.

type VersionInfo

type VersionInfo = gitver.VersionInfo

VersionInfo is an alias for backward compatibility.

Directories

Path Synopsis
Package contributors holds the build-strategy contributors that supply rows into a perform run's domains.
Package contributors holds the build-strategy contributors that supply rows into a perform run's domains.
Package domains makes a perform run a single domain-ordered narrative.
Package domains makes a perform run a single domain-ordered narrative.
Package engines contains all built-in build engines.
Package engines contains all built-in build engines.

Jump to

Keyboard shortcuts

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