Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
fix(logs): keep console_print_target on stdout (#934)
Louis Choquel4b5519f068f0
diff --git a/.pipelex/pipelex.toml b/.pipelex/pipelex.tomlindex 0057c498e..a7bfd34ca 100644--- a/.pipelex/pipelex.toml+++ b/.pipelex/pipelex.toml@@ -161,7 +161,17 @@ default_directory_base_name = "pipeline"# Default logging level: "DEBUG", "INFO", "WARNING", "ERROR"default_log_level = "INFO"# Log output target: "stdout" or "stderr"-console_log_target = "stdout"+# console_log_target controls the RichHandler used by the logging system (log.debug/info/...).+# Logs are diagnostics → stderr.+console_log_target = "stderr"+# console_print_target controls the Console returned by get_console(), used for banners,+# deck notices, and the main `pipelex` CLI's data tables (`show backends`, `show models`,+# `which`, `doctor`). Tables are data the user pipes to a file → stdout.+# Note: the agent CLI (`pipelex-agent`) emits its actual JSON/markdown results via bare+# builtin `print(...)` to sys.stdout, bypassing Rich entirely — so this knob does NOT+# affect the agent CLI data channel. The agent CLI factory additionally forces both+# targets to stderr internally to keep its stdout strictly reserved for the success+# envelope.console_print_target = "stdout"[pipelex.log_config.package_log_levels]diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 885385ad5..bcbec570b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,13 @@# Changelog+## [Unreleased]++### Fixed++- **`console_log_target` package default is now `stderr` (was `stdout`).** Logs now stay off the data channel by default, matching the intent of PR #452 ("default to stderr for outputs happening before initialization"). Downstream tooling that parses `pipelex` / `pipelex-agent` stdout as JSON (e.g. `mthds-js`'s `PipelexRunner`) is no longer at risk of stdout pollution from package-level logs — the bug was latent for stock installs because the agent-CLI JSON paths happen not to log at INFO+, but surfaced for anyone who raised `package_log_levels.pipelex` to DEBUG or added a setup-time log on the command path. The same flip is applied to the kit template (`pipelex/kit/configs/pipelex.toml`) that `pipelex init` copies to `~/.pipelex/`. **Note:** `console_print_target` is intentionally left at `stdout` — the main `pipelex` CLI emits human-facing tables (`show backends`, `show models`, `which`, `doctor`) via that channel, and downstream piping (`pipelex show backends > out.txt`) must keep working.++- **`pipelex-agent` now pins both console targets to `stderr` regardless of user config.** `make_pipelex_for_agent_cli` injects `config_overrides` into `Pipelex.make()` that force `console_log_target = "stderr"` and `console_print_target = "stderr"` from the very first log/print fired during init, so a user override of either knob in `~/.pipelex/pipelex.toml` can no longer leak diagnostics onto the agent CLI's JSON data channel. Defense-in-depth post-init calls to `log.redirect_to_stderr()` and `get_pipelex_hub().set_console_print_target(STDERR)` remain. A new adversarial E2E test (`tests/e2e/agent_cli/test_stdout_is_clean_json.py::test_models_json_stdout_resists_user_targets_override_to_stdout`) pins the contract by overriding both targets to `stdout` and `package_log_levels.pipelex` to `DEBUG` and asserting `json.loads(stdout)` still parses.+## [v0.29.1] - 2026-05-21### Fixeddiff --git a/pipelex/cli/agent_cli/commands/agent_cli_factory.py b/pipelex/cli/agent_cli/commands/agent_cli_factory.pyindex eb68f1938..aac4c228b 100644--- a/pipelex/cli/agent_cli/commands/agent_cli_factory.py+++ b/pipelex/cli/agent_cli/commands/agent_cli_factory.py@@ -1,13 +1,18 @@"""Factory function for agent CLI commands -- JSON-only error output."""import warnings+from collections.abc import Mappingfrom pathlib import Path+from types import MappingProxyType+from typing import Anyimport typerfrom pipelex.cli.agent_cli.commands.agent_output import agent_error, record_setup_warningfrom pipelex.cogt.exceptions import GatewayUnknownModelError, ModelDeckPresetValidatonError+from pipelex.hub import PipelexHubfrom pipelex.pipelex import Pipelex+from pipelex.system.console_target import ConsoleTargetfrom pipelex.system.pipelex_service.exceptions import (GatewayApiKeyMissingError,GatewayDoNotTrackConflictError,@@ -23,6 +28,77 @@ from pipelex.tools.log.log import logfrom pipelex.tools.log.log_levels import LogLevelfrom pipelex.tools.misc.pretty import PrettyPrinter, PrettyPrintMode+# Canonical leaf dict for "for any agent-CLI invocation, both Rich-managed channels land+# on stderr." Composed by two distinct call sites:+# - ``_AGENT_CLI_STDERR_CONSOLE_OVERRIDES`` below wraps it in the full-config-tree shape+# required by ``Pipelex.make(config_overrides=...)`` for the full-init path.+# - ``pipelex.cli.agent_cli.commands.doctor_cmd`` passes it flat to+# ``setup_doctor_runtime(log_config_overrides=...)`` for the doctor-only path that+# does not go through ``Pipelex.make``.+#+# These two knobs only control Rich-managed diagnostic channels — NOT the agent CLI's+# data channel:+# - ``console_log_target`` -> the ``RichHandler`` for Python's logging system+# (``log.debug/info/warning/error``).+# - ``console_print_target`` -> the ``Console`` returned by ``get_console()`` and used+# for banners, deck notices, and the main ``pipelex`` CLI's+# ``show backends`` / ``show models`` tables.+#+# The agent CLI's actual results (the JSON / markdown success envelope) are written by+# ``agent_success`` / ``agent_success_formatted`` in ``agent_output.py`` via the bare+# builtin ``print(...)`` straight to ``sys.stdout``. They do NOT go through Rich, so they+# are unaffected by these overrides. Error envelopes go via ``print(..., file=sys.stderr)``+# — also bypassing Rich.+#+# Pinning both targets to ``stderr`` therefore ensures that EVERYTHING ELSE Pipelex might+# emit (setup-time ``log.debug`` from ``telemetry_factory.py``, a banner from+# ``deck_notice.py``, any future ``get_console().print(...)`` on the agent CLI setup path)+# lands on stderr regardless of what the user's ``~/.pipelex/pipelex.toml`` says — so the+# JSON data channel on stdout stays clean for downstream consumers like ``mthds-js``'s+# ``PipelexRunner`` that do ``JSON.parse(stdout)``.+#+# Wrapped in ``MappingProxyType`` so a stray ``AGENT_CLI_STDERR_LOG_FIELDS[...] = ...`` in+# a future contributor's hot-fix raises immediately instead of silently mutating the+# shared canonical instance (which both consumers below alias).+AGENT_CLI_STDERR_LOG_FIELDS: Mapping[str, Any] = MappingProxyType(+ {+ "console_log_target": ConsoleTarget.STDERR,+ "console_print_target": ConsoleTarget.STDERR,+ }+)++# Direct alias: deep_update recurses into any ``Mapping`` and converts frozen leaves to+# plain dicts at merge time, so referencing the canonical ``MappingProxyType`` here is+# safe AND keeps mutation attempts on either reference loud (TypeError on the frozen+# proxy) instead of silently diverging.+_AGENT_CLI_STDERR_CONSOLE_OVERRIDES: dict[str, Any] = {+ "pipelex": {"log_config": AGENT_CLI_STDERR_LOG_FIELDS},+}+++def apply_agent_cli_output_discipline(log_level: LogLevel = LogLevel.WARNING) -> None:+ """Pin pipelex log level, pretty-print silence, and hub console target to stderr.++ Called from two paths:+ - ``make_pipelex_for_agent_cli`` (full-init): defense-in-depth. ``Pipelex.__init__``+ already pinned the hub console via ``set_console_print_target`` from the loaded+ log_config (whose ``console_print_target`` was overridden to STDERR by+ ``_AGENT_CLI_STDERR_CONSOLE_OVERRIDES``).+ - ``agent_doctor_cmd`` (doctor-only): also defense-in-depth, since+ ``setup_doctor_runtime`` now mirrors ``Pipelex.__init__`` and applies+ ``set_console_print_target`` itself from the overridden log_config.++ Safe to call from the broken-config doctor path where ``setup_doctor_runtime`` was+ skipped: ``log.redirect_to_stderr`` no-ops when no rich_handler is registered, and+ the hub print-target call is gated on a hub being installed.+ """+ log.set_level_for_package("pipelex", log_level)+ log.redirect_to_stderr()+ PrettyPrinter.mode = PrettyPrintMode.SILENT+ hub = PipelexHub.get_optional_instance()+ if hub is not None:+ hub.set_console_print_target(target=ConsoleTarget.STDERR)+def make_pipelex_for_agent_cli(library_dirs: list[str] | list[Path] | None = None,@@ -41,6 +117,20 @@ def make_pipelex_for_agent_cli(human-readable markdown to stdout and exits 0, so the calling agentcan display setup guidance directly.+ Stdout contract: every ``pipelex-agent`` invocation reserves stdout exclusively+ for the structured success envelope (JSON via ``--format json``, or markdown via+ ``--format markdown``) emitted by ``agent_success`` / ``agent_success_formatted``.+ All other output channels — logs, ``get_console().print(...)`` output, Rich pretty+ prints, and ``agent_error`` envelopes — are pinned to stderr regardless of what the+ user's ``pipelex.toml`` says. The factory enforces this via three layers:++ 1. ``config_overrides`` injected into ``Pipelex.make()`` pins both+ ``console_log_target`` and ``console_print_target`` to ``stderr`` from the+ very first log/print fired during init.+ 2. ``PrettyPrinter.mode = SILENT`` neutralizes ``pretty_print(...)`` entirely.+ 3. Post-init ``log.redirect_to_stderr()`` and+ ``get_pipelex_hub().set_console_print_target(STDERR)`` defense-in-depth.+Args:library_dirs: Optional library directories to use for the Pipelex instance.log_level: Log verbosity level (default WARNING for silent agent output).@@ -58,7 +148,11 @@ def make_pipelex_for_agent_cli(with warnings.catch_warnings(record=True) as caught:warnings.simplefilter("always", RemoteConfigStaleWarning)pipelex_instance = Pipelex.make(- integration_mode=IntegrationMode.CLI, library_dirs=library_dirs, needs_inference=needs_inference, needs_model_specs=needs_model_specs+ integration_mode=IntegrationMode.CLI,+ library_dirs=library_dirs,+ needs_inference=needs_inference,+ needs_model_specs=needs_model_specs,+ config_overrides=_AGENT_CLI_STDERR_CONSOLE_OVERRIDES,)# Surface a structured ``RemoteConfigStale`` entry so JSON consumers can react to# stale-cache operation without parsing stderr.@@ -117,7 +211,5 @@ def make_pipelex_for_agent_cli(# Suppress Rich pretty-printing and INFO/DEV/DEBUG log noise so that agent# commands only emit structured JSON. Warnings and errors still reach stderr.- PrettyPrinter.mode = PrettyPrintMode.SILENT- log.set_level_for_package("pipelex", log_level)- log.redirect_to_stderr()+ apply_agent_cli_output_discipline(log_level=log_level)return pipelex_instancediff --git a/pipelex/cli/agent_cli/commands/doctor_cmd.py b/pipelex/cli/agent_cli/commands/doctor_cmd.pyindex 07279a273..3721b44e1 100644--- a/pipelex/cli/agent_cli/commands/doctor_cmd.py+++ b/pipelex/cli/agent_cli/commands/doctor_cmd.py@@ -4,14 +4,18 @@ from typing import Annotated, Anyimport typer+from pipelex.base_exceptions import PipelexConfigError+from pipelex.cli.agent_cli.commands.agent_cli_factory import AGENT_CLI_STDERR_LOG_FIELDS, apply_agent_cli_output_disciplinefrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, agent_error, agent_success, set_agent_cli_error_formatfrom pipelex.cli.commands.doctor_cmd import (+ BackendFileReport,ConfigLocationInfo,check_backend_credentials,check_config_files,check_models,check_telemetry_config,gather_config_location,+ setup_doctor_runtime,)from pipelex.system.configuration.config_loader import config_manager@@ -67,7 +71,11 @@ def _format_doctor_markdown(result: dict[str, Any]) -> str:# Modelsmodels_check = checks["models"]- lines.append(f"\n## Models \u2014 {_status_icon(models_check['healthy'])}\n")+ models_skipped_flag = models_check.get("skipped", False)+ # Skipped state renders with the warn icon so consumers don't confuse "deferred until+ # config is fixed" with a genuine models failure.+ models_icon = "\u26a0\ufe0f" if models_skipped_flag else _status_icon(models_check["healthy"])+ lines.append(f"\n## Models \u2014 {models_icon}\n")lines.append(models_check["message"])for file_entry in models_check.get("backend_files", []):name = file_entry["backend_name"]@@ -132,14 +140,52 @@ def agent_doctor_cmd(else:config_location = gather_config_location()+ # Filesystem-only checks run BEFORE bootstrap: when no --global override is in+ # play, setup_doctor_runtime's load_config materializes ~/.pipelex/ from kit+ # templates as a side effect. Running it first would turn check_config_files into+ # a silent installer on a fresh machine. (The --global path skips materialization+ # — see load_config.)config_healthy, config_missing_count, config_message = check_config_files(config_dir=config_dir)telemetry_healthy, telemetry_message = check_telemetry_config(config_dir=config_dir)backends_healthy, backend_credential_reports, backends_message = check_backend_credentials(config_dir=config_dir)- models_healthy, models_message, backend_file_reports = check_models(config_dir=config_dir)++ # check_models requires the hub + log.configure produced by setup_doctor_runtime.+ # When the config is broken (either shape-check fails up front or full validation+ # raises PipelexConfigError inside the bootstrap), we skip running check_models and+ # mark models as skipped — keeping the partial check tuples gathered above so the+ # JSON envelope still reports telemetry/backends instead of degrading to a single+ # error payload.+ models_skipped: bool = False+ models_healthy: bool+ models_message: str+ backend_file_reports: dict[str, BackendFileReport]+ if config_healthy:+ try:+ setup_doctor_runtime(log_config_overrides=AGENT_CLI_STDERR_LOG_FIELDS, config_dir=config_dir)+ models_healthy, models_message, backend_file_reports = check_models(config_dir=config_dir)+ except PipelexConfigError as exc:+ # A config can pass check_config_files's shape check and still fail full validation+ # inside setup_doctor_runtime (e.g. a layered override file). Surface the translated+ # message via the same partial-report shape as the broken-config branch.+ models_skipped = True+ models_healthy = False+ models_message = f"skipped — {exc.message}"+ backend_file_reports = {}+ else:+ models_skipped = True+ models_healthy = False+ models_message = "skipped — fix configuration errors first"+ backend_file_reports = {}except Exception as exc: # noqa: BLE001- # Agent CLI command boundary: agent_error() (NoReturn) converts any unexpected failure into the structured error payload.+ # Agent CLI command boundary: agent_error() (NoReturn) converts any genuinely+ # unexpected failure into the structured error payload. PipelexConfigError is+ # handled by the inner arm above and never reaches here.agent_error(f"Health check failed unexpectedly: {exc}", type(exc).__name__, cause=exc)+ # Pin stdout discipline regardless of bootstrap path (broken-config branch never+ # installed a hub or configured log — the helper guards both internally).+ apply_agent_cli_output_discipline()+all_healthy = config_healthy and telemetry_healthy and backends_healthy and models_healthy# Build backend credential details@@ -215,6 +261,7 @@ def agent_doctor_cmd(},"models": {"healthy": models_healthy,+ "skipped": models_skipped,"message": models_message,"backend_files": backend_files_list,},diff --git a/pipelex/cli/commands/doctor_cmd.py b/pipelex/cli/commands/doctor_cmd.pyindex ff97de45b..f4204b75a 100644--- a/pipelex/cli/commands/doctor_cmd.py+++ b/pipelex/cli/commands/doctor_cmd.py@@ -44,6 +44,7 @@ from pipelex.kit.paths import get_kit_configs_dirfrom pipelex.system.configuration.config_loader import config_managerfrom pipelex.system.configuration.configs import PipelexConfigfrom pipelex.system.environment import get_optional_env+from pipelex.system.exceptions import ConfigValidationErrorfrom pipelex.system.pipelex_service.exceptions import (RemoteConfigUnavailableError,RemoteConfigValidationError,@@ -54,6 +55,7 @@ from pipelex.system.pipelex_service.pipelex_service_config import ()from pipelex.system.pipelex_service.remote_config_fetcher import RemoteConfigFetcherfrom pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME, TelemetryConfig+from pipelex.tools.log.log_config import LogConfigfrom pipelex.tools.misc.dict_utils import extract_vars_from_strings_recursivefrom pipelex.tools.misc.file_utils import path_existsfrom pipelex.tools.misc.placeholder import value_is_placeholder@@ -61,6 +63,8 @@ from pipelex.tools.misc.toml_utils import TomlError, load_toml_from_pathfrom pipelex.tools.secrets.env_secrets_provider import EnvSecretsProviderif TYPE_CHECKING:+ from collections.abc import Mapping+from pipelex.system.pipelex_service.types import RemoteConfigSource@@ -120,21 +124,32 @@ def check_config_files(config_dir: Path | None = None) -> tuple[bool, int, str]:except (PipelexCLIError, OSError) as exc:return False, 0, f"Error checking config files: {exc}"- # Check if main config can be loaded using the hub's setup.- # Note: load_config() uses config_manager's own resolution chain (package → global → project)- # which may differ from config_dir when --global is used. This is acceptable for a diagnostic- # check — the existence check guards the path, while load_config() validates the merged config.+ # Validate the merged config against the same scope the diagnostic is reporting on.+ # Threading config_dir through:+ # - matches what setup_doctor_runtime will load (no silent shape disagreement),+ # - and skips ensure_global_config_exists when --global is set, so this probe+ # stays a check and never silently materializes ~/.pipelex/ on a fresh machine.pipelex_config_path = config_manager.resolve_config_file("pipelex.toml", config_dir=config_dir)if path_exists(pipelex_config_path):try:# Suppress stderr and stdout to prevent tracebacks from being printedwith contextlib.redirect_stderr(io.StringIO()), contextlib.redirect_stdout(io.StringIO()):- config = config_manager.load_config()+ config = config_manager.load_config(config_dir=config_dir)PipelexConfig.model_validate(config)except ValidationError as validation_error:validation_error_msg = report_validation_error(category="config", validation_error=validation_error)msg = f"Configuration validation failed:\n{validation_error_msg}"return False, 0, msg+ except ConfigValidationError as exc:+ # ConfigRoot.__init__ wraps pydantic.ValidationError into ConfigValidationError;+ # recover the original via __cause__ so we still emit the migration-aware report.+ underlying = exc.__cause__+ if isinstance(underlying, ValidationError):+ validation_error_msg = report_validation_error(category="config", validation_error=underlying)+ msg = f"Configuration validation failed:\n{validation_error_msg}"+ else:+ msg = f"Configuration validation failed: {exc.message}"+ return False, 0, msgexcept (TomlError, OSError) as exc:return False, 0, f"Error loading pipelex.toml: {exc}"@@ -436,6 +451,7 @@ def display_health_report(deck_report: DeckSyncReport,config_location: ConfigLocationInfo,fix_mode: bool = False,+ models_skipped: bool = False,) -> None:"""Display a comprehensive health report.@@ -456,6 +472,9 @@ def display_health_report(deck_report: Per-file sync status report (used to render the per-file detail when not healthy)config_location: Resolved configuration location informationfix_mode: Whether we're in interactive fix mode (--fix flag)+ models_skipped: True when check_models was bypassed because config is broken — render+ the Models row as a yellow advisory and suppress its standalone Solutions entry,+ since the Config Files row already steers the user."""all_healthy = config_healthy and telemetry_healthy and backends_healthy and models_healthy and deck_healthy@@ -536,6 +555,10 @@ def display_health_report(console.print("[bold]Models[/bold]")if models_healthy:console.print(f" [green]✓[/green] {models_message}")+ elif models_skipped:+ # Skipped reads as advisory, not failure — the Config Files row is the real issue.+ console.print(f" [yellow]⚠[/yellow] {models_message}")+ console.print(" [dim]Models check deferred until config errors are fixed.[/dim]")else:console.print(f" [red]✗[/red] {models_message}")@@ -713,9 +736,62 @@ def check_deck_sync(config_dir: Path | None = None) -> tuple[bool, DeckSyncReporreturn False, report, f"{len(actionable)} deck file(s) need action"+def setup_doctor_runtime(+ log_config_overrides: Mapping[str, Any] | None = None,+ config_dir: Path | None = None,+) -> None:+ """Spin up a fresh PipelexHub and configure logging for doctor checks.++ Doctor intentionally bypasses ``Pipelex.make`` so it can diagnose a broken config+ without crashing during full init. This helper performs the minimum runtime setup+ that ``check_models`` requires — a hub with a loaded config, a hub-level console+ print target, and a configured logger — mirroring ``Pipelex.__init__`` step for+ step on that subset.++ The agent doctor passes ``AGENT_CLI_STDERR_LOG_FIELDS`` so the JSON envelope on+ stdout stays clean for downstream consumers. The human doctor passes nothing and+ inherits the user's configured log targets.++ Overrides are merged via ``LogConfig.model_validate`` (full re-validation) so that+ a wrong-typed override surfaces loudly instead of silently breaking downstream+ match/case dispatch on ``ConsoleTarget`` etc.++ ``log.configure`` is invoked through ``configure_if_unset`` so that if a library+ embedding or interleaved test has already configured logging, this call no-ops+ instead of raising the once-per-process ``RuntimeError``.++ Args:+ log_config_overrides: Optional mapping of ``LogConfig`` field names → values to+ merge into the loaded log_config before ``log.configure`` is called.+ config_dir: Optional explicit config dir (e.g. for ``--global``). When provided,+ project/global layering is bypassed and only this directory is read.++ Raises:+ PipelexConfigError: If config validation fails. Translation of+ ``pydantic.ValidationError`` to keep doctor's error surface stable.+ """+ pipelex_hub = PipelexHub()+ set_pipelex_hub(pipelex_hub)+ try:+ pipelex_hub.setup_config(config_cls=PipelexConfig, config_dir=config_dir)+ except ValidationError as validation_error:+ validation_error_msg = report_validation_error(category="config", validation_error=validation_error)+ msg = f"Could not setup config because of: {validation_error_msg}"+ raise PipelexConfigError(msg) from validation_error++ log_config = get_config().pipelex.log_config+ if log_config_overrides is not None:+ log_config = LogConfig.model_validate({**log_config.model_dump(), **log_config_overrides})+ pipelex_hub.set_console_print_target(target=log_config.console_print_target)+ log.configure_if_unset(log_config=log_config)++def check_models(config_dir: Path | None = None) -> tuple[bool, str, dict[str, BackendFileReport]]:"""Check if models are valid, including backend file validation.+ Assumes ``setup_doctor_runtime`` has already run — the function reads from the+ active hub and relies on ``log`` being configured.+Args:config_dir: Explicit config directory override (e.g. for --global).If None, uses layered resolution (project .pipelex/ → global ~/.pipelex/).@@ -735,24 +811,18 @@ def check_models(config_dir: Path | None = None) -> tuple[bool, str, dict[str, Bmsg = f"Backend configuration error: {first_error}"return False, msg, backend_file_reports- # If backend files are OK, try to load and validate models- pipelex_hub = PipelexHub()- set_pipelex_hub(pipelex_hub)-- try:- pipelex_hub.setup_config(config_cls=PipelexConfig)- except ValidationError as validation_error:- validation_error_msg = report_validation_error(category="config", validation_error=validation_error)- msg = f"Could not setup config because of: {validation_error_msg}"- raise PipelexConfigError(msg) from validation_error-- log.configure(log_config=get_config().pipelex.log_config)-- # Fetch gateway model specs if Gateway is enabled+ # Fetch gateway model specs if Gateway is enabled.+ # Probe the same backends.toml / pipelex_service.toml the doctor is reporting on+ # (project-vs-global) instead of always defaulting to the global path — otherwise+ # --global on a machine with a project-local backends.toml would mis-report gateway+ # state because the layered `config_manager.backends_file_path` would still resolve+ # to the project file.+ backends_file_path = config_dir / "inference" / "backends.toml" if config_dir is not None else None+ service_config_dir = config_dir if config_dir is not None else config_manager.global_config_dirgateway_config: GatewayConfig | None = Nonegateway_config_source: RemoteConfigSource | None = None- if is_pipelex_gateway_enabled():- pipelex_service_config = load_pipelex_service_config_if_exists(config_dir=config_manager.global_config_dir)+ if is_pipelex_gateway_enabled(backends_file_path=backends_file_path):+ pipelex_service_config = load_pipelex_service_config_if_exists(config_dir=service_config_dir)if pipelex_service_config is None:return False, "Pipelex Gateway is enabled but service configuration is missing", backend_file_reportsif not pipelex_service_config.agreement.terms_accepted:@@ -768,6 +838,13 @@ def check_models(config_dir: Path | None = None) -> tuple[bool, str, dict[str, Bexcept (RemoteConfigUnavailableError, RemoteConfigValidationError) as exc:return False, f"Failed to fetch Pipelex Gateway remote configuration: {exc}", backend_file_reports+ # When --global (config_dir set), pin every path so layered config_manager.X+ # resolution doesn't silently fall back to the project-local files.+ backends_library_override = str(config_dir / "inference" / "backends.toml") if config_dir is not None else None+ backends_dir_override = str(config_dir / "inference" / "backends") if config_dir is not None else None+ routing_profile_override = str(config_dir / "inference" / "routing_profiles.toml") if config_dir is not None else None+ deck_dir_override = str(config_dir / "inference" / "deck") if config_dir is not None else None+models_manager = ModelManager()secrets_provider = EnvSecretsProvider()try:@@ -775,6 +852,10 @@ def check_models(config_dir: Path | None = None) -> tuple[bool, str, dict[str, Bsecrets_provider=secrets_provider,gateway_config=gateway_config,gateway_config_source=gateway_config_source,+ backends_library_path=backends_library_override,+ backends_dir_path=backends_dir_override,+ routing_profile_library_path=routing_profile_override,+ deck_dir_path=deck_dir_override,)models_manager.validate_model_deck()except InferenceBackendLibraryError as exc:@@ -838,11 +919,28 @@ def do_doctor_cmd(# Gather config location infoconfig_location = gather_config_location()- # Run health checks (config_dir=None uses layered resolution: project → global)+ # Filesystem-only checks run BEFORE bootstrap: when no --global override is in play,+ # setup_doctor_runtime's load_config materializes ~/.pipelex/ from kit templates as a+ # side effect. Running it first would turn check_config_files into a silent installer+ # on a fresh machine. (The --global path skips materialization — see load_config.)config_healthy, config_missing_count, config_message = check_config_files()telemetry_healthy, telemetry_message = check_telemetry_config()backends_healthy, backend_credential_reports, backends_message = check_backend_credentials()- models_healthy, models_message, backend_file_reports = check_models()++ # check_models requires the hub + log.configure produced by setup_doctor_runtime.+ # When the config is broken, skipping setup keeps the friendly translation alive+ # (setup_doctor_runtime would raise PipelexConfigError on an invalid config and+ # discard the partial check tuples gathered so far).+ if config_healthy:+ setup_doctor_runtime()+ models_healthy, models_message, backend_file_reports = check_models()+ models_skipped = False+ else:+ models_healthy = False+ models_message = "skipped — fix configuration errors first"+ backend_file_reports = {}+ models_skipped = True+deck_healthy, deck_report, deck_message = check_deck_sync()# Display report@@ -857,6 +955,7 @@ def do_doctor_cmd(backend_credential_reports=backend_credential_reports,models_healthy=models_healthy,models_message=models_message,+ models_skipped=models_skipped,backend_file_reports=backend_file_reports,deck_healthy=deck_healthy,deck_message=deck_message,diff --git a/pipelex/cogt/models/model_manager.py b/pipelex/cogt/models/model_manager.pyindex 9f7a40945..329e57486 100644--- a/pipelex/cogt/models/model_manager.py+++ b/pipelex/cogt/models/model_manager.py@@ -64,21 +64,27 @@ class ModelManager(ModelManagerAbstract):gateway_config: GatewayConfig | None,gateway_config_source: RemoteConfigSource | None,needs_inference: bool = True,+ backends_library_path: str | None = None,+ backends_dir_path: str | None = None,+ routing_profile_library_path: str | None = None,+ deck_dir_path: str | None = None,) -> None:+ # Override paths let the doctor scope --global properly; default None falls+ # back to layered config_manager paths for all other callers.self.inference_backend_library.load(secrets_provider=secrets_provider,- backends_library_path=str(config_manager.backends_file_path),- backends_dir_path=str(config_manager.backends_dir_path),+ backends_library_path=backends_library_path or str(config_manager.backends_file_path),+ backends_dir_path=backends_dir_path or str(config_manager.backends_dir_path),gateway_config=gateway_config,lenient=not needs_inference,)enabled_backends = self.inference_backend_library.all_enabled_backends()self._routing_profile = load_active_routing_profile(- routing_profile_library_path=str(config_manager.routing_profiles_file_path),+ routing_profile_library_path=routing_profile_library_path or str(config_manager.routing_profiles_file_path),enabled_backends=enabled_backends,lenient=not needs_inference,)- model_deck_paths = ModelManager.get_model_deck_paths(deck_dir_path=str(config_manager.model_decks_dir_path))+ model_deck_paths = ModelManager.get_model_deck_paths(deck_dir_path=deck_dir_path or str(config_manager.model_decks_dir_path))deck_blueprint = load_model_deck_blueprint(model_deck_paths=model_deck_paths)self.model_deck = self.build_deck(enabled_backends=enabled_backends, model_deck_blueprint=deck_blueprint)diff --git a/pipelex/core/validation.py b/pipelex/core/validation.pyindex 8070c9f38..ead9fe43b 100644--- a/pipelex/core/validation.py+++ b/pipelex/core/validation.py@@ -1,41 +1,47 @@from pydantic import ValidationError-from pipelex import log-from pipelex.config import get_config+from pipelex.hub import PipelexHub+from pipelex.system.configuration.configs import MigrationConfig, PipelexConfigfrom pipelex.tools.typing.pydantic_utils import analyze_pydantic_validation_errordef report_validation_error(category: str, validation_error: ValidationError) -> str:validation_error_analysis = analyze_pydantic_validation_error(validation_error)- migration_config = get_config().migration+ # Doctor calls this from inside its bootstrap, where setup_config may have raised+ # mid-flight and the hub's _config is still None. Reading via the optional getters+ # lets the friendly translation work without a try/except RuntimeError catch-all.+ pipelex_hub = PipelexHub.get_optional_instance()+ config = pipelex_hub.get_optional_config() if pipelex_hub is not None else None+ migration_config: MigrationConfig | None+ if isinstance(config, PipelexConfig):+ migration_config = config.migration+ else:+ migration_config = Nonemigration_reports: list[str] = []- # Build field-to-renamings mapping for missing fields- log.verbose(validation_error_analysis.missing_fields, title="Missing fields")missing_field_renamings: dict[tuple[tuple[str, str], ...], list[str]] = {}- for missing_field in validation_error_analysis.missing_fields:- text = missing_field.split(".")[-1]- if renamings := migration_config.text_in_renaming_values(category=category, text=text):- # Use tuple of renamings as key for grouping- renamings_key = tuple(renamings)- if renamings_key not in missing_field_renamings:- missing_field_renamings[renamings_key] = []- missing_field_renamings[renamings_key].append(missing_field)+ if migration_config is not None:+ for missing_field in validation_error_analysis.missing_fields:+ text = missing_field.split(".")[-1]+ if renamings := migration_config.text_in_renaming_values(category=category, text=text):+ renamings_key = tuple(renamings)+ if renamings_key not in missing_field_renamings:+ missing_field_renamings[renamings_key] = []+ missing_field_renamings[renamings_key].append(missing_field)- # Build field-to-renamings mapping for extra fields- log.verbose(validation_error_analysis.extra_fields, title="Extra fields")extra_field_renamings: dict[tuple[tuple[str, str], ...], list[str]] = {}- for extra_field in validation_error_analysis.extra_fields:- # Extract field path before the colon (extra fields include ": value")- field_path = extra_field.split(":")[0].strip()- text = field_path.split(".")[-1]- if renamings := migration_config.text_in_renaming_keys(category=category, text=text):- renamings_key = tuple(renamings)- if renamings_key not in extra_field_renamings:- extra_field_renamings[renamings_key] = []- extra_field_renamings[renamings_key].append(extra_field)+ if migration_config is not None:+ for extra_field in validation_error_analysis.extra_fields:+ # Extract field path before the colon (extra fields include ": value")+ field_path = extra_field.split(":")[0].strip()+ text = field_path.split(".")[-1]+ if renamings := migration_config.text_in_renaming_keys(category=category, text=text):+ renamings_key = tuple(renamings)+ if renamings_key not in extra_field_renamings:+ extra_field_renamings[renamings_key] = []+ extra_field_renamings[renamings_key].append(extra_field)# Format grouped output for missing fieldsfor renamings_tuple, fields in missing_field_renamings.items():diff --git a/pipelex/hub.py b/pipelex/hub.pyindex e486c837c..0f5ae8715 100644--- a/pipelex/hub.py+++ b/pipelex/hub.py@@ -111,7 +111,7 @@ class PipelexHub:# tools- def setup_config(self, config_cls: type[ConfigRoot], config_overrides: dict[str, Any] | None = None):+ def setup_config(self, config_cls: type[ConfigRoot], config_overrides: dict[str, Any] | None = None, config_dir: Path | None = None):"""Set the global configuration instance.Args:@@ -119,8 +119,12 @@ class PipelexHub:config_overrides: Optional dict deep-merged on top of all TOML layersas the highest-priority override. Useful for tests that needspecific config without editing TOML files.+ config_dir: Optional explicit config dir. When provided, project/global+ layering is bypassed and only this directory is read. Used by the+ doctor ``--global`` path so the hub reflects exactly the directory+ being reported on."""- config_dict = config_manager.load_config(extra_overrides=config_overrides)+ config_dict = config_manager.load_config(extra_overrides=config_overrides, config_dir=config_dir)self.set_config(config=config_cls.model_validate(config_dict))def set_config(self, config: ConfigRoot):@@ -222,6 +226,15 @@ class PipelexHub:raise RuntimeError(msg)return self._config+ def get_optional_config(self) -> ConfigRoot | None:+ """Get the current configuration if it has been set, otherwise None.++ Non-raising counterpart to ``get_required_config``. Used by callers that must+ run before/around bootstrap (e.g. ``report_validation_error`` invoked from the+ doctor's setup helper when ``setup_config`` itself failed).+ """+ return self._config+def get_console(self) -> Console:if self._console:return self._consolediff --git a/pipelex/kit/configs/pipelex.toml b/pipelex/kit/configs/pipelex.tomlindex 0057c498e..a7bfd34ca 100644--- a/pipelex/kit/configs/pipelex.toml+++ b/pipelex/kit/configs/pipelex.toml@@ -161,7 +161,17 @@ default_directory_base_name = "pipeline"# Default logging level: "DEBUG", "INFO", "WARNING", "ERROR"default_log_level = "INFO"# Log output target: "stdout" or "stderr"-console_log_target = "stdout"+# console_log_target controls the RichHandler used by the logging system (log.debug/info/...).+# Logs are diagnostics → stderr.+console_log_target = "stderr"+# console_print_target controls the Console returned by get_console(), used for banners,+# deck notices, and the main `pipelex` CLI's data tables (`show backends`, `show models`,+# `which`, `doctor`). Tables are data the user pipes to a file → stdout.+# Note: the agent CLI (`pipelex-agent`) emits its actual JSON/markdown results via bare+# builtin `print(...)` to sys.stdout, bypassing Rich entirely — so this knob does NOT+# affect the agent CLI data channel. The agent CLI factory additionally forces both+# targets to stderr internally to keep its stdout strictly reserved for the success+# envelope.console_print_target = "stdout"[pipelex.log_config.package_log_levels]diff --git a/pipelex/pipelex.toml b/pipelex/pipelex.tomlindex 0cbcd75f1..298441769 100644--- a/pipelex/pipelex.toml+++ b/pipelex/pipelex.toml@@ -70,7 +70,17 @@ cost_report_unit_scale = 1.0[pipelex.log_config]default_log_level = "INFO"-console_log_target = "stdout"+# console_log_target controls the RichHandler used by the logging system (log.debug/info/...).+# Logs are diagnostics → stderr.+console_log_target = "stderr"+# console_print_target controls the Console returned by get_console(), used for banners,+# deck notices, and the main `pipelex` CLI's data tables (`show backends`, `show models`,+# `which`, `doctor`). Tables are data the user pipes to a file → stdout.+# Note: the agent CLI (`pipelex-agent`) emits its actual JSON/markdown results via bare+# builtin `print(...)` to sys.stdout, bypassing Rich entirely — so this knob does NOT+# affect the agent CLI data channel. The agent CLI factory additionally forces both+# targets to stderr internally to keep its stdout strictly reserved for the success+# envelope (see `_AGENT_CLI_STDERR_CONSOLE_OVERRIDES` in `agent_cli_factory.py`).console_print_target = "stdout"is_console_logging_enabled = truediff --git a/pipelex/system/configuration/config_loader.py b/pipelex/system/configuration/config_loader.pyindex ecad69506..c226019dd 100644--- a/pipelex/system/configuration/config_loader.py+++ b/pipelex/system/configuration/config_loader.py@@ -192,10 +192,16 @@ class ConfigLoader:files.append(config_dir / "pipelex_temporary_override.toml")return files- def load_config(self, extra_overrides: dict[str, Any] | None = None) -> dict[str, Any]:+ def load_config(self, extra_overrides: dict[str, Any] | None = None, config_dir: Path | None = None) -> dict[str, Any]:"""Load and merge configurations from pipelex and local config files.- The configuration is loaded and deep-merged in the following order+ When ``config_dir`` is provided, the load is scoped to a single directory+ (package defaults + ``config_dir`` base + ``config_dir`` overrides + ``extra_overrides``).+ This is what the doctor command uses for ``--global``: it wants the hub to reflect+ exactly the directory it is reporting on, with no project/global layering muddying+ the view.++ Otherwise the configuration is loaded and deep-merged in the following order(later wins per leaf key):1. Package defaults (pipelex/pipelex.toml)@@ -218,27 +224,37 @@ class ConfigLoader:precedence. Global and project run_mode files are not loaded, to keeptest runs hermetic.+ Args:+ extra_overrides: Optional dict deep-merged on top as the final layer.+ config_dir: Optional explicit config dir. When given, project/global layering+ is bypassed and only this directory is read.+Returns:dict[str, Any]: The merged configuration dictionary"""- self.ensure_global_config_exists()-is_unit_testing = runtime_manager.is_unit_testing- project_dir = self.project_config_dir- list_of_configs: list[Path] = [- self.pipelex_root_dir / CONFIG_NAME,- self.global_config_dir / CONFIG_NAME,- ]- list_of_configs.extend(- self._override_files_for_dir(self.global_config_dir, include_run_mode=not is_unit_testing),- )+ list_of_configs: list[Path] = [self.pipelex_root_dir / CONFIG_NAME]- if project_dir is not None and project_dir != self.global_config_dir:- list_of_configs.append(project_dir / CONFIG_NAME)+ if config_dir is not None:+ list_of_configs.append(config_dir / CONFIG_NAME)list_of_configs.extend(- self._override_files_for_dir(project_dir, include_run_mode=not is_unit_testing),+ self._override_files_for_dir(config_dir, include_run_mode=not is_unit_testing),)+ else:+ self.ensure_global_config_exists()+ project_dir = self.project_config_dir++ list_of_configs.append(self.global_config_dir / CONFIG_NAME)+ list_of_configs.extend(+ self._override_files_for_dir(self.global_config_dir, include_run_mode=not is_unit_testing),+ )++ if project_dir is not None and project_dir != self.global_config_dir:+ list_of_configs.append(project_dir / CONFIG_NAME)+ list_of_configs.extend(+ self._override_files_for_dir(project_dir, include_run_mode=not is_unit_testing),+ )if is_unit_testing:list_of_configs.append(Path.cwd() / "tests" / f"pipelex_{runtime_manager.run_mode}.toml")diff --git a/pipelex/tools/log/log.py b/pipelex/tools/log/log.pyindex f97f2da70..f82959e0c 100644--- a/pipelex/tools/log/log.py+++ b/pipelex/tools/log/log.py@@ -70,6 +70,25 @@ class Log:self.poor_handler = Noneself.log_dispatch.reset()+ def configure_if_unset(self, log_config: LogConfig) -> bool:+ """Configure logging unless already configured.++ Useful for entry points that may be reached after another caller (a library+ embedding Pipelex, an interleaved test) has already initialized logging.+ ``configure`` itself is once-per-process and raises on a second call; this+ guarded variant returns False instead.++ Args:+ log_config: The log configuration to use.++ Returns:+ True if configuration was applied, False if logging was already configured.+ """+ if self._log_config_instance is not None:+ return False+ self.configure(log_config=log_config)+ return True+def configure(self, log_config: LogConfig):"""Configure the logging system with the given project name and log configuration.diff --git a/pipelex/tools/misc/json_utils.py b/pipelex/tools/misc/json_utils.pyindex 813c8b517..f2215f00e 100644--- a/pipelex/tools/misc/json_utils.py+++ b/pipelex/tools/misc/json_utils.py@@ -232,17 +232,23 @@ def load_json_list_from_path(path: str) -> list[Any]:raise JsonTypeError(msg)-def deep_update(target_dict: dict[str, Any], updates: dict[str, Any]):- """Recursively updates a dictionary with values from another dictionary.+def deep_update(target_dict: dict[str, Any], updates: Mapping[str, Any]):+ """Recursively updates a dictionary with values from another mapping.- This function performs a deep merge of two dictionaries, handling nested- dictionaries. For dictionaries, it recursively updates values. For all other- types (including lists), values from updates override the target values.+ This function performs a deep merge, handling nested mappings (``dict`` or any+ ``Mapping`` — ``MappingProxyType``, etc.). For mappings, it recursively updates+ values. For all other types (including lists), values from ``updates`` override+ the target values.++ The merged ``target_dict`` always holds plain ``dict`` instances at recursion+ points, even when an input branch was a frozen ``Mapping``. Downstream code that+ iterates results expecting a real ``dict`` (Pydantic ``model_validate`` on a+ sub-tree, deep-merge with another layer) stays compatible.Args:target_dict (Dict[str, Any]): The dictionary to update. This dictionarywill be modified in place.- updates (Dict[str, Any]): The dictionary containing updates to apply.+ updates: The mapping containing updates to apply.Example:>>> base = {"a": 1, "b": {"x": 2, "y": 3}, "c": [1, 2]}@@ -253,8 +259,10 @@ def deep_update(target_dict: dict[str, Any], updates: dict[str, Any]):"""for key, value in updates.items():- if isinstance(value, dict) and key in target_dict and isinstance(target_dict[key], dict):+ if isinstance(value, Mapping) and key in target_dict and isinstance(target_dict[key], dict):deep_update(target_dict[key], value) # pyright: ignore[reportUnknownArgumentType]+ elif isinstance(value, Mapping) and not isinstance(value, dict):+ target_dict[key] = dict(value) # pyright: ignore[reportUnknownArgumentType]else:target_dict[key] = valuediff --git a/tests/e2e/agent_cli/test_stdout_is_clean_json.py b/tests/e2e/agent_cli/test_stdout_is_clean_json.pynew file mode 100644index 000000000..285871a28--- /dev/null+++ b/tests/e2e/agent_cli/test_stdout_is_clean_json.py@@ -0,0 +1,211 @@+"""E2E test that the agent CLI's stdout stays clean for JSON-emitting commands.++Downstream tooling (e.g. ``mthds-js``'s ``PipelexRunner``) calls ``JSON.parse(stdout)``+on commands like ``pipelex-agent models --format json``. The package-default+``console_log_target`` / ``console_print_target`` must therefore route logs and rich+prints to stderr — otherwise a single log line on a setup code path will break every+downstream consumer.++This test spawns a real ``pipelex-agent`` subprocess with an isolated ``HOME`` (so no+user-local ``~/.pipelex/`` overrides leak in). The hermetic ``~/.pipelex/pipelex.toml``+is rewritten to set ``package_log_levels.pipelex = "DEBUG"`` so existing setup-time+``log.debug(...)`` calls (e.g. ``telemetry_factory.py``) actually fire — that's the same+flip any user can make in their override file, and it's the scenario described in PR+#452's intent ("default to stderr for outputs happening before initialization").++With ``console_log_target = "stdout"`` (the bug), those DEBUG lines land on stdout and+break ``json.loads``. With ``console_log_target = "stderr"`` (the fix), they land on+stderr and stdout stays clean.++Asserts that:++ - the command exits 0+ - the captured stdout parses as JSON in one shot via ``json.loads`` — no stripping,+ no last-object hunting.++If anyone flips the kit-template / package default back to stdout, or adds a+``print(...)`` on the models command path that targets stdout, this test fails.+"""++from __future__ import annotations++import json+import subprocess # noqa: S404 — invokes the real pipelex-agent binary for E2E coverage+from typing import TYPE_CHECKING, cast++import pytest++from tests.e2e.agent_cli.conftest import PIPELEX_AGENT_BIN++if TYPE_CHECKING:+ from pathlib import Path+++def _set_pipelex_package_log_level_to_debug(pipelex_toml_path: Path) -> None:+ """Rewrite the ``pipelex = "INFO"`` line inside ``[pipelex.log_config.package_log_levels]``+ to ``"DEBUG"`` so any setup-time ``log.debug`` in the ``pipelex.*`` namespace fires.++ Targets the specific kit-template structure (``pipelex = "INFO"`` lives directly under+ that section). Asserts on no-match so a future kit refactor surfaces here instead of+ silently neutering the test.+ """+ original_text = pipelex_toml_path.read_text(encoding="utf-8")+ lines = original_text.splitlines(keepends=True)+ in_target_section = False+ rewrote = False+ for index, line in enumerate(lines):+ stripped = line.strip()+ if stripped.startswith("[") and stripped.endswith("]"):+ in_target_section = stripped == "[pipelex.log_config.package_log_levels]"+ continue+ if in_target_section and stripped.startswith("pipelex"):+ lines[index] = 'pipelex = "DEBUG"\n'+ rewrote = True+ break+ if not rewrote:+ msg = f"Could not find 'pipelex = ...' under [pipelex.log_config.package_log_levels] in {pipelex_toml_path}"+ raise AssertionError(msg)+ pipelex_toml_path.write_text("".join(lines), encoding="utf-8")+++def _set_console_targets(pipelex_toml_path: Path, *, log_target: str, print_target: str) -> None:+ """Rewrite ``console_log_target`` and ``console_print_target`` directly under+ ``[pipelex.log_config]`` to the given values.++ Used by the adversarial defense-in-depth test to simulate a user who overrides both+ targets to ``"stdout"`` in their ``~/.pipelex/pipelex.toml``. The agent CLI must keep+ its stdout channel clean for JSON consumers regardless of this user config.++ Asserts on no-match for either knob so a future kit refactor surfaces here instead of+ silently neutering the test.+ """+ original_text = pipelex_toml_path.read_text(encoding="utf-8")+ lines = original_text.splitlines(keepends=True)+ in_target_section = False+ log_target_rewritten = False+ print_target_rewritten = False+ for index, line in enumerate(lines):+ stripped = line.strip()+ if stripped.startswith("[") and stripped.endswith("]"):+ in_target_section = stripped == "[pipelex.log_config]"+ continue+ if not in_target_section:+ continue+ if stripped.startswith("console_log_target"):+ lines[index] = f'console_log_target = "{log_target}"\n'+ log_target_rewritten = True+ elif stripped.startswith("console_print_target"):+ lines[index] = f'console_print_target = "{print_target}"\n'+ print_target_rewritten = True+ if not log_target_rewritten:+ msg = f"Could not find 'console_log_target = ...' under [pipelex.log_config] in {pipelex_toml_path}"+ raise AssertionError(msg)+ if not print_target_rewritten:+ msg = f"Could not find 'console_print_target = ...' under [pipelex.log_config] in {pipelex_toml_path}"+ raise AssertionError(msg)+ pipelex_toml_path.write_text("".join(lines), encoding="utf-8")++[email protected]_disabled # Slow subprocess-based E2E; runs locally and on PR-gated workflows.+class TestAgentCliStdoutIsCleanJson:+ def test_models_json_stdout_parses_as_single_json_document(+ self,+ hermetic_home: Path,+ offline_subprocess_env: dict[str, str],+ ) -> None:+ """``pipelex-agent models --format json`` stdout must be a single JSON document.++ Bumps ``package_log_levels.pipelex`` to DEBUG (the exact knob a downstream user+ would flip when debugging) so the latent ``console_log_target`` bug surfaces as+ DEBUG lines on stdout. Then ``json.loads`` on the entire stdout (with no slicing,+ no last-object walker) must succeed and return a dict envelope.+ """+ _set_pipelex_package_log_level_to_debug(hermetic_home / ".pipelex" / "pipelex.toml")++ result = subprocess.run( # noqa: S603+ [+ str(PIPELEX_AGENT_BIN),+ "--log-level",+ "debug",+ "models",+ "--format",+ "json",+ ],+ env=offline_subprocess_env,+ cwd=str(hermetic_home),+ capture_output=True,+ text=True,+ check=False,+ timeout=120,+ )++ assert result.returncode == 0, f"pipelex-agent models --format json must succeed.\nstdout={result.stdout!r}\nstderr={result.stderr!r}"++ try:+ parsed = json.loads(result.stdout)+ except json.JSONDecodeError as exc:+ msg = (+ f"stdout must be a single parseable JSON document (no log/print pollution).\n"+ f"stdout={result.stdout!r}\nstderr={result.stderr!r}\nparse error={exc!s}"+ )+ raise AssertionError(msg) from exc++ assert isinstance(parsed, dict), f"Expected a JSON object envelope; got {type(parsed).__name__}: {parsed!r}"+ payload = cast("dict[str, object]", parsed)+ assert payload.get("success") is True, f"Expected ``success=True`` in envelope; got {payload!r}"++ def test_models_json_stdout_resists_user_targets_override_to_stdout(+ self,+ hermetic_home: Path,+ offline_subprocess_env: dict[str, str],+ ) -> None:+ """Adversarial defense-in-depth: even when the user's ``pipelex.toml`` sets BOTH+ ``console_log_target = "stdout"`` and ``console_print_target = "stdout"`` AND+ bumps ``package_log_levels.pipelex`` to DEBUG, the agent CLI's stdout channel+ must remain a clean, parseable JSON envelope.++ The agent CLI's stdout-as-JSON contract is too important to leave at the mercy of+ the user's ``~/.pipelex/pipelex.toml``. ``make_pipelex_for_agent_cli`` injects+ config_overrides that pin both targets to stderr from the very first log/print+ call during ``Pipelex.make()`` — so this test exercises the override defense end+ to end, not just the shipped TOML defaults.+ """+ pipelex_toml = hermetic_home / ".pipelex" / "pipelex.toml"+ _set_pipelex_package_log_level_to_debug(pipelex_toml)+ _set_console_targets(pipelex_toml, log_target="stdout", print_target="stdout")++ result = subprocess.run( # noqa: S603+ [+ str(PIPELEX_AGENT_BIN),+ "--log-level",+ "debug",+ "models",+ "--format",+ "json",+ ],+ env=offline_subprocess_env,+ cwd=str(hermetic_home),+ capture_output=True,+ text=True,+ check=False,+ timeout=120,+ )++ assert result.returncode == 0, (+ f"pipelex-agent models --format json must succeed under adversarial user override.\nstdout={result.stdout!r}\nstderr={result.stderr!r}"+ )++ try:+ parsed = json.loads(result.stdout)+ except json.JSONDecodeError as exc:+ msg = (+ f"stdout must stay parseable JSON even when the user pipelex.toml routes "+ f"both console_log_target and console_print_target to stdout — the agent CLI "+ f"factory must override them back to stderr.\n"+ f"stdout={result.stdout!r}\nstderr={result.stderr!r}\nparse error={exc!s}"+ )+ raise AssertionError(msg) from exc++ assert isinstance(parsed, dict), f"Expected a JSON object envelope; got {type(parsed).__name__}: {parsed!r}"+ payload = cast("dict[str, object]", parsed)+ assert payload.get("success") is True, f"Expected ``success=True`` in envelope; got {payload!r}"diff --git a/tests/unit/pipelex/cli/test_agent_cli_output_discipline.py b/tests/unit/pipelex/cli/test_agent_cli_output_discipline.pynew file mode 100644index 000000000..99e076cbe--- /dev/null+++ b/tests/unit/pipelex/cli/test_agent_cli_output_discipline.py@@ -0,0 +1,68 @@+"""Unit tests for apply_agent_cli_output_discipline real side effects.++The discipline helper is the single source of truth for "agent CLI stdout stays clean."+The existing test_agent_doctor_cmd suite asserts the helper is called, but the autouse+fixture there stubs the helper out — so a typo regression inside the helper would ship+green. This module covers the real side effects (log redirect, PrettyPrinter mode flip,+hub print-target swap) by patching the dependencies the helper touches and asserting+the helper drives them correctly.+"""++from __future__ import annotations++import logging+from typing import TYPE_CHECKING++import pytest++if TYPE_CHECKING:+ from pytest_mock import MockerFixture++from pipelex.cli.agent_cli.commands.agent_cli_factory import apply_agent_cli_output_discipline+from pipelex.system.console_target import ConsoleTarget+from pipelex.tools.log.log_levels import LogLevel+from pipelex.tools.misc.pretty import PrettyPrinter, PrettyPrintMode+++class TestApplyAgentCliOutputDiscipline:+ @pytest.fixture(autouse=True)+ def _restore_globals(self):+ """Restore PrettyPrinter.mode and the pipelex logger level after each test."""+ original_mode = PrettyPrinter.mode+ pipelex_logger = logging.getLogger("pipelex")+ original_level = pipelex_logger.level+ yield+ PrettyPrinter.mode = original_mode+ pipelex_logger.setLevel(original_level)++ def test_pins_console_print_target_to_stderr_when_hub_installed(self, mocker: MockerFixture) -> None:+ """When a hub is installed, the helper must pin its console_print_target to STDERR."""+ mock_redirect = mocker.patch("pipelex.cli.agent_cli.commands.agent_cli_factory.log.redirect_to_stderr")+ mock_hub = mocker.MagicMock()+ mocker.patch(+ "pipelex.cli.agent_cli.commands.agent_cli_factory.PipelexHub.get_optional_instance",+ return_value=mock_hub,+ )++ apply_agent_cli_output_discipline(log_level=LogLevel.WARNING)++ mock_redirect.assert_called_once()+ mock_hub.set_console_print_target.assert_called_once_with(target=ConsoleTarget.STDERR)+ assert PrettyPrinter.mode is PrettyPrintMode.SILENT+ assert logging.getLogger("pipelex").level == LogLevel.WARNING.int_logging_level++ def test_no_hub_path_skips_hub_call_safely(self, mocker: MockerFixture) -> None:+ """When no hub is installed (broken-config doctor path), the helper must still pin+ log + PrettyPrinter without raising — the hub call is gated on get_optional_instance.+ """+ mock_redirect = mocker.patch("pipelex.cli.agent_cli.commands.agent_cli_factory.log.redirect_to_stderr")+ mocker.patch(+ "pipelex.cli.agent_cli.commands.agent_cli_factory.PipelexHub.get_optional_instance",+ return_value=None,+ )++ apply_agent_cli_output_discipline(log_level=LogLevel.WARNING)++ mock_redirect.assert_called_once()+ assert PrettyPrinter.mode is PrettyPrintMode.SILENT+ assert logging.getLogger("pipelex").level == LogLevel.WARNING.int_logging_leveldiff --git a/tests/unit/pipelex/cli/test_agent_doctor_cmd.py b/tests/unit/pipelex/cli/test_agent_doctor_cmd.pyindex 54f107997..805c008e0 100644--- a/tests/unit/pipelex/cli/test_agent_doctor_cmd.py+++ b/tests/unit/pipelex/cli/test_agent_doctor_cmd.py@@ -11,14 +11,29 @@ import typerif TYPE_CHECKING:from pytest_mock import MockerFixture+from pipelex.cli.agent_cli.commands.agent_cli_factory import AGENT_CLI_STDERR_LOG_FIELDSfrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormatfrom pipelex.cli.agent_cli.commands.doctor_cmd import agent_doctor_cmdfrom pipelex.cogt.model_backends.backend_library import BackendCredentialsReport+from pipelex.system.console_target import ConsoleTargetclass TestAgentDoctorCmd:"""Tests for agent_doctor_cmd JSON output."""+ @pytest.fixture(autouse=True)+ def _mock_doctor_bootstrap(self, mocker: MockerFixture) -> None:+ """Stub the runtime bootstrap so unit tests don't load real config or reconfigure logging.++ ``setup_doctor_runtime`` instantiates a PipelexHub, loads config from disk, and+ calls ``log.configure`` (once-per-process). ``apply_agent_cli_output_discipline``+ mutates global PrettyPrinter mode and the hub's console target. Both are out of+ scope for these tests — they cover the command's output shape, not the runtime+ bootstrap mechanics.+ """+ mocker.patch("pipelex.cli.agent_cli.commands.doctor_cmd.setup_doctor_runtime")+ mocker.patch("pipelex.cli.agent_cli.commands.doctor_cmd.apply_agent_cli_output_discipline")+def test_healthy_output_json(self, mocker: MockerFixture, capsys: pytest.CaptureFixture[str]) -> None:"""Healthy checks should produce JSON with all_healthy=true and no recommended_actions."""mocker.patch(@@ -127,3 +142,138 @@ class TestAgentDoctorCmd:parsed = json.loads(capsys.readouterr().err)assert parsed["error"] is Trueassert "unexpected kaboom" in parsed["message"]++ def test_broken_config_skips_bootstrap_and_preserves_partial_report(+ self,+ mocker: MockerFixture,+ capsys: pytest.CaptureFixture[str],+ ) -> None:+ """Regression: when check_config_files reports unhealthy, the doctor must NOT+ run setup_doctor_runtime / check_models — calling them on a broken config+ either raises PipelexConfigError (discarding the partial check tuples) or+ falls through to "Health check failed unexpectedly" instead of the friendly+ translation. The fix short-circuits to a "skipped — fix configuration errors+ first" model section so the full triage report still reaches stdout.+ """+ mock_setup = mocker.patch("pipelex.cli.agent_cli.commands.doctor_cmd.setup_doctor_runtime")+ mock_check_models = mocker.patch("pipelex.cli.agent_cli.commands.doctor_cmd.check_models")+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_config_files",+ return_value=(False, 0, "Configuration validation failed: bogus_field is not a valid field"),+ )+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_telemetry_config",+ return_value=(True, "OK"),+ )+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_backend_credentials",+ return_value=(True, {}, "OK"),+ )++ agent_doctor_cmd(output_format=CliOutputFormat.JSON)++ mock_setup.assert_not_called()+ mock_check_models.assert_not_called()++ parsed = json.loads(capsys.readouterr().out)+ assert parsed["all_healthy"] is False+ # Per-check breakdown still present — the user gets full triage, not just one error line.+ assert parsed["checks"]["config_files"]["healthy"] is False+ assert "bogus_field" in parsed["checks"]["config_files"]["message"]+ assert parsed["checks"]["telemetry"]["healthy"] is True+ assert parsed["checks"]["backend_credentials"]["healthy"] is True+ assert parsed["checks"]["models"]["healthy"] is False+ assert parsed["checks"]["models"]["skipped"] is True+ assert "skipped" in parsed["checks"]["models"]["message"].lower()+ # Config-error recommended action is still emitted.+ assert any("pipelex.toml" in action or "pipelex init config" in action for action in parsed["recommended_actions"])++ def test_pipelex_config_error_from_bootstrap_preserves_partial_report(+ self,+ mocker: MockerFixture,+ capsys: pytest.CaptureFixture[str],+ ) -> None:+ """Regression: a config that passes check_config_files's shape check but fails full+ validation inside setup_doctor_runtime must still produce the full triage envelope.++ Before the fix, the PipelexConfigError arm called agent_error() (NoReturn), which+ discarded the telemetry/backends tuples gathered before the bootstrap and degraded+ the JSON output to a single error payload. The current contract: treat this the+ same as the broken-config short-circuit — mark models as skipped, surface the+ translated message under checks.models, keep every other check in the envelope.+ """+ from pipelex.base_exceptions import PipelexConfigError # noqa: PLC0415++ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.setup_doctor_runtime",+ side_effect=PipelexConfigError("translated validation message"),+ )+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_config_files",+ return_value=(True, 0, "All config files present"),+ )+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_telemetry_config",+ return_value=(True, "Telemetry configured"),+ )+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_backend_credentials",+ return_value=(True, {}, "All backends healthy"),+ )++ agent_doctor_cmd(output_format=CliOutputFormat.JSON)++ parsed = json.loads(capsys.readouterr().out)+ assert parsed["all_healthy"] is False+ # All non-models sections survive intact.+ assert parsed["checks"]["config_files"]["healthy"] is True+ assert parsed["checks"]["telemetry"]["healthy"] is True+ assert parsed["checks"]["backend_credentials"]["healthy"] is True+ # Models marked as skipped with the translated message inline.+ assert parsed["checks"]["models"]["healthy"] is False+ assert parsed["checks"]["models"]["skipped"] is True+ assert "translated validation message" in parsed["checks"]["models"]["message"]++ def test_bootstrap_pins_console_targets_to_stderr(self, mocker: MockerFixture) -> None:+ """Regression: agent_doctor_cmd must pass AGENT_CLI_STDERR_LOG_FIELDS to setup_doctor_runtime.++ The original bug: agent_doctor_cmd bypassed the agent CLI stdout-hardening that+ every other agent CLI command receives via make_pipelex_for_agent_cli. Doctor's+ check_models internally called log.configure with the user's raw log_config, so a+ user with console_log_target = "stdout" and a raised pipelex log level got log+ lines on stdout before the JSON envelope — breaking json.loads(stdout) for any+ downstream consumer.++ This test asserts that agent_doctor_cmd now folds the stderr overrides into the+ bootstrap call, so log/print targets are pinned before any check can fire, and+ that the defense-in-depth discipline helper is also invoked.+ """+ # Re-mock setup_doctor_runtime and apply_agent_cli_output_discipline so we can+ # capture their call args (the autouse fixture also mocks them, but we need the+ # fresh handles here).+ mock_setup = mocker.patch("pipelex.cli.agent_cli.commands.doctor_cmd.setup_doctor_runtime")+ mock_discipline = mocker.patch("pipelex.cli.agent_cli.commands.doctor_cmd.apply_agent_cli_output_discipline")+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_config_files",+ return_value=(True, 0, "OK"),+ )+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_telemetry_config",+ return_value=(True, "OK"),+ )+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_backend_credentials",+ return_value=(True, {}, "OK"),+ )+ mocker.patch(+ "pipelex.cli.agent_cli.commands.doctor_cmd.check_models",+ return_value=(True, "OK", {}),+ )++ agent_doctor_cmd(output_format=CliOutputFormat.JSON)++ mock_setup.assert_called_once_with(log_config_overrides=AGENT_CLI_STDERR_LOG_FIELDS, config_dir=None)+ mock_discipline.assert_called_once()+ # Pin the contract of the field dict itself: both Rich-managed channels must be stderr.+ assert AGENT_CLI_STDERR_LOG_FIELDS["console_log_target"] is ConsoleTarget.STDERR+ assert AGENT_CLI_STDERR_LOG_FIELDS["console_print_target"] is ConsoleTarget.STDERRdiff --git a/tests/unit/pipelex/cli/test_doctor_cmd.py b/tests/unit/pipelex/cli/test_doctor_cmd.pyindex ce66f587d..38e64470b 100644--- a/tests/unit/pipelex/cli/test_doctor_cmd.py+++ b/tests/unit/pipelex/cli/test_doctor_cmd.py@@ -34,7 +34,14 @@ class TestDoctorLayeredResolution:"""def test_do_doctor_cmd_delegates_layered_resolution_to_checks(self, mocker: MockerFixture) -> None:- """do_doctor_cmd should call check functions with no config_dir so they use layered resolution."""+ """do_doctor_cmd should call check functions with no config_dir so they use layered resolution.++ Also asserts the bootstrap is invoked exactly once (no overrides) — pinning the+ contract that human doctor inherits the user's configured log targets.+ """+ # Stub the runtime bootstrap so the test doesn't load real config or call log.configure+ # (once-per-process). The bootstrap call itself is exercised separately.+ mock_setup = mocker.patch("pipelex.cli.commands.doctor_cmd.setup_doctor_runtime")mock_check_config = mocker.patch("pipelex.cli.commands.doctor_cmd.check_config_files",return_value=(True, 0, "OK"),@@ -65,6 +72,8 @@ class TestDoctorLayeredResolution:do_doctor_cmd(fix=False)assert exc_info.value.code == 0+ # Bootstrap runs exactly once with no overrides (human doctor inherits user log targets)+ mock_setup.assert_called_once_with()# All checks must be called without config_dir (layered resolution)mock_check_config.assert_called_once_with()mock_check_telemetry.assert_called_once_with()diff --git a/tests/unit/pipelex/core/test_validation_report.py b/tests/unit/pipelex/core/test_validation_report.pynew file mode 100644index 000000000..e16aff6dc--- /dev/null+++ b/tests/unit/pipelex/core/test_validation_report.py@@ -0,0 +1,69 @@+"""Unit tests for report_validation_error — runs before/around bootstrap.++Pins the regression where ``log.verbose`` raised ``RuntimeError("LogConfig is not set")``+inside ``report_validation_error`` because the doctor calls this helper from inside its+own bootstrap (setup_config raised, hub._config still None, log not configured). The+fix dropped the now-unnecessary log.verbose calls and replaced the broad+``try/except RuntimeError`` around ``get_config().migration`` with non-raising hub+accessors. This test pins both behaviors.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++import pytest+from pydantic import BaseModel, ValidationError++from pipelex.core.validation import report_validation_error+from pipelex.hub import PipelexHub++if TYPE_CHECKING:+ from pytest_mock import MockerFixture+++class _ConfigShape(BaseModel):+ required_field: str+++def _make_validation_error() -> ValidationError:+ try:+ _ConfigShape.model_validate({})+ except ValidationError as exc:+ return exc+ pytest.fail("Expected _ConfigShape.model_validate to raise ValidationError")+++class TestReportValidationError:+ def test_returns_message_when_hub_singleton_is_none(self, mocker: MockerFixture) -> None:+ """report_validation_error must still produce the friendly translation when no hub+ is installed on the process singleton.++ Reproduces the agent doctor's pre-fix crash path: with the new ordering,+ check_config_files calls report_validation_error before setup_doctor_runtime,+ so no hub has been installed yet. (Note: tests/conftest.py's autouse Pipelex.make+ fixture configures ``log`` for this process — this test pins hub-state isolation,+ not log-state isolation.)+ """+ # Ensure the hub singleton is None for this test — mirrors a fresh process+ # where Pipelex.make hasn't run yet.+ mocker.patch.object(PipelexHub, "_instance", None)++ validation_error = _make_validation_error()+ report = report_validation_error(category="config", validation_error=validation_error)++ assert "required_field" in report++ def test_returns_message_when_hub_has_no_config(self, mocker: MockerFixture) -> None:+ """Hub exists but _config is None (setup_config raised mid-flight).++ get_optional_config() returns None; migration hints are omitted; the error+ translation still flows.+ """+ hub_without_config = PipelexHub()+ mocker.patch.object(PipelexHub, "_instance", hub_without_config)++ validation_error = _make_validation_error()+ report = report_validation_error(category="config", validation_error=validation_error)++ assert "required_field" in reportdiff --git a/tests/unit/pipelex/tools/test_log_config_defaults.py b/tests/unit/pipelex/tools/test_log_config_defaults.pynew file mode 100644index 000000000..4d6e571c4--- /dev/null+++ b/tests/unit/pipelex/tools/test_log_config_defaults.py@@ -0,0 +1,76 @@+"""Regression guard for the shipped console targets.++Two TOML files ship in the PyPI wheel and define every consumer's defaults+before any user/project override:++- ``pipelex/pipelex.toml`` — the package-default that ``Pipelex.make()`` loads first.+- ``pipelex/kit/configs/pipelex.toml`` — the template ``pipelex init`` copies to+ ``~/.pipelex/``.++The contract these defaults must satisfy:++- ``console_log_target`` defaults to stderr — logs are diagnostics and must stay+ off the data channel so JSON-emitting CLI commands (e.g.+ ``pipelex-agent models --format json``) stay parseable by downstream tooling+ (``mthds-js`` calls ``JSON.parse(stdout)``).+- ``console_print_target`` defaults to stdout — the main ``pipelex`` CLI emits+ human-facing tables (``show backends``, ``show models``, ``which``, ``doctor``)+ via that channel and ``pipelex show backends > out.txt`` must keep working.++PR #452 introduced the targetable console settings with the stated intent of+stderr for logs; the print target then got over-corrected to stderr in commit+ac858de8, which broke the redirect-to-file flow. This test pins both knobs in+both shipped TOMLs and fails fast if either is flipped in either direction.+"""++from pathlib import Path+from typing import Any++import pytest+import tomli++from pipelex.system.console_target import ConsoleTarget++PIPELEX_REPO_ROOT = Path(__file__).resolve().parents[4]+PACKAGE_DEFAULT_TOML = PIPELEX_REPO_ROOT / "pipelex" / "pipelex.toml"+KIT_TEMPLATE_TOML = PIPELEX_REPO_ROOT / "pipelex" / "kit" / "configs" / "pipelex.toml"+++class TestShippedConsoleTargets:+ @pytest.mark.parametrize(+ ("label", "toml_path"),+ [+ ("package-default", PACKAGE_DEFAULT_TOML),+ ("kit-template", KIT_TEMPLATE_TOML),+ ],+ )+ def test_shipped_targets_are_log_stderr_and_print_stdout(+ self,+ label: str,+ toml_path: Path,+ ) -> None:+ """Both shipped TOMLs route logs to stderr and prints to stdout.++ Reads each file directly (bypassing the layered loader) so the assertion+ is against the shipped values, not the merged config produced by the+ dev project or the user's ``~/.pipelex/`` override. The kit template+ intentionally carries only the user-facing subset of ``LogConfig``+ fields, so we assert against the raw TOML values rather than+ reconstructing the full model.+ """+ assert toml_path.is_file(), f"[{label}] toml not found at {toml_path}"+ with toml_path.open("rb") as toml_file:+ raw_config: dict[str, Any] = tomli.load(toml_file)++ log_config_section = raw_config["pipelex"]["log_config"]+ log_target_raw = log_config_section.get("console_log_target")+ print_target_raw = log_config_section.get("console_print_target")++ assert log_target_raw == ConsoleTarget.STDERR, (+ f"[{label}] console_log_target must be stderr — logs are diagnostics and must stay off the data channel; got {log_target_raw!r}"+ )+ assert print_target_raw == ConsoleTarget.STDOUT, (+ f"[{label}] console_print_target must be stdout — the main pipelex CLI emits human-facing tables "+ f"(show backends/models, which, doctor) via that channel and must remain redirectable to a file; "+ f"got {print_target_raw!r}"+ )diff --git a/tests/unit/pipelex/tools/test_log_idempotence.py b/tests/unit/pipelex/tools/test_log_idempotence.pynew file mode 100644index 000000000..fe866a446--- /dev/null+++ b/tests/unit/pipelex/tools/test_log_idempotence.py@@ -0,0 +1,82 @@+"""Unit tests for Log.configure_if_unset (doctor's idempotent bootstrap).++Pins the once-per-process guard that lets the doctor's setup_doctor_runtime coexist+with library embedders or interleaved tests that may already have called+``log.configure`` earlier in the same process — instead of raising the once-per-process+RuntimeError, ``configure_if_unset`` returns False and no-ops.++Each test uses the ``fresh_log`` fixture so the RichHandler installed by ``configure``+is removed from the global root logger on teardown; otherwise handlers accumulate+across the suite and pollute later test output.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++import pytest++from pipelex.tools.log.log import Log+from pipelex.tools.log.log_config import LogConfig+from pipelex.tools.misc.toml_utils import load_toml_from_path++if TYPE_CHECKING:+ from collections.abc import Iterator+++def log_config() -> LogConfig:+ """Build a real LogConfig from the package defaults — no hand-rolled stub."""+ from pipelex.system.configuration.config_loader import ConfigLoader # noqa: PLC0415++ loader = ConfigLoader()+ config_dict = load_toml_from_path(loader.pipelex_root_dir / "pipelex.toml")+ return LogConfig.model_validate(config_dict["pipelex"]["log_config"])+++def fresh_log() -> Iterator[Log]:+ """Yield a fresh Log() instance and reset it on teardown.++ ``Log.configure`` attaches a RichHandler to the global root logger+ (``logging.getLogger()``) and StreamHandlers to every named poor_logger. Without+ explicit cleanup these handlers leak across tests in the same process — later tests+ inherit duplicated handlers and stray output. ``reset()`` removes them.+ """+ log_instance = Log()+ try:+ yield log_instance+ finally:+ log_instance.reset()+++class TestLogConfigureIfUnset:+ def test_returns_true_and_applies_on_fresh_instance(self, fresh_log: Log, log_config: LogConfig) -> None:+ """A fresh Log() instance has no config; configure_if_unset must apply it."""+ applied = fresh_log.configure_if_unset(log_config=log_config)++ assert applied is True+ # rich_handler is only built inside configure(); seeing it set proves we+ # didn't take the no-op branch.+ assert fresh_log.rich_handler is not None++ def test_returns_false_after_prior_configure_without_raising(self, fresh_log: Log, log_config: LogConfig) -> None:+ """A second call must no-op and return False instead of raising RuntimeError.++ Pins the contract that lets doctor coexist with library embedders / interleaved+ tests that already called log.configure earlier in the process.+ """+ fresh_log.configure(log_config=log_config)++ applied = fresh_log.configure_if_unset(log_config=log_config)++ assert applied is False++ def test_returns_true_again_after_reset(self, fresh_log: Log, log_config: LogConfig) -> None:+ """log.reset() must restore the unset state so configure_if_unset can re-apply."""+ fresh_log.configure(log_config=log_config)+ fresh_log.reset()++ applied = fresh_log.configure_if_unset(log_config=log_config)++ assert applied is Truediff --git a/wip/console-targets-and-agent-cli-stdout.md b/wip/console-targets-and-agent-cli-stdout.mdnew file mode 100644index 000000000..ef0f41c98--- /dev/null+++ b/wip/console-targets-and-agent-cli-stdout.md@@ -0,0 +1,248 @@+# Console targets — partial revert + agent CLI stdout hardening++> **Status:** Both parts landed on branch `fix/Log-target`. Part 1 (partial revert + dual-TOML test) shipped in commit `3d22ea9f`. Part 2 (agent-CLI factory-level hardening + adversarial E2E test) is included in this PR — `make_pipelex_for_agent_cli` now injects `config_overrides` that pin both console targets to stderr from the very first log/print during init, and the new test `test_models_json_stdout_resists_user_targets_override_to_stdout` pins the contract under adversarial user overrides.+>+> **Cold-start prerequisite:** read `pipelex/tools/log/log.py:91`, `pipelex/hub.py:137-148`, `pipelex/cli/agent_cli/commands/agent_cli_factory.py:118-122`, `pipelex/cli/agent_cli/commands/agent_output.py` (where `agent_success` writes to stdout), and `pipelex/tools/misc/pretty.py:214` (the bare `Console()` instantiation).++## TL;DR++We have two independent knobs in `[pipelex.log_config]`:++- `console_log_target` — controls the `RichHandler` attached to Python's logging system. **Logs are diagnostics → stderr.** Flipping the default to `stderr` is correct and stays.+- `console_print_target` — controls the hub's `_console` returned by `get_console()`. This console is used by the main `pipelex` CLI for human-facing **data tables** (`pipelex show backends`, `pipelex show models`, `pipelex which`, `pipelex doctor`). **Data → stdout.** Flipping the default to `stderr` was an over-correction and must be reverted.++The actual bug ("logs polluting stdout breaks downstream JSON parsers like `mthds-js`'s `PipelexRunner`") was about logs, not prints. The log-target flip alone fixes it.++Separately, the agent CLI's stdout channel is a strict JSON contract for downstream tooling. It deserves explicit, defense-in-depth hardening at the factory level so a user override in `~/.pipelex/pipelex.toml` cannot re-pollute it.++## Part 1 — Partial revert on `fix/Log-target`++### What stays++In all three TOML files, **keep** `console_log_target = "stderr"`:++- `pipelex/pipelex.toml:73`+- `pipelex/kit/configs/pipelex.toml:164`+- `.pipelex/pipelex.toml:164`++Rationale: logs are diagnostics, they belong on stderr per 12-factor/Unix convention. This matches the stated intent of PR #452 ("default to stderr for outputs happening before initialization"). Empirically this is what surfaces the original bug — the failing case in `tests/e2e/agent_cli/test_stdout_is_clean_json.py` is a `log.debug(...)` call from `pipelex/system/telemetry/telemetry_factory.py:77` routed through the `RichHandler`, which obeys `console_log_target`.++### What reverts++In all three TOML files, **flip back** `console_print_target = "stdout"`:++- `pipelex/pipelex.toml:74` → `console_print_target = "stdout"`+- `pipelex/kit/configs/pipelex.toml:165` → `console_print_target = "stdout"`+- `.pipelex/pipelex.toml:165` → `console_print_target = "stdout"`++Rationale: confirmed user-facing regression. With the post-flip tree:++```+$ .venv/bin/pipelex show backends > out.txt 2> err.txt+$ wc -c out.txt err.txt+ 0 out.txt+4110 err.txt+```++The entire backends table now lands on stderr. Same regression for `pipelex show models <backend>`, `pipelex which <code>`, `pipelex doctor`, and especially `pipelex show models <backend> --flat` whose docstring explicitly advertises it as "easy to copy-paste into configuration files".++The breakage is real because `pipelex show backends` (and friends) route through `get_console()` → `pipelex_hub._console` → controlled by `console_print_target`. See `pipelex/cli/commands/show_cmd.py:96` and the `pipelex_hub.set_console_print_target(...)` call at `pipelex/pipelex.py:118` driven by the config value.++### What changes in tests++`tests/unit/pipelex/tools/test_log_config_defaults.py` (already on the branch): widen the assertion to pin both targets to their intended values, so neither knob can be flipped silently in either direction:++```python+assert log_config.console_log_target == ConsoleTarget.STDERR # logs are diagnostics+assert log_config.console_print_target == ConsoleTarget.STDOUT # prints are data+```++Also extend the test to additionally validate the **kit template** (`pipelex/kit/configs/pipelex.toml`) — currently a partial revert of just the kit template (the file `pipelex init` copies to `~/.pipelex/`) would pass this test silently. Either add a second test or parametrize over both `(package_default, kit_template)` paths.++`tests/e2e/agent_cli/test_stdout_is_clean_json.py` (already on the branch): no changes needed — it surfaces the LOG-target bug via the `RichHandler`, and the log target stays `stderr` post-revert. The test stays green and stays meaningful.++### What changes in the changelog++Rewrite the `## [Unreleased]` entry to narrow the scope. Replace the current single bullet with:++```markdown+### Fixed++- **`console_log_target` package default is now `stderr` (was `stdout`).** Logs now stay off the data channel by default, matching the intent of PR #452 ("default to stderr for outputs happening before initialization"). Downstream tooling that parses `pipelex` / `pipelex-agent` stdout as JSON (e.g. `mthds-js`'s `PipelexRunner`) is no longer at risk of stdout pollution from package-level logs — the bug was latent for stock installs because the agent-CLI JSON paths happen not to log at INFO+, but surfaced for anyone who raised `package_log_levels.pipelex` to DEBUG or added a setup-time log on the command path. Same flip applied to the kit template (`pipelex/kit/configs/pipelex.toml`) that `pipelex init` copies to `~/.pipelex/`. **Note:** `console_print_target` is intentionally left at `stdout` — the main `pipelex` CLI emits human-facing tables (`show backends`, `show models`, `which`, `doctor`) via that channel, and downstream piping (`pipelex show backends > out.txt`) must keep working.+```++Drop the migration sentence that said "anyone who was capturing stdout to collect logs should switch to capturing stderr" — it's no longer true at this scope (logs were on stdout already only by virtue of `console_log_target = "stdout"`; same flip). Keep the framing as a `Fixed`, not a `Breaking`, because no user behavior that *should have worked* gets broken.++### Commit shape++One commit on `fix/Log-target`:++```+fix(logs): keep console_print_target on stdout (logs to stderr, prints to stdout)++Walks back the print_target half of ac858de8 — that flip broke+`pipelex show backends > out.txt` (empty file). Log target stays on+stderr (the actual fix for stdout-as-JSON-channel pollution); print+target reverts to stdout because the main pipelex CLI's human-facing+tables go through get_console() and must remain redirectable.+```++Then run `make agent-check && make agent-test` and force-push the branch (history-rewrite is fine here since the PR isn't merged yet).++## Part 2 — Agent CLI stdout hardening (the deeper fix) — LANDED++> Why this is its own piece of work: the partial revert above restores correctness for stock installs, but the agent CLI's stdout-as-JSON-channel contract is too important to leave at the mercy of the user's `~/.pipelex/pipelex.toml`. A user override of `console_print_target = "stderr"` shouldn't break the agent CLI's data channel either way, and a hypothetical override of `console_log_target = "stdout"` must NOT re-pollute the agent CLI's stdout. The defense should live in the factory, not depend on the config defaults staying lucky.++> **Implementation note vs the original plan below.** The original plan proposed a single post-init `get_pipelex_hub().set_console_print_target(STDERR)` line. That covers post-init `get_console().print(...)` calls, but does NOT cover logs/prints that fire DURING `Pipelex.make()` (e.g. `telemetry_factory.py:77` DEBUG line, the deck-notice print). The shipped fix uses `config_overrides` passed to `Pipelex.make()` to pin both `console_log_target` and `console_print_target` to `stderr` from the very first log/print, which is strictly stronger. The post-init `set_console_print_target` and `log.redirect_to_stderr()` calls are kept as defense-in-depth.++### The contract we want++For every `pipelex-agent <command>` invocation:++| Channel | What goes there | Enforcement |+|---|---|---|+| **stdout** | ONLY the structured success envelope (JSON via `--format json`, or markdown via `--format markdown`). Nothing else. | `agent_success` / `agent_success_formatted` use bare `print(...)` to stdout — that's it. No log handler, no hub console, no `pretty_print` ever writes to stdout. |+| **stderr** | Logs (any level), all `get_console().print(...)` output (banners, deck notices, plugin list tables), all `pretty_print(...)` output (currently silenced via `PrettyPrinter.mode = PrettyPrintMode.SILENT`), structured error envelopes via `agent_error`. | Factory forces all three subsystems to stderr at boot, regardless of user config. |++The contract must hold:++- Regardless of `console_log_target` / `console_print_target` in the user's config.+- Regardless of `package_log_levels.pipelex` raising the verbosity.+- Regardless of any `get_console().print(...)` call site added in the future on the agent CLI's setup or command path.++### Current state (`make_pipelex_for_agent_cli`, `pipelex/cli/agent_cli/commands/agent_cli_factory.py:118-122`)++```python+# Suppress Rich pretty-printing and INFO/DEV/DEBUG log noise so that agent+# commands only emit structured JSON. Warnings and errors still reach stderr.+PrettyPrinter.mode = PrettyPrintMode.SILENT+log.set_level_for_package("pipelex", log_level)+log.redirect_to_stderr()+return pipelex_instance+```++- ✅ `PrettyPrinter.mode = SILENT` neutralizes `pretty_print(...)` entirely (the bare `Console()` at `pretty.py:214` would have hit stdout — silencing the printer is the simplest defense).+- ✅ `log.redirect_to_stderr()` forces `RichHandler.console = Console(file=sys.stderr)` regardless of `console_log_target`.+- ❌ **Missing:** no symmetric `pipelex_hub.set_console_print_target(ConsoleTarget.STDERR)` call. The hub's `_console` is whatever the user's `console_print_target` says — which, after Part 1, defaults to stdout. So any `get_console().print(...)` reached during agent CLI setup or command execution writes to stdout. That's a JSON-channel pollution risk.++### Where `get_console()` is reached on the agent CLI path++Grep `get_console` across the codebase. Today the call sites include:++- `pipelex/cli/_cli.py:111` — banner in `app_callback` (main CLI only, the agent CLI has its own callback in `_agent_cli.py` which does not print the banner — verify).+- `pipelex/cli/deck_notice.py:34` — first-run deck notice. Triggered from `Pipelex.make()` setup paths. Could fire under the agent CLI.+- `pipelex/plugins/openai/openai_list.py`, `anthropic_list.py`, `google_list.py`, `mistral_list.py`, `bedrock_list.py` — backend list tables. Reachable from `pipelex show models <backend>` (main CLI) but NOT directly from agent CLI commands today — verify.+- `pipelex/cli/error_handlers.py` — error panels for various exception types. Used by the main CLI, not the agent CLI (agent CLI uses `agent_error()` instead).++The risk surface today is small — primarily `deck_notice` and any future setup-time addition. But "small" is not "zero", and the contract is too important to depend on a static-analysis snapshot.++### The fix++Add ONE line to `make_pipelex_for_agent_cli` (after Pipelex init, alongside the existing log redirect):++```python+from pipelex.hub import get_pipelex_hub+from pipelex.system.console_target import ConsoleTarget++# (after PrettyPrinter.mode = SILENT and before/after log.redirect_to_stderr())+get_pipelex_hub().set_console_print_target(target=ConsoleTarget.STDERR)+```++This makes `get_console()` return a stderr-bound Console for the entire agent CLI process lifetime, regardless of what the user's config said. Symmetric to `log.redirect_to_stderr()`. Together with the existing `PrettyPrinter.mode = SILENT`, every diagnostic output channel is pinned to stderr at the boundary.++Confirm the hub-access import path: today the file imports `Pipelex`, not the hub directly. Find the canonical import (it's likely `from pipelex.hub import get_pipelex_hub` — verify in `pipelex/hub.py`).++### Test coverage++Add a new test (or extend `tests/e2e/agent_cli/test_stdout_is_clean_json.py`) that pins the defense:++**Test: agent CLI ignores user override of `console_print_target = "stderr"`** — wait, this would actually trivially pass since the override IS stderr. The real test is the **inverse**:++**Test: agent CLI keeps stdout clean even when user overrides BOTH targets to stdout.**++```python+def test_agent_cli_resists_user_override_to_stdout(+ self,+ hermetic_home: Path,+ offline_subprocess_env: dict[str, str],+) -> None:+ """Defense-in-depth: even with `console_log_target = "stdout"` AND+ `console_print_target = "stdout"` in the user's pipelex.toml, the agent+ CLI must keep its stdout channel clean for JSON consumers.+ """+ pipelex_toml = hermetic_home / ".pipelex" / "pipelex.toml"+ _set_pipelex_package_log_level_to_debug(pipelex_toml)+ _set_console_targets(pipelex_toml, log_target="stdout", print_target="stdout")++ result = subprocess.run(+ [str(PIPELEX_AGENT_BIN), "--log-level", "debug", "models", "--format", "json"],+ env=offline_subprocess_env, cwd=str(hermetic_home),+ capture_output=True, text=True, check=False, timeout=120,+ )++ assert result.returncode == 0, ...+ payload = json.loads(result.stdout) # must still parse cleanly+ assert payload.get("success") is True+```++This is the test that pins the contract end-to-end. The helper `_set_console_targets` rewrites the two TOML keys (similar to the existing `_set_pipelex_package_log_level_to_debug`). Watch out for the helper-fragility class flagged in the code review (use anchored regex or a tomlkit round-trip rather than `startswith`).++Optionally also parametrize the test across multiple JSON-emitting agent commands (`models`, `check-model`, `validate bundle --format json --dry-run`, `doctor --format json`) so a future setup-path `get_console()` addition on any one of them surfaces immediately.++### Companion: audit `get_console()` call sites for "data vs diagnostic"++This is the larger architectural cleanup, NOT in scope for this PR but worth a follow-up issue:++`get_console()` today is used for both:++- **Data** that users pipe to files (`pipelex show backends`, `pipelex show models`, `pipelex which`) — should write to stdout.+- **Diagnostics** that users want on stderr (banners, deck notices, error panels) — should write to stderr.++Mixing the two in one knob is the root cause of the current confusion. The cleanest long-term shape is to split the hub into two consoles:++- `hub.get_data_console()` — pinned to stdout. Used by `show backends`, `show models`, `which`, `doctor`, `show config`, `show pipe`. Always redirectable to a file.+- `hub.get_diag_console()` — pinned to stderr. Used by banner, deck notice, error panels, anything that's "talking to the human about the run".++`pretty_print` would also pick one of the two (probably `data` for `show pipe`, `show config`; or expose both flavors). The `console_print_target` config knob then either goes away entirely (the split is hardcoded) or is renamed and re-scoped to only the diag console (which would be weird since stderr is the only sensible default).++That's a bigger PR. Out of scope for `fix/Log-target`. File as a follow-up.++## Acceptance criteria++For Part 1 (partial revert) — must hold before re-pushing `fix/Log-target`:++- [ ] `console_log_target = "stderr"` in all three TOML files.+- [ ] `console_print_target = "stdout"` in all three TOML files.+- [ ] `pipelex show backends > /tmp/out.txt && [ -s /tmp/out.txt ]` (non-empty stdout).+- [ ] `pipelex-agent --log-level debug models --format json | jq .success` returns `true` (stdout still clean JSON).+- [ ] Unit test pins both targets (log=stderr, print=stdout); covers package default AND kit template paths.+- [ ] E2E test still passes — surfaces the log-target bug via `log.debug` → RichHandler → stderr.+- [ ] CHANGELOG entry narrowed to scope (logs only).+- [ ] `make agent-check && make agent-test` clean.++For Part 2 (agent CLI hardening) — LANDED in this PR:++- [x] `make_pipelex_for_agent_cli` injects `config_overrides` pinning both targets to stderr, and additionally calls `get_pipelex_hub().set_console_print_target(STDERR)` post-init alongside `log.redirect_to_stderr()`.+- [x] New E2E test `test_models_json_stdout_resists_user_targets_override_to_stdout` pins the contract under adversarial user overrides (both targets set to stdout, package log level DEBUG, `--log-level debug`).+- [ ] (Optional but recommended) E2E test parametrized across `models`, `check-model`, `doctor`, `validate bundle` — all JSON-emitting agent commands. Deferred: the current test exercises the same `Pipelex.make()` setup path that every other agent command goes through, so adding more command variants gives marginal extra signal.+- [x] Docstring of `make_pipelex_for_agent_cli` updated to explicitly call out the stdout-channel contract.++## How to start (cold)++1. `git checkout fix/Log-target && git log --oneline -3` — confirm at `ac858de8`.+2. Run the regression check first to internalize what's broken:+ ```+ .venv/bin/pipelex show backends > /tmp/out.txt 2> /tmp/err.txt+ wc -c /tmp/out.txt /tmp/err.txt # expect 0 out, ~4k err+ ```+3. Do Part 1 (partial revert + test + changelog) as one commit. Push.+4. Open a fresh branch `feature/agent-cli-stdout-defense` off `dev` (after Part 1 lands) for Part 2.+5. Implement Part 2 (one-line hub call + new E2E test + docstring update). Push as a separate PR.++## References++- Original bug commit: `ac858de8` "fix: route console logs and prints to stderr by default"+- The PR that introduced the targetable knobs: `dd0c9d266` "feature/JSONContent" (PR #452, 2025-11-18) — stated intent was stderr defaults; the package default ended up flipped to stdout.+- The PR that propagated the wrong default into the kit template: `9580406c` "Feature/chicago" (PR #706, 2026-02-25).+- Downstream JSON consumer that motivated the fix: `mthds-js`'s `PipelexRunner` — does `JSON.parse(stdout)` on `pipelex-agent models --format json`, `check-model --format json`, etc.+- Agent CLI authoring conventions: `pipelex/cli/agent_cli/CLAUDE.md`.