diff --git a/.agent-eval/tasks/rename-cli-flag/check.py b/.agent-eval/tasks/rename-cli-flag/check.py index 894eb6356b..bc394f21f4 100644 --- a/.agent-eval/tasks/rename-cli-flag/check.py +++ b/.agent-eval/tasks/rename-cli-flag/check.py @@ -62,6 +62,7 @@ def fake_single(entry, **kwargs): return {"library": entry.key, "name": entry.name, "status": "ok", "result": {"steps": {"evaluation": {"summary": {"with_avg": 80.0}}}}} + # This verifier imports benchmark from the historical base pinned in task.json. saved = benchmark._load_registry, benchmark._run_single_library benchmark._load_registry = lambda args: Registry() benchmark._run_single_library = fake_single diff --git a/dokimi/changelog.d/20261129_120000_napetrov_shared-command-helpers.md b/dokimi/changelog.d/20261129_120000_napetrov_shared-command-helpers.md new file mode 100644 index 0000000000..82029925f7 --- /dev/null +++ b/dokimi/changelog.d/20261129_120000_napetrov_shared-command-helpers.md @@ -0,0 +1,3 @@ +### Changed + +- **Internal refactor of the command helpers.** Flags, output, file names and exit codes are unchanged. diff --git a/dokimi/docs/reference/cli-interface.json b/dokimi/docs/reference/cli-interface.json index 9b2870f389..cfa22e21fa 100644 --- a/dokimi/docs/reference/cli-interface.json +++ b/dokimi/docs/reference/cli-interface.json @@ -798,7 +798,7 @@ "allow_abbrev": true, "params": [ {"key": "skill", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "argument", "nargs": null, "position": 0, "required": true, "type": null}, - {"key": "--extract-model", "action": "_StoreAction", "choices": null, "const": null, "default": ["anthropic", "claude-sonnet-5-5"], "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.commands.repo_hits._judge_ref#f8f456f0565f"}, + {"key": "--extract-model", "action": "_StoreAction", "choices": null, "const": null, "default": ["anthropic", "claude-sonnet-5-5"], "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.commands._shared.judge_ref#2304e1942183"}, {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--json", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--max-usd", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_usd#3f7e5c8902a3"}, @@ -1463,7 +1463,7 @@ {"key": "--dry-run", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--json", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, - {"key": "--judge", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": true, "type": "dokimi.commands.repo_hits._judge_ref#f8f456f0565f"}, + {"key": "--judge", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": true, "type": "dokimi.commands._shared.judge_ref#2304e1942183"}, {"key": "--labels", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--max-usd", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_usd#3f7e5c8902a3"} ], diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index 29d78b2cd6..cc184005f4 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -2,6 +2,7 @@ depends_on: - dokimi/dokimi/repos/** - dokimi/dokimi/commands/repo.py + - dokimi/dokimi/commands/_shared.py - dokimi/dokimi/commands/repo_reach.py - dokimi/dokimi/commands/repo_run.py - dokimi/dokimi/schemas/repo_*.json diff --git a/dokimi/dokimi/artifacts.py b/dokimi/dokimi/artifacts.py index a1c7d86ce8..d3db940de4 100644 --- a/dokimi/dokimi/artifacts.py +++ b/dokimi/dokimi/artifacts.py @@ -418,3 +418,9 @@ def load_artifact(kind: str, path: Path | str, *, validate: bool = True) -> dict except ArtifactValidationError as exc: raise InputError(f"{path} is not a valid {kind} artifact: {exc}") from exc return data + + +def safe_file_name(name: str) -> str: + """A file-name piece for a cell or product name: other characters become ``-``, ``cell`` if none is left.""" + safe = "".join(c if c.isalnum() or c in ("-", "_", ".") else "-" for c in name) + return safe.strip("-") or "cell" diff --git a/dokimi/dokimi/commands/_shared.py b/dokimi/dokimi/commands/_shared.py new file mode 100644 index 0000000000..1a76325d59 --- /dev/null +++ b/dokimi/dokimi/commands/_shared.py @@ -0,0 +1,249 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Helpers the command modules share, public so no module imports another's private name. + +Each one moved here from the module that defined it, unchanged except for its name. A name +used only by its own module stays there. +""" + +from __future__ import annotations + +import argparse +import importlib.util +import os +import re +import shutil +import sys +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from dokimi.commands._output import save_artifact_or_exit +from dokimi.defaults import ( + DEFAULT_JUDGE_MODEL, + DEFAULT_JUDGE_PROVIDER, +) +from dokimi.repos.l0.config import new_failures +from dokimi.utils import InputError + +if TYPE_CHECKING: + from dokimi.repos import RepoSource + + +def require_ragas() -> None: + """Exit before any model call when the ragas extra is not installed.""" + if importlib.util.find_spec("ragas") is None: + sys.exit("RAGAS meta-evaluation needs the ragas extra: pip install 'dokimi[ragas]'") + + +def run_ragas_eval(answers, output_path, args) -> None: + """Run RAGAS meta-evaluation and save results alongside answers.""" + from dokimi.eval.question_text import EmptyQuestionError + from dokimi.eval.ragas_eval import RagasEvaluator + from dokimi.records import AskOutcomeError + + ragas_model = getattr(args, "ragas_model", DEFAULT_JUDGE_MODEL) + ragas_provider = getattr(args, "ragas_provider", DEFAULT_JUDGE_PROVIDER) + + print(f"\nšŸ” Running RAGAS meta-evaluation ({ragas_provider}/{ragas_model})...") + try: + evaluator = RagasEvaluator( + llm_model=ragas_model, + provider=ragas_provider, + ) + result = evaluator.evaluate(answers, include_without_docs=True) + + # Save ragas results alongside answers + ragas_path = output_path.with_name(output_path.stem + "_ragas.json") + payload = {**result.to_dict(), "ragas_model": f"{ragas_provider}/{ragas_model}"} + save_artifact_or_exit("ragas", payload, ragas_path, code=2) + + print(result.format_summary()) + print(f"āœ… Saved RAGAS results to {ragas_path}") + + except (AskOutcomeError, EmptyQuestionError): + raise # a bad input record is a refusal, not a RAGAS failure: cli.main reports it (exit 2) + except ImportError as exc: + sys.exit(f"RAGAS meta-evaluation was requested but cannot run: {exc}") + except Exception as exc: # noqa: BLE001 - RAGAS is an optional extra pass; its failure is printed + print(f"\nāš ļø RAGAS evaluation failed: {exc}") + + +def judge_ref(text: str) -> tuple[str, str]: + """``PROVIDER/MODEL`` as ``(provider, model)``; the model may hold more slashes (``openrouter/a/b``).""" + from dokimi.llm import ANSWER_PROVIDERS, PROVIDER_ALIASES + + provider, sep, model = text.partition("/") + known = (*ANSWER_PROVIDERS, *PROVIDER_ALIASES) + if not sep or not model.strip() or provider not in known: + raise argparse.ArgumentTypeError(f"takes PROVIDER/MODEL, PROVIDER one of {', '.join(known)}; got {text!r}") + return provider, model + + +def print_scan_text(manifest, payload: dict, out: str | None) -> None: + """The text report of ``repo scan``: the counts, the warnings, the typecheck and static lines, the FAIL lines.""" + c = payload["counts"] + detected = " (detected)" if payload["adapters_detected"] else "" + print(f"{manifest.id}: {len(payload['files'])} guidance files in {payload['repo']['tree']}; " + f"adapters: {', '.join(payload['adapters']) or 'none'}{detected}") + ignored = f" ({c['ignored']} ignored)" if c.get("ignored") else "" + print(f" claims: {c['total']} (ok {c['ok']}, unresolved {c['unresolved']}{ignored}, fail {c['fail']})") + for warning in payload["warnings"]: + print(f" warning: {warning}") + if payload["incomplete"]: + print(f" incomplete: {'; '.join(payload['incomplete_reasons'])} (repo scan --fail-on fail exits 1)") + tc = payload["typecheck"] + if tc is not None: + where = tc["python"] or "no --python-env: unknown" + print(f" typecheck {tc['tool']} {tc['tool_version'] or ''} ({where}): {tc['fences']} python fences, " + f"{tc['checked']} checked, {tc['fail']} fail, {tc['unknown']} unknown, {tc['syntax']} not Python") + static_info = payload["static"] + if static_info is not None and not static_info["errors"]: + r = payload["by_source"]["repository"] + print(f" repository static: {r['total']} claims, {r['fail']} fail; " + f"{static_info['superseded']} framework claims replaced") + base = payload.get("baseline") + if base: + print(f" baseline {base['source']}: {base['new']} new fail, {base['known']} known, {base['fixed']} fixed") + for claim in payload["claims"]: + if claim["status"].split("_", 1)[0] == "fail": + mark = "known" if claim.get("baselined") else "FAIL" + print(f" {mark} {claim['file']}:{claim['line']} [{claim.get('kind')}] " + f"{str(claim.get('claim'))[:90]} -- {claim.get('why')}") + if out: + print(f"wrote {out}") + + +def scan_gate(payload: dict, gate: bool) -> None: + """--fail-on fail: exit 1 on a failed claim or an incomplete scan, saying on stderr what the scan missed.""" + if not gate or not (new_failures(payload) or payload["incomplete"]): + return + if payload["incomplete"]: + print(f"āœ— scan incomplete: {'; '.join(payload['incomplete_reasons'])}", file=sys.stderr) + sys.exit(1) + + +def scan_reason(payload: dict, static_errors: list, gate: bool) -> str: + """Why a --json scan failed: every cause the gate tripped on, joined by ``; `` (a scan can fail on more than + one). The --static problems always fail the run; the failed claims and the incomplete scan only under + --fail-on fail.""" + parts = [] + if static_errors: + parts.append(f"{len(static_errors)} --static problem(s) not merged") + if gate and new_failures(payload): + known = (payload.get("baseline") or {}).get("known") + parts.append(f"{new_failures(payload)} claim(s) failed" + (f" ({known} more known in the baseline)" if known else "")) + if gate and payload["incomplete"]: + reasons = "; ".join(payload.get("incomplete_reasons") or []) + parts.append(f"scan incomplete: {reasons}" if reasons else "scan incomplete") + return "; ".join(parts) + + +def typecheck_or_exit(args: argparse.Namespace): + """The ``--typecheck`` check, or None; ``--python-env`` needs it and must name an interpreter.""" + from dokimi.repos.l0 import Check + + if not args.typecheck: + if args.python_env is not None: + raise InputError("--python-env needs --typecheck") + if args.typecheck_tool is not None: + raise InputError("--typecheck-tool needs --typecheck") + return None + tool = args.typecheck_tool or "mypy" + # a directory is X_OK too: only a regular file can be the interpreter + if args.python_env is not None and not (os.path.isfile(args.python_env) and os.access(args.python_env, os.X_OK)): + raise InputError(f"--python-env {args.python_env}: not an executable interpreter") + if tool != "mypy" and shutil.which(tool) is None: + raise InputError(f"--typecheck-tool {tool}: not on PATH") + python = os.path.abspath(args.python_env) if args.python_env is not None else None # the tool runs elsewhere + return Check(tool, python) + + +def cache_dir_from_args(args: argparse.Namespace) -> Path | None: + """``--cache-dir`` as given, or ``None``; a value no clone can be cached in is a usage error (2) (#765). + + Without the flag, a non-empty ``$DOKIMI_REPO_CACHE`` is checked and returned the same way (#827); the flag wins. + A read-only directory passes: a populated one replays without writing; an empty one fails later with exit 1. + """ + from dokimi.commands.cache_dir import CLONE_USE, resolved_cache_dir + + env = os.environ.get("DOKIMI_REPO_CACHE") + if not args.cache_dir and env: + return resolved_cache_dir(env, CLONE_USE, label="$DOKIMI_REPO_CACHE") + return resolved_cache_dir(args.cache_dir, CLONE_USE, label="--cache-dir") + + +def parse_source(args: argparse.Namespace) -> RepoSource: + """The source as typed: a malformed string, an unpinned remote, a local path that is not a directory or a ``--cache-dir`` that is not a usable directory is a usage error (2); a local path the filesystem refuses to stat (no permission to traverse it) is 1.""" + from dokimi.repos import RepoSource, SourceError + + try: + source = RepoSource.parse(args.source) + except SourceError as exc: + raise InputError(str(exc)) from exc + except OSError as exc: # Path.is_dir raises PermissionError on Python 3.11-3.13 + print(f"āœ— {exc}", file=sys.stderr) + sys.exit(1) + cache_dir_from_args(args) # a bad --cache-dir is a usage error too, and must not reach a handler of the clone's failures + return source + + +def normalize_whitespace(text: str, max_len: int | None = 100) -> str: + """One line: whitespace runs become one space, control characters are escaped, then truncated.""" + flat = re.sub(r"\s+", " ", text).strip() + printable = "".join(c if c.isprintable() else c.encode("unicode_escape").decode("ascii") for c in flat) + return printable[:max_len] + + +def code_index_for(path: str | None) -> Any: + """The SCIP index at ``path`` (``None`` without one); exit 2 when it cannot be read.""" + if path is None: + return None + from dokimi.repos.code_index import load + from dokimi.repos.errors import CodeIndexError + + try: + return load(path) + except (OSError, CodeIndexError) as exc: + raise InputError(f"cannot read the code index {path}: {exc}") from exc + + +def run_errors(): + from dokimi.repos import ManifestError, SourceError + from dokimi.repos.container import ContainerError + from dokimi.repos.harness_profile import ProfileError + from dokimi.repos.arms import ArmError + from dokimi.repos.workspace import PrepError + + return (ArmError, SourceError, ManifestError, ContainerError, PrepError, ProfileError, ValueError, OSError) + + +def pairwise_judges(args: argparse.Namespace) -> list[tuple[str, str]]: + """``(model, provider)`` of the pairwise judge, then of the escalation judge when one is named.""" + judges = [(args.judge_model, args.judge_provider)] + if getattr(args, "escalate_model", None): + judges.append((args.escalate_model, args.escalate_provider or args.judge_provider)) + return judges + + +def load_runtime_config() -> dict: + import yaml + + from dokimi.config import runtime_config_path + + config_path = runtime_config_path() + if not config_path.exists(): + return {} + try: + loaded = yaml.safe_load(config_path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError) as exc: + raise InputError(f"cannot read {config_path}: {exc}") from exc + except (yaml.YAMLError, ValueError, RecursionError) as exc: # ValueError: a bad date; RecursionError: deep nesting + raise InputError(f"invalid YAML in {config_path}: {exc}") from exc + if loaded is not None and not isinstance(loaded, dict): + raise InputError(f"expected a mapping in {config_path}") + config = loaded or {} + for key in ("products", "retrieval"): + if config.get(key) is not None and not isinstance(config[key], dict): + raise InputError(f"'{key}' in {config_path} must be a mapping") + return config diff --git a/dokimi/dokimi/commands/answers.py b/dokimi/dokimi/commands/answers.py index 0609aca816..1f1291ab88 100644 --- a/dokimi/dokimi/commands/answers.py +++ b/dokimi/dokimi/commands/answers.py @@ -12,7 +12,7 @@ from dokimi.cli_model_ref import add_model_flag from dokimi import cli_flags from dokimi.llm import CALLER_CHOICES -from dokimi.commands.evaluate import _require_ragas, _run_ragas_eval +from dokimi.commands._shared import load_runtime_config, require_ragas, run_ragas_eval from dokimi.eval.arms_refusals import refuse_knowledge_provider from dokimi.records import KNOWLEDGE_INTENT, PAIRED_INTENT from dokimi.exit_codes import EXIT_FAILURE @@ -28,29 +28,6 @@ from dokimi.utils import InputError -def _load_runtime_config() -> dict: - import yaml - - from dokimi.config import runtime_config_path - - config_path = runtime_config_path() - if not config_path.exists(): - return {} - try: - loaded = yaml.safe_load(config_path.read_text(encoding="utf-8")) - except (OSError, UnicodeDecodeError) as exc: - raise InputError(f"cannot read {config_path}: {exc}") from exc - except (yaml.YAMLError, ValueError, RecursionError) as exc: # ValueError: a bad date; RecursionError: deep nesting - raise InputError(f"invalid YAML in {config_path}: {exc}") from exc - if loaded is not None and not isinstance(loaded, dict): - raise InputError(f"expected a mapping in {config_path}") - config = loaded or {} - for key in ("products", "retrieval"): - if config.get(key) is not None and not isinstance(config[key], dict): - raise InputError(f"'{key}' in {config_path} must be a mapping") - return config - - def _load_questions(path: str) -> list: from dokimi.questions.artifact import load_questions @@ -73,7 +50,7 @@ def _output_path(args: argparse.Namespace) -> Path: def cmd_answers_generate(args: argparse.Namespace) -> None: """Generate context-arm and baseline answers for questions.""" if getattr(args, "ragas", False): - _require_ragas() + require_ragas() from dokimi.eval import Answerer from dokimi.mcp.factory import ( create_doc_source_client, @@ -81,7 +58,7 @@ def cmd_answers_generate(args: argparse.Namespace) -> None: resolve_library_id_for_product, ) - config = _load_runtime_config() + config = load_runtime_config() _retrieval_cfg = config.get("retrieval") or {} if args.top_k is None: args.top_k = _retrieval_cfg.get("top_k", DEFAULT_RETRIEVAL_TOP_K) @@ -151,7 +128,7 @@ def cmd_answers_generate(args: argparse.Namespace) -> None: # Optional RAGAS meta-evaluation (--ragas flag) if getattr(args, "ragas", False): - _run_ragas_eval(answers, output_path, args) + run_ragas_eval(answers, output_path, args) def register(sub, positive_int) -> None: diff --git a/dokimi/dokimi/commands/arms.py b/dokimi/dokimi/commands/arms.py index c1ffb4acb1..42d6943992 100644 --- a/dokimi/dokimi/commands/arms.py +++ b/dokimi/dokimi/commands/arms.py @@ -29,6 +29,7 @@ JUDGE_MODEL_HELP, ) from dokimi.eval.question_text import EmptyQuestionError +from dokimi.artifacts import safe_file_name if TYPE_CHECKING: from dokimi.eval.arms_run import ArmsRunConfig @@ -225,10 +226,10 @@ def run_matrix(config: ArmsRunConfig, *, arms: str, questions: str, matrix_cells def before_run() -> None: # once every cell is set up; each cell names its partial file at its first save _make_cells_dir(cells_dir) - partials.update((cell.name, _Partial(cells_dir / f"{_safe_name(cell.name)}.json")) for cell in cells) + partials.update((cell.name, _Partial(cells_dir / f"{safe_file_name(cell.name)}.json")) for cell in cells) def save_cell(cell, output: dict) -> None: - safe_name = _safe_name(cell.name) + safe_name = safe_file_name(cell.name) cell_json = cells_dir / f"{safe_name}.json" _save_arms_output(output, cell_json, cells_dir / f"{safe_name}.md", partials.get(cell.name)) cell_artifacts.append((cell.name, cell_json, output)) @@ -717,15 +718,10 @@ def _validate_unique_cell_filenames(cells) -> None: """Reject matrix cells that would overwrite each other's artifacts.""" seen: dict[str, str] = {} for cell in cells: - safe_name = _safe_name(cell.name) + safe_name = safe_file_name(cell.name) if safe_name in seen: raise ValueError( "matrix cell names collide after filename sanitization: " f"{seen[safe_name]!r} and {cell.name!r} both map to {safe_name!r}" ) seen[safe_name] = cell.name - - -def _safe_name(name: str) -> str: - safe = "".join(c if c.isalnum() or c in ("-", "_", ".") else "-" for c in name) - return safe.strip("-") or "cell" diff --git a/dokimi/dokimi/commands/baseline.py b/dokimi/dokimi/commands/baseline.py index ae728bf5c5..6f5c149df0 100644 --- a/dokimi/dokimi/commands/baseline.py +++ b/dokimi/dokimi/commands/baseline.py @@ -49,7 +49,7 @@ def _read_eval(path: str) -> Tuple[bytes, Dict[str, Any]]: return raw, _json_object(path, data) -def _baseline_manifest() -> Dict[str, Any]: +def baseline_index() -> Dict[str, Any]: """Load or create the baseline manifest; a corrupt one is an :class:`InputError`.""" manifest_path = BASELINES_DIR / "manifest.json" if not manifest_path.exists(): @@ -208,7 +208,7 @@ def cmd_baseline_save(args: argparse.Namespace) -> None: from datetime import datetime, timezone eval_path = Path(args.from_eval) - manifest = _baseline_manifest() # first: a corrupt manifest fails fast and leaves no orphan file + manifest = baseline_index() # first: a corrupt manifest fails fast and leaves no orphan file raw, eval_data = _read_eval(args.from_eval) product = args.product or eval_data.get("product", "unknown") timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%f") @@ -258,7 +258,7 @@ def _remove_copy(copy: Path) -> None: def cmd_baseline_list(args: argparse.Namespace) -> None: """List all saved baselines.""" - manifest = _baseline_manifest() + manifest = baseline_index() baselines = manifest.get("baselines", []) product_filter = getattr(args, "product", None) @@ -342,7 +342,7 @@ def cmd_baseline_compare(args: argparse.Namespace) -> None: baseline_regression.require_gate_for_min_matched(args) eval_path = Path(args.eval) eval_data = _read_json_object(eval_path) - manifest = _baseline_manifest() + manifest = baseline_index() baselines = manifest.get("baselines", []) if not baselines: diff --git a/dokimi/dokimi/commands/benchmark.py b/dokimi/dokimi/commands/benchmark.py index 78abf5ac08..84bccf0057 100644 --- a/dokimi/dokimi/commands/benchmark.py +++ b/dokimi/dokimi/commands/benchmark.py @@ -29,7 +29,7 @@ JUDGE_MODEL_FOR_PROVIDER, JUDGE_MODEL_HELP, ) -from dokimi.commands.library import _load_registry +from dokimi.commands.library import load_registry from dokimi.exit_codes import EXIT_USAGE from dokimi.llm_cli import SamplingError from dokimi.utils import InputError, check_bedrock_model, refuse_device @@ -358,7 +358,7 @@ def _check_doc_source(plan: dict, entry: Any, refuse: Callable[[str], None], err def cmd_benchmark_preflight(args: argparse.Namespace) -> None: """Validate the resolved benchmark plan without running LLM calls.""" - registry = _load_registry(args) + registry = load_registry(args) try: entry = registry.get(args.library) except KeyError as exc: @@ -428,7 +428,7 @@ def cmd_benchmark_run(args: argparse.Namespace) -> None: """Run full evaluation pipeline for a single registered library.""" import statistics as _stats _refuse_judge_sampling(args) - registry = _load_registry(args) + registry = load_registry(args) try: entry = registry.get(args.library) except KeyError as exc: @@ -509,7 +509,7 @@ def cmd_benchmark_run(args: argparse.Namespace) -> None: def cmd_benchmark_batch(args: argparse.Namespace) -> None: """Run evaluation pipeline for multiple registered libraries.""" _refuse_judge_sampling(args) - registry = _load_registry(args) + registry = load_registry(args) if args.all_libraries or not args.libraries: entries = registry.list() diff --git a/dokimi/dokimi/commands/catalog_novelty.py b/dokimi/dokimi/commands/catalog_novelty.py index 627476ca59..67a0e1f57a 100644 --- a/dokimi/dokimi/commands/catalog_novelty.py +++ b/dokimi/dokimi/commands/catalog_novelty.py @@ -189,12 +189,12 @@ def _dirname(key: str) -> str: def _fingerprint(args: argparse.Namespace, placebo_text: Optional[str]) -> dict[str, Any]: """The settings a measured row was made under; a resumed run keeps a row only when these are unchanged.""" - from dokimi.commands.novelty import _settings + from dokimi.commands.novelty_flags import settings_from_args from dokimi.novelty import cost fingerprint = { "roles": {role: list(pair) for role, pair in cost.role_models(args).items()}, - "settings": dict(_settings(args).values), + "settings": dict(settings_from_args(args).values), "arms": args.arms, "budgets": list(args.budgets), "max_atoms": args.max_atoms, @@ -218,16 +218,17 @@ def _analyze_skill(args: argparse.Namespace, placebo_text: Optional[str], cache_ Returns the :class:`~dokimi.novelty.analyze.AnalyzeResult`; the caller decides what to save. """ - from dokimi.commands.novelty import _arms, _bundle_from_args, _settings, stamp + from dokimi.commands.novelty_flags import arms_from_spec, bundle_from_args, settings_from_args + from dokimi.commands.novelty import stamp from dokimi.novelty import cost from dokimi.novelty.analyze import AnalyzeConfig, analyze - bundle = _bundle_from_args(args) - settings = _settings(args) + bundle = bundle_from_args(args) + settings = settings_from_args(args) extractor, answerer, judge = cost.clients(args) config = AnalyzeConfig( artifact_ref=args.artifact, artifact_kind=bundle.kind, name=bundle.name, - description=bundle.description, frontmatter=bundle.frontmatter, arms=_arms(args.arms), + description=bundle.description, frontmatter=bundle.frontmatter, arms=arms_from_spec(args.arms), budgets=tuple(args.budgets), concurrency=args.concurrency, allow_self_judge=args.allow_self_judge, placebo_text=placebo_text, context_framing=args.context_framing, cache_dir=cache_dir, seed=args.seed, @@ -427,7 +428,7 @@ def _emit_summary(summary: dict, args: argparse.Namespace) -> None: def cmd_catalog_novelty(args: argparse.Namespace) -> None: from dokimi.commands.inputs import placebo_text_for_arms_or_exit - from dokimi.commands.novelty import _arms + from dokimi.commands.novelty_flags import arms_from_spec from dokimi.commands.novelty_run import usable_cache_dir from dokimi.novelty.client import SpendCap from dokimi.novelty.sweep import load_strata @@ -443,7 +444,7 @@ def cmd_catalog_novelty(args: argparse.Namespace) -> None: if not root.is_dir(): raise InputError(f"ROOT is not a directory: {root}") _refuse_unsafe_run(args, jsonl, out_dir) - placebo_text = placebo_text_for_arms_or_exit(args.placebo_text, _arms(args.arms)) + placebo_text = placebo_text_for_arms_or_exit(args.placebo_text, arms_from_spec(args.arms)) cache_dir = usable_cache_dir(args.cache_dir) all_items = _items(root, None) if not all_items: @@ -660,7 +661,7 @@ def review(item: _Item) -> Optional[dict]: def register(catalog_sub, positive_int) -> None: """Add ``catalog novelty``: the corpus sweep, a catalog verb like ``catalog routing``.""" - from dokimi.commands.novelty_flags import _add_bundle_args, _add_model_args + from dokimi.commands.novelty_flags import add_bundle_args, add_model_args from dokimi.cli_types import positive_usd from dokimi.novelty.sweep import RESAMPLES from dokimi.novelty.tiers import TIERS @@ -712,6 +713,6 @@ def register(catalog_sub, positive_int) -> None: p.add_argument("--seed", type=int, default=0, help="Seed for the controls and the selection, per skill") p.add_argument("--cache-dir", default=None, dest="cache_dir", help="Disk cache for retention adjudications") - _add_model_args(p, positive_int) # --model, --judge-model, ... and --max-usd: the whole-run budget - _add_bundle_args(p, positive_int) + add_model_args(p, positive_int) # --model, --judge-model, ... and --max-usd: the whole-run budget + add_bundle_args(p, positive_int) p.set_defaults(func=stops_at_cap(cmd_catalog_novelty)) diff --git a/dokimi/dokimi/commands/eval_graph.py b/dokimi/dokimi/commands/eval_graph.py index 81a7c87bfd..d5af602c90 100644 --- a/dokimi/dokimi/commands/eval_graph.py +++ b/dokimi/dokimi/commands/eval_graph.py @@ -238,7 +238,7 @@ def _as_skill(ref: str) -> str: def register(eval_sub) -> None: """Add ``eval graph`` to the ``eval`` group.""" from dokimi.commands.novelty_run import add_spend_cap - from dokimi.commands.repo_hits import _judge_ref as model_ref + from dokimi.commands._shared import judge_ref as model_ref from dokimi.defaults import DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER default = f"{DEFAULT_JUDGE_PROVIDER}/{DEFAULT_JUDGE_MODEL}" diff --git a/dokimi/dokimi/commands/evaluate.py b/dokimi/dokimi/commands/evaluate.py index 04e07af4c6..cc2e592916 100644 --- a/dokimi/dokimi/commands/evaluate.py +++ b/dokimi/dokimi/commands/evaluate.py @@ -6,7 +6,6 @@ from __future__ import annotations import argparse -import importlib.util import json import sys from pathlib import Path @@ -29,6 +28,7 @@ from dokimi.commands._output import save_artifact_or_exit from dokimi.exit_codes import EXIT_INCONCLUSIVE from dokimi.utils import InputError, warn_judge_independence, warn_recorded_self_judge +from dokimi.commands._shared import require_ragas, run_ragas_eval _warn_judge_independence = warn_judge_independence @@ -41,45 +41,6 @@ def _load_answers(path: str): return load(path, section="answers") -def _require_ragas() -> None: - """Exit before any model call when the ragas extra is not installed.""" - if importlib.util.find_spec("ragas") is None: - sys.exit("RAGAS meta-evaluation needs the ragas extra: pip install 'dokimi[ragas]'") - - -def _run_ragas_eval(answers, output_path, args) -> None: - """Run RAGAS meta-evaluation and save results alongside answers.""" - from dokimi.eval.question_text import EmptyQuestionError - from dokimi.eval.ragas_eval import RagasEvaluator - from dokimi.records import AskOutcomeError - - ragas_model = getattr(args, "ragas_model", DEFAULT_JUDGE_MODEL) - ragas_provider = getattr(args, "ragas_provider", DEFAULT_JUDGE_PROVIDER) - - print(f"\nšŸ” Running RAGAS meta-evaluation ({ragas_provider}/{ragas_model})...") - try: - evaluator = RagasEvaluator( - llm_model=ragas_model, - provider=ragas_provider, - ) - result = evaluator.evaluate(answers, include_without_docs=True) - - # Save ragas results alongside answers - ragas_path = output_path.with_name(output_path.stem + "_ragas.json") - payload = {**result.to_dict(), "ragas_model": f"{ragas_provider}/{ragas_model}"} - save_artifact_or_exit("ragas", payload, ragas_path, code=2) - - print(result.format_summary()) - print(f"āœ… Saved RAGAS results to {ragas_path}") - - except (AskOutcomeError, EmptyQuestionError): - raise # a bad input record is a refusal, not a RAGAS failure: cli.main reports it (exit 2) - except ImportError as exc: - sys.exit(f"RAGAS meta-evaluation was requested but cannot run: {exc}") - except Exception as exc: # noqa: BLE001 - RAGAS is an optional extra pass; its failure is printed - print(f"\nāš ļø RAGAS evaluation failed: {exc}") - - def _print_left_out(rows: list, valid: list) -> None: """The mean covers only the questions in `valid`; say how many it leaves out, so it is not read as the whole set.""" left_out = len(rows) - len(valid) @@ -247,7 +208,7 @@ def cmd_eval_score(args: argparse.Namespace) -> None: def cmd_eval_ragas(args: argparse.Namespace) -> None: """Run standalone RAGAS meta-evaluation on an answers JSON.""" - _require_ragas() + require_ragas() run = _load_answers(args.answers) answers = list(run.records) print(f"Loaded {len(answers)} answers from {args.answers}") @@ -258,7 +219,7 @@ class _Args: ragas_provider = args.ragas_provider output_path = Path(args.answers) - _run_ragas_eval(answers, output_path, _Args()) + run_ragas_eval(answers, output_path, _Args()) def cmd_eval_grounding(args: argparse.Namespace) -> None: @@ -285,9 +246,9 @@ def _validity_judges(args: argparse.Namespace) -> list[tuple[str, str]]: """``(model, provider)`` of the judge, then of the escalation judge; none for a typed scorer.""" if args.scorer != "judge": # a typed scorer reads the answer and calls no judge return [] - from dokimi.commands.judge_reliability import _pairwise_judges + from dokimi.commands._shared import pairwise_judges - return _pairwise_judges(args) # the judges pairwise_judge(args) builds; one copy of the escalation default + return pairwise_judges(args) # the judges pairwise_judge(args) builds; one copy of the escalation default def _judge_arg_problems(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/judge_reliability.py b/dokimi/dokimi/commands/judge_reliability.py index 752788302c..12723a0755 100644 --- a/dokimi/dokimi/commands/judge_reliability.py +++ b/dokimi/dokimi/commands/judge_reliability.py @@ -23,6 +23,7 @@ from dokimi.utils import InputError, read_json_input, warn_recorded_self_judge from dokimi.commands._output import save_artifact_or_exit, write_text_or_exit from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE, EXIT_INVALID +from dokimi.commands._shared import pairwise_judges if TYPE_CHECKING: from dokimi.eval.cross_judge import Measure @@ -128,14 +129,6 @@ def _check_judge_temperature(judges: list[tuple[str, str]], temperature) -> None raise InputError(f"--judge-temperature {temperature} is rejected by judge {provider}/{model}: {exc}") from exc -def _pairwise_judges(args: argparse.Namespace) -> list[tuple[str, str]]: - """``(model, provider)`` of the pairwise judge, then of the escalation judge when one is named.""" - judges = [(args.judge_model, args.judge_provider)] - if getattr(args, "escalate_model", None): - judges.append((args.escalate_model, args.escalate_provider or args.judge_provider)) - return judges - - def pairwise_judge(args: argparse.Namespace): """A both-order pairwise judge from --judge-* and optional --escalate-* args; returns (judge, label).""" from dokimi.eval.judge import Judge @@ -148,7 +141,7 @@ def asker(model: str, provider: str): return lambda prompt, draw=0, cache_if=None: llm.invoke(prompt, draw=draw, cache_if=cache_if).content label = f"{args.judge_provider}/{args.judge_model} pairwise" - judges = _pairwise_judges(args) + judges = pairwise_judges(args) escalate = None if len(judges) > 1: label += f" → {judges[1][1]}/{judges[1][0]}" @@ -170,7 +163,7 @@ def cmd_eval_pairwise(args: argparse.Namespace) -> None: arms = [a.strip() for a in args.arms.split(",")] if args.arms else None _require_arms(args.answers, records, "eval score pairwise") pairwise_jobs(records, baseline_arm=baseline, arms=arms) # refuse a blank question before the probe call - warn_recorded_self_judge(data, _pairwise_judges(args), "eval score pairwise") + warn_recorded_self_judge(data, pairwise_judges(args), "eval score pairwise") judge, label = pairwise_judge(args) print(f"Pairwise comparison: {label}, {len(records)} questions, baseline `{baseline}`") report = run_arm_pairwise( diff --git a/dokimi/dokimi/commands/library.py b/dokimi/dokimi/commands/library.py index 75c6d78f8f..38223267bb 100644 --- a/dokimi/dokimi/commands/library.py +++ b/dokimi/dokimi/commands/library.py @@ -48,7 +48,7 @@ def _load_custom(cls, flag: str, value): return loaded -def _load_registry(args): +def load_registry(args): """The registry for the `benchmark` commands: the same InputError as `_load_registry_checked`.""" return _load_registry_checked(args) diff --git a/dokimi/dokimi/commands/novelty.py b/dokimi/dokimi/commands/novelty.py index f2a0cfa48f..555b17b4ed 100644 --- a/dokimi/dokimi/commands/novelty.py +++ b/dokimi/dokimi/commands/novelty.py @@ -15,16 +15,13 @@ import json import sys from pathlib import Path -from typing import TYPE_CHECKING from dokimi.commands.inputs import placebo_text_for_arms_or_exit from dokimi.commands.novelty_run import (attach_panel, exit_if_analyze_partial, judge2_client, panel_clients, save_panel_verdicts, stamp, usable_cache_dir) from dokimi.utils import InputError - -if TYPE_CHECKING: - from dokimi.novelty.tiers import RunSettings +from dokimi.commands.novelty_flags import arms_from_spec, bundle_from_args, settings_from_args def cmd_novelty_analyze(args: argparse.Namespace) -> None: @@ -46,8 +43,8 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: from dokimi.commands.novelty_budget import print_estimate_only, print_run_estimate - artifact_bundle = _bundle_from_args(args) - settings = _settings(args) + artifact_bundle = bundle_from_args(args) + settings = settings_from_args(args) record = settings.tier_record() if record: print(f"Tier `{args.tier}`: " + ", ".join( @@ -63,7 +60,7 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: cache_dir = usable_cache_dir(args.cache_dir) print_run_estimate(args, settings, artifact_bundle.text, cost.estimate_usd) - placebo_text = placebo_text_for_arms_or_exit(args.placebo_text, _arms(args.arms)) + placebo_text = placebo_text_for_arms_or_exit(args.placebo_text, arms_from_spec(args.arms)) extractor, answerer, judge = cost.clients(args) panel = panel_clients(args, cost.client) judge2 = judge2_client(args, answerer, judge, cost.client, panel) @@ -73,7 +70,7 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: name=artifact_bundle.name, description=artifact_bundle.description, frontmatter=artifact_bundle.frontmatter, - arms=_arms(args.arms), + arms=arms_from_spec(args.arms), budgets=tuple(args.budgets), concurrency=args.concurrency, allow_self_judge=args.allow_self_judge, @@ -93,7 +90,7 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: raise InputError(str(exc)) from exc except (ExtractionError, ValueError) as exc: # a model failure under way raise SystemExit(str(exc)) from None - out_dir = Path(args.out_dir) if args.out_dir else _default_dir(args.artifact) + out_dir = Path(args.out_dir) if args.out_dir else default_dir(args.artifact) out_json = Path(args.out_json) if args.out_json else out_dir / "novelty.json" exit_if_analyze_partial(result, out_json) # a run the cap stopped keeps what it paid for stamp(result.artifact, args, result.measure_result, answerer=answerer, judge=judge, judge2=judge2) @@ -128,8 +125,8 @@ def cmd_novelty_atoms(args: argparse.Namespace) -> None: from dokimi.novelty.report import cap_warning from dokimi.novelty.spans import segment, span_summary - artifact_bundle = _bundle_from_args(args) - settings = _settings(args) + artifact_bundle = bundle_from_args(args) + settings = settings_from_args(args) extractor = cost.client(args.extract_model or args.model, args.extract_provider or args.provider, "extractor", args) spans = segment(artifact_bundle.text) cap = settings.values["max_atoms"] @@ -147,7 +144,7 @@ def cmd_novelty_atoms(args: argparse.Namespace) -> None: partial = extraction.partial # a cap that stopped extraction keeps what it read if settings.values["verify_faithfulness"] and partial is None: partial = verify_or_partial(sample, spans, extractor) - out = Path(args.out) if args.out else _default_dir(args.artifact) / "atoms.json" + out = Path(args.out) if args.out else default_dir(args.artifact) / "atoms.json" save_atoms_run(atoms, spans, out, partial, extractor=extractor.model, extractor_provider=extractor.provider, cap=cap, bundle=artifact_bundle.summary(), extraction=extraction, sample=sample) @@ -177,8 +174,8 @@ def cmd_novelty_probe(args: argparse.Namespace) -> None: raise InputError(verdict.message) for note in verdict.notes: print(note, file=sys.stderr) - settings = _settings(args) - placebo_text = placebo_text_for_arms_or_exit(args.placebo_text, _arms(args.arms)) + settings = settings_from_args(args) + placebo_text = placebo_text_for_arms_or_exit(args.placebo_text, arms_from_spec(args.arms)) extractor, answerer, judge = cost.clients(args) panel = panel_clients(args, cost.client) warn_answer_key(saved, answerer, judge) @@ -202,7 +199,7 @@ def cmd_novelty_probe(args: argparse.Namespace) -> None: try: result = run_measurement( atoms, probe_set.probes, verdict.text, answerer=answerer, judge=judge, - arms=_arms(args.arms), concurrency=args.concurrency, + arms=arms_from_spec(args.arms), concurrency=args.concurrency, allow_self_judge=args.allow_self_judge, seed=args.seed, placebo_text=placebo_text, framing=args.context_framing, panel=panel, aggregate=args.judge_aggregate, @@ -218,7 +215,7 @@ def cmd_novelty_probe(args: argparse.Namespace) -> None: ) attach_panel(payload, result, args.judge_aggregate, answerer.model) stamp(payload, args, result, answerer=answerer, judge=judge, judge2=judge2) - out = Path(args.out) if args.out else _default_dir(args.artifact) / "probes.json" + out = Path(args.out) if args.out else default_dir(args.artifact) / "probes.json" # A run the cap stopped keeps the answers it paid for, as a partial result (and exits). save_probe_measure(payload, out, result) print(f"OK Saved {len(result.runs)} probe runs: {out}") @@ -395,44 +392,7 @@ def cmd_novelty_view(args: argparse.Namespace) -> None: print(shares_text) -def _bundle_from_args(args: argparse.Namespace): - """Resolve `--artifact` to a bundle, with the note that keeps a cheap run honest.""" - from dokimi.novelty.bundle import load_bundle - - try: - artifact_bundle = load_bundle( - args.artifact, - include_resources=args.include_resources, - roles=tuple(args.resource_roles) if args.resource_roles else None, - max_file_words=args.max_file_words, - max_total_words=args.max_resource_words, - ) - except (OSError, ValueError, RecursionError) as exc: - raise InputError(f"cannot load --artifact {args.artifact}: {exc}") from exc - note = artifact_bundle.coverage_note() - if note: - print(f"NOTE: {note}", file=sys.stderr) - return artifact_bundle - - -def _settings(args: argparse.Namespace) -> RunSettings: - """The run settings these flags resolve to; a flag the command lacks is unset.""" - from dokimi.novelty.tiers import FLAG_DEFAULTS, resolve_settings - - return resolve_settings(getattr(args, "tier", None), { - flag: getattr(args, flag, default) for flag, default in FLAG_DEFAULTS.items()}) - - -def _arms(spec: str) -> tuple[str, ...]: - from dokimi.novelty.measure import parse_arms - - try: - return parse_arms(spec) - except ValueError as exc: - raise InputError(str(exc)) from exc - - -def _default_dir(ref: str) -> Path: +def default_dir(ref: str) -> Path: """Where results land when the caller named no output path.""" return Path("results/novelty") / _safe(ref) diff --git a/dokimi/dokimi/commands/novelty_budget.py b/dokimi/dokimi/commands/novelty_budget.py index ab04132e6a..43bca34e3b 100644 --- a/dokimi/dokimi/commands/novelty_budget.py +++ b/dokimi/dokimi/commands/novelty_budget.py @@ -19,7 +19,7 @@ from pathlib import Path from typing import NoReturn -from dokimi.commands.novelty_routing_report import _partial_destinations, stop_partial +from dokimi.commands.novelty_routing_report import partial_destinations, stop_partial def partial_destination(out: Path) -> Path: @@ -29,7 +29,7 @@ def partial_destination(out: Path) -> Path: ``out`` resolves to (a symlinked ``out``, dangling or not) is passed over: the save of ``out`` would land in it. The names are compared by :func:`_resolved`'s key, case and Unicode form aside.""" target = _resolved(out) - return next(p for p in _partial_destinations(Path(out)) if _resolved(p) != target) + return next(p for p in partial_destinations(Path(out)) if _resolved(p) != target) def _resolved(path: Path) -> str: @@ -44,7 +44,7 @@ def fresh_partial_destination(out: Path) -> Path: its ``--out`` spelling. A name that is the file ``out`` resolves to is passed over as in :func:`partial_destination`.""" target = _resolved(out) - return next(p for p in _partial_destinations(Path(out)) + return next(p for p in partial_destinations(Path(out)) if _resolved(p) != target and not os.path.lexists(p)) @@ -52,7 +52,7 @@ def partial_write(out: Path, write: Callable[[Path], object]) -> Path: """Run ``write`` on the first sidecar beside ``out`` that takes a partial result. A read-only file that holds one refuses the write, and is passed over for the next name, as the routing report's save does; a new file that is refused is raised.""" - for dest in _partial_destinations(Path(out)): + for dest in partial_destinations(Path(out)): try: write(dest) except PermissionError: diff --git a/dokimi/dokimi/commands/novelty_flags.py b/dokimi/dokimi/commands/novelty_flags.py index 486290d198..af3b47f034 100644 --- a/dokimi/dokimi/commands/novelty_flags.py +++ b/dokimi/dokimi/commands/novelty_flags.py @@ -1,18 +1,16 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""The argparse flags shared by `skill novelty analyze|atoms|probe` and `skill shorten`. - -Kept apart from `novelty.py` (its 800-line cap): these functions only declare flags, so the -flag set reads in one place. The flag names, defaults and help are unchanged. -""" +"""Shared argparse flags and input resolution for skill and catalog novelty.""" from __future__ import annotations import argparse +import sys +from typing import TYPE_CHECKING -from dokimi.cli_model_ref import add_model_flag from dokimi import cli_flags +from dokimi.cli_model_ref import add_model_flag from dokimi.cli_types import unit_interval from dokimi.commands.novelty_run import add_judge2_args, add_panel_args, add_spend_cap from dokimi.defaults import ( @@ -24,9 +22,50 @@ DEFAULT_JUDGE_PROVIDER, ) from dokimi.llm import ANSWER_PROVIDERS as PROVIDERS +from dokimi.utils import InputError + +if TYPE_CHECKING: + from dokimi.novelty.tiers import RunSettings + + +def settings_from_args(args: argparse.Namespace) -> RunSettings: + """The run settings these flags resolve to; a flag the command lacks is unset.""" + from dokimi.novelty.tiers import FLAG_DEFAULTS, resolve_settings + + return resolve_settings(getattr(args, "tier", None), { + flag: getattr(args, flag, default) for flag, default in FLAG_DEFAULTS.items()}) + + +def arms_from_spec(spec: str) -> tuple[str, ...]: + from dokimi.novelty.measure import parse_arms + + try: + return parse_arms(spec) + except ValueError as exc: + raise InputError(str(exc)) from exc + + +def bundle_from_args(args: argparse.Namespace): + """Resolve `--artifact` to a bundle, with the note that keeps a cheap run honest.""" + from dokimi.novelty.bundle import load_bundle + + try: + artifact_bundle = load_bundle( + args.artifact, + include_resources=args.include_resources, + roles=tuple(args.resource_roles) if args.resource_roles else None, + max_file_words=args.max_file_words, + max_total_words=args.max_resource_words, + ) + except (OSError, ValueError, RecursionError) as exc: + raise InputError(f"cannot load --artifact {args.artifact}: {exc}") from exc + note = artifact_bundle.coverage_note() + if note: + print(f"NOTE: {note}", file=sys.stderr) + return artifact_bundle -def _add_bundle_args(parser: argparse.ArgumentParser, positive_int) -> None: +def add_bundle_args(parser: argparse.ArgumentParser, positive_int) -> None: """Flags that decide *which files of the artifact* are measured. On `atoms` as well as `analyze`: the cheap path is `skill novelty atoms` once and @@ -55,7 +94,7 @@ def _add_bundle_args(parser: argparse.ArgumentParser, positive_int) -> None: "(reference, pattern, eval, rest) and recorded per exclusion") -def _add_common(parser: argparse.ArgumentParser, positive_int) -> None: +def add_common_args(parser: argparse.ArgumentParser, positive_int) -> None: parser.add_argument("--artifact", required=True, help="skill:, or text:") parser.add_argument("--max-atoms", type=positive_int, default=None, dest="max_atoms", @@ -73,14 +112,14 @@ def _add_common(parser: argparse.ArgumentParser, positive_int) -> None: "are reproducible across runs") -def _add_extractor_arg(parser: argparse.ArgumentParser, help: str) -> None: +def add_extractor_arg(parser: argparse.ArgumentParser, help: str) -> None: add_model_flag( parser, "--extract-model", dest="extract_model", provider_dest="extract_provider", providers=PROVIDERS, default_model=None, default_provider=None, help=help, ) -def _add_cache_dir(parser: argparse.ArgumentParser, *, reruns_pay_for: str) -> None: +def add_cache_dir_arg(parser: argparse.ArgumentParser, *, reruns_pay_for: str) -> None: """The retention memo: read by the commands that adjudicate retention (analyze, shorten).""" parser.add_argument("--cache-dir", default=None, dest="cache_dir", help="Disk memo of the retention adjudications only, not the model replies: " @@ -89,7 +128,7 @@ def _add_cache_dir(parser: argparse.ArgumentParser, *, reruns_pay_for: str) -> N f"writable directory); without it a rerun pays again for {reruns_pay_for}.") -def _add_model_args(parser: argparse.ArgumentParser, positive_int) -> None: +def add_model_args(parser: argparse.ArgumentParser, positive_int) -> None: add_model_flag( parser, "--model", dest="model", provider_dest="provider", providers=PROVIDERS, default_model=DEFAULT_ANSWER_MODEL, default_provider=DEFAULT_ANSWER_PROVIDER, @@ -107,7 +146,7 @@ def _add_model_args(parser: argparse.ArgumentParser, positive_int) -> None: "that runs on this provider; if none does, the run exits asking " "for --judge-model") add_panel_args(parser) - _add_extractor_arg(parser, "Extractor/adjudicator model (defaults to --judge-model, " + add_extractor_arg(parser, "Extractor/adjudicator model (defaults to --judge-model, " "so the answering model never writes its own answer key)") cli_flags.add(parser, "tokens", "--max-output-tokens", metavar="N", type=positive_int, default=None, dest="max_tokens", help="Output-token ceiling. Raise for reasoning models, which can " diff --git a/dokimi/dokimi/commands/novelty_routing.py b/dokimi/dokimi/commands/novelty_routing.py index ef3c9e668e..63b4e14544 100644 --- a/dokimi/dokimi/commands/novelty_routing.py +++ b/dokimi/dokimi/commands/novelty_routing.py @@ -15,7 +15,7 @@ from pathlib import Path from typing import NoReturn -from dokimi.commands.novelty import _default_dir +from dokimi.commands.novelty import default_dir from dokimi.commands.novelty_routing_inputs import checked_out_path, load_all_vs_all_field, load_routing_field from dokimi.commands.novelty_routing_report import ( check_all_vs_all_args, @@ -134,7 +134,7 @@ def cmd_routing(args: argparse.Namespace) -> tuple[dict, Path, str] | None: return None lexical = dict(lexical_routing(candidates, queries, gold=0), queries_self_derived=self_derived) - out = checked_out_path(args.out, "routing", default=str(_default_dir(args.artifact) / "routing.json")) + out = checked_out_path(args.out, "routing", default=str(default_dir(args.artifact) / "routing.json")) out.parent.mkdir(parents=True, exist_ok=True) if not lexical["n_queries_scored"]: _refuse_no_queries(args, queries, self_derived, out, len(candidates), queries_source) diff --git a/dokimi/dokimi/commands/novelty_routing_report.py b/dokimi/dokimi/commands/novelty_routing_report.py index ed8bbe237f..f4ad0f07a6 100644 --- a/dokimi/dokimi/commands/novelty_routing_report.py +++ b/dokimi/dokimi/commands/novelty_routing_report.py @@ -553,7 +553,7 @@ def _takes_partial(candidate: Path) -> bool: one (:func:`_wrote` tries the write). A FIFO or device is never opened: its read blocks (#516). A symlink, dangling or a loop, is not followed and is skipped: a write would land at its target. Any other error is raised, since every later name can fail the same way and the search would - not end. A name too long does not reach here: :func:`_partial_destinations` shortens the stem.""" + not end. A name too long does not reach here: :func:`partial_destinations` shortens the stem.""" try: mode = os.lstat(candidate).st_mode except FileNotFoundError: @@ -609,7 +609,7 @@ def _sidecar_stem(out: Path, tail: str = _LONGEST_TAIL) -> str: return stem + tag -def _partial_destinations(out: Path) -> Iterator[Path]: +def partial_destinations(out: Path) -> Iterator[Path]: """Each of ``.partial.json``, ``.partial2.json``, ... in turn that is free or holds a partial result (:func:`_takes_partial`), so a partial result never replaces a finished one. A stem too long for a name to fit is shortened for it (:func:`_sidecar_stem`).""" @@ -641,7 +641,7 @@ def save_result(payload: dict, out: Path, model_arm: dict) -> Path: ``model_arm`` is the arm the cap may have stopped: its ``partial`` block, if any, marks the result (:func:`partial_block`). A partial result goes to ``out`` unless ``out`` already holds something that is not itself a partial result (a finished measurement, or a file this cannot - read): then it goes to the first sidecar beside it (:func:`_partial_destinations`) that is free + read): then it goes to the first sidecar beside it (:func:`partial_destinations`) that is free or a writable partial result, so a cap does not replace a complete run with a prefix. """ payload.update(partial_block(model_arm)) @@ -652,7 +652,7 @@ def save_result(payload: dict, out: Path, model_arm: dict) -> Path: except ValueError as exc: # two skill names that are one once read back: nothing is written (#1163) raise InputError(f"cannot write the routing result to {out}: {exc}") from exc if "partial" in payload and out.exists() and not _is_partial_file(out): - return next(side for side in _partial_destinations(out) if _wrote(side, text)) + return next(side for side in partial_destinations(out) if _wrote(side, text)) out.write_text(text, encoding="utf-8") return out diff --git a/dokimi/dokimi/commands/questions.py b/dokimi/dokimi/commands/questions.py index 70a474e9f5..65d3070e2b 100644 --- a/dokimi/dokimi/commands/questions.py +++ b/dokimi/dokimi/commands/questions.py @@ -272,10 +272,10 @@ def print_validation_stats(stats: Dict[str, Any]) -> None: def cmd_questions_generate(args: argparse.Namespace) -> None: """Generate questions from personas and seed topics.""" - from dokimi.commands.answers import _load_runtime_config + from dokimi.commands._shared import load_runtime_config from dokimi.questions import RagasSeedExtractor, QuestionGenerator, QuestionValidator - config = _load_runtime_config() + config = load_runtime_config() _product_config = (config.get("products") or {}).get(args.product, {}) _retrieval_cfg = config.get("retrieval") or {} diff --git a/dokimi/dokimi/commands/repo.py b/dokimi/dokimi/commands/repo.py index 6fe12682a8..b802fd2eeb 100644 --- a/dokimi/dokimi/commands/repo.py +++ b/dokimi/dokimi/commands/repo.py @@ -6,7 +6,6 @@ from __future__ import annotations import argparse -import re import sys from pathlib import Path from typing import TYPE_CHECKING, Any @@ -18,39 +17,18 @@ from dokimi.commands.repo_reach import add_reach_parser from dokimi.commands.repo_skill_reach import add_skill_reach_parser from dokimi.exit_codes import EXIT_USAGE -from dokimi.commands.repo_scan import (_loaded_with_default, _print_scan_text, _scan_gate, _scan_reason, - _typecheck_or_exit) +from dokimi.commands._shared import (cache_dir_from_args, code_index_for, normalize_whitespace, parse_source, + print_scan_text, scan_gate, scan_reason, typecheck_or_exit) +from dokimi.commands.repo_scan import loaded_with_default from dokimi.utils import InputError, read_json_input -def _normalize_whitespace(text: str, max_len: int | None = 100) -> str: - """One line: whitespace runs become one space, control characters are escaped, then truncated.""" - flat = re.sub(r"\s+", " ", text).strip() - printable = "".join(c if c.isprintable() else c.encode("unicode_escape").decode("ascii") for c in flat) - return printable[:max_len] - - -def _parse_source(args: argparse.Namespace) -> RepoSource: - """The source as typed: a malformed string, an unpinned remote, a local path that is not a directory or a ``--cache-dir`` that is not a usable directory is a usage error (2); a local path the filesystem refuses to stat (no permission to traverse it) is 1.""" - from dokimi.repos import RepoSource, SourceError - - try: - source = RepoSource.parse(args.source) - except SourceError as exc: - raise InputError(str(exc)) from exc - except OSError as exc: # Path.is_dir raises PermissionError on Python 3.11-3.13 - print(f"āœ— {exc}", file=sys.stderr) - sys.exit(1) - _cache_dir(args) # a bad --cache-dir is a usage error too, and must not reach a handler of the clone's failures - return source - - def _open_tree(source: RepoSource, args: argparse.Namespace): """The source's tree, cloned into ``--cache-dir`` when remote: a bad ``--cache-dir`` or a pinned local path that is not the repository root is a usage error (2); a clone, fetch or pin resolution failure is 1.""" from dokimi.repos import SourceError, open_source from dokimi.repos.source import SourceArgumentError - cache_dir = _cache_dir(args) # before the handlers below: InputError is a ValueError + cache_dir = cache_dir_from_args(args) # before the handlers below: InputError is a ValueError try: return open_source(source, cache_dir) except SourceArgumentError as exc: @@ -60,9 +38,9 @@ def _open_tree(source: RepoSource, args: argparse.Namespace): sys.exit(1) -def _source_tree(args: argparse.Namespace) -> tuple: +def source_tree(args: argparse.Namespace) -> tuple: """The source (source, tree): a malformed string, unpinned remote or pinned local path that is not the repository root is a usage error (2); a clone, fetch or pin resolution failure is 1.""" - source = _parse_source(args) + source = parse_source(args) return source, _open_tree(source, args) @@ -74,7 +52,7 @@ def _manifest_or_exit(tree, args: argparse.Namespace, *, guidance_default: bool from dokimi.repos.source import SourceArgumentError try: - return _load_manifest(tree, args, guidance_default=guidance_default) + return manifest_for_tree(tree, args, guidance_default=guidance_default) except (SourceArgumentError, ManifestError, *also_usage) as exc: raise InputError(str(exc)) from exc except SourceError as exc: @@ -87,7 +65,7 @@ def cmd_repo_validate(args: argparse.Namespace) -> None: from dokimi.repos import check_repo from dokimi.repos.source import base_opener - source, tree = _source_tree(args) + source, tree = source_tree(args) manifest = _manifest_or_exit(tree, args) open_base = base_opener(source, tree) report = check_repo(tree, manifest, open_base) @@ -141,12 +119,12 @@ def cmd_repo_scan(args: argparse.Namespace) -> None: from dokimi.repos.l0 import scan_repo from dokimi.repos.l0.typecheck import TypecheckError - _, tree = _source_tree(args) + _, tree = source_tree(args) manifest = _manifest_or_exit(tree, args, guidance_default=True, also_usage=(OSError,)) static = _read_static(args.static) if args.static else None - check = _typecheck_or_exit(args) + check = typecheck_or_exit(args) try: - loaded, not_counted = _loaded_with_default(tree, manifest) + loaded, not_counted = loaded_with_default(tree, manifest) payload = scan_repo(tree, manifest, static, typecheck=check, also=loaded, not_counted=not_counted) except TypecheckError as exc: print(f"āœ— repo scan --typecheck: {exc}", file=sys.stderr) # the error says whether the tool or the interpreter @@ -167,31 +145,18 @@ def cmd_repo_scan(args: argparse.Namespace) -> None: failed = bool(gate and (new_failures(payload) or payload["incomplete"]) or static_errors) cli_output.emit_leaf("repo scan", stamp("repo_readiness", dict(payload)), status="failed" if failed else "complete", - reason=_scan_reason(payload, static_errors, gate) if failed else None, + reason=scan_reason(payload, static_errors, gate) if failed else None, next_steps=[] if failed else [_budget_step(args)], subjects=scan_subjects(payload), summary={"claims": dict(payload["counts"]), "files": len(payload["files"]), "adapters": ", ".join(payload.get("adapters") or []) or "none"}) else: - _print_scan_text(manifest, payload, args.out) - _scan_gate(payload, gate) # runs first: an invalid --static still gets the incomplete reason + print_scan_text(manifest, payload, args.out) + scan_gate(payload, gate) # runs first: an invalid --static still gets the incomplete reason if static_errors: sys.exit(1) -def _code_index(path: str | None) -> Any: - """The SCIP index at ``path`` (``None`` without one); exit 2 when it cannot be read.""" - if path is None: - return None - from dokimi.repos.code_index import load - from dokimi.repos.errors import CodeIndexError - - try: - return load(path) - except (OSError, CodeIndexError) as exc: - raise InputError(f"cannot read the code index {path}: {exc}") from exc - - def _print_structure(section: dict[str, Any] | None) -> None: if section is None: return @@ -202,7 +167,7 @@ def _print_structure(section: dict[str, Any] | None) -> None: + f", {len(section['modules'])} modules, {len(kept)} kept" + ("; top reference fan-in:" if kept else "")) for m in kept[:5]: share = "n/a" if m["ambiguity"] is None else f"{m['ambiguity']:.2f}" - print(f" {_normalize_whitespace(m['module'], max_len=None)}: fan-in {m['reference_fanin']}, " + print(f" {normalize_whitespace(m['module'], max_len=None)}: fan-in {m['reference_fanin']}, " f"other-tree modules {m['other_tree_modules']}, ambiguity {share}" + ("" if m["in_guidance"] else ", not in guidance")) @@ -223,8 +188,8 @@ def cmd_repo_inspect(args: argparse.Namespace) -> None: from dokimi.artifacts import save_artifact, stamp from dokimi.repos.environment import inspect_repo - _, tree = _source_tree(args) - payload = inspect_repo(tree, large=args.large_bytes, index=_code_index(args.index)) + _, tree = source_tree(args) + payload = inspect_repo(tree, large=args.large_bytes, index=code_index_for(args.index)) if "structure" in payload and not payload["structure"]["index"]["documents_in_tree"]: raise InputError(f"no document of the code index {args.index} is a file of this tree") if args.out: @@ -253,8 +218,8 @@ def cmd_repo_inspect(args: argparse.Namespace) -> None: print(f" findings: {c['error']} error, {c['warning']} warning, {c['info']} info") for f in payload["findings"]: if f["severity"] != "info": - where = f" {_normalize_whitespace(f['path'], max_len=None)}" if f["path"] else "" - print(f" {f['severity'].upper()} {f['rule']}{where} -- {_normalize_whitespace(f['why'])}") + where = f" {normalize_whitespace(f['path'], max_len=None)}" if f["path"] else "" + print(f" {f['severity'].upper()} {f['rule']}{where} -- {normalize_whitespace(f['why'])}") print(" stages: " + ", ".join(f"{s['stage']} {s['status']}" for s in payload["stages"])) _print_structure(payload.get("structure")) if args.out: @@ -292,7 +257,7 @@ def cmd_repo_budget(args: argparse.Namespace) -> None: profile = load_profile(args.harness) except ProfileError as exc: raise InputError(str(exc)) from exc - _, tree = _source_tree(args) + _, tree = source_tree(args) payload = budget(tree, profile.guidance_names, profile.import_max_depth, profile.reads_claude_rules, claude_displaces_agents=profile.claude_displaces_agents, follow_imports=profile.follows_imports) @@ -331,7 +296,7 @@ def cmd_repo_budget(args: argparse.Namespace) -> None: ) -def _load_manifest(tree, args: argparse.Namespace, *, guidance_default: bool = False): +def manifest_for_tree(tree, args: argparse.Namespace, *, guidance_default: bool = False): """The manifest from the tree, or from --manifest-file for a repository not aligned yet. With ``guidance_default`` (the commands that only read guidance), a tree with neither @@ -384,22 +349,6 @@ def _manifest_id(label: str) -> str: return name or "repo" -def _cache_dir(args: argparse.Namespace) -> Path | None: - """``--cache-dir`` as given, or ``None``; a value no clone can be cached in is a usage error (2) (#765). - - Without the flag, a non-empty ``$DOKIMI_REPO_CACHE`` is checked and returned the same way (#827); the flag wins. - A read-only directory passes: a populated one replays without writing; an empty one fails later with exit 1. - """ - import os - - from dokimi.commands.cache_dir import CLONE_USE, resolved_cache_dir - - env = os.environ.get("DOKIMI_REPO_CACHE") - if not args.cache_dir and env: - return resolved_cache_dir(env, CLONE_USE, label="$DOKIMI_REPO_CACHE") - return resolved_cache_dir(args.cache_dir, CLONE_USE, label="--cache-dir") - - def register(sub, positive_int, eval_sub) -> None: """Add the `repo` subcommand group. Its check moved to `eval check` (#94 M1).""" repo_p = sub.add_parser( @@ -484,7 +433,7 @@ def register(sub, positive_int, eval_sub) -> None: fetch_p.add_argument("--cache-dir", default=None, dest="cache_dir", help=cache_help) fetch_p.set_defaults(func=cmd_repo_fetch, emits_cli_output=True, cli_kind="repo fetch") - add_reach_parser(repo_sub, positive_int, source_help, cache_help, _open_tree, _load_manifest) + add_reach_parser(repo_sub, positive_int, source_help, cache_help, _open_tree, manifest_for_tree) add_skill_reach_parser(repo_sub, positive_int) diff --git a/dokimi/dokimi/commands/repo_hits.py b/dokimi/dokimi/commands/repo_hits.py index 51f5a23222..5eb5bef27d 100644 --- a/dokimi/dokimi/commands/repo_hits.py +++ b/dokimi/dokimi/commands/repo_hits.py @@ -20,17 +20,7 @@ from dokimi.utils import InputError from ._output import exit_on_unwritable - - -def _judge_ref(text: str) -> tuple[str, str]: - """``PROVIDER/MODEL`` as ``(provider, model)``; the model may hold more slashes (``openrouter/a/b``).""" - from dokimi.llm import ANSWER_PROVIDERS, PROVIDER_ALIASES - - provider, sep, model = text.partition("/") - known = (*ANSWER_PROVIDERS, *PROVIDER_ALIASES) - if not sep or not model.strip() or provider not in known: - raise argparse.ArgumentTypeError(f"takes PROVIDER/MODEL, PROVIDER one of {', '.join(known)}; got {text!r}") - return provider, model +from dokimi.commands._shared import judge_ref def _batch(args: argparse.Namespace) -> Path: @@ -203,7 +193,7 @@ def register(repo_sub, positive_int, usd: Callable[[str], float]) -> None: "judge", help="Label each credited (thread, finding) pair same point, related or unrelated with a judge " "model, reading the full texts; write /hits_judged.json with recall_judged (<= recall)") judge_p.add_argument("batch_dir", help="/ of `repo run`") - judge_p.add_argument("--judge", required=True, type=_judge_ref, metavar="PROVIDER/MODEL", + judge_p.add_argument("--judge", required=True, type=judge_ref, metavar="PROVIDER/MODEL", help="The judge; refused when it runs the model of any answer of the batch") judge_p.add_argument("--labels", default=None, metavar="FILE", help="A `repo hits sheet` file with `label` filled in: report agreement and Cohen's kappa " diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index d6cea34eb9..e970c98ff7 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -27,9 +27,10 @@ from dokimi.repos.source import SourceArgumentError, tree_path from dokimi.utils import tree_digest from dokimi.utils import InputError +from dokimi.commands._shared import run_errors -def _refuse_typed(source, args: argparse.Namespace) -> None: +def refuse_typed(source, args: argparse.Namespace) -> None: """Exit 2 for what the user typed: a pinned local path inside a repository, or a ``--manifest`` that leaves the tree as written. A path the tree supplies (a link out of it) fails later, with exit 1.""" from dokimi.repos.source import check_pinned_root @@ -63,8 +64,8 @@ def _context(args: argparse.Namespace, out: Path, source, pin: bool = False): With ``pin`` (a batch), the batch keeps the eval tree it started with: a later invocation from another revision would grade new cells with other graders, so it is refused. A working tree has no revision, so the batch is pinned to the digests of its eval dir and of the image - (whose tag is the build context's digest). ``source`` is the source as typed (``_parse_source``), already refused - by :func:`_refuse_typed` when the user mistyped it. + (whose tag is the build context's digest). ``source`` is the source as typed (``parse_source``), already refused + by :func:`refuse_typed` when the user mistyped it. """ from dokimi.repos import open_source from dokimi.repos.container import DockerRunner @@ -76,20 +77,21 @@ def _context(args: argparse.Namespace, out: Path, source, pin: bool = False): from dokimi.repos.manifest import require_runnable - from .repo import _cache_dir, _load_manifest + from ._shared import cache_dir_from_args + from .repo import manifest_for_tree - tree = open_source(source, _cache_dir(args)) - manifest = _load_manifest(tree, args) + tree = open_source(source, cache_dir_from_args(args)) + manifest = manifest_for_tree(tree, args) require_runnable(manifest) if manifest.image is None: raise ValueError(f"{manifest.path} declares no `image`; entry points and agents run in it") _check_cache_paths(args, manifest) # before the export and the image build (#826) - git_dir = source_git_dir(source, tree, _cache_dir(args)) + git_dir = source_git_dir(source, tree, cache_dir_from_args(args)) content = out / "_eval" / "content" # a pinned batch keeps its content until the pin is checked staged = export_eval_dir(tree, manifest, content.with_name("content.next") if pin else content) _require_grade(staged, manifest, args.task) # before the pin and the image build - suite = _suite_bases(args, tree, staged, manifest, _cache_dir(args)) # its pins go in the batch pin + suite = _suite_bases(args, tree, staged, manifest, cache_dir_from_args(args)) # its pins go in the batch pin runner = DockerRunner(args.docker) image, ctx_dir = args.image, None if not image: @@ -257,16 +259,6 @@ def _progress(line: str) -> None: print(line, flush=True) -def _errors(): - from dokimi.repos import ManifestError, SourceError - from dokimi.repos.container import ContainerError - from dokimi.repos.harness_profile import ProfileError - from dokimi.repos.arms import ArmError - from dokimi.repos.workspace import PrepError - - return (ArmError, SourceError, ManifestError, ContainerError, PrepError, ProfileError, ValueError, OSError) - - def cmd_eval_check(args: argparse.Namespace) -> None: """`eval check`: the self-check, or with --schema-only the manifest and task checks (`repo validate`, #94 M1).""" from .repo import cmd_repo_validate @@ -287,11 +279,11 @@ def cmd_repo_tasks_check(args: argparse.Namespace) -> None: from dokimi.repos.selfcheck import run_check from dokimi.repos.workspace import load_tasks, parse_arm - from .repo import _parse_source + from ._shared import parse_source out = Path(args.out).resolve() - source = _parse_source(args) - _refuse_typed(source, args) # before the manifest, the image build and the tasks + source = parse_source(args) + refuse_typed(source, args) # before the manifest, the image build and the tasks _check_cache_flags(args) # before the source is opened try: ctx, _ = _context(args, out, source) @@ -306,7 +298,7 @@ def cmd_repo_tasks_check(args: argparse.Namespace) -> None: results = run_check(ctx, tasks, out / "check", warm=args.warm, jobs=args.jobs, log=_progress) except InputError: # a ValueError: a bad cache path is a usage error (2), not a failed run (1) (#826) raise - except _errors() as exc: + except run_errors() as exc: print(f"āœ— {exc}", file=sys.stderr) sys.exit(1) bad = [r for r in results if r["verdict"] != "ok"] @@ -334,20 +326,21 @@ def cmd_repo_tasks_replay(args: argparse.Namespace) -> None: from dokimi.repos.replay import DEFAULT_PROMPT, History, Options, build_all, read_threads from dokimi.repos.workspace import source_git_dir - from .repo import _cache_dir, _load_manifest, _parse_source + from ._shared import cache_dir_from_args, parse_source + from .repo import manifest_for_tree - source = _parse_source(args) - _refuse_typed(source, args) # before the input files: a source refusal is not masked by an unreadable one + source = parse_source(args) + refuse_typed(source, args) # before the input files: a source refusal is not masked by an unreadable one try: prs = read_threads(Path(args.threads)) prompt = Path(args.prompt_file).read_text(encoding="utf-8").strip() if args.prompt_file else DEFAULT_PROMPT if not prompt: raise ValueError(f"the prompt file {args.prompt_file} is empty") - tree = open_source(source, _cache_dir(args)) - manifest = _load_manifest(tree, args) + tree = open_source(source, cache_dir_from_args(args)) + manifest = manifest_for_tree(tree, args) opts = Options(out=Path(args.out), window=args.window, prompt=prompt, force=args.force, fetch=source.remote) - outcomes = build_all(History(source_git_dir(source, tree, _cache_dir(args))), manifest, prs, opts) - except _errors() as exc: + outcomes = build_all(History(source_git_dir(source, tree, cache_dir_from_args(args))), manifest, prs, opts) + except run_errors() as exc: print(f"āœ— {exc}", file=sys.stderr) sys.exit(1) for o in outcomes: @@ -372,21 +365,22 @@ def cmd_repo_tasks_authoring(args: argparse.Namespace) -> None: from dokimi.repos.replay.authoring_prs import build_all from dokimi.repos.workspace import source_git_dir - from .repo import _cache_dir, _load_manifest, _parse_source + from ._shared import cache_dir_from_args, parse_source + from .repo import manifest_for_tree - source = _parse_source(args) - _refuse_typed(source, args) # before the input files: a source refusal is not masked by an unreadable one + source = parse_source(args) + refuse_typed(source, args) # before the input files: a source refusal is not masked by an unreadable one try: prs = read_threads(Path(args.prs), "mergeCommit", "pull request file") text = Path(args.prompt_file).read_text(encoding="utf-8").strip() if args.prompt_file else DEFAULT_INSTRUCTION if not text: raise ValueError(f"the prompt file {args.prompt_file} is empty") - tree = open_source(source, _cache_dir(args)) - manifest = _load_manifest(tree, args) + tree = open_source(source, cache_dir_from_args(args)) + manifest = manifest_for_tree(tree, args) opts = Options(out=Path(args.out), max_lines=args.max_lines, instruction=text, force=args.force, fetch=source.remote) - outcomes = build_all(History(source_git_dir(source, tree, _cache_dir(args))), manifest, prs, opts) - except _errors() as exc: + outcomes = build_all(History(source_git_dir(source, tree, cache_dir_from_args(args))), manifest, prs, opts) + except run_errors() as exc: print(f"āœ— {exc}", file=sys.stderr) sys.exit(1) for o in outcomes: @@ -426,10 +420,10 @@ def _run_locked(args: argparse.Namespace, arms: list[str], batch_dir: Path, lock from dokimi.repos.selfcheck import ANCESTOR_NAMES, isolation_probe from dokimi.repos.workspace import load_tasks, parse_arm, source_git_dir - from .repo import _cache_dir, _parse_source + from ._shared import cache_dir_from_args, parse_source - source = _parse_source(args) # as typed, before the build and the pin: a usage error - _refuse_typed(source, args) # before the arms and the harness + source = parse_source(args) # as typed, before the build and the pin: a usage error + refuse_typed(source, args) # before the arms and the harness _check_cache_flags(args) # before `pin_arms` opens the source try: parsed = [parse_arm(a) for a in arms] # before the image build: a typo or an unreadable patch fails now @@ -438,7 +432,7 @@ def _run_locked(args: argparse.Namespace, arms: list[str], batch_dir: Path, lock candidates = load_candidate_file(args.candidates) if args.candidates else None profile.tool_args(args.tools, args.delegation) # a profile that cannot turn subagents off: refuse now harness_bin = _harness_bin(args.bin or profile.bin) - arms = pin_arms(parsed, source_git_dir(source, open_source(source, _cache_dir(args)), _cache_dir(args)), + arms = pin_arms(parsed, source_git_dir(source, open_source(source, cache_dir_from_args(args)), cache_dir_from_args(args)), args.source) lock.enter_context(batch_lock(batch_dir)) # before _context, which rewrites _eval/content ctx, _ = _context(args, batch_dir, source, pin=True) @@ -473,7 +467,7 @@ def _run_locked(args: argparse.Namespace, arms: list[str], batch_dir: Path, lock sys.exit(EXIT_INFRA) except ConfigRefused as exc: # a config the agent's CLI rejects: refused before any cell, not rerun (exit 2) raise InputError(str(exc)) from exc # cli.main prints it and exits 2 - except _errors() as exc: + except run_errors() as exc: print(f"āœ— {exc}", file=sys.stderr) sys.exit(1) print(f"{summary['ran']} ran, {summary['skipped']} already done, {len(summary['errors'])} crashed, " diff --git a/dokimi/dokimi/commands/repo_scan.py b/dokimi/dokimi/commands/repo_scan.py index bda915b4d3..fcadc96d15 100644 --- a/dokimi/dokimi/commands/repo_scan.py +++ b/dokimi/dokimi/commands/repo_scan.py @@ -11,33 +11,11 @@ import posixpath import re import sys -import shutil -from dokimi.repos.l0.config import new_failures from dokimi.utils import InputError, read_json_input -def _typecheck_or_exit(args: argparse.Namespace): - """The ``--typecheck`` check, or None; ``--python-env`` needs it and must name an interpreter.""" - from dokimi.repos.l0 import Check - - if not args.typecheck: - if args.python_env is not None: - raise InputError("--python-env needs --typecheck") - if args.typecheck_tool is not None: - raise InputError("--typecheck-tool needs --typecheck") - return None - tool = args.typecheck_tool or "mypy" - # a directory is X_OK too: only a regular file can be the interpreter - if args.python_env is not None and not (os.path.isfile(args.python_env) and os.access(args.python_env, os.X_OK)): - raise InputError(f"--python-env {args.python_env}: not an executable interpreter") - if tool != "mypy" and shutil.which(tool) is None: - raise InputError(f"--typecheck-tool {tool}: not on PATH") - python = os.path.abspath(args.python_env) if args.python_env is not None else None # the tool runs elsewhere - return Check(tool, python) - - -def _loaded_with_default(tree, manifest) -> tuple[tuple[str, ...], tuple[str, ...]]: +def loaded_with_default(tree, manifest) -> tuple[tuple[str, ...], tuple[str, ...]]: """The rules and the Markdown ``@`` imports Claude Code loads with the default guidance, and the warnings of the rules budget does not count (a linked ``.claude/rules``); for a written manifest the rules and imports are () and the warnings are the guidance paths the tree could not look at. @@ -213,65 +191,6 @@ def _listed(tree, listed: set[str], path: str) -> str | None: return target if target in listed else None -def _print_scan_text(manifest, payload: dict, out: str | None) -> None: - """The text report of ``repo scan``: the counts, the warnings, the typecheck and static lines, the FAIL lines.""" - c = payload["counts"] - detected = " (detected)" if payload["adapters_detected"] else "" - print(f"{manifest.id}: {len(payload['files'])} guidance files in {payload['repo']['tree']}; " - f"adapters: {', '.join(payload['adapters']) or 'none'}{detected}") - ignored = f" ({c['ignored']} ignored)" if c.get("ignored") else "" - print(f" claims: {c['total']} (ok {c['ok']}, unresolved {c['unresolved']}{ignored}, fail {c['fail']})") - for warning in payload["warnings"]: - print(f" warning: {warning}") - if payload["incomplete"]: - print(f" incomplete: {'; '.join(payload['incomplete_reasons'])} (repo scan --fail-on fail exits 1)") - tc = payload["typecheck"] - if tc is not None: - where = tc["python"] or "no --python-env: unknown" - print(f" typecheck {tc['tool']} {tc['tool_version'] or ''} ({where}): {tc['fences']} python fences, " - f"{tc['checked']} checked, {tc['fail']} fail, {tc['unknown']} unknown, {tc['syntax']} not Python") - static_info = payload["static"] - if static_info is not None and not static_info["errors"]: - r = payload["by_source"]["repository"] - print(f" repository static: {r['total']} claims, {r['fail']} fail; " - f"{static_info['superseded']} framework claims replaced") - base = payload.get("baseline") - if base: - print(f" baseline {base['source']}: {base['new']} new fail, {base['known']} known, {base['fixed']} fixed") - for claim in payload["claims"]: - if claim["status"].split("_", 1)[0] == "fail": - mark = "known" if claim.get("baselined") else "FAIL" - print(f" {mark} {claim['file']}:{claim['line']} [{claim.get('kind')}] " - f"{str(claim.get('claim'))[:90]} -- {claim.get('why')}") - if out: - print(f"wrote {out}") - - -def _scan_reason(payload: dict, static_errors: list, gate: bool) -> str: - """Why a --json scan failed: every cause the gate tripped on, joined by ``; `` (a scan can fail on more than - one). The --static problems always fail the run; the failed claims and the incomplete scan only under - --fail-on fail.""" - parts = [] - if static_errors: - parts.append(f"{len(static_errors)} --static problem(s) not merged") - if gate and new_failures(payload): - known = (payload.get("baseline") or {}).get("known") - parts.append(f"{new_failures(payload)} claim(s) failed" + (f" ({known} more known in the baseline)" if known else "")) - if gate and payload["incomplete"]: - reasons = "; ".join(payload.get("incomplete_reasons") or []) - parts.append(f"scan incomplete: {reasons}" if reasons else "scan incomplete") - return "; ".join(parts) - - -def _scan_gate(payload: dict, gate: bool) -> None: - """--fail-on fail: exit 1 on a failed claim or an incomplete scan, saying on stderr what the scan missed.""" - if not gate or not (new_failures(payload) or payload["incomplete"]): - return - if payload["incomplete"]: - print(f"āœ— scan incomplete: {'; '.join(payload['incomplete_reasons'])}", file=sys.stderr) - sys.exit(1) - - def baseline_from(args: argparse.Namespace, payload: dict) -> None: """--baseline FILE: mark the fail claims that earlier report also fails; a file that cannot be read is exit 2.""" from dokimi.repos.l0.config import apply_baseline diff --git a/dokimi/dokimi/commands/runs.py b/dokimi/dokimi/commands/runs.py index 2e13fafb15..6b18836d21 100644 --- a/dokimi/dokimi/commands/runs.py +++ b/dokimi/dokimi/commands/runs.py @@ -359,9 +359,9 @@ def _baselines_held(root: Path, pointers: bool) -> dict[str, str]: def _manifest_held() -> dict[str, str]: - from dokimi.commands.baseline import BASELINES_DIR, _baseline_manifest + from dokimi.commands.baseline import BASELINES_DIR, baseline_index manifest = BASELINES_DIR / "manifest.json" - try: # _baseline_manifest's Path.exists() reads "no permission" as absent on Python 3.14 + try: # baseline_index's Path.exists() reads "no permission" as absent on Python 3.14 found = lookup(manifest) unreachable = found is None and lookup(manifest, follow_symlinks=False) except OSError as exc: @@ -373,7 +373,7 @@ def _manifest_held() -> dict[str, str]: if found is not None and not stat.S_ISREG(found.st_mode): # a FIFO would block gc, under the lock raise InputError(f"{manifest.as_posix()}: not a regular file, so the runs the baselines " "hold are not known") - return baseline_runs(_baseline_manifest()["baselines"]) + return baseline_runs(baseline_index()["baselines"]) def _age(text: str) -> timedelta: diff --git a/dokimi/dokimi/commands/skill.py b/dokimi/dokimi/commands/skill.py index 4aa4e12b03..6603f18165 100644 --- a/dokimi/dokimi/commands/skill.py +++ b/dokimi/dokimi/commands/skill.py @@ -61,7 +61,11 @@ def register_check(skill_sub) -> None: def register_skill(skill_sub, positive_int) -> None: """Add `skill novelty` (analyze, atoms, probe, ground, items, view) and `skill shorten` (#94 M2).""" from dokimi.commands.novelty_flags import ( - _add_bundle_args, _add_cache_dir, _add_common, _add_extractor_arg, _add_model_args, + add_bundle_args, + add_cache_dir_arg, + add_common_args, + add_extractor_arg, + add_model_args, ) from dokimi.commands.novelty import ( cmd_novelty_analyze, @@ -86,9 +90,9 @@ def register_skill(skill_sub, positive_int) -> None: analyze_p = novelty_sub.add_parser( "analyze", help="Full pipeline: atoms → probes → categories → attribution → shortening" ) - _add_common(analyze_p, positive_int) - _add_model_args(analyze_p, positive_int) - _add_cache_dir(analyze_p, reruns_pay_for="every model call except memoized retention adjudications") + add_common_args(analyze_p, positive_int) + add_model_args(analyze_p, positive_int) + add_cache_dir_arg(analyze_p, reruns_pay_for="every model call except memoized retention adjudications") analyze_p.add_argument("--out-dir", default=None, dest="out_dir", help="Directory for novelty.json and the view (default: results/novelty/)") cli_flags.add(analyze_p, "output", "--out", default=None, dest="out_json", @@ -117,11 +121,11 @@ def register_skill(skill_sub, positive_int) -> None: cli_flags.add(analyze_p, "dry_run", "--dry-run", action="store_true", dest="estimate_only", help="Print the projected model-call bill and exit without " "spending anything") - _add_bundle_args(analyze_p, positive_int) + add_bundle_args(analyze_p, positive_int) analyze_p.set_defaults(func=stops_at_cap(cmd_novelty_analyze)) atoms_p = novelty_sub.add_parser("atoms", help="Extract knowledge atoms and spans only") - _add_common(atoms_p, positive_int) + add_common_args(atoms_p, positive_int) # The extractor writes the answer key; `analyze` gives that role to the judge, so the # two paths default to the same model and a saved atom set matches an analyze run. add_model_flag( @@ -130,19 +134,19 @@ def register_skill(skill_sub, positive_int) -> None: help="Extractor model when --extract-model is not given " f"(default: {DEFAULT_JUDGE_MODEL}, the default judge)", ) - _add_extractor_arg(atoms_p, "Extractor model override (a bare model uses the --model provider)") + add_extractor_arg(atoms_p, "Extractor model override (a bare model uses the --model provider)") cli_flags.add(atoms_p, "tokens", "--max-output-tokens", metavar="N", type=positive_int, default=None, dest="max_tokens", help="Output-token ceiling per extraction call; raise it for reasoning models") atoms_p.add_argument("--no-verify", action="store_true", dest="no_verify", help="Skip the per-atom faithfulness check") atoms_p.add_argument("--out", default=None, help="atoms.json output path") add_spend_cap(atoms_p) - _add_bundle_args(atoms_p, positive_int) + add_bundle_args(atoms_p, positive_int) atoms_p.set_defaults(func=stops_at_cap(cmd_novelty_atoms)) probe_p = novelty_sub.add_parser("probe", help="Run paired probes against a saved atom set") - _add_common(probe_p, positive_int) - _add_model_args(probe_p, positive_int) + add_common_args(probe_p, positive_int) + add_model_args(probe_p, positive_int) probe_p.add_argument("--atoms", required=True, help="atoms.json from `skill novelty atoms`") probe_p.add_argument("--out", default=None, help="probes.json output path") probe_p.set_defaults(func=stops_at_cap(cmd_novelty_probe)) @@ -224,8 +228,8 @@ def register_skill(skill_sub, positive_int) -> None: shorten_p = skill_sub.add_parser( "shorten", help="Score shortening candidates on tokens/knowledge/value/protection/routing" ) - _add_common(shorten_p, positive_int) - _add_cache_dir(shorten_p, reruns_pay_for="retention adjudications missing from the memo") + add_common_args(shorten_p, positive_int) + add_cache_dir_arg(shorten_p, reruns_pay_for="retention adjudications missing from the memo") shorten_p.add_argument("--atoms", required=True, help="atoms.json from `skill novelty atoms`") # Same model as the retention oracle inside `analyze` (its extractor, i.e. the judge): # adjudications are cached per model, and a different one would score other verdicts. @@ -235,7 +239,7 @@ def register_skill(skill_sub, positive_int) -> None: help="Retention adjudicator model " f"(default: {DEFAULT_JUDGE_MODEL}, the default judge)", ) - _add_extractor_arg(shorten_p, "Retention adjudicator override (a bare model uses the --model provider)") + add_extractor_arg(shorten_p, "Retention adjudicator override (a bare model uses the --model provider)") cli_flags.add(shorten_p, "tokens", "--max-output-tokens", metavar="N", type=positive_int, default=None, dest="max_tokens", help="Output-token ceiling per shortening adjudication; raise it for reasoning models") shorten_p.add_argument("--lexical-only", action="store_true", dest="lexical_only", diff --git a/dokimi/dokimi/commands/skill_sensitivity.py b/dokimi/dokimi/commands/skill_sensitivity.py index 561338bac1..fd0d18189b 100644 --- a/dokimi/dokimi/commands/skill_sensitivity.py +++ b/dokimi/dokimi/commands/skill_sensitivity.py @@ -9,7 +9,7 @@ import json import sys -from dokimi.commands.novelty import _default_dir +from dokimi.commands.novelty import default_dir from dokimi.commands.novelty_routing_inputs import checked_out_path, load_routing_field from dokimi.commands.novelty_routing_report import ( field_record, @@ -43,7 +43,7 @@ def cmd_skill_sensitivity(args: argparse.Namespace) -> None: if args.estimate_only: _print_estimate(args, plan, queries) return - out = checked_out_path(args.out, "skill sensitivity", default=str(_default_dir(args.artifact) / "sensitivity.json")) + out = checked_out_path(args.out, "skill sensitivity", default=str(default_dir(args.artifact) / "sensitivity.json")) out.parent.mkdir(parents=True, exist_ok=True) selector = cost.client(args.model, args.provider, "selector", args) result = run_sensitivity(gold, competitors, queries, client=selector, seed=args.seed, diff --git a/dokimi/dokimi/commands/subjects.py b/dokimi/dokimi/commands/subjects.py index e7583eab9e..68cafe432a 100644 --- a/dokimi/dokimi/commands/subjects.py +++ b/dokimi/dokimi/commands/subjects.py @@ -170,8 +170,8 @@ def _run_subject(run, descriptor, args: argparse.Namespace, *, baseline_arm: str work_tasks: list, novelty: tuple[list[dict], list[str]]) -> dict: """The cells of a `subjects run` in its run directory: the plan, the awareness matrix per product, the work, then the scorecard, saved there and returned (docs/run-directories.md).""" - from dokimi.artifacts import load_artifact - from dokimi.commands.arms import _safe_name, run_config_from_args, run_matrix + from dokimi.artifacts import load_artifact, safe_file_name + from dokimi.commands.arms import run_config_from_args, run_matrix from dokimi.eval.cells import load_matrix_cells from dokimi.subjects import build_subject_scorecard from dokimi.subjects.loader import awareness_arm_specs @@ -194,7 +194,7 @@ def _run_subject(run, descriptor, args: argparse.Namespace, *, baseline_arm: str awareness_runs: list[dict] = [] for product, questions_path in zip(descriptor.suite.products, questions, strict=True): - run_dir = out_dir / _safe_name(product) + run_dir = out_dir / safe_file_name(product) rollup_json = run_dir / "matrix-rollup.json" rollup_md = run_dir / "matrix-rollup.md" try: @@ -241,10 +241,10 @@ def on_row(row: dict) -> None: # each work cell once it ends, so a stop keeps t def _record_product(run, product: str, cells: list, arms: list[str], product_dir: Path) -> None: """Give one product's awareness cells the status of the `arms.v1` files its matrix saved, and list those, a stopped cell's partial file, the rollup and the plugin deltas in run.json.""" - from dokimi.commands.arms import _safe_name + from dokimi.artifacts import safe_file_name from dokimi.subjects.run_plan import record_awareness - saved = {cell.name: product_dir / "cells" / f"{_safe_name(cell.name)}.json" for cell in cells} + saved = {cell.name: product_dir / "cells" / f"{safe_file_name(cell.name)}.json" for cell in cells} record_awareness(run, product, cells, arms, {name: path for name, path in saved.items() if path.is_file()}) run.add_artifact("matrix_rollup", product_dir / "matrix-rollup.json") for path in sorted((product_dir / "cells").glob("*.json")): # finished cells and a stopped one's partial file @@ -560,9 +560,9 @@ def _run_own_names() -> set[str]: def _validate_unique_product_output_dirs(products: tuple[str, ...]) -> None: - from dokimi.commands.arms import _safe_name + from dokimi.artifacts import safe_file_name - safe_names = [_safe_name(product) for product in products] + safe_names = [safe_file_name(product) for product in products] dot_names = [product for product, safe in zip(products, safe_names, strict=True) if safe in {".", ".."}] if dot_names: raise ValueError( @@ -578,7 +578,7 @@ def _validate_unique_product_output_dirs(products: tuple[str, ...]) -> None: collisions = sorted({name for name in safe_names if safe_names.count(name) > 1}) if collisions: details = ", ".join( - f"{name}: {', '.join(product for product in products if _safe_name(product) == name)}" + f"{name}: {', '.join(product for product in products if safe_file_name(product) == name)}" for name in collisions ) raise ValueError(f"suite.products collide after output directory sanitization: {details}") diff --git a/dokimi/dokimi/commands/tasks_generate.py b/dokimi/dokimi/commands/tasks_generate.py index cf91a39531..afc4f88ccf 100644 --- a/dokimi/dokimi/commands/tasks_generate.py +++ b/dokimi/dokimi/commands/tasks_generate.py @@ -95,14 +95,15 @@ def _generate_graph(args: argparse.Namespace) -> None: from dokimi.repos.graph_tasks import Options, plan, write from dokimi.repos.source import GitTree - from .repo import _code_index, _normalize_whitespace, _source_tree + from ._shared import code_index_for, normalize_whitespace + from .repo import source_tree if not args.index: raise InputError("--from graph needs --index FILE, a SCIP index of the source") if not args.references and not args.derives: raise InputError("--references 0 --derives 0 asks for no task") - index = _code_index(args.index) # before the source: a bad index must not cost a clone first - _, tree = _source_tree(args) + index = code_index_for(args.index) # before the source: a bad index must not cost a clone first + _, tree = source_tree(args) if not isinstance(tree, GitTree): raise InputError(f"pin the revision the index was built from: {args.source}@; a task's base is a commit") opts = Options(out=Path(args.out), base=tree.sha, references=args.references, derives=args.derives, seed=args.seed, @@ -123,7 +124,7 @@ def _generate_graph(args: argparse.Namespace) -> None: print(f"kept {o.task}") continue print(f"{'would write' if args.dry_run else 'written'} {o.task}: {len(c.gold)} gold, " - f"`{_normalize_whitespace(c.qualified, max_len=None)}`" + f"`{normalize_whitespace(c.qualified, max_len=None)}`" + (f" ({c.same_name} symbols of this name)" if c.ambiguous else "")) n = {k: sum(o.status == k for o in p.outcomes) for k in ("written", "kept")} verb = "to write" if args.dry_run else "written" @@ -145,8 +146,10 @@ def _generate_history(args: argparse.Namespace) -> None: from dokimi.repos.source import GitTree, is_shallow from dokimi.repos.workspace import source_git_dir - from .repo import _cache_dir, _load_manifest, _parse_source - from .repo_run import _errors, _refuse_typed + from ._shared import cache_dir_from_args, parse_source + from .repo import manifest_for_tree + from ._shared import run_errors + from .repo_run import refuse_typed try: if args.subject == "": @@ -154,26 +157,26 @@ def _generate_history(args: argparse.Namespace) -> None: subject = re.compile(DEFAULT_SUBJECT if args.subject is None else args.subject, re.I) except (re.error, OverflowError, RecursionError) as exc: raise InputError(f"--subject {args.subject!r} is not a regular expression: {exc}") from None - source = _parse_source(args) + source = parse_source(args) if not source.rev: raise InputError(f"pin the revision whose history to read: {args.source}@ (a branch, tag or SHA)") - _refuse_typed(source, args) # before the prompt file: a source refusal is not masked by an unreadable one + refuse_typed(source, args) # before the prompt file: a source refusal is not masked by an unreadable one try: text = Path(args.prompt_file).read_text(encoding="utf-8").strip() if args.prompt_file else DEFAULT_INSTRUCTION if not text: raise ValueError(f"the prompt file {args.prompt_file} is empty") - tree = open_source(source, _cache_dir(args)) + tree = open_source(source, cache_dir_from_args(args)) if not isinstance(tree, GitTree): # a pinned source always opens as a git tree; kept for the type raise ValueError(f"{tree.label} is not a git revision") - manifest = _load_manifest(tree, args) + manifest = manifest_for_tree(tree, args) opts = Options(out=Path(args.out), max_lines=args.max_lines, instruction=text, force=args.force) - git_dir = source_git_dir(source, tree, _cache_dir(args)) + git_dir = source_git_dir(source, tree, cache_dir_from_args(args)) if is_shallow(git_dir): raise InputError("history generation needs a full clone; run git fetch --unshallow") h = History(git_dir) commits, n_read, n_merges = first_parent(h, tree.sha, args.commits, subject) outcomes = build_all(h, manifest, commits, opts, dry_run=args.dry_run) - except _errors() as exc: + except run_errors() as exc: print(f"āœ— {exc}", file=sys.stderr) sys.exit(1) print(f"{len(commits)} of {n_read} first-parent commit(s) of {tree.label} have a subject --subject matches" diff --git a/dokimi/dokimi/eval/matrix_rollup.py b/dokimi/dokimi/eval/matrix_rollup.py index c90cd3d296..579307340b 100644 --- a/dokimi/dokimi/eval/matrix_rollup.py +++ b/dokimi/dokimi/eval/matrix_rollup.py @@ -11,6 +11,7 @@ from typing import Any from dokimi.eval.plugin_delta import PluginDeltaError, compare_plugin_runs +from dokimi.artifacts import safe_file_name def build_matrix_rollup( @@ -100,8 +101,8 @@ def _paired_plugin_deltas( ) pair_suffix = sha256(f"{baseline_name}\0{plugin_name}".encode("utf-8", "surrogatepass")).hexdigest()[:8] delta_path = out_dir / ( - f"plugin-delta-{_safe_name(baseline_name)}-to-" - f"{_safe_name(plugin_name)}-{pair_suffix}.json" + f"plugin-delta-{safe_file_name(baseline_name)}-to-" + f"{safe_file_name(plugin_name)}-{pair_suffix}.json" ) deltas.append({ "baseline_cell": baseline_name, @@ -139,8 +140,3 @@ def _pair_key(data: dict[str, Any]) -> tuple[Any, ...]: (data.get("run_config") or {}).get("session_turns"), (data.get("run_config") or {}).get("turn_reminder"), ) - - -def _safe_name(name: str) -> str: - safe = "".join(c if c.isalnum() or c in ("-", "_", ".") else "-" for c in name) - return safe.strip("-") or "cell" diff --git a/dokimi/tests/test_answers_command.py b/dokimi/tests/test_answers_command.py index c9a6c71122..20ed2a831e 100644 --- a/dokimi/tests/test_answers_command.py +++ b/dokimi/tests/test_answers_command.py @@ -38,21 +38,21 @@ def _point_config(monkeypatch, path: Path) -> None: def test_missing_config_is_empty(tmp_path, monkeypatch): _point_config(monkeypatch, tmp_path / "absent.yaml") - assert answers._load_runtime_config() == {} + assert answers.load_runtime_config() == {} def test_empty_config_file_is_empty(tmp_path, monkeypatch): path = tmp_path / "products.yaml" path.write_text("", encoding="utf-8") _point_config(monkeypatch, path) - assert answers._load_runtime_config() == {} + assert answers.load_runtime_config() == {} def test_config_file_is_read(tmp_path, monkeypatch): path = tmp_path / "products.yaml" path.write_text("retrieval:\n top_k: 7\n", encoding="utf-8") _point_config(monkeypatch, path) - assert answers._load_runtime_config() == {"retrieval": {"top_k": 7}} + assert answers.load_runtime_config() == {"retrieval": {"top_k": 7}} def test_invalid_yaml_config_exits(tmp_path, monkeypatch, capsys): @@ -60,7 +60,7 @@ def test_invalid_yaml_config_exits(tmp_path, monkeypatch, capsys): path.write_text("products: [unclosed\n", encoding="utf-8") _point_config(monkeypatch, path) with refusal() as exc: - answers._load_runtime_config() + answers.load_runtime_config() assert exc.code == 2 assert "invalid YAML" in exc.err @@ -81,7 +81,7 @@ def test_non_utf8_config_exits_with_message(tmp_path, monkeypatch, capsys): path.write_bytes(b"retrieval:\n top_k: \xff\xfe\n") _point_config(monkeypatch, path) with refusal() as exc: - answers._load_runtime_config() + answers.load_runtime_config() assert exc.code == 2 assert f"cannot read {path}" in exc.err @@ -91,7 +91,7 @@ def test_unreadable_config_exits_with_message(tmp_path, monkeypatch, capsys): path.mkdir() # a directory where the file should be: read_text raises OSError _point_config(monkeypatch, path) with refusal() as exc: - answers._load_runtime_config() + answers.load_runtime_config() assert exc.code == 2 assert f"cannot read {path}" in exc.err @@ -101,7 +101,7 @@ def test_non_mapping_config_exits(tmp_path, monkeypatch, capsys): path.write_text("- a\n- b\n", encoding="utf-8") _point_config(monkeypatch, path) with refusal() as exc: - answers._load_runtime_config() + answers.load_runtime_config() assert exc.code == 2 assert "expected a mapping" in exc.err @@ -111,7 +111,7 @@ def test_non_utf8_config_exits(tmp_path, monkeypatch, capsys): path.write_bytes(b"\xff\xfe\x00bad: [") _point_config(monkeypatch, path) with refusal() as exc: - answers._load_runtime_config() + answers.load_runtime_config() assert exc.code == 2 assert f"cannot read {path}" in exc.err @@ -119,7 +119,7 @@ def test_non_utf8_config_exits(tmp_path, monkeypatch, capsys): def test_unreadable_config_path_exits(tmp_path, monkeypatch, capsys): _point_config(monkeypatch, tmp_path) with refusal() as exc: - answers._load_runtime_config() + answers.load_runtime_config() assert exc.code == 2 assert f"cannot read {tmp_path}" in exc.err @@ -133,7 +133,7 @@ def test_config_section_of_the_wrong_shape_exits(tmp_path, monkeypatch, capsys, path.write_text(text, encoding="utf-8") _point_config(monkeypatch, path) with refusal() as exc: - answers._load_runtime_config() + answers.load_runtime_config() assert exc.code == 2 assert f"'{key}' in {path} must be a mapping" in exc.err diff --git a/dokimi/tests/test_benchmark_command_question_set.py b/dokimi/tests/test_benchmark_command_question_set.py index 5033d2486b..d96892ecdb 100644 --- a/dokimi/tests/test_benchmark_command_question_set.py +++ b/dokimi/tests/test_benchmark_command_question_set.py @@ -58,7 +58,7 @@ def fake_run_single_library(entry, **kwargs): }, } - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) monkeypatch.setattr(benchmark, "_run_single_library", fake_run_single_library) output_dir = tmp_path / "onetbb_eval" @@ -106,7 +106,7 @@ class Registry: def get(self, key: str) -> ProductEntry: return ProductEntry(key=key, name=key, description=key, doc_sources=[]) - monkeypatch.setattr(benchmark, "_load_registry", lambda args: Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: Registry()) monkeypatch.setattr(benchmark, "_run_single_library", fake_run_single_library) output_dir = tmp_path / "benchmarks" @@ -140,7 +140,7 @@ def fake_run_single_library(entry, **kwargs): calls.append(kwargs) return {"library": entry.key, "name": entry.name, "status": "ok", "result": {}} - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) monkeypatch.setattr(benchmark, "_run_single_library", fake_run_single_library) questions_root = tmp_path / "content-repo" / "questions" @@ -187,7 +187,7 @@ def run(self, concurrency=5): def test_preflight_reports_the_questions_root(monkeypatch, tmp_path, capsys): monkeypatch.setenv("OPENAI_API_KEY", "test") - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) monkeypatch.setattr( "dokimi.mcp.factory.create_doc_source_client", lambda doc_source: object(), @@ -221,7 +221,7 @@ def test_preflight_validates_questions_from(monkeypatch, tmp_path, capsys): ) monkeypatch.setenv("OPENAI_API_KEY", "test") - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) monkeypatch.setattr( "dokimi.mcp.factory.create_doc_source_client", lambda doc_source: object(), @@ -251,7 +251,7 @@ def _preflight(monkeypatch, tmp_path, *extra, env=("OPENAI_API_KEY",)): monkeypatch.delenv(key, raising=False) for key in env: monkeypatch.setenv(key, "test") - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) monkeypatch.setattr( "dokimi.mcp.factory.create_doc_source_client", lambda doc_source: object(), @@ -346,7 +346,7 @@ def _preflight_with_doc_source(monkeypatch, tmp_path, *extra, error=None, creden monkeypatch.delenv(key, raising=False) if credential: monkeypatch.setenv("OPENAI_API_KEY", "test") - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) # By default a failure of the check itself (the source cannot be reached), not a bad --doc-source value. failure = error or RuntimeError("doc source unreachable") @@ -418,7 +418,7 @@ def test_preflight_questions_from_skips_root_check(monkeypatch, tmp_path, capsys empty_root.mkdir() monkeypatch.setenv("OPENAI_API_KEY", "test") - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) monkeypatch.setattr( "dokimi.mcp.factory.create_doc_source_client", lambda doc_source: object(), @@ -465,7 +465,7 @@ def test_run_rejects_an_unusable_questions_from_before_any_call( calls: list[object] = [] (tmp_path / "bad.json").write_text(json.dumps({"a": 1}), encoding="utf-8") (tmp_path / "adir" / "questions" / "onetbb.json").mkdir(parents=True) - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) monkeypatch.setattr(benchmark, "_run_single_library", lambda *a, **k: calls.append(k)) args = build_parser().parse_args([ @@ -507,7 +507,7 @@ def fake_run_single_library(entry, **kwargs): json.dumps({"questions": [{"id": "g1", "question": "How?"}]}), encoding="utf-8" ) - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) monkeypatch.setattr(benchmark, "_run_single_library", fake_run_single_library) output_dir = tmp_path / "onetbb_eval" diff --git a/dokimi/tests/test_cli_output.py b/dokimi/tests/test_cli_output.py index ae3c7e58df..f9d14159ba 100644 --- a/dokimi/tests/test_cli_output.py +++ b/dokimi/tests/test_cli_output.py @@ -576,17 +576,17 @@ def test_a_payload_that_will_not_serialize_leaves_the_fallback_document_to_print def test_a_failed_scan_with_no_incomplete_reason_still_says_what_failed(): - from dokimi.commands.repo import _scan_reason + from dokimi.commands._shared import scan_reason - assert _scan_reason({"incomplete": True, "incomplete_reasons": [], "counts": {"fail": 0}}, [], True) == "scan incomplete" - assert _scan_reason({"incomplete": False, "incomplete_reasons": [], "counts": {"fail": 2}}, [], True) == "2 claim(s) failed" + assert scan_reason({"incomplete": True, "incomplete_reasons": [], "counts": {"fail": 0}}, [], True) == "scan incomplete" + assert scan_reason({"incomplete": False, "incomplete_reasons": [], "counts": {"fail": 2}}, [], True) == "2 claim(s) failed" # every cause the gate tripped on is in the reason, not only the first - assert _scan_reason({"incomplete": True, "incomplete_reasons": ["x"], "counts": {"fail": 2}}, [], True) == \ + assert scan_reason({"incomplete": True, "incomplete_reasons": ["x"], "counts": {"fail": 2}}, [], True) == \ "2 claim(s) failed; scan incomplete: x" - assert _scan_reason({"incomplete": False, "incomplete_reasons": [], "counts": {"fail": 0}}, ["bad"], True) == \ + assert scan_reason({"incomplete": False, "incomplete_reasons": [], "counts": {"fail": 0}}, ["bad"], True) == \ "1 --static problem(s) not merged" # without --fail-on fail, failed claims and an incomplete scan are not what failed the run - assert _scan_reason({"incomplete": True, "incomplete_reasons": ["x"], "counts": {"fail": 2}}, ["bad"], False) == \ + assert scan_reason({"incomplete": True, "incomplete_reasons": ["x"], "counts": {"fail": 2}}, ["bad"], False) == \ "1 --static problem(s) not merged" diff --git a/dokimi/tests/test_empty_question_rule.py b/dokimi/tests/test_empty_question_rule.py index 0c090ded1e..84a1376624 100644 --- a/dokimi/tests/test_empty_question_rule.py +++ b/dokimi/tests/test_empty_question_rule.py @@ -317,7 +317,7 @@ def test_ragas_refuses_before_any_call(monkeypatch): def test_ragas_refusal_propagates_through_the_command_wrapper(monkeypatch, capsys, tmp_path): import dokimi.eval.ragas_eval as ragas_mod - from dokimi.commands.evaluate import _run_ragas_eval + from dokimi.commands._shared import run_ragas_eval class Refusing: def __init__(self, **kw): @@ -328,7 +328,7 @@ def evaluate(self, answers, include_without_docs=True): monkeypatch.setattr(ragas_mod, "RagasEvaluator", Refusing) with pytest.raises(EmptyQuestionError): - _run_ragas_eval([], tmp_path / "x.json", object()) + run_ragas_eval([], tmp_path / "x.json", object()) assert "RAGAS evaluation failed" not in capsys.readouterr().out diff --git a/dokimi/tests/test_eval_output_write_errors.py b/dokimi/tests/test_eval_output_write_errors.py index 426db4638d..a77b018719 100644 --- a/dokimi/tests/test_eval_output_write_errors.py +++ b/dokimi/tests/test_eval_output_write_errors.py @@ -128,7 +128,7 @@ def test_ragas_results_that_cannot_be_written_exit_2_naming_the_path(tmp_path, m import types import dokimi.eval.ragas_eval as ragas_eval - from dokimi.commands.evaluate import _run_ragas_eval + from dokimi.commands._shared import run_ragas_eval class Evaluator: def __init__(self, **kw): @@ -140,7 +140,7 @@ def evaluate(self, answers, include_without_docs=True): monkeypatch.setattr(ragas_eval, "RagasEvaluator", Evaluator) blocked = _blocked(tmp_path) with refusal() as exc: - _run_ragas_eval([], blocked, types.SimpleNamespace()) + run_ragas_eval([], blocked, types.SimpleNamespace()) assert exc.code == 2 assert f"Error: cannot write {blocked.with_name('out_ragas.json')}" in exc.err diff --git a/dokimi/tests/test_eval_writers_save_artifact.py b/dokimi/tests/test_eval_writers_save_artifact.py index e27db25f12..98f7a33a3c 100644 --- a/dokimi/tests/test_eval_writers_save_artifact.py +++ b/dokimi/tests/test_eval_writers_save_artifact.py @@ -13,7 +13,7 @@ from dokimi import artifacts, __version__ from dokimi.cli import build_parser -from dokimi.commands.evaluate import _run_ragas_eval +from dokimi.commands._shared import run_ragas_eval from dokimi.exit_codes import EXIT_INCONCLUSIVE from dokimi.eval import ragas_eval from tests.test_eval_output_write_errors import _JUDGE_COMMANDS, _Report, _stub_judge_commands @@ -105,7 +105,7 @@ def evaluate(self, answers, include_without_docs=True): monkeypatch.setattr(ragas_eval, "RagasEvaluator", Evaluator) args = types.SimpleNamespace(ragas_model="m", ragas_provider="anthropic") - _run_ragas_eval([], tmp_path / "answers.json", args) + run_ragas_eval([], tmp_path / "answers.json", args) _assert_saved_with_envelope(tmp_path / "answers_ragas.json", "ragas.v1", "ragas_summary") # The judge that scored the answers is recorded, so runs list and show can name it. saved = json.loads((tmp_path / "answers_ragas.json").read_text(encoding="utf-8")) diff --git a/dokimi/tests/test_exit_codes_boundaries.py b/dokimi/tests/test_exit_codes_boundaries.py index 626ae92805..2deb9cb532 100644 --- a/dokimi/tests/test_exit_codes_boundaries.py +++ b/dokimi/tests/test_exit_codes_boundaries.py @@ -20,7 +20,7 @@ import pytest from dokimi import cli -from dokimi.commands import benchmark, evaluate +from dokimi.commands import _shared, benchmark from dokimi.eval import arms_run from dokimi.records import RecordError from dokimi.repos import SourceError @@ -365,7 +365,7 @@ def failing_load(tree, args, **kwargs): repo = tmp_path / "repo" repo.mkdir() - monkeypatch.setattr("dokimi.commands.repo._load_manifest", failing_load) + monkeypatch.setattr("dokimi.commands.repo.manifest_for_tree", failing_load) extra = [*REACH_ARGS[:-1], str(tmp_path / "reach-out")] if command == "reach" else [] err = _expect_exit(monkeypatch, capsys, 1, *_leaf(command), str(repo), *extra) assert "git show failed" in err @@ -381,7 +381,7 @@ def failing_shadow(profile, tree, kinds): repo = tmp_path / "repo" repo.mkdir() - monkeypatch.setattr("dokimi.commands.repo._load_manifest", lambda tree, args, **kwargs: SimpleNamespace()) + monkeypatch.setattr("dokimi.commands.repo.manifest_for_tree", lambda tree, args, **kwargs: SimpleNamespace()) monkeypatch.setattr("dokimi.repos.reach.probe_files", lambda tree, manifest, profile: ["AGENTS.md"]) monkeypatch.setattr("dokimi.repos.reach.followable", lambda tree, files: (files, {}, [])) monkeypatch.setattr("dokimi.repos.reach.shadow_for", failing_shadow) @@ -405,7 +405,7 @@ def failing_check(reach, manifest_id, profile_name, sha): monkeypatch.setattr("dokimi.commands.repo_reach._saved_reach_inputs", lambda args: (SimpleNamespace(name="claude-code"), SimpleNamespace(), {"scenarios": []})) monkeypatch.setattr("dokimi.repos.open_source", lambda source, cache: SimpleNamespace(sha="a" * 40)) - monkeypatch.setattr("dokimi.commands.repo._load_manifest", lambda tree, args, **kwargs: SimpleNamespace(id="m")) + monkeypatch.setattr("dokimi.commands.repo.manifest_for_tree", lambda tree, args, **kwargs: SimpleNamespace(id="m")) monkeypatch.setattr("dokimi.repos.receipt.check_saved_reach", failing_check) err = _expect_exit(monkeypatch, capsys, 1, "repo", "reach", str(repo), "--from", str(saved)) assert "git show failed" in err @@ -534,7 +534,7 @@ def list(self): def test_batch_with_no_known_library_exits_2(monkeypatch, capsys): - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _NoLibraries()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _NoLibraries()) _argv(monkeypatch, "benchmark", "batch", "--libraries", "no-such-library") with refusal() as exc: cli.main() @@ -553,7 +553,7 @@ def get(self, key): def test_preflight_unknown_doc_source_format_exits_2(tmp_path, monkeypatch, capsys): monkeypatch.setenv("OPENAI_API_KEY", "test") - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _OneLibrary()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _OneLibrary()) _argv(monkeypatch, "benchmark", "preflight", "--library", "onetbb", "--doc-source", "bogus:docs", "--out-dir", str(tmp_path / "out"), "--model", "openai/gpt-6.1-sol", "--judge", "openai/judge-x") @@ -572,7 +572,7 @@ def test_preflight_refuses_a_local_doc_source_path_that_does_not_exist(tmp_path, if exists: docs.mkdir() monkeypatch.setenv("OPENAI_API_KEY", "test") - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _OneLibrary()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _OneLibrary()) _argv(monkeypatch, "benchmark", "preflight", "--library", "onetbb", "--doc-source", f"{prefix}{docs}", "--out-dir", str(tmp_path / "out"), "--model", "openai/gpt-6.1-sol", "--judge", "openai/judge-x") if exists: @@ -591,7 +591,7 @@ def test_external_content_walkthrough_states_the_exit_of_a_preflight_without_key doc = Path(__file__).resolve().parents[1] / "docs" / "external-content.md" stated = int(re.search(r"It exited (\d+) here because no API keys were set", doc.read_text(encoding="utf-8")).group(1)) monkeypatch.delenv("OPENAI_API_KEY", raising=False) - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _OneLibrary()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _OneLibrary()) _argv(monkeypatch, "benchmark", "preflight", "--library", "onetbb", "--out-dir", str(tmp_path / "out"), "--model", "openai/gpt-6.1-sol", "--judge", "openai/judge-x") with refusal() as exc: @@ -798,7 +798,7 @@ def without_ragas(name, *args, **kwargs): monkeypatch.setattr(importlib.util, "find_spec", without_ragas) message = "RAGAS meta-evaluation needs the ragas extra: pip install 'dokimi[ragas]'" with refusal() as exc: - evaluate._require_ragas() + _shared.require_ragas() assert exc.code == 1 assert message in exc.err diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 5615688c67..e44fd18bfc 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -545,7 +545,7 @@ def test_ragas_cli_refuses_ask_answers_before_grading(monkeypatch, capsys, tmp_p from dokimi.commands import evaluate from dokimi.eval import ragas_eval - monkeypatch.setattr(evaluate, "_require_ragas", lambda: None) + monkeypatch.setattr(evaluate, "require_ragas", lambda: None) evaluate_ragas = MagicMock() monkeypatch.setattr(ragas_eval, "_import_ragas_runtime", lambda: (MagicMock(), evaluate_ragas)) diff --git a/dokimi/tests/test_input_devices.py b/dokimi/tests/test_input_devices.py index 8591e017c9..35c9436592 100644 --- a/dokimi/tests/test_input_devices.py +++ b/dokimi/tests/test_input_devices.py @@ -137,7 +137,7 @@ def test_the_custom_set_loader_refuses_a_device_set_after_construction(tmp_path) def test_benchmark_refuses_a_device_as_questions_from_with_its_own_message(monkeypatch, tmp_path, capsys, command): """Refused before the read, so the message is not a read error's (an empty one, for a MemoryError).""" monkeypatch.setenv("OPENAI_API_KEY", "test") - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) monkeypatch.setattr("dokimi.mcp.factory.create_doc_source_client", lambda doc_source: object()) monkeypatch.setattr(benchmark, "_run_single_library", lambda *a, **k: pytest.fail("the run started")) assert _main(monkeypatch, "benchmark", command, "--library", "onetbb", "--doc-source", "local:docs", diff --git a/dokimi/tests/test_llm_cli.py b/dokimi/tests/test_llm_cli.py index f32a85274d..211d80b069 100644 --- a/dokimi/tests/test_llm_cli.py +++ b/dokimi/tests/test_llm_cli.py @@ -979,7 +979,7 @@ def get(self, key): return ProductEntry(key="onetbb", name="oneTBB", description="TBB", doc_sources=["local:docs"]) monkeypatch.setenv("OPENAI_API_KEY", "test") - monkeypatch.setattr(benchmark, "_load_registry", lambda args: Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: Registry()) monkeypatch.setattr("dokimi.mcp.factory.create_doc_source_client", lambda doc_source: object()) monkeypatch.setattr(process, "run", _auth_runner(status)) args = build_parser().parse_args([ diff --git a/dokimi/tests/test_novelty_routing_spend_cap_partial.py b/dokimi/tests/test_novelty_routing_spend_cap_partial.py index c5c98e19b4..ac74406788 100644 --- a/dokimi/tests/test_novelty_routing_spend_cap_partial.py +++ b/dokimi/tests/test_novelty_routing_spend_cap_partial.py @@ -511,12 +511,12 @@ def test_a_partial_run_whose_out_name_holds_an_undecodable_byte_is_saved(tmp_pat @pytest.mark.skipif(os.name != "posix", reason="a non-UTF-8 file name is POSIX") def test_a_long_out_name_with_undecodable_bytes_is_shortened_within_name_max(tmp_path): - from dokimi.commands.novelty_routing_report import _partial_destinations + from dokimi.commands.novelty_routing_report import partial_destinations name_max = os.pathconf(tmp_path, "PC_NAME_MAX") out = tmp_path / (os.fsdecode(b"\xff" * (name_max - len(".json"))) + ".json") out.write_text('{"status": "ok"}', encoding="utf-8") - name = next(_partial_destinations(out)).name + name = next(partial_destinations(out)).name assert len(os.fsencode(name)) <= name_max assert os.fsencode(name).startswith(b"\xff\xff") and name.endswith(".partial.json") @@ -620,11 +620,11 @@ def test_a_name_limit_too_small_for_a_sidecar_name_is_an_error_not_a_hang(tmp_pa @pytest.mark.skipif(not hasattr(os, "pathconf"), reason="NAME_MAX is POSIX") def test_a_second_long_name_partial_save_goes_to_the_next_numbered_shortened_name(tmp_path): - from dokimi.commands.novelty_routing_report import _partial_destinations + from dokimi.commands.novelty_routing_report import partial_destinations out = tmp_path / ("x" * (os.pathconf(tmp_path, "PC_NAME_MAX") - len(".json")) + ".json") out.write_text('{"status": "ok"}', encoding="utf-8") - names = _partial_destinations(out) + names = partial_destinations(out) first = next(names) first.write_text('{"status": "ok"}', encoding="utf-8") # a finished result there: taken second = next(names) @@ -646,13 +646,13 @@ def test_a_short_out_at_a_small_name_limit_still_saves_its_partial_result(tmp_pa def test_a_stem_that_fits_its_unnumbered_sidecar_keeps_it_and_its_numbered_ones_fit(tmp_path, monkeypatch): - from dokimi.commands.novelty_routing_report import _partial_destinations + from dokimi.commands.novelty_routing_report import partial_destinations monkeypatch.setattr(os, "pathconf", lambda *args: 255, raising=False) stem = "x" * 240 out = tmp_path / f"{stem}.json" out.write_text('{"status": "ok"}', encoding="utf-8") - names = _partial_destinations(out) + names = partial_destinations(out) first = next(names) first.write_text('{"status": "ok"}', encoding="utf-8") # a finished result there: taken second = next(names) diff --git a/dokimi/tests/test_pipeline_empty_question_set.py b/dokimi/tests/test_pipeline_empty_question_set.py index 62c435d532..f420cd1cd8 100644 --- a/dokimi/tests/test_pipeline_empty_question_set.py +++ b/dokimi/tests/test_pipeline_empty_question_set.py @@ -72,7 +72,7 @@ def no_personas(self): raise AssertionError("no personas should be discovered for an empty cached question set") monkeypatch.setattr(EvaluationPipeline, "_discover_personas", no_personas) - monkeypatch.setattr(benchmark, "_load_registry", lambda args: _Registry()) + monkeypatch.setattr(benchmark, "load_registry", lambda args: _Registry()) args = build_parser().parse_args([ "benchmark", "run", "--library", "onetbb", "--out-dir", str(out), "--model", "openai/gpt-6.1-sol", "--judge", "openai/judge-x", diff --git a/dokimi/tests/test_questions_generate_inputs.py b/dokimi/tests/test_questions_generate_inputs.py index 88f08236bc..fdd4358ae2 100644 --- a/dokimi/tests/test_questions_generate_inputs.py +++ b/dokimi/tests/test_questions_generate_inputs.py @@ -95,7 +95,7 @@ def test_generate_exits_2_when_the_output_cannot_be_written(tmp_path, monkeypatc topics = tmp_path / "topics.json" topics.write_text("[]", encoding="utf-8") out = _unwritable_outputs(tmp_path)[which] - monkeypatch.setattr("dokimi.commands.answers._load_runtime_config", dict) + monkeypatch.setattr("dokimi.commands._shared.load_runtime_config", dict) monkeypatch.setattr("dokimi.questions.QuestionGenerator", _FakeGenerator) assert _generate(monkeypatch, "--personas", str(personas), "--topics", str(topics), "--out", str(out)) == 2 @@ -141,7 +141,7 @@ def test_generate_exits_1_when_the_generated_set_fails_validation(tmp_path, monk topics = tmp_path / "topics.json" topics.write_text("[]", encoding="utf-8") out = tmp_path / "o.json" - monkeypatch.setattr("dokimi.commands.answers._load_runtime_config", dict) + monkeypatch.setattr("dokimi.commands._shared.load_runtime_config", dict) monkeypatch.setattr("dokimi.questions.QuestionGenerator", _BogusGenerator) assert _generate(monkeypatch, "--personas", str(personas), "--topics", str(topics), "--out", str(out)) == 1 @@ -158,7 +158,7 @@ def runs_list(subject): monkeypatch.chdir(tmp_path) monkeypatch.delenv("DOKIMI_RUNS_DIR", raising=False) - monkeypatch.setattr("dokimi.commands.answers._load_runtime_config", dict) + monkeypatch.setattr("dokimi.commands._shared.load_runtime_config", dict) (tmp_path / "personas.json").write_text(json.dumps(GOOD_PERSONAS), encoding="utf-8") (tmp_path / "topics.json").write_text('["parallel_for"]', encoding="utf-8") llm = Mock(invoke=Mock(return_value=Mock(content='["How does parallel_for split a range?"]'))) @@ -180,7 +180,7 @@ def runs_list(subject): def test_generate_exits_2_when_a_local_doc_source_path_is_missing(tmp_path, monkeypatch, capsys, scheme): """#1086: `--doc-source local:` and `okf:` are input errors naming the path, before any generation.""" monkeypatch.chdir(tmp_path) - monkeypatch.setattr("dokimi.commands.answers._load_runtime_config", dict) + monkeypatch.setattr("dokimi.commands._shared.load_runtime_config", dict) (tmp_path / "personas.json").write_text('{"personas": []}', encoding="utf-8") missing = tmp_path / "missing" assert _generate(monkeypatch, "--personas", "personas.json", "--doc-source", f"{scheme}:{missing}", @@ -196,7 +196,7 @@ def test_generate_accepts_an_existing_local_doc_source(tmp_path, monkeypatch, ca docs.mkdir() (docs / "index.md").write_text("# parallel_for\nUse tbb::parallel_for.", encoding="utf-8") monkeypatch.chdir(tmp_path) - monkeypatch.setattr("dokimi.commands.answers._load_runtime_config", dict) + monkeypatch.setattr("dokimi.commands._shared.load_runtime_config", dict) (tmp_path / "personas.json").write_text('{"personas": []}', encoding="utf-8") monkeypatch.setattr("sys.argv", ["dokimi", "eval", "questions", "generate", "--product", "oneTBB", "--personas", "personas.json", "--doc-source", f"local:{docs}", @@ -208,7 +208,7 @@ def test_generate_accepts_an_existing_local_doc_source(tmp_path, monkeypatch, ca def test_generate_exits_2_when_a_local_doc_source_name_is_too_long(tmp_path, monkeypatch, capsys): """#1086: a filename past NAME_MAX is a missing path, an input error and not a traceback.""" monkeypatch.chdir(tmp_path) - monkeypatch.setattr("dokimi.commands.answers._load_runtime_config", dict) + monkeypatch.setattr("dokimi.commands._shared.load_runtime_config", dict) (tmp_path / "personas.json").write_text('{"personas": []}', encoding="utf-8") assert _generate(monkeypatch, "--personas", "personas.json", "--doc-source", f"local:{'0' * 256}", "--out", "out.json") == 2 diff --git a/dokimi/tests/test_ragas_runtime.py b/dokimi/tests/test_ragas_runtime.py index 6f2730f65c..af4f6a1f53 100644 --- a/dokimi/tests/test_ragas_runtime.py +++ b/dokimi/tests/test_ragas_runtime.py @@ -70,12 +70,12 @@ def test_the_real_import_check_fails_instead_of_skipping_when_ragas_is_required( def test_ragas_without_the_extra_exits_with_the_install_command(monkeypatch, tmp_path): - from dokimi.commands.evaluate import _run_ragas_eval + from dokimi.commands._shared import run_ragas_eval monkeypatch.setitem(sys.modules, "ragas", None) monkeypatch.setitem(sys.modules, "ragas.llms", None) with pytest.raises(SystemExit) as exc: - _run_ragas_eval([], tmp_path / "answers.json", object()) + run_ragas_eval([], tmp_path / "answers.json", object()) assert "pip install 'dokimi[ragas]'" in str(exc.value) assert not (tmp_path / "answers_ragas.json").exists() @@ -92,3 +92,17 @@ def test_ragas_commands_exit_before_any_work_without_the_extra(monkeypatch, tmp_ with pytest.raises(SystemExit) as exc: run(args) assert "pip install 'dokimi[ragas]'" in str(exc.value) + + +def test_ragas_runtime_failure_is_reported_and_skipped(monkeypatch, tmp_path, capsys): + from unittest.mock import Mock + + from dokimi.commands._shared import run_ragas_eval + from dokimi.eval import ragas_eval + + evaluator = Mock() + evaluator.evaluate.side_effect = RuntimeError("judge returned nothing") + monkeypatch.setattr(ragas_eval, "RagasEvaluator", lambda **kwargs: evaluator) + run_ragas_eval([], tmp_path / "answers.json", argparse.Namespace()) + assert "RAGAS evaluation failed: judge returned nothing" in capsys.readouterr().out + assert not (tmp_path / "answers_ragas.json").exists() diff --git a/dokimi/tests/test_repo_cache_dir_usable.py b/dokimi/tests/test_repo_cache_dir_usable.py index 4382696904..f2e5fe4995 100644 --- a/dokimi/tests/test_repo_cache_dir_usable.py +++ b/dokimi/tests/test_repo_cache_dir_usable.py @@ -12,7 +12,7 @@ import pytest from dokimi import cli -from dokimi.commands.repo import _cache_dir +from dokimi.commands._shared import cache_dir_from_args from tests.cli_refusal import refusal PIN = "HEAD" @@ -104,10 +104,10 @@ def test_cache_dir_passes_unset_an_existing_directory_and_a_missing_child_unchan def args(value): return argparse.Namespace(cache_dir=value) - assert _cache_dir(args(None)) is None - assert _cache_dir(args("")) is None - assert _cache_dir(args(str(tmp_path))) == tmp_path - assert _cache_dir(args(str(tmp_path / "new" / "deeper"))) == tmp_path / "new" / "deeper" + assert cache_dir_from_args(args(None)) is None + assert cache_dir_from_args(args("")) is None + assert cache_dir_from_args(args(str(tmp_path))) == tmp_path + assert cache_dir_from_args(args(str(tmp_path / "new" / "deeper"))) == tmp_path / "new" / "deeper" assert not (tmp_path / "new").exists() diff --git a/dokimi/tests/test_repo_cache_env_usable.py b/dokimi/tests/test_repo_cache_env_usable.py index ab30b3ffb7..0a0fab631b 100644 --- a/dokimi/tests/test_repo_cache_env_usable.py +++ b/dokimi/tests/test_repo_cache_env_usable.py @@ -11,7 +11,7 @@ import pytest from dokimi import cli -from dokimi.commands.repo import _cache_dir +from dokimi.commands._shared import cache_dir_from_args from tests.cli_refusal import refusal CLOSING = "pass a directory the repository clones can be cached in" @@ -117,10 +117,10 @@ def test_a_bad_cache_dir_flag_is_still_named_when_the_variable_is_set(tmp_path, def test_cache_dir_returns_a_good_variable_and_an_empty_one_counts_as_unset(tmp_path, monkeypatch): args = argparse.Namespace(cache_dir=None) monkeypatch.setenv("DOKIMI_REPO_CACHE", "") - assert _cache_dir(args) is None + assert cache_dir_from_args(args) is None monkeypatch.setenv("DOKIMI_REPO_CACHE", str(tmp_path)) - assert _cache_dir(args) == tmp_path - assert _cache_dir(argparse.Namespace(cache_dir="")) == tmp_path + assert cache_dir_from_args(args) == tmp_path + assert cache_dir_from_args(argparse.Namespace(cache_dir="")) == tmp_path monkeypatch.setenv("DOKIMI_REPO_CACHE", str(tmp_path / "new" / "deeper")) - assert _cache_dir(args) == tmp_path / "new" / "deeper" + assert cache_dir_from_args(args) == tmp_path / "new" / "deeper" assert not (tmp_path / "new").exists() diff --git a/dokimi/tests/test_repo_environment.py b/dokimi/tests/test_repo_environment.py index 496b212d60..f44a673685 100644 --- a/dokimi/tests/test_repo_environment.py +++ b/dokimi/tests/test_repo_environment.py @@ -1074,13 +1074,13 @@ def test_redirection_keeps_its_fd_digit(): def test_whitespace_is_one_line_and_control_characters_are_escaped(): - from dokimi.commands.repo import _normalize_whitespace - assert _normalize_whitespace("a\r\n\tb c") == "a b c" - assert _normalize_whitespace("rm\x1b[2K ok") == "rm\\x1b[2K ok" - assert _normalize_whitespace("a\u200bb\u202e\ud800") == "a\\u200bb\\u202e\\ud800" - assert _normalize_whitespace("dir\ndz") == "dir dz" - assert _normalize_whitespace("x" * 150) == "x" * 100 - assert _normalize_whitespace("x" * 150, max_len=None) == "x" * 150 + from dokimi.commands._shared import normalize_whitespace + assert normalize_whitespace("a\r\n\tb c") == "a b c" + assert normalize_whitespace("rm\x1b[2K ok") == "rm\\x1b[2K ok" + assert normalize_whitespace("a\u200bb\u202e\ud800") == "a\\u200bb\\u202e\\ud800" + assert normalize_whitespace("dir\ndz") == "dir dz" + assert normalize_whitespace("x" * 150) == "x" * 100 + assert normalize_whitespace("x" * 150, max_len=None) == "x" * 150 @pytest.mark.parametrize("command, flagged", [ diff --git a/dokimi/tests/test_repo_l0_typecheck.py b/dokimi/tests/test_repo_l0_typecheck.py index 0bf7464e4c..e4cb8ab02d 100644 --- a/dokimi/tests/test_repo_l0_typecheck.py +++ b/dokimi/tests/test_repo_l0_typecheck.py @@ -130,10 +130,10 @@ def test_fence_file_names_map_back_to_their_index_only(): def test_the_scan_command_refuses_python_env_without_typecheck(tmp_path, capsys): args = build_parser().parse_args(["repo", "scan", str(tmp_path), "--python-env", sys.executable]) - from dokimi.commands.repo import _typecheck_or_exit + from dokimi.commands._shared import typecheck_or_exit with refusal() as out: - _typecheck_or_exit(args) + typecheck_or_exit(args) assert out.code == 2 assert "needs --typecheck" in capsys.readouterr().err @@ -141,21 +141,21 @@ def test_the_scan_command_refuses_python_env_without_typecheck(tmp_path, capsys) def test_the_scan_command_refuses_a_python_env_that_is_not_executable(tmp_path, capsys): missing = tmp_path / "no-such-python" args = build_parser().parse_args(["repo", "scan", str(tmp_path), "--typecheck", "--python-env", str(missing)]) - from dokimi.commands.repo import _typecheck_or_exit + from dokimi.commands._shared import typecheck_or_exit with refusal() as out: - _typecheck_or_exit(args) + typecheck_or_exit(args) assert out.code == 2 assert "not an executable interpreter" in capsys.readouterr().err def test_bare_typecheck_flag_means_mypy(tmp_path): - from dokimi.commands.repo import _typecheck_or_exit + from dokimi.commands._shared import typecheck_or_exit args = build_parser().parse_args(["repo", "scan", str(tmp_path), "--typecheck"]) assert args.typecheck is True assert args.python_env is None - assert _typecheck_or_exit(args).tool == "mypy" + assert typecheck_or_exit(args).tool == "mypy" def test_the_typecheck_flag_takes_no_value_so_a_source_after_it_is_not_its_checker(tmp_path): @@ -171,11 +171,11 @@ def test_the_checker_is_chosen_by_typecheck_tool(tmp_path): def test_typecheck_tool_without_typecheck_is_refused(tmp_path, capsys): - from dokimi.commands.repo import _typecheck_or_exit + from dokimi.commands._shared import typecheck_or_exit args = build_parser().parse_args(["repo", "scan", str(tmp_path), "--typecheck-tool", "mypy"]) with refusal() as out: - _typecheck_or_exit(args) + typecheck_or_exit(args) assert out.code == 2 assert "needs --typecheck" in capsys.readouterr().err @@ -282,13 +282,13 @@ def test_truncated_tool_output_is_an_error_not_a_partial_result(monkeypatch): def test_a_relative_python_env_is_made_absolute_before_the_tool_runs(tmp_path, monkeypatch): - from dokimi.commands.repo import _typecheck_or_exit + from dokimi.commands._shared import typecheck_or_exit link = tmp_path / "py" link.symlink_to(sys.executable) monkeypatch.chdir(tmp_path) args = build_parser().parse_args(["repo", "scan", str(tmp_path), "--typecheck", "--python-env", "py"]) - assert Path(_typecheck_or_exit(args).python).is_absolute() + assert Path(typecheck_or_exit(args).python).is_absolute() def test_a_fence_too_deep_for_the_parser_is_unresolved_not_a_crash(tmp_path): @@ -903,9 +903,9 @@ def parse_3_7(source, filename="", mode="exec", *, feature_version=None def test_the_scan_command_refuses_a_python_env_that_is_a_directory(tmp_path, capsys): # os.access(X_OK) is true for a directory: only a regular file can be the interpreter args = build_parser().parse_args(["repo", "scan", str(tmp_path), "--typecheck", "--python-env", str(tmp_path)]) - from dokimi.commands.repo import _typecheck_or_exit + from dokimi.commands._shared import typecheck_or_exit with refusal() as out: - _typecheck_or_exit(args) + typecheck_or_exit(args) assert out.code == 2 assert "not an executable interpreter" in capsys.readouterr().err diff --git a/dokimi/tests/test_repo_source_exit_2.py b/dokimi/tests/test_repo_source_exit_2.py index 975c0345a8..3e38fb318a 100644 --- a/dokimi/tests/test_repo_source_exit_2.py +++ b/dokimi/tests/test_repo_source_exit_2.py @@ -228,8 +228,8 @@ def test_a_windows_manifest_path_leaving_an_unpinned_tree_is_refused_as_typed(tm monkeypatch.setattr(repo_run, "os", SimpleNamespace(path=windows_path)) # only this module; posixpath stays for manifest in ("..\\outside.yaml", "sub\\..\\..\\outside.yaml"): with pytest.raises(InputError, match=r"^path escapes the repository: "): - repo_run._refuse_typed(source, SimpleNamespace(manifest=manifest, manifest_file=None)) - repo_run._refuse_typed(source, SimpleNamespace(manifest="sub\\..\\ok.yaml", manifest_file=None)) + repo_run.refuse_typed(source, SimpleNamespace(manifest=manifest, manifest_file=None)) + repo_run.refuse_typed(source, SimpleNamespace(manifest="sub\\..\\ok.yaml", manifest_file=None)) def test_a_windows_drive_manifest_is_refused_for_an_unpinned_tree(tmp_path, monkeypatch): @@ -244,7 +244,7 @@ def test_a_windows_drive_manifest_is_refused_for_an_unpinned_tree(tmp_path, monk monkeypatch.setattr(repo_run, "os", SimpleNamespace(path=windows_path)) # `D:/other/x.yaml` is not absolute for the `/` check on the tree path: only the drive check refuses it. with pytest.raises(InputError) as raised: - repo_run._refuse_typed(source, SimpleNamespace(manifest="D:\\other\\x.yaml", manifest_file=None)) + repo_run.refuse_typed(source, SimpleNamespace(manifest="D:\\other\\x.yaml", manifest_file=None)) assert str(raised.value) == "path escapes the repository: D:\\other\\x.yaml" @@ -261,9 +261,9 @@ def test_a_windows_manifest_path_leaving_a_pinned_tree_is_refused_as_typed(monke for manifest in ("..\\outside.yaml", "sub\\..\\..\\outside.yaml", "D:/other/x.yaml", "D:\\other\\x.yaml", "D:x.yaml", "//host/share/x.yaml"): with pytest.raises(InputError) as raised: - repo_run._refuse_typed(pinned, SimpleNamespace(manifest=manifest, manifest_file=None)) + repo_run.refuse_typed(pinned, SimpleNamespace(manifest=manifest, manifest_file=None)) assert str(raised.value) == f"path escapes the repository: {manifest}" - repo_run._refuse_typed(pinned, SimpleNamespace(manifest="sub\\..\\ok.yaml", manifest_file=None)) + repo_run.refuse_typed(pinned, SimpleNamespace(manifest="sub\\..\\ok.yaml", manifest_file=None)) def test_a_pinned_source_gets_only_the_tree_path_check_for_a_manifest_that_stays_in_the_tree(tmp_path): @@ -273,11 +273,11 @@ def test_a_pinned_source_gets_only_the_tree_path_check_for_a_manifest_that_stays from dokimi.utils import InputError pinned = SimpleNamespace(location="https://example.invalid/r.git", remote=True, rev="a" * 40, subdir=None) - repo_run._refuse_typed(pinned, SimpleNamespace(manifest="sub/../ok.yaml", manifest_file=None)) + repo_run.refuse_typed(pinned, SimpleNamespace(manifest="sub/../ok.yaml", manifest_file=None)) with pytest.raises(InputError, match=r"^path escapes the repository: \.\./x\.yaml$"): - repo_run._refuse_typed(pinned, SimpleNamespace(manifest="../x.yaml", manifest_file=None)) + repo_run.refuse_typed(pinned, SimpleNamespace(manifest="../x.yaml", manifest_file=None)) unpinned = SimpleNamespace(location=str(tmp_path), remote=False, rev=None, subdir=None) - repo_run._refuse_typed(unpinned, SimpleNamespace(manifest="sub/../ok.yaml", manifest_file=None)) + repo_run.refuse_typed(unpinned, SimpleNamespace(manifest="sub/../ok.yaml", manifest_file=None)) def test_no_typed_manifest_or_a_manifest_file_leaves_the_manifest_path_unchecked(tmp_path): @@ -286,9 +286,9 @@ def test_no_typed_manifest_or_a_manifest_file_leaves_the_manifest_path_unchecked from dokimi.commands import repo_run source = SimpleNamespace(location=str(tmp_path), remote=False, rev=None, subdir=None) - assert repo_run._refuse_typed(source, SimpleNamespace(manifest=None, manifest_file=None)) is None + assert repo_run.refuse_typed(source, SimpleNamespace(manifest=None, manifest_file=None)) is None # `--manifest-file` supplies the manifest, so a `--manifest` beside it is not read as a tree path. - assert repo_run._refuse_typed(source, SimpleNamespace(manifest="../x.yaml", manifest_file="m.yaml")) is None + assert repo_run.refuse_typed(source, SimpleNamespace(manifest="../x.yaml", manifest_file="m.yaml")) is None @pytest.mark.skipif(shutil.which("git") is None, reason="needs git") diff --git a/dokimi/tests/test_saved_self_judge_warning.py b/dokimi/tests/test_saved_self_judge_warning.py index 24710b263e..c9de5ee78f 100644 --- a/dokimi/tests/test_saved_self_judge_warning.py +++ b/dokimi/tests/test_saved_self_judge_warning.py @@ -124,7 +124,8 @@ def stop(data, judges, context, roles=("answer", "judge")): raise Stop monkeypatch.setattr(importlib.import_module(module), "warn_recorded_self_judge", stop) - monkeypatch.setattr("dokimi.commands.evaluate._require_ragas", lambda: None) + if words == ("eval", "score", "ragas"): + monkeypatch.setattr("dokimi.commands.evaluate.require_ragas", lambda: None) args = parse_args(argv) with pytest.raises(Stop): args.func(args) @@ -177,7 +178,8 @@ def test_pairwise_checks_the_escalation_judge_too(tmp_path, monkeypatch): def test_escalation_defaults_to_the_judge_provider_and_is_in_the_label(tmp_path, monkeypatch): - from dokimi.commands.judge_reliability import _pairwise_judges, pairwise_judge + from dokimi.commands._shared import pairwise_judges + from dokimi.commands.judge_reliability import pairwise_judge built = [] @@ -189,7 +191,7 @@ def __init__(self, model, provider, temperature=None): monkeypatch.setattr("dokimi.eval.judge.Judge", FakeJudge) args = parse_args(["eval", "score", "pairwise", "--answers", str(_arms_file(tmp_path)), "--judge", "anthropic/claude-sonnet-5-5", "--escalate-model", "claude-opus-5-5"]) - assert _pairwise_judges(args)[1] == ("claude-opus-5-5", "anthropic") + assert pairwise_judges(args)[1] == ("claude-opus-5-5", "anthropic") _, label = pairwise_judge(args) assert label.endswith(" pairwise → anthropic/claude-opus-5-5") # stored as the measure name assert ("claude-opus-5-5", "anthropic") in built