Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(terminal): strip C1 controls; print adapter, evidence and dataset text through for_terminal (#1552)

Alpamys Makazhanfa2f228e62dd
diff --git a/changelog.d/0.75.1/1552.fixed.md b/changelog.d/0.75.1/1552.fixed.md
new file mode 100644
index 00000000..5bf71ceb
--- /dev/null
+++ b/changelog.d/0.75.1/1552.fixed.md
@@ -0,0 +1,18 @@
+- Terminal output strips the C1 control range (U+0080-U+009F) as well as C0
+ and DEL, and text read from files is printed through the shared
+ `for_terminal` helper instead of raw, through `escape()` alone, or quoted
+ with `repr()` after escaping: adapter-config base model names in `soup
+ chat`, `soup merge`, `soup serve`, `soup export`, `soup eval benchmark` and
+ the `--trust-remote-code` warning; `soup adapters list` / `info` /
+ `compare` / `diff`; benchmark names in the `soup ship` footer; `soup edit
+ diff`; the SFT "cannot open image/audio" warnings; audio file names in the
+ `soup infer --task asr` skip warnings; the config loader's validation
+ lines; `soup probe interference` loss keys; and the Web UI's log line for a
+ refused config. Markup in such a value no longer changes an exit code: a
+ signature sidecar whose `backend` name contains `[/]` gets `soup attest
+ verify`'s documented exit code 3 instead of 1, and a path or key
+ containing `[/]` gets exit code 2 instead of 1 from `soup env lock` / `env
+ fix`, `soup tunability`, `soup deploy autopilot --measure` and `soup probe
+ interference` (`soup data forge` and `soup adapters arithmetic` now print
+ such a name as text too). A `.can` manifest `author` refuses control
+ characters (#1552).
diff --git a/src/soup_cli/cans/schema.py b/src/soup_cli/cans/schema.py
index 9e510820..04a796ad 100644
--- a/src/soup_cli/cans/schema.py
+++ b/src/soup_cli/cans/schema.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import re
+import unicodedata
from typing import Literal, Optional
from pydantic import BaseModel, Field, field_validator
@@ -199,8 +200,14 @@ class Manifest(BaseModel):
@field_validator("author")
@classmethod
def _clean_author(cls, value: str) -> str:
- if "\x00" in value or "\n" in value or "\r" in value:
- raise ValueError("author must not contain null bytes or newlines")
+ # Category Cc is C0 (NUL, TAB, LF, CR, ESC, ...), DEL and C1. An author
+ # handle has no use for any of them, and the field is printed whenever
+ # a can is inspected or run.
+ if any(unicodedata.category(ch) == "Cc" for ch in value):
+ raise ValueError(
+ "author must not contain control characters "
+ "(null bytes, newlines, tabs, ESC, DEL or C1 controls)"
+ )
return value
@field_validator("created_at")
diff --git a/src/soup_cli/commands/adapters.py b/src/soup_cli/commands/adapters.py
index 2ddd2d02..4c6ad4b1 100644
--- a/src/soup_cli/commands/adapters.py
+++ b/src/soup_cli/commands/adapters.py
@@ -98,18 +98,19 @@ def list_adapters(
rel_path = adapter_path.relative_to(dir_path)
except ValueError:
rel_path = adapter_path
- # Escape every adapter-config-sourced value — a crafted
- # base_model_name_or_path like "[link=evil]click[/]" would
- # otherwise render as live Rich markup in the terminal.
+ # Every value but ``size`` comes from the adapter directory or
+ # its adapter_config.json, so each goes through for_terminal():
+ # Rich markup such as "[link=...]" is shown literally and
+ # control characters (ESC, C1) are dropped.
table.add_row(
- escape(str(rel_path)),
- escape(str(base)),
- escape(lora_r),
- escape(str(peft_type)),
+ for_terminal(rel_path),
+ for_terminal(base),
+ for_terminal(lora_r),
+ for_terminal(peft_type),
size,
)
except (json.JSONDecodeError, OSError):
- table.add_row(escape(str(adapter_path)), "[red]error[/]", "-", "-", "-")
+ table.add_row(for_terminal(adapter_path), "[red]error[/]", "-", "-", "-")
console.print(table)
console.print(f"\n[dim]Found {len(adapters)} adapter(s).[/]")
@@ -147,22 +148,23 @@ def info(
else:
modules_str = str(target_modules)
- # Escape every adapter-config-sourced value before embedding into
- # Rich markup. A crafted base_model_name_or_path like
- # "[link=http://evil]click[/]" would otherwise render as a live
- # clickable link in the terminal.
+ # Every value read from adapter_config.json goes through for_terminal()
+ # before it is embedded in Rich markup: a tag such as "[link=...]" is
+ # shown literally and control characters (ESC, C1) are dropped.
info_text = (
- f"Base model: [bold]{escape(str(base_model))}[/]\n"
- f"PEFT type: [bold]{escape(str(peft_type))}[/]\n"
- f"Task: [bold]{escape(str(task_type))}[/]\n"
- f"LoRA rank: [bold]{escape(str(lora_r))}[/], "
- f"alpha: [bold]{escape(str(lora_alpha))}[/], "
- f"dropout: [bold]{escape(str(lora_dropout))}[/]\n"
- f"Targets: [bold]{escape(modules_str)}[/]\n"
+ f"Base model: [bold]{for_terminal(base_model)}[/]\n"
+ f"PEFT type: [bold]{for_terminal(peft_type)}[/]\n"
+ f"Task: [bold]{for_terminal(task_type)}[/]\n"
+ f"LoRA rank: [bold]{for_terminal(lora_r)}[/], "
+ f"alpha: [bold]{for_terminal(lora_alpha)}[/], "
+ f"dropout: [bold]{for_terminal(lora_dropout)}[/]\n"
+ f"Targets: [bold]{for_terminal(modules_str)}[/]\n"
f"Size on disk: [bold]{size}[/]"
)
- console.print(Panel(info_text, title=f"Adapter Info -- {escape(adapter_path.name)}"))
+ console.print(
+ Panel(info_text, title=f"Adapter Info -- {for_terminal(adapter_path.name)}")
+ )
@app.command()
@@ -212,15 +214,15 @@ def compare(
if isinstance(val2, list):
val2 = ", ".join(str(item) for item in val2)
- # Escape always at the value layer; decoration wraps after.
- # Mirrors v0.57.0 `adapters diff` / `info` policy — equal-value
- # rows must NOT skip escape just because the highlight branch
- # doesn't fire (otherwise a shared crafted value like
- # "[link=evil]click[/]" still injects live markup).
- val1_str = escape(str(val1))
- val2_str = escape(str(val2))
+ # Sanitise always at the value layer; decoration wraps after.
+ # Mirrors the `adapters diff` / `info` policy: equal-value rows
+ # must NOT skip for_terminal() just because the highlight branch
+ # does not fire, or a value both adapters share would reach the
+ # terminal as live markup.
+ val1_str = for_terminal(val1)
+ val2_str = for_terminal(val2)
- # Highlight differences (already-escaped values wrap in yellow).
+ # Highlight differences (already-sanitised values wrap in yellow).
if val1_str != val2_str:
val1_str = f"[yellow]{val1_str}[/]"
val2_str = f"[yellow]{val2_str}[/]"
@@ -308,13 +310,18 @@ def diff(
return
# Default Rich table
- table = Table(title=f"Adapter diff: {escape(report.adapter_a)} vs {escape(report.adapter_b)}")
+ table = Table(
+ title=(
+ f"Adapter diff: {for_terminal(report.adapter_a)} "
+ f"vs {for_terminal(report.adapter_b)}"
+ )
+ )
table.add_column("Layer", style="bold")
table.add_column("ΔW Frobenius", justify="right")
table.add_column("Relative", justify="right")
for layer in sorted(report.per_layer, key=lambda d: d.frobenius, reverse=True)[:top_k]:
table.add_row(
- escape(layer.name),
+ for_terminal(layer.name),
f"{layer.frobenius:.4f}",
f"{layer.relative:.2%}",
)
@@ -756,7 +763,7 @@ def arithmetic(
name, path = name.strip(), path.strip()
if not name_re.match(name):
console.print(
- f"[red]Invalid adapter name {escape(name)!r} "
+ f"[red]Invalid adapter name {for_terminal(repr(name))} "
"(use [A-Za-z0-9_.-]).[/]"
)
raise typer.Exit(1)
diff --git a/src/soup_cli/commands/attest.py b/src/soup_cli/commands/attest.py
index 373eb3af..edbdbc77 100644
--- a/src/soup_cli/commands/attest.py
+++ b/src/soup_cli/commands/attest.py
@@ -343,7 +343,7 @@ def verify_cmd(
if backend != "ed25519" or not sig_hex:
console.print(
- f"[yellow]Signature backend {escape(backend or 'unsigned')!r} "
+ f"[yellow]Signature backend {for_terminal(repr(backend or 'unsigned'))} "
"is not cryptographically verifiable.[/]"
)
raise typer.Exit(3)
diff --git a/src/soup_cli/commands/chat.py b/src/soup_cli/commands/chat.py
index 1ddcd3f5..76720599 100644
--- a/src/soup_cli/commands/chat.py
+++ b/src/soup_cli/commands/chat.py
@@ -8,6 +8,8 @@ import typer
from rich.console import Console
from rich.panel import Panel
+from soup_cli.utils.terminal import for_terminal
+
console = Console()
@@ -110,7 +112,7 @@ def chat(
console.print(
Panel(
f"Model: [bold]{model_path}[/]\n"
- + (f"Base: [bold]{base_model}[/]\n" if is_adapter else "")
+ + (f"Base: [bold]{for_terminal(base_model)}[/]\n" if is_adapter else "")
+ f"Device: [bold]{device}[/]\n"
f"Type: [bold]{'LoRA adapter' if is_adapter else 'Full model'}[/]",
title="Loading model",
@@ -231,7 +233,7 @@ def _load_model(
if is_adapter:
from peft import PeftModel
- console.print(f"[dim]Loading base model: {base_model}...[/]")
+ console.print(f"[dim]Loading base model: {for_terminal(base_model)}...[/]")
base = AutoModelForCausalLM.from_pretrained(
base_model,
trust_remote_code=trust_remote_code,
diff --git a/src/soup_cli/commands/data_forge.py b/src/soup_cli/commands/data_forge.py
index c970eac3..2bb90aae 100644
--- a/src/soup_cli/commands/data_forge.py
+++ b/src/soup_cli/commands/data_forge.py
@@ -9,6 +9,8 @@ from rich.console import Console
from rich.markup import escape
from rich.panel import Panel
+from soup_cli.utils.terminal import for_terminal
+
console = Console()
@@ -137,7 +139,7 @@ def forge(
# (code-review MEDIUM fix v0.71.5 #157).
console.print(
f"[yellow]--hub {escape(hub_canonical)} ignored:[/] --teacher "
- f"{escape(teacher)!r} is not a repo id (owner/name), so there "
+ f"{for_terminal(repr(teacher))} is not a repo id (owner/name), so there "
"is nothing to pre-fetch."
)
diff --git a/src/soup_cli/commands/deploy.py b/src/soup_cli/commands/deploy.py
index a59491bf..505c5f61 100644
--- a/src/soup_cli/commands/deploy.py
+++ b/src/soup_cli/commands/deploy.py
@@ -761,10 +761,11 @@ def _run_deploy_autopilot_measure(
run_measure,
)
from soup_cli.utils.paths import is_under_cwd
+ from soup_cli.utils.terminal import for_terminal
if not is_under_cwd(tasks_file):
console.print(
- f"[red]--tasks {escape(tasks_file)!r} must stay under cwd[/]"
+ f"[red]--tasks {for_terminal(repr(tasks_file))} must stay under cwd[/]"
)
raise typer.Exit(2)
if not Path(tasks_file).is_file():
diff --git a/src/soup_cli/commands/env.py b/src/soup_cli/commands/env.py
index 377f9992..5deacb85 100644
--- a/src/soup_cli/commands/env.py
+++ b/src/soup_cli/commands/env.py
@@ -28,6 +28,7 @@ from soup_cli.utils.env_lock import (
write_requirements_txt,
)
from soup_cli.utils.paths import is_under_cwd
+from soup_cli.utils.terminal import for_terminal
console = Console()
@@ -56,7 +57,7 @@ def env_lock_cmd(
console.print("[red]output path must not contain null bytes[/]")
raise typer.Exit(2)
if not is_under_cwd(output):
- console.print(f"[red]output {escape(output)!r} is outside cwd[/]")
+ console.print(f"[red]output {for_terminal(repr(output))} is outside cwd[/]")
raise typer.Exit(2)
try:
@@ -253,7 +254,7 @@ def env_fix_cmd(
console.print("[red]output path must not contain null bytes[/]")
raise typer.Exit(2)
if not is_under_cwd(output):
- console.print(f"[red]output {escape(output)!r} is outside cwd[/]")
+ console.print(f"[red]output {for_terminal(repr(output))} is outside cwd[/]")
raise typer.Exit(2)
try:
write_requirements_txt(lock, output)
diff --git a/src/soup_cli/commands/eval.py b/src/soup_cli/commands/eval.py
index e19cd8a8..d05eed32 100644
--- a/src/soup_cli/commands/eval.py
+++ b/src/soup_cli/commands/eval.py
@@ -42,7 +42,7 @@ def _reject_lm_eval_injection(value: str, field: str) -> None:
if "," in value or "=" in value:
console.print(
f"[red]Refusing to evaluate:[/] {field} contains ',' or '=' "
- f"({value!r}); these are lm-eval model_args delimiters and could "
+ f"({for_terminal(repr(value))}); these are lm-eval model_args delimiters and could "
"smuggle trust_remote_code=True (arbitrary code execution)."
)
raise typer.Exit(1)
@@ -109,7 +109,7 @@ def benchmark(
)
model_arg = f"pretrained={base_model},peft={model_path}"
console.print(
- f"[dim]LoRA adapter detected. Base model: {base_model}[/]"
+ f"[dim]LoRA adapter detected. Base model: {for_terminal(base_model)}[/]"
)
else:
model_arg = f"pretrained={model_path}"
diff --git a/src/soup_cli/commands/export.py b/src/soup_cli/commands/export.py
index 7599e4c5..b3a3a07d 100644
--- a/src/soup_cli/commands/export.py
+++ b/src/soup_cli/commands/export.py
@@ -13,6 +13,8 @@ from rich.console import Console
from rich.markup import escape
from rich.panel import Panel
+from soup_cli.utils.terminal import for_terminal
+
console = Console()
SUPPORTED_FORMATS = (
@@ -404,7 +406,7 @@ def _merge_adapter(
requires_remote_code=requires,
)
- console.print(f"[dim]Loading base model: {base_model}...[/]")
+ console.print(f"[dim]Loading base model: {for_terminal(base_model)}...[/]")
model = AutoModelForCausalLM.from_pretrained(
base_model,
torch_dtype=torch.float16,
diff --git a/src/soup_cli/commands/infer.py b/src/soup_cli/commands/infer.py
index a1b985ff..1dd5578d 100644
--- a/src/soup_cli/commands/infer.py
+++ b/src/soup_cli/commands/infer.py
@@ -585,11 +585,13 @@ def _infer_asr(
hyp = transcribe(resolved)
except (ValueError, OSError, ImportError) as exc:
skipped += 1
- # Escape + control-strip the dataset-derived filename AND the
- # exception (whose message embeds that filename) before printing.
- name = for_terminal(Path(str(audio)).name)
+ # Quote the dataset-derived filename first, then escape and
+ # control-strip it (repr() after the escape would double the
+ # escape's backslash and make a tag live again); the exception,
+ # whose message embeds that filename, is escaped too.
+ name = for_terminal(repr(Path(str(audio)).name))
console.print(
- f"[yellow]Skipped {name!r}: {for_terminal(str(exc))}[/]"
+ f"[yellow]Skipped {name}: {for_terminal(str(exc))}[/]"
)
continue
rec = {"audio": audio, "transcription": hyp}
@@ -603,9 +605,9 @@ def _infer_asr(
row_wer = wer(ref, hyp)
row_cer = cer(ref, hyp)
except ValueError as exc:
- name = for_terminal(Path(str(audio)).name)
+ name = for_terminal(repr(Path(str(audio)).name))
console.print(
- f"[yellow]Metric skipped for {name!r}: "
+ f"[yellow]Metric skipped for {name}: "
f"{for_terminal(str(exc))}[/]"
)
else:
diff --git a/src/soup_cli/commands/merge.py b/src/soup_cli/commands/merge.py
index e657dd8d..808f017f 100644
--- a/src/soup_cli/commands/merge.py
+++ b/src/soup_cli/commands/merge.py
@@ -8,6 +8,8 @@ import typer
from rich.console import Console
from rich.panel import Panel
+from soup_cli.utils.terminal import for_terminal
+
console = Console()
@@ -139,7 +141,7 @@ def merge(
console.print(
Panel(
f"Adapter: [bold]{adapter_path}[/]\n"
- f"Base: [bold]{base}[/]\n"
+ f"Base: [bold]{for_terminal(base)}[/]\n"
f"Output: [bold]{output_path}[/]\n"
f"Dtype: [bold]{dtype}[/]",
title="Merge Plan",
@@ -172,7 +174,7 @@ def merge(
requires_remote_code=requires,
)
- console.print(f"[dim]Loading base model: {base}...[/]")
+ console.print(f"[dim]Loading base model: {for_terminal(base)}...[/]")
model = AutoModelForCausalLM.from_pretrained(
base,
torch_dtype=model_dtype,
@@ -237,7 +239,7 @@ def merge(
console.print("Run: [bold]pip install torch transformers peft[/]")
raise typer.Exit(1)
except Exception as exc:
- console.print(f"[red]Merge failed: {exc}[/]")
+ console.print(f"[red]Merge failed: {for_terminal(exc)}[/]")
raise typer.Exit(1)
# Calculate output size
diff --git a/src/soup_cli/commands/probe.py b/src/soup_cli/commands/probe.py
index a54ec62a..7808ae9d 100644
--- a/src/soup_cli/commands/probe.py
+++ b/src/soup_cli/commands/probe.py
@@ -24,6 +24,7 @@ from rich.panel import Panel
from rich.table import Table
from soup_cli.utils.paths import atomic_write_text, enforce_under_cwd_and_no_symlink
+from soup_cli.utils.terminal import for_terminal
console = Console()
@@ -629,7 +630,8 @@ def interference(
for key, value in losses_raw.items():
if not isinstance(key, str) or "|" not in key:
console.print(
- f"[red]Invalid losses key {key!r}; expected 'a|b' shape.[/]"
+ f"[red]Invalid losses key {for_terminal(repr(key))}; "
+ "expected 'a|b' shape.[/]"
)
raise typer.Exit(2)
# H3 review fix (v0.66.0): validate the value is numeric BEFORE
@@ -638,7 +640,7 @@ def interference(
# with a confusing message.
if isinstance(value, bool) or not isinstance(value, (int, float)):
console.print(
- f"[red]losses[{escape(key)!r}] must be numeric, "
+ f"[red]losses[{for_terminal(repr(key))}] must be numeric, "
f"got {type(value).__name__}[/]"
)
raise typer.Exit(2)
diff --git a/src/soup_cli/commands/serve.py b/src/soup_cli/commands/serve.py
index d2686c92..3029cdea 100644
--- a/src/soup_cli/commands/serve.py
+++ b/src/soup_cli/commands/serve.py
@@ -714,7 +714,7 @@ def serve(
console.print(
Panel(
f"Model: [bold]{model_path}[/]\n"
- + (f"Base: [bold]{base_model}[/]\n" if is_adapter else "")
+ + (f"Base: [bold]{for_terminal(base_model)}[/]\n" if is_adapter else "")
+ f"Device: [bold]{device}[/]\n"
f"Type: [bold]{'LoRA adapter' if is_adapter else 'Full model'}[/]\n"
f"Backend: [bold]{backend_label}[/]"
@@ -1390,7 +1390,7 @@ def _load_model(
if is_adapter:
from peft import PeftModel
- console.print(f"[dim]Loading base model: {base_model}...[/]")
+ console.print(f"[dim]Loading base model: {for_terminal(base_model)}...[/]")
base = AutoModelForCausalLM.from_pretrained(
base_model,
trust_remote_code=trust_remote_code,
diff --git a/src/soup_cli/commands/tunability.py b/src/soup_cli/commands/tunability.py
index 2e54337f..bb2face1 100644
--- a/src/soup_cli/commands/tunability.py
+++ b/src/soup_cli/commands/tunability.py
@@ -15,6 +15,7 @@ from rich.panel import Panel
from rich.table import Table
from soup_cli.utils.paths import is_under_cwd
+from soup_cli.utils.terminal import for_terminal
from soup_cli.utils.tunability import (
DEFAULT_CANDIDATES,
CandidateBase,
@@ -126,7 +127,7 @@ def tunability_cmd(
console.print("[red]dataset path must not contain null bytes[/]")
raise typer.Exit(2)
if not is_under_cwd(dataset):
- console.print(f"[red]dataset {escape(dataset)!r} is outside cwd[/]")
+ console.print(f"[red]dataset {for_terminal(repr(dataset))} is outside cwd[/]")
raise typer.Exit(2)
try:
@@ -217,7 +218,7 @@ def tunability_cmd(
console.print("[red]output path must not contain null bytes[/]")
raise typer.Exit(2)
if not is_under_cwd(output):
- console.print(f"[red]output {escape(output)!r} is outside cwd[/]")
+ console.print(f"[red]output {for_terminal(repr(output))} is outside cwd[/]")
raise typer.Exit(2)
try:
write_report(report, output)
diff --git a/src/soup_cli/config/loader.py b/src/soup_cli/config/loader.py
index 077f7dcc..360ad4e6 100644
--- a/src/soup_cli/config/loader.py
+++ b/src/soup_cli/config/loader.py
@@ -163,7 +163,8 @@ def load_config(
console.print("[red bold]Config validation error:[/]\n")
for err in e.errors():
loc = " -> ".join(str(part) for part in err["loc"])
- console.print(f" [red]{loc}:[/] {err['msg']}")
+ # Both can quote config keys or values from the file.
+ console.print(f" [red]{for_terminal(loc)}:[/] {for_terminal(err['msg'])}")
raise SystemExit(1)
staged_error = _report_staged_fields(raw, config=config)
diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.py
index d21d3f27..bd604452 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -23,6 +23,7 @@ from soup_cli.utils.gpu import (
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
+from soup_cli.utils.terminal import for_terminal
logger = logging.getLogger(__name__)
@@ -2004,7 +2005,10 @@ class SFTTrainerWrapper(StreamingSetupMixin):
try:
image = PILImage.open(image_path).convert("RGB")
except (FileNotFoundError, OSError):
- console.print(f"[yellow]Warning: cannot open image: {image_path}[/]")
+ console.print(
+ "[yellow]Warning: cannot open image: "
+ f"{for_terminal(image_path)}[/]"
+ )
result = {"images": []}
if image is not None:
@@ -2137,7 +2141,10 @@ class SFTTrainerWrapper(StreamingSetupMixin):
audio_path, sr=16000, mono=True,
)
except (FileNotFoundError, OSError):
- console.print(f"[yellow]Warning: cannot open audio: {audio_path}[/]")
+ console.print(
+ "[yellow]Warning: cannot open audio: "
+ f"{for_terminal(audio_path)}[/]"
+ )
messages = example["messages"]
if hasattr(self.processor, "apply_chat_template"):
diff --git a/src/soup_cli/ui/app.py b/src/soup_cli/ui/app.py
index 41ecb9b9..e89369fa 100644
--- a/src/soup_cli/ui/app.py
+++ b/src/soup_cli/ui/app.py
@@ -644,6 +644,7 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):
# Validate config before writing to disk
from soup_cli.config.loader import load_config_from_string
+ from soup_cli.utils.terminal import strip_control
try:
load_config_from_string(req.config_yaml)
@@ -651,12 +652,14 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):
# The loader's own message names the field and the suggestion;
# an unknown key now refuses here (#879), so this is where a
# Web UI user learns which key. Rendered through escapeHtml().
- logger.warning("Invalid training config: %s", exc)
+ # The log line goes to the server's terminal, so the key's
+ # control characters are stripped there.
+ logger.warning("Invalid training config: %s", strip_control(exc))
raise HTTPException(
status_code=400, detail=f"Invalid training configuration: {exc}"
)
except Exception as exc:
- logger.warning("Invalid training config: %s", exc)
+ logger.warning("Invalid training config: %s", strip_control(exc))
raise HTTPException(
status_code=400, detail="Invalid training configuration"
)
@@ -1007,6 +1010,7 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):
import yaml
from soup_cli.config.loader import load_config_from_string
+ from soup_cli.utils.terminal import strip_control
# Build YAML from form values
config_dict = {}
@@ -1022,10 +1026,10 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):
load_config_from_string(yaml_str)
return {"yaml": yaml_str}
except ValueError as exc:
- logger.warning("Config form validation error: %s", exc)
+ logger.warning("Config form validation error: %s", strip_control(exc))
return {"error": f"Invalid configuration: {exc}"}
except TypeError as exc:
- logger.warning("Config form validation error: %s", exc)
+ logger.warning("Config form validation error: %s", strip_control(exc))
return {"error": "Invalid configuration"}
# --- Chat Proxy ---
diff --git a/src/soup_cli/utils/edit_diff.py b/src/soup_cli/utils/edit_diff.py
index 8dd15455..25807d17 100644
--- a/src/soup_cli/utils/edit_diff.py
+++ b/src/soup_cli/utils/edit_diff.py
@@ -345,15 +345,18 @@ def _generate_live_changes(
def render_diff_table(report: DiffReport, console) -> None:
"""Render a diff report as a Rich table."""
- from rich.markup import escape
from rich.table import Table
+ from soup_cli.utils.terminal import for_terminal
+
if not isinstance(report, DiffReport):
raise TypeError("report must be DiffReport")
+ # Run ids, probe prompts and model outputs are all text from outside
+ # the program: show markup literally, drop control characters.
title = (
- f"Edit diff — {escape(report.before_run_id)} -> "
- f"{escape(report.after_run_id)}"
+ f"Edit diff \u2014 {for_terminal(report.before_run_id)} -> "
+ f"{for_terminal(report.after_run_id)}"
)
table = Table(title=title)
table.add_column("prompt", overflow="fold")
@@ -372,9 +375,9 @@ def render_diff_table(report: DiffReport, console) -> None:
for c in report.changes:
mark = "[green]yes[/]" if c.changed else "[dim]no[/]"
table.add_row(
- escape(c.prompt),
- escape(c.before),
- escape(c.after),
+ for_terminal(c.prompt),
+ for_terminal(c.before),
+ for_terminal(c.after),
mark,
)
console.print(table)
diff --git a/src/soup_cli/utils/ship_verdict.py b/src/soup_cli/utils/ship_verdict.py
index a6ea343b..0f786489 100644
--- a/src/soup_cli/utils/ship_verdict.py
+++ b/src/soup_cli/utils/ship_verdict.py
@@ -668,7 +668,9 @@ def render_ship_panel(verdict: ShipVerdict) -> Panel:
else:
table.add_row("[dim](none measured)[/]", "-", "-", "-", "[red]missing[/]")
- footer = f"[dim]{escape(_failed_rule_explanation(verdict))}[/]"
+ # The explanation names regressed benchmarks, which come from evidence
+ # files: strip control characters as well as escaping markup.
+ footer = f"[dim]{escape(for_terminal(_failed_rule_explanation(verdict)))}[/]"
parts = [header, "", table, ""]
if verdict.noise_floor is not None:
parts.extend([
diff --git a/src/soup_cli/utils/terminal.py b/src/soup_cli/utils/terminal.py
index 45a06a62..c18bc075 100644
--- a/src/soup_cli/utils/terminal.py
+++ b/src/soup_cli/utils/terminal.py
@@ -1,36 +1,40 @@
"""Terminal hygiene for text that came from outside the program.
-Two things bite when an untrusted string -- a config key from a YAML file, a
-benchmark name from an evidence file, a dataset row -- is printed through a
-Rich console:
+Two things go wrong when a string from outside the program -- a config key
+from a YAML file, a benchmark name from an evidence file, a dataset row -- is
+printed through a Rich console:
* ``rich.markup.escape`` neutralises ``[...]`` tags and NOTHING else, so a
key spelled ``[bold red]x[/]`` would restyle the terminal.
-* Rich passes C0 control bytes through, so a raw ESC (0x1B) in the text is a
- live escape sequence -- window-title spoofing, OSC-8 link spoofing, and on
- some emulators worse -- that ``escape()`` never sees.
+* Rich passes control characters through, so a raw ESC (0x1B) in the text --
+ or a C1 control such as U+009B, which some terminals treat in UTF-8 output
+ as a one-character CSI -- starts a live escape sequence (a window-title
+ change, an OSC-8 link) that ``escape()`` never sees.
-:func:`for_terminal` does both. Some call sites only need the strip half —
+:func:`for_terminal` does both. Some call sites only need the strip half --
e.g. text handed to ``Text.append(..., style=...)``, which Rich never parses
-as markup, or a string that a caller escapes itself further downstream — so
-:func:`strip_control` is exported too. Both draw on the same table so there
-is exactly one definition of "which bytes are dangerous" in the tree.
+as markup, a plain log line, or a string that a caller escapes itself further
+downstream -- so :func:`strip_control` is exported too. Both draw on the same
+table so there is exactly one definition of "which characters never reach the
+terminal" in the tree.
"""
from __future__ import annotations
from rich.markup import escape as _escape_markup
-#: Every C0 control byte except TAB / LF / CR, plus DEL.
+#: Every C0 control character except TAB / LF / CR, plus DEL, plus the C1
+#: range U+0080-U+009F.
_CONTROL_STRIP_TABLE = {i: None for i in range(0x20) if i not in (0x09, 0x0A, 0x0D)}
_CONTROL_STRIP_TABLE[0x7F] = None
+_CONTROL_STRIP_TABLE.update(dict.fromkeys(range(0x80, 0xA0)))
def strip_control(text: object) -> str:
- """Strip C0/DEL control bytes without touching Rich markup."""
+ """Strip C0 (except TAB/LF/CR), DEL and C1 controls; leave Rich markup alone."""
return str(text).translate(_CONTROL_STRIP_TABLE)
def for_terminal(text: object) -> str:
- """Strip control bytes, then escape Rich markup, in that order."""
+ """Strip control characters, then escape Rich markup, in that order."""
return _escape_markup(strip_control(text))
diff --git a/src/soup_cli/utils/trust_remote.py b/src/soup_cli/utils/trust_remote.py
index 310faa22..909e100c 100644
--- a/src/soup_cli/utils/trust_remote.py
+++ b/src/soup_cli/utils/trust_remote.py
@@ -128,9 +128,12 @@ def resolve_trust_remote_code(
# in environments that don't otherwise pull in rich.
from rich.panel import Panel
+ from soup_cli.utils.terminal import for_terminal
+
console.print(
Panel.fit(
- f"[yellow]--trust-remote-code is enabled for[/] [bold]{model_name}[/]\n"
+ f"[yellow]--trust-remote-code is enabled for[/] "
+ f"[bold]{for_terminal(model_name)}[/]\n"
f"This will execute Python code shipped in the model repo. "
f"Only proceed if you trust the source.",
title="[red]REMOTE CODE WARNING[/]",
diff --git a/tests/test_can_output_control_bytes.py b/tests/test_can_output_control_bytes.py
index d2fe2402..b8e46411 100644
--- a/tests/test_can_output_control_bytes.py
+++ b/tests/test_can_output_control_bytes.py
@@ -10,10 +10,11 @@ from typer.testing import CliRunner
runner = CliRunner()
-# ``name`` is held to ``[A-Za-z0-9_.-]`` by the schema, so a control byte there
-# refuses the whole manifest; the other printed fields accept one.
+# ``name`` is held to ``[A-Za-z0-9_.-]`` and ``author`` refuses control
+# characters, so a control byte in either refuses the whole manifest; the
+# other printed fields accept one.
MANIFEST = (
- 'can_format_version: 1\nname: "n"\nauthor: "a\\e[3A\\e[2K"\n'
+ 'can_format_version: 1\nname: "n"\nauthor: "a"\n'
'created_at: "2026-01-01"\nbase_hash: "h\\e]8;;http://x\\e\\\\"\n'
'tags: ["t\\e[31m"]\ndescription: "\\e]0;TITLE\\e\\\\"\n'
)
@@ -52,7 +53,6 @@ def test_manifest_fixture_carries_escape_bytes(can_file):
from soup_cli.cans.unpack import inspect_can
manifest = inspect_can(can_file)
- assert "\x1b" in manifest.author
assert "\x1b" in manifest.base_hash
assert "\x1b" in manifest.tags[0]
assert "\x1b" in manifest.description
diff --git a/tests/test_file_derived_text_printing.py b/tests/test_file_derived_text_printing.py
new file mode 100644
index 00000000..804f4c57
--- /dev/null
+++ b/tests/test_file_derived_text_printing.py
@@ -0,0 +1,681 @@
+"""Text read from files reaches the terminal as text, not as markup or control.
+
+Several printers interpolated a value read from a file -- an adapter config's
+``base_model_name_or_path``, an attestation sidecar's ``backend``, a layer name
+from ``adapter_model.safetensors``, a benchmark name from evidence, a dataset
+row's media path, a pydantic message quoting a config key -- into a Rich markup
+string either raw, through ``rich.markup.escape`` alone (which leaves ESC and
+C1 controls in place), or as ``{escape(x)!r}``, where ``repr()`` doubles the
+backslash ``escape()`` added and the tag is live again. Each now goes through
+``soup_cli.utils.terminal.for_terminal`` (or ``strip_control`` for a plain log
+line).
+
+Every test drives the real command or function that prints, with the module's
+console swapped for ``Console(file=StringIO(), color_system=None)`` so Rich
+emits no styling of its own: any ESC in the capture came from the value.
+Non-ASCII characters are built with ``chr()`` so this file stays ASCII.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import sys
+import types
+from io import StringIO
+
+import pytest
+from rich.console import Console
+from typer.testing import CliRunner
+
+runner = CliRunner()
+
+ESC = chr(27)
+BEL = chr(7)
+CSI_C1 = chr(0x9B)
+BACKSLASH = chr(92)
+MARKUP = "[b]x[/b][/]"
+
+#: A value as it can sit in an adapter config, an evidence file or a dataset
+#: row: an OSC title sequence, a C1 CSI, a tag pair and a bare closing tag.
+FILE_TEXT = "org/m" + ESC + "]0;T" + BEL + CSI_C1 + "2J" + MARKUP
+
+#: What the terminal must show for it: controls gone, brackets literal.
+SHOWN = "org/m]0;T2J" + MARKUP
+
+
+def _console(buffer: StringIO) -> Console:
+ return Console(file=buffer, color_system=None, width=400)
+
+
+def _swap_console(monkeypatch, module) -> StringIO:
+ buffer = StringIO()
+ monkeypatch.setattr(module, "console", _console(buffer))
+ return buffer
+
+
+def _assert_shown_literally(out: str, *, times: int = 1) -> None:
+ assert out.count(SHOWN) >= times, out
+ assert ESC not in out, repr(out)
+ assert CSI_C1 not in out, repr(out)
+
+
+def _adapter_dir(root, base_model: str = FILE_TEXT, name: str = "adp", **extra):
+ adapter = root / name
+ adapter.mkdir()
+ config = {"base_model_name_or_path": base_model, "peft_type": "LORA", "r": 8}
+ config.update(extra)
+ (adapter / "adapter_config.json").write_text(json.dumps(config), encoding="utf-8")
+ return adapter
+
+
+class _StopLoadingError(Exception):
+ """Raised by the stand-in loaders once the line under test has printed."""
+
+
+def _stand_in_hf_modules(monkeypatch, message: str = "stopped before the model load") -> list:
+ """Replace ``transformers`` / ``peft`` with stand-ins that stop at the first load.
+
+ The tokenizer loads (so the base-model line is reached); the first model
+ load raises :class:`_StopLoadingError` with ``message``, before anything
+ is downloaded.
+ """
+ calls: list = []
+
+ def _model_from_pretrained(name, *args, **kwargs):
+ calls.append(name)
+ raise _StopLoadingError(message)
+
+ tokenizer = types.SimpleNamespace(pad_token="<pad>", eos_token="<eos>")
+ transformers = types.ModuleType("transformers")
+ transformers.AutoModelForCausalLM = types.SimpleNamespace(
+ from_pretrained=_model_from_pretrained
+ )
+ transformers.AutoTokenizer = types.SimpleNamespace(
+ from_pretrained=lambda *args, **kwargs: tokenizer
+ )
+ peft = types.ModuleType("peft")
+ peft.PeftModel = types.SimpleNamespace(from_pretrained=_model_from_pretrained)
+ monkeypatch.setitem(sys.modules, "transformers", transformers)
+ monkeypatch.setitem(sys.modules, "peft", peft)
+ return calls
+
+
+def _yaml_escape(code: int) -> str:
+ return f"{BACKSLASH}x{code:02x}"
+
+
+# ---------------------------------------------------------------------------
+# soup attest verify: the sidecar's backend name
+# ---------------------------------------------------------------------------
+
+
+class TestAttestVerifyBackendName:
+ def test_a_backend_name_containing_markup_keeps_exit_code_3(
+ self, tmp_path, monkeypatch
+ ) -> None:
+ """Exit 3 is "invalid signature / policy mismatch"; exit 1 means the
+ verifier was unavailable. A sidecar is the input being judged, so its
+ content must not be able to turn the first into the second."""
+ from soup_cli.commands import attest as attest_cmd
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "stmt.json").write_text('{"_type": "x"}', encoding="utf-8")
+ (tmp_path / "stmt.json.sig").write_text(
+ json.dumps({"backend": "[/]x" + ESC + CSI_C1, "signature": "00"}),
+ encoding="utf-8",
+ )
+ buffer = _swap_console(monkeypatch, attest_cmd)
+ result = runner.invoke(
+ attest_cmd.app, ["verify", "stmt.json", "--signature", "stmt.json.sig"]
+ )
+ out = buffer.getvalue()
+ assert result.exit_code == 3, (out, repr(result.exception))
+ # The quoted form is repr()'s, so the two controls arrive as their
+ # escape text and the tag as literal brackets.
+ quoted = "'[/]x" + BACKSLASH + "x1b" + BACKSLASH + "x9b'"
+ assert f"Signature backend {quoted} is not cryptographically verifiable" in out, out
+
+ def test_an_ordinary_backend_name_is_still_shown_quoted(
+ self, tmp_path, monkeypatch
+ ) -> None:
+ from soup_cli.commands import attest as attest_cmd
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "stmt.json").write_text('{"_type": "x"}', encoding="utf-8")
+ (tmp_path / "stmt.json.sig").write_text(
+ json.dumps({"backend": "hmac", "signature": "00"}), encoding="utf-8"
+ )
+ buffer = _swap_console(monkeypatch, attest_cmd)
+ result = runner.invoke(
+ attest_cmd.app, ["verify", "stmt.json", "--signature", "stmt.json.sig"]
+ )
+ assert result.exit_code == 3, (buffer.getvalue(), repr(result.exception))
+ assert "Signature backend 'hmac' is not" in buffer.getvalue()
+
+
+# ---------------------------------------------------------------------------
+# The adapter config's base_model_name_or_path: chat / merge / serve / export
+# ---------------------------------------------------------------------------
+
+
+class TestAdapterBaseModelName:
+ def test_chat_loading_panel(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.cli import app
+ from soup_cli.commands import chat as chat_cmd
+
+ adapter = _adapter_dir(tmp_path)
+ buffer = _swap_console(monkeypatch, chat_cmd)
+
+ def _stop_loading(**kwargs):
+ raise _StopLoadingError("stopped before loading")
+
+ monkeypatch.setattr(chat_cmd, "_load_model", _stop_loading)
+ result = runner.invoke(app, ["chat", "--model", str(adapter), "--device", "cpu"])
+ assert isinstance(result.exception, _StopLoadingError), (
+ buffer.getvalue(),
+ repr(result.exception),
+ )
+ _assert_shown_literally(buffer.getvalue())
+
+ def test_chat_loading_base_model_line(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.commands import chat as chat_cmd
+
+ calls = _stand_in_hf_modules(monkeypatch)
+ buffer = _swap_console(monkeypatch, chat_cmd)
+ with pytest.raises(_StopLoadingError):
+ chat_cmd._load_model(
+ model_path=str(tmp_path), base_model=FILE_TEXT, is_adapter=True, device="cpu"
+ )
+ assert calls == [FILE_TEXT]
+ out = buffer.getvalue()
+ assert "Loading base model: " + SHOWN in out, out
+ _assert_shown_literally(out)
+
+ def test_merge_plan_panel_loading_line_and_failure(self, tmp_path, monkeypatch) -> None:
+ """The plan panel, the loading line, and the failure line: a loader
+ error commonly quotes the repo id it could not load."""
+ from soup_cli.cli import app
+ from soup_cli.commands import merge as merge_cmd
+
+ monkeypatch.chdir(tmp_path)
+ _adapter_dir(tmp_path)
+ _stand_in_hf_modules(monkeypatch, message="cannot load " + FILE_TEXT)
+ buffer = _swap_console(monkeypatch, merge_cmd)
+ result = runner.invoke(app, ["merge", "--adapter", "adp", "--output", "merged"])
+ out = buffer.getvalue()
+ assert result.exit_code == 1, (out, repr(result.exception))
+ assert isinstance(result.exception, SystemExit), repr(result.exception)
+ assert "Merge failed: cannot load " + SHOWN in out, out
+ assert "Loading base model: " + SHOWN in out, out
+ _assert_shown_literally(out, times=3)
+
+ def test_serve_loading_panel(self, tmp_path, monkeypatch) -> None:
+ pytest.importorskip("fastapi")
+ pytest.importorskip("uvicorn")
+ from soup_cli.cli import app
+ from soup_cli.commands import serve as serve_cmd
+
+ adapter = _adapter_dir(tmp_path)
+ buffer = _swap_console(monkeypatch, serve_cmd)
+ # An unknown --structured-output mode is refused right after the
+ # panel, so the command stops before any model is loaded.
+ result = runner.invoke(
+ app,
+ [
+ "serve", "--model", str(adapter), "--device", "cpu",
+ "--structured-output", "unknown-mode",
+ ],
+ )
+ out = buffer.getvalue()
+ assert result.exit_code == 1, (out, repr(result.exception))
+ assert isinstance(result.exception, SystemExit), repr(result.exception)
+ assert "Unknown structured-output mode" in out, out
+ _assert_shown_literally(out)
+
+ def test_serve_loading_base_model_line(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.commands import serve as serve_cmd
+
+ _stand_in_hf_modules(monkeypatch)
+ buffer = _swap_console(monkeypatch, serve_cmd)
+ with pytest.raises(_StopLoadingError):
+ serve_cmd._load_model(
+ model_path=str(tmp_path), base_model=FILE_TEXT, is_adapter=True, device="cpu"
+ )
+ out = buffer.getvalue()
+ assert "Loading base model: " + SHOWN in out, out
+ _assert_shown_literally(out)
+
+ def test_export_merge_step_loading_line(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.commands import export as export_cmd
+
+ adapter = _adapter_dir(tmp_path)
+ _stand_in_hf_modules(monkeypatch)
+ buffer = _swap_console(monkeypatch, export_cmd)
+ with pytest.raises(_StopLoadingError):
+ export_cmd._merge_adapter(str(adapter), FILE_TEXT, str(tmp_path / "merged"))
+ out = buffer.getvalue()
+ assert "Loading base model: " + SHOWN in out, out
+ _assert_shown_literally(out)
+
+ def test_remote_code_warning_panel(self) -> None:
+ from soup_cli.utils.trust_remote import resolve_trust_remote_code
+
+ buffer = StringIO()
+ assert resolve_trust_remote_code(FILE_TEXT, requested=True, console=_console(buffer))
+ out = buffer.getvalue()
+ assert "--trust-remote-code is enabled for" in out, out
+ _assert_shown_literally(out)
+
+
+class TestEvalBenchmarkBaseModel:
+ """``soup eval benchmark`` reads the base model from the adapter config.
+
+ ``lm_eval`` is made unimportable, so the command stops at its own
+ "not installed" message, which comes right after the line under test.
+ """
+
+ def test_the_detected_base_model_line(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.cli import app
+ from soup_cli.commands import eval as eval_cmd
+
+ adapter = _adapter_dir(tmp_path)
+ monkeypatch.setitem(sys.modules, "lm_eval", None)
+ buffer = _swap_console(monkeypatch, eval_cmd)
+ result = runner.invoke(app, ["eval", "benchmark", "--model", str(adapter)])
+ out = buffer.getvalue()
+ assert result.exit_code == 1, (out, repr(result.exception))
+ assert isinstance(result.exception, SystemExit), repr(result.exception)
+ assert "lm-eval not installed" in out, out
+ assert "LoRA adapter detected. Base model: " + SHOWN in out, out
+ _assert_shown_literally(out)
+
+ def test_a_refused_base_model_is_quoted_literally(self, tmp_path, monkeypatch) -> None:
+ """A ',' or '=' in the base model is refused before lm-eval sees it,
+ and the refusal quotes the value back."""
+ from soup_cli.cli import app
+ from soup_cli.commands import eval as eval_cmd
+
+ adapter = _adapter_dir(tmp_path, base_model="org/m,[/]x")
+ buffer = _swap_console(monkeypatch, eval_cmd)
+ result = runner.invoke(app, ["eval", "benchmark", "--model", str(adapter)])
+ out = buffer.getvalue()
+ assert result.exit_code == 1, (out, repr(result.exception))
+ assert isinstance(result.exception, SystemExit), repr(result.exception)
+ assert "Refusing to evaluate:" in out and "('org/m,[/]x')" in out, out
+
+
+# ---------------------------------------------------------------------------
+# soup adapters list / info / compare / diff
+# ---------------------------------------------------------------------------
+
+
+class TestAdaptersCommands:
+ def test_list(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.commands import adapters as adapters_cmd
+
+ scan = tmp_path / "scan"
+ scan.mkdir()
+ _adapter_dir(scan, peft_type=FILE_TEXT)
+ buffer = _swap_console(monkeypatch, adapters_cmd)
+ result = runner.invoke(adapters_cmd.app, ["list", str(scan)])
+ assert result.exit_code == 0, (buffer.getvalue(), repr(result.exception))
+ _assert_shown_literally(buffer.getvalue(), times=2)
+
+ def test_list_directory_names(self, tmp_path, monkeypatch) -> None:
+ """Adapter directory names come from the disk being scanned.
+
+ POSIX file names may hold control characters; Windows file names may
+ not, so discovery is stubbed to hand back such names without creating
+ them. One adapter reads cleanly, the other takes the unreadable-config
+ branch, which prints its full path.
+ """
+ from soup_cli.commands import adapters as adapters_cmd
+
+ scan = (tmp_path / "scan").resolve()
+ scan.mkdir()
+ readable = scan / ("ok" + ESC + "]0;T" + CSI_C1 + "2J[b]x")
+ unreadable = scan / ("bad" + ESC + "]0;T" + CSI_C1 + "2J[b]y")
+
+ def _read(adapter_path):
+ if adapter_path == unreadable:
+ raise json.JSONDecodeError("unreadable", "{", 0)
+ return {"base_model_name_or_path": "m", "r": 8, "peft_type": "LORA"}
+
+ monkeypatch.setattr(
+ adapters_cmd, "_find_adapters", lambda directory: [readable, unreadable]
+ )
+ monkeypatch.setattr(adapters_cmd, "_read_adapter_config", _read)
+ monkeypatch.setattr(adapters_cmd, "_get_adapter_size", lambda adapter_path: "1 B")
+ buffer = _swap_console(monkeypatch, adapters_cmd)
+ result = runner.invoke(adapters_cmd.app, ["list", str(scan)])
+ out = buffer.getvalue()
+ assert result.exit_code == 0, (out, repr(result.exception))
+ assert "ok]0;T2J[b]x" in out and "bad]0;T2J[b]y" in out, out
+ assert ESC not in out and CSI_C1 not in out, repr(out)
+
+ def test_info(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.commands import adapters as adapters_cmd
+
+ adapter = _adapter_dir(tmp_path, task_type=FILE_TEXT, target_modules=[FILE_TEXT])
+ buffer = _swap_console(monkeypatch, adapters_cmd)
+ result = runner.invoke(adapters_cmd.app, ["info", str(adapter)])
+ assert result.exit_code == 0, (buffer.getvalue(), repr(result.exception))
+ _assert_shown_literally(buffer.getvalue(), times=3)
+
+ def test_compare(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.commands import adapters as adapters_cmd
+
+ first = _adapter_dir(tmp_path, name="a1")
+ second = _adapter_dir(tmp_path, base_model="other", name="a2")
+ buffer = _swap_console(monkeypatch, adapters_cmd)
+ result = runner.invoke(adapters_cmd.app, ["compare", str(first), str(second)])
+ assert result.exit_code == 0, (buffer.getvalue(), repr(result.exception))
+ _assert_shown_literally(buffer.getvalue())
+
+ def test_diff_layer_names(self, tmp_path, monkeypatch) -> None:
+ np = pytest.importorskip("numpy")
+ safetensors_numpy = pytest.importorskip("safetensors.numpy")
+ from soup_cli.commands import adapters as adapters_cmd
+
+ monkeypatch.chdir(tmp_path)
+ for name, scale in (("a1", 1.0), ("a2", 2.0)):
+ adapter = _adapter_dir(tmp_path, name=name)
+ safetensors_numpy.save_file(
+ {FILE_TEXT: np.full((2, 2), scale, dtype=np.float32)},
+ str(adapter / "adapter_model.safetensors"),
+ )
+ buffer = _swap_console(monkeypatch, adapters_cmd)
+ result = runner.invoke(adapters_cmd.app, ["diff", "a1", "a2"])
+ assert result.exit_code == 0, (buffer.getvalue(), repr(result.exception))
+ _assert_shown_literally(buffer.getvalue())
+
+
+# ---------------------------------------------------------------------------
+# soup ship: benchmark names in the verdict footer
+# ---------------------------------------------------------------------------
+
+
+class TestShipVerdictFooter:
+ def test_regressed_benchmark_names(self) -> None:
+ from soup_cli.utils.ship_verdict import (
+ build_task_win,
+ compute_benchmark_deltas,
+ decide_ship,
+ render_ship_panel,
+ )
+
+ verdict = decide_ship(
+ build_task_win("metric", 0.40, 0.99),
+ compute_benchmark_deltas({FILE_TEXT: 0.80}, {FILE_TEXT: 0.50}),
+ )
+ buffer = StringIO()
+ _console(buffer).print(render_ship_panel(verdict))
+ out = buffer.getvalue()
+ assert "regressed past" in out, out
+ _assert_shown_literally(out, times=2)
+
+
+# ---------------------------------------------------------------------------
+# soup edit diff: run ids and probe text
+# ---------------------------------------------------------------------------
+
+
+class TestEditDiffTable:
+ def test_run_ids_prompts_and_outputs(self) -> None:
+ from soup_cli import __version__
+ from soup_cli.utils.edit_diff import DiffReport, FactChange, render_diff_table
+
+ report = DiffReport(
+ before_run_id=FILE_TEXT,
+ after_run_id="run-2",
+ changes=(FactChange(prompt=FILE_TEXT, before=FILE_TEXT, after="y", changed=True),),
+ total_probes=1,
+ soup_version=__version__,
+ )
+ buffer = StringIO()
+ render_diff_table(report, _console(buffer))
+ _assert_shown_literally(buffer.getvalue(), times=3)
+
+
+# ---------------------------------------------------------------------------
+# SFT vision / audio: a dataset row's media path in the "cannot open" warning
+# ---------------------------------------------------------------------------
+
+
+class TestSftMediaPathWarnings:
+ def test_vision_image_path(self, monkeypatch) -> None:
+ pytest.importorskip("PIL")
+ pytest.importorskip("datasets")
+ from soup_cli.trainer import sft as sft_module
+
+ buffer = _swap_console(monkeypatch, sft_module)
+ wrapper = object.__new__(sft_module.SFTTrainerWrapper)
+ row = {"messages": [{"role": "user", "content": "hi"}], "image": "imgs/" + FILE_TEXT}
+ wrapper._prepare_vision_dataset({"train": [row]})
+ out = buffer.getvalue()
+ assert "cannot open image: imgs/" + SHOWN in out, out
+ _assert_shown_literally(out)
+
+ def test_audio_path(self, monkeypatch) -> None:
+ pytest.importorskip("datasets")
+ from soup_cli.trainer import sft as sft_module
+
+ def _load(path, *args, **kwargs):
+ raise FileNotFoundError(path)
+
+ librosa = types.ModuleType("librosa")
+ librosa.load = _load
+ monkeypatch.setitem(sys.modules, "librosa", librosa)
+ buffer = _swap_console(monkeypatch, sft_module)
+ wrapper = object.__new__(sft_module.SFTTrainerWrapper)
+ wrapper.processor = types.SimpleNamespace()
+ row = {"messages": [{"role": "user", "content": "hi"}], "audio": "clips/" + FILE_TEXT}
+ wrapper._prepare_audio_dataset({"train": [row]})
+ out = buffer.getvalue()
+ assert "cannot open audio: clips/" + SHOWN in out, out
+ _assert_shown_literally(out)
+
+
+# ---------------------------------------------------------------------------
+# soup infer --task asr: a dataset row's audio file name in the skip warnings
+# ---------------------------------------------------------------------------
+
+
+class TestInferAsrAudioName:
+ """The skip and metric-skip warnings quote the row's audio file name.
+
+ The name was escaped and then quoted (``name = for_terminal(...)``, then
+ ``{name!r}``): ``repr()`` doubled the backslash the escape added, so
+ ``[b]`` became a live tag. Quoting first keeps it text.
+ """
+
+ NAME = "[b]a.wav"
+
+ def _run(self, tmp_path, monkeypatch, row: dict, transcriber):
+ from soup_cli.cli import app
+ from soup_cli.commands import infer as infer_cmd
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "in.jsonl").write_text(json.dumps(row) + "\n", encoding="utf-8")
+ monkeypatch.setattr(infer_cmd, "_ASR_TRANSCRIBER_OVERRIDE", transcriber)
+ buffer = _swap_console(monkeypatch, infer_cmd)
+ result = runner.invoke(
+ app,
+ ["infer", "--task", "asr", "--model", "m", "--input", "in.jsonl",
+ "--output", "out.jsonl"],
+ )
+ return result, buffer.getvalue()
+
+ def test_a_skipped_row(self, tmp_path, monkeypatch) -> None:
+ def _cannot_decode(path):
+ raise OSError("cannot decode")
+
+ result, out = self._run(tmp_path, monkeypatch, {"audio": self.NAME}, _cannot_decode)
+ # The only row was skipped, which the command reports with exit 2.
+ assert result.exit_code == 2, (out, repr(result.exception))
+ assert "Skipped '[b]a.wav': cannot decode" in out, out
+
+ def test_a_row_whose_metric_is_skipped(self, tmp_path, monkeypatch) -> None:
+ # A reference over the WER/CER input cap is transcribed but unscored.
+ row = {"audio": self.NAME, "text": "word " * 300_000}
+ result, out = self._run(tmp_path, monkeypatch, row, lambda path: "hello")
+ assert result.exit_code == 0, (out, repr(result.exception))
+ assert "Metric skipped for '[b]a.wav':" in out, out
+
+
+# ---------------------------------------------------------------------------
+# Config loader: a validation message quoting a config key
+# ---------------------------------------------------------------------------
+
+
+class TestConfigValidationErrorLines:
+ def test_a_message_quoting_a_key_is_printed_literally(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.config import loader
+
+ buffer = _swap_console(monkeypatch, loader)
+ path = tmp_path / "soup.yaml"
+ path.write_text(
+ "base: test-model\n"
+ "data:\n"
+ " train: ./data.jsonl\n"
+ "training:\n"
+ " lora:\n"
+ " rank_pattern:\n"
+ ' "q[/]x": "eight"\n',
+ encoding="utf-8",
+ )
+ with pytest.raises(SystemExit) as excinfo:
+ loader.load_config(path)
+ assert excinfo.value.code == 1
+ out = buffer.getvalue()
+ assert "rank_pattern" in out and "'q[/]x'" in out, out
+
+ def test_a_location_naming_a_key_is_printed_literally(self, tmp_path, monkeypatch) -> None:
+ """No schema field puts a key from the file into ``loc`` today -- the
+ dict-typed fields are rebuilt by their own validators -- so the error
+ is built by hand: the printer must not depend on that staying true."""
+ from pydantic_core import InitErrorDetails, ValidationError
+
+ from soup_cli.config import loader
+
+ def _refuse(raw):
+ raise ValidationError.from_exception_data(
+ "SoupConfig",
+ [InitErrorDetails(type="missing", loc=("training", "q[/]" + ESC + "x"), input={})],
+ )
+
+ monkeypatch.setattr(loader, "_build_config", _refuse)
+ buffer = _swap_console(monkeypatch, loader)
+ path = tmp_path / "soup.yaml"
+ path.write_text("base: test-model\ndata:\n train: ./data.jsonl\n", encoding="utf-8")
+ with pytest.raises(SystemExit) as excinfo:
+ loader.load_config(path)
+ assert excinfo.value.code == 1
+ out = buffer.getvalue()
+ assert "training -> q[/]x:" in out, out
+ assert ESC not in out, repr(out)
+
+
+# ---------------------------------------------------------------------------
+# soup probe interference: keys of the losses JSON
+# ---------------------------------------------------------------------------
+
+
+class TestProbeInterferenceLossKeys:
+ @pytest.mark.parametrize(
+ "losses, expected",
+ [
+ ({"[/]x": 1.0}, "Invalid losses key '[/]x'"),
+ ({"a|[/]x": "high"}, "losses['a|[/]x'] must be numeric"),
+ ],
+ ids=["key-without-separator", "non-numeric-value"],
+ )
+ def test_a_key_containing_markup_keeps_exit_code_2(
+ self, tmp_path, monkeypatch, losses, expected
+ ) -> None:
+ from soup_cli.commands import probe as probe_cmd
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "losses.json").write_text(
+ json.dumps({"adapters": ["a", "b"], "losses": losses}), encoding="utf-8"
+ )
+ buffer = _swap_console(monkeypatch, probe_cmd)
+ result = runner.invoke(probe_cmd.app, ["interference", "losses.json"])
+ out = buffer.getvalue()
+ assert result.exit_code == 2, (out, repr(result.exception))
+ assert expected in out, out
+
+
+# ---------------------------------------------------------------------------
+# Web UI: the server-side log line for a refused config
+# ---------------------------------------------------------------------------
+
+
+class TestWebUiConfigLogLines:
+ LOGGER = "soup_cli.ui.app"
+ KEY = ESC + "]0;T" + CSI_C1 + "2Jquantizaton"
+
+ @staticmethod
+ def _client():
+ pytest.importorskip("fastapi")
+ from fastapi.testclient import TestClient
+
+ from soup_cli.ui.app import create_app, get_auth_token
+
+ return TestClient(create_app()), {"Authorization": f"Bearer {get_auth_token()}"}
+
+ def _logged(self, caplog) -> list[str]:
+ return [record.getMessage() for record in caplog.records if record.name == self.LOGGER]
+
+ def _assert_clean(self, messages: list[str], visible: str) -> None:
+ assert any(visible in message for message in messages), messages
+ for message in messages:
+ assert ESC not in message and CSI_C1 not in message, repr(message)
+
+ def test_train_start_refused_config(self, caplog) -> None:
+ client, headers = self._client()
+ config_yaml = (
+ "base: m\n"
+ "data:\n"
+ " train: ./t.jsonl\n"
+ "training:\n"
+ f' "{_yaml_escape(0x1B)}]0;T{_yaml_escape(0x9B)}2Jquantizaton": 4bit\n'
+ )
+ with caplog.at_level(logging.WARNING, logger=self.LOGGER):
+ response = client.post(
+ "/api/train/start", json={"config_yaml": config_yaml}, headers=headers
+ )
+ assert response.status_code == 400, response.text
+ self._assert_clean(self._logged(caplog), "2Jquantizaton")
+
+ def test_config_from_form_refused_config(self, caplog) -> None:
+ client, headers = self._client()
+ body = {"base": "m", "data": {"train": "./t.jsonl"}, "training": {self.KEY: "4bit"}}
+ with caplog.at_level(logging.WARNING, logger=self.LOGGER):
+ response = client.post("/api/config/from-form", json=body, headers=headers)
+ assert response.status_code == 200, response.text
+ assert "error" in response.json(), response.json()
+ self._assert_clean(self._logged(caplog), "2Jquantizaton")
+
+ @pytest.mark.parametrize(
+ "route, raised",
+ [("/api/train/start", RuntimeError), ("/api/config/from-form", TypeError)],
+ ids=["train-start", "from-form"],
+ )
+ def test_the_other_error_branch(self, caplog, monkeypatch, route, raised) -> None:
+ from soup_cli.config import loader
+
+ def _refuse(text):
+ raise raised("refused " + self.KEY)
+
+ monkeypatch.setattr(loader, "load_config_from_string", _refuse)
+ client, headers = self._client()
+ body = (
+ {"config_yaml": "base: m\n"}
+ if route == "/api/train/start"
+ else {"base": "m", "data": {"train": "./t.jsonl"}}
+ )
+ with caplog.at_level(logging.WARNING, logger=self.LOGGER):
+ client.post(route, json=body, headers=headers)
+ self._assert_clean(self._logged(caplog), "2Jquantizaton")
diff --git a/tests/test_terminal_c1_controls.py b/tests/test_terminal_c1_controls.py
new file mode 100644
index 00000000..1e59cf72
--- /dev/null
+++ b/tests/test_terminal_c1_controls.py
@@ -0,0 +1,215 @@
+"""Terminal output strips the C1 control range, U+0080-U+009F.
+
+``soup_cli.utils.terminal`` holds the one table in the tree of characters that
+must never reach the terminal. It covered C0 (minus TAB / LF / CR) and DEL, but
+not C1: U+0080-U+009F passed through ``strip_control`` and ``for_terminal``
+unchanged, and some terminals act on a C1 character in UTF-8 output the way
+they act on ESC (U+009B is a one-character CSI). Every printer built on the two
+helpers inherited that, so the range is pinned here at both edges and through
+two real printers.
+
+The ``.can`` manifest ``author`` field now refuses control characters outright
+(``unicodedata.category == "Cc"``: C0, DEL and C1) instead of only NUL / CR /
+LF -- an author handle has no use for any of them.
+
+Every non-ASCII character below is built with ``chr()`` so this file stays
+ASCII.
+"""
+
+from __future__ import annotations
+
+import io
+import tarfile
+from io import StringIO
+
+import pytest
+from rich.console import Console
+from typer.testing import CliRunner
+
+runner = CliRunner()
+
+BACKSLASH = chr(92)
+C1_CODES = tuple(range(0x80, 0xA0))
+
+
+def _c1_found(text: str) -> list[str]:
+ return [hex(ord(ch)) for ch in text if 0x80 <= ord(ch) <= 0x9F]
+
+
+def _plain_console(buffer: StringIO) -> Console:
+ return Console(file=buffer, color_system=None, width=400)
+
+
+class TestTheHelpersStripC1:
+ @pytest.mark.parametrize("code", C1_CODES, ids=[f"{code:#04x}" for code in C1_CODES])
+ def test_every_c1_code_point_is_stripped(self, code: int) -> None:
+ from soup_cli.utils.terminal import for_terminal, strip_control
+
+ assert strip_control(f"a{chr(code)}b") == "ab"
+ assert for_terminal(f"a{chr(code)}b") == "ab"
+
+ @pytest.mark.parametrize(
+ "code, kept",
+ [(0x7E, True), (0x7F, False), (0x80, False), (0x9F, False), (0xA0, True), (0xA1, True)],
+ ids=["0x7e-tilde", "0x7f-del", "0x80-first-c1", "0x9f-last-c1", "0xa0-nbsp", "0xa1"],
+ )
+ def test_the_range_edges(self, code: int, kept: bool) -> None:
+ from soup_cli.utils.terminal import for_terminal, strip_control
+
+ expected = f"a{chr(code)}b" if kept else "ab"
+ assert strip_control(f"a{chr(code)}b") == expected
+ assert for_terminal(f"a{chr(code)}b") == expected
+
+ def test_printable_text_outside_ascii_is_left_alone(self) -> None:
+ from soup_cli.utils.terminal import for_terminal, strip_control
+
+ text = "caf" + chr(0xE9) + " " + chr(0x65E5) + chr(0x672C) + " " + chr(0x2014) + " x"
+ assert strip_control(text) == text
+ assert for_terminal(text) == text
+
+ def test_tab_newline_and_carriage_return_are_still_kept(self) -> None:
+ from soup_cli.utils.terminal import strip_control
+
+ assert strip_control("a\tb\nc\rd") == "a\tb\nc\rd"
+
+ def test_the_strip_runs_before_the_escape(self) -> None:
+ """A C1 character between a backslash and a tag must not end up live markup.
+
+ Escaping first would see ``backslash, C1, [bold]`` (no backslash
+ directly before the bracket), add one backslash, and the later strip
+ would leave two -- which Rich reads as a literal backslash followed by
+ a LIVE tag. Stripping first lets the escape see the real neighbours.
+ """
+ from soup_cli.utils.terminal import for_terminal
+
+ value = BACKSLASH + chr(0x9B) + "[bold]x[/bold]"
+ buffer = StringIO()
+ _plain_console(buffer).print(for_terminal(value))
+ assert buffer.getvalue().rstrip("\n") == BACKSLASH + "[bold]x[/bold]"
+
+
+def _write_can(path: str, manifest: str, config: str = "base: m\n") -> str:
+ with tarfile.open(path, "w:gz") as archive:
+ for name, body in (("manifest.yaml", manifest), ("config.yaml", config)):
+ payload = body.encode("utf-8")
+ info = tarfile.TarInfo(name)
+ info.size = len(payload)
+ archive.addfile(info, io.BytesIO(payload))
+ return path
+
+
+def _yaml_escape(code: int) -> str:
+ """The YAML double-quoted spelling of one code point, e.g. ``\\x9b``."""
+ return f"{BACKSLASH}x{code:02x}"
+
+
+class TestCanInspectPrintsNoC1:
+ MANIFEST = (
+ "can_format_version: 1\n"
+ 'name: "n"\n'
+ 'author: "a"\n'
+ 'created_at: "2026-01-01"\n'
+ 'base_hash: "h"\n'
+ f'tags: ["t{_yaml_escape(0x9B)}31m"]\n'
+ f'description: "{_yaml_escape(0x9D)}0;TITLE{_yaml_escape(0x9C)}d"\n'
+ )
+
+ @pytest.mark.parametrize("force_terminal", [False, True], ids=["plain", "terminal"])
+ def test_description_and_tags(self, tmp_path, monkeypatch, force_terminal: bool) -> None:
+ from soup_cli.cans.unpack import inspect_can
+ from soup_cli.cli import app
+ from soup_cli.commands import can as can_cmd
+
+ monkeypatch.chdir(tmp_path)
+ _write_can("c.can", self.MANIFEST)
+ manifest = inspect_can("c.can")
+ assert _c1_found(manifest.description), "fixture must carry C1 characters"
+ assert _c1_found(manifest.tags[0]), "fixture must carry C1 characters"
+
+ buffer = StringIO()
+ console = (
+ Console(file=buffer, force_terminal=True, width=400)
+ if force_terminal
+ else _plain_console(buffer)
+ )
+ monkeypatch.setattr(can_cmd, "console", console)
+ result = runner.invoke(app, ["can", "inspect", "c.can"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ out = buffer.getvalue()
+ assert "TITLE" in out and "31m" in out, out
+ assert _c1_found(out) == [], repr(out)
+
+
+class TestTheConfigLoaderPrintsNoC1:
+ def test_an_unknown_key_carrying_c1_is_named_without_it(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.config import loader
+
+ buffer = StringIO()
+ monkeypatch.setattr(loader, "console", _plain_console(buffer))
+ path = tmp_path / "soup.yaml"
+ path.write_text(
+ "base: test-model\n"
+ "data:\n"
+ " train: ./data.jsonl\n"
+ "training:\n"
+ f' "{_yaml_escape(0x9B)}2Jquantizaton": 4bit\n',
+ encoding="utf-8",
+ )
+ with pytest.raises(SystemExit):
+ loader.load_config(path)
+ out = buffer.getvalue()
+ assert "2Jquantizaton" in out, out
+ assert _c1_found(out) == [], repr(out)
+
+
+class TestManifestAuthorRefusesControlCharacters:
+ @staticmethod
+ def _manifest(author: str):
+ from soup_cli.cans.schema import Manifest
+
+ return Manifest(
+ can_format_version=1,
+ name="x",
+ author=author,
+ created_at="2026-04-20",
+ base_hash="abc",
+ )
+
+ @pytest.mark.parametrize(
+ "code",
+ [0x00, 0x09, 0x0A, 0x0D, 0x1B, 0x7F, 0x80, 0x85, 0x9B, 0x9F],
+ ids=["nul", "tab", "lf", "cr", "esc", "del", "0x80", "nel", "csi", "0x9f"],
+ )
+ def test_a_control_character_is_refused_naming_the_field(self, code: int) -> None:
+ with pytest.raises(ValueError, match="author") as excinfo:
+ self._manifest(f"alice{chr(code)}x")
+ assert "control" in str(excinfo.value)
+
+ @pytest.mark.parametrize(
+ "author",
+ ["alice", "J" + chr(0xF6) + "rg", "[team] alice", "a" + chr(0xA0) + "b"],
+ ids=["ascii", "latin1-letter", "brackets", "nbsp"],
+ )
+ def test_printable_authors_are_still_accepted(self, author: str) -> None:
+ assert self._manifest(author).author == author
+
+ def test_can_inspect_names_the_refused_field(self, tmp_path, monkeypatch) -> None:
+ from soup_cli.cli import app
+ from soup_cli.commands import can as can_cmd
+
+ monkeypatch.chdir(tmp_path)
+ _write_can(
+ "c.can",
+ "can_format_version: 1\n"
+ 'name: "n"\n'
+ f'author: "a{_yaml_escape(0x9B)}2K"\n'
+ 'created_at: "2026-01-01"\n'
+ 'base_hash: "h"\n',
+ )
+ buffer = StringIO()
+ monkeypatch.setattr(can_cmd, "console", _plain_console(buffer))
+ result = runner.invoke(app, ["can", "inspect", "c.can"])
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ out = buffer.getvalue()
+ assert "Cannot inspect can" in out and "author" in out, out
+ assert _c1_found(out) == [], repr(out)
diff --git a/tests/test_terminal_output_hygiene.py b/tests/test_terminal_output_hygiene.py
new file mode 100644
index 00000000..6aecabd8
--- /dev/null
+++ b/tests/test_terminal_output_hygiene.py
@@ -0,0 +1,369 @@
+"""No module under ``src/soup_cli`` takes ``repr()`` of an escaped string.
+
+``rich.markup.escape`` -- and ``soup_cli.utils.terminal.for_terminal``, which
+calls it -- neutralises a tag by putting one backslash in front of its ``[``.
+``repr()`` doubles every backslash, so ``f"{escape(x)!r}"`` hands Rich two of
+them, which Rich reads as a literal backslash followed by a LIVE tag: the
+escape is undone by the quoting. A value containing ``[/]`` then raises
+``MarkupError`` wherever it is printed (``soup attest verify`` exited 1,
+"verifier unavailable", instead of 3 that way), and any other tag restyles
+the line. The order that works is quote first, escape second:
+``for_terminal(repr(x))``.
+
+This ratchet is deliberately narrow. In every tracked module under
+``src/soup_cli`` it flags exactly these spellings:
+
+* an f-string replacement field with the ``!r`` conversion whose value is a
+ call to an escaping helper, and ``repr(<call to an escaping helper>)``, at
+ any scope;
+* the same two applied to a plain name -- ``{name!r}`` / ``repr(name)`` --
+ when that name is assigned from a call to an escaping helper in the same
+ scope (``name = for_terminal(x)`` ... ``{name!r}``). A nested function or
+ class is its own scope, so a closure is not followed, and any such
+ assignment marks the name for the whole scope.
+
+An escaping helper is a name the module binds to ``rich.markup.escape`` or
+``soup_cli.utils.terminal.for_terminal`` (``as`` aliases and plain
+re-assignments such as ``_safe = for_terminal`` included), or the attribute
+call ``<module>.escape`` / ``<module>.for_terminal`` on a name bound to one
+of those two modules. ``re.escape`` and ``html.escape`` are never flagged.
+It does not look for values printed with no escaping at all -- that needs
+data flow, not a syntax check -- so a clean scan here says nothing about
+those.
+"""
+
+from __future__ import annotations
+
+import ast
+import subprocess
+from io import StringIO
+from pathlib import Path
+
+import pytest
+from rich.console import Console
+from rich.errors import MarkupError
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+
+_RICH_MARKUP = "rich.markup"
+_TERMINAL = "soup_cli.utils.terminal"
+
+#: module -> the attribute of it whose return value is Rich-escaped text.
+_HELPERS = {_RICH_MARKUP: "escape", _TERMINAL: "for_terminal"}
+
+
+def _tracked_python_files() -> list[Path]:
+ out = subprocess.run(
+ ["git", "ls-files", "src/soup_cli"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ return [REPO_ROOT / line for line in out.stdout.splitlines() if line.endswith(".py")]
+
+
+class _EscapingNames:
+ """What the escaping helpers are called in one module."""
+
+ def __init__(self, tree: ast.AST) -> None:
+ #: local names bound to a helper function
+ self.functions: set[str] = set()
+ #: dotted local name of a helper module -> the helper attribute
+ self.modules: dict[str, str] = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.level == 0:
+ for alias in node.names:
+ local = alias.asname or alias.name
+ if _HELPERS.get(node.module or "") == alias.name:
+ self.functions.add(local)
+ full = f"{node.module}.{alias.name}"
+ if full in _HELPERS:
+ self.modules[local] = _HELPERS[full]
+ elif isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name in _HELPERS:
+ self.modules[alias.asname or alias.name] = _HELPERS[alias.name]
+ self._follow_reassignments(tree)
+
+ def _follow_reassignments(self, tree: ast.AST) -> None:
+ assignments = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Assign) and isinstance(node.value, ast.Name)
+ ]
+ changed = True
+ while changed:
+ changed = False
+ for node in assignments:
+ if node.value.id not in self.functions:
+ continue
+ for target in node.targets:
+ if isinstance(target, ast.Name) and target.id not in self.functions:
+ self.functions.add(target.id)
+ changed = True
+
+ def is_escaping_call(self, node: ast.AST) -> bool:
+ if not isinstance(node, ast.Call):
+ return False
+ func = node.func
+ if isinstance(func, ast.Name):
+ return func.id in self.functions
+ if isinstance(func, ast.Attribute):
+ return self.modules.get(ast.unparse(func.value)) == func.attr
+ return False
+
+
+_SCOPES = (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)
+
+
+def _reprs_of(nodes, matches) -> list[int]:
+ """Lines of ``{x!r}`` / ``repr(x)`` among ``nodes`` where ``matches(x)``."""
+ lines: list[int] = []
+ for node in nodes:
+ if (
+ isinstance(node, ast.FormattedValue)
+ and node.conversion == ord("r")
+ and matches(node.value)
+ ):
+ lines.append(node.value.lineno)
+ elif (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "repr"
+ and len(node.args) == 1
+ and matches(node.args[0])
+ ):
+ lines.append(node.lineno)
+ return lines
+
+
+def _scope_nodes(scope: ast.AST) -> list[ast.AST]:
+ """Every node inside ``scope`` that does not belong to a nested scope."""
+ found: list[ast.AST] = []
+ stack = list(ast.iter_child_nodes(scope))
+ while stack:
+ node = stack.pop()
+ found.append(node)
+ if not isinstance(node, _SCOPES):
+ stack.extend(ast.iter_child_nodes(node))
+ return found
+
+
+def _escaped_names(nodes, names: _EscapingNames) -> set[str]:
+ """Names assigned from a call to an escaping helper among ``nodes``."""
+ escaped: set[str] = set()
+ for node in nodes:
+ if isinstance(node, ast.Assign) and names.is_escaping_call(node.value):
+ escaped.update(t.id for t in node.targets if isinstance(t, ast.Name))
+ elif (
+ isinstance(node, ast.AnnAssign)
+ and node.value is not None
+ and isinstance(node.target, ast.Name)
+ and names.is_escaping_call(node.value)
+ ):
+ escaped.add(node.target.id)
+ return escaped
+
+
+def repr_of_escaped_lines(source: str) -> list[int]:
+ """Line numbers of every ``repr()`` taken of escaped text.
+
+ ``{helper(...)!r}`` / ``repr(helper(...))`` anywhere, plus ``{name!r}`` /
+ ``repr(name)`` where ``name`` is assigned from a helper call in the same
+ scope.
+ """
+ tree = ast.parse(source)
+ names = _EscapingNames(tree)
+ lines = _reprs_of(ast.walk(tree), names.is_escaping_call)
+ for scope in ast.walk(tree):
+ if not isinstance(scope, _SCOPES):
+ continue
+ nodes = _scope_nodes(scope)
+ escaped = _escaped_names(nodes, names)
+ if escaped:
+ lines.extend(
+ _reprs_of(
+ nodes,
+ lambda value, escaped=escaped: (
+ isinstance(value, ast.Name) and value.id in escaped
+ ),
+ )
+ )
+ return sorted(lines)
+
+
+class TestNoReprOfEscapedTextInSrc:
+ def test_the_source_tree_has_none(self) -> None:
+ offenders: list[str] = []
+ for path in _tracked_python_files():
+ rel = path.relative_to(REPO_ROOT).as_posix()
+ try:
+ lines = repr_of_escaped_lines(path.read_text(encoding="utf-8"))
+ except SyntaxError as exc:
+ pytest.fail(f"{rel} does not parse ({exc.msg} at line {exc.lineno})")
+ offenders.extend(f"{rel}:{line}" for line in lines)
+ assert not offenders, (
+ "repr() applied to an escaped string re-activates the markup it "
+ "escaped. Quote first, escape second -- for_terminal(repr(x)) -- "
+ "instead of {escape(x)!r}:\n " + "\n ".join(offenders)
+ )
+
+ def test_the_scan_reads_the_source_tree(self) -> None:
+ """A listing that silently came back short would pass vacuously."""
+ scanned = _tracked_python_files()
+ assert len(scanned) > 300, f"only {len(scanned)} files listed"
+ names = {path.name for path in scanned}
+ assert {"attest.py", "terminal.py", "probe.py"} <= names
+
+
+class TestTheDetector:
+ """The tree is clean, so these are the proof that the scan can fail."""
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "from rich.markup import escape\nmsg = f'backend {escape(name)!r}'\n",
+ "from rich.markup import escape as _esc\nmsg = f'{_esc(name)!r}'\n",
+ "from soup_cli.utils.terminal import for_terminal\nmsg = f'{for_terminal(name)!r}'\n",
+ "from soup_cli.utils.terminal import for_terminal\n_safe = for_terminal\n"
+ "msg = f'{_safe(name)!r}'\n",
+ "from rich import markup\nmsg = f'{markup.escape(name)!r}'\n",
+ "import rich.markup\nmsg = f'{rich.markup.escape(name)!r}'\n",
+ "from soup_cli.utils import terminal\nmsg = f'{terminal.for_terminal(name)!r}'\n",
+ "from rich.markup import escape\nmsg = 'x ' + repr(escape(name))\n",
+ "def show(name):\n from rich.markup import escape\n"
+ " return f'[red]{escape(name)!r}[/]'\n",
+ ],
+ ids=[
+ "escape", "escape-alias", "for-terminal", "reassigned", "module-attribute",
+ "dotted-module", "terminal-module", "explicit-repr", "function-local-import",
+ ],
+ )
+ def test_each_spelling_is_flagged(self, source: str) -> None:
+ assert len(repr_of_escaped_lines(source)) == 1, source
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "from soup_cli.utils.terminal import for_terminal\n"
+ "msg = f'backend {for_terminal(repr(name))}'\n",
+ "from rich.markup import escape\nmsg = f'{escape(name)}'\n",
+ "msg = f'{name!r}'\n",
+ "import re\nmsg = f'{re.escape(name)!r}'\n",
+ "from html import escape\nmsg = f'{escape(name)!r}'\n",
+ "from soup_cli.utils.terminal import strip_control\n"
+ "msg = f'{strip_control(name)!r}'\n",
+ ],
+ ids=[
+ "quote-then-escape", "escape-without-repr", "plain-repr", "re-escape",
+ "html-escape", "strip-only",
+ ],
+ )
+ def test_other_spellings_are_not_flagged(self, source: str) -> None:
+ assert repr_of_escaped_lines(source) == [], source
+
+
+class TestTheDetectorFollowsAssignedNames:
+ """``name = for_terminal(x)`` followed by ``{name!r}`` in the same scope."""
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "def warn(audio):\n"
+ " from soup_cli.utils.terminal import for_terminal\n"
+ " name = for_terminal(audio)\n"
+ " return f'[yellow]Skipped {name!r}[/]'\n",
+ "from rich.markup import escape\nname = escape(value)\nmsg = 'x ' + repr(name)\n",
+ "from rich.markup import escape\nname: str = escape(value)\nmsg = f'{name!r}'\n",
+ "from rich.markup import escape\n"
+ "class Report:\n"
+ " label = escape(value)\n"
+ " line = f'{label!r}'\n",
+ ],
+ ids=["function-scope", "module-scope-explicit-repr", "annotated", "class-scope"],
+ )
+ def test_each_spelling_is_flagged(self, source: str) -> None:
+ assert len(repr_of_escaped_lines(source)) == 1, source
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "from soup_cli.utils.terminal import for_terminal\n"
+ "name = for_terminal(repr(value))\nmsg = f'{name}'\n",
+ "from rich.markup import escape\nname = escape(value)\nmsg = f'{name}'\n",
+ "from rich.markup import escape\n"
+ "def first(value):\n"
+ " name = escape(value)\n"
+ " return name\n"
+ "def second(name):\n"
+ " return f'{name!r}'\n",
+ "name = value.strip()\nmsg = f'{name!r}'\n",
+ "import re\nname = re.escape(value)\nmsg = f'{name!r}'\n",
+ "from soup_cli.utils.terminal import for_terminal\n"
+ "_safe = for_terminal\nmsg = f'{_safe!r}'\n",
+ ],
+ ids=[
+ "quoted-first", "escaped-without-repr", "other-scope", "plain-assignment",
+ "re-escape", "function-alias",
+ ],
+ )
+ def test_other_spellings_are_not_flagged(self, source: str) -> None:
+ assert repr_of_escaped_lines(source) == [], source
+
+
+class TestSitesTheRatchetFoundKeepTheirExitCode:
+ """Two of the sites this ratchet found on its first run, through the CLI.
+
+ Both refuse a path outside the working directory with exit 2 and quote
+ the path back; with ``{escape(path)!r}`` a path containing ``[/]`` raised
+ ``MarkupError`` instead, which the CLI reports as exit 1.
+ """
+
+ @pytest.mark.parametrize(
+ "module_name, argv, expected",
+ [
+ ("env", ["env", "lock", "-o", "../[/]x.lock"], "output '../[/]x.lock' is outside cwd"),
+ (
+ "tunability",
+ ["tunability", "--dataset", "../[/]d.jsonl"],
+ "dataset '../[/]d.jsonl' is outside cwd",
+ ),
+ ],
+ ids=["env-lock", "tunability"],
+ )
+ def test_a_path_containing_markup_is_quoted_literally(
+ self, tmp_path, monkeypatch, module_name, argv, expected
+ ) -> None:
+ import importlib
+
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ module = importlib.import_module(f"soup_cli.commands.{module_name}")
+ monkeypatch.chdir(tmp_path)
+ buffer = StringIO()
+ monkeypatch.setattr(module, "console", Console(file=buffer, color_system=None, width=200))
+ result = CliRunner().invoke(app, argv)
+ assert result.exit_code == 2, (buffer.getvalue(), repr(result.exception))
+ assert expected in buffer.getvalue(), buffer.getvalue()
+
+
+class TestWhyTheOrderMatters:
+ """The behaviour the ratchet exists for, shown on Rich itself."""
+
+ def test_repr_after_escape_leaves_a_live_closing_tag(self) -> None:
+ from rich.markup import escape
+
+ with pytest.raises(MarkupError):
+ Console(file=StringIO()).print(f"[yellow]backend {escape('[/]')!r} refused[/]")
+
+ def test_escape_after_repr_prints_the_quoted_text(self) -> None:
+ from soup_cli.utils.terminal import for_terminal
+
+ buffer = StringIO()
+ Console(file=buffer, color_system=None, width=200).print(
+ f"[yellow]backend {for_terminal(repr('[/]'))} refused[/]"
+ )
+ assert buffer.getvalue().strip() == "backend '[/]' refused"