config

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrValidation = errors.New("config validation")

ErrValidation is returned when config validation fails.

Functions

func LoadDotEnv

func LoadDotEnv()

func LoadProjectContext

func LoadProjectContext(workDir string) (content string, path string)

LoadProjectContext reads the first available project context file from workDir. It checks AGENTS.md, .m31a/agents.md, and MEMORY.md in priority order. Returns the file content and the path it was loaded from. Returns empty string and empty path if no context file is found.

func LocalConfigPath

func LocalConfigPath() (string, error)

LocalConfigPath returns the path where a new project-level m31a.toml should be created (cwd/m31a.toml).

func RenderInstructions added in v1.3.0

func RenderInstructions(files []InstructionFile) string

RenderInstructions concatenates discovered instruction files into a single string suitable for injection into the system prompt.

func WatchConfig

func WatchConfig(ctx context.Context, path string, ch chan<- ConfigReloadMsg)

WatchConfig watches the config file for changes using fsnotify and sends ConfigReloadMsg to the provided channel when a change is detected. Falls back to polling with ConfigWatchInterval if fsnotify is unavailable. Runs until ctx is cancelled.

Types

type AgentsConfig

type AgentsConfig struct {
	Default    string `toml:"default"`
	Initialize string `toml:"initialize"`
	Research   string `toml:"research"`
	Plan       string `toml:"plan"`
	Execute    string `toml:"execute"`
	Verify     string `toml:"verify"`
	Ship       string `toml:"ship"`
	Discuss    string `toml:"discuss"`

	// Profiles holds user-configurable overrides for subagent profiles.
	// Keys are profile names (e.g., "explore", "general", "security").
	// Built-in profiles can be overridden; new profiles can be added.
	Profiles map[string]SubagentProfileConfig `toml:"profiles,omitempty"`
}

type CompactionConfig added in v1.3.0

type CompactionConfig struct {
	Auto       bool `toml:"auto"`
	Buffer     int  `toml:"buffer"`
	KeepTokens int  `toml:"keep_tokens"`

	// Proactive compaction settings (Wave 2B)
	Proactive          bool `toml:"proactive"`            // trigger compaction before phase transitions
	ToolCallsThreshold int  `toml:"tool_calls_threshold"` // check compaction every N tool calls during Execute
	PhaseTransitionPct int  `toml:"phase_transition_pct"` // trigger compaction at this % before phase transition
}

CompactionConfig holds automatic session compaction settings.

type Config

type Config struct {
	Provider     ProviderConfig     `toml:"provider"`
	Model        ModelConfig        `toml:"model"`
	UI           UIConfig           `toml:"ui"`
	Permissions  PermissionsConfig  `toml:"permissions"`
	Features     FeaturesConfig     `toml:"features"`
	Ledger       LedgerConfig       `toml:"ledger"`
	Tools        ToolsConfig        `toml:"tools"`
	Agents       AgentsConfig       `toml:"agents"`
	Git          GitConfig          `toml:"git"`
	Verify       VerifyConfig       `toml:"verify"`
	Compaction   CompactionConfig   `toml:"compaction"`
	Instructions InstructionsConfig `toml:"instructions"`
	Skills       SkillsConfig       `toml:"skills"`
}

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sane defaults. Missing config file causes Load to return DefaultConfig without error.

func Load

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

Load reads a TOML config file from the given path, applies multi-layer merging (global TOML → env vars → project m31a.toml), validation, and variable substitution, then returns the resulting Config.

Config loading order (later overrides earlier):

  1. DefaultConfig() — zero-valued defaults
  2. Global TOML (~/.m31a/config.toml via path arg)
  3. Environment variable overrides (M31A_*)
  4. Project-level m31a.toml (walked up from cwd, max 3 levels)
  5. Variable substitution — ${VAR} → env value
  6. Validation — type/range checks on known fields

Missing global config file is not an error — first-run flow handles creation.

func (*Config) ResolveAPIKeys

func (c *Config) ResolveAPIKeys(kc keychain.Keychain) error

ResolveAPIKeys resolves API keys for OpenRouter and Zen using the priority order: environment variable → OS keychain → config file field.

Resolution per provider:

  1. Check M31A_OPENROUTER_API_KEY / M31A_ZEN_API_KEY env var
  2. If not set, try keychain.Get("openrouter") / keychain.Get("zen")
  3. If keychain returns ErrKeyNotFound or ErrKeychainUnavailable, fall back to c.Provider.OpenRouter.APIKey / c.Provider.Zen.APIKey

Never returns an error for missing keys — keys may be left empty for first-run or settings screen to handle.

func (*Config) Save

func (c *Config) Save(path string) error

Save writes the config to a TOML file atomically (temp file + rename). If M31A_CONFIG env var is set, it is used as the path instead. API keys are never persisted to the config file — they must be set via environment variables or the OS keychain.

func (*Config) SaveProject

func (c *Config) SaveProject(path string) error

SaveProject writes the config to a project-level m31a.toml in the working directory. API keys are always cleared from project config for security — they belong in the global config or keychain.

func (*Config) SaveWithKeychain

func (c *Config) SaveWithKeychain(path string, kc keychain.Keychain) error

SaveWithKeychain writes the config to a TOML file atomically. If a keychain is provided and available, API keys are saved to the keychain and cleared from the config file. If the keychain is unavailable or nil, API keys are persisted to the config file as a fallback (with a warning).

type ConfigReloadMsg

type ConfigReloadMsg struct {
	Config *Config
	Error  error
}

ConfigReloadMsg is emitted when the config file changes on disk.

type FeaturesConfig

type FeaturesConfig struct {
	AutoBackup      bool `toml:"auto_backup"`
	ResumeOnStartup bool `toml:"resume_on_startup"`
	// WorkflowMode controls phase-skipping behaviour:
	//   "auto"   — classify and adapt automatically (default)
	//   "full"   — always run all 6 phases
	//   "fast"   — skip Plan phase (Discuss→Execute)
	//   "direct" — skip Discuss, Plan, Verify (only Initialize→Execute→Ship)
	// Empty string means auto.
	WorkflowMode string `toml:"workflow_mode"`
	// Model cache TTL in minutes. Default 5.
	ModelCacheTTLMinutes int `toml:"model_cache_ttl_minutes"`
	// Stale cache TTL in hours. Default 24.
	ModelCacheStaleHours int `toml:"model_cache_stale_hours"`
	// Health check latency thresholds in milliseconds.
	HealthCheckLiveMs int `toml:"healthcheck_live_ms"`
	HealthCheckSlowMs int `toml:"healthcheck_slow_ms"`
	// Session ID length in hex chars. Default 8.
	SessionIDLength int `toml:"session_id_length"`
	// Max recent models to remember. Default 10.
	MaxRecentModels int `toml:"max_recent_models"`
	// Session retention in days. Default 30.
	SessionRetentionDays int `toml:"session_retention_days"`
	// Health check timeout in seconds. Default 10.
	HealthCheckTimeoutSecs int `toml:"health_check_timeout_secs"`
	// Rate limit backoff in seconds. Default 120.
	RateLimitBackoffSecs int `toml:"rate_limit_backoff_secs"`
	// Optional per-session budget limit in USD. 0 means no limit.
	// When set, workflow phases check cumulative cost before proceeding.
	BudgetLimitUSD float64 `toml:"budget_limit_usd"`

	// Metrics collection (observability pipeline). Enabled by default.
	// When true, the session records tool execution, LLM token usage,
	// and workflow phase metrics to METRICS.json in the session directory.
	MetricsEnabled bool `toml:"metrics_enabled"`

	// Plan enhancements (GSD-inspired sub-steps within the Plan phase)
	PlanResearch       bool `toml:"plan_research"`        // Pre-plan research step
	PlanCheck          bool `toml:"plan_check"`           // Plan quality checker + revision loop
	PlanCheckMaxIter   int  `toml:"plan_check_max_iter"`  // Max revision iterations (default 3)
	PlanSecurityGate   bool `toml:"plan_security_gate"`   // Security heuristic gate
	PlanCoverageGate   bool `toml:"plan_coverage_gate"`   // Requirements coverage gate
	PlanGapAnalysis    bool `toml:"plan_gap_analysis"`    // Post-plan gap analysis
	PlanChunked        bool `toml:"plan_chunked"`         // Chunked plan generation
	PlanChunkThreshold int  `toml:"plan_chunk_threshold"` // Tasks threshold for auto-chunking (default 10)

	// Discuss phase enhancements
	DiscussQualityCheck bool `toml:"discuss_quality_check"` // Question quality checker
	DiscussCompleteness bool `toml:"discuss_completeness"`  // Answer completeness check
	DiscussFollowUps    bool `toml:"discuss_follow_ups"`    // Follow-up question generation

	// Execute phase enhancements
	ExecutePreflight   bool `toml:"execute_preflight"`    // Pre-execution validation
	ExecuteQualityGate bool `toml:"execute_quality_gate"` // Per-task acceptance criteria checks
	ExecuteLoopDetect  bool `toml:"execute_loop_detect"`  // Tool call loop detection

	// Verify + Ship phase enhancements
	VerifyReport   bool `toml:"verify_report"`   // Generate verification report
	VerifySecurity bool `toml:"verify_security"` // Security file scanning
	ShipPreflight  bool `toml:"ship_preflight"`  // Pre-ship checklist
	ShipChangelog  bool `toml:"ship_changelog"`  // Changelog generation

	// Initialize phase enhancements
	InitDeepAnalysis bool `toml:"init_deep_analysis"` // Deep project analysis
	InitPreflight    bool `toml:"init_preflight"`     // Environment pre-flight checks

	// Intent classification (LLM-based prompt routing)
	IntentClassification bool `toml:"intent_classification"` // Pre-classify REPL input for routing
}

type GitConfig

type GitConfig struct {
	CommitPrefix string `toml:"commit_prefix"`
	FixPrefix    string `toml:"fix_prefix"`
	ShipPrefix   string `toml:"ship_prefix"`
	UserName     string `toml:"user_name"`
	UserEmail    string `toml:"user_email"`
}

GitConfig holds configurable git commit message prefixes and user identity.

func DefaultGitConfig

func DefaultGitConfig() GitConfig

DefaultGitConfig returns the default git configuration.

type InstructionFile added in v1.3.0

type InstructionFile struct {
	Path    string
	Content string
}

InstructionFile represents a discovered AGENTS.md file.

func DiscoverInstructions added in v1.3.0

func DiscoverInstructions(projectRoot, workDir string) []InstructionFile

DiscoverInstructions walks from workDir up to projectRoot collecting AGENTS.md files. Also checks the global config directory (~/.m31a/AGENTS.md). Returns files ordered from outermost (project root) to innermost (workDir).

type InstructionsConfig added in v1.3.0

type InstructionsConfig struct {
	Enabled        bool `toml:"enabled"`
	DisableProject bool `toml:"disable_project"`
}

InstructionsConfig controls AGENTS.md file discovery for project-aware context.

type LedgerConfig

type LedgerConfig struct {
	Enabled    bool `toml:"enabled"`
	MaxEntries int  `toml:"max_entries"`
}

type ModelConfig

type ModelConfig struct {
	Default                 string  `toml:"default"`
	ContextWarningThreshold float64 `toml:"context_warning_threshold"`
	ShowThinkingByDefault   bool    `toml:"show_thinking_by_default"`
	AutoCollapseTools       bool    `toml:"auto_collapse_tools"`
	AutoArbitrage           bool    `toml:"auto_arbitrage"`
	ArbitrageThreshold      float64 `toml:"arbitrage_threshold"`
	// Default context length used when provider doesn't return one.
	DefaultContextLength int `toml:"default_context_length"`
	// Token estimator EMA calibration rate (0.0–1.0). Lower = slower calibration.
	TokenEMAAlpha float64 `toml:"token_ema_alpha"`
}

type PermissionRule

type PermissionRule struct {
	Tool      string          `toml:"tool"`
	Resource  string          `toml:"resource"`
	Pattern   string          `toml:"pattern"`
	RiskLevel types.RiskLevel `toml:"risk_level"`
	Action    string          `toml:"action"`
}

type PermissionsAgentConfig

type PermissionsAgentConfig struct {
	DefaultAction string           `toml:"default_action"`
	Rules         []PermissionRule `toml:"rules"`
}

PermissionsAgentConfig defines per-agent permission profiles. Each agent (e.g., "build", "plan", "default") can have its own default action and ruleset.

type PermissionsConfig

type PermissionsConfig struct {
	DefaultMode    string                            `toml:"default_mode"`
	TimeoutSeconds int                               `toml:"timeout_seconds"`
	Rules          []PermissionRule                  `toml:"rules"`
	Agents         map[string]PermissionsAgentConfig `toml:"agents,omitempty"`
}

type ProviderConfig

type ProviderConfig struct {
	Default      string                   `toml:"default"`
	AutoFallback bool                     `toml:"auto_fallback"`
	OpenRouter   ProviderCredentialConfig `toml:"openrouter"`
	Zen          ProviderCredentialConfig `toml:"zen"`
	Nvidia       ProviderCredentialConfig `toml:"nvidia"`
	// Custom base URLs for self-hosted or proxied gateways.
	// Empty means use the default provider URLs.
	OpenRouterBaseURL string `toml:"openrouter_base_url"`
	ZenBaseURL        string `toml:"zen_base_url"`
	NvidiaBaseURL     string `toml:"nvidia_base_url"`
	// HTTP-Referer and X-Title headers sent to OpenRouter.
	// Empty means use defaults ("https://github.com/eshanized/M31A", "M31A").
	OpenRouterReferer string `toml:"openrouter_referer"`
	OpenRouterTitle   string `toml:"openrouter_title"`
}

type ProviderCredentialConfig

type ProviderCredentialConfig struct {
	APIKey string `toml:"api_key"`
}

type SkillsConfig added in v1.3.0

type SkillsConfig struct {
	Sources []string `toml:"sources"`
}

SkillsConfig controls skill discovery directories for composable slash commands.

type SubagentProfileConfig added in v1.3.0

type SubagentProfileConfig struct {
	Description  string   `toml:"description,omitempty"`
	Mode         string   `toml:"mode,omitempty"`
	SystemPrompt string   `toml:"system_prompt,omitempty"`
	Model        string   `toml:"model,omitempty"`
	Hidden       *bool    `toml:"hidden,omitempty"`
	AllowedTools []string `toml:"allowed_tools,omitempty"`
	DeniedTools  []string `toml:"denied_tools,omitempty"`
	MaxTools     int      `toml:"max_tools,omitempty"`
	MaxTokens    int      `toml:"max_tokens,omitempty"`
	MaxTurns     int      `toml:"max_turns,omitempty"`
	Disabled     bool     `toml:"disabled,omitempty"`
}

SubagentProfileConfig defines user-configurable overrides for a subagent profile. Zero-value fields inherit from the built-in default.

type ToolsConfig

type ToolsConfig struct {
	MaxGlobResults       int      `toml:"max_glob_results"`
	MaxGrepResults       int      `toml:"max_grep_results"`
	BashKillGraceSecs    int      `toml:"bash_kill_grace_secs"`
	MaxBackupsPerFile    int      `toml:"max_backups_per_file"`
	WebfetchMaxRedirects int      `toml:"webfetch_max_redirects"`
	WebfetchUserAgent    string   `toml:"webfetch_user_agent"`
	SkipDirs             []string `toml:"skip_dirs"`
	WebSearchBaseURL     string   `toml:"websearch_base_url"`
	WebSearchEnabled     bool     `toml:"websearch_enabled"`
	OutputMaxLines       int      `toml:"output_max_lines"`
	OutputMaxBytes       int      `toml:"output_max_bytes"`
}

AgentsConfig defines per-workflow-phase model assignments. Each field names a workflow phase and holds a model ID string. Allows users to assign different models to different workflow phases (e.g., cheap model for Plan, powerful model for Execute). ToolsConfig defines configurable limits for tool execution.

type UIConfig

type UIConfig struct {
	Theme            string `toml:"theme"`
	CompactMode      bool   `toml:"compact_mode"`
	ShowTokenUsage   bool   `toml:"show_token_usage"`
	ShowCostEstimate bool   `toml:"show_cost_estimate"`
	MaxIterations    int    `toml:"max_iterations"`
	// Leader key for chord shortcuts. Default "ctrl+x".
	LeaderKey string `toml:"leader_key"`
	// Leader key timeout duration in milliseconds. Default 1000.
	LeaderTimeoutMs int `toml:"leader_timeout_ms"`
	// Minimum terminal width before sidebar auto-shows. Default 120.
	SidebarWidthThreshold int `toml:"sidebar_width_threshold"`
	// Discuss Q&A timeout in seconds. Default 300 (5 minutes).
	DiscussTimeout int `toml:"discuss_timeout"`
	// Max lines for thinking block content. Default 20.
	ThinkingMaxLines int `toml:"thinking_max_lines"`
	// Permission modal width in columns. Default 60.
	PermissionModalWidth int `toml:"permission_modal_width"`
	// Sidebar width in columns. Default 42.
	SidebarWidth int `toml:"sidebar_width"`
	// Max message history entries. Default 1000.
	MaxMessageHistory int `toml:"max_message_history"`
	// Fallback banner display duration in seconds. Default 15.
	FallbackBannerSecs int `toml:"fallback_banner_timeout_secs"`
	// Default number of log lines to show. Default 20.
	DefaultLogLines int `toml:"default_log_lines"`
	// Max sessions to list in resume screen. Default 10.
	SessionListLimit int `toml:"session_list_limit"`
	// Thinking block opacity. Default 0.6.
	ThinkingOpacity float64 `toml:"thinking_opacity"`
	// Frecent history max entries. Default 100.
	FrecentHistorySize int `toml:"frecent_history_size"`

	// New - Theme & Colors
	AccentColor      string `toml:"accent_color"`
	CustomBackground string `toml:"custom_background"`
	BorderStyle      string `toml:"border_style"`

	// New - Typography
	BoldHeaders    bool `toml:"bold_headers"`
	ItalicThinking bool `toml:"italic_thinking"`
	TabWidth       int  `toml:"tab_width"`

	// Accessibility
	ReducedMotion bool `toml:"reduced_motion"`

	// New - Layout
	SidebarPosition string `toml:"sidebar_position"`
	SidebarAutoShow bool   `toml:"sidebar_auto_show"`
	CardPadding     int    `toml:"card_padding"`
	WelcomeScreen   bool   `toml:"welcome_screen"`
	ZenModeKey      string `toml:"zen_mode_key"`

	// New - Animation
	AnimationSpeed   string `toml:"animation_speed"`
	SpinnerStyle     string `toml:"spinner_style"`
	TransitionStyle  string `toml:"transition_style"`
	BreathingEffects bool   `toml:"breathing_effects"`
	LogoAnimation    bool   `toml:"logo_animation"`

	// New - Status Bar
	StatusBarStyle      string `toml:"status_bar_style"`
	StatusBarPosition   string `toml:"status_bar_position"`
	ShowSpinnerInStatus bool   `toml:"show_spinner_in_status"`

	// New - Tool Cards
	ToolCardStyle      string `toml:"tool_card_style"`
	ToolOutputMaxLines int    `toml:"tool_output_max_lines"`
	SyntaxHighlight    bool   `toml:"syntax_highlight"`

	// New - Toasts
	ToastPosition     string `toml:"toast_position"`
	ToastDurationSecs int    `toml:"toast_duration_secs"`
	ToastMaxVisible   int    `toml:"toast_max_visible"`
}

type ValidationError

type ValidationError struct {
	Field        string
	ExpectedType string
	ActualValue  string
}

ValidationError describes a single field-level config validation failure.

func (ValidationError) Error

func (e ValidationError) Error() string

type VerifyConfig

type VerifyConfig struct {
	BuildCommand string `toml:"build_command"`
	TestCommand  string `toml:"test_command"`
}

VerifyConfig holds configurable verification commands. Empty values trigger auto-detection (existing behavior).

Jump to

Keyboard shortcuts

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