Independent Auditing of AI Agents. Run by human or the agent itself, to answer the most crucial question in the AI Agent Economy. Is the agent doing what is supposed to do? With iFixAi you can have this answer in less than 120 seconds.
Python agent-evaluationaiai-alignmentai-evaluationai-governanceai-safetyclidiagnostic-tooleu-ai-acthallucination-detectioniso-42001llm-evaluationllm-securitynist-ai-rmfowasp-llmprompt-injectionpythonresponsible-airisk-assessmentrisk-management
feat(cli): CLI — setup wizard, suites, config, insights (#44)
Sebabaian8fdc223f9396
diff --git a/.gitignore b/.gitignoreindex ed959a3..8853535 100644--- a/.gitignore+++ b/.gitignore@@ -57,6 +57,9 @@ logs/.DS_StoreThumbs.db+# ─── Local run config (contains user choices; never commit) ───────────+ifixai.yaml+# ─── Test / test outputs (regenerated locally) ────────────────────────ifixai-results/ifixai-results-full/diff --git a/README.md b/README.mdindex 7347d58..8cfd4f8 100644--- a/README.md+++ b/README.md@@ -9,10 +9,9 @@<p align="center"><a href="#quick-start">Quick start</a> •- <a href="#two-ways-to-run-it">Two ways to run</a> •+ <a href="#three-ways-to-run">Three ways to run</a> •<a href="#test-your-own-agent">Test your agent</a> •<a href="#what-you-get-back">Scoring</a> •- <a href="#in-the-wild">In the wild</a> •<a href="docs/">Docs</a> •<a href="CONTRIBUTING.md">Contributing</a></p>@@ -30,9 +29,9 @@</p><p align="center">- <img src="docs/assets/ifixai-demo.gif" alt="iFixAi demo" width="720" />+ <img src="docs/assets/scorecard-screenshot.png" alt="iFixAi CLI scorecard" width="900" /><br/>- <em>Recorded from a custom client build. The open-source CLI runs the same diagnostic with different presentation.</em>+ <em>The scorecard from one <code>ifixai run</code>: an A–F grade, the five scored core pillars, and a free preview of the premium tier.</em></p>---@@ -63,32 +62,61 @@ is judged by independent providers rather than by itself, one in Standard mode aof two or more in Full mode. Every run also writes a manifest of all its inputs, so the resultcan be audited and replayed.-## Two ways to run it+## Three ways to run-There are two ways to run iFixAi, and both run the same diagnostic underneath: the-command-line tool (the CLI) or the Claude Code plugin. Either one tests any model and lets-you choose who grades it. The difference is who drives: you script the CLI yourself, or let-Claude operate the plugin for you.+All three run the same diagnostic underneath. The difference is how you configure and drive it.-| | **CLI** (`pip install`) | **Claude Code plugin** |-|---|---|---|-| **How you drive it** | you write the **fixture** (the config describing your agent) and CLI flags; scriptable, CI-friendly | Claude is the operator: it discovers your setup, builds the fixture, runs it, and explains the scorecard |-| **What you can test** | any provider, or your agent's real endpoint | any provider (Anthropic, OpenAI, Gemini, Azure, Bedrock, …); Claude only guides |-| **Who grades it** | any judge: self, one independent vendor, or a panel | same: self, one independent judge, or a cross-vendor panel |-| **Output** | JSON + markdown/HTML reports | interactive results artifact (+ JSON source of truth; static-report fallback) |-| **Setup** | `pip install` + the provider key(s) you'll test | keys in your Claude Code `settings.json` env; the engine self-provisions |-| **Best for** | CI, automation, audit-ready batch runs | a guided, explained run with discovery and an interactive scorecard |--**Plugin:** Claude runs the diagnostic for you. Open this repo in [Claude Code](https://claude.com/claude-code) and say-*"run iFixAi on my setup."* Claude reads your agent's config, shows the test fixture-it builds and names the cost before billing, runs the diagnostic on the model(s)-and judge(s) you choose, then explains the scorecard. The rest of this page covers the CLI.+| | **CLI — guided wizard** | **CLI — explicit flags** | **Claude Code plugin** |+|---|---|---|---|+| **How you drive it** | `ifixai setup` once → `ifixai run` zero-flag every time; config saved to `ifixai.yaml` | pass every option as a CLI flag; fully scriptable | Claude is the operator: discovers your setup, builds the fixture, runs it, and explains the scorecard |+| **Best for** | first-time users, fast repeatable runs, team onboarding | CI, automation, audit-ready scripted batches | a guided, explained run with an interactive scorecard |+| **Setup** | `pip install "ifixai[<provider>]"` + `ifixai setup` | `pip install "ifixai[<provider>]"` + export keys | add keys to Claude Code `settings.json`; engine self-provisions |+| **Keys** | auto-detected by wizard; stored as env-var name in `ifixai.yaml`, never the secret itself | `--api-key` flag or env var | configured in Claude Code settings |+| **What you test** | any provider, or your agent's real endpoint | same | same |+| **Who grades it** | self, one independent vendor, or a multi-judge ensemble | same | same |+| **Output** | JSON + Markdown reports + rich terminal scorecard | same | interactive results artifact (+ JSON source of truth; static-report fallback) |+| **Suite** | pick with arrow keys in the wizard | `--suite smoke\|strategic\|core\|extended\|all` | you pick the preset (quick · standard · full) |## Quick start-Now try it yourself. In three commands you install iFixAi, check that it runs, then grade a-real model. The grade you get back is citable because a different vendor's AI does the grading,-not the agent judging itself. Full walkthrough: **[docs/get-started.md](docs/get-started.md)**.+Now try it yourself. The guided wizard gets you running with zero flags from the second run+onward; the Claude Code plugin lets Claude drive the whole thing; or use explicit flags for full+control and CI. Full walkthrough: **[docs/get-started.md](docs/get-started.md)**.++### Guided wizard (recommended)++```bash+pip install "ifixai[openai]" # or anthropic, gemini, etc. — install the provider extra you'll test+ifixai setup # arrow-key wizard: pick provider, model, judge, suite → writes ifixai.yaml+ifixai run # no flags needed from now on+```++`ifixai setup` detects API keys already in your environment and surfaces them at the top of+each prompt. No key found? The wizard tells you which env var to export; if it's still missing+when you run, you'll be prompted for it before the first API call. After setup, `ifixai run`+reads everything from `ifixai.yaml` — no flags, no copy-pasting keys.++### Claude Code plugin++Let Claude run the whole thing for you, with no flags or fixtures to write. If you already have+[Claude Code](https://claude.com/claude-code), from inside it:++1. **Install it.** Add this repo as a plugin marketplace, then install the plugin:++ ```+ /plugin marketplace add ifixai-ai/iFixAi+ /plugin install ifixai@ifixai-ai+ ```++ Restart Claude Code or run `/reload-plugins` if it doesn't show up right away.++2. **Run it.** Just ask Claude in plain English (*"run iFixAi on my setup"*), or type the slash command **`/ifixai:ifixai`**.++Claude then reads your agent's config, shows the test fixture it builds and names the cost before+anything is billed, runs the diagnostic on the model(s) and judge(s) you pick, then walks you+through the scorecard.++### Explicit flags```bash# 1. Install the CLI + the extra for the provider you'll test@@ -115,8 +143,26 @@ Reports land in `./ifixai-results/` as JSON **and** Markdown. Without a second k`--eval-mode self` to run as a smoke test (the grade still prints, but it's flagged asself-judged, not a result you can cite). Pinning the judge, Full-mode ensembles, and the eval modes:**[docs/running.md](docs/running.md)**. Other providers (OpenAI, OpenRouter, Gemini,-Azure, Bedrock, Hugging Face, HTTP, LangChain) install the matching extra and follow the-same steps: **[docs/providers.md](docs/providers.md)**.+Azure, Bedrock, Hugging Face) install the matching extra and follow the same steps; the+HTTP and LangChain adapters need no provider extra: **[docs/providers.md](docs/providers.md)**.++### Suite options++| Suite | Tests | Use when |+|---|---|---|+| `smoke` | 3 | just checking the pipeline works |+| `strategic` | 8 | quick read on the riskiest spots |+| `core` | 32 | the graded five-pillar scorecard |+| `extended` | 13 | frontier risk signal (5 graded, 8 exploratory) |+| `all` | 45 | everything (the default when you pass no `--suite`) |++Four themes (`security`, `reliability`, `compliance`, `frontier`) also work as `--suite` values; run `ifixai list suites` to browse them all.++```bash+ifixai run --provider openai --suite strategic # quick 8-test read+ifixai run --provider openai --suite core # the graded scorecard+ifixai list suites # browse all suites and themes+```### Test your own agent@@ -133,6 +179,23 @@ score, instead of marking them `insufficient_evidence` (it couldn't see enough oagent to judge; these are reported but don't count for or against your grade). Fullwalkthrough with the model-vs-agent coverage map: **[docs/testing-your-agent.md](docs/testing-your-agent.md)**.+## Reusable config++`ifixai setup` writes `ifixai.yaml`; `ifixai run` layers it under any explicit flag (flag > config > env > default). It stores the key env-var name, never the secret:++```yaml+provider: openai+model: gpt-4o+api_key_env: OPENAI_API_KEY+suite: core+judges:+ - provider: anthropic+ model: claude-3-5-sonnet-latest+```++`ifixai setup` also records `fixture`, `mode`, and `eval_mode` (trimmed here for brevity).+Keep `ifixai.yaml` out of version control — it is git-ignored by default.+## What you get backA letter grade with the breakdown behind it. iFixAi groups the 45 inspections into **16 categories**, five core pillars plus eleven premium. The five core pillars:@@ -159,20 +222,6 @@ can't skew comparisons.Full math and weights: **[docs/scoring.md](docs/scoring.md)**. The full `B01`–`B32` → pillarmapping and every premium category: **[docs/inspection_categories.md](docs/inspection_categories.md)**.-## In the wild--Three real open-source AI systems, graded end-to-end: two F's and a D. Each ran against a fixture-that describes its real setup (tools, rules, permissions), graded by a panel of judges from different vendors.--| System | Upstream model | Score | Grade | Key finding |-|---|---|---|---|---|-| [Hermes Agent](case_studies/hermes-gpt-4o-mini/SCORECARD.md) (Nous Research) | `gpt-4o-mini` | **33.9%** | **F** | Capable model, but nothing stops bad actions; 23 of 32 inspections failed. [deep dive](https://ifixai.ai/docs/diagnostics/hermes) |-| [OpenClaw](case_studies/openclaw-haiku/SCORECARD.md) v2026.5.4 | `claude-3.5-haiku` | **60.0%** | **D** | Follows the rules when asked plainly; caves when the request is dressed up. [deep dive](https://ifixai.ai/docs/diagnostics/openclaw) |-| [Open WebUI](case_studies/openwebui-sonnet/SCORECARD.md) v0.9.5 | `claude-sonnet-4.6` | **11.3%** | **F** | Nothing passes once you strip the scaffolding that faked compliance. [deep dive](https://ifixai.ai/docs/diagnostics/openwebui) |--The takeaway from Hermes is the clearest: a capable model with nothing enforcing its rules-is not safe. All scorecards live in **[case_studies/](case_studies/)**.-## DocumentationDocs are sorted by what you came to do. Start in **[docs/](docs/)**:@@ -184,8 +233,7 @@ Docs are sorted by what you came to do. Start in **[docs/](docs/)**:## Contributing-Issues and PRs welcome. See **[CONTRIBUTING.md](CONTRIBUTING.md)** (`pip install -e ".[dev]"`,-then `ruff`, `bandit`, `pytest`). Good first issues are+Issues and PRs welcome. See **[CONTRIBUTING.md](CONTRIBUTING.md)**. Good first issues are[labelled here](https://github.com/ifixai-ai/iFixAi/issues?q=is%3Aopen+label%3A%22good+first+issue%22).## Contactdiff --git a/docs/assets/scorecard-screenshot.png b/docs/assets/scorecard-screenshot.pngnew file mode 100644index 0000000..74f1578Binary files /dev/null and b/docs/assets/scorecard-screenshot.png differdiff --git a/ifixai/cli/config_file.py b/ifixai/cli/config_file.pynew file mode 100644index 0000000..7c1c492--- /dev/null+++ b/ifixai/cli/config_file.py@@ -0,0 +1,67 @@+"""Reusable run configuration persisted as ``ifixai.yaml``."""++from __future__ import annotations++from pathlib import Path++import yaml+from pydantic import BaseModel, ValidationError++CONFIG_FILENAME = "ifixai.yaml"+++class JudgeSpec(BaseModel):+ provider: str+ model: str | None = None+++class RunConfig(BaseModel):+ """Persisted defaults for ``ifixai run`` (every field optional)."""++ provider: str | None = None+ model: str | None = None+ api_key_env: str | None = None+ endpoint: str | None = None+ fixture: str | None = None+ suite: str | None = None+ mode: str | None = None+ eval_mode: str | None = None+ judges: list[JudgeSpec] = []+ output: str | None = None+ format: str | None = None+ timeout: int | None = None+ name: str | None = None++ def to_yaml(self) -> str:+ data = self.model_dump(exclude_none=True)+ if not self.judges:+ data.pop("judges", None)+ return yaml.safe_dump(data, sort_keys=False, default_flow_style=False)+++def config_path(start_dir: Path | None = None) -> Path:+ return (start_dir or Path.cwd()) / CONFIG_FILENAME+++def load_config(start_dir: Path | None = None) -> RunConfig | None:+ """Load ``ifixai.yaml`` from ``start_dir`` (cwd by default), or None."""+ path = config_path(start_dir)+ if not path.exists():+ return None+ try:+ raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}+ except yaml.YAMLError as exc:+ raise ValueError(f"{CONFIG_FILENAME} is not valid YAML: {exc}") from exc+ if not isinstance(raw, dict):+ raise ValueError(f"{CONFIG_FILENAME} must contain a mapping at the top level.")+ try:+ return RunConfig(**raw)+ except ValidationError as exc:+ raise ValueError(f"{CONFIG_FILENAME} has invalid fields:\n{exc}") from exc+++def write_config(config: RunConfig, start_dir: Path | None = None) -> Path:+ """Write ``config`` to ``ifixai.yaml`` and return the path."""+ path = config_path(start_dir)+ path.write_text(config.to_yaml(), encoding="utf-8")+ return pathdiff --git a/ifixai/cli/init.py b/ifixai/cli/init.pyindex bb75b1e..14de8da 100644--- a/ifixai/cli/init.py+++ b/ifixai/cli/init.py@@ -27,6 +27,41 @@ def detect_available_providers() -> list[tuple[str, str]]:]+def load_dotenv_file(path: "Path | None" = None) -> list[str]:+ """Load ``KEY=VALUE`` pairs from a ``.env`` file (the cwd's by default) into+ ``os.environ`` without overriding variables already set, returning the names of+ the keys it added.++ Real environment variables always win, so anything you exported in the shell is+ never clobbered. The parser skips blank lines and ``#`` comments, tolerates a+ leading ``export``, and strips surrounding single/double quotes."""+ env_path = path or (Path.cwd() / ".env")+ if not env_path.is_file():+ return []+ try:+ text = env_path.read_text(encoding="utf-8")+ except OSError:+ return []+ loaded: list[str] = []+ for raw in text.splitlines():+ line = raw.strip()+ if not line or line.startswith("#"):+ continue+ if line.startswith("export "):+ line = line[len("export ") :].lstrip()+ key, sep, value = line.partition("=")+ if not sep:+ continue+ key = key.strip()+ value = value.strip()+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):+ value = value[1:-1]+ if key and key not in os.environ:+ os.environ[key] = value+ loaded.append(key)+ return loaded++@click.command()@click.option("--non-interactive",@@ -68,7 +103,10 @@ def init(non_interactive: bool) -> None:)click.echo()- click.echo(click.style("Suggested first run:", bold=True))+ click.echo(click.style("Recommended: guided setup (writes ifixai.yaml):", bold=True))+ click.echo(" ifixai setup")+ click.echo()+ click.echo(click.style("Or run directly:", bold=True))click.echo(f" {suggested_command}")click.echo()click.echo(diff --git a/ifixai/cli/list_cmd.py b/ifixai/cli/list_cmd.pyindex 4c849c2..016cda8 100644--- a/ifixai/cli/list_cmd.py+++ b/ifixai/cli/list_cmd.py@@ -1,7 +1,14 @@import clickfrom ifixai.api import list_tests as get_tests, list_fixtures as get_fixture_names+from ifixai.cli import uifrom ifixai.core.fixture_loader import load_fixture+from ifixai.harness.registry import (+ CATEGORIES,+ CATEGORY_DESCRIPTIONS,+ get_tests_by_category,+ suite_catalog,+)@click.group("list")@@ -50,6 +57,71 @@ def list_tests(verbose: bool) -> None:click.echo()+@list_group.command("suites")+def list_suites() -> None:+ """List the named suites accepted by `ifixai run --suite`."""+ rows = suite_catalog()+ table_rows = [+ [r["name"], r["kind"], str(r["count"]), r["description"]] for r in rows+ ]++ if not ui.table(+ "iFixAi Suites", ["Suite", "Kind", "Tests", "Description"], table_rows+ ):+ click.echo()+ click.echo(click.style("ifixai Suites", bold=True))+ click.echo()+ header = f"{'Suite':<14} {'Kind':<8} {'Tests':>5} Description"+ click.echo(header)+ click.echo("-" * len(header))+ last_kind = None+ for row in rows:+ if last_kind is not None and row["kind"] != last_kind:+ click.echo()+ last_kind = row["kind"]+ click.echo(+ f"{row['name']:<14} {row['kind']:<8} "+ f"{row['count']:>5} {row['description']}"+ )++ click.echo()+ click.echo(click.style("Run a suite: ifixai run --provider <p> --suite core", dim=True))+ click.echo()+++@list_group.command("categories")+def list_categories() -> None:+ """List the failure categories accepted by `ifixai run --category`."""+ rows = []+ for category_id in sorted(CATEGORIES):+ category = CATEGORIES[category_id]+ members = get_tests_by_category(category_id)+ description = CATEGORY_DESCRIPTIONS.get(category_id, "")+ tail = description.split("—", 1)[1].strip() if "—" in description else ""+ rows.append([category.value, str(len(members)), tail])++ if not ui.table(+ "iFixAi Categories", ["Category", "Tests", "Description"], rows+ ):+ click.echo()+ click.echo(click.style("ifixai Categories", bold=True))+ click.echo()+ header = f"{'Category':<22} {'Tests':>5} Description"+ click.echo(header)+ click.echo("-" * len(header))+ for name, count, tail in rows:+ click.echo(f"{name:<22} {count:>5} {tail}")++ click.echo()+ click.echo(+ click.style(+ "Run a category: ifixai run --provider <p> --category MANIPULATION",+ dim=True,+ )+ )+ click.echo()++@list_group.command("fixtures")def list_fixtures() -> None:diff --git a/ifixai/cli/main.py b/ifixai/cli/main.pyindex 0d872a5..5b68032 100644--- a/ifixai/cli/main.py+++ b/ifixai/cli/main.py@@ -1,10 +1,13 @@+import logging+import osimport sysimport clickfrom ifixai._version import VERSION-from ifixai.cli.init import init+from ifixai.cli.init import init, load_dotenv_filefrom ifixai.cli.run import run+from ifixai.cli.setup_cmd import setupfrom ifixai.cli.list_cmd import list_groupfrom ifixai.cli.validate import validatefrom ifixai.cli.compare import compare@@ -16,6 +19,7 @@ def ifixai_cli() -> None:pass+ifixai_cli.add_command(setup)ifixai_cli.add_command(init)ifixai_cli.add_command(run)ifixai_cli.add_command(list_group, name="list")@@ -43,8 +47,43 @@ def _ensure_utf8_stdout() -> None:sys.stderr = _fix(sys.stderr)+class _CleanFormatter(logging.Formatter):+ """One-line log formatter that hides Python tracebacks unless in debug mode."""++ def __init__(self, show_tracebacks: bool) -> None:+ super().__init__("%(message)s")+ self._show_tracebacks = show_tracebacks++ def format(self, record: logging.LogRecord) -> str:+ if not self._show_tracebacks and (record.exc_info or record.stack_info):+ record = logging.makeLogRecord(record.__dict__)+ record.exc_info = None+ record.exc_text = None+ record.stack_info = None+ return super().format(record)+++def _configure_cli_logging() -> None:+ """Install a clean console handler so runs aren't buried in tracebacks."""+ debug = bool(os.environ.get("IFIXAI_DEBUG") or os.environ.get("IFIXAI_VERBOSE"))+ handler = logging.StreamHandler(sys.stderr)+ handler.setFormatter(_CleanFormatter(show_tracebacks=debug))+ root = logging.getLogger()+ root.handlers[:] = [handler]+ root.setLevel(logging.DEBUG if debug else logging.WARNING)++def main() -> None:_ensure_utf8_stdout()+ loaded = load_dotenv_file()+ _configure_cli_logging()+ if loaded:+ click.echo(+ click.style(+ f"Loaded {len(loaded)} key(s) from .env: {', '.join(loaded)}", dim=True+ ),+ err=True,+ )ifixai_cli()diff --git a/ifixai/cli/model_catalog.py b/ifixai/cli/model_catalog.pynew file mode 100644index 0000000..474065c--- /dev/null+++ b/ifixai/cli/model_catalog.py@@ -0,0 +1,66 @@+"""Curated model suggestions per provider for the setup wizard."""++from __future__ import annotations++DEFAULT_MODEL: dict[str, str] = {+ "openrouter": "openai/gpt-4o",+ "openai": "gpt-4o",+ "anthropic": "claude-3-5-sonnet-latest",+ "gemini": "gemini-2.0-flash",+ "azure": "gpt-4o",+ "bedrock": "anthropic.claude-3-5-sonnet-20241022-v2:0",+ "huggingface": "meta-llama/Llama-3.3-70B-Instruct",+}++MODEL_SUGGESTIONS: dict[str, list[tuple[str, str]]] = {+ "openrouter": [+ ("anthropic/claude-sonnet-4.5", "Anthropic Claude Sonnet 4.5 — strong reasoning & safety"),+ ("anthropic/claude-opus-4.1", "Anthropic Claude Opus 4.1 — most capable, pricier"),+ ("anthropic/claude-haiku-4.5", "Anthropic Claude Haiku 4.5 — fast & cheap"),+ ("openai/gpt-5", "OpenAI GPT-5 — flagship general reasoning"),+ ("openai/gpt-5-mini", "OpenAI GPT-5 Mini — cheaper & faster"),+ ("openai/gpt-4.1", "OpenAI GPT-4.1 — strong, widely available"),+ ("openai/o4-mini", "OpenAI o4 Mini — reasoning-optimized, low cost"),+ ("google/gemini-2.5-pro", "Google Gemini 2.5 Pro — large context, strong reasoning"),+ ("google/gemini-2.5-flash", "Google Gemini 2.5 Flash — fast and inexpensive"),+ ("deepseek/deepseek-r1", "DeepSeek R1 — open reasoning model, very low cost"),+ ("deepseek/deepseek-chat-v3.1", "DeepSeek V3.1 — strong, very low cost"),+ ("meta-llama/llama-4-maverick", "Meta Llama 4 Maverick — open-weights flagship"),+ ("meta-llama/llama-3.3-70b-instruct", "Meta Llama 3.3 70B — open-weights, good value"),+ ],+ "openai": [+ ("gpt-4o", "Flagship — strong general reasoning"),+ ("gpt-4o-mini", "Cheaper & faster"),+ ("o3-mini", "Reasoning-optimized, cost-effective"),+ ("gpt-4.1", "Latest large model"),+ ],+ "anthropic": [+ ("claude-3-5-sonnet-latest", "Balanced reasoning & speed"),+ ("claude-3-7-sonnet-latest", "Newer Sonnet"),+ ("claude-3-5-haiku-latest", "Fastest & cheapest Claude"),+ ],+ "gemini": [+ ("gemini-2.0-flash", "Fast and inexpensive"),+ ("gemini-1.5-pro", "Larger context, stronger reasoning"),+ ],+ "azure": [+ ("gpt-4o", "Your Azure deployment name for GPT-4o"),+ ("gpt-4o-mini", "Cheaper/faster deployment"),+ ],+ "bedrock": [+ ("anthropic.claude-3-5-sonnet-20241022-v2:0", "Claude 3.5 Sonnet on Bedrock"),+ ("anthropic.claude-3-5-haiku-20241022-v1:0", "Claude 3.5 Haiku on Bedrock"),+ ],+ "huggingface": [+ ("meta-llama/Llama-3.3-70B-Instruct", "Open-weights Llama 3.3"),+ ("mistralai/Mistral-7B-Instruct-v0.3", "Small, fast Mistral"),+ ],+}+++def default_model(provider: str) -> str | None:+ return DEFAULT_MODEL.get(provider.lower())+++def suggestions(provider: str) -> list[tuple[str, str]]:+ return MODEL_SUGGESTIONS.get(provider.lower(), [])diff --git a/ifixai/cli/orchestrator.py b/ifixai/cli/orchestrator.pyindex a6000c6..d3728fe 100644--- a/ifixai/cli/orchestrator.py+++ b/ifixai/cli/orchestrator.py@@ -2,7 +2,6 @@ import ioimport osimport sysimport threading-from collections import Counterimport click@@ -210,6 +209,8 @@ def _print_error_summary(result: TestRunResult) -> None:Listing the affected test IDs lets operators see exactly whichbenchmarks did not execute."""+ from ifixai.providers.base import friendly_provider_message+errored = [br for br in result.test_results if br.status == TestStatus.ERROR]if not errored:return@@ -224,52 +225,21 @@ def _print_error_summary(result: TestRunResult) -> None:bold=True,))++ grouped: dict[str, list[str]] = {}for br in errored:reason = br.error_message or br.error or "no detail available"- click.echo(click.style(f" - {br.test_id}: {reason}", fg="red"))---def _print_inconclusive_summary(result: TestRunResult) -> None:- inconclusive = [- br for br in result.test_results if br.status == TestStatus.INCONCLUSIVE- ]-- if not inconclusive:- click.echo(click.style("Inconclusive: 0 tests.", fg="green"))- return-- by_category: Counter[str] = Counter(br.category.value for br in inconclusive)- breakdown = ", ".join(f"{cat}={n}" for cat, n in by_category.most_common())- click.echo(- click.style(- f"Inconclusive: {len(inconclusive)} tests ({breakdown})",- fg="yellow",- )- )---def _print_insufficient_evidence_summary(result: TestRunResult) -> None:- insufficient = [br for br in result.test_results if br.insufficient_evidence]- total = len(result.test_results)- if not insufficient:- click.echo(- click.style(- f"All {total} tests produced sufficient evidence to be scored.",- fg="green",- )- )- return- inspection_ids = ", ".join(sorted(br.test_id for br in insufficient))- click.echo(- click.style(- f"{len(insufficient)} out of {total} tests had insufficient evidence "- f"to be scored ({inspection_ids}). The remaining tests were scored but "- f"may still be below threshold -- see the per-category bars above. "- f"Wrap your provider in a governance layer or run with ≥2 provider "- f"credentials. See docs/methodology.md.",- fg="yellow",- )- )+ grouped.setdefault(reason, []).append(br.test_id)++ for reason, ids in grouped.items():+ friendly = friendly_provider_message(reason)+ affected = ", ".join(sorted(ids))+ if friendly is not None:+ click.echo(click.style(f" {friendly}", fg="yellow", bold=True))+ click.echo(click.style(f" Affected: {affected}", fg="red"))+ click.echo(click.style(f" Details: {reason}", dim=True))+ else:+ click.echo(click.style(f" - {affected}: {reason}", fg="red"))# Basic 16-color ANSI foreground codes only. xterm-256 (`38;5;`) and truecolordiff --git a/ifixai/cli/reports.py b/ifixai/cli/reports.pyindex 42acbfb..4aca164 100644--- a/ifixai/cli/reports.py+++ b/ifixai/cli/reports.py@@ -6,6 +6,7 @@ import clickfrom ifixai.reporting.scorecard import (generate_json_report,generate_markdown_report,+ generate_summary_report,)from ifixai.core.types import TestRunResult@@ -28,14 +29,18 @@ def save_reports(fixture_slug = _slugify(result.fixture_name)base_name = f"ifixai-{system_slug}-{fixture_slug}"- click.echo(click.style("Access your Full Report here:", bold=True))-- if report_format in ("json", "both"):- json_path = out_path / f"{base_name}.json"- json_path.write_text(generate_json_report(result), encoding="utf-8")- click.echo(f" JSON report: {json_path}")+ click.echo(click.style("Reports saved:", bold=True))if report_format in ("markdown", "both"):+ summary_path = out_path / f"{base_name}-summary.md"+ summary_path.write_text(generate_summary_report(result), encoding="utf-8")+ click.echo(f" Summary (start here): {summary_path}")+md_path = out_path / f"{base_name}.md"md_path.write_text(generate_markdown_report(result), encoding="utf-8")- click.echo(f" Markdown report: {md_path}")+ click.echo(f" Full report: {md_path}")++ if report_format in ("json", "both"):+ json_path = out_path / f"{base_name}.json"+ json_path.write_text(generate_json_report(result), encoding="utf-8")+ click.echo(f" JSON (machine): {json_path}")diff --git a/ifixai/cli/run.py b/ifixai/cli/run.pyindex 979d32a..c5cea21 100644--- a/ifixai/cli/run.py+++ b/ifixai/cli/run.py@@ -15,9 +15,11 @@ from pathlib import Pathimport clickfrom ifixai import __version__ as IFIXAI_VERSION+from ifixai.cli import uifrom ifixai.cli._branding import (print_startup_banner,)+from ifixai.cli.config_file import CONFIG_FILENAME, load_configfrom ifixai.cli._imecore_prompt import print_imecore_conclusionfrom ifixai.cli.orchestrator import (_build_judge_config,@@ -25,8 +27,6 @@ from ifixai.cli.orchestrator import (_lookup_env_api_key,_print_category_summary,_print_error_summary,- _print_inconclusive_summary,- _print_insufficient_evidence_summary,_resolve_judge_label,_resolve_standard_eval_mode,execute_tests,@@ -59,6 +59,7 @@ from ifixai.harness.registry import (SPEC_BY_ID,resolve_category_test_ids,)+from ifixai.harness.suites import SUITE_NAMES, resolve_suitefrom ifixai.utils.fixture_digest import compute_fixture_digestfrom ifixai.utils.rubric_digest import compute_rubric_digests_for_tests_layoutfrom ifixai.core.grounding import GroundingMode, compose_system_prompt@@ -161,6 +162,17 @@ def _resolve_concurrency(flag_value: int | None, no_parallel: bool) -> int:return DEFAULT_CONCURRENCY+def _cfg_value(ctx: click.Context, name: str, current, cfg_value):+ """Return cfg_value when the flag was left at its default, else current."""+ from click.core import ParameterSource++ if cfg_value is None:+ return current+ if ctx.get_parameter_source(name) == ParameterSource.DEFAULT:+ return cfg_value+ return current++def _format_elapsed(seconds: float) -> str:"""Human-readable wall-clock duration: ``1h 23m 4s`` / ``2m 5s`` / ``18s``.@@ -182,16 +194,20 @@ def _describe_filter(strategic: bool,test: tuple[str, ...],categories: tuple[str, ...],+ suite: str | None = None,) -> str:"""Human-readable summary of which tests the run will execute.``test`` is the already-merged selection (explicit -b IDs plus any IDs- expanded from ``categories``); ``categories`` is the raw, unexpanded set- of category names so the label can name them.+ expanded from ``suite`` and ``categories``); ``categories`` and ``suite``+ are the raw, unexpanded selectors so the label can name them."""+ if suite and not categories:+ return f"suite '{suite.strip().lower()}' -> {len(test)} tests"if categories:names = ", ".join(name.strip().upper() for name in categories)- return f"categories ({names}) -> {len(test)} tests"+ prefix = f"suite '{suite.strip().lower()}' + " if suite else ""+ return f"{prefix}categories ({names}) -> {len(test)} tests"if strategic:return "strategic (top 8)"if test:@@ -306,6 +322,14 @@ def _print_concurrency_banner(resolved: int) -> None:"select several categories; combine with -b to add individual tests. ""Takes precedence over --strategic.",)+ "--suite",+ default=None,+ help="Run a named suite. Tiers: smoke, strategic, core (32 graded), "+ "extended (13 frontier), all. Themes: security, reliability, compliance, "+ "frontier. Folds into the selection like --category; combine with -b/-c to "+ "add more. Run `ifixai list suites` to browse.",+)@click.option("--output","-o",@@ -558,7 +582,9 @@ def _print_concurrency_banner(resolved: int) -> None:help="Suppress the startup banner and the post-run iMe Core conclusion. ""Stdout still contains scores so CI gates keep working.",)[email protected]_contextdef run(+ ctx: click.Context,provider: str | None,api_key: str | None,fixture: str,@@ -569,6 +595,7 @@ def run(strategic: bool,test: tuple[str, ...],categories: tuple[str, ...],+ suite: str | None,output: str,report_format: str,timeout: int,@@ -601,6 +628,55 @@ def run() -> None:"""Run ifixai against a target AI assistant."""run_start_monotonic = time.monotonic()++ try:+ config_obj = load_config()+ except ValueError as exc:+ click.echo(click.style(f"Config error: {exc}", fg="red"), err=True)+ sys.exit(1)+ if config_obj is not None:+ from click.core import ParameterSource++ provider = _cfg_value(ctx, "provider", provider, config_obj.provider)+ model = _cfg_value(ctx, "model", model, config_obj.model)+ fixture = _cfg_value(ctx, "fixture", fixture, config_obj.fixture)+ explicit_selector = (+ strategic+ or bool(test)+ or bool(categories)+ or ctx.get_parameter_source("suite") != ParameterSource.DEFAULT+ )+ if config_obj.suite and not explicit_selector:+ suite = config_obj.suite+ run_mode = _cfg_value(ctx, "run_mode", run_mode, config_obj.mode)+ eval_mode = _cfg_value(ctx, "eval_mode", eval_mode, config_obj.eval_mode)+ output = _cfg_value(ctx, "output", output, config_obj.output)+ report_format = _cfg_value(+ ctx, "report_format", report_format, config_obj.format+ )+ timeout = _cfg_value(ctx, "timeout", timeout, config_obj.timeout)+ endpoint = _cfg_value(ctx, "endpoint", endpoint, config_obj.endpoint)+ system_name = _cfg_value(ctx, "system_name", system_name, config_obj.name)+ if api_key is None and config_obj.api_key_env:+ api_key = os.environ.get(config_obj.api_key_env)+ if config_obj.judges and (+ ctx.get_parameter_source("judge_provider") == ParameterSource.DEFAULT+ ):+ judge_provider = tuple(j.provider for j in config_obj.judges)+ if any(j.model for j in config_obj.judges):+ judge_model = tuple((j.model or "") for j in config_obj.judges)+ resolved_judge_keys: list[str] = []+ for j in config_obj.judges:+ if j.provider == provider and api_key:+ resolved_judge_keys.append(api_key)+ else:+ resolved_judge_keys.append(_lookup_env_api_key(j.provider) or "")+ judge_api_key = tuple(resolved_judge_keys)+ if not quiet:+ click.echo(+ click.style(f"Using config: {CONFIG_FILENAME}", fg="cyan"), err=True+ )+if run_nonce is not None and not is_valid_run_nonce(run_nonce):raise click.BadParameter(f"--run-nonce must be 16 lowercase hex chars; got {run_nonce!r}",@@ -737,10 +813,29 @@ def run(model = interactive["model"]if api_key is None:- api_key = click.prompt("API key", hide_input=True)+ api_key = click.prompt(+ f"API key for the system under test ({provider})", hide_input=True+ )resolved_name = system_name or provider+ if suite:+ suite_resolution = resolve_suite(suite)+ if suite_resolution["unknown"]:+ click.echo(+ click.style(+ f"Error: unknown suite '{suite}'. "+ f"Available: {', '.join(SUITE_NAMES)}",+ fg="red",+ )+ )+ sys.exit(1)+ test = tuple(+ dict.fromkeys(+ [*(tid.upper() for tid in test), *suite_resolution["test_ids"]]+ )+ )+if categories:resolution = resolve_category_test_ids(categories)if resolution["unknown"]:@@ -1055,7 +1150,7 @@ def run(click.echo(click.style("ifixai Run", bold=True))click.echo(f" Provider: {provider}")click.echo(f" Fixture: {fixture}")- click.echo(f" Filter: {_describe_filter(strategic, test, categories)}")+ click.echo(f" Filter: {_describe_filter(strategic, test, categories, suite)}")click.echo(f" Mode: {run_mode}")click.echo(f" Judge: {judge_label}")click.echo(f" Timeout: {timeout}s")@@ -1196,41 +1291,44 @@ def run(" — score reproducibility increased.")- _print_category_summary(result)+ if not ui.render_scorecard(result):+ _print_category_summary(result)- click.echo()- click.echo(click.style("Results", bold=True))- scored_categories = sum(1 for cs in result.category_scores if cs.score is not None)- total_categories = len(result.category_scores)- coverage_suffix = (- f" ({scored_categories}/{total_categories} categories scored)"- if 0 < scored_categories < total_categories- else ""- )- score_label = "Partial Score:" if coverage_suffix else "Overall Score:"- verdict = (- click.style("PASS", fg="green")- if result.passed- else click.style("FAIL", fg="red")- )- click.echo(f" {score_label} {result.overall_score:.1%}{coverage_suffix}")- click.echo(f" Grade: {result.grade.value}")- click.echo(f" Strategic Score: {result.strategic_score:.1%}")- click.echo(f" Passed: {verdict}")- if result.self_judged:+ click.echo()+ click.echo(click.style("Results", bold=True))+ scored_categories = sum(+ 1 for cs in result.category_scores if cs.score is not None+ )+ total_categories = len(result.category_scores)+ coverage_suffix = (+ f" ({scored_categories}/{total_categories} categories scored)"+ if 0 < scored_categories < total_categories+ else ""+ )+ score_label = "Partial Score:" if coverage_suffix else "Overall Score:"+ verdict = (+ click.style("PASS", fg="green")+ if result.passed+ else click.style("FAIL", fg="red")+ )click.echo(- " "- + click.style(- "⚠ self-judged — the model graded its own output; "- "this grade is a smoke test, not a citable result.",- fg="yellow",- )+ f" {score_label} {result.overall_score:.1%}{coverage_suffix}")- click.echo()+ click.echo(f" Grade: {result.grade.value}")+ click.echo(f" Strategic Score: {result.strategic_score:.1%}")+ click.echo(f" Passed: {verdict}")+ if result.self_judged:+ click.echo(+ " "+ + click.style(+ "⚠ self-judged — the model graded its own output; "+ "this grade is a smoke test, not a citable result.",+ fg="yellow",+ )+ )+ click.echo()_print_error_summary(result)- _print_inconclusive_summary(result)- _print_insufficient_evidence_summary(result)click.echo()elapsed = _format_elapsed(time.monotonic() - run_start_monotonic)@@ -1345,7 +1443,7 @@ def gather_interactive_config() -> InteractiveConfig:type=click.Choice(PROVIDER_CHOICES, case_sensitive=False),)- api_key = click.prompt("API key", hide_input=True)+ api_key = click.prompt(f"API key for {provider}", hide_input=True)endpoint = Noneif click.confirm("Custom endpoint?", default=False):diff --git a/ifixai/cli/setup_cmd.py b/ifixai/cli/setup_cmd.pynew file mode 100644index 0000000..eb70d08--- /dev/null+++ b/ifixai/cli/setup_cmd.py@@ -0,0 +1,385 @@+"""``ifixai setup`` — interactive wizard that writes ifixai.yaml and can run it."""++from __future__ import annotations++import os+import subprocess+import sys++import click++from ifixai._version import VERSION as IFIXAI_VERSION+from ifixai.cli import ui+from ifixai.cli._branding import print_startup_banner+from ifixai.cli.config_file import CONFIG_FILENAME, JudgeSpec, RunConfig, write_config+from ifixai.cli.init import PROVIDER_ENV_KEYS, detect_available_providers+from ifixai.cli.model_catalog import default_model, suggestions+from ifixai.core.fixture_loader import list_fixture_names, load_fixture+from ifixai.harness.suites import suite_catalog++_PROVIDER_DESCRIPTIONS: dict[str, str] = {+ "openrouter": "One key → many models (OpenAI, Anthropic, Google, Llama…)",+ "openai": "OpenAI API — GPT-4o / o-series",+ "anthropic": "Anthropic API — Claude family",+ "gemini": "Google Gemini",+ "azure": "Azure OpenAI deployment",+ "bedrock": "AWS Bedrock-hosted models",+ "huggingface": "Hugging Face Inference endpoints",+ "http": "Any OpenAI-compatible HTTP endpoint",+ "langchain": "A LangChain-wrapped model",+ "mock": "Built-in offline mock — no key, just to try the tool",+}++_MODE_DESCRIPTIONS: dict[str, str] = {+ "standard": (+ "One judge grades each answer (auto-paired from a different vendor when you "+ "have a second key). Fast and citable. Best for most runs."+ ),+ "full": (+ "An ensemble of 2+ judges vote on each answer (majority vote, conservative "+ "tie-break), so no single judge decides the grade. Same inspections, sturdier "+ "result. Needs 2+ judge providers."+ ),+}++_ALL_PROVIDERS = [+ "openrouter",+ "openai",+ "anthropic",+ "gemini",+ "azure",+ "bedrock",+ "huggingface",+ "http",+ "langchain",+ "mock",+]++_CUSTOM_MODEL = "✏ Enter a custom model id…"+++def _pick_model(provider: str, *, role: str) -> str | None:+ """Model picker (default / suggestions / custom); None means provider default."""+ dm = default_model(provider)+ default_label = f"Provider default ({dm})" if dm else "Provider default"+ sugg = suggestions(provider)++ labels = [default_label, *[m for m, _ in sugg], _CUSTOM_MODEL]+ desc = {default_label: "Use the provider's built-in default model"}+ for model_id, description in sugg:+ desc[model_id] = description+ desc[_CUSTOM_MODEL] = "Type an exact model id yourself"++ choice = ui.select(+ f"Which model should be the {role}?",+ labels,+ default=default_label,+ descriptions=desc,+ )+ if choice == _CUSTOM_MODEL:+ return ui.text("Model id:", default=dm or "").strip() or None+ if choice == default_label:+ return None+ return choice+++def _missing_keys(selected: list[tuple[str, str]]) -> list[tuple[str, str, str]]:+ """For each (role, provider) chosen, return (role, provider, env_var) whose key+ is not set in the environment. De-duplicated by env var so a shared key is+ reported once, giving the user one clean export list."""+ missing: list[tuple[str, str, str]] = []+ seen: set[str] = set()+ for role, prov in selected:+ env = PROVIDER_ENV_KEYS.get(prov)+ if env and env not in seen and not os.environ.get(env):+ seen.add(env)+ missing.append((role, prov, env))+ return missing++[email protected]_context+def setup(ctx: click.Context) -> None:+ """Interactively configure a run and save it to ifixai.yaml."""+ if not ui.is_interactive():+ click.echo(+ click.style(+ "Error: `ifixai setup` needs an interactive terminal.\n"+ "In a script or CI, configure the run with explicit flags, e.g.:\n"+ " ifixai run --provider openai --suite core --mode standard",+ fg="red",+ ),+ err=True,+ )+ raise SystemExit(1)++ print_startup_banner(IFIXAI_VERSION)+ click.echo(+ click.style("Guided setup — a few prompts, then run zero-flag.", bold=True)+ )+ click.echo()++ available = detect_available_providers()+ available_names = [p for p, _ in available]+ if available_names:+ click.echo(+ click.style(+ f"✓ Detected credentials for: {', '.join(available_names)}", fg="green"+ )+ )+ else:+ click.echo(+ click.style("No provider API keys detected in your environment.", fg="yellow")+ )++ provider_choices = available_names + [+ p for p in _ALL_PROVIDERS if p not in available_names+ ]+ provider_desc = {+ p: _PROVIDER_DESCRIPTIONS.get(p, "")+ + (" — key detected" if p in available_names else "")+ for p in provider_choices+ }+ provider = ui.select(+ "Which provider hosts the system under test?",+ provider_choices,+ default=available_names[0] if available_names else "openrouter",+ descriptions=provider_desc,+ )+ api_key_env = PROVIDER_ENV_KEYS.get(provider)++ model = _pick_model(provider, role="system under test")++ judges: list[JudgeSpec] = []+ if provider == "mock":+ # Mock is a free offline preview, so there are no real providers or keys to+ # choose — just ask how many mock judges. A mock judge gives a non-self-judged+ # scorecard offline; 0 = self-judge.+ click.echo()+ choice = ui.select(+ "Mock judges (a judge gives a non-self-judged scorecard, all offline):",+ ["0", "1", "2"],+ default="1",+ descriptions={+ "0": "self-judge: mock grades itself (biased, flagged not citable)",+ "1": "one mock judge: a non-self single-judge run",+ "2": "two mock judges: an ensemble",+ },+ )+ judges = [JudgeSpec(provider="mock", model=None) for _ in range(int(choice))]+ if judges:+ click.echo(+ click.style(f" ✓ {len(judges)} mock judge(s) configured.", fg="green")+ )+ else:+ click.echo(+ click.style(" Self-judge (advisory, redacted score).", fg="yellow")+ )+ else:+ # Offer every provider as a judge — not just ones with a key already set.+ # The end-of-setup scan reminds the user which keys to export before running.+ judge_candidates = [p for p in provider_choices if p != "mock"]+ judge_desc = {}+ for p in judge_candidates:+ base = _PROVIDER_DESCRIPTIONS.get(p, "")+ env = PROVIDER_ENV_KEYS.get(p)+ if p == provider:+ judge_desc[p] = f"{base} — same vendor as the SUT; not an independent (citable) judge"+ elif p in available_names:+ judge_desc[p] = f"{base} — key detected"+ elif env:+ judge_desc[p] = f"{base} — set {env} before running"+ else:+ judge_desc[p] = base++ click.echo()+ click.echo(+ click.style(+ "Judges score your model's answers. None = self-judge (biased, redacted). "+ "One judge from a DIFFERENT vendor = a citable score; a same-vendor judge is "+ "an independence-limited smoke test, not citable. Two or more = a cross-vendor "+ "ensemble. You can mix providers, or use different models on one key.",+ dim=True,+ )+ )++ # Default the judge to a DIFFERENT vendor — citability requires cross-vendor+ # grading. Prefer one whose key is already present, else any non-SUT provider,+ # and only fall back to the SUT as a last resort.+ judge_default = next(+ (p for p in judge_candidates if p != provider and p in available_names),+ next((p for p in judge_candidates if p != provider), provider),+ )+ add_judge = ui.confirm(+ "Add an independent judge? (recommended — needed for a real score)",+ default=True,+ )+ while add_judge:+ jp = ui.select(+ f"Judge #{len(judges) + 1} — provider:",+ judge_candidates,+ default=judge_default,+ descriptions=judge_desc,+ )+ jm = _pick_model(jp, role=f"judge #{len(judges) + 1}")+ judges.append(JudgeSpec(provider=jp, model=jm))+ click.echo(+ click.style(+ f" ✓ Judge #{len(judges)}: {jp} / {jm or 'provider default'}",+ fg="green",+ )+ )+ add_judge = ui.confirm(+ "Add another judge? (2+ judges = ensemble)", default=False+ )++ if not judges:+ click.echo(+ click.style(+ " No judge selected — running self-judge (advisory, redacted score).",+ fg="yellow",+ )+ )+ elif len(judges) >= 2:+ click.echo(+ click.style(f" Ensemble of {len(judges)} judges configured.", fg="cyan")+ )++ fixtures = list_fixture_names()+ fixture_desc = {}+ for name in fixtures:+ try:+ fx = load_fixture(name)+ fixture_desc[name] = fx.metadata.domain or fx.metadata.name or name+ except Exception:+ fixture_desc[name] = name+ fixture = ui.select(+ "Fixture (the deployment profile to test against):",+ fixtures,+ default="default" if "default" in fixtures else fixtures[0],+ descriptions=fixture_desc,+ )++ suite_rows = suite_catalog()+ suite_names = [r["name"] for r in suite_rows]+ suite_desc = {+ r["name"]: f"{r['count']} inspections — {r['description']}" for r in suite_rows+ }+ suite = ui.select(+ "Suite (which inspections to run):",+ suite_names,+ default="core",+ descriptions=suite_desc,+ )++ click.echo()+ click.echo(+ click.style(+ "Run mode sets how many judges grade each answer, not how many "+ "inspections run. Standard uses one judge; Full uses an ensemble of 2+ "+ "that vote, so no single judge decides your grade.",+ dim=True,+ )+ )+ mode = ui.select(+ "Run mode:",+ ["standard", "full"],+ default="standard",+ descriptions=_MODE_DESCRIPTIONS,+ )++ # eval_mode follows the judge panel. Keep `mode` consistent with it so the+ # wizard never saves a contradictory config (Full mode + self-judge) that the+ # engine rejects at run time.+ if len(judges) >= 2:+ eval_mode = "full"+ elif len(judges) == 1:+ eval_mode = "single"+ else:+ eval_mode = "self"+ if mode == "full" and eval_mode != "full":+ click.echo(+ click.style(+ f" Full mode needs an ensemble of 2+ judges; you added {len(judges)}. "+ "Saving as Standard mode instead; add a second judge to use Full.",+ fg="yellow",+ )+ )+ mode = "standard"++ config = RunConfig(+ provider=provider,+ model=model,+ api_key_env=api_key_env,+ fixture=fixture,+ suite=suite,+ mode=mode,+ eval_mode=eval_mode,+ judges=judges,+ )++ click.echo()+ click.echo(click.style("Your configuration:", bold=True))+ click.echo(config.to_yaml())++ click.echo(+ click.style(+ f"Saving writes these settings to {CONFIG_FILENAME} in this folder so "+ "`ifixai run` needs no flags next time. It records only each key's env-var "+ "name (never the secret itself), and the file is git-ignored by default. "+ "Choose No to skip saving and configure runs with flags instead.",+ dim=True,+ )+ )+ if not ui.confirm(f"Save to {CONFIG_FILENAME}?", default=True):+ click.echo("Aborted — nothing written.")+ return++ path = write_config(config)+ click.echo(click.style(f"✓ Saved {path}", fg="green"))++ # Scan every provider the user selected (SUT + judges) and report which keys+ # still need exporting before a real run.+ selected = [+ ("system under test", provider),+ *((f"judge #{i}", j.provider) for i, j in enumerate(judges, 1)),+ ]+ missing = _missing_keys(selected)++ click.echo()+ if missing:+ click.echo(+ click.style(+ "Before you run the diagnostic, export these provider keys "+ "(selected, but not in your environment):",+ fg="yellow",+ bold=True,+ )+ )+ for role, prov, env in missing:+ click.echo(click.style(f" export {env}=… ({role}: {prov})", fg="yellow"))+ else:+ click.echo(+ click.style(+ "✓ Every selected provider has a key in your environment.", fg="green"+ )+ )+ click.echo()++ if ui.confirm("Run iFixAi now?", default=not missing):+ cmd = [sys.argv[0], "run"]+ if provider == "mock":+ cmd += ["-k", "unused"]+ if missing:+ click.echo(+ click.style(+ " Note: the run stops at preflight until the keys above are set "+ "(the system-under-test key can also be entered when prompted).",+ fg="yellow",+ )+ )+ click.echo()+ subprocess.run(cmd)+ else:+ click.echo(click.style("When you're ready:", bold=True))+ click.echo(click.style(" ifixai run", fg="cyan"))diff --git a/ifixai/cli/ui.py b/ifixai/cli/ui.pynew file mode 100644index 0000000..fbd5cca--- /dev/null+++ b/ifixai/cli/ui.py@@ -0,0 +1,517 @@+"""Thin presentation layer over ``rich`` and ``questionary`` with safe fallback.++The only module that imports rich/questionary. Both are imported lazily and+every renderer/prompt degrades gracefully when stdout is not a TTY or NO_COLOR+is set. Rendering helpers return True when handled via rich, False otherwise so+callers keep their plain-text path.+"""++from __future__ import annotations++import sys+from functools import lru_cache+from typing import Sequence++from ifixai.cli._branding import supports_color++_ACCENT = "rgb(232,99,42)"+_DIM = "grey62"+++@lru_cache(maxsize=1)+def _rich_available() -> bool:+ try:+ import rich # noqa: F401++ return True+ except Exception:+ return False+++@lru_cache(maxsize=1)+def _questionary_available() -> bool:+ try:+ import questionary # noqa: F401++ return True+ except Exception:+ return False+++def use_rich() -> bool:+ """True when styled rich output is appropriate (TTY + colour + lib)."""+ return supports_color() and _rich_available()+++def is_interactive() -> bool:+ """True only when we can safely run an interactive prompt."""+ return (+ supports_color()+ and _questionary_available()+ and sys.stdin.isatty()+ and sys.stdout.isatty()+ )+++@lru_cache(maxsize=1)+def console():+ """Lazy singleton ``rich.Console`` writing to stdout."""+ from rich.console import Console++ return Console()+++def _qstyle():+ """A branded questionary style (accent pointer/highlight)."""+ import questionary++ return questionary.Style(+ [+ ("qmark", "fg:#e8632a bold"),+ ("question", "bold"),+ ("pointer", "fg:#e8632a bold"),+ ("highlighted", "fg:#e8632a bold"),+ ("selected", "fg:#4ade80"),+ ("answer", "fg:#e8632a bold"),+ ("instruction", "fg:#9aa0a6"),+ ("text", ""),+ ]+ )+++def _choices(labels, descriptions):+ """Build questionary Choice objects with optional inline descriptions."""+ import questionary++ desc = descriptions or {}+ return [+ questionary.Choice(title=label, value=label, description=desc.get(label))+ for label in labels+ ]+++def select(+ message: str,+ choices: Sequence[str],+ default: str | None = None,+ descriptions: dict[str, str] | None = None,+) -> str:+ """Single-choice select; returns the default when non-interactive."""+ choices = list(choices)+ if not choices:+ raise ValueError("select() requires at least one choice")+ if not is_interactive():+ return default if default in choices else choices[0]+ import questionary++ kwargs = dict(+ choices=_choices(choices, descriptions),+ default=default or choices[0],+ style=_qstyle(),+ use_shortcuts=False,+ instruction="(↑/↓ to move, enter to select)",+ )+ if descriptions:+ kwargs["show_description"] = True+ answer = questionary.select(message, **kwargs).ask()+ return answer if answer is not None else (default or choices[0])+++def multiselect(+ message: str,+ choices: Sequence[str],+ *,+ descriptions: dict[str, str] | None = None,+ hint: str = "space to toggle, ↵ to confirm",+) -> list[str]:+ """Multi-choice checkbox with descriptions. Empty list when non-interactive."""+ choices = list(choices)+ if not is_interactive():+ return []+ import questionary++ kwargs = dict(+ choices=_choices(choices, descriptions),+ style=_qstyle(),+ instruction=f"({hint})",+ )+ if descriptions:+ kwargs["show_description"] = True+ answer = questionary.checkbox(message, **kwargs).ask()+ return answer or []+++def confirm(message: str, default: bool = True) -> bool:+ """Yes/no confirmation. Falls back to click.confirm when non-interactive."""+ if not is_interactive():+ return default+ import questionary++ answer = questionary.confirm(message, default=default, style=_qstyle()).ask()+ return default if answer is None else bool(answer)+++def text(message: str, default: str = "") -> str:+ """Free-text prompt. Falls back to click.prompt when non-interactive."""+ if not is_interactive():+ return default+ import questionary++ answer = questionary.text(message, default=default, style=_qstyle()).ask()+ return default if answer is None else answer+++def table(title: str, columns: Sequence[str], rows: Sequence[Sequence[str]]) -> bool:+ """Render a rich table. Returns False (no-op) when rich is unavailable."""+ if not use_rich():+ return False+ from rich.table import Table++ tbl = Table(title=title, title_style=f"bold {_ACCENT}", header_style="bold")+ for col in columns:+ tbl.add_column(col)+ for row in rows:+ tbl.add_row(*[str(c) for c in row])+ console().print(tbl)+ return True+++def _score_style(score: float) -> str:+ if score >= 0.9:+ return "bold green"+ if score >= 0.7:+ return "bold yellow"+ return "bold red"+++def _grade_color(grade: str) -> str:+ return {+ "A": "green",+ "B": "green",+ "C": "yellow",+ "D": "red",+ "F": "red",+ }.get((grade or "F")[0].upper(), "red")+++def _bar(ratio: float, width: int = 18) -> str:+ filled = max(0, min(width, round(ratio * width)))+ return "█" * filled + "·" * (width - filled)+++def _verdict_style(passed: bool) -> str:+ return "bold white on green" if passed else "bold white on red"+++def _row_style(score: float | None) -> str:+ if score is None:+ return "yellow"+ if score >= 0.9:+ return "bright_green"+ if score >= 0.7:+ return "yellow"+ return "red"+++def render_scorecard(result) -> bool:+ """Render the premium scorecard; False when rich is unavailable (use fallback)."""+ if not use_rich():+ return False++ from rich import box as rich_box+ from rich.align import Align+ from rich.columns import Columns+ from rich.panel import Panel+ from rich.rule import Rule+ from rich.table import Table+ from rich.text import Text++ from ifixai.reporting.scorecard import compute_insights++ ins = compute_insights(result)+ c = console()++ c.print()++ overall = ins["overall_score"]+ self_judged = ins["self_judged"]+ if overall is None:+ result_body = Text(justify="center")+ result_body.append("n/a\n\n", style="bold yellow")+ result_body.append("Insufficient evidence across all inspections.", style=_DIM)+ if self_judged:+ result_body.append(+ "\n\n⚠ Self-judged: this run graded its own output (biased, not citable).",+ style="bold yellow",+ )+ c.print(+ Panel(+ Align.center(result_body),+ title="[bold]iFixAi Result[/bold]",+ border_style="yellow",+ padding=(1, 4),+ expand=True,+ )+ )+ else:+ # The grade and score are always shown, regardless of the judge setup.+ # A self-judged run still prints its grade, flagged as biased / not citable.+ grade = ins["grade"]+ gcolor = _grade_color(grade)+ passed = ins["passed"]+ verdict_label = "PASS" if passed else "FAIL"+ verdict_color = "green" if passed else "red"++ grade_txt = Text(f" {grade} ", style=f"bold white on {gcolor}", justify="center")+ verdict_txt = Text(f" {verdict_label} ", style=f"bold white on {verdict_color}", justify="center")++ badges = Columns(+ [+ Align.center(grade_txt),+ Align.center(verdict_txt),+ ],+ equal=True,+ expand=False,+ )++ # Left-justify the lines (the whole block is still centered in the panel by+ # Align.center below) so the two score bars line up at the same column.+ body = Text(justify="left")+ body.append("\n")+ bar_overall = _bar(overall, 30)+ body.append(f"{bar_overall}", style=_score_style(overall))+ body.append(f" {overall:.1%}", style=f"bold {_score_style(overall)}")+ body.append(" overall score\n", style=_DIM)++ strategic = ins["strategic_score"]+ if strategic is not None:+ bar_strategic = _bar(strategic, 30)+ body.append(f"{bar_strategic}", style=_score_style(strategic))+ body.append(f" {strategic:.1%}", style=_score_style(strategic))+ body.append(" strategic (8 riskiest inspections)\n", style=_DIM)++ if self_judged:+ body.append(+ "\n⚠ Self-judged: the provider graded its own output, so this grade "+ "is biased and not citable.\n",+ style="bold yellow",+ )+ body.append(+ "Add a different-vendor judge for a citable grade: "+ "--judge-provider … --eval-mode single",+ style="italic",+ )++ from rich.console import Group+ panel_content = Group(+ Align.center(badges),+ Align.center(body),+ )+ accent = "yellow" if self_judged else _ACCENT+ c.print(+ Panel(+ panel_content,+ title=f"[bold {accent}]iFixAi Result[/bold {accent}]",+ border_style=accent,+ padding=(1, 4),+ expand=True,+ )+ )++ c.print()++ # The five core pillars are the graded foundation; everything after is the+ # premium tier, shipped here as a free preview. Split them into two tables.+ core_pillars = {+ "FABRICATION",+ "MANIPULATION",+ "DECEPTION",+ "UNPREDICTABILITY",+ "OPACITY",+ }++ def _scorecard_table(title: str, caption: str) -> Table:+ t = Table(+ title=title,+ title_style=f"bold {_ACCENT}",+ caption=caption,+ caption_style=_DIM,+ box=rich_box.ROUNDED,+ border_style="grey42",+ header_style=f"bold {_ACCENT}",+ show_lines=True,+ expand=True,+ )+ t.add_column("#", style="grey62", justify="center", width=3)+ t.add_column("Category", style="bold", min_width=20)+ t.add_column("Score", justify="center", min_width=8)+ t.add_column("Progress", min_width=24)+ t.add_column("Passed", justify="center", width=12)+ t.add_column("Result", justify="center", min_width=16)+ return t++ def _scorecard_row(t: Table, idx: int, cs) -> None:+ total_in_suite = len(cs.test_ids)+ failed = cs.test_count - cs.tests_passed+ inconclusive = total_in_suite - cs.test_count+ ratio = cs.tests_passed / total_in_suite if total_in_suite else 0.0+ row_style = _row_style(cs.score)+ score_txt = Text(+ "—" if cs.score is None else f"{cs.score:.0%}",+ style=f"bold {row_style}",+ justify="center",+ )+ bar_txt = Text(_bar(ratio, 20), style=row_style)+ tests_txt = Text(+ f"{cs.tests_passed}/{total_in_suite}",+ style=row_style,+ justify="center",+ )+ # Color the Result by the same score band as the rest of the row, so each row+ # reads as one consistent colour (no green "all passed" next to a yellow 83%).+ # The ✓/✗/⊘ icons still convey pass / fail / inconclusive.+ if cs.score is None:+ result_txt = Text("⊘ not scored", style="yellow", justify="center")+ elif failed == 0 and inconclusive == 0:+ result_txt = Text("✓ all passed", style=f"bold {row_style}", justify="center")+ else:+ # Show failures AND inconclusives so passed + failed + inconclusive = total.+ result_txt = Text(justify="center")+ if failed > 0:+ result_txt.append(f"✗ {failed} failed", style=f"bold {row_style}")+ if failed > 0 and inconclusive > 0:+ result_txt.append(" ")+ if inconclusive > 0:+ result_txt.append(f"⊘ {inconclusive} inconclusive", style=row_style)+ t.add_row(str(idx), cs.category.value, score_txt, bar_txt, tests_txt, result_txt)++ core_tbl = _scorecard_table(+ "Scorecard — Core pillars (scored)",+ "The five pillars that form your A–F grade.",+ )+ premium_tbl = _scorecard_table(+ "Premium preview — frontier categories",+ "A free preview of iFixAi's premium suite. Scored rows add to your grade; "+ "un-scored rows are exploratory (excluded from the grade, listed below).",+ )+ core_idx = premium_idx = 0+ for cs in result.category_scores:+ if len(cs.test_ids) == 0:+ continue+ if cs.category.value in core_pillars:+ core_idx += 1+ _scorecard_row(core_tbl, core_idx, cs)+ else:+ premium_idx += 1+ _scorecard_row(premium_tbl, premium_idx, cs)++ if core_idx:+ c.print(core_tbl)+ if premium_idx:+ if core_idx:+ c.print()+ c.print()+ c.print(premium_tbl)+ c.print()++ legend = Text(justify="left")+ legend.append("Colour: ", style=_DIM)+ legend.append("green", style="bold bright_green")+ legend.append(" strong (≥ 90%) ", style=_DIM)+ legend.append("yellow", style="bold yellow")+ legend.append(" needs work (70–89%) ", style=_DIM)+ legend.append("red", style="bold red")+ legend.append(" weak (below 70%)\n", style=_DIM)+ legend.append("⊘ inconclusive", style="yellow")+ legend.append(+ ": we couldn't grade the check (e.g. too little evidence); "+ "it doesn't count for or against the score.\n",+ style=_DIM,+ )+ legend.append(+ 'Score is a weighted average of how well each check did, so a category can '+ 'read "all passed" and still be below 100%.\n',+ style=_DIM,+ )+ legend.append(+ "Strategic score = the 8 highest-priority inspections (B01–B07, B25).",+ style=_DIM,+ )+ c.print(+ Panel(+ legend,+ title=f"[bold {_ACCENT}]How scoring works[/bold {_ACCENT}]",+ border_style=_DIM,+ padding=(0, 2),+ expand=True,+ )+ )+ c.print()++ sc = ins["status_counts"]+ summary = Table(box=None, pad_edge=False, show_header=False, expand=True)+ summary.add_column("label", style=_DIM)+ summary.add_column("value")++ tests_txt = Text()+ tests_txt.append(f"✓ {sc['pass']} passed", style="green")+ tests_txt.append(" ")+ tests_txt.append(f"✗ {sc['fail']} failed", style="red")+ tests_txt.append(" ")+ tests_txt.append(f"⊘ {sc['inconclusive']} inconclusive", style="yellow")+ if sc["error"]:+ tests_txt.append(f" ⚠ {sc['error']} error", style="bold red")++ summary.add_row("Tests", tests_txt)+ summary.add_row(+ "Coverage",+ Text(+ f"{ins['scored_categories']} of {ins['total_categories']} categories scored",+ style=_DIM,+ ),+ )++ if ins["weakest_pillars"] and not ins["self_judged"]:+ weakest_txt = Text()+ for i, (name, score) in enumerate(ins["weakest_pillars"]):+ if i:+ weakest_txt.append(" ")+ weakest_txt.append(f"{name} ", style="bold")+ weakest_txt.append(f"{score:.0%}", style=_score_style(score))+ summary.add_row("Weakest pillars", weakest_txt)++ c.print(Panel(summary, title="Run Summary", border_style=_DIM, expand=True))++ if ins["exploratory"]:+ expl_tbl = Table(+ box=rich_box.SIMPLE,+ header_style="bold grey62",+ show_header=True,+ caption="Signal: ✓ = passed its check; · = scored below threshold",+ caption_style=_DIM,+ expand=True,+ )+ expl_tbl.add_column("ID", style=_DIM, width=6)+ expl_tbl.add_column("Name")+ expl_tbl.add_column("Score", justify="right", width=8)+ expl_tbl.add_column("Signal", justify="center", width=8)+ for item in ins["exploratory"]:+ mark = Text("✓", style="green") if item["passing"] else Text("·", style=_DIM)+ expl_tbl.add_row(+ item["test_id"],+ item["name"],+ Text(f"{item['score']:.0%}", style=_DIM),+ mark,+ )+ c.print(+ Panel(+ expl_tbl,+ title="[grey62]Exploratory — frontier signal, excluded from grade[/grey62]",+ border_style=_DIM,+ expand=True,+ )+ )++ c.print(Rule(style="grey23"))+ c.print()+ return Truediff --git a/ifixai/core/fixture_loader.py b/ifixai/core/fixture_loader.pyindex 7d51d1d..28e444c 100644--- a/ifixai/core/fixture_loader.py+++ b/ifixai/core/fixture_loader.py@@ -43,6 +43,10 @@ def resolve_fixture_path(name_or_path: str | Path) -> Path:if builtin_path.exists():return builtin_path+ example_path = _FIXTURES_DIR / "examples" / f"{name_or_path}.yaml"+ if example_path.exists():+ return example_path+raise FileNotFoundError(f"Fixture not found: '{name_or_path}'. "f"Provide a file path or a built-in name from: {list_fixture_names()}"@@ -51,11 +55,16 @@ def resolve_fixture_path(name_or_path: str | Path) -> Path:def list_fixture_names() -> list[str]:if not _FIXTURES_DIR.exists():return []- return sorted(+ builtin = {d.namefor d in _FIXTURES_DIR.iterdir()if d.is_dir() and (d / "fixture.yaml").exists()+ }+ examples_dir = _FIXTURES_DIR / "examples"+ examples = (+ {p.stem for p in examples_dir.glob("*.yaml")} if examples_dir.is_dir() else set())+ return sorted(builtin | examples)def load_fixture(path: str | Path) -> Fixture:fixture_path = resolve_fixture_path(path)diff --git a/ifixai/evaluation/analytic_judge.py b/ifixai/evaluation/analytic_judge.pyindex 54847c5..b3bfedc 100644--- a/ifixai/evaluation/analytic_judge.py+++ b/ifixai/evaluation/analytic_judge.py@@ -14,6 +14,7 @@ from json_repair import repair_jsonfrom ifixai.judge.evaluator import EnsembleJudgeEvaluator, JudgeEvaluatorfrom ifixai.core.refusal import is_platform_refusal+from ifixai.providers.base import is_fatal_provider_errorfrom ifixai.core.types import (AnalyticRubric,ChatMessage,@@ -834,6 +835,16 @@ class AnalyticRubricJudge:)except Exception as exc:last_exc = exc+ if is_fatal_provider_error(exc):+ logger.error(+ "Judge call for %s aborted (non-retryable): %s",+ rubric.test_id,+ exc,+ )+ raise JudgeCommunicationError(+ f"Judge provider rejected the request (non-retryable): "+ f"{type(exc).__name__}: {exc}"+ ) from excif attempt < self._EXTRACTION_RETRIES:logger.warning("Judge communication error for %s (attempt %d/%d), retrying — %s: %s",diff --git a/ifixai/harness/registry.py b/ifixai/harness/registry.pyindex c85a598..ae10ad7 100644--- a/ifixai/harness/registry.py+++ b/ifixai/harness/registry.py@@ -394,6 +394,22 @@ class CategoryResolution(TypedDict):unknown: list[str]+def _import_suites(): # pragma: no cover+ from ifixai.harness import suites++ return suites+++def resolve_suite(name: str):+ """Re-export of ifixai.harness.suites.resolve_suite."""+ return _import_suites().resolve_suite(name)+++def suite_catalog():+ """Re-export of ifixai.harness.suites.suite_catalog."""+ return _import_suites().suite_catalog()++def resolve_category_test_ids(names: Iterable[str]) -> CategoryResolution:"""Expand failure-category names into the test IDs they contain.diff --git a/ifixai/harness/suites.py b/ifixai/harness/suites.pynew file mode 100644index 0000000..b778f7b--- /dev/null+++ b/ifixai/harness/suites.py@@ -0,0 +1,155 @@+"""Named test suites for the ``--suite`` selector (tiers and themes)."""++from __future__ import annotations++from typing import TypedDict++from ifixai.core.types import InspectionCategory++_CORE_PILLARS: frozenset[InspectionCategory] = frozenset(+ {+ InspectionCategory.FABRICATION,+ InspectionCategory.MANIPULATION,+ InspectionCategory.DECEPTION,+ InspectionCategory.UNPREDICTABILITY,+ InspectionCategory.OPACITY,+ }+)+++class SuiteResolution(TypedDict):+ test_ids: list[str]+ unknown: list[str]+++def _core_ids() -> list[str]:+ from ifixai.harness.registry import ALL_SPECS++ return [s.test_id for s in ALL_SPECS if s.category in _CORE_PILLARS]+++def _extended_ids() -> list[str]:+ from ifixai.harness.registry import ALL_SPECS++ return [s.test_id for s in ALL_SPECS if s.category not in _CORE_PILLARS]+++def _all_ids() -> list[str]:+ from ifixai.harness.registry import ALL_SPECS++ return [s.test_id for s in ALL_SPECS]+++def _strategic_ids() -> list[str]:+ from ifixai.harness.registry import STRATEGIC_TESTS++ return list(STRATEGIC_TESTS)+++def _smoke_ids() -> list[str]:+ return _strategic_ids()[:3]+++_TIER_RESOLVERS: dict[str, "callable[[], list[str]]"] = {+ "smoke": _smoke_ids,+ "strategic": _strategic_ids,+ "core": _core_ids,+ "extended": _extended_ids,+ "all": _all_ids,+}++_TIER_DESCRIPTIONS: dict[str, str] = {+ "smoke": "Fastest sanity check (3 strategic inspections).",+ "strategic": "The headline strategic set used for the strategic score.",+ "core": "The 32 graded five-pillar inspections (B-series).",+ "extended": "The 13 frontier inspections (P/C/S/X-series).",+ "all": "Every registered inspection.",+}+++class _Theme(TypedDict):+ categories: list[str]+ extra_ids: list[str]+ description: str+++_THEMES: dict[str, _Theme] = {+ "security": {+ "categories": ["MANIPULATION"],+ "extra_ids": ["P01", "P22", "P27", "P13"],+ "description": "Injection, privilege escalation, sabotage, power elevation.",+ },+ "reliability": {+ "categories": ["UNPREDICTABILITY"],+ "extra_ids": ["B16", "B17", "B29", "B32", "C02", "C05", "C11"],+ "description": "Consistency, reproducibility, silent failure, uncertainty calibration.",+ },+ "compliance": {+ "categories": ["OPACITY"],+ "extra_ids": ["B03", "B23", "P08", "X04", "X11"],+ "description": "Auditability, traceability, regulatory readiness, oversight gates.",+ },+ "frontier": {+ "categories": [],+ "extra_ids": [],+ "description": "The frontier / extended-risk roster (P/C/S/X-series).",+ },+}+++TIER_NAMES: list[str] = list(_TIER_RESOLVERS)+THEME_NAMES: list[str] = list(_THEMES)+SUITE_NAMES: list[str] = TIER_NAMES + THEME_NAMES+++def _dedup(ids: list[str]) -> list[str]:+ from ifixai.harness.registry import ALL_SPECS++ wanted = set(ids)+ return [s.test_id for s in ALL_SPECS if s.test_id in wanted]+++def resolve_suite(name: str) -> SuiteResolution:+ """Expand a suite name into its concrete, de-duplicated test IDs."""+ from ifixai.harness.registry import resolve_category_test_ids++ key = name.strip().lower()++ if key in _TIER_RESOLVERS:+ return {"test_ids": _dedup(_TIER_RESOLVERS[key]()), "unknown": []}++ if key in _THEMES:+ theme = _THEMES[key]+ if key == "frontier":+ return {"test_ids": _extended_ids(), "unknown": []}+ from_categories = resolve_category_test_ids(theme["categories"])["test_ids"]+ return {+ "test_ids": _dedup([*from_categories, *theme["extra_ids"]]),+ "unknown": [],+ }++ return {"test_ids": [], "unknown": [name]}+++def suite_catalog() -> list[dict[str, object]]:+ """Rows for ``ifixai list suites``: name, kind, count, description."""+ rows: list[dict[str, object]] = []+ for tier in TIER_NAMES:+ rows.append(+ {+ "name": tier,+ "kind": "tier",+ "count": len(resolve_suite(tier)["test_ids"]),+ "description": _TIER_DESCRIPTIONS.get(tier, ""),+ }+ )+ for theme in THEME_NAMES:+ rows.append(+ {+ "name": theme,+ "kind": "theme",+ "count": len(resolve_suite(theme)["test_ids"]),+ "description": _THEMES[theme]["description"],+ }+ )+ return rowsdiff --git a/ifixai/providers/base.py b/ifixai/providers/base.pyindex 109d988..3485130 100644--- a/ifixai/providers/base.py+++ b/ifixai/providers/base.py@@ -95,6 +95,67 @@ class ProviderResponseError(ProviderError):pass+_FATAL_ERROR_MARKERS: tuple[str, ...] = (+ "401",+ "403",+ "invalid api key",+ "invalid_api_key",+ "incorrect api key",+ "unauthorized",+ "permission denied",+ "permissiondenied",+ "authentication",+ "limit exceeded",+ "quota",+ "insufficient_quota",+ "billing",+ "payment required",+ "credit",+)+++def is_fatal_provider_error(exc: BaseException) -> bool:+ """True when an error means the credential is rejected / out of quota."""+ if isinstance(exc, ProviderAuthError):+ return True+ text = str(exc).lower()+ return any(marker in text for marker in _FATAL_ERROR_MARKERS)+++def friendly_provider_message(detail: str) -> str | None:+ """Map a raw provider error string to one actionable sentence, or None."""+ low = detail.lower()+ if "limit exceeded" in low or "quota" in low or "insufficient_quota" in low:+ return (+ "API key is out of quota / hit its usage limit. "+ "Top it up, raise the limit, or use a different key."+ )+ if (+ "401" in low+ or "invalid api key" in low+ or "incorrect api key" in low+ or "unauthorized" in low+ or "authentication" in low+ ):+ return (+ "API key was rejected (authentication failed). "+ "Check the key value and that it matches the chosen provider."+ )+ if "403" in low or "permission" in low or "forbidden" in low:+ return (+ "Access was forbidden (403). The key may lack permission for this "+ "model, or have exceeded a usage/billing limit."+ )+ if "429" in low or "rate limit" in low or "rate_limit" in low:+ return (+ "Rate limited by the provider. Lower --concurrency or wait a moment "+ "and retry."+ )+ if "billing" in low or "payment" in low or "credit" in low:+ return "Provider reports a billing/credit problem on the account."+ return None++class ProviderEmptyContentError(ProviderResponseError):"""Provider returned a successful response with no text content.diff --git a/ifixai/reporting/scorecard.py b/ifixai/reporting/scorecard.pyindex 8b06441..dcd856d 100644--- a/ifixai/reporting/scorecard.py+++ b/ifixai/reporting/scorecard.py@@ -35,6 +35,94 @@ B22_SKIPPED_MESSAGE: Final[str] = (SEED_UNSUPPORTED_PREFIX: Final[str] = "b12 seed accepted but provider cannot honour: "+def compute_insights(result: TestRunResult) -> dict[str, object]:+ """Derive presentation-ready insights shared by console and file reports."""+ results = result.test_results++ status_counts = {"pass": 0, "fail": 0, "inconclusive": 0, "error": 0}+ for br in results:+ status_counts[br.status.value] = status_counts.get(br.status.value, 0) + 1++ scored = [+ (cs.category.value, cs.score)+ for cs in result.category_scores+ if cs.score is not None+ ]+ weakest = sorted(scored, key=lambda pair: pair[1])[:3]++ total_categories = len(result.category_scores)+ scored_categories = len(scored)++ exploratory = [+ {+ "test_id": br.test_id,+ "name": br.name,+ "score": br.score,+ "passing": br.passing,+ }+ for br in results+ if br.spec is not None and br.spec.is_exploratory+ ]++ delta = None+ if (+ not result.self_judged+ and result.overall_score is not None+ and result.strategic_score is not None+ ):+ delta = result.overall_score - result.strategic_score++ return {+ "self_judged": result.self_judged,+ "status_counts": status_counts,+ "total_tests": len(results),+ "weakest_pillars": weakest,+ "scored_categories": scored_categories,+ "total_categories": total_categories,+ "exploratory": exploratory,+ "overall_score": result.overall_score,+ "strategic_score": result.strategic_score,+ "grade": result.grade.value,+ "strategic_overall_delta": delta,+ "passed": result.passed,+ }+++def render_insights(result: TestRunResult) -> str:+ """Markdown "Insights" section derived from :func:`compute_insights`."""+ ins = compute_insights(result)+ sc = ins["status_counts"]+ lines = ["## Insights", ""]+ lines.append(+ f"- **Tests:** {sc['pass']} passed · {sc['fail']} failed · "+ f"{sc['inconclusive']} inconclusive"+ + (f" · {sc['error']} error" if sc["error"] else "")+ )+ lines.append(+ f"- **Category coverage:** {ins['scored_categories']}/"+ f"{ins['total_categories']} categories scored"+ )+ if not ins["self_judged"] and ins["weakest_pillars"]:+ weakest = ", ".join(+ f"{name} ({score:.0%})" for name, score in ins["weakest_pillars"]+ )+ lines.append(f"- **Weakest pillars:** {weakest}")+ if not ins["self_judged"] and ins["strategic_overall_delta"] is not None:+ delta = ins["strategic_overall_delta"]+ sign = "+" if delta >= 0 else ""+ lines.append(+ f"- **Overall vs strategic:** {ins['overall_score']:.1%} overall "+ f"vs {ins['strategic_score']:.1%} strategic ({sign}{delta:.1%})"+ )+ if ins["exploratory"]:+ names = ", ".join(item["test_id"] for item in ins["exploratory"])+ lines.append(+ f"- **Exploratory (not scored):** {len(ins['exploratory'])} "+ f"inspection(s) — {names}"+ )+ return "\n".join(lines)++def insufficient_evidence_warnings(test_results: list[TestResult],) -> list[str]:@@ -182,6 +270,7 @@ def generate_json_report(result: TestRunResult) -> str:"mandatory_minimums": build_mandatory_minimums_section(result),"test_results": build_test_results_section(result, frameworks),"regulatory": build_regulatory_json_section(result, frameworks),+ "insights": compute_insights(result),}return json.dumps(report, indent=2, ensure_ascii=False)@@ -193,6 +282,7 @@ def generate_markdown_report(result: TestRunResult) -> str:sections = [render_header(result),render_summary(result),+ render_insights(result),render_category_table(result),render_mandatory_minimums(result),render_consistency_warnings(result),@@ -208,6 +298,44 @@ def generate_markdown_report(result: TestRunResult) -> str:return "\n\n".join(s for s in sections if s) + "\n"+def _render_top_failures(result: TestRunResult, limit: int = 8) -> str:+ """A compact 'where it hurts most' list — lowest-scoring failed inspections."""+ failed = [+ br+ for br in result.test_results+ if br.status == TestStatus.FAIL and not br.insufficient_evidence+ ]+ if not failed:+ return ""+ failed.sort(key=lambda br: br.score)+ lines = ["## Top failures", ""]+ for br in failed[:limit]:+ name = br.name or br.test_id+ lines.append(+ f"- **{br.test_id}** {name} — {br.score:.0%} "+ f"(threshold {br.threshold:.0%}, {br.category.value})"+ )+ remaining = len(failed) - limit+ if remaining > 0:+ lines.append(f"- …and {remaining} more (see the full report).")+ return "\n".join(lines)+++def generate_summary_report(result: TestRunResult) -> str:+ """Short scannable report: headline, insights, categories, top failures."""+ sections = [+ render_header(result),+ render_summary(result),+ render_insights(result),+ render_category_table(result),+ render_mandatory_minimums(result),+ _render_top_failures(result),+ "_This is the summary. The full report (with per-inspection evidence) "+ "is the companion `.md` without the `-summary` suffix._",+ ]+ return "\n\n".join(s for s in sections if s) + "\n"++def build_metadata_section(result: TestRunResult,frameworks: dict[str, RegulatoryFramework] | None = None,diff --git a/plugin/README.md b/plugin/README.mdnew file mode 100644index 0000000..b7c9db8--- /dev/null+++ b/plugin/README.md@@ -0,0 +1,27 @@+# iFixAi: Claude Code plugin++Let Claude run iFixAi's operational-misalignment diagnostic on your own agent. It discovers your+setup, builds the test fixture, names the cost before anything is billed, runs the diagnostic on+the model(s) and judge(s) you pick, then walks you through the scorecard. No flags or fixtures to+write.++## Install++From inside [Claude Code](https://claude.com/claude-code):++```+/plugin marketplace add ifixai-ai/iFixAi+/plugin install ifixai@ifixai-ai+```++Restart Claude Code or run `/reload-plugins` if it doesn't show up right away.++## Run++Just ask Claude in plain English:++> run iFixAi on my setup++or type the slash command `/ifixai:ifixai`.++Claude takes it from there. Full project docs: https://github.com/ifixai-ai/iFixAi#readmediff --git a/pyproject.toml b/pyproject.tomlindex 1945ea6..785a264 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -34,6 +34,8 @@ dependencies = ["aiohttp>=3.9","python-dateutil>=2.8.2","json-repair>=0.25",+ "rich>=13.0",+ "questionary>=2.0",][project.optional-dependencies]