src — config

Module: src-config Cohesion: 0.80 Members: 0

src — config

The src/config module is the central nervous system for managing all configuration within Code Buddy. It provides a robust, layered, and extensible system for defining, loading, resolving, and dynamically updating application settings from various sources. This includes user preferences, project-specific rules, enterprise policies, environment variables, and CLI arguments.

The module is designed to ensure:

Module Structure

The src/config module is composed of several specialized files, each addressing a specific aspect of configuration:

Configuration Resolution & Precedence

Code Buddy employs a layered approach to configuration, where settings from different sources are applied in a specific order of precedence. The ConfigResolver and AdminConfig are key to this process.

config-resolver.ts - Connection Profile Resolution

The ConfigResolver class is responsible for determining the active LLM connection configuration (e.g., baseURL, apiKey, model, provider). It prioritizes settings from the following sources, from highest to lowest:

  1. CLI Overrides: Explicit --profile, --baseURL, --apiKey, or --model flags provided at runtime.
  2. Active Profile: The currently selected connection profile (e.g., grok, openai, lmstudio).
  3. Environment Variables: If envVarsFallback is enabled, environment variables like GROK_API_KEY, OPENAI_API_KEY, etc., are used as a fallback.
  4. Default Profile: A designated default profile if no active profile is set or enabled.
  5. Built-in Defaults: Hardcoded fallback values if no other configuration is found.

The ConfigResolver also manages a collection of ConnectionProfile objects, allowing users to define and switch between different API endpoints and credentials. It includes functionality for auto-detecting local LLM servers (like LM Studio or Ollama) and testing connections.

graph TD
    subgraph "Config Resolution Precedence (ConfigResolver.resolve)"
        CLI_PROFILE[1. CLI Profile (--profile)] --> A{Profile Exists?}
        A -- Yes --> PROFILE_CFG(Profile Config)
        A -- No --> CLI_DIRECT[2. CLI Direct (--baseURL, --apiKey)]
        CLI_DIRECT --> B{CLI Direct Set?}
        B -- Yes --> CLI_CFG(CLI Direct Config)
        B -- No --> ACTIVE_PROFILE[3. Active Profile]
        ACTIVE_PROFILE --> C{Profile Enabled?}
        C -- Yes --> ACTIVE_CFG(Active Profile Config)
        C -- No --> ENV_VARS[4. Environment Variables]
        ENV_VARS --> D{Env Vars Set?}
        D -- Yes --> ENV_CFG(Env Config)
        D -- No --> DEFAULT_PROFILE[5. Default Profile]
        DEFAULT_PROFILE --> E{Default Profile Exists?}
        E -- Yes --> DEFAULT_CFG(Default Profile Config)
        E -- No --> BUILTIN_FALLBACK[6. Built-in Fallback]

        PROFILE_CFG --> RESOLVED(ResolvedConfig)
        CLI_CFG --> RESOLVED
        ACTIVE_CFG --> RESOLVED
        ENV_CFG --> RESOLVED
        DEFAULT_CFG --> RESOLVED
        BUILTIN_FALLBACK --> RESOLVED
    end

Key Functions/Classes:

admin-config.ts - Enterprise Admin Configuration

This module handles configuration enforced by system administrators, typically in enterprise deployments. It loads settings from /etc/codebuddy/requirements.toml and /etc/codebuddy/managed_config.toml.

The applyAdminRequirements function is crucial here, as it merges these admin policies with a user's configuration, ensuring that enforced requirements always take precedence.

Key Functions/Classes:

Configuration Sources & Management

toml-config.ts - TOML Configuration Manager

This module provides a singleton TomlConfigManager for loading and saving configuration from TOML files. It supports a hierarchy of configuration:

It merges these files, with project-level settings overriding user-level settings. This manager is the primary source for many application-wide settings that are not connection-related.

Key Functions/Classes:

user-settings.ts - User Settings Manager

Similar to toml-config.ts, but specifically for JSON-based user settings, typically stored in ~/.codebuddy/user-settings.json. It provides a simple key-value store for user preferences.

Key Functions/Classes:

codebuddyrules.ts - Project-Specific Rules (.codebuddyrules)

This module introduces project-specific AI behavior configuration via .codebuddyrules files (YAML, JSON, or Markdown). These files can define custom instructions, code style preferences, ignore patterns, security policies, and more.

The CodeBuddyRulesManager supports:

Key Functions/Classes:

env-schema.ts - Environment Variable Schema

This module defines a comprehensive schema (ENV_SCHEMA) for all environment variables used by Code Buddy. It includes metadata like type, default value, description, and sensitivity.

Key Functions/Classes:

Advanced Configuration Features

advanced-config.ts - Advanced Configuration Classes

This file groups several advanced configuration features, each encapsulated in its own class:

Key Functions/Classes:

feature-flags.ts - Feature Flags System

A centralized system for enabling or disabling features at runtime. Feature flags can be overridden by environment variables and persisted in user-level or project-level JSON files (.codebuddy/feature-flags.json).

Key Functions/Classes:

secret-ref.ts - Secret Reference Resolution

This module provides utilities for resolving secret references embedded in configuration values. It supports two patterns:

This allows sensitive information (like API keys) to be stored securely outside of configuration files.

Key Functions/Classes:

Model & Agent Configuration

model-registry.ts - LLM Model Registry

A central registry for all supported LLM models, their providers, and their token limits. This is critical for consistent model handling across the application.

Key Functions/Classes:

model-defaults.ts - Model Defaults

Provides default model identifiers for different LLM providers. This ensures that if a specific model isn't configured, a sensible default is used.

Key Functions/Classes:

model-pricing.ts - Model Pricing

Contains pricing information for various LLM models, used by the cost tracker and analytics modules.

Key Functions/Classes:

model-tools.ts - Model Tooling Utilities

Provides utilities related to model capabilities and tool usage, such as checking if a model supports specific tools or function calling.

Key Functions/Classes:

agent-defaults.ts - Agent Defaults

Provides access to agent-specific default settings, such as the image generation model or per-agent parameter overrides. These are typically loaded from the toml-config.ts manager.

Key Functions/Classes:

Dynamic Configuration & Hot Reload

The src/config/hot-reload sub-module provides a sophisticated system for detecting configuration file changes and dynamically reloading affected parts of the application without a full restart.

hot-reload/index.ts - Hot Reload Manager

The HotReloadManager orchestrates the entire hot-reload process. It uses a ConfigWatcher to monitor files, diff.ts to identify changes, and reloader.ts to apply those changes to specific subsystems.

graph TD
    subgraph "Config Hot-Reload Flow"
        A[ConfigWatcher] -- File Change Detected --> B{New Config Snapshot}
        B -- Compare with Old --> C[diffConfigs]
        C -- Changes Found --> D[HotReloadManager.applyChanges]
        D -- Group by Subsystem --> E[reloadSubsystems]
        E -- For each Subsystem --> F[SubsystemReloader.reload]
        F -- Success --> G[Update Config]
        F -- Failure --> H[SubsystemReloader.rollback]
        H --> I[Revert Config]
    end

Key Functions/Classes:

hot-reload/watcher.ts - Config File Watcher

The ConfigWatcher monitors specified configuration files and directories for changes. It debounces events to prevent excessive reloads and notifies the HotReloadManager when a stable change is detected.

Key Functions/Classes:

hot-reload/diff.ts - Config Diffing

This module provides utilities for comparing configuration snapshots. It generates a list of ConfigChange objects, indicating what values have been added, removed, or modified. It also maps changes to affected SubsystemIds.

Key Functions/Classes:

hot-reload/reloader.ts - Subsystem Reloaders

This module manages SubsystemReloader functions, which are responsible for applying configuration changes to specific parts of the application. It handles the order of reloads based on dependencies and provides rollback mechanisms in case of failure.

Key Functions/Classes:

config-mutator.ts - Config Mutator

The ConfigMutator provides a programmatic way to set configuration values using dot-notation key paths (e.g., middleware.max_turns). It handles type validation, value coercion, and SecretRef resolution. It also supports dry-run mode and batch updates.

Key Functions/Classes:

Constants & Utilities

constants.ts - Centralized Constants

This file consolidates various application-wide constants, grouped by domain (e.g., AGENT_CONFIG, SEARCH_CONFIG, API_CONFIG, PATHS). This provides a single source of truth for common values and avoids magic numbers/strings throughout the codebase.

Key Constants:

settings-hierarchy.ts - Settings Hierarchy

Defines the search order and locations for various configuration files, ensuring that Code Buddy can locate settings in common user and project directories.

Key Functions/Classes:

migration.ts - Configuration Migration

Contains logic for migrating older configuration formats or settings to newer versions, ensuring backward compatibility.

Key Functions/Classes:

types.ts - Shared Types

This file defines common TypeScript interfaces and types used across the configuration module and other parts of the application, ensuring type safety and consistency.

Key Types:

How to Contribute or Extend

  1. Ensure its configuration is part of a watched file (e.g., config.toml).
  2. Define a SubsystemId in src/config/hot-reload/types.ts.
  3. Implement a SubsystemReloader function that takes a patch (the changed config values) and applies them.
  4. Register this reloader using registerReloader(subsystemId, yourReloaderFunction).
  5. If there are dependencies between subsystems, update SUBSYSTEM_DEPENDENCIES in types.ts.