definitions

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MPL-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package definitions is the canonical definitions-bundle vocabulary and the pure diffing engine behind `definitions export | check | plan | apply` (source-of-truth ADR, as amended by the flat-model ADR). Like internal/schema it is a pure library: a bundle in, a canonical serialization or a diff out — no store, no authorization, no clock. The service layer (#70) feeds it a snapshot of current state and turns its diff into a plan; the importer (#68) emits an additive bundle through it. Nothing here reads a repository, and nothing here decides policy.

The bundle carries a project's *shape* and nothing value-derived: keys, declarations, presence rules, key groups, and the environment list. Values, snapshots, and manifests are structurally out of scope (ADR § safety boundary), so this package cannot import them.

Index

Constants

View Source
const (
	// MaxBundleBytes bounds the raw request body before it is parsed.
	MaxBundleBytes = 1 << 20 // 1 MiB
	// MaxBundleEntries bounds keys + environments + groups combined.
	MaxBundleEntries = 10_000
)

Bounds. A bundle is attacker-supplied request material (ops-spec row 15), so every ceiling is a named constant refused with a loud ErrLimitExceeded-class refusal — the raw-byte cap before the parse where possible, the entry cap after decode.

View Source
const FormatVersion = 1

FormatVersion is the bundle format version. It advances only when the serialization changes incompatibly; unknown fields already reject loudly, so a newer server's export never applies silently truncated to an older one.

Variables

View Source
var (
	ErrMalformed = errors.New("not a well-formed document")
	ErrTrailing  = errors.New("trailing content after the document")
)

ErrMalformed is a JSON syntax or shape failure; ErrTrailing is content after the top-level document. Both are content-free on purpose.

Functions

func Compare

func Compare(b Bundle, cur CurrentState) (DriftState, Diff, error)

Compare classifies drift and renders the diff in one pass, for the diagnostic `check`. It tolerates additive modification (records it as a difference rather than refusing), because check reports state and never writes.

func DecodeStrict

func DecodeStrict(raw []byte, into any) error

DecodeStrict rejects duplicate object members and unknown fields, decodes into `into`, and refuses trailing content. It is the closed-schema decode every artifact parser funnels through.

func Digest

func Digest(b CanonicalBundle) (string, error)

Digest is the SHA-256 of the canonical encoding, hex-encoded and unprefixed. It is computed over canonical bytes, never the raw file bytes, so a whitespace-only edit does not move the apply pin while any content change does. (This deliberately differs from internal/importer.Digest, whose "sha256:"-prefixed form is a template-reference spelling.)

func Encode

func Encode(b CanonicalBundle) ([]byte, error)

Encode renders a validated canonical bundle: sorted object keys at every depth (including any JSON Schema document embedded in a declaration), two-space indentation, HTML escaping off, and exactly one trailing newline. Byte-stability is what makes the digest a meaningful apply pin and a PR diff legible.

Parse and Canonicalize are the only producers of an encodable bundle, so every successful result parses back to the same canonical model.

func NeedsReveal

func NeedsReveal(u KeyUpdate) bool

NeedsReveal mirrors the two locked reveal gates: a value-dependent rule change on a currently-secret key (schema ADR), and declassification secret→config (reclassification ceremony). Presence-driven reveal — an environment begins delivering a secret the publisher did not supply — is enforced by the publish pipeline itself at apply, not previewed here.

func RejectDuplicateMembers

func RejectDuplicateMembers(raw []byte) error

RejectDuplicateMembers walks the raw token stream before any decode.

Types

type AdditiveModificationError

type AdditiveModificationError struct {
	Key string
	// contains filtered or unexported fields
}

AdditiveModificationError is the refusal to modify an existing entry with an additive bundle. It names the key so the service can attach the definitions.additive_modification_refused audit event, and carries caller-safe detail like every other bundle refusal.

func (*AdditiveModificationError) Error

func (e *AdditiveModificationError) Error() string

func (*AdditiveModificationError) SafeDetail

func (e *AdditiveModificationError) SafeDetail() string

func (*AdditiveModificationError) Unwrap

func (e *AdditiveModificationError) Unwrap() error

type Bundle

type Bundle struct {
	FormatVersion int           `json:"format_version"`
	BaseRevision  *int64        `json:"base_revision,omitempty"`
	Environments  []Environment `json:"environments"`
	KeyGroups     []KeyGroup    `json:"key_groups"`
	Keys          []Key         `json:"keys"`
}

Bundle is the mutable definitions wire/import DTO. Construct it only at an import or test boundary, then immediately pass it to Canonicalize. Application paths encode CanonicalBundle instead. BaseRevision is a pointer so its absence — which makes the bundle *additive* (ADR § Additive bundles) — is distinguishable from a zero base revision.

func (Bundle) Additive

func (b Bundle) Additive() bool

Additive reports whether the bundle carries no base revision, in which case omission derives no deletion and modifying an existing entry is refused (ADR § Additive bundles).

type CanonicalBundle

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

CanonicalBundle is a validated, normalized bundle snapshot. Its fields stay private so only Parse and Canonicalize can create an encodable value. WireBundle returns a detached copy for review and for non-encoding domain operations; mutating that copy cannot alter this canonical snapshot.

func Canonicalize

func Canonicalize(b Bundle) (CanonicalBundle, error)

Canonicalize validates, sorts, and canonicalizes a raw wire-model bundle. Import and test boundaries use it immediately after constructing Bundle.

func Parse

func Parse(raw []byte) (CanonicalBundle, error)

Parse reads a bundle strictly and returns it normalized: the closed schema rejects unknown fields (naming the field and the version mismatch), duplicate members, trailing content, an ids-without-base template, and the deleted `base` field; the size bounds refuse an oversized or overpopulated bundle before it can drive any work. A parsed bundle is normalized (entries sorted by name, declarations in schema-canonical form, presence lists sorted), so it is the sole producer of the canonical form Encode assumes.

func (CanonicalBundle) Additive

func (b CanonicalBundle) Additive() bool

Additive reports whether the canonical bundle has no base revision.

func (CanonicalBundle) WireBundle

func (b CanonicalBundle) WireBundle() Bundle

WireBundle returns a detached copy of the canonical wire model.

type CompiledBundle

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

CompiledBundle keeps parsed wire data separate from the classified declaration artifacts built from it. Apply paths consume both so a declaration is not compiled again after parsing.

func ParseCompiled

func ParseCompiled(raw []byte) (CompiledBundle, error)

ParseCompiled parses and normalizes a wire bundle while retaining each declaration's classified artifact for an immediate apply.

func (CompiledBundle) Canonical

func (b CompiledBundle) Canonical() CanonicalBundle

Canonical returns the validated canonical bundle retained with the compiled declaration artifacts.

func (CompiledBundle) CompiledDeclaration

func (b CompiledBundle) CompiledDeclaration(keyName string) (*schema.Compiled, bool)

CompiledDeclaration returns the artifact for a normalized key name.

func (CompiledBundle) WireBundle

func (b CompiledBundle) WireBundle() Bundle

WireBundle returns a detached wire-model copy of the canonical bundle.

type CurrentKey

type CurrentKey struct {
	ID              string
	Name            string
	FolderPath      string
	Classification  string
	Description     string
	Deprecated      bool
	DeprecationNote string
	GroupID         string
	Declaration     schema.Declaration
	Required        schema.Presence
	Forbidden       schema.Presence
}

CurrentKey is one live catalogue key. GroupID is "" when the key belongs to no group; Required/Forbidden carry environment ids in their explicit sets.

type CurrentState

type CurrentState struct {
	SchemaRevision int64
	Environments   []Environment
	KeyGroups      []KeyGroup
	Keys           []CurrentKey
}

CurrentState is the pure snapshot of a project's definitions a bundle is diffed against. The service builds it from the store; this package never sees a store or service type. Environment and key-group ids are always populated (they are the identities the matcher binds); presence is expressed by environment id, the stable identity the diff compares in.

type Diff

type Diff struct {
	Environments   KindDiff `json:"environments"`
	KeyGroups      KindDiff `json:"key_groups"`
	Keys           KindDiff `json:"keys"`
	RevealRequired []string `json:"reveal_required"`
}

Diff is the human-readable plan preview derived from a Resolution. Deletion live-occurrence counts and reveal enforcement are the service's to enrich; the pure diff carries the structural shape and the reveal-required key names.

type DriftState

type DriftState string

DriftState is the four-way file-versus-database classification (source-of-truth ADR § Drift). check reports it with the 0/1/2 exit contract.

const (
	DriftEqual     DriftState = "equal"
	DriftFileAhead DriftState = "file_ahead"
	DriftDBAhead   DriftState = "db_ahead"
	DriftDiverged  DriftState = "diverged"
)

func Classify

func Classify(b Bundle, cur CurrentState) (DriftState, error)

Classify reports the drift between a bundle and current state. A bundle whose base revision is ahead of current is impossible or foreign and is refused; a base behind current with content matching current is db_ahead, with content differing is diverged; an equal base is equal or file_ahead by whether the bundle changes anything. An additive bundle has no base, so it is file_ahead when it would create or change anything and equal otherwise.

type DuplicateMemberError

type DuplicateMemberError struct{ Member string }

DuplicateMemberError names an object member that appeared more than once. encoding/json otherwise accepts duplicates with last-one-wins semantics, which is unsafe for a reviewed artifact.

func (*DuplicateMemberError) Error

func (e *DuplicateMemberError) Error() string

type Environment

type Environment struct {
	ID   string `json:"id,omitempty"`
	Name string `json:"name"`
}

Environment is one environment-topology entry: a portable name and an optional server-owned id (present on export, stripped by --portable).

type Key

type Key struct {
	ID              string             `json:"id,omitempty"`
	Name            string             `json:"name"`
	FolderPath      string             `json:"folder_path"`
	Classification  string             `json:"classification"`
	Description     string             `json:"description"`
	Deprecated      bool               `json:"deprecated"`
	DeprecationNote string             `json:"deprecation_note"`
	Group           string             `json:"group"`
	Declaration     schema.Declaration `json:"declaration"`
	RequiredIn      Presence           `json:"required_in"`
	ForbiddenIn     Presence           `json:"forbidden_in"`
}

Key is one declaration entry. Every non-id field is always emitted — a bundle is desired state read as a diff, and an omitted field is indistinguishable from an intentional clear. `group` references a KeyGroup by name and is empty when the key belongs to no group.

type KeyGroup

type KeyGroup struct {
	ID   string `json:"id,omitempty"`
	Name string `json:"name"`
}

KeyGroup is one project-scoped key group by name, with an optional id.

type KeyUpdate

type KeyUpdate struct {
	ID                 string
	PrevName           string
	Desired            Key
	Renamed            bool
	MetaChanged        bool
	DeclChanged        bool
	Reclassified       bool
	GroupChanged       bool
	PresenceChanged    bool
	PrevClassification string
	PrevDeclaration    schema.Declaration
}

KeyUpdate is a bound key whose desired state differs from the database. It carries the desired form (presence and group still by name, resolved to ids by apply once the final topology exists) and the change flags the plan and the reveal gate read.

type KindDiff

type KindDiff struct {
	Creates []string `json:"creates"`
	Updates []string `json:"updates"`
	Renames []Rename `json:"renames"`
	Deletes []string `json:"deletes"`
}

KindDiff is the rendered per-kind change list carried by a plan and by a check result. Environment and key-group entries have only a name, so their changes appear as Creates, Renames, and Deletes; Updates is a key-only field.

type Presence

type Presence struct {
	Mode         string   `json:"mode"`
	Environments []string `json:"environments"`
}

Presence is a bundle's per-environment presence rule. It mirrors schema.Presence but names environments by their portable **name**, never by server-owned id, and always serializes its list (determinism beats brevity), so it is a distinct type resolved to ids only after environment matching.

type Ref

type Ref struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type Rename

type Rename struct {
	ID   string `json:"id"`
	From string `json:"from"`
	To   string `json:"to"`
}

Rename records an identity whose name moves. Ref names an identity by id and its current name.

type Resolution

type Resolution struct {
	Additive bool

	EnvCreates []string
	EnvRenames []Rename
	EnvDeletes []Ref

	GroupCreates []string
	GroupRenames []Rename
	GroupDeletes []Ref

	KeyCreates []Key
	KeyUpdates []KeyUpdate
	KeyDeletes []Ref

	RevealKeys []string
}

Resolution is the executable diff: the exact set of store operations apply runs, plus the reveal-requiring keys the preview names. Environment and group topology ops resolve first at apply, then key ops resolve their group name and presence environment names against the final topology. Nothing here has executed — Resolve is pure.

func Resolve

func Resolve(b Bundle, cur CurrentState) (Resolution, error)

Resolve diffs a normalized bundle against current state, applying the ADR's matching algorithm to environments, key groups, and keys independently and composing the result. It enforces the structural invariants that do not need the store: dangling presence/group references, additive-modification refusal, and the identity/name uniqueness the matcher guards. Value-dependent declaration and store-backed invariants (secret literal keywords, live pins, live occurrences) are enforced by the service at apply against the shared helpers.

func (Resolution) DeletionsPresent

func (r Resolution) DeletionsPresent() bool

DeletionsPresent reports whether any kind carries a deletion.

func (Resolution) Diff

func (r Resolution) Diff() Diff

Diff renders the resolution as the plan preview.

func (Resolution) Empty

func (r Resolution) Empty() bool

Empty reports whether the resolution changes nothing.

type UnknownFieldError

type UnknownFieldError struct{ Field string }

UnknownFieldError names a field the target schema does not know — for a closed, versioned artifact that always means a version mismatch.

func (*UnknownFieldError) Error

func (e *UnknownFieldError) Error() string

Jump to

Keyboard shortcuts

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