Documentation
¶
Overview ¶
Package config loads and validates the engine sections of hive's config.yaml: the settings the hive engine reads, which both the CLI and Hive Desktop run on. Sections only the CLI reads live in cmd/hive/internal/config, which embeds this Config.
Index ¶
- Constants
- Variables
- func ApplyEdit(path string, edit Edit, check Check) error
- func CheckWorkspace(path string) error
- func ConfigPathIn(dir string) string
- func CreateFile(path string) error
- func DefaultConfigDir() string
- func DefaultConfigPath() string
- func DefaultDataDir() string
- func IsReservedAgentKey(key string) bool
- func LogFilePath(dataDir string) string
- func ReadFile(configPath string) ([]byte, error)
- func ResolveDataDir(getenv func(string) string, fallback string) string
- func ValidateCloneStrategy(s string) error
- func YAMLFlowSequence(ss []string) string
- func YAMLScalar(s string) string
- type ActionTemplateData
- type AgentProfile
- type AgentsConfig
- type BatchSpawnTemplateData
- type BranchTemplateData
- type Check
- type Config
- func (c *Config) BinDir() string
- func (c *Config) Complete(dataDir string)
- func (c *Config) ContextDir() string
- func (c *Config) DatabaseFile() string
- func (c *Config) GetBranchTemplate(remote string) string
- func (c *Config) GetCloneProtocol(candidates ...string) session.CloneProtocol
- func (c *Config) GetCloneStrategy(remote string) string
- func (c *Config) GetMaxRecycled(remote string) int
- func (c *Config) GetRecycleCommands(remote string) []string
- func (c *Config) RepoContextDir(owner, repo string) string
- func (c *Config) ReposDir() string
- func (c *Config) SharedContextDir() string
- func (c *Config) Validate() error
- func (c *Config) ValidateDeep(configPath string) error
- func (c *Config) Warnings() []ValidationWarning
- type ConfirmPolicyConfig
- type ContextConfig
- type DatabaseConfig
- type Edit
- type EditProfile
- type ExperimentalConfig
- type GitConfig
- type InvalidEditError
- type MessagingConfig
- type MissingPolicyConfig
- type PaneConfig
- type RecycleTemplateData
- type Rule
- type ServerConfig
- type SpawnStrategy
- type SpawnTemplateData
- type TerminalConfig
- type TerminalConfirmConfig
- type TerminalStatusConfig
- type TmuxConfig
- type TodosConfig
- type TodosLimiterConfig
- type TodosNotifyConfig
- type ValidationWarning
- type WindowConfig
Constants ¶
const ( CloneStrategyFull = "full" CloneStrategyWorktree = "worktree" )
Clone strategy constants.
const ( // EnvDefaultAgent overrides agents.default when set. EnvDefaultAgent = "HIVE_DEFAULT_AGENT" // EnvContextBaseDir overrides context.base_dir when set. EnvContextBaseDir = "HIVE_CONTEXT_BASE_DIR" // EnvGitPath overrides git_path when set. EnvGitPath = "HIVE_GIT_PATH" )
const ( // EnvConfig names the config file, overriding the probe of the config // directory. EnvConfig = "HIVE_CONFIG" EnvDataDir = "HIVE_DATA_DIR" // EnvDesktopDataDir names the hive data directory for Hive Desktop only. It // wins over EnvDataDir so a development desktop can point at a hive.db // other than the one the shell's hive CLI uses. EnvDesktopDataDir = "HIVE_DESKTOP_HIVE_DATA_DIR" )
const DefaultMaxRecycled = 5
DefaultMaxRecycled is the default limit for recycled sessions per repository.
Variables ¶
var ( ErrWorkspaceEmpty = InvalidEditError{Reason: "choose a folder"} ErrWorkspaceMissing = InvalidEditError{Reason: "that folder does not exist"} ErrWorkspaceNotDir = InvalidEditError{Reason: "that is a file, not a folder"} // ErrWorkspaceIsRepo is the mistake people actually make, and the resulting // config finds nothing with no hint as to why. ErrWorkspaceIsRepo = InvalidEditError{Reason: "that is a repository, not the folder that holds your repositories"} )
Workspace problems CheckWorkspace reports. Each is an InvalidEditError, so its message is what a setup screen shows; another caller compares with errors.Is and words its own.
var DefaultRecycleCommands = []string{
"git fetch origin",
"git checkout -f {{ .DefaultBranch }}",
"git reset --hard origin/{{ .DefaultBranch }}",
"git clean -fd",
}
DefaultRecycleCommands are the default commands run when recycling a session.
Functions ¶
func ApplyEdit ¶
ApplyEdit reconciles the owned keys while preserving the rest of an existing document. A new or keyless file is rendered with explanatory comments. When provided, check runs against the candidate before replacement so Hive can reject an edit without breaking the next launch.
func CheckWorkspace ¶
CheckWorkspace checks a path is usable as a workspace: an existing directory that is not itself a git repository. A leading ~ is expanded.
func ConfigPathIn ¶
ConfigPathIn returns the first config file present in dir, probing config.yaml, config.yml, hive.yaml and hive.yml in that order. When none is present it returns dir/config.yaml, the file a writer creates.
func CreateFile ¶
CreateFile writes the commented header and nothing else, for a user who asked to open the file in an editor before setup has anything to put in it. An existing file, symlink included, is left alone.
func DefaultConfigDir ¶
func DefaultConfigDir() string
DefaultConfigDir returns $XDG_CONFIG_HOME/hive (falling back to ~/.config/hive).
func DefaultConfigPath ¶
func DefaultConfigPath() string
DefaultConfigPath returns the config file present in DefaultConfigDir, or "" when there is none.
func DefaultDataDir ¶
func DefaultDataDir() string
DefaultDataDir returns the default data directory using XDG_DATA_HOME.
func IsReservedAgentKey ¶
IsReservedAgentKey reports whether key inside `agents:` is a setting rather than a profile name.
func LogFilePath ¶ added in v0.62.0
LogFilePath returns the shared CLI and Desktop log path in dataDir.
func ReadFile ¶
ReadFile returns the config file's contents, or nil when configPath is empty or names no file.
func ResolveDataDir ¶
ResolveDataDir returns the hive data directory the environment names: EnvDesktopDataDir, then EnvDataDir, then fallback. getenv is a parameter because a desktop launched from the Dock reads these from the login shell, not from its own environment.
func ValidateCloneStrategy ¶
ValidateCloneStrategy returns an error if s is not a valid clone strategy value.
func YAMLFlowSequence ¶
YAMLFlowSequence renders ss as an inline YAML sequence, `[]` when empty.
func YAMLScalar ¶
YAMLScalar renders s as a YAML scalar for hand-written template output, quoting it when its YAML meaning would otherwise change.
Types ¶
type ActionTemplateData ¶
ActionTemplateData provides template variables for custom action templates.
type AgentProfile ¶
type AgentProfile struct {
Command string `json:"command" yaml:"command"` // CLI binary (defaults to profile key if omitted)
Flags []string `json:"flags" yaml:"flags"` // extra CLI args appended to command on spawn
}
AgentProfile defines an agent's command and flags.
func (AgentProfile) CommandOrDefault ¶
func (p AgentProfile) CommandOrDefault(key string) string
CommandOrDefault returns the command, falling back to the given key name.
func (AgentProfile) ShellFlags ¶
func (p AgentProfile) ShellFlags() string
ShellFlags returns the flags as a space-joined string. Individual flags are NOT quoted; the caller is responsible for quoting the entire value (e.g., via shq in templates) or relying on shell word splitting when consuming the value.
type AgentsConfig ¶
type AgentsConfig struct {
Default string // reserved key selecting the active profile
AgentSelector bool // when true, the TUI new-session form prompts for agent selection
Profiles map[string]AgentProfile // profile name → agent configuration
}
AgentsConfig holds agent profile configuration. The "default" key selects which profile to use; all other keys are profile definitions.
func (AgentsConfig) DefaultProfile ¶
func (a AgentsConfig) DefaultProfile() AgentProfile
DefaultProfile returns the profile selected by the Default key. Returns a zero AgentProfile if the default is not found.
func (*AgentsConfig) UnmarshalYAML ¶
func (a *AgentsConfig) UnmarshalYAML(node *yaml.Node) error
UnmarshalYAML separates the "default" and "agent_selector" keys from profile entries.
type BatchSpawnTemplateData ¶
type BatchSpawnTemplateData struct {
Path string // Absolute path to the session directory
Name string // Session name (directory basename)
Prompt string // User-provided prompt (batch only)
Slug string // Session slug (URL-safe version of name)
ContextDir string // Path to context directory
Owner string // Repository owner
Repo string // Repository name
ID string // Short random ID shared with the session directory
}
BatchSpawnTemplateData defines available fields for batch_spawn command templates (hive batch).
type BranchTemplateData ¶
type BranchTemplateData struct {
Name string // Session name (display name)
Slug string // Session slug (URL-safe version of name)
Owner string // Repository owner
Repo string // Repository name
ID string // Short random ID shared with the session directory
}
BranchTemplateData defines available fields for branch_template Go templates.
type Check ¶
Check inspects a candidate config file before it replaces the real one, and an error stops the write. It lets a program that reads more sections than this package validates check the whole file.
type Config ¶
type Config struct {
Git GitConfig `json:"git" yaml:"git"`
GitPath string `json:"git_path" yaml:"git_path"`
Rules []Rule `json:"rules" yaml:"rules"`
Agents AgentsConfig `json:"agents" yaml:"agents"`
AutoDeleteCorrupted bool `json:"auto_delete_corrupted" yaml:"auto_delete_corrupted"`
Context ContextConfig `json:"context" yaml:"context"`
Messaging MessagingConfig `json:"messaging" yaml:"messaging"`
Tmux TmuxConfig `json:"tmux" yaml:"tmux"`
Terminal TerminalConfig `json:"terminal" yaml:"terminal"`
Database DatabaseConfig `json:"database" yaml:"database"`
Todos TodosConfig `json:"todos" yaml:"todos"`
Experimental ExperimentalConfig `json:"experimental" yaml:"experimental"`
Servers []ServerConfig `json:"servers" yaml:"servers"`
Workspaces []string `json:"workspaces" yaml:"workspaces"` // parent directories containing git repository folders for new session dialog
RepoDirsCompat []string `json:"-" yaml:"repo_dirs"` // deprecated: use workspaces instead (kept for backwards compatibility)
DataDir string `json:"-" yaml:"-"` // set by caller, not from config file
}
Config holds the engine configuration. Decoding is not strict, so a file that also carries CLI-only sections loads without error.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
func Load ¶
Load reads configuration from the given path and sets the data directory. If configPath is empty or doesn't exist, returns defaults with the provided dataDir.
func (*Config) Complete ¶
Complete finishes a decoded Config: it sets the data directory, adopts the deprecated repo_dirs key, fills defaults for unset values and applies environment overrides. Load calls it; a program that decodes the file into its own struct calls it on the embedded Config before validating.
func (*Config) ContextDir ¶
ContextDir returns the base context directory path.
func (*Config) DatabaseFile ¶
DatabaseFile returns the path to the SQLite database file.
func (*Config) GetBranchTemplate ¶
GetBranchTemplate returns the branch_template for the given remote URL. The last matching rule with a branch_template set wins. Returns "" if no rule defines a template (caller uses the default "hive-<id>" branch).
func (*Config) GetCloneProtocol ¶ added in v0.66.0
func (c *Config) GetCloneProtocol(candidates ...string) session.CloneProtocol
GetCloneProtocol returns the clone protocol for a repository given every spelling of it. The last rule whose pattern matches any candidate and sets clone_protocol wins, then git.clone_protocol; "" means no preference.
func (*Config) GetCloneStrategy ¶
GetCloneStrategy returns the effective clone strategy for the given remote. The last matching rule with a clone_strategy set wins; defaults to "full".
func (*Config) GetMaxRecycled ¶
GetMaxRecycled returns the max recycled sessions limit for the given remote URL. Returns DefaultMaxRecycled (5) if no limit is configured. Returns 0 for unlimited.
func (*Config) GetRecycleCommands ¶
GetRecycleCommands returns the recycle commands for the given remote URL. Rules are evaluated in order; the last matching rule with recycle commands wins. If no rules define recycle commands, returns DefaultRecycleCommands.
func (*Config) RepoContextDir ¶
RepoContextDir returns the context directory for a specific owner/repo.
func (*Config) SharedContextDir ¶
SharedContextDir returns the shared context directory.
func (*Config) ValidateDeep ¶
ValidateDeep performs comprehensive validation of the configuration including template syntax, regex patterns, and file accessibility. The configPath argument specifies the config file location to validate (empty string skips config file check). This calls Validate() first for basic structural validation, then adds I/O checks.
func (*Config) Warnings ¶
func (c *Config) Warnings() []ValidationWarning
Warnings returns non-fatal configuration issues.
type ConfirmPolicyConfig ¶
type ConfirmPolicyConfig struct {
Polls int `json:"polls" yaml:"polls"`
MinDuration time.Duration `json:"min_duration" yaml:"min_duration"`
StableContent *bool `json:"stable_content" yaml:"stable_content"` // nil = default
}
ConfirmPolicyConfig is the YAML/JSON shape of one status.ConfirmPolicy.
type ContextConfig ¶
type ContextConfig struct {
BaseDir string `json:"base_dir" yaml:"base_dir"` // override context base path (default: $HIVE_DATA_DIR/context/)
SymlinkName string `json:"symlink_name" yaml:"symlink_name"` // default: ".hive"
}
ContextConfig configures context directory behavior.
type DatabaseConfig ¶
type DatabaseConfig struct {
MaxOpenConns int `json:"max_open_conns" yaml:"max_open_conns"` // max open connections (default: 2)
MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns"` // max idle connections (default: 2)
BusyTimeout int `json:"busy_timeout" yaml:"busy_timeout"` // busy timeout in milliseconds (default: 5000)
}
DatabaseConfig holds SQLite database configuration.
type Edit ¶
type Edit struct {
DefaultAgent string
Profiles []EditProfile
Workspaces []string
}
Edit is the set of config fields a setup flow owns: the workspaces the session launcher scans, the agent profiles it offers, and which of them is the default. Comments, key order and keys this build does not know survive a write as parsed, and so do the blank lines around them; indentation is re-emitted by yaml.v3.
Profiles and Workspaces are each the whole set, not a delta: the editor holds every entry while it is open, so a write reconciles the file to exactly what it was given (the agentws/write.go pattern).
type EditProfile ¶
EditProfile is one agent profile in an Edit. An empty Command writes the profile name as the command.
type ExperimentalConfig ¶ added in v0.68.0
type ExperimentalConfig struct {
// Daemon routes session writes and session status through `hive daemon`,
// which a client starts on first use.
Daemon bool `json:"daemon" yaml:"daemon"`
}
ExperimentalConfig turns on features that are not finished. A change takes effect when a program restarts.
type GitConfig ¶
type GitConfig struct {
StatusWorkers int `json:"status_workers" yaml:"status_workers"`
// CloneProtocol is the transport for clone URLs hive generates from an
// item's repository. Empty means no preference.
CloneProtocol session.CloneProtocol `json:"clone_protocol" yaml:"clone_protocol"`
}
GitConfig holds git-related configuration.
type InvalidEditError ¶
type InvalidEditError struct{ Reason string }
InvalidEditError is an edit the user can fix, as opposed to a disk that would not take the write. It is a distinct type so a caller classifies it with errors.As rather than by reading the message.
func (InvalidEditError) Error ¶
func (e InvalidEditError) Error() string
type MessagingConfig ¶
type MessagingConfig struct {
TopicPrefix string `json:"topic_prefix" yaml:"topic_prefix"` // default: "agent"
MaxMessages int `json:"max_messages" yaml:"max_messages"` // max messages per topic (default: 100, 0 = unlimited)
}
MessagingConfig holds messaging-related configuration.
type MissingPolicyConfig ¶
type MissingPolicyConfig struct {
Polls int `json:"polls" yaml:"polls"`
}
MissingPolicyConfig is deliberately polls-only: missing is decided by the tmux transport counting consecutive list-panes failures (polls N tolerates N-1 failures), never by the tracker's duration/content-stability debounce, so min_duration and stable_content have no meaning here — the narrower shape is what keeps them unconfigurable.
type PaneConfig ¶
type PaneConfig struct {
Command string `json:"command,omitempty" yaml:"command,omitempty"` // Command to run (template string, empty = shell)
Dir string `json:"dir,omitempty" yaml:"dir,omitempty"` // Working directory override (template string)
Size string `json:"size,omitempty" yaml:"size,omitempty"` // Pane size passed to tmux -l (for example "30%")
Split string `json:"split,omitempty" yaml:"split,omitempty"` // Split direction: horizontal or vertical (default vertical)
}
PaneConfig defines a tmux pane to create inside a window.
type RecycleTemplateData ¶
type RecycleTemplateData struct {
DefaultBranch string // Default branch name (e.g., "main" or "master")
}
RecycleTemplateData defines available fields for recycle command templates.
type Rule ¶
type Rule struct {
// Pattern matches against remote URL (regex). Empty = matches all.
Pattern string `json:"pattern" yaml:"pattern"`
// Agent selects the agent profile used for matching repositories.
Agent string `json:"agent,omitempty" yaml:"agent,omitempty"`
// Commands to run in the session directory after clone/recycle.
Commands []string `json:"commands,omitempty" yaml:"commands,omitempty"`
// Copy are glob patterns to copy from source directory.
Copy []string `json:"copy,omitempty" yaml:"copy,omitempty"`
// MaxRecycled sets the max recycled sessions for matching repos.
// nil = inherit from previous rule or default (5), 0 = unlimited, >0 = limit
MaxRecycled *int `json:"max_recycled,omitempty" yaml:"max_recycled,omitempty"`
// Windows defines tmux windows to create when spawning a session.
// Mutually exclusive with Spawn/BatchSpawn.
Windows []WindowConfig `json:"windows,omitempty" yaml:"windows,omitempty"`
// Spawn commands to run when creating a new session (hive new).
Spawn []string `json:"spawn,omitempty" yaml:"spawn,omitempty"`
// BatchSpawn commands to run when creating a batch session (hive batch).
BatchSpawn []string `json:"batch_spawn,omitempty" yaml:"batch_spawn,omitempty"`
// Recycle commands to run when recycling a session.
Recycle []string `json:"recycle,omitempty" yaml:"recycle,omitempty"`
// CloneStrategy overrides the clone strategy for matching repos ("full" or "worktree").
CloneStrategy string `json:"clone_strategy,omitempty" yaml:"clone_strategy,omitempty"`
// BranchTemplate is a Go template for the git branch name when using the worktree
// clone strategy. Available variables: .Name, .Slug, .Owner, .Repo, .ID.
// Defaults to "hive/{{ .Slug }}-{{ .ID }}" when empty.
BranchTemplate string `json:"branch_template,omitempty" yaml:"branch_template,omitempty"`
// CloneProtocol overrides git.clone_protocol for repositories this rule matches.
CloneProtocol session.CloneProtocol `json:"clone_protocol,omitempty" yaml:"clone_protocol,omitempty"`
}
Rule defines actions to take for matching repositories.
type ServerConfig ¶ added in v0.68.0
type ServerConfig struct {
Name string `json:"name" yaml:"name"`
SSH string `json:"ssh" yaml:"ssh"`
SSHConfig string `json:"ssh_config" yaml:"ssh_config"`
Binary string `json:"binary" yaml:"binary"`
}
ServerConfig names a remote hive server whose daemon a client reaches over ssh.
func (ServerConfig) Host ¶ added in v0.68.0
func (s ServerConfig) Host() server.Host
Host is the ssh target for s.
type SpawnStrategy ¶
type SpawnStrategy struct {
Windows []WindowConfig
Commands []string
Agent string
}
SpawnStrategy holds the resolved spawn method for a session. Exactly one of Windows or Commands is populated.
func ResolveSpawn ¶
func ResolveSpawn(rules []Rule, remote string, batch bool) SpawnStrategy
ResolveSpawn determines the spawn strategy for the given remote URL. Rules are evaluated in order (last-match-wins). If the last matching rule has windows, those are used. If it has spawn/batch_spawn commands, those are used. If nothing matches, DefaultWindows() is returned.
func (SpawnStrategy) IsWindows ¶
func (s SpawnStrategy) IsWindows() bool
IsWindows returns true if the strategy uses declarative window config.
type SpawnTemplateData ¶
type SpawnTemplateData struct {
Path string // Absolute path to the session directory
Name string // Session name (directory basename)
Slug string // Session slug (URL-safe version of name)
ContextDir string // Path to context directory
Owner string // Repository owner
Repo string // Repository name
ID string // Short random ID shared with the session directory
}
SpawnTemplateData defines available fields for spawn command templates (hive new).
type TerminalConfig ¶
type TerminalConfig struct {
Status TerminalStatusConfig `json:"status" yaml:"status"`
}
TerminalConfig holds integration-agnostic terminal status settings. Transport-specific knobs (poll cadence, capture) stay under tmux:.
type TerminalConfirmConfig ¶
type TerminalConfirmConfig struct {
Idle ConfirmPolicyConfig `json:"idle" yaml:"idle"`
Missing MissingPolicyConfig `json:"missing" yaml:"missing"`
Approval ConfirmPolicyConfig `json:"approval" yaml:"approval"`
}
TerminalConfirmConfig holds one confirmation policy per status transition.
type TerminalStatusConfig ¶
type TerminalStatusConfig struct {
Confirm TerminalConfirmConfig `json:"confirm" yaml:"confirm"`
}
TerminalStatusConfig configures the Stage 2 debounce tracker (internal/domain/terminal/status.Tracker).
type TmuxConfig ¶
type TmuxConfig struct {
PollInterval time.Duration `json:"poll_interval" yaml:"poll_interval"` // status check frequency, default 1.5s
PreviewWindowMatcher []string `json:"preview_window_matcher" yaml:"preview_window_matcher"` // regex patterns for preferred window names (e.g., ["claude", "aider"])
}
TmuxConfig holds tmux integration configuration.
type TodosConfig ¶
type TodosConfig struct {
Actions map[string]string `json:"actions" yaml:"actions"` // scheme -> command template
Limiter TodosLimiterConfig `json:"limiter" yaml:"limiter"`
Notifications TodosNotifyConfig `json:"notifications" yaml:"notifications"`
}
TodosConfig holds configuration for the human todo system.
type TodosLimiterConfig ¶
type TodosLimiterConfig struct {
MaxPending int `json:"max_pending" yaml:"max_pending"`
RateLimitPerSession time.Duration `json:"rate_limit_per_session" yaml:"rate_limit_per_session"`
}
TodosLimiterConfig holds rate limiting settings for todo creation.
type TodosNotifyConfig ¶
type TodosNotifyConfig struct {
Toast bool `json:"toast" yaml:"toast"`
}
TodosNotifyConfig holds notification settings for the todo system.
type ValidationWarning ¶
type ValidationWarning struct {
Category string `json:"category"`
Item string `json:"item,omitempty"`
Message string `json:"message"`
}
ValidationWarning represents a non-fatal configuration issue.
type WindowConfig ¶
type WindowConfig struct {
Name string `json:"name" yaml:"name"` // Window name (template string, required)
Command string `json:"command,omitempty" yaml:"command,omitempty"` // Command to run (template string, empty = shell); mutually exclusive with Panes
Dir string `json:"dir,omitempty" yaml:"dir,omitempty"` // Working directory override (template string)
Focus bool `json:"focus,omitempty" yaml:"focus,omitempty"` // Select this window after creation
Panes []PaneConfig `json:"panes,omitempty" yaml:"panes,omitempty"` // Panes to create in this window; mutually exclusive with Command
}
WindowConfig defines a tmux window to create when spawning a session.
func DefaultWindows ¶
func DefaultWindows() []WindowConfig
DefaultWindows returns the default window layout for new sessions. Uses template strings rendered at spawn time from the active agent profile.