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 ¶
- func EnsureConfigDir() error
- type CheckpointConfig
- type ChromemConfig
- type Config
- type ConsolidationSchedulerConfig
- type Duration
- type EmbeddingsConfig
- type ObservabilityConfig
- type PreFetchConfig
- type PreFetchRulesConfig
- type ProductionConfig
- type QdrantConfig
- type RepositoryConfig
- type RuleConfig
- type Secret
- func (s Secret) GoString() string
- func (s Secret) IsSet() bool
- func (s Secret) MarshalJSON() ([]byte, error)
- func (s Secret) MarshalText() ([]byte, error)
- func (s Secret) MarshalYAML() (interface{}, error)
- func (s Secret) String() string
- func (s *Secret) UnmarshalJSON(data []byte) error
- func (s *Secret) UnmarshalText(text []byte) error
- func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error
- func (s Secret) Value() string
- type ServerConfig
- type StatuslineConfig
- type StatuslineShowConfig
- type StatuslineThresholds
- type VectorStoreConfig
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 ¶
LoadWithFile loads configuration from YAML file, then overrides with environment variables.
Configuration precedence (highest to lowest):
- Environment variables (SERVER_HTTP_PORT, OBSERVABILITY_SERVICE_NAME, etc.)
- YAML config file (~/.config/contextd/config.yaml)
- 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)
}
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 ¶
Duration wraps time.Duration for text unmarshaling (YAML, env vars).
func (Duration) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Duration) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Duration) UnmarshalText ¶
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 ¶
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) MarshalJSON ¶
MarshalJSON implements json.Marshaler. Always returns redacted value.
func (Secret) MarshalText ¶
MarshalText implements encoding.TextMarshaler. Always returns redacted value.
func (Secret) MarshalYAML ¶
MarshalYAML implements yaml.Marshaler. Always returns redacted value.
func (*Secret) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler. Accepts raw secrets. Treats "[REDACTED]" as a test token for test compatibility.
func (*Secret) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler. Accepts raw secret values.
func (*Secret) UnmarshalYAML ¶
UnmarshalYAML implements yaml.Unmarshaler. Accepts raw secret values.
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.