config

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package config merges and compiles agentd configuration into immutable snapshots.

Owns: four-layer merge, CompileMerged, Store hot-path snapshot, debounced reload, persist, PrepareUserConfig (daemon-start user bootstrap), SetToggle/GetToggle (CLI feature toggles), OfflineFor (edge unreachable path), metrics YAML compile. Must not: dispatch routing (dispatch), hook wire (hookedge).

Invariants:

  • Hot path: Store.Current() only — no disk I/O per Invoke.
  • Reload debounced; atomic snapshot swap.
  • Project cache: `projectsMu` RLock on hit; load under `reloadMu` then `projectsMu` (never reverse).
  • OfflineFor may read disk; used only when the daemon is unreachable.
  • PrepareUserConfig runs only from daemon start; Load/LoadWith never bootstrap.
  • SetToggle may bootstrap the user config file when missing (same shape as PrepareUserConfig).

Entry: Store.Current, CompileMerged, PrepareUserConfig, SetToggle, GetToggle, LookupToggle, OfflineFor. See DESIGN.md §1.5 (config_reload), §7.

Index

Constants

View Source
const (
	GuardSecrets = "secrets"
	GuardShell   = "shell"
	GuardMCP     = "mcp"
	GuardPaths   = "paths"
)

Variables

View Source
var DefaultSecretsRules = []string{
	"aws_key",
	"github_pat",
	"github_fine_grained",
	"slack_token",
	"stripe_live",
	"anthropic_key",
	"openai_key",
	"google_api_key",
	"private_key",
	"jwt",
	"assigned_secret",
}

DefaultSecretsRules are the built-in rule names enabled when secrets.rules is empty.

View Source
var ErrParseConfig = errors.New("parse config")

ErrParseConfig indicates YAML in a config file could not be unmarshaled.

View Source
var ErrToggleAlreadySet = errors.New("toggle already set")

ErrToggleAlreadySet indicates the target layer already matches the requested value.

View Source
var ErrUnknownToggle = errors.New("unknown toggle")

ErrUnknownToggle indicates the feature name is not in the curated toggle catalog.

Functions

func ApprovalFingerprint

func ApprovalFingerprint(kind ApprovalKind, tool, stableKey string) string

ApprovalFingerprint builds the stable approval id for kind+tool+stableKey. Format: sha256:<kind>/<hex>. stableKey must not contain secret material.

func DefaultLogPath

func DefaultLogPath() string

DefaultLogPath returns the default daemon operational log file path.

func DefaultRuntimePath

func DefaultRuntimePath() string

DefaultRuntimePath returns $XDG_STATE_HOME/agentd/runtime.yaml, or $HOME/.local/state/agentd/runtime.yaml when XDG_STATE_HOME is unset. Returns "" when no home/state directory can be resolved.

func DefaultStateDir

func DefaultStateDir() string

DefaultStateDir returns the agentd state directory (parent of runtime.yaml).

func DefaultUserPath

func DefaultUserPath() string

DefaultUserPath returns the default user config path ($HOME/.agentd.yaml). It returns "" when the home directory cannot be resolved.

func FindProjectConfig

func FindProjectConfig(startDir, projectRoot string) (string, bool)

FindProjectConfig walks ancestors of startDir looking for .agentd.yaml. When projectRoot is non-empty and contains .agentd.yaml, that path wins. Returns the absolute path and true when found.

func Fingerprint

func Fingerprint(merged *fileConfig) (string, error)

Fingerprint returns sha256 hex of canonical JSON for the merged fileConfig.

func ListToggleNames added in v0.0.4

func ListToggleNames() []string

ListToggleNames returns sorted curated feature names.

func LookupToggle added in v0.0.4

func LookupToggle(name string) (toggleDef, error)

LookupToggle returns a catalog entry by CLI feature name.

func PrepareUserConfig added in v0.0.4

func PrepareUserConfig(userPath string, notify io.Writer) error

PrepareUserConfig ensures the user config file exists and compiles before daemon load. Creates a minimal bootstrap file when missing. Invalid parse/compile failures print to notify and return an error without modifying the file. Only daemon start should call this.

func SecretsStableKey

func SecretsStableKey(ruleIDs []string) string

SecretsStableKey returns the sorted rule-id key for secrets approvals.

Types

type Approval

type Approval struct {
	Kind        ApprovalKind
	Fingerprint string
	Scope       ApprovalScope
	Project     string
	SessionID   string
	ExpiresAt   time.Time // zero = no wall-clock expiry (session)
	GrantedBy   string
}

Approval is one non-expired runtime approval entry.

type ApprovalKind

type ApprovalKind string

ApprovalKind names the Ask-capable guard that granted the approval.

const (
	ApprovalKindSecrets ApprovalKind = "secrets"
	ApprovalKindShell   ApprovalKind = "shell"
)

func ParseApprovalKind

func ParseApprovalKind(fingerprint string) (ApprovalKind, error)

ParseApprovalKind extracts the guard kind embedded in an approval fingerprint.

type ApprovalScope

type ApprovalScope string

ApprovalScope is the lifetime binding for a recorded approval.

const (
	ApprovalScopeProject ApprovalScope = "project"
	ApprovalScopeSession ApprovalScope = "session"
)

type Approvals

type Approvals struct {
	Secrets []Approval
	Shell   []Approval
}

Approvals is the compiled set of active approvals by kind.

func (Approvals) HasApproval

func (a Approvals) HasApproval(kind ApprovalKind, fingerprint, project, sessionID string, now time.Time) bool

HasApproval reports whether a non-expired matching approval exists.

type AskFallback

type AskFallback string
const (
	AskFallbackDeny       AskFallback = "deny"
	AskFallbackNoDecision AskFallback = "no_decision"
)

type AsyncConfig

type AsyncConfig struct {
	QueueCapacity int
	WorkerLimit   int
	TargetTimeout time.Duration
	OnOverflow    OverflowMode
}

AsyncConfig is the compiled async queue settings.

type CompileResult

type CompileResult struct {
	Policy          Policy
	Async           AsyncConfig
	Guards          Guards
	Approvals       Approvals
	TemporaryBlocks []TemporaryBlock
	Trajectory      TrajectoryConfig
	Logging         LoggingConfig
	Metrics         MetricsConfig
	Routes          []CompiledRoute
	Merged          *fileConfig
}

CompileResult is the compiled Snapshot fields from a layer merge.

func CompileMerged

func CompileMerged(user, project, runtime *fileConfig) (CompileResult, error)

CompileMerged merges defaults ⊕ user ⊕ project ⊕ runtime and compiles Snapshot fields.

type CompiledRoute

type CompiledRoute struct {
	Name        string
	Kind        string // legacy single-kind key for default routes; empty when Match is set
	Match       RouteMatch
	Mode        DispatchMode
	SyncTimeout time.Duration // 0 = no route cap; used with provider timeout margin
	Sync        []CompiledTarget
	Async       []CompiledTarget
	Default     bool // true for routes synthesized from dispatch_defaults
}

CompiledRoute is a compiled dispatch route.

type CompiledTarget

type CompiledTarget struct {
	Kind     TargetKind
	Guards   []string // builtin sync
	Observe  bool     // builtin async
	URL      string   // http
	Command  []string // exec
	Stdin    string   // exec: "raw" or empty
	Level    string   // log: info|warn|error|debug
	Path     string   // file
	Retry    int      // http (M3: always 0)
	Timeout  time.Duration
	Endpoint string   // grpc
	OnError  FailMode // grpc sync: fail_closed (default) | fail_open
	Merge    SyncMerge
}

CompiledTarget is one sync or async target on a route.

type DispatchMode

type DispatchMode string

DispatchMode is a route dispatch mode.

const (
	ModeSyncOnly      DispatchMode = "sync_only"
	ModeAsyncOnly     DispatchMode = "async_only"
	ModeParallel      DispatchMode = "parallel"
	ModeAfterSync     DispatchMode = "after_sync"
	ModeSyncThenAsync DispatchMode = "sync_then_async" // alias for after_sync
)

func NormalizeMode

func NormalizeMode(m DispatchMode) DispatchMode

NormalizeMode maps aliases to canonical modes.

type FailMode

type FailMode string
const (
	FailOpen   FailMode = "fail_open"
	FailClosed FailMode = "fail_closed"
)

func OfflineFor added in v0.0.3

func OfflineFor(opts LoadOptions, cwd string) (FailMode, error)

OfflineFor returns compiled policy.offline for defaults ⊕ user ⊕ project(cwd) ⊕ runtime. Disk I/O is intentional — for the hook edge when the daemon is unreachable only. If opts.RuntimePath is empty, DefaultRuntimePath() is used (missing file is OK).

type GetToggleOptions added in v0.0.4

type GetToggleOptions struct {
	Name       string
	UserPath   string
	ProjectDir string
}

GetToggleOptions configures effective toggle inspection.

type GetToggleResult added in v0.0.4

type GetToggleResult struct {
	Name    string
	Enabled bool
	Source  ToggleSource
}

GetToggleResult is the effective toggle state after merge (runtime excluded).

func GetToggle added in v0.0.4

func GetToggle(opts GetToggleOptions) (GetToggleResult, error)

GetToggle returns the effective toggle state (defaults ⊕ user ⊕ project; no runtime).

type GuardAction

type GuardAction string
const (
	GuardAsk  GuardAction = "ask"
	GuardDeny GuardAction = "deny"
)

type Guards

type Guards struct {
	Secrets SecretsGuard
	Shell   ShellGuard
	MCP     MCPGuard
	Paths   PathsGuard
}

Guards holds compiled guard settings.

type ImportProviderConfig

type ImportProviderConfig struct {
	Enabled bool
	Path    string
}

ImportProviderConfig is compiled per-provider transcript import settings.

type KindDefault

type KindDefault struct {
	Mode DispatchMode
}

KindDefault is a per-kind dispatch default.

type Layer

type Layer string

Layer identifies a config source for Get / show.

const (
	LayerUser    Layer = "user"
	LayerProject Layer = "project"
	LayerRuntime Layer = "runtime"
	LayerMerged  Layer = "merged"
)

type LoadOptions

type LoadOptions struct {
	UserPath    string
	RuntimePath string // empty skips runtime layer
}

LoadOptions configures LoadWith.

type LogLevel

type LogLevel string

LogLevel is the daemon operational log verbosity.

const (
	LogLevelDebug LogLevel = "debug"
	LogLevelInfo  LogLevel = "info"
	LogLevelWarn  LogLevel = "warn"
	LogLevelError LogLevel = "error"
)

type LoggingConfig

type LoggingConfig struct {
	Level LogLevel
	File  string // empty = default state-dir agentd.log
}

LoggingConfig is compiled daemon operational logging settings.

func (LoggingConfig) EffectiveFile

func (c LoggingConfig) EffectiveFile(override string) string

EffectiveFile returns the configured log file path, or "" when the default state-dir path should be used. CLI override wins when non-empty.

func (LoggingConfig) EffectiveLevel

func (c LoggingConfig) EffectiveLevel(override string) (slog.Level, error)

EffectiveLevel returns the slog level, applying a non-empty CLI override first.

type MCPGuard

type MCPGuard struct {
	Enabled     bool
	DenyServers []string
}

MCPGuard is compiled MCP server deny settings.

type MetricsConfig added in v0.0.6

type MetricsConfig struct {
	Enabled bool
	Listen  string
}

MetricsConfig is compiled daemon Prometheus scrape settings.

func (MetricsConfig) EffectiveListen added in v0.0.6

func (c MetricsConfig) EffectiveListen(override string) (enabled bool, listen string, err error)

EffectiveListen returns whether metrics HTTP is enabled and the listen address. A non-empty override enables metrics and overrides the configured listen address.

type OverflowMode

type OverflowMode string
const (
	OverflowDrop OverflowMode = "drop"
	OverflowLog  OverflowMode = "log"
)

type PathsGuard

type PathsGuard struct {
	Enabled   bool
	DenyRead  []string
	DenyWrite []string
}

PathsGuard is compiled filesystem path deny settings.

type Policy

type Policy struct {
	Fail        FailMode
	AskFallback AskFallback
	Offline     FailMode
}

Policy is the compiled fail/ask policy.

type RecordDecisionOptions

type RecordDecisionOptions struct {
	Fingerprint string
	Scope       ApprovalScope
	Project     string
	SessionID   string
	ExpiresAt   time.Time // zero → default by scope
}

RecordDecisionOptions configures Store.RecordDecision.

type RouteMatch

type RouteMatch struct {
	Kinds     []string // empty = any
	Providers []string // empty or ["*"] = any
	Tools     []string // empty = any; tool name or canonical class
}

RouteMatch is compiled match criteria for a declarative route.

type SecretsGuard

type SecretsGuard struct {
	Enabled bool
	Action  GuardAction
	Rules   []string
}

SecretsGuard is compiled secrets guard settings.

type SetToggleOptions added in v0.0.4

type SetToggleOptions struct {
	Name       string
	Scope      ToggleScope
	Enabled    bool
	UserPath   string
	ProjectDir string
}

SetToggleOptions configures a persistent user or project layer write.

type SetToggleResult added in v0.0.4

type SetToggleResult struct {
	Name       string
	Enabled    bool
	Scope      ToggleScope
	ConfigPath string
	AlreadySet bool
}

SetToggleResult describes the outcome of SetToggle.

func SetToggle added in v0.0.4

func SetToggle(opts SetToggleOptions) (SetToggleResult, error)

SetToggle writes a bool toggle to the user or project config file.

type ShellGuard

type ShellGuard struct {
	Enabled      bool
	DenyPatterns []string
	AskOn        []string
}

ShellGuard is compiled shell command guard settings.

type Snapshot

type Snapshot struct {
	Generation      uint64
	Fingerprint     string
	UserPath        string
	RuntimePath     string
	ProjectPath     string
	Policy          Policy
	Async           AsyncConfig
	Guards          Guards
	Approvals       Approvals
	TemporaryBlocks []TemporaryBlock
	Trajectory      TrajectoryConfig
	Logging         LoggingConfig
	Metrics         MetricsConfig
	Routes          []CompiledRoute
}

Snapshot is an immutable compiled configuration generation.

type Store

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

Store holds the current config snapshot for lock-free reads on the hot path.

func Load

func Load(_ context.Context, userPath string) (*Store, error)

Load reads defaults merged with optional user YAML (no runtime path). A missing user file is not an error.

func LoadWith

func LoadWith(_ context.Context, opts LoadOptions) (*Store, error)

LoadWith reads defaults ⊕ user ⊕ runtime into a Store.

func (*Store) Current

func (s *Store) Current() *Snapshot

Current returns the active base snapshot (defaults ⊕ user ⊕ runtime).

func (*Store) EnsureProject

func (s *Store) EnsureProject(cwd, projectRoot string) (*Snapshot, error)

EnsureProject resolves, loads, and caches a project layer. Missing project is not an error (returns base snapshot, nil error).

func (*Store) FlushRuntime

func (s *Store) FlushRuntime() error

FlushRuntime writes the in-memory runtime overlay to disk immediately.

func (*Store) IgnoreSelfWrite

func (s *Store) IgnoreSelfWrite(path string)

IgnoreSelfWrite marks path so the next watch events for it are skipped (atomic rename).

func (*Store) LayerYAML

func (s *Store) LayerYAML(layer Layer, cwd, projectRoot string) ([]byte, error)

LayerYAML returns YAML bytes for a config layer.

func (*Store) PatchRuntime

func (s *Store) PatchRuntime(yamlPatch []byte) error

PatchRuntime merges yamlPatch into the in-memory runtime layer and recompiles. Schedules a debounced flush to runtime.yaml when RuntimePath is set.

func (*Store) ProjectPaths

func (s *Store) ProjectPaths() []string

ProjectPaths returns absolute paths of lazily loaded project configs.

func (*Store) RecordDecision

func (s *Store) RecordDecision(opts RecordDecisionOptions) error

RecordDecision upserts a runtime approval and recompiles.

func (*Store) Reload

func (s *Store) Reload(ctx context.Context) error

Reload re-reads user and runtime files and recompiles base + known projects.

func (*Store) RuntimePath

func (s *Store) RuntimePath() string

RuntimePath returns the configured runtime overlay path.

func (*Store) SetLogger

func (s *Store) SetLogger(log *slog.Logger)

SetLogger configures operational logging for background persist failures.

func (*Store) SetOnReload added in v0.0.6

func (s *Store) SetOnReload(fn func(result string))

SetOnReload registers a callback invoked after Store.Reload completes. result is "ok" or "error". Not called from PatchRuntime.

func (*Store) SnapshotFor

func (s *Store) SnapshotFor(cwd, projectRoot string) *Snapshot

SnapshotFor returns a project-aware snapshot when cwd/projectRoot resolve to a project file; otherwise the base snapshot. Hot-path map lookup after first sighting.

func (*Store) UserPath

func (s *Store) UserPath() string

UserPath returns the configured user config path.

func (*Store) Watch

func (s *Store) Watch(opts WatchOptions) (*Watcher, error)

Watch starts watching the store's user and runtime config paths.

type SyncMerge

type SyncMerge string

SyncMerge is the sync merge policy for a grpc target (engine uses first_conclusive).

const (
	MergeFirstConclusive SyncMerge = "first_conclusive"
)

type TargetKind

type TargetKind string

TargetKind identifies a dispatch target type.

const (
	TargetBuiltin TargetKind = "builtin"
	TargetExec    TargetKind = "exec"
	TargetHTTP    TargetKind = "http"
	TargetLog     TargetKind = "log"
	TargetFile    TargetKind = "file"
	TargetGRPC    TargetKind = "grpc"
)

type TemporaryBlock

type TemporaryBlock struct {
	Tool    string
	Pattern string
	Reason  string
	Until   time.Time
}

TemporaryBlock is one non-expired runtime deny rule.

func MatchTemporaryBlock

func MatchTemporaryBlock(blocks []TemporaryBlock, toolName, haystack string, now time.Time) *TemporaryBlock

MatchTemporaryBlock returns the first active block matching tool name and pattern substring.

type ToggleScope added in v0.0.4

type ToggleScope string

ToggleScope is the config layer written by SetToggle.

const (
	ToggleScopeUser    ToggleScope = "user"
	ToggleScopeProject ToggleScope = "project"
)

type ToggleSource added in v0.0.4

type ToggleSource string

ToggleSource names which merge layer wins for GetToggle.

const (
	ToggleSourceDefault ToggleSource = "default"
	ToggleSourceUser    ToggleSource = "user"
	ToggleSourceProject ToggleSource = "project"
)

type TrajectoryConfig

type TrajectoryConfig struct {
	Enabled           bool
	Statistics        bool
	IncludeRaw        bool
	RedactSecretRules bool
	MaxEventBytes     int
	QueueCapacity     int
	Import            map[string]ImportProviderConfig
}

TrajectoryConfig is compiled trajectory ledger settings.

func (TrajectoryConfig) ClaudeImport

func (c TrajectoryConfig) ClaudeImport() ImportProviderConfig

ClaudeImport returns compiled claude-code import settings.

func (TrajectoryConfig) CodexImport

func (c TrajectoryConfig) CodexImport() ImportProviderConfig

CodexImport returns compiled codex import settings.

func (TrajectoryConfig) CursorImport

func (c TrajectoryConfig) CursorImport() ImportProviderConfig

CursorImport returns compiled cursor import settings.

type WatchOptions

type WatchOptions struct {
	Debounce time.Duration
	Log      *slog.Logger
}

WatchOptions configures Watch.

type Watcher

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

Watcher debounces fsnotify events on user, runtime, and project config files.

func (*Watcher) Close

func (w *Watcher) Close() error

Close stops the watcher.

Jump to

Keyboard shortcuts

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