~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat: Implement centralized environment settings system (issue #598) (#626)
LearningCircuit1a7fe64ee10c
diff --git a/.github/workflows/check-env-vars.yml b/.github/workflows/check-env-vars.ymlnew file mode 100644index 0000000000..9715b367f5--- /dev/null+++ b/.github/workflows/check-env-vars.yml@@ -0,0 +1,34 @@+name: Check Environment Variables++on:+ pull_request:+ paths:+ - '**.py'+ - 'src/local_deep_research/settings/**'+ - '.github/workflows/check-env-vars.yml'+ push:+ branches:+ - main+ - dev+ paths:+ - '**.py'++jobs:+ check-env-vars:+ runs-on: ubuntu-latest++ steps:+ - uses: actions/checkout@v4++ - name: Set up Python+ uses: actions/setup-python@v5+ with:+ python-version: '3.11'++ - name: Install dependencies+ run: |+ pip install loguru sqlalchemy sqlalchemy-utc platformdirs pydantic++ - name: Run environment variable validation+ run: |+ python tests/settings/env_vars/test_env_var_usage.pydiff --git a/.gitignore b/.gitignoreindex 5b256d8d58..37735c0500 100644--- a/.gitignore+++ b/.gitignore@@ -35,6 +35,10 @@!.pre-commit-config.yaml!.isort.cfg+# Allow pre-commit hooks+!.pre-commit-hooks/+!.pre-commit-hooks/*.py+# Block all other dot files/folders.*.*/diff --git a/.pre-commit-hooks/check-env-vars.py b/.pre-commit-hooks/check-env-vars.pyindex d27dc1d682..c989e41c2c 100755--- a/.pre-commit-hooks/check-env-vars.py+++ b/.pre-commit-hooks/check-env-vars.py@@ -1,106 +1,56 @@#!/usr/bin/env python3"""-Pre-commit hook to check for direct environment variable access.-Ensures environment variables are accessed through SettingsManager where appropriate.+Simple pre-commit hook to check for direct os.environ usage.+This is a lightweight check - comprehensive validation happens in CI."""import astimport sys-import os-# Set environment variable for pre-commit hooks to allow unencrypted databases-os.environ["LDR_ALLOW_UNENCRYPTED"] = "true"--# Allowed patterns - these can use os.environ directly+# Files/patterns where direct os.environ access is allowedALLOWED_PATTERNS = {- # Configuration files and initialization- "config/",+ # Configuration and settings"settings/",- "__init__.py",- "setup.py",- # Test files+ "config/",+ # Tests"test_","_test.py","tests/",# Scripts and utilities"scripts/",- "utils/",- "cli.py",".pre-commit-hooks/",- # Example scripts demonstrating usage+ # Example and optimization scripts"examples/",- # Specific modules that need direct access+ # Specific modules that need direct access (bootstrap/config)"log_utils.py", # Logging configuration- "paths.py", # Path configuration- "queue_config.py", # Queue configuration- "server_config.py", # Server configuration (needed before DB)- "memory_cache/", # Cache configuration- # Database and migrations+ "server_config.py", # Server configuration+ # Database initialization (needs env vars before DB exists)"alembic/","migrations/",- "encrypted_db.py", # Database encryption setup- "sqlcipher_utils.py", # SQLCipher configuration (needed before DB)+ "encrypted_db.py",+ "sqlcipher_utils.py",}-# Import SettingsManager to get allowed environment variables-try:- # Add parent directory to Python path for imports- import os-- parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- sys.path.insert(0, os.path.join(parent_dir, "src"))-- from local_deep_research.settings.manager import SettingsManager-- # Get bootstrap vars from SettingsManager- BOOTSTRAP_VARS = set(SettingsManager.get_bootstrap_env_vars().keys())-except ImportError:- # Fallback if import fails (e.g., during initial setup)- BOOTSTRAP_VARS = {- "LDR_ENCRYPTION_KEY",- "LDR_SECRET_KEY",- "LDR_DATABASE_URL",- "LDR_DATA_DIR",- "LDR_CONFIG_DIR",- "LDR_LOG_DIR",- "LDR_TEST_MODE",- "LDR_USE_FALLBACK_LLM",- }--# Additional always-allowed vars (system/OS level)-SYSTEM_ALLOWED_VARS = {- # Development and debugging- "DEBUG",- "PYTHONPATH",+# System environment variables that are always allowed+SYSTEM_VARS = {"PATH",- # System configuration"HOME","USER",+ "PYTHONPATH","TMPDIR","TEMP",- # CI/CD and deployment+ "DEBUG","CI","GITHUB_ACTIONS",- "DOCKER_CONTAINER",+ "TESTING", # External testing flag}-# Combine all always-allowed variables-ALWAYS_ALLOWED_VARS = BOOTSTRAP_VARS | SYSTEM_ALLOWED_VARS-class EnvVarChecker(ast.NodeVisitor):def __init__(self, filename: str):self.filename = filenameself.errors = []- self.has_settings_manager_import = False-- def visit_ImportFrom(self, node):- if node.module and "settings" in node.module.lower():- for alias in node.names:- if "SettingsManager" in (alias.name or ""):- self.has_settings_manager_import = True- self.generic_visit(node)def visit_Call(self, node):# Check for os.environ.get() or os.getenv()@@ -132,16 +82,28 @@ class EnvVarChecker(ast.NodeVisitor):env_var_name = node.args[0].valueif is_environ_get and env_var_name:- # Check if this variable is always allowed- if env_var_name not in ALWAYS_ALLOWED_VARS:- # Check if file is in allowed locations- if not self._is_file_allowed():+ # Allow system vars+ if env_var_name in SYSTEM_VARS:+ return self.generic_visit(node)++ # Check if file is in allowed location+ if not self._is_file_allowed():+ # For LDR_ vars, suggest using SettingsManager+ if env_var_name.startswith("LDR_"):self.errors.append((node.lineno,f"Environment variable '{env_var_name}' should be accessed through SettingsManager, not os.environ",))+ # For other vars, generic warning+ else:+ self.errors.append(+ (+ node.lineno,+ f"Direct access to environment variable '{env_var_name}' - consider using SettingsManager",+ )+ )self.generic_visit(node)@@ -155,14 +117,26 @@ class EnvVarChecker(ast.NodeVisitor):and isinstance(node.slice, ast.Constant)):env_var_name = node.slice.value- if env_var_name not in ALWAYS_ALLOWED_VARS:- if not self._is_file_allowed():++ # Allow system vars+ if env_var_name in SYSTEM_VARS:+ return self.generic_visit(node)++ if not self._is_file_allowed():+ if env_var_name.startswith("LDR_"):self.errors.append((node.lineno,f"Environment variable '{env_var_name}' should be accessed through SettingsManager, not os.environ",))+ else:+ self.errors.append(+ (+ node.lineno,+ f"Direct access to environment variable '{env_var_name}' - consider using SettingsManager",+ )+ )self.generic_visit(node)@@ -216,41 +190,17 @@ def main():files_to_check = sys.argv[1:]has_errors = False- print("Checking environment variable access patterns...")-for filename in files_to_check:if not check_file(filename):has_errors = Trueif has_errors:- print("\n❌ Environment variable checks failed!")- print("\nGuidelines:")- print(- "1. Use SettingsManager for application settings instead of os.environ"- )- print("2. Direct os.environ access is allowed in:")- print(" - Configuration and initialization files")- print(" - Test files")- print(" - Scripts and utilities")- print("3. Always allowed environment variables:")- print(" - System vars: HOME, PATH, USER, etc.")- print(" - Security vars: encryption keys, secrets")- print(" - LDR system paths: LDR_DATA_DIR, etc.")- print("\nTo add a setting:")- print(- " 1. Add it to defaults/default_settings.json with 'env_var' field"- )- print(" 2. Access via: settings_manager.get_setting('category.name')")- print(- " 3. The env var will automatically override the DB value if set"- )- print("\nNOTE: This is being migrated - see issue #598")- print(- "Run this check on all files: find . -name '*.py' | xargs python .pre-commit-hooks/check-env-vars.py"- )+ print("\n⚠️ Direct environment variable access detected!")+ print("\nFor LDR_ variables, use SettingsManager instead of os.environ")+ print("See issue #598 for migration details")+ print("\nNote: Full validation runs in CI")sys.exit(1)else:- print("✅ Environment variable checks passed!")sys.exit(0)diff --git a/src/local_deep_research/settings/README.md b/src/local_deep_research/settings/README.mdnew file mode 100644index 0000000000..ef0fa5afc0--- /dev/null+++ b/src/local_deep_research/settings/README.md@@ -0,0 +1,70 @@+# Environment Settings System++## Quick Start++```python+# Use environment settings+from local_deep_research.settings.env_registry import is_test_mode, use_fallback_llm++if is_test_mode():+ # Running in test mode+ pass+```++## Architecture++- `env_settings.py`: Base classes for all setting types+- `env_registry.py`: Global registry and convenience functions+- `env_definitions/`: Setting definitions by category+ - `testing.py`: Test/CI flags+ - `bootstrap.py`: Pre-database settings+ - `db_config.py`: Database configuration++## Adding New Environment Settings++1. Create setting in `env_definitions/category.py`:+```python+from ..env_settings import BooleanSetting++MY_SETTING = BooleanSetting(+ key="category.my_setting",+ env_var="LDR_MY_SETTING",+ default=False,+ description="My new setting"+)+```++2. Register it:+```python+from ..env_registry import registry+registry.register(MY_SETTING)+```++3. Import module in `env_registry.py`++## Setting Types++- `BooleanSetting`: True/false values+- `IntegerSetting`: Numbers with min/max validation+- `StringSetting`: Text values+- `PathSetting`: File paths with expansion+- `SecretSetting`: Sensitive values (hidden in logs)+- `EnumSetting`: Choice from predefined options++## Environment Variables++### Testing+- `LDR_TEST_MODE`: Enable test mode+- `LDR_USE_FALLBACK_LLM`: Use fallback LLM+- `CI`: Running in CI++### Bootstrap (needed before DB)+- `LDR_ENCRYPTION_KEY`: Master encryption key+- `LDR_DATA_DIR`: Data directory+- `LDR_DB_*`: Database configuration++## Integration++- Automatically works with SettingsManager+- Pre-commit hook recognizes all registered env vars+- Type-safe with automatic validationdiff --git a/src/local_deep_research/settings/env_definitions/__init__.py b/src/local_deep_research/settings/env_definitions/__init__.pynew file mode 100644index 0000000000..a6e5b9cd46--- /dev/null+++ b/src/local_deep_research/settings/env_definitions/__init__.py@@ -0,0 +1,21 @@+"""+Environment setting definitions organized by category.+"""++from .testing import TESTING_SETTINGS+from .bootstrap import BOOTSTRAP_SETTINGS+from .db_config import DB_CONFIG_SETTINGS++# Combine all settings for easy access+ALL_SETTINGS = {+ "testing": TESTING_SETTINGS,+ "bootstrap": BOOTSTRAP_SETTINGS,+ "db_config": DB_CONFIG_SETTINGS,+}++__all__ = [+ "TESTING_SETTINGS",+ "BOOTSTRAP_SETTINGS",+ "DB_CONFIG_SETTINGS",+ "ALL_SETTINGS",+]diff --git a/src/local_deep_research/settings/env_definitions/bootstrap.py b/src/local_deep_research/settings/env_definitions/bootstrap.pynew file mode 100644index 0000000000..0f762d3e40--- /dev/null+++ b/src/local_deep_research/settings/env_definitions/bootstrap.py@@ -0,0 +1,60 @@+"""+Bootstrap environment settings.++These settings are required early in the application lifecycle,+before database initialization and other core systems.+"""++from ..env_settings import (+ BooleanSetting,+ StringSetting,+ PathSetting,+ SecretSetting,+)+++# Bootstrap settings required before DB init+BOOTSTRAP_SETTINGS = [+ # Security and encryption+ SecretSetting(+ key="bootstrap.encryption_key",+ description="Database encryption key",+ required=False, # Not required if allow_unencrypted is True+ ),+ SecretSetting(+ key="bootstrap.secret_key",+ description="Application secret key for session encryption",+ ),+ # Database+ StringSetting(+ key="bootstrap.database_url",+ description="Database connection URL",+ ),+ BooleanSetting(+ key="bootstrap.allow_unencrypted",+ description="Allow unencrypted database (for development)",+ default=False,+ ),+ # System paths+ PathSetting(+ key="bootstrap.data_dir",+ description="Data directory path",+ create_if_missing=True,+ ),+ PathSetting(+ key="bootstrap.config_dir",+ description="Configuration directory path",+ create_if_missing=True,+ ),+ PathSetting(+ key="bootstrap.log_dir",+ description="Log directory path",+ create_if_missing=True,+ ),+ # Logging+ BooleanSetting(+ key="bootstrap.enable_file_logging",+ description="Enable logging to file",+ default=False,+ ),+]diff --git a/src/local_deep_research/settings/env_definitions/db_config.py b/src/local_deep_research/settings/env_definitions/db_config.pynew file mode 100644index 0000000000..956991daea--- /dev/null+++ b/src/local_deep_research/settings/env_definitions/db_config.py@@ -0,0 +1,72 @@+"""+Database configuration environment settings.++These settings control SQLite and SQLCipher database parameters+that must be set before opening the database connection.+"""++from ..env_settings import (+ IntegerSetting,+ StringSetting,+ EnumSetting,+)+++# Database configuration settings+DB_CONFIG_SETTINGS = [+ # Performance settings+ IntegerSetting(+ key="db_config.cache_size_mb",+ description="SQLite cache size in MB",+ min_value=1,+ max_value=10000,+ default=100,+ ),+ EnumSetting(+ key="db_config.journal_mode",+ description="SQLite journal mode",+ allowed_values={+ "DELETE",+ "TRUNCATE",+ "PERSIST",+ "MEMORY",+ "WAL",+ "OFF",+ },+ default="WAL",+ case_sensitive=False,+ ),+ EnumSetting(+ key="db_config.synchronous",+ description="SQLite synchronous mode",+ allowed_values={"OFF", "NORMAL", "FULL", "EXTRA"},+ default="NORMAL",+ case_sensitive=False,+ ),+ # Storage settings+ IntegerSetting(+ key="db_config.page_size",+ description="SQLite page size (must be power of 2)",+ min_value=512,+ max_value=65536,+ default=4096,+ ),+ # Encryption settings+ IntegerSetting(+ key="db_config.kdf_iterations",+ description="Number of KDF iterations for key derivation",+ min_value=1000,+ max_value=1000000,+ default=256000,+ ),+ StringSetting(+ key="db_config.kdf_algorithm",+ description="Key derivation function algorithm",+ default="PBKDF2_HMAC_SHA512",+ ),+ StringSetting(+ key="db_config.hmac_algorithm",+ description="HMAC algorithm for database integrity",+ default="HMAC_SHA512",+ ),+]diff --git a/src/local_deep_research/settings/env_definitions/testing.py b/src/local_deep_research/settings/env_definitions/testing.pynew file mode 100644index 0000000000..5c85110c37--- /dev/null+++ b/src/local_deep_research/settings/env_definitions/testing.py@@ -0,0 +1,34 @@+"""+Testing and CI environment settings.++These settings control test mode behavior and CI/testing flags.+"""++import os+from ..env_settings import BooleanSetting+++# External environment variables (not LDR-prefixed, set by external systems)+# These are read directly since we don't control them+CI = os.environ.get("CI", "false").lower() in ("true", "1", "yes")+GITHUB_ACTIONS = os.environ.get("GITHUB_ACTIONS", "false").lower() in (+ "true",+ "1",+ "yes",+)+TESTING = os.environ.get("TESTING", "false").lower() in ("true", "1", "yes")+++# LDR Testing settings (our application's test configuration)+TESTING_SETTINGS = [+ BooleanSetting(+ key="testing.test_mode",+ description="Enable test mode (adds delays for testing concurrency)",+ default=False,+ ),+ BooleanSetting(+ key="testing.use_fallback_llm",+ description="Use mock LLM for testing (skips API calls and DB operations)",+ default=False,+ ),+]diff --git a/src/local_deep_research/settings/env_registry.py b/src/local_deep_research/settings/env_registry.pynew file mode 100644index 0000000000..6accc35a3c--- /dev/null+++ b/src/local_deep_research/settings/env_registry.py@@ -0,0 +1,82 @@+"""+Registry of all environment-only settings.++This module creates the global registry and registers all environment settings+defined in the env_definitions subfolder.+"""++from typing import Optional, Any++from .env_settings import SettingsRegistry+from .env_definitions import ALL_SETTINGS+++def _create_registry() -> SettingsRegistry:+ """Create and initialize the global registry with all defined settings."""+ registry = SettingsRegistry()++ # Register all setting categories+ for category_name, settings_list in ALL_SETTINGS.items():+ registry.register_category(category_name, settings_list)++ return registry+++# Global registry instance (singleton)+registry = _create_registry()+++# Convenience functions for direct access+def get_env_setting(key: str, default: Optional[Any] = None) -> Any:+ """+ Get an environment setting value.++ Args:+ key: Setting key (e.g., "testing.test_mode")+ default: Default value if not set++ Returns:+ Setting value or default+ """+ return registry.get(key, default)+++def is_test_mode() -> bool:+ """Quick check for test mode."""+ return bool(registry.get("testing.test_mode", False))+++def use_fallback_llm() -> bool:+ """Quick check for fallback LLM mode."""+ return bool(registry.get("testing.use_fallback_llm", False))+++def is_ci_environment() -> bool:+ """Quick check for CI environment."""+ # CI is now an external variable, read it dynamically+ import os++ return os.environ.get("CI", "false").lower() in ("true", "1", "yes")+++def is_github_actions() -> bool:+ """Check if running in GitHub Actions."""+ # GITHUB_ACTIONS is now an external variable, read it dynamically+ import os++ return os.environ.get("GITHUB_ACTIONS", "false").lower() in (+ "true",+ "1",+ "yes",+ )+++# Export the registry and convenience functions+__all__ = [+ "registry",+ "get_env_setting",+ "is_test_mode",+ "use_fallback_llm",+ "is_ci_environment",+ "is_github_actions",+]diff --git a/src/local_deep_research/settings/env_settings.py b/src/local_deep_research/settings/env_settings.pynew file mode 100644index 0000000000..614a934402--- /dev/null+++ b/src/local_deep_research/settings/env_settings.py@@ -0,0 +1,345 @@+"""+Environment-only settings that are loaded early and never stored in database.++These settings are:+1. Required before database initialization+2. Used for testing/CI configuration+3. System bootstrap configuration++They are accessed through SettingsManager but always read from environment variables.++Why some settings must be environment-only:+- Bootstrap settings (paths, encryption keys) are needed to initialize the database itself+- Database configuration settings must be available before connecting to the database+- Testing flags need to be checked before any database operations occur+- CI/CD variables control build-time behavior before the application starts++These settings cannot be stored in the database because they are prerequisites for+accessing the database. This creates a bootstrapping requirement where certain+configuration must come from the environment to establish the system state needed+to access persisted settings.+"""++import os+from pathlib import Path+from typing import Any, Dict, Optional, List, Set, TypeVar, Generic+from abc import ABC, abstractmethod+from loguru import logger+++T = TypeVar("T")+++class EnvSetting(ABC, Generic[T]):+ """Base class for all environment settings."""++ def __init__(+ self,+ key: str,+ description: str,+ default: Optional[T] = None,+ required: bool = False,+ ):+ self.key = key+ # Auto-generate env_var from key+ # e.g., "testing.test_mode" -> "LDR_TESTING_TEST_MODE"+ self.env_var = "LDR_" + key.upper().replace(".", "_")+ self.description = description+ self.default = default+ self.required = required++ def get_value(self) -> Optional[T]:+ """Get the value from environment with type conversion."""+ raw = self._get_raw_value()+ if raw is None:+ if self.required and self.default is None:+ raise ValueError(+ f"Required environment variable {self.env_var} is not set"+ )+ return self.default+ return self._convert_value(raw)++ @abstractmethod+ def _convert_value(self, raw: str) -> T:+ """Convert raw string value to the appropriate type."""+ pass++ def _get_raw_value(self) -> Optional[str]:+ """Get raw string value from environment."""+ return os.environ.get(self.env_var)++ @property+ def is_set(self) -> bool:+ """Check if the environment variable is set."""+ return self.env_var in os.environ++ def __repr__(self) -> str:+ """String representation for debugging."""+ return f"{self.__class__.__name__}(key='{self.key}', env_var='{self.env_var}')"+++class BooleanSetting(EnvSetting[bool]):+ """Boolean environment setting."""++ def __init__(+ self,+ key: str,+ description: str,+ default: bool = False,+ ):+ super().__init__(key, description, default)++ def _convert_value(self, raw: str) -> bool:+ """Convert string to boolean."""+ return raw.lower() in ("true", "1", "yes", "on", "enabled")+++class StringSetting(EnvSetting[str]):+ """String environment setting."""++ def __init__(+ self,+ key: str,+ description: str,+ default: Optional[str] = None,+ required: bool = False,+ ):+ super().__init__(key, description, default, required)++ def _convert_value(self, raw: str) -> str:+ """Return string value as-is."""+ return raw+++class IntegerSetting(EnvSetting[int]):+ """Integer environment setting."""++ def __init__(+ self,+ key: str,+ description: str,+ default: Optional[int] = None,+ min_value: Optional[int] = None,+ max_value: Optional[int] = None,+ ):+ super().__init__(key, description, default)+ self.min_value = min_value+ self.max_value = max_value++ def _convert_value(self, raw: str) -> Optional[int]:+ """Convert string to integer with validation."""+ try:+ value = int(raw)+ if self.min_value is not None and value < self.min_value:+ raise ValueError(+ f"{self.env_var} value {value} is below minimum {self.min_value}"+ )+ if self.max_value is not None and value > self.max_value:+ raise ValueError(+ f"{self.env_var} value {value} is above maximum {self.max_value}"+ )+ return value+ except ValueError as e:+ if "invalid literal" in str(e):+ logger.warning(+ f"Invalid integer value '{raw}' for {self.env_var}, using default: {self.default}"+ )+ return self.default+ raise+++class PathSetting(StringSetting):+ """Path environment setting with validation."""++ def __init__(+ self,+ key: str,+ description: str,+ default: Optional[str] = None,+ must_exist: bool = False,+ create_if_missing: bool = False,+ ):+ super().__init__(key, description, default)+ self.must_exist = must_exist+ self.create_if_missing = create_if_missing++ def get_value(self) -> Optional[str]:+ """Get path value with optional validation/creation."""+ path_str = super().get_value()+ if path_str is None:+ return None++ # Use pathlib for path operations+ path = Path(path_str).expanduser()+ # Expand environment variables manually since pathlib doesn't have expandvars+ path_str = os.path.expandvars(str(path))+ path = Path(path_str)++ if self.create_if_missing and not path.exists():+ try:+ path.mkdir(parents=True, exist_ok=True)+ except OSError:+ # Silently fail if we can't create - let app handle it+ pass+ elif self.must_exist and not path.exists():+ # Only raise if explicitly required to exist+ raise ValueError(+ f"Path {path} specified in {self.env_var} does not exist"+ )++ return str(path)+++class SecretSetting(StringSetting):+ """Secret/sensitive environment setting."""++ def __init__(+ self,+ key: str,+ description: str,+ default: Optional[str] = None,+ required: bool = False,+ ):+ super().__init__(key, description, default, required)++ def __repr__(self) -> str:+ """Hide the value in string representation."""+ return f"SecretSetting(key='{self.key}', value=***)"++ def __str__(self) -> str:+ """Hide the value in string conversion."""+ value = "SET" if self.is_set else "NOT SET"+ return f"{self.key}=<{value}>"+++class EnumSetting(EnvSetting[str]):+ """Enum-style setting with allowed values."""++ def __init__(+ self,+ key: str,+ description: str,+ allowed_values: Set[str],+ default: Optional[str] = None,+ case_sensitive: bool = False,+ ):+ super().__init__(key, description, default)+ self.allowed_values = allowed_values+ self.case_sensitive = case_sensitive++ # Store lowercase versions for case-insensitive comparison+ if not case_sensitive:+ self._allowed_lower = {v.lower() for v in allowed_values}+ # Create a mapping from lowercase to original case+ self._canonical_map = {v.lower(): v for v in allowed_values}++ def _convert_value(self, raw: str) -> str:+ """Convert and validate value against allowed values."""+ if self.case_sensitive:+ if raw not in self.allowed_values:+ raise ValueError(+ f"{self.env_var} value '{raw}' not in allowed values: {self.allowed_values}"+ )+ return raw+ else:+ # Case-insensitive matching+ raw_lower = raw.lower()+ if raw_lower not in self._allowed_lower:+ raise ValueError(+ f"{self.env_var} value '{raw}' not in allowed values: {self.allowed_values}"+ )+ # Return the canonical version (from allowed_values)+ return self._canonical_map[raw_lower]+++class SettingsRegistry:+ """Registry for all environment settings."""++ def __init__(self):+ self._settings: Dict[str, EnvSetting] = {}+ self._categories: Dict[str, List[EnvSetting]] = {}++ def register_category(self, category: str, settings: List[EnvSetting]):+ """Register a category of settings."""+ self._categories[category] = settings+ for setting in settings:+ self._settings[setting.key] = setting++ def get(self, key: str, default: Optional[Any] = None) -> Any:+ """+ Get a setting value.++ Args:+ key: Setting key (e.g., "testing.test_mode")+ default: Default value if not set or on error++ Returns:+ Setting value or default+ """+ setting = self._settings.get(key)+ if not setting:+ return default++ try:+ value = setting.get_value()+ # Use provided default if setting returns None+ return value if value is not None else default+ except ValueError:+ # On validation error, return default+ return default++ def get_setting_object(self, key: str) -> Optional[EnvSetting]:+ """Get the setting object itself for introspection."""+ return self._settings.get(key)++ def is_env_only(self, key: str) -> bool:+ """Check if a key is an env-only setting."""+ return key in self._settings++ def get_env_var(self, key: str) -> Optional[str]:+ """Get the environment variable name for a key."""+ setting = self._settings.get(key)+ return setting.env_var if setting else None++ def get_all_env_vars(self) -> Dict[str, str]:+ """Get all environment variables and descriptions."""+ return {+ setting.env_var: setting.description+ for setting in self._settings.values()+ }++ def get_category_settings(self, category: str) -> List[EnvSetting]:+ """Get all settings in a category."""+ return self._categories.get(category, [])++ def get_bootstrap_vars(self) -> Dict[str, str]:+ """Get bootstrap environment variables (bootstrap + db_config)."""+ result = {}+ for category in ["bootstrap", "db_config"]:+ for setting in self._categories.get(category, []):+ result[setting.env_var] = setting.description+ return result++ def get_testing_vars(self) -> Dict[str, str]:+ """Get testing environment variables."""+ result = {}+ for setting in self._categories.get("testing", []):+ result[setting.env_var] = setting.description+ return result++ def list_all_settings(self) -> List[str]:+ """List all registered setting keys."""+ return list(self._settings.keys())+++# Export list for better IDE discovery+__all__ = [+ "EnvSetting",+ "BooleanSetting",+ "StringSetting",+ "IntegerSetting",+ "PathSetting",+ "SecretSetting",+ "EnumSetting",+ "SettingsRegistry",+]diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.pyindex 70b3368fe1..9af111050e 100644--- a/src/local_deep_research/settings/manager.py+++ b/src/local_deep_research/settings/manager.py@@ -20,6 +20,7 @@ from ..web.models.settings import (SearchSetting,)from .base import ISettingsManager+from .env_registry import registry as env_registrydef check_env_setting(key: str) -> str | None:@@ -239,6 +240,11 @@ class SettingsManager(ISettingsManager):Returns:Setting value or default if not found"""++ # First check if this is an env-only setting+ if env_registry.is_env_only(key):+ return env_registry.get(key, default)+# If using database first approach and session available, check databasetry:settings = self.__query_settings(key)@@ -765,27 +771,8 @@ class SettingsManager(ISettingsManager):Returns:Dict mapping env var names to their descriptions"""- return {- # Security and encryption- "LDR_ENCRYPTION_KEY": "Database encryption key (required for encrypted databases)",- "LDR_SECRET_KEY": "Application secret key for session encryption",- "LDR_DATABASE_URL": "Database connection URL",- # Database configuration (needed before opening DB)- "LDR_DB_CACHE_SIZE_MB": "SQLite cache size in MB",- "LDR_DB_HMAC_ALGORITHM": "HMAC algorithm for database integrity",- "LDR_DB_JOURNAL_MODE": "SQLite journal mode (e.g., WAL)",- "LDR_DB_KDF_ALGORITHM": "Key derivation function algorithm",- "LDR_DB_KDF_ITERATIONS": "Number of KDF iterations",- "LDR_DB_PAGE_SIZE": "SQLite page size",- "LDR_DB_SYNCHRONOUS": "SQLite synchronous mode",- # System paths- "LDR_DATA_DIR": "Data directory path",- "LDR_CONFIG_DIR": "Configuration directory path",- "LDR_LOG_DIR": "Log directory path",- # Testing/CI- "LDR_TEST_MODE": "Enable test mode",- "LDR_USE_FALLBACK_LLM": "Use fallback LLM for testing",- }+ # Get bootstrap vars from env registry+ return env_registry.get_bootstrap_vars()@staticmethoddef is_bootstrap_env_var(env_var: str) -> bool:@@ -801,6 +788,19 @@ class SettingsManager(ISettingsManager):bootstrap_vars = SettingsManager.get_bootstrap_env_vars()return env_var in bootstrap_vars+ @staticmethod+ def is_env_only_setting(key: str) -> bool:+ """+ Check if a setting key is environment-only.++ Args:+ key: Setting key to check++ Returns:+ True if it's an env-only setting, False otherwise+ """+ return env_registry.is_env_only(key)+@staticmethoddef get_env_var_for_setting(setting_key: str) -> str:"""diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.pyindex 2780ba485e..d9b5597d28 100644--- a/src/local_deep_research/utilities/db_utils.py+++ b/src/local_deep_research/utilities/db_utils.py@@ -1,5 +1,4 @@import functools-import osfrom typing import Any, Callable, Dictfrom cachetools import LRUCache@@ -7,6 +6,8 @@ from flask import g, has_app_context, session as flask_sessionfrom loguru import loggerfrom sqlalchemy.orm import Session+from ..settings.env_registry import use_fallback_llm+from ..config.paths import get_data_directoryfrom ..database.encrypted_db import db_managerfrom .threading_utils import thread_specific_cache@@ -160,7 +161,7 @@ def get_setting_from_db_main_thread("""# In fallback LLM mode, always return default values without database access- if os.environ.get("LDR_USE_FALLBACK_LLM", ""):+ if use_fallback_llm():logger.debug(f"Using default value for {key} in fallback LLM environment")diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 62f3cde38f..006a573d62 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -121,7 +121,10 @@ def create_app():)# Check if using custom location- custom_data_dir = os.environ.get("LDR_DATA_DIR", None)+ from local_deep_research.settings.manager import SettingsManager++ settings_manager = SettingsManager()+ custom_data_dir = settings_manager.get_setting("bootstrap.data_dir")if custom_data_dir:logger.info(f"Using custom data location via LDR_DATA_DIR: {custom_data_dir}"diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 465dfe8643..6fd0c6e017 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -2118,7 +2118,10 @@ def api_get_data_location():encrypted_db_path = get_encrypted_database_path()# Check if LDR_DATA_DIR environment variable is set- custom_data_dir = os.environ.get("LDR_DATA_DIR", None)+ from local_deep_research.settings.manager import SettingsManager++ settings_manager = SettingsManager()+ custom_data_dir = settings_manager.get_setting("bootstrap.data_dir")# Get platform-specific default location infoplatform_info = {diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex f7dab7375b..93a6ae95a7 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -1562,9 +1562,9 @@ def cleanup_research_resources(# For testing: Add a small delay to simulate research taking time# This helps test concurrent research limits- import os+ from ...settings.env_registry import is_test_mode- if os.environ.get("LDR_TEST_MODE") == "true":+ if is_test_mode():import timelogger.info(diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.pyindex 9aa64056db..4e1a7be6fb 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py@@ -2,7 +2,6 @@Adaptive rate limit tracker that learns optimal retry wait times for each search engine."""-import osimport randomimport timefrom collections import deque@@ -10,6 +9,8 @@ from typing import Dict, List, Optional, Tuplefrom loguru import logger+from ...settings.env_registry import use_fallback_llm, is_ci_environment+from ...config.thread_settings import (get_settings_context,get_setting_from_snapshot,@@ -144,7 +145,7 @@ class AdaptiveRateLimitTracker:return# Skip database operations in fallback mode- if os.environ.get("LDR_USE_FALLBACK_LLM", ""):+ if use_fallback_llm():logger.debug("Skipping rate limit estimate loading in fallback mode")@@ -311,7 +312,7 @@ class AdaptiveRateLimitTracker:f"Skipping database recording in programmatic mode for {engine_type}")# Skip database operations in fallback mode- elif not os.environ.get("LDR_USE_FALLBACK_LLM", ""):+ elif not use_fallback_llm():# Try to get research context from search tracker (for username/password)from ...metrics.search_tracker import get_search_tracker@@ -455,7 +456,7 @@ class AdaptiveRateLimitTracker:logger.debug(f"Skipping estimate persistence in programmatic mode for {engine_type}")- elif not os.environ.get("LDR_USE_FALLBACK_LLM", ""):+ elif not use_fallback_llm():# Try to get research context from search trackerfrom ...metrics.search_tracker import get_search_tracker@@ -531,9 +532,7 @@ class AdaptiveRateLimitTracker:List of tuples with engine statistics"""# Skip database operations in test/fallback mode- if os.environ.get("LDR_USE_FALLBACK_LLM", "") or os.environ.get(- "CI", ""- ):+ if use_fallback_llm() or is_ci_environment():logger.debug("Skipping database stats in test/CI mode")# Return stats from in-memory estimatesstats = []@@ -619,9 +618,7 @@ class AdaptiveRateLimitTracker:return# Skip database operations in test/fallback mode- if os.environ.get("LDR_USE_FALLBACK_LLM", "") or os.environ.get(- "CI", ""- ):+ if use_fallback_llm() or is_ci_environment():logger.debug(f"Reset rate limit data for {engine_type} (memory only in test/CI mode)")@@ -731,9 +728,7 @@ class AdaptiveRateLimitTracker:return# Skip database operations in test/fallback mode- if os.environ.get("LDR_USE_FALLBACK_LLM", "") or os.environ.get(- "CI", ""- ):+ if use_fallback_llm() or is_ci_environment():logger.debug("Skipping database cleanup in test/CI mode")returndiff --git a/tests/settings/env_vars/test_env_auto_generation.py b/tests/settings/env_vars/test_env_auto_generation.pynew file mode 100644index 0000000000..d33eb654d3--- /dev/null+++ b/tests/settings/env_vars/test_env_auto_generation.py@@ -0,0 +1,188 @@+"""Test environment variable auto-generation and external variables."""++import os+from unittest.mock import patch++from local_deep_research.settings.env_settings import (+ BooleanSetting,+ StringSetting,+ IntegerSetting,+ PathSetting,+ SecretSetting,+ EnumSetting,+)+++class TestEnvVarAutoGeneration:+ """Test that environment variable names are auto-generated correctly."""++ def test_simple_key_generation(self):+ """Test basic key to env var conversion."""+ test_cases = [+ ("testing.test_mode", "LDR_TESTING_TEST_MODE"),+ ("bootstrap.data_dir", "LDR_BOOTSTRAP_DATA_DIR"),+ ("db_config.cache_size", "LDR_DB_CONFIG_CACHE_SIZE"),+ ("app.debug", "LDR_APP_DEBUG"),+ ("search.max_results", "LDR_SEARCH_MAX_RESULTS"),+ ]++ for key, expected_env_var in test_cases:+ setting = StringSetting(key, "Test description")+ assert setting.env_var == expected_env_var, f"Failed for key: {key}"++ def test_all_setting_types_generate_correctly(self):+ """Test that all setting types auto-generate env vars."""+ settings = [+ BooleanSetting("test.bool", "Bool setting"),+ StringSetting("test.string", "String setting"),+ IntegerSetting("test.int", "Int setting"),+ PathSetting("test.path", "Path setting"),+ SecretSetting("test.secret", "Secret setting"),+ EnumSetting("test.enum", "Enum setting", allowed_values={"A", "B"}),+ ]++ for setting in settings:+ assert setting.env_var.startswith("LDR_TEST_")+ assert (+ setting.env_var+ == f"LDR_TEST_{setting.key.split('.')[-1].upper()}"+ )++ def test_no_duplicate_env_vars_in_registry(self):+ """Test that all registered settings have unique env vars."""+ from local_deep_research.settings.env_registry import registry++ all_env_vars = []+ for key in registry.list_all_settings():+ env_var = registry.get_env_var(key)+ if env_var:+ all_env_vars.append(env_var)++ # Check for duplicates+ assert len(all_env_vars) == len(set(all_env_vars)), (+ "Duplicate env vars found!"+ )++ def test_env_var_reading(self):+ """Test that settings correctly read from environment."""+ test_env_var = "LDR_TEST_SETTING"+ test_value = "test_value_123"++ with patch.dict(os.environ, {test_env_var: test_value}):+ setting = StringSetting("test.setting", "Test")+ assert setting.get_value() == test_value++ def test_boolean_conversion(self):+ """Test boolean environment variable conversion."""+ setting = BooleanSetting("test.flag", "Test flag")++ test_cases = [+ ("true", True),+ ("True", True),+ ("TRUE", True),+ ("1", True),+ ("yes", True),+ ("false", False),+ ("False", False),+ ("0", False),+ ("no", False),+ ("", False),+ ]++ for env_value, expected in test_cases:+ with patch.dict(os.environ, {"LDR_TEST_FLAG": env_value}):+ assert setting.get_value() == expected, (+ f"Failed for value: {env_value}"+ )+++class TestExternalEnvVars:+ """Test external environment variables (CI, GITHUB_ACTIONS, etc.)."""++ def test_external_vars_are_booleans(self):+ """Test that external vars are properly converted to booleans."""+ from local_deep_research.settings.env_definitions.testing import (+ CI,+ GITHUB_ACTIONS,+ TESTING,+ )++ # They should be booleans+ assert isinstance(CI, bool)+ assert isinstance(GITHUB_ACTIONS, bool)+ assert isinstance(TESTING, bool)++ def test_external_vars_respond_to_environment(self):+ """Test that external vars read from environment correctly."""+ # We need to reimport the module after changing env vars+ with patch.dict(+ os.environ, {"CI": "true", "GITHUB_ACTIONS": "1", "TESTING": "yes"}+ ):+ # Clear the module from cache and reimport+ import sys++ if (+ "local_deep_research.settings.env_definitions.testing"+ in sys.modules+ ):+ del sys.modules[+ "local_deep_research.settings.env_definitions.testing"+ ]++ from local_deep_research.settings.env_definitions.testing import (+ CI,+ GITHUB_ACTIONS,+ TESTING,+ )++ assert CI is True+ assert GITHUB_ACTIONS is True+ assert TESTING is True++ def test_external_vars_default_to_false(self):+ """Test that external vars default to False when not set."""+ with patch.dict(os.environ, {}, clear=True):+ # Clear and reimport+ import sys++ if (+ "local_deep_research.settings.env_definitions.testing"+ in sys.modules+ ):+ del sys.modules[+ "local_deep_research.settings.env_definitions.testing"+ ]++ from local_deep_research.settings.env_definitions.testing import (+ CI,+ GITHUB_ACTIONS,+ TESTING,+ )++ assert CI is False+ assert GITHUB_ACTIONS is False+ assert TESTING is False+++class TestBackwardCompatibility:+ """Test that the refactoring maintains backward compatibility."""++ def test_expected_env_var_names(self):+ """Test that common env vars still map to expected names."""+ from local_deep_research.settings.env_registry import registry++ # These are the env vars that existing code might depend on+ expected_mappings = [+ ("testing.test_mode", "LDR_TESTING_TEST_MODE"),+ ("testing.use_fallback_llm", "LDR_TESTING_USE_FALLBACK_LLM"),+ ("bootstrap.encryption_key", "LDR_BOOTSTRAP_ENCRYPTION_KEY"),+ ("bootstrap.database_url", "LDR_BOOTSTRAP_DATABASE_URL"),+ ("bootstrap.data_dir", "LDR_BOOTSTRAP_DATA_DIR"),+ ("db_config.cache_size_mb", "LDR_DB_CONFIG_CACHE_SIZE_MB"),+ ]++ for key, expected_env_var in expected_mappings:+ actual = registry.get_env_var(key)+ assert actual == expected_env_var, (+ f"Backward compatibility broken for {key}"+ )diff --git a/tests/settings/env_vars/test_env_var_usage.py b/tests/settings/env_vars/test_env_var_usage.pynew file mode 100755index 0000000000..5c651540a7--- /dev/null+++ b/tests/settings/env_vars/test_env_var_usage.py@@ -0,0 +1,342 @@+#!/usr/bin/env python3+"""+Test that environment variables are accessed correctly throughout the codebase.+This validates that all env var access goes through SettingsManager where appropriate.+"""++import ast+import sys+from pathlib import Path+from typing import List, Tuple++# Make pytest optional for standalone execution+try:+ import pytest+except ImportError:+ pytest = None++# Add src to path to import settings+sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent / "src"))++from local_deep_research.settings.manager import SettingsManager+from local_deep_research.settings.env_registry import registry as env_registry+++# Get all registered environment variables+ALL_ENV_VARS = set(env_registry.get_all_env_vars().keys())+BOOTSTRAP_VARS = set(SettingsManager.get_bootstrap_env_vars().keys())+++# Files/patterns where direct os.environ access is allowed+ALLOWED_PATTERNS = {+ # Configuration and settings modules+ "settings/",+ "config/",+ "setup.py",+ # Test files+ "test_",+ "_test.py",+ "tests/",+ # Scripts and utilities+ "scripts/",+ "utils/",+ "cli.py",+ ".pre-commit-hooks/",+ # Example scripts+ "examples/",+ # Specific modules that need direct access+ "log_utils.py",+ "paths.py",+ "queue_config.py",+ "server_config.py",+ "memory_cache/",+ # Database and migrations+ "alembic/",+ "migrations/",+ "encrypted_db.py",+ "sqlcipher_utils.py",+}++# System environment variables that are always allowed+SYSTEM_VARS = {+ "PATH",+ "HOME",+ "USER",+ "PYTHONPATH",+ "TMPDIR",+ "TEMP",+ "PWD",+ "SHELL",+ "TERM",+ "LANG",+ "LC_ALL",+ "TZ",+ "DEBUG",+ "CI",+ "GITHUB_ACTIONS",+ "TESTING", # External testing flag+ "DOCKER_CONTAINER",+}+++class EnvVarChecker(ast.NodeVisitor):+ def __init__(self, filename: str):+ self.filename = filename+ self.errors = []+ self.has_settings_manager_import = False++ def visit_ImportFrom(self, node):+ if node.module and "settings" in node.module.lower():+ for alias in node.names:+ if "SettingsManager" in (alias.name or ""):+ self.has_settings_manager_import = True+ self.generic_visit(node)++ def visit_Call(self, node):+ # Check for os.environ.get() or os.getenv()+ is_environ_get = False+ env_var_name = None++ # Pattern 1: os.environ.get("VAR_NAME")+ if (+ isinstance(node.func, ast.Attribute)+ and node.func.attr == "get"+ and isinstance(node.func.value, ast.Attribute)+ and node.func.value.attr == "environ"+ and isinstance(node.func.value.value, ast.Name)+ and node.func.value.value.id == "os"+ ):+ is_environ_get = True+ if node.args and isinstance(node.args[0], ast.Constant):+ env_var_name = node.args[0].value++ # Pattern 2: os.getenv("VAR_NAME")+ elif (+ isinstance(node.func, ast.Attribute)+ and node.func.attr == "getenv"+ and isinstance(node.func.value, ast.Name)+ and node.func.value.id == "os"+ ):+ is_environ_get = True+ if node.args and isinstance(node.args[0], ast.Constant):+ env_var_name = node.args[0].value++ if is_environ_get and env_var_name:+ self._check_env_var_usage(node.lineno, env_var_name)++ self.generic_visit(node)++ def visit_Subscript(self, node):+ # Check for os.environ["VAR_NAME"] pattern+ if (+ isinstance(node.value, ast.Attribute)+ and node.value.attr == "environ"+ and isinstance(node.value.value, ast.Name)+ and node.value.value.id == "os"+ and isinstance(node.slice, ast.Constant)+ ):+ env_var_name = node.slice.value+ self._check_env_var_usage(node.lineno, env_var_name)++ self.generic_visit(node)++ def _check_env_var_usage(self, line_num: int, env_var_name: str):+ """Check if this environment variable usage is allowed."""+ # Always allow system vars+ if env_var_name in SYSTEM_VARS:+ return++ # Always allow registered vars in allowed files+ if env_var_name in ALL_ENV_VARS or env_var_name in BOOTSTRAP_VARS:+ if self._is_file_allowed():+ return++ # Check if file is allowed to use os.environ+ if not self._is_file_allowed():+ # For registered LDR vars, provide specific guidance+ if env_var_name in ALL_ENV_VARS or env_var_name in BOOTSTRAP_VARS:+ # Find the setting key for this env var+ setting_key = self._find_setting_key(env_var_name)+ if setting_key:+ self.errors.append(+ (+ line_num,+ f"Environment variable '{env_var_name}' should be accessed via "+ f"SettingsManager.get_setting('{setting_key}')",+ )+ )+ else:+ self.errors.append(+ (+ line_num,+ f"Registered environment variable '{env_var_name}' should be accessed through SettingsManager",+ )+ )+ # For unregistered LDR vars, flag as potential issue+ elif env_var_name.startswith("LDR_"):+ self.errors.append(+ (+ line_num,+ f"Unregistered LDR environment variable '{env_var_name}' - should this be added to settings?",+ )+ )+ # For other vars, suggest evaluation+ else:+ self.errors.append(+ (+ line_num,+ f"Direct access to environment variable '{env_var_name}' - consider if this should use SettingsManager",+ )+ )++ def _is_file_allowed(self) -> bool:+ """Check if this file is allowed to use os.environ directly."""+ for pattern in ALLOWED_PATTERNS:+ if pattern in self.filename:+ return True+ return False++ def _find_setting_key(self, env_var_name: str) -> str:+ """Find the setting key for a given environment variable."""+ try:+ # Check all registered settings+ for setting_key in env_registry.list_all_settings():+ if env_registry.get_env_var(setting_key) == env_var_name:+ return setting_key+ except:+ pass+ return ""+++def check_file(filepath: Path) -> List[Tuple[int, str]]:+ """Check a single Python file for environment variable issues."""+ try:+ content = filepath.read_text(encoding="utf-8")+ except Exception as e:+ print(f"Error reading {filepath}: {e}")+ return []++ try:+ tree = ast.parse(content, str(filepath))+ checker = EnvVarChecker(str(filepath))+ checker.visit(tree)+ return checker.errors+ except SyntaxError:+ # Skip files with syntax errors+ return []+ except Exception as e:+ print(f"Error parsing {filepath}: {e}")+ return []+++class TestEnvironmentVariableUsage:+ """Test that environment variables are accessed correctly in the codebase."""++ def all_python_files(self):+ """Get all Python files in the repository."""+ repo_root = Path(__file__).parent.parent.parent.parent+ python_files = []++ for py_file in repo_root.rglob("*.py"):+ # Skip virtual environments and build directories+ if any(+ part in py_file.parts+ for part in [+ ".venv",+ "venv",+ "build",+ "dist",+ "__pycache__",+ ".git",+ ]+ ):+ continue+ python_files.append(py_file)++ return python_files++ def test_env_vars_loaded(self):+ """Test that we successfully loaded env var definitions."""+ assert len(ALL_ENV_VARS) > 0, (+ "No environment variables loaded from registry"+ )+ assert len(BOOTSTRAP_VARS) > 0, "No bootstrap variables loaded"+ print(f"✓ Loaded {len(ALL_ENV_VARS)} registered environment variables")+ print(f"✓ Loaded {len(BOOTSTRAP_VARS)} bootstrap environment variables")++ def test_no_invalid_env_var_access(self, all_python_files=None):+ """Test that no files have invalid direct environment variable access."""+ # If not provided (when running without pytest), get the files+ if all_python_files is None:+ all_python_files = self.all_python_files()++ all_errors = []+ files_checked = 0++ for py_file in all_python_files:+ files_checked += 1+ errors = check_file(py_file)+ if errors:+ all_errors.append((py_file, errors))++ print(f"\n📊 Checked {files_checked} Python files")++ if all_errors:+ # Format error message+ repo_root = Path(__file__).parent.parent.parent.parent+ error_msg = [+ f"\n❌ Found environment variable issues in {len(all_errors)} files:\n"+ ]++ for filepath, errors in all_errors:+ rel_path = filepath.relative_to(repo_root)+ error_msg.append(f"\n{rel_path}:")+ for line_num, error in errors:+ error_msg.append(f" Line {line_num}: {error}")++ error_msg.append("\n📚 Guidelines:")+ error_msg.append(+ "1. Use SettingsManager.get_setting() for application settings"+ )+ error_msg.append("2. Direct os.environ access is only allowed in:")+ error_msg.append(" - Configuration/settings modules")+ error_msg.append(" - Test files")+ error_msg.append(" - Database initialization modules")+ error_msg.append(+ "3. All LDR_ environment variables should be registered in settings"+ )++ error_message = "\n".join(error_msg)+ # Use pytest.fail if available, otherwise raise AssertionError+ try:+ import pytest++ pytest.fail(error_message)+ except ImportError:+ raise AssertionError(error_message)+ else:+ print("✅ All environment variable usage is compliant!")+++if __name__ == "__main__":+ # Allow running as a standalone script (for CI without full pytest deps)+ import sys++ if pytest:+ # Run with pytest if available+ sys.exit(pytest.main([__file__, "-v"]))+ else:+ # Run without pytest+ print("Running validation without pytest...")+ test = TestEnvironmentVariableUsage()++ # Load env vars+ test.test_env_vars_loaded()++ # Run validation+ try:+ test.test_no_invalid_env_var_access()+ sys.exit(0)+ except AssertionError as e:+ print(str(e))+ sys.exit(1)diff --git a/tests/settings/test_env_settings.py b/tests/settings/test_env_settings.pynew file mode 100644index 0000000000..4f7bc3d11e--- /dev/null+++ b/tests/settings/test_env_settings.py@@ -0,0 +1,315 @@+"""Test suite for the environment settings system."""++import os+import pytest++from local_deep_research.settings.env_registry import (+ registry,+ get_env_setting,+ is_test_mode,+ use_fallback_llm,+ is_ci_environment,+)+from local_deep_research.settings.manager import SettingsManager+++class TestEnvRegistry:+ """Test the environment registry functionality."""++ @pytest.fixture(autouse=True)+ def clean_env(self):+ """Clean environment before each test."""+ # Store original env vars+ original_env = {+ k: v+ for k, v in os.environ.items()+ if k.startswith("LDR_") or k in ["CI", "TESTING"]+ }++ # Clean env vars+ for key in list(os.environ.keys()):+ if key.startswith("LDR_") or key in ["CI", "TESTING"]:+ os.environ.pop(key, None)++ yield++ # Restore original env vars+ for key in list(os.environ.keys()):+ if key.startswith("LDR_") or key in ["CI", "TESTING"]:+ os.environ.pop(key, None)+ for key, value in original_env.items():+ os.environ[key] = value++ def test_registry_has_settings(self):+ """Test that registry has settings registered."""+ all_settings = registry.list_all_settings()+ assert len(all_settings) > 0, "Registry should have settings"+ assert "testing.test_mode" in all_settings+ assert "testing.use_fallback_llm" in all_settings+ assert "bootstrap.encryption_key" in all_settings+ assert "db_config.cache_size_mb" in all_settings++ def test_categories(self):+ """Test that all categories have settings."""+ categories = ["testing", "bootstrap", "db_config"]+ for cat in categories:+ settings = registry.get_category_settings(cat)+ assert len(settings) > 0, f"Category '{cat}' should have settings"++ def test_boolean_setting(self):+ """Test boolean setting conversion."""+ # Test various true values+ for value in [+ "true",+ "True",+ "TRUE",+ "1",+ "yes",+ "YES",+ "on",+ "enabled",+ ]:+ os.environ["LDR_TESTING_TEST_MODE"] = value+ assert is_test_mode(), f"'{value}' should be True"++ # Test various false values+ for value in ["false", "False", "FALSE", "0", "no", "NO", "off", ""]:+ os.environ["LDR_TESTING_TEST_MODE"] = value+ assert not is_test_mode(), f"'{value}' should be False"++ def test_fallback_llm_setting(self):+ """Test fallback LLM setting with defaults."""+ # Test default value when not set+ assert not use_fallback_llm()++ os.environ["LDR_TESTING_USE_FALLBACK_LLM"] = "1"+ assert use_fallback_llm()++ os.environ["LDR_TESTING_USE_FALLBACK_LLM"] = "yes"+ assert use_fallback_llm()++ os.environ.pop("LDR_TESTING_USE_FALLBACK_LLM")+ assert not use_fallback_llm()++ def test_ci_environment(self):+ """Test CI environment detection."""+ assert not is_ci_environment()++ os.environ["CI"] = "true"+ assert is_ci_environment()++ os.environ["CI"] = "false"+ assert not is_ci_environment()++ def test_integer_setting(self):+ """Test integer setting conversion and validation."""+ os.environ["LDR_DB_CONFIG_CACHE_SIZE_MB"] = "512"+ cache_size = get_env_setting("db_config.cache_size_mb")+ assert cache_size == 512++ # Test invalid integer returns default+ os.environ["LDR_DB_CONFIG_CACHE_SIZE_MB"] = "invalid"+ cache_size = get_env_setting("db_config.cache_size_mb", 100)+ assert cache_size == 100++ # Test when not set uses default from setting definition+ os.environ.pop("LDR_DB_CONFIG_CACHE_SIZE_MB", None)+ cache_size = get_env_setting("db_config.cache_size_mb")+ assert cache_size == 100 # Default from db_config.py++ def test_enum_setting(self):+ """Test enum setting with case-insensitive matching."""+ # Test lowercase input returns canonical form+ os.environ["LDR_DB_CONFIG_JOURNAL_MODE"] = "wal"+ journal_mode = get_env_setting("db_config.journal_mode")+ assert journal_mode == "WAL"++ os.environ["LDR_DB_CONFIG_JOURNAL_MODE"] = "TRUNCATE"+ journal_mode = get_env_setting("db_config.journal_mode")+ assert journal_mode == "TRUNCATE"++ # Test default when not set+ os.environ.pop("LDR_DB_CONFIG_JOURNAL_MODE", None)+ journal_mode = get_env_setting("db_config.journal_mode")+ assert journal_mode == "WAL" # Default value++ def test_path_setting(self):+ """Test path setting expansion."""+ test_path = "/tmp/test_ldr_path"+ os.environ["LDR_BOOTSTRAP_DATA_DIR"] = test_path+ data_dir = get_env_setting("bootstrap.data_dir")+ assert data_dir == test_path++ # Test home expansion+ os.environ["LDR_BOOTSTRAP_DATA_DIR"] = "~/test_path"+ data_dir = get_env_setting("bootstrap.data_dir")+ assert data_dir.startswith(os.path.expanduser("~"))+ assert "test_path" in data_dir++ def test_secret_setting(self):+ """Test secret setting hides values."""+ os.environ["LDR_BOOTSTRAP_ENCRYPTION_KEY"] = "secret_key_123"+ setting_obj = registry.get_setting_object("bootstrap.encryption_key")++ # Value should be hidden in string representation+ assert "secret_key_123" not in str(setting_obj)+ assert "SET" in str(setting_obj)++ # But value should still be retrievable+ value = get_env_setting("bootstrap.encryption_key")+ assert value == "secret_key_123"+++class TestSettingsManagerIntegration:+ """Test SettingsManager integration with env settings."""++ @pytest.fixture(autouse=True)+ def clean_env(self):+ """Clean environment before each test."""+ original_env = {+ k: v for k, v in os.environ.items() if k.startswith("LDR_")+ }+ for key in list(os.environ.keys()):+ if key.startswith("LDR_"):+ os.environ.pop(key, None)+ yield+ for key in list(os.environ.keys()):+ if key.startswith("LDR_"):+ os.environ.pop(key, None)+ for key, value in original_env.items():+ os.environ[key] = value++ def test_get_env_only_setting(self):+ """Test getting env-only settings through SettingsManager."""+ sm = SettingsManager(db_session=None)++ os.environ["LDR_TESTING_TEST_MODE"] = "true"+ test_mode = sm.get_setting("testing.test_mode")+ assert test_mode++ # Test with default when env var not set+ result = sm.get_setting("testing.use_fallback_llm", default=True)+ assert (+ not result+ ) # Env setting default (False) overrides our param default++ os.environ["LDR_TESTING_USE_FALLBACK_LLM"] = "false"+ result = sm.get_setting("testing.use_fallback_llm", default=True)+ assert not result # Env var overrides default++ def test_is_env_only_setting(self):+ """Test checking if a setting is env-only."""+ sm = SettingsManager(db_session=None)++ # These should be env-only+ assert sm.is_env_only_setting("testing.test_mode")+ assert sm.is_env_only_setting("testing.use_fallback_llm")+ assert sm.is_env_only_setting("bootstrap.encryption_key")+ assert sm.is_env_only_setting("db_config.cache_size_mb")++ # These should NOT be env-only (regular settings)+ assert not sm.is_env_only_setting("app.debug")+ assert not sm.is_env_only_setting("llm.provider")+ assert not sm.is_env_only_setting("search.max_concurrent")++ def test_get_bootstrap_vars(self):+ """Test getting bootstrap environment variables."""+ sm = SettingsManager(db_session=None)++ bootstrap_vars = sm.get_bootstrap_env_vars()++ # Should include bootstrap settings+ assert "LDR_BOOTSTRAP_ENCRYPTION_KEY" in bootstrap_vars+ assert "LDR_BOOTSTRAP_DATA_DIR" in bootstrap_vars+ assert "LDR_BOOTSTRAP_CONFIG_DIR" in bootstrap_vars++ # Should include db_config settings+ assert "LDR_DB_CONFIG_CACHE_SIZE_MB" in bootstrap_vars+ assert "LDR_DB_CONFIG_JOURNAL_MODE" in bootstrap_vars++ # Should have a reasonable number of vars+ assert len(bootstrap_vars) >= 10++ def test_is_bootstrap_env_var(self):+ """Test checking if an env var is a bootstrap variable."""+ sm = SettingsManager(db_session=None)++ # Bootstrap vars+ assert sm.is_bootstrap_env_var("LDR_BOOTSTRAP_ENCRYPTION_KEY")+ assert sm.is_bootstrap_env_var("LDR_DB_CONFIG_PAGE_SIZE")+ assert sm.is_bootstrap_env_var("LDR_BOOTSTRAP_DATA_DIR")++ # Testing vars are in ALL_ENV_ONLY_VARS but not specifically bootstrap+ # They are allowed by the pre-commit hook but not considered bootstrap vars+ assert not sm.is_bootstrap_env_var("LDR_TESTING_TEST_MODE")+ assert not sm.is_bootstrap_env_var("LDR_TESTING_USE_FALLBACK_LLM")++ # Non-existent var+ assert not sm.is_bootstrap_env_var("RANDOM_VAR")+ assert not sm.is_bootstrap_env_var("SOME_OTHER_VAR")+++class TestEnvVarMapping:+ """Test environment variable name mapping."""++ def test_get_env_var_for_setting(self):+ """Test getting env var name for a setting."""+ assert (+ registry.get_env_var("testing.test_mode") == "LDR_TESTING_TEST_MODE"+ )+ assert (+ registry.get_env_var("testing.use_fallback_llm")+ == "LDR_TESTING_USE_FALLBACK_LLM"+ )+ assert (+ registry.get_env_var("bootstrap.encryption_key")+ == "LDR_BOOTSTRAP_ENCRYPTION_KEY"+ )+ assert (+ registry.get_env_var("db_config.cache_size_mb")+ == "LDR_DB_CONFIG_CACHE_SIZE_MB"+ )+ assert registry.get_env_var("nonexistent.setting") is None++ def test_get_all_env_vars(self):+ """Test getting all environment variables."""+ all_env_vars = registry.get_all_env_vars()++ # Should have a reasonable number+ assert len(all_env_vars) >= 15++ # Should include key variables+ assert "LDR_TESTING_TEST_MODE" in all_env_vars+ assert "LDR_TESTING_USE_FALLBACK_LLM" in all_env_vars+ assert "LDR_BOOTSTRAP_ENCRYPTION_KEY" in all_env_vars+ # CI and TESTING are external vars, not in registry anymore++ def test_category_specific_vars(self):+ """Test getting category-specific environment variables."""+ # Testing vars+ testing_vars = registry.get_testing_vars()+ assert (+ len(testing_vars) >= 2+ ) # We only have test_mode and use_fallback_llm now+ assert "LDR_TESTING_TEST_MODE" in testing_vars+ assert "LDR_TESTING_USE_FALLBACK_LLM" in testing_vars+ # CI and TESTING are now external vars, not in the registry++ # Bootstrap vars (includes db_config)+ bootstrap_vars = registry.get_bootstrap_vars()+ assert len(bootstrap_vars) >= 10+ assert "LDR_BOOTSTRAP_ENCRYPTION_KEY" in bootstrap_vars+ assert "LDR_BOOTSTRAP_DATA_DIR" in bootstrap_vars+ assert "LDR_DB_CONFIG_CACHE_SIZE_MB" in bootstrap_vars+ assert "LDR_DB_CONFIG_JOURNAL_MODE" in bootstrap_vars++ def test_is_env_only(self):+ """Test checking if a setting is env-only."""+ # These should be env-only+ assert registry.is_env_only("testing.test_mode")+ assert registry.is_env_only("bootstrap.encryption_key")+ assert registry.is_env_only("db_config.cache_size_mb")++ # These should not exist in env registry+ assert not registry.is_env_only("app.debug")+ assert not registry.is_env_only("nonexistent.setting")