config

package
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: GPL-3.0 Imports: 14 Imported by: 0

README

Config Package

Configuration loading for contextd-v2 using Koanf library.

Features

  • Environment-based: Load from environment variables
  • File-based: Load from YAML config files with path validation
  • Hierarchical: Environment variables override YAML
  • Secure: File permission checks, path traversal prevention
  • Validated: Configuration validation with clear error messages

Usage

Simple Environment-based Loading
cfg := config.Load()
fmt.Println("Port:", cfg.Server.Port)
File-based Loading with YAML
cfg, err := config.LoadWithFile("~/.config/contextd/config.yaml")
if err != nil {
    log.Fatal(err)
}

Configuration Structure

type Config struct {
    Server        ServerConfig
    Observability ObservabilityConfig
    PreFetch      PreFetchConfig
    Checkpoint    CheckpointConfig
}

Environment Variables

Variable Default Description
SERVER_PORT 9090 HTTP server port
SERVER_SHUTDOWN_TIMEOUT 10s Graceful shutdown timeout
OTEL_ENABLE true Enable OpenTelemetry
OTEL_SERVICE_NAME contextd Service name for traces
PREFETCH_ENABLED true Enable pre-fetch engine
CHECKPOINT_MAX_CONTENT_SIZE_KB 1024 Max checkpoint size (KB)

Security

File Permissions

Config files MUST have secure permissions:

  • 0600 (owner read/write only) - recommended
  • 0400 (owner read only) - also accepted
Path Validation

Only config files in allowed directories:

  • ~/.config/contextd/ (user config)
  • /etc/contextd/ (system-wide)
File Size Limit

Config files larger than 1MB are rejected.

Testing

Run tests with:

go test ./internal/config -v

Migration Notes

Ported from contextd/pkg/config to contextd-v2/internal/config:

  • Updated import paths
  • Removed dependencies on unused packages
  • Kept Koanf-based approach
  • All tests passing

Documentation

Overview

Package config provides configuration loading for contextd v2.

Configuration is loaded from environment variables with sensible defaults. This package supports server, observability, and application-specific settings.

Package config provides configuration loading for contextd.

internal/config/types.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnsureConfigDir added in v0.3.0

func EnsureConfigDir() error

EnsureConfigDir creates the contextd config directory if it doesn't exist. This is called during startup to ensure new users have the config directory ready. The directory is created with 0700 permissions (owner read/write/execute only).

Types

type CheckpointConfig

type CheckpointConfig struct {
	MaxContentSizeKB int `koanf:"max_content_size_kb"` // Maximum content size in KB (default: 1024 = 1MB)
}

CheckpointConfig holds checkpoint service configuration.

type ChromemConfig added in v0.3.0

type ChromemConfig struct {
	// Path is the directory for persistent storage.
	// Default: "~/.config/contextd/vectorstore"
	Path string `koanf:"path"`

	// Compress enables gzip compression for stored data.
	// Default: true
	Compress bool `koanf:"compress"`

	// DefaultCollection is the default collection name.
	// Default: "contextd_default"
	DefaultCollection string `koanf:"default_collection"`

	// VectorSize is the expected embedding dimension.
	// Must match the embedder's output dimension.
	// Default: 384 (for FastEmbed bge-small-en-v1.5)
	VectorSize int `koanf:"vector_size"`
}

ChromemConfig holds chromem-go embedded vector database configuration. chromem-go is a pure Go, embedded vector database with zero third-party dependencies.

func (*ChromemConfig) Validate added in v0.3.0

func (c *ChromemConfig) Validate() error

Validate validates ChromemConfig.

type Config

type Config struct {
	Production             ProductionConfig
	Server                 ServerConfig
	Observability          ObservabilityConfig
	PreFetch               PreFetchConfig
	Checkpoint             CheckpointConfig
	VectorStore            VectorStoreConfig
	Qdrant                 QdrantConfig
	Embeddings             EmbeddingsConfig
	Repository             RepositoryConfig
	Statusline             StatuslineConfig
	ConsolidationScheduler ConsolidationSchedulerConfig
}

Config holds the complete contextd v2 configuration.

func Load

func Load() *Config

Load loads configuration from environment variables with defaults.

Environment variables:

Server:

  • SERVER_PORT: HTTP server port (default: 9090)
  • SERVER_SHUTDOWN_TIMEOUT: Graceful shutdown timeout (default: 10s)

Qdrant:

  • QDRANT_HOST: Qdrant host (default: localhost)
  • QDRANT_PORT: Qdrant gRPC port (default: 6334)
  • QDRANT_HTTP_PORT: Qdrant HTTP port (default: 6333)
  • QDRANT_COLLECTION: Default collection name (default: contextd_default)
  • QDRANT_VECTOR_SIZE: Vector dimensions (default: 384 for FastEmbed)
  • CONTEXTD_DATA_PATH: Base data path (default: /data)

Embeddings:

  • EMBEDDINGS_PROVIDER: Provider type: fastembed or tei (default: fastembed)
  • EMBEDDINGS_MODEL: Embedding model (default: BAAI/bge-small-en-v1.5)
  • EMBEDDING_BASE_URL: TEI URL if using TEI (default: http://localhost:8080)
  • EMBEDDINGS_CACHE_DIR: Model cache directory for fastembed (default: ./local_cache)

Checkpoint:

  • CHECKPOINT_MAX_CONTENT_SIZE_KB: Max checkpoint size in KB (default: 1024)

Consolidation Scheduler:

  • CONSOLIDATION_SCHEDULER_ENABLED: Enable automatic consolidation (default: false)
  • CONSOLIDATION_SCHEDULER_INTERVAL: Time between runs (default: 24h)
  • CONSOLIDATION_SCHEDULER_SIMILARITY_THRESHOLD: Similarity threshold (default: 0.8)

Telemetry:

  • OTEL_ENABLE: Enable OpenTelemetry (default: false, requires OTEL collector)
  • OTEL_SERVICE_NAME: Service name for traces (default: contextd)

Pre-fetch:

  • PREFETCH_ENABLED: Enable pre-fetch engine (default: true)
  • PREFETCH_CACHE_TTL: Cache TTL (default: 5m)
  • PREFETCH_CACHE_MAX_ENTRIES: Maximum cache entries (default: 100)

Example:

cfg := config.Load()
fmt.Println("Qdrant host:", cfg.Qdrant.Host)

func LoadWithFile

func LoadWithFile(configPath string) (*Config, error)

LoadWithFile loads configuration from YAML file, then overrides with environment variables.

Configuration precedence (highest to lowest):

  1. Environment variables (SERVER_HTTP_PORT, OBSERVABILITY_SERVICE_NAME, etc.)
  2. YAML config file (~/.config/contextd/config.yaml)
  3. Hardcoded defaults

The configPath parameter specifies the YAML file to load. If empty, uses default path. Default path: ~/.config/contextd/config.yaml

Security Considerations

File Permissions: Configuration file MUST have 0600 permissions (owner read/write only). Files with weaker permissions (e.g., 0644 world-readable) will be rejected.

Path Validation: Only configuration files in allowed directories can be loaded:

  • ~/.config/contextd/ (user's config directory)
  • /etc/contextd/ (system-wide config directory)

Absolute paths outside these directories are rejected to prevent path traversal attacks.

File Size Limit: Configuration files larger than 1MB are rejected to prevent resource exhaustion attacks.

Environment Variable Mapping

Environment variables use underscore separator and are uppercased. The transformer maps environment variables to YAML field names:

SERVER_HTTP_PORT -> server.http_port
OBSERVABILITY_SERVICE_NAME -> observability.service_name
PREFETCH_CACHE_TTL -> prefetch.cache_ttl

Example

cfg, err := config.LoadWithFile("")  // Use default path
if err != nil {
    log.Fatal(err)
}

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

Returns an error if:

  • Server port is not between 1 and 65535
  • Shutdown timeout is not positive
  • Service name is empty (when telemetry is enabled)

type ConsolidationSchedulerConfig added in v0.3.0

type ConsolidationSchedulerConfig struct {
	Enabled             bool          `koanf:"enabled"`              // Enable automatic consolidation (default: false)
	Interval            time.Duration `koanf:"interval"`             // Time between consolidation runs (default: 24h)
	SimilarityThreshold float64       `koanf:"similarity_threshold"` // Similarity threshold for consolidation (default: 0.8)
}

ConsolidationSchedulerConfig holds automatic memory consolidation configuration.

type Duration

type Duration time.Duration

Duration wraps time.Duration for text unmarshaling (YAML, env vars).

func (Duration) Duration

func (d Duration) Duration() time.Duration

Duration returns the underlying time.Duration.

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Duration) MarshalText

func (d Duration) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type EmbeddingsConfig

type EmbeddingsConfig struct {
	Provider    string `koanf:"provider"` // "fastembed" or "tei"
	BaseURL     string `koanf:"base_url"` // TEI URL (if using TEI)
	Model       string `koanf:"model"`
	CacheDir    string `koanf:"cache_dir"`    // Model cache directory (for fastembed)
	ONNXVersion string `koanf:"onnx_version"` // Optional ONNX runtime version override
}

EmbeddingsConfig holds embeddings service configuration.

type ObservabilityConfig

type ObservabilityConfig struct {
	EnableTelemetry   bool   `koanf:"enable_telemetry"`
	ServiceName       string `koanf:"service_name"`
	OTLPEndpoint      string `koanf:"otlp_endpoint"`        // OTLP endpoint (default: localhost:4317)
	OTLPProtocol      string `koanf:"otlp_protocol"`        // "grpc" or "http/protobuf" (default: grpc)
	OTLPInsecure      bool   `koanf:"otlp_insecure"`        // Use insecure connection (default: true for localhost)
	OTLPTLSSkipVerify bool   `koanf:"otlp_tls_skip_verify"` // Skip TLS verification for internal CAs
}

ObservabilityConfig holds OpenTelemetry configuration.

type PreFetchConfig

type PreFetchConfig struct {
	Enabled         bool
	CacheTTL        time.Duration
	CacheMaxEntries int
	Rules           PreFetchRulesConfig
}

PreFetchConfig holds pre-fetch engine configuration.

type PreFetchRulesConfig

type PreFetchRulesConfig struct {
	BranchDiff   RuleConfig
	RecentCommit RuleConfig
	CommonFiles  RuleConfig
}

PreFetchRulesConfig holds configuration for individual pre-fetch rules.

type ProductionConfig added in v0.3.0

type ProductionConfig struct {
	// Enabled indicates whether production mode is active.
	// Set via CONTEXTD_PRODUCTION_MODE=1 environment variable.
	Enabled bool `koanf:"enabled"`

	// LocalModeAcknowledged allows development features in production mode.
	// Set via CONTEXTD_LOCAL_MODE=1 environment variable.
	// Use only for local development/testing.
	LocalModeAcknowledged bool `koanf:"local_mode_acknowledged"`

	// RequireAuthentication enforces authentication in production.
	RequireAuthentication bool `koanf:"require_authentication"`

	// AuthenticationConfigured indicates if auth is properly set up.
	AuthenticationConfigured bool `koanf:"authentication_configured"`

	// RequireTLS enforces TLS for external services (Qdrant, OTEL).
	RequireTLS bool `koanf:"require_tls"`

	// AllowNoIsolation permits NoIsolation mode (testing only).
	// Always false in production mode.
	AllowNoIsolation bool `koanf:"allow_no_isolation"`
}

ProductionConfig holds production deployment configuration.

func (*ProductionConfig) IsLocal added in v0.3.0

func (c *ProductionConfig) IsLocal() bool

IsLocal returns true if local mode is acknowledged.

func (*ProductionConfig) IsProduction added in v0.3.0

func (c *ProductionConfig) IsProduction() bool

IsProduction returns true if running in production mode.

func (*ProductionConfig) Validate added in v0.3.0

func (c *ProductionConfig) Validate() error

Validate checks production configuration for security issues.

type QdrantConfig

type QdrantConfig struct {
	Host           string `koanf:"host"`
	Port           int    `koanf:"port"`
	HTTPPort       int    `koanf:"http_port"`
	CollectionName string `koanf:"collection_name"`
	VectorSize     uint64 `koanf:"vector_size"`
	DataPath       string `koanf:"data_path"`
}

QdrantConfig holds Qdrant vector database configuration.

type RepositoryConfig

type RepositoryConfig struct {
	// IgnoreFiles is a list of ignore file names to parse from project root.
	// Patterns from these files are used as exclude patterns during indexing.
	// Default: [".gitignore", ".dockerignore", ".contextdignore"]
	IgnoreFiles []string `koanf:"ignore_files"`

	// FallbackExcludes are used when no ignore files are found in the project.
	// Default: [".git/**", "node_modules/**", "vendor/**", "__pycache__/**"]
	FallbackExcludes []string `koanf:"fallback_excludes"`
}

RepositoryConfig holds repository indexing configuration.

type RuleConfig

type RuleConfig struct {
	Enabled   bool
	MaxFiles  int
	MaxSizeKB int
	TimeoutMS int
}

RuleConfig holds configuration for a single pre-fetch rule.

type Secret

type Secret string

Secret wraps strings that should be redacted in logs and serialization. Use Value() to access the actual secret value.

func (Secret) GoString

func (s Secret) GoString() string

GoString implements fmt.GoStringer for %#v formatting.

func (Secret) IsSet

func (s Secret) IsSet() bool

IsSet returns true if the secret has a non-empty value.

func (Secret) MarshalJSON

func (s Secret) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. Always returns redacted value.

func (Secret) MarshalText

func (s Secret) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler. Always returns redacted value.

func (Secret) MarshalYAML

func (s Secret) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaler. Always returns redacted value.

func (Secret) String

func (s Secret) String() string

String implements fmt.Stringer. Always returns redacted value.

func (*Secret) UnmarshalJSON

func (s *Secret) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler. Accepts raw secrets. Treats "[REDACTED]" as a test token for test compatibility.

func (*Secret) UnmarshalText

func (s *Secret) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler. Accepts raw secret values.

func (*Secret) UnmarshalYAML

func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements yaml.Unmarshaler. Accepts raw secret values.

func (Secret) Value

func (s Secret) Value() string

Value returns the actual secret value. Use sparingly.

type ServerConfig

type ServerConfig struct {
	Port            int           `koanf:"http_port"`
	ShutdownTimeout time.Duration `koanf:"shutdown_timeout"`
}

ServerConfig holds HTTP server configuration.

type StatuslineConfig added in v0.3.0

type StatuslineConfig struct {
	Enabled    bool                 `koanf:"enabled"`
	Endpoint   string               `koanf:"endpoint"` // HTTP endpoint for status
	Show       StatuslineShowConfig `koanf:"show"`
	Thresholds StatuslineThresholds `koanf:"thresholds"`
}

StatuslineConfig holds statusline display configuration.

type StatuslineShowConfig added in v0.3.0

type StatuslineShowConfig struct {
	Service     bool `koanf:"service"`     // 🟢/🟡/🔴
	Memories    bool `koanf:"memories"`    // 🧠12
	Checkpoints bool `koanf:"checkpoints"` // 💾3
	Context     bool `koanf:"context"`     // 📊68%
	Confidence  bool `koanf:"confidence"`  // C:.85
	Compression bool `koanf:"compression"` // F:2.1x
}

StatuslineShowConfig controls which items to display.

type StatuslineThresholds added in v0.3.0

type StatuslineThresholds struct {
	ContextWarning  int `koanf:"context_warning"`  // Yellow threshold (default: 70)
	ContextCritical int `koanf:"context_critical"` // Red threshold (default: 85)
}

StatuslineThresholds controls warning thresholds.

type VectorStoreConfig added in v0.3.0

type VectorStoreConfig struct {
	Provider string        `koanf:"provider"` // "chromem" or "qdrant" (default: "chromem")
	Chromem  ChromemConfig `koanf:"chromem"`
}

VectorStoreConfig holds vectorstore provider configuration.

func (*VectorStoreConfig) Validate added in v0.3.0

func (c *VectorStoreConfig) Validate() error

Validate validates VectorStoreConfig.

Jump to

Keyboard shortcuts

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