Help us shape the future of Go! Take the 2026 Go Developer Survey

config

package
v0.65.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 14 Imported by: 0

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

View Source
const (
	CloneStrategyFull     = "full"
	CloneStrategyWorktree = "worktree"
)

Clone strategy constants.

View Source
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"
)
View Source
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"
)
View Source
const DefaultMaxRecycled = 5

DefaultMaxRecycled is the default limit for recycled sessions per repository.

Variables

View Source
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.

View Source
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

func ApplyEdit(path string, edit Edit, check Check) error

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

func CheckWorkspace(path string) error

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

func ConfigPathIn(dir string) string

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

func CreateFile(path string) error

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

func IsReservedAgentKey(key string) bool

IsReservedAgentKey reports whether key inside `agents:` is a setting rather than a profile name.

func LogFilePath added in v0.62.0

func LogFilePath(dataDir string) string

LogFilePath returns the shared CLI and Desktop log path in dataDir.

func ReadFile

func ReadFile(configPath string) ([]byte, error)

ReadFile returns the config file's contents, or nil when configPath is empty or names no file.

func ResolveDataDir

func ResolveDataDir(getenv func(string) string, fallback string) string

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

func ValidateCloneStrategy(s string) error

ValidateCloneStrategy returns an error if s is not a valid clone strategy value.

func YAMLFlowSequence

func YAMLFlowSequence(ss []string) string

YAMLFlowSequence renders ss as an inline YAML sequence, `[]` when empty.

func YAMLScalar

func YAMLScalar(s string) string

YAMLScalar renders s as a YAML scalar for hand-written template output, quoting it when its YAML meaning would otherwise change.

Types

type ActionTemplateData

type ActionTemplateData struct {
	Scheme string
	Value  string
	URI    string
}

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

type Check func(path string) error

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"`
	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

func Load(configPath, dataDir string) (*Config, error)

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) BinDir

func (c *Config) BinDir() string

BinDir returns the path to the extracted bundled scripts directory.

func (*Config) Complete

func (c *Config) Complete(dataDir string)

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

func (c *Config) ContextDir() string

ContextDir returns the base context directory path.

func (*Config) DatabaseFile

func (c *Config) DatabaseFile() string

DatabaseFile returns the path to the SQLite database file.

func (*Config) GetBranchTemplate

func (c *Config) GetBranchTemplate(remote string) string

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) GetCloneStrategy

func (c *Config) GetCloneStrategy(remote string) string

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

func (c *Config) GetMaxRecycled(remote string) int

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

func (c *Config) GetRecycleCommands(remote string) []string

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

func (c *Config) RepoContextDir(owner, repo string) string

RepoContextDir returns the context directory for a specific owner/repo.

func (*Config) ReposDir

func (c *Config) ReposDir() string

ReposDir returns the path where cloned repositories are stored.

func (*Config) SharedContextDir

func (c *Config) SharedContextDir() string

SharedContextDir returns the shared context directory.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that the configuration is valid.

func (*Config) ValidateDeep

func (c *Config) ValidateDeep(configPath string) error

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; blank lines and indentation are 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).

func (Edit) Validate

func (e Edit) Validate() error

Validate rejects edits that would make Hive reject the whole config. It runs before any file is touched.

type EditProfile

type EditProfile struct {
	Name    string
	Command string
	Flags   []string
}

EditProfile is one agent profile in an Edit. An empty Command writes the profile name as the command.

type GitConfig

type GitConfig struct {
	StatusWorkers int `json:"status_workers" yaml:"status_workers"`
}

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"`
}

Rule defines actions to take for matching repositories.

func (Rule) Matches

func (r Rule) Matches(remote string) bool

Matches reports whether this rule matches the given remote URL. An empty pattern matches everything.

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.

Jump to

Keyboard shortcuts

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