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
- Variables
- func ApprovalFingerprint(kind ApprovalKind, tool, stableKey string) string
- func DefaultLogPath() string
- func DefaultRuntimePath() string
- func DefaultStateDir() string
- func DefaultUserPath() string
- func FindProjectConfig(startDir, projectRoot string) (string, bool)
- func Fingerprint(merged *fileConfig) (string, error)
- func ListToggleNames() []string
- func LookupToggle(name string) (toggleDef, error)
- func PrepareUserConfig(userPath string, notify io.Writer) error
- func SecretsStableKey(ruleIDs []string) string
- type Approval
- type ApprovalKind
- type ApprovalScope
- type Approvals
- type AskFallback
- type AsyncConfig
- type CompileResult
- type CompiledRoute
- type CompiledTarget
- type DispatchMode
- type FailMode
- type GetToggleOptions
- type GetToggleResult
- type GuardAction
- type Guards
- type ImportProviderConfig
- type KindDefault
- type Layer
- type LoadOptions
- type LogLevel
- type LoggingConfig
- type MCPGuard
- type MetricsConfig
- type OverflowMode
- type PathsGuard
- type Policy
- type RecordDecisionOptions
- type RouteMatch
- type SecretsGuard
- type SetToggleOptions
- type SetToggleResult
- type ShellGuard
- type Snapshot
- type Store
- func (s *Store) Current() *Snapshot
- func (s *Store) EnsureProject(cwd, projectRoot string) (*Snapshot, error)
- func (s *Store) FlushRuntime() error
- func (s *Store) IgnoreSelfWrite(path string)
- func (s *Store) LayerYAML(layer Layer, cwd, projectRoot string) ([]byte, error)
- func (s *Store) PatchRuntime(yamlPatch []byte) error
- func (s *Store) ProjectPaths() []string
- func (s *Store) RecordDecision(opts RecordDecisionOptions) error
- func (s *Store) Reload(ctx context.Context) error
- func (s *Store) RuntimePath() string
- func (s *Store) SetLogger(log *slog.Logger)
- func (s *Store) SetOnReload(fn func(result string))
- func (s *Store) SnapshotFor(cwd, projectRoot string) *Snapshot
- func (s *Store) UserPath() string
- func (s *Store) Watch(opts WatchOptions) (*Watcher, error)
- type SyncMerge
- type TargetKind
- type TemporaryBlock
- type ToggleScope
- type ToggleSource
- type TrajectoryConfig
- type WatchOptions
- type Watcher
Constants ¶
const ( GuardSecrets = "secrets" GuardShell = "shell" GuardMCP = "mcp" GuardPaths = "paths" )
Variables ¶
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.
var ErrParseConfig = errors.New("parse config")
ErrParseConfig indicates YAML in a config file could not be unmarshaled.
var ErrToggleAlreadySet = errors.New("toggle already set")
ErrToggleAlreadySet indicates the target layer already matches the requested value.
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 ¶
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 ¶
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
LookupToggle returns a catalog entry by CLI feature name.
func PrepareUserConfig ¶ added in v0.0.4
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 ¶
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 ¶
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
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
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 ¶
ImportProviderConfig is compiled per-provider transcript import settings.
type KindDefault ¶
type KindDefault struct {
Mode DispatchMode
}
KindDefault is a per-kind dispatch default.
type LoadOptions ¶
LoadOptions configures LoadWith.
type LoggingConfig ¶
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 MetricsConfig ¶ added in v0.0.6
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 ¶
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 ¶
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 ¶
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) EnsureProject ¶
EnsureProject resolves, loads, and caches a project layer. Missing project is not an error (returns base snapshot, nil error).
func (*Store) FlushRuntime ¶
FlushRuntime writes the in-memory runtime overlay to disk immediately.
func (*Store) IgnoreSelfWrite ¶
IgnoreSelfWrite marks path so the next watch events for it are skipped (atomic rename).
func (*Store) PatchRuntime ¶
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 ¶
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) RuntimePath ¶
RuntimePath returns the configured runtime overlay path.
func (*Store) SetOnReload ¶ added in v0.0.6
SetOnReload registers a callback invoked after Store.Reload completes. result is "ok" or "error". Not called from PatchRuntime.
func (*Store) SnapshotFor ¶
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.
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 ¶
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 ¶
WatchOptions configures Watch.