refactor(config): pydantic-settings revamp + drop `is_whitebox` plumbing

Replaces 200+ lines of bespoke env-loader / persist / change-detection
machinery with ``pydantic_settings.BaseSettings`` (already a transitive
of ``openai-agents → mcp``, no new direct dep).

What was wrong with ``Config``:

- 14 knobs flat in one namespace, weak grouping by comment-block.
- ``Config._applied_from_default`` and ``Config._config_file_override``
  were externally mutated from ``interface/main.py:532-534``. Private
  members were part of the public contract.
- Stringly-typed values: every caller had to coerce
  (``int(Config.get("llm_timeout") or "300")``,
  ``... not in {"0", "false", "no", "off"}``).
- Dead knob: ``strix_llm_max_retries`` declared, persisted, listed in
  ``_LLM_CANONICAL_NAMES`` — zero readers (``DEFAULT_RETRY``
  hardcodes ``max_retries=5``). Dropped.
- ``_LLM_CANONICAL_NAMES`` tuple maintained alongside class vars —
  duplicate source of truth.
- ``_tracked_names()`` introspected ``vars(cls).items()`` filtered on
  ``(v is None or isinstance(v, str))`` — fragile.
- Awkward path: ``strix/config/config.py`` inside ``strix/config/``
  with ``__init__.py`` just re-exporting.
- Dual access for the same fact: ``web_search`` read
  ``os.getenv("PERPLEXITY_API_KEY")`` while ``main.py`` read
  ``Config.get("perplexity_api_key")``.

New shape:

- ``strix/config/settings.py`` — typed dataclass tree:
  ``Settings.{llm,runtime,telemetry,integrations}``. Each sub-model is
  its own ``BaseSettings`` so it reads env independently. Field-level
  ``alias=`` and ``validation_alias=AliasChoices(...)`` mirror the
  existing flat env-var names — user-facing env contract is unchanged.
  Bool fields auto-parse ``"0"``/``"false"``/``"no"``/``"off"``;
  int fields auto-coerce.
- ``strix/config/loader.py`` — thin ``load_settings()``,
  ``apply_config_override(path)``, ``persist_current()`` with module
  cache. JSON file reader walks aliases to populate sub-models, dropping
  entries already covered by env (so env still wins).
- 13 callsites migrated from ``Config.get("...")`` to
  ``load_settings().<group>.<field>``.
- ``posthog._is_enabled()`` collapses to one line.
- ``--config <path>`` flow simplified: one
  ``apply_config_override(...)`` call replaces three lines of
  class-private mutation.

Drive-by — drop ``is_whitebox`` from ``scan_config`` dict:

- It was being derived as ``bool(args.local_sources)`` in three places
  (``cli.py``, ``tui.py``, ``main.py``) and stuffed into the dict for
  ``entry.py`` to read back. The fact is fully derivable from
  ``scan_config["targets"]`` — any target with ``type == "local_code"``.
- New helper ``is_whitebox_scan(targets)`` in ``interface/utils.py``
  alongside the other target-classification utilities.
- ``entry.py`` computes once; ``main.py``'s posthog start uses the same
  helper. Triplicate derivation gone.

Verified: ruff at baseline (3), mypy at baseline (69). Six smoke tests
pass — defaults / JSON-only / env-wins-over-JSON / alias-chain
fallback / bool parsing / ``is_whitebox_scan``.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
0xallam
2026-04-25 16:05:40 -07:00
co-authored by Claude Opus 4.7
parent 346cc477a7
commit 1e641e56ce
15 changed files with 317 additions and 308 deletions
+100
View File
@@ -0,0 +1,100 @@
"""Strix application settings — pydantic-settings powered.
Three sources, env-precedence-first:
1. Environment variables (``STRIX_LLM``, ``LLM_API_KEY``, etc.) — highest.
2. ``~/.strix/cli-config.json`` (or ``--config <path>``) — middle.
3. Field defaults — lowest.
Bool fields auto-parse ``"0"``/``"false"``/``"no"``/``"off"`` as falsy
and any other non-empty string as truthy. Int fields auto-coerce from
string env. The ``api_base`` field walks an alias chain so users can
point at any OpenAI-compatible endpoint via whichever env name they
prefer (``LLM_API_BASE`` / ``OPENAI_API_BASE`` / ``LITELLM_BASE_URL`` /
``OLLAMA_API_BASE``).
Each sub-model is a :class:`BaseSettings` so it reads env independently
— the alternative (one mega-BaseSettings with flat fields) would lose
the logical grouping ``s.llm.model`` / ``s.runtime.image`` / etc.
"""
from __future__ import annotations
from typing import Literal
from pydantic import AliasChoices, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
ReasoningEffort = Literal["low", "medium", "high"]
_BASE_CONFIG = SettingsConfigDict(
case_sensitive=False,
populate_by_name=True,
extra="ignore",
)
class LlmSettings(BaseSettings):
"""LLM provider + model + per-call defaults."""
model_config = _BASE_CONFIG
model: str | None = Field(default=None, alias="STRIX_LLM")
api_key: str | None = Field(default=None, alias="LLM_API_KEY")
api_base: str | None = Field(
default=None,
validation_alias=AliasChoices(
"LLM_API_BASE",
"OPENAI_API_BASE",
"LITELLM_BASE_URL",
"OLLAMA_API_BASE",
),
)
reasoning_effort: ReasoningEffort = Field(default="high", alias="STRIX_REASONING_EFFORT")
timeout: int = Field(default=300, alias="LLM_TIMEOUT")
class RuntimeSettings(BaseSettings):
"""Sandbox image + backend selector."""
model_config = _BASE_CONFIG
image: str = Field(
default="ghcr.io/usestrix/strix-sandbox:0.1.13",
alias="STRIX_IMAGE",
)
backend: str = Field(default="docker", alias="STRIX_RUNTIME_BACKEND")
class TelemetrySettings(BaseSettings):
"""Telemetry toggles. ``posthog`` is None → inherit ``master``."""
model_config = _BASE_CONFIG
master: bool = Field(default=True, alias="STRIX_TELEMETRY")
posthog: bool | None = Field(default=None, alias="STRIX_POSTHOG_TELEMETRY")
@property
def posthog_enabled(self) -> bool:
"""Effective PostHog toggle: explicit value if set, else ``master``."""
return self.master if self.posthog is None else self.posthog
class IntegrationSettings(BaseSettings):
"""Third-party integration credentials."""
model_config = _BASE_CONFIG
perplexity_api_key: str | None = Field(default=None, alias="PERPLEXITY_API_KEY")
class Settings(BaseSettings):
"""Composite Strix settings. Instantiate via :func:`strix.config.load_settings`."""
model_config = _BASE_CONFIG
llm: LlmSettings = Field(default_factory=LlmSettings)
runtime: RuntimeSettings = Field(default_factory=RuntimeSettings)
telemetry: TelemetrySettings = Field(default_factory=TelemetrySettings)
integrations: IntegrationSettings = Field(default_factory=IntegrationSettings)