Repository navigation
refactor(commands): share command helpers publicly, one safe filename helper #1413
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
79631d4
refactor(commands): share command helpers publicly, one _safe_name
napetrov b7e217a
docs(changelog): describe shared command helpers
napetrov e0f335f
style(commands): trim blank lines left by helper moves
napetrov 3e0d5d3
docs(novelty): follow moved command flags
napetrov ec0bfd1
Use the public novelty output directory in skill sensitivity
napetrov 0e6dec7
Exercise generic RAGAS failures in the shared command helper
napetrov 96f11a5
docs(repo): reread the repo contract when commands/_shared.py changes
xaleryb 948a3ce
test(tasks): the rename-cli-flag check patches the renamed registry l…
napetrov 2d27cdc
Keep the flag-rename verifier on its pinned benchmark API
napetrov e3b29c0
Merge commit 'refs/pr-address/base/main' into HEAD
napetrov eb1e8f8
fix(repo): preserve ignored scan counts
napetrov c058b05
refactor(novelty): group shared novelty helpers
napetrov b43aa82
docs(changelog): clarify command refactor scope
napetrov 6fad4c8
style(commands): tidy imports and whitespace
napetrov e5fbb6e
test(ragas): patch the exact dependency check
napetrov 02c4400
test(tasks): record the pinned oracle fix
napetrov 7e4be49
test(repo): record scan review verification
napetrov dd66c27
Merge commit 'refs/pr-address/fallback-a/main' into HEAD
napetrov 5e4ce5f
test(cli): supply an agent run fault fixture
napetrov 4789d42
Merge commit 'ed7a4e2ffdb7d60bd96d39b78ed7467967c39310' into HEAD
napetrov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 3 additions & 0 deletions
3
dokimi/changelog.d/20261129_120000_napetrov_shared-command-helpers.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| ### Changed | ||
|
|
||
| - **Internal refactor of the command helpers.** Flags, output, file names and exit codes are unchanged. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. | ||
|
napetrov marked this conversation as resolved.
Resolved
|
||
|
|
||
| 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}") | ||
|
napetrov marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is main's
_safe_name, moved unchanged. Both directory uses refuse./..before writing (_safe_subject_id,_validate_unique_product_output_dirs; tests intest_subjects.py). The other calls add a suffix. Mapping..tocellwould hide those refusals.