Skip to content
Merged
Show file tree
Hide file tree
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 Nov 29, 2026
b7e217a
docs(changelog): describe shared command helpers
napetrov Nov 30, 2026
e0f335f
style(commands): trim blank lines left by helper moves
napetrov Nov 30, 2026
3e0d5d3
docs(novelty): follow moved command flags
napetrov Nov 30, 2026
ec0bfd1
Use the public novelty output directory in skill sensitivity
napetrov Dec 1, 2026
0e6dec7
Exercise generic RAGAS failures in the shared command helper
napetrov Dec 1, 2026
96f11a5
docs(repo): reread the repo contract when commands/_shared.py changes
xaleryb Dec 2, 2026
948a3ce
test(tasks): the rename-cli-flag check patches the renamed registry l…
napetrov Dec 2, 2026
2d27cdc
Keep the flag-rename verifier on its pinned benchmark API
napetrov Dec 2, 2026
e3b29c0
Merge commit 'refs/pr-address/base/main' into HEAD
napetrov Dec 2, 2026
eb1e8f8
fix(repo): preserve ignored scan counts
napetrov Dec 2, 2026
c058b05
refactor(novelty): group shared novelty helpers
napetrov Dec 2, 2026
b43aa82
docs(changelog): clarify command refactor scope
napetrov Dec 2, 2026
6fad4c8
style(commands): tidy imports and whitespace
napetrov Dec 2, 2026
e5fbb6e
test(ragas): patch the exact dependency check
napetrov Dec 2, 2026
02c4400
test(tasks): record the pinned oracle fix
napetrov Dec 2, 2026
7e4be49
test(repo): record scan review verification
napetrov Dec 2, 2026
dd66c27
Merge commit 'refs/pr-address/fallback-a/main' into HEAD
napetrov Dec 2, 2026
5e4ce5f
test(cli): supply an agent run fault fixture
napetrov Dec 2, 2026
4789d42
Merge commit 'ed7a4e2ffdb7d60bd96d39b78ed7467967c39310' into HEAD
napetrov Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agent-eval/tasks/rename-cli-flag/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
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.
4 changes: 2 additions & 2 deletions dokimi/docs/reference/cli-interface.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand Down Expand Up @@ -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"}
],
Expand Down
1 change: 1 addition & 0 deletions dokimi/docs/repo-evaluation-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions dokimi/dokimi/artifacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Comment on lines +423 to +426

Copy link
Copy Markdown
Contributor Author

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 in test_subjects.py). The other calls add a suffix. Mapping .. to cell would hide those refusals.

249 changes: 249 additions & 0 deletions dokimi/dokimi/commands/_shared.py
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.
Comment thread
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:

Check warning on line 29 in dokimi/dokimi/commands/_shared.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
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}")
Comment thread
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:

Check warning on line 78 in dokimi/dokimi/commands/_shared.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
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 ""

Check warning on line 86 in dokimi/dokimi/commands/_shared.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
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"

Check warning on line 110 in dokimi/dokimi/commands/_shared.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
print(f" {mark} {claim['file']}:{claim['line']} [{claim.get('kind')}] "
f"{str(claim.get('claim'))[:90]} -- {claim.get('why')}")

Check warning on line 112 in dokimi/dokimi/commands/_shared.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
if out:

Check warning on line 113 in dokimi/dokimi/commands/_shared.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
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:

Check warning on line 156 in dokimi/dokimi/commands/_shared.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
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
31 changes: 4 additions & 27 deletions dokimi/dokimi/commands/answers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand All @@ -73,15 +50,15 @@ 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,
require_local_doc_source,
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)
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading