Skip to content

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.

feature/Rich-behind-extra · L-260916-fe7969 — rich extra, lazy import, guard (#1210)

Louis Choquelf766e39e93c7
diff --git a/.drift/acks/config-docs.toml b/.drift/acks/config-docs.toml
index 84083e0c2..cb4c4bf4a 100644
--- a/.drift/acks/config-docs.toml
+++ b/.drift/acks/config-docs.toml
@@ -1,15 +1,15 @@
contract = "config-docs"
-digest = "sha256:882e711271ff0716aefa3315cc794c70ac30667f386bca3436d260df3ec1f0c7"
+digest = "sha256:f7050e3e65c768937a8f9796327e1d85501bc6d3d55849955ebc0610e1dfd64e"
reviewed_by = "Louis Choquel"
-reviewed_at = "2026-09-25T14:40:46Z"
-rationale = "Merge of dev, which now carries the redaction member, into the gcp sink branch. Each side was acked on its own; the merge only combines them: log_config.py holds both GcpLogSinkConfig and LogRedactionConfig with LogConfig carrying both the redaction and gcp sections, and pipelex.toml ships both [runtime.log.gcp] and [runtime.log.redaction]. logging-config.md already documents both sections and both appear in its example configuration; both are additions with shipped defaults, so no migration ledger entry is owed, and the defaults@5 golden carries both tables."
+reviewed_at = "2026-09-25T14:56:51Z"
+rationale = "Merge of dev, which now carries the redaction and gcp members, into the Rich extraction branch. The trigger files combine what each side acked on its own: pipelex.toml and log_config.py are dev's, with both the redaction and gcp sections already documented in logging-config.md, and config_check.py only defers its Rich Panel import into the warning branch that prints it, because Rich is now the cli extra. No config model, default or validator changes in the merge itself, so no configuration doc and no migration ledger entry is owed."
[trigger_files]
"pipelex/cogt/config_cogt.py" = "blob:02f71cb4a6b01aebda59c2e31f262ef9c865e17b"
"pipelex/cogt/img_gen/img_gen_job_components.py" = "blob:084985080413fd8d6c3b1b9b0747020cb0161858"
"pipelex/pipelex.toml" = "blob:8d5b60c54ea342992546918b718563a02629d31f"
"pipelex/system/configuration/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"
-"pipelex/system/configuration/config_check.py" = "blob:88e15a92b186088a5ea1c7c4ebcedac830707d3a"
+"pipelex/system/configuration/config_check.py" = "blob:2d5de29aba3d2ce205d3d82b4623f37b53108332"
"pipelex/system/configuration/config_loader.py" = "blob:ac384ce993933656682999c26afffb4c9f9b1975"
"pipelex/system/configuration/config_model.py" = "blob:83b29dc6e93393c9b98c4353636caf0135c80339"
"pipelex/system/configuration/config_root.py" = "blob:c7d43851270912d17413cfc6a511247d3c7cc160"
diff --git a/.drift/acks/hub-layering-convention.toml b/.drift/acks/hub-layering-convention.toml
index 824d79221..d403d60c7 100644
--- a/.drift/acks/hub-layering-convention.toml
+++ b/.drift/acks/hub-layering-convention.toml
@@ -1,10 +1,10 @@
contract = "hub-layering-convention"
-digest = "sha256:ba531715aa9e9f29262c7ea2fd18c4a63e31b9878c5b5f1507b135f511aa7b38"
-reviewed_by = "Claude (Opus 5)"
-reviewed_at = "2026-09-16T08:54:20Z"
-rationale = "Round-2 review fix in runtime_hub is docstring-only: reset_boot_state no longer claims the agent CLI pins silent before booting (it pins after), and now says a mode assigned after boot is released too. No import, accessor or layer placement changed. Read docs/contribute/hub-layering.md: it specifies the boundary, the forbidden import list and the accessor table, and describes neither reset_boot_state nor the pretty-print mode. Nothing stale."
+digest = "sha256:75768fa677bc8550119a8b20ce80c22e5edfa1040eee6b32fe574f7ae2019435"
+reviewed_by = "Louis Choquel"
+reviewed_at = "2026-09-17T17:57:19Z"
+rationale = "The runtime hub no longer imports Rich at module level. Its console accessor builds the Rich console lazily after checking that the cli extra is installed, and the console print target now stores the stream instead of building a console. No accessor was added, moved or removed and no layer placement changed, so the partition table in the hub-layering doc, which lists get_console as the console accessor, is still accurate. The new Rich import guard reuses the import graph of the hub-layering guard without changing it, and the rich-imports contribute doc says so."
[trigger_files]
"pipelex/cli/dev_cli/commands/hub_layering_guard.py" = "blob:2dbadcbab7d44364a7b5f1d16268b23b26700a00"
"pipelex/interpreter_hub.py" = "blob:327e75d0fbb5bdf46f6cbf06024f83840f0106d0"
-"pipelex/runtime_hub.py" = "blob:4682e96a187338d7c0c6728319f0b81e270b0c21"
+"pipelex/runtime_hub.py" = "blob:48caf3ba024b97e112aca1a8c3db5e5d2f17b4cd"
diff --git a/.github/workflows/lint-check.yml b/.github/workflows/lint-check.yml
index edc19967e..1b0f95467 100644
--- a/.github/workflows/lint-check.yml
+++ b/.github/workflows/lint-check.yml
@@ -156,7 +156,32 @@ jobs:
run: make check-hub-layering
# --------------------------------------------------------------------------
-# 6. Drift contracts — single job, version-independent
+# 6. Rich imports — single job, version-independent. Rich is the `cli` extra,
+# so no module outside pipelex/cli/ may import it at module level.
+# --------------------------------------------------------------------------
+ lint-rich-imports:
+ name: Lint (rich imports)
+ runs-on: ubuntu-latest
+ env:
+ VIRTUAL_ENV: ${{ github.workspace }}/.venv
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install uv (with cache)
+ uses: astral-sh/setup-uv@v7
+ with:
+ enable-cache: true
+ cache-dependency-glob: "uv.lock"
+
+ - name: Install dependencies
+ run: PYTHON_VERSION=3.11 TEST_PROFILE=ci make install
+
+ - name: Run Rich import check
+ run: make check-rich-imports
+
+# --------------------------------------------------------------------------
+# 7. Drift contracts — single job, version-independent
# BLOCKING, but through the ruleset rather than through lint-all: `Lint
# (drift-contracts)` is named as a required status check on both `dev` and
# `main`, so an open contract already stops the merge. It stays out of
@@ -185,7 +210,7 @@ jobs:
run: make drift-check
# --------------------------------------------------------------------------
-# 7. Agent rules sync — single job, version-independent
+# 8. Agent rules sync — single job, version-independent
# --------------------------------------------------------------------------
lint-agent-rules:
name: Lint (agent-rules)
@@ -209,16 +234,16 @@ jobs:
run: make check-rules
# --------------------------------------------------------------------------
-# 8. Aggregator job — the required status check that covers every lint job,
+# 9. Aggregator job — the required status check that covers every lint job,
# including the ones the rulesets do not name individually
-# (`Lint (hub layering)`, `Lint (agent-rules)`). It is not the only
-# required lint check: the rulesets name several of the jobs above by
-# name as well. Anything added to `needs` becomes blocking through here.
+# (`Lint (hub layering)`, `Lint (rich imports)`, `Lint (agent-rules)`). It is
+# not the only required lint check: the rulesets name several of the jobs
+# above by name as well. Anything added to `needs` becomes blocking through here.
# --------------------------------------------------------------------------
lint-all:
name: Lint (all)
runs-on: ubuntu-latest
- needs: [lint-ruff-plxt, lint-typecheck, lint-config-sync, lint-keyword-only, lint-hub-layering, lint-agent-rules]
+ needs: [lint-ruff-plxt, lint-typecheck, lint-config-sync, lint-keyword-only, lint-hub-layering, lint-rich-imports, lint-agent-rules]
if: always()
steps:
@@ -229,6 +254,7 @@ jobs:
[ "${{ needs.lint-config-sync.result }}" != "success" ] || \
[ "${{ needs.lint-keyword-only.result }}" != "success" ] || \
[ "${{ needs.lint-hub-layering.result }}" != "success" ] || \
+ [ "${{ needs.lint-rich-imports.result }}" != "success" ] || \
[ "${{ needs.lint-agent-rules.result }}" != "success" ]; then
echo "::error::At least one lint job failed."
exit 1
diff --git a/.github/workflows/lint-fresh-check.yml b/.github/workflows/lint-fresh-check.yml
index eca40c29b..03b214caf 100644
--- a/.github/workflows/lint-fresh-check.yml
+++ b/.github/workflows/lint-fresh-check.yml
@@ -67,6 +67,9 @@ jobs:
- name: Run hub layering check
run: make check-hub-layering
+ - name: Run Rich import check
+ run: make check-rich-imports
+
- name: Run drift contracts check
run: make drift-check
diff --git a/AGENTS.md b/AGENTS.md
index bde475258..656c7ff03 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -9,7 +9,7 @@
```bash
make agent-check
# If the current system doesn't have the `make` command,
- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering drift-check)
+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check)
```
This runs multiple code quality tools:
@@ -176,6 +176,7 @@
- Do not import libraries in functions or classes unless in very specific cases, to be discussed with the user, as they would required a `# noqa: ...` comment to pass linting
- Do not bother with ordering the imports or removing unused imports, our Ruff linter will handle it for us.
- `if TYPE_CHECKING:` blocks must always be the **last** block in the imports section, placed after all regular imports.
+- **Rich is the standing exception.** It is the `cli` extra, which a server does not install, so outside `pipelex/cli/` it is imported inside the function that renders, after `require_rich(...)` (`pipelex.tools.misc.rich_extra`) or `require_rich_for_rendering()` (`pipelex.tools.misc.pretty`), and a type-only import of it goes under `if TYPE_CHECKING:`. Such a deferred import needs no suppression comment, and `make check-rich-imports` refuses a module-level one, as well as a module-level import of a CLI module that imports Rich. See `docs/contribute/rich-imports.md`.
#### Removing unused imports
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3052eee24..6c3ba9e5f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@
### Changed
+- **Rich is the `cli` extra (Breaking)**: `rich` is no longer a core dependency, so install `pipelex[cli]` for the `pipelex` and `pipelex-agent` commands, the `console` log sink and the `rich` pretty-print mode (`uv tool install "pipelex[cli]"`). The runtime imports Rich only inside the code that renders, so a process installed without it boots and runs methods with `sink = "json"` and `pretty_print_mode` set to `"poor"` or `"silent"`, while a boot selecting the `console` sink or the `rich` mode without Rich stops naming the extra, and a `get_console()`, `rendered_pretty()`, model-listing, pipe-listing or directory-diff call raises `MissingDependencyError` naming it too. What this delivers is that no code path the runtime takes on the way to running a method needs Rich — not an environment with no Rich in it, since `typer` and `instructor` are core dependencies that both require it, so a plain `pip install pipelex` still installs Rich and `import pipelex` still loads it. Two consequences worth knowing: a `poor`-mode panel title no longer substitutes emoji codes, the substitution table being Rich's own, and a cost report whose console table cannot render still writes its CSV. [Rich Imports](contribute/rich-imports.md) documents the convention and the `make check-rich-imports` guard, which also refuses a deferred Rich import that no `require_rich(...)` precedes.
- **Loggers are named by module (Breaking)**: a record from `pipelex/pipe_operators/pipe_llm.py` is emitted on the `pipelex.pipe_operators.pipe_llm` logger instead of `pipelex`, so a handler keyed on the bare package name must key on the prefix, a filter an integration attached to the `pipelex` logger must move to its handler since Python never consults an ancestor logger's filters for a record propagating up from a module logger, and a `package_log_levels` key now works at module depth too, `pipelex-pipe_operators-pipe_llm = "DEBUG"` for instance. The stack walk that named the logger on every line is gone, replaced by one frame lookup, and the caller-info templates that name the module now render instead of raising.
- **`include_exception` carries the traceback as the record's `exc_info`**: instead of splicing `traceback.format_exc()` into the message, so the console renders one Rich traceback, the `json` sink an `exception` field and the `otlp` sink the `exception.*` attributes, and a call made outside an `except` block carries nothing where a `NoneType: None` line used to be appended.
- **Teardown removes only the handlers Pipelex installed**: `log.reset()` no longer strips every handler off the root logger nor calls `logging.shutdown()`, so a host's or a test's handler survives a Pipelex teardown; the sink's handler is flushed and closed, which is where a batching sink ships what it still holds.
diff --git a/CLAUDE.md b/CLAUDE.md
index e32296030..5400ba8cd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,7 +4,7 @@
`make` targets activate the virtual environment themselves; anything else (`pytest`, `pipelex`, `pipelex-dev`) runs from `.venv/bin/` (`.venv\Scripts\` on Windows), never bare. The Makefile is the reference for every target and alias; without `make`, read the target there and run its prerequisites one by one.
-- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering drift-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check and the drift contracts. The drift digest reads the git index, so stage your changes before the check.
+- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module) and the drift contracts. The drift digest reads the git index, so stage your changes before the check.
- **Keyword-only arguments** (the convention is in the standards and in `docs/contribute/keyword-only-arguments.md`): `make check-keyword-only` (`cko`) is the gate, `make fix-keyword-only` (`fko`) inserts the bare `*` where it can — on ungranted subjects too — and reports the shapes it cannot fix, and `make subject-grant FUNC="<path>::<qualname>" RATIONALE="…"` (`sgr`) grants a positional subject. Grant before `make agent-check`, which runs the fixer.
- **Drift contracts.** When `make drift-check` reports an open contract: `make drift-plan`, review and fix the stale targets, `git add` the trigger files, then `make drift-ack CONTRACT=<id> RATIONALE="…"`. No bypass flag; "reviewed, no doc change needed" is a legitimate rationale. See `docs/contribute/drift-contracts.md`.
- **`make agent-test` at the end of every coding session.** Heartbeat lines while running, full output only on failure. If it hangs or fails opaquely, `make agent-test-debug` (`atd`) adds stale-process cleanup, an outer timeout and a live log; the methodology is `docs/agents/debugging-hanging-pytest-runs.md`. At intermediate steps in a local setup, running only the relevant tests is fine: `.venv/bin/pytest -x -q tests/unit/path/to/test_module.py`, or `make t TEST=<name>` (pytest `-k` substring matching; `TEST=LF` reruns the last failures). `make tp` / `make test-with-prints` are for a human at a terminal; an agent in the cloud or in a sandbox uses `make agent-test` only.
diff --git a/Makefile b/Makefile
index 4a9d42b13..4fa6602a3 100644
--- a/Makefile
+++ b/Makefile
@@ -184,6 +184,8 @@ make subject-grant - Record a subject grant (FUNC="<path>::<qualname>
make sgr - Shorthand -> subject-grant
make check-hub-layering - Enforce the runtime_hub / interpreter_hub layering boundary
make chl - Shorthand -> check-hub-layering
+make check-rich-imports - Refuse a module-level Rich import or reach outside pipelex/cli/ (Rich is the cli extra)
+make cri - Shorthand -> check-rich-imports
make check-TODOs - Check for TODOs
make docs - Serve documentation locally with mkdocs
@@ -223,7 +225,7 @@ export HELP
.PHONY: \
all help env env-verbose check-uv check-uv-verbose lock install update build \
format lint ruff-format ruff-lint pyright mypy pylint plxt plxt-format plxt-lint \
- rules rules-claude-standalone up-kit-configs ukc check-config-sync ccs check-keyword-only cko fix-keyword-only fko subject-grant sgr check-hub-layering chl check-rules check-urls cu insert-skeleton \
+ rules rules-claude-standalone up-kit-configs ukc check-config-sync ccs check-keyword-only cko fix-keyword-only fko subject-grant sgr check-hub-layering chl check-rich-imports cri check-rules check-urls cu insert-skeleton \
drift-plan dp drift-check dc drift-ack da \
cleanderived cleanenv cleanall \
test test-xdist t test-quiet tq test-with-prints tp test-inference ti \
@@ -396,6 +398,13 @@ check-hub-layering: env
chl: check-hub-layering
@echo "> done: chl = check-hub-layering"
+check-rich-imports: env
+ $(call PRINT_TITLE,"Refusing module-level Rich imports and reaches outside pipelex/cli/")
+ $(VENV_PIPELEX_DEV) check-rich-imports --quiet
+
+cri: check-rich-imports
+ @echo "> done: cri = check-rich-imports"
+
drift-plan: env
$(VENV_PIPELEX_DEV) drift plan $(CONTRACT)
@@ -1273,10 +1282,10 @@ cc: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet genera
up: generate-mthds-schema-quiet generate-corpus-vocabulary-quiet update-gateway-models-quiet up-kit-configs rules
@echo "> done: up = generate-mthds-schema generate-corpus-vocabulary update-gateway-models up-kit-configs rules"
-check: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet update-gateway-models-quiet check-unused-imports check-config-sync check-rules check-urls check-gateway-models check-mthds-schema check-ledger check-migration-schemas check-keyword-only check-hub-layering drift-check format lint pyright mypy pylint
+check: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet update-gateway-models-quiet check-unused-imports check-config-sync check-rules check-urls check-gateway-models check-mthds-schema check-ledger check-migration-schemas check-keyword-only check-hub-layering check-rich-imports drift-check format lint pyright mypy pylint
@echo "> done: check"
-agent-check: fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering drift-check
+agent-check: fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check
@echo "> done: agent-check"
v: validate
diff --git a/README.md b/README.md
index a58ab6052..bb908caba 100644
--- a/README.md
+++ b/README.md
@@ -91,15 +91,16 @@ This repository is the Pipelex runtime: the Python package that reads a `.mthds`
### Install
```bash
-uv tool install pipelex
+uv tool install "pipelex[cli]"
pipelex init
pipelex doctor
```
-`pipelex init` writes your `~/.pipelex` configuration and offers to install the editor extension; `pipelex doctor` reports what is configured and what is missing.
+`pipelex init` writes your `~/.pipelex` configuration and offers to install the editor extension; `pipelex doctor` reports what is configured and what is missing. The `cli` extra installs Rich, which the `pipelex` and `pipelex-agent` commands render their output through.
Some providers and features need an extra:
+- `cli`: Rich, for the `pipelex` and `pipelex-agent` commands, the `console` log sink and the `rich` pretty-print mode. Install it wherever Pipelex runs in a terminal; a server leaves it out and selects the `json` log sink with the `poor` or `silent` pretty-print mode, and then nothing the runtime does on the way to running a method asks for Rich. Leaving the extra out does not make the environment Rich-free: `typer` and `instructor` are core dependencies and both require Rich, so a stock install still contains it
- `anthropic`: Anthropic/Claude support for text generation
- `google`: Google models (Vertex) support for text generation
- `google-genai`: Google Gemini API support for text and image generation
@@ -112,7 +113,7 @@ Some providers and features need an extra:
Name the ones you need when you install, or take them all:
```bash
-uv tool install "pipelex[anthropic,google,google-genai,mistralai,bedrock,fal,linkup,docling]"
+uv tool install "pipelex[cli,anthropic,google,google-genai,mistralai,bedrock,fal,linkup,docling]"
```
### Configure AI Access
diff --git a/docs/configuration/config-practical/logging-config.md b/docs/configuration/config-practical/logging-config.md
index 826606241..b5c0d9086 100644
--- a/docs/configuration/config-practical/logging-config.md
+++ b/docs/configuration/config-practical/logging-config.md
@@ -44,7 +44,7 @@ sink = "console"
```
- Names the registered log sink boot installs on the root logger, the way `runtime.storage.method` names a storage backend
-- `"console"`: the Rich handler, for a terminal. The default, so the CLI keeps its rendering
+- `"console"`: the Rich handler, for a terminal. The default, so the CLI keeps its rendering. It needs the `cli` extra (`pipelex[cli]`), and a boot that selects it without Rich installed stops, naming the extra and the `json` alternative
- `"json"`: one JSON object per line, for a server behind a log agent
- `"otlp"`: the OpenTelemetry logs signal, for a collector
- `"gcp"`: Google Cloud Logging through the client library, for a process that must write to it directly
@@ -68,10 +68,10 @@ pretty_print_mode = "rich"
```
- Controls the panels that `pretty_print(...)` renders, such as the "Output of pipe" panel shown after every operator pipe
-- `"rich"`: Rich tables and panels on the console print target
-- `"poor"`: plain text in a drawn frame on stderr, with no Rich panel; a pipe's output prints as its plain rendering
+- `"rich"`: Rich tables and panels on the console print target. It needs the `cli` extra (`pipelex[cli]`), and a boot that selects it without Rich installed stops, naming the extra and the two modes below
+- `"poor"`: plain text in a drawn frame on stderr, with no Rich panel and no Rich import; a pipe's output prints as its plain rendering
- `"silent"`: nothing is printed and no renderable is built, for a host with no console or one that must not spend time rendering on the thread that runs pipes
-- Default: `"rich"`. The agent CLI forces `"silent"`
+- Default: `"rich"`. The agent CLI forces `"silent"`, and a server installed without the `cli` extra sets `"poor"` or `"silent"` beside `sink = "json"`
- Boot applies the key, replacing any `PrettyPrinter.mode` assigned in code before it, and teardown returns the printer to the mode the process held before that boot
### JSON Formatting
diff --git a/docs/contribute/rich-imports.md b/docs/contribute/rich-imports.md
new file mode 100644
index 000000000..cf5c93fa3
--- /dev/null
+++ b/docs/contribute/rich-imports.md
@@ -0,0 +1,114 @@
+---
+title: "Rich Imports"
+description: "Rich is the cli extra: where the runtime may import it, how a rendering outside the CLI imports it, and the guard and the test that keep it off the path to running a method."
+---
+
+# Rich imports
+
+[Rich](https://github.com/Textualize/rich) renders everything Pipelex shows in a terminal: the CLI's tables and panels, the `console` log sink, the "Output of pipe" panels of the `rich` pretty-print mode. None of that has a place in a server, which writes JSON lines to a log agent and prints nothing. So Rich is not a core dependency of `pipelex`. It is the **`cli` extra**, which the command-line tools install and a server leaves out:
+
+```bash
+uv tool install "pipelex[cli]" # the pipelex and pipelex-agent commands
+uv pip install pipelex # a process that embeds the runtime
+```
+
+## What this delivers, and what it does not
+
+The property the convention on this page holds is that **no code path the runtime takes on the way to running a method needs Rich**: a process that selects the `json` log sink and a Rich-free pretty-print mode boots, runs a method and tears down with every `rich` import refused.
+
+It is **not** that the second install above leaves an environment with no Rich in it. `typer` and `instructor` are core dependencies of `pipelex` and both require `rich` unconditionally, so `uv pip install pipelex` installs Rich anyway, and `import pipelex` loads it — through `httpx`, another core dependency, whose optional command-line module imports `rich.console` inside a `try`. Taking Rich out of that transitive closure is separate work on the install side, and it is not what the guard or the test below measure. It is also why the test measures the property with Rich **blocked** by an import hook rather than by inspecting an environment: in a real environment Rich is present, and its absence is what has to be simulated.
+
+This page is the specification of the convention that keeps the runtime off it, and of the checks that enforce it.
+
+## The rule
+
+> **Outside `pipelex/cli/`, no module imports Rich at module level, no module reaches Rich through a module-level import of a CLI module, and no deferred Rich import is reached before something asked whether Rich is there.**
+
+The CLI package installs the extra, so its modules import Rich at the top of the file like any other dependency. Every other module that renders through Rich imports it inside the function that renders, so importing the module costs a process without Rich nothing.
+
+The third clause is the other half of the same contract: deferring the import is what keeps Rich off the import path, and calling the guard first is what makes the failure a `MissingDependencyError` naming the extra instead of a bare `ModuleNotFoundError`. It is checked one function at a time, in statement order — a guard reaches the statements after it in its own block and everything nested inside them, not the ones above it and not the other branch of its own `if`. A guard that a callee performs is therefore invisible to the check, so a function whose Rich is already assured by something it called spells the guard out beside the import anyway.
+
+"Module level" means what importing the module executes. An import statement counts wherever it sits outside a function body: at the top of the file, inside a module-level `try` or `if` block, in a class body. Two places are exempt, because nothing in them runs at import time:
+
+- a function or coroutine body;
+- the body of an `if TYPE_CHECKING:` or `if typing.TYPE_CHECKING:` block. Its `else` branch is runtime code and is checked, and so is the body of `if not TYPE_CHECKING:`.
+
+There is one escape hatch, and it belongs to the transitive clause alone. That clause walks the module-level import graph the hub-layering guard builds, and a statement carrying that guard's `# hub-layering: ignore` marker is no edge in it — so the marker, whose stated purpose is a different guard, also hides the marked module's own path to Rich. Reach for it only where the hub-layering guard is the reason, and say so in the comment. Nothing else can be switched off: a module that genuinely needs Rich at import time is a CLI module, and it belongs under `pipelex/cli/`.
+
+## Rendering through Rich outside the CLI
+
+A function that renders checks that Rich is installed first, then imports what it renders with. The check raises `MissingDependencyError`, which names the `cli` extra and the install command, so a process without Rich gets an instruction rather than a bare `ModuleNotFoundError`:
+
+```python
+from typing import TYPE_CHECKING
+
+from pipelex.core.stuffs.stuff_content import StuffContent
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
+
+class TextContent(StuffContent):
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.markdown import Markdown
+
+ return Markdown(self.text)
+```
+
+- **`require_rich_for_rendering()`** (`pipelex.tools.misc.pretty`) is the check for a rendering: the `rendered_pretty` methods of the content types and the builder specs, and the `rich` pretty-print mode. Its message points at the Rich-free pretty-print modes as well as at the extra.
+- **`require_rich(message=...)`** (`pipelex.tools.misc.rich_extra`) is the check for anything else, with a message saying what needed Rich: the `console` log sink uses it, and so does `get_console()`.
+- **`is_rich_installed()`**, in the same module, answers without raising, for a caller that has a Rich-free fallback. The stuff viewer page uses it, and shows the JSON rendering in its Pretty tab when Rich is absent.
+- **A type-only import goes under `if TYPE_CHECKING:`.** In a module with `from __future__ import annotations`, the annotation can stay unquoted; in a pydantic model module without it, quote the annotation, as `"PrettyPrintable"` is quoted above, since pydantic resolves annotations at class creation.
+
+Ruff agrees with the convention: `pyproject.toml` bans `rich` as a module-level import under `flake8-tidy-imports.banned-module-level-imports` (rule `TID253`), which also exempts a deferred Rich import from `import-outside-top-level`, so none needs a suppression comment. The CLI package and the test suite, which installs every extra, are exempt from the ban in `per-file-ignores`. The ruff rule gives the warning in the editor; the guard below is the gate, because ruff sees neither the import graph nor the allowlist as one declaration.
+
+## What a process without Rich gives up
+
+Nothing a server needs. What needs Rich stops as early as it can, naming the extra:
+
+| Surface | Without Rich |
+|---------|--------------|
+| `sink = "console"` in `[runtime.log]` | The boot stops, naming the extra and the `json` sink. |
+| `pretty_print_mode = "rich"` in `[runtime.log]` | The boot stops, naming the extra and the `poor` and `silent` modes. |
+| `pretty_print_mode = "poor"` | Plain text in a drawn frame, with no Rich import. A panel title's Rich markup is read by a Rich-free reading, `plain_markup_text`, which follows Rich's own tag pattern and escaping. Two differences from Rich, both documented on that function: an emoji code is left as written, since substituting it needs Rich's own code table, and markup Rich would refuse for a reason that needs its style grammar is stripped rather than kept. |
+| `pretty_print_mode = "silent"` | Nothing is built or printed. |
+| `get_console()` | Raises `MissingDependencyError` when called. |
+| A `rendered_pretty()` or `rendered_pretty_text()` call | Raises `MissingDependencyError`. |
+| `pipelex models list`, the pipe listing, the directory diff | Raise `MissingDependencyError`: each builds a Rich table or renderable and has no plain form. |
+| A cost report with `is_log_costs_to_console = true` | The CSV report is written; the console table raises, which the caller reports as a warning. |
+| The stuff viewer page | The Pretty tab shows the JSON rendering. |
+| The `pipelex`, `pipelex-agent` and `pipelex-dev` commands | Would fail at import with a bare `ImportError`. Not reachable on a documented install, since `typer` and `instructor` keep Rich installed; a launcher that names the extra belongs with the work that removes them from the closure. |
+
+The boot checks the sink and the pretty-print mode together, in `runtime_boot.py`, so a server that forgot either setting fails at startup rather than at the first pipe that logs or prints its output.
+
+## Enforcement
+
+The convention is checked twice, by a static guard and by a run, because they fail independently: the guard reads source and cannot see an import assembled at runtime or one a dependency performs, and the run covers one path through the runtime rather than every module.
+
+### The rule: `make check-rich-imports`
+
+```bash
+make check-rich-imports # alias: make cri
+```
+
+An AST guard (`pipelex-dev check-rich-imports`, core in `pipelex/cli/dev_cli/commands/rich_import_guard.py`) that runs in `make agent-check`, in the `make check` aggregate, and in CI as the `Lint (rich imports)` job and a step of the pre-main fresh lint. It scans `pipelex/` and checks three rules:
+
+1. **The direct rule.** A module outside `pipelex/cli/` may not import `rich` or any `rich.*` module at module level. The match is on the package boundary, so a module named `richer` or `rich_extra` is not Rich, and a relative import never is.
+2. **The transitive rule.** A module outside `pipelex/cli/` may not reach a CLI module that imports Rich at module level, through any chain of module-level imports. It walks the module-level import graph the [hub-layering guard](hub-layering.md) builds, with the same carve-outs — including that guard's `# hub-layering: ignore` marker, which is the one escape hatch named above — and the same modelling of the package `__init__.py` files an import executes on the way, and reports the shortest chain at the line of its first hop. A module outside the CLI that imports Rich itself is the direct rule's finding only: removing that import is the fix for every module that reaches it.
+3. **The ordering rule.** A Rich import deferred into a function body must be preceded, in that function, by something that asked whether Rich is available: `require_rich(...)`, `require_rich_for_rendering()`, `get_console()` — whose own construction raises the named error — or, for a rendering that falls back rather than failing, `is_rich_installed()` or a test on `sys.modules`. The walk is per function and in statement order, so a guard covers what follows it in its own block and what nests inside that, and never the statements above it or the sibling branch of its own `if`. A nested `def` is a scope of its own and carries its own guard. The rule follows no calls, which is deliberate: it keeps the check readable at the site rather than dependent on a call graph, at the cost of a redundant guard in the few functions whose Rich is already assured by a callee.
+
+The guard refuses to pass vacuously: a scan root that yields no module, none under `pipelex/cli/`, or an import graph that does not hold the modules the scan read raises instead of reporting a pass.
+
+### The property: `tests/integration/pipelex/test_rich_free_run.py`
+
+The test runs, in a subprocess, what a server does. A meta-path finder installed before the first `pipelex` import raises `ImportError` for `rich` and every `rich.*` module. The subprocess then boots the kernel with `sink = "json"`, runs a `PipeCompose` pipe in direct mode through `PipelexMTHDSProtocol`, which needs no inference and prints the operator's "Output of pipe" panel, and asserts that the run returns its output and that no Rich module was loaded. It runs once in the `silent` mode, where every line on stderr must be a JSON log record, and once in the `poor` mode, where the panel must print as plain text. A third case boots with `pretty_print_mode = "rich"` and asserts the boot refusal names the extra.
+
+A subprocess is required rather than preferred: the test process has Rich loaded, since the suite installs every extra, and evicting it from `sys.modules` would leave duplicate classes behind for every later test.
+
+Every one of those boots asks for no model specs (`needs_model_specs=False`), which is what lets the test run where inference was never set up — a CI runner — because that branch of the boot wants neither the gateway terms nor the network. `needs_inference` stays true on purpose: a keyless boot forces every run this process starts to DRY, and the dry path never prints the "Output of pipe" panel, which is the Rich reach the test is here for.
+
+The test blocks Rich rather than checking that it is absent from an ordinary environment, because an environment is not the measure. Whether Rich is installed also depends on what the other dependencies of `pipelex` require, and some third-party packages import Rich whenever it is installed. What the runtime owns is that it never needs Rich on a server's path, and that is what the blocked run measures.
+
+`tests/unit/pipelex/tools/test_log_console_sink_without_rich.py` pins the `console` sink's own refusal the same way, and `tests/unit/pipelex/tools/misc/test_plain_markup_text.py` compares the Rich-free markup reading with Rich's.
diff --git a/docs/get-started/mthds-language-tutorial.md b/docs/get-started/mthds-language-tutorial.md
index 9ac70c53a..ce64f5865 100644
--- a/docs/get-started/mthds-language-tutorial.md
+++ b/docs/get-started/mthds-language-tutorial.md
@@ -10,11 +10,13 @@ This tutorial walks you through writing `.mthds` files manually, step by step.
Set up your project and get free AI access:
```bash
-uv tool install pipelex
+uv tool install "pipelex[cli]"
pipelex init
pipelex login
```
+The `cli` extra installs Rich, which the `pipelex` command renders its output through.
+
`pipelex init` creates your project configuration. `pipelex login` opens your browser to authenticate with Pipelex Gateway (free). See [Configure AI Providers](./configure-ai-providers.md) for other options: bring your own keys, local AI, etc.
!!! tip "VS Code Extension"
diff --git a/docs/get-started/run-it-yourself.md b/docs/get-started/run-it-yourself.md
index 2df09f8f2..acef451de 100644
--- a/docs/get-started/run-it-yourself.md
+++ b/docs/get-started/run-it-yourself.md
@@ -10,15 +10,16 @@ The Pipelex runtime is the Python package that reads a `.mthds` file and runs it
## Install
```bash
-uv tool install pipelex
+uv tool install "pipelex[cli]"
pipelex init
pipelex doctor
```
-`pipelex init` writes your `~/.pipelex` configuration and offers to install the editor extension; `pipelex doctor` reports what is configured and what is missing.
+`pipelex init` writes your `~/.pipelex` configuration and offers to install the editor extension; `pipelex doctor` reports what is configured and what is missing. The `cli` extra installs Rich, which the `pipelex` and `pipelex-agent` commands render their output through.
Some providers and features need an extra:
+- `cli`: Rich, for the `pipelex` and `pipelex-agent` commands, the `console` log sink and the `rich` pretty-print mode. Install it wherever Pipelex runs in a terminal; a server leaves it out and selects the `json` log sink with the `poor` or `silent` pretty-print mode (see [Rich Imports](../contribute/rich-imports.md))
- `anthropic`: Anthropic/Claude support for text generation
- `google`: Google models (Vertex) support for text generation
- `google-genai`: Google Gemini API support for text and image generation
@@ -31,7 +32,7 @@ Some providers and features need an extra:
Name the ones you need when you install, or take them all:
```bash
-uv tool install "pipelex[anthropic,google,google-genai,mistralai,bedrock,fal,linkup,docling]"
+uv tool install "pipelex[cli,anthropic,google,google-genai,mistralai,bedrock,fal,linkup,docling]"
```
## Configure AI access
diff --git a/docs/tools/cli/agent-cli.md b/docs/tools/cli/agent-cli.md
index 9648d7f53..89d51ded5 100644
--- a/docs/tools/cli/agent-cli.md
+++ b/docs/tools/cli/agent-cli.md
@@ -8,6 +8,8 @@ The `pipelex-agent` CLI is a machine-oriented companion to the main `pipelex` CL
It is consumed by the `mthds-agent` CLI (from the `mthds` npm package) which itself is used by Claude Code skills, the VS Code extension, and can be called directly from the command line.
+It ships in the same `cli` extra as the main CLI, `uv tool install "pipelex[cli]"`: its own output carries no Rich formatting, but the command modules it shares with `pipelex` import Rich.
+
## Global Options
| Option | Description |
diff --git a/docs/tools/cli/index.md b/docs/tools/cli/index.md
index 22a316786..f4087abe9 100644
--- a/docs/tools/cli/index.md
+++ b/docs/tools/cli/index.md
@@ -7,6 +7,16 @@ description: "Master the `pipelex` runtime CLI and understand where the `mthds`
The `pipelex` CLI is the runtime and project-configuration CLI for Pipelex. Use it to initialize config, validate methods, run pipes, inspect the runtime state, and generate supporting files.
+## Installation
+
+The CLI renders its tables, panels and log lines through Rich, which is the `cli` extra, so install the package with it:
+
+```bash
+uv tool install "pipelex[cli]"
+```
+
+The same extra serves the [`pipelex-agent`](agent-cli.md) CLI. A process that only embeds Pipelex, a server for instance, installs the package without it; see [Rich Imports](../../contribute/rich-imports.md) for what that process gives up and how the runtime keeps Rich out of it.
+
## Overview
The Pipelex CLI is organized into several command groups:
diff --git a/docs/tools/logging.md b/docs/tools/logging.md
index 45cfa95c8..e52d0147e 100644
--- a/docs/tools/logging.md
+++ b/docs/tools/logging.md
@@ -172,7 +172,7 @@ Logging is configured in two steps at boot. `log.configure` sets the levels and
## Console rendering
-The default sink, `console`, renders through Rich with every `[runtime.log.rich_log]` setting. Rich is imported when the sink is built and nowhere else, so a process that selects `json` or `otlp` never loads it, and one that selects `console` without Rich installed stops at boot naming the extra to install and the `json` alternative.
+The default sink, `console`, renders through Rich with every `[runtime.log.rich_log]` setting. Rich is the `cli` extra (`pipelex[cli]`), which the command-line tools install and a server leaves out. The sink imports Rich when it is built, so a process that selects `json` or `otlp` never loads it through the sink, and one that selects `console` without Rich installed stops at boot naming the extra to install and the `json` alternative. A server without the extra also sets `pretty_print_mode` to `"poor"` or `"silent"`, since the `"rich"` panels are refused at boot the same way (see [Pretty-Print Mode](../configuration/config-practical/logging-config.md#pretty-print-mode)).
### Rich Formatting
diff --git a/docs/under-the-hood/log-sink-plugins.md b/docs/under-the-hood/log-sink-plugins.md
index 1b88914de..710ff648a 100644
--- a/docs/under-the-hood/log-sink-plugins.md
+++ b/docs/under-the-hood/log-sink-plugins.md
@@ -122,7 +122,7 @@ class LogSinkPlugin:
| Sink | What it does | Where it reads its settings |
|------|--------------|-----------------------------|
| `json` | One JSON object per line on the configured stream: `time`, `severity`, `logger`, `message`, `exception` when there is one, then the fields, the context identifiers and `data` flat beside them, a field named like one of those keys under a `field_` prefix on every line, a non-finite float as the string `"NaN"`, `"Infinity"` or `"-Infinity"`. The key names are the ones the CloudWatch agent, the Google Cloud Logging agent and any OTLP collector ingest without a parser, and no ANSI ever. What the hosted plane's runner and worker select. | `console_log_target` |
-| `console` | The Rich handler with the emoji formatter and every `[runtime.log.rich_log]` setting, byte for byte what the console showed before sinks existed. Rich is imported when the handler is built, and a process that selects another sink never loads it through this path. | `console_log_target`, `[runtime.log.rich_log]` |
+| `console` | The Rich handler with the emoji formatter and every `[runtime.log.rich_log]` setting, byte for byte what the console showed before sinks existed. Rich, the `cli` extra, is imported when the handler is built, and a process that selects another sink never loads it through this path. | `console_log_target`, `[runtime.log.rich_log]` |
| `otlp` | The OpenTelemetry logs signal: a `LoggerProvider` carrying the same service identity as the tracer, a `BatchLogRecordProcessor` and the OTLP HTTP log exporter. The message is the body, the level maps onto the OTel severity scale, the fields, identifiers and `data` ride as attributes (a mapping as JSON text), an exception lands under the `exception.*` semantic-convention keys, and a collector receives the logs beside the spans the runtime already exports. The keys the sink writes itself, the `code.*` source location and the `exception.*` set, are reserved on every record whether or not it carries an exception, so a field named like one of them rides under a `field_` prefix rather than being overwritten. A filter on the handler rejects the records of the sink's own export path, the SDK's by logger name and the transport's by the context value the SDK sets around an export, before the handler's lock is taken, so an export failure never re-enters the pipeline and a shutdown never waits on itself. | `[runtime.log.otlp]` |
| `gcp` | Google Cloud Logging through the `google-cloud-logging` client library, behind the `gcp-logging` extra. Each record becomes one struct entry: the level maps onto the Cloud Logging severity scale (which has nothing below `DEBUG`, so `VERBOSE` and `DEV` both land there), the message, the logger, the exception and the fields become the JSON payload, the run-scoped identifiers become the entry's labels, which is what Cloud Logging indexes, and the entry's `trace` field carries the run's own OpenTelemetry trace id project-qualified, derived from `pipeline_run_id` by the same hash the tracer uses, so a line and the spans of its run agree on it. The entries leave through the client library's background-thread transport, which batches them off the calling thread. **Most processes on Google Cloud want `json` instead**: a platform whose logging agent reads the container's stdout, Cloud Run and GKE among them, ingests what that sink writes and needs no client at all; `gcp` is for a process with no such agent in front of it, or one writing to a log or a project that is not the ambient one. | `[runtime.log.gcp]` |
@@ -130,7 +130,7 @@ The `otlp` factory imports the OpenTelemetry logs SDK when it runs, and the `gcp
### Why `console` is the default
-`pipelex/pipelex.toml` ships `sink = "console"`. A user who installs the CLI expects the rendering the CLI always had, the emoji, the colours, the clickable paths, and a default that changed it would be a regression for every terminal. A server is the process that must choose: it selects `json`, and the fail-loud factory is what makes the choice hard to forget. Rich is a hard dependency today, so a server that forgot to select `json` still boots with the console sink; once Rich moves behind the CLI extra, the same server refuses to boot with the extra and the `json` alternative named, rather than shipping ANSI to a log agent.
+`pipelex/pipelex.toml` ships `sink = "console"`. A user who installs the CLI expects the rendering the CLI always had, the emoji, the colours, the clickable paths, and a default that changed it would be a regression for every terminal. A server is the process that must choose: it selects `json`, and the fail-loud factory is what makes the choice hard to forget. Rich is the `cli` extra, which a server installs pipelex without, so a server that forgot to select `json` refuses to boot with the extra and the `json` alternative named, rather than shipping ANSI to a log agent. How the rest of the runtime keeps Rich out of such a process, and the guard that holds it there, is in [Rich Imports](../contribute/rich-imports.md).
---
diff --git a/mkdocs.yml b/mkdocs.yml
index 4dddc3aa5..cb7a2d727 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -360,6 +360,7 @@ plugins:
- contribute/configuration-defaults-and-overrides.md: "Configuration Internals"
- contribute/keyword-only-arguments.md: "Keyword-Only Arguments"
- contribute/hub-layering.md: "Hub Layering"
+ - contribute/rich-imports.md: "Rich Imports"
- contribute/test-duration-map.md: "Test Duration Map"
- contribute/registration-surface.md: "Registration Surface"
- contribute/drift-contracts.md: "Drift Contracts"
@@ -594,6 +595,7 @@ nav:
- Configuration Internals: contribute/configuration-defaults-and-overrides.md
- Keyword-Only Arguments: contribute/keyword-only-arguments.md
- Hub Layering: contribute/hub-layering.md
+ - Rich Imports: contribute/rich-imports.md
- Test Duration Map: contribute/test-duration-map.md
- Registration Surface: contribute/registration-surface.md
- Drift Contracts: contribute/drift-contracts.md
diff --git a/pipelex/builder/bundle_header_spec.py b/pipelex/builder/bundle_header_spec.py
index cb7498b00..320f3f107 100644
--- a/pipelex/builder/bundle_header_spec.py
+++ b/pipelex/builder/bundle_header_spec.py
@@ -1,12 +1,15 @@
+from typing import TYPE_CHECKING
+
from pydantic import Field
-from rich.console import Group
-from rich.text import Text
from typing_extensions import override
from pipelex.cogt.content_generation.dry_mock import MOCK_MAIN_PIPE_CODE
from pipelex.cogt.content_generation.dry_run_factory import MockFormat
from pipelex.core.stuffs.structured_content import StructuredContent
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class BundleHeaderSpec(StructuredContent):
@@ -18,7 +21,11 @@ class BundleHeaderSpec(StructuredContent):
main_pipe: str = Field(description="The main pipe of the domain.", examples=[MOCK_MAIN_PIPE_CODE])
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.text import Text
+
bundle_group = Group()
if title:
bundle_group.renderables.append(Text(title, style="bold"))
diff --git a/pipelex/builder/bundle_spec.py b/pipelex/builder/bundle_spec.py
index fa7e0ea5f..722200a41 100644
--- a/pipelex/builder/bundle_spec.py
+++ b/pipelex/builder/bundle_spec.py
@@ -1,9 +1,6 @@
from typing import TYPE_CHECKING, Any, cast
from pydantic import ConfigDict, Field, ValidationError, field_validator, model_validator
-from rich.console import Group
-from rich.table import Table
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.concept.concept_spec import ConceptSpec
@@ -16,9 +13,12 @@ from pipelex.mthds_parsing.pipe_sorter import sort_pipes_by_dependencies
from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipeBlueprintUnion, PipelexBundleBlueprint
from pipelex.pipe_machinery.pipe_blueprint import SIGNATURE_ONLY_KEYS, normalize_typeless_signature_section
from pipelex.pipe_machinery.validation import is_pipe_code_valid
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
if TYPE_CHECKING:
from pipelex.core.concepts.concept_blueprint import ConceptBlueprint
@@ -161,7 +161,12 @@ class PipelexBundleSpec(StructuredContent):
raise PipelexBundleSpecBlueprintError(msg) from exc
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.table import Table
+ from rich.text import Text
+
bundle_group = Group()
# Bundle header info
diff --git a/pipelex/builder/concept/concept_spec.py b/pipelex/builder/concept/concept_spec.py
index 50a16f376..8fc372cfc 100644
--- a/pipelex/builder/concept/concept_spec.py
+++ b/pipelex/builder/concept/concept_spec.py
@@ -1,11 +1,8 @@
from datetime import date, datetime
from enum import StrEnum
-from typing import Any, Self, cast
+from typing import TYPE_CHECKING, Any, Self, cast
from pydantic import ConfigDict, Field, field_validator, model_validator
-from rich.console import Group
-from rich.table import Table
-from rich.text import Text
from typing_extensions import override
from pipelex import log
@@ -15,9 +12,12 @@ from pipelex.core.concepts.concept_blueprint import ConceptBlueprint, ConceptStr
from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprintFieldType
from pipelex.core.concepts.validation import is_concept_ref_or_code_valid
from pipelex.core.stuffs.structured_content import StructuredContent
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.misc.string_utils import is_pascal_case, normalize_to_ascii, snake_to_pascal_case
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class ConceptStructureSpecFieldType(StrEnum):
TEXT = "text"
@@ -372,7 +372,12 @@ class ConceptSpec(StructuredContent):
return field_spec.type
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.table import Table
+ from rich.text import Text
+
concept_group = Group()
if title:
concept_group.renderables.append(Text(title, style="bold"))
diff --git a/pipelex/builder/pipe/pipe_batch_spec.py b/pipelex/builder/pipe/pipe_batch_spec.py
index 5ebb7226f..d977c97e2 100644
--- a/pipelex/builder/pipe/pipe_batch_spec.py
+++ b/pipelex/builder/pipe/pipe_batch_spec.py
@@ -1,13 +1,14 @@
-from typing import Literal, Self
+from typing import TYPE_CHECKING, Literal, Self
from pydantic import Field, model_validator
-from rich.console import Group
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeBatchSpec(PipeSpec):
@@ -70,7 +71,11 @@ class PipeBatchSpec(PipeSpec):
return self
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_compose_spec.py b/pipelex/builder/pipe/pipe_compose_spec.py
index a1e0dda84..94cdf95db 100644
--- a/pipelex/builder/pipe/pipe_compose_spec.py
+++ b/pipelex/builder/pipe/pipe_compose_spec.py
@@ -1,21 +1,21 @@
from enum import StrEnum
-from typing import Any, Literal, Self
+from typing import TYPE_CHECKING, Any, Literal, Self
from pydantic import ConfigDict, Field, field_validator, model_validator
from pydantic.json_schema import SkipJsonSchema
-from rich.console import Group
-from rich.panel import Panel
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.cogt.templating.template_blueprint import TemplateBlueprint
from pipelex.pipe_operators.compose.pipe_compose_blueprint import PipeComposeBlueprint
from pipelex.tools.jinja2.template_category import TemplateCategory
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.templating.templating_style import TagStyle, TemplatingStyle
from pipelex.tools.templating.text_format import TextFormat
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class TargetFormat(StrEnum):
PLAIN = "plain"
@@ -170,7 +170,12 @@ class PipeComposeSpec(PipeSpec):
return self
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.panel import Panel
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_condition_spec.py b/pipelex/builder/pipe/pipe_condition_spec.py
index 91345ec72..11ceb4402 100644
--- a/pipelex/builder/pipe/pipe_condition_spec.py
+++ b/pipelex/builder/pipe/pipe_condition_spec.py
@@ -1,17 +1,16 @@
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from pydantic import Field
from pydantic.json_schema import SkipJsonSchema
-from rich.console import Group
-from rich.panel import Panel
-from rich.table import Table
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint
from pipelex.pipe_controllers.condition.special_outcome import SpecialOutcome
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeConditionSpec(PipeSpec):
@@ -32,7 +31,13 @@ class PipeConditionSpec(PipeSpec):
default_outcome: str | SpecialOutcome = Field(description="The fallback outcome if the expression result does not match any key in outcome map.")
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.panel import Panel
+ from rich.table import Table
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_extract_spec.py b/pipelex/builder/pipe/pipe_extract_spec.py
index c14b52aad..b0966ee6b 100644
--- a/pipelex/builder/pipe/pipe_extract_spec.py
+++ b/pipelex/builder/pipe/pipe_extract_spec.py
@@ -1,16 +1,16 @@
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from pydantic import Field, field_validator
from pydantic.json_schema import SkipJsonSchema
-from rich.console import Group
-from rich.markup import escape
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.cogt.content_generation.dry_run_factory import MockFormat
from pipelex.pipe_operators.extract.pipe_extract_blueprint import PipeExtractBlueprint
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeExtractSpec(PipeSpec):
@@ -69,7 +69,12 @@ class PipeExtractSpec(PipeSpec):
return inputs_value
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markup import escape
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_func_spec.py b/pipelex/builder/pipe/pipe_func_spec.py
index ff07f5ac6..eb7629d58 100644
--- a/pipelex/builder/pipe/pipe_func_spec.py
+++ b/pipelex/builder/pipe/pipe_func_spec.py
@@ -1,14 +1,15 @@
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from pydantic import Field
from pydantic.json_schema import SkipJsonSchema
-from rich.console import Group
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.pipe_operators.func.pipe_func_blueprint import PipeFuncBlueprint
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeFuncSpec(PipeSpec):
@@ -19,7 +20,11 @@ class PipeFuncSpec(PipeSpec):
function_name: str = Field(description="The name of the function to call.")
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_img_gen_spec.py b/pipelex/builder/pipe/pipe_img_gen_spec.py
index 86ee0a30b..3409d94c3 100644
--- a/pipelex/builder/pipe/pipe_img_gen_spec.py
+++ b/pipelex/builder/pipe/pipe_img_gen_spec.py
@@ -1,15 +1,15 @@
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from pydantic import Field, field_validator
-from rich.console import Group
-from rich.markup import escape
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.cogt.img_gen.img_gen_job_components import ImgGenSize
from pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBlueprint
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeImgGenSpec(PipeSpec):
@@ -49,7 +49,12 @@ class PipeImgGenSpec(PipeSpec):
return value
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markup import escape
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_llm_spec.py b/pipelex/builder/pipe/pipe_llm_spec.py
index 59cf9a7eb..96c887e4d 100644
--- a/pipelex/builder/pipe/pipe_llm_spec.py
+++ b/pipelex/builder/pipe/pipe_llm_spec.py
@@ -1,18 +1,17 @@
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from pydantic import Field, field_validator
from pydantic.json_schema import SkipJsonSchema
-from rich.console import Group
-from rich.markup import escape
-from rich.panel import Panel
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint, StructuringMethod
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.templating.templating_style import TagStyle, TemplatingStyle
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class PipeLLMSpec(PipeSpec):
"""Spec for LLM-based pipe operations in the Pipelex framework.
@@ -85,7 +84,13 @@ So, don't have to write a bullet-list of all the attributes definitions yourself
return value
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markup import escape
+ from rich.panel import Panel
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_parallel_spec.py b/pipelex/builder/pipe/pipe_parallel_spec.py
index fb6d0e5fa..4f194ea5e 100644
--- a/pipelex/builder/pipe/pipe_parallel_spec.py
+++ b/pipelex/builder/pipe/pipe_parallel_spec.py
@@ -1,15 +1,15 @@
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from pydantic import Field
-from rich.console import Group
-from rich.table import Table
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec
from pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprint
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeParallelSpec(PipeSpec):
@@ -36,7 +36,12 @@ class PipeParallelSpec(PipeSpec):
add_each_output: bool = Field(default=False, description="Whether to also expose each branch output by its result name in memory.")
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.table import Table
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_search_spec.py b/pipelex/builder/pipe/pipe_search_spec.py
index 1faa06b34..a0de80b36 100644
--- a/pipelex/builder/pipe/pipe_search_spec.py
+++ b/pipelex/builder/pipe/pipe_search_spec.py
@@ -1,16 +1,15 @@
import re
-from typing import Any, Literal
+from typing import TYPE_CHECKING, Any, Literal
from pydantic import ConfigDict, Field, field_validator, model_validator
-from rich.console import Group
-from rich.markup import escape
-from rich.panel import Panel
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.pipe_operators.search.pipe_search_blueprint import PipeSearchBlueprint
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeSearchSpec(PipeSpec):
@@ -79,7 +78,13 @@ class PipeSearchSpec(PipeSpec):
return date_value
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markup import escape
+ from rich.panel import Panel
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_sequence_spec.py b/pipelex/builder/pipe/pipe_sequence_spec.py
index 1825339f5..b366ecb95 100644
--- a/pipelex/builder/pipe/pipe_sequence_spec.py
+++ b/pipelex/builder/pipe/pipe_sequence_spec.py
@@ -1,16 +1,16 @@
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from pydantic import Field
from pydantic.json_schema import SkipJsonSchema
-from rich.console import Group
-from rich.table import Table
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec
from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeSequenceSpec(PipeSpec):
@@ -26,7 +26,12 @@ class PipeSequenceSpec(PipeSpec):
)
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.table import Table
+ from rich.text import Text
+
# Get base pipe information from parent
base_group = super().rendered_pretty(title=title, depth=depth)
diff --git a/pipelex/builder/pipe/pipe_signature_spec.py b/pipelex/builder/pipe/pipe_signature_spec.py
index 08c02aea1..96615ae1a 100644
--- a/pipelex/builder/pipe/pipe_signature_spec.py
+++ b/pipelex/builder/pipe/pipe_signature_spec.py
@@ -1,17 +1,16 @@
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from pydantic import Field
from pydantic.json_schema import SkipJsonSchema
-from rich.console import Group
-from rich.markup import escape
-from rich.table import Table
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.pipe_machinery.pipe_blueprint import PipeType
from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprint
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeSignatureSpec(PipeSpec):
@@ -71,7 +70,13 @@ class PipeSignatureSpec(PipeSpec):
)
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markup import escape
+ from rich.table import Table
+ from rich.text import Text
+
pipe_group = Group()
if title:
pipe_group.renderables.append(Text(title, style="bold"))
diff --git a/pipelex/builder/pipe/pipe_spec.py b/pipelex/builder/pipe/pipe_spec.py
index 4b58b3065..170b05a9a 100644
--- a/pipelex/builder/pipe/pipe_spec.py
+++ b/pipelex/builder/pipe/pipe_spec.py
@@ -1,10 +1,7 @@
import re
-from typing import Any
+from typing import TYPE_CHECKING, Any
from pydantic import ConfigDict, Field, field_validator
-from rich.console import Group
-from rich.table import Table
-from rich.text import Text
from typing_extensions import override
from pipelex import log
@@ -22,9 +19,12 @@ from pipelex.core.pipes.variable_multiplicity import (
)
from pipelex.core.stuffs.structured_content import StructuredContent
from pipelex.pipe_machinery.pipe_blueprint import PipeBlueprint, PipeCategory, PipeType, valid_pipe_type_tags
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.misc.string_utils import is_snake_case, normalize_to_ascii
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class PipeSpec(StructuredContent):
"""Spec defining a pipe: an executable component with a clear contract defined by its inputs and output.
@@ -211,7 +211,12 @@ class PipeSpec(StructuredContent):
)
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.table import Table
+ from rich.text import Text
+
pipe_group = Group()
if title:
pipe_group.renderables.append(Text(title, style="bold"))
diff --git a/pipelex/builder/pipe/pipe_structure_spec.py b/pipelex/builder/pipe/pipe_structure_spec.py
index 94cd1c178..ece5fa406 100644
--- a/pipelex/builder/pipe/pipe_structure_spec.py
+++ b/pipelex/builder/pipe/pipe_structure_spec.py
@@ -1,15 +1,15 @@
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from pydantic import Field, field_validator
from pydantic.json_schema import SkipJsonSchema
-from rich.console import Group
-from rich.markup import escape
-from rich.text import Text
from typing_extensions import override
from pipelex.builder.pipe.pipe_spec import PipeSpec
from pipelex.pipe_operators.structure.pipe_structure_blueprint import PipeStructureBlueprint
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PipeStructureSpec(PipeSpec):
@@ -40,7 +40,12 @@ class PipeStructureSpec(PipeSpec):
return value
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markup import escape
+ from rich.text import Text
+
base_group = super().rendered_pretty(title=title, depth=depth)
structure_group = Group()
diff --git a/pipelex/cli/dev_cli/_dev_cli.py b/pipelex/cli/dev_cli/_dev_cli.py
index 3012fa365..db1f6030a 100644
--- a/pipelex/cli/dev_cli/_dev_cli.py
+++ b/pipelex/cli/dev_cli/_dev_cli.py
@@ -17,6 +17,7 @@ from pipelex.cli.dev_cli.commands.check_keyword_only_cmd import check_keyword_on
from pipelex.cli.dev_cli.commands.check_ledger_cmd import check_ledger_cmd
from pipelex.cli.dev_cli.commands.check_migration_schemas_cmd import check_migration_schemas_cmd
from pipelex.cli.dev_cli.commands.check_mthds_schema_cmd import check_mthds_schema_cmd
+from pipelex.cli.dev_cli.commands.check_rich_imports_cmd import check_rich_imports_cmd
from pipelex.cli.dev_cli.commands.check_rules_sync_cmd import check_rules_sync_cmd
from pipelex.cli.dev_cli.commands.check_urls_cmd import DEFAULT_TIMEOUT, check_urls_cmd
from pipelex.cli.dev_cli.commands.drift.drift_cmd import drift_app
@@ -53,6 +54,7 @@ class PipelexDevCLI(TyperGroup):
"check-ledger",
"check-migration-schemas",
"check-mthds-schema",
+ "check-rich-imports",
"check-rules",
"check-urls",
"drift",
@@ -400,6 +402,28 @@ def check_hub_layering_command(
sys.exit(1)
[email protected](name="check-rich-imports", help="Refuse a module-level Rich import or reach outside pipelex/cli/ (Rich is the cli extra)")
+def check_rich_imports_command(
+ quiet: Annotated[
+ bool, typer.Option("--quiet", "-q", help="Light output on success (single line); the full violation list still prints on failure")
+ ] = False,
+) -> None:
+ """Refuse a module-level Rich import outside pipelex/cli/, direct or through a CLI module."""
+ try:
+ check_rich_imports_cmd(quiet=quiet)
+ except (typer.Exit, typer.Abort):
+ # Typer control-flow exits carry an intended exit code — not a failure. Let them through.
+ raise
+ except Exception: # ruff: ignore[blind-except]
+ # Dev CLI command root: print a traceback for any unexpected failure and exit non-zero.
+ console = get_console()
+ console.print()
+ console.print("[bold red]Unexpected error occurred[/bold red]")
+ console.print()
+ console.print(Traceback())
+ sys.exit(1)
+
+
@app.command(name="check-keyword-only", help="Enforce the keyword-only-arguments convention across pipelex/ source")
def check_keyword_only_command(
report: Annotated[bool, typer.Option("--report", help="Print the full violation inventory grouped by package")] = False,
diff --git a/pipelex/cli/dev_cli/commands/check_rich_imports_cmd.py b/pipelex/cli/dev_cli/commands/check_rich_imports_cmd.py
new file mode 100644
index 000000000..756d74edc
--- /dev/null
+++ b/pipelex/cli/dev_cli/commands/check_rich_imports_cmd.py
@@ -0,0 +1,83 @@
+"""Command enforcing that no module outside ``pipelex/cli/`` imports Rich at module level, or reaches it through a CLI module.
+
+Rich is the ``cli`` extra, and a server installs pipelex without it. The AST collection lives in the
+``rich_import_guard`` module; this module is the presentation layer wired into the
+``pipelex-dev`` Typer app (``make check-rich-imports`` / ``make agent-check`` / ``make check`` / CI). The
+tree is compliant, so the guard hard-blocks on any violation. The human-readable specification lives in
+``docs/contribute/rich-imports.md``.
+"""
+
+from __future__ import annotations
+
+import sys
+
+from rich.markup import escape
+from rich.panel import Panel
+
+from pipelex.cli.dev_cli.commands.rich_import_guard import (
+ CLI_PACKAGE_PREFIX,
+ REMEDY,
+ SOURCE_ROOT,
+ RichImportViolation,
+ collect_violations,
+)
+from pipelex.runtime_hub import get_console
+
+
+def check_rich_imports_cmd(*, quiet: bool = False) -> None:
+ """Refuse a module-level Rich import, direct or through a CLI module, anywhere outside the CLI package.
+
+ Args:
+ quiet: If True, keep the success output to a single line (for Make targets / CI). Quiet only
+ trims the happy path: a failure still prints every offending import.
+ """
+ console = get_console()
+
+ if not SOURCE_ROOT.exists():
+ # An error is always loud: quiet only trims success output, never failures.
+ console.print(f"[red]✗ Rich import check: FAILED[/red] - scan root [cyan]{escape(SOURCE_ROOT.as_posix())}/[/cyan] does not exist")
+ sys.exit(1)
+
+ violations = collect_violations(root=SOURCE_ROOT)
+
+ if not violations:
+ if quiet:
+ console.print("[green]✓ Rich import check: PASSED[/green]")
+ else:
+ console.print()
+ console.print(
+ Panel(
+ f"[green]✓[/green] No module outside [cyan]{escape(CLI_PACKAGE_PREFIX)}[/cyan] imports Rich at module level "
+ "or reaches it through a CLI module.",
+ title="[bold green]Rich Import Check: PASSED[/bold green]",
+ border_style="green",
+ padding=(1, 2),
+ )
+ )
+ console.print()
+ return
+
+ if quiet:
+ console.print(f"[red]✗ Rich import check: FAILED[/red] - {len(violations)} violation(s):")
+ else:
+ console.print()
+ console.print(
+ Panel(
+ f"[red]✗[/red] {len(violations)} module-level Rich import(s) or reach(es) outside [cyan]{escape(CLI_PACKAGE_PREFIX)}[/cyan].\n\n"
+ "[dim]Rich is the `cli` extra: a server installs pipelex without it.[/dim]",
+ title="[bold red]Rich Import Check: FAILED[/bold red]",
+ border_style="red",
+ padding=(1, 2),
+ )
+ )
+ console.print()
+ _print_violations(violations=violations)
+ sys.exit(1)
+
+
+def _print_violations(*, violations: list[RichImportViolation]) -> None:
+ """Print each offending import, then the remedy once."""
+ console = get_console()
+ for violation in violations:
+ console.print(f" [red]{escape(violation.relative_path)}:{violation.lineno}[/red] [yellow]{escape(violation.detail)}[/yellow]")
+ console.print(f"[dim]Remedy: {escape(REMEDY)}. See docs/contribute/rich-imports.md[/dim]")
diff --git a/pipelex/cli/dev_cli/commands/rich_import_guard.py b/pipelex/cli/dev_cli/commands/rich_import_guard.py
new file mode 100644
index 000000000..0f880481d
--- /dev/null
+++ b/pipelex/cli/dev_cli/commands/rich_import_guard.py
@@ -0,0 +1,449 @@
+"""AST core for the Rich import guard.
+
+Rich is the ``cli`` extra: the ``pipelex`` and ``pipelex-agent`` CLIs install it, and a server leaves it
+out. What the rules below hold is that **no code path the runtime takes on the way to running a method
+needs Rich** — not that a server's environment has none, which is not this repo's to promise: ``typer``
+and ``instructor`` are core dependencies and both require Rich unconditionally, so a stock install still
+contains it and ``import pipelex`` still loads it, through ``httpx``'s optional command-line module.
+
+Three rules, which this module checks mechanically:
+
+1. **The direct rule. Outside ``pipelex/cli/``, no module imports Rich at module level.** Everything else
+ that renders through Rich, the console log sink, the pretty-print engine's ``rich`` mode, the
+ ``rendered_pretty`` renderings, the model listing and cost tables, imports it inside the function that
+ renders, so importing any of those modules asks a server for nothing.
+2. **The transitive rule. Outside ``pipelex/cli/``, no module reaches Rich through a CLI module either.**
+ A module that imports a CLI module at module level loads whatever that module imports, so a CLI module
+ importing Rich at the top of its file puts Rich into every importer of it. The rule resolves the
+ module-level import graph of ``pipelex/``, the one the hub-layering guard builds, and reports the
+ shortest chain from the offending module to a CLI module that imports Rich, at the line of its first hop.
+3. **The ordering rule. A deferred Rich import is reached only after something asked whether Rich is
+ there.** Deferring the import is what the first two rules are about; calling ``require_rich(...)`` or
+ ``require_rich_for_rendering()`` first is what turns a bare ``ModuleNotFoundError`` into the
+ ``MissingDependencyError`` that names the extra. A rendering with a Rich-free fallback asks instead of
+ raising, through ``is_rich_installed()`` or the ``sys.modules`` question, which counts the same.
+
+The human-readable specification lives in ``docs/contribute/rich-imports.md``.
+
+"Module level" means what an ``import`` of the module executes. An import statement counts wherever it sits
+outside a function body: at the top of the file, in a module-level ``try`` or ``if`` block, in a class
+body. Two places are exempt, because nothing in them runs at import time: a function body, and the body
+of an ``if TYPE_CHECKING:`` block (its ``else`` branch is runtime code and is checked).
+
+Every rule reads source, so none of them sees an import assembled at runtime, and the third reads one
+function at a time rather than following calls, so a guard a callee performs is invisible to it and is
+spelled out at the deferred import as well. What pins the property itself, a pipe run with Rich refused,
+is ``tests/integration/pipelex/test_rich_free_run.py``.
+
+**There is one escape hatch, and it is the transitive rule's alone.** That rule walks the import graph the
+hub-layering guard builds, and a statement carrying that guard's ``# hub-layering: ignore`` marker is no
+edge in it — so the marker, whose stated purpose is a different guard, also hides the marked module's path
+to Rich. Nothing else here can be switched off: a module that genuinely needs Rich at module level is a
+CLI module and belongs under ``pipelex/cli/``.
+
+This module depends on the stdlib and on the sibling ``hub_layering_guard``, whose import graph it reuses.
+The presentation layer wired into the ``pipelex-dev`` Typer app lives in ``check_rich_imports_cmd.py``.
+"""
+
+from __future__ import annotations
+
+import ast
+from collections import deque
+from pathlib import Path
+from typing import TYPE_CHECKING, NamedTuple
+
+from typing_extensions import override
+
+from pipelex.cli.dev_cli.commands.hub_layering_guard import ImportGraph, build_import_graph, module_qname_for
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+#: Source root the guard scans (relative to the repo root / cwd). Tests are not scanned: the suite
+#: installs every extra.
+SOURCE_ROOT = Path("pipelex")
+
+#: The package allowed to import Rich at module level, as a repo-root-relative posix path prefix.
+CLI_PACKAGE_PREFIX = "pipelex/cli/"
+
+#: The top-level package the guard refuses at module level.
+RICH_PACKAGE = "rich"
+
+#: The ``typing.TYPE_CHECKING`` flag name, matched bare (``TYPE_CHECKING``) or attributed (``typing.TYPE_CHECKING``).
+TYPE_CHECKING_NAME = "TYPE_CHECKING"
+
+#: The only receiver the attributed form may be rooted at, so an unrelated ``x.TYPE_CHECKING`` earns no exemption.
+TYPING_MODULE_NAME = "typing"
+
+REMEDY = (
+ "import Rich inside the function that renders, after `require_rich(...)` or `require_rich_for_rendering()`, "
+ "and put a type-only import under `if TYPE_CHECKING:`; a module that reaches Rich through a CLI module "
+ "defers that import into the function that needs it, or moves what it needs out of `pipelex/cli/`"
+)
+
+#: The calls that answer whether Rich is installed, so a deferred import below one of them is reached only
+#: where Rich is there. ``require_rich`` and ``require_rich_for_rendering`` raise ``MissingDependencyError``
+#: naming the extra; ``get_console`` hands out a console whose own construction raised it already;
+#: ``is_rich_installed`` asks without importing, for a rendering that falls back instead of failing.
+GUARD_CALL_NAMES = frozenset({"require_rich", "require_rich_for_rendering", "get_console", "is_rich_installed"})
+
+#: The module the other fallback shape asks: ``if "rich" not in sys.modules: return None`` holds no Rich object
+#: to render, and answers that without paying for an import.
+SYS_MODULE_RECEIVER = "sys"
+SYS_MODULES_ATTRIBUTE = "modules"
+
+
+class RichImportGuardError(Exception):
+ """The guard cannot run as configured: a self-check failure, never a violation.
+
+ Kept local to this stdlib-only module rather than derived from ``PipelexError``, for the reason
+ ``hub_layering_guard`` gives for its own.
+ """
+
+
+class RichImportViolation(NamedTuple):
+ """One module-level Rich import, located for a report line."""
+
+ relative_path: str
+ lineno: int
+ detail: str
+
+ @property
+ def key(self) -> str:
+ """Stable sort key: file, then line."""
+ return f"{self.relative_path}:{self.lineno:06d}"
+
+
+def is_rich_module(*, module_name: str) -> bool:
+ """Whether a dotted module name is Rich or inside it, matched on the package boundary (``richer`` is not Rich)."""
+ return module_name == RICH_PACKAGE or module_name.startswith(f"{RICH_PACKAGE}.")
+
+
+def is_allowed_path(*, relative_path: str) -> bool:
+ """Whether a repo-root-relative posix path sits in the CLI package, which installs the ``cli`` extra."""
+ return relative_path.startswith(CLI_PACKAGE_PREFIX)
+
+
+def _is_type_checking_test(*, test: ast.expr) -> bool:
+ """Whether an ``if`` test is the bare ``TYPE_CHECKING`` / ``typing.TYPE_CHECKING`` flag.
+
+ Only the bare forms count: ``if not TYPE_CHECKING:`` guards a runtime branch and is not exempt.
+ """
+ match test:
+ case ast.Name(id=name):
+ return name == TYPE_CHECKING_NAME
+ case ast.Attribute(value=ast.Name(id=receiver), attr=attr):
+ return receiver == TYPING_MODULE_NAME and attr == TYPE_CHECKING_NAME
+ case _:
+ return False
+
+
+class _ModuleLevelRichImportCollector(ast.NodeVisitor):
+ """Walks the statements an import of one module executes, recording every Rich import among them."""
+
+ def __init__(self, *, relative_path: str) -> None:
+ self.relative_path = relative_path
+ self.violations: list[RichImportViolation] = []
+
+ def _record(self, *, node: ast.Import | ast.ImportFrom, module_name: str) -> None:
+ self.violations.append(
+ RichImportViolation(relative_path=self.relative_path, lineno=node.lineno, detail=f"imports `{module_name}` at module level")
+ )
+
+ @override
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None: # pylint: disable=invalid-name # ast.NodeVisitor dispatch name
+ """A function body runs when the function is called, not when the module is imported."""
+
+ @override
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: # pylint: disable=invalid-name # ast.NodeVisitor dispatch name
+ """A coroutine body runs when the coroutine is awaited, not when the module is imported."""
+
+ @override
+ def visit_If(self, node: ast.If) -> None: # pylint: disable=invalid-name # ast.NodeVisitor dispatch name
+ """Skip the body of ``if TYPE_CHECKING:``; its ``else`` branch is ordinary runtime code."""
+ if not _is_type_checking_test(test=node.test):
+ self.generic_visit(node)
+ return
+ for statement in node.orelse:
+ self.visit(statement)
+
+ @override
+ def visit_Import(self, node: ast.Import) -> None: # pylint: disable=invalid-name # ast.NodeVisitor dispatch name
+ """``import rich`` / ``import rich.console as console``."""
+ for alias in node.names:
+ if is_rich_module(module_name=alias.name):
+ self._record(node=node, module_name=alias.name)
+ return
+
+ @override
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None: # pylint: disable=invalid-name # ast.NodeVisitor dispatch name
+ """``from rich.console import Console`` / ``from rich import box``. A relative import is never Rich."""
+ if node.level == 0 and node.module is not None and is_rich_module(module_name=node.module):
+ self._record(node=node, module_name=node.module)
+
+
+def _module_level_rich_imports(*, source: str, relative_path: str) -> list[RichImportViolation]:
+ """Every module-level Rich import in one module's source, wherever the module sits."""
+ collector = _ModuleLevelRichImportCollector(relative_path=relative_path)
+ collector.visit(ast.parse(source))
+ return sorted(collector.violations, key=lambda violation: violation.key)
+
+
+def _called_name(*, func: ast.expr) -> str | None:
+ """The bare name a call is made through: ``require_rich(...)`` and ``self.require_rich(...)`` both answer the same."""
+ match func:
+ case ast.Name(id=name):
+ return name
+ case ast.Attribute(attr=attr):
+ return attr
+ case _:
+ return None
+
+
+def _is_sys_modules(*, node: ast.AST) -> bool:
+ """Whether a node is the ``sys.modules`` mapping itself."""
+ return (
+ isinstance(node, ast.Attribute)
+ and node.attr == SYS_MODULES_ATTRIBUTE
+ and isinstance(node.value, ast.Name)
+ and node.value.id == SYS_MODULE_RECEIVER
+ )
+
+
+def _mentions_a_guard(*, node: ast.AST) -> bool:
+ """Whether one expression asks whether Rich is available, by a guard call or by the ``sys.modules`` mapping."""
+ for child in ast.walk(node):
+ if isinstance(child, ast.Call) and _called_name(func=child.func) in GUARD_CALL_NAMES:
+ return True
+ if _is_sys_modules(node=child):
+ return True
+ return False
+
+
+def _establishes_rich_is_available(*, statement: ast.stmt) -> bool:
+ """Whether one statement asks whether Rich is available, so that what follows it may import Rich.
+
+ The question is asked of the statement itself, not of the branches it opens: an ``if`` is read by its
+ condition, so ``if "rich" not in sys.modules: return None`` and ``if is_rich_installed():`` both count,
+ and a guard *call* buried inside a branch counts for that branch and its sequel rather than for the
+ statements above it. That is deliberately permissive — it settles that the question was asked, not that
+ every path through the answer is sound. What pins the property itself is the Rich-refused pipe run in
+ ``tests/integration/pipelex/test_rich_free_run.py``.
+ """
+ match statement:
+ case ast.If(test=test) | ast.While(test=test):
+ return _mentions_a_guard(node=test)
+ case ast.For() | ast.AsyncFor() | ast.With() | ast.AsyncWith() | ast.Try() | ast.ClassDef():
+ return False
+ case _:
+ return _mentions_a_guard(node=statement)
+
+
+def _nested_bodies(*, statement: ast.stmt) -> Iterator[list[ast.stmt]]:
+ """The statement lists one compound statement runs, excluding an ``if TYPE_CHECKING:`` body, which never runs."""
+ match statement:
+ case ast.If(test=test, body=then, orelse=otherwise):
+ if _is_type_checking_test(test=test):
+ yield otherwise
+ return
+ yield then
+ yield otherwise
+ case ast.For(body=then, orelse=otherwise) | ast.AsyncFor(body=then, orelse=otherwise) | ast.While(body=then, orelse=otherwise):
+ yield then
+ yield otherwise
+ case ast.With(body=then) | ast.AsyncWith(body=then) | ast.ClassDef(body=then):
+ yield then
+ case ast.Try(body=then, handlers=handlers, orelse=otherwise, finalbody=finally_):
+ yield then
+ for handler in handlers:
+ yield handler.body
+ yield otherwise
+ yield finally_
+ case _:
+ return
+
+
+def _rich_import_in(*, statement: ast.stmt) -> str | None:
+ """The Rich module one import statement names, or ``None`` for any other statement."""
+ match statement:
+ case ast.Import(names=names):
+ return next((alias.name for alias in names if is_rich_module(module_name=alias.name)), None)
+ case ast.ImportFrom(level=0, module=str() as module) if is_rich_module(module_name=module):
+ return module
+ case _:
+ return None
+
+
+def _unguarded_deferred_rich_imports(*, source: str, relative_path: str) -> list[RichImportViolation]:
+ """Every deferred Rich import that nothing above it in its own function established Rich for.
+
+ Deferring the import is the direct rule's business; this is the other half of the same contract, the one
+ that turns a bare ``ModuleNotFoundError`` into the ``MissingDependencyError`` that names the extra.
+ """
+ violations: list[RichImportViolation] = []
+ for function in _function_scopes(tree=ast.parse(source)):
+ violations.extend(_unguarded_in_block(body=function.body, guarded=False, function_name=function.name, relative_path=relative_path))
+ return violations
+
+
+def _unguarded_in_block(*, body: list[ast.stmt], guarded: bool, function_name: str, relative_path: str) -> list[RichImportViolation]:
+ """Walk one block in order, carrying whether something above already asked that Rich is available.
+
+ A guard reaches everything after it in its own block and everything nested inside those statements; it
+ does not reach backwards, and it does not reach out of the branch it sits in. A nested ``def`` is skipped,
+ being a scope of its own with a guard of its own: its body runs when it is called, not here.
+ """
+ violations: list[RichImportViolation] = []
+ for statement in body:
+ if isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ module_name = _rich_import_in(statement=statement)
+ if module_name is not None and not guarded:
+ violations.append(
+ RichImportViolation(
+ relative_path=relative_path,
+ lineno=statement.lineno,
+ detail=f"imports `{module_name}` inside `{function_name}` with no `require_rich(...)` above it",
+ )
+ )
+ guarded_here = guarded or _establishes_rich_is_available(statement=statement)
+ for nested in _nested_bodies(statement=statement):
+ violations.extend(_unguarded_in_block(body=nested, guarded=guarded_here, function_name=function_name, relative_path=relative_path))
+ guarded = guarded_here
+ return violations
+
+
+def _function_scopes(*, tree: ast.AST) -> Iterator[ast.FunctionDef | ast.AsyncFunctionDef]:
+ """Every function and coroutine in one module, at any depth, each yielded once."""
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ yield node
+
+
+def find_violations_in_source(*, source: str, relative_path: str) -> list[RichImportViolation]:
+ """Scan one module's source and return its module-level Rich imports, or none for a CLI module.
+
+ Args:
+ source: The module's full source text.
+ relative_path: Its repo-root-relative posix path, which decides whether it is a CLI module.
+
+ Raises:
+ SyntaxError: If the source does not parse. Never swallowed: an unparseable module in the scanned
+ tree would otherwise be a blind spot.
+ """
+ if is_allowed_path(relative_path=relative_path):
+ return []
+ violations = _module_level_rich_imports(source=source, relative_path=relative_path)
+ violations.extend(_unguarded_deferred_rich_imports(source=source, relative_path=relative_path))
+ return sorted(violations, key=lambda violation: violation.key)
+
+
+def shortest_chain_to_any(*, graph: ImportGraph, start: str, targets: frozenset[str]) -> list[str]:
+ """The shortest module-level import chain from ``start`` to any module of ``targets``, or ``[]`` if none.
+
+ One breadth-first walk per start rather than one per target, since a CLI module that imports Rich is
+ one of many. Among chains of equal length the next hop is picked in module-name order, so the report
+ is deterministic; cutting one chain may leave another, which the next run reports in turn.
+ """
+ previous: dict[str, str] = {}
+ seen = {start}
+ queue = deque([start])
+ while queue:
+ current = queue.popleft()
+ for module in sorted(graph.edges.get(current, {})):
+ if module in seen:
+ continue
+ previous[module] = current
+ if module in targets:
+ chain = [module]
+ while chain[-1] != start:
+ chain.append(previous[chain[-1]])
+ return list(reversed(chain))
+ seen.add(module)
+ queue.append(module)
+ return []
+
+
+def find_transitive_violations(*, graph: ImportGraph, rich_importers: frozenset[str]) -> list[RichImportViolation]:
+ """Every module outside the CLI package that reaches a CLI module importing Rich, through module-level imports.
+
+ Args:
+ graph: The module-level import graph of the source tree.
+ rich_importers: The dotted names of the CLI modules that import Rich at module level. A module outside
+ the CLI that imports Rich itself is the direct rule's finding, and its importers are not reported
+ again here: removing that one import is the fix for all of them.
+ """
+ violations: list[RichImportViolation] = []
+ for qname, path in sorted(graph.paths.items()):
+ relative_path = path.as_posix()
+ if is_allowed_path(relative_path=relative_path):
+ continue
+ chain = shortest_chain_to_any(graph=graph, start=qname, targets=rich_importers)
+ if not chain:
+ continue
+ first_hop = chain[1]
+ violations.append(
+ RichImportViolation(
+ relative_path=relative_path,
+ lineno=graph.edges[qname][first_hop],
+ detail=f"reaches Rich via {' → '.join(chain[1:])}, which imports it at module level",
+ )
+ )
+ return violations
+
+
+def iter_source_files(*, root: Path) -> Iterator[Path]:
+ """Yield every ``.py`` file under ``root``, excluding ``__pycache__``."""
+ for path in sorted(root.rglob("*.py")):
+ if "__pycache__" in path.parts:
+ continue
+ yield path
+
+
+def collect_violations(*, root: Path) -> list[RichImportViolation]:
+ """Scan every ``.py`` file under ``root`` and return the violations of both rules, sorted by location.
+
+ Args:
+ root: The source root, relative to the repo root: the allowlist is matched on the paths it yields,
+ and the import graph derives module names from them.
+
+ Raises:
+ RichImportGuardError: If the scan finds no module, or none under the CLI package, or an import graph
+ that does not hold the modules the scan read. Each means the root is not the repo-root-relative
+ ``pipelex`` the allowlist and the module names are written against, and the guard would
+ otherwise report a pass having checked nothing, or everything.
+ """
+ violations: list[RichImportViolation] = []
+ rich_importers: set[str] = set()
+ nb_modules = 0
+ nb_cli_modules = 0
+ for path in iter_source_files(root=root):
+ relative_path = path.as_posix()
+ nb_modules += 1
+ source = path.read_text(encoding="utf-8")
+ rich_imports = _module_level_rich_imports(source=source, relative_path=relative_path)
+ if is_allowed_path(relative_path=relative_path):
+ nb_cli_modules += 1
+ # Only a module-level import puts Rich into this module's importers: a deferred one runs on a call.
+ if rich_imports:
+ rich_importers.add(module_qname_for(path=path))
+ else:
+ violations.extend(rich_imports)
+ violations.extend(_unguarded_deferred_rich_imports(source=source, relative_path=relative_path))
+ if nb_modules == 0 or nb_cli_modules == 0:
+ msg = (
+ f"the Rich import guard scanned {nb_modules} module(s) under `{root}`, {nb_cli_modules} of them under "
+ f"`{CLI_PACKAGE_PREFIX}`, so its allowlist matched nothing. Run it from the repo root with the "
+ f"repo-root-relative `{SOURCE_ROOT}` root, or update CLI_PACKAGE_PREFIX if the CLI package moved."
+ )
+ raise RichImportGuardError(msg)
+
+ graph = build_import_graph(root=root)
+ if len(graph.paths) != nb_modules or not rich_importers <= graph.paths.keys():
+ msg = (
+ f"the Rich import guard's import graph holds {len(graph.paths)} module(s) where the scan read {nb_modules}, "
+ f"so the transitive rule would walk a different tree than the direct rule checked."
+ )
+ raise RichImportGuardError(msg)
+ violations.extend(find_transitive_violations(graph=graph, rich_importers=frozenset(rich_importers)))
+ return sorted(violations, key=lambda violation: violation.key)
diff --git a/pipelex/cogt/model_backends/model_lists.py b/pipelex/cogt/model_backends/model_lists.py
index 39b19a4c8..890deebb0 100644
--- a/pipelex/cogt/model_backends/model_lists.py
+++ b/pipelex/cogt/model_backends/model_lists.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-from rich.markup import escape
-
from pipelex.cli.exceptions import PipelexCLIError
from pipelex.cogt.exceptions import ModelListingUnsupportedError, ModelManagerError
from pipelex.runtime_hub import get_console, get_model_lister_registry, get_models_manager
@@ -31,7 +29,10 @@ class ModelLister:
# A backend with no model specs is a valid config state — there is simply nothing to list.
if not backend.model_specs:
+ # The note renders through Rich; the console hands out the named failure when the extra is missing.
console = get_console()
+ from rich.markup import escape
+
if flat:
console.print(f"# Note: Backend '{escape(backend_name)}' has no models configured")
else:
@@ -95,7 +96,10 @@ class ModelLister:
) -> None:
"""Display message about unsupported SDKs."""
if not any_listed and unsupported_sdks:
+ # As above: nothing renders unless there is something to say, so the guard sits with the printing.
console = get_console()
+ from rich.markup import escape
+
if not flat:
console.print(
f"\n[yellow]Note: Backend '{escape(backend_name)}' has models using SDKs that we don't support for remote listing:[/yellow]"
diff --git a/pipelex/cogt/usage/cost_registry.py b/pipelex/cogt/usage/cost_registry.py
index b4dd9dd74..2174dbf6f 100644
--- a/pipelex/cogt/usage/cost_registry.py
+++ b/pipelex/cogt/usage/cost_registry.py
@@ -4,8 +4,6 @@ from pathlib import Path
from typing import Any, NamedTuple
from pydantic import Field, RootModel
-from rich import box
-from rich.table import Table
from pipelex import log
from pipelex.cogt.exceptions import CostRegistryError
@@ -158,8 +156,18 @@ class CostRegistry(RootModel[CostRegistryRoot]):
msg = "Empty report aggregation by model name"
raise CostRegistryError(msg)
+ # The CSV report is written first because it is the output that does not need Rich, the `cli` extra.
+ # Rendering the console table ahead of it would make a process without the extra lose both: the caller
+ # downgrades the missing-dependency error to a warning, so the loss would be silent.
+ if cost_report_file_path:
+ cls.save_to_csv(records, file_path=cost_report_file_path)
+
if print_to_console:
+ # The console table is the one output here that needs Rich.
console = get_console()
+ from rich import box
+ from rich.table import Table
+
title = f"Costs by model for pipeline '{pipeline_run_id}'"
table = Table(title=title, box=box.ROUNDED)
@@ -223,9 +231,6 @@ class CostRegistry(RootModel[CostRegistryRoot]):
console.print(table)
console.print(" [dim]Note: some costs might be missing or not up-to-date.[/dim]")
- if cost_report_file_path:
- cls.save_to_csv(records, file_path=cost_report_file_path)
-
@staticmethod
def save_to_csv(records: list[dict[str, Any]], *, file_path: Path) -> None:
"""Save records to CSV file."""
diff --git a/pipelex/core/stuffs/date_content.py b/pipelex/core/stuffs/date_content.py
index 658e6fbb9..053ee7620 100644
--- a/pipelex/core/stuffs/date_content.py
+++ b/pipelex/core/stuffs/date_content.py
@@ -1,17 +1,19 @@
import datetime
import json
-from typing import Any
+from typing import TYPE_CHECKING, Any
from pydantic import Field, ValidationInfo, field_validator
-from rich.json import JSON
from typing_extensions import override
from pipelex.core.stuffs.exceptions import DateContentError
from pipelex.core.stuffs.iso_temporal import parse_iso_date, parse_iso_time
from pipelex.core.stuffs.stuff_content import StuffContent
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.misc.string_utils import is_numeric_string
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class DateContent(StuffContent):
"""A calendar date, optionally with a time of day — as precise as its source states.
@@ -114,7 +116,10 @@ class DateContent(StuffContent):
return json.dumps({"date": self.date.isoformat(), "time": self.time.isoformat() if self.time is not None else None})
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.json import JSON
+
# The base renders smart_dump() (real date/time objects, which stdlib json can't serialize);
# render the ISO two-field JSON instead so pretty_print of a Date does not crash.
return JSON(self.rendered_json())
diff --git a/pipelex/core/stuffs/document_content.py b/pipelex/core/stuffs/document_content.py
index cfa8ae482..71f6d0fac 100644
--- a/pipelex/core/stuffs/document_content.py
+++ b/pipelex/core/stuffs/document_content.py
@@ -1,16 +1,18 @@
-from typing import Self
+from typing import TYPE_CHECKING, Self
from pydantic import Field, model_validator
-from rich.text import Text
from typing_extensions import override
from pipelex.core.stuffs.stuff_content import StuffContent
from pipelex.tools.jinja2.jinja2_rendering import render_jinja2_sync
from pipelex.tools.jinja2.template_category import TemplateCategory
from pipelex.tools.misc.http_utils import validate_url_resource_exists
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.uri.uri_resolver import extract_filename_from_uri, resolve_uri
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class DocumentContent(StuffContent):
"""A document"""
@@ -86,7 +88,10 @@ class DocumentContent(StuffContent):
return result
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.text import Text
+
source_text = Text()
if self.title:
source_text.append(self.title, style="bold")
diff --git a/pipelex/core/stuffs/image_content.py b/pipelex/core/stuffs/image_content.py
index 5fc39302c..be5c7a805 100644
--- a/pipelex/core/stuffs/image_content.py
+++ b/pipelex/core/stuffs/image_content.py
@@ -1,9 +1,6 @@
-from typing import Self
+from typing import TYPE_CHECKING, Self
from pydantic import Field, model_validator
-from rich.console import Group
-from rich.markdown import Markdown
-from rich.text import Text
from typing_extensions import override
from pipelex.core.stuffs.stuff_content import StuffContent
@@ -11,10 +8,13 @@ from pipelex.tools.jinja2.image_registry import ImageRegistry
from pipelex.tools.jinja2.jinja2_rendering import render_jinja2_sync
from pipelex.tools.jinja2.template_category import TemplateCategory
from pipelex.tools.misc.http_utils import validate_url_resource_exists
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.templating.text_format import TextFormat
from pipelex.tools.uri.uri_resolver import describe_uri, extract_filename_from_uri
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class ImageContent(StuffContent):
"""An image"""
@@ -90,7 +90,12 @@ class ImageContent(StuffContent):
return f"[Image {image_index + 1}]"
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markdown import Markdown
+ from rich.text import Text
+
group = Group()
# title indicating it's an image:
diff --git a/pipelex/core/stuffs/json_content.py b/pipelex/core/stuffs/json_content.py
index 4829e88c3..ad1233222 100644
--- a/pipelex/core/stuffs/json_content.py
+++ b/pipelex/core/stuffs/json_content.py
@@ -1,14 +1,16 @@
import json
-from typing import Any
+from typing import TYPE_CHECKING, Any
from json2html import json2html
from pydantic import Field, field_validator
-from rich.json import JSON
from typing_extensions import override
from pipelex.core.stuffs.stuff_content import StuffContent
from pipelex.tools.misc.markdown_utils import convert_to_markdown
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
# TODO: use pipelex.tools.misc.json_utils.JsonContent to support lists in addition to dicts
@@ -50,5 +52,8 @@ class JSONContent(StuffContent):
return json.dumps(self.json_obj, indent=4)
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.json import JSON
+
return JSON.from_data(self.json_obj, indent=4)
diff --git a/pipelex/core/stuffs/list_content.py b/pipelex/core/stuffs/list_content.py
index c5aa1e784..a7c61b59a 100644
--- a/pipelex/core/stuffs/list_content.py
+++ b/pipelex/core/stuffs/list_content.py
@@ -1,15 +1,16 @@
-from typing import Any, Generic, Iterator, overload
+from typing import TYPE_CHECKING, Any, Generic, Iterator, overload
-from rich.pretty import Pretty
-from rich.table import Table
from typing_extensions import override
from pipelex.core.stuffs.stuff_content import StuffContent, StuffContentType
from pipelex.tools.jinja2.image_registry import ImageRegistry
from pipelex.tools.jinja2.image_renderable import ImageRenderable
-from pipelex.tools.misc.pretty import MAX_RENDER_DEPTH, PrettyPrintable, PrettyPrinter
+from pipelex.tools.misc.pretty import MAX_RENDER_DEPTH, PrettyPrinter, require_rich_for_rendering
from pipelex.tools.templating.text_format import TextFormat
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class ListContent(StuffContent, Generic[StuffContentType]):
items: list[StuffContentType]
@@ -156,7 +157,11 @@ class ListContent(StuffContent, Generic[StuffContentType]):
return "\n".join(parts)
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.pretty import Pretty
+ from rich.table import Table
+
# Check if we've exceeded maximum depth - fall back to Pretty rendering
# Pretty shows the Python object structure beautifully, just like when calling pretty_print(stuff)
if depth >= MAX_RENDER_DEPTH:
diff --git a/pipelex/core/stuffs/page_content.py b/pipelex/core/stuffs/page_content.py
index 20f12b9c3..3c6c7d8f3 100644
--- a/pipelex/core/stuffs/page_content.py
+++ b/pipelex/core/stuffs/page_content.py
@@ -1,13 +1,15 @@
+from typing import TYPE_CHECKING
+
from pydantic import Field
-from rich.console import Group
-from rich.markdown import Markdown
-from rich.text import Text
from typing_extensions import override
from pipelex.core.stuffs.image_content import ImageContent
from pipelex.core.stuffs.structured_content import StructuredContent
from pipelex.core.stuffs.text_and_images_content import TextAndImagesContent
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
class PageContent(StructuredContent):
@@ -17,7 +19,12 @@ class PageContent(StructuredContent):
page_view: ImageContent | None = Field(default=None, description="The screenshot of the page")
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markdown import Markdown
+ from rich.text import Text
+
# If there's no page_view, just return the text_and_images rendering
if self.page_view is None:
return self.text_and_images.rendered_pretty(depth=depth)
diff --git a/pipelex/core/stuffs/search_result_content.py b/pipelex/core/stuffs/search_result_content.py
index 949ef5fa8..2718cbc77 100644
--- a/pipelex/core/stuffs/search_result_content.py
+++ b/pipelex/core/stuffs/search_result_content.py
@@ -1,16 +1,17 @@
import html as html_module
+from typing import TYPE_CHECKING
from pydantic import Field
-from rich.console import Group
-from rich.markdown import Markdown
-from rich.text import Text
from typing_extensions import override
from pipelex.core.stuffs.document_content import DocumentContent
from pipelex.core.stuffs.stuff_content import StuffContent
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class SearchResultContent(StuffContent):
"""Represents the result of a search query with an answer and list of sources."""
@@ -53,7 +54,12 @@ class SearchResultContent(StuffContent):
return result
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markdown import Markdown
+ from rich.text import Text
+
group = Group()
# Title
diff --git a/pipelex/core/stuffs/structured_content.py b/pipelex/core/stuffs/structured_content.py
index effba109e..7cc5af411 100644
--- a/pipelex/core/stuffs/structured_content.py
+++ b/pipelex/core/stuffs/structured_content.py
@@ -1,8 +1,6 @@
import html as html_module
-from typing import Any, cast
+from typing import TYPE_CHECKING, Any, cast
-from rich.pretty import Pretty
-from rich.table import Table
from typing_extensions import override
from pipelex.core.stuffs.html_rendering import render_value_html
@@ -10,10 +8,13 @@ from pipelex.core.stuffs.stuff_content import StuffContent
from pipelex.tools.jinja2.image_registry import ImageRegistry
from pipelex.tools.jinja2.image_renderable import ImageRenderable
from pipelex.tools.misc.markdown_utils import convert_to_markdown
-from pipelex.tools.misc.pretty import MAX_RENDER_DEPTH, PrettyPrintable, PrettyPrinter
+from pipelex.tools.misc.pretty import MAX_RENDER_DEPTH, PrettyPrinter, require_rich_for_rendering
from pipelex.tools.templating.text_format import TextFormat
from pipelex.tools.typing.pydantic_utils import clean_model_to_dict
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class StructuredContent(StuffContent):
@property
@@ -124,7 +125,11 @@ class StructuredContent(StuffContent):
# -------------------------------------------------------------------------
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.pretty import Pretty
+ from rich.table import Table
+
# Check if we've exceeded maximum depth - fall back to Pretty rendering
# Pretty shows the Python object structure beautifully, just like when calling pretty_print(stuff)
if depth >= MAX_RENDER_DEPTH:
diff --git a/pipelex/core/stuffs/stuff.py b/pipelex/core/stuffs/stuff.py
index 8445d85de..82911805e 100644
--- a/pipelex/core/stuffs/stuff.py
+++ b/pipelex/core/stuffs/stuff.py
@@ -1,5 +1,5 @@
# pyright: reportImportCycles=false
-from typing import Any, cast, get_args, get_origin
+from typing import TYPE_CHECKING, Any, cast, get_args, get_origin
from kajson import kajson
from mthds.protocol.stuff import StuffAbstract
@@ -22,10 +22,13 @@ from pipelex.core.stuffs.stuff_content import StuffContent, StuffContentType
from pipelex.core.stuffs.text_and_images_content import TextAndImagesContent
from pipelex.core.stuffs.text_content import TextContent
from pipelex.core.stuffs.yes_no_content import YesNoContent
-from pipelex.tools.misc.pretty import PrettyPrintable, PrettyRenderable
+from pipelex.tools.misc.pretty import PrettyRenderable
from pipelex.tools.misc.string_utils import pascal_case_to_snake_case
from pipelex.tools.typing.pydantic_utils import CustomBaseModel, format_pydantic_validation_error
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class Stuff(PrettyRenderable, CustomBaseModel, StuffAbstract[Concept, StuffContent]):
def make_artefact(self) -> StuffArtefact:
@@ -250,7 +253,7 @@ class Stuff(PrettyRenderable, CustomBaseModel, StuffAbstract[Concept, StuffConte
return self.content_as(MermaidContent)
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
"""Render stuff for pretty printing.
Args:
diff --git a/pipelex/core/stuffs/stuff_content.py b/pipelex/core/stuffs/stuff_content.py
index b45704d6a..8719f3506 100644
--- a/pipelex/core/stuffs/stuff_content.py
+++ b/pipelex/core/stuffs/stuff_content.py
@@ -1,14 +1,16 @@
-from typing import Any, TypeVar, final
+from typing import TYPE_CHECKING, Any, TypeVar, final
from kajson import kajson
from mthds.protocol.stuff import StuffContentAbstract
-from rich.json import JSON
from typing_extensions import override
-from pipelex.tools.misc.pretty import PrettyPrintable, PrettyPrinter, PrettyPrintMode, PrettyRenderable, pretty_print
+from pipelex.tools.misc.pretty import PrettyPrinter, PrettyPrintMode, PrettyRenderable, pretty_print, require_rich_for_rendering
from pipelex.tools.templating.text_format import TextFormat
from pipelex.tools.typing.pydantic_utils import CustomBaseModel
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
StuffContentType = TypeVar("StuffContentType", bound="StuffContent")
@@ -122,13 +124,16 @@ class StuffContent(PrettyRenderable, CustomBaseModel, StuffContentAbstract):
# -------------------------------------------------------------------------
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
"""Render content for pretty printing.
Args:
title: Optional title for the rendering
depth: Current nesting depth, used to prevent nesting too many sub-tables which would end up too narrow in the console
"""
+ require_rich_for_rendering()
+ from rich.json import JSON
+
json_data = self.smart_dump()
return JSON.from_data(json_data, indent=4)
diff --git a/pipelex/core/stuffs/stuff_viewer.py b/pipelex/core/stuffs/stuff_viewer.py
index 9e5e20f61..e7f619e2a 100644
--- a/pipelex/core/stuffs/stuff_viewer.py
+++ b/pipelex/core/stuffs/stuff_viewer.py
@@ -13,6 +13,7 @@ from pipelex.tools.jinja2.jinja2_rendering import render_jinja2_async
from pipelex.tools.jinja2.jinja2_template_registry import TemplateRegistry
from pipelex.tools.jinja2.template_category import TemplateCategory
from pipelex.tools.misc.pretty import PRETTY_WIDTH_FOR_EXPORT
+from pipelex.tools.misc.rich_extra import is_rich_installed
# Template registry key
_STUFF_VIEWER_TEMPLATE_KEY = "stuff/stuff_viewer.html.jinja2"
@@ -44,7 +45,9 @@ async def render_stuff_viewer(
# Get content data in various formats
stuff_data = stuff.content.smart_dump()
- stuff_data_text = stuff.content.rendered_pretty_text(width=PRETTY_WIDTH_FOR_EXPORT)
+ # The Pretty tab is Rich's text rendering, and Rich is the `cli` extra: without it the tab shows the JSON,
+ # which is the fallback the page already has for a missing text rendering.
+ stuff_data_text = stuff.content.rendered_pretty_text(width=PRETTY_WIDTH_FOR_EXPORT) if is_rich_installed() else None
stuff_data_html = await stuff.content.rendered_html_async()
content_type = stuff.content.content_type
diff --git a/pipelex/core/stuffs/text_and_images_content.py b/pipelex/core/stuffs/text_and_images_content.py
index 063fecef5..02488abf8 100644
--- a/pipelex/core/stuffs/text_and_images_content.py
+++ b/pipelex/core/stuffs/text_and_images_content.py
@@ -1,17 +1,18 @@
+from typing import TYPE_CHECKING
+
from pydantic import Field
-from rich.console import Group
-from rich.markdown import Markdown
-from rich.table import Table
-from rich.text import Text
from typing_extensions import override
from pipelex.core.stuffs.image_content import ImageContent
from pipelex.core.stuffs.stuff_content import StuffContent
from pipelex.core.stuffs.text_content import TextContent
from pipelex.tools.jinja2.image_registry import ImageRegistry
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.templating.text_format import TextFormat
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class TextAndImagesContent(StuffContent):
text: TextContent | None = Field(default=None, description="A text content")
@@ -90,7 +91,13 @@ class TextAndImagesContent(StuffContent):
return "\n".join(parts)
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.markdown import Markdown
+ from rich.table import Table
+ from rich.text import Text
+
# If neither text nor images are present
if not self.text and not self.images:
return Text("(empty)", style="dim italic")
diff --git a/pipelex/core/stuffs/text_content.py b/pipelex/core/stuffs/text_content.py
index 7a7a9d536..d772c7867 100644
--- a/pipelex/core/stuffs/text_content.py
+++ b/pipelex/core/stuffs/text_content.py
@@ -1,14 +1,16 @@
import html
import json
import re
+from typing import TYPE_CHECKING
from pydantic import Field
-from rich.markdown import Markdown
-from rich.syntax import Syntax
from typing_extensions import override
from pipelex.core.stuffs.stuff_content import StuffContent
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
+
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
HTML_PATTERN = re.compile(r"^\s*<(!DOCTYPE|!--|[a-zA-Z])", re.IGNORECASE)
@@ -46,7 +48,11 @@ class TextContent(StuffContent):
return bool(HTML_PATTERN.match(self.text))
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.markdown import Markdown
+ from rich.syntax import Syntax
+
if self._looks_like_html():
return Syntax(self.text, "html", word_wrap=True)
return Markdown(self.text)
diff --git a/pipelex/core/stuffs/time_content.py b/pipelex/core/stuffs/time_content.py
index 0acff41a8..aa86d1caa 100644
--- a/pipelex/core/stuffs/time_content.py
+++ b/pipelex/core/stuffs/time_content.py
@@ -1,16 +1,18 @@
import datetime
import json
-from typing import Any
+from typing import TYPE_CHECKING, Any
from pydantic import Field, field_validator
-from rich.json import JSON
from typing_extensions import override
from pipelex.core.stuffs.iso_temporal import parse_iso_time
from pipelex.core.stuffs.stuff_content import StuffContent
-from pipelex.tools.misc.pretty import PrettyPrintable
+from pipelex.tools.misc.pretty import require_rich_for_rendering
from pipelex.tools.misc.string_utils import is_numeric_string
+if TYPE_CHECKING:
+ from pipelex.tools.misc.pretty import PrettyPrintable
+
class TimeContent(StuffContent):
"""A time of day, optionally with a UTC offset — as precise as its source states.
@@ -71,7 +73,10 @@ class TimeContent(StuffContent):
return json.dumps({"time": self.time.isoformat()})
@override
- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":
+ require_rich_for_rendering()
+ from rich.json import JSON
+
# The base renders smart_dump() (a real time object, which stdlib json can't serialize);
# render the ISO JSON instead so pretty_print of a Time does not crash.
return JSON(self.rendered_json())
diff --git a/pipelex/kit/agent_rules/codex_commands.md b/pipelex/kit/agent_rules/codex_commands.md
index 796981911..bea72f961 100644
--- a/pipelex/kit/agent_rules/codex_commands.md
+++ b/pipelex/kit/agent_rules/codex_commands.md
@@ -7,7 +7,7 @@
```bash
make agent-check
# If the current system doesn't have the `make` command,
- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering drift-check)
+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check)
```
This runs multiple code quality tools:
diff --git a/pipelex/kit/agent_rules/commands.md b/pipelex/kit/agent_rules/commands.md
index c9670cb09..32deaead2 100644
--- a/pipelex/kit/agent_rules/commands.md
+++ b/pipelex/kit/agent_rules/commands.md
@@ -2,7 +2,7 @@
`make` targets activate the virtual environment themselves; anything else (`pytest`, `pipelex`, `pipelex-dev`) runs from `.venv/bin/` (`.venv\Scripts\` on Windows), never bare. The Makefile is the reference for every target and alias; without `make`, read the target there and run its prerequisites one by one.
-- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering drift-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check and the drift contracts. The drift digest reads the git index, so stage your changes before the check.
+- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module) and the drift contracts. The drift digest reads the git index, so stage your changes before the check.
- **Keyword-only arguments** (the convention is in the standards and in `docs/contribute/keyword-only-arguments.md`): `make check-keyword-only` (`cko`) is the gate, `make fix-keyword-only` (`fko`) inserts the bare `*` where it can — on ungranted subjects too — and reports the shapes it cannot fix, and `make subject-grant FUNC="<path>::<qualname>" RATIONALE="…"` (`sgr`) grants a positional subject. Grant before `make agent-check`, which runs the fixer.
- **Drift contracts.** When `make drift-check` reports an open contract: `make drift-plan`, review and fix the stale targets, `git add` the trigger files, then `make drift-ack CONTRACT=<id> RATIONALE="…"`. No bypass flag; "reviewed, no doc change needed" is a legitimate rationale. See `docs/contribute/drift-contracts.md`.
- **`make agent-test` at the end of every coding session.** Heartbeat lines while running, full output only on failure. If it hangs or fails opaquely, `make agent-test-debug` (`atd`) adds stale-process cleanup, an outer timeout and a live log; the methodology is `docs/agents/debugging-hanging-pytest-runs.md`. At intermediate steps in a local setup, running only the relevant tests is fine: `.venv/bin/pytest -x -q tests/unit/path/to/test_module.py`, or `make t TEST=<name>` (pytest `-k` substring matching; `TEST=LF` reruns the last failures). `make tp` / `make test-with-prints` are for a human at a terminal; an agent in the cloud or in a sandbox uses `make agent-test` only.
diff --git a/pipelex/kit/agent_rules/python_standards.md b/pipelex/kit/agent_rules/python_standards.md
index 12e040f67..a034bb57c 100644
--- a/pipelex/kit/agent_rules/python_standards.md
+++ b/pipelex/kit/agent_rules/python_standards.md
@@ -50,6 +50,7 @@
- Do not import libraries in functions or classes unless in very specific cases, to be discussed with the user, as they would required a `# noqa: ...` comment to pass linting
- Do not bother with ordering the imports or removing unused imports, our Ruff linter will handle it for us.
- `if TYPE_CHECKING:` blocks must always be the **last** block in the imports section, placed after all regular imports.
+- **Rich is the standing exception.** It is the `cli` extra, which a server does not install, so outside `pipelex/cli/` it is imported inside the function that renders, after `require_rich(...)` (`pipelex.tools.misc.rich_extra`) or `require_rich_for_rendering()` (`pipelex.tools.misc.pretty`), and a type-only import of it goes under `if TYPE_CHECKING:`. Such a deferred import needs no suppression comment, and `make check-rich-imports` refuses a module-level one, as well as a module-level import of a CLI module that imports Rich. See `docs/contribute/rich-imports.md`.
### Removing unused imports
diff --git a/pipelex/libraries/pipe/pipe_library.py b/pipelex/libraries/pipe/pipe_library.py
index 870c7af2d..4af6476ab 100644
--- a/pipelex/libraries/pipe/pipe_library.py
+++ b/pipelex/libraries/pipe/pipe_library.py
@@ -2,8 +2,6 @@ from itertools import groupby
from typing import Self
from pydantic import RootModel
-from rich import box
-from rich.table import Table
from typing_extensions import override
from pipelex import pretty_print
@@ -11,6 +9,7 @@ from pipelex.core.qualified_ref import QualifiedRef
from pipelex.libraries.pipe.exceptions import EntryPipeAmbiguousError, EntryPipeNotFoundError, PipeLibraryError, PipeNotFoundError
from pipelex.libraries.pipe.pipe_library_abstract import PipeLibraryAbstract
from pipelex.pipe_machinery.pipe_abstract import PipeAbstract
+from pipelex.tools.misc.rich_extra import RICH_TABLE_MISSING_MESSAGE, require_rich
PipeLibraryRoot = dict[str, PipeAbstract]
@@ -200,6 +199,11 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):
@override
def pretty_list_pipes(self) -> None:
+ # The table is built whatever the pretty-print mode, so this listing needs Rich in every mode.
+ require_rich(message=RICH_TABLE_MISSING_MESSAGE)
+ from rich import box
+ from rich.table import Table
+
def _format_concept_code(concept_code: str | None, *, current_domain: str) -> str:
"""Format concept code by removing domain prefix if it matches current domain."""
if not concept_code:
diff --git a/pipelex/providers/anthropic/anthropic_list.py b/pipelex/providers/anthropic/anthropic_list.py
index 97990931f..7a0b1f706 100644
--- a/pipelex/providers/anthropic/anthropic_list.py
+++ b/pipelex/providers/anthropic/anthropic_list.py
@@ -3,13 +3,11 @@ from __future__ import annotations
import importlib.util
from typing import TYPE_CHECKING
-from rich import box
-from rich.table import Table
-
from pipelex.cli.exceptions import PipelexCLIError
from pipelex.plugins.model_handle import ModelHandle
from pipelex.runtime_hub import get_console
from pipelex.system.exceptions import MissingDependencyError
+from pipelex.tools.misc.rich_extra import RICH_TABLE_MISSING_MESSAGE, require_rich
if TYPE_CHECKING:
from anthropic.types import ModelInfo
@@ -93,6 +91,10 @@ def _display_anthropic_models_table(
backend_name: str,
) -> None:
"""Display Anthropic models in table format."""
+ require_rich(message=RICH_TABLE_MISSING_MESSAGE)
+ from rich import box
+ from rich.table import Table
+
table = Table(
title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
show_header=True,
diff --git a/pipelex/providers/bedrock/bedrock_list.py b/pipelex/providers/bedrock/bedrock_list.py
index 4d4d38ce4..55b5c30e9 100644
--- a/pipelex/providers/bedrock/bedrock_list.py
+++ b/pipelex/providers/bedrock/bedrock_list.py
@@ -3,15 +3,13 @@ from __future__ import annotations
import importlib.util
from typing import TYPE_CHECKING, Any
-from rich import box
-from rich.table import Table
-
from pipelex.cli.exceptions import PipelexCLIError
from pipelex.config import get_config
from pipelex.plugins.model_handle import ModelHandle
from pipelex.runtime_hub import get_console
from pipelex.system.exceptions import MissingDependencyError
from pipelex.tools.aws.exceptions import AwsCredentialsError
+from pipelex.tools.misc.rich_extra import RICH_TABLE_MISSING_MESSAGE, require_rich
if TYPE_CHECKING:
from pipelex.cogt.model_backends.backend import InferenceBackend
@@ -103,6 +101,10 @@ def _display_bedrock_models_table(
aws_region: str,
) -> None:
"""Display Bedrock models in table format."""
+ require_rich(message=RICH_TABLE_MISSING_MESSAGE)
+ from rich import box
+ from rich.table import Table
+
table = Table(
title=f"Available Bedrock Models in {aws_region} (SDK: {sdk})",
show_header=True,
diff --git a/pipelex/providers/google/google_list.py b/pipelex/providers/google/google_list.py
index c2658249f..2f888c0ca 100644
--- a/pipelex/providers/google/google_list.py
+++ b/pipelex/providers/google/google_list.py
@@ -3,11 +3,9 @@ from __future__ import annotations
import importlib.util
from typing import TYPE_CHECKING, Any
-from rich import box
-from rich.table import Table
-
from pipelex.runtime_hub import get_console
from pipelex.system.exceptions import MissingDependencyError
+from pipelex.tools.misc.rich_extra import RICH_TABLE_MISSING_MESSAGE, require_rich
if TYPE_CHECKING:
from pipelex.cogt.model_backends.backend import InferenceBackend
@@ -79,6 +77,10 @@ def _display_google_models_table(
backend_name: str,
) -> None:
"""Display Google GenAI models in table format."""
+ require_rich(message=RICH_TABLE_MISSING_MESSAGE)
+ from rich import box
+ from rich.table import Table
+
table = Table(
title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
show_header=True,
diff --git a/pipelex/providers/mistral/mistral_list.py b/pipelex/providers/mistral/mistral_list.py
index 039c14235..10efe9575 100644
--- a/pipelex/providers/mistral/mistral_list.py
+++ b/pipelex/providers/mistral/mistral_list.py
@@ -3,11 +3,9 @@ from __future__ import annotations
import importlib.util
from typing import Any
-from rich import box
-from rich.table import Table
-
from pipelex.runtime_hub import get_console
from pipelex.system.exceptions import MissingDependencyError
+from pipelex.tools.misc.rich_extra import RICH_TABLE_MISSING_MESSAGE, require_rich
def list_mistral_models(
@@ -74,6 +72,10 @@ def _display_mistral_models_table(
backend_name: str,
) -> None:
"""Display Mistral models in table format."""
+ require_rich(message=RICH_TABLE_MISSING_MESSAGE)
+ from rich import box
+ from rich.table import Table
+
table = Table(
title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
show_header=True,
diff --git a/pipelex/providers/openai/openai_list.py b/pipelex/providers/openai/openai_list.py
index 0149f6ea1..d521bd08c 100644
--- a/pipelex/providers/openai/openai_list.py
+++ b/pipelex/providers/openai/openai_list.py
@@ -3,12 +3,10 @@ from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
-from rich import box
-from rich.table import Table
-
from pipelex.plugins.model_handle import ModelHandle
from pipelex.providers.openai.openai_llms import openai_list_available_models
from pipelex.runtime_hub import get_console
+from pipelex.tools.misc.rich_extra import RICH_TABLE_MISSING_MESSAGE, require_rich
if TYPE_CHECKING:
from openai.types import Model
@@ -74,6 +72,10 @@ def _display_openai_models_table(
backend_name: str,
) -> None:
"""Display OpenAI models in table format."""
+ require_rich(message=RICH_TABLE_MISSING_MESSAGE)
+ from rich import box
+ from rich.table import Table
+
table = Table(
title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
show_header=True,
diff --git a/pipelex/runtime_boot.py b/pipelex/runtime_boot.py
index 798e349d5..e72d07624 100644
--- a/pipelex/runtime_boot.py
+++ b/pipelex/runtime_boot.py
@@ -124,6 +124,7 @@ from pipelex.test_extras.registry_test_models import TestRegistryModels
from pipelex.tools.jinja2.jinja2_template_loader import TemplateLoader
from pipelex.tools.jinja2.jinja2_template_registry import TemplateRegistry
from pipelex.tools.misc.package_utils import get_package_info
+from pipelex.tools.misc.pretty import PrettyPrintMode, require_rich_for_rendering
from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract
from pipelex.urls import URLs
@@ -556,6 +557,11 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
log_config = get_config().runtime.log
log_sink_registry = LogSinkRegistry(plugin_registrar.log_sinks)
log.install_sink(log_sink_registry.get_required(method=log_config.sink)(log_config))
+ # The pretty-print mode is checked beside the sink, for the same reason: Rich is the ``cli`` extra,
+ # and a process asking for the ``rich`` panels without it stops here, naming the extra and the
+ # Rich-free modes, rather than failing at the first pipe that prints its output.
+ if log_config.pretty_print_mode is PrettyPrintMode.RICH:
+ require_rich_for_rendering()
# Secrets provider precedence: explicit setup() param > config-selected registry factory.
# The built-in SecretsPlugin supplies the "env" method, so there is no separate core default.
diff --git a/pipelex/runtime_hub.py b/pipelex/runtime_hub.py
index 4682e96a1..48caf3ba0 100644
--- a/pipelex/runtime_hub.py
+++ b/pipelex/runtime_hub.py
@@ -24,10 +24,9 @@ from collections.abc import Callable, Generator
from contextlib import contextmanager
from contextvars import ContextVar
from pathlib import Path
-from typing import TYPE_CHECKING, Any, ClassVar, Optional
+from typing import TYPE_CHECKING, Any, ClassVar, Optional, TextIO
from kajson.class_registry_abstract import ClassRegistryAbstract
-from rich.console import Console
from pipelex import log
from pipelex.cogt.content_generation.content_generator_protocol import (
@@ -49,6 +48,7 @@ from pipelex.system.registries.class_registry_access import get_class_registry a
from pipelex.system.registries.func_registry import FuncRegistry
from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract
from pipelex.tools.misc.pretty import PrettyPrinter, PrettyPrintMode
+from pipelex.tools.misc.rich_extra import require_rich
from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract
@@ -56,6 +56,9 @@ if TYPE_CHECKING:
# Deferred import: avoid pulling heavy SDK at module-load time
from opentelemetry.trace import Tracer as OTelTracer
+ # Rich is the `cli` extra: the console is built when it is first asked for, never at import or at boot.
+ from rich.console import Console
+
from pipelex.plugins.bundle_validator_registry import BundleValidatorRegistry
from pipelex.plugins.inference_backend_registry import InferenceBackendRegistry
from pipelex.plugins.model_lister_registry import ModelListerRegistry
@@ -74,6 +77,18 @@ def _never_in_isolated_execution() -> bool:
return False
+def _make_console(*, file: TextIO | None = None, stderr: bool = False) -> "Console":
+ """A Rich console, built on demand because Rich is the ``cli`` extra.
+
+ Raises:
+ MissingDependencyError: If Rich is not installed.
+ """
+ require_rich(message="get_console() hands out the Rich console the CLI prints its tables, panels and banners through.")
+ from rich.console import Console
+
+ return Console(file=file, stderr=stderr)
+
+
class RuntimeHub:
"""Central dependency manager for process-scoped infrastructure services.
@@ -89,6 +104,8 @@ class RuntimeHub:
# tools
self._config: ConfigRoot | None = None
self._console: Console | None = None
+ # The stream boot's console_print_target resolved to, held until the console is first asked for.
+ self._console_print_stream: TextIO | None = None
self._secrets_provider: SecretsProviderAbstract | None = None
self._storage_provider: StorageProviderAbstract | None = None
self._telemetry_manager: TelemetryManagerAbstract | None = None
@@ -222,16 +239,23 @@ class RuntimeHub:
PrettyPrinter.mode = mode
def set_console_print_target(self, target: ConsoleTarget):
+ """Resolve the stream ``get_console()`` prints to, and drop any console built or set before.
+
+ The stream is the one current now, as the console built here used to capture it; the console
+ itself is built when first asked for, because Rich is the ``cli`` extra and a process that never
+ prints a table must not need it.
+ """
match target:
case ConsoleTarget.STDOUT:
- self._console = Console(file=sys.stdout)
+ self._console_print_stream = sys.stdout
case ConsoleTarget.STDERR:
- self._console = Console(file=sys.stderr)
+ self._console_print_stream = sys.stderr
case _:
msg = f"Invalid console target: {target}"
raise ValueError(msg)
+ self._console = None
- def set_console(self, console: Console):
+ def set_console(self, console: "Console"):
self._console = console
def set_secrets_provider(self, secrets_provider: SecretsProviderAbstract):
@@ -328,11 +352,18 @@ class RuntimeHub:
"""
return self._config
- def get_console(self) -> Console:
+ def get_console(self) -> "Console":
+ """The console set, or the one on boot's print target, built on first use; a stderr console before boot.
+
+ Raises:
+ MissingDependencyError: If a console has to be built and Rich is not installed.
+ """
if self._console:
return self._console
- else:
- return Console(stderr=True)
+ if self._console_print_stream is not None:
+ self._console = _make_console(file=self._console_print_stream)
+ return self._console
+ return _make_console(stderr=True)
def get_required_secrets_provider(self) -> SecretsProviderAbstract:
if self._secrets_provider is None:
@@ -667,9 +698,14 @@ def get_event_log_override() -> "EventLogProtocol | None":
return _event_log_override.get()
-def get_console() -> Console:
+def get_console() -> "Console":
+ """The Rich console the CLI prints its tables, panels and banners through.
+
+ Raises:
+ MissingDependencyError: If Rich is not installed.
+ """
runtime_hub = RuntimeHub.get_optional_instance()
if runtime_hub:
return runtime_hub.get_console()
else:
- return Console(stderr=True)
+ return _make_console(stderr=True)
diff --git a/pipelex/system/configuration/config_check.py b/pipelex/system/configuration/config_check.py
index 88e15a92b..2d5de29ab 100644
--- a/pipelex/system/configuration/config_check.py
+++ b/pipelex/system/configuration/config_check.py
@@ -1,5 +1,3 @@
-from rich.panel import Panel
-
from pipelex.runtime_hub import get_console
from pipelex.system.configuration.config_loader import CONFIG_NAME, config_manager
from pipelex.tools.misc.file_utils import path_exists
@@ -20,7 +18,9 @@ def check_is_initialized(*, print_warning_if_not: bool = True) -> bool:
is_initialized = config_exists and backends_exists and routing_exists
if not is_initialized and print_warning_if_not:
+ # The warning panel is the one thing here that needs Rich, the `cli` extra: the check itself does not.
console = get_console()
+ from rich.panel import Panel
# Build a descriptive message about what's missing
issues: list[str] = []
diff --git a/pipelex/test_extras/shared_pytest_plugins.py b/pipelex/test_extras/shared_pytest_plugins.py
index 03ee1f58d..3c0c93c8e 100644
--- a/pipelex/test_extras/shared_pytest_plugins.py
+++ b/pipelex/test_extras/shared_pytest_plugins.py
@@ -3,14 +3,14 @@ from enum import StrEnum
import pytest
from pytest import Config, FixtureRequest, Parser
-from rich.console import Console
-from rich.panel import Panel
-from pipelex.runtime_hub import get_console
from pipelex.system.environment import is_env_var_set, is_env_var_truthy, set_env
from pipelex.system.pipe_run_mode import PipeRunMode
from pipelex.system.runtime import CODEX_CLOUD_ENV_VAR_KEY, RunMode, runtime_manager
from pipelex.tools.misc.placeholder import make_placeholder_value, value_is_placeholder
+from pipelex.tools.misc.pretty import plain_markup_text
+from pipelex.tools.misc.rich_extra import is_rich_installed
+from pipelex.tools.misc.terminal_utils import print_to_stderr
class ClassRegistryMode(StrEnum):
@@ -89,6 +89,40 @@ def pytest_addoption(parser: Parser):
)
+#: What a session stopped for the terms agreement says. Written as Rich markup once: the Rich panel renders it,
+#: and the Rich-free path prints the text it renders to, so the message arrives either way.
+_TERMS_REQUIRED_MARKUP = (
+ "[bold yellow]Pipelex Service Terms Agreement Required[/bold yellow]\n\n"
+ "Tests cannot run because Pipelex Gateway is enabled but terms haven't been accepted.\n\n"
+ "[bold]To fix this, choose one option:[/bold]\n\n"
+ " [cyan]1.[/cyan] Run [green]pipelex init agreement[/green] to accept terms (quick, no config reset)\n\n"
+ " [cyan]2.[/cyan] Run [green]pipelex init config[/green] to fully reset and configure backends\n\n"
+ " [cyan]3.[/cyan] Disable gateway in [blue].pipelex/inference/backends.toml[/blue]:\n"
+ " [dim]Set pipelex_gateway.enabled = false[/dim]\n"
+)
+
+_TERMS_REQUIRED_TITLE = "⚠️ Setup Required"
+
+
+def _print_terms_required() -> None:
+ """Say why the session is stopping, framed by Rich where the extra is installed and plainly where it is not.
+
+ Rich is the ``cli`` extra and this plugin loads in every session of every project that registers it, so the
+ message a stopped session depends on is never allowed to depend on it.
+ """
+ if not is_rich_installed():
+ print_to_stderr("")
+ print_to_stderr(_TERMS_REQUIRED_TITLE)
+ print_to_stderr(plain_markup_text(markup=_TERMS_REQUIRED_MARKUP) or _TERMS_REQUIRED_MARKUP)
+ return
+ from rich.console import Console
+ from rich.panel import Panel
+
+ console = Console()
+ console.print()
+ console.print(Panel(_TERMS_REQUIRED_MARKUP, title=_TERMS_REQUIRED_TITLE, border_style="yellow"))
+
+
@pytest.hookimpl(tryfirst=True)
def pytest_configure(config: Config) -> None:
"""Set the test run mode, then check prerequisites before test collection starts.
@@ -128,21 +162,7 @@ def pytest_configure(config: Config) -> None:
pipelex_service_config = load_pipelex_service_config_if_exists(config_dir=config_manager.global_config_dir)
if pipelex_service_config is None or not pipelex_service_config.agreement.terms_accepted:
- console = Console()
- console.print()
- console.print(
- Panel(
- "[bold yellow]Pipelex Service Terms Agreement Required[/bold yellow]\n\n"
- "Tests cannot run because Pipelex Gateway is enabled but terms haven't been accepted.\n\n"
- "[bold]To fix this, choose one option:[/bold]\n\n"
- " [cyan]1.[/cyan] Run [green]pipelex init agreement[/green] to accept terms (quick, no config reset)\n\n"
- " [cyan]2.[/cyan] Run [green]pipelex init config[/green] to fully reset and configure backends\n\n"
- " [cyan]3.[/cyan] Disable gateway in [blue].pipelex/inference/backends.toml[/blue]:\n"
- " [dim]Set pipelex_gateway.enabled = false[/dim]\n",
- title="⚠️ Setup Required",
- border_style="yellow",
- )
- )
+ _print_terms_required()
pytest.exit("Service terms not accepted - run 'pipelex init agreement' first", returncode=1)
@@ -175,7 +195,9 @@ def _setup_env_var_placeholders(env_var_keys: list[str]) -> None:
substitutions_counter += 1
if substitutions_counter > 0:
- get_console().print(f"[yellow]Set {substitutions_counter} placeholder environment variables[/yellow]")
+ # A plain line rather than a console one: this plugin loads in every session of every project that
+ # registers it, and a CI diagnostic must never be the reason a suite cannot run.
+ print_to_stderr(f"Set {substitutions_counter} placeholder environment variables")
def _cleanup_placeholder_env_vars(env_var_keys: list[str]) -> None:
@@ -198,7 +220,8 @@ def _cleanup_placeholder_env_vars(env_var_keys: list[str]) -> None:
removed_counter += 1
if removed_counter > 0:
- get_console().print(f"[yellow]Cleaned up {removed_counter} placeholder environment variables[/yellow]")
+ # As above: a plain line, for the same reason.
+ print_to_stderr(f"Cleaned up {removed_counter} placeholder environment variables")
@pytest.fixture(scope="session", autouse=True)
diff --git a/pipelex/tools/log/console_log_sink.py b/pipelex/tools/log/console_log_sink.py
index a9618acd7..bb04b281f 100644
--- a/pipelex/tools/log/console_log_sink.py
+++ b/pipelex/tools/log/console_log_sink.py
@@ -1,8 +1,13 @@
"""The ``console`` sink: the Rich handler with the emoji formatter and every ``[runtime.log.rich_log]`` setting.
-Rich is imported when the handler is built and nowhere else in this module, so a process that selects
-another sink never loads it, and one that selects this sink without Rich installed fails at boot with
-the extra to install and the ``json`` alternative named, per the plugin system's fail-at-use rule.
+Rich is the ``cli`` extra. It is imported when the handler is built and nowhere else in this module, so
+this module asks for Rich only where this sink is the one selected; a process that selects another sink
+never reaches that import. One that selects this sink without Rich installed fails at boot with the extra
+to install and the ``json`` alternative named, per the plugin system's fail-at-use rule.
+
+Note that selecting another sink does not leave the process without Rich loaded: ``typer`` and
+``instructor`` are core dependencies that require it, so an ``import pipelex`` loads Rich whatever this
+module does. What is true is that nothing here is the reason.
"""
from __future__ import annotations
@@ -12,10 +17,10 @@ from typing import TYPE_CHECKING
from typing_extensions import override
-from pipelex.system.exceptions import MissingDependencyError
from pipelex.tools.log.log_config import HighlighterName
from pipelex.tools.log.log_formatter import EmojiLogFormatter
from pipelex.tools.log.log_sink import LogSink, LogSinkMethod, stream_for_target
+from pipelex.tools.misc.rich_extra import require_rich
if TYPE_CHECKING:
import logging
@@ -25,8 +30,11 @@ if TYPE_CHECKING:
from pipelex.system.console_target import ConsoleTarget
from pipelex.tools.log.log_config import RichLogConfig
-# The extra that installs Rich. Rich is a hard dependency today; this is the name the extra takes when it moves.
-RICH_EXTRA_NAME = "cli"
+#: What this sink says when the extra is missing, named once for every place in it that asks for Rich.
+CONSOLE_SINK_MISSING_MESSAGE = (
+ f"The '{LogSinkMethod.CONSOLE}' log sink renders through Rich. Install the extra, "
+ f"or select the '{LogSinkMethod.JSON}' sink in [runtime.log] for a process with no terminal."
+)
class ConsoleLogSink(LogSink):
@@ -40,16 +48,10 @@ class ConsoleLogSink(LogSink):
@override
def make_handler(self) -> logging.Handler:
- try:
- from rich.console import Console # ruff: ignore[import-outside-top-level]
- from rich.highlighter import Highlighter, JSONHighlighter, ReprHighlighter # ruff: ignore[import-outside-top-level]
- from rich.logging import RichHandler # ruff: ignore[import-outside-top-level]
- except ImportError as exc:
- msg = (
- f"The '{LogSinkMethod.CONSOLE}' log sink renders through Rich. Install the extra, "
- f"or select the '{LogSinkMethod.JSON}' sink in [runtime.log] for a process with no terminal."
- )
- raise MissingDependencyError(dependency_name="rich", extra_name=RICH_EXTRA_NAME, message=msg) from exc
+ require_rich(message=CONSOLE_SINK_MISSING_MESSAGE)
+ from rich.console import Console
+ from rich.highlighter import Highlighter, JSONHighlighter, ReprHighlighter
+ from rich.logging import RichHandler
# Declared here because ``RichHandler`` is imported here, which is what keeps Rich off the import
# path of a process that selected another sink. ``RichHandler`` overrides ``emit`` and does not
@@ -93,9 +95,14 @@ class ConsoleLogSink(LogSink):
@override
def redirect_to_stderr(self) -> None:
- from rich.console import Console # ruff: ignore[import-outside-top-level]
-
+ # The handler is built first, so a process without Rich meets the same named failure as at boot. The
+ # guard is spelled out beside the import as well: a handler this sink already holds proves Rich is
+ # there, but that is a fact about the object rather than about this function, and the import guard
+ # reads functions.
+ require_rich(message=CONSOLE_SINK_MISSING_MESSAGE)
if self._rich_handler is None:
_ = self.handler
if self._rich_handler is not None:
+ from rich.console import Console
+
self._rich_handler.console = Console(file=sys.stderr)
diff --git a/pipelex/tools/misc/diff.py b/pipelex/tools/misc/diff.py
index 91ce459e4..6f585c92c 100644
--- a/pipelex/tools/misc/diff.py
+++ b/pipelex/tools/misc/diff.py
@@ -5,13 +5,8 @@ import filecmp
from pathlib import Path
from typing import TYPE_CHECKING
-from rich.console import Group
-from rich.syntax import Syntax
-from rich.table import Table
-from rich.text import Text
-
from pipelex.tools.misc.file_utils import is_excluded_by_name
-from pipelex.tools.misc.pretty import PrettyPrinter, PrettyPrintMode
+from pipelex.tools.misc.pretty import PrettyPrinter, PrettyPrintMode, require_rich_for_rendering
if TYPE_CHECKING:
from collections.abc import Set as AbstractSet
@@ -238,6 +233,12 @@ def make_diff_dirs_pretty(
and different files with full diff content. For different files, indicates
which version is newer based on modification time.
"""
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.syntax import Syntax
+ from rich.table import Table
+ from rich.text import Text
+
dir1 = Path(dir1)
dir2 = Path(dir2)
exclude_dirs = exclude_dirs or set()
diff --git a/pipelex/tools/misc/pretty.py b/pipelex/tools/misc/pretty.py
index 1c2d47680..f160bb2a9 100644
--- a/pipelex/tools/misc/pretty.py
+++ b/pipelex/tools/misc/pretty.py
@@ -1,27 +1,46 @@
+"""The pretty-print engine: the mode, the Rich panels, and the plain-text panels printed without Rich.
+
+Rich is the ``cli`` extra, so this module imports it nowhere at module level: each method of the ``rich``
+mode, and each ``rendered_pretty`` on the model types, checks that Rich is installed and imports what it
+renders with, inside its body. The ``poor`` mode frames plain text itself and never imports Rich; the
+``silent`` mode builds nothing. A process without Rich renders in ``poor`` or ``silent`` and never loads
+it, and one that asks for ``rich`` without it is refused at boot, naming the extra.
+"""
+
+from __future__ import annotations
+
+import re
import shutil
+import sys
from abc import ABC, abstractmethod
from enum import StrEnum
from io import StringIO
-from typing import Any, ClassVar
+from typing import TYPE_CHECKING, Any, ClassVar
from kajson import kajson
from pydantic import BaseModel
-from rich.console import Console, Group
-from rich.errors import MarkupError
-from rich.json import JSON
-from rich.markdown import Markdown
-from rich.measure import Measurement
-from rich.panel import Panel
-from rich.pretty import Pretty
-from rich.style import StyleType
-from rich.syntax import Syntax
-from rich.table import Table
-from rich.text import Text, TextType
from pipelex.tools.misc.attribute_utils import AttributePolisher
+from pipelex.tools.misc.rich_extra import require_rich
from pipelex.tools.misc.terminal_utils import BOLD_FONT, RESET_FONT, TerminalColor, print_to_stderr
from pipelex.tools.typing.pydantic_utils import make_truncated_wrapper
+if TYPE_CHECKING:
+ from typing import TypeAlias
+
+ from rich.console import Group
+ from rich.json import JSON
+ from rich.markdown import Markdown
+ from rich.panel import Panel
+ from rich.pretty import Pretty
+ from rich.style import StyleType
+ from rich.syntax import Syntax
+ from rich.table import Table
+ from rich.text import Text, TextType
+
+ # The renderables a ``rendered_pretty`` returns and the ``rich`` mode prints as they are.
+ PrettyPrintable: TypeAlias = Markdown | Text | JSON | Table | Group | Syntax | Pretty
+
TEXT_COLOR = TerminalColor.WHITE
TITLE_COLOR = TerminalColor.CYAN
BORDER_COLOR = TerminalColor.YELLOW
@@ -31,13 +50,83 @@ PRETTY_WIDTH_MIN: int = 125
PRETTY_WIDTH_FOR_EXPORT: int = 100
MAX_RENDER_DEPTH = 6
-PrettyPrintable = Markdown | Text | JSON | Table | Group | Syntax | Pretty
+RICH_RENDERING_MISSING_MESSAGE = (
+ 'The pretty-print mode "rich" and the rendered_pretty renderings print through Rich. Install the extra, '
+ 'or set pretty_print_mode to "poor" or "silent" in [runtime.log] for a process with no terminal: both render without it.'
+)
+
+# Rich's own console-markup tag pattern, ``rich.markup.RE_TAGS``: a run of backslashes, then a bracketed tag
+# whose name starts with a lowercase letter, ``#``, ``/`` or ``@``.
+_MARKUP_TAG_PATTERN = re.compile(r"((\\*)\[([a-z#/@][^[]*?)])")
+
+
+def require_rich_for_rendering() -> None:
+ """Raise ``MissingDependencyError`` naming the ``cli`` extra and the Rich-free modes when Rich is not installed.
+
+ A ``rendered_pretty`` implementation calls it first, then imports what it renders with.
+ """
+ require_rich(message=RICH_RENDERING_MISSING_MESSAGE)
+
+
+def plain_markup_text(*, markup: str) -> str | None:
+ """The text Rich console markup reads as, tags dropped, or ``None`` where it cannot be read as tags at all.
+
+ Rich-free, so the ``poor`` mode reads a title without importing Rich. It follows ``rich.markup``'s own tag
+ pattern and its backslash escaping, and it tracks how deep the tags nest so that a closing tag with
+ nothing open — a bracketed path, say — is reported rather than silently eaten. Anything it accepts, it
+ returns as text.
+
+ Two deliberate differences from Rich, both in the direction of accepting more:
+
+ - **Which tag a close matches is not decided here.** Rich resolves a closing tag through its style
+ grammar, so it knows that ``[b]`` and ``[/bold]`` are one style and that ``[/italic]`` cannot close
+ ``[bold]``. Reproducing that means reproducing ``Style.parse``, which is Rich. This reading closes the
+ innermost open tag whatever either is named, which strips the same text and refuses less.
+ - **A ``@`` tag's parameters are dropped unread**, where Rich parses them and refuses a malformed one.
+
+ Accepting more than Rich costs this caller nothing: the ``poor`` mode prints whatever happens, and a
+ title that reads as text beats one that prints its own tags. Refusing more would cost it the title.
+
+ One thing it does not do at all: an emoji code is left as it is written, since substituting ``:rocket:``
+ needs Rich's own code table. That is a behaviour change of the ``poor`` mode, documented in
+ ``docs/contribute/rich-imports.md``.
+ """
+ if "[" not in markup:
+ return markup
+ pieces: list[str] = []
+ open_depth = 0
+ position = 0
+ for match in _MARKUP_TAG_PATTERN.finditer(markup):
+ full_text, escapes, tag_text = match.groups()
+ start, end = match.span()
+ if start > position:
+ pieces.append(markup[position:start].replace("\\[", "["))
+ position = end
+ backslashes, escaped = divmod(len(escapes), 2)
+ pieces.append("\\" * backslashes)
+ if escaped:
+ pieces.append(full_text[len(escapes) :])
+ continue
+ tag_name = tag_text.partition("=")[0]
+ if not tag_name.startswith("/"):
+ open_depth += 1
+ continue
+ if open_depth == 0:
+ return None
+ open_depth -= 1
+ if position < len(markup):
+ pieces.append(markup[position:].replace("\\[", "["))
+ return "".join(pieces)
class PrettyRenderable(ABC):
@abstractmethod
def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> PrettyPrintable:
- pass
+ """A Rich renderable of this object, for the console.
+
+ Rich is the ``cli`` extra: an implementation calls ``require_rich_for_rendering()`` and then imports
+ what it renders with, inside the method.
+ """
def rendered_pretty_text(self, *, title: str | None = None, width: int = PRETTY_WIDTH_FOR_EXPORT) -> str:
"""Render as plain ASCII text string.
@@ -48,6 +137,9 @@ class PrettyRenderable(ABC):
Returns:
Plain text string representation
+
+ Raises:
+ MissingDependencyError: If Rich is not installed.
"""
pretty = self.rendered_pretty(title=title, depth=0)
return PrettyPrinter.pretty_text(pretty, width=width)
@@ -94,9 +186,17 @@ def pretty_print_md(
# A silent printer builds no renderable, and does not measure the terminal to size one.
return
width = width or PrettyPrinter.pretty_width()
- md_content = Markdown(content)
- PrettyPrinter.pretty_print(
- content=md_content,
+ if PrettyPrinter.mode is PrettyPrintMode.POOR:
+ # The poor printer renders no Markdown: it frames the source it was given.
+ PrettyPrinter.pretty_print_without_rich(
+ content, title=title, subtitle=subtitle, inner_title=inner_title, width=width, console_width=console_width
+ )
+ return
+ require_rich_for_rendering()
+ from rich.markdown import Markdown
+
+ PrettyPrinter.pretty_print_using_rich(
+ Markdown(content),
title=title,
subtitle=subtitle,
inner_title=inner_title,
@@ -121,7 +221,17 @@ def pretty_print_url(
return
if url.startswith("/"):
url = "file://" + url
- pretty_print(
+ if PrettyPrinter.mode is PrettyPrintMode.POOR:
+ # The url on a row of its own, so a terminal can linkify it whole. The border style is the one thing
+ # dropped here: the plain frame is monochrome, so there is nothing for it to colour.
+ PrettyPrinter.pretty_print_url_without_rich(
+ url, title=title, subtitle=subtitle, inner_title=inner_title, width=width, console_width=console_width
+ )
+ return
+ require_rich_for_rendering()
+ from rich.text import Text
+
+ PrettyPrinter.pretty_print_using_rich(
Text(url, style="link " + url, no_wrap=False),
title=title,
subtitle=subtitle,
@@ -177,6 +287,12 @@ class PrettyPrinter:
width: int | None = None,
console_width: int | None = None,
):
+ """Print the content in a Rich panel on stdout, between two blank lines.
+
+ Raises:
+ MissingDependencyError: If Rich is not installed.
+ """
+ require_rich_for_rendering()
panel = cls.make_pretty_panel(
content=content,
title=title,
@@ -186,6 +302,7 @@ class PrettyPrinter:
width=width,
console_width=console_width,
)
+ from rich.console import Console
Console(width=console_width).print("", panel, "", sep="\n")
@@ -213,15 +330,23 @@ class PrettyPrinter:
width: int | None = None,
console_width: int | None = None,
) -> Panel:
+ """The Rich panel the ``rich`` mode prints.
+
+ Raises:
+ MissingDependencyError: If Rich is not installed.
+ """
+ require_rich_for_rendering()
pretty = cls.make_pretty(content, inner_title=inner_title, depth=0)
# When width is not specified, measure the content to determine optimal console width
if width is None:
+ from rich.console import Console
+ from rich.measure import Measurement
+
# Create a console to measure the panel
measure_console = Console(width=console_width)
measurement = Measurement.get(measure_console, measure_console.options, pretty)
# Use the maximum width that fits the content, with some buffer for panel border rendering
width = measurement.maximum + 4
- # print(f"width: {width}")
if console_width is not None:
width = min(width, console_width)
return cls.wrap_in_panel(pretty=pretty, title=title, subtitle=subtitle, border_style=border_style, width=width)
@@ -236,6 +361,10 @@ class PrettyPrinter:
border_style: StyleType | None = None,
width: int | None = None,
) -> Panel:
+ """Raises MissingDependencyError if Rich is not installed."""
+ require_rich_for_rendering()
+ from rich.panel import Panel
+
return Panel(
pretty,
title=title,
@@ -264,7 +393,13 @@ class PrettyPrinter:
Returns:
Plain text string representation
+
+ Raises:
+ MissingDependencyError: If Rich is not installed.
"""
+ require_rich_for_rendering()
+ from rich.console import Console
+
buf = StringIO()
console = Console(record=True, file=buf, width=width, force_terminal=False)
console.print(pretty)
@@ -272,6 +407,10 @@ class PrettyPrinter:
@classmethod
def pretty_svg(cls, pretty: PrettyPrintable, *, width: int = PRETTY_WIDTH_FOR_EXPORT) -> str:
+ """Raises MissingDependencyError if Rich is not installed."""
+ require_rich_for_rendering()
+ from rich.console import Console
+
buf = StringIO()
console = Console(record=True, file=buf, width=width, force_terminal=False)
console.print(pretty)
@@ -279,9 +418,23 @@ class PrettyPrinter:
@classmethod
def make_pretty(cls, value: Any, *, inner_title: str | None = None, depth: int = 0) -> PrettyPrintable:
+ """The Rich renderable for any value: a renderable as it is, a ``PrettyRenderable`` rendered, anything else by its type.
+
+ Raises:
+ MissingDependencyError: If Rich is not installed.
+ """
+ require_rich_for_rendering()
+ from rich.console import Group
+ from rich.json import JSON
+ from rich.markdown import Markdown
+ from rich.pretty import Pretty
+ from rich.syntax import Syntax
+ from rich.table import Table
+ from rich.text import Text
+
pretty: PrettyPrintable
# Format the value
- if isinstance(value, PrettyPrintable):
+ if isinstance(value, (Markdown, Text, JSON, Table, Group, Syntax, Pretty)):
pretty = value
elif isinstance(value, PrettyRenderable):
pretty = value.rendered_pretty(depth=depth)
@@ -348,7 +501,9 @@ class PrettyPrinter:
console_width: int | None = None,
):
if isinstance(content, str) and content.startswith(("http://", "https://")):
- cls.pretty_print_url_without_rich(content=content, title=title, subtitle=subtitle, width=width, console_width=console_width)
+ cls.pretty_print_url_without_rich(
+ content=content, title=title, subtitle=subtitle, inner_title=inner_title, width=width, console_width=console_width
+ )
return
# Titles are Rich markup in every mode (a caller writes them once, for the Rich panel), so they are
# measured and printed as the text they render to, not as the tags they are spelled with.
@@ -371,11 +526,9 @@ class PrettyPrinter:
# A title never widens the frame past the terminal: it is elided to the width the content wraps to, the way
# Rich's `Panel` truncates an over-wide title, rather than spilling the box it is supposed to sit inside.
title_lines = [cls._elide(line=line, max_width=max_content_width) for line in title_lines]
- if isinstance(content, PrettyPrintable):
- # A caller handing over a Rich renderable gets its text, not the object's repr.
- content_str = cls.pretty_text(content, width=max_content_width)
- else:
- content_str = f"{content}"
+ # A caller handing over a Rich renderable gets its text, not the object's repr.
+ renderable_text = cls._rich_renderable_text(content=content, width=max_content_width)
+ content_str = f"{content}" if renderable_text is None else renderable_text
wrapped_lines: list[str] = []
for line in content_str.splitlines():
if not line:
@@ -403,17 +556,37 @@ class PrettyPrinter:
print_to_stderr(f"{BORDER_COLOR}│ {TEXT_COLOR}{line}{RESET_FONT}{padding}{BORDER_COLOR}│{RESET_FONT}")
print_to_stderr(f"{BORDER_COLOR}{bottom_border}{RESET_FONT}")
+ @classmethod
+ def _rich_renderable_text(cls, *, content: Any, width: int) -> str | None:
+ """The text of a Rich renderable handed to the poor printer, or ``None`` for any other content.
+
+ A Rich object exists only once Rich is imported, so a process that has not imported Rich holds none
+ to hand over, and the check costs it no import.
+ """
+ if "rich" not in sys.modules:
+ return None
+ from rich.console import Group
+ from rich.json import JSON
+ from rich.markdown import Markdown
+ from rich.pretty import Pretty
+ from rich.syntax import Syntax
+ from rich.table import Table
+ from rich.text import Text
+
+ if not isinstance(content, (Markdown, Text, JSON, Table, Group, Syntax, Pretty)):
+ return None
+ return cls.pretty_text(content, width=width)
+
@classmethod
def _plain_title(cls, *, title: TextType) -> str:
"""The text a panel title renders to: markup tags dropped, as Rich's `Panel` would drop them."""
- if isinstance(title, Text):
+ if not isinstance(title, str):
+ # A Rich `Text`, which exists only where Rich is imported.
return title.plain
- try:
- return Text.from_markup(title).plain
- except MarkupError:
- # A title spelling something Rich reads as an unmatched closing tag — a path in brackets, say — is
- # printed as it stands. The poor mode is the one that prints whatever happens, so it never raises here.
- return title
+ plain = plain_markup_text(markup=title)
+ # A title spelling something Rich reads as an unmatched closing tag — a path in brackets, say — is
+ # printed as it stands. The poor mode is the one that prints whatever happens, so it never raises here.
+ return title if plain is None else plain
@classmethod
def _elide(cls, *, line: str, max_width: int) -> str:
@@ -431,12 +604,13 @@ class PrettyPrinter:
*,
title: TextType | None = None,
subtitle: TextType | None = None,
+ inner_title: str | None = None,
width: int | None = None,
console_width: int | None = None,
):
# The url itself prints on a row of its own, outside the frame, so a terminal can linkify it whole.
# Everything around it obeys the same rules as the framed printer: markup titles render to their text,
- # and nothing is drawn wider than the terminal.
+ # each title sits on a row of its own, and nothing is drawn wider than the terminal.
title_str = cls._plain_title(title=title) if title else ""
if subtitle:
title_str += f" ({cls._plain_title(title=subtitle)})"
@@ -445,13 +619,13 @@ class PrettyPrinter:
if width:
frame_width = min(frame_width, width + 6)
frame_width = max(frame_width, 5)
- title_str = cls._elide(line=title_str, max_width=frame_width - 4)
+ title_lines = [cls._elide(line=line, max_width=frame_width - 4) for line in (title_str, inner_title or "") if line]
top_border = "╭" + "─" * (frame_width - 2) + "╮"
bottom_border = "╰" + "─" * (frame_width - 2) + "╯"
print_to_stderr(f"{BORDER_COLOR}{top_border}{RESET_FONT}")
- if title_str:
- title_padding = " " * (frame_width - len(title_str) - 4)
- print_to_stderr(f"{BORDER_COLOR}│ {BOLD_FONT}{TITLE_COLOR}{title_str}{RESET_FONT}:{title_padding}{BORDER_COLOR}│{RESET_FONT}")
+ for title_line in title_lines:
+ title_padding = " " * (frame_width - len(title_line) - 4)
+ print_to_stderr(f"{BORDER_COLOR}│ {BOLD_FONT}{TITLE_COLOR}{title_line}{RESET_FONT}:{title_padding}{BORDER_COLOR}│{RESET_FONT}")
print_to_stderr(f"{TEXT_COLOR}{content}{RESET_FONT}")
print_to_stderr(f"{BORDER_COLOR}{bottom_border}{RESET_FONT}")
diff --git a/pipelex/tools/misc/rich_extra.py b/pipelex/tools/misc/rich_extra.py
new file mode 100644
index 000000000..c21c2a058
--- /dev/null
+++ b/pipelex/tools/misc/rich_extra.py
@@ -0,0 +1,48 @@
+"""Rich is the ``cli`` extra: this module names the extra and says so when it is missing.
+
+Nothing here imports Rich at module level, and nothing here imports ``pipelex`` at module level either:
+the pretty-print engine imports this module, and the engine sits under the log package every
+``import pipelex`` loads first.
+"""
+
+import importlib
+import importlib.util
+
+# The extra that installs Rich: the console log sink, the pretty-print engine's ``rich`` mode, the
+# ``rendered_pretty`` renderings and the CLI all render through it.
+RICH_EXTRA_NAME = "cli"
+
+#: What a listing whose result is a Rich table says when the extra is missing. The model listings and the pipe
+#: listing share it: each builds a table and has nothing else to print it as.
+RICH_TABLE_MISSING_MESSAGE = "This listing prints its result in a Rich table."
+
+
+def require_rich(*, message: str) -> None:
+ """Import Rich, or raise ``MissingDependencyError`` naming the ``cli`` extra.
+
+ Called before a lazy ``from rich… import …``, so a process without the extra is told what to
+ install, and what to select instead, rather than handed a bare ``ModuleNotFoundError``.
+
+ Args:
+ message: What renders through Rich here, and the Rich-free alternative when there is one.
+
+ Raises:
+ MissingDependencyError: If Rich cannot be imported.
+ """
+ try:
+ importlib.import_module("rich")
+ except ImportError as exc:
+ # Deferred: see the module docstring.
+ from pipelex.system.exceptions import MissingDependencyError # ruff: ignore[import-outside-top-level]
+
+ raise MissingDependencyError(dependency_name="rich", extra_name=RICH_EXTRA_NAME, message=message) from exc
+
+
+def is_rich_installed() -> bool:
+ """Whether Rich is installed, asked without importing it, for a rendering that has a Rich-free fallback rather than a failure."""
+ try:
+ return importlib.util.find_spec("rich") is not None
+ except (ImportError, ValueError):
+ # An import hook refusing the name answers as an absent package would; a ``rich`` module left in
+ # ``sys.modules`` without a spec is not an installation either.
+ return False
diff --git a/pyproject.toml b/pyproject.toml
index 5faab8090..6df615a83 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -50,7 +50,6 @@ dependencies = [
"PyYAML>=6.0.2",
"reportlab>=4.0,<5", # for generating synthetic PDFs
"requests>=2.33.0",
- "rich>=13.8.1",
"semantic-version>=2.10.0",
"shortuuid>=1.0.13",
# Not stdlib tomllib: our error path reads TOMLDecodeError.{msg,doc,pos,lineno,colno},
@@ -75,6 +74,12 @@ Changelog = "https://docs.pipelex.com/changelog/"
[project.optional-dependencies]
anthropic = ["anthropic>=0.78.0"]
bedrock = ["boto3>=1.34.131", "aioboto3>=13.4.0"]
+# Rich renders the terminal: the `pipelex` and `pipelex-agent` CLIs, the console log sink and the
+# pretty-print mode "rich". Nothing the runtime does on the way to running a method needs it, so a
+# server selects the json sink and a Rich-free pretty-print mode and never reaches for it. Leaving this
+# extra out does not make the environment Rich-free, though: `typer` and `instructor` are core
+# dependencies and both require Rich unconditionally, so a stock install still contains it.
+cli = ["rich>=13.8.1"]
docling = [
"docling>=2.94.0",
"lxml>=6.1.0",
@@ -483,13 +488,24 @@ runtime-evaluated-base-classes = [
"pipelex.system.configuration.config_root.ConfigRoot",
]
+[tool.ruff.lint.flake8-tidy-imports]
+# Rich is the `cli` extra, so outside the CLI it is imported inside the function that renders, never at
+# module level. Listing it here is also what lets such a deferred import stand without an
+# `import-outside-top-level` suppression. The authoritative gate is `make check-rich-imports`, which applies
+# the same allowlist and also sees an import in a module-level `try` block or class body; the per-file
+# ignore for `pipelex/cli/` below mirrors its allowlist.
+banned-module-level-imports = ["rich"]
+
[tool.ruff.lint.per-file-ignores]
"tests/**/*.py" = [
- "implicit-namespace-package", # Allow test files to not have __init__.py in their directories (avoids namespace collisions)
- "blind-except", # Broad `except Exception` is acceptable in tests (asserting failure modes, defensive fixtures)
- "float-equality-comparison", # Tests assert exact float literals that round-trip exactly; `pytest.approx` would only add noise
- "import-private-name", # Tests reach into private `_core` modules on purpose, to exercise the logic behind a CLI command without going through the CLI
+ "implicit-namespace-package", # Allow test files to not have __init__.py in their directories (avoids namespace collisions)
+ "blind-except", # Broad `except Exception` is acceptable in tests (asserting failure modes, defensive fixtures)
+ "float-equality-comparison", # Tests assert exact float literals that round-trip exactly; `pytest.approx` would only add noise
+ "import-private-name", # Tests reach into private `_core` modules on purpose, to exercise the logic behind a CLI command without going through the CLI
+ "banned-module-level-imports", # The test suite installs every extra, the `cli` extra's Rich included
]
+# The CLI installs the `cli` extra: the check-rich-imports guard's allowlist.
+"pipelex/cli/**/*.py" = ["banned-module-level-imports"]
# The usage example in `needs_inference_in_pipelex` is a pytest fixture, so it contains a bare `yield`
# line. Ruff's Google-style parser reads any line starting with `yield` as a section header, wherever it
diff --git a/tests/integration/pipelex/test_rich_free_run.py b/tests/integration/pipelex/test_rich_free_run.py
new file mode 100644
index 000000000..8b61a7260
--- /dev/null
+++ b/tests/integration/pipelex/test_rich_free_run.py
@@ -0,0 +1,206 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess # ruff: ignore[suspicious-subprocess-import]
+import sys
+import textwrap
+from pathlib import Path
+
+import pytest
+
+from pipelex.tools.misc.pretty import PrettyPrintMode
+from pipelex.tools.misc.rich_extra import RICH_EXTRA_NAME
+
+#: Anchored on `tests/` by name rather than by a parent count, for the reason `test_hub_layering_guard.py` gives.
+_REPO_ROOT = next(parent for parent in Path(__file__).resolve().parents if parent.name == "tests").parent
+
+# Rich is the `cli` extra, and a server installs pipelex without it. The suite installs every extra, so the
+# subprocess stands in for that install: a meta-path finder installed before the first `pipelex` import
+# refuses every `rich` module, which is exactly what an uninstalled Rich is to an `import`. A subprocess,
+# because the test process has Rich loaded already and evicting it would leave duplicate classes behind.
+_NO_RICH_PRELUDE = textwrap.dedent(
+ """
+ import importlib.abc
+ import sys
+
+ class _RichBlocker(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path, target=None):
+ if fullname == "rich" or fullname.startswith("rich."):
+ raise ImportError(f"no-rich guard blocked '{fullname}'")
+ return None
+
+ sys.meta_path.insert(0, _RichBlocker())
+
+ from pipelex.pipelex import Pipelex
+ from pipelex.system.runtime import IntegrationMode
+
+ # A pytest-spawned process, and it says so. The session's run mode is set on the in-process
+ # `runtime_manager` and never exported, so a child can neither read it nor claim `IntegrationMode.CI`
+ # on the strength of it; what keeps these boots credential-free is `needs_model_specs=False` below,
+ # not the mode.
+ INTEGRATION_MODE = IntegrationMode.PYTEST
+ """
+)
+
+# A live run of an operator pipe that needs no inference, in-process, so the "Output of pipe" panel every
+# operator prints is on the path. Rich must still be absent from the process when the run is over.
+#
+# `needs_model_specs=False` is what makes the boot runnable on a machine that has never configured
+# inference — a CI runner, that is. The bundle below names no model, so the Pipelex service's published
+# specs are of no use to it: the boot takes the dummy-specs branch, which asks for neither the gateway
+# terms nor the network. `needs_inference` stays True on purpose — a keyless boot forces every run to DRY,
+# and the dry path does not print the "Output of pipe" panel, which is the Rich reach under test.
+_RUN_SCRIPT = _NO_RICH_PRELUDE + textwrap.dedent(
+ """
+ import asyncio
+
+ from pipelex.pipeline.runner import PipelexMTHDSProtocol
+
+ BUNDLE = '''
+ domain = "rich_free_run"
+ description = "A compose pipe, which needs no inference"
+ main_pipe = "greet"
+
+ [pipe.greet]
+ type = "PipeCompose"
+ description = "Greet the name"
+ inputs = { name = "Text" }
+ output = "Text"
+ template = "Hello {{ name }}!"
+ '''
+
+ Pipelex.make(
+ integration_mode=INTEGRATION_MODE,
+ needs_model_specs=False,
+ config_overrides={"runtime": {"log": {"sink": "json", "pretty_print_mode": sys.argv[1]}}},
+ )
+ result = asyncio.run(PipelexMTHDSProtocol().execute(mthds_contents=[BUNDLE], inputs={"name": {"concept": "Text", "content": "world"}}))
+ assert result.pipe_output.main_stuff_as_str == "Hello world!", result.pipe_output.main_stuff_as_str
+ Pipelex.teardown_if_needed()
+ loaded = sorted(name for name in sys.modules if name == "rich" or name.startswith("rich."))
+ assert not loaded, loaded
+ print("rich-free run OK")
+ """
+)
+
+# The pretty-print mode "rich" needs Rich: a boot without it stops at boot, naming the extra and the
+# Rich-free modes, rather than at the first pipe that prints its output. `needs_model_specs=False` for
+# the same reason as above: the refusal under test must be the one Rich's absence raises, on a machine
+# where inference was never set up as much as on one where it was.
+_RICH_MODE_BOOT_SCRIPT = _NO_RICH_PRELUDE + textwrap.dedent(
+ """
+ from pipelex.system.exceptions import MissingDependencyError
+
+ try:
+ Pipelex.make(
+ integration_mode=INTEGRATION_MODE,
+ needs_model_specs=False,
+ config_overrides={"runtime": {"log": {"sink": "json", "pretty_print_mode": "rich"}}},
+ )
+ except MissingDependencyError as exc:
+ print(f"refused: {exc.dependency_name} | {exc.extra_name} | {exc}")
+ else:
+ raise SystemExit("expected MissingDependencyError from a rich pretty-print mode without Rich")
+ """
+)
+
+
+# `pipelex.test_extras.shared_pytest_plugins` loads in every session of every project that registers it, so a
+# downstream suite installed without the extra must still collect and run. The blocker goes in at the top of
+# the conftest, before the plugin is imported; `CI` is what puts the placeholder fixture on the path, which is
+# where the console calls that used to break such a session were.
+_DOWNSTREAM_CONFTEST = textwrap.dedent(
+ """
+ import importlib.abc
+ import sys
+
+ class _RichBlocker(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path, target=None):
+ if fullname == "rich" or fullname.startswith("rich."):
+ raise ImportError(f"no-rich guard blocked '{fullname}'")
+ return None
+
+ sys.meta_path.insert(0, _RichBlocker())
+
+ pytest_plugins = ["pipelex.test_extras.shared_pytest_plugins"]
+ """
+)
+
+_DOWNSTREAM_TEST = textwrap.dedent(
+ """
+ def test_a_downstream_project_runs_its_own_test():
+ assert True
+ """
+)
+
+
+def _run_python(*, script: str, args: list[str]) -> subprocess.CompletedProcess[str]:
+ return subprocess.run( # ruff: ignore[subprocess-without-shell-equals-true]
+ [sys.executable, "-c", script, *args],
+ capture_output=True,
+ text=True,
+ check=False,
+ cwd=_REPO_ROOT,
+ timeout=150,
+ )
+
+
[email protected](scope="module", autouse=True)
+def reset_pipelex_config_fixture() -> None:
+ """Override the global module fixture: every boot here happens in a subprocess, so this process boots nothing."""
+
+
+class TestRichFreeRun:
+ @pytest.mark.parametrize("pretty_print_mode", [PrettyPrintMode.SILENT, PrettyPrintMode.POOR])
+ def test_a_pipe_runs_with_rich_refused(self, pretty_print_mode: PrettyPrintMode) -> None:
+ """The kernel boots and a direct-mode pipe runs with the json sink, a Rich-free pretty-print mode and no Rich importable."""
+ result = _run_python(script=_RUN_SCRIPT, args=[pretty_print_mode.value])
+
+ assert result.returncode == 0, f"rich-free run failed:\nstdout={result.stdout}\nstderr={result.stderr}"
+ assert "rich-free run OK" in result.stdout
+ stderr_lines = [line for line in result.stderr.splitlines() if line]
+ match pretty_print_mode:
+ case PrettyPrintMode.SILENT:
+ # What a server writes: every stderr line is one JSON log record, and no ANSI anywhere.
+ records = [json.loads(line) for line in stderr_lines]
+ assert records, "expected the run's log records on stderr"
+ assert all(isinstance(record, dict) and "severity" in record and "message" in record for record in records)
+ assert "\x1b" not in result.stderr
+ case PrettyPrintMode.POOR:
+ # The poor printer frames the operator's output in plain text, its title's markup rendered away.
+ assert any("Output of pipe greet → Text" in line for line in stderr_lines), result.stderr
+ assert any("Hello world!" in line for line in stderr_lines), result.stderr
+ case PrettyPrintMode.RICH:
+ pytest.fail("the rich mode is the one this test refuses")
+
+ def test_a_downstream_suite_registering_the_shared_plugin_runs_with_rich_refused(self, tmp_path: Path) -> None:
+ """A project that registers the shared pytest plugin and installs no extra still collects and runs its tests."""
+ (tmp_path / "conftest.py").write_text(_DOWNSTREAM_CONFTEST, encoding="utf-8")
+ (tmp_path / "test_downstream.py").write_text(_DOWNSTREAM_TEST, encoding="utf-8")
+
+ result = subprocess.run(
+ [sys.executable, "-m", "pytest", "-p", "no:randomly", "-q", "test_downstream.py"],
+ capture_output=True,
+ text=True,
+ check=False,
+ cwd=tmp_path,
+ timeout=150,
+ # `CI` is what the plugin reads to set the placeholder env vars, and disabling the entry-point
+ # plugins keeps an unrelated third-party plugin's own Rich import out of the measurement.
+ env={**os.environ, "CI": "1", "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"},
+ )
+
+ assert result.returncode == 0, f"downstream suite failed:\nstdout={result.stdout}\nstderr={result.stderr}"
+ assert "1 passed" in result.stdout, result.stdout
+
+ def test_the_rich_pretty_print_mode_is_refused_at_boot_naming_the_extra(self) -> None:
+ """Without Rich, `pretty_print_mode = "rich"` stops the boot with the extra to install and the Rich-free modes."""
+ result = _run_python(script=_RICH_MODE_BOOT_SCRIPT, args=[])
+
+ assert result.returncode == 0, f"boot check failed:\nstdout={result.stdout}\nstderr={result.stderr}"
+ (refusal,) = [line for line in result.stdout.splitlines() if line.startswith("refused: ")]
+ assert refusal.startswith(f"refused: rich | {RICH_EXTRA_NAME} | ")
+ assert f"pipelex[{RICH_EXTRA_NAME}]" in refusal
+ assert '"poor"' in refusal
+ assert '"silent"' in refusal
diff --git a/tests/unit/pipelex/cli/dev/test_check_rich_imports_cmd.py b/tests/unit/pipelex/cli/dev/test_check_rich_imports_cmd.py
new file mode 100644
index 000000000..29c705094
--- /dev/null
+++ b/tests/unit/pipelex/cli/dev/test_check_rich_imports_cmd.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+import io
+from typing import TYPE_CHECKING
+
+import pytest
+from rich.console import Console
+
+from pipelex.cli.dev_cli.commands import check_rich_imports_cmd as cmd_mod
+from pipelex.cli.dev_cli.commands.check_rich_imports_cmd import check_rich_imports_cmd
+from pipelex.cli.dev_cli.commands.rich_import_guard import REMEDY, RichImportViolation
+
+if TYPE_CHECKING:
+ from pytest_mock import MockerFixture
+
+#: Wide enough that no assertion below depends on where Rich decides to wrap.
+CONSOLE_WIDTH = 400
+
+VIOLATION = RichImportViolation(relative_path="pipelex/core/stuffs/sample_content.py", lineno=4, detail="imports `rich.json` at module level")
+
+
+class TestCheckRichImportsCmd:
+ @pytest.fixture
+ def console_buffer(self, mocker: MockerFixture) -> io.StringIO:
+ """Route every `get_console()` call in the command module to one StringIO-backed console."""
+ buffer = io.StringIO()
+ mocker.patch.object(cmd_mod, "get_console", return_value=Console(file=buffer, force_terminal=False, width=CONSOLE_WIDTH))
+ return buffer
+
+ @pytest.mark.parametrize(
+ ("quiet", "expected_verdict"),
+ [
+ (True, "Rich import check: PASSED"),
+ (False, "Rich Import Check: PASSED"),
+ ],
+ )
+ def test_a_clean_tree_passes(self, mocker: MockerFixture, console_buffer: io.StringIO, quiet: bool, expected_verdict: str) -> None:
+ """A clean tree returns normally, which is exit 0, and a quiet run says so in one line."""
+ mocker.patch.object(cmd_mod, "collect_violations", return_value=[])
+ check_rich_imports_cmd(quiet=quiet)
+ output = console_buffer.getvalue()
+ assert expected_verdict in output
+ if quiet:
+ assert output.strip().splitlines() == [f"✓ {expected_verdict}"]
+
+ @pytest.mark.parametrize("quiet", [True, False])
+ def test_a_violation_exits_1_with_its_site_and_the_remedy(self, mocker: MockerFixture, console_buffer: io.StringIO, quiet: bool) -> None:
+ """The gate: any violation is exit 1, and a quiet CI run still carries the site and the remedy."""
+ mocker.patch.object(cmd_mod, "collect_violations", return_value=[VIOLATION])
+
+ with pytest.raises(SystemExit) as exit_info:
+ check_rich_imports_cmd(quiet=quiet)
+
+ assert exit_info.value.code == 1
+ output = console_buffer.getvalue()
+ assert "pipelex/core/stuffs/sample_content.py:4" in output
+ assert "imports `rich.json` at module level" in output
+ assert REMEDY in output
diff --git a/tests/unit/pipelex/cli/dev/test_rich_import_guard.py b/tests/unit/pipelex/cli/dev/test_rich_import_guard.py
new file mode 100644
index 000000000..2fc015e3f
--- /dev/null
+++ b/tests/unit/pipelex/cli/dev/test_rich_import_guard.py
@@ -0,0 +1,181 @@
+from __future__ import annotations
+
+import textwrap
+from pathlib import Path
+
+import pytest
+
+from pipelex.cli.dev_cli.commands.rich_import_guard import (
+ SOURCE_ROOT,
+ RichImportGuardError,
+ collect_violations,
+ find_violations_in_source,
+)
+
+#: Anchored on `tests/` by name rather than by a parent count, for the reason `test_hub_layering_guard.py` gives.
+_REPO_ROOT = next(parent for parent in Path(__file__).resolve().parents if parent.name == "tests").parent
+
+SERVER_PATH = "pipelex/core/stuffs/sample_content.py"
+CLI_PATH = "pipelex/cli/commands/sample_cmd.py"
+
+
+def _lines(source: str, *, relative_path: str = SERVER_PATH) -> list[int]:
+ """The lines the guard flags in an inline snippet."""
+ return [violation.lineno for violation in find_violations_in_source(source=textwrap.dedent(source), relative_path=relative_path)]
+
+
+class TestRichImportGuard:
+ @pytest.mark.parametrize(
+ ("topic", "source", "expected_lines"),
+ [
+ ("from-import at the top", "from rich.console import Console\n", [1]),
+ ("plain import", "import rich\n", [1]),
+ ("submodule import with alias", "import rich.table as table\n", [1]),
+ ("package-level from-import", "from rich import box\n", [1]),
+ ("module-level try block", "try:\n from rich.text import Text\nexcept ImportError:\n Text = None\n", [2]),
+ ("class body", "class Renderer:\n from rich.panel import Panel\n", [2]),
+ ("else branch of TYPE_CHECKING", "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n pass\nelse:\n import rich\n", [5]),
+ ("negated TYPE_CHECKING", "from typing import TYPE_CHECKING\nif not TYPE_CHECKING:\n import rich\n", [3]),
+ ("guarded function body", "def render():\n require_rich_for_rendering()\n from rich.text import Text\n return Text()\n", []),
+ ("guarded coroutine body", "async def render():\n require_rich_for_rendering()\n import rich\n", []),
+ (
+ "guarded method body",
+ (
+ "class Content:\n"
+ " def rendered_pretty(self):\n"
+ " require_rich_for_rendering()\n"
+ " from rich.json import JSON\n"
+ " return JSON('{}')\n"
+ ),
+ [],
+ ),
+ ("TYPE_CHECKING block", "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from rich.console import Console\n", []),
+ ("typing.TYPE_CHECKING block", "import typing\nif typing.TYPE_CHECKING:\n from rich.console import Console\n", []),
+ ("a package merely named like Rich", "import richer\nfrom rich_extra import thing\n", []),
+ ("a relative import", "from .rich import thing\n", []),
+ ("pipelex's own rich_extra module", "from pipelex.tools.misc.rich_extra import require_rich\n", []),
+ ],
+ )
+ def test_flags_exactly_the_imports_that_run_at_module_import(self, topic: str, source: str, expected_lines: list[int]) -> None:
+ """What counts is whether importing the module executes the import, wherever the statement sits."""
+ assert _lines(source) == expected_lines, topic
+
+ def test_the_cli_package_may_import_rich_at_module_level(self) -> None:
+ """The CLI installs the `cli` extra, so a CLI module's module-level Rich import is not a violation."""
+ assert _lines("from rich.console import Console\n", relative_path=CLI_PATH) == []
+ # The allowlist is a package prefix, not a name fragment.
+ assert _lines("from rich.console import Console\n", relative_path="pipelex/client/sample.py") == [1]
+
+ def test_the_real_tree_is_clean(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The source tree as committed: no module outside `pipelex/cli/` imports Rich at module level."""
+ monkeypatch.chdir(_REPO_ROOT)
+ assert collect_violations(root=SOURCE_ROOT) == []
+
+ def test_a_module_reaching_rich_through_a_cli_module_is_refused_with_its_chain(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The transitive rule: importing a CLI module that imports Rich loads Rich, however many hops away."""
+ tree = {
+ "pipelex/__init__.py": "",
+ "pipelex/cli/__init__.py": "",
+ "pipelex/cli/panels.py": "from rich.panel import Panel\n",
+ "pipelex/cli/uses_panels.py": "from pipelex.cli.panels import Panel\n",
+ "pipelex/cli/plain.py": "PLAIN = 1\n",
+ "pipelex/core/__init__.py": "",
+ "pipelex/core/direct.py": '"""Reaches a CLI module that imports Rich."""\n\nfrom pipelex.cli.panels import Panel\n',
+ "pipelex/core/indirect.py": "import pipelex.core.direct\n",
+ "pipelex/core/via_cli.py": "from pipelex.cli import uses_panels\n",
+ "pipelex/core/plain_cli.py": "from pipelex.cli.plain import PLAIN\n",
+ "pipelex/core/deferred.py": "def render():\n from pipelex.cli.panels import Panel\n return Panel\n",
+ "pipelex/core/type_only.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from pipelex.cli.panels import Panel\n",
+ "pipelex/core/own_rich.py": "import rich\n",
+ "pipelex/core/imports_own_rich.py": "from pipelex.core.own_rich import rich\n",
+ }
+ for relative_path, source in tree.items():
+ path = tmp_path / relative_path
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(source, encoding="utf-8")
+ monkeypatch.chdir(tmp_path)
+
+ found = {(violation.relative_path, violation.lineno, violation.detail) for violation in collect_violations(root=SOURCE_ROOT)}
+
+ assert found == {
+ ("pipelex/core/direct.py", 3, "reaches Rich via pipelex.cli.panels, which imports it at module level"),
+ ("pipelex/core/indirect.py", 1, "reaches Rich via pipelex.core.direct → pipelex.cli.panels, which imports it at module level"),
+ ("pipelex/core/via_cli.py", 1, "reaches Rich via pipelex.cli.uses_panels → pipelex.cli.panels, which imports it at module level"),
+ # A module outside the CLI that imports Rich itself is the direct rule's finding, and only that.
+ ("pipelex/core/own_rich.py", 1, "imports `rich` at module level"),
+ }
+
+ def test_a_root_the_allowlist_cannot_match_fails_loudly(self, tmp_path: Path) -> None:
+ """An absolute or empty root would make the allowlist match nothing and the verdict meaningless."""
+ (tmp_path / "module.py").write_text("x = 1\n", encoding="utf-8")
+ with pytest.raises(RichImportGuardError, match="allowlist matched nothing"):
+ collect_violations(root=tmp_path)
+
+
+class TestDeferredRichImportGuard:
+ """The ordering rule: a deferred Rich import is reached only after something established Rich is installed.
+
+ Deferring the import is what keeps Rich off a server's import path; calling the guard first is what turns a
+ bare `ModuleNotFoundError` into the `MissingDependencyError` that names the extra. The direct rule checks
+ the first and cannot see the second, so this is a rule of its own.
+ """
+
+ @pytest.mark.parametrize(
+ ("topic", "source", "expected_lines"),
+ [
+ ("no guard at all", "def render():\n from rich.text import Text\n return Text()\n", [2]),
+ ("guard on the line before", "def render():\n require_rich(message='x')\n from rich.text import Text\n", []),
+ ("the rendering guard", "def render():\n require_rich_for_rendering()\n from rich.text import Text\n", []),
+ ("a console hands out a guarded object", "def render():\n console = get_console()\n from rich.table import Table\n", []),
+ ("guard after the import does not reach it", "def render():\n from rich.text import Text\n require_rich(message='x')\n", [2]),
+ (
+ "a guard inside a branch does not cover the function",
+ "def render(flat):\n from rich.markup import escape\n if flat:\n console = get_console()\n",
+ [2],
+ ),
+ (
+ "a top-level guard covers an import inside a branch",
+ "def render(flat):\n require_rich(message='x')\n if flat:\n from rich.text import Text\n",
+ [],
+ ),
+ (
+ "a guard beside the import in the same branch covers it",
+ "def render(missing):\n if missing:\n console = get_console()\n from rich.panel import Panel\n",
+ [],
+ ),
+ (
+ "a guard in one branch does not cover the other",
+ "def render(missing):\n if missing:\n require_rich(message='x')\n else:\n from rich.panel import Panel\n",
+ [5],
+ ),
+ (
+ "a fallback asks sys.modules rather than raising",
+ "def render(content):\n if 'rich' not in sys.modules:\n return None\n from rich.text import Text\n",
+ [],
+ ),
+ (
+ "a nested function is its own scope",
+ "def outer():\n require_rich(message='x')\n\n def inner():\n from rich.text import Text\n",
+ [5],
+ ),
+ ("a coroutine is checked the same way", "async def render():\n import rich.box\n", [2]),
+ (
+ "a method is checked the same way",
+ "class Content:\n def rendered_pretty(self):\n from rich.json import JSON\n",
+ [3],
+ ),
+ ("a type-only import inside a function needs no guard", "def render():\n if TYPE_CHECKING:\n from rich.text import Text\n", []),
+ ],
+ )
+ def test_a_deferred_import_is_flagged_unless_a_guard_precedes_it(self, topic: str, source: str, expected_lines: list[int]) -> None:
+ assert _lines(source) == expected_lines, topic
+
+ def test_the_cli_package_needs_no_guard_before_a_deferred_import(self) -> None:
+ """A CLI module may import Rich at the top of the file, so deferring one inside a function asks nothing of it."""
+ assert _lines("def render():\n from rich.text import Text\n", relative_path=CLI_PATH) == []
+
+ def test_the_remedy_names_the_guard_a_reader_has_to_call(self) -> None:
+ """The report is what a developer acts on, so it names the call rather than describing the problem."""
+ violations = find_violations_in_source(source="def render():\n from rich.text import Text\n", relative_path=SERVER_PATH)
+ assert len(violations) == 1
+ assert "require_rich" in violations[0].detail
diff --git a/tests/unit/pipelex/cogt/usage/test_cost_registry.py b/tests/unit/pipelex/cogt/usage/test_cost_registry.py
index 8f8ed5b6c..380e75b52 100644
--- a/tests/unit/pipelex/cogt/usage/test_cost_registry.py
+++ b/tests/unit/pipelex/cogt/usage/test_cost_registry.py
@@ -9,6 +9,7 @@ from pipelex.cogt.llm.llm_report import LLMTokenCostReportField, LLMTokensUsage
from pipelex.cogt.usage.cost_category import CostCategory
from pipelex.cogt.usage.cost_registry import CostRegistry
from pipelex.cogt.usage.token_category import TokenCategory
+from pipelex.system.exceptions import MissingDependencyError
from pipelex.system.job_metadata import JobMetadata
@@ -365,7 +366,8 @@ class TestCostRegistry:
"""Test that unit scaling is applied correctly to cost display."""
# Mock console to avoid output during tests
mocker.patch("pipelex.cogt.usage.cost_registry.get_console", return_value=mocker.MagicMock())
- mock_table_class = mocker.patch("pipelex.cogt.usage.cost_registry.Table")
+ # Rich is imported where the table is built, so the class is patched where it is defined.
+ mock_table_class = mocker.patch("rich.table.Table")
mock_table = mock_table_class.return_value
# Create test data
@@ -499,6 +501,41 @@ class TestCostRegistry:
assert len(rows) == 1
assert rows[0][LLMTokenCostReportField.LLM_NAME] == "test-model"
+ def test_the_csv_is_written_even_when_the_console_table_cannot_render(self, job_metadata: JobMetadata, tmp_path: Path, mocker: MockerFixture):
+ """Rich is the `cli` extra, and the CSV report does not need it: a console that cannot render loses only itself.
+
+ The shipped default prints to the console, and the caller downgrades a `PipelexError` to a warning, so a
+ console table that raises used to take the CSV report with it silently.
+ """
+ mocker.patch(
+ "pipelex.cogt.usage.cost_registry.get_console",
+ side_effect=MissingDependencyError(dependency_name="rich", extra_name="cli", message="no console here"),
+ )
+
+ llm_tokens_usage = LLMTokensUsage(
+ job_metadata=job_metadata,
+ inference_model_name="test-model",
+ inference_model_id="test-model-id",
+ nb_tokens_by_category={TokenCategory.INPUT: 100, TokenCategory.OUTPUT: 50},
+ unit_costs={CostCategory.INPUT: 1000, CostCategory.OUTPUT: 2000},
+ )
+
+ csv_file = tmp_path / "costs_without_rich.csv"
+ with pytest.raises(MissingDependencyError):
+ CostRegistry.generate_report(
+ pipeline_run_id="test-pipeline",
+ tokens_usages=[llm_tokens_usage],
+ unit_scale=1.0,
+ cost_report_file_path=csv_file,
+ print_to_console=True,
+ )
+
+ assert csv_file.exists(), "the CSV report is the output that does not need Rich"
+ with open(csv_file, encoding="utf-8") as file:
+ rows = list(csv.DictReader(file))
+ assert len(rows) == 1
+ assert rows[0][LLMTokenCostReportField.LLM_NAME] == "test-model"
+
def test_aggregate_costs_totals_and_reportability(self, job_metadata: JobMetadata):
"""One aggregation pass yields the run total and the reportable-work flag.
diff --git a/tests/unit/pipelex/tools/misc/test_plain_markup_text.py b/tests/unit/pipelex/tools/misc/test_plain_markup_text.py
new file mode 100644
index 000000000..d8726d828
--- /dev/null
+++ b/tests/unit/pipelex/tools/misc/test_plain_markup_text.py
@@ -0,0 +1,78 @@
+import pytest
+from rich.errors import MarkupError
+from rich.text import Text
+
+from pipelex.tools.misc.pretty import plain_markup_text
+
+
+class TestPlainMarkupText:
+ @pytest.mark.parametrize(
+ "markup",
+ [
+ "",
+ "no markup at all",
+ "Output of pipe [red]greet[/red] → [bold cyan]Text[/bold cyan]",
+ "[bold]nested [italic]styles[/italic] close[/]",
+ "implicit [green]close[/]",
+ "[bold red]order[/red bold] does not matter",
+ "[bold]case[/BOLD] does not matter in a closing tag",
+ # A style alias: Rich normalizes both sides of the pair, so `b` and `bold` are one style to it.
+ "[b]an alias[/bold] pair",
+ "[bold]the other way[/b] round",
+ "[i]italic[/italic] by its alias",
+ "a [link=https://pipelex.com]link[/link] with parameters",
+ "an unclosed [yellow]tag is fine",
+ r"an escaped \[bold] tag",
+ r"a literal backslash \\[bold]then a tag[/bold]",
+ "brackets that are no tag: [1, 2, 3] and [A] and [ ]",
+ r"an open brace escape \[ alone",
+ "a list[str] type and dict[str, Any]",
+ ],
+ )
+ def test_renders_the_plain_text_rich_renders(self, markup: str) -> None:
+ """What the ``poor`` mode prints as a title is what Rich's panel title would read.
+
+ Compared against ``emoji=False`` deliberately: substituting an emoji code needs Rich's own code table,
+ so the Rich-free reading leaves ``:rocket:`` as written. That difference is a documented behaviour
+ change of the ``poor`` mode rather than a divergence this test is meant to catch.
+ """
+ assert plain_markup_text(markup=markup) == Text.from_markup(markup, emoji=False).plain
+
+ @pytest.mark.parametrize(
+ "markup",
+ [
+ "a closing tag [/bold] with nothing open",
+ "an implicit close [/] with nothing open",
+ "text [green]then[/green] a stray [/red] close",
+ ],
+ )
+ def test_refuses_a_close_with_nothing_open(self, markup: str) -> None:
+ """The one thing that cannot be read as tags at all: a closing tag where nothing is open.
+
+ Rich raises ``MarkupError`` here too, and the caller keeps the title as it was written.
+ """
+ with pytest.raises(MarkupError):
+ Text.from_markup(markup)
+ assert plain_markup_text(markup=markup) is None
+
+ @pytest.mark.parametrize(
+ ("markup", "expected"),
+ [
+ # Rich matches a closing tag against the style it names, which needs its style grammar. This
+ # reading tracks nesting depth instead, so it closes the innermost open tag whatever it is named.
+ ("[bold]a mismatched[/italic] close", "a mismatched close"),
+ ("[red on blue]a reordered pair[/blue on red]", "a reordered pair"),
+ # Rich parses a `@` tag's parameters and refuses malformed ones. This reading drops them unread.
+ ("[@click=foo(]a malformed handler[/@click]", "a malformed handler"),
+ ],
+ )
+ def test_is_deliberately_more_permissive_than_rich(self, markup: str, expected: str) -> None:
+ """Where Rich refuses markup this reading accepts, it strips the tags rather than keeping them.
+
+ The ``poor`` mode prints whatever happens, and a title that reads as text is better than one that
+ prints its own tags. Accepting more than Rich costs a reader nothing; refusing more would cost them
+ the title.
+ """
+ with pytest.raises(MarkupError):
+ Text.from_markup(markup)
+ assert plain_markup_text(markup=markup) == expected
diff --git a/tests/unit/pipelex/tools/misc/test_pretty_without_rich.py b/tests/unit/pipelex/tools/misc/test_pretty_without_rich.py
index 46e5cf1aa..712f83660 100644
--- a/tests/unit/pipelex/tools/misc/test_pretty_without_rich.py
+++ b/tests/unit/pipelex/tools/misc/test_pretty_without_rich.py
@@ -19,6 +19,40 @@ def widths() -> tuple[int, int]:
return (100, 150)
+class TestPrettyPrintUrlWithoutRich:
+ def test_the_inner_title_reaches_the_poor_url_frame(self, widths: tuple[int, int], capsys: CaptureFixture[str]):
+ """A url loses its inner title in no mode: the framed printer renders it, so the url printer does too."""
+ width, console_width = widths
+ PrettyPrinter.pretty_print_url_without_rich(
+ "https://pipelex.com",
+ title="the title",
+ inner_title="the inner title",
+ width=width,
+ console_width=console_width,
+ )
+
+ output = remove_ansi_escape_codes(capsys.readouterr().err)
+
+ assert "the title" in output
+ assert "the inner title" in output, f"the inner title was dropped:\n{output}"
+ assert "https://pipelex.com" in output
+
+ def test_a_bare_url_handed_to_the_framed_printer_keeps_its_inner_title(self, widths: tuple[int, int], capsys: CaptureFixture[str]):
+ """The framed printer hands a bare url to the url printer, and that hand-off carries the inner title too."""
+ width, console_width = widths
+ PrettyPrinter.pretty_print_without_rich(
+ content="https://pipelex.com",
+ title="the title",
+ inner_title="the inner title",
+ width=width,
+ console_width=console_width,
+ )
+
+ output = remove_ansi_escape_codes(capsys.readouterr().err)
+
+ assert "the inner title" in output, f"the inner title was dropped on the bare-url path:\n{output}"
+
+
class TestPrettyPrintWithoutRich:
def test_pretty_without_rich_empty_content(self, widths: tuple[int, int], capsys: CaptureFixture[str]):
width, console_width = widths
diff --git a/tests/unit/pipelex/tools/test_log_console_sink_without_rich.py b/tests/unit/pipelex/tools/test_log_console_sink_without_rich.py
index 49c3562e0..bd7f3f3e4 100644
--- a/tests/unit/pipelex/tools/test_log_console_sink_without_rich.py
+++ b/tests/unit/pipelex/tools/test_log_console_sink_without_rich.py
@@ -1,10 +1,10 @@
"""Selecting the ``console`` sink without Rich installed fails at boot naming the extra and the ``json`` alternative.
-Rich is a hard dependency today and the runtime's own modules import it, so the subprocess evicts every
-``rich`` module and installs a meta-path finder that refuses to import it again: the next import, the one
-the sink's ``make_handler`` performs, is exactly what an uninstalled Rich would be. A subprocess, because
-evicting a package from ``sys.modules`` in the test process would leave duplicate class objects behind
-for every later test. Modelled on ``test_import_light_boot.py``.
+Rich is the ``cli`` extra and the test suite installs every extra, so the subprocess installs a meta-path
+finder that refuses to import it before anything else is imported: the sink's module imports cleanly, and
+the import its ``make_handler`` performs is exactly what an uninstalled Rich would be. A subprocess, because
+the test process has Rich loaded already and evicting it would leave duplicate class objects behind for
+every later test. Modelled on ``test_import_light_boot.py``.
"""
import subprocess # ruff: ignore[suspicious-subprocess-import]
@@ -16,14 +16,6 @@ _GUARD_SCRIPT = textwrap.dedent(
import importlib.abc
import sys
- from pipelex.system.console_target import ConsoleTarget
- from pipelex.system.exceptions import MissingDependencyError
- from pipelex.tools.log.console_log_sink import RICH_EXTRA_NAME, ConsoleLogSink
- from pipelex.tools.log.log_config import HighlighterName, RichLogConfig
-
- for name in [module for module in sys.modules if module == "rich" or module.startswith("rich.")]:
- del sys.modules[name]
-
class _Blocker(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
if fullname == "rich" or fullname.startswith("rich."):
@@ -32,6 +24,12 @@ _GUARD_SCRIPT = textwrap.dedent(
sys.meta_path.insert(0, _Blocker())
+ from pipelex.system.console_target import ConsoleTarget
+ from pipelex.system.exceptions import MissingDependencyError
+ from pipelex.tools.log.console_log_sink import ConsoleLogSink
+ from pipelex.tools.log.log_config import HighlighterName, RichLogConfig
+ from pipelex.tools.misc.rich_extra import RICH_EXTRA_NAME
+
sink = ConsoleLogSink(
rich_log_config=RichLogConfig(
is_show_time=False,
diff --git a/uv.lock b/uv.lock
index 7555810d7..3e2f4ea20 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3476,7 +3476,6 @@ dependencies = [
{ name = "pyyaml" },
{ name = "reportlab" },
{ name = "requests" },
- { name = "rich" },
{ name = "semantic-version" },
{ name = "shortuuid" },
{ name = "tomli" },
@@ -3494,6 +3493,9 @@ bedrock = [
{ name = "aioboto3" },
{ name = "boto3" },
]
+cli = [
+ { name = "rich" },
+]
dev = [
{ name = "boto3-stubs" },
{ name = "cryptography" },
@@ -3649,7 +3651,7 @@ requires-dist = [
{ name = "pyyaml", specifier = ">=6.0.2" },
{ name = "reportlab", specifier = ">=4.0,<5" },
{ name = "requests", specifier = ">=2.33.0" },
- { name = "rich", specifier = ">=13.8.1" },
+ { name = "rich", marker = "extra == 'cli'", specifier = ">=13.8.1" },
{ name = "ruff", marker = "extra == 'dev'", specifier = "==0.16.4" },
{ name = "semantic-version", specifier = ">=2.10.0" },
{ name = "shortuuid", specifier = ">=1.0.13" },
@@ -3665,7 +3667,7 @@ requires-dist = [
{ name = "typing-extensions", specifier = ">=4.13.2" },
{ name = "urllib3", specifier = ">=2.7.0" },
]
-provides-extras = ["anthropic", "bedrock", "docling", "fal", "gcp-logging", "gcp-storage", "google", "google-genai", "huggingface", "linkup", "mistralai", "dynamodb", "s3", "docs", "dev"]
+provides-extras = ["anthropic", "bedrock", "cli", "docling", "fal", "gcp-logging", "gcp-storage", "google", "google-genai", "huggingface", "linkup", "mistralai", "dynamodb", "s3", "docs", "dev"]
[[package]]
name = "pipelex-tools"
diff --git a/wip/structured-logs/review-deferrals.md b/wip/structured-logs/review-deferrals.md
index da121890e..faf31dd3d 100644
--- a/wip/structured-logs/review-deferrals.md
+++ b/wip/structured-logs/review-deferrals.md
@@ -171,6 +171,50 @@ The reason it belongs there rather than here is that the cure is a contract choi
A later round that re-raises this should be closed against this entry rather than argued again.
+## L-260916-fe7969, round 1 (rich extra, lazy import, guard)
+
+Round 1 was launched by an earlier session and never triaged; this pass is its triage. Four reviewers ran. cubic and code-review read the member's own six commits; the two Codex passes ran against `dev`, so most of what they raised belongs to the two branches below and is entered under those members above. Every finding was verified against the code before triage, and the guard's own new rule then found more unguarded sites than any reviewer had read.
+
+What the pass fixed: the ordering half of the named-error contract, which the guard documented and structurally could not check, at every deferred site in the tree; the cost report's CSV, which the console table's missing dependency used to take with it silently; the shared pytest plugin's console diagnostics, which broke every test of a downstream suite installed without the extra; the claims in the changelog, the README, the `pyproject.toml` comment, the console sink's docstring, the guard's docstring and the contribute page that said a server installs pipelex without Rich; the guard's own "there is no escape hatch", which its docstring contradicted six lines earlier; the style-alias pair that made a poor-mode panel title print its own tags; and the inner title the poor url frame dropped.
+
+- **An emoji code is not substituted in the `poor` mode** (*verified*, code-review). `_plain_title` used to call `Text.from_markup(title)`, whose default substitutes `:rocket:` from Rich's own code table; `plain_markup_text` leaves it as written, so a title carrying an emoji code prints the code. Unfixable Rich-free: the substitution table *is* a Rich asset. Documented as a behaviour change of the mode in `docs/contribute/rich-imports.md` and in the function's docstring, and the test compares against `emoji=False` for that reason rather than by oversight.
+- **The Rich-free markup reading accepts more than Rich** (*verified*, code-review and cubic). Which open tag a closing tag matches is decided by Rich's style grammar, so `[/italic]` cannot close `[bold]` there and `[b]` and `[/bold]` are one style; and a `@` tag's parameters are parsed and refused when malformed. Reproducing either means reproducing `Style.parse`, which is Rich. The reading tracks nesting depth instead and drops a `@` tag's parameters unread, so it strips the tags where Rich raises. Deliberate, and now tested as such: the `poor` mode prints whatever happens, and a title that reads as text beats one that prints its own tags. It still refuses the one case that cannot be read as tags at all, a close with nothing open, which is what the refusal exists for.
+- **The console scripts raise a bare `ImportError` with Rich blocked** (*verified*, code-review). All three are declared unconditionally while Rich is optional, and each entry module imports Rich at module level — legally, being CLI modules — so with Rich absent `pipelex init` would traceback naming neither the extra nor the fix. It cannot happen on any documented install: `typer` and `instructor` are core dependencies that both require Rich, so a stock install always has it. The launcher that would name the extra belongs with the install-side work that makes the scenario reachable, L-260917-c29954, which the sprint fenced; adding it here would guard against a state the packaging does not produce.
+- **`border_style` is dropped by the poor url frame** — rejected. The plain frame is monochrome and `pretty_print_without_rich` has no such parameter either, so this is a property of every poor rendering rather than an omission on the url path. The `inner_title` half of the same finding was real and is fixed.
+
+## L-260916-fe7969, round 2 (bar defects)
+
+All four reviewers ran over the branch against `origin/dev` at `1ec05b2db`, cubic with a focus naming this member's own commits, and the round changed no code. Two findings landed in this member's code and both were verified; both are deferred, each for a reason stronger than preference.
+
+**The branch is nine commits behind its own base, and that is what most of this round found.** `feature/Log-sink-seam` has moved to `b15446950` while this branch still sits on `e6769a0e8`, so the reviewers read code the member below has already repaired. Two of `codex:review`'s three findings are artefacts of exactly that: the unreserved `_pipelex_forwarded` marker and the OTLP `code.*`/`exception.*` keys overwriting carried fields were both cured on the sink branch at `208f2ad63`. They are not defects of the merged result and are recorded here only so the next round does not re-raise them as new. The staleness itself is the actionable part and belongs to the merge rather than to a bar.
+
+**A guard that admits a shape nobody has written** (*verified*, cubic). `_establishes_rich_is_available` in `pipelex/cli/dev_cli/commands/rich_import_guard.py` matches on syntactic mention: any call named in `GUARD_CALL_NAMES` or any `sys.modules` attribute in a statement — or, for an `if`, in its test — marks everything after it as guarded. Both of cubic's examples really do pass, run through the guard's own `find_violations_in_source`: `if not is_rich_installed(): pass` and a bare `print(sys.modules)` each let a following `from rich.console import Console` through. Deferred because the permissiveness is deliberate, documented and compensated, and because nothing exploits it. The function's own docstring says it settles that the question was asked rather than that every path through the answer is sound, and names what pins the property instead: the Rich-refused pipe run in `tests/integration/pipelex/test_rich_free_run.py`, which installs a blocking meta-path finder before the first `pipelex` import and runs a live compose pipe end to end. An audit of every deferred Rich import outside `pipelex/cli/` found all of them guarded by one of four genuine shapes, the two that use cubic's own shapes included — `pipelex/test_extras/shared_pytest_plugins.py:113` and `pipelex/tools/misc/pretty.py:568` both **return** in the branch, so the import below is reached only with Rich present. Making the rule sound needs dataflow — does the branch return, which arm imports — which is a different guard rather than a correction to this one. One refinement in the guard's favour that the finding omits: a guard *call* inside an `if` body does not carry past the `if`.
+
+**The doctor's fallback sink is not Rich-free, and the doctor cannot be reached without Rich anyway** (*verified*, code-review). The chain is exactly as reported and was reproduced: `_install_fallback_log_sink` (`pipelex/cli/commands/doctor_cmd.py:1103`) builds a `ConsoleLogSink`, `install_sink` reads `sink.handler`, `ConsoleLogSink.make_handler` opens with `require_rich`, and all three failure arms of `install_doctor_log_sink` call it, so with Rich absent the arm written to produce a diagnostic row raises `MissingDependencyError` instead. `PipelexConfigError` is a sibling class rather than an ancestor, so it escapes the arms around `setup_doctor_runtime` and reaches the broad handler, which prints `Unexpected error:` and exits 1 with no report. Deferred because the scenario cannot occur: `doctor_cmd.py:13-16` imports `rich.markup`, `rich.panel`, `rich.prompt` and `rich.text` at module level — legally, `pipelex/cli/` being the package the convention allows — so with Rich blocked the command dies at import before any of this runs, and `get_console()` at `:1357` sits outside the `try` in any case. It is also not made live by the fenced install-side item `L-260917-c29954` alone, which makes a Rich-free *install* producible without making the *doctor* Rich-free, something the package convention says it will never be. This is the same class as the console scripts' bare `ImportError` already recorded under round 1 above. If the fallback is ever hardened anyway, the sound move is one pass over `install_doctor_log_sink` doing two things at once: swapping in `JsonLogSink(stream=sys.stderr)`, which needs no optional dependency and is registered by the same core builtin plugin, and adding the `log.sink is None` gate that `L-260916-7e131d` asks for — at the cost of the human doctor's own log lines rendering as JSON in the ordinary Rich-present case.
+
+Belonging to the members below and entered here so they are not lost:
+
+- **The log-sink row is reported healthy when no sink exists at all** (*unverified*, code-review), `pipelex/cli/commands/doctor_cmd.py:1235` on the sink member `L-260916-aa6e58`. When `log.configure_if_unset` returns `False`, `setup_doctor_runtime` records `LogSinkCheck(is_healthy=True, …)` without asking whether a sink was ever installed, and `Log.configure` and `install_sink` are two separate steps — so an embedder whose boot raised between them has a holding handler and no sink, the doctor emits into it and prints nothing, and the one row that would have named the problem says everything is fine. `log.sink is None` is the question that arm should ask.
+- **A structured log call pays a second full serialization per record** (*unverified*, code-review), `pipelex/tools/log/log_dispatch.py:176`. `data = json.loads(rendered)` re-parses what the purify helpers just produced, for every structured call at an enabled level, on the calling thread, whether or not the installed sink reads `data` — and the default `console` sink never does. Already recorded as a round-3 deferral on `L-260916-a1dbd5`; re-raised here with the observation that the seam has now landed with the parse still unconditional, so it is a decision to take rather than inherit. It is an improvement rather than a defect, which `defects` excludes.
+- **The doctor fallback raises `RuntimeError("A log sink is already installed")` after a partial install** (codex:review), already filed as `L-260916-7e131d`.
+
+Settled rather than deferred:
+
+- **The migration re-enables logging a deployment disabled** (codex:adversarial, confidence 1.0), `pipelex/migration/ledgers/pipelex-config.toml`. This is the sink member's D1, settled by the owner on 2026-09-17 and recorded above under its own heading. The reviewer reproduced the mechanism, which was never in dispute, and offered no new fact — and the settlement is explicit that reopening needs a configuration that actually sets one of the retired keys together with a reason it may not be edited by hand, not another reading of the same code.
+
+## L-260916-fe7969, round 3, after the rebase and the dev absorption (bar necessity)
+
+The branch had been rebased onto the sink seam after its two recorded passes, so the landing gate found no pass on the head, and the orchestrator spent this verification round on the integrated branch: pull request #1210 at `610001f5a`, measured against `origin/dev` with #1205, #1206, #1207 and #1209 already absorbed as squash commits. Every reviewer the profile names produced a review; `codex:review` found nothing, and the round changed no code. The one finding that could have been a critical was verified and is not one, so everything below is deferred at this bar.
+
+- **The pretty-print type aliases are no longer runtime attributes** (*verified*, codex:adversarial). `PrettyPrintable`, `TextType` and `StyleType` in `pipelex/tools/misc/pretty.py` now exist only under `TYPE_CHECKING`, so `from pipelex.tools.misc.pretty import PrettyPrintable` raises `ImportError`, and `typing.get_type_hints` raises `NameError` on `pretty_print`, on `PrettyPrinter.make_pretty` and on every `rendered_pretty`, Rich installed or not. The mechanism is real and nothing breaks: no module of this repo or its tests resolves those annotations at runtime (the function registry rejects a pretty function before it reads hints, the structure printer resolves class hints only, and building every CLI through typer succeeds), and no dependent repo on this machine names any of the three. What is owed is a clause in the changelog's "Rich is the `cli` extra (Breaking)" entry saying these names left the runtime API, which the no-backward-compatibility policy asks for and no dependent needs.
+- **The ordering rule never looks inside a `match` case or an `except*` handler** (*unverified*, code-review and cubic, each with a probe through `find_violations_in_source`). `_nested_bodies` in `pipelex/cli/dev_cli/commands/rich_import_guard.py` has no arm for `ast.Match` or `ast.TryStar`, so an unguarded `from rich…` under `case PrettyPrintMode.RICH:` passes `make check-rich-imports` and would fail at runtime with a bare `ModuleNotFoundError` rather than the named `MissingDependencyError`; and a guard call inside one case marks everything after the whole statement as guarded. No such site exists today. It is the guard's permissiveness recorded under round 2 in a new shape, and the fix is two arms and their tests.
+- **`log-sink-plugins.md` says a server that forgot `json` refuses to boot** (*unverified*, cubic). The "Why `console` is the default" paragraph in `docs/under-the-hood/log-sink-plugins.md` still says a server installs pipelex without Rich, so forgetting `sink = "json"` stops the boot. A stock install gets Rich through `typer` and `instructor`, so it boots the console sink and ships ANSI, which the changelog, the README, the `pyproject.toml` comment and `docs/contribute/rich-imports.md` already say. The sentence was on the branch before the dev absorption; the round-1 rewrite of the other five claims missed this page.
+- **The documented reason `import pipelex` loads Rich names the wrong path** (*unverified*, code-review's reviewer, from its own reading). The changelog entry, the `cli` extra's comment in `pyproject.toml`, the README and the `console_log_sink.py` docstring say Rich arrives because `typer` and `instructor` require it. That is why it is *installed*; what *imports* it is `httpx`'s optional command-line module, reached through `pipelex/cogt/inference/error_classification.py`, which the `rich_import_guard.py` docstring already says correctly.
+- **Rich's version floor lives only in the `cli` extra** (*unverified*, code-review). A plain `pip install pipelex` keeps the console scripts and the Rich-rendering defaults while Rich arrives through `typer` and `instructor`, neither of which enforces `>=13.8.1`, so an environment held to an older Rich installs cleanly and fails later on an attribute or a keyword rather than on the named missing-extra error.
+- **The Rich renderable types are listed three times** (*unverified*, cubic). The `PrettyPrintable` alias and the runtime `isinstance` tuples in `make_pretty` and `_rich_renderable_text` in `pipelex/tools/misc/pretty.py` must be kept in step by hand.
+- **Two test modules hold two test classes each** (*unverified*, cubic), `tests/unit/pipelex/cli/dev/test_rich_import_guard.py` and `tests/unit/pipelex/tools/misc/test_pretty_without_rich.py`, against the one-class-per-module rule.
+- **The pipe-listing telemetry records `nb_pipes` as `None`** (*unverified*, cubic, outside this diff). `do_list_pipes` in `pipelex/cli/commands/show_cmd.py` stores the return of `pretty_list_pipes`, which returns nothing. Pre-existing; this branch edits the method, so it could return the count, but the defect is not the branch's.
+
## L-260916-9f1908, round 1 (bar open)
The branch is stacked on the sink seam, so the pass measured it against `dev` with a focus naming this member's own commits. Every reviewer but cubic raised the same defect independently, and the round-1 verifier reproduced it against the installed `google-cloud-logging`: the library reports a refused batch through its own transport logger, which propagates to the root because only its `setup_logging` sets `propagate = False`, so the report was exported, failed with the batch and was reported again, and with the teardown holding the handler lock while `queue.join()` waited on the worker, that was a deadlock at exit. The pass fixed it with a filter that rejects the library's logging loggers and the export thread before the lock, bounded the handler's flush, which had no deadline to pass, reserved the `json` sink's whole key set so a field named `time` or `severity` keeps one wire name under either sink, routed the traceback through the stdlib formatter the `json` sink uses, and split the test module to one class each. What follows was read as real and left.