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.

docs: config and CLI reference generated from the code (#1799)

Alpamys Makazhancfc27ed5a47d
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5fd219ac..d1941d1b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -195,6 +195,8 @@ Accepted runs are recorded in [`benchmarks/gpu-test-runs.md`](benchmarks/gpu-tes
> A representative sample of the suite below. Run `pytest tests/ -v` for the complete list.
+Name a new test file after the module or feature it covers (`test_<module>.py`), not after
+an issue number or a version. Existing test files keep their names.
| File | Covers |
|------|--------|
@@ -412,6 +414,13 @@ use the newest released version in `CHANGELOG.md`, prefer the PR number rather t
issue it closes, and choose `added`, `changed`, `deprecated`, `removed`, `fixed`, or
`security`.
+If you add or remove a CLI command, option, argument or a `soup.yaml` field, or change its
+type, default or bounds, run `python scripts/gen_reference_docs.py` and commit the pages
+it rewrites (`docs/cli-reference.md`, `docs/config-reference.md`); the tests fail until
+you do and name what differs. Rewording a help string or a description needs nothing:
+maintainers regenerate the wording at release. On a merge conflict in either generated
+page, keep either side and re-run `python scripts/gen_reference_docs.py`.
+
### 3. Run Tests & Lint
Before pushing, ensure everything passes:
diff --git a/changelog.d/0.76.0/1799.added.md b/changelog.d/0.76.0/1799.added.md
new file mode 100644
index 00000000..a8d5226b
--- /dev/null
+++ b/changelog.d/0.76.0/1799.added.md
@@ -0,0 +1,12 @@
+- **Two reference pages generated from the code: `docs/config-reference.md` lists every
+ `soup.yaml` key with its type, default, constraints and description, and
+ `docs/cli-reference.md` lists every command, option and argument with its type, default,
+ whether it is required, and its help (#1799).** `python scripts/gen_reference_docs.py` renders
+ both from `SoupConfig` and the live command tree. The test suite checks that the pages still
+ state what the code does (keys, types, defaults and constraints; commands and their
+ parameters) and names each one that differs. Rewording a help string or a description needs
+ no regeneration; `SOUP_DOCS_EXACT=1` adds the byte-exact check that a release runs.
+ `CONTRIBUTING.md` says when to regenerate. Found on the way: the help of `soup eval against`
+ sent the reader to `soup runs list`, a subcommand that does not exist. It now names
+ `soup runs`, and a test resolves every `soup ...` invocation written in a help string or a
+ field description against the live CLI.
diff --git a/docs/README.md b/docs/README.md
index 90996a3d..5d7e4b54 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -18,6 +18,8 @@ feature reference — every `soup` capability, grouped by area.
| [Compliance & governance quickstart](compliance.md) | HIPAA/SOC2/EU-AI-Act/SR-11-7 `init` templates, provenance (BOM/attest/repro-receipt), audit log, air-gap, model-card autogen (`soup card`), CI gate (`soup ci init`) |
| [Backends, platform & ops](backends-and-ops.md) | MLX/Unsloth backends, Modal cloud GPU training, alternative hubs, HF Hub integration, autopilot, experiment tracking, plan/apply, env lockfiles, hardware-fit, completions, plugins, utility commands |
| [Command reference](commands.md) | The full `soup` command list |
+| [CLI reference](cli-reference.md) | Every command with every option and argument: type, default, whether it is required — generated from the code |
+| [Config reference](config-reference.md) | Every `soup.yaml` key: type, default, bounds and allowed values — generated from the schema |
| [Supported models & extras](models.md) | Recommended model families, the VRAM size guide, the pip extras matrix |
| [Issue difficulty](issue-difficulty.md) | How issues are rated 1-10 and what each level means |
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
new file mode 100644
index 00000000..a982c135
--- /dev/null
+++ b/docs/cli-reference.md
@@ -0,0 +1,3722 @@
+# CLI reference
+
+[← Back to the docs index](README.md)
+
+> **Generated file — do not edit by hand.**
+> It is rendered from the live Typer command tree (`soup_cli.cli:app`). After adding or
+> removing a command, an option or an argument, or changing its type, its default or
+> whether it is required, run `python scripts/gen_reference_docs.py` and commit the
+> result; the test suite fails until the page matches. Help text is refreshed when a
+> release is cut, so between releases the wording here can trail the code.
+
+Every `soup` command with every option and argument. For a one-line-per-task listing
+see the [Command reference](commands.md); for the keys of `soup.yaml` see the
+[Config reference](config-reference.md).
+
+How to read a table:
+
+- **Name** is an option with its short form, or an argument in capitals (`PATH`;
+ `PATH...` takes any number of values). `--flag` / `--no-flag` is one switch with
+ both spellings.
+- **Type**: a `flag` takes no value; `text`, `integer`, `float` and `path` take one;
+ a `repeatable` option may be given more than once.
+- **Default** is the value used when the option is left out (`on` / `off` for a flag);
+ an empty cell means there is none. *(set at runtime)* marks a default computed on
+ the machine, which this page does not print.
+- **Required** says `yes` when the command refuses to run without it.
+
+`--help` works on every command and is not listed. Global options go before the
+command name: `soup --verbose train --config soup.yaml`.
+
+## Global options
+
+Usage: `soup [OPTIONS] <command> [ARGS]...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--verbose`, `-V` | flag | off | | Show full traceback on errors |
+| `--log-level` | text | `normal` | | Logging tier: quiet \| normal \| verbose \| debug |
+| `--no-audit-log` | flag | off | | Disable the local HIPAA/SOC2 audit log for this invocation (also via SOUP_NO_AUDIT_LOG=1). Default: a one-line record per command under \~/.soup/audit.jsonl. v0.71.3. |
+| `--no-telemetry` | flag | off | | Opt-out of anonymous hardware-only telemetry for this run. |
+| `--install-completion` | flag | | | Install shell completion for the current shell. |
+| `--show-completion` | flag | | | Print the shell completion script, to copy or customise it. |
+
+## Commands
+
+| Command | Summary |
+|---|---|
+| [`soup ab`](#soup-ab) | Two-sided mSPRT sequential A/B harness on latency / judge_score / retry_rate: reports whether the treatment is better or worse, valid under re-running after every new row (v0.63.0). |
+| [`soup adapters`](#soup-adapters) | Adapter management: list, info, compare LoRA adapters. |
+| [`soup advise`](#soup-advise) | Pre-flight decision: PROMPT_ENG / RAG / SFT / DPO / GRPO. Run BEFORE you spend 8 hours on a GPU (v0.54.0). |
+| [`soup agent`](#soup-agent) | Agent Forge: spec -> tool-calling dataset / train / eval (v0.46.0). |
+| [`soup airgap-bundle`](#soup-airgap-bundle) | Build a signed tarball with model + datasets + wheels + kernels (v0.60.0). |
+| [`soup apple-adapter`](#soup-apple-adapter) | Convert / sign HF / MLX / Apple FoundationModels adapters (v0.68.0). |
+| [`soup apply`](#soup-apply) | Execute the planned training run, refusing on drift between soup.yaml and soup.tfstate (v0.64.0). |
+| [`soup attest`](#soup-attest) | In-toto + SLSA-3 attestations per Soup Can stage (v0.59.0). |
+| [`soup audit-log`](#soup-audit-log) | HIPAA/SOC2-shaped JSONL audit log: tail + rotate (v0.59.0). |
+| [`soup autopilot`](#soup-autopilot) | Autopilot: give model+data+goal, Soup picks optimal hyperparameters. |
+| [`soup bench`](#soup-bench) | Benchmark a model: inference speed (infer, the default) or training (train). |
+| [`soup bom`](#soup-bom) | CycloneDX ML-BOM + SPDX AI bill-of-materials emitter (v0.59.0). |
+| [`soup build`](#soup-build) | dbt-for-SFT DAG: validate, plan, and materialise dataset transforms. |
+| [`soup can`](#soup-can) | Soup Cans: pack/inspect/verify/fork shareable .can artifacts. |
+| [`soup card`](#soup-card) | Generate a HuggingFace model card from a registry entry. |
+| [`soup chat`](#soup-chat) | Chat with a fine-tuned model in the terminal. |
+| [`soup ci`](#soup-ci) | Fine-tuning CI: init a PR gate workflow. |
+| [`soup compile`](#soup-compile) | Compile a DSPy / GEPA prompt program against an eval suite (v0.68.0). |
+| [`soup compile-tools`](#soup-compile-tools) | Compile / optimize tool schemas + descriptions (v0.68.0). |
+| [`soup completions`](#soup-completions) | Emit a bash / zsh / fish completion script. Use with `eval "$(soup completions bash)"` (v0.64.0). |
+| [`soup cost`](#soup-cost) | Estimate training cost in USD across cloud providers. |
+| [`soup data`](#soup-data) | Dataset tools: inspect, convert, merge, dedup, validate, stats. |
+| [`soup delinearize-llama4`](#soup-delinearize-llama4) | Delinearize Llama 4 fused expert weights to 3-D form. |
+| [`soup deploy`](#soup-deploy) | Deploy models: Ollama integration (deploy, list, remove). |
+| [`soup diagnose`](#soup-diagnose) | Post-training report card: forgetting / refusal / format / mode_collapse / memorization / contamination (v0.56.0). |
+| [`soup diff`](#soup-diff) | Compare outputs of two models side-by-side on the same prompts. |
+| [`soup distill-prompt`](#soup-distill-prompt) | Distill prompt-heavy traces into a small FT plan (v0.68.0). |
+| [`soup doctor`](#soup-doctor) | Check system dependencies, GPU, and compatibility. |
+| [`soup draft`](#soup-draft) | Train + measure a speculative-decoding draft model: distil your tuned model into a tiny draft, then serve it with --auto-spec (v0.71.33). |
+| [`soup drift-alarm`](#soup-drift-alarm) | Rolling-KL drift alarm on output-token distribution with optional Slack/Discord webhook (v0.63.0). |
+| [`soup edit`](#soup-edit) | Knowledge editing (ROME / MEMIT / AlphaEdit) - patch facts without re-training (v0.61.0). |
+| [`soup env`](#soup-env) | Hermetic env lockfile + ABI drift detection (v0.64.0). |
+| [`soup eval`](#soup-eval) | Evaluate models: benchmarks, custom evals, LLM judge, leaderboard. |
+| [`soup expect`](#soup-expect) | Run an expectations suite against a JSONL dataset. |
+| [`soup export`](#soup-export) | Export a model to GGUF, ONNX, TensorRT-LLM, AWQ, GPTQ, or TorchAO format. |
+| [`soup fetch`](#soup-fetch) | Fetch a ready-to-edit example config from the bundled catalog. |
+| [`soup history`](#soup-history) | Show the lineage tree for all entries with a given name. |
+| [`soup infer`](#soup-infer) | Run batch inference on a JSONL file of prompts. |
+| [`soup ingest`](#soup-ingest) | Universal trace importer: Langfuse / LangSmith / Helicone / OpenPipe / OTel / OpenAI Stored Completions (v0.63.0). |
+| [`soup init`](#soup-init) | Create a new soup.yaml config interactively or from a template. |
+| [`soup iterative-dpo`](#soup-iterative-dpo) | Iterative DPO sample, score, pair, and train loop. |
+| [`soup license-advisor`](#soup-license-advisor) | Recommend a license-clean base for a deploy target (b2c / defense / embedded) + flag downstream risk (v0.64.0). |
+| [`soup llama`](#soup-llama) | Proxy to llama.cpp binaries (cli / mtmd-cli / gguf-split / server). |
+| [`soup local-rl`](#soup-local-rl) | Personal-LLM flywheel daemon (init / status / record / harvest / train) (v0.68.0). |
+| [`soup lock`](#soup-lock) | Shared run lockfile (write / show / check). |
+| [`soup loop`](#soup-loop) | Data flywheel: traces -> preference pairs -> DPO -> gate -> canary deploy -> rollback, all from the CLI (v0.58.0). |
+| [`soup mcp`](#soup-mcp) | Model Context Protocol server - drive Soup from any MCP client (v0.71.28). |
+| [`soup merge`](#soup-merge) | Merge a LoRA adapter with its base model into a full model. |
+| [`soup merge-sharded-fsdp-weights`](#soup-merge-sharded-fsdp-weights) | Consolidate FSDP shard files into a single safetensors file. |
+| [`soup migrate`](#soup-migrate) | Import a config from LLaMA-Factory, Axolotl, or Unsloth notebook. |
+| [`soup monitor`](#soup-monitor) | Live GPU monitor: Util / Temp / VRAM / Power per GPU. |
+| [`soup plan`](#soup-plan) | Render a pre-flight training plan (cost / ETA / SHA / VRAM) and write soup.tfstate for `soup apply` to consult (v0.64.0). |
+| [`soup plugins`](#soup-plugins) | Discover, list, enable, and disable Soup plugins. |
+| [`soup probe`](#soup-probe) | Activation probes: sleeper-agent defection / honesty / misuse / pairwise interference / SAE feature diff / probe pack (v0.66.0, truth+harm v0.71.8). |
+| [`soup profile`](#soup-profile) | Estimate memory, speed, and GPU requirements BEFORE training. |
+| [`soup prune-prompt`](#soup-prune-prompt) | Detect + strip a shared system-prompt prefix across training data so the FT model internalises it (v0.63.0). |
+| [`soup push`](#soup-push) | Push a trained model to HuggingFace Hub (or alternate hub). |
+| [`soup quantize`](#soup-quantize) | Quantize a model - ergonomic alias for `soup export --format <to>`. |
+| [`soup quickstart`](#soup-quickstart) | Run a complete demo: create sample data, config, and train. |
+| [`soup ra-dit`](#soup-ra-dit) | RA-DIT two-stage orchestrator: retriever -> generator (v0.71.10). |
+| [`soup recipes`](#soup-recipes) | Ready-made configs: list, show, use, search recipes for popular models. |
+| [`soup registry`](#soup-registry) | Model Registry: push, list, show, diff, search, promote, delete. |
+| [`soup reward`](#soup-reward) | Synthesize a deterministic reward verifier from reference outputs, with a calibration report that refuses degenerate verifiers (v0.71.40). |
+| [`soup rewind`](#soup-rewind) | Name the dataset rows behind a loss spike, from the training flight recorder. |
+| [`soup runs`](#soup-runs) | Experiment tracking: list, show, compare runs. |
+| [`soup serve`](#soup-serve) | Start a local inference server with OpenAI-compatible API. |
+| [`soup ship`](#soup-ship) | SHIP / DON'T SHIP verdict after fine-tuning: task win AND no catastrophic forgetting, fused into one decision (v0.71.25). |
+| [`soup shrink`](#soup-shrink) | Depth-prune a model (drop the least-important contiguous layer block by residual angular distance) + optional distill-heal (v0.71.29). |
+| [`soup spectrum`](#soup-spectrum) | Spectrum SNR scan for targeted training (v0.71.23). |
+| [`soup steer`](#soup-steer) | Activation steering (CAA / ITI / RepE) - inference-time intervention without retraining (v0.62.0). |
+| [`soup sweep`](#soup-sweep) | Run hyperparameter sweep: grid or random search over training parameters. |
+| [`soup tokenizer`](#soup-tokenizer) | Tokenizer tools: train a BPE tokenizer from JSONL (v0.53.9). |
+| [`soup train`](#soup-train) | Start training from a soup.yaml config. |
+| [`soup tui`](#soup-tui) | Full-screen terminal dashboard: list runs, inspect metrics, tail logs. |
+| [`soup tunability`](#soup-tunability) | Probe-train 6-10 small bases on a held-out slice + report Pareto frontier of (eval delta, train cost, license) (v0.64.0). |
+| [`soup ui`](#soup-ui) | Launch the Soup Web UI. |
+| [`soup version`](#soup-version) | Show Soup CLI version. |
+| [`soup why`](#soup-why) | Explain training anomalies for a run in plain English. |
+
+## `soup ab`
+
+Two-sided mSPRT sequential A/B harness on latency / judge_score / retry_rate: reports whether the treatment is better or worse, valid under re-running after every new row (v0.63.0).
+
+Usage: `soup ab [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | JSONL with {arm, &lt;metric>} per row. |
+| `--metric` | text | | yes | Metric: latency \| judge_score \| retry_rate. |
+| `--alpha` | float | `0.05` | | Error rate (0, 1) of both verdicts, kept for a test re-run after every new row, at any number of rows: with no difference the test ends in reject_h0, and with a true difference of --effect-size or more in accept_h0, each in at most this share of runs. |
+| `--beta` | float | | | Retired (#1418): ignored, with a warning. --alpha now bounds wrong accept_h0 verdicts too. |
+| `--effect-size` | float | `0.1` | | Minimum detectable difference in means. |
+| `--slack-url` | text | | | Optional Slack webhook URL — POSTed on a reject_h0 / accept_h0 decision (not on continue). SSRF-validated. |
+| `--discord-url` | text | | | Optional Discord webhook URL — POSTed on a reject_h0 / accept_h0 decision (not on continue). SSRF-validated. |
+
+## `soup adapters`
+
+Adapter management: list, info, compare LoRA adapters.
+
+Usage: `soup adapters <command> [ARGS]...`
+
+Subcommands:
+
+- [`arithmetic`](#soup-adapters-arithmetic)
+- [`audit`](#soup-adapters-audit)
+- [`bisect`](#soup-adapters-bisect)
+- [`blame`](#soup-adapters-blame)
+- [`branch`](#soup-adapters-branch)
+- [`branches`](#soup-adapters-branches)
+- [`check`](#soup-adapters-check)
+- [`check-safetensors`](#soup-adapters-check-safetensors)
+- [`checkout`](#soup-adapters-checkout)
+- [`compare`](#soup-adapters-compare)
+- [`diff`](#soup-adapters-diff)
+- [`info`](#soup-adapters-info)
+- [`list`](#soup-adapters-list)
+- [`merge`](#soup-adapters-merge)
+- [`pr`](#soup-adapters-pr)
+- [`scan`](#soup-adapters-scan)
+- [`sign`](#soup-adapters-sign)
+- [`verify`](#soup-adapters-verify)
+
+### `soup adapters arithmetic`
+
+Task-vector arithmetic over LoRA adapters (add / scale / negate) (v0.71.34).
+
+Usage: `soup adapters arithmetic [OPTIONS] EXPRESSION`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `EXPRESSION` | text | | yes | Task-vector expression, e.g. "coder + 0.5\*math - toxic". |
+| `--adapter` | text, repeatable | | yes | name=path mapping for each adapter referenced in the expression (repeatable). Names use \[A-Za-z0-9\_.-]. |
+| `--output`, `-o` | text | | yes | Output directory for the merged adapter |
+| `--rank` | integer, at least 1 | | | Truncated-SVD rank cap. Passing it routes the merge through the exact concat path and caps the output rank at N via SVD (works for same-rank AND mixed-rank inputs). Without it, mixed-rank inputs keep the full concatenated rank (Σ rᵢ) and same-rank inputs use the fast element-wise path. |
+| `--allow-unscanned` | flag | off | | Skip the backdoor-scan gate (v0.71.2 #192). By default refuses an input whose `adapters scan` returns FAIL or cannot be scanned. |
+| `--allow-cross-base` | flag | off | | Allow combining adapters trained on different base models. By default a base-model mismatch is refused (task vectors from different bases are not comparable). |
+
+### `soup adapters audit`
+
+Check whether a finished run did what its config asked for (#762).
+
+Usage: `soup adapters audit [OPTIONS] ADAPTER`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER` | text | | yes | Path to adapter directory |
+| `--config`, `-c` | text | | yes | soup.yaml the run was started from |
+| `--json` | flag | off | | Emit machine-readable JSON |
+
+### `soup adapters bisect`
+
+Binary-search a training history to find the first failing checkpoint.
+
+Usage: `soup adapters bisect [OPTIONS] HISTORY...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `HISTORY...` | text, any number | | yes | Ordered checkpoint identifiers (oldest first). At least 2. Example: `soup adapters bisect ckpt-100 ckpt-200 ckpt-300 ckpt-400` |
+| `--eval-command` | text | | yes | Shell command template; '{ckpt}' is replaced with each checkpoint id. Exit code 0 means PASS, non-zero means FAIL. Example: 'soup eval custom --model {ckpt} --tasks tasks.jsonl' |
+| `--plan-only` | flag | off | | Print the plan and exit without running the bisect |
+| `--output`, `-o` | text | | | Write JSON result to path |
+
+### `soup adapters blame`
+
+Attribute weight movement to dataset rows via DataInf influence (v0.66.0).
+
+Usage: `soup adapters blame [OPTIONS] ADAPTER_DIR`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER_DIR` | text | | yes | Path to trained adapter |
+| `--dataset` | text | | yes | Training JSONL the adapter was built on |
+| `--layer` | text | | yes | Layer to attribute (e.g. q_proj.7) |
+| `--budget` | text | `4h` | | Wall-clock budget (e.g. 4h, 30m) |
+| `--shards` | integer, 2 to 100 | `10` | | Number of dataset shards for leave-one-out |
+| `--top-k` | integer, 1 to 10000 | `50` | | Number of top influencer rows to report (v0.66.0) |
+| `--plan-only` | flag | off | | Print plan and exit without running |
+| `--output`, `-o` | text | | | Write JSON blame result to path (v0.66.0) |
+
+### `soup adapters branch`
+
+Snapshot a training environment as a comparable branch (v0.57.0).
+
+Usage: `soup adapters branch [OPTIONS] NAME`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME` | text | | yes | Branch name (alphanumeric + .\_-) |
+| `--config`, `-c` | text | | | Path to soup.yaml (required unless --from-registry) |
+| `--base` | text | | | Base model id (required unless --from-registry) |
+| `--dataset` | text | | | Training dataset path (optional) |
+| `--attach-to-registry` | text | | | Registry entry id/ref to attach this branch pointer to as a branch_ref artifact + link via registry_entry_id (v0.71.4). |
+| `--from-registry` | text | | | Derive config + base_model + dataset hash from a Registry entry instead of --config/--base (v0.71.4). |
+
+### `soup adapters branches`
+
+List all snapshotted branches (v0.57.0).
+
+Usage: `soup adapters branches`
+
+Takes no options or arguments.
+
+### `soup adapters check`
+
+Audit whether an adapter is trained: Frobenius delta, zero B, inner keys (#1721).
+
+Usage: `soup adapters check [OPTIONS] ADAPTER`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER` | text | | yes | Path to adapter directory |
+| `--json` | flag | off | | Emit machine-readable JSON document |
+
+### `soup adapters check-safetensors`
+
+Refuse pickle / PyTorch-classic weights at the boundary (v0.60.0).
+
+Usage: `soup adapters check-safetensors [OPTIONS] ADAPTER`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER` | text | | yes | Path to adapter / model directory |
+| `--strict` | flag | off | | Exit 3 on any unsafe (pickle / PyTorch-classic) weight file |
+
+### `soup adapters checkout`
+
+Restore a snapshotted branch's config into cwd (v0.57.0).
+
+Usage: `soup adapters checkout [OPTIONS] NAME`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME` | text | | yes | Branch name to check out |
+| `--output`, `-o` | text | `soup.yaml` | | Where to write the restored config |
+
+### `soup adapters compare`
+
+Compare two LoRA adapters side-by-side.
+
+Usage: `soup adapters compare ADAPTER1 ADAPTER2`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER1` | text | | yes | Path to first adapter |
+| `ADAPTER2` | text | | yes | Path to second adapter |
+
+### `soup adapters diff`
+
+Per-layer ΔW Frobenius diff + effective-rank drift (v0.57.0).
+
+Usage: `soup adapters diff [OPTIONS] ADAPTER_A ADAPTER_B`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER_A` | text | | yes | Path to first adapter |
+| `ADAPTER_B` | text | | yes | Path to second adapter |
+| `--top-k` | integer, 1 to 200 | `10` | | Number of top changed projections to report |
+| `--format` | text | `table` | | Output format: table \| json \| markdown |
+| `--output`, `-o` | text | | | Write report to file (json/markdown only) |
+
+### `soup adapters info`
+
+Show detailed metadata for a LoRA adapter.
+
+Usage: `soup adapters info ADAPTER`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER` | text | | yes | Path to adapter directory |
+
+### `soup adapters list`
+
+Scan a directory for LoRA adapters and list them.
+
+Usage: `soup adapters list [DIRECTORY]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DIRECTORY` | text | `.` | | Directory to scan for adapters (recursive) |
+
+### `soup adapters merge`
+
+Merge LoRA adapters via linear / ties / dare / svd (v0.57.0, v0.60.0 license gate).
+
+Usage: `soup adapters merge [OPTIONS] ADAPTERS...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTERS...` | text, any number | | yes | Two or more adapter paths to merge |
+| `--output`, `-o` | text | | yes | Output directory for merged adapter |
+| `--strategy` | text | `linear` | | linear \| ties \| dare \| svd \| cmaes |
+| `--weights` | text | | | Comma-separated weights (default: equal) |
+| `--density` | float | `0.2` | | Trim density for ties/dare in (0, 1] |
+| `--seed` | integer | `0` | | Random seed for dare / cmaes |
+| `--rank` | integer | | | SVD rank (svd strategy only) |
+| `--eval` | text | | | Path to eval suite (required for --strategy cmaes). Used by the evolutionary loop to score candidate merges. |
+| `--budget` | text | `1h` | | Wall-clock budget for cmaes (60s..24h, e.g. 1h, 30m) |
+| `--population` | integer, 2 to 256 | `8` | | cmaes population size per generation |
+| `--max-generations` | integer, 1 to 10000 | `20` | | cmaes generation cap |
+| `--license` | text, repeatable | | | SPDX license id per adapter (repeatable; same order as inputs). v0.60.0 refuses merges with conflicting licenses unless --license-override &lt;reason> is passed. |
+| `--license-override` | text | | | Free-text justification (>=8 chars) to merge across a license conflict. Logged to the audit log for legal review (v0.71.2). |
+| `--allow-unscanned` | flag | off | | Skip the v0.71.2 backdoor-scan gate. By default `adapters merge` refuses to merge an input whose `adapters scan` returns FAIL (or that cannot be scanned). |
+| `--canary` | text | | | Canary-suite JSON to compute a live OK/MINOR/MAJOR verdict for the merged adapter vs the first input (v0.71.4 #172). Shape: {"baseline_scores": \[...], "candidate_scores": \[...]}. |
+| `--strict-verdict` | flag | off | | Exit 2 when the canary verdict is MAJOR (CI gate). |
+
+### `soup adapters pr`
+
+Render a GitHub-style PR for an adapter.
+
+Usage: `soup adapters pr [OPTIONS] TITLE`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `TITLE` | text | | yes | Short PR title (e.g. 'add-support-tone') |
+| `--base-sha` | text | | yes | 64-hex SHA of the base model |
+| `--adapter` | text | | yes | Path to candidate adapter |
+| `--eval` | text | | | Path to JSON eval-deltas: list of {"metric": ..., "baseline": ..., "candidate": ...} |
+| `--samples` | text | | | Path to JSON sample diffs: list of {"prompt": ..., "baseline_output": ..., "candidate_output": ...} |
+| `--dataset-diff` | text | | | Path to a text file containing the dataset diff |
+| `--output`, `-o` | text | | | Write rendered Markdown to path (default: stdout) |
+| `--format`, `-f` | text | `markdown` | | markdown \| json |
+| `--push` | text | | | Post the rendered Markdown as a comment on a GitHub PR: owner/repo#N (e.g. MakazhanAlpamys/Soup#42). Auth via GITHUB_TOKEN / GH_TOKEN (v0.71.4). |
+
+### `soup adapters scan`
+
+Spectral backdoor scan over LoRA adapter weights (v0.60.0).
+
+Usage: `soup adapters scan [OPTIONS] ADAPTER`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER` | text | | yes | Path to adapter directory |
+| `--format` | text | `text` | | Output format: text \| json |
+
+### `soup adapters sign`
+
+Compute manifest + write ``.soup-signature.json`` (v0.60.0, ed25519 v0.71.2).
+
+Usage: `soup adapters sign [OPTIONS] ADAPTER`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER` | text | | yes | Path to adapter directory |
+| `--backend` | text | `unsigned` | | Signing backend: unsigned \| ed25519 \| sigstore (keyless OIDC) |
+| `--key` | text | | | ed25519 private-key PEM path (or set SOUP_SIGNING_KEY). |
+| `--generate-key` | text | | | Generate a fresh ed25519 keypair, persist the private key here (PEM, 0600), and sign with it. |
+| `--interactive-oidc` | flag | off | | Allow Sigstore browser OIDC when no ambient credential exists. Off by default so headless runners fail instead of hanging. |
+
+### `soup adapters verify`
+
+Verify ``.soup-signature.json`` against current files (v0.60.0, ed25519 v0.71.2).
+
+Usage: `soup adapters verify [OPTIONS] ADAPTER`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ADAPTER` | text | | yes | Path to adapter directory |
+| `--strict` | flag | off | | Exit 3 on any verification failure (CI-friendly) |
+| `--public-key` | text | | | Trusted ed25519 public-key PEM. When set, the embedded signing key must match it and requires an ed25519 signature (genuine authentication, not just consistency). |
+| `--cert-identity` | text | | | Trusted Sigstore certificate identity (SAN). Requires --cert-oidc-issuer and is required for sigstore-signed adapters. |
+| `--cert-oidc-issuer` | text | | | Trusted OIDC issuer. Required together with --cert-identity. |
+
+## `soup advise`
+
+Pre-flight decision: PROMPT_ENG / RAG / SFT / DPO / GRPO. Run BEFORE you spend 8 hours on a GPU (v0.54.0).
+
+Usage: `soup advise <command> [ARGS]...`
+
+Subcommands:
+
+- [`compare`](#soup-advise-compare)
+- [`explain`](#soup-advise-explain)
+- [`run`](#soup-advise-run)
+
+### `soup advise compare`
+
+Show prior verdicts from advise_history.jsonl.
+
+Usage: `soup advise compare [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--limit` | integer, 1 to 1000 | `20` | | How many recent verdicts to show. |
+
+### `soup advise explain`
+
+Print the rubric, weights, and evidence trail of the last verdict.
+
+Usage: `soup advise explain`
+
+Takes no options or arguments.
+
+### `soup advise run`
+
+Render a Verdict for the supplied dataset.
+
+Usage: `soup advise run [OPTIONS] DATA`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DATA` | text | | yes | Path to JSONL dataset to advise on (must stay under cwd). |
+| `--goal`, `-g` | text | | | One-line goal statement: e.g. "make our chatbot more concise". Sharpens task classification. |
+| `--probe` | flag | off | | Also run an ROI probe (zero/few-shot + RAG baseline + N-step LoRA). Heuristic by default; pass --probe-model &lt;id> for a LIVE probe that loads the model + LoRA-trains on a tiny held-out slice. |
+| `--probe-model` | text | | | Base model id for a LIVE probe (e.g. HuggingFaceTB/SmolLM2-135M). When set, the probe loads this model, scores zero/few-shot, LoRA-trains, and measures base-model proximity. Implies --probe. |
+| `--probe-device` | text | | | Device for the live probe (cuda / cpu). Auto-detected when omitted. |
+| `--record` | flag | off | | Append this verdict to advise_history.jsonl with accepted=True. Omit --record to skip. Stored under \~/.soup/. |
+| `--notes` | text | `""` | | Optional notes attached to the recorded verdict (&lt;=4096 chars). |
+
+## `soup agent`
+
+Agent Forge: spec -> tool-calling dataset / train / eval (v0.46.0).
+
+Usage: `soup agent <command> [ARGS]...`
+
+Subcommands:
+
+- [`eval`](#soup-agent-eval)
+- [`synth`](#soup-agent-synth)
+- [`train`](#soup-agent-train)
+
+### `soup agent eval`
+
+Score predicted tool-calls against the spec's tool catalog.
+
+Usage: `soup agent eval [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--spec`, `-s` | text | | yes | API spec (under cwd). |
+| `--predictions`, `-p` | text | | yes | JSONL of model outputs, one per line, with at minimum {tool: &lt;name>, arguments: {...}}. |
+| `--sandbox` | flag | off | | Execute each heuristic-passing prediction against a sandboxed mock of the endpoint (v0.71.18 #110): classify ok / tool_error / timeout / arg_error. Strong isolation is POSIX-only (reduced isolation on Windows; a friendly advisory is printed). |
+
+### `soup agent synth`
+
+Parse an API spec and synthesise a tool-calling SFT dataset.
+
+Usage: `soup agent synth [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--spec`, `-s` | text | | yes | Path to OpenAPI / MCP / GraphQL spec (YAML or JSON, under cwd). |
+| `--output`, `-o` | text | `agent_dataset.jsonl` | | Where to write the synthesised JSONL dataset (under cwd). |
+| `--kind`, `-k` | text | | | Spec kind override: openapi \| mcp \| graphql. Auto-detected if omitted. |
+| `--examples-per-endpoint`, `-n` | integer, 1 to 32 | `1` | | Number of synthetic rows to emit per endpoint. |
+
+### `soup agent train`
+
+One-shot wrapper: synth + planned soup train invocation (printed).
+
+Usage: `soup agent train [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--spec`, `-s` | text | | yes | API spec (under cwd). |
+| `--base`, `-b` | text | | yes | Base model HF repo id to fine-tune. |
+| `--dataset-out` | text | `agent_dataset.jsonl` | | Where the synth step writes its dataset (under cwd). |
+| `--output-dir` | text | `./agent_train_output` | | Where the planned soup train run will store checkpoints. |
+| `--examples-per-endpoint`, `-n` | integer, 1 to 32 | `4` | | |
+
+## `soup airgap-bundle`
+
+Build a signed tarball with model + datasets + wheels + kernels (v0.60.0).
+
+Usage: `soup airgap-bundle [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--output`, `-o` | text | | yes | Output tarball path (cwd-contained) |
+| `--model` | text | | yes | Path to model directory |
+| `--dataset` | text, repeatable | | | Dataset directory (repeatable) |
+| `--wheel` | text, repeatable | | | Wheel directory (repeatable) |
+| `--kernel` | text, repeatable | | | CUDA / kernel directory (repeatable) |
+| `--bundle-size-cap` | float | `100.0` | | Cap in GiB (default 100). Build aborts when exceeded. |
+| `--repro-receipt` | text | | | Embed a reproducibility receipt JSON (from `soup train --repro-receipt`) into the bundle. Auto-detected from &lt;model>/repro-receipt.json when not given. v0.71.3 #188. |
+
+## `soup apple-adapter`
+
+Convert / sign HF / MLX / Apple FoundationModels adapters (v0.68.0).
+
+Usage: `soup apple-adapter [OPTIONS] SOURCE`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `SOURCE` | text | | yes | Source adapter directory |
+| `--direction` | text | `hf-to-mlx` | | Allowed: hf-to-apple, hf-to-mlx, mlx-to-apple, mlx-to-hf |
+| `--output`, `-o` | text | | yes | Output directory |
+| `--sign` / `--no-sign` | flag | off | | Sign converted adapter via v0.60 Merkle-root signing. |
+| `--plan-only` | flag | off | | Render plan + exit 0 (no live conversion). |
+
+## `soup apply`
+
+Execute the planned training run, refusing on drift between soup.yaml and soup.tfstate (v0.64.0).
+
+Usage: `soup apply [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--config`, `-c` | text | `soup.yaml` | | Path to soup.yaml. |
+| `--state` | text | `soup.tfstate` | | Path to the state file written by `soup plan`. |
+| `--dry-run` | flag | off | | Verify drift and exit without invoking training. |
+
+## `soup attest`
+
+In-toto + SLSA-3 attestations per Soup Can stage (v0.59.0).
+
+Usage: `soup attest <command> [ARGS]...`
+
+Subcommands:
+
+- [`emit`](#soup-attest-emit)
+- [`verify`](#soup-attest-verify)
+
+### `soup attest emit`
+
+Emit a per-stage in-toto/SLSA-3 attestation.
+
+Usage: `soup attest emit [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--stage` | text | | yes | Stage: extract / train / eval / export / publish. |
+| `--subject` | text | | yes | Artefact name. |
+| `--sha` | text | | yes | 64-hex SHA-256 of the artefact. |
+| `--builder` | text | `soup-cli` | | Builder identity (default: soup-cli). |
+| `--invocation` | text | | | Free-form invocation marker (e.g. command line). |
+| `--sign` | text | `unsigned` | | Signature backend: unsigned (default) \| ed25519 \| sigstore (keyless OIDC + Fulcio/Rekor). |
+| `--key` | text | | | ed25519 private-key PEM path (or set SOUP_SIGNING_KEY). |
+| `--output`, `-o` | text | | | Output file path (cwd-contained). |
+| `--attach-to-registry` | text | | | Attach the emitted attestation statement to a registry entry id (needs --output). |
+| `--interactive-oidc` | flag | off | | Allow Sigstore browser OIDC when no ambient credential exists. Off by default so headless runners fail instead of hanging. |
+
+### `soup attest verify`
+
+Verify an ed25519 or Sigstore-signed attestation.
+
+Usage: `soup attest verify [OPTIONS] STATEMENT`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `STATEMENT` | text | | yes | Path to the in-toto Statement JSON. |
+| `--signature`, `-s` | text | | yes | Path to the .sig JSON sidecar written by `attest emit --sign`. |
+| `--public-key` | text | | | Trusted ed25519 public-key PEM. When set, the embedded key must match it (genuine authentication). |
+| `--cert-identity` | text | | | Trusted Sigstore certificate identity (SAN). Requires --cert-oidc-issuer and is required for sigstore-signed attestations. |
+| `--cert-oidc-issuer` | text | | | Trusted OIDC issuer. Required together with --cert-identity. |
+
+## `soup audit-log`
+
+HIPAA/SOC2-shaped JSONL audit log: tail + rotate (v0.59.0).
+
+Usage: `soup audit-log <command> [ARGS]...`
+
+Subcommands:
+
+- [`rotate`](#soup-audit-log-rotate)
+- [`tail`](#soup-audit-log-tail)
+
+### `soup audit-log rotate`
+
+Force a rotation pass at the current cap.
+
+Usage: `soup audit-log rotate [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--path` | text | | | Override audit log path. |
+| `--cap-mb` | integer, 1 to 10000 | `100` | | Rotation cap in MiB. |
+
+### `soup audit-log tail`
+
+Show the most recent audit records.
+
+Usage: `soup audit-log tail [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--limit` | integer | `50` | | Max records to show (1-100000). |
+| `--path` | text | | | Override audit log path (default: \$SOUP_AUDIT_LOG_PATH or \~/.soup/audit.jsonl). |
+| `--json` | flag | off | | Emit raw JSONL instead of a table. |
+
+## `soup autopilot`
+
+Autopilot: give model+data+goal, Soup picks optimal hyperparameters.
+
+Usage: `soup autopilot [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | | Base model (HF model id) |
+| `--data`, `-d` | text | | | Dataset path (JSONL) |
+| `--goal`, `-g` | text | | | Goal: chat \| reasoning \| code \| classification \| tool-calling \| alignment \| domain-adapt |
+| `--gpu-budget` | text | `""` | | VRAM budget, e.g. 24GB (default: auto-detect) |
+| `--output`, `-o` | text | `soup.yaml` | | Output config path |
+| `--dry-run` | flag | off | | Show decisions but don't write the config |
+| `--yes`, `-y` | flag | off | | Skip confirmation prompts |
+
+## `soup bench`
+
+Benchmark a model: inference speed (infer, the default) or training (train).
+
+Usage: `soup bench <command> [ARGS]...`
+
+Subcommands:
+
+- [`infer`](#soup-bench-infer)
+- [`train`](#soup-bench-train)
+
+### `soup bench infer`
+
+Run an inference benchmark (speed and memory) on a loaded model.
+
+Usage: `soup bench infer [OPTIONS] MODEL`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `MODEL` | text | | yes | Path to model (LoRA adapter or full model) to benchmark |
+| `--base`, `-b` | text | | | Base model for LoRA adapter (auto-detected if not set) |
+| `--max-tokens` | integer | `128` | | Maximum tokens to generate per prompt |
+| `--num-prompts`, `-n` | integer | `3` | | Number of prompts to run for averaging (ignored when --prompts-file is set) |
+| `--prompts-file` | text | | | Path to custom prompts file (.txt or .jsonl) |
+| `--p50` | flag | off | | Print p50 (median) per-prompt latency. v0.53.9 #26. |
+| `--p95` | flag | off | | Print p95 per-prompt latency. v0.53.9 #26. |
+| `--backend` | text | `auto` | | Inference backend hint: auto (default) \| transformers \| mlx. v0.53.9 #28. |
+| `--cuda-graphs` | flag | off | | Experimental CUDA graph decode for resident, unquantized Qwen2/Llama models. |
+
+### `soup bench train`
+
+Train for a fixed number of steps and report timing, memory and tokens -- failing when the model was not actually training.
+
+Usage: `soup bench train [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--config`, `-c` | text | `soup.yaml` | | Config to train |
+| `--steps` | integer, at least 1 | `20` | | Optimizer steps to run |
+| `--warmup` | integer, at least 0 | `3` | | Leading steps measured but left out of the timing |
+| `--output`, `-o` | text | `bench-train.json` | | Where to write the JSON report |
+
+## `soup bom`
+
+CycloneDX ML-BOM + SPDX AI bill-of-materials emitter (v0.59.0).
+
+Usage: `soup bom <command> [ARGS]...`
+
+Subcommands:
+
+- [`emit`](#soup-bom-emit)
+
+### `soup bom emit`
+
+Emit a CycloneDX + SPDX BOM from CLI-supplied SHAs.
+
+Usage: `soup bom emit [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--name` | text | | yes | Model / adapter name. |
+| `--version` | text | `0.1.0` | | Model version string. |
+| `--base-model` | text | | yes | HF repo id of the base model. |
+| `--base-sha` | text | | yes | SHA-256 of the base model. |
+| `--config-sha` | text | | yes | SHA-256 of the resolved soup.yaml config. |
+| `--data-sha` | text | | | SHA-256 of the training dataset. |
+| `--task` | text | `sft` | | Training task (sft / dpo / grpo / ...). |
+| `--license` | text | | | License: an SPDX id (e.g. Apache-2.0, MIT; case-insensitive), an SPDX expression (Apache-2.0 OR MIT), or any other name. |
+| `--format`, `-f` | text | `cyclonedx` | | Output BOM format: cyclonedx \| spdx \| both. |
+| `--output`, `-o` | text | | | Output file path (cwd-contained). When --format=both, this is the prefix and Soup writes &lt;prefix>.cdx.json + &lt;prefix>.spdx.json. |
+| `--energy`, `-e` | text | | | Path to energy measurement JSON. |
+| `--attach-to-registry` | text | | | Attach the emitted BOM file(s) to a registry entry id (needs --output). |
+
+## `soup build`
+
+dbt-for-SFT DAG: validate, plan, and materialise dataset transforms.
+
+Usage: `soup build [OPTIONS] CONFIG`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `CONFIG` | text | | yes | Path to build manifest (YAML) |
+| `--output-dir`, `-o` | text | `build_out` | | Directory (under cwd) for materialised model JSONL + state store. |
+| `--dry-run` | flag | off | | Validate the manifest + print the topological plan; do not execute. |
+
+## `soup can`
+
+Soup Cans: pack/inspect/verify/fork shareable .can artifacts.
+
+Usage: `soup can <command> [ARGS]...`
+
+Subcommands:
+
+- [`fork`](#soup-can-fork)
+- [`inspect`](#soup-can-inspect)
+- [`pack`](#soup-can-pack)
+- [`publish`](#soup-can-publish)
+- [`run`](#soup-can-run)
+- [`verify`](#soup-can-verify)
+
+### `soup can fork`
+
+Fork a can with config modifications and re-pack.
+
+Usage: `soup can fork [OPTIONS] SOURCE`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `SOURCE` | text | | yes | Source .can path |
+| `--out`, `-o` | text | | yes | Output forked .can path |
+| `--modify` | text, repeatable | | | Modification like 'training.lr=5e-5' (repeatable) |
+| `--author` | text | `unknown` | | |
+
+### `soup can inspect`
+
+Preview a .can file's manifest without extracting.
+
+Usage: `soup can inspect PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to .can file |
+
+### `soup can pack`
+
+Pack a registry entry into a shareable .can file.
+
+Usage: `soup can pack [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--entry-id` | text | | yes | Registry entry id / prefix / name:tag |
+| `--out`, `-o` | text | | yes | Output .can path |
+| `--author` | text | `unknown` | | Author handle |
+| `--description` | text | `""` | | Free-form description |
+| `--attest` | text, repeatable | | | Embed an in-toto Statement JSON into the can manifest (v3, repeatable). Each file is shape-validated. v0.71.3. |
+
+### `soup can publish`
+
+Publish a .can file to HF Hub as a dataset.
+
+Usage: `soup can publish [OPTIONS] CAN_PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `CAN_PATH` | text | | yes | Path to .can file |
+| `--hf-hub` | text | | yes | HF Hub dataset repo (e.g. 'me/my-recipe-can') |
+| `--private` | flag | off | | |
+| `--message`, `-m` | text | | | Commit message (first line only, capped at 200 chars) |
+
+### `soup can run`
+
+Run a can end-to-end: extract -> train (-> optional deploy).
+
+Usage: `soup can run [OPTIONS] CAN_PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `CAN_PATH` | text | | yes | Path to .can file |
+| `--yes`, `-y` | flag | off | | Skip the security confirmation panel (auto-trains, auto-fetches data) |
+| `--deploy` | flag | off | | Run the can's deploy_targets after a successful train |
+| `--extract-dir` | text | | | Where to extract (default: fresh tmp dir) |
+| `--env-capture` | text | | | Write env summary (pip freeze + GPU info) to this path |
+
+### `soup can verify`
+
+Verify a .can file's schema and config parseability.
+
+Usage: `soup can verify PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to .can file |
+
+## `soup card`
+
+Generate a HuggingFace model card from a registry entry.
+
+Usage: `soup card [OPTIONS] REF`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `REF` | text | | yes | Registry entry id / prefix / name:tag |
+| `-o`, `--output` | text | `MODELCARD.md` | | Output markdown path (must stay under the current directory) |
+
+## `soup chat`
+
+Chat with a fine-tuned model in the terminal.
+
+Usage: `soup chat [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | yes | Path to LoRA adapter directory or full model |
+| `--base`, `-b` | text | | | Base model ID. Auto-detected from adapter_config.json if not set. |
+| `--device` | text | | | Device: cuda, mps, cpu. Auto-detected if not set. |
+| `--max-tokens` | integer | `512` | | Maximum number of tokens to generate |
+| `--temperature`, `-t` | float | `0.7` | | Sampling temperature (0.0 = greedy, 1.0 = creative) |
+| `--system`, `-s` | text | | | System prompt for the conversation |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+| `--hub` | text | `hf` | | Source hub for the base model: hf (default) / modelscope / modelers. Non-HF hubs require the matching SDK; the base model is snapshotted to a cwd-contained cache before chat starts (v0.53.10 #152). |
+
+## `soup ci`
+
+Fine-tuning CI: init a PR gate workflow.
+
+Usage: `soup ci <command> [ARGS]...`
+
+Subcommands:
+
+- [`init`](#soup-ci-init)
+
+### `soup ci init`
+
+Write a GitHub Actions fine-tuning gate workflow.
+
+Usage: `soup ci init [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--data` | text | `./data/train.jsonl` | | Training data path (repo-relative) |
+| `--suite` | text | `expectations.yaml` | | Expectations suite YAML (repo-relative) |
+| `--evidence` | text | `ship_evidence.json` | | Ship evidence JSON (repo-relative) |
+| `--python` | text | `3.11` | | Python version for the CI runner (e.g. 3.11) |
+| `--branch` | text | `main` | | Branch the workflow triggers on |
+| `--config` | text | | | Bind the ship gate to a committed soup.yaml (refuses stale evidence) |
+| `-o`, `--output` | text | `.github/workflows/soup-gate.yml` | | Workflow output path |
+| `--force`, `-f` | flag | off | | Overwrite an existing workflow |
+
+## `soup compile`
+
+Compile a DSPy / GEPA prompt program against an eval suite (v0.68.0).
+
+Usage: `soup compile [OPTIONS] PROGRAM`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PROGRAM` | text | | yes | Path to DSPy / GEPA program (.py) |
+| `--eval` | text | | yes | Path to eval-suite JSON / JSONL file |
+| `--optimizer` | text | `mipro` | | Optimizer name. Allowed: bootstrap_fewshot, copro, gepa, mipro, textgrad |
+| `--max-iters` | integer | `10` | | Maximum optimizer iterations |
+| `--output`, `-o` | text | `compiled_program.py` | | Output program path |
+| `--plan-only` | flag | off | | Render the resolved plan + exit 0 (no live compile). |
+
+## `soup compile-tools`
+
+Compile / optimize tool schemas + descriptions (v0.68.0).
+
+Usage: `soup compile-tools [OPTIONS] SPEC`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `SPEC` | text | | yes | OpenAPI / MCP / GraphQL spec path |
+| `--eval` | text | | yes | Path to tool-call eval JSONL |
+| `--optimizer` | text | `textgrad` | | Allowed: gepa, textgrad |
+| `--output`, `-o` | text | `compiled_tools.json` | | Output schema path |
+| `--plan-only` | flag | off | | Render plan + exit 0 (no live optimise). |
+
+## `soup completions`
+
+Emit a bash / zsh / fish completion script. Use with `eval "$(soup completions bash)"` (v0.64.0).
+
+Usage: `soup completions SHELL`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `SHELL` | text | | yes | One of: bash, zsh, fish. |
+
+## `soup cost`
+
+Estimate training cost in USD across cloud providers.
+
+Usage: `soup cost [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--config`, `-c` | text | `soup.yaml` | | Path to soup.yaml config file |
+| `--gpu`, `-g` | text | | | Filter by specific GPU (e.g., A100, H100, RTX 4090) |
+| `--json` | flag | off | | Output as JSON for scripting |
+
+## `soup data`
+
+Dataset tools: inspect, convert, merge, dedup, validate, stats.
+
+Usage: `soup data <command> [ARGS]...`
+
+Subcommands:
+
+- [`active-sample`](#soup-data-active-sample)
+- [`augment`](#soup-data-augment)
+- [`best-of-n`](#soup-data-best-of-n)
+- [`brain-rot`](#soup-data-brain-rot)
+- [`canary`](#soup-data-canary)
+- [`clean`](#soup-data-clean)
+- [`convert`](#soup-data-convert)
+- [`decontaminate`](#soup-data-decontaminate)
+- [`dedup`](#soup-data-dedup)
+- [`demo`](#soup-data-demo)
+- [`doctor`](#soup-data-doctor)
+- [`download`](#soup-data-download)
+- [`educational`](#soup-data-educational)
+- [`evolve`](#soup-data-evolve)
+- [`filter`](#soup-data-filter)
+- [`forge`](#soup-data-forge)
+- [`from-traces`](#soup-data-from-traces)
+- [`gen-magpie`](#soup-data-gen-magpie)
+- [`generate`](#soup-data-generate)
+- [`ingest`](#soup-data-ingest)
+- [`inspect`](#soup-data-inspect)
+- [`langdetect`](#soup-data-langdetect)
+- [`lint`](#soup-data-lint)
+- [`merge`](#soup-data-merge)
+- [`mix`](#soup-data-mix)
+- [`persona-mix`](#soup-data-persona-mix)
+- [`pii`](#soup-data-pii)
+- [`preprocess`](#soup-data-preprocess)
+- [`preview`](#soup-data-preview)
+- [`push`](#soup-data-push)
+- [`recipe`](#soup-data-recipe)
+- [`register`](#soup-data-register)
+- [`registry`](#soup-data-registry)
+- [`review`](#soup-data-review)
+- [`sample`](#soup-data-sample)
+- [`score`](#soup-data-score)
+- [`search`](#soup-data-search)
+- [`split`](#soup-data-split)
+- [`stats`](#soup-data-stats)
+- [`topics`](#soup-data-topics)
+- [`toxicity`](#soup-data-toxicity)
+- [`unregister`](#soup-data-unregister)
+- [`validate`](#soup-data-validate)
+
+### `soup data active-sample`
+
+Surface the most uncertain prod traces for human review.
+
+Usage: `soup data active-sample [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | JSONL of trace rows with rm_score or rm_scores fields. |
+| `--output`, `-o` | text | `active_samples.jsonl` | | Output JSONL of the top-uncertainty rows (default: active_samples.jsonl). |
+| `--budget` | integer | `100` | | Max rows to surface for human review (1 - 100_000). |
+| `--slack-url` | text | | | Optional Slack webhook URL — POSTed on completion. SSRF-validated. |
+| `--discord-url` | text | | | Optional Discord webhook URL — POSTed on completion. SSRF-validated. |
+
+### `soup data augment`
+
+Augment a dataset via LLM (rephrase / translate / style).
+
+Usage: `soup data augment [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | Source JSONL file |
+| `--output`, `-o` | text | `augmented.jsonl` | | Output JSONL path |
+| `--strategy`, `-s` | text | `rephrase` | | Augmentation strategy: rephrase, translate, style |
+| `--provider`, `-p` | text | `ollama` | | LLM provider: ollama, anthropic, vllm |
+| `--model` | text | `""` | | Provider model id (default per provider) |
+| `--base-url` | text | `""` | | Provider base URL (ollama/vllm; defaults to loopback) |
+| `--count`, `-c` | integer, 1 to 10 | `2` | | Augmentation multiplier (1-10) |
+| `--lang` | text | `""` | | Comma-separated target languages for translate |
+| `--styles` | text | `""` | | Comma-separated styles for style strategy |
+| `--requests-per-minute` | integer, 1 to 600 | `60` | | Rate limit for provider requests |
+| `--dedup` | flag | off | | Deduplicate augmented + original data |
+
+### `soup data best-of-n`
+
+Best-of-N rejection sampling: sample N per prompt, a judge picks the winner.
+
+Usage: `soup data best-of-n [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--base` | text | `""` | | Local base model id/path to sample from |
+| `--prompts` | text | `""` | | JSONL of {prompt\|messages} rows |
+| `--judge` | text | `""` | | Judge URL (ollama://\|https://\|http://localhost) |
+| `--provider` | text | `""` | | Provider sampler: ollama \| vllm |
+| `--model` | text | `""` | | Provider sampler model id |
+| `--base-url` | text | `""` | | Provider sampler base URL |
+| `--n` | integer | `8` | | Candidates per prompt \[2, 64] |
+| `--output`, `-o` | text | `""` | | Output SFT JSONL (required unless --plan-only) |
+| `--emit-pairs` | text | `""` | | Also write winner/loser DPO pairs to this JSONL |
+| `--checkpoint` | text | `""` | | Recovery journal (default: &lt;output-or-artifact>.checkpoint.jsonl) |
+| `--manifest` | text | `""` | | Commit manifest (default: &lt;output>.manifest.json) |
+| `--resume` | flag | off | | Resume a matching checkpoint |
+| `--export-candidates` | text | `""` | | Sampling-only candidate artifact JSONL |
+| `--candidate-artifact` | text | `""` | | Offline candidate artifact to materialize |
+| `--judgments` | text | `""` | | Offline verified judgments JSONL |
+| `--temperature` | float | `1.0` | | Sampling temp \[0, 2] |
+| `--max-new-tokens` | integer | `256` | | Max new tokens per candidate \[1, 4096] |
+| `--device` | text | `""` | | Local sampler device: cuda \| cpu |
+| `--seed` | integer | `0` | | Local sampling seed |
+| `--revision` | text | `""` | | Pinned local model revision |
+| `--trust-remote-code` | flag | off | | Allow custom model code on local --base |
+| `--plan-only` | flag | off | | Validate + print plan |
+
+### `soup data brain-rot`
+
+Score a dataset for brain-rot per arXiv 2510.13928.
+
+Usage: `soup data brain-rot [OPTIONS] DATA`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DATA` | text | | yes | Path to JSONL dataset |
+| `--strict` | flag | off | | Exit 3 on MAJOR verdict (CI gate mode) |
+| `--max-major-fraction` | float | `0.25` | | Strict-mode MAJOR-row fraction cap \[0, 1] |
+| `--lang` | text | `en` | | Per-language heuristic bundle: en \| es \| fr \| de \| ru \| auto. Closes issue #234. |
+
+### `soup data canary`
+
+Dataset canaries (memorization probe).
+
+Usage: `soup data canary <command> [ARGS]...`
+
+Subcommands:
+
+- [`check`](#soup-data-canary-check)
+- [`insert`](#soup-data-canary-insert)
+
+#### `soup data canary check`
+
+Check a model for memorization of the manifest's canaries.
+
+Usage: `soup data canary check [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--manifest` | text | | yes | Canary manifest |
+| `--base` | text | | yes | Base model id or path |
+| `--adapter` | text | | | LoRA adapter to check |
+| `--controls` | integer | `128` | | Never-inserted controls to rank against |
+| `--device` | text | `auto` | | auto/cpu/cuda |
+| `--output`, `-o` | text | | | Write the report as JSON |
+
+#### `soup data canary insert`
+
+Insert K unique canaries into a dataset and record them.
+
+Usage: `soup data canary insert [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file |
+| `--output`, `-o` | text | | yes | Output file: .jsonl, or .json for a JSON array |
+| `--manifest` | text | | yes | Where to write the canary manifest (CONTAINS THE SECRETS) |
+| `--count`, `-k` | integer | `16` | | Number of canaries |
+| `--seed` | integer | `0` | | Seed for the canaries and the rows they go to |
+| `--format` | text | `auto` | | Dataset format to write the canaries in: auto (detect), alpaca, sharegpt, chatml |
+
+### `soup data clean`
+
+Clean and repair a fine-tuning dataset: control characters, whitespace, format sanity.
+
+Usage: `soup data clean [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to input dataset file (JSONL) |
+| `--output`, `-o` | text | | | Path to write cleaned dataset (default: &lt;input>\_cleaned.jsonl) |
+| `--force`, `-f` | flag | off | | Overwrite output file if it already exists |
+| `--dry-run` | flag | off | | Preview modifications without writing output file |
+| `--min-tokens` | integer | `1` | | Minimum character/token length for assistant turns (shorter turns are dropped) |
+| `--prune-echo` / `--no-prune-echo` | flag | off | | Prune assistant turns that merely echo the user prompt (opt-in) |
+| `--strip-boilerplate` / `--no-strip-boilerplate` | flag | off | | Strip canned AI disclaimers ('As an AI...', 'Certainly!...') |
+| `--repair-code` / `--no-repair-code` | flag | off | | Auto-close unclosed markdown \`\`\` code fences in assistant completions |
+| `--repair-json` / `--no-repair-json` | flag | off | | Repair trailing commas and markdown fences in tool-call arguments |
+| `--drop-invalid-json` | flag | off | | Drop tool-calling rows with unrepairable JSON syntax errors |
+| `--json` | flag | off | | Output machine-readable JSON summary |
+
+### `soup data convert`
+
+Convert a dataset between formats (alpaca, sharegpt, chatml).
+
+Usage: `soup data convert [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Input dataset file |
+| `--to`, `-t` | text | | yes | Target format: alpaca, sharegpt, chatml |
+| `--output`, `-o` | text | | | Output file path (default: &lt;input>\_&lt;format>.jsonl) |
+
+### `soup data decontaminate`
+
+Drop rows that overlap public benchmarks (n-gram heuristic).
+
+Usage: `soup data decontaminate [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | |
+| `--benchmarks`, `-b` | text | | | Comma-separated benchmark names (label only; corpora not bundled). |
+| `--benchmark-file` | text | | | v0.53.7: operator-supplied benchmark JSONL (under cwd). Each row's ``text``/``prompt``/``content`` field contributes to the n-gram contamination set. Compatible with --benchmarks (extends). |
+| `--output`, `-o` | text | `clean.jsonl` | | Output JSONL of rows that survived decontamination. |
+| `--threshold` | float, 0.0 to 1.0 | `0.8` | | |
+| `--n` | integer, 1 to 32 | `8` | | |
+
+### `soup data dedup`
+
+Remove near-duplicate rows: MinHash (default) or embeddings (--semantic).
+
+Usage: `soup data dedup [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file |
+| `--output`, `-o` | text | | | Output file path (default: &lt;input>\_deduped.jsonl) |
+| `--threshold` | float | `0.8` | | Similarity threshold (0.0-1.0): MinHash Jaccard by default, embedding cosine under --semantic. |
+| `--field`, `-f` | text | | | Field to hash/embed (default: all text fields concatenated) |
+| `--semantic` | flag | off | | Use embedding cosine (SemDeDup) instead of MinHash. Catches paraphrases MinHash misses. Requires soup-cli\[train]. |
+| `--embed-model` | text | `sentence-transformers/all-MiniLM-L6-v2` | | Embedding model used by --semantic. |
+| `--device` | text | `auto` | | Device for --semantic (auto/cpu/cuda). |
+
+### `soup data demo`
+
+List or copy a bundled demo dataset (v0.43.0).
+
+Usage: `soup data demo [OPTIONS] [NAME]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME` | text | | | Bundle name (alpaca_demo / sharegpt_demo / dpo_demo / grpo_demo). Omit to list available bundles. |
+| `--output`, `-o` | text | | | Destination JSONL path (defaults to ./&lt;name>.jsonl). |
+
+### `soup data doctor`
+
+Chat-template compatibility report + loss-mask X-ray.
+
+Usage: `soup data doctor [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file (jsonl/json/csv/parquet). |
+| `--model`, `-m` | text | | yes | Tokenizer id or local path to check chat-template compatibility against. |
+| `--format`, `-f` | text | `auto` | | Dataset format (auto-detects by default). |
+| `--max-length` | integer | `2048` | | Training max_length — used for the truncation-risk check. |
+| `--sample` | integer | `200` | | Number of rows to sample for the checks. |
+| `--show-mask` | integer | | | Render N sample rows with per-token trained/masked colouring (the real collator path). |
+| `--train-on-responses-only` / `--no-train-on-responses-only` | flag | on | | Mask non-assistant tokens (mirrors data.train_on_responses_only). |
+| `--train-on-messages-with-train-field` | flag | off | | Per-message train:bool field masking (mirrors the same soup.yaml flag). |
+| `--mask-history` / `--no-mask-history` | flag | off | | Train only the LAST assistant turn (mirrors data.mask_history). |
+| `--train-on-eot` | flag | off | | Extend the trained span through the trailing EOS/EOT token. |
+| `--trust-remote-code` | flag | off | | Allow loading a tokenizer that ships custom code. |
+| `--output`, `-o` | text | | | Write the report JSON to this path. |
+
+### `soup data download`
+
+Download a HuggingFace dataset and save as JSONL.
+
+Usage: `soup data download [OPTIONS] DATASET_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DATASET_ID` | text | | yes | HuggingFace dataset ID (e.g. teknium/OpenHermes-2.5) |
+| `--output`, `-o` | text | | | Output file path (default: &lt;dataset-name>.jsonl) |
+| `--split` | text | `train` | | Dataset split to download (e.g. train, test, train\[:1000]) |
+| `--samples`, `-n` | integer | | | Max number of samples to download (streams, no full download) |
+| `--format`, `-f` | text | | | Convert to Soup format after download: alpaca, sharegpt, chatml |
+| `--trust-remote-code` | flag | off | | Allow datasets that ship custom Python loaders. Default deny (v0.36.0). Only enable if you trust the source. |
+| `--hub` | text | `hf` | | Source hub: hf (default) / modelscope / modelers. Non-HF hubs require the matching SDK (v0.53.8 #130). |
+
+### `soup data educational`
+
+Tag each row with an educational-value score \[0, 1].
+
+Usage: `soup data educational [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | |
+| `--output`, `-o` | text | `educational.jsonl` | | |
+
+### `soup data evolve`
+
+Evol-Instruct: deepen (depth) or diversify (breadth) seed instructions.
+
+Usage: `soup data evolve [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input` | text | | yes | Seed JSONL ({prompt\|instruction\|messages} per row) |
+| `--provider` | text | | yes | ollama \| vllm |
+| `--model` | text | | yes | Provider model id |
+| `--strategy` | text | `depth` | | depth \| breadth |
+| `--rounds` | integer | `1` | | Evolution rounds \[1, 5] |
+| `--output`, `-o` | text | `""` | | Output JSONL (required unless --plan-only) |
+| `--base-url` | text | `""` | | Provider base URL |
+| `--temperature` | float | `1.0` | | Sampling temp \[0, 2] |
+| `--max-tokens` | integer | `512` | | Max tokens \[1, 16384] |
+| `--plan-only` | flag | off | | Validate + print plan |
+
+### `soup data filter`
+
+Filter dataset by quality: perplexity and/or coherence scoring.
+
+Usage: `soup data filter [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file |
+| `--output`, `-o` | text | | | Output file path (default: &lt;input>\_filtered.jsonl) |
+| `--perplexity`, `--ppl` | float | | | Max perplexity threshold (rows above this are removed) |
+| `--coherence`, `--min-coherence` | float | | | Min coherence threshold 0.0-1.0 (rows below this are removed) |
+| `--ppl-model` | text | `gpt2` | | Model for perplexity scoring (default: gpt2) |
+| `--field`, `-f` | text | | | Field to score (default: all text fields concatenated) |
+| `--score-only` | flag | off | | Add scores to data without filtering (writes \_scored.jsonl) |
+
+### `soup data forge`
+
+Run the multi-stage synthetic data pipeline with provenance.
+
+Usage: `soup data forge [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--docs`, `-d` | text | | yes | Directory of documents (txt/md/json/jsonl, under cwd). |
+| `--task`, `-t` | text | `sft` | | Forge task: sft \| preference \| tool. |
+| `--target-rows`, `-r` | integer, 1 to 1000000 | `100` | | Maximum number of synthesised rows. |
+| `--teacher` | text | `local-judge` | | Label recorded in provenance for the judge backend. |
+| `--output`, `-o` | text | `forge_dataset.jsonl` | | JSONL output path (under cwd). |
+| `--provenance` | text | `forge_provenance.json` | | Provenance manifest output path (under cwd). |
+| `--uncertainty-threshold` | float, 0.0 to 1.0 | `0.0` | | Minimum Jaccard-distance score required to keep a synthesised row. |
+| `--max-chunk-chars` | integer, 1 to 64000 | `1000` | | Maximum chars per document chunk before judge call. |
+| `--judge-provider` | text | | | v0.53.7 #111: live judge backend. One of ollama / anthropic / vllm. Omit for the deterministic offline stub. |
+| `--judge-model` | text | `llama3.1` | | Model name for the live judge provider (default llama3.1). |
+| `--judge-base-url` | text | | | Override base URL for Ollama (localhost-only) / vLLM (scheme allowlist + loopback). Ignored for Anthropic. |
+| `--hub` | text | `hf` | | Teacher hub: hf (default) / modelscope / modelers. When non-HF and --teacher is a repo id (owner/name), the teacher is pre-fetched from that hub (v0.71.5 #157). |
+
+### `soup data from-traces`
+
+Harvest preference pairs from production traces.
+
+Usage: `soup data from-traces [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--logs` | text | | yes | Trace source: a JSONL file for langchain/openai, or the directory `soup serve --trace-log` writes for soup-serve (a single file is refused) |
+| `--format` | text | | yes | Trace format: langchain \| openai \| soup-serve |
+| `--signal` | text | `thumbs_up` | | Signal to extract pairs from: thumbs_up \| regenerations \| user_edit |
+| `--output`, `-o` | text | `prefs.jsonl` | | Output path for preference pairs (JSONL) |
+| `--judge` | flag | off | | Filter pairs via LLM-as-a-judge confidence (v0.40.3 #33). |
+| `--judge-provider` | text | `openai` | | Judge backend: openai \| server \| ollama. Used with --judge. |
+| `--judge-model` | text | `gpt-4o-mini` | | Judge model id (e.g. 'gpt-4o-mini', 'llama3', 'qwen2.5'). Used with --judge. |
+| `--judge-api-base` | text | | | Judge API base URL. SSRF-protected. Used with --judge. |
+| `--min-confidence` | float | `0.7` | | Drop pairs with judge-confidence below this threshold (0.0 - 1.0). |
+
+### `soup data gen-magpie`
+
+Generate synthetic data from a chat-template prefix.
+
+Usage: `soup data gen-magpie [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--base` | text | | yes | Aligned chat-tuned base model id |
+| `--provider` | text | | yes | ollama \| anthropic \| vllm |
+| `--target` | integer | | yes | Target row count \[1, 1_000_000] |
+| `--output`, `-o` | text | `""` | | Output JSONL path (required unless --plan-only) |
+| `--base-url` | text | `""` | | Provider base URL (ollama/vllm; defaults to loopback) |
+| `--max-tokens` | integer | `512` | | Max tokens per generation \[1, 16384] |
+| `--quality-filter` / `--no-quality-filter` | flag | on | | Apply non-empty + educational heuristics (not a toxicity classifier) |
+| `--plan-only` | flag | off | | Validate + print plan; do not generate. |
+
+### `soup data generate`
+
+Generate synthetic training data using an LLM.
+
+Usage: `soup data generate [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--prompt`, `-p` | text | | yes | System prompt describing what kind of data to generate |
+| `--count`, `-n` | integer | `100` | | Number of examples to generate |
+| `--output`, `-o` | text | `generated.jsonl` | | Output file path |
+| `--format`, `-f` | text | `alpaca` | | Output format: alpaca, sharegpt, chatml |
+| `--provider` | text | `openai` | | LLM provider: openai, local, server, ollama, anthropic, vllm |
+| `--model`, `-m` | text | `gpt-4o-mini` | | Model name (OpenAI model ID, Ollama model, or local model path) |
+| `--api-key` | text | | | \[deprecated] Use OPENAI_API_KEY env var instead. Env: `OPENAI_API_KEY`. |
+| `--api-base` | text | | | Custom API base URL (must use HTTPS for remote APIs) |
+| `--batch-size` | integer | `5` | | Number of examples per API call |
+| `--temperature`, `-t` | float | `0.8` | | Sampling temperature for generation |
+| `--dedup-with` | text | | | Path to existing dataset to deduplicate against |
+| `--seed` | text | | | Path to seed examples file (JSONL) to guide generation |
+| `--template` | text | | | Domain template: code, conversation, qa, preference, reasoning |
+| `--language` | text | `Python` | | Language for code template (Python, JavaScript, Go, Rust, Java) |
+| `--task-type` | text | `function` | | Task type for code template (function, debug, explain, refactor, test) |
+| `--turns` | integer | `4` | | Number of turns for conversation template (2-10) |
+| `--topic` | text | `general knowledge` | | Topic for conversation template |
+| `--context` | text | | | Path to context document for QA template |
+| `--pref-task` | text | `dpo` | | Preference task format: dpo, kto, orpo |
+| `--domain` | text | `math` | | Domain for reasoning template (math, logic, code) |
+| `--ollama-model` | text | | | Ollama model name (e.g. llama3.1). Shorthand for --provider ollama --model X |
+| `--validate` | flag | off | | Auto-validate generated data after generation |
+| `--filter` | flag | off | | Auto-filter generated data by quality (perplexity + coherence) |
+| `--dedup` | flag | off | | Auto-dedup generated data (MinHash) |
+| `--quality-pipeline` | flag | off | | Run full quality pipeline: validate + filter + dedup |
+| `--requests-per-minute`, `--rpm` | integer | `60` | | Rate limit for API requests (default: 60) |
+| `--trust-remote-code` | flag | off | | Allow loading local-provider models that ship custom Python via auto_map. Default deny (v0.36.0). |
+
+### `soup data ingest`
+
+Ingest a document into JSONL with one row per page / heading.
+
+Usage: `soup data ingest [OPTIONS] FILE`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `FILE` | text | | yes | PDF / DOCX / MD / TXT file |
+| `--output`, `-o` | text | `./ingested.jsonl` | | Output JSONL path |
+
+### `soup data inspect`
+
+Inspect a dataset: show stats and sample rows.
+
+Usage: `soup data inspect [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file (jsonl, csv, parquet) |
+| `--rows`, `-r` | integer | `5` | | Number of sample rows to show |
+| `--image-dir` | text | | | Directory containing referenced images |
+
+### `soup data langdetect`
+
+Tag each row with a 2-letter language code (heuristic).
+
+Usage: `soup data langdetect [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | |
+| `--output`, `-o` | text | `langdetect.jsonl` | | |
+
+### `soup data lint`
+
+Preference-data linter (dpo/orpo/simpo/ipo/bco/kto).
+
+Usage: `soup data lint [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to preference dataset file (dpo/kto). |
+| `--format`, `-f` | text | `auto` | | Dataset format: auto, dpo, kto. |
+| `--model`, `-m` | text | | | Optional tokenizer for exact token-length bias (default: word count). |
+| `--sample` | integer | `2000` | | Number of rows to sample for the checks. |
+| `--trust-remote-code` | flag | off | | Allow loading a tokenizer that ships custom code. |
+| `--output`, `-o` | text | | | Write the report JSON to this path. |
+
+### `soup data merge`
+
+Merge multiple datasets into a single file.
+
+Usage: `soup data merge [OPTIONS] FILES...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `FILES...` | text, any number | | yes | Paths to dataset files to merge |
+| `--output`, `-o` | text | `merged.jsonl` | | Output file path |
+| `--shuffle` | flag | off | | Shuffle after merging |
+
+### `soup data mix`
+
+BETA: optimise per-dataset mixture weights against a proxy run.
+
+Usage: `soup data mix [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--optimize` | flag | off | | Run Bayesian search over dataset mixture weights. |
+| `--apply` | text | | | Re-print a previously written mix-recipe (path under cwd). |
+| `--datasets` | text | | | Comma-separated list of dataset JSONL paths (>= 2, all under cwd). |
+| `--budget` | text | `1h` | | Wall-clock cap: digits + optional s/m/h suffix (e.g. 1h, 30m). |
+| `--num-probes`, `-n` | integer, 1 to 256 | `8` | | Maximum number of proxy runs. |
+| `--seed` | integer, 0 to 2147483647 | `42` | | RNG seed for the optimiser. |
+| `--output`, `-o` | text | `mix_recipe.yaml` | | YAML recipe output path (under cwd). |
+| `--overwrite` | flag | off | | Overwrite the output path when it exists. |
+| `--live` | flag | off | | v0.53.5 #116 — run live short `soup train` proxy runs per candidate (requires --base-yaml). Defaults to the offline synthetic proxy. |
+| `--base-yaml` | text | | | Path to a base soup.yaml (under cwd) supplying base/task/training/output. Required with --live. |
+
+### `soup data persona-mix`
+
+Sample a prompt × persona × style matrix.
+
+Usage: `soup data persona-mix [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--prompts` | text | | yes | JSONL file with one prompt per row |
+| `--n` | integer | | yes | Number of rows to emit \[1, 1_000_000] |
+| `--output` | text | | yes | Output JSONL path |
+| `--personas` | text | `""` | | Optional JSONL of personas (defaults to bundled set) |
+| `--styles` | text | `""` | | Optional JSONL of styles (defaults to bundled set) |
+| `--seed` | integer | `0` | | Deterministic seed |
+
+### `soup data pii`
+
+Flag rows containing email / phone / SSN / credit-card patterns.
+
+Usage: `soup data pii [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | |
+| `--output`, `-o` | text | `pii.jsonl` | | |
+
+### `soup data preprocess`
+
+AOT-tokenize a dataset and cache to disk for reuse across runs.
+
+Usage: `soup data preprocess [OPTIONS] CONFIG_PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `CONFIG_PATH` | text | | yes | Path to soup.yaml — uses data.train + tokenizer + max_length |
+| `--output`, `-o` | text | `./.soup-tokenized` | | Cache directory under cwd |
+| `--yes` | flag | off | | Skip confirmation prompt |
+
+### `soup data preview`
+
+Preview a remote HuggingFace dataset: metadata, splits, features.
+
+Usage: `soup data preview DATASET_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DATASET_ID` | text | | yes | HuggingFace dataset ID (e.g. teknium/OpenHermes-2.5) |
+
+### `soup data push`
+
+Upload a local JSONL dataset to a model hub as a dataset repo.
+
+Usage: `soup data push [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | Path to local JSONL dataset file |
+| `--hf-dataset` | text | | yes | HuggingFace dataset repo id (e.g. user/my-dataset) |
+| `--private` | flag | off | | Make the HF dataset repo private |
+| `--message` | text | `Upload dataset with Soup CLI` | | Commit message for the dataset upload |
+| `--hub` | text | `hf` | | Target hub: hf (default) / modelscope / modelers. Non-HF hubs upload via the matching SDK (v0.71.5 #157) — repo_type=dataset, commit message sanitised to first line + 200 chars. |
+
+### `soup data recipe`
+
+Validate a Data Recipe DAG and optionally execute every node.
+
+Usage: `soup data recipe [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to recipe.yaml under cwd |
+| `--execute` | flag | off | | Run the validated DAG end-to-end (v0.53.7 #106 — live per-node execution: seed / llm_text / code / judge / validator / sampler). |
+| `--output`, `-o` | text | | | Output dir for sampler node (required with --execute). |
+| `--provider` | text | | | LLM provider for llm_text/judge nodes: ollama, anthropic, or vllm. |
+| `--model` | text | | | Provider model name (defaults to llama3.1). |
+| `--base-url` | text | | | Provider base URL (Ollama/vLLM; defaults to loopback). |
+| `--offline` | flag | off | | Explicitly allow placeholder generation and accept-all judging. |
+
+### `soup data register`
+
+Register a local dataset by name for use in soup.yaml.
+
+Usage: `soup data register [OPTIONS] [NAME_ARG] [PATH_ARG]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME_ARG` | text | | | Dataset name (positional alternative to --name) |
+| `PATH_ARG` | text | | | Path to dataset file (positional alternative to --path) |
+| `--name`, `-n` | text | | | Dataset name |
+| `--path`, `-p` | text | | | Path to dataset file |
+| `--format`, `-f` | text | `auto` | | Dataset format: alpaca, sharegpt, chatml, dpo, kto, auto |
+
+### `soup data registry`
+
+List all registered datasets.
+
+Usage: `soup data registry`
+
+Takes no options or arguments.
+
+### `soup data review`
+
+Preview preference pairs for manual review.
+
+Usage: `soup data review [OPTIONS] INPUT`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `INPUT` | text | | yes | Path to preference JSONL (chosen/rejected) |
+| `--sample`, `-s` | integer | `10` | | How many pairs to preview (1-100) |
+
+### `soup data sample`
+
+Sample a subset of a dataset using various strategies.
+
+Usage: `soup data sample [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file |
+| `--output`, `-o` | text | | | Output file path (default: &lt;input>\_sampled.jsonl) |
+| `--n`, `-n` | integer | | | Number of samples to select |
+| `--pct` | float | | | Percentage of dataset to sample (0-100) |
+| `--strategy`, `-s` | text | `random` | | Sampling strategy: random, diverse (TF-IDF + clusters), hard (by length) |
+| `--seed` | integer | | | Random seed for reproducibility |
+
+### `soup data score`
+
+Composite data-quality scorecard (PII + keyword triage + lang + edu + dec).
+
+Usage: `soup data score [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | JSONL input under cwd. |
+| `--benchmarks`, `-b` | text | | | Benchmark labels (e.g. mmlu,gsm8k), validated only; they do not select or filter --benchmark-file texts. Requires --benchmark-file; corpora are not bundled. |
+| `--benchmark-file` | text | | | Operator-supplied benchmark JSONL under cwd, with usable 8-gram text in every row. |
+| `--threshold` | float, 0.0 to 1.0 | `0.8` | | Decontamination overlap threshold. |
+
+### `soup data search`
+
+Search HuggingFace Hub for datasets.
+
+Usage: `soup data search [OPTIONS] QUERY`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `QUERY` | text | | yes | Search query for HuggingFace datasets |
+| `--limit`, `-l` | integer | `20` | | Maximum results to show |
+| `--sort`, `-s` | text | `downloads` | | Sort by: downloads, likes, lastModified, trending, createdAt |
+
+### `soup data split`
+
+Split dataset into train/val/test files.
+
+Usage: `soup data split [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file |
+| `--val` | integer | | | Validation split: percentage (default) or absolute count (with --absolute) |
+| `--test` | integer | | | Test split: percentage (default) or absolute count (with --absolute) |
+| `--train` | integer | | | Train split (informational; the train remainder is implied by --val + --test). Accepted for command parity. |
+| `--absolute` | flag | off | | Treat --val/--test as absolute sample counts instead of percentages |
+| `--seed` | integer | | | Random seed for reproducible splits |
+| `--stratify` | text | | | Field name for stratified splitting (preserves category distribution) |
+| `--stratify-semantic` | flag | off | | Use semantic clustering (TF-IDF + K-Means) to perform stratified splitting without requiring a category field |
+| `--num-clusters` | integer | | | Number of semantic clusters to use for semantic stratified splitting (default: 5) |
+
+### `soup data stats`
+
+Extended dataset statistics: length distribution, token counts, languages.
+
+Usage: `soup data stats PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file |
+
+### `soup data topics`
+
+Cluster a dataset into topics and show a coverage table.
+
+Usage: `soup data topics [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file (jsonl/json/csv) |
+| `--clusters`, `-k` | text | `auto` | | Number of topic clusters, or 'auto' (sqrt heuristic). |
+| `--embed-model` | text | `sentence-transformers/all-MiniLM-L6-v2` | | Embedding model. |
+| `--device` | text | `auto` | | auto/cpu/cuda |
+| `--seed` | integer | `0` | | Clustering seed. |
+| `--output`, `-o` | text | | | Write the report as JSON. |
+
+### `soup data toxicity`
+
+Run an abuse-keyword heuristic (not a toxicity classifier).
+
+Usage: `soup data toxicity [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | |
+| `--output`, `-o` | text | `toxicity.jsonl` | | |
+| `--threshold` | float, 0.0 to 1.0 | `0.05` | | Rows meeting the abuse-keyword threshold are kept. |
+
+### `soup data unregister`
+
+Remove a dataset from the local registry.
+
+Usage: `soup data unregister [OPTIONS] [NAME_ARG]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME_ARG` | text | | | Dataset name (positional alternative to --name) |
+| `--name`, `-n` | text | | | Dataset name to remove |
+
+### `soup data validate`
+
+Validate a dataset, returning exit 3 for input errors and 2 for unusable data.
+
+Usage: `soup data validate [OPTIONS] PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | | yes | Path to dataset file |
+| `--format`, `-f` | text | `auto` | | Expected format: auto, alpaca, sharegpt, chatml, dpo, kto, plaintext |
+| `--min-valid-fraction` | float, 0.0 to 1.0 | `0.0` | | Exit 2 when the fraction of valid rows is below this value |
+
+## `soup delinearize-llama4`
+
+Delinearize Llama 4 fused expert weights to 3-D form.
+
+Usage: `soup delinearize-llama4 [OPTIONS] SOURCE_DIR`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `SOURCE_DIR` | text | | yes | Llama 4 checkpoint directory (containing \*.safetensors). |
+| `--target`, `-o` | text | | yes | Destination directory for the delinearized weights (under cwd). |
+| `--model-id` | text | | | Optional model id; warn if it doesn't look like a Llama 4 model. |
+| `--num-experts` | integer | | | Expert count for the reshape. Defaults to config.json's num_local_experts. |
+| `--plan-only` | flag | off | | Render the plan and exit without reshaping (v0.44.0 flow). |
+
+## `soup deploy`
+
+Deploy models: Ollama integration (deploy, list, remove).
+
+Usage: `soup deploy <command> [ARGS]...`
+
+Subcommands:
+
+- [`autopilot`](#soup-deploy-autopilot)
+- [`hf-space`](#soup-deploy-hf-space)
+- [`ollama`](#soup-deploy-ollama)
+
+### `soup deploy autopilot`
+
+Pick PEFT + quant + spec-decoding combo for a hardware target.
+
+Usage: `soup deploy autopilot [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--target`, `-t` | text | | | Profile name (e.g. mac-m3, rtx-4090-24gb, ollama-local). |
+| `--base`, `-b` | text | `meta-llama/Llama-3.2-1B` | | Base model HF repo id or local path to embed in the recipe. |
+| `--recipe-out` | text | `deploy_autopilot.yaml` | | Where to write the rendered soup.yaml recipe (under cwd). |
+| `--script-out` | text | `deploy_autopilot.sh` | | Where to write the planned deploy shell script (under cwd). |
+| `--output-dir` | text | `./output` | | Recipe's training output directory. |
+| `--list`, `-l` | flag | off | | List all known deploy profiles. |
+| `--measure` | flag | off | | Run Quant-Lobotomy measurement on candidate quants. Requires --tasks. Results cached at \~/.soup/deploy_autopilot_cache.json (v0.53.1 #109). |
+| `--tasks` | text | | | JSONL eval tasks for --measure (one prompt + expected per line). |
+| `--measure-candidates` | text | | | Comma-separated quant candidates to measure (default: profile's primary quant). Example: 4bit,gptq,awq |
+
+### `soup deploy hf-space`
+
+Create a HuggingFace Space wrapping a fine-tuned model.
+
+Usage: `soup deploy hf-space [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | yes | HuggingFace model repo id to wrap in the Space (e.g. user/my-model) |
+| `--space`, `-s` | text | | yes | HuggingFace Space repo id to create (e.g. user/my-space) |
+| `--template`, `-t` | text | `gradio-chat` | | Space template: gradio-chat, streamlit-chat |
+| `--template-dir` | text | | | Custom template directory (overrides --template). Must contain app.py + README.md, optionally requirements.txt. Use {MODEL_REPO} placeholder for substitution. |
+| `--private` | flag | off | | Create the Space as private |
+| `--yes`, `-y` | flag | off | | Skip confirmation |
+
+### `soup deploy ollama`
+
+Deploy a GGUF model to local Ollama instance.
+
+Usage: `soup deploy ollama [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | | Path to GGUF model file |
+| `--name`, `-n` | text | | | Ollama model name (e.g. soup-my-model) |
+| `--system`, `-s` | text | | | System prompt for the model |
+| `--template`, `-t` | text | `auto` | | Chat template: auto, chatml, llama, mistral, vicuna, zephyr |
+| `--parameter`, `-p` | text, repeatable | | | Ollama parameter (repeatable): temperature=0.7, top_p=0.9, etc. |
+| `--list`, `-l` | flag | off | | List Soup-deployed models in Ollama |
+| `--remove`, `-r` | text | | | Remove a model from Ollama by name |
+| `--yes`, `-y` | flag | off | | Skip confirmation prompt |
+
+## `soup diagnose`
+
+Post-training report card: forgetting / refusal / format / mode_collapse / memorization / contamination (v0.56.0).
+
+Usage: `soup diagnose [OPTIONS] RUN_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | yes | Registry run id (or any opaque tag). |
+| `--base` | text | `""` | | Base model name (informational). |
+| `--adapter` | text | `""` | | Adapter name (informational). |
+| `--evidence` | text | | | JSON file with pre-computed probe scores (see README). |
+| `--output`, `-o` | text | | | Write the report JSON to this path. |
+| `--badge` | text | | | Write an SVG badge to this path. |
+| `--attach-to-registry` | text | | | Attach the --output report to a registry entry id (needs --output). Exits 1 when the attach fails. |
+| `--base-model` | text | | | Base model id to LOAD for a live diagnose run (e.g. HuggingFaceTB/SmolLM2-135M). When set, the 6 probes run live against the model instead of emitting neutral scores. |
+| `--dataset` | text | | | Training JSONL for live format / memorization / citation probes (must stay under cwd). |
+| `--holdout` | text | | | Held-out evaluation JSONL for the live forgetting probe (must stay under cwd; falls back to built-in general prompts if unset). |
+| `--tokenizer` | text | | | Tokenizer id/path for a sub-word memorization probe (live). |
+| `--device` | text | | | Device for the live run (cuda / cpu). |
+| `--citation-style` | text | `bracket` | | Citation style for the live RAFT citation probe: bracket (\[doc-id]) / inline ((doc-id)) / footnote (\[^id]). Must match the style the model was trained to emit. (v0.71.17 #254) |
+| `--allow-not-run` | flag | off | | Exit 0 even when a requested probe did not run (verdict NOT_RUN). Without it such a run exits 3. |
+| `--shuffle-seed` | integer | | | RAFT document-shuffle seed for the live citation probe (composes the \[doc-N] ids the model is scored against). (v0.71.17 #254) |
+
+## `soup diff`
+
+Compare outputs of two models side-by-side on the same prompts.
+
+Usage: `soup diff [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model-a`, `-a` | text | | yes | Path to first model (LoRA adapter or full model) |
+| `--model-b`, `-b` | text | | yes | Path to second model (LoRA adapter or full model) |
+| `--prompts`, `-p` | text | | | Path to prompts file (JSONL with 'prompt' field, or one prompt per line) |
+| `--prompt` | text, repeatable | | | Single prompt to compare (can be repeated) |
+| `--base-a` | text | | | Base model for model A (auto-detected for LoRA adapters) |
+| `--base-b` | text | | | Base model for model B (auto-detected for LoRA adapters) |
+| `--max-tokens` | integer | `256` | | Maximum tokens to generate per response |
+| `--temperature`, `-t` | float | `0.7` | | Sampling temperature |
+| `--device` | text | | | Device: cuda, mps, cpu. Auto-detected if not set. |
+| `--output`, `-o` | text | | | Save results to JSONL file |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+
+## `soup distill-prompt`
+
+Distill prompt-heavy traces into a small FT plan (v0.68.0).
+
+Usage: `soup distill-prompt [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--traces` | text | | yes | Path to traces JSONL |
+| `--teacher` | text | | yes | Teacher model id |
+| `--student` | text | | yes | Student model id |
+| `--strategy` | text | `sft` | | Distill strategy. Allowed: kl, preference, sft |
+| `--provider` | text | `ollama` | | Teacher/student provider: ollama / anthropic / vllm. |
+| `--base-url` | text | | | Provider base URL (ollama / vllm). |
+| `--temperature` | float | `0.0` | | Sampling temperature for teacher/student. |
+| `--max-rows` | integer | | | Cap the number of distilled rows. |
+| `--output`, `-o` | text | `distilled.jsonl` | | Output JSONL path |
+| `--plan-only` | flag | off | | Render plan + exit 0 (no live preparation). |
+
+## `soup doctor`
+
+Check system dependencies, GPU, and compatibility.
+
+Usage: `soup doctor [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--nccl` | flag | off | | Measure NCCL bandwidth and check against reference table. |
+| `--disk` | flag | off | | Detect the disk media type (NVMe / SSD / HDD). Layer streaming's disk overflow tier needs NVMe. Off by default: the probe costs \~9 s on Windows, and on Linux it WRITES a \~64 MiB scratch file (.soup-diskprobe-\*, git-ignored) into the current directory to measure sequential read throughput. |
+| `--config`, `-c` | text | | | Also check a soup.yaml: report which of the settings it actually sets are not read on its task and backend (#755). |
+
+## `soup draft`
+
+Train + measure a speculative-decoding draft model: distil your tuned model into a tiny draft, then serve it with --auto-spec (v0.71.33).
+
+Usage: `soup draft <command> [ARGS]...`
+
+Subcommands:
+
+- [`distill`](#soup-draft-distill)
+- [`list`](#soup-draft-list)
+- [`measure`](#soup-draft-measure)
+
+### `soup draft distill`
+
+Distil a target model into a tiny dense speculative-decoding draft.
+
+Usage: `soup draft distill [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--target` | text | | yes | The tuned model to speed up (the teacher). |
+| `--draft-base` | text | | yes | Tiny model to distil into (the student). Must share the target's tokenizer. A `soup shrink` output qualifies by construction. |
+| `--data` | text | | yes | JSONL distillation set (chat / instruction rows). |
+| `-o`, `--output` | text | `draft` | | Directory for the dense draft model. |
+| `--steps` | integer, 1 to 1000000 | `500` | | Approximate training steps. |
+| `--device` | text | | | cpu \| cuda (default: auto-detect). |
+| `--no-register` | flag | off | | Do not record the draft in \~/.soup/drafts.json (it then won't be picked up by `soup serve --auto-spec`). |
+| `--trust-remote-code` | flag | off | | Allow custom modelling code from the target / draft-base (required for architectures that ship an auto_map). |
+| `--force` | flag | off | | Overwrite -o even if it already contains a non-draft directory. |
+| `--plan-only` | flag | off | | Print the distill config and exit; write nothing. |
+
+### `soup draft list`
+
+List locally-trained drafts that `soup serve --auto-spec` can use.
+
+Usage: `soup draft list`
+
+Takes no options or arguments.
+
+### `soup draft measure`
+
+Report a draft's acceptance rate + throughput against its target.
+
+Usage: `soup draft measure [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--target` | text | | yes | The model being served. |
+| `--draft` | text | | yes | The draft model (a `soup draft distill` output). |
+| `--prompts` | text | | yes | JSONL prompts representative of production traffic. |
+| `--max-new-tokens` | integer, 1 to 4096 | `64` | | Tokens to generate per prompt. |
+| `--num-assistant-tokens` | integer, 1 to 64 | `5` | | Tokens the draft proposes per step (the assisted-generation knob). |
+| `--device` | text | | | cpu \| cuda. |
+| `--min-acceptance` | float, 0.0 to 1.0 | | | Exit 2 if the acceptance rate falls below this (for CI gating). |
+| `--trust-remote-code` | flag | off | | Allow custom modelling code from the target / draft (required for architectures that ship an auto_map). |
+| `-o`, `--output` | text | | | Write the report as JSON. |
+| `--sweep-k` | text | | | Also time assisted generation at each of these draft lengths, e.g. 1,2,3,5,8 (at most 8, each in 1..64). |
+
+## `soup drift-alarm`
+
+Rolling-KL drift alarm on output-token distribution with optional Slack/Discord webhook (v0.63.0).
+
+Usage: `soup drift-alarm [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--reference` | text | | yes | JSONL of FT-time reference outputs. |
+| `--live` | text | | yes | JSONL of live production outputs. |
+| `--threshold` | float | `0.2` | | Drift threshold (KL divergence). Default 0.2. |
+| `--slack-url` | text | | | Optional Slack webhook URL — POSTed on drift. SSRF-validated. |
+| `--discord-url` | text | | | Optional Discord webhook URL — POSTed on drift. SSRF-validated. |
+
+## `soup edit`
+
+Knowledge editing (ROME / MEMIT / AlphaEdit) - patch facts without re-training (v0.61.0).
+
+Usage: `soup edit <command> [ARGS]...`
+
+Subcommands:
+
+- [`diff`](#soup-edit-diff)
+- [`set`](#soup-edit-set)
+
+### `soup edit diff`
+
+Knowledge-injection diff: facts changed between before / after.
+
+Usage: `soup edit diff [OPTIONS] BEFORE AFTER`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `BEFORE` | text | | yes | Label or run id of the model BEFORE the edit (metadata). |
+| `AFTER` | text | | yes | Label or run id of the model AFTER the edit (metadata). |
+| `--probes` | text | | | JSONL file with probe prompts; required when both --before-model and --after-model are given. Each row should have a 'prompt' field. Capped at 1000 rows. |
+| `--output`, `-o` | text | | | Where to write the rendered diff JSON. |
+| `--top-k`, `-k` | integer | `10` | | Number of changed facts to surface (1-100). |
+| `--before-model` | text | | | Model path / HF id of the BEFORE model (live generation with --after-model and --probes). |
+| `--after-model` | text | | | Model path / HF id of the AFTER model (live generation with --before-model and --probes). |
+| `--device` | text | | | torch device (cpu / cuda). Defaults to CUDA when available. |
+
+### `soup edit set`
+
+Apply a single surgical knowledge edit.
+
+Usage: `soup edit set [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--base`, `-b` | text | | yes | Base model HF id or local path. |
+| `--method`, `-m` | text | `rome` | | Edit method: rome / memit / alphaedit. |
+| `--subject`, `-s` | text | | yes | Prefix sentence (e.g. "Paris is the capital of France"). |
+| `--target`, `-t` | text | | yes | New completion target (e.g. "Lyon"). |
+| `--layer`, `-l` | integer | | | MLP layer index to edit (defaults to method-specific recommended layer). |
+| `--output`, `-o` | text | | | Directory to save the edited model / GRACE codebook (cwd-contained). |
+| `--device` | text | | | torch device (cpu / cuda). Defaults to CUDA when available. |
+| `--governor` / `--no-governor` | flag | on | | Consult the sequential-edit governor (refuse on norm blowup). |
+| `--cov-corpus` | text | | | ROME only: JSONL/text corpus to estimate the key covariance C for a C^{-1}-preconditioned update (reduces collateral damage). |
+| `--plan-only` | flag | off | | Print the resolved EditPlan and exit without applying. |
+| `--registry-id` | text | | | Registry entry id to attach the saved result to (needs --output): the weight file(s) as edited_model, or the GRACE codebook as grace_codebook. Exits 1 when the attach fails. |
+
+## `soup env`
+
+Hermetic env lockfile + ABI drift detection (v0.64.0).
+
+Usage: `soup env <command> [ARGS]...`
+
+Subcommands:
+
+- [`check`](#soup-env-check)
+- [`fix`](#soup-env-fix)
+- [`lock`](#soup-env-lock)
+- [`status`](#soup-env-status)
+
+### `soup env check`
+
+Compare the current env against the lock and report drift.
+
+Usage: `soup env check [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--lock` | text | `soup-env.lock` | | Path to the lock file to compare against. |
+
+### `soup env fix`
+
+Render a reproducible install plan from ``soup-env.lock``.
+
+Usage: `soup env fix [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--lock` | text | `soup-env.lock` | | Path to the lock file to render an install plan from. |
+| `--format` | text | `uv-pip` | | Install-plan format: uv-pip (copy/paste uv commands) \| requirements. |
+| `--output`, `-o` | text | | | Optionally also write a requirements.txt to this path (under cwd). |
+
+### `soup env lock`
+
+Snapshot the current env into a lock file.
+
+Usage: `soup env lock [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--output`, `-o` | text | `soup-env.lock` | | Path to write the lock file (default: ./soup-env.lock). |
+
+### `soup env status`
+
+Print currently-locked env summary.
+
+Usage: `soup env status [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--lock` | text | `soup-env.lock` | | Path to the lock file (default: ./soup-env.lock). |
+
+## `soup eval`
+
+Evaluate models: benchmarks, custom evals, LLM judge, leaderboard.
+
+Usage: `soup eval <command> [ARGS]...`
+
+Subcommands:
+
+- [`against`](#soup-eval-against)
+- [`aider`](#soup-eval-aider)
+- [`auto`](#soup-eval-auto)
+- [`behavior`](#soup-eval-behavior)
+- [`benchmark`](#soup-eval-benchmark)
+- [`capability`](#soup-eval-capability)
+- [`checklist`](#soup-eval-checklist)
+- [`citation`](#soup-eval-citation)
+- [`compare`](#soup-eval-compare)
+- [`coverage`](#soup-eval-coverage)
+- [`custom`](#soup-eval-custom)
+- [`design`](#soup-eval-design)
+- [`discover`](#soup-eval-discover)
+- [`gate`](#soup-eval-gate)
+- [`gate-install`](#soup-eval-gate-install)
+- [`human`](#soup-eval-human)
+- [`irt-subset`](#soup-eval-irt-subset)
+- [`judge`](#soup-eval-judge)
+- [`leaderboard`](#soup-eval-leaderboard)
+- [`lock`](#soup-eval-lock)
+- [`quant-check`](#soup-eval-quant-check)
+- [`unlearning`](#soup-eval-unlearning)
+
+### `soup eval against`
+
+Run-vs-run regression check (paired-bootstrap CI).
+
+Usage: `soup eval against [OPTIONS] BASELINE_RUN_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `BASELINE_RUN_ID` | text | | yes | Baseline run id (from `soup runs`). |
+| `--candidate` | text | | yes | Candidate run id whose metrics are compared to the baseline. |
+| `--metric` | text | `task_accuracy` | | Metric to check: task_accuracy \| refusal_rate \| format_validity \| p95_latency_ms \| custom \| aider_polyglot \| judge:&lt;model> \| benchmark:&lt;lm-eval-task>. |
+| `--n-samples` | integer | `1000` | | Paired-bootstrap samples (100-100000). |
+| `--seed` | integer | `0` | | Deterministic seed. |
+| `--json-only` | flag | off | | Suppress Rich output; emit a single JSON verdict line. |
+| `--suite` | text | | | Locked eval suite (from `soup eval lock`) to validate as a gate precondition — a missing / unparseable suite BLOCKS the check (exit 3). cwd-contained. The generated pre-push hook passes \$GATE_SUITE here so the locked suite is actually enforced. |
+
+### `soup eval aider`
+
+Run Aider's Polyglot coding benchmark in its official Docker image.
+
+Usage: `soup eval aider [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | yes | Aider model identifier (for example, openai/gpt-4.1) |
+| `--output`, `-o` | text | | yes | Contained directory for upstream and Soup result files |
+| `--exercises-dir` | text | `tmp.benchmarks/polyglot-benchmark` | | Prepared Aider-AI/polyglot-benchmark checkout |
+| `--image` | text | `aider-benchmark` | | Locally built upstream Aider benchmark image |
+| `--threads`, `-t` | integer, 1 to 64 | `1` | | Number of benchmark exercises to run concurrently |
+| `--num-tests`, `-n` | integer | `-1` | | Number of exercises to run (-1 runs all exercises) |
+| `--timeout` | integer, 60 to 86400 | `86400` | | Maximum benchmark runtime in seconds |
+| `--run-id` | text | | | Save the aggregate score under an existing Soup run ID |
+| `--allow-host-services` | flag | off | | Let the benchmark container reach services on the host |
+
+### `soup eval auto`
+
+Run automatic evaluation using config from soup.yaml.
+
+Usage: `soup eval auto [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--config`, `-c` | text | `soup.yaml` | | Path to soup.yaml config file |
+| `--benchmarks`, `-b` | text | | | Comma-separated benchmarks (overrides config) |
+| `--tasks`, `-t` | text | | | Path to custom eval JSONL (overrides config) |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+
+### `soup eval behavior`
+
+Score a run on a bundled behaviour battery (pre/post diff).
+
+Usage: `soup eval behavior [OPTIONS] RUN_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | yes | Run identifier. |
+| `--battery`, `-b` | text | `xstest` | | Battery: xstest / harmbench / jailbreakbench / elephant / syceval. |
+| `--evidence`, `-e` | text | | | Path to a JSON file with {pre_responses, post_responses, oracle} arrays. Here each oracle entry is a word the matching response must contain; --base-model scores refusal behaviour instead. |
+| `--output`, `-o` | text | | | Where to write the rendered BehaviorDiffReport JSON. |
+| `--base-model` | text | | | Base model id for a LIVE diff (generates pre/post responses). |
+| `--adapter` | text | | | LoRA adapter path for the 'post' model in a live diff. |
+| `--device` | text | | | Device for the live diff (cuda / cpu). |
+
+### `soup eval benchmark`
+
+Evaluate on standard benchmarks (wraps lm-evaluation-harness).
+
+Usage: `soup eval benchmark [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | yes | Path to model or LoRA adapter directory |
+| `--benchmarks`, `-b` | text | `mmlu` | | Comma-separated benchmark names (mmlu, gsm8k, hellaswag, etc.) |
+| `--fewshot`, `-f` | integer | | | Number of few-shot examples (benchmark default if not set) |
+| `--batch-size` | integer | `8` | | Batch size for evaluation |
+| `--run-id` | text | | | Link results to an existing training run |
+| `--device` | text | | | Device: cuda, mps, cpu. Auto-detected if not set. |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+
+### `soup eval capability`
+
+Run a bundled capability profile (MMLU-Pro / GPQA / AIME / ...).
+
+Usage: `soup eval capability [OPTIONS] RUN_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | yes | Run identifier. |
+| `--suite`, `-s` | text | `fast` | | Profile: full / fast / math / code. |
+| `--output`, `-o` | text | | | Where to write the rendered CapabilityReport JSON. |
+| `--live` | flag | off | | Run the suite LIVE via lm-eval-harness against --model. |
+| `--model`, `-m` | text | | | HF model id for a live run (required with --live). |
+| `--tasks` | text | | | Comma-separated lm-eval task override (live; bypasses --suite). |
+| `--limit` | integer | | | Cap eval examples per task (live; use 1-5 for a smoke). |
+| `--device` | text | | | Device for the live run (cuda / cpu). |
+
+### `soup eval checklist`
+
+Run CheckList MFT / INV / DIR behavioural tests.
+
+Usage: `soup eval checklist [OPTIONS] SPEC_PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `SPEC_PATH` | text | | yes | Path to CheckList DSL YAML. |
+| `--evidence`, `-e` | text | | | Required JSON with operator-supplied per-test responses. |
+| `--output`, `-o` | text | | | Where to write the rendered CheckListReport JSON. |
+
+### `soup eval citation`
+
+Score citation precision / recall / F1 over a JSONL (#202).
+
+Usage: `soup eval citation [OPTIONS] DATA`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DATA` | text | | yes | JSONL of {predicted, expected_ids} rows OR RAFT rows {query, golden_doc, distractor_docs, answer}. |
+| `--style` | text | `bracket` | | Citation style: bracket / inline / footnote. |
+| `--shuffle-seed` | integer | | | For RAFT-shaped rows: the data.raft_shuffle_seed used at train time, so the golden \[doc-N] id matches what the model saw. Ignored for {predicted, expected_ids} rows. |
+| `--output`, `-o` | text | | | Write the per-row + aggregate CitationScore JSON here. |
+
+### `soup eval compare`
+
+Compare eval results between two training runs.
+
+Usage: `soup eval compare RUN1 RUN2`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN1` | text | | yes | First run ID |
+| `RUN2` | text | | yes | Second run ID |
+
+### `soup eval coverage`
+
+Heuristic coverage / gap analysis for a locked or drafted suite.
+
+Usage: `soup eval coverage [OPTIONS] DESIGN_PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DESIGN_PATH` | text | | yes | Path to an EvalDesign JSON |
+| `--task` | text | | yes | Task category from v0.54.0 taxonomy: factual_lookup \| style_shaping \| format_conversion \| reasoning \| tool_use \| summarization \| classification. |
+
+### `soup eval custom`
+
+Run custom evaluation tasks from a JSONL file.
+
+Usage: `soup eval custom [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--tasks`, `-t` | text | | yes | Path to eval tasks JSONL file |
+| `--model`, `-m` | text | | yes | Path to model directory |
+| `--run-id` | text | | | Link results to an existing training run |
+| `--attach-to-registry` | text | | | Attach the eval JSON to a registry entry as kind=eval_results |
+| `--output`, `-o` | text | | | Path to write the eval JSON output. Honored independently of --attach-to-registry (v0.40.1 / G10). |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+
+### `soup eval design`
+
+Draft an evaluation suite from training data + a one-line goal.
+
+Usage: `soup eval design [OPTIONS] DATA`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DATA` | text | | yes | Training-data JSONL path |
+| `--goal`, `-g` | text | | yes | One-line goal description (e.g. 'better at SQL'). |
+| `--num-dimensions`, `-n` | integer | `5` | | Number of eval dimensions to draft (1-20). |
+| `--output`, `-o` | text | `evals/design.json` | | Where to write the rendered EvalDesign JSON. |
+
+### `soup eval discover`
+
+Discover a held-out canary set for regression detection.
+
+Usage: `soup eval discover [OPTIONS] DATA`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DATA` | text | | yes | Training-data JSONL path |
+| `--base` | text | | | Base model id (recorded; consumed by `soup diagnose`). |
+| `--num-clusters` | integer | `5` | | Number of behavioural clusters to discover (1-64). |
+| `--per-cluster` | integer | `3` | | Held-out canaries to draw per cluster (1-64). |
+| `--seed` | integer | `0` | | Deterministic seed. |
+| `--output`, `-o` | text | `evals/canaries.json` | | Where to write the rendered CanarySet JSON. |
+
+### `soup eval gate`
+
+Run an eval-gate suite standalone (post-hoc verdict).
+
+Usage: `soup eval gate [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--suite`, `-s` | text | | yes | Path to eval suite YAML (see evals/gate.yaml example) |
+| `--baseline`, `-b` | text | | | Baseline: registry://&lt;id> or path to stamped/flat score JSON |
+| `--regression-threshold` | float | `0.05` | | Max absolute drop vs baseline before regression fires (0.0-1.0) |
+| `--model`, `-m` | text | | | Model path or HF id to evaluate (required for live scoring) |
+| `--write-baseline` | text | | | Write this run's task scores as a stamped baseline JSON ({'scores', 'provenance'}) consumable by --baseline (#404). |
+
+### `soup eval gate-install`
+
+Install a pre-push regression gate for the selected baseline.
+
+Usage: `soup eval gate-install [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--baseline` | text | | yes | Baseline run id the pre-push hook compares against. |
+| `--suite` | text | `evals/locked.json` | | Path to the locked eval suite (cwd-contained). |
+| `--hook-path` | text | `.git/hooks/pre-push` | | Hook target — usually .git/hooks/pre-push. |
+| `--force` | flag | off | | Overwrite an existing hook. |
+
+### `soup eval human`
+
+Run human A/B evaluation between two models.
+
+Usage: `soup eval human [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | Path to JSONL file with evaluation prompts |
+| `--model-a`, `-a` | text | | yes | Path to first model |
+| `--model-b`, `-b` | text | | yes | Path to second model |
+| `--output`, `-o` | text | `human_eval_results.json` | | Output file for results |
+
+### `soup eval irt-subset`
+
+Pick a minimum-cost eval subset that preserves ranking power.
+
+Usage: `soup eval irt-subset [OPTIONS] RESPONSES_PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RESPONSES_PATH` | text | | yes | Path to JSONL with rows {item_id, correct(bool), respondent_id? (required for 2pl/3pl)}. |
+| `--size`, `-z` | text | `small` | | Subset profile: full / small / tiny. |
+| `--model`, `-m` | text | `1pl` | | IRT model: 1pl (Rasch) / 2pl (discrimination) / 3pl (+ guessing). |
+| `--output`, `-o` | text | | | Where to write the rendered IrtSubsetPlan JSON. |
+
+### `soup eval judge`
+
+Evaluate model outputs using LLM-as-a-judge.
+
+Usage: `soup eval judge [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--target` | text | | yes | Path to JSONL with prompt+response pairs to evaluate |
+| `--model`, `-m` | text | `gpt-4o-mini` | | Judge model name |
+| `--provider` | text | `openai` | | Judge provider: openai, server, ollama |
+| `--rubric`, `-r` | text | | | Path to rubric YAML file |
+| `--api-base` | text | | | API base URL for judge model |
+| `--run-id` | text | | | Link results to an existing training run |
+
+### `soup eval leaderboard`
+
+Show local leaderboard across all evaluated models.
+
+Usage: `soup eval leaderboard [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--sort-by`, `-s` | text | | | Sort by specific benchmark (default: average) |
+| `--format`, `-f` | text | `table` | | Output format: table, json, csv |
+
+### `soup eval lock`
+
+Freeze an EvalDesign as a checksummed eval_suite artifact.
+
+Usage: `soup eval lock [OPTIONS] DESIGN_PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DESIGN_PATH` | text | | yes | Path to an EvalDesign JSON (from `soup eval design`) |
+| `--output`, `-o` | text | `evals/locked.json` | | Where to write the canonicalised locked suite. |
+| `--attach-to-registry` | text | | | Registry entry id or name to attach the locked suite to. |
+
+### `soup eval quant-check`
+
+Compare accuracy before vs after quantization on the same eval suite.
+
+Usage: `soup eval quant-check [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--before` | text | | yes | Before-quantization model path or registry://&lt;id> |
+| `--after` | text | | yes | After-quantization model path or registry://&lt;id> |
+| `--tasks` | text | | yes | JSONL eval tasks file (see 'soup eval custom') |
+| `--format` | text | `table` | | Output format: table \| json \| markdown |
+| `--allow-stub` | flag | off | | Allow deterministic stub generators if live model loading fails. |
+
+### `soup eval unlearning`
+
+Score an unlearn run on TOFU / MUSE / WMDP.
+
+Usage: `soup eval unlearning [OPTIONS] RUN_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | yes | Run identifier (e.g. registry id of the unlearn run). |
+| `--benchmark`, `-b` | text | `tofu` | | Benchmark: tofu / muse / wmdp. |
+| `--evidence`, `-e` | text | | | Path to a JSON file with pre-computed evidence. Schema: {forget_quality: {pre_loss, post_loss}, model_utility: {pre_acc, post_acc}, priv_leak: {mia_auc}}. Missing keys fall through to a neutral OK score. |
+| `--output`, `-o` | text | | | Where to write the rendered UnlearnReport JSON. |
+| `--attach-to-registry` | text | | | Registry entry id to attach the --output report to as an eval_results artifact (needs --output). Exits 1 when the attach fails. |
+
+## `soup expect`
+
+Run an expectations suite against a JSONL dataset.
+
+Usage: `soup expect [OPTIONS] DATA SUITE`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `DATA` | text | | yes | Path to JSONL dataset |
+| `SUITE` | text | | yes | Path to expectations suite YAML |
+| `--judge` | text | | | Judge model URL (e.g. ollama://llama3.1, https://api.openai.com/gpt-4o-mini) |
+
+## `soup export`
+
+Export a model to GGUF, ONNX, TensorRT-LLM, AWQ, GPTQ, or TorchAO format.
+
+Usage: `soup export [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | yes | Path to model directory (full model or LoRA adapter) |
+| `--format`, `-f` | text | `gguf` | | Export format: gguf, onnx, tensorrt, awq, gptq, bitnet, tq1_0 (awq and gptq are deprecated and will be removed in Soup v0.77) |
+| `--quant`, `-q` | text | `q4_k_m` | | Quantization type: q4_0, q4_k_m, q5_k_m, q8_0, f16, f32 |
+| `--output`, `-o` | text | | | Output file path. Default: &lt;model-name>.&lt;quant>.gguf |
+| `--base`, `-b` | text | | | Base model ID (for LoRA adapters). Auto-detected if not set. |
+| `--llama-cpp` | text | | | Path to llama.cpp directory. Auto-detected or cloned to \~/.soup/llama.cpp |
+| `--onnx-task` | text | `text-generation` | | ONNX export task: text-generation (causal LM) or feature-extraction (embedding) |
+| `--deploy` | text | | | Auto-deploy after export. Currently supported: ollama |
+| `--deploy-name` | text | | | Model name for deployment (used with --deploy) |
+| `--bits` | integer | `4` | | Quantization bits for AWQ/GPTQ: 4 or 8 |
+| `--group-size` | integer | `128` | | Group size for AWQ/GPTQ quantization |
+| `--calibration-data` | text | | | Path to calibration JSONL. Required for AWQ and GPTQ. |
+| `--calibration-samples` | integer | `128` | | Number of calibration samples for AWQ/GPTQ |
+| `--registry-id` | text | | | Attach exported artifact to this registry entry (default: auto-match by source --model output dir) |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+| `--quant-config` | text | | | Path to YAML for torchao PTQ export (v0.53.1 #142). Required when --format=torchao. |
+| `--gguf-flavour` | text | | | Advanced GGUF format flag — UD-Q\*\_K_XL / IQ\*\_M / Q4_0_4_4 / etc. Required when --format=gguf-ud (v0.53.1 #139). |
+| `--hub` | text | `hf` | | Source hub for the base model when --model is a LoRA adapter: hf (default) / modelscope / modelers (v0.53.10 #152). |
+
+## `soup fetch`
+
+Fetch a ready-to-edit example config from the bundled catalog.
+
+Usage: `soup fetch [OPTIONS] NAMESPACE [NAME]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAMESPACE` | text | | yes | One of: examples, configs, deepspeed_configs. |
+| `NAME` | text | | | Catalog entry name (omit to list). |
+| `--output`, `-o` | text | | | Destination path (default: ./&lt;filename> in cwd). |
+| `--force` | flag | off | | Overwrite if --output already exists. |
+
+## `soup history`
+
+Show the lineage tree for all entries with a given name.
+
+Usage: `soup history NAME`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME` | text | | yes | Registry entry name to trace (e.g. 'medical-chat') |
+
+## `soup infer`
+
+Run batch inference on a JSONL file of prompts.
+
+Usage: `soup infer [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | yes | Path to model (LoRA adapter or full model) |
+| `--input`, `-i` | text | | yes | Path to input JSONL file (each line: {"prompt": "..."}) |
+| `--output`, `-o` | text | | yes | Path to output JSONL file for results |
+| `--base`, `-b` | text | | | Base model for LoRA adapter (auto-detected if not set) |
+| `--max-tokens` | integer, 1 to 16384 | `256` | | Maximum tokens to generate per response (1-16384) |
+| `--temperature`, `-t` | float | `0.7` | | Sampling temperature (0 = greedy) |
+| `--batch-size` | integer, at least 1 | `1` | | Number of causal-LM prompts to generate together (default: 1; batching is opt-in; fp16/bf16 batching may not be bit-exact with batch size 1) |
+| `--device` | text | | | Device: cuda, mps, cpu. Auto-detected if not set. |
+| `--task` | text | `text` | | Inference task: 'text' (default, chat generation) or 'asr' (Whisper transcription; input rows are {"audio": path\[, "text": reference]}). |
+| `--asr-language` | text | | | ASR decode language (overrides the training sidecar). --task asr only. |
+| `--asr-task` | text | | | ASR decode objective: transcribe \| translate. --task asr only. |
+| `--audio-dir` | text | | | Base directory audio paths in --input must stay under (--task asr; defaults to the --input file's directory). Traversal / UNC paths are rejected. |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+| `--hub` | text | `hf` | | Source hub for the base model: hf (default) / modelscope / modelers. Non-HF hubs require the matching SDK (v0.53.10 #152). |
+| `--cuda-graphs` | flag | off | | Experimental CUDA graph decode for resident, unquantized Qwen2/Llama models. |
+
+## `soup ingest`
+
+Universal trace importer: Langfuse / LangSmith / Helicone / OpenPipe / OTel / OpenAI Stored Completions (v0.63.0).
+
+Usage: `soup ingest [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--source` | text | | yes | Trace source: langfuse \| langsmith \| helicone \| openpipe \| otel \| openai-stored |
+| `--logs` | text | | | Path to JSONL trace export (one event per line). Required unless --pull. |
+| `--output`, `-o` | text | | | Output JSONL (default: traces.jsonl in cwd). |
+| `--pull` | flag | off | | Fetch generations live from the Langfuse API instead of reading --logs (--source langfuse only). Reads LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY, plus LANGFUSE_HOST for another region or a self-hosted instance. |
+| `--since` | text | | | With --pull: how far back to fetch, e.g. 30m, 24h, 7d (default 7d, max 365d). |
+| `--max-pages` | integer, 1 to 10000 | | | With --pull: stop with an error, writing nothing, if results are still pending after this many pages of 100 generations (default 100). |
+| `--allow-private-host` | flag | off | | With --pull: allow LANGFUSE_HOST to be a private or loopback address (self-hosted Langfuse). HTTPS is still required. |
+| `--slack-url` | text | | | Optional Slack webhook URL — POSTed on completion. SSRF-validated. |
+| `--discord-url` | text | | | Optional Discord webhook URL — POSTed on completion. SSRF-validated. |
+
+## `soup init`
+
+Create a new soup.yaml config interactively or from a template.
+
+Usage: `soup init [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--template`, `-t` | text | | | Template: audio, bco, chat, code, embedding, eu-ai-act, hipaa, ipo, kto, longcontext, medical, moe, orpo, pretrain, reasoning, rlhf, simpo, soc2, sr-11-7, tool-calling, vision |
+| `--output`, `-o` | text | `soup.yaml` | | Output config file path |
+| `--force`, `-f` | flag | off | | Overwrite existing config without prompting (v0.40.1 / M2). |
+
+## `soup iterative-dpo`
+
+Iterative DPO sample, score, pair, and train loop.
+
+Usage: `soup iterative-dpo [OPTIONS] [<command>] [ARGS]...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--base-model` | text | | yes | HF id / local path |
+| `--reward-model` | text | | yes | RM HF id / path |
+| `--prompts` | text | | yes | Source prompts JSONL |
+| `--output-dir` | text | | yes | Output dir |
+| `--rounds` | integer | `3` | | Number of iterative-DPO rounds |
+| `--pairs-per-round` | integer | `500` | | Number of (chosen, rejected) pairs per round |
+| `--plan-only` | flag | off | | Print the resolved plan and exit (no training). |
+
+## `soup license-advisor`
+
+Recommend a license-clean base for a deploy target (b2c / defense / embedded) + flag downstream risk (v0.64.0).
+
+Usage: `soup license-advisor [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--target`, `-t` | text | | yes | Deploy target: b2c \| defense \| embedded. |
+| `--license` | text | | | Optional: per-license risk check (e.g. apache-2.0, llama-3). |
+| `--monthly-active-users`, `--mau` | integer | `0` | | Expected MAU for the per-license risk check (default 0). |
+
+## `soup llama`
+
+Proxy to llama.cpp binaries (cli / mtmd-cli / gguf-split / server).
+
+Usage: `soup llama [<command>] [ARGS]...`
+
+Subcommands:
+
+- [`cli`](#soup-llama-cli)
+- [`gguf-split`](#soup-llama-gguf-split)
+- [`mtmd-cli`](#soup-llama-mtmd-cli)
+- [`quantize`](#soup-llama-quantize)
+- [`server`](#soup-llama-server)
+
+### `soup llama cli`
+
+Forward args to llama.cpp binary llama-cli.
+
+Usage: `soup llama cli [ARGS]...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ARGS...` | text, any number | | | Args forwarded to llama-cli. |
+
+### `soup llama gguf-split`
+
+Forward args to llama.cpp binary llama-gguf-split.
+
+Usage: `soup llama gguf-split [ARGS]...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ARGS...` | text, any number | | | Args forwarded to llama-gguf-split. |
+
+### `soup llama mtmd-cli`
+
+Forward args to llama.cpp binary llama-mtmd-cli.
+
+Usage: `soup llama mtmd-cli [ARGS]...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ARGS...` | text, any number | | | Args forwarded to llama-mtmd-cli. |
+
+### `soup llama quantize`
+
+Forward args to llama.cpp binary llama-quantize.
+
+Usage: `soup llama quantize [ARGS]...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ARGS...` | text, any number | | | Args forwarded to llama-quantize. |
+
+### `soup llama server`
+
+Forward args to llama.cpp binary llama-server.
+
+Usage: `soup llama server [ARGS]...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ARGS...` | text, any number | | | Args forwarded to llama-server. |
+
+## `soup local-rl`
+
+Personal-LLM flywheel daemon (init / status / record / harvest / train) (v0.68.0).
+
+Usage: `soup local-rl <command> [ARGS]...`
+
+Subcommands:
+
+- [`harvest`](#soup-local-rl-harvest)
+- [`init`](#soup-local-rl-init)
+- [`record`](#soup-local-rl-record)
+- [`status`](#soup-local-rl-status)
+- [`train`](#soup-local-rl-train)
+
+### `soup local-rl harvest`
+
+Harvest DPO pairs from thumbs into a JSONL file.
+
+Usage: `soup local-rl harvest [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--db` | text | `local_rl.db` | | Path to local-RL SQLite database |
+| `--output`, `-o` | text | `dpo_pairs.jsonl` | | Output JSONL path |
+
+### `soup local-rl init`
+
+Create the local-RL SQLite schema.
+
+Usage: `soup local-rl init [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--db` | text | `local_rl.db` | | Path to local-RL SQLite database |
+
+### `soup local-rl record`
+
+Append a thumbs-up / thumbs-down record.
+
+Usage: `soup local-rl record [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--db` | text | `local_rl.db` | | Path to local-RL SQLite database |
+| `--prompt` | text | | yes | Prompt text |
+| `--response` | text | | yes | Model response |
+| `--thumb` | text | | yes | up / down |
+
+### `soup local-rl status`
+
+Print counters from the local-RL database.
+
+Usage: `soup local-rl status [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--db` | text | `local_rl.db` | | Path to local-RL SQLite database |
+
+### `soup local-rl train`
+
+Run (``--once``) or schedule the nightly DPO/KTO/ORPO train.
+
+Usage: `soup local-rl train [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--db` | text | `local_rl.db` | | Path to local-RL SQLite database |
+| `--backend` | text | | | Accepted for compatibility; has no effect on training. Allowed: mlx, ollama |
+| `--model` | text | | yes | Training base — HF repo id or local path (NOT the Ollama tag) |
+| `--train-method` | text | `dpo` | | Allowed: dpo, kto, orpo |
+| `--once` | flag | off | | Run the train now (ad-hoc); skip scheduler install. |
+| `--min-pairs` | integer | `10` | | Skip training when fewer pairs are harvested. |
+| `--output`, `-o` | text | `local_rl_adapter` | | Adapter output directory |
+| `--scheduler-dir` | text | `local-rl-scheduler` | | Directory to render the systemd / launchd scaffold into. |
+| `--hour` | integer | `3` | | Daily train hour (local time). |
+| `--minute` | integer | `0` | | Daily train minute. |
+
+## `soup lock`
+
+Shared run lockfile (write / show / check).
+
+Usage: `soup lock <command> [ARGS]...`
+
+Subcommands:
+
+- [`check`](#soup-lock-check)
+- [`show`](#soup-lock-show)
+- [`write`](#soup-lock-write)
+
+### `soup lock check`
+
+Refuse with exit 2 if the lock has drifted from current state.
+
+Usage: `soup lock check [OPTIONS] [PATH]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | `soup.lock` | | Path to tracked soup.lock |
+| `--base-sha` | text | | yes | 64-hex current base-model SHA |
+| `--dataset-sha` | text | | yes | 64-hex current dataset SHA |
+| `--env-hash` | text | | yes | 64-hex current env hash |
+| `--base-model` | text | | yes | Current base model id |
+
+### `soup lock show`
+
+Print a tracked lock file.
+
+Usage: `soup lock show [PATH]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `PATH` | text | `soup.lock` | | Path to soup.lock |
+
+### `soup lock write`
+
+Render a ``soup.lock`` from the base/dataset/env hashes.
+
+Usage: `soup lock write [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--base-model` | text | | yes | HF model id / path |
+| `--base-sha` | text | | yes | 64-hex base-model SHA |
+| `--dataset-sha` | text | | yes | 64-hex dataset SHA |
+| `--env-hash` | text | | | 64-hex env hash. If omitted, auto-derived from --env-lock (soup-env.lock) via `soup env lock`. |
+| `--env-lock` | text | `soup-env.lock` | | Path to a soup-env.lock to auto-derive --env-hash from (used only when --env-hash is omitted). |
+| `--output`, `-o` | text | `soup.lock` | | Output path |
+
+## `soup loop`
+
+Data flywheel: traces -> preference pairs -> DPO -> gate -> canary deploy -> rollback, all from the CLI (v0.58.0).
+
+Usage: `soup loop <command> [ARGS]...`
+
+Subcommands:
+
+- [`canary`](#soup-loop-canary)
+- [`init`](#soup-loop-init)
+- [`pause`](#soup-loop-pause)
+- [`replay`](#soup-loop-replay)
+- [`resume`](#soup-loop-resume)
+- [`status`](#soup-loop-status)
+- [`watch`](#soup-loop-watch)
+
+### `soup loop canary`
+
+Promote ``new_adapter`` as the canary with a traffic split.
+
+Usage: `soup loop canary [OPTIONS] NEW_ADAPTER`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NEW_ADAPTER` | text | | yes | Adapter id/path to canary. |
+| `--traffic` | text | `5%` | | Traffic share, e.g. "5%" or "5". |
+| `--autoroll-on-regress` / `--no-autoroll-on-regress` | flag | on | | Roll back automatically on MAJOR verdict. |
+
+### `soup loop init`
+
+Create the .soup/loop.yaml control file (one-time setup).
+
+Usage: `soup loop init [OPTIONS] SERVED_MODEL`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `SERVED_MODEL` | text | | yes | Served model id (e.g. registry://abc12). |
+| `--eval` | text | | yes | Eval suite path or registry ref. |
+| `--baseline` | text | | yes | Baseline registry id or file. |
+| `--monthly-budget` | text | | | Monthly USD cap (e.g. 50usd, 100). |
+| `--max-runs-per-day` | integer | | | Cap on iteration starts per UTC day. |
+| `--pre-wired` | flag | off | | Use the pre-wired harvest/train/gate/deploy stages (utils/loop_stages.py) on watch instead of no-op stubs (v0.71.4). |
+| `--force` | flag | off | | Overwrite existing loop.yaml. |
+
+### `soup loop pause`
+
+Pause the watch daemon at the next iteration boundary.
+
+Usage: `soup loop pause`
+
+Takes no options or arguments.
+
+### `soup loop replay`
+
+Replay a recorded loop iteration manifest.
+
+Usage: `soup loop replay [OPTIONS] [ITERATION_ID]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `ITERATION_ID` | text | | | Iteration id (omit to list all). |
+| `--extract` | text | | | Extract the iteration's .can to this directory for a what-if re-run (v0.71.4). |
+
+### `soup loop resume`
+
+Resume a paused loop (next watch iteration picks up automatically).
+
+Usage: `soup loop resume`
+
+Takes no options or arguments.
+
+### `soup loop status`
+
+Show counters and current status.
+
+Usage: `soup loop status`
+
+Takes no options or arguments.
+
+### `soup loop watch`
+
+Run the harvest → train → gate → deploy daemon.
+
+Usage: `soup loop watch [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--foreground` | flag | off | | Run in foreground (default). |
+| `--detach` | flag | off | | Spawn a background subprocess running --foreground. |
+| `--max-iterations` | integer | | | Stop after N iterations (test/demo use). |
+| `--poll-interval` | float | `60.0` | | Seconds between iterations \[1, 3600]. |
+| `--pre-wired` | flag | off | | Force the pre-wired production stages even if loop.yaml didn't set it. |
+| `--pack-cans` | flag | off | | Pack each iteration as a v0.26 Soup Can + Registry entry (v0.71.4). |
+
+## `soup mcp`
+
+Model Context Protocol server - drive Soup from any MCP client (v0.71.28).
+
+Usage: `soup mcp <command> [ARGS]...`
+
+Subcommands:
+
+- [`runs`](#soup-mcp-runs)
+- [`serve`](#soup-mcp-serve)
+
+### `soup mcp runs`
+
+Recover persisted MCP execution runs.
+
+Usage: `soup mcp runs <command> [ARGS]...`
+
+Subcommands:
+
+- [`reconcile`](#soup-mcp-runs-reconcile)
+
+#### `soup mcp runs reconcile`
+
+Recover execution capacity left blocked by a crashed MCP server.
+
+Usage: `soup mcp runs reconcile [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--expunge-launching` | flag | off | | Delete stale launching rows after checking that no recorded PID is alive. |
+| `--older-than-seconds` | integer, at least 1 | `300` | | Only consider launching rows at least this many seconds old. |
+
+### `soup mcp serve`
+
+Start the MCP server (read-only tools by default).
+
+Usage: `soup mcp serve [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--allow-mutating` | flag | off | | Enable the plan-only mutating tools (train_start / export). Even when enabled they only render the command that would run - v1 never executes training or export. Off by default: those tools refuse. |
+| `--allow-execute` | flag | off | | Reserve the execution gate for future MCP tools. Implies --allow-mutating, but train_start and export remain plan-only and never execute in this version. |
+| `--transport` | text | `stdio` | | stdio (default), sse, or http. stdio speaks JSON-RPC over the process pipes and is what a client that spawns Soup wants. sse and http open a local listener instead, for remote or multi-client setups, and require a Bearer token. |
+| `--host` | text | | | Interface to bind for --transport sse/http. Defaults to 127.0.0.1. Binding anything else exposes the server to the network, where the Bearer token is the only gate. |
+| `--port` | integer | | | Port to bind for --transport sse/http. Defaults to 8765. |
+| `--auth-token` | text | | | Override the auto-generated Bearer token (16-128 urlsafe base64 chars) for --transport sse/http. When omitted, a fresh token is generated each startup and printed. |
+
+## `soup merge`
+
+Merge a LoRA adapter with its base model into a full model.
+
+Usage: `soup merge [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--adapter`, `-a` | text | | yes | Path to the LoRA adapter directory |
+| `--base`, `-b` | text | | | Base model ID. Auto-detected from adapter_config.json if not set. |
+| `--output`, `-o` | text | `./merged` | | Output directory for the merged model |
+| `--dtype` | text | `float16` | | Data type for the merged model: float16, bfloat16, float32 |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+| `--save-format` | text | `fp16` | | Merged-checkpoint save format. fp16 (default) writes a standard fp16 merge. 4bit / 4bit_forced write a single BNB-4bit-quantized merge without the dequant-merge-requant cycle (v0.53.1 #142). |
+| `--double-quant` / `--no-double-quant` | flag | on | | BNB double-quantization for the 4bit / 4bit_forced save formats (#321). Default on, matching the training loaders; pass --no-double-quant to disable. Ignored for the fp16 save format. |
+| `--hub` | text | `hf` | | Source hub for the base model: hf (default) / modelscope / modelers. Non-HF hubs require the matching SDK (v0.53.10 #152). |
+
+## `soup merge-sharded-fsdp-weights`
+
+Consolidate FSDP shard files into a single safetensors file.
+
+Usage: `soup merge-sharded-fsdp-weights [OPTIONS] SHARD_DIR`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `SHARD_DIR` | text | | yes | Directory containing pytorch_model_fsdp\_\*.bin shard files. |
+| `--output`, `-o` | text | | yes | Destination .safetensors file path (under cwd). |
+| `--plan-only` | flag | off | | Print the consolidation plan and exit without writing anything. |
+
+## `soup migrate`
+
+Import a config from LLaMA-Factory, Axolotl, or Unsloth notebook.
+
+Usage: `soup migrate [OPTIONS] CONFIG_FILE`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--from` | text | | yes | Source tool: llamafactory, axolotl, or unsloth |
+| `CONFIG_FILE` | text | | yes | Path to the source config file (.yaml or .ipynb) |
+| `--output`, `-o` | text | `soup.yaml` | | Output path for generated soup.yaml |
+| `--dry-run` | flag | off | | Print generated config without writing to file |
+| `--yes`, `-y` | flag | off | | Skip confirmation prompts |
+
+## `soup monitor`
+
+Live GPU monitor: Util / Temp / VRAM / Power per GPU.
+
+Usage: `soup monitor [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--refresh`, `-r` | float | `2.0` | | Refresh interval in seconds (0.25 to 30). |
+| `--once` | flag | off | | Print one snapshot and exit (skip the live panel). |
+
+## `soup plan`
+
+Render a pre-flight training plan (cost / ETA / SHA / VRAM) and write soup.tfstate for `soup apply` to consult (v0.64.0).
+
+Usage: `soup plan [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--config`, `-c` | text | `soup.yaml` | | Path to soup.yaml. |
+| `--state` | text | `soup.tfstate` | | Path to write the state file (default: ./soup.tfstate). |
+
+## `soup plugins`
+
+Discover, list, enable, and disable Soup plugins.
+
+Usage: `soup plugins [<command>] [ARGS]...`
+
+Subcommands:
+
+- [`disable`](#soup-plugins-disable)
+- [`enable`](#soup-plugins-enable)
+- [`install`](#soup-plugins-install)
+- [`list`](#soup-plugins-list)
+
+### `soup plugins disable`
+
+Usage: `soup plugins disable NAME`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME` | text | | yes | Plugin name |
+
+### `soup plugins enable`
+
+Usage: `soup plugins enable NAME`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME` | text | | yes | Plugin name |
+
+### `soup plugins install`
+
+Explain how to install plugins without pretending an install occurred.
+
+Usage: `soup plugins install NAME`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME` | text | | yes | Plugin name |
+
+### `soup plugins list`
+
+List all registered plugins.
+
+Usage: `soup plugins list`
+
+Takes no options or arguments.
+
+## `soup probe`
+
+Activation probes: sleeper-agent defection / honesty / misuse / pairwise interference / SAE feature diff / probe pack (v0.66.0, truth+harm v0.71.8).
+
+Usage: `soup probe <command> [ARGS]...`
+
+Subcommands:
+
+- [`harm`](#soup-probe-harm)
+- [`interference`](#soup-probe-interference)
+- [`pack`](#soup-probe-pack)
+- [`sae-diff`](#soup-probe-sae-diff)
+- [`sleeper`](#soup-probe-sleeper)
+- [`truth`](#soup-probe-truth)
+
+### `soup probe harm`
+
+Apply the HarmBench-style misuse probe to activations (v0.71.8 #217).
+
+Usage: `soup probe harm [OPTIONS] BASE`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `BASE` | text | | yes | Base model id (must have a bundled probe) |
+| `--evidence` | text | | | JSON with 'activations': \[\[...], ...] (2D float matrix) |
+| `--weights` | text | | | Operator-supplied calibrated probe weights (.npz / .npy / .safetensors) |
+| `--output`, `-o` | text | | | Write probe result JSON to path |
+
+### `soup probe interference`
+
+Pairwise N×N adapter interference matrix (v0.66.0; --measure v0.71.8 #218).
+
+Usage: `soup probe interference [OPTIONS] [LOSSES]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `LOSSES` | text | | | JSON: {adapters: \[...], losses: {'a\|b': loss_value, ...}} |
+| `--measure` | text | | | Auto-measure losses against this eval-suite JSONL instead of supplying a losses JSON. Requires --base-model + ≥2 --adapter (v0.71.8 #218). |
+| `--base-model` | text | | | Base model id for --measure |
+| `--adapter` | text, repeatable | | | name=path adapter spec for --measure (repeatable) |
+| `--device` | text | | | Device for --measure (cpu / cuda) |
+| `--output`, `-o` | text | | | Write matrix JSON to path |
+
+### `soup probe pack`
+
+Assemble or list calibrated probe packs for a base (v0.66.0).
+
+Usage: `soup probe pack [OPTIONS] [BASE]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `BASE` | text | | | Base model id (e.g. meta-llama/Llama-3-8B) |
+| `--list` | flag | off | | List all bases that ship a probe pack |
+| `--output`, `-o` | text | | | Write pack manifest JSON to path |
+
+### `soup probe sae-diff`
+
+SAE feature diff between pre- and post-FT activations (v0.66.0).
+
+Usage: `soup probe sae-diff [OPTIONS] SAE PRE_ACTS POST_ACTS`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `SAE` | text | | yes | Path to SAE safetensors checkpoint (or repo id with --auto-download) |
+| `PRE_ACTS` | text | | yes | JSON: {'activations': \[\[...]]} |
+| `POST_ACTS` | text | | yes | JSON: {'activations': \[\[...]]} |
+| `--top-k` | integer, 1 to 10000 | `20` | | Top-K changed features to report |
+| `--auto-download` | flag | off | | Treat &lt;sae> as an HF Hub repo id and download it into \~/.soup/sae-cache/ first (must be in HF_HUB_ALLOWLIST; v0.71.8 #216). |
+| `--output`, `-o` | text | | | Write diff report JSON to path |
+
+### `soup probe sleeper`
+
+Apply the sleeper-agent defection probe to activations (v0.66.0).
+
+Usage: `soup probe sleeper [OPTIONS] BASE`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `BASE` | text | | yes | Base model id (must have a bundled probe) |
+| `--evidence` | text | | | JSON with 'activations': \[\[...], ...] (2D float matrix) |
+| `--weights` | text | | | Operator-supplied calibrated probe weights (.npz / .npy / .safetensors). When set, replaces the synthetic seed fallback and accepts any base id (v0.71.8 #215). |
+| `--output`, `-o` | text | | | Write probe result JSON to path |
+
+### `soup probe truth`
+
+Apply the TruthfulQA-style honesty probe to activations (v0.71.8 #217).
+
+Usage: `soup probe truth [OPTIONS] BASE`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `BASE` | text | | yes | Base model id (must have a bundled probe) |
+| `--evidence` | text | | | JSON with 'activations': \[\[...], ...] (2D float matrix) |
+| `--weights` | text | | | Operator-supplied calibrated probe weights (.npz / .npy / .safetensors) |
+| `--output`, `-o` | text | | | Write probe result JSON to path |
+
+## `soup profile`
+
+Estimate memory, speed, and GPU requirements BEFORE training.
+
+Usage: `soup profile [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--config`, `-c` | text | `soup.yaml` | | Path to soup.yaml config file |
+| `--gpu`, `-g` | text | | | Target GPU for recommendations (e.g., rtx3090, rtx4090, a100, h100). Auto-detects if not set. |
+| `--json` | flag | off | | Output as JSON for scripting |
+
+## `soup prune-prompt`
+
+Detect + strip a shared system-prompt prefix across training data so the FT model internalises it (v0.63.0).
+
+Usage: `soup prune-prompt [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | Input JSONL with {prompt, output} rows (e.g. from `soup ingest`). |
+| `--output`, `-o` | text | | yes | Output JSONL with the shared prefix stripped from `prompt`. |
+| `--min-frequency` | float | `0.95` | | Prefix must appear in >= this fraction of rows to be stripped (0.0 - 1.0). |
+| `--tokenizer` | text | | | Optional HF tokenizer (model id or local path) for token-aware prefix detection. Default: whitespace-character level. |
+| `--slack-url` | text | | | Optional Slack webhook URL — POSTed on completion. SSRF-validated. |
+| `--discord-url` | text | | | Optional Discord webhook URL — POSTed on completion. SSRF-validated. |
+
+## `soup push`
+
+Push a trained model to HuggingFace Hub (or alternate hub).
+
+Usage: `soup push [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | yes | Path to the trained model / LoRA adapter directory |
+| `--repo`, `-r` | text | | yes | HuggingFace repo ID, e.g. username/my-model |
+| `--private` | flag | off | | Make the HuggingFace repo private |
+| `--token`, `-t` | text | | | Upload token. For --hub hf: \[deprecated] use HF_TOKEN or cached login. For other hubs: that hub's token (or MODELSCOPE_API_TOKEN / MODELERS_TOKEN). Env: `HF_TOKEN`. |
+| `--message` | text | `Upload model trained with Soup CLI` | | Commit message for the upload |
+| `--collection` | text | | | Add the pushed repo to an existing HF Collection (slug: 'owner/title-hash') |
+| `--hub` | text | `hf` | | Destination hub: hf (default) / modelscope / modelers. Non-HF hubs require the matching SDK and skip the HF-specific Collections / model-card auto-render path (v0.53.10 #152). |
+| `--card` | text | | | Registry entry id / prefix / name:tag — render its provenance-rich model card (via `soup card`) and upload it as README.md, overriding the auto-generated card (v0.71.35). HF hub only. |
+
+## `soup quantize`
+
+Quantize a model - ergonomic alias for `soup export --format <to>`.
+
+Usage: `soup quantize [OPTIONS] MODEL_PATH`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `MODEL_PATH` | text | | yes | Source checkpoint (safetensors directory or single .safetensors). |
+| `--to` | text | `gguf` | | Target format: gguf \| gptq \| awq \| onnx \| tensorrt (awq and gptq are deprecated and will be removed in Soup v0.77). |
+| `--bits` | integer | `4` | | Quantization bits (1-16; respected by gguf/gptq/awq). |
+| `--output`, `-o` | text | | | Destination directory (default: &lt;model_path>-&lt;to>). |
+
+## `soup quickstart`
+
+Run a complete demo: create sample data, config, and train.
+
+Usage: `soup quickstart [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--yes`, `-y` | flag | off | | Skip confirmation prompt |
+| `--dry-run` | flag | off | | Create data and config only, do not train |
+| `--output`, `-o` | text | | | Output directory for data, config, and run artifacts (default: current directory). |
+
+## `soup ra-dit`
+
+RA-DIT two-stage orchestrator: retriever -> generator (v0.71.10).
+
+Usage: `soup ra-dit [OPTIONS] [<command>] [ARGS]...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--retriever-config`, `-r` | text | | yes | Stage-1 embedding/contrastive recipe (cwd-contained). |
+| `--generator-config`, `-g` | text | | yes | Stage-2 RAFT-SFT recipe (cwd-contained). |
+| `--retriever-model` | text | | | Manual retriever-model override; skips Registry auto-link. |
+| `--timeout` | integer | `21600` | | Per-stage hard timeout in seconds (60..21600). |
+| `--plan-only` | flag | off | | Validate config paths + render the plan; skip training. |
+
+## `soup recipes`
+
+Ready-made configs: list, show, use, search recipes for popular models.
+
+Usage: `soup recipes <command> [ARGS]...`
+
+Subcommands:
+
+- [`list`](#soup-recipes-list)
+- [`search`](#soup-recipes-search)
+- [`show`](#soup-recipes-show)
+- [`use`](#soup-recipes-use)
+- [`verify`](#soup-recipes-verify)
+
+### `soup recipes list`
+
+List all available recipes.
+
+Usage: `soup recipes list`
+
+Takes no options or arguments.
+
+### `soup recipes search`
+
+Search recipes by keyword, task, or model size.
+
+Usage: `soup recipes search [OPTIONS] [QUERY]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `QUERY` | text | | | Search keyword |
+| `--task` | text | | | Filter by task |
+| `--size` | text | | | Filter by model size |
+
+### `soup recipes show`
+
+Show a recipe config (print YAML to stdout).
+
+Usage: `soup recipes show NAME`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME` | text | | yes | Recipe name |
+
+### `soup recipes use`
+
+Copy a recipe to soup.yaml (or custom path).
+
+Usage: `soup recipes use [OPTIONS] NAME`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `NAME` | text | | yes | Recipe name |
+| `--output`, `-o` | text | `soup.yaml` | | Output path for config file |
+| `--yes`, `-y` | flag | off | | Skip confirmation prompts |
+
+### `soup recipes verify`
+
+Check that a config can attach a LoRA adapter, without downloading weights.
+
+Usage: `soup recipes verify [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--config`, `-c` | text | | | Verify one config instead of the whole catalogue. |
+| `--json` | flag | off | | Machine-readable rows on stdout. |
+| `--templates` / `--no-templates` | flag | on | | Also verify src/soup_cli/templates and examples/ (catalogue mode). |
+
+## `soup registry`
+
+Model Registry: push, list, show, diff, search, promote, delete.
+
+Usage: `soup registry <command> [ARGS]...`
+
+Subcommands:
+
+- [`delete`](#soup-registry-delete)
+- [`diff`](#soup-registry-diff)
+- [`list`](#soup-registry-list)
+- [`promote`](#soup-registry-promote)
+- [`push`](#soup-registry-push)
+- [`search`](#soup-registry-search)
+- [`show`](#soup-registry-show)
+
+### `soup registry delete`
+
+Delete a registry entry and its lineage / artifact rows.
+
+Usage: `soup registry delete [OPTIONS] REF`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `REF` | text | | yes | Entry ref to delete |
+| `--yes`, `-y` | flag | off | | Skip confirmation |
+
+### `soup registry diff`
+
+Side-by-side config + eval delta between two entries.
+
+Usage: `soup registry diff LEFT RIGHT`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `LEFT` | text | | yes | Left entry ref |
+| `RIGHT` | text | | yes | Right entry ref |
+
+### `soup registry list`
+
+List registry entries.
+
+Usage: `soup registry list [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--name`, `-n` | text | | | |
+| `--tag`, `-t` | text | | | |
+| `--base`, `-b` | text | | | |
+| `--task` | text | | | |
+| `--limit`, `-l` | integer | `100` | | |
+
+### `soup registry promote`
+
+Add a tag to an existing entry (e.g. promote to 'prod').
+
+Usage: `soup registry promote [OPTIONS] REF`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `REF` | text | | yes | Entry ref to promote |
+| `--tag`, `-t` | text | | yes | Tag to assign |
+
+### `soup registry push`
+
+Register a completed training run as a registry entry.
+
+Usage: `soup registry push [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--run-id` | text | | yes | Training run id to register |
+| `--name`, `-n` | text | | yes | Registry entry name |
+| `--tag`, `-t` | text | `v1` | | Tag (e.g. v1, prod-2024) |
+| `--notes` | text | `""` | | Free-form notes |
+
+### `soup registry search`
+
+Search registry entries by name/base/task/notes.
+
+Usage: `soup registry search [OPTIONS] QUERY`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `QUERY` | text | | yes | Keyword to search for |
+| `--limit`, `-l` | integer | `50` | | |
+
+### `soup registry show`
+
+Show full details of a registry entry.
+
+Usage: `soup registry show REF`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `REF` | text | | yes | Entry id / prefix / name:tag |
+
+## `soup reward`
+
+Synthesize a deterministic reward verifier from reference outputs, with a calibration report that refuses degenerate verifiers (v0.71.40).
+
+Usage: `soup reward <command> [ARGS]...`
+
+Subcommands:
+
+- [`stress`](#soup-reward-stress)
+- [`synth`](#soup-reward-synth)
+
+### `soup reward stress`
+
+Adversarially probe a reward verifier for gameability (exit 0 robust / 2 gameable).
+
+Usage: `soup reward stress [OPTIONS] REWARD_TARGET`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `REWARD_TARGET` | text | | yes | Verifier to probe: a .py path, a builtin name, or 'verifiable'. |
+| `--references` | text | | | JSONL of gold outputs (enables gold-aware probing). |
+| `--field` | text | `answer` | | Gold field (default: answer). |
+| `--verifiable-domain` | text | | | Domain for a 'verifiable' target. |
+| `--sentinel` | text | `GOLD` | | Sentinel-spam token. |
+| `--threshold` | float | `0.5` | | Reward >= this = accept. |
+| `--max-gameable` | float | `0.0` | | Max junk accept-rate allowed before the verdict flips to gameable. |
+| `--attacks` | text | `empty,length,repetition,sentinel,wrapped_junk,answer_spray` | | Comma list: empty,length,repetition,sentinel,wrapped_junk,answer_spray. |
+| `--output-report` | text | | | Also write the stress report as JSON. |
+
+### `soup reward synth`
+
+Synthesize a deterministic reward verifier from reference outputs.
+
+Usage: `soup reward synth [OPTIONS] REFERENCES`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `REFERENCES` | text | | yes | JSONL of reference (gold) outputs — a gold field or chat messages. |
+| `-o`, `--output` | text | | | Where to write the verifier .py. |
+| `--kind` | text | `auto` | | Verifier family: auto \| numeric \| json_schema \| regex \| tool_call. |
+| `--field` | text | `answer` | | Gold-output field (default: answer). |
+| `--tolerance` | float | | | Numeric match tolerance (numeric kind only). |
+| `--min-discrimination` | float | `0.5` | | Refuse to emit unless (accept_rate refs - accept_rate negatives) >= this. |
+| `--force` | flag | off | | Overwrite an existing output. |
+| `--plan-only` | flag | off | | Detect + report the induced spec; write nothing. |
+| `--output-report` | text | | | Also write the calibration report as JSON. |
+
+## `soup rewind`
+
+Name the dataset rows behind a loss spike, from the training flight recorder.
+
+Usage: `soup rewind [OPTIONS] [RUN_ID]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | | Run ID (or prefix). Defaults to the most recent run. |
+| `--step` | integer | | | Detail this step instead of the worst spike. |
+| `--top` | integer, at least 1 | `10` | | How many rows to list for the detailed step (at least 1). |
+| `--json` | text | | | Write the spikes and the ranked rows to this path as JSON (must stay under the current directory). |
+| `--no-preview` | flag | off | | Skip the row previews (does not load the dataset). |
+
+## `soup runs`
+
+Experiment tracking: list, show, compare runs.
+
+Usage: `soup runs [OPTIONS] [<command>] [ARGS]...`
+
+Subcommands:
+
+- [`clean`](#soup-runs-clean)
+- [`compare`](#soup-runs-compare)
+- [`curriculum-curve`](#soup-runs-curriculum-curve)
+- [`delete`](#soup-runs-delete)
+- [`replay`](#soup-runs-replay)
+- [`show`](#soup-runs-show)
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--limit`, `-l` | integer | `20` | | Max runs to show |
+| `--cwd-only` | flag | off | | Only show runs whose output_dir is under the current working directory (default: show all in \~/.soup/experiments.db). |
+
+### `soup runs clean`
+
+Intelligently clean up redundant checkpoint files to reclaim disk space.
+
+Usage: `soup runs clean [OPTIONS] [RUN_ID]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | | Run ID (or prefix) to clean. Omit if --all is used. |
+| `--all` | flag | off | | Cleanup all historical runs. |
+| `--dry-run` | flag | off | | Estimate space savings without deleting. |
+| `--force`, `-f` | flag | off | | Skip confirmation |
+| `--keep-weights` / `--no-keep-weights` | flag | on | | Keep intermediate model weights and delete only optimizer and scheduler states (default). --no-keep-weights deletes whole non-best checkpoints. |
+
+### `soup runs compare`
+
+Compare two training runs side by side.
+
+Usage: `soup runs compare RUN_1 RUN_2`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_1` | text | | yes | First run ID (or prefix) |
+| `RUN_2` | text | | yes | Second run ID (or prefix) |
+
+### `soup runs curriculum-curve`
+
+v0.48.0 (BETA) — visualise dynamic curriculum bucket weights.
+
+Usage: `soup runs curriculum-curve [OPTIONS] RUN_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | yes | Run ID (or prefix). |
+| `--history` | text | | | Override path to curriculum_history.jsonl (default: under run output_dir). |
+| `--width` | integer, 4 to 200 | `10` | | Per-bucket column width. |
+
+### `soup runs delete`
+
+Delete a training run and its metrics.
+
+Usage: `soup runs delete [OPTIONS] RUN_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | yes | Run ID (or prefix) to delete |
+| `--force`, `-f` | flag | off | | Skip confirmation |
+
+### `soup runs replay`
+
+Replay a completed run's metrics — re-renders summary + loss curve.
+
+Usage: `soup runs replay [OPTIONS] RUN_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | yes | Run ID (or prefix) to replay. |
+| `--plot` / `--no-plot` | flag | on | | Render loss curve |
+
+### `soup runs show`
+
+Show detailed info about a specific run, including loss curve.
+
+Usage: `soup runs show [OPTIONS] RUN_ID`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | yes | Run ID (or prefix) to show |
+| `--plot` / `--no-plot` | flag | on | | Show loss curve |
+
+## `soup serve`
+
+Start a local inference server with OpenAI-compatible API.
+
+Usage: `soup serve [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | yes | Path to LoRA adapter directory or full model |
+| `--base`, `-b` | text | | | Base model ID. Auto-detected from adapter_config.json if not set. |
+| `--port`, `-p` | integer | `8000` | | Port to serve on |
+| `--host` | text | `127.0.0.1` | | Host to bind to. Defaults to loopback (127.0.0.1). Any other host needs --tool-auth-token, which is checked on the tool, thumbs and adapter routes only: the generation routes take no token. |
+| `--device` | text | | | Device: cuda, cuda:&lt;index>, mps or cpu. Auto-detected if not set. With the transformers backend, cpu loads on the CPU in float32 (unless --kv-cache-type bf16/f16 picks the dtype); cuda:&lt;index> and mps are pinned to that device; cuda uses device_map=auto, all in float16. |
+| `--max-tokens` | integer | `512` | | Default max tokens for generation |
+| `--backend` | text | `transformers` | | Inference backend: transformers (default), vllm, sglang, or mii |
+| `--tensor-parallel`, `--tp` | integer | `1` | | Number of GPUs for tensor parallelism (vLLM only) |
+| `--gpu-memory` | float | `0.9` | | Fraction of GPU memory to use (vLLM only, 0.0-1.0) |
+| `--max-model-len` | integer | | | Maximum sequence length for the vLLM engine (vLLM only). Lower this when the engine refuses to start because the KV cache does not fit. Default: the model's own maximum. |
+| `--speculative-decoding` | text | | | Draft model for speculative decoding (smaller/faster model ID or path) |
+| `--num-speculative-tokens` | integer | `5` | | Number of tokens the draft model generates per step (speculative decoding) |
+| `--adapters` | text, repeatable | | | LoRA adapters as name=path pairs (repeatable). E.g. chat=./chat-adapter |
+| `--prefix-cache` | flag | off | | Enable vLLM prefix caching for shared system prompts (RAG/agent workloads). |
+| `--auto-spec` | flag | off | | Auto-pair draft model for speculative decoding based on target model. |
+| `--structured-output` | text | `off` | | Constrain generation: off (default) \| json \| regex. |
+| `--json-schema` | text | | | Path to JSON schema file (used with --structured-output json). |
+| `--regex-pattern` | text | | | Regex pattern (used with --structured-output regex). |
+| `--dashboard` | flag | off | | Enable live continuous-batching dashboard + /metrics endpoint. |
+| `--trace` | flag | off | | Enable OpenTelemetry request tracing (requires opentelemetry-sdk). |
+| `--trace-endpoint` | text | | | OTLP endpoint URL (default: http://localhost:4317). |
+| `--auto-quant` | flag | off | | Unavailable until Soup can measure each loaded candidate; the command refuses instead of guessing a format. |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+| `--trace-log` | text | | | Append per-request {prompt, response, latency_ms, tokens, ts} to JSONL at this path. Path must stay under cwd. Rotates at 100 MB (one backup retained). Added in v0.40.3 (#33). |
+| `--trace-log-cap-mb` | integer | `100` | | Rotation cap in MB for --trace-log (1 - 10000). Default 100. |
+| `--record-thumbs` | text | | | Auto-capture thumbs-up/down feedback into a local-rl SQLite at this path via POST /v1/thumbs. Path must stay under cwd. Transformers backend only. v0.71.1 (#230). |
+| `--reasoning-parser` | text | | | Strip reasoning-trace blocks from responses. One of: deepseek-r1 \| qwen3 \| phi4 \| openthinker. v0.53.9 #98. |
+| `--steer` | text | | | Apply a stored activation-steering vector at decode time (CAA / ITI / RepE). Pass the name registered via `soup steer train`; the transformers backend installs the decode hook after loading the model. |
+| `--steer-strength` | float | `1.0` | | Steering strength multiplier (\|s\| &lt;= 10.0). Ignored when --steer is unset. |
+| `--hub` | text | `hf` | | Source hub for the base model: hf (default) / modelscope / modelers. Non-HF hubs require the matching SDK (v0.53.10 #152). |
+| `--bank` | text | | | Path to a VeRA / VB-LoRA vector bank (JSON). Multi-tenant LoRA serving at MB-per-user: the per-token delta is v_u ⊙ Px, routed by the X-User-Id request header. Requires --backend transformers. (v0.71.12 #221) |
+| `--bank-strength` | float | `1.0` | | Vector-bank delta strength multiplier. Ignored when --bank is unset. |
+| `--mole` | text | | | Path to a MoLE training output dir (mole_gate.pt + mole_manifest.json). Serves the base + N frozen task LoRAs with per-token gate blending at decode time. Requires --backend transformers; not combinable with --bank / --steer / --adapters. (v0.71.17 #259) |
+| `--kv-cache-type` | text | | | KV-cache type for decoding: q8_0 (8-bit quantized, needs hqq) / bf16 / f16 (cache dtype) / fp8 (vLLM+Hopper only). Transformers backend only — vLLM / SGLang routing is in the blocked tail. v0.71.14 (#140). |
+| `--tool-auth-token` | text | | | Require 'Authorization: Bearer &lt;token>' on the code-exec tool endpoints (/v1/tools/python, /v1/tools/web_search). Strongly recommended whenever --host is not loopback, since those endpoints run caller-supplied Python in a best-effort sandbox. |
+
+## `soup ship`
+
+SHIP / DON'T SHIP verdict after fine-tuning: task win AND no catastrophic forgetting, fused into one decision (v0.71.25).
+
+Usage: `soup ship [OPTIONS] [<command>] [ARGS]...`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--base` | text | | | Base model id/path (the 'before'). |
+| `--tuned` | text | | | Tuned model id/path (a separate 'after' model). |
+| `--adapter` | text | | | LoRA adapter path (tuned = base + this adapter). |
+| `--task-eval` | text | | | JSONL of leg-1 task-win eval tasks. |
+| `--task-mode` | text | `metric` | | Leg-1 mode: metric \| judge_score \| pairwise (judge win-rate). |
+| `--noise-floor` | integer | | | Re-run the BASE model N times (2-10) to measure what this instrument can resolve, print it beside the verdict, and refuse to call any delta smaller than the measured floor significant. Costs N extra base passes. The leg-1 task floor is measured in every --task-mode; in judge_score / pairwise each repeat is N extra JUDGE passes (N x the judge API calls), and the floor is labelled decode + judge. |
+| `--judge-model` | text | | | Judge model URL for --task-mode judge_score or pairwise. |
+| `--general-suite` | text | | | Comma list of leg-2 benchmarks (default: the bundled offline suite — MCQ/arithmetic + tool-call/JSON/safety; non-bundled names route through lm-eval). |
+| `--baseline` | text | | | registry://&lt;id> or stamped JSON of base leg-2 scores (skips base run). Unstamped or scorer_revision-mismatched baselines warn once — re-measure so both sides share one scorer scale (#404). |
+| `--forgetting-threshold` | float | `0.05` | | Max allowed leg-2 drop in absolute points before DON'T SHIP. |
+| `--evidence` | text | | | JSON of pre-computed scores (offline, no model load). |
+| `--output`, `-o` | text | | | Write the verdict JSON to this path. |
+| `--emit-evidence` | text | | | Write the scores in the --evidence INPUT schema so this run can be replayed offline (output-is-input). With --config it also STAMPS the config's provenance onto the emitted evidence. |
+| `--config` | text | | | soup.yaml whose eval.ship block supplies defaults (CLI flags win). With --evidence alone it GATES (refuses evidence whose config_sha drifted from this config, or whose numerics family does not match); with --emit-evidence it STAMPS this config's provenance. |
+| `--push` | text | | | Post the verdict as a GitHub PR comment (owner/repo#N). Auth via GITHUB_TOKEN / GH_TOKEN; needs the `gh` CLI. |
+| `--device` | text | | | Device for the live run (cuda / cpu). |
+
+## `soup shrink`
+
+Depth-prune a model (drop the least-important contiguous layer block by residual angular distance) + optional distill-heal (v0.71.29).
+
+Usage: `soup shrink [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model` | text | | yes | Model id or local path to shrink. |
+| `--drop-ratio` | float | | | Fraction of layers to drop (0-1); e.g. 0.25. |
+| `--drop-layers` | integer | | | Explicit number of contiguous layers to drop. |
+| `--calib` | text | | yes | Calibration JSONL (prompts) - must stay under cwd. |
+| `--heal` | text | | | Heal JSONL (chat rows) - distill the original into the pruned model. |
+| `--heal-steps` | integer | `200` | | Approx. optimiser steps for the distill heal. |
+| `--tolerance` | float | `0.1` | | Perplexity-regression tolerance for the verdict. |
+| `--output-dir`, `-o` | text | `./shrunk` | | Directory for the shrunk model + report. |
+| `--device` | text | | | Device for the importance/ppl passes (cuda / cpu). |
+| `--trust-remote-code` | flag | off | | Allow custom modeling code (auto_map). |
+| `--attach-to-registry` | text | | | Attach the shrink report to a registry entry id. |
+| `--plan-only` | flag | off | | Print the importance table + chosen block and exit. |
+
+## `soup spectrum`
+
+Spectrum SNR scan for targeted training (v0.71.23).
+
+Usage: `soup spectrum <command> [ARGS]...`
+
+Subcommands:
+
+- [`scan`](#soup-spectrum-scan)
+
+### `soup spectrum scan`
+
+Scan a model's layer SNR and emit a ``training.unfrozen_parameters`` patch.
+
+Usage: `soup spectrum scan [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--model`, `-m` | text | | yes | HF Hub id or local model directory. |
+| `--top-percent` | float | `50.0` | | Keep the top N% of layers (by SNR) within each module type. |
+| `--modules` | text | `all` | | Comma list of module types to scan: e.g. 'mlp,attn' — or 'all'. |
+| `--output`, `-o` | text | | | Write the YAML patch to this path (must stay under cwd). |
+| `--no-cache` | flag | off | | Skip the \~/.soup/spectrum scan cache. |
+
+## `soup steer`
+
+Activation steering (CAA / ITI / RepE) - inference-time intervention without retraining (v0.62.0).
+
+Usage: `soup steer <command> [ARGS]...`
+
+Subcommands:
+
+- [`apply`](#soup-steer-apply)
+- [`list`](#soup-steer-list)
+- [`train`](#soup-steer-train)
+
+### `soup steer apply`
+
+Resolve + load a stored steering vector and print its metadata.
+
+Usage: `soup steer apply [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--name`, `-n` | text | | yes | Identifier of a stored steering vector. |
+| `--strength`, `-s` | float | `1.0` | | Steering strength multiplier (\|s\| &lt;= 10.0). |
+
+### `soup steer list`
+
+List locally-stored steering vectors (Registry artifact kind ``steering_vector``).
+
+Usage: `soup steer list`
+
+Takes no options or arguments.
+
+### `soup steer train`
+
+Train a steering vector from contrastive prompt pairs.
+
+Usage: `soup steer train [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--base`, `-b` | text | | yes | Base model HF id or local path. |
+| `--method`, `-m` | text | `caa` | | Steering method: caa / iti / repe. |
+| `--name`, `-n` | text | | yes | Identifier for the trained vector (e.g. 'safety-v1'). |
+| `--pairs`, `-p` | text | | yes | Path to JSONL of contrastive (positive, negative) prompt pairs. |
+| `--layer`, `-l` | integer | | | Decoder layer index to extract the residual-stream vector from (default: the middle layer). |
+| `--output`, `-o` | text | | | Directory to write the steering vector to (default: ./steering/&lt;name>). Cwd-contained. |
+| `--device` | text | | | torch device (cpu / cuda). Defaults to CUDA when available. |
+| `--top-k`, `-k` | integer | `8` | | ITI only: number of attention heads to intervene on (1-256). |
+| `--plan-only` | flag | off | | Validate inputs + print the resolved plan; skip the live fit. |
+| `--registry-id` | text | | | Registry entry id to attach the trained vector file to, as a steering_vector artifact. Exits 1 when the attach fails. |
+
+## `soup sweep`
+
+Run hyperparameter sweep: grid or random search over training parameters.
+
+Usage: `soup sweep [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--config`, `-c` | text | `soup.yaml` | | Path to base soup.yaml config file |
+| `--param`, `-p` | text, repeatable | | | Parameter to sweep: key=val1,val2,val3 (e.g., lr=1e-5,2e-5,5e-5) |
+| `--sweep-config` | text | | | Path to a standalone sweep YAML (strategy/n_runs/seed/params) instead of --param; its strategy, n_runs and seed take precedence over --strategy/--max-runs |
+| `--strategy`, `-s` | text | `grid` | | Search strategy: grid, random |
+| `--max-runs` | integer | | | Max number of runs (useful for random strategy) |
+| `--name`, `-n` | text | | | Sweep experiment name prefix |
+| `--dry-run` | flag | off | | Show planned runs without executing |
+| `--early-stop` | float | | | Stop early if run's loss exceeds best loss by this factor (e.g. 1.5 = 50% worse) |
+| `--yes`, `-y` | flag | off | | Skip confirmation prompt |
+
+## `soup tokenizer`
+
+Tokenizer tools: train a BPE tokenizer from JSONL (v0.53.9).
+
+Usage: `soup tokenizer <command> [ARGS]...`
+
+Subcommands:
+
+- [`train`](#soup-tokenizer-train)
+
+### `soup tokenizer train`
+
+Train a BPE tokenizer from a local corpus.
+
+Usage: `soup tokenizer train [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--input`, `-i` | text | | yes | Path to JSONL or .txt corpus (must stay under cwd). |
+| `--vocab-size`, `-v` | integer | `32000` | | Target vocabulary size (256-200000). |
+| `--output`, `-o` | text | `tokenizer_out` | | Output directory for tokenizer.json + vocab.json (under cwd). |
+| `--min-frequency` | integer | `2` | | Minimum pair frequency (>=1). |
+| `--special-token` | text, repeatable | | | Add special token (repeatable). Defaults: &lt;pad>, &lt;s>, &lt;/s>, &lt;unk>. |
+
+## `soup train`
+
+Start training from a soup.yaml config.
+
+Usage: `soup train [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--config`, `-c` | text | `soup.yaml` | | Path to soup.yaml config file |
+| `--name`, `-n` | text | | | Experiment name (auto-generated if not set) |
+| `--dry-run` | flag | off | | Validate config and data without training |
+| `--resume`, `-r` | text | | | Resume from checkpoint: path to checkpoint dir ('auto' for latest); on the MLX backend, a path to a .safetensors adapter file instead. Not supported when training.relora_steps is configured |
+| `--wandb` | flag | off | | Enable Weights &amp; Biases logging |
+| `--tensorboard` | flag | off | | Enable TensorBoard logging (logs to output_dir/runs/) |
+| `--tracker` | text | | | Experiment tracker: mlflow / swanlab / trackio (v0.43.0). Mutually exclusive with --wandb / --tensorboard. |
+| `--deepspeed` | text | | | Enable DeepSpeed: zero2, zero3, zero2_offload, zero3_offload (stage 3 + CPU parameter offload), zero++ (ZeRO++), or path to config JSON |
+| `--fsdp` | text | | | Enable FSDP2: full_shard, shard_grad, or full_offload |
+| `--gpus` | text | | | GPUs per node for distributed training ('auto' or integer) |
+| `--nodes` | integer | `1` | | Number of machines; each must use the same --gpus count |
+| `--node-rank` | integer | | | This machine's rank, from 0 to nodes minus 1 (default 0) |
+| `--master-addr` | text | | | Rank 0 hostname or IP reachable by all nodes; required with --nodes > 1 |
+| `--master-port` | integer | | | Shared coordinator port for multiple nodes (default 29500) |
+| `--no-reexec` | flag | off | | Print the distributed launch command instead of launching it |
+| `--gate` | text | | | Enable eval-gated training with a suite file (shortcut for training.eval_gate.enabled=true + suite=&lt;path>) |
+| `--push-as` | text | | | Auto-push each save_steps checkpoint to HF Hub as 'checkpoint-&lt;step>' branch of the given repo (e.g. user/my-model) |
+| `--hf-resume` | flag | off | | Download the latest checkpoint branch from the --push-as repo and resume from it. Requires --push-as; not supported when training.relora_steps is configured. |
+| `--find-lr` | flag | off | | LR range finder (v0.32.0): run a short geometric LR sweep, write a JSON report with the recommended LR, then exit without training. |
+| `--find-lr-start` | float | `1e-07` | | LR range finder: starting LR (default 1e-7) |
+| `--find-lr-end` | float | `0.1` | | LR range finder: ending LR (default 1e-1) |
+| `--find-lr-steps` | integer | `100` | | LR range finder: number of sweep steps (default 100) |
+| `--find-lr-output` | text | `lr_finder.json` | | LR range finder: JSON report path (default ./lr_finder.json) |
+| `--yes`, `-y` | flag | off | | Skip confirmation prompt |
+| `--trust-remote-code` | flag | off | | Allow loading models that ship custom Python via auto_map. Default deny (v0.36.0). Only enable if you trust the source. |
+| `--echo-trap-tokenizer-aware` | flag | off | | Use tokenizer-id n-grams for echo-trap scoring. Requires training.echo_trap_enabled=true on grpo/ppo. |
+| `--reward-hack-detector` | text | | | Reward-hacking detector for GRPO/PPO: info_rm \| rm_ensemble. Overrides training.reward_hack_detector. (v0.71.26) |
+| `--reward-hack-halt` | flag | off | | Auto-halt training on a HACK verdict. Requires --reward-hack-detector (or training.reward_hack_detector). (v0.71.26) |
+| `--replay` | text | | | Old dataset to interleave as continual-learning rehearsal, so training on the new task does not erase the previous one. sft/pretrain only; incompatible with packing/multipack. Overrides data.replay. (v0.71.36) |
+| `--replay-ratio` | float | | | Fraction of the FINAL mixed train set that is replay rows (default 0.1). Overrides data.replay_ratio. (v0.71.36) |
+| `--replay-seed` | integer | | | Seed for the replay sample + interleave. Overrides data.replay_seed. (v0.71.36) |
+| `--reward-hack-mitigation` | text | | | Closed-loop reward-hacking mitigation mode: off \| log_only \| kl_control \| pid_lagrangian. Requires training.reward_hack_detector on grpo/ppo. Overrides training.reward_hack_mitigation. (v0.71.26) |
+| `--minillm-on-policy` | flag | off | | Use the TRUE on-policy MiniLLM teacher-mixed rollout (v0.71.18 #257) instead of the offline distribution blend. Requires training.minillm_enabled=true on task='distill'. |
+| `--profile` | flag | off | | Record a torch.profiler trace (Chrome trace JSON) during early training steps. Output: &lt;output>/profiles/&lt;run_id>.trace.json |
+| `--allow-oom-attempt` | flag | off | | Bypass the analytical hardware-fit VRAM gate and launch even when the run is predicted to run out of GPU memory (opt-out). |
+| `--diagnose-gate` | text | | | After training, run `soup diagnose` against the supplied evidence JSON (or scratch evidence). Refuses to mark the run successful if any failure mode returns MAJOR (exit 2) or NOT_RUN (exit 3). |
+| `--annex-xi` | text | | | After training, render an EU AI Act Annex XI/XII auto-doc to the given output path (cwd-contained). Markdown body now; PDF in v0.59.1. |
+| `--repro-receipt` | text | | | After training, write an SR 11-7-style reproducibility receipt (seeds + kernel versions + GPU + OS) to the given path. v0.59.0. |
+| `--capture-activations` | text | | | After training, capture residual-stream activations at the named decoder layer (e.g. model.layers.5) on --capture-prompts and write them to &lt;output>/activations/activations.json for soup probe sae-diff / sleeper. v0.71.8 #219. |
+| `--capture-prompts` | text | | | JSONL (or .txt) of prompts to run for --capture-activations (one prompt per line; 'prompt'/'text' field or raw text). |
+| `--track-energy` | flag | off | | Measure the training window's energy + CO2 via codecarbon (offline; requires `pip install soup-cli[carbon]`). Feeds the kWh / CO2 into --annex-xi. v0.71.3. |
+| `--energy-country` | text | `USA` | | ISO 3166-1 alpha-3 country code for the CO2 grid-intensity estimate used by --track-energy (default USA). |
+| `--energy-out` | text | | | Write the --track-energy measurement to this JSON file (cwd-contained) so `soup bom emit --energy <path>` can consume it. v0.71.15. |
+| `--cloud` | text | | | Train on a cloud GPU instead of locally (v0.71.18 #16). Supported: modal, lambda (runpod is planned). Renders a cloud app stub from the config (plan-only); use --cloud-submit to submit live. |
+| `--gpu` | text | `a100` | | Cloud GPU type for --cloud (t4 / l4 / a10 / a10g / a100 / a100-80gb / l40s / h100 / a6000). Default a100. Provider-specific allowlists apply. |
+| `--cloud-submit` | flag | off | | With --cloud, submit the rendered run live via the cloud's SDK or API (gated on respective provider token/API key). Default is plan-only (render + print the command). Lambda requires a registered SSH key. |
+
+## `soup tui`
+
+Full-screen terminal dashboard: list runs, inspect metrics, tail logs.
+
+Usage: `soup tui [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--refresh` | float | `1.0` | | Refresh interval in seconds (0.25 - 10.0). |
+| `--limit` | integer | `50` | | Maximum runs to load into the dashboard. |
+
+## `soup tunability`
+
+Probe-train 6-10 small bases on a held-out slice + report Pareto frontier of (eval delta, train cost, license) (v0.64.0).
+
+Usage: `soup tunability [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--dataset`, `-d` | text | | | Path to held-out JSONL slice used for the probe. |
+| `--candidates` | text | | | Comma-separated subset of default candidates by name. |
+| `--probe-steps` | integer | `100` | | Steps per candidate probe (10-10000). |
+| `--holdout-size` | integer | `64` | | Number of holdout rows used for delta scoring (10-100000). |
+| `--output`, `-o` | text | | | Optional path for the JSON report. |
+| `--plan-only` | flag | off | | Print planned candidates + cost estimate, exit without probing. |
+| `--list` | flag | off | | List built-in candidate catalogue + exit. |
+| `--live` | flag | off | | Run a LIVE LoRA probe per candidate (loads each repo + trains --probe-steps on a tiny held-out slice). Without it, a deterministic offline heuristic is used. |
+| `--device` | text | | | Device for the live probe (cuda / cpu). Auto-detected when omitted. |
+
+## `soup ui`
+
+Launch the Soup Web UI.
+
+Usage: `soup ui [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--port`, `-p` | integer | `7860` | | Port to serve on |
+| `--host` | text | `127.0.0.1` | | Host to bind to |
+| `--no-browser` | flag | off | | Don't open browser automatically |
+| `--show-token` | flag | off | | Print the auth token and exit (for scripting) |
+| `--public` | flag | off | | Bind to 0.0.0.0 so the UI is reachable from a phone on the same LAN. Prints a phone-scannable URL + ASCII QR at startup. Loopback HTTP is auto-upgraded to require a Bearer token in the query string. v0.53.9 #95. |
+| `--auth-token` | text | | | Override the auto-generated Bearer token (16-128 urlsafe base64 chars). Useful for stable phone bookmarks. When omitted, a fresh token is generated each startup. |
+
+## `soup version`
+
+Show Soup CLI version.
+
+Usage: `soup version [OPTIONS]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `--full`, `-f` | flag | off | | Show system info and extras |
+| `--json` | flag | off | | Output in JSON format |
+
+## `soup why`
+
+Explain training anomalies for a run in plain English.
+
+Usage: `soup why [RUN_ID]`
+
+| Name | Type | Default | Required | Help |
+|---|---|---|---|---|
+| `RUN_ID` | text | | | Run ID (or prefix). Defaults to the most recent run. |
diff --git a/docs/config-reference.md b/docs/config-reference.md
new file mode 100644
index 00000000..dcf52c5f
--- /dev/null
+++ b/docs/config-reference.md
@@ -0,0 +1,406 @@
+# Config reference
+
+[← Back to the docs index](README.md)
+
+> **Generated file — do not edit by hand.**
+> It is rendered from `SoupConfig` in `src/soup_cli/config/schema.py`. After adding or
+> removing a field, or changing its type, default or bounds, run
+> `python scripts/gen_reference_docs.py` and commit the result; the test suite fails
+> until the page matches. Descriptions are refreshed when a release is cut, so between
+> releases the wording here can trail the code.
+
+Every key `soup.yaml` accepts. A key that is not on this page **refuses the load** — see
+[Unknown config keys](backends-and-ops.md#unknown-config-keys) for the error and the
+nearest-name hint. The guides linked from the [docs index](README.md) explain what the
+settings do together; this page is the lookup table.
+
+How to read a table:
+
+- **Key** is the full YAML path: `training.lora.r` is `r:` under `lora:` under
+ `training:`.
+- **Type** uses `str`, `int`, `float`, `bool`, `list[...]` and `dict[...]`; `null` means
+ the key may be left out or set to `null`; `section` is a nested block with a table of
+ its own. A value in quotes (`"auto"`) is the one literal accepted next to the type.
+- **Default** is written the way YAML reads it (`null`, `true`, `"auto"`, `["a"]`).
+ **required** means there is none. *(set at runtime)* marks a default computed on
+ the machine, which this page does not print.
+- **Constraints** are the rules on the value itself: bounds, lengths, the allowed
+ choices. Rules that span keys (a setting valid for one task or backend only) are
+ enforced by the schema's validators and named in the description.
+
+Sections:
+
+- [Top-level keys](#top-level-keys)
+- [`data`](#data)
+- [`training`](#training)
+- [`training.lora`](#traininglora)
+- [`training.eval_gate`](#trainingeval_gate)
+- [`eval`](#eval)
+- [`eval.ship`](#evalship)
+- [`advise`](#advise)
+
+## Top-level keys
+
+| Key | Type | Default | Constraints | Description |
+|---|---|---|---|---|
+| `base` | `str` | **required** | | Base model name or path (HF model ID) |
+| `task` | `str` | `"sft"` | one of `"sft"`, `"dpo"`, `"grpo"`, `"ppo"`, `"reward_model"`, `"kto"`, `"orpo"`, `"simpo"`, `"ipo"`, `"bco"`, `"preference"`, `"pretrain"`, `"embedding"`, `"prm"`, `"tts"`, `"classifier"`, `"reranker"`, `"cross_encoder"`, `"distill"`, `"unlearn"`, `"moe_lora_routing"`, `"online_dpo"`, `"asr"` | Training task type. v0.50.0 added 'prm'; v0.52.0 adds 'tts' (TTS fine-tuning), 'classifier' / 'reranker' / 'cross_encoder' (classification heads), and 'distill' (knowledge distillation). v0.61.0 adds 'unlearn' (NPO / SimNPO / RMU). v0.67.0 adds 'moe_lora_routing' (per-token gating over N task LoRAs). |
+| `modality` | `str` | `"text"` | one of `"text"`, `"vision"`, `"audio"`, `"audio_out"` | Training modality: text (default), vision (multimodal), audio (audio-input), or audio_out (audio-output — paired with task='tts', v0.52.0). |
+| `backend` | `str` | `"transformers"` | one of `"transformers"`, `"unsloth"`, `"mlx"` | Training backend: transformers (default), unsloth (2-5x faster on CUDA), or mlx (Apple Silicon M1-M4) |
+| `data` | `section` | **required** | | See [`data`](#data). |
+| `training` | `section` | section defaults | | See [`training`](#training). |
+| `output` | `str` | `"./output"` | | Output directory for trained model |
+| `experiment_name` | `str \| null` | `null` | | Experiment name for tracking |
+| `eval` | `section \| null` | `null` | | Evaluation configuration for auto-eval after training. See [`eval`](#eval). |
+| `advise` | `section \| null` | `null` | | Pre-flight decision settings consumed by `soup advise`. See [`advise`](#advise). |
+
+## `data`
+
+| Key | Type | Default | Constraints | Description |
+|---|---|---|---|---|
+| `data.train` | `str \| list[str]` | **required** | | Path to training data or HF dataset name, or a list of >= 2 local file paths to combine via data.interleave. (#443) |
+| `data.format` | `str` | `"auto"` | one of `"alpaca"`, `"sharegpt"`, `"chatml"`, `"dpo"`, `"kto"`, `"llava"`, `"sharegpt4v"`, `"plaintext"`, `"embedding"`, `"audio"`, `"tool-calling"`, `"auto"`, `"prm"`, `"pre_tokenized"`, `"input_output"`, `"video"`, `"multimodal"`, `"raft"`, `"asr"`, `"cross_encoder"` | Data format |
+| `data.val_split` | `float` | `0.1` | `>= 0.0`, `<= 0.5` | Validation split ratio |
+| `data.max_length` | `int` | `2048` | `>= 64`, `<= 1048576` | Max sequence length in tokens |
+| `data.image_dir` | `str \| null` | `null` | | Base directory for resolving relative image paths in vision datasets |
+| `data.audio_dir` | `str \| null` | `null` | | Base directory for resolving relative audio paths in audio datasets |
+| `data.train_on_responses_only` | `bool` | `true` | | Mask non-assistant tokens with IGNORE_INDEX (-100). When True, only assistant content contributes to the SFT loss. Mirrors LlamaFactory + Axolotl default — replaces TRL's heuristic. (v0.36.0) |
+| `data.train_on_messages_with_train_field` | `bool` | `false` | | Per-message training mask via messages\[i].train: bool. Mutually exclusive with train_on_responses_only. (v0.36.0) |
+| `data.chat_template` | `str \| null` | `null` | | Override the tokenizer chat template. Accepts a registered name (chatml, llama3, qwen2.5, mistral, gemma3, phi4, deepseek-r1) or a raw Jinja string. None = use the tokenizer's shipped template (errors loudly if absent). (v0.36.0) |
+| `data.raft_shuffle_seed` | `int \| null` | `null` | `>= 0`, `<= 2147483647` | Seed for the RAFT golden/distractor document shuffle (data.format='raft'). Documents are always shuffled for distractor robustness; this knob fixes which reproducible permutation. None = seed 0. (v0.71.10 #199) |
+| `data.raft_epoch_shuffle` | `bool` | `false` | | Re-permute RAFT golden/distractor documents EACH training epoch (data.format='raft'). When False (default) the document order is baked once at tokenisation time and fixed across epochs; when True the trainer re-composes + re-tokenises rows per epoch with an epoch salt so the model cannot memorise a fixed golden-doc slot. (v0.71.17 #253) |
+| `data.replay` | `str \| null` | `null` | | Path to an OLD dataset to interleave into training as continual-learning rehearsal, so fine-tuning on a new task does not erase the previous one. Rows are mixed into train ONLY (never val, which stays pure new-task). sft / pretrain only; incompatible with packing / multipack. (v0.71.36) |
+| `data.replay_ratio` | `float` | `0.1` | `> 0.0`, `<= 0.5` | Fraction of the FINAL mixed train set that is replay rows: n_replay = round(r/(1-r) \* n_new). At 0.1 over 1000 new rows that is 111 replay rows -> 1111 total -> 10.0%. (v0.71.36) |
+| `data.replay_seed` | `int \| null` | `null` | `>= 0`, `<= 2147483647` | Seed for the replay sample + interleave. None = seed 0. (v0.71.36) |
+| `data.video_dir` | `str \| null` | `null` | | Base directory for resolving relative video paths in video datasets. Mirrors image_dir / audio_dir. (v0.42.0) |
+| `data.tokenized_path` | `str \| null` | `null` | | Path to a pre-tokenized cache produced by `soup data preprocess`. When set, the trainer skips the tokenize stage and reads tensors directly. Mirrors LF tokenized_path / Axolotl `empty` type. (v0.42.0) |
+| `data.streaming` | `bool` | `false` | | Pass-through to HF datasets `streaming=True`. Use for datasets that don't fit on disk. Pairs with `buffer_size`. (v0.42.0) |
+| `data.buffer_size` | `int \| null` | `null` | | Shuffle buffer size for streaming datasets. None = HF default. Bounds \[1, 1_000_000]. (v0.42.0) |
+| `data.shards` | `int \| null` | `null` | | Number of shards for HF dataset splits (axolotl `shards`). Bounds \[1, 1024]. (v0.42.0) |
+| `data.interleave` | `str \| dict \| null` | `null` | | Multi-dataset interleave strategy: 'concat' / 'under' / 'over' / {strategy: 'probs', probs: \[...]}. (v0.42.0) |
+| `data.mask_history` | `bool` | `false` | | LF mask_history — mask all but the last assistant turn during loss computation. (v0.42.0) |
+| `data.train_on_prompt` | `bool` | `false` | | LF train_on_prompt — include the prompt tokens in the loss. Inverse of train_on_responses_only. (v0.42.0) |
+| `data.eval_on_each_dataset` | `bool` | `false` | | LF eval_on_each_dataset — when interleaving, run eval on every constituent dataset separately. (v0.42.0) |
+| `data.split_thinking` | `bool` | `false` | | Axolotl split_thinking — separate `<think>` reasoning blocks from the final answer for fine-grained masking. Qwen3-style. (v0.42.0) |
+| `data.image_min_pixels` | `int \| null` | `null` | | Per-image min pixel count for vision data. (v0.42.0) |
+| `data.image_max_pixels` | `int \| null` | `null` | | Per-image max pixel count for vision data. (v0.42.0) |
+| `data.image_resize_algorithm` | `str \| null` | `null` | one of `"nearest"`, `"bilinear"`, `"bicubic"`, `"lanczos"` | Pillow resize algorithm for image preprocessing. (v0.42.0) |
+| `data.video_fps` | `float \| null` | `null` | | Target frames-per-second for video preprocessing. (v0.42.0) |
+| `data.video_maxlen` | `int \| null` | `null` | | Max number of frames per video clip. Bounds (0, 4096]. (v0.42.0) |
+| `data.add_new_tokens` | `list[str] \| null` | `null` | | Add these tokens to the tokenizer vocab + resize embeddings. Cap 10_000 entries; per-token &lt;= 256 chars; no duplicates. (v0.42.0) |
+| `data.new_special_tokens` | `list[str] \| null` | `null` | | Like add_new_tokens but registered as additional_special_tokens so they are not split by the tokenizer. (v0.42.0) |
+| `data.resize_vocab` | `bool` | `false` | | Resize the model's input/output embedding matrix when add_new_tokens / new_special_tokens grew the vocab. (v0.42.0) |
+| `data.extend_conversation` | `bool` | `false` | | Unsloth-style conversation extension — extend the last assistant turn with N more tokens for 'continue' prompts. (v0.42.0) |
+| `data.skip_prepare_dataset` | `bool` | `false` | | Axolotl skip_prepare_dataset — escape hatch when the input is already in the trainer's expected schema. (v0.42.0) |
+| `data.remove_unused_columns` | `bool` | `false` | | HF Trainer remove_unused_columns. No trainer reads this field; the trainers that set it pass False so a custom collator can still see the extra columns. An explicit `true` loads with a warning and is ignored, and a later release refuses it. (v0.42.0; #759) |
+| `data.prompt_strategy` | `str \| null` | `null` | | Axolotl-style 'module.path:function_name' Python transform, resolved lazily and applied to each row during SFT formatting. |
+| `data.forget_set` | `str \| null` | `null` | | Path or HF dataset name for the forget set (rows to unlearn). Required when task='unlearn'. Null-byte rejected, capped at 4096 chars. Containment is deferred to the trainer-side loader so HF dataset IDs (e.g. ``locuslab/TOFU``) still pass schema. (v0.61.0) |
+| `data.retain_set` | `str \| null` | `null` | | Path or HF dataset name for the retain set (rows whose performance must be preserved). Optional but recommended — NPO/SimNPO/RMU all degrade without one. Same validation as forget_set. (v0.61.0) |
+
+## `training`
+
+| Key | Type | Default | Constraints | Description |
+|---|---|---|---|---|
+| `training.epochs` | `int` | `3` | `>= 1` | Number of training epochs |
+| `training.lr` | `float` | `2e-05` | `> 0` | Learning rate |
+| `training.batch_size` | `int \| "auto"` | `"auto"` | | Batch size. 'auto' = find max that fits in memory. |
+| `training.auto_batch_size_strategy` | `str` | `"auto"` | one of `"auto"`, `"static"`, `"probe"` | How to pick the auto batch size: 'static' (fast formula), 'probe' (real OOM try/halve loop), 'auto' (probe on CUDA, static on CPU). Default 'auto' (v0.36.0). |
+| `training.gradient_accumulation_steps` | `int` | `4` | `>= 1` | |
+| `training.seed` | `int \| null` | `null` | `>= 0`, `<= 4294967295` | Training seed (weight init of new params, data order, dropout). Reaches TrainingArguments.seed and the multipack sampler. Unset = HF's default of 42. |
+| `training.data_seed` | `int \| null` | `null` | `>= 0`, `<= 4294967295` | Separate seed for data sampling only (TrainingArguments.data_seed). Set it alongside `seed` to vary data order while holding initialisation fixed. Unset = follow `seed`. |
+| `training.warmup_ratio` | `float` | `0.03` | `>= 0.0`, `<= 0.5` | |
+| `training.weight_decay` | `float` | `0.01` | `>= 0.0` | |
+| `training.max_grad_norm` | `float` | `1.0` | `> 0` | |
+| `training.lora` | `section` | section defaults | | See [`training.lora`](#traininglora). |
+| `training.quantization` | `str` | `"4bit"` | one of `"4bit"`, `"8bit"`, `"none"`, `"gptq"`, `"awq"`, `"hqq:1bit"`, `"hqq:2bit"`, `"hqq:3bit"`, `"hqq:4bit"`, `"hqq:5bit"`, `"hqq:6bit"`, `"hqq:8bit"`, `"aqlm"`, `"eetq"`, `"mxfp4"`, `"fp8"`, `"bitnet_1.58"` | Quantization (v0.38.0 — Quant Menu): 4bit (BNB QLoRA), 8bit (BNB), none, gptq / awq (load pre-quantized checkpoint, train LoRA on top), hqq:Nbit (HQQ 1-8 bit, N in {1..6, 8}), aqlm (extreme 2-bit), eetq (8-bit fast), mxfp4 (MXFP4 pre-quantized base, dequantized on load), fp8 (load FP8 checkpoint with dequantize-on-load), bitnet_1.58 (reserved until BitNet trainer routing is available). |
+| `training.gptq_disable_exllama` | `bool` | `true` | | v0.38.0 — disable exllama backend for GPTQ. PEFT requires triton backend; exllama silently breaks adapter training. |
+| `training.bnb_4bit_quant_storage` | `str \| null` | `null` | one of `"uint8"`, `"float16"`, `"bfloat16"`, `"float32"` | v0.38.0 — BNB 4-bit storage dtype. FSDP+QLoRA resolves this automatically to the effective floating compute dtype; outside FSDP, None keeps BNB's legacy uint8 default. |
+| `training.quantization_aware` | `bool \| "fp8" \| "quest"` | `false` | | Quantization-Aware Training. False=off, True=refused at load (int8 QAT is not implemented, #1222), 'fp8'=FP8 training on H100/B100 (v0.28.0), 'quest'=experimental mixed W4/A4+A16 QuEST route (#674). |
+| `training.fp8_recipe` | `str` | `"tensorwise"` | one of `"tensorwise"`, `"rowwise"`, `"rowwise_with_gw_hp"` | FP8 scaling recipe (only used when quantization_aware='fp8'). 'tensorwise' (fastest, default), 'rowwise' (more accurate, CUTLASS rowwise), 'rowwise_with_gw_hp' (most accurate, grad_weight in high precision). (v0.28.1). |
+| `training.optimizer` | `str` | `"adamw_torch"` | | Optimizer name (v0.41.0 expanded the allowlist: HF-native, bnb-8bit, lomo/adalomo, apollo_adamw, grokadamw, schedule_free). Note: ten names transformers 5.x rejects in TrainingArguments (e.g. badam, adam_mini, muon, dion, came_pytorch, ao_adamw\_{fp8,4bit,8bit}) are refused at config load (#1269); adamw_hf and muon still work on backend: mlx. See soup_cli.utils.optimizer_zoo.SUPPORTED_OPTIMIZERS for the full list. |
+| `training.lr_groups` | `list[dict[str, str \| float]] \| null` | `null` | | Staged, not applied: a per-module LR override (list of {pattern, lr} entries or a {pattern: lr} dict, capped at 32) that no optimizer reads; setting it warns at load, then is refused (#761). (v0.41.0) |
+| `training.expand_layers` | `int \| null` | `null` | `>= 1`, `<= 64` | LLaMA Pro: append N zero-init transformer blocks and freeze the original ones before SFT or pre-training. |
+| `training.freeze_trainable_layers` | `int \| null` | `null` | | LLaMA Pro: applies only together with expand_layers, must equal it, and is refused otherwise. It freezes every parameter of the original model so only the appended blocks train; it does not select top-N or bottom-N layers. Magnitude capped at 1000. (v0.41.0) |
+| `training.use_mod` | `bool` | `false` | | Enable Mixture-of-Depths selective-token routing (arXiv:2404.02258). Live in v0.71.12 #84 for SFT + Pretrain on Llama / Qwen / Mistral; each decoder layer gets a router that passes only the top-k tokens (k = floor(seq_len \* mod_capacity_factor)) through the block. |
+| `training.mod_capacity_factor` | `float` | `0.125` | `> 0.0`, `<= 1.0` | Fraction of tokens routed through each block when use_mod=True. Bounded (0, 1]; default 0.125 (per the MoD paper). (v0.71.12 #84) |
+| `training.load_in_8bit` | `bool \| null` | `null` | | Friendly alias for quantization='8bit' / 'none'. When True, rewrites quantization to '8bit' if currently 'none'/'4bit'. Conflicts with load_in_16bit. (v0.41.0) |
+| `training.load_in_16bit` | `bool \| null` | `null` | | Friendly alias: when True, sets quantization='none' (full bf16/fp16 LoRA). Conflicts with load_in_8bit. (v0.41.0) |
+| `training.scheduler` | `str` | `"cosine"` | | LR scheduler type |
+| `training.save_steps` | `int` | `100` | | Save checkpoint every N steps |
+| `training.logging_steps` | `int` | `10` | | Log metrics every N steps |
+| `training.eval_steps` | `int \| null` | `null` | `>= 1` | Evaluate the validation split every N optimizer steps (counted after gradient accumulation, like save_steps). Unset = evaluate at the end of every epoch. grpo evaluates only when this is set, because an evaluation there generates completions. (#1223) |
+| `training.dpo_beta` | `float` | `0.1` | `> 0` | DPO beta — KL penalty coefficient |
+| `training.kto_beta` | `float` | `0.1` | `> 0` | KTO beta — KL penalty coefficient |
+| `training.orpo_beta` | `float` | `0.1` | `> 0` | ORPO beta — odds ratio weight |
+| `training.simpo_gamma` | `float` | `0.5` | `>= 0` | SimPO gamma — reward margin term |
+| `training.cpo_alpha` | `float` | `1.0` | `> 0` | CPO/SimPO alpha — NLL loss weight |
+| `training.ipo_tau` | `float` | `0.1` | `> 0` | IPO tau — regularization strength |
+| `training.bco_beta` | `float` | `0.1` | `> 0` | BCO beta — KL penalty coefficient |
+| `training.preference_loss` | `str \| null` | `null` | one of `"dpo"`, `"simpo"`, `"orpo"`, `"ipo"`, `"bco"` | Preference loss for task='preference'. One of: dpo, simpo, orpo, ipo, bco. Mutually exclusive with task in {dpo, simpo, orpo, ipo, bco}. |
+| `training.dpo_beta_schedule` | `str \| null` | `null` | one of `"linear"`, `"cosine"`, `"exponential"` | Anneal DPO β over training. None = constant β (default). Requires dpo_beta_end. DPO-family tasks only (dpo, ipo, preference+dpo). |
+| `training.dpo_beta_end` | `float \| null` | `null` | `> 0` | Target β at the end of training when dpo_beta_schedule is set. Must be > 0. The starting β is dpo_beta. |
+| `training.dpo_ref_regen_epochs` | `int \| null` | `null` | `>= 1`, `<= 1000` | Replace the frozen ref adapter with the current active adapter every N epochs. Copies .default. adapter weights into .ref. under torch.no_grad(). Requires LoRA (lora.r >= 1); full fine-tuning is not supported. |
+| `training.preference_loss_weights` | `dict[str, float] \| null` | `null` | | Weighted blend of preference losses, e.g. {'dpo': 0.7, 'bco': 0.3}. Each weight ∈ (0, 1]; weights must sum to 1.0 (±1e-6). All keys must be members of {dpo, simpo, orpo, ipo, bco}. Requires task='preference'; mutually exclusive with preference_loss (the scalar form). Capped at 5 components (the supported set). |
+| `training.grpo_beta` | `float` | `0.1` | `>= 0.0`; finite | GRPO beta - KL penalty coefficient (default 0.1). Set to 0 to disable the KL penalty entirely (KL-free recipes like DAPO and Dr. GRPO, #1247). |
+| `training.num_generations` | `int` | `4` | `>= 2` | Number of generations per prompt for GRPO |
+| `training.reward_fn` | `str \| null` | `"accuracy"` | | Reward function: 'accuracy', 'format', 'verifiable', a path to a custom .py file, or a comma-separated ensemble of the above (e.g. 'accuracy,format') — the comma form is GRPO-only (v0.71.40). |
+| `training.verifiable_domain` | `str \| null` | `null` | one of `"math"`, `"code"`, `"json_schema"` | RLVR verifiable reward domain: math \| code \| json_schema. Required when reward_fn='verifiable'. |
+| `training.prm_reward` | `str \| null` | `null` | | Path (or HF id) to a Soup-trained PRM (task='prm') used as the GRPO per-step reward (v0.71.30). When set, the PRM replaces reward_fn. Requires task='grpo', backend='transformers', modality='text'. |
+| `training.prm_aggregate` | `str` | `"min"` | one of `"min"`, `"prod"`, `"last"` | How PRM per-step scores fold into one reward: min (weakest-link, default) \| prod \| last. Only meaningful when prm_reward is set. NOTE: 'prod' assumes per-step scores are bounded in \~\[0,1] (a probability of step-correctness). Soup's PRM head is trained with unconstrained MSE regression, so 'prod' can blow up / flip sign on unbounded labels — prefer the default 'min' unless your PRM labels are calibrated to \[0,1]. |
+| `training.online_dpo_judge` | `str \| null` | `null` | | Judge URL (ollama://model \| https://... \| http://localhost) for task='online_dpo'. Mutually exclusive with reward_model. |
+| `training.online_dpo_loss_type` | `str` | `"sigmoid"` | one of `"sigmoid"`, `"ipo"` | Online DPO loss type (maps to OnlineDPOConfig.loss_type). |
+| `training.online_dpo_max_new_tokens` | `int` | `64` | `>= 1`, `<= 4096` | Max new tokens generated per online-DPO step. |
+| `training.asr_language` | `str \| null` | `null` | | Target language for task='asr' (Whisper), e.g. 'en' or 'spanish'. Sets the forced decoder prompt; None uses the model default / language detection. |
+| `training.asr_task` | `str` | `"transcribe"` | one of `"transcribe"`, `"translate"` | Whisper decoding objective for task='asr': 'transcribe' (same language) or 'translate' (to English). |
+| `training.asr_lora` | `bool` | `false` | | Opt-in LoRA for task='asr' (adapts q/v attention projections). Default False = full fine-tune (tiny Whisper fits a 4 GB GPU). Mirrors classifier_lora — the standard training.lora block still supplies r/alpha/dropout when enabled. |
+| `training.grpo_variant` | `str \| null` | `null` | one of `"standard"`, `"gspo"`, `"dapo"`, `"dr_grpo"`, `"bnpo"`, `"two_sided"`, `"rft"` | GRPO objective variant: standard \| gspo \| dapo \| dr_grpo \| bnpo \| two_sided \| rft. Defaults to None (legacy GRPO). Requires task='grpo'; the selected loss is installed by the GRPO trainer. |
+| `training.grpo_delta` | `float \| null` | `null` | `> 0.0`, `<= 1.0` | Symmetric clipping radius for grpo_variant='two_sided' (required) or grpo_variant='gspo' (optional sequence clipping radius, defaults to 0.2). Rejected for all other variants. |
+| `training.grpo_fp16` | `bool` | `false` | | Force FP16 mixed precision for GRPO/RL (unsloth parity). On CUDA, the GRPO trainer forwards fp16=True and bf16=False; on non-CUDA devices this flag does not enable FP16. |
+| `training.long_context_grpo` | `bool` | `false` | | Enable long-context GRPO (unsloth: 380K B200 / 110K H100). Compatibility validation only: no trainer consumes this flag yet. Requires task='grpo' on a non-mlx backend and use_ring_attention=False. |
+| `training.vllm_sleep_mode` | `bool` | `false` | | Enable vLLM sleep/standby between rollouts (memory savings during the optimisation step). Requires backend in {transformers, unsloth}; forwarded to compatible TRL and vLLM runtimes by the GRPO trainer. |
+| `training.rollout_backend` | `str \| null` | `null` | one of `"art"`, `"ruler"`, `"nemo_gym"`, `"openenv"` | Multi-turn agent rollout backend (unsloth / axolotl parity): art (OpenPipe ART) / ruler / nemo_gym / openenv. Requires task='grpo'. openenv runs live (v0.71.21 #125) via training.rollout_func; art/ruler/nemo_gym are lazy-import gated. |
+| `training.rollout_func` | `str \| null` | `null` | | OpenEnv rollout function as 'module.path:function_name' (v0.71.21 #125). Requires rollout_backend='openenv'. The callable receives the seed prompts list and returns rollout rows ({'prompt': str\|messages, 'answer'?: str}) that replace the GRPO prompt dataset. Trusted-input policy: names operator-controlled code (mirrors data.prompt_strategy). |
+| `training.ref_model_ema_alpha` | `float \| null` | `null` | `> 0.0`, `<= 1.0` | Exponential moving average coefficient for ref-model sync (policy → reference). Must be in (0, 1]. None = disabled. Axolotl parity. |
+| `training.replay_buffer_size` | `int \| null` | `null` | `>= 1`, `<= 1000000` | Bounded replay buffer size for GRPO rollouts. None = disabled. Axolotl parity. |
+| `training.async_grpo_prefetch` | `bool` | `false` | | Overlap rollout + train via async prefetch (axolotl). Requires backend in {transformers, unsloth}. |
+| `training.tis_threshold` | `float \| null` | `null` | `> 0.0`, `<= 100.0` | Truncated importance sampling threshold (unsloth, axolotl). Must be in (0, 100]. None = disabled. |
+| `training.mask_truncated_completions` | `bool` | `false` | | Mask out truncated completions when computing the policy gradient (paired with tis_threshold). Unsloth + axolotl parity. |
+| `training.defer_rerolling` | `bool` | `false` | | Defer re-rolling identical prompts across optimisation steps (axolotl). Saves rollouts on repeat prompts. |
+| `training.skip_zero_advantage` | `bool` | `false` | | Skip backward pass on samples whose advantage is exactly zero (axolotl). Avoids wasted compute on no-signal samples. |
+| `training.off_policy_mask_threshold` | `float \| null` | `null` | `>= 0.0`, `<= 1.0` | Off-policy mask threshold for token/sequence gating (axolotl). Must be in \[0, 1]. None = disabled. |
+| `training.vision_grpo` | `bool` | `false` | | Enable Vision RL / VLM RL — extends GRPO/PPO to vision modality (Qwen2-VL / Pixtral / InternVL). Requires modality='vision', task in {grpo, ppo}, backend in {transformers, unsloth}. Compatibility validation is available, but no trainer consumes this flag yet. |
+| `training.hub` | `str` | `"hf"` | one of `"hf"`, `"modelscope"`, `"modelers"` | Training-time model-download hub. 'hf' (default), 'modelscope' (China-hosted; mirrors most Llama/Qwen/etc.), 'modelers' (Openmind hub). `soup push --hub` selects its upload destination independently of this field. |
+| `training.tts_family` | `str \| null` | `null` | one of `"orpheus"`, `"sesame_csm"`, `"llasa"`, `"spark"`, `"oute"` | TTS model family — required when task='tts'. Runnable choices are orpheus, llasa, spark, and oute. sesame_csm is retained only so legacy configs receive an explicit refusal until Soup has a native CSM multimodal trainer. |
+| `training.tts_emotion` | `str \| null` | `null` | | Optional emotion tag for emotion-conditioned families (Orpheus / Oute). Allowlisted per-family. (v0.52.0) |
+| `training.num_labels` | `int \| null` | `null` | `>= 1`, `<= 1024` | Number of output labels for task in (classifier, reranker, cross_encoder). Required when task is one of those. (v0.52.0) |
+| `training.classifier_kind` | `str \| null` | `null` | one of `"single_label"`, `"multi_label"` | Sequence-classification head kind: single_label (default for task='classifier') or multi_label. (v0.52.0) |
+| `training.label_names` | `list[str] \| null` | `null` | | Optional human-readable label names. Length must match num_labels. Capped at 1024 entries. (v0.52.0) |
+| `training.mole_task_adapters` | `list[str] \| null` | `null` | | Paths (HF ids or local dirs) to the N pre-trained task LoRA adapters routed over by the MoLE gate. Required when task='moe_lora_routing'; 2-64 entries, deduplicated. The base model + every task adapter stay frozen — only the gate trains. (v0.71.12 #222) |
+| `training.mole_top_k` | `int \| null` | `null` | | Number of task adapters each token is routed to (sparse top-k dispatch). Defaults to num_task_adapters (dense) when unset. 1 &lt;= top_k &lt;= len(mole_task_adapters). (v0.71.12 #222) |
+| `training.mole_temperature` | `float \| null` | `null` | | Softmax temperature for the MoLE router (default 1.0). (1e-6, 100.0]. (v0.71.12 #222) |
+| `training.teacher_model` | `str \| null` | `null` | | Teacher model HF id or local path — required when task='distill'. Loaded frozen by the distillation trainer. Null-byte rejected, capped at 512 chars. |
+| `training.distill_divergence` | `str \| null` | `null` | one of `"forward_kl"`, `"reverse_kl"`, `"js"` | Divergence used for distillation loss. 'kl' is an alias for 'forward_kl' (canonical form). (v0.52.0) |
+| `training.distill_temperature` | `float \| null` | `null` | | Softmax temperature applied to teacher and student logits before the divergence. Bounded \[0.05, 100.0]. (v0.52.0) |
+| `training.distill_mode` | `str` | `"token"` | one of `"token"`, `"sequence"` | Distillation mode. 'token' (default, v0.53.2) = column-aligned logit KL — requires a shared tokenizer (or set uld_strategy for the cross-tokenizer logit path). 'sequence' (v0.71.12) = sequence-level KD: the teacher GENERATES a completion per prompt and the student does plain CE on the re-tokenised output, which works across ANY tokenizer pair (e.g. Llama-3 student / Qwen-2 teacher). |
+| `training.distill_chunk_size` | `int \| null` | `null` | | Token chunk size for evaluating the distillation divergence kernel. Chunks the active supervised tokens to reduce peak memory retention. Unset (None) processes all tokens in a single chunk. (#722) |
+| `training.distill_checkpoint` | `bool` | `false` | | Enable non-reentrant activation checkpointing per token chunk during distillation divergence computation to minimize autograd retained memory. (#722) |
+| `training.classifier_lora` | `bool` | `false` | | Wrap the sequence-classification head with LoRA (task_type='SEQ_CLS') instead of full fine-tuning. Opt-in (default False preserves the v0.53.2 full-finetune behaviour). Reuses the training.lora block (r / alpha / dropout / target_modules). Only honored for task in (classifier, reranker, cross_encoder). (v0.71.12 #146) |
+| `training.ebft_variant` | `str \| null` | `null` | one of `"structured"`, `"strided"` | Refused at config load (#1230): EBFT is not yet a distinct objective. The added term had no causal shift, so it rewarded copying the input token, and shifted it duplicates the cross-entropy. |
+| `training.ebft_temperature` | `float \| null` | `null` | | Sampling temperature for EBFT energy proxy. Bounded \[1e-4, 100.0]. Only applies with ebft_variant, which is refused at config load (#1230). (v0.52.0) |
+| `training.gdpo_variant` | `str \| null` | `null` | one of `"standard"`, `"length_normalized"`, `"margin"` | Refused at config load (#1309): supported TRL versions lack the DPO loss hook. Remove this field; use plain task: dpo for standard, or task: simpo as the nearest (not identical) length-normalized objective. |
+| `training.moe_expert_quant` | `str \| null` | `null` | one of `"nf4"`, `"int8_rowwise"` | Per-expert quantization for fused-MoE Linear blocks. Requires moe_lora=true. (v0.52.0) |
+| `training.train_router_only` | `bool` | `false` | | Freeze every expert + train only the gating router (unsloth MoE recipe). Requires moe_lora=true. (v0.52.0) |
+| `training.reasoning_effort` | `str \| null` | `null` | one of `"low"`, `"medium"`, `"high"` | gpt-oss train-time reasoning effort level. Injected as a prompt prefix by the SFT-family data formatter. |
+| `training.train_on_eot` | `bool` | `false` | | Include explicit EOT / EOS control tokens in the SFT loss (axolotl ``train_on_eot``). Default False matches HF Trainer convention. (v0.52.0) |
+| `training.kv_cache_type` | `str \| null` | `null` | one of `"q8_0"`, `"bf16"`, `"f16"`, `"fp8"` | KV-cache element type for inference (q8_0 / bf16 / f16 / fp8). Applied by soup serve on the transformers backend; backend and hardware compatibility are validated before model loading. |
+| `training.fp8_attention` | `bool` | `false` | | Extend the v0.28.0 FP8 menu to FP8 attention (axolotl-parity flag). Requires quantization_aware='fp8'. DPO-family, GRPO/PPO, pre-training, reward-model, and embedding wrappers route it through the shared advanced-precision setup; the default SFT path does not consume it. |
+| `training.nvfp4` | `bool` | `false` | | Blackwell-only NVFP4 training (unsloth + axolotl). DPO-family, GRPO/PPO, pre-training, reward-model, and embedding wrappers route it through torchao conversion; the default SFT path does not consume it. |
+| `training.unsloth_bnb_4bit` | `bool` | `false` | | Promote Unsloth Dynamic 4-bit from 'inferable' to a native flag. Requires backend='unsloth' and quantization='4bit'. (v0.53.0) |
+| `training.bnb_4bit_use_double_quant` | `bool \| null` | `null` | | Apply BNB 4-bit double-quantization (LF / Axolotl parity). Unset means the shipped default (on, to match every 4-bit load path); set false to disable it. Only meaningful when quantization='4bit'. (v0.53.0) |
+| `training.llm_int8` | `bool` | `false` | | Explicit 8-bit LLM.int8 alias for quantization='8bit'. When True, requires quantization='8bit'. (v0.53.0) |
+| `training.quantize_ref_model` | `bool` | `false` | | Apply the same Quant Menu config to the reference model (DPO/IPO/SimPO/ORPO/BCO ref model) — extends v0.40.5. (v0.53.0) |
+| `training.quantize_reward_model` | `bool` | `false` | | Apply the same Quant Menu config to the reward model (PPO/reward_model task) — extends v0.40.5. (v0.53.0) |
+| `training.echo_trap_enabled` | `bool` | `false` | | Enable RAGEN-style echo-trap detection during multi-turn agent RL. Requires task in {'grpo', 'ppo'} on a non-mlx backend; installs the shared RL signal callback. |
+| `training.echo_trap_threshold` | `float` | `0.6` | `>= 0.0`, `<= 1.0` | Threshold on the aggregate echo signal. Above this = TRAP. Bounded \[0.0, 1.0]. (v0.70.0) |
+| `training.echo_trap_halt` | `bool` | `false` | | Auto-halt training on TRAP verdict. Requires echo_trap_enabled=True. (v0.70.0) |
+| `training.echo_trap_tokenizer_aware` | `bool` | `false` | | Use tokenizer-id n-grams for echo-trap scoring instead of whitespace tokens. More sensitive to subword repetition but bound to the active tokenizer vocabulary. Requires echo_trap_enabled=True. (v0.70.x) |
+| `training.rl_checkpoint_save_every_steps` | `int \| null` | `null` | `>= 1`, `<= 10000000` | Save an RL-aware mid-epoch checkpoint every N steps. None = use HF Trainer's per-epoch checkpoint only. Requires task in {'grpo', 'ppo'}; the callback persists the policy adapter, optional optimizer state, and a manifest. |
+| `training.rl_checkpoint_keep_last` | `int` | `3` | `>= 1`, `<= 100` | Number of recent RL checkpoints to retain. Older ones are pruned at write time. (v0.70.0) |
+| `training.rl_checkpoint_include_optimizer` | `bool` | `true` | | Include AdamW / Lion optimizer state in the mid-epoch RL checkpoint. (v0.70.0) |
+| `training.rl_checkpoint_include_ref_model` | `bool` | `false` | | Include the frozen reference model state in the RL checkpoint. Default False (ref model is reconstructable from cfg.base). (v0.70.0) |
+| `training.rl_checkpoint_include_rollout_buffer` | `bool` | `false` | | Include the rollout / replay buffer in the RL checkpoint so resumed runs don't lose collected experience. (v0.70.0) |
+| `training.minillm_enabled` | `bool` | `false` | | Enable MiniLLM-style on-policy distillation (Gu et al. 2024). Requires task='distill' on a non-mlx backend; installs the teacher-mixed sampling and reverse-KL loss path. |
+| `training.minillm_teacher_mix_ratio` | `float` | `0.0` | `>= 0.0`, `<= 1.0` | Teacher mixture used by MiniLLM. Offline (minillm_on_policy=false): weight of the teacher distribution in the reverse-KL target (ratio \* teacher + (1 - ratio) \* stopgrad(student)). 0.0 is rejected when MiniLLM is enabled because the teacher then has zero weight. On-policy: probability of sampling from the teacher at rollout time; 0.0 = student-only sampling, and the loss is still KL(student \|\| teacher). Typical range 0.2-0.5. (v0.70.0; offline zero rejected in #692) |
+| `training.minillm_length_normalize` | `bool` | `true` | | Length-normalise the rollout log-probability before the reverse-KL term. Prevents long completions from dominating the gradient. (v0.70.0) |
+| `training.minillm_pretrain_anchor_weight` | `float` | `0.0` | `>= 0.0`, `<= 1.0` | Weight on the pretrain-loss anchor term (SFT on a small pretrain corpus). Prevents drift away from coherent language. Requires minillm_pretrain_anchor_path when > 0. (v0.70.0) |
+| `training.minillm_pretrain_anchor_path` | `str \| null` | `null` | | Path to the pretrain JSONL used by the anchor term. Required when minillm_pretrain_anchor_weight > 0. Null-byte rejected; capped at 4096 chars. (v0.70.0) |
+| `training.minillm_on_policy` | `bool` | `false` | | Use the TRUE on-policy MiniLLM teacher-mixed rollout (Gu et al. 2024 §3.1): sample a fresh autoregressive rollout per step (per-token teacher/student mix) then compute length-normalised reverse-KL on it. Default off = the cheap offline distribution blend. Requires minillm_enabled=True. (v0.71.18 #257) |
+| `training.minillm_rollout_length` | `int \| null` | `null` | `>= 1`, `<= 512` | On-policy rollout length (number of generated tokens per step). When None the distill trainer auto-derives min(max_length, 32) for the consumer-GPU budget. The autoregressive loop re-forwards the full growing prefix each step (\~O(L^2) graph), so keep this small. Requires minillm_on_policy=True. (v0.71.18 #257) |
+| `training.uld_strategy` | `str \| null` | `null` | one of `"wasserstein"`, `"topk_align"`, `"wasserstein_aligned"` | Cross-tokenizer distillation strategy: 'wasserstein' (no alignment needed), 'topk_align' (requires uld_top_k), or 'wasserstein_aligned' (token-sequence alignment for fully disjoint tokenizers, v0.71.18 #258). Requires task='distill' on a non-mlx backend. |
+| `training.uld_top_k` | `int \| null` | `null` | `>= 1`, `<= 262144` | Top-K teacher logits to align (uld_strategy='topk_align' only). Bounded \[1, 262144] to cap pathological vocabs. (v0.70.0) |
+| `training.reward_hack_detector` | `str \| null` | `null` | one of `"info_rm"`, `"rm_ensemble"` | Reward-hacking detector for GRPO/PPO. 'info_rm' tracks InfoRM cluster-separation across training; 'rm_ensemble' tracks pairwise variance across an RM ensemble. Requires task in {'grpo', 'ppo'} on a non-mlx backend; installs the shared reward-signal callback. |
+| `training.reward_hack_halt` | `bool` | `false` | | Auto-halt training on HACK verdict (drop_pct >= 30% in cluster separation). Requires reward_hack_detector to be set. (v0.70.0) |
+| `training.reward_hack_mitigation` | `str` | `"off"` | one of `"off"`, `"log_only"`, `"kl_control"`, `"pid_lagrangian"` | Closed-loop reward-hacking mitigation mode (v0.71.26). 'off' = no mitigation; 'log_only' = instrument + append a mitigation log without touching training; 'kl_control' = reversible bang-bang KL/β controller; 'pid_lagrangian' = PID-Lagrangian controller + rollback escalation ladder. Any non-'off' mode requires reward_hack_detector (the signal source) and task in {'grpo', 'ppo'} on a non-mlx backend. |
+| `training.reward_hack_beta_floor` | `float` | `0.02` | `> 0.0` | v0.71.26 — lower β/kl_coef bound for the mitigation controller. Must be > 0 (β=0 gates off the ref-log-prob path at generation). |
+| `training.reward_hack_beta_ceil` | `float` | `1.0` | `> 0.0`, `<= 1000.0` | v0.71.26 — upper β/kl_coef bound for the mitigation controller. Must be > reward_hack_beta_floor. |
+| `training.reward_hack_trip_band` | `float` | `0.3` | `>= 0.0`, `<= 1.0` | v0.71.26 — hacking drop_pct at/above which the controller wants to RAISE β. Must be > reward_hack_release_band. |
+| `training.reward_hack_release_band` | `float` | `0.1` | `>= 0.0`, `<= 1.0` | v0.71.26 — hacking drop_pct at/below which the controller wants to RELAX β. Must be &lt; reward_hack_trip_band. |
+| `training.reward_hack_dwell_steps` | `int` | `2` | `>= 1`, `<= 100000` | v0.71.26 — consecutive trip-band steps required before the controller raises β (hysteresis). |
+| `training.reward_hack_release_patience` | `int` | `3` | `>= 1`, `<= 100000` | v0.71.26 — consecutive release-band steps required before the controller relaxes β. |
+| `training.reward_hack_kl_gain` | `float` | `1.5` | `> 1.0`, `<= 100.0` | v0.71.26 — multiplicative β step per trip (>1). β is multiplied on trip / divided on release, clamped to \[floor, ceil]. |
+| `training.reward_hack_signals` | `list[str]` | `["info_rm"]` | max length 4 | v0.71.26 — signals combined into the controller's multi-signal vote. Allowlist (max 4): info_rm, rm_ensemble, length_trend, repetition. |
+| `training.reward_hack_pid_kp` | `float` | `0.5` | `>= 0.0`, `<= 1000.0` | v0.71.26 — PID proportional gain (pid_lagrangian mode). |
+| `training.reward_hack_pid_ki` | `float` | `0.1` | `>= 0.0`, `<= 1000.0` | v0.71.26 — PID integral gain (pid_lagrangian mode). |
+| `training.reward_hack_pid_kd` | `float` | `0.05` | `>= 0.0`, `<= 1000.0` | v0.71.26 — PID derivative gain (pid_lagrangian mode). |
+| `training.reward_hack_signal_target` | `float` | `0.15` | `>= 0.0`, `< 1.0` | v0.71.26 — target hacking drop_pct the PID controller holds (pid_lagrangian mode). |
+| `training.reward_hack_integral_clamp` | `float` | `1.0` | `> 0.0`, `<= 1000.0` | v0.71.26 — PID anti-windup bound on the integral accumulator (pid_lagrangian mode). Independent of beta_ceil. |
+| `training.reward_hack_rollback` | `bool` | `false` | | v0.71.26 — enable rollback to the last-good RL checkpoint in the escalation ladder. Requires rl_checkpoint_save_every_steps set. |
+| `training.reward_hack_rollback_patience` | `int` | `3` | `>= 1`, `<= 100000` | v0.71.26 — consecutive HACK steps before a rollback is triggered. |
+| `training.reward_hack_max_recovery_attempts` | `int` | `2` | `>= 0`, `<= 1000` | v0.71.26 — max rollbacks before the controller early-stops training (terminal rung of the escalation ladder). |
+| `training.reward_hack_signal_smoothing` | `str` | `"none"` | one of `"none"`, `"ema"`, `"median"` | v0.71.26 — per-signal smoothing before the controller vote: 'none', 'ema' (0.5·prev+0.5·new), or 'median' over a window. |
+| `training.reward_hack_smoothing_window` | `int` | `8` | `>= 2`, `<= 256` | v0.71.26 — window length for signal smoothing. |
+| `training.reward_hack_conservative_on_disagreement` | `bool` | `false` | | v0.71.26 — when detectors disagree, keep KL high (use the MAX signal) instead of relaxing. |
+| `training.reward_hack_reward_shaping` | `bool` | `false` | | v0.71.26 — apply a bounded penalty on the gamed proxy (length/repetition/sentinel) via a shaping shim over the reward fn. Requires reward_hack_shaping_strength > 0 and a control mode. |
+| `training.reward_hack_shaping_kind` | `str` | `"length"` | one of `"length"`, `"repetition"`, `"sentinel"` | v0.71.26 — which gamed proxy the reward-shaping shim penalises. |
+| `training.reward_hack_shaping_strength` | `float` | `0.0` | `>= 0.0`, `<= 1.0` | v0.71.26 — magnitude of the bounded reward-shaping penalty \[0, 1]. |
+| `training.ppo_epochs` | `int` | `4` | `>= 1` | Number of PPO optimization epochs per batch |
+| `training.ppo_clip_ratio` | `float` | `0.2` | `> 0`, `<= 1.0` | PPO clipping range for policy ratio |
+| `training.ppo_kl_penalty` | `float` | `0.05` | `>= 0` | KL divergence penalty coefficient for PPO |
+| `training.reward_model` | `str \| null` | `null` | | Path or HF ID of a trained reward model for PPO |
+| `training.loraplus_lr_ratio` | `float \| null` | `null` | `> 0` | LoRA+ lr ratio: lr_B = lr × ratio. None = disabled (standard LoRA). |
+| `training.use_lorafa` | `bool` | `false` | | Enable LoRA-FA (Frozen-A LoRA) optimizer: freezes LoRA A matrices to reduce activation memory |
+| `training.use_galore` | `bool` | `false` | | Enable GaLore (Gradient Low-Rank Projection) for memory-efficient training |
+| `training.galore_rank` | `int` | `128` | `>= 1` | GaLore projection rank |
+| `training.galore_update_proj_gap` | `int` | `200` | `>= 1` | GaLore projection update interval (steps) |
+| `training.galore_scale` | `float` | `0.25` | `> 0` | GaLore gradient scaling factor |
+| `training.moe_lora` | `bool` | `false` | | Enable MoE-aware LoRA (ScatterMoE) — applies LoRA to expert FFN layers |
+| `training.moe_aux_loss_coeff` | `float` | `0.01` | `>= 0` | Auxiliary load-balancing loss coefficient for MoE models |
+| `training.use_liger` | `bool` | `false` | | Enable Liger Kernel fused operations (20-60% memory savings, 20-40% speedup) |
+| `training.use_flash_attn` | `bool` | `false` | | Enable FlashAttention (auto-detects v2/v3/v4 for faster attention) |
+| `training.use_ring_attention` | `bool` | `false` | | Enable Ring FlashAttention for sequence parallelism across GPUs |
+| `training.rope_scaling_type` | `str \| null` | `null` | one of `"linear"`, `"dynamic"`, `"yarn"`, `"llama3"` | RoPE scaling method for long-context: linear, dynamic, yarn or llama3 (v0.49.0). 'longrope' is refused at config load (#1239). Applied by task sft, tts and pretrain on backend: transformers (sft: the text path without layer streaming); refused at config load anywhere else (#1697). |
+| `training.yarn_factor` | `float \| null` | `null` | `> 1.0`, `<= 1024.0` | YaRN scaling factor (s). Optional — when omitted, the runtime falls back to ``target_length / original_length`` (HF default behaviour). |
+| `training.yarn_attn_factor` | `float \| null` | `null` | `>= 0.0`, `<= 10.0` | YaRN attention temperature multiplier (default 1.0 in HF). |
+| `training.yarn_beta_fast` | `int \| null` | `null` | `>= 1`, `<= 1024` | YaRN beta_fast cutoff (HF default 32). |
+| `training.yarn_beta_slow` | `int \| null` | `null` | `>= 1`, `<= 1024` | YaRN beta_slow cutoff (HF default 1). |
+| `training.use_longlora` | `bool` | `false` | | Refused at config load (#1240): the LongLoRA override rolled the Q/K projections of half the heads with wrap-around under full causal attention, leaking future tokens, and applied no S² grouped attention. Use rope_scaling_type with plain LoRA to extend the context. |
+| `training.gradient_checkpointing` | `bool \| "selective" \| "medium" \| "full" \| "auto"` | `false` | | Gradient checkpointing for memory savings on long sequences. False/True (legacy bool) or tier: 'selective' (attention only), 'medium' (every other block), 'full' (all blocks), 'auto' (picks based on available VRAM). (v0.28.0). |
+| `training.use_cut_ce` | `bool` | `false` | | Enable Cut Cross-Entropy (CCE) for large-vocab models. Saves 8-24GB VRAM on Llama 3.1 128k vocab. Requires cut_cross_entropy. Mutually exclusive with Unsloth/MLX backends. |
+| `training.kernel_auto_compose` | `bool` | `false` | | Unsupported compatibility field. Set use_liger and/or use_flash_attn explicitly instead. |
+| `training.packing_cross_doc_attn_mask` | `bool` | `false` | | Never worked: Soup mapped this to packing_strategy='attention_free', which is not in TRL's allowlist (bfd / bfd-requeue / wrapped) on any released trl. Use packing: true with FlashAttention instead. (v0.28.0 / #691 / #709). |
+| `training.activation_offloading` | `str \| null` | `null` | one of `"cpu"`, `"disk"` | Offload activations to CPU or disk during backward pass. None=off, 'cpu'=offload to RAM, 'disk'=offload to tmp file. (v0.28.0). |
+| `training.embedding_loss` | `str` | `"contrastive"` | one of `"contrastive"`, `"triplet"`, `"cosine"` | Loss function for embedding training: contrastive, triplet, or cosine |
+| `training.embedding_margin` | `float` | `0.5` | `> 0` | Margin for contrastive/triplet loss (higher = stricter separation) |
+| `training.embedding_pooling` | `str` | `"mean"` | one of `"mean"`, `"cls"`, `"last"` | Pooling strategy for sentence embeddings: mean, cls, or last token |
+| `training.embedding_temperature` | `float` | `0.05` | `> 0` | Temperature for contrastive (InfoNCE) loss — lower = stricter similarity |
+| `training.curriculum` | `bool` | `false` | | Enable curriculum learning (sort dataset by difficulty, easy → hard) |
+| `training.curriculum_metric` | `str` | `"length"` | one of `"length"`, `"perplexity"`, `"loss"` | Metric for curriculum difficulty: length, perplexity, or loss |
+| `training.curriculum_buckets` | `int` | `4` | `>= 1`, `<= 20` | Number of difficulty stages for curriculum learning |
+| `training.curriculum_dynamic` | `bool` | `false` | | BETA: dynamically re-weight curriculum buckets every N steps via online uncertainty estimation (per-sample loss + grad norm). Requires curriculum=true. Multi-rank launches must wire an all_reduce hook on per-bucket stats (see utils.curriculum_dynamic.validate_distributed_curriculum). |
+| `training.curriculum_dynamic_recompute_steps` | `int` | `50` | `>= 1`, `<= 100000` | Recompute curriculum bucket sampler weights every N global training steps. |
+| `training.curriculum_dynamic_floor` | `float` | `0.05` | `> 0.0`, `<= 0.5` | Minimum normalised per-bucket weight after softmax. Must be in (0.0, 1/curriculum_buckets]; the cross-validator tightens this to the per-config ceiling. Prevents bucket starvation. |
+| `training.curriculum_dynamic_temperature` | `float` | `1.0` | `> 0.0`, `<= 100.0` | Softmax temperature on the uncertainty signal. Higher = flatter distribution; lower = concentrate on hardest buckets. |
+| `training.loss_watchdog` | `bool` | `false` | | Enable loss spike detection (auto-stop if loss exceeds threshold) |
+| `training.loss_watchdog_threshold` | `float` | `3.0` | `> 0`, `<= 100.0` | Stop training if loss exceeds this threshold |
+| `training.loss_watchdog_patience` | `int` | `5` | `>= 1`, `<= 1000` | Consecutive high-loss steps before stopping |
+| `training.rewind_log` | `bool` | `true` | | Write &lt;output>/rewind.jsonl: the dataset rows in every training micro-batch with each row's loss, read by `soup rewind` to name the rows behind a loss spike. SFT only (transformers and MLX, single process); resumed runs and packing turn it off with one warning. |
+| `training.loss_spike_recovery` | `bool` | `false` | | On watchdog trigger: write &lt;output>/spike_recovery.json with decayed LR and attempt count for re-launch (instead of bare stop). Requires loss_watchdog=true. |
+| `training.loss_spike_recovery_max_attempts` | `int` | `3` | `>= 1`, `<= 10` | Max number of spike-recovery attempts before giving up |
+| `training.loss_spike_recovery_lr_decay` | `float` | `0.5` | `> 0.0`, `< 1.0` | Multiply LR by this factor on each spike recovery (0.5 = halve) |
+| `training.relora_steps` | `int \| null` | `null` | `>= 1`, `<= 10000000` | Fire a paper-faithful ReLoRA restart every N global steps: merge the LoRA update into the base weight, reinitialize lora_A/lora_B, and optionally clear optimizer state. None disables. Requires float LoRA (training.quantization defaults to '4bit' and must be set to 'none'; incompatible with VeRA, DoRA, layer streaming, and FSDP2 compile). |
+| `training.relora_warmup_ratio` | `float` | `0.1` | `>= 0.0`, `<= 1.0` | Skip ReLoRA firings during the first warmup_ratio fraction of training |
+| `training.relora_reset_optimizer` | `bool` | `true` | | Clear optimizer state for lora_A/lora_B parameters after each ReLoRA merge+reinit restart |
+| `training.relora_prune_ratio` | `float` | `0.9` | `> 0.0`, `< 1.0` | Deprecated: kept so older YAML still loads. Restarts no longer magnitude-prune adapter weights; relora_reset_optimizer controls optimizer clearing instead. |
+| `training.convergence_detection` | `bool` | `false` | | Watch for loss plateau / oscillation and surface advice (continue / early_stop / lower_lr) at the end of training. |
+| `training.convergence_window` | `int` | `50` | `>= 5`, `<= 10000` | Staged, not enforced during training: number of recent losses to inspect for plateau / oscillation |
+| `training.convergence_rel_tol` | `float` | `0.005` | `> 0.0`, `<= 1.0` | Staged, not enforced during training: relative range threshold below which the window is a plateau |
+| `training.warmup_auto` | `bool` | `false` | | Auto-pick warmup_steps from dataset_size × epochs × warmup_ratio. Overrides any manual warmup_steps in the trainer. |
+| `training.auto_mixed_precision` | `bool` | `false` | | Pick bf16/fp16 based on model + GPU compute capability. Applied by task='sft' (and 'tts', which trains through the SFT trainer); refused on every other task, whose trainers pick their own precision. |
+| `training.grad_accum_auto_tune` | `bool` | `false` | | Monitor VRAM each step; warn (and recommend new batch/accum) when memory pressure is high. Advisory only: it does not rebuild the DataLoader or change accumulation during a run. |
+| `training.grad_accum_pressure_threshold` | `float` | `0.92` | `> 0.05`, `< 0.99` | VRAM utilisation fraction that triggers a recommendation |
+| `training.freeze_layers` | `int \| null` | `null` | `>= 1`, `<= 1000` | Freeze first N layers (from bottom). Train only remaining layers. Applied by tasks sft and tts on the text path with backend transformers and no layer streaming; refused everywhere else. |
+| `training.freeze_ratio` | `float \| null` | `null` | `> 0.0`, `< 1.0` | Freeze this fraction of layers (0.75 = freeze 75% from bottom). Applied by tasks sft and tts on the text path with backend transformers and no layer streaming; refused everywhere else. |
+| `training.unfrozen_parameters` | `list[str] \| null` | `null` | | Spectrum (#266) targeted training: regex patterns of parameter names to keep trainable — every other parameter is frozen. Full fine-tuning, LoRA off. Generate with `soup spectrum scan`. Mutually exclusive with LoRA features / freeze_layers / freeze_ratio / train_router_only; sft + transformers backend only. |
+| `training.lisa_enabled` | `bool` | `false` | | Enable LISA layerwise importance sampling (#267): every lisa_interval_steps, freeze all decoder layers except a random lisa_num_layers set (embeddings + head always trainable). Full fine-tuning, LoRA off. sft or pretrain + transformers + text + quantization=none only; mutually exclusive with LoRA features / freeze_layers / freeze_ratio / unfrozen_parameters. |
+| `training.lisa_num_layers` | `int` | `2` | `>= 1`, `<= 64` | LISA: number of decoder layers kept trainable per interval (clamped to the model's layer count). Small = LoRA-like memory. |
+| `training.lisa_interval_steps` | `int` | `20` | `>= 1`, `<= 1000000` | LISA: re-sample the active decoder layers every N global steps. |
+| `training.lisa_reset_optimizer` | `bool` | `true` | | Clear optimizer state for decoder layers that LISA re-freezes on each interval (avoids stale Adam moments). Mirrors relora_reset_optimizer. |
+| `training.lisa_train_embeddings` | `bool` | `true` | | Keep the always-on group (input embeddings + LM head + final norm) trainable every LISA interval. Default true is LISA as published (#267). Set false to freeze that group so only the sampled lisa_num_layers decoder layers train — the always-on set is the majority of LISA's memory, so this is the knob that buys the memory saving (#377). It is a real trade: the always-on set may be load-bearing for quality, so measure both ways. |
+| `training.stream_layers` | `bool` | `false` | | BETA — stream the frozen base layer-by-layer from CPU RAM so a model larger than VRAM can be fine-tuned. sft + transformers + text + quantization=none only; batch_size 1, no gradient accumulation. Slower than resident training, but these models did not run on the card at all. |
+| `training.stream_source` | `str` | `"auto"` | one of `"auto"`, `"ram"`, `"disk"` | Where the streamed base lives. 'ram' (the only tier implemented in v0.72.0) pins the base in CPU RAM; 'disk' is the v0.72.3 overflow tier; 'auto' picks RAM only when the store fits free-RAM headroom and the store plus resident extras fits the physical RAM ceiling. |
+| `training.stream_ngram_source` | `str` | `"auto"` | one of `"auto"`, `"ram"`, `"disk"` | Where Qwen4-Exp's frozen PLE N-gram embedding lives while layer streaming. 'disk' gathers only requested rows from the original safetensors through a read-only mmap; 'ram' keeps the table in CPU RAM; 'auto' uses RAM only when the table and selected base tier plus resident extras fit within free-RAM headroom and the physical RAM ceiling. oMLX/oQ affine PLE tables require 'disk' (or 'auto') so only selected rows are dequantized. A non-default value warns when the checkpoint has no external PLE table. |
+| `training.stream_buffers` | `int` | `2` | `>= 2`, `<= 8` | Pre-allocated VRAM layer buffers. 2 = double buffering, which is what lets the next layer load while the current one computes. A single buffer cannot overlap load with compute. |
+| `training.stream_read_ahead` | `int` | `2` | `>= 1`, `<= 8` | Layers the async disk tier stages ahead on its background thread. One staging slot is always held by the layer currently being consumed, so a setting of N stages N-1 layers ahead, not N: 1 = the read merely leaves the compute thread (nothing staged ahead of the one in use), 2 = one layer in flight while one is consumed, up to 7 staged ahead at the maximum setting of 8. Each level costs one layer of pinned host memory, which is 441 MB on a 70B. |
+| `training.stream_pin` | `bool \| null` | `null` | | Force the page-locked (pinned) host memory on or off — the RAM tier's base store, or the disk tier's async-reader host staging (#971). None (the default) lets the box decide: it attempts to page-lock that memory and falls back to pageable — announcing the cost — when the host cannot page-lock it. 'false' forces the pageable store, the only known escape hatch when a pinning path is suspect (it was the sole mitigation while #331 was live). 'true' forces pinning and REFUSES the run rather than silently degrading if the box cannot page-lock it: on the RAM tier naming the store size, on the disk tier naming training.stream_read_ahead as the depth that decides how much staging gets locked — page-locking is worth up to 6.56x measured throughput, so a silent fallback spends the whole margin the feature exists to provide. Non-CUDA targets (CPU or MPS) are the one case pinning stays INAPPLICABLE: 'true' is announced there and the run proceeds with a pageable CPU source, so the key stays committable to a config shared between CUDA and non-CUDA boxes. |
+| `training.stream_vram_override` | `int \| null` | `null` | `>= 0` | Bytes to assume free instead of measuring torch.cuda.mem_get_info(). mem_get_info() is a device-level driver query, so it cannot see a per-process cap (set_per_process_memory_fraction, a MIG slice, a card another process is also using), so on that hardware the pre-flight sees the whole device's free VRAM regardless of what this process can actually use. Set this to replace the measured figure in either direction: raise it to let a known-safe over-prediction through, or lower it to make the pre-flight enforce a cap the driver itself cannot report. |
+| `training.stream_vram_probe` | `bool` | `false` | | Decide the layer-streaming VRAM pre-flight on a MEASUREMENT instead of the fitted formula. One real forward+backward runs at the configured shape after the streamed model is built, and its peak decides whether the run proceeds; the prediction is printed beside it so a divergence is visible. The formula under-predicts past seq 4352 (measured 0.934x the real peak at seq 5120 and 0.787x at 6144), which is the direction that does not announce itself — an OOM on Linux, a silent spill to host memory on Windows. Against the probe the same formula reads 0.992x at seq 4096 and 0.830x at 5120, because the probe itself runs 12.5-14.3% above the real training step — the direction that makes it safe as a gate. Off by default: it costs one step (1-5 s measured) and it can refuse a run the formula accepts. task='sft' only: the probe runs a plain causal-LM forward+backward, which IS the SFT step but not a preference loss. At the one preference shape measured it reads +13.5% high (probe 6.021 GB against a real DPO step's 5.304 GB) — the same safe direction it shows for SFT — but one shape is not a validation, so the restriction stands until it is measured across shapes. |
+| `training.stream_disk_kind` | `str \| null` | `null` | one of `"nvme"`, `"ssd"`, `"hdd"` | Override the auto-detected disk media type for the streaming disk overflow tier. Detection classifies a device by a measured sequential read when the kernel's rotational flag is unreliable — virtio and other paravirtual disks report spinning with no media hint, so a fast cloud disk is otherwise refused (#365). Set this for the case where even that is wrong: 'nvme' forces the disk tier on, 'ssd'/'hdd' force it off. The resolved value is printed beside what was detected. |
+| `training.packing` | `bool` | `false` | | Pack multiple short samples into one sequence for faster training |
+| `training.multipack` | `bool` | `false` | | Use FFD bin-packing sampler to maximise tokens-per-batch on uneven-length data. Mutually exclusive with packing. Only supported for sft / pretrain tasks (transformers backend). (v0.37.0). |
+| `training.neftune_alpha` | `float \| null` | `null` | `>= 0.0`, `<= 50.0` | NEFTune noise alpha (0-50). Adds noise to embeddings for better chat quality. |
+| `training.forgetting_detection` | `bool` | `false` | | Staged, not enforced during training: enable periodic general-knowledge eval to detect catastrophic forgetting |
+| `training.forgetting_eval_steps` | `int` | `100` | `>= 10`, `<= 10000` | Staged, not enforced during training: run forgetting eval every N steps |
+| `training.forgetting_threshold` | `float` | `0.1` | `>= 0.01`, `<= 0.5` | Staged, not enforced during training: warn if accuracy drops beyond this threshold (0.01-0.50) |
+| `training.forgetting_benchmark` | `str` | `"mini_mmlu"` | one of `"mini_mmlu"`, `"mini_common_sense"`, `"mini_instruction"` | Staged, not enforced during training: built-in mini benchmark for forgetting detection |
+| `training.forgetting_stop` | `bool` | `false` | | Staged, not enforced during training: stop on severe forgetting |
+| `training.checkpoint_intelligence` | `bool` | `false` | | Staged, not enforced during training: track best checkpoints by quality |
+| `training.checkpoint_eval_steps` | `int` | `200` | `>= 50`, `<= 10000` | Staged, not enforced during training: evaluate checkpoint quality |
+| `training.checkpoint_eval_metric` | `str` | `"composite"` | one of `"judge"`, `"mmlu"`, `"custom"`, `"composite"` | Staged, not enforced during training: checkpoint quality metric |
+| `training.checkpoint_eval_tasks` | `str \| null` | `null` | | Staged, not enforced during training: JSONL tasks for checkpoint scoring |
+| `training.checkpoint_keep_top` | `int` | `3` | `>= 1`, `<= 20` | Staged, not enforced during training: keep top-N quality checkpoints |
+| `training.early_stop_on_regression` | `bool` | `false` | | Staged, not enforced during training: stop after consecutive regressions |
+| `training.early_stop_patience` | `int` | `2` | `>= 1`, `<= 10` | Staged, not enforced during training: regressions before stopping (1-10) |
+| `training.eval_gate` | `section \| null` | `null` | | Optional EvalGateConfig — block training on regressions. See [`training.eval_gate`](#trainingeval_gate). |
+| `training.use_fsdp2_compile` | `bool` | `false` | | Enable torch.compile on top of FSDP2 for +20-30% training speed. Requires --fsdp, CUDA, and backend=transformers. |
+| `training.parallelism` | `str` | `"data"` | one of `"data"`, `"pipeline"` | Distributed strategy: 'data' (DDP/FSDP/DeepSpeed) or 'pipeline' (pipeline parallel, v0.27.0 wiring only). |
+| `training.pipeline_stages` | `int` | `1` | `>= 1`, `<= 16` | Number of pipeline parallel stages. Ignored when parallelism='data'. |
+| `training.unlearn_method` | `str \| null` | `null` | one of `"npo"`, `"simnpo"`, `"rmu"` | Unlearning method backend — required when task='unlearn'. npo (Negative Preference Optimization, DPO-shaped negative-only loss); simnpo (length-normalised NPO without ref model); rmu (Representation Misdirection Unlearning, residual-stream noise). |
+| `training.unlearn_alpha` | `float \| null` | `null` | | Retain-set weighting in the unlearn loss (forget vs retain mixing coefficient). 0.0 = pure forget loss; higher values increasingly favour the retain set. Bounded \[0.0, 10.0]. (v0.61.0) |
+| `training.ra_dit_stage` | `str \| null` | `null` | one of `"retriever"`, `"generator"` | RA-DIT pipeline stage. 'retriever' trains the sentence-transformer via the v0.16 embedding trainer; 'generator' runs RAFT-style SFT on `data.format='raft'`. Composes with the v0.62.0 RAFT recipe. (v0.62.0) |
+| `training.ra_dit_retriever_model` | `str \| null` | `null` | | Optional retriever model id (e.g. `sentence-transformers/all-mpnet-base-v2`) used by the generator stage to pre-encode distractor docs. (v0.62.0) |
+| `training.citation_faithful` | `bool` | `false` | | Opt INTO citation-precision / recall scoring + a loss-mask rule that emphasises citation spans. Requires `data.format='raft'`; SFT and RAFT trainers apply the weighted citation-span mask. |
+| `training.citation_style` | `str \| null` | `null` | one of `"bracket"`, `"inline"`, `"footnote"` | Citation rendering style. 'bracket' = `[doc-1]` inline tag (canonical RAFT default), 'inline' = `(doc-1)`, and 'footnote' = `[^doc-1]`. Used by citation scoring and span masking. |
+| `training.citation_recall_threshold` | `float \| null` | `null` | | Staged, not applied: a citation-recall threshold in \[0.0, 1.0] that nothing gates a save or a run on; setting it warns at load, then is refused (#761). (v0.62.0) |
+| `training.grace_codebook` | `bool` | `false` | | Reserve GRACE codebook configuration for training. Compatibility validation only: no trainer or knowledge-edit command consumes this field yet. |
+| `training.grace_codebook_size` | `int \| null` | `null` | | Reserved GRACE codebook entry count. Required when grace_codebook=True and bounded \[1, 100_000], but not consumed at runtime yet. |
+| `training.grace_codebook_dim` | `int \| null` | `null` | | Reserved GRACE codebook entry dimension. Required when grace_codebook=True and bounded \[1, 16_384], but not consumed at runtime yet. |
+
+## `training.lora`
+
+| Key | Type | Default | Constraints | Description |
+|---|---|---|---|---|
+| `training.lora.r` | `int` | `64` | `>= 0` | LoRA rank. 0 = full fine-tuning: no adapter, every base parameter trains (sft / embedding + transformers + text + quantization='none' only). |
+| `training.lora.alpha` | `int` | `16` | | LoRA alpha |
+| `training.lora.dropout` | `float` | `0.05` | | LoRA dropout |
+| `training.lora.target_modules` | `str \| list[str]` | `"auto"` | | Target modules for LoRA. 'auto' = let peft decide. |
+| `training.lora.target_parameters` | `"auto" \| list[str] \| null` | `null` | | Raw 2-D/3-D nn.Parameter tensors to adapt with PEFT LoRA. Use 'auto' to select architecture-specific parameter targets (currently Qwen4-Exp routed experts), a list of parameter-name suffixes for explicit control, or omit to disable. Requires dropout=0 and is wired for transformers SFT/pretrain. |
+| `training.lora.use_dora` | `bool` | `false` | | Enable DoRA (Weight-Decomposed Low-Rank Adaptation) |
+| `training.lora.use_rslora` | `bool` | `false` | | Enable rank-stabilized LoRA scaling (better for high ranks) |
+| `training.lora.use_vera` | `bool` | `false` | | Enable VeRA (Vector-based Random Matrix Adaptation). Shared random matrices — much smaller memory than LoRA. Mutually exclusive with use_dora and use_olora. |
+| `training.lora.use_olora` | `bool` | `false` | | Enable OLoRA (Orthogonal LoRA init via QR decomposition). Passes init_lora_weights='olora' to peft. Mutually exclusive with use_dora and use_vera. Equivalent to init_strategy='olora'. |
+| `training.lora.rank_pattern` | `dict[str, int] \| null` | `null` | | Per-target-module-pattern LoRA rank override. Maps module name patterns (e.g. 'q_proj', 'experts.\*.w1') to integer rank values. Useful for MoE configs where expert FFNs need lower rank than attn. Incompatible with use_vera (VeRA shares one rank across modules). |
+| `training.lora.alpha_pattern` | `dict[str, int] \| null` | `null` | | Per-target-module-pattern LoRA alpha override. Maps module name patterns to integer alpha values. Pairs with rank_pattern. Incompatible with use_vera. |
+| `training.lora.init_strategy` | `str` | `"random"` | one of `"random"`, `"pissa"`, `"olora"`, `"loftq"` | LoRA init strategy. 'random' (default) is standard Kaiming init. 'pissa' (PiSSA) initializes A/B from the SVD of the base weight — faster early convergence but adds an SVD pass on the first epoch. 'olora' is equivalent to use_olora=True (orthogonal QR init). 'loftq' (v0.41.0) initialises A/B + a low-bit base together, useful with QLoRA. Cannot be combined with use_dora or use_vera. |
+| `training.lora.loftq_iter` | `int` | `1` | `>= 1`, `<= 10` | LoftQ iteration count (1-10). Higher = better quant-aware init at the cost of one-time setup latency. Used only when init_strategy='loftq'. |
+| `training.lora.loftq_bits` | `int` | `4` | one of `2`, `4`, `8` | LoftQ target bitwidth — must be one of {2, 4, 8}. Used only when init_strategy='loftq'. |
+
+## `training.eval_gate`
+
+| Key | Type | Default | Constraints | Description |
+|---|---|---|---|---|
+| `training.eval_gate.enabled` | `bool` | `false` | | Turn the eval gate on |
+| `training.eval_gate.suite` | `str \| null` | `null` | | Path to eval-suite YAML (evals/gate.yaml) |
+| `training.eval_gate.every_n_epochs` | `int` | `1` | `>= 1`, `<= 100` | Run gate every N epochs (1-100) |
+| `training.eval_gate.regression_threshold` | `float` | `0.05` | `>= 0.0`, `<= 1.0` | Max absolute drop vs baseline before regression fires |
+| `training.eval_gate.baseline` | `str \| null` | `null` | | registry://&lt;id> \| 'previous' \| file path - scores to compare against |
+| `training.eval_gate.on_regression` | `str` | `"stop"` | one of `"stop"`, `"warn"`, `"continue"` | Action on regression: stop training \| warn only \| continue |
+
+## `eval`
+
+| Key | Type | Default | Constraints | Description |
+|---|---|---|---|---|
+| `eval.auto_eval` | `bool` | `false` | | Run evaluation automatically after training completes |
+| `eval.benchmarks` | `list[str] \| null` | `null` | | lm-evaluation-harness benchmark names to run |
+| `eval.custom_tasks` | `str \| null` | `null` | | Path to custom eval JSONL file |
+| `eval.judge` | `dict \| null` | `null` | | LLM-as-a-judge config: model, rubric, provider |
+| `eval.ship` | `section \| null` | `null` | | soup ship verdict defaults (task_eval / task_mode / general_suite / forgetting_threshold / judge_model / baseline / noise_floor). See [`eval.ship`](#evalship). |
+
+## `eval.ship`
+
+| Key | Type | Default | Constraints | Description |
+|---|---|---|---|---|
+| `eval.ship.task_eval` | `str \| null` | `null` | | JSONL of leg-1 task-win eval tasks |
+| `eval.ship.task_mode` | `str` | `"metric"` | one of `"metric"`, `"judge_score"`, `"pairwise"` | Leg-1 mode: metric \| judge_score \| pairwise (judge win-rate) |
+| `eval.ship.general_suite` | `str \| null` | `null` | | Comma list of leg-2 benchmarks (default: bundled offline suite) |
+| `eval.ship.forgetting_threshold` | `float` | `0.05` | `>= 0.0`, `<= 1.0` | Max allowed leg-2 drop in absolute points before DON'T SHIP |
+| `eval.ship.judge_model` | `str \| null` | `null` | | Judge model URL for task_mode judge_score / pairwise |
+| `eval.ship.baseline` | `str \| null` | `null` | | registry://&lt;id> \| stamped baseline JSON ({scores, provenance.scorer_revision}) of base leg-2 scores |
+| `eval.ship.noise_floor` | `int \| null` | `null` | `>= 2`, `<= 10` | Repeats of the BASE run used to measure a leg-2 noise floor; a leg-2 drop within the floor is treated as noise, not regression. Bounded \[2, 10]. A live input: measured when producing evidence, refused under --evidence. |
+
+## `advise`
+
+| Key | Type | Default | Constraints | Description |
+|---|---|---|---|---|
+| `advise.goal` | `str \| null` | `null` | max length 4096 | Default goal string for `soup advise`. Sharpens task classification when set. |
+| `advise.probe` | `bool` | `false` | | Run the 10-minute ROI probe by default when `soup advise` is invoked through this config. Heuristic stubs in v0.54.0. |
+| `advise.record` | `bool` | `false` | | Append every verdict from this config to \~/.soup/advise_history.jsonl with accepted=True. |
diff --git a/scripts/gen_reference_docs.py b/scripts/gen_reference_docs.py
new file mode 100644
index 00000000..12ab7ac0
--- /dev/null
+++ b/scripts/gen_reference_docs.py
@@ -0,0 +1,1257 @@
+"""Render the two generated reference pages from the code.
+
+``docs/config-reference.md`` lists every key ``soup.yaml`` accepts, walked out of
+``SoupConfig.model_fields``. ``docs/cli-reference.md`` lists every command, option and
+argument, walked out of the Click tree behind the Typer app. Neither page is written
+by hand: change the schema field or the option, then run this script.
+
+ python scripts/gen_reference_docs.py # rewrite the pages that changed
+ python scripts/gen_reference_docs.py --check-structure # what the test suite runs
+ python scripts/gen_reference_docs.py --check # byte-exact, for a release
+
+Two checks, because they answer different questions. ``--check-structure`` parses the
+committed tables back into rows and compares what a page *states*: per config key its
+type, default and constraints; per command its parameters, each with its names, type,
+default and whether it is required. A missing, extra or changed one fails and is named.
+Descriptions, help text and command summaries are not compared, so rewording a help
+string does not turn a pull request red; the wording is refreshed when a release is cut.
+``--check`` compares the text itself and is what a release runs
+(``SOUP_DOCS_EXACT=1`` makes the test suite run it too).
+
+For the same reason no line on a page is a total or a list over several items: every
+line belongs to one key, one command or one parameter, so two changes that each add a
+different option merge as text and the merged page is still right.
+
+``tests/test_gen_reference_docs.py`` runs the check on every interpreter and OS in the
+CI matrix, so the same text has to come out everywhere. What keeps it that way:
+
+* Types are spelled here, from ``typing`` introspection, never from ``repr()``:
+ ``Optional[int]``, ``Union[int, None]`` and ``int | None`` all read ``int | null``.
+* Nothing is taken from ``--help`` output, which carries ANSI colour and wraps at the
+ terminal width. Commands and parameters are read off the Click objects; Rich markup
+ in help strings is removed by a regex of its own.
+* Field and parameter order is the declaration order; command names are sorted.
+* A default that only this machine could have produced (a path under the home or the
+ working directory, a drive path, a callable, a non-container factory value) is
+ printed as ``(set at runtime)``, never as its value. Environment variables are named,
+ never read.
+* The two completion options Typer adds change shape with shell detection, so their
+ rows are fixed text.
+* Pages are written as UTF-8 with ``\\n`` newlines; the check compares text, so a CRLF
+ checkout (``core.autocrlf``) of an LF blob still passes.
+
+A numeric default computed from the machine (``os.cpu_count()``) cannot be told from a
+literal one. There is none today; the cross-OS check is what would catch the first.
+
+Rendering imports the schema and the CLI, never torch: both stay on the light core.
+"""
+
+from __future__ import annotations
+
+import argparse
+import collections.abc
+import enum
+import json
+import os
+import re
+import sys
+import tempfile
+import types
+import typing
+import unicodedata
+from dataclasses import dataclass
+from pathlib import Path, PurePath
+from typing import Any, Callable, Sequence
+
+import click
+from pydantic import BaseModel
+from pydantic.fields import FieldInfo
+
+_SCRIPT_REPO_ROOT = Path(__file__).resolve().parent.parent
+#: Where the pages are read and written. Tests set this to a scratch tree.
+_REPO_ROOT = _SCRIPT_REPO_ROOT
+
+CONFIG_PAGE = "docs/config-reference.md"
+CLI_PAGE = "docs/cli-reference.md"
+RUNTIME_DEFAULT = "(set at runtime)"
+
+_REGENERATE = "python scripts/gen_reference_docs.py"
+#: How many differences ``--check-structure`` prints per page before "... and N more".
+_MAX_SHOWN = 10
+_NONE_TYPE = type(None)
+_NOT_LITERAL = object()
+
+
+# --------------------------------------------------------------------------
+# Markdown
+# --------------------------------------------------------------------------
+
+_CODE_SPAN = re.compile(r"(?<!`)(`+)(?!`)(.+?)(?<!`)\1(?!`)")
+#: ``&`` first, so the entities written for ``<`` are not escaped again; the backslash
+#: before every escape that is itself written with one.
+_PROSE_ESCAPES = (
+ ("&", "&amp;"),
+ ("<", "&lt;"),
+ ("\\", "\\\\"),
+ ("`", "\\`"),
+ ("*", "\\*"),
+ ("[", "\\["),
+ ("|", "\\|"),
+ ("~", "\\~"),
+ ("$", "\\$"),
+)
+#: An underscore inside a word (``snake_case``) never opens emphasis; any other one can.
+_LOOSE_UNDERSCORE = re.compile(r"(?<![A-Za-z0-9])_|_(?![A-Za-z0-9])")
+#: What would turn a paragraph of its own into a heading, a quote or a list item.
+_BLOCK_START = re.compile(r"^(?:#{1,6}(?=\s|$)|>|[+-](?=\s|$))")
+_LIST_START = re.compile(r"^(\d+)([.)])(?=\s|$)")
+_INTERNAL_PHASE = re.compile(r"\b(v\d+(?:\.\d+){1,2})\s+part\s+[a-z]\b", re.IGNORECASE)
+#: Rich's own tag grammar (``rich.markup.RE_TAGS``): a ``[`` then a lowercase letter,
+#: ``#``, ``/`` or ``@``, up to the next ``]``, with any backslashes in front of it.
+_RICH_TAG = re.compile(r"(\\*)\[([a-z#/@][^\[\]]*)\]")
+_RICH_COLOUR = re.compile(
+ r"#[0-9a-f]{6}|color\(\d{1,3}\)|rgb\(\d{1,3},\d{1,3},\d{1,3}\)|gr[ae]y\d{0,3}"
+ r"|(?:bright_)?(?:black|red|green|yellow|blue|magenta|cyan|white)"
+)
+_RICH_WORDS = frozenset(
+ "bold b dim italic i underline u strike s reverse blink conceal link not on default".split()
+)
+
+
+def _escape_prose(text: str) -> str:
+ for raw, safe in _PROSE_ESCAPES:
+ text = text.replace(raw, safe)
+ return _LOOSE_UNDERSCORE.sub(r"\\_", text)
+
+
+def escape_cell(text: str) -> str:
+ """``text`` as one table cell: a single line, no cell break, no stray markup.
+
+ Code spans are kept as code (only their ``|`` is escaped, which a GitHub table
+ undoes inside code); everything else has the characters that Markdown or HTML
+ would interpret escaped, so ``<id>`` stays visible and ``*`` stays a star.
+ """
+ text = " ".join(text.split())
+ parts: list[str] = []
+ position = 0
+ for match in _CODE_SPAN.finditer(text):
+ parts.append(_escape_prose(text[position : match.start()]))
+ parts.append(match.group(0).replace("|", "\\|"))
+ position = match.end()
+ parts.append(_escape_prose(text[position:]))
+ return "".join(parts)
+
+
+def _escape_paragraph(text: str) -> str:
+ """``escape_cell`` for a paragraph of its own, which must not open a block."""
+ escaped = _LIST_START.sub(r"\1\\\2", escape_cell(text))
+ return f"\\{escaped}" if _BLOCK_START.match(escaped) else escaped
+
+
+def _code(text: str) -> str:
+ """``text`` as a code span that survives a table cell."""
+ text = text.replace("\r", " ").replace("\n", " ")
+ fence = "`"
+ while fence in text:
+ fence += "`"
+ pad = " " if text.startswith("`") or text.endswith("`") else ""
+ return f"{fence}{pad}{text.replace('|', chr(92) + '|')}{pad}{fence}"
+
+
+def _row(cells: Sequence[str]) -> str:
+ return "| " + " | ".join(cells) + " |"
+
+
+def _table_head(*titles: str) -> list[str]:
+ return [_row(titles), "|" + "---|" * len(titles)]
+
+
+def strip_internal_phase(text: str) -> str:
+ """Drop the planning label from ``v0.42.0 Part B``; public docs keep the version."""
+ return _INTERNAL_PHASE.sub(r"\1", text)
+
+
+def _is_rich_style(tag: str) -> bool:
+ body = tag[1:] if tag.startswith("/") else tag
+ if not body:
+ return True # ``[/]`` closes whatever is open
+ if body.startswith(("link=", "@")):
+ return True
+ return all(word in _RICH_WORDS or _RICH_COLOUR.fullmatch(word) for word in body.split())
+
+
+def strip_rich_markup(text: str) -> str:
+ """Remove Rich style tags from a help string and undo its ``\\[`` escapes.
+
+ Only tags that are styles are removed. Rich itself also swallows ``[sigstore]`` in
+ ``pip install soup-cli[sigstore]`` when the author forgot the backslash; the
+ bracketed text is what was meant, so it is kept here.
+ """
+
+ def replace(match: re.Match[str]) -> str:
+ slashes, tag = match.group(1), match.group(2)
+ kept = "\\" * (len(slashes) // 2)
+ if len(slashes) % 2 or not _is_rich_style(tag):
+ return f"{kept}[{tag}]"
+ return kept
+
+ return _RICH_TAG.sub(replace, text)
+
+
+def summary_line(help_text: str | None) -> str:
+ """The first paragraph of a command's help, on one line."""
+ text = (help_text or "").split("\f", 1)[0].strip()
+ first = re.split(r"\n[ \t]*\n", text, maxsplit=1)[0]
+ return " ".join(first.split())
+
+
+def github_slug(heading: str) -> str:
+ """The anchor GitHub gives a heading: lowercase, spaces dashed, and only letters,
+ marks, decimal digits, ``_`` and ``-`` kept (so the subscript in ``CO₂`` is dropped)."""
+ text = heading.replace("`", "").strip().lower()
+ kept = []
+ for char in text:
+ category = unicodedata.category(char)
+ if char == " ":
+ kept.append("-")
+ elif char == "-" or category[0] in "LM" or category in ("Nd", "Nl", "Pc"):
+ kept.append(char)
+ return "".join(kept)
+
+
+class _Slugger:
+ """Anchors in document order; GitHub numbers a repeated heading ``-1``, ``-2``."""
+
+ def __init__(self) -> None:
+ self._seen: dict[str, int] = {}
+
+ def take(self, heading: str) -> str:
+ base = github_slug(heading)
+ count = self._seen.get(base, 0)
+ self._seen[base] = count + 1
+ return base if not count else f"{base}-{count}"
+
+
+# --------------------------------------------------------------------------
+# Values that must read the same on every machine
+# --------------------------------------------------------------------------
+
+
+def _machine_markers() -> tuple[str, ...]:
+ """This machine's home, working and temp directories, normalised for matching.
+
+ Only those at least two directories deep. A checkout at ``/repo`` or ``/data`` (a
+ container's working directory) is also an ordinary piece of a relative default such
+ as ``./data/train.jsonl``, and must not turn that default into a placeholder there.
+ """
+ found = set()
+ for raw in (os.path.expanduser("~"), os.getcwd(), tempfile.gettempdir()):
+ marker = raw.replace("\\", "/").rstrip("/").casefold()
+ if marker.count("/") >= 2: # "/home/u" and "c:/users/u"; not "/repo", "/tmp", "c:"
+ found.add(marker)
+ return tuple(sorted(found))
+
+
+def _is_machine_specific(text: str) -> bool:
+ """True for a string only this machine could have produced: a Windows drive path, or
+ one of this machine's directories as a whole path (never as the tail of another)."""
+ normalised = text.replace("\\", "/").casefold()
+ if re.match(r"^[a-z]:/", normalised):
+ return True
+ return any(
+ re.search(r"(?<![\w./~-])" + re.escape(marker) + r"(?=/|$)", normalised)
+ for marker in _machine_markers()
+ )
+
+
+def _plain_literal(value: Any) -> Any:
+ """``value`` as JSON-ready data, or ``_NOT_LITERAL`` when it is not a stable literal."""
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ if isinstance(value, enum.Enum):
+ return _plain_literal(value.value)
+ if isinstance(value, PurePath):
+ return _plain_literal(value.as_posix())
+ if isinstance(value, str):
+ return _NOT_LITERAL if _is_machine_specific(value) else value
+ if isinstance(value, (set, frozenset)):
+ try:
+ value = sorted(value)
+ except TypeError:
+ return _NOT_LITERAL
+ if isinstance(value, (list, tuple)):
+ items = [_plain_literal(item) for item in value]
+ return _NOT_LITERAL if any(item is _NOT_LITERAL for item in items) else items
+ if isinstance(value, dict):
+ out = {}
+ for key, item in value.items():
+ plain = _plain_literal(item)
+ if not isinstance(key, str) or plain is _NOT_LITERAL:
+ return _NOT_LITERAL
+ out[key] = plain
+ return out
+ return _NOT_LITERAL
+
+
+def format_default(value: Any) -> str:
+ """A default as a YAML flow value (``null``, ``true``, ``"auto"``, ``["a"]``).
+
+ Anything that is not a plain literal, or that carries this machine's paths, is
+ ``RUNTIME_DEFAULT``.
+ """
+ plain = _plain_literal(value)
+ if plain is _NOT_LITERAL:
+ return RUNTIME_DEFAULT
+ return json.dumps(plain, ensure_ascii=False)
+
+
+def _default_cell(text: str) -> str:
+ return f"*{RUNTIME_DEFAULT}*" if text == RUNTIME_DEFAULT else _code(text)
+
+
+# --------------------------------------------------------------------------
+# Types
+# --------------------------------------------------------------------------
+
+_SCALARS = {str: "str", int: "int", float: "float", bool: "bool", bytes: "bytes"}
+
+
+def _is_class(annotation: Any) -> bool:
+ """A real class, never a parametrised generic. ``isinstance(type[int], type)`` is
+ true on Python 3.10 and false from 3.11, so asking only that would spell the same
+ annotation two ways."""
+ return typing.get_origin(annotation) is None and isinstance(annotation, type)
+
+
+def _container_name(base: Any) -> str | None:
+ """``list`` / ``dict`` / ``set`` / ``tuple`` for a container class or generic origin
+ (``typing.List``, ``collections.abc.Sequence`` and ``list`` all read ``list``)."""
+ if not isinstance(base, type) or issubclass(base, (str, bytes)):
+ return None
+ if issubclass(base, tuple):
+ return "tuple"
+ if issubclass(base, collections.abc.Mapping):
+ return "dict"
+ if issubclass(base, collections.abc.Set):
+ return "set"
+ if issubclass(base, collections.abc.Sequence):
+ return "list"
+ return None
+
+
+def _is_model(annotation: Any) -> bool:
+ return _is_class(annotation) and issubclass(annotation, BaseModel)
+
+
+def _union_members(annotation: Any) -> list[Any]:
+ """The members of a union, flattened, ``Annotated`` unwrapped, ``None`` as its type."""
+ origin = typing.get_origin(annotation)
+ if origin is typing.Annotated:
+ return _union_members(typing.get_args(annotation)[0])
+ if origin is typing.Union or origin is types.UnionType:
+ members: list[Any] = []
+ for arg in typing.get_args(annotation):
+ members.extend(_union_members(arg))
+ return members
+ return [_NONE_TYPE if annotation is None else annotation]
+
+
+def _choice_values(annotation: Any) -> list[Any] | None:
+ """The values of a ``Literal`` or an ``Enum`` class, else ``None``."""
+ if typing.get_origin(annotation) is typing.Literal:
+ return [
+ item.value if isinstance(item, enum.Enum) else item
+ for item in typing.get_args(annotation)
+ ]
+ if _is_class(annotation) and issubclass(annotation, enum.Enum):
+ return [member.value for member in annotation]
+ return None
+
+
+def _unique(items: Sequence[Any]) -> list[Any]:
+ """Order-preserving, and ``1`` is not ``True``."""
+ seen = set()
+ out = []
+ for item in items:
+ key = (type(item), item)
+ if key not in seen:
+ seen.add(key)
+ out.append(item)
+ return out
+
+
+def literal_choices(annotation: Any) -> list[Any]:
+ """The allowed values when the annotation is nothing but a choice (or ``None``).
+
+ A choice mixed with another type (``int | "auto"``) is spelled in the type instead,
+ so this is empty for it.
+ """
+ values: list[Any] = []
+ for member in _union_members(annotation):
+ if member is _NONE_TYPE:
+ continue
+ found = _choice_values(member)
+ if found is None:
+ return []
+ values.extend(found)
+ return _unique(values)
+
+
+def _value_type(value: Any) -> str:
+ return "null" if value is None else _SCALARS.get(type(value), type(value).__name__)
+
+
+def _format_member(annotation: Any) -> str:
+ if annotation is typing.Any:
+ return "any"
+ origin = typing.get_origin(annotation)
+ container = _container_name(annotation if origin is None else origin)
+ if container is not None:
+ args = [arg for arg in typing.get_args(annotation) if arg is not Ellipsis]
+ inner = ", ".join(format_type(arg) for arg in args)
+ return f"{container}[{inner}]" if inner else container
+ if not _is_class(annotation):
+ return "any"
+ if annotation in _SCALARS:
+ return _SCALARS[annotation]
+ if issubclass(annotation, BaseModel):
+ return "section"
+ if issubclass(annotation, PurePath):
+ return "path"
+ return annotation.__name__
+
+
+def format_type(annotation: Any) -> str:
+ """One spelling per type, whatever the source wrote and whatever Python runs this.
+
+ ``null`` goes last. A pure choice reads as the type of its values (the values are
+ listed as a constraint); a choice mixed with other types is spelled inline.
+ """
+ members = _union_members(annotation)
+ rest = [member for member in members if member is not _NONE_TYPE]
+ pure_choice = bool(rest) and all(_choice_values(member) is not None for member in rest)
+ names: list[str] = []
+ for member in rest:
+ values = _choice_values(member)
+ if values is None:
+ names.append(_format_member(member))
+ elif pure_choice:
+ names.extend(_value_type(value) for value in values)
+ else:
+ names.extend(json.dumps(value, ensure_ascii=False) for value in values)
+ if len(rest) != len(members):
+ names.append("null")
+ return " | ".join(dict.fromkeys(names))
+
+
+# --------------------------------------------------------------------------
+# docs/config-reference.md
+# --------------------------------------------------------------------------
+
+_BOUNDS = (("gt", ">"), ("ge", ">="), ("lt", "<"), ("le", "<="))
+_CONSTRAINT_ATTRS = (
+ "gt",
+ "ge",
+ "lt",
+ "le",
+ "multiple_of",
+ "min_length",
+ "max_length",
+ "pattern",
+ "allow_inf_nan",
+)
+
+
+@dataclass(frozen=True)
+class ConfigRow:
+ """One ``soup.yaml`` key, every cell already Markdown."""
+
+ key: str
+ type: str
+ default: str
+ constraints: str
+ description: str
+
+
+def format_constraints(info: FieldInfo) -> str:
+ """The single-value rules of a field, as one Markdown cell."""
+ found: dict[str, Any] = {}
+ for meta in info.metadata:
+ for attr in _CONSTRAINT_ATTRS:
+ value = getattr(meta, attr, None)
+ if value is not None:
+ found[attr] = value
+ bounds = [_code(f"{sign} {found[attr]!r}") for attr, sign in _BOUNDS if attr in found]
+ parts = [", ".join(bounds)] if bounds else []
+ if "multiple_of" in found:
+ parts.append(f"multiple of {found['multiple_of']!r}")
+ if "min_length" in found:
+ parts.append(f"min length {found['min_length']}")
+ if "max_length" in found:
+ parts.append(f"max length {found['max_length']}")
+ if "pattern" in found:
+ pattern = found["pattern"]
+ parts.append("pattern " + _code(getattr(pattern, "pattern", pattern)))
+ if found.get("allow_inf_nan") is False:
+ parts.append("finite")
+ choices = literal_choices(info.annotation)
+ if choices:
+ parts.append(
+ "one of " + ", ".join(_code(json.dumps(item, ensure_ascii=False)) for item in choices)
+ )
+ return "; ".join(parts)
+
+
+def _config_default(info: FieldInfo) -> str:
+ factory = info.default_factory
+ if factory is not None:
+ if _is_model(factory):
+ return "section defaults"
+ try:
+ value = factory() # type: ignore[call-arg]
+ except Exception:
+ return f"*{RUNTIME_DEFAULT}*"
+ # A factory exists to build a fresh container. A scalar out of one was computed.
+ if not isinstance(value, (list, tuple, dict, set, frozenset)):
+ return f"*{RUNTIME_DEFAULT}*"
+ return _default_cell(format_default(value))
+ if info.is_required():
+ return "**required**"
+ return _default_cell(format_default(info.default))
+
+
+def _nested_models(annotation: Any) -> list[tuple[str, type[BaseModel]]]:
+ """``(path suffix, model)`` for every model a field holds: ``""`` for the field
+ itself, ``"[]"`` for the items of a sequence, ``".*"`` for the values of a mapping."""
+ found: list[tuple[str, type[BaseModel]]] = []
+ for member in _union_members(annotation):
+ if _is_model(member):
+ found.append(("", member))
+ continue
+ container = _container_name(typing.get_origin(member))
+ if container is None:
+ continue
+ args = [arg for arg in typing.get_args(member) if arg is not Ellipsis]
+ if container == "dict":
+ args, suffix = args[1:], ".*"
+ else:
+ suffix = "[]"
+ for arg in args:
+ found.extend((suffix + deeper, model) for deeper, model in _nested_models(arg))
+ return found
+
+
+def _yaml_key(name: str, info: FieldInfo) -> str:
+ for alias in (info.validation_alias, info.alias):
+ if isinstance(alias, str):
+ return alias
+ return name
+
+
+def config_sections(
+ model: type[BaseModel], prefix: str = "", _stack: tuple[type[BaseModel], ...] = ()
+) -> list[tuple[str, list[ConfigRow]]]:
+ """``(YAML path, rows)`` per section: the model's own keys, then every nested model
+ depth-first in field order. A model already being rendered is not entered again."""
+ stack = (*_stack, model)
+ rows: list[ConfigRow] = []
+ nested: list[tuple[str, type[BaseModel]]] = []
+ for name, info in model.model_fields.items():
+ key = _yaml_key(name, info)
+ path = f"{prefix}.{key}" if prefix else key
+ children = [
+ (path + suffix, sub)
+ for suffix, sub in _nested_models(info.annotation)
+ if sub not in stack
+ ]
+ nested.extend(children)
+ description = escape_cell(strip_internal_phase(info.description or ""))
+ links = ", ".join(f"[{_code(child)}](#{github_slug(child)})" for child, _ in children)
+ if links:
+ if description and not description.endswith((".", "!", "?", ":")):
+ description += "."
+ description = f"{description} See {links}.".strip()
+ rows.append(
+ ConfigRow(
+ key=path,
+ type=_code(format_type(info.annotation)),
+ default=_config_default(info),
+ constraints=format_constraints(info),
+ description=description,
+ )
+ )
+ sections = [(prefix, rows)]
+ for child_path, sub in nested:
+ sections.extend(config_sections(sub, child_path, stack))
+ return sections
+
+
+def _load_config_model() -> type[BaseModel]:
+ from soup_cli.config.schema import SoupConfig
+
+ return SoupConfig
+
+
+def render_config_reference(model: type[BaseModel] | None = None) -> str:
+ """The text of ``docs/config-reference.md``."""
+ sections = config_sections(model if model is not None else _load_config_model())
+ lines = [
+ "# Config reference",
+ "",
+ "[← Back to the docs index](README.md)",
+ "",
+ "> **Generated file — do not edit by hand.**",
+ "> It is rendered from `SoupConfig` in `src/soup_cli/config/schema.py`. After adding or",
+ "> removing a field, or changing its type, default or bounds, run",
+ f"> `{_REGENERATE}` and commit the result; the test suite fails",
+ "> until the page matches. Descriptions are refreshed when a release is cut, so between",
+ "> releases the wording here can trail the code.",
+ "",
+ "Every key `soup.yaml` accepts. A key that is not on this page **refuses the load** — see",
+ "[Unknown config keys](backends-and-ops.md#unknown-config-keys) for the error and the",
+ "nearest-name hint. The guides linked from the [docs index](README.md) explain what the",
+ "settings do together; this page is the lookup table.",
+ "",
+ "How to read a table:",
+ "",
+ "- **Key** is the full YAML path: `training.lora.r` is `r:` under `lora:` under",
+ " `training:`.",
+ "- **Type** uses `str`, `int`, `float`, `bool`, `list[...]` and `dict[...]`; `null` means",
+ " the key may be left out or set to `null`; `section` is a nested block with a table of",
+ " its own. A value in quotes (`\"auto\"`) is the one literal accepted next to the type.",
+ "- **Default** is written the way YAML reads it (`null`, `true`, `\"auto\"`, `[\"a\"]`).",
+ " **required** means there is none. *(set at runtime)* marks a default computed on",
+ " the machine, which this page does not print.",
+ "- **Constraints** are the rules on the value itself: bounds, lengths, the allowed",
+ " choices. Rules that span keys (a setting valid for one task or backend only) are",
+ " enforced by the schema's validators and named in the description.",
+ "",
+ "Sections:",
+ "",
+ ]
+ # One line per section and one row per key, never a total: two changes that each
+ # add a different key then merge as text and the merged page is still right.
+ for path, _rows in sections:
+ title = _code(path) if path else "Top-level keys"
+ anchor = github_slug(path) if path else "top-level-keys"
+ lines.append(f"- [{title}](#{anchor})")
+ for path, rows in sections:
+ lines += ["", f"## {_code(path)}" if path else "## Top-level keys", ""]
+ lines += _table_head("Key", "Type", "Default", "Constraints", "Description")
+ lines += [
+ _row([_code(row.key), row.type, row.default, row.constraints, row.description])
+ for row in rows
+ ]
+ return "\n".join(lines) + "\n"
+
+
+# --------------------------------------------------------------------------
+# docs/cli-reference.md
+# --------------------------------------------------------------------------
+
+#: Typer builds these two as flags when it can detect the shell and as options that
+#: take a shell name when it cannot (no ``shellingham``), with different help text.
+_TYPER_COMPLETION_HELP = {
+ "install_completion": "Install shell completion for the current shell.",
+ "show_completion": "Print the shell completion script, to copy or customise it.",
+}
+
+
+@dataclass(frozen=True)
+class CommandEntry:
+ """One visible command and the names that lead to it (``("data", "inspect")``)."""
+
+ path: tuple[str, ...]
+ command: click.Command
+
+
+def _visible_params(command: click.Command) -> list[click.Parameter]:
+ return [param for param in command.params if not getattr(param, "hidden", False)]
+
+
+def iter_commands(root: click.Command) -> list[CommandEntry]:
+ """Every visible command below ``root``: a group before its subcommands, names sorted.
+
+ A hidden group hides everything under it.
+ """
+ entries: list[CommandEntry] = []
+
+ def walk(command: click.Command, path: tuple[str, ...]) -> None:
+ if path:
+ entries.append(CommandEntry(path, command))
+ if isinstance(command, click.Group):
+ for name in sorted(command.commands):
+ sub = command.commands[name]
+ if not getattr(sub, "hidden", False):
+ walk(sub, (*path, name))
+
+ walk(root, ())
+ return entries
+
+
+def _is_typer_completion(param: click.Parameter) -> bool:
+ return param.name in _TYPER_COMPLETION_HELP and not param.expose_value
+
+
+def _range_words(param_type: Any) -> str:
+ low, high = param_type.min, param_type.max
+ if low is not None and high is not None and not (param_type.min_open or param_type.max_open):
+ return f"{low!r} to {high!r}"
+ parts = []
+ if low is not None:
+ parts.append(("above " if param_type.min_open else "at least ") + repr(low))
+ if high is not None:
+ parts.append(("below " if param_type.max_open else "at most ") + repr(high))
+ return ", ".join(parts)
+
+
+def _click_type_name(param_type: click.ParamType) -> str:
+ if isinstance(param_type, click.Choice):
+ values = [str(getattr(choice, "value", choice)) for choice in param_type.choices]
+ return "one of " + ", ".join(_code(value) for value in values)
+ if isinstance(param_type, (click.IntRange, click.FloatRange)):
+ name = "integer" if isinstance(param_type, click.IntRange) else "float"
+ return ", ".join(part for part in (name, _range_words(param_type)) if part)
+ if isinstance(param_type, click.types.IntParamType):
+ return "integer"
+ if isinstance(param_type, click.types.FloatParamType):
+ return "float"
+ if isinstance(param_type, click.types.BoolParamType):
+ return "boolean"
+ if isinstance(param_type, click.Path):
+ return "path"
+ if isinstance(param_type, click.File):
+ return "file"
+ if isinstance(param_type, click.DateTime):
+ return "datetime"
+ return "text"
+
+
+def format_click_type(param: click.Parameter) -> str:
+ """The Type cell of a parameter, read off the Click object (never its ``repr``)."""
+ if _is_typer_completion(param) or getattr(param, "is_flag", False):
+ return "flag"
+ if getattr(param, "count", False):
+ return "counter"
+ parts = [_click_type_name(param.type)]
+ if param.nargs == -1:
+ parts.append("any number")
+ elif param.nargs != 1:
+ parts.append(f"{param.nargs} values")
+ if getattr(param, "multiple", False):
+ parts.append("repeatable")
+ return ", ".join(parts)
+
+
+def format_click_default(param: click.Parameter) -> str:
+ """The Default cell: the value as typed on the command line, ``on`` / ``off`` for a
+ flag, empty when there is none, the placeholder when the machine computed it."""
+ value = param.default
+ if _is_typer_completion(param) or value is None:
+ return ""
+ if type(value).__module__.partition(".")[0] == "click":
+ return "" # Click's own "no default" sentinel
+ if callable(value) and not isinstance(value, enum.Enum):
+ return f"*{RUNTIME_DEFAULT}*"
+ if getattr(param, "is_flag", False) and isinstance(value, bool):
+ return "on" if value else "off"
+ if isinstance(value, (list, tuple, set, frozenset, dict)) and not value:
+ return ""
+ plain = _plain_literal(value)
+ if plain is _NOT_LITERAL:
+ return f"*{RUNTIME_DEFAULT}*"
+ if isinstance(plain, str):
+ return _code(plain) if plain else _code('""')
+ return _code(json.dumps(plain, ensure_ascii=False))
+
+
+def _param_name(param: click.Parameter) -> str:
+ if isinstance(param, click.Option):
+ names = ", ".join(_code(opt) for opt in param.opts)
+ if param.secondary_opts:
+ names += " / " + ", ".join(_code(opt) for opt in param.secondary_opts)
+ return names
+ return _code(_metavar(param))
+
+
+def _argument_name(param: click.Parameter) -> str:
+ return getattr(param, "metavar", None) or (param.name or "").upper()
+
+
+def _metavar(param: click.Parameter) -> str:
+ name = _argument_name(param)
+ return f"{name}..." if param.nargs == -1 else name
+
+
+def _declared_argument_help(command: click.Command) -> dict[str, str]:
+ """``{argument name: help}`` as declared to Typer.
+
+ Click 8.5 gave ``Argument`` a ``help`` of its own and resets the attribute Typer
+ 0.20 has already set, so ``param.help`` is ``None`` there and the declared string
+ on an older Click. The declaration reads the same on both.
+ """
+ if command.callback is None:
+ return {}
+ try:
+ from typer.models import ArgumentInfo
+ from typer.utils import get_params_from_function
+
+ declared = get_params_from_function(command.callback)
+ except Exception:
+ return {}
+ return {
+ name: meta.default.help
+ for name, meta in declared.items()
+ if isinstance(meta.default, ArgumentInfo) and meta.default.help
+ }
+
+
+def _param_help(param: click.Parameter, declared: dict[str, str]) -> str:
+ if _is_typer_completion(param):
+ return _TYPER_COMPLETION_HELP[param.name or ""]
+ raw = getattr(param, "help", None) or declared.get(param.name or "") or ""
+ text = escape_cell(strip_internal_phase(strip_rich_markup(raw)))
+ envvar = getattr(param, "envvar", None)
+ if envvar:
+ names = [envvar] if isinstance(envvar, str) else list(envvar)
+ if text and not text.endswith((".", "!", "?", ":")):
+ text += "."
+ text = f"{text} Env: {', '.join(_code(name) for name in names)}.".strip()
+ return text
+
+
+def _param_rows(command: click.Command) -> list[str]:
+ declared = _declared_argument_help(command)
+ return [
+ _row(
+ [
+ _param_name(param),
+ format_click_type(param),
+ format_click_default(param),
+ "yes" if param.required else "",
+ _param_help(param, declared),
+ ]
+ )
+ for param in _visible_params(command)
+ ]
+
+
+def _usage(path: tuple[str, ...], command: click.Command) -> str:
+ params = _visible_params(command)
+ parts = ["soup", *path]
+ if any(isinstance(param, click.Option) for param in params):
+ parts.append("[OPTIONS]")
+ if isinstance(command, click.Group):
+ # `<command>`, not Click's `COMMAND`: the docs guard that resolves every
+ # documented invocation (#1465) reads a bare capitalised word as a subcommand.
+ optional = bool(path) and command.invoke_without_command
+ parts.append("[<command>] [ARGS]..." if optional else "<command> [ARGS]...")
+ for param in params:
+ if isinstance(param, click.Argument):
+ name = _argument_name(param)
+ name = name if param.required else f"[{name}]"
+ parts.append(f"{name}..." if param.nargs == -1 else name)
+ passes_extra = (command.context_settings or {}).get("allow_extra_args")
+ variadic = any(isinstance(param, click.Argument) and param.nargs == -1 for param in params)
+ if passes_extra and not variadic and not isinstance(command, click.Group):
+ parts.append("[ARGS]...")
+ return " ".join(parts)
+
+
+def _command_summary(command: click.Command) -> str:
+ return _escape_paragraph(strip_internal_phase(strip_rich_markup(summary_line(command.help))))
+
+
+def _command_section(entry: CommandEntry, anchors: dict[tuple[str, ...], str]) -> list[str]:
+ command = entry.command
+ level = "#" * min(len(entry.path) + 1, 6)
+ blocks = [[f"{level} {_code('soup ' + ' '.join(entry.path))}"]]
+ summary = _command_summary(command)
+ if summary:
+ blocks.append([summary])
+ blocks.append([f"Usage: {_code(_usage(entry.path, command))}"])
+ if isinstance(command, click.Group):
+ subs = [
+ f"- [{_code(name)}](#{anchors[(*entry.path, name)]})"
+ for name in sorted(command.commands)
+ if (*entry.path, name) in anchors
+ ]
+ if subs: # one line per subcommand, so adding one never rewrites a shared line
+ blocks.append(["Subcommands:", "", *subs])
+ rows = _param_rows(command)
+ if rows:
+ blocks.append([*_table_head("Name", "Type", "Default", "Required", "Help"), *rows])
+ elif not isinstance(command, click.Group):
+ blocks.append(["Takes no options or arguments."])
+ return [line for block in blocks for line in ("", *block)]
+
+
+def _load_cli_root() -> click.Command:
+ import typer
+
+ from soup_cli.cli import app
+
+ return typer.main.get_command(app)
+
+
+def render_cli_reference(root: click.Command | None = None) -> str:
+ """The text of ``docs/cli-reference.md``."""
+ root = root if root is not None else _load_cli_root()
+ entries = iter_commands(root)
+ slugger = _Slugger()
+ for fixed in ("CLI reference", "Global options", "Commands"):
+ slugger.take(fixed)
+ anchors = {entry.path: slugger.take("soup " + " ".join(entry.path)) for entry in entries}
+
+ # No totals anywhere on the page: every line below the header belongs to one
+ # command or one parameter, so two changes that each add a different option merge
+ # as text and the merged page is still right.
+ lines = [
+ "# CLI reference",
+ "",
+ "[← Back to the docs index](README.md)",
+ "",
+ "> **Generated file — do not edit by hand.**",
+ "> It is rendered from the live Typer command tree (`soup_cli.cli:app`). After adding or",
+ "> removing a command, an option or an argument, or changing its type, its default or",
+ f"> whether it is required, run `{_REGENERATE}` and commit the",
+ "> result; the test suite fails until the page matches. Help text is refreshed when a",
+ "> release is cut, so between releases the wording here can trail the code.",
+ "",
+ "Every `soup` command with every option and argument. For a one-line-per-task listing",
+ "see the [Command reference](commands.md); for the keys of `soup.yaml` see the",
+ "[Config reference](config-reference.md).",
+ "",
+ "How to read a table:",
+ "",
+ "- **Name** is an option with its short form, or an argument in capitals (`PATH`;",
+ " `PATH...` takes any number of values). `--flag` / `--no-flag` is one switch with",
+ " both spellings.",
+ "- **Type**: a `flag` takes no value; `text`, `integer`, `float` and `path` take one;",
+ " a `repeatable` option may be given more than once.",
+ "- **Default** is the value used when the option is left out (`on` / `off` for a flag);",
+ " an empty cell means there is none. *(set at runtime)* marks a default computed on",
+ " the machine, which this page does not print.",
+ "- **Required** says `yes` when the command refuses to run without it.",
+ "",
+ "`--help` works on every command and is not listed. Global options go before the",
+ "command name: `soup --verbose train --config soup.yaml`.",
+ "",
+ "## Global options",
+ "",
+ f"Usage: {_code(_usage((), root))}",
+ "",
+ *_table_head("Name", "Type", "Default", "Required", "Help"),
+ *_param_rows(root),
+ "",
+ "## Commands",
+ "",
+ *_table_head("Command", "Summary"),
+ ]
+ for entry in entries:
+ if len(entry.path) == 1:
+ link = f"[{_code('soup ' + entry.path[0])}](#{anchors[entry.path]})"
+ lines.append(_row([link, _command_summary(entry.command)]))
+ for entry in entries:
+ lines += _command_section(entry, anchors)
+ return "\n".join(lines) + "\n"
+
+
+# --------------------------------------------------------------------------
+# Check / write
+# --------------------------------------------------------------------------
+
+
+def render_pages() -> dict[str, str]:
+ """``{repo-relative path: text}`` for both pages."""
+ return {
+ CONFIG_PAGE: render_config_reference(_load_config_model()),
+ CLI_PAGE: render_cli_reference(_load_cli_root()),
+ }
+
+
+def _committed(root: Path, rel: str) -> str | None:
+ """The page on disk with LF newlines, or ``None`` when there is no such file."""
+ path = root / rel
+ if not path.is_file():
+ return None
+ return path.read_bytes().decode("utf-8").replace("\r\n", "\n")
+
+
+def stale_pages(root: Path, pages: dict[str, str]) -> list[str]:
+ """The pages under ``root`` that are missing or differ from ``pages``."""
+ return [rel for rel, text in pages.items() if _committed(root, rel) != text]
+
+
+def _first_difference(committed: str, fresh: str) -> list[str]:
+ old, new = committed.split("\n"), fresh.split("\n")
+ index = next(
+ (i for i, (left, right) in enumerate(zip(old, new)) if left != right),
+ min(len(old), len(new)),
+ )
+
+ def shown(lines: list[str]) -> str:
+ text = lines[index] if index < len(lines) else "<end of file>"
+ return text[:160].encode("ascii", "backslashreplace").decode("ascii")
+
+ return [
+ f" first difference at line {index + 1}:",
+ f" committed: {shown(old)}",
+ f" rendered: {shown(new)}",
+ ]
+
+
+class PageFormatError(ValueError):
+ """A table line on a page that is not a row this generator writes."""
+
+
+#: GitHub ends a cell at a ``|`` unless a backslash stands right before it, whatever
+#: comes before that backslash: ``a\|b`` and ``a\\|b`` are both ONE cell (rendered
+#: ``a|b`` and ``a\|b``). Read off GitHub's own renderer, not assumed.
+_CELL_END = re.compile(r"(?<!\\)\|")
+_HEADER_CELLS = frozenset({"Key", "Name", "Command"})
+
+
+def split_row(line: str) -> list[str]:
+ """The cells of one Markdown table row, split where GitHub splits it."""
+ return [cell.strip() for cell in _CELL_END.split(line.strip())[1:-1]]
+
+
+def _data_cells(line: str, lineno: int, columns: int) -> list[str] | None:
+ """The cells of a body row; ``None`` for a line that is no table line, or is a header
+ or a rule. A table line that is none of those raises: skipping a row that does not
+ parse would take its key out of the comparison without a word."""
+ if not line.startswith("|"):
+ return None
+ cells = split_row(line)
+ if set(line) <= set("|-: ") or (cells and cells[0] in _HEADER_CELLS):
+ return None
+ if len(cells) != columns or not cells[0].startswith("`"):
+ raise PageFormatError(
+ f"line {lineno} is not a {columns}-column row of this page: {line[:70]}"
+ )
+ return cells
+
+
+def parse_config_page(text: str) -> dict[str, dict[str, str]]:
+ """``{key: {"type": ..., "default": ..., "constraints": ...}}``, read back from the
+ tables of a config page. The description column is left out on purpose."""
+ keys: dict[str, dict[str, str]] = {}
+ for lineno, line in enumerate(text.split("\n"), start=1):
+ cells = _data_cells(line, lineno, 5)
+ if cells is not None:
+ keys[cells[0].replace("`", "")] = {
+ "type": cells[1],
+ "default": cells[2],
+ "constraints": cells[3],
+ }
+ return keys
+
+
+def parse_cli_page(text: str) -> dict[str, dict[str, dict[str, str]]]:
+ """``{command: {parameter names: {"type": ..., "default": ..., "required": ...}}}``,
+ read back from a CLI page; the global options are under ``"soup"``. Help text, the
+ usage line and the command summary are left out on purpose."""
+ commands: dict[str, dict[str, dict[str, str]]] = {}
+ current: dict[str, dict[str, str]] | None = None
+ for lineno, line in enumerate(text.split("\n"), start=1):
+ if line.startswith("#"):
+ title = line.lstrip("#").strip().replace("`", "")
+ if title == "Global options":
+ title = "soup"
+ is_command = title == "soup" or title.startswith("soup ")
+ current = commands.setdefault(title, {}) if is_command else None
+ continue
+ if current is None:
+ continue
+ cells = _data_cells(line, lineno, 5)
+ if cells is not None:
+ current[cells[0].replace("`", "")] = {
+ "type": cells[1],
+ "default": cells[2],
+ "required": cells[3],
+ }
+ return commands
+
+
+def _shown(cell: str) -> str:
+ return cell.replace("\\|", "|") or "(empty)"
+
+
+def _stated(cells: dict[str, str], columns: Sequence[str] | None = None) -> str:
+ chosen = cells if columns is None else {column: cells[column] for column in columns}
+ return ", ".join(f"{column} {_shown(cell)}" for column, cell in chosen.items())
+
+
+def _item_drift(
+ label: str, old: dict[str, str] | None, new: dict[str, str] | None, absent: str
+) -> list[str]:
+ """One line for a key or a parameter whose row differs, each side named: what the
+ committed page states, then what the code states now."""
+ if new is None:
+ assert old is not None
+ return [f"{label}: committed page: {_stated(old)} | code now: {absent}"]
+ if old is None:
+ return [f"{label}: committed page: (not listed) | code now: {_stated(new)}"]
+ changed = [column for column in new if old[column] != new[column]]
+ if not changed:
+ return []
+ return [
+ f"{label}: committed page: {_stated(old, changed)} | code now: {_stated(new, changed)}"
+ ]
+
+
+def config_drift(
+ old: dict[str, dict[str, str]], new: dict[str, dict[str, str]]
+) -> list[str]:
+ """One line per key the committed config page states differently from the schema."""
+ lines: list[str] = []
+ for key in dict.fromkeys([*new, *old]):
+ lines += _item_drift(key, old.get(key), new.get(key), "(no such field)")
+ return lines
+
+
+def cli_drift(
+ old: dict[str, dict[str, dict[str, str]]], new: dict[str, dict[str, dict[str, str]]]
+) -> list[str]:
+ """One line per command or parameter the committed CLI page states differently."""
+ lines: list[str] = []
+ for command in dict.fromkeys([*new, *old]):
+ if command not in old:
+ lines.append(f"{command}: committed page: (no section) | code now: a command")
+ elif command not in new:
+ lines.append(f"{command}: committed page: a section | code now: (no such command)")
+ else:
+ was, now = old[command], new[command]
+ for name in dict.fromkeys([*now, *was]):
+ lines += _item_drift(
+ f"{command} {name}", was.get(name), now.get(name), "(no such parameter)"
+ )
+ return lines
+
+
+def _page_drift(
+ parse: Callable[[str], Any],
+ compare: Callable[[Any, Any], list[str]],
+ committed: str,
+ fresh: str,
+) -> list[str]:
+ new = parse(fresh) # a render that cannot be read back is a bug in here: let it raise
+ try:
+ old = parse(committed)
+ except PageFormatError as error:
+ return [f"the committed page cannot be read back: {error}"]
+ return compare(old, new)
+
+
+def structure_drift(root: Path, pages: dict[str, str]) -> dict[str, list[str]]:
+ """``{page: differences}`` for every page under ``root`` whose tables no longer state
+ what the code does. Wording is not looked at. A missing page is one difference, and
+ so is a committed page with a table line that cannot be read back."""
+ found: dict[str, list[str]] = {}
+ for rel, fresh in pages.items():
+ committed = _committed(root, rel)
+ if committed is None:
+ found[rel] = ["the page is missing"]
+ elif rel == CONFIG_PAGE:
+ found[rel] = _page_drift(parse_config_page, config_drift, committed, fresh)
+ else:
+ found[rel] = _page_drift(parse_cli_page, cli_drift, committed, fresh)
+ return {rel: lines for rel, lines in found.items() if lines}
+
+
+def _report_structure(drift: dict[str, list[str]]) -> None:
+ for rel, lines in drift.items():
+ subject = "the schema" if rel == CONFIG_PAGE else "the CLI"
+ count = f"{len(lines)} difference{'s' if len(lines) != 1 else ''}"
+ print(f"{rel} no longer matches {subject} ({count}):")
+ for line in lines[:_MAX_SHOWN]:
+ print(" " + line.encode("ascii", "backslashreplace").decode("ascii"))
+ if len(lines) > _MAX_SHOWN:
+ print(f" ... and {len(lines) - _MAX_SHOWN} more")
+ print(f"Run `{_REGENERATE}` and commit the result.")
+
+
+def _ensure_checkout_on_path() -> None:
+ """Import ``soup_cli`` from this checkout when the script is run by path."""
+ src = str(_SCRIPT_REPO_ROOT / "src")
+ if "soup_cli" not in sys.modules and src not in sys.path:
+ sys.path.insert(0, src)
+
+
+def _foreign_install() -> str | None:
+ """Where ``soup_cli`` was imported from, when that is not this checkout's ``src``."""
+ import soup_cli
+
+ src = os.path.normcase(os.path.realpath(_SCRIPT_REPO_ROOT / "src"))
+ origin = os.path.normcase(os.path.realpath(soup_cli.__file__))
+ try:
+ inside = os.path.commonpath([src, origin]) == src
+ except ValueError: # different drives
+ inside = False
+ return None if inside else soup_cli.__file__
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ """Rewrite the pages, or with one of the two checks report and exit 1."""
+ parser = argparse.ArgumentParser(
+ description="Render docs/config-reference.md and docs/cli-reference.md from the code."
+ )
+ mode = parser.add_mutually_exclusive_group()
+ mode.add_argument(
+ "--check-structure",
+ action="store_true",
+ help=(
+ "write nothing; exit 1 and name each key, command or parameter the pages state "
+ "differently from the code (wording is not compared)"
+ ),
+ )
+ mode.add_argument(
+ "--check",
+ action="store_true",
+ help="write nothing; exit 1 and name each page whose text differs from a fresh render",
+ )
+ args = parser.parse_args(argv)
+
+ _ensure_checkout_on_path()
+ foreign = _foreign_install()
+ if foreign is not None:
+ print(f"soup_cli is imported from {foreign}, not from {_SCRIPT_REPO_ROOT / 'src'}.")
+ print("The pages would describe that copy. Install this checkout (pip install -e .)")
+ print("or put its src directory first on PYTHONPATH, then run this again.")
+ return 2
+
+ pages = render_pages()
+ if args.check_structure:
+ drift = structure_drift(_REPO_ROOT, pages)
+ if drift:
+ _report_structure(drift)
+ return 1
+ print(f"{CONFIG_PAGE} and {CLI_PAGE} state what the code does (wording not compared).")
+ return 0
+ stale = stale_pages(_REPO_ROOT, pages)
+ if not stale:
+ state = "up to date" if args.check else "up to date; nothing to do"
+ print(f"{CONFIG_PAGE} and {CLI_PAGE} are {state}.")
+ return 0
+ if args.check:
+ for rel in stale:
+ committed = _committed(_REPO_ROOT, rel)
+ if committed is None:
+ print(f"{rel} is missing.")
+ continue
+ print(f"{rel} is stale.")
+ for line in _first_difference(committed, pages[rel]):
+ print(line)
+ print(f"Run `{_REGENERATE}` and commit the result.")
+ return 1
+ for rel in stale:
+ target = _REPO_ROOT / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(pages[rel].encode("utf-8"))
+ print(f"wrote {rel}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/soup_cli/commands/_eval_v0550.py b/src/soup_cli/commands/_eval_v0550.py
index 9486733f..993492f3 100644
--- a/src/soup_cli/commands/_eval_v0550.py
+++ b/src/soup_cli/commands/_eval_v0550.py
@@ -240,7 +240,7 @@ def register(app: typer.Typer, console: Console) -> None:
@app.command(name="against", cls=GateCommand)
def against_cmd(
baseline_run_id: str = typer.Argument(
- ..., help="Baseline run id (from `soup runs list`).",
+ ..., help="Baseline run id (from `soup runs`).",
),
candidate_run_id: str = typer.Option(
..., "--candidate",
diff --git a/tests/test_gen_reference_docs.py b/tests/test_gen_reference_docs.py
new file mode 100644
index 00000000..5a0abd25
--- /dev/null
+++ b/tests/test_gen_reference_docs.py
@@ -0,0 +1,1757 @@
+"""``scripts/gen_reference_docs.py``: the generated config and CLI reference pages.
+
+Four things are held here.
+
+1. **The committed pages state what the code does** (``--check-structure``): the same
+ keys with the same type, default and constraints, the same commands with the same
+ parameters. Wording is NOT compared, on purpose: a pull request that rewords a help
+ string or a description must not go red here. The byte-exact check (``--check``) is
+ a release-time one and runs only with ``SOUP_DOCS_EXACT=1``.
+2. **The render is the same everywhere.** CI runs this on Python 3.10 and 3.12, on
+ Linux, Windows and macOS, so every helper that keeps the output identical across
+ them is pinned on its own: the type spelling, the default and constraint rendering,
+ the cell escaping, the Rich-markup stripping.
+3. **Coverage is complete.** Every ``SoupConfig`` key is exactly one row, every
+ registered command one section, every visible option and argument one row. The
+ schema and the Click tree are walked HERE, independently of the generator's own
+ walkers, so a walker that skips something cannot agree with itself.
+4. **Rendering is import-light.** ``conftest.py`` has already imported torch into the
+ pytest process, so that part runs in a fresh interpreter, like
+ ``tests/test_cli_startup_is_light.py``.
+
+Nothing below pins a value that lives in the schema or in a help string (a default, a
+bound, a sentence). Those change in ordinary pull requests, and this file must not be
+one more thing to edit then: shapes are pinned on the toy model and the toy apps, and
+what is asserted about the real pages is derived from the real schema and Click tree.
+"""
+
+from __future__ import annotations
+
+import collections.abc
+import difflib
+import enum
+import json
+import os
+import re
+import subprocess
+import sys
+import tempfile
+import typing
+from collections import Counter
+from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath
+from typing import Annotated, Any, Dict, List, Literal, Optional, Union
+
+import click
+import pytest
+import typer
+from pydantic import BaseModel, Field, create_model
+
+from scripts import gen_reference_docs as gen
+
+_ROOT = Path(__file__).resolve().parents[1]
+_HEAVY = ("torch", "transformers", "accelerate", "peft", "trl", "datasets", "bitsandbytes")
+_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
+#: the same shape ``tests/test_issue823_stale_feature_descriptions.py`` bans from CLI help
+_INTERNAL_PHASE = re.compile(r"\bv\d+(?:\.\d+){1,2}\s+part\s+[a-z]\b", re.IGNORECASE)
+_CONFIG_ROW_KEY = re.compile(r"^\| `([^`]+)` \|", re.MULTILINE)
+_COMMAND_HEADING = re.compile(r"^#{2,6} `(soup [^`]+)`$")
+_UNESCAPED_PIPE = re.compile(r"(?<!\\)\|")
+
+
+def _plain(text: str) -> str:
+ """ANSI-strip + whitespace-collapse, as in ``tests/test_auto_tuning.py``."""
+ return " ".join(_ANSI_RE.sub("", text).split())
+
+
+def _cells(row: str) -> list[str]:
+ """The cells of one Markdown table row (an escaped ``\\|`` stays inside its cell)."""
+ return [cell.strip() for cell in _UNESCAPED_PIPE.split(row.strip())[1:-1]]
+
+
+def _rows(lines: list[str]) -> list[list[str]]:
+ """Body rows of the tables in ``lines``: header and separator rows dropped."""
+ out = []
+ for index, line in enumerate(lines):
+ if not line.startswith("|") or set(line) <= set("|- "):
+ continue
+ if index + 1 < len(lines) and set(lines[index + 1]) <= set("|- ") and lines[index + 1]:
+ continue # the header row sits right above its separator
+ out.append(_cells(line))
+ return out
+
+
[email protected](scope="module")
+def pages() -> dict[str, str]:
+ return gen.render_pages()
+
+
[email protected](scope="module")
+def config_page(pages: dict[str, str]) -> str:
+ return pages[gen.CONFIG_PAGE]
+
+
[email protected](scope="module")
+def cli_page(pages: dict[str, str]) -> str:
+ return pages[gen.CLI_PAGE]
+
+
+def _mirror(tmp_path: Path, rendered: dict[str, str]) -> None:
+ """Write ``rendered`` under ``tmp_path`` the way the generator would."""
+ (tmp_path / "docs").mkdir(exist_ok=True)
+ for rel, text in rendered.items():
+ (tmp_path / rel).write_bytes(text.encode("utf-8"))
+
+
+# --------------------------------------------------------------------------
+# 1. the committed pages: structure always, bytes at release
+# --------------------------------------------------------------------------
+
+_EXACT_REASON = (
+ "byte-exact freshness is a release-time check: maintainers set SOUP_DOCS_EXACT=1 when "
+ "they regenerate the reference pages for a release. Between releases only the structure "
+ "is held (test_the_committed_pages_state_what_the_code_does), so that rewording a help "
+ "string does not fail a pull request."
+)
+
+
+def test_the_committed_pages_state_what_the_code_does(capsys: pytest.CaptureFixture[str]) -> None:
+ """The default freshness test. If it fails, the message names the keys or parameters
+ and the command to run; a wording-only change never fails it."""
+ code = gen.main(["--check-structure"])
+ report = capsys.readouterr().out
+ assert code == 0, "\n" + report # one offending key per line: do not collapse them
+ assert "state what the code does" in _plain(report)
+
+
[email protected](os.environ.get("SOUP_DOCS_EXACT") != "1", reason=_EXACT_REASON)
+def test_the_committed_pages_are_byte_exact(capsys: pytest.CaptureFixture[str]) -> None:
+ code = gen.main(["--check"])
+ out = _plain(capsys.readouterr().out)
+ assert code == 0, out
+ assert "up to date" in out, out
+
+
+def test_the_exact_test_is_skipped_with_a_reason_a_contributor_can_act_on() -> None:
+ marks = [mark for mark in test_the_committed_pages_are_byte_exact.pytestmark]
+ assert [mark.name for mark in marks] == ["skipif"]
+ assert "SOUP_DOCS_EXACT=1" in marks[0].kwargs["reason"]
+ assert "release" in marks[0].kwargs["reason"]
+
+
+def test_the_two_checks_cannot_be_asked_for_together(capsys: pytest.CaptureFixture[str]) -> None:
+ with pytest.raises(SystemExit) as stopped:
+ gen.main(["--check", "--check-structure"])
+ assert stopped.value.code == 2
+ assert "not allowed with" in _plain(capsys.readouterr().err)
+
+
+def test_the_generator_renders_exactly_the_two_pages(pages: dict[str, str]) -> None:
+ assert sorted(pages) == ["docs/cli-reference.md", "docs/config-reference.md"]
+ assert {gen.CONFIG_PAGE, gen.CLI_PAGE} == set(pages)
+
+
+def test_the_docs_index_links_both_pages() -> None:
+ """Nothing else links them: a page missing from the index cannot be found."""
+ index = (_ROOT / "docs" / "README.md").read_text(encoding="utf-8")
+ rows = [line for line in index.splitlines() if line.startswith("| [")]
+ assert sum("](config-reference.md)" in row for row in rows) == 1, rows
+ assert sum("](cli-reference.md)" in row for row in rows) == 1, rows
+
+
+def test_check_names_only_the_page_that_lost_a_row(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ pages: dict[str, str],
+) -> None:
+ _mirror(tmp_path, pages)
+ monkeypatch.setattr(gen, "_REPO_ROOT", tmp_path)
+ assert gen.main(["--check"]) == 0, capsys.readouterr().out
+
+ page = tmp_path / gen.CONFIG_PAGE
+ lines = page.read_bytes().decode("utf-8").splitlines(keepends=True)
+ victim = next(i for i, line in enumerate(lines) if line.startswith("| `"))
+ key = _cells(lines[victim])[0].strip("`")
+ del lines[victim]
+ page.write_bytes("".join(lines).encode("utf-8"))
+ capsys.readouterr()
+
+ assert gen.main(["--check"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/config-reference.md is stale" in out, out
+ assert "docs/cli-reference.md" not in out, out
+ assert out.endswith("Run `python scripts/gen_reference_docs.py` and commit the result."), out
+ assert f"first difference at line {victim + 1}" in out, out
+
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert f"{key}: committed page: (not listed) | code now: type " in out, out
+ assert "docs/cli-reference.md" not in out, out
+
+
+def test_check_fails_when_the_schema_gains_a_field(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ pages: dict[str, str],
+) -> None:
+ from soup_cli.config.schema import SoupConfig
+
+ class Grown(SoupConfig):
+ brand_new_knob: int = Field(default=7, ge=1, le=9, description="Not on the page yet.")
+
+ _mirror(tmp_path, pages)
+ monkeypatch.setattr(gen, "_REPO_ROOT", tmp_path)
+ monkeypatch.setattr(gen, "_load_config_model", lambda: Grown)
+
+ assert gen.main(["--check"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/config-reference.md is stale" in out, out
+ assert "docs/cli-reference.md" not in out, out
+
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/config-reference.md no longer matches the schema (1 difference)" in out, out
+ assert (
+ "brand_new_knob: committed page: (not listed) | code now: type `int`, default `7`" in out
+ ), out
+ assert "docs/cli-reference.md" not in out, out
+
+
+def test_check_fails_when_a_command_gains_an_option(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ pages: dict[str, str],
+) -> None:
+ root = _live_root()
+ title, command = next(
+ (title, cmd)
+ for title, cmd in _command_tree(root).items()
+ if not isinstance(cmd, click.Group) and _visible(cmd)
+ )
+ command.params.append(
+ click.Option(["--brand-new-flag"], is_flag=True, default=False, help="Not yet.")
+ )
+ _mirror(tmp_path, pages)
+ monkeypatch.setattr(gen, "_REPO_ROOT", tmp_path)
+ monkeypatch.setattr(gen, "_load_cli_root", lambda: root)
+
+ assert gen.main(["--check"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/cli-reference.md is stale" in out, out
+ assert "docs/config-reference.md" not in out, out
+
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/cli-reference.md no longer matches the CLI (1 difference)" in out, out
+ listed = f"{title} --brand-new-flag: committed page: (not listed) | code now: type flag"
+ assert listed in out, out
+ assert "docs/config-reference.md" not in out, out
+
+
+def test_check_reports_a_page_that_does_not_exist(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ monkeypatch.setattr(gen, "_REPO_ROOT", tmp_path)
+
+ assert gen.main(["--check"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/config-reference.md is missing" in out, out
+ assert "docs/cli-reference.md is missing" in out, out
+
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/config-reference.md no longer matches the schema (1 difference)" in out, out
+ assert "docs/cli-reference.md no longer matches the CLI (1 difference)" in out, out
+ assert out.count("the page is missing") == 2, out
+ assert not (tmp_path / "docs").exists(), "a check must not write anything"
+
+
+def test_writing_produces_lf_utf8_pages_that_then_pass_the_check(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ (tmp_path / "docs").mkdir()
+ monkeypatch.setattr(gen, "_REPO_ROOT", tmp_path)
+
+ assert gen.main([]) == 0
+ first = _plain(capsys.readouterr().out)
+ assert "wrote docs/config-reference.md" in first, first
+ assert "wrote docs/cli-reference.md" in first, first
+ for rel in (gen.CONFIG_PAGE, gen.CLI_PAGE):
+ raw = (tmp_path / rel).read_bytes()
+ assert b"\r" not in raw, rel
+ assert raw.endswith(b"\n") and not raw.endswith(b"\n\n"), rel
+ assert not raw.startswith(b"\xef\xbb\xbf"), f"{rel} carries a BOM"
+ raw.decode("utf-8")
+
+ assert gen.main(["--check"]) == 0
+ capsys.readouterr()
+ assert gen.main([]) == 0
+ assert "nothing to do" in _plain(capsys.readouterr().out)
+
+
+def test_check_reads_a_crlf_checkout_as_the_same_page(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, pages: dict[str, str]
+) -> None:
+ """``core.autocrlf=true`` (the Windows runners' default) checks the pages out with
+ CRLF; the committed blob is still the LF text the generator renders."""
+ (tmp_path / "docs").mkdir()
+ for rel, text in pages.items():
+ (tmp_path / rel).write_bytes(text.replace("\n", "\r\n").encode("utf-8"))
+ monkeypatch.setattr(gen, "_REPO_ROOT", tmp_path)
+
+ assert gen.stale_pages(tmp_path, pages) == []
+ assert gen.structure_drift(tmp_path, pages) == {}
+ assert gen.main(["--check"]) == 0
+ assert gen.main(["--check-structure"]) == 0
+
+
[email protected]("mode", ["--check", "--check-structure"])
+def test_a_shadowing_install_is_refused_by_name(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], mode: str
+) -> None:
+ """A same-version copy of ``soup_cli`` in site-packages shadows the working tree;
+ pages rendered from it would describe other code and still look plausible."""
+ import soup_cli
+
+ elsewhere = tmp_path / "site-packages" / "soup_cli" / "__init__.py"
+ monkeypatch.setattr(soup_cli, "__file__", str(elsewhere))
+
+ assert gen.main([mode]) == 2
+ out = _plain(capsys.readouterr().out)
+ assert "soup_cli is imported from" in out, out
+ assert "site-packages" in out, out
+
+
+# --------------------------------------------------------------------------
+# 2a. config page coverage
+# --------------------------------------------------------------------------
+
+
+def _is_model(annotation: Any) -> bool:
+ return (
+ typing.get_origin(annotation) is None
+ and isinstance(annotation, type)
+ and issubclass(annotation, BaseModel)
+ )
+
+
+def _schema_fields(model: type[BaseModel], prefix: str = "") -> list[tuple[str, Any, bool]]:
+ """``(path, FieldInfo, is a nested model)`` for every field, walked here on purpose."""
+ fields: list[tuple[str, Any, bool]] = []
+ for name, info in model.model_fields.items():
+ path = f"{prefix}{name}"
+ nested = [m for m in (info.annotation, *typing.get_args(info.annotation)) if _is_model(m)]
+ fields.append((path, info, bool(nested)))
+ for member in nested:
+ fields.extend(_schema_fields(member, f"{path}."))
+ return fields
+
+
+def _schema_paths(model: type[BaseModel]) -> tuple[list[str], list[str]]:
+ """(every field path, every path that is a nested model)."""
+ fields = _schema_fields(model)
+ return [path for path, _, _ in fields], [path for path, _, nested in fields if nested]
+
+
+def test_every_config_field_is_exactly_one_row(config_page: str) -> None:
+ from soup_cli.config.schema import SoupConfig
+
+ paths, sections = _schema_paths(SoupConfig)
+ assert len(paths) >= 300, len(paths)
+ assert "training.lora" in sections, sections
+
+ rendered = Counter(_CONFIG_ROW_KEY.findall(config_page))
+ assert set(rendered) == set(paths), (
+ sorted(set(paths) - set(rendered)),
+ sorted(set(rendered) - set(paths)),
+ )
+ assert [key for key, count in rendered.items() if count != 1] == []
+
+
+def test_every_nested_model_is_a_section_named_by_its_yaml_path(config_page: str) -> None:
+ from soup_cli.config.schema import SoupConfig
+
+ _, sections = _schema_paths(SoupConfig)
+ headings = [line for line in config_page.splitlines() if line.startswith("## ")]
+ assert headings == ["## Top-level keys", *(f"## `{path}`" for path in sections)]
+ listed = re.findall(r"^- \[`?([^`\]]+)`?\]\(#", config_page, re.MULTILINE)
+ assert listed == ["Top-level keys", *sections], "one line per section in the header list"
+
+
+def test_every_row_states_its_own_fields_default_and_bounds(config_page: str) -> None:
+ """Every scalar default and every bound of the real schema, recomputed here from the
+ ``FieldInfo`` with ``json.dumps`` / ``repr`` rather than the generator's formatters.
+ Derived, not pinned: changing a default in the schema never needs an edit here."""
+ from soup_cli.config.schema import SoupConfig
+
+ stated = gen.parse_config_page(config_page)
+ scalars = bounds = required = 0
+ for path, info, nested in _schema_fields(SoupConfig):
+ cells = stated[path]
+ if info.is_required():
+ required += 1
+ assert cells["default"] == "**required**", path
+ elif info.default_factory is None and not nested and cells["default"].startswith("`"):
+ scalars += 1 # a code cell: "(set at runtime)", were one ever needed, is not
+ literal = json.dumps(info.default, ensure_ascii=False)
+ assert cells["default"].replace("\\|", "|") == f"`{literal}`", path
+ for meta in info.metadata:
+ for attr, sign in (("gt", ">"), ("ge", ">="), ("lt", "<"), ("le", "<=")):
+ bound = getattr(meta, attr, None)
+ if bound is not None:
+ bounds += 1
+ assert f"`{sign} {bound!r}`" in cells["constraints"], (path, cells)
+ assert required >= 1 and scalars >= 250 and bounds >= 100, (required, scalars, bounds)
+
+
+def test_a_field_added_to_the_schema_gets_a_full_row() -> None:
+ from soup_cli.config.schema import SoupConfig
+
+ class Grown(SoupConfig):
+ brand_new_knob: Optional[int] = Field(default=7, ge=1, le=9, description="New | knob.")
+
+ page = gen.render_config_reference(Grown)
+ row = next(line for line in page.splitlines() if line.startswith("| `brand_new_knob` |"))
+ assert _cells(row) == [
+ "`brand_new_knob`",
+ "`int \\| null`",
+ "`7`",
+ "`>= 1`, `<= 9`",
+ "New \\| knob.",
+ ]
+
+
+class _Inner(BaseModel):
+ depth: int = Field(default=2, ge=1, le=8, description="How deep.")
+
+
+class _Toy(BaseModel):
+ name: str = Field(description="Required, with a | pipe,\nan <angle> and `a|b` code.")
+ mode: Literal["fast", "slow"] = Field(default="fast", description="Speed.")
+ ratio: Optional[float] = Field(default=None, gt=0.0, lt=1.0, allow_inf_nan=False)
+ tags: List[str] = Field(default_factory=lambda: ["a"], min_length=1, max_length=4)
+ stamp: str = Field(default_factory=lambda: "computed")
+ workdir: str = Field(default="C:\\Users\\someone\\out")
+ code: str = Field(default="x", pattern=r"^[a-z|]+$")
+ inner: _Inner = Field(default_factory=_Inner, description="Nested (v0.1.0 Part B).")
+ maybe: Optional[_Inner] = None
+ renamed: int = Field(default=1, alias="yamlName")
+
+
+def test_a_toy_model_renders_every_kind_of_row() -> None:
+ page = gen.render_config_reference(_Toy)
+ rows = {cells[0]: cells[1:] for cells in _rows(page.splitlines()) if len(cells) == 5}
+
+ assert rows["`name`"] == [
+ "`str`",
+ "**required**",
+ "",
+ "Required, with a \\| pipe, an &lt;angle> and `a\\|b` code.",
+ ]
+ assert rows["`mode`"] == ["`str`", '`"fast"`', 'one of `"fast"`, `"slow"`', "Speed."]
+ assert rows["`ratio`"] == ["`float \\| null`", "`null`", "`> 0.0`, `< 1.0`; finite", ""]
+ assert rows["`tags`"] == ["`list[str]`", '`["a"]`', "min length 1; max length 4", ""]
+ assert rows["`stamp`"][1] == "*(set at runtime)*", "a scalar from a factory is computed"
+ assert rows["`workdir`"][1] == "*(set at runtime)*"
+ assert rows["`code`"][2] == "pattern `^[a-z\\|]+$`"
+ assert rows["`inner`"] == [
+ "`section`",
+ "section defaults",
+ "",
+ "Nested (v0.1.0). See [`inner`](#inner).",
+ ]
+ assert rows["`maybe`"] == ["`section \\| null`", "`null`", "", "See [`maybe`](#maybe)."]
+ assert rows["`yamlName`"][0] == "`int`", "the YAML key is the alias, not the attribute"
+ assert "`renamed`" not in rows
+ assert rows["`inner.depth`"] == ["`int`", "`2`", "`>= 1`, `<= 8`", "How deep."]
+ assert rows["`maybe.depth`"] == rows["`inner.depth`"]
+ assert "someone" not in page
+
+
+def test_a_self_referencing_model_does_not_recurse_forever() -> None:
+ class Node(BaseModel):
+ label: str = "x"
+ child: Optional["Node"] = None
+
+ Node.model_rebuild()
+ sections = gen.config_sections(Node)
+ assert [path for path, _rows_ in sections] == [""]
+ assert [row.key for row in sections[0][1]] == ["label", "child"]
+
+
+# --------------------------------------------------------------------------
+# 2b. CLI page coverage
+# --------------------------------------------------------------------------
+
+
+def _live_root() -> click.Group:
+ from soup_cli.cli import app
+
+ return typer.main.get_command(app)
+
+
+def _visible(cmd: click.Command) -> list[click.Parameter]:
+ return [param for param in cmd.params if not getattr(param, "hidden", False)]
+
+
+def _command_tree(cmd: click.Command, path: tuple[str, ...] = ()) -> dict[str, click.Command]:
+ """``{"soup data inspect": command}`` for every visible command, walked here."""
+ found: dict[str, click.Command] = {}
+ if path:
+ found["soup " + " ".join(path)] = cmd
+ if isinstance(cmd, click.Group):
+ for name in cmd.list_commands(None) or []:
+ sub = cmd.get_command(None, name)
+ if sub is not None and not sub.hidden:
+ found.update(_command_tree(sub, (*path, name)))
+ return found
+
+
+def _cli_sections(page: str) -> dict[str, list[str]]:
+ """``{"soup data inspect": [lines of that section]}``; other headings end a section."""
+ sections: dict[str, list[str]] = {}
+ current: list[str] | None = None
+ for line in page.splitlines():
+ match = _COMMAND_HEADING.match(line)
+ if match:
+ assert match.group(1) not in sections, f"two sections for {match.group(1)}"
+ current = sections.setdefault(match.group(1), [])
+ elif line.startswith("#"):
+ current = None
+ elif current is not None:
+ current.append(line)
+ return sections
+
+
+def _row_names(row: list[str]) -> set[str]:
+ return set(re.findall(r"`([^`]+)`", row[0]))
+
+
+def test_every_registered_command_has_exactly_one_section(cli_page: str) -> None:
+ tree = _command_tree(_live_root())
+ leaves = [title for title, cmd in tree.items() if not isinstance(cmd, click.Group)]
+ assert len(leaves) >= 200, len(leaves)
+
+ sections = _cli_sections(cli_page)
+ assert sorted(sections) == sorted(tree), (
+ sorted(set(tree) - set(sections)),
+ sorted(set(sections) - set(tree)),
+ )
+
+
+def test_every_visible_option_and_argument_is_one_row_of_its_command(cli_page: str) -> None:
+ tree = _command_tree(_live_root())
+ sections = _cli_sections(cli_page)
+ options = 0
+ arguments = 0
+ for title, cmd in tree.items():
+ rows = _rows(sections[title])
+ params = _visible(cmd)
+ assert len(rows) == len(params), (title, len(rows), len(params))
+ for param, row in zip(params, rows):
+ if isinstance(param, click.Option):
+ options += 1
+ assert _row_names(row) == {*param.opts, *param.secondary_opts}, (title, row[0])
+ else:
+ arguments += 1
+ shown = param.metavar or param.name.upper() # what `--help` prints
+ assert row[0] in (f"`{shown}`", f"`{shown}...`"), (title, row[0])
+ assert row[3] == ("yes" if param.required else ""), (title, row)
+ assert options >= 1000, options
+ assert arguments >= 100, arguments
+
+
+def test_the_global_options_are_listed_before_the_commands(cli_page: str) -> None:
+ lines = cli_page.splitlines()
+ start = lines.index("## Global options")
+ end = lines.index("## Commands")
+ assert start < end
+ rows = _rows(lines[start:end])
+ root_params = _visible(_live_root())
+ assert root_params, "the root has options of its own"
+ assert [_row_names(row) for row in rows] == [
+ {*param.opts, *param.secondary_opts} for param in root_params
+ ]
+
+
+def test_the_commands_index_links_every_top_level_command(cli_page: str) -> None:
+ lines = cli_page.splitlines()
+ start = lines.index("## Commands")
+ stop = next(i for i in range(start + 1, len(lines)) if lines[i].startswith("#"))
+ linked = re.findall(r"\[`(soup [^`]+)`\]\(#([^)]+)\)", "\n".join(lines[start:stop]))
+ root = _live_root()
+ top = sorted(name for name, cmd in root.commands.items() if not cmd.hidden)
+ assert [title for title, _ in linked] == [f"soup {name}" for name in top]
+ assert all(anchor == title.replace(" ", "-") for title, anchor in linked), linked[:3]
+
+
+def _declared_argument_help(cmd: click.Command) -> dict[str, str]:
+ """Argument help as declared to Typer: Click 8.5 drops it from the Click object."""
+ from typer.models import ArgumentInfo
+ from typer.utils import get_params_from_function
+
+ if cmd.callback is None:
+ return {}
+ return {
+ name: meta.default.help
+ for name, meta in get_params_from_function(cmd.callback).items()
+ if isinstance(meta.default, ArgumentInfo) and meta.default.help
+ }
+
+
+def _help_strings(root: click.Group) -> list[tuple[str, str]]:
+ """``(where, text)`` for every command help and parameter help of the live CLI."""
+ found: list[tuple[str, str]] = []
+ for title, cmd in {"soup": root, **_command_tree(root)}.items():
+ found.append((title, cmd.help or ""))
+ declared = _declared_argument_help(cmd)
+ for param in cmd.params:
+ text = getattr(param, "help", None) or declared.get(param.name, "")
+ found.append((f"{title} {param.name}", text))
+ return found
+
+
+def test_every_command_a_help_string_or_a_description_names_is_registered() -> None:
+ """``soup eval against`` told its reader to take the run id "from `soup runs list`",
+ a subcommand that does not exist (``soup runs`` lists them). The docs guard (#1465)
+ reads the committed pages, whose wording may trail the code, so every `` `soup ...` ``
+ span is resolved here at its source: command help, parameter help, field description.
+ """
+ from soup_cli.config.schema import SoupConfig
+ from tests.test_issue1465_documented_invocations_exist import check_invocation
+
+ root = _live_root()
+ texts = _help_strings(root) + [
+ (path, info.description or "") for path, info, _ in _schema_fields(SoupConfig)
+ ]
+ spans = [
+ (where, span) for where, text in texts for span in re.findall(r"`(soup [^`\n]+)`", text)
+ ]
+ assert len(spans) >= 20, len(spans)
+ assert any(where.count(" ") >= 2 for where, _ in spans), "parameter help is read too"
+
+ problems = [
+ (where, span, reason)
+ for where, span in spans
+ for reason in [check_invocation(span, root)]
+ if reason is not None
+ ]
+ assert problems == []
+ assert check_invocation("soup runs list", root) is not None, "the control"
+
+
+class _Colour(str, enum.Enum):
+ red = "red"
+ blue = "blue"
+
+
+def _toy_root() -> click.Command:
+ app = typer.Typer(rich_markup_mode="rich")
+ oven = typer.Typer(help="Oven tools.")
+
+ @app.callback()
+ def _main(verbose: bool = typer.Option(False, "--verbose", "-V", help="Say more.")) -> None:
+ """A toy app."""
+
+ @app.command()
+ def bake(
+ recipe: str = typer.Argument(..., help="Recipe [bold]name[/bold]."),
+ extras: Optional[List[str]] = typer.Argument(None, help="Extra toppings."),
+ heat: int = typer.Option(3, "--heat", "-t", min=1, max=9, help="Heat | level."),
+ ratio: float = typer.Option(0.5, "--ratio", min=0.0),
+ colour: _Colour = typer.Option(_Colour.red, "--colour", help="Icing."),
+ dry_run: bool = typer.Option(True, "--dry-run/--wet-run", help="Do not light it."),
+ token: Optional[str] = typer.Option(
+ None, "--token", envvar="BAKE_TOKEN", help='Needs "soup-cli\\[bake]" and [doc-N].'
+ ),
+ tag: Optional[List[str]] = typer.Option(None, "--tag", help="[dim]Repeat me.[/]"),
+ secret: bool = typer.Option(False, "--secret", hidden=True, help="Not shown."),
+ workdir: str = typer.Option("C:\\Users\\someone", "--workdir", help="Where."),
+ stamp: str = typer.Option("", "--stamp", help="Empty by default."),
+ when: str = typer.Option(default_factory=lambda: "now", help="Computed."),
+ ) -> None:
+ """Bake a [green]thing[/green]
+ on two lines (v0.1.0 Part C).
+
+ soup bake --nope is on a later paragraph and must not reach the page.
+ """
+
+ @app.command(hidden=True)
+ def backdoor() -> None:
+ """Hidden."""
+
+ @oven.command("clean")
+ def clean() -> None:
+ """Scrub it."""
+
+ app.add_typer(oven, name="oven")
+ return typer.main.get_command(app)
+
+
+def test_a_toy_app_renders_every_kind_of_parameter() -> None:
+ page = gen.render_cli_reference(_toy_root())
+ sections = _cli_sections(page)
+ assert sorted(sections) == ["soup bake", "soup oven", "soup oven clean"]
+ assert "backdoor" not in page and "--secret" not in page
+
+ bake = sections["soup bake"]
+ assert "Bake a thing on two lines (v0.1.0)." in bake
+ assert "Usage: `soup bake [OPTIONS] RECIPE [EXTRAS]...`" in bake
+ assert "--nope" not in page
+ rows = {row[0]: row[1:] for row in _rows(bake)}
+ assert rows["`RECIPE`"] == ["text", "", "yes", "Recipe name."]
+ assert rows["`EXTRAS...`"] == ["text, any number", "", "", "Extra toppings."]
+ assert rows["`--heat`, `-t`"] == ["integer, 1 to 9", "`3`", "", "Heat \\| level."]
+ assert rows["`--ratio`"][:2] == ["float, at least 0.0", "`0.5`"]
+ assert rows["`--colour`"] == ["one of `red`, `blue`", "`red`", "", "Icing."]
+ assert rows["`--dry-run` / `--wet-run`"] == ["flag", "on", "", "Do not light it."]
+ assert rows["`--token`"] == [
+ "text",
+ "",
+ "",
+ 'Needs "soup-cli\\[bake]" and \\[doc-N]. Env: `BAKE_TOKEN`.',
+ ]
+ assert rows["`--tag`"] == ["text, repeatable", "", "", "Repeat me."]
+ assert rows["`--workdir`"][1] == "*(set at runtime)*"
+ assert rows["`--stamp`"][1] == '`""`'
+ assert rows["`--when`"][1] == "*(set at runtime)*"
+ assert "someone" not in page
+
+ oven = sections["soup oven"]
+ assert oven[oven.index("Subcommands:") + 2] == "- [`clean`](#soup-oven-clean)", oven
+ assert "Takes no options or arguments." in sections["soup oven clean"]
+ assert "| `--verbose`, `-V` | flag | off | | Say more. |" in page
+
+
+def test_a_plain_click_tree_renders_the_remaining_parameter_shapes() -> None:
+ """Shapes the Typer toy does not produce; also proves nothing here needs Typer."""
+ passthrough = {"allow_extra_args": True, "ignore_unknown_options": True}
+ tool = click.Command(
+ "tool",
+ help="- not a bullet",
+ params=[
+ click.Option(["-v", "--loud"], count=True, help="More output"),
+ click.Option(["--pair"], nargs=2, type=int),
+ click.Option(["--src"], type=click.Path(), envvar=["SRC", "SOURCE"], help="From"),
+ click.Option(["--share"], type=click.FloatRange(0, 1, min_open=True), default=0.5),
+ click.Option(["--strict"], type=bool, default=None),
+ click.Option(["--mode"], type=click.Choice(["a", "b"]), default="a", required=True),
+ click.Option(["--keep"], multiple=True, default=("x", "y")),
+ ],
+ )
+ group = click.Group(
+ "runs",
+ help="1. not a list",
+ invoke_without_command=True,
+ params=[click.Option(["--limit"], type=int, default=10)],
+ commands={
+ "show": click.Command("show", help="# not a heading"),
+ "more": click.Group(
+ "more", commands={"deep": click.Command("deep", help="Three names down.")}
+ ),
+ },
+ )
+ root = click.Group(
+ "soup",
+ commands={
+ "tool": tool,
+ "runs": group,
+ "raw": click.Command("raw", help="> not a quote", context_settings=passthrough),
+ "plain": click.Command("plain", help="--flag stays as typed"),
+ },
+ )
+
+ page = gen.render_cli_reference(root)
+ lines = page.splitlines()
+ sections = _cli_sections(page)
+ assert list(sections) == [
+ "soup plain",
+ "soup raw",
+ "soup runs",
+ "soup runs more",
+ "soup runs more deep",
+ "soup runs show",
+ "soup tool",
+ ]
+ assert "#### `soup runs more deep`" in lines, "one heading level per name, three deep"
+ for escaped in ("\\- not a bullet", "1\\. not a list", "\\# not a heading", "\\> not a quote"):
+ assert escaped in lines, escaped
+ assert "--flag stays as typed" in lines
+ assert "Usage: `soup raw [ARGS]...`" in lines
+ assert "Usage: `soup runs [OPTIONS] [<command>] [ARGS]...`" in lines
+ assert "Usage: `soup <command> [ARGS]...`" in lines, "a root without options of its own"
+ assert "### `soup runs show`" in lines
+
+ rows = {row[0]: row[1:] for row in _rows(sections["soup tool"])}
+ assert rows["`-v`, `--loud`"] == ["counter", "`0`", "", "More output"]
+ assert rows["`--pair`"][0] == "integer, 2 values"
+ assert rows["`--src`"] == ["path", "", "", "From. Env: `SRC`, `SOURCE`."]
+ assert rows["`--share`"][:2] == ["float, above 0, at most 1", "`0.5`"]
+ assert rows["`--strict`"][:2] == ["boolean", ""]
+ assert rows["`--mode`"][:3] == ["one of `a`, `b`", "`a`", "yes"]
+ assert rows["`--keep`"][:2] == ["text, repeatable", '`["x", "y"]`']
+
+
+def test_argument_help_reads_the_same_whether_or_not_click_kept_it() -> None:
+ """Click 8.5 resets the ``help`` Typer 0.20 sets on an argument; older Click keeps
+ it. The page must not change with the Click that happens to be installed."""
+ declared = {"recipe": "Recipe [bold]name[/bold].", "extras": "Extra toppings."}
+ kept, reset = _toy_root(), _toy_root()
+ for root, value in ((kept, declared), (reset, {})):
+ for param in root.commands["bake"].params:
+ if isinstance(param, click.Argument):
+ param.help = value.get(param.name)
+
+ assert gen.render_cli_reference(kept) == gen.render_cli_reference(reset)
+ assert "| `RECIPE` | text | | yes | Recipe name. |" in gen.render_cli_reference(reset)
+
+
+def test_typer_completion_options_do_not_depend_on_shell_detection(
+ monkeypatch: pytest.MonkeyPatch, cli_page: str
+) -> None:
+ """Without ``shellingham`` (or with detection disabled) Typer swaps the two
+ completion flags for options that take a shell name, with other help text."""
+ monkeypatch.setenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION", "1")
+ undetected = _live_root()
+ install = next(p for p in undetected.params if p.name == "install_completion")
+ assert not install.is_flag, "the control: Typer really built the other variant"
+
+ assert gen.render_cli_reference(undetected) == cli_page
+ assert "| `--install-completion` | flag |" in cli_page
+
+
+def test_rendering_ignores_the_terminal(
+ monkeypatch: pytest.MonkeyPatch, pages: dict[str, str]
+) -> None:
+ """Nothing is taken from ``--help`` output, so width and colour cannot leak in."""
+ monkeypatch.setenv("COLUMNS", "40")
+ monkeypatch.setenv("FORCE_COLOR", "1")
+ monkeypatch.setenv("TERM", "dumb")
+ assert gen.render_pages() == pages
+
+
+# --------------------------------------------------------------------------
+# 1c. --check-structure, on a toy schema and a toy CLI
+# --------------------------------------------------------------------------
+
+_RUN_THIS = "Run `python scripts/gen_reference_docs.py` and commit the result."
+
+
+def toy_tree(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """A scratch repo whose two pages are the toy model's and the toy app's, with the
+ generator pointed at both. Each structure test then changes exactly one thing."""
+ _mirror(
+ tmp_path,
+ {
+ gen.CONFIG_PAGE: gen.render_config_reference(_Toy),
+ gen.CLI_PAGE: gen.render_cli_reference(_toy_root()),
+ },
+ )
+ monkeypatch.setattr(gen, "_REPO_ROOT", tmp_path)
+ monkeypatch.setattr(gen, "_load_config_model", lambda: _Toy)
+ monkeypatch.setattr(gen, "_load_cli_root", _toy_root)
+ return tmp_path
+
+
+def _toy_with(**fields: Any) -> type[BaseModel]:
+ """The toy model with fields added, or redeclared in place."""
+ return create_model("ToyVariant", __base__=_Toy, **fields)
+
+
+class _DeeperInner(BaseModel):
+ depth: int = Field(default=3, ge=1, le=8, description="How deep.")
+
+
+def _param(root: click.Command, command: str, name: str) -> click.Parameter:
+ target = root.commands[command] if command else root
+ return next(param for param in target.params if param.name == name)
+
+
+def _toy_root_after(*mutations: Any) -> click.Command:
+ root = _toy_root()
+ for mutate in mutations:
+ mutate(root)
+ return root
+
+
+_SPEED = "Speed."
+_CONFIG_CHANGES: dict[str, tuple[Any, str]] = {
+ "default": (
+ lambda: _toy_with(
+ mode=(Literal["fast", "slow"], Field(default="slow", description=_SPEED))
+ ),
+ 'mode: committed page: default `"fast"` | code now: default `"slow"`',
+ ),
+ "default-removed": (
+ lambda: _toy_with(mode=(Literal["fast", "slow"], Field(description=_SPEED))),
+ 'mode: committed page: default `"fast"` | code now: default **required**',
+ ),
+ "type": (
+ lambda: _toy_with(code=(Optional[str], Field(default="x", pattern=r"^[a-z|]+$"))),
+ "code: committed page: type `str` | code now: type `str | null`",
+ ),
+ "bound": (
+ lambda: _toy_with(
+ tags=(List[str], Field(default_factory=lambda: ["a"], min_length=1, max_length=8))
+ ),
+ "tags: committed page: constraints min length 1; max length 4"
+ " | code now: constraints min length 1; max length 8",
+ ),
+ "choice": (
+ lambda: _toy_with(
+ mode=(Literal["fast", "slow", "turbo"], Field(default="fast", description=_SPEED))
+ ),
+ 'mode: committed page: constraints one of `"fast"`, `"slow"`'
+ ' | code now: constraints one of `"fast"`, `"slow"`, `"turbo"`',
+ ),
+ "nested-default": (
+ lambda: _toy_with(inner=(_DeeperInner, Field(default_factory=_DeeperInner))),
+ "inner.depth: committed page: default `2` | code now: default `3`",
+ ),
+ "two-columns-one-line": (
+ lambda: _toy_with(mode=(Optional[Literal["fast", "slow"]], Field(default=None))),
+ 'mode: committed page: type `str`, default `"fast"`'
+ " | code now: type `str | null`, default `null`",
+ ),
+ "new-key": (
+ lambda: _toy_with(fresh_knob=(int, Field(default=7, ge=1, description="New."))),
+ "fresh_knob: committed page: (not listed)"
+ " | code now: type `int`, default `7`, constraints `>= 1`",
+ ),
+}
+
+
[email protected]("case", sorted(_CONFIG_CHANGES))
+def test_a_changed_config_key_fails_structure_and_is_named(
+ toy_tree: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], case: str
+) -> None:
+ variant, expected = _CONFIG_CHANGES[case]
+ monkeypatch.setattr(gen, "_load_config_model", variant)
+
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/config-reference.md no longer matches the schema (1 difference):" in out, out
+ assert expected in out, out
+ assert "docs/cli-reference.md" not in out, out
+ assert out.endswith(_RUN_THIS), out
+ assert gen.main(["--check"]) == 1, "what structure refuses, the exact check refuses too"
+
+
+def test_a_key_that_left_the_schema_fails_structure_and_is_named(
+ toy_tree: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ with_extra = gen.render_config_reference(_toy_with(fresh_knob=(int, Field(default=7))))
+ (toy_tree / gen.CONFIG_PAGE).write_bytes(with_extra.encode("utf-8"))
+
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/config-reference.md no longer matches the schema (1 difference):" in out, out
+ assert (
+ "fresh_knob: committed page: type `int`, default `7`, constraints (empty)"
+ " | code now: (no such field)"
+ ) in out, out
+ assert out.endswith(_RUN_THIS), out
+
+
+def test_rewording_a_description_passes_structure_and_fails_exact(
+ toy_tree: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ reworded = _toy_with(
+ mode=(Literal["fast", "slow"], Field(default="fast", description="How fast the run goes.")),
+ inner=(_Inner, Field(default_factory=_Inner, description="A nested block, reworded.")),
+ )
+ monkeypatch.setattr(gen, "_load_config_model", lambda: reworded)
+
+ assert gen.main(["--check-structure"]) == 0
+ assert "state what the code does" in _plain(capsys.readouterr().out)
+ assert gen.main(["--check"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/config-reference.md is stale" in out, out
+ assert "docs/cli-reference.md" not in out, out
+
+
+_FRESH_FLAG = click.Option(["--fresh-flag"], is_flag=True, default=False, help="New.")
+_CLI_CHANGES: dict[str, tuple[Any, str]] = {
+ "default": (
+ lambda root: setattr(_param(root, "bake", "heat"), "default", 5),
+ "soup bake --heat, -t: committed page: default `3` | code now: default `5`",
+ ),
+ "required": (
+ lambda root: setattr(_param(root, "bake", "tag"), "required", True),
+ "soup bake --tag: committed page: required (empty) | code now: required yes",
+ ),
+ "type": (
+ lambda root: setattr(_param(root, "bake", "heat"), "type", click.IntRange(1, 12)),
+ "soup bake --heat, -t: committed page: type integer, 1 to 9"
+ " | code now: type integer, 1 to 12",
+ ),
+ "new-option": (
+ lambda root: root.commands["bake"].params.append(_FRESH_FLAG),
+ "soup bake --fresh-flag: committed page: (not listed)"
+ " | code now: type flag, default off, required (empty)",
+ ),
+ "new-argument": (
+ lambda root: root.commands["oven"].commands["clean"].params.append(
+ click.Argument(["target"])
+ ),
+ "soup oven clean TARGET: committed page: (not listed)"
+ " | code now: type text, default (empty), required yes",
+ ),
+ "new-command": (
+ lambda root: root.commands.__setitem__("fresh", click.Command("fresh", help="New.")),
+ "soup fresh: committed page: (no section) | code now: a command",
+ ),
+ "global-option": (
+ lambda root: setattr(_param(root, "", "verbose"), "default", True),
+ "soup --verbose, -V: committed page: default off | code now: default on",
+ ),
+}
+
+
[email protected]("case", sorted(_CLI_CHANGES))
+def test_a_changed_command_or_parameter_fails_structure_and_is_named(
+ toy_tree: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], case: str
+) -> None:
+ mutate, expected = _CLI_CHANGES[case]
+ monkeypatch.setattr(gen, "_load_cli_root", lambda: _toy_root_after(mutate))
+
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/cli-reference.md no longer matches the CLI (1 difference):" in out, out
+ assert expected in out, out
+ assert "docs/config-reference.md" not in out, out
+ assert out.endswith(_RUN_THIS), out
+ assert gen.main(["--check"]) == 1, "what structure refuses, the exact check refuses too"
+
+
+ ("case", "expected"),
+ [
+ (
+ "new-option",
+ "soup bake --fresh-flag: committed page: type flag, default off, required (empty)"
+ " | code now: (no such parameter)",
+ ),
+ ("new-command", "soup fresh: committed page: a section | code now: (no such command)"),
+ ],
+)
+def test_what_left_the_cli_fails_structure_and_is_named(
+ toy_tree: Path, capsys: pytest.CaptureFixture[str], case: str, expected: str
+) -> None:
+ with_extra = gen.render_cli_reference(_toy_root_after(_CLI_CHANGES[case][0]))
+ (toy_tree / gen.CLI_PAGE).write_bytes(with_extra.encode("utf-8"))
+
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/cli-reference.md no longer matches the CLI (1 difference):" in out, out
+ assert expected in out, out
+ assert out.endswith(_RUN_THIS), out
+
+
+def test_rewording_help_passes_structure_and_fails_exact(
+ toy_tree: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ def reword(root: click.Command) -> None:
+ root.commands["bake"].help = "Bake something, said differently."
+ _param(root, "bake", "heat").help = "How hot, reworded."
+ _param(root, "", "verbose").help = "Say a lot more."
+
+ monkeypatch.setattr(gen, "_load_cli_root", lambda: _toy_root_after(reword))
+
+ assert gen.main(["--check-structure"]) == 0
+ assert "state what the code does" in _plain(capsys.readouterr().out)
+ assert gen.main(["--check"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/cli-reference.md is stale" in out, out
+ assert "docs/config-reference.md" not in out, out
+
+
+def test_structure_names_ten_differences_per_page_and_counts_the_rest(
+ toy_tree: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ knobs = {f"knob_{index:02d}": (int, Field(default=index)) for index in range(13)}
+ monkeypatch.setattr(gen, "_load_config_model", lambda: _toy_with(**knobs))
+ monkeypatch.setattr(gen, "_load_cli_root", lambda: _toy_root_after(_CLI_CHANGES["type"][0]))
+
+ assert gen.main(["--check-structure"]) == 1
+ report = capsys.readouterr().out
+ out = _plain(report)
+ assert "docs/config-reference.md no longer matches the schema (13 differences):" in out, out
+ assert out.count(": committed page: (not listed)") == 10, out
+ assert "knob_09: committed page: (not listed)" in out and "knob_10" not in out, out
+ # one offending key per line, indented under its page
+ per_key = [line for line in report.splitlines() if line.startswith(" knob_")]
+ assert len(per_key) == len(set(per_key)) == gen._MAX_SHOWN, report
+ assert all(line.count("committed page:") == line.count("| code now:") == 1 for line in per_key)
+ # the count of what was not shown closes the first page's block
+ assert "... and 3 more docs/cli-reference.md no longer matches the CLI (1 difference):" in out
+ assert out.count(_RUN_THIS) == 1 and out.endswith(_RUN_THIS), out
+
+
+def test_split_row_splits_where_github_does() -> None:
+ r"""Each row below was rendered through GitHub's Markdown API on 2026-10-12. A pipe
+ right after a backslash never ends a cell, however many backslashes come before it,
+ and GitHub then drops exactly one of them: `x\\|y` in code shows as `x\|y`."""
+ assert gen.split_row("| a | b |") == ["a", "b"]
+ assert gen.split_row("|---|---|") == ["---", "---"]
+ assert gen.split_row(r"| `x\|y` | p\|q | | z |") == [r"`x\|y`", r"p\|q", "", "z"]
+ assert gen.split_row(r"| `x\\|y` | p\\|q |") == [r"`x\\|y`", r"p\\|q"]
+ assert gen.split_row(r"| `x\\\|y` | p\\\|q |") == [r"`x\\\|y`", r"p\\\|q"]
+ assert gen.split_row(r"| `^[a-z\\|]+$` | end\\ |") == [r"`^[a-z\\|]+$`", r"end\\"]
+ assert gen.split_row(r"| `tail\` | z |") == [r"`tail\`", "z"]
+
+
+class _Patterns(BaseModel):
+ alt: str = Field(default="a", pattern=r"^a\|b$", description=r"A literal \| bar, either side.")
+ after: int = Field(default=1, ge=1, description="The row below it.")
+
+
+def test_a_backslash_before_a_pipe_does_not_take_the_row_out_of_the_check(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ r"""A regex such as ``^a\|b$`` is written ``^a\\|b$`` in the cell, which is what makes
+ GitHub show it as it is. Split by backslash parity, that row had six cells, did not
+ look like a row, and silently left the comparison."""
+ page = gen.render_config_reference(_Patterns)
+ row = next(line for line in page.splitlines() if line.startswith("| `alt` |"))
+ assert row == (
+ r"| `alt` | `str` | `" + '"a"' + "` "
+ r"| pattern `^a\\|b$` | A literal \\\| bar, either side. |"
+ )
+ parsed = gen.parse_config_page(page)
+ assert list(parsed) == ["alt", "after"]
+ assert parsed["alt"]["constraints"] == r"pattern `^a\\|b$`"
+
+ _mirror(tmp_path, {gen.CONFIG_PAGE: page, gen.CLI_PAGE: gen.render_cli_reference(_toy_root())})
+ monkeypatch.setattr(gen, "_REPO_ROOT", tmp_path)
+ monkeypatch.setattr(gen, "_load_cli_root", _toy_root)
+ monkeypatch.setattr(gen, "_load_config_model", lambda: _Patterns)
+ assert gen.main(["--check-structure"]) == 0, capsys.readouterr().out
+ capsys.readouterr()
+
+ changed = create_model(
+ "Changed", __base__=_Patterns, alt=(str, Field(default="b", pattern=r"^a\|b$"))
+ )
+ monkeypatch.setattr(gen, "_load_config_model", lambda: changed)
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert 'alt: committed page: default `"a"` | code now: default `"b"`' in out, out
+
+
+ ("good", "bad"),
+ [
+ ("| `mode` | `str` |", "| `mode` | `str` | one cell too many |"),
+ ("| `mode` | `str` |", "| `mode` | `str | int` |"), # a pipe written without its backslash
+ ("| `mode` | `str` |", "| mode | `str` |"), # the key is not a code span
+ ],
+)
+def test_a_table_line_that_cannot_be_read_back_fails_the_check(
+ toy_tree: Path, capsys: pytest.CaptureFixture[str], good: str, bad: str
+) -> None:
+ """Never a skip: a row the parser cannot read would drop its key from the check."""
+ page = toy_tree / gen.CONFIG_PAGE
+ text = page.read_bytes().decode("utf-8")
+ assert text.count(good) == 1
+ broken = text.replace(good, bad)
+ page.write_bytes(broken.encode("utf-8"))
+
+ with pytest.raises(gen.PageFormatError, match="is not a 5-column row of this page"):
+ gen.parse_config_page(broken)
+ assert gen.main(["--check-structure"]) == 1
+ out = _plain(capsys.readouterr().out)
+ assert "docs/config-reference.md no longer matches the schema (1 difference):" in out, out
+ assert "the committed page cannot be read back: line " in out, out
+ assert "mode" in out and out.endswith(_RUN_THIS), out
+
+
+def test_the_parsers_read_back_what_the_renderers_stated() -> None:
+ config = gen.parse_config_page(gen.render_config_reference(_Toy))
+ assert list(config) == [
+ "name",
+ "mode",
+ "ratio",
+ "tags",
+ "stamp",
+ "workdir",
+ "code",
+ "inner",
+ "maybe",
+ "yamlName",
+ "inner.depth",
+ "maybe.depth",
+ ]
+ assert config["code"] == {
+ "type": "`str`",
+ "default": '`"x"`',
+ "constraints": "pattern `^[a-z\\|]+$`",
+ }
+ assert config["ratio"]["type"] == "`float \\| null`"
+ assert config["name"] == {"type": "`str`", "default": "**required**", "constraints": ""}
+
+ cli = gen.parse_cli_page(gen.render_cli_reference(_toy_root()))
+ assert list(cli) == ["soup", "soup bake", "soup oven", "soup oven clean"]
+ assert list(cli["soup"]) == ["--verbose, -V", "--install-completion", "--show-completion"]
+ assert cli["soup"]["--verbose, -V"] == {"type": "flag", "default": "off", "required": ""}
+ assert list(cli["soup bake"])[:3] == ["RECIPE", "EXTRAS...", "--heat, -t"]
+ assert cli["soup bake"]["RECIPE"] == {"type": "text", "default": "", "required": "yes"}
+ assert cli["soup bake"]["--dry-run / --wet-run"]["default"] == "on"
+ assert cli["soup oven"] == {} and cli["soup oven clean"] == {}
+
+
+def test_the_structure_parsers_read_every_row_of_the_real_pages(
+ config_page: str, cli_page: str
+) -> None:
+ """A parser that silently read nothing would let the structure check pass for ever."""
+ from soup_cli.config.schema import SoupConfig
+
+ paths, _ = _schema_paths(SoupConfig)
+ assert sorted(gen.parse_config_page(config_page)) == sorted(paths)
+
+ root = _live_root()
+ tree = _command_tree(root)
+ parsed = gen.parse_cli_page(cli_page)
+ assert set(parsed) == {"soup", *tree}
+ assert len(parsed["soup"]) == len(_visible(root))
+ for title, cmd in tree.items():
+ assert len(parsed[title]) == len(_visible(cmd)), title
+
+
+# --------------------------------------------------------------------------
+# 1d. one line per item: concurrent changes merge as text and stay right
+# --------------------------------------------------------------------------
+
+
+def _insertions(base: str, changed: str) -> dict[int, list[str]]:
+ """``{line index in base: lines inserted there}`` for a change that only adds lines;
+ fails when the change removes or rewrites a line that was already on the page."""
+ old, new = base.split("\n"), changed.split("\n")
+ found: dict[int, list[str]] = {}
+ matcher = difflib.SequenceMatcher(None, old, new, autojunk=False)
+ for tag, old_start, old_stop, new_start, new_stop in matcher.get_opcodes():
+ if tag == "equal":
+ continue
+ assert tag == "insert", (tag, old[old_start:old_stop], new[new_start:new_stop])
+ found[old_start] = new[new_start:new_stop]
+ return found
+
+
+def _merged(base: str, *changes: str) -> str:
+ """The three-way text merge of changes that insert at different places."""
+ lines = base.split("\n")
+ inserted: dict[int, list[str]] = {}
+ for change in changes:
+ for index, added in _insertions(base, change).items():
+ assert index not in inserted, f"two changes insert at line {index + 1}"
+ inserted[index] = added
+ for index in sorted(inserted, reverse=True):
+ lines[index:index] = inserted[index]
+ return "\n".join(lines)
+
+
+def test_two_changes_that_each_add_a_key_merge_as_text_and_stay_right() -> None:
+ def page(*names: str) -> str:
+ fields = {name: (int, Field(default=len(name), description=name)) for name in names}
+ return gen.render_config_reference(create_model("Merged", **fields))
+
+ base = page("alpha", "beta", "gamma")
+ first = page("alpha", "one", "beta", "gamma")
+ second = page("alpha", "beta", "two", "gamma")
+ assert list(_insertions(base, first).values()) == [["| `one` | `int` | `3` | | one |"]]
+ assert _merged(base, first, second) == page("alpha", "one", "beta", "two", "gamma")
+
+
+def test_changes_that_add_an_option_and_commands_merge_as_text_and_stay_right() -> None:
+ def add_option(root: click.Command) -> None:
+ root.commands["bake"].params.insert(3, click.Option(["--extra"], help="More."))
+
+ def add_subcommand(root: click.Command) -> None:
+ root.commands["oven"].commands["wipe"] = click.Command("wipe", help="Wipe it.")
+
+ def add_command(root: click.Command) -> None:
+ root.commands["apple"] = click.Command("apple", help="Core it.")
+
+ def page(*mutations: Any) -> str:
+ return gen.render_cli_reference(_toy_root_after(*mutations))
+
+ base = page()
+ assert list(_insertions(base, page(add_option)).values()) == [
+ ["| `--extra` | text | | | More. |"]
+ ]
+ assert "- [`wipe`](#soup-oven-wipe)" in sum(
+ _insertions(base, page(add_subcommand)).values(), []
+ )
+ merged = _merged(base, page(add_option), page(add_subcommand), page(add_command))
+ assert merged == page(add_option, add_subcommand, add_command)
+
+
+# --------------------------------------------------------------------------
+# 2c. what the pages must never carry
+# --------------------------------------------------------------------------
+
+
+def _leaked_paths(page: str, directories: typing.Iterable[PurePath]) -> list[str]:
+ """The directories that appear in ``page`` as a whole path.
+
+ A plain substring test is wrong here: a checkout at ``/repo`` or ``/data`` is also
+ ordinary page text (``./data/train.jsonl``). So a directory fewer than two levels
+ deep is not looked for at all, and a deeper one only counts where a path starts, not
+ as the tail of another path or the head of a longer name."""
+ leaked = set()
+ for directory in directories:
+ if len(directory.parts) < 3: # the anchor and two levels
+ continue
+ for spelled in (str(directory), directory.as_posix()):
+ if re.search(r"(?<![\w./\\~-])" + re.escape(spelled) + r"(?![\w-])", page):
+ leaked.add(spelled)
+ return sorted(leaked)
+
+
[email protected]("rel", ["docs/config-reference.md", "docs/cli-reference.md"])
+def test_a_page_carries_nothing_from_this_machine(pages: dict[str, str], rel: str) -> None:
+ page = pages[rel]
+ assert _leaked_paths(page, (Path.home(), _ROOT, Path.cwd())) == [], rel
+ for needle in ("\r", "\t", "\x1b"):
+ assert needle not in page, (rel, needle)
+ assert not re.search(r"\b[A-Za-z]:\\", page), "a Windows drive path"
+ assert [line for line in page.splitlines() if line != line.rstrip()] == []
+ assert page.endswith("\n") and not page.endswith("\n\n")
+
+
+def test_the_leak_check_reads_whole_paths_only() -> None:
+ text = "default `./data/train.jsonl`; /home/someone/.soup; C:\\Users\\someone\\x; /repository"
+ shallow = [PurePosixPath("/data"), PurePosixPath("/repo"), PurePosixPath("/")]
+ assert _leaked_paths(text, shallow) == []
+ assert _leaked_paths("mounted at /data, cloned to /repo", shallow) == []
+ assert _leaked_paths(text, [PurePosixPath("/home/someone")]) == ["/home/someone"]
+ assert _leaked_paths(text, [PureWindowsPath("C:\\Users\\someone")]) == ["C:\\Users\\someone"]
+ assert _leaked_paths("see ./home/someone/x", [PurePosixPath("/home/someone")]) == []
+ assert _leaked_paths("see /home/someone-else/x", [PurePosixPath("/home/someone")]) == []
+ assert _leaked_paths("/srv/ci/soup", [PurePosixPath("/srv/ci/soup")]) == ["/srv/ci/soup"]
+
+
[email protected]("rel", ["docs/config-reference.md", "docs/cli-reference.md"])
+def test_a_page_says_it_is_generated_and_how_to_regenerate_it(
+ pages: dict[str, str], rel: str
+) -> None:
+ lines = pages[rel].split("\n## ", 1)[0].splitlines()
+ head = " ".join(" ".join(line.lstrip("> ") for line in lines).split())
+ assert "Generated file" in head and "do not edit by hand" in head, head
+ assert "`python scripts/gen_reference_docs.py` and commit the result" in head, head
+ assert "refreshed when a release is cut" in head, head
+
+
[email protected]("rel", ["docs/config-reference.md", "docs/cli-reference.md"])
+def test_a_page_header_carries_no_number_at_all(pages: dict[str, str], rel: str) -> None:
+ """No total, count, date or version above the first table: a line that sums over
+ the page changes in every pull request that adds a row, so two of them conflict,
+ or worse merge cleanly into a number that is wrong."""
+ head = pages[rel].split("\n## ", 1)[0]
+ assert re.findall(r"\d+", head) == [], rel
+
+
[email protected]("rel", ["docs/config-reference.md", "docs/cli-reference.md"])
+def test_a_page_carries_no_internal_release_phase_label(pages: dict[str, str], rel: str) -> None:
+ """"vX.Y.Z Part B" is planning shorthand; public docs carry the version only."""
+ assert _INTERNAL_PHASE.findall(pages[rel]) == []
+
+
+def _slug(heading: str) -> str:
+ """GitHub's heading anchor, written here independently of the generator's."""
+ text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", heading.replace("`", "")).strip().lower()
+ return "".join("-" if char == " " else char for char in text if char.isalnum() or char in "_- ")
+
+
+def _anchors(markdown: str) -> set[str]:
+ seen: Counter[str] = Counter()
+ anchors = set()
+ for line in markdown.splitlines():
+ match = re.match(r"^#{1,6}\s+(.*?)\s*$", line)
+ if match:
+ base = _slug(match.group(1))
+ anchors.add(base if not seen[base] else f"{base}-{seen[base]}")
+ seen[base] += 1
+ return anchors
+
+
+def _internal_targets(page: str) -> list[str]:
+ """The link targets this page is answerable for: an in-page ``#anchor`` or a relative
+ ``*.md`` file. A URL with a scheme is somebody else's page, and a description is free
+ to carry one (``See [the guide](https://example.com/lr)``)."""
+ targets = re.findall(r"\]\(([^)\s]+)\)", page)
+ return [
+ target
+ for target in targets
+ if not re.match(r"[A-Za-z][A-Za-z0-9+.-]*:", target)
+ and (target.startswith("#") or target.partition("#")[0].endswith(".md"))
+ ]
+
+
+def _broken_links(page: str) -> list[str]:
+ own = _anchors(page)
+ broken = []
+ for target in _internal_targets(page):
+ file_part, _, fragment = target.partition("#")
+ if not file_part:
+ known = own
+ else:
+ other = _ROOT / "docs" / file_part
+ if not other.is_file():
+ broken.append(target)
+ continue
+ known = _anchors(other.read_text(encoding="utf-8")) if fragment else set()
+ if fragment and fragment not in known:
+ broken.append(target)
+ return broken
+
+
[email protected]("rel", ["docs/config-reference.md", "docs/cli-reference.md"])
+def test_every_link_in_a_page_resolves(pages: dict[str, str], rel: str) -> None:
+ assert len(_internal_targets(pages[rel])) >= 8
+ assert _broken_links(pages[rel]) == []
+
+
+def test_an_external_link_in_a_description_is_not_a_broken_file() -> None:
+ class Linked(BaseModel):
+ rate: float = Field(default=0.1, description="See [the guide](https://example.com/lr).")
+ mail: str = Field(default="", description="Ask [us](mailto:[email protected]) or (x)[y].")
+ page: str = Field(default="", description="Raw: [md](https://example.com/guide.md#lr).")
+ logo: str = Field(default="", description="A picture, ![logo](assets/none.png).")
+
+ page = gen.render_config_reference(Linked)
+ assert "https://example.com/lr" in page and "assets/none.png" in page
+ assert "#top-level-keys" in _internal_targets(page)
+ assert [target for target in _internal_targets(page) if ":" in target] == []
+ assert _broken_links(page) == []
+ # the control: an internal target that goes nowhere is still caught
+ assert _broken_links(page + "\n[a](#nowhere) [b](missing-page.md) [c](README.md#nope)\n") == [
+ "#nowhere",
+ "missing-page.md",
+ "README.md#nope",
+ ]
+
+
+def test_the_config_page_links_the_unknown_key_section(config_page: str) -> None:
+ assert "refuses the load" in " ".join(config_page.split())
+ assert "](backends-and-ops.md#unknown-config-keys)" in config_page
+
+
+# --------------------------------------------------------------------------
+# 1b. the determinism helpers, one by one
+# --------------------------------------------------------------------------
+
+
+ ("annotation", "expected"),
+ [
+ (str, "str"),
+ (bool, "bool"),
+ (Optional[int], "int | null"),
+ (Union[int, None], "int | null"),
+ (Union[None, int], "int | null"),
+ (int | None, "int | null"),
+ (None | int, "int | null"),
+ (Union[str, List[str]], "str | list[str]"),
+ (str | list[str], "str | list[str]"),
+ (List[str], "list[str]"),
+ (list[str], "list[str]"),
+ (list, "list"),
+ (List, "list"),
+ (Dict[str, int], "dict[str, int]"),
+ (dict[str, int], "dict[str, int]"),
+ (Optional[dict[str, float]], "dict[str, float] | null"),
+ (Dict, "dict"),
+ (dict, "dict"),
+ (Union[str, Dict, None], "str | dict | null"),
+ (Optional[List[Dict[str, Union[str, float]]]], "list[dict[str, str | float]] | null"),
+ (Literal["a", "b"], "str"),
+ (Optional[Literal["a", "b"]], "str | null"),
+ (Literal[1, 2], "int"),
+ (Literal["a", 1], "str | int"),
+ (Union[int, Literal["auto"]], 'int | "auto"'),
+ (Union[bool, Literal["fp8", "quest"]], 'bool | "fp8" | "quest"'),
+ (Union[Literal["auto"], List[str], None], '"auto" | list[str] | null'),
+ (Annotated[int, Field(ge=1)], "int"),
+ (Optional[Annotated[int, Field(ge=1)]], "int | null"),
+ (_Inner, "section"),
+ (Optional[_Inner], "section | null"),
+ (List[_Inner], "list[section]"),
+ (_Colour, "str"),
+ (Optional[_Colour], "str | null"),
+ (tuple[int, ...], "tuple[int]"),
+ (frozenset[str], "set[str]"),
+ (collections.abc.Sequence[str], "list[str]"),
+ (typing.Mapping[str, int], "dict[str, int]"),
+ (Path, "path"),
+ (Any, "any"),
+ # isinstance(type[int], type) is True on 3.10 and False from 3.11: the generic
+ # must not fall through to the class branch on one of them only
+ (type[int], "any"),
+ (typing.Callable[[int], str], "any"),
+ (type(None), "null"),
+ ],
+)
+def test_types_are_spelled_one_way_on_every_python(annotation: Any, expected: str) -> None:
+ assert gen.format_type(annotation) == expected
+
+
+ ("annotation", "expected"),
+ [
+ (Literal["a", "b"], ["a", "b"]),
+ (Optional[Literal["a", "b"]], ["a", "b"]),
+ (Literal[1, True], [1, True]),
+ (_Colour, ["red", "blue"]),
+ (Union[int, Literal["auto"]], []), # spelled inline in the type instead
+ (Optional[int], []),
+ (str, []),
+ ],
+)
+def test_choices_are_listed_only_for_a_pure_choice(annotation: Any, expected: list) -> None:
+ found = gen.literal_choices(annotation)
+ assert found == expected and [type(v) for v in found] == [type(v) for v in expected]
+
+
+ ("value", "expected"),
+ [
+ (None, "null"),
+ (True, "true"),
+ (False, "false"),
+ (0, "0"),
+ (0.0002, "0.0002"),
+ (1e-05, "1e-05"),
+ (1.0, "1.0"),
+ ("auto", '"auto"'),
+ ("", '""'),
+ ("./output", '"./output"'),
+ ("caf\u00e9", '"caf\u00e9"'),
+ (["info_rm"], '["info_rm"]'),
+ (("a", 1), '["a", 1]'),
+ ({"r": 8, "alpha": 16}, '{"r": 8, "alpha": 16}'),
+ ({"b", "a"}, '["a", "b"]'),
+ (frozenset({2, 1}), "[1, 2]"),
+ (_Colour.blue, '"blue"'),
+ (Path("out") / "run", '"out/run"'),
+ ],
+)
+def test_literal_defaults_are_written_as_yaml_flow_values(value: Any, expected: str) -> None:
+ assert gen.format_default(value) == expected
+
+
+def somewhere(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The generator believes its home is ``/home/someone`` and its checkout
+ ``/srv/checkout/soup``, wherever the suite really runs."""
+ monkeypatch.setattr(gen, "_machine_markers", lambda: ("/home/someone", "/srv/checkout/soup"))
+
+
+ "value",
+ [
+ object(),
+ lambda: 1,
+ os.cpu_count,
+ "/home/someone",
+ "/home/someone/.soup/cache",
+ "/srv/checkout/soup/output",
+ "/SRV/CHECKOUT/SOUP/OUT",
+ "\\srv\\checkout\\soup\\out",
+ "sqlite:/home/someone/runs.db",
+ "C:\\Users\\someone\\models",
+ "d:/models",
+ ["fine", object()],
+ {"nested": {"deeper": object()}},
+ {("tuple", "key"): 1},
+ {1, "a"},
+ PurePosixPath("/home/someone/models"),
+ ],
+)
+def test_a_default_this_machine_computed_becomes_the_placeholder(
+ somewhere: None, value: Any
+) -> None:
+ assert gen.format_default(value) == gen.RUNTIME_DEFAULT == "(set at runtime)"
+
+
+ "value",
+ [
+ "ollama://model",
+ "https://example.com/v1",
+ "/v1/chat/completions",
+ "module.path:function",
+ "./home/someone/x", # the tail of a relative path
+ "data/srv/checkout/soup",
+ "/home/someone-else/x", # the head of a longer name
+ "/home/someoneelse",
+ ],
+)
+def test_a_constant_that_only_looks_like_a_path_stays_a_literal(
+ somewhere: None, value: str
+) -> None:
+ assert gen.format_default(value) == f'"{value}"'
+
+
+def test_a_shallow_working_directory_marks_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ """In a container the checkout is often ``/repo``, ``/work`` or ``/data``. As a marker
+ that would turn the real default ``./data/train.jsonl`` into a placeholder on that
+ machine only, and its pages would stop matching everybody else's."""
+ monkeypatch.setattr(os.path, "expanduser", lambda path: "/root")
+ monkeypatch.setattr(os, "getcwd", lambda: "/data")
+ monkeypatch.setattr(tempfile, "gettempdir", lambda: "/tmp")
+ assert gen._machine_markers() == ()
+ assert gen.format_default("./data/train.jsonl") == '"./data/train.jsonl"'
+ assert gen.format_default("/data/train.jsonl") == '"/data/train.jsonl"'
+
+ monkeypatch.setattr(os.path, "expanduser", lambda path: "/home/someone")
+ monkeypatch.setattr(os, "getcwd", lambda: "C:\\Work\\Soup\\")
+ assert gen._machine_markers() == ("/home/someone", "c:/work/soup")
+ assert gen.format_default("/home/someone/.cache") == gen.RUNTIME_DEFAULT
+
+
+ ("text", "expected"),
+ [
+ ("a | b", "a \\| b"),
+ ("line one\nline two\r\n three", "line one line two three"),
+ ("math | code | json_schema", "math \\| code \\| json_schema"),
+ ("registry://<id> | 'previous'", "registry://&lt;id> \\| 'previous'"),
+ ("`a|b` stays code, <c> does not", "`a\\|b` stays code, &lt;c> does not"),
+ ("``x <y>`` is code too", "``x <y>`` is code too"),
+ ("ratio * teacher + (1 - ratio) * x", "ratio \\* teacher + (1 - ratio) \\* x"),
+ ("snake_case_name stays", "snake_case_name stays"),
+ ("_private and __dunder__", "\\_private and \\_\\_dunder\\_\\_"),
+ ("bounded in ~[0,1] (a probability)", "bounded in \\~\\[0,1] (a probability)"),
+ ("a $x$ sum and R&D &lt;", "a \\$x\\$ sum and R&amp;D &amp;lt;"),
+ ("a lone ` backtick and a \\ slash", "a lone \\` backtick and a \\\\ slash"),
+ ("", ""),
+ ],
+)
+def test_cell_text_cannot_break_the_table(text: str, expected: str) -> None:
+ escaped = gen.escape_cell(text)
+ assert escaped == expected
+ assert "\n" not in escaped and len(_cells(f"| {escaped} |")) == 1
+
+
+ ("text", "expected"),
+ [
+ ("[bold]Train[/bold] a model", "Train a model"),
+ ("[dim]quiet[/]", "quiet"),
+ ("[bold red on white]loud[/bold red on white]", "loud"),
+ ("[link=https://example.com]docs[/link]", "docs"),
+ ("[#ff8800]orange[/#ff8800]", "orange"),
+ ('pip install "soup-cli\\[train]"', 'pip install "soup-cli[train]"'),
+ ("a literal \\\\[bold]x", "a literal \\x"),
+ ("cite as [doc-N] or [doc-id]", "cite as [doc-N] or [doc-id]"),
+ ("pip install soup-cli[sigstore]", "pip install soup-cli[sigstore]"),
+ ("range [0, 1] and [OPTIONS]", "range [0, 1] and [OPTIONS]"),
+ ("[/path/to/file]", "[/path/to/file]"),
+ ],
+)
+def test_rich_markup_is_stripped_and_bracketed_text_is_kept(text: str, expected: str) -> None:
+ assert gen.strip_rich_markup(text) == expected
+
+
+ ("text", "expected"),
+ [
+ ("streaming. (v0.42.0 Part B)", "streaming. (v0.42.0)"),
+ ("(v0.42.0 Part E; #759)", "(v0.42.0; #759)"),
+ ("the v0.62.0 Part A RAFT recipe", "the v0.62.0 RAFT recipe"),
+ ("v0.38.0 part g \u2014 storage", "v0.38.0 \u2014 storage"),
+ ("Part of the v0.42.0 work", "Part of the v0.42.0 work"),
+ ("spare Part B", "spare Part B"),
+ ],
+)
+def test_the_internal_phase_label_is_dropped_and_the_version_kept(text: str, expected: str) -> None:
+ assert gen.strip_internal_phase(text) == expected
+
+
+ ("heading", "expected"),
+ [
+ ("`training.lora`", "traininglora"),
+ ("`training.eval_gate`", "trainingeval_gate"),
+ ("Top-level keys", "top-level-keys"),
+ ("`soup data inspect`", "soup-data-inspect"),
+ ("`soup eval gate-install`", "soup-eval-gate-install"),
+ ("Telemetry (opt-in)", "telemetry-opt-in"),
+ ],
+)
+def test_heading_anchors_follow_githubs_slug(heading: str, expected: str) -> None:
+ assert gen.github_slug(heading) == expected == _slug(heading)
+
+
+def test_the_slug_drops_what_github_drops() -> None:
+ """Read off github.com on 2026-10-12: the heading ``Attaching energy + CO₂
+ (`--energy`)`` in ``docs/adapters-and-governance.md`` has this anchor. The subscript
+ is a number GitHub does not keep, which ``str.isalnum`` would."""
+ heading = "Attaching energy + CO₂ (`--energy`)"
+ assert gen.github_slug(heading) == "attaching-energy--co---energy"
+ assert gen.github_slug("Café déjà vu — v0.71.20") == "café-déjà-vu--v07120"
+
+
+def test_first_paragraph_only_is_the_command_summary() -> None:
+ assert gen.summary_line("One line.\n\nMore.\n\nsoup x --y") == "One line."
+ assert gen.summary_line("Wrapped\n summary.\n \n Later.") == "Wrapped summary."
+ assert gen.summary_line("Before the form feed.\fhidden") == "Before the form feed."
+ assert gen.summary_line(None) == ""
+
+
+# --------------------------------------------------------------------------
+# 3. import-light, and runnable as a script
+# --------------------------------------------------------------------------
+
+_PROBE = (
+ "import sys\n"
+ "{prelude}"
+ "from scripts import gen_reference_docs as gen\n"
+ "pages = gen.render_pages()\n"
+ "assert sorted(pages) == ['docs/cli-reference.md', 'docs/config-reference.md']\n"
+ "assert all(len(text) > 20000 for text in pages.values())\n"
+ "print(','.join(sorted(m for m in {heavy!r} if m in sys.modules)))\n"
+)
+
+
+def _heavy_after_rendering(prelude: str = "") -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [sys.executable, "-c", _PROBE.format(prelude=prelude, heavy=_HEAVY)],
+ capture_output=True,
+ text=True,
+ timeout=300,
+ cwd=_ROOT,
+ )
+
+
+def test_rendering_both_pages_does_not_import_torch() -> None:
+ proc = _heavy_after_rendering()
+ assert proc.returncode == 0, (proc.stdout, proc.stderr)
+ leaked = [name for name in proc.stdout.strip().split(",") if name]
+ assert leaked == [], f"rendering the reference pages imported {leaked}"
+
+
+def test_the_torch_probe_would_catch_a_regression() -> None:
+ proc = _heavy_after_rendering(prelude="import torch\n")
+ if proc.returncode != 0:
+ pytest.skip("torch not installed (light-core-only environment)")
+ assert "torch" in proc.stdout.strip().split(","), (proc.stdout, proc.stderr)
+
+
+def test_the_script_runs_from_any_directory(tmp_path: Path) -> None:
+ """``python scripts/gen_reference_docs.py`` is what a contributor types: no
+ ``scripts`` package on ``sys.path``, and the pages found from the script's path."""
+ script = str(_ROOT / "scripts" / "gen_reference_docs.py")
+ proc = subprocess.run(
+ [sys.executable, script, "--check-structure"],
+ capture_output=True,
+ text=True,
+ timeout=300,
+ cwd=tmp_path,
+ )
+ assert proc.returncode == 0, (proc.stdout, proc.stderr)
+ assert "state what the code does" in _plain(proc.stdout), (proc.stdout, proc.stderr)
+ assert list(tmp_path.iterdir()) == []