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
+3 -5
View File
@@ -13,7 +13,7 @@ from rich.live import Live
from rich.panel import Panel
from rich.text import Text
from strix.config import Config
from strix.config import load_settings
from strix.entry import run_strix_scan
from strix.runtime import session_manager
from strix.telemetry.tracer import Tracer, set_global_tracer
@@ -25,12 +25,12 @@ from .utils import (
def _resolve_sandbox_image() -> str:
image = Config.get("strix_image")
image = load_settings().runtime.image
if not image:
raise RuntimeError(
"strix_image is not configured. Set it in ~/.strix/cli-config.json.",
)
return str(image)
return image
def _resolve_sources_path(args: Any) -> Path:
@@ -99,7 +99,6 @@ async def run_cli(args: Any) -> None: # noqa: PLR0915
console.print()
scan_mode = getattr(args, "scan_mode", "deep")
is_whitebox = bool(getattr(args, "local_sources", []))
scan_config: dict[str, Any] = {
"scan_id": args.run_name,
@@ -108,7 +107,6 @@ async def run_cli(args: Any) -> None: # noqa: PLR0915
"run_name": args.run_name,
"diff_scope": getattr(args, "diff_scope", {"active": False}),
"scan_mode": scan_mode,
"is_whitebox": is_whitebox,
}
tracer = Tracer(args.run_name)
+30 -65
View File
@@ -6,7 +6,6 @@ Strix Agent Interface
import argparse
import asyncio
import logging
import os
import shutil
import sys
from pathlib import Path
@@ -18,15 +17,10 @@ from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from strix.config import Config, apply_saved_config, save_current_config
from strix.config.config import resolve_llm_config
apply_saved_config()
from strix.interface.cli import run_cli # noqa: E402
from strix.interface.tui import run_tui # noqa: E402
from strix.interface.utils import ( # noqa: E402
from strix.config import apply_config_override, load_settings, persist_current
from strix.interface.cli import run_cli
from strix.interface.tui import run_tui
from strix.interface.utils import (
assign_workspace_subdirs,
build_final_stats_text,
check_docker_connection,
@@ -35,17 +29,18 @@ from strix.interface.utils import ( # noqa: E402
generate_run_name,
image_exists,
infer_target_type,
is_whitebox_scan,
process_pull_line,
resolve_diff_scope_context,
rewrite_localhost_targets,
validate_config_file,
validate_llm_response,
)
from strix.telemetry import posthog
from strix.telemetry.tracer import get_global_tracer
HOST_GATEWAY_HOSTNAME = "host.docker.internal"
from strix.telemetry import posthog # noqa: E402
from strix.telemetry.tracer import get_global_tracer # noqa: E402
logging.getLogger().setLevel(logging.ERROR)
@@ -56,31 +51,20 @@ def validate_environment() -> None:
missing_required_vars = []
missing_optional_vars = []
strix_llm = Config.get("strix_llm")
if not strix_llm:
settings = load_settings()
if not settings.llm.model:
missing_required_vars.append("STRIX_LLM")
has_base_url = any(
[
Config.get("llm_api_base"),
Config.get("openai_api_base"),
Config.get("litellm_base_url"),
Config.get("ollama_api_base"),
]
)
if not Config.get("llm_api_key"):
if not settings.llm.api_key:
missing_optional_vars.append("LLM_API_KEY")
if not has_base_url:
if not settings.llm.api_base:
missing_optional_vars.append("LLM_API_BASE")
if not Config.get("perplexity_api_key"):
if not settings.integrations.perplexity_api_key:
missing_optional_vars.append("PERPLEXITY_API_KEY")
if not Config.get("strix_reasoning_effort"):
missing_optional_vars.append("STRIX_REASONING_EFFORT")
if missing_required_vars:
error_text = Text()
error_text.append("MISSING REQUIRED ENVIRONMENT VARIABLES", style="bold red")
@@ -207,25 +191,22 @@ async def warm_up_llm() -> None:
console = Console()
try:
model_name, api_key, api_base = resolve_llm_config()
litellm_model: str | None = model_name
llm = load_settings().llm
test_messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Reply with just 'OK'."},
]
llm_timeout = int(Config.get("llm_timeout") or "300")
completion_kwargs: dict[str, Any] = {
"model": litellm_model,
"model": llm.model,
"messages": test_messages,
"timeout": llm_timeout,
"timeout": llm.timeout,
}
if api_key:
completion_kwargs["api_key"] = api_key
if api_base:
completion_kwargs["api_base"] = api_base
if llm.api_key:
completion_kwargs["api_key"] = llm.api_key
if llm.api_base:
completion_kwargs["api_base"] = llm.api_base
response = litellm.completion(**completion_kwargs)
@@ -486,11 +467,13 @@ def pull_docker_image() -> None:
console = Console()
client = check_docker_connection()
if image_exists(client, Config.get("strix_image")): # type: ignore[arg-type]
image = load_settings().runtime.image
if image_exists(client, image):
return
console.print()
console.print(f"[dim]Pulling image[/] {Config.get('strix_image')}")
console.print(f"[dim]Pulling image[/] {image}")
console.print("[dim yellow]This only happens on first run and may take a few minutes...[/]")
console.print()
@@ -499,7 +482,7 @@ def pull_docker_image() -> None:
layers_info: dict[str, str] = {}
last_update = ""
for line in client.api.pull(Config.get("strix_image"), stream=True, decode=True):
for line in client.api.pull(image, stream=True, decode=True):
last_update = process_pull_line(line, layers_info, status, last_update)
except DockerException as e:
@@ -507,7 +490,7 @@ def pull_docker_image() -> None:
error_text = Text()
error_text.append("FAILED TO PULL IMAGE", style="bold red")
error_text.append("\n\n", style="white")
error_text.append(f"Could not download: {Config.get('strix_image')}\n", style="white")
error_text.append(f"Could not download: {image}\n", style="white")
error_text.append(str(e), style="dim red")
panel = Panel(
@@ -526,22 +509,6 @@ def pull_docker_image() -> None:
console.print()
def apply_config_override(config_path: str) -> None:
# Clear env vars that were automatically applied from the default config file
# so they don't leak into the custom config context.
for var_name in Config._applied_from_default:
os.environ.pop(var_name, None)
Config._applied_from_default = {}
Config._config_file_override = validate_config_file(config_path)
apply_saved_config(force=True)
def persist_config() -> None:
if Config._config_file_override is None:
save_current_config()
def main() -> None:
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
@@ -549,7 +516,7 @@ def main() -> None:
args = parse_arguments()
if args.config:
apply_config_override(args.config)
apply_config_override(validate_config_file(args.config))
check_docker_installed()
pull_docker_image()
@@ -557,7 +524,7 @@ def main() -> None:
validate_environment()
asyncio.run(warm_up_llm())
persist_config()
persist_current()
args.run_name = generate_run_name(args.targets_info)
@@ -602,12 +569,10 @@ def main() -> None:
else:
args.instruction = diff_scope.instruction_block
is_whitebox = bool(args.local_sources)
posthog.start(
model=Config.get("strix_llm"),
model=load_settings().llm.model,
scan_mode=args.scan_mode,
is_whitebox=is_whitebox,
is_whitebox=is_whitebox_scan(args.targets_info),
interactive=not args.non_interactive,
has_instructions=bool(args.instruction),
)
+2 -3
View File
@@ -31,7 +31,7 @@ from textual.screen import ModalScreen
from textual.widgets import Button, Label, Static, TextArea, Tree
from textual.widgets.tree import TreeNode
from strix.config import Config
from strix.config import load_settings
from strix.entry import run_strix_scan
from strix.interface.tool_components.agent_message_renderer import AgentMessageRenderer
from strix.interface.tool_components.registry import get_tool_renderer
@@ -763,7 +763,6 @@ class StrixTUIApp(App): # type: ignore[misc]
"run_name": args.run_name,
"diff_scope": getattr(args, "diff_scope", {"active": False}),
"scan_mode": getattr(args, "scan_mode", "deep"),
"is_whitebox": bool(getattr(args, "local_sources", [])),
}
def _setup_cleanup_handlers(self) -> None:
@@ -1408,7 +1407,7 @@ class StrixTUIApp(App): # type: ignore[misc]
try:
if not self._scan_stop_event.is_set():
image = Config.get("strix_image") or "strix-sandbox:latest"
image = load_settings().runtime.image or "strix-sandbox:latest"
sources_path = self._resolve_sources_path()
loop.run_until_complete(
run_strix_scan(
+8 -3
View File
@@ -20,7 +20,7 @@ from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from strix.config import Config
from strix.config import load_settings
# Token formatting utilities
@@ -304,7 +304,7 @@ def build_live_stats_text(tracer: Any) -> Text:
if not tracer:
return stats_text
model = Config.get("strix_llm") or "unknown"
model = load_settings().llm.model or "unknown"
stats_text.append("Model ", style="dim")
stats_text.append(str(model), style="white")
stats_text.append("\n")
@@ -375,7 +375,7 @@ def build_tui_stats_text(tracer: Any) -> Text:
if not tracer:
return stats_text
model = Config.get("strix_llm") or "unknown"
model = load_settings().llm.model or "unknown"
stats_text.append(str(model), style="white")
llm_stats = tracer.get_total_llm_stats()
@@ -1190,6 +1190,11 @@ def assign_workspace_subdirs(targets_info: list[dict[str, Any]]) -> None:
details["workspace_subdir"] = workspace_subdir
def is_whitebox_scan(targets_info: list[dict[str, Any]]) -> bool:
"""True iff any target is a local source tree (whitebox / source-aware)."""
return any(t.get("type") == "local_code" for t in targets_info or [])
def collect_local_sources(targets_info: list[dict[str, Any]]) -> list[dict[str, str]]:
local_sources: list[dict[str, str]] = []