config

package
v1.23.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: GPL-3.0 Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	AnthropicAPIKeyEnv = "ANTHROPIC_API_KEY"
	OpenAIAPIKeyEnv    = "OPENAI_API_KEY"
	GeminiAPIKeyEnv    = "GEMINI_API_KEY"
	DeepSeekAPIKeyEnv  = "DEEPSEEK_API_KEY"
	MistralAPIKeyEnv   = "MISTRAL_API_KEY"
	CohereAPIKeyEnv    = "COHERE_API_KEY"
	OllamaHostEnv      = "OLLAMA_HOST"
)

Per-provider environment variable names. These are the single source of truth for which env var each provider's credential (or, for ollama, base URL) comes from: ApplyEnv below reads them, and each provider package's Metadata() (internal/provider/*/metadata.go) imports these same constants for its APIKeyEnv field instead of re-spelling the literal. Before this, six provider packages carried their own `const apiKeyEnv = "..."` copy with nothing tying it back to the value actually read here — a rename here would have left the generated inventory (internal/meta/surface.json) and README pointing at a dead variable name while every test still passed.

View Source
const CurrentSchemaVersion = 1

Variables

This section is empty.

Functions

func ApplyEnv

func ApplyEnv(c *Config)

func LoadFileWith added in v1.17.0

func LoadFileWith(path string, opts LoadOptions) (*Config, []UnknownKey, error)

LoadFileWith is LoadFile with explicit options; see LoadOptions.

func LoadWith added in v1.17.0

func LoadWith(globalPath, repoPath string, opts LoadOptions) (*Config, []UnknownKey, error)

LoadWith is Load with explicit options. It additionally returns every unknown key it walked past; with the strict (zero) options that slice is always empty, because the first offender is an error instead.

func Migrate

func Migrate(c *Config) error

func PatchField added in v1.17.0

func PatchField(path string, keyPath []string, value any) error

PatchField writes a single value into the YAML document at path, touching only the node named by keyPath.

It exists to replace the decode-into-Config-then-marshal-the-whole-thing write path `config set` and `providers use` used before: that round-trip silently destroyed three different things on a partial or hand-edited file — see .ssot/plans/2026-09-19-wave-0-ground-truth/06-config-set-write-path.md for the full account. A `Default()`-style merge would only have fixed the first of those (zero-value destruction); an unknown top-level `x-` key has no field in Config at all, so no merge strategy can carry it through a struct round-trip — only operating on the raw document does.

What is guaranteed

Everything else in the document is preserved: comments, key order, anchors/aliases (e.g. a top-level `x-defaults: &d` merged elsewhere via `<<: *d`, or a scalar shared via `&m`/`*m` — patching the anchor's own node keeps every alias to it pointing at the updated value, same as a human editing the `&m` line would), and any key the typed Config schema doesn't know about (including one dropped by --ignore-unknown-config).

Two shapes are refused outright rather than risking a silent loss:

  • a multi-document file (a second `---`-separated document with real content) — only the first document would round-trip;
  • a non-empty file yaml.v3 attaches nothing recoverable to at all (every line commented out, or whitespace-only, with no `---` marker) — there is no way to tell "just blank lines" apart from "a commented-out api_key" from what the parser hands back, so this refuses rather than guess (Faz 06 review turu 2, item G).

What is NOT guaranteed (accepted, by design — Faz 06 review turu 1 item E, turu 2 items I, J, K)

Re-emitting through yaml.v3's encoder is not a line-level surgical patch. None of the following lose data, and each is pinned by a test (patch_test.go) so the behavior stays deliberate rather than drifting:

  • blank lines between sections are collapsed;
  • CRLF line endings become LF;
  • a zero-indented block sequence (`key:\n- item`) is re-indented under its key (`key:\n - item`);
  • the exact scalar node being patched loses its own prior quote style and any explicit tag (`model: "sonnet"` → `model: opus`, dropping the quotes; `base_url: !!str http://x` → `base_url: http://y`, dropping the tag) — everything else in the document, flow-style collections included, keeps its original style;
  • an inline comment's spacing before `#` is normalized to a single space on ANY line in the document, not just the one being patched (`provider: mock # note` → `provider: mock # note`) — this is yaml.v3's encoder, not something PatchField's own logic touches; the comment's content and every other line are untouched, nothing is lost;
  • a merge key (`<<:`) that happens to be the ONLY nested block-mapping structure under an unknown/`x-` key can still push detectIndent to its 4-space fallback instead of matching the file's real indent width — unreachable through any schema-known key, since `guard.secret_patterns` and friends are always nested under a real mapping detectIndent already finds first.

Fixing any of these would require a real line-level patch instead of a parse/mutate/re-emit round-trip, which is out of scope for this fix.

keyPath is the dotted-path segments (e.g. ["output", "lang"] or ["providers", "anthropic", "api_key"]); every segment but the last names a mapping to descend into (created empty if absent, or converted in place if it was a bare/null key). value's Go type determines the YAML scalar tag written (bool/int/float64/string): pass the already-coerced, already-validated value, not the raw command-line string.

When path does not exist yet, or is a genuinely empty (zero-byte) file, PatchField creates it with just the minimal nested structure for keyPath — there is nothing on disk to preserve, so there is nothing lost by not writing a full default skeleton here; callers that want that first-run skeleton (setup.WriteConfig with a config.Default()-based value) should check existence themselves and skip PatchField for the "file doesn't exist" case, exactly as internal/cli/config.go and internal/cli/providers.go do.

Types

type CacheConfig

type CacheConfig struct {
	Enabled   bool `yaml:"enabled"`
	TTLDays   int  `yaml:"ttl_days"`
	MaxSizeMB int  `yaml:"max_size_mb"`
}

CacheConfig controls the local response cache (ADR-0008). MaxSizeMB bounds the on-disk cache: after each write, if the cache directory exceeds this many mebibytes the oldest entries are evicted oldest-first until it fits (the just-written entry is never evicted). Zero — the default — disables eviction; `cache prune` stays the manual stand-in. A new key rather than the v0.9.1-removed `max_size_mb` revival: this one is actually read on the Put path.

type CommandConfig added in v1.3.0

type CommandConfig struct {
	Default string `yaml:"default"`
}

CommandConfig customizes the bare `commitbrief` invocation. Default is the argument string applied when `commitbrief` is run with NO arguments at all — e.g. "--unstaged --cli gemini" makes a bare `commitbrief` behave like `commitbrief --unstaged --cli gemini`. Empty (the default) preserves the built-in behavior, `commitbrief` == `commitbrief --staged`. It only fires for the truly bare invocation; passing any flag or subcommand bypasses it entirely (the user is being explicit). Tokens are whitespace-split; shell quoting is not interpreted.

type CommitConfig added in v1.5.0

type CommitConfig struct {
	Type     string `yaml:"type"`
	Generate int    `yaml:"generate"`
}

CommitConfig sets defaults for the `commit` command (ADR-0019) so a repo or user can pin a preferred message format / suggestion count without retyping flags. Precedence is flag > config > built-in default. Type is one of plain|conventional|conventional+body|gitmoji|subject+body; an empty value means "use the built-in default" (plain). Generate is the number of suggestions to offer; zero/negative means the built-in default (1). The values are validated at the CLI layer, not here, so a stale config never blocks loading.

type Config

type Config struct {
	Version   int                       `yaml:"version"`
	Provider  string                    `yaml:"provider"`
	Providers map[string]ProviderConfig `yaml:"providers"`
	Output    OutputConfig              `yaml:"output"`
	Cache     CacheConfig               `yaml:"cache"`
	Guard     GuardConfig               `yaml:"guard"`
	Cost      CostConfig                `yaml:"cost"`
	Command   CommandConfig             `yaml:"command"`
	Commit    CommitConfig              `yaml:"commit"`
	Review    ReviewConfig              `yaml:"review"`
}

func Default

func Default() *Config

func Load

func Load(globalPath, repoPath string) (*Config, error)

func LoadFile

func LoadFile(path string) (*Config, error)

type CostConfig added in v0.8.0

type CostConfig struct {
	WarnThresholdUSD float64 `yaml:"warn_threshold_usd"`
}

CostConfig controls the pre-send cost preflight added in v0.8.0. WarnThresholdUSD is the estimated-cost ceiling above which the CLI will prompt (TTY) or abort (non-TTY) before contacting the provider. Zero or negative disables the check entirely; the default of 0.50 is a "occasional dev review" budget — users running scheduled jobs should bump it via config or pass --no-cost-check per-invocation.

type GuardConfig added in v0.8.0

type GuardConfig struct {
	SecretScan     bool                  `yaml:"secret_scan"`
	TokenPreflight bool                  `yaml:"token_preflight"`
	SecretPatterns []SecretPatternConfig `yaml:"secret_patterns"`
	InjectionScan  bool                  `yaml:"injection_scan"`
}

GuardConfig toggles pre-send protections that don't quite fit elsewhere. SecretScan controls the credential-pattern scan added in v0.8.0 (ADR-0007 follow-up); leaving it true is the safe default, false disables it entirely for users who pipeline outputs through a secrets manager and don't want the prompt.

TokenPreflight is an opt-in (default false) guard (ADR-0003): when on, a review whose estimated prompt tokens exceed the provider's context window prompts for confirmation (TTY) or aborts (non-TTY) before the paid round-trip, instead of letting the provider reject it with a raw 400. Off by default because the estimate is a chars/4 heuristic and a false positive shouldn't block a review nobody asked to guard.

SecretPatterns lets a user ADD their own credential regexes on top of the built-in set (ADR-0024); it is purely additive — the built-ins always run and cannot be disabled via this field (set secret_scan: false to turn the whole scan off). Each entry compiles once per review; an invalid regex fails the review with a clear error naming the offending pattern. Only meaningful while secret_scan is on.

InjectionScan controls the prompt-injection scan of a non-default COMMITBRIEF.md / OUTPUT.md (ADR-0025): when on (the default), the CLI warns — never aborts — if the user's own rules content contains injection-shaped phrasing ("ignore previous instructions", etc.). It is defense-in-depth visibility complementing the passive XML-wrap immutability guard; the embedded defaults are trusted and skipped.

type LoadOptions added in v1.17.0

type LoadOptions struct {
	// IgnoreUnknownKeys downgrades an unknown key from a hard failure to a
	// reported finding: the load proceeds and the offenders come back as
	// []UnknownKey for the caller to warn about. It exists for `commitbrief
	// --ignore-unknown-config` — a config that loaded yesterday must not
	// become unusable today — and deliberately does NOT restore the old
	// silence: a caller that drops the returned findings on the floor is
	// reintroducing the exact bug strict validation removed.
	//
	// Note what "ignoring" means: the key stays in the merged map and is
	// dropped by the final typed decode, so a typo'd key simply has no
	// effect. That is precisely why the warning is mandatory — the user
	// believes the setting is in force and it is not.
	IgnoreUnknownKeys bool
}

LoadOptions tunes a load. The zero value is the strict default, so every existing caller keeps the behavior it had.

type ModelPricing added in v1.2.0

type ModelPricing struct {
	InputPer1M       float64 `yaml:"input_per_1m,omitempty"`
	OutputPer1M      float64 `yaml:"output_per_1m,omitempty"`
	CachedInputPer1M float64 `yaml:"cached_input_per_1m,omitempty"`
}

ModelPricing is a per-1M-token rate override for one model.

type OutputConfig

type OutputConfig struct {
	Lang   string `yaml:"lang"`
	Stream bool   `yaml:"stream"`
	Color  string `yaml:"color"`
}

type ProviderConfig

type ProviderConfig struct {
	APIKey  string `yaml:"api_key,omitempty"`
	Model   string `yaml:"model,omitempty"`
	BaseURL string `yaml:"base_url,omitempty"`

	// APIKeyEnv names the environment variable the credential is read from.
	// When set it beats both the provider's fixed env var (ANTHROPIC_API_KEY
	// and friends) and api_key; if it is set but the named variable is
	// empty, the run fails instead of falling back. Opt-in on every API
	// provider; no effect for the *-cli providers (see
	// provider.ResolveAPIKeyEnv and cli.applyAPIKeyEnvLenient).
	APIKeyEnv string `yaml:"api_key_env,omitempty"`

	// ContextWindow overrides the provider's built-in per-model context
	// window, in tokens. Zero (unset) keeps the provider table. Consumed by
	// the token preflight and dry-run via resolveContextWindow
	// (internal/cli); it is the only source for openai-compatible, whose
	// models are unknown to CommitBrief.
	ContextWindow int `yaml:"context_window,omitempty"`

	// Pricing overrides the built-in per-model rate table (OQ-09), keyed
	// by model name. Useful when the hard-coded snapshot drifts or for a
	// negotiated rate. Zero fields fall back to the built-in value, so a
	// partial override (e.g. only output_per_1m) is allowed. Consumed by
	// the cost preflight, verbose footer, and cached-cost figures via
	// resolvePricing (internal/cli).
	Pricing map[string]ModelPricing `yaml:"pricing,omitempty"`
}

type ReviewConfig added in v1.7.0

type ReviewConfig struct {
	Flaky            bool     `yaml:"flaky"`
	Baseline         bool     `yaml:"baseline"`
	Architecture     bool     `yaml:"architecture"`
	ArchitectureFile string   `yaml:"architecture_file"`
	SandboxRerun     int      `yaml:"sandbox_rerun"`
	SandboxCommand   []string `yaml:"sandbox_command"`
	Timeout          string   `yaml:"timeout,omitempty"`
}

ReviewConfig toggles review-time behaviors that aren't pre-send guards.

Flaky enables the deterministic static flaky-test detector (ADR-0022): a provider-free pre-pass that flags timing/randomness anti-patterns in changed test files and merges them into the structured findings. On by default; precedence is --no-flaky > review.flaky config > built-in (true).

Baseline enables the user-private signal-control baseline (ADR-0027, SC1): when on (the default) and a <repoRoot>/.commitbrief/baseline.json exists, findings whose fingerprint is recorded there are removed from the run (a TRUE removal — fail-on + JSON findings[] + display, distinct from the display-only --min-severity). The file is per-developer and gitignored so it never reaches CI/the senior gate. Precedence is --no-baseline > review.baseline config > built-in (true); --update-baseline rewrites the file from the current findings instead of filtering this run. A missing file is a transparent no-op even when this is true. Architecture enables architecture-aware review (ADR-0030): when on (the default) and a <repoRoot>/architecture.json (archlint's config) exists, CommitBrief renders a compact summary of the declared layers and their allowed/forbidden import edges into the review prompt as an <architecture_constraints> block, so the LLM can flag a diff that crosses a declared boundary. It is a one-way READ of archlint's public config — CommitBrief never lints or enforces, archlint owns that. A missing or malformed file is a transparent no-op. Precedence is --no-architecture > review.architecture config > built-in (true); the file location is overridable via review.architecture_file (default architecture.json).

SandboxRerun opts into sandbox-rerun confirmation for the flaky detector (ADR-0022 §Update 2026-06-21): the number of times a statically flagged candidate is re-run in isolation to classify it empirically (mixed pass+fail → confirmed flaky, all-fail → real failure, all-pass → transient). 0 (the default) disables it, so the static-only behaviour is unchanged. It is effective only when a rerun Executor is bound (the seam is caller-provided), and only the flaky pre-pass is affected. Precedence is --sandbox-rerun[=N] > review.sandbox_rerun config > built-in (0 / off).

Timeout bounds a whole command run — diff acquisition, prompt build, provider call, render, and any interactive confirmation in between. It is a STRING, not a duration, so the YAML stays readable (`timeout: "10m"`) instead of serializing as a nanosecond count; both a Go duration ("90s", "10m", "1h30m") and a bare whole number of seconds ("600") parse. Empty or "0" (the default) means no deadline, leaving each provider's built-in cap in place — the historical behaviour. Precedence is --timeout > review.timeout > built-in, so `--timeout 0` cancels a configured value for a single run. Beyond the deadline it also RAISES the caps that would otherwise fire first (clireview's 5 minutes, ollama's http.Client timeout, the Anthropic SDK's 10-minute non-streaming ceiling) via provider.TimeoutSetter.

SandboxCommand is the argv of the command that re-runs a single flagged test in isolation (ADR-0033). Each element is a Go text/template over {{.File}}, {{.Line}}, {{.Test}} and is passed to exec as an argv element — never through a shell. Empty (the default) leaves sandbox rerun inert even when --sandbox-rerun is set: running repository code takes two deliberate opt-ins.

type SecretPatternConfig added in v1.7.0

type SecretPatternConfig struct {
	Name  string `yaml:"name"`
	Regex string `yaml:"regex"`
}

SecretPatternConfig is one user-supplied credential pattern (ADR-0024). Name is the human-readable label echoed in scan output (line numbers + names only — the matched substring is never recorded); Regex is a Go regexp/syntax expression compiled at review time. Both are required; an empty name or an invalid regex fails the review with a clear error.

type UnknownKey added in v1.17.0

type UnknownKey struct {
	Path    string
	Source  string
	Allowed []string

	// TopLevel is true when the offender sits at the document root rather
	// than inside a known section. It exists purely to shape Error()'s
	// hint: a root-level typo is the one place an `x-` prefix (see
	// walkMapping) would have silenced it, so that's the one place the
	// message suggests it.
	TopLevel bool
}

UnknownKey is one configuration key that has no home in Config.

It exists because the load path is a round-trip through map[string]any (see load.go): yaml.v3 quietly discards any mapping key without a matching struct field, so a typo like `regexp:` for `regex:` used to produce a zero-valued field instead of an error — leaving the user silently unprotected. Path is the dotted YAML path of the offender (slice elements carry their index, e.g. guard.secret_patterns[0].regexp), Source is the file the key came from, and Allowed is the sibling key set at that level.

func ValidateKeys added in v1.17.0

func ValidateKeys(m map[string]any, source string) []UnknownKey

ValidateKeys reports every key in m that Config has no field for.

The legal key set is derived by reflecting over Config's yaml tags rather than hand-written, so adding a field to Config can never leave this validator behind — drift here would reintroduce exactly the silent discard it exists to prevent.

Findings are returned sorted by path: Go randomizes map iteration, and an error message that changes between runs is not a usable error message.

func (UnknownKey) Error added in v1.17.0

func (u UnknownKey) Error() string

Error follows the established "name the offender, list the allowed set" wording (cf. internal/cli/config.go's `unknown field %q in guard`).

This is deliberately a plain, English-only Go error — it is NOT run through the i18n catalog (fixed 2026-09-19, review turu 2 item 10: an earlier version of this comment claimed "the CLI boundary is what localizes it", but resolveContext (internal/cli/context.go) returns this error as-is via errors.As, and internal/config cannot import internal/i18n without an import cycle risk anyway). The sibling warning for the lenient path (config.unknown_key_ignored) IS localized, at the CLI layer, because that one is a literal built there from scratch; this one is the terminal, English message for the strict failure path and is treated like any other wrapped stdlib/library error in this codebase (e.g. yaml.v3's own parse errors, which are English too).

Jump to

Keyboard shortcuts

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