diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index e4b324378b..0045a8e648 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -10,7 +10,11 @@ on: paths: - 'dokimi/fuzz/**' - 'dokimi/dokimi/llm_json.py' - - 'dokimi/dokimi/utils.py' + - 'dokimi/dokimi/frontmatter.py' + - 'dokimi/dokimi/files.py' + - 'dokimi/dokimi/records.py' + - 'dokimi/dokimi/digest.py' + - 'dokimi/dokimi/model_names.py' - 'dokimi/dokimi/eval/checklist.py' - 'dokimi/dokimi/eval/pairwise.py' - 'dokimi/dokimi/eval/reference_checks.py' diff --git a/dokimi/changelog.d/20261124_120000_napetrov_arch-c14.md b/dokimi/changelog.d/20261124_120000_napetrov_arch-c14.md new file mode 100644 index 0000000000..47a67bd240 --- /dev/null +++ b/dokimi/changelog.d/20261124_120000_napetrov_arch-c14.md @@ -0,0 +1,3 @@ +### Changed + +- **Utility helpers have focused import paths.** Use `dokimi.frontmatter` for frontmatter, `dokimi.files` for input and filesystem guards, `dokimi.digest` for digests, `dokimi.model_names` for model identity and `dokimi.records` for `question_id`. `dokimi.utils` keeps public import aliases. Private helpers and test patch targets use the defining module. diff --git a/dokimi/docs/architecture.md b/dokimi/docs/architecture.md index e5915f1a27..066741f058 100644 --- a/dokimi/docs/architecture.md +++ b/dokimi/docs/architecture.md @@ -73,11 +73,15 @@ points up: | tracks | `runner`, `runs`, `report`, `subjects`, `novelty`, `harnesses`, `agent_run`, `context`, `repos`, `explore`, `tool_preference`, `external`, `dashboard`, `orchestrator`, `datasets_export`, `coverage`, `task_formats`, and the checkers `config_check`, `schema_check`, `schema_compat` | | evaluation | `eval`, `personas`, `questions`, `treatments`, `plugins` | | components | `ingest`, `metrics`, `gate`, `mcp`, `skills`, `agent_profiles` | -| foundation | `__init__` (the `dokimi` package itself), `_version`, `artifacts`, `records`, `llm`, `llm_providers`, `process`, `container_policy`, `docker_cmd`, `caching`, `config`, `registry`, `intents`, `defaults`, `console`, `utils`, `metrics/usage.py` | +| foundation | `__init__` (the `dokimi` package itself), `_version`, `artifacts`, `records`, `llm`, `llm_providers`, `process`, `container_policy`, `docker_cmd`, `caching`, `config`, `registry`, `intents`, `defaults`, `console`, `digest`, `files`, `frontmatter`, `model_names`, `utils` (compatibility imports), `metrics/usage.py` | So `report` (a track) can call `gate` (a component), and `gate` cannot import `report`. The sections below follow the tracks, not the layers. +`dokimi.utils` keeps public import aliases. Import private helpers and patch +moved helpers in their defining modules, for example `dokimi.digest` for +`tree_digest`. + ## Static documentation track Lives under `dokimi/{ingest,metrics,gate,runner,report}`. `gate/` and @@ -478,7 +482,7 @@ deterministic checks on it; `dokimi memory lint`. Guide: [memory.md](memory.md). and Windows reader threads close theirs at EOF. `dokimi/process_hooks.py` holds what the signal handler runs before the kill (notices) and after it (hooks): a run directory records its stop there. `FakeRunner` is its test adapter: code that spawns takes a `runner` argument. -- Bad input: a library loader raises `dokimi.utils.InputError`, naming the file, and +- Bad input: a library loader raises `dokimi.files.InputError`, naming the file, and never ends the process. `cli.main` prints `Error: ` and exits 2; exit 1 stays the verdict of a gate. `tests/test_import_architecture.py` allows an exit only in the frontend. diff --git a/dokimi/docs/judge-panel-study.md b/dokimi/docs/judge-panel-study.md index 9db82a6a84..079cbb37b1 100644 --- a/dokimi/docs/judge-panel-study.md +++ b/dokimi/docs/judge-panel-study.md @@ -284,7 +284,7 @@ What exists: EFFECT` or `NOT MEASURED`. Judges that fail `--validity` do not vote. `--strict` makes `JUDGE-DEPENDENT` an error. This is the right shape, per-judge numbers rather than an average that hides the spread, and it already guards against "(one judge)" results. -- **Self-judging** is a warning on an exact model match (`utils.warn_judge_independence`). +- **Self-judging** is a warning on an exact model match (`dokimi.model_names.warn_judge_independence`). It never refuses, and a judge from the same family passes silently. What is missing (each item was needed to produce this note): diff --git a/dokimi/dokimi/agent_profiles/loader.py b/dokimi/dokimi/agent_profiles/loader.py index 03ff353205..a7cde5352e 100644 --- a/dokimi/dokimi/agent_profiles/loader.py +++ b/dokimi/dokimi/agent_profiles/loader.py @@ -21,7 +21,7 @@ from pathlib import Path from typing import List -from dokimi.utils import parse_frontmatter +from dokimi.frontmatter import parse_frontmatter @dataclass diff --git a/dokimi/dokimi/agent_run/adapters.py b/dokimi/dokimi/agent_run/adapters.py index d24ec58a95..d3b3ac41e1 100644 --- a/dokimi/dokimi/agent_run/adapters.py +++ b/dokimi/dokimi/agent_run/adapters.py @@ -16,7 +16,7 @@ from urllib.parse import urlsplit from dokimi.repos.events import TRACE_FORMATS -from dokimi.utils import InputError +from dokimi.files import InputError _WINDOWS = os.name == "nt" _NPM_ENTRYPOINTS = { diff --git a/dokimi/dokimi/agent_run/checker.py b/dokimi/dokimi/agent_run/checker.py index fac3fb11c3..f78d284388 100644 --- a/dokimi/dokimi/agent_run/checker.py +++ b/dokimi/dokimi/agent_run/checker.py @@ -13,7 +13,7 @@ from dokimi import process from dokimi.harnesses.tasks import TaskSpec -from dokimi.utils import InputError +from dokimi.files import InputError from .scoring import PROCESS_POINTS diff --git a/dokimi/dokimi/agent_run/replay.py b/dokimi/dokimi/agent_run/replay.py index 8214ed5ffb..768537a663 100644 --- a/dokimi/dokimi/agent_run/replay.py +++ b/dokimi/dokimi/agent_run/replay.py @@ -11,7 +11,7 @@ from pathlib import Path from typing import Any -from dokimi.utils import InputError +from dokimi.files import InputError from .scoring import usage_summary diff --git a/dokimi/dokimi/agent_run/runner.py b/dokimi/dokimi/agent_run/runner.py index 674b1f4fdc..aebd65a0f4 100644 --- a/dokimi/dokimi/agent_run/runner.py +++ b/dokimi/dokimi/agent_run/runner.py @@ -25,7 +25,8 @@ from dokimi.harnesses.tasks import TaskSpec from dokimi.repos.events import convert from dokimi.repos.transcript import Transcript -from dokimi.utils import InputError, tree_digest +from dokimi.digest import tree_digest +from dokimi.files import InputError from .adapters import Adapter, Route, Unavailable, adapter_for from .checker import SYSTEM_ENV, check, inconclusive, refuse_workspace_checker, session_env diff --git a/dokimi/dokimi/artifacts.py b/dokimi/dokimi/artifacts.py index 8366f36c73..77d15c94f5 100644 --- a/dokimi/dokimi/artifacts.py +++ b/dokimi/dokimi/artifacts.py @@ -57,7 +57,7 @@ from dokimi.atomic_write import write_bytes_in_place_or_atomic from dokimi.dokimi_commit import dokimi_commit from dokimi.process_io import json_utf8_bytes -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input logger = logging.getLogger(__name__) @@ -303,14 +303,14 @@ def save_artifact(kind: str, data: dict, path: Path | str, *, ensure_ascii: bool process that last saved it, so an artifact built from a loaded one takes the new run's id. ``data`` itself is not mutated. - A ``novelty`` payload with ``status`` or ``partial`` (what a ``--max-usd`` stop keeps) is - refused with :class:`~dokimi.utils.InputError`, as :func:`load_artifact` refuses it: nothing + refused with :class:`~dokimi.files.InputError`, as :func:`load_artifact` refuses it: nothing is written, since ``runs`` would list the file as a finished run. - The payload is validated first. :class:`ArtifactValidationError` means nothing was written at ``path`` (a file already there is untouched); the rejected payload is kept at ``.rejected`` so a paid run is not lost to a schema problem. A later valid save to ``path`` removes that ``.rejected`` (only that sibling), so a leftover always belongs to the latest attempt; if it cannot be removed the save still stands and - a warning is logged. :class:`~dokimi.utils.InputError` means ``DOKIMI_RUN_ID`` is malformed + a warning is logged. :class:`~dokimi.files.InputError` means ``DOKIMI_RUN_ID`` is malformed (``cli.main`` refuses it before a command runs): nothing is written at ``path`` and the payload is kept at ``.rejected`` the same way. ``KeyError`` means ``kind`` is not registered in :data:`SCHEMA_VERSIONS`. @@ -400,7 +400,7 @@ def _is_partial_novelty(kind: str, data: dict) -> bool: def load_artifact(kind: str, path: Path | str, *, validate: bool = True) -> dict: """Read and (optionally) validate an artifact of ``kind`` from ``path``. - Every failure is an :class:`~dokimi.utils.InputError` naming ``path``: a file that is + Every failure is an :class:`~dokimi.files.InputError` naming ``path``: a file that is missing, unreadable, not UTF-8 or JSON, not a JSON object, or that fails the schema, and the partial file of an unfinished novelty or arms run. """ diff --git a/dokimi/dokimi/cli.py b/dokimi/dokimi/cli.py index 36900ae803..bac913afbe 100755 --- a/dokimi/dokimi/cli.py +++ b/dokimi/dokimi/cli.py @@ -459,7 +459,7 @@ def main() -> None: tolerate_console_encoding() from dokimi import cli_output from dokimi.artifacts import run_id - from dokimi.utils import InputError + from dokimi.files import InputError cli_output.reset() # before the parse: a usage error prints its document from there args = parse_args() diff --git a/dokimi/dokimi/cli_output.py b/dokimi/dokimi/cli_output.py index 0da8445df3..8950b2525a 100644 --- a/dokimi/dokimi/cli_output.py +++ b/dokimi/dokimi/cli_output.py @@ -17,7 +17,7 @@ from dokimi import artifacts from dokimi.artifacts import SCHEMA_DIR from dokimi.dokimi_commit import dokimi_commit -from dokimi.utils import InputError +from dokimi.files import InputError SCHEMA_VERSION = "cli_output.v1" STATUSES = ("complete", "partial", "budget_stopped", "cancelled", "failed") diff --git a/dokimi/dokimi/commands/_shared.py b/dokimi/dokimi/commands/_shared.py index 1a76325d59..8c7dc6e0cd 100644 --- a/dokimi/dokimi/commands/_shared.py +++ b/dokimi/dokimi/commands/_shared.py @@ -24,7 +24,7 @@ DEFAULT_JUDGE_PROVIDER, ) from dokimi.repos.l0.config import new_failures -from dokimi.utils import InputError +from dokimi.files import InputError if TYPE_CHECKING: from dokimi.repos import RepoSource diff --git a/dokimi/dokimi/commands/agent_run.py b/dokimi/dokimi/commands/agent_run.py index d8704beb51..f403d7e690 100644 --- a/dokimi/dokimi/commands/agent_run.py +++ b/dokimi/dokimi/commands/agent_run.py @@ -15,7 +15,7 @@ from dokimi import cli_flags, cli_output from dokimi.artifacts import save_artifact, stamp from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE -from dokimi.utils import InputError +from dokimi.files import InputError def _live_cost(rows: list[dict[str, Any]]) -> dict[str, Any]: diff --git a/dokimi/dokimi/commands/answer_formats.py b/dokimi/dokimi/commands/answer_formats.py index 228eb006ed..296a2daeff 100644 --- a/dokimi/dokimi/commands/answer_formats.py +++ b/dokimi/dokimi/commands/answer_formats.py @@ -16,7 +16,7 @@ from pathlib import Path from dokimi import cli_flags from dokimi.cli_model_ref import add_model_flag -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input def cmd_questions_import(args: argparse.Namespace) -> None: @@ -52,7 +52,7 @@ def cmd_eval_reference(args: argparse.Namespace) -> None: except ValueError as e: # ArtifactValidationError: names the record and the fix raise InputError(str(e)) from e if not args.no_judge: - from dokimi.utils import warn_recorded_self_judge + from dokimi.model_names import warn_recorded_self_judge warn_recorded_self_judge(data, [(args.judge_model, args.judge_provider)], "eval score reference") try: diff --git a/dokimi/dokimi/commands/answers.py b/dokimi/dokimi/commands/answers.py index 1f1291ab88..84eaf4f65a 100644 --- a/dokimi/dokimi/commands/answers.py +++ b/dokimi/dokimi/commands/answers.py @@ -25,7 +25,7 @@ DEFAULT_MAX_TOKENS_PER_QUESTION, DEFAULT_RETRIEVAL_TOP_K, ) -from dokimi.utils import InputError +from dokimi.files import InputError def _load_questions(path: str) -> list: diff --git a/dokimi/dokimi/commands/arms.py b/dokimi/dokimi/commands/arms.py index 02393b13d4..3a9da3d636 100644 --- a/dokimi/dokimi/commands/arms.py +++ b/dokimi/dokimi/commands/arms.py @@ -19,7 +19,8 @@ from dokimi.report.arms_pairs import print_pairs_note, shown_mean from dokimi.report.arms_report import ask_summary_lines from dokimi.llm import ANSWER_PROVIDERS -from dokimi.utils import InputError, question_id, read_json_input +from dokimi.files import InputError, read_json_input +from dokimi.records import question_id from dokimi.write_probe import can_write from dokimi.eval.judge import JUDGE_PROVIDERS from dokimi.defaults import ( diff --git a/dokimi/dokimi/commands/baseline.py b/dokimi/dokimi/commands/baseline.py index 749b93f0c0..3fb410280c 100644 --- a/dokimi/dokimi/commands/baseline.py +++ b/dokimi/dokimi/commands/baseline.py @@ -13,11 +13,11 @@ from dokimi.artifacts import _write_target, save_artifact from dokimi.atomic_write import write_bytes_atomic -from dokimi.utils import model_identity, same_model +from dokimi.model_names import model_identity, same_model from dokimi.commands import baseline_regression from dokimi.commands._output import exit_on_rejected from dokimi.exit_codes import EXIT_INVALID -from dokimi.utils import InputError, read_json_input, read_json_input_bytes +from dokimi.files import InputError, read_json_input, read_json_input_bytes BASELINES_DIR = Path("baselines/eval") diff --git a/dokimi/dokimi/commands/baseline_regression.py b/dokimi/dokimi/commands/baseline_regression.py index 848cdc042a..13a8a223da 100644 --- a/dokimi/dokimi/commands/baseline_regression.py +++ b/dokimi/dokimi/commands/baseline_regression.py @@ -9,7 +9,7 @@ import math from decimal import Decimal, InvalidOperation -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.records import BASELINE, CONTEXT, Record diff --git a/dokimi/dokimi/commands/benchmark.py b/dokimi/dokimi/commands/benchmark.py index 373c45184e..ad40b1d4ec 100644 --- a/dokimi/dokimi/commands/benchmark.py +++ b/dokimi/dokimi/commands/benchmark.py @@ -16,7 +16,7 @@ from dokimi.cli_model_ref import add_model_flag from dokimi.eval.judge_sampling import check_judge_sampling from dokimi.llm import CALLER_CHOICES, PROVIDER_ALIASES, PROVIDERS, credential_env_var, resolve_api_key, resolve_model -from dokimi.utils import warn_judge_independence as _warn_judge_independence +from dokimi.model_names import warn_judge_independence as _warn_judge_independence from dokimi.eval.judge import JUDGE_PROVIDERS from dokimi.defaults import ( DEFAULT_ANSWER_MODEL, @@ -32,7 +32,8 @@ 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 +from dokimi.files import InputError, refuse_device +from dokimi.model_names import check_bedrock_model def _refuse_judge_sampling(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/cache_dir.py b/dokimi/dokimi/commands/cache_dir.py index 165997ae60..328eb9f547 100644 --- a/dokimi/dokimi/commands/cache_dir.py +++ b/dokimi/dokimi/commands/cache_dir.py @@ -22,7 +22,7 @@ def usable_cache_dir(raw: str | None, use: str = RETENTION_USE, *, label: str = call or a clone (#701, #765). ``use`` closes the message: "pass a directory "; ``label`` names the setting at its start (``--cache-dir`` unless the caller says otherwise: #826). """ - from dokimi.utils import InputError + from dokimi.files import InputError if not raw: return None @@ -53,7 +53,7 @@ def resolved_cache_dir(raw: str | None, use: str, *, label: str) -> Path | None: A path that cannot be resolved (an unreadable ancestor, a symbolic link loop) raises ``InputError`` naming ``label``. The resolved path is returned: the cache is made there. """ - from dokimi.utils import InputError + from dokimi.files import InputError if not raw: return None diff --git a/dokimi/dokimi/commands/catalog.py b/dokimi/dokimi/commands/catalog.py index e4c51be3a8..3bd7e5a9ec 100644 --- a/dokimi/dokimi/commands/catalog.py +++ b/dokimi/dokimi/commands/catalog.py @@ -28,7 +28,7 @@ ) from dokimi.external.catalog_rates import RateTally, text_lines from dokimi.llm import ANSWER_PROVIDERS, PROVIDER_ALIASES, is_litellm_route -from dokimi.utils import InputError +from dokimi.files import InputError def _print_strict_reasons(rows: list, strict: bool) -> None: @@ -520,7 +520,7 @@ def cmd_catalog_formats(args: argparse.Namespace) -> None: def _question_sources(specs: list) -> list: """Each ``--questions PATH=LABEL`` as a (questions, rule) source.""" - from dokimi.utils import read_json_input + from dokimi.files import read_json_input sources = [] for spec in specs: @@ -543,7 +543,7 @@ def _trigger_set_sources(specs: list, catalog) -> list: any other source. TARGET names the skill a skill-creator set was written for. """ from dokimi.external import trigger_set as ts - from dokimi.utils import read_json_input + from dokimi.files import read_json_input names = {s.name for s in catalog} out = [] diff --git a/dokimi/dokimi/commands/catalog_eval.py b/dokimi/dokimi/commands/catalog_eval.py index be8622eb7e..05af0832c4 100644 --- a/dokimi/dokimi/commands/catalog_eval.py +++ b/dokimi/dokimi/commands/catalog_eval.py @@ -21,7 +21,7 @@ from dokimi import __version__ from dokimi.atomic_write import keep_owner_group_mode from dokimi.artifacts import save_artifact -from dokimi.utils import InputError +from dokimi.files import InputError _OUTPUTS = ("catalog.json", "plan.json", "result.json", "report.md") _REPORT_HEADER = "# Catalog static evaluation" diff --git a/dokimi/dokimi/commands/catalog_novelty.py b/dokimi/dokimi/commands/catalog_novelty.py index 4052d8ce90..3ff19849cf 100644 --- a/dokimi/dokimi/commands/catalog_novelty.py +++ b/dokimi/dokimi/commands/catalog_novelty.py @@ -40,7 +40,7 @@ from dokimi.cli_types import unit_interval from dokimi.commands.novelty_run import stops_at_cap from dokimi.novelty.sweep import bundle_instances, read_rows, resumable, summarize, summary_lines -from dokimi.utils import InputError +from dokimi.files import InputError if TYPE_CHECKING: from dokimi.novelty.client import SpendCap @@ -113,7 +113,7 @@ def directory(self) -> Path: def _skill_digest(skill_md: Path) -> str: """The digest a resumed run compares: the directory tree, and the entry point's loaded content (a symlinked SKILL.md changes its target's text without changing the link the tree digest reads).""" - from dokimi.utils import tree_digest + from dokimi.digest import tree_digest entry = hashlib.sha256(skill_md.read_bytes()).hexdigest() tree = tree_digest(skill_md.parent.resolve(), tracked={}) # resolved: tree_digest hashes a symlinked ROOT by its link text diff --git a/dokimi/dokimi/commands/catalog_probe.py b/dokimi/dokimi/commands/catalog_probe.py index afe3d1eb56..00efb9cdf8 100644 --- a/dokimi/dokimi/commands/catalog_probe.py +++ b/dokimi/dokimi/commands/catalog_probe.py @@ -15,7 +15,7 @@ from pathlib import Path from dokimi import cli_flags from dokimi.atomic_write import write_text_atomic -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input from dokimi.write_probe import can_write diff --git a/dokimi/dokimi/commands/catalog_provenance.py b/dokimi/dokimi/commands/catalog_provenance.py index bf5a5b268d..46c79c4f7c 100644 --- a/dokimi/dokimi/commands/catalog_provenance.py +++ b/dokimi/dokimi/commands/catalog_provenance.py @@ -14,7 +14,7 @@ from pathlib import Path from dokimi import cli_flags -from dokimi.utils import InputError +from dokimi.files import InputError def _rel(skill_dir: Path, root: Path) -> str: diff --git a/dokimi/dokimi/commands/catalog_scan.py b/dokimi/dokimi/commands/catalog_scan.py index 558f80afc2..8eeb16f6d1 100644 --- a/dokimi/dokimi/commands/catalog_scan.py +++ b/dokimi/dokimi/commands/catalog_scan.py @@ -27,14 +27,14 @@ from dokimi.external.findings import locate from dokimi.external.listing import listed_chars from dokimi.external.skill_format import NOT_CHECKED_CODES, not_checked -from dokimi.utils import InputError +from dokimi.files import InputError def _listing_source(entry): """``(file, meta, body, directory name, at root, sha256 of the bytes read)`` of the SKILL.md ``repo budget`` would read for the entry, None when it is not named ``SKILL.md``, cannot be read or resolves outside the catalog root. The directory name and ``at root`` are those of the directory the skill is listed in, not of a symlink target.""" - from dokimi.utils import parse_frontmatter + from dokimi.frontmatter import parse_frontmatter if entry.path is None: return None @@ -176,7 +176,7 @@ def skill_dir_digest(entry, outputs: Iterable[Path] = ()) -> Optional[str]: Files in *outputs* (resolved paths) that sit in the directory are left out. None when it cannot be read. """ - from dokimi.utils import tree_digest + from dokimi.digest import tree_digest path = entry.skill.path.parent if entry.loaded and entry.skill is not None else entry.path if path is not None and path.name == "SKILL.md": diff --git a/dokimi/dokimi/commands/context.py b/dokimi/dokimi/commands/context.py index 3250a11cdf..63a3863b4d 100644 --- a/dokimi/dokimi/commands/context.py +++ b/dokimi/dokimi/commands/context.py @@ -13,7 +13,7 @@ from dokimi.cli_types import non_negative_int, unit_interval from dokimi.exit_codes import EXIT_INCONCLUSIVE -from dokimi.utils import InputError, refuse_device +from dokimi.files import InputError, refuse_device def cmd_context_trace(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/dashboard.py b/dokimi/dokimi/commands/dashboard.py index cd34773a8b..ebe8c3ae78 100644 --- a/dokimi/dokimi/commands/dashboard.py +++ b/dokimi/dokimi/commands/dashboard.py @@ -9,7 +9,7 @@ from pathlib import Path from dokimi import cli_flags from dokimi.commands._output import exit_on_rejected -from dokimi.utils import InputError +from dokimi.files import InputError def cmd_dashboard_generate(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/dataset.py b/dokimi/dokimi/commands/dataset.py index 266fef2556..7daff9f9c6 100644 --- a/dokimi/dokimi/commands/dataset.py +++ b/dokimi/dokimi/commands/dataset.py @@ -7,7 +7,7 @@ import argparse from pathlib import Path -from dokimi.utils import InputError +from dokimi.files import InputError def cmd_dataset_export(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/delivery.py b/dokimi/dokimi/commands/delivery.py index 08c3541532..ed61fed7ac 100644 --- a/dokimi/dokimi/commands/delivery.py +++ b/dokimi/dokimi/commands/delivery.py @@ -12,7 +12,7 @@ from dokimi.llm import ANSWER_PROVIDERS from dokimi.harnesses.delivery import run from dokimi.report.delivery import render -from dokimi.utils import InputError +from dokimi.files import InputError def _cost_summary(observations: list[dict]) -> dict: diff --git a/dokimi/dokimi/commands/eval_coverage.py b/dokimi/dokimi/commands/eval_coverage.py index cb9a860436..20db4c37ba 100644 --- a/dokimi/dokimi/commands/eval_coverage.py +++ b/dokimi/dokimi/commands/eval_coverage.py @@ -10,7 +10,7 @@ from pathlib import Path from dokimi.exit_codes import EXIT_FAILURE, EXIT_USAGE -from dokimi.utils import InputError +from dokimi.files import InputError METRICS = ("weighted", "core_rare_critical", "rare_critical") diff --git a/dokimi/dokimi/commands/eval_graph.py b/dokimi/dokimi/commands/eval_graph.py index d5af602c90..c9f44ad770 100644 --- a/dokimi/dokimi/commands/eval_graph.py +++ b/dokimi/dokimi/commands/eval_graph.py @@ -21,7 +21,7 @@ from typing import TYPE_CHECKING, NoReturn from dokimi.exit_codes import EXIT_FAILURE -from dokimi.utils import InputError +from dokimi.files import InputError if TYPE_CHECKING: from dokimi.novelty.client import LLMClient diff --git a/dokimi/dokimi/commands/evaluate.py b/dokimi/dokimi/commands/evaluate.py index cc2e592916..3a274d2b0a 100644 --- a/dokimi/dokimi/commands/evaluate.py +++ b/dokimi/dokimi/commands/evaluate.py @@ -27,7 +27,8 @@ from dokimi import cli_flags 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.files import InputError +from dokimi.model_names import warn_judge_independence, warn_recorded_self_judge from dokimi.commands._shared import require_ragas, run_ragas_eval diff --git a/dokimi/dokimi/commands/explore.py b/dokimi/dokimi/commands/explore.py index 711c678876..4551b588f9 100644 --- a/dokimi/dokimi/commands/explore.py +++ b/dokimi/dokimi/commands/explore.py @@ -10,7 +10,7 @@ from typing import NoReturn from dokimi import cli_flags -from dokimi.utils import InputError +from dokimi.files import InputError _TASKS_ROOT_HELP = ( "Directory of exploration task YAML files (default: data/explore_tasks of a " diff --git a/dokimi/dokimi/commands/headroom.py b/dokimi/dokimi/commands/headroom.py index 46e814e218..b416957688 100644 --- a/dokimi/dokimi/commands/headroom.py +++ b/dokimi/dokimi/commands/headroom.py @@ -23,7 +23,7 @@ from dokimi.artifacts import ENVELOPE_KEYS from dokimi.commands._output import exit_on_unwritable from dokimi.eval.judge_context import PROTOCOL_MIXED -from dokimi.utils import InputError +from dokimi.files import InputError def _read_json(path) -> Any: diff --git a/dokimi/dokimi/commands/ingest.py b/dokimi/dokimi/commands/ingest.py index 81d92e2242..a9a2b092bf 100644 --- a/dokimi/dokimi/commands/ingest.py +++ b/dokimi/dokimi/commands/ingest.py @@ -8,7 +8,7 @@ import argparse import sys from pathlib import Path -from dokimi.utils import InputError +from dokimi.files import InputError def cmd_ingest_docling(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/inputs.py b/dokimi/dokimi/commands/inputs.py index 119ba4b71a..6cb5fe732d 100644 --- a/dokimi/dokimi/commands/inputs.py +++ b/dokimi/dokimi/commands/inputs.py @@ -6,7 +6,7 @@ from __future__ import annotations from pathlib import Path -from dokimi.utils import InputError, refuse_device +from dokimi.files import InputError, refuse_device def read_text_or_exit(path: str | None, flag: str) -> str | None: diff --git a/dokimi/dokimi/commands/judge_reliability.py b/dokimi/dokimi/commands/judge_reliability.py index fc0dd19b6b..964e77f85a 100644 --- a/dokimi/dokimi/commands/judge_reliability.py +++ b/dokimi/dokimi/commands/judge_reliability.py @@ -20,7 +20,8 @@ ) from dokimi.eval.judge import JUDGE_PROVIDERS from dokimi.eval.judge_validity import DEFAULT_MIN_ACCURACY -from dokimi.utils import InputError, read_json_input, warn_recorded_self_judge +from dokimi.files import InputError, read_json_input +from dokimi.model_names import 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 @@ -329,8 +330,7 @@ def score(library, question, answer, ground_truth, context): library = args.product or (data.get("library_name") if isinstance(data, dict) else None) or "the library" report = CrossJudgeReport(baseline_arm=baseline, require_validated=args.require_validated) from dokimi.eval.judge_context import JUDGE_CONTEXT_BASELINE, SOURCE_STORED, JudgeContextStore - from dokimi.records import ASK, outcome_of - from dokimi.utils import question_id + from dokimi.records import ASK, outcome_of, question_id # What the arms run's judge saw, when the file keeps it (judge_materials). Built # once and only for --judge: it is the store the gate checks and the judge reads. diff --git a/dokimi/dokimi/commands/leak.py b/dokimi/dokimi/commands/leak.py index 6fb03b23b2..c70bf3f4ce 100644 --- a/dokimi/dokimi/commands/leak.py +++ b/dokimi/dokimi/commands/leak.py @@ -33,7 +33,7 @@ from dokimi.cli_types import positive_fraction, positive_int from dokimi.digest_entries import listed_entries from dokimi.exit_codes import EXIT_INCONCLUSIVE -from dokimi.utils import InputError +from dokimi.files import InputError def _same_file(a: str, b: str) -> bool: diff --git a/dokimi/dokimi/commands/library.py b/dokimi/dokimi/commands/library.py index 38223267bb..7535b9bee9 100644 --- a/dokimi/dokimi/commands/library.py +++ b/dokimi/dokimi/commands/library.py @@ -11,7 +11,7 @@ from __future__ import annotations import argparse -from dokimi.utils import InputError +from dokimi.files import InputError def _load_custom(cls, flag: str, value): diff --git a/dokimi/dokimi/commands/llms_txt.py b/dokimi/dokimi/commands/llms_txt.py index c4f5f80e15..846867c0b8 100644 --- a/dokimi/dokimi/commands/llms_txt.py +++ b/dokimi/dokimi/commands/llms_txt.py @@ -14,7 +14,7 @@ from pathlib import Path from dokimi import cli_flags, llms_txt -from dokimi.utils import InputError +from dokimi.files import InputError def resolve(path: str) -> Path: diff --git a/dokimi/dokimi/commands/memory.py b/dokimi/dokimi/commands/memory.py index 7607f2178d..a4cbfddac5 100644 --- a/dokimi/dokimi/commands/memory.py +++ b/dokimi/dokimi/commands/memory.py @@ -8,7 +8,7 @@ import argparse import sys -from dokimi.utils import InputError +from dokimi.files import InputError def cmd_memory_lint(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/novelty.py b/dokimi/dokimi/commands/novelty.py index 555b17b4ed..bfaf67f814 100644 --- a/dokimi/dokimi/commands/novelty.py +++ b/dokimi/dokimi/commands/novelty.py @@ -20,7 +20,7 @@ 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 +from dokimi.files import InputError from dokimi.commands.novelty_flags import arms_from_spec, bundle_from_args, settings_from_args diff --git a/dokimi/dokimi/commands/novelty_atoms_file.py b/dokimi/dokimi/commands/novelty_atoms_file.py index e3936f5b8b..f42a527c17 100644 --- a/dokimi/dokimi/commands/novelty_atoms_file.py +++ b/dokimi/dokimi/commands/novelty_atoms_file.py @@ -9,7 +9,7 @@ import argparse import sys -from dokimi.utils import InputError +from dokimi.files import InputError def warn_unread(spans: list, consequence: str) -> None: @@ -203,7 +203,7 @@ def score_candidates(args: argparse.Namespace, spans: list, atoms: list, scored: def warn_answer_key(saved: dict, answerer, judge) -> None: """Warn when the saved answer key was written by the model under measurement, or by the judge's model or family.""" from dokimi.novelty.client import _REMEDY_PROBE, warn_extractor_judge - from dokimi.utils import same_model + from dokimi.model_names import same_model extractor = saved.get("extractor") if not isinstance(extractor, str): diff --git a/dokimi/dokimi/commands/novelty_budget.py b/dokimi/dokimi/commands/novelty_budget.py index 43bca34e3b..e2ae2a8a34 100644 --- a/dokimi/dokimi/commands/novelty_budget.py +++ b/dokimi/dokimi/commands/novelty_budget.py @@ -209,7 +209,7 @@ def run_estimate(args: argparse.Namespace, settings, text: str, estimate_usd) -> from dokimi.novelty import cost from dokimi.novelty.measure import parse_arms from dokimi.novelty.spans import segment - from dokimi.utils import InputError + from dokimi.files import InputError try: arms = parse_arms(args.arms) diff --git a/dokimi/dokimi/commands/novelty_flags.py b/dokimi/dokimi/commands/novelty_flags.py index af3b47f034..7f1d6fc9c5 100644 --- a/dokimi/dokimi/commands/novelty_flags.py +++ b/dokimi/dokimi/commands/novelty_flags.py @@ -22,7 +22,7 @@ DEFAULT_JUDGE_PROVIDER, ) from dokimi.llm import ANSWER_PROVIDERS as PROVIDERS -from dokimi.utils import InputError +from dokimi.files import InputError if TYPE_CHECKING: from dokimi.novelty.tiers import RunSettings diff --git a/dokimi/dokimi/commands/novelty_ground.py b/dokimi/dokimi/commands/novelty_ground.py index f24089a4da..28f1e7d33a 100644 --- a/dokimi/dokimi/commands/novelty_ground.py +++ b/dokimi/dokimi/commands/novelty_ground.py @@ -9,7 +9,7 @@ import sys from pathlib import Path -from dokimi.utils import InputError +from dokimi.files import InputError def _refuse_bad_sources(tools: list[str], headers: list[str], libraries: list[str], diff --git a/dokimi/dokimi/commands/novelty_retest.py b/dokimi/dokimi/commands/novelty_retest.py index 9839c961c9..755cbe7dd1 100644 --- a/dokimi/dokimi/commands/novelty_retest.py +++ b/dokimi/dokimi/commands/novelty_retest.py @@ -9,7 +9,7 @@ from pathlib import Path from dokimi.artifacts import save_artifact -from dokimi.utils import InputError +from dokimi.files import InputError def cmd_novelty_retest(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/novelty_routing.py b/dokimi/dokimi/commands/novelty_routing.py index 63b4e14544..57b2758b76 100644 --- a/dokimi/dokimi/commands/novelty_routing.py +++ b/dokimi/dokimi/commands/novelty_routing.py @@ -35,7 +35,7 @@ stop_if_partial, warn_blind_skills, ) -from dokimi.utils import InputError +from dokimi.files import InputError def _cmd_routing_all_vs_all(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/novelty_routing_inputs.py b/dokimi/dokimi/commands/novelty_routing_inputs.py index 2b66e17297..18d417d596 100644 --- a/dokimi/dokimi/commands/novelty_routing_inputs.py +++ b/dokimi/dokimi/commands/novelty_routing_inputs.py @@ -12,7 +12,7 @@ from pathlib import Path from typing import TYPE_CHECKING -from dokimi.utils import InputError, is_symlink_loop +from dokimi.files import InputError, is_symlink_loop from dokimi.write_probe import can_write if TYPE_CHECKING: diff --git a/dokimi/dokimi/commands/novelty_routing_report.py b/dokimi/dokimi/commands/novelty_routing_report.py index f4ad0f07a6..9c1c789113 100644 --- a/dokimi/dokimi/commands/novelty_routing_report.py +++ b/dokimi/dokimi/commands/novelty_routing_report.py @@ -21,7 +21,7 @@ from typing import TYPE_CHECKING, NoReturn from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE -from dokimi.utils import InputError +from dokimi.files import InputError if TYPE_CHECKING: from collections.abc import Callable, Iterator diff --git a/dokimi/dokimi/commands/novelty_run.py b/dokimi/dokimi/commands/novelty_run.py index 4c3d511d44..d8090fd908 100644 --- a/dokimi/dokimi/commands/novelty_run.py +++ b/dokimi/dokimi/commands/novelty_run.py @@ -121,7 +121,7 @@ def add_panel_args(parser: argparse.ArgumentParser) -> None: def panel_clients(args: argparse.Namespace, make_client) -> tuple: """Clients for the judges after the first ``--judge`` (the first is the judge client).""" from dokimi.novelty.cost import judge_refs - from dokimi.utils import InputError + from dokimi.files import InputError try: refs = judge_refs(args) diff --git a/dokimi/dokimi/commands/novelty_view_inputs.py b/dokimi/dokimi/commands/novelty_view_inputs.py index 1b9abb4d94..2f2080c229 100644 --- a/dokimi/dokimi/commands/novelty_view_inputs.py +++ b/dokimi/dokimi/commands/novelty_view_inputs.py @@ -7,7 +7,7 @@ from pathlib import Path -from dokimi.utils import InputError +from dokimi.files import InputError def load_view_inputs(novelty_path: str, atoms_path: str): diff --git a/dokimi/dokimi/commands/opportunities.py b/dokimi/dokimi/commands/opportunities.py index 98cda8f9f5..890797ee5f 100644 --- a/dokimi/dokimi/commands/opportunities.py +++ b/dokimi/dokimi/commands/opportunities.py @@ -18,7 +18,7 @@ from dokimi import cli_flags, llms_txt, opportunities from dokimi.artifacts import schema_errors from dokimi.commands._output import write_report_text -from dokimi.utils import InputError +from dokimi.files import InputError def _looks_like_json(path: str, text: str) -> bool: diff --git a/dokimi/dokimi/commands/orchestrate.py b/dokimi/dokimi/commands/orchestrate.py index 32f1bda30e..487acf9b57 100644 --- a/dokimi/dokimi/commands/orchestrate.py +++ b/dokimi/dokimi/commands/orchestrate.py @@ -14,8 +14,8 @@ from dokimi.eval.judge_sampling import check_judge_sampling from dokimi.llm import CALLER_CHOICES from dokimi.llm_cli import SamplingError -from dokimi.utils import check_bedrock_model -from dokimi.utils import warn_judge_independence as _warn_judge_independence +from dokimi.model_names import check_bedrock_model +from dokimi.model_names import warn_judge_independence as _warn_judge_independence from dokimi.eval.judge import JUDGE_PROVIDERS from dokimi.defaults import ( DEFAULT_ANSWER_MODEL, @@ -24,7 +24,7 @@ JUDGE_MODEL_FOR_PROVIDER, JUDGE_MODEL_HELP, ) -from dokimi.utils import InputError +from dokimi.files import InputError def cmd_evaluate(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/personas.py b/dokimi/dokimi/commands/personas.py index b65981f0e5..3c6fe6768c 100644 --- a/dokimi/dokimi/commands/personas.py +++ b/dokimi/dokimi/commands/personas.py @@ -18,7 +18,7 @@ from dokimi.exit_codes import EXIT_INCONCLUSIVE from dokimi.personas.analyzer import PersonaAnalyzer from dokimi.personas.generator import PersonaGenerator, check_can_generate, estimate_generation -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input def _usd_text(usd: float) -> str: diff --git a/dokimi/dokimi/commands/questions.py b/dokimi/dokimi/commands/questions.py index 1c318e3ad8..e387fd8f92 100644 --- a/dokimi/dokimi/commands/questions.py +++ b/dokimi/dokimi/commands/questions.py @@ -16,7 +16,9 @@ from dokimi.llm import ANSWER_PROVIDERS, CALLER_CHOICES from dokimi.commands._output import exit_on_rejected, exit_on_unwritable from dokimi.defaults import DEFAULT_GENERATOR_MODEL, DEFAULT_GENERATOR_PROVIDER -from dokimi.utils import InputError, key_bytes, read_json_input, warn_recorded_self_judge +from dokimi.files import InputError, read_json_input +from dokimi.digest import key_bytes +from dokimi.model_names import warn_recorded_self_judge def _load_questions_json(path: str): diff --git a/dokimi/dokimi/commands/redteam.py b/dokimi/dokimi/commands/redteam.py index 5917554fed..101a4141fd 100644 --- a/dokimi/dokimi/commands/redteam.py +++ b/dokimi/dokimi/commands/redteam.py @@ -15,7 +15,7 @@ import argparse import sys from dokimi.exit_codes import EXIT_INCONCLUSIVE -from dokimi.utils import InputError +from dokimi.files import InputError def _ask(args: argparse.Namespace): diff --git a/dokimi/dokimi/commands/repair_receipt.py b/dokimi/dokimi/commands/repair_receipt.py index 17b05edaf2..fe5b42f92e 100644 --- a/dokimi/dokimi/commands/repair_receipt.py +++ b/dokimi/dokimi/commands/repair_receipt.py @@ -9,7 +9,7 @@ import json from pathlib import Path -from dokimi.utils import InputError +from dokimi.files import InputError def add_repair_receipt(catalog_sub) -> None: diff --git a/dokimi/dokimi/commands/repo.py b/dokimi/dokimi/commands/repo.py index aadc54a5cf..8d0dd4acd2 100644 --- a/dokimi/dokimi/commands/repo.py +++ b/dokimi/dokimi/commands/repo.py @@ -20,7 +20,7 @@ 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 +from dokimi.files import InputError, read_json_input def _open_tree(source: RepoSource, args: argparse.Namespace): diff --git a/dokimi/dokimi/commands/repo_hits.py b/dokimi/dokimi/commands/repo_hits.py index 5eb5bef27d..01c44c3d8c 100644 --- a/dokimi/dokimi/commands/repo_hits.py +++ b/dokimi/dokimi/commands/repo_hits.py @@ -17,7 +17,7 @@ from typing import Any, Callable, NoReturn from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE, EXIT_USAGE -from dokimi.utils import InputError +from dokimi.files import InputError from ._output import exit_on_unwritable from dokimi.commands._shared import judge_ref diff --git a/dokimi/dokimi/commands/repo_reach.py b/dokimi/dokimi/commands/repo_reach.py index 0398e121a4..706d65c3ea 100644 --- a/dokimi/dokimi/commands/repo_reach.py +++ b/dokimi/dokimi/commands/repo_reach.py @@ -18,7 +18,7 @@ from dokimi import cli_flags from dokimi.exit_codes import EXIT_USAGE -from dokimi.utils import InputError +from dokimi.files import InputError # The probe's flags, unset by default: --from refuses any of them given, even at its default value. _PROBE_ONLY = {"only": None, "salt": None, "work_dir": None, "keep": False, "bin": None, "dry_run": False, diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 7b82d706bc..c7f90d909f 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -25,8 +25,8 @@ from dokimi.exit_codes import EXIT_INCONCLUSIVE, EXIT_INFRA from dokimi.repos.harness_profile import DELEGATION_MODES from dokimi.repos.source import SourceArgumentError, tree_path -from dokimi.utils import tree_digest -from dokimi.utils import InputError +from dokimi.digest import tree_digest +from dokimi.files import InputError from dokimi.commands._shared import run_errors diff --git a/dokimi/dokimi/commands/repo_scan.py b/dokimi/dokimi/commands/repo_scan.py index 172ddef785..e59cb007e5 100644 --- a/dokimi/dokimi/commands/repo_scan.py +++ b/dokimi/dokimi/commands/repo_scan.py @@ -12,7 +12,7 @@ import re import sys -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input def loaded_with_default(tree, manifest) -> tuple[tuple[str, ...], tuple[str, ...]]: diff --git a/dokimi/dokimi/commands/repo_security.py b/dokimi/dokimi/commands/repo_security.py index 037635ffc9..8e808518f6 100644 --- a/dokimi/dokimi/commands/repo_security.py +++ b/dokimi/dokimi/commands/repo_security.py @@ -11,7 +11,7 @@ from typing import Any, NoReturn from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE, EXIT_INVALID -from dokimi.utils import InputError +from dokimi.files import InputError #: Shorter canaries match by chance, and the report keeps the last 4 characters of each. MIN_CANARY = 12 diff --git a/dokimi/dokimi/commands/repo_skill_reach.py b/dokimi/dokimi/commands/repo_skill_reach.py index 7b208fea23..7ce3504f31 100644 --- a/dokimi/dokimi/commands/repo_skill_reach.py +++ b/dokimi/dokimi/commands/repo_skill_reach.py @@ -13,7 +13,7 @@ from pathlib import Path from dokimi import cli_flags -from dokimi.utils import InputError +from dokimi.files import InputError DEFAULT_BUDGET = 0.10 # USD per scenario, for a harness whose invoke passes {budget} diff --git a/dokimi/dokimi/commands/report.py b/dokimi/dokimi/commands/report.py index 9bd6a27179..a947860bcf 100644 --- a/dokimi/dokimi/commands/report.py +++ b/dokimi/dokimi/commands/report.py @@ -11,7 +11,7 @@ from dokimi import cli_flags from dokimi.commands._output import exit_on_rejected from dokimi.exit_codes import EXIT_USAGE -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input def _write_combined_report(args, regular_runs, golden_runs, run_ids, warnings) -> None: diff --git a/dokimi/dokimi/commands/routing_compare.py b/dokimi/dokimi/commands/routing_compare.py index bbf6895082..c0b49460e6 100644 --- a/dokimi/dokimi/commands/routing_compare.py +++ b/dokimi/dokimi/commands/routing_compare.py @@ -9,7 +9,7 @@ import json from pathlib import Path -from dokimi.utils import InputError +from dokimi.files import InputError #: How many changed picks the console lists; the whole list is in ``--out``. SHOWN_CHANGES = 20 diff --git a/dokimi/dokimi/commands/run.py b/dokimi/dokimi/commands/run.py index 7a4f9e7965..6d468d3a8c 100644 --- a/dokimi/dokimi/commands/run.py +++ b/dokimi/dokimi/commands/run.py @@ -21,7 +21,7 @@ from dokimi.runner.compare import CompareInputError, compare_snapshots from dokimi.runner.run import DocLoadError, load_benchmark_spec, run_benchmark, save_snapshot from dokimi.runner.spec import DocSelectionError -from dokimi.utils import InputError +from dokimi.files import InputError logger = logging.getLogger(__name__) diff --git a/dokimi/dokimi/commands/runs.py b/dokimi/dokimi/commands/runs.py index 5b7628cb28..68eeb9ae67 100644 --- a/dokimi/dokimi/commands/runs.py +++ b/dokimi/dokimi/commands/runs.py @@ -36,7 +36,7 @@ select, ) from dokimi.runs.show import Shown, ShownRun, names_a_run, show_target -from dokimi.utils import InputError +from dokimi.files import InputError def _untimed(artifact: Artifact) -> bool: diff --git a/dokimi/dokimi/commands/runs_bundle.py b/dokimi/dokimi/commands/runs_bundle.py index 8f33a26830..e963e1a954 100644 --- a/dokimi/dokimi/commands/runs_bundle.py +++ b/dokimi/dokimi/commands/runs_bundle.py @@ -17,7 +17,7 @@ from dokimi.exit_codes import EXIT_INFRA, EXIT_INVALID, EXIT_USAGE from dokimi.runs import baseline, bundle from dokimi.runs.scan import existing_root, plain, runs_root -from dokimi.utils import InputError +from dokimi.files import InputError def _count(n: int, noun: str) -> str: diff --git a/dokimi/dokimi/commands/skill_coverage.py b/dokimi/dokimi/commands/skill_coverage.py index fdd6997320..1916e3bc33 100644 --- a/dokimi/dokimi/commands/skill_coverage.py +++ b/dokimi/dokimi/commands/skill_coverage.py @@ -22,7 +22,7 @@ from dokimi import cli_flags from dokimi.cli_types import positive_usd from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE -from dokimi.utils import InputError +from dokimi.files import InputError def _model_ref(value: str) -> tuple[str, str]: from dokimi.eval.judge import JUDGE_PROVIDERS diff --git a/dokimi/dokimi/commands/skill_sensitivity.py b/dokimi/dokimi/commands/skill_sensitivity.py index fd0d18189b..25646582e0 100644 --- a/dokimi/dokimi/commands/skill_sensitivity.py +++ b/dokimi/dokimi/commands/skill_sensitivity.py @@ -20,7 +20,7 @@ save_result, stop_if_partial, ) -from dokimi.utils import InputError +from dokimi.files import InputError def cmd_skill_sensitivity(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/subjects.py b/dokimi/dokimi/commands/subjects.py index d806a322c6..747c4e2f94 100644 --- a/dokimi/dokimi/commands/subjects.py +++ b/dokimi/dokimi/commands/subjects.py @@ -24,7 +24,7 @@ JUDGE_MODEL_HELP, ) from dokimi.judge_rule import apply_default_judge, follow_answerer_cli, refuse_judge_model -from dokimi.utils import InputError +from dokimi.files import InputError # The work's task_runs artifact and its report, in --work-output-dir (else /work). TASK_RUNS_FILE = "task-runs.json" diff --git a/dokimi/dokimi/commands/tasks.py b/dokimi/dokimi/commands/tasks.py index 62ab18318a..124aa00c52 100644 --- a/dokimi/dokimi/commands/tasks.py +++ b/dokimi/dokimi/commands/tasks.py @@ -12,7 +12,7 @@ from dokimi import cli_flags from dokimi.commands.explore import list_localization_tasks -from dokimi.utils import InputError +from dokimi.files import InputError _TASKS_ROOT_HELP = ( "Directory holding one sub-directory per task (each with task.toml or task.md). " diff --git a/dokimi/dokimi/commands/tasks_generate.py b/dokimi/dokimi/commands/tasks_generate.py index afc4f88ccf..7a2cfa5117 100644 --- a/dokimi/dokimi/commands/tasks_generate.py +++ b/dokimi/dokimi/commands/tasks_generate.py @@ -19,7 +19,7 @@ from dokimi import cli_flags from dokimi.cli_types import non_negative_int -from dokimi.utils import InputError +from dokimi.files import InputError if TYPE_CHECKING: from dokimi.repos.graph_tasks import Plan diff --git a/dokimi/dokimi/commands/tools.py b/dokimi/dokimi/commands/tools.py index 72b5402a5f..43ba1b0aa4 100644 --- a/dokimi/dokimi/commands/tools.py +++ b/dokimi/dokimi/commands/tools.py @@ -19,7 +19,7 @@ from dokimi.cli_types import positive_usd from dokimi.defaults import DEFAULT_ANSWER_PROVIDER from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE, EXIT_USAGE -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input PROVIDERS = list(API_PROVIDERS) # tool calling: no CLI backend diff --git a/dokimi/dokimi/context/consistency.py b/dokimi/dokimi/context/consistency.py index aec7d37cce..e6a72d8d0e 100644 --- a/dokimi/dokimi/context/consistency.py +++ b/dokimi/dokimi/context/consistency.py @@ -59,7 +59,7 @@ from dokimi.eval.stats import _mean as stats_mean from dokimi.eval.stats import _pow2_scale as pow2_scale from dokimi.eval.stats import _sample_sd as sample_sd -from dokimi.utils import InputError, refuse_device +from dokimi.files import InputError, refuse_device #: How a write tool writes its file: "replace" the whole file, or "modify" what it holds. _TOOL_WRITES = {"Write": "replace", "Edit": "modify", "MultiEdit": "modify", "NotebookEdit": "modify"} diff --git a/dokimi/dokimi/context/contract.py b/dokimi/dokimi/context/contract.py index a86f13d8bb..020dbf1963 100644 --- a/dokimi/dokimi/context/contract.py +++ b/dokimi/dokimi/context/contract.py @@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Any from dokimi.context import shell -from dokimi.utils import refuse_device +from dokimi.files import refuse_device if TYPE_CHECKING: from dokimi.context.consistency import Event, Run diff --git a/dokimi/dokimi/context/session_log.py b/dokimi/dokimi/context/session_log.py index 64427f40ea..ff98ebeb6f 100644 --- a/dokimi/dokimi/context/session_log.py +++ b/dokimi/dokimi/context/session_log.py @@ -26,7 +26,7 @@ from typing import Any from dokimi.text_spans import replace_pairs -from dokimi.utils import InputError, refuse_device +from dokimi.files import InputError, refuse_device # Input keys whose value is file content or a model-facing brief, not the agent's intent: left out of an event's text. _CONTENT_KEYS = frozenset({"old_string", "new_string", "content", "new_source", "edits", diff --git a/dokimi/dokimi/context/trace.py b/dokimi/dokimi/context/trace.py index 09a90aa488..aa15becbf0 100644 --- a/dokimi/dokimi/context/trace.py +++ b/dokimi/dokimi/context/trace.py @@ -38,7 +38,7 @@ from pathlib import Path from typing import Any -from dokimi.utils import InputError, refuse_device +from dokimi.files import InputError, refuse_device # Tools whose call can change what a later identical call returns; one ends every earlier repeat. MUTATING = frozenset({"Bash", "Edit", "MultiEdit", "NotebookEdit", "Write"}) diff --git a/dokimi/dokimi/digest.py b/dokimi/dokimi/digest.py new file mode 100644 index 0000000000..39bea112eb --- /dev/null +++ b/dokimi/dokimi/digest.py @@ -0,0 +1,464 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Content digests of text, single files and whole trees, read through git where a repository holds them. + +A tree digest takes each tracked file's blob id from git (a :class:`GitDigestTree` snapshot of the work tree's +index and ignore rules), so a CRLF checkout under core.autocrlf digests as its LF twin does. A link digests +by its text. +""" + +import errno +import hashlib +import os +import stat +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Callable, Iterable, Mapping + +from dokimi.process_io import disk_path_text, exact_path_text, flagged, worktree_changed + +if TYPE_CHECKING: + from dokimi.process import Env + + +def digest_text(text: str) -> str: + """Content-digest a prompt or other text blob. + + Uses the ``sha256:`` prefix convention the plugin-set and subject + digests already use, so provenance fields read the same way across artifacts. + The digest itself is the full 64-char hex: the plugin-set digest is truncated + to 32, so the two are comparable in shape but never equal for the same input. + + Args: + text: The text to digest. + + Returns: + ``"sha256:"`` followed by the hex digest of the UTF-8 encoding. + """ + import hashlib + + return "sha256:" + hashlib.sha256((text or "").encode("utf-8", errors="surrogatepass")).hexdigest() + + +def key_bytes(text: str) -> bytes: + """Bytes a cache key hashes: ``surrogateescape``; NUL-led text gets ``\\0e``; a surrogate it cannot map (U+D800..U+DC7F, U+DD00..U+DFFF) tags the text ``\\0sp`` and uses ``surrogatepass``.""" + try: + return b"\0e" * text.startswith("\0") + text.encode("utf-8", "surrogateescape") + except UnicodeEncodeError: # a JSON `\ud800` has no escape + return b"\0sp" + text.encode("utf-8", "surrogatepass") + + +def _plain_path(text: str) -> str: + r"""A Windows absolute path without its extended-length prefix. os.readlink gives an absolute link target as + \\?\C:\... (or \\?\UNC\...), while the anchors are plain: the two read as different drives. + Any other text is returned unchanged.""" + if text.startswith("\\\\?\\UNC\\"): + return "\\\\" + text[len("\\\\?\\UNC\\"):] + if text.startswith("\\\\?\\"): + return text[len("\\\\?\\"):] + return text + + +def _settled(target: str) -> str: + """An absolute ``target`` with each ``..`` that follows a real directory folded into it, as the kernel reads the + path. A ``..`` that follows a link is kept: the kernel resolves it from the link's target, which a fold would miss.""" + anchor, *names = Path(target).parts + kept: list[str] = [] + for name in names: + if name == "..": + top = kept[-1] if kept else None + here = os.path.join(anchor, *kept) + if top not in (None, "..") and os.path.isdir(here) and not os.path.islink(here): + kept.pop() + continue + kept.append(name) + return os.path.join(anchor, *kept) + + +def _posix_separators(text: str, sep: str = os.sep) -> str: + """``text`` with its native separator ``sep`` written as ``/``, so a relative link target digests the same on Windows + (where os.readlink gives backslashes) as on POSIX. On POSIX a backslash is part of a name and is kept.""" + return text if sep == "/" else text.replace(sep, "/") + + +@dataclass(frozen=True) +class GitDigestTree: + """A work tree a digest reads through git: its top (a real path), the walk's base (top-relative, "" for the top), the + untracked, ignored paths git leaves out (top-relative, a directory by its name as ``ls-files --directory`` gives it), + and the blob ids of the tracked files git finds unchanged (their index entries). A tree is a snapshot: build one per + digest. ``indexed`` is left out of the hash only: a mapping cannot hash, and equality must see the snapshot. + ``tracked`` holds every path the top's index holds and each directory above one: git stores those, so a nested + repository's rules never leave them out. ``nested`` is filled as a walk meets directories: for one holding ``.git`` + (a nested repository or submodule), the paths its own git ignores, relative to it; None for any other. It is a + cache, so equality and the hash leave it out.""" + + top: Path + base: str + ignored: frozenset[str] + indexed: Mapping[str, str] = field(hash=False) + tracked: frozenset[str] = frozenset() + nested: dict[str, frozenset[str] | None] = field(default_factory=dict, hash=False, compare=False, repr=False) + + def top_rel(self, path: Path) -> str | None: + """``path`` relative to the top, as POSIX, its own link (if it is one) not followed; None outside the tree.""" + real = Path(os.path.realpath(path.parent)) / path.name + try: + return real.relative_to(self.top).as_posix() + except ValueError: + return None + + def skipped(self, path: Path) -> bool: + """True for what git leaves out: an ignored path below the base, by the top's rules or (unless the top tracks it) + by those of a nested repository holding it, or anything under a ``.git`` (a nested repository's own). An ignored + directory above the base is not this walk's to apply. OSError when git cannot read such a nested repository.""" + rel = self.top_rel(path) + if rel is None: + return False + parts = rel.split("/") + first = len(self.base.split("/")) + 1 if self.base else 1 + if ".git" in parts or any("/".join(parts[:i]) in self.ignored for i in range(first, len(parts) + 1)): + return True + return rel not in self.tracked and any(self._inner_skips(parts, j, first) for j in range(1, len(parts))) + + def _inner_skips(self, parts: list[str], j: int, first: int) -> bool: + """True when the directory ``parts[:j]`` is a nested repository that ignores ``parts[j:]`` or a directory of it + below the base (``first``: the walk's first own part).""" + inner = self._inner_ignored("/".join(parts[:j])) + if not inner: + return False + return any("/".join(parts[j:i]) in inner for i in range(max(first, j + 1), len(parts) + 1)) + + def _inner_ignored(self, rel: str) -> frozenset[str] | None: + if rel not in self.nested: # read once per nested repository, no git call for a directory without .git + here = self.top / rel + if not os.path.lexists(here / ".git"): + self.nested[rel] = None + elif (why := _not_own_top(here)) is not None: + raise OSError(errno.EIO, f"git cannot read this nested repository: {why}", os.fspath(here)) + elif (inner := _ignored_paths(os.fspath(here))) is not None: + self.nested[rel] = inner + else: # leaving nothing out would hash its ignored files only where git cannot read it + raise OSError(errno.EIO, "git cannot read this nested repository", os.fspath(here)) + return self.nested[rel] + + +def _not_own_top(here: Path) -> str | None: + """Why git does not read ``here`` as its own work tree's top: git's message, or the top it found instead (git skips + a ``.git`` it cannot read as a repository and walks up to the enclosing one). None when it does.""" + from dokimi.process import run + + top = run(["git", "-C", os.fspath(here), "rev-parse", "--show-toplevel"], timeout=60, env=_git_env()) + if not top.ok: + return top.stderr.strip() or f"exit {top.returncode}" + found = os.fsdecode(top.stdout_bytes).removesuffix("\n") # git ends the name with one newline + return None if Path(os.path.realpath(found)) == Path(os.path.realpath(here)) else f"git reads {found} instead" + + +def _git_env() -> "Env": + from dokimi.process import Env + + # GIT_* variables (a hook's GIT_DIR or GIT_INDEX_FILE) would point git at some other repository + return Env.only(allow=[k for k in os.environ if not k.startswith("GIT_")]) + + +def git_tree(base: Path) -> GitDigestTree | None: + """The work tree holding ``base``, with what git leaves out of it. None when ``base`` is in no work tree (or git + cannot say): the digest then hashes the bytes on disk and leaves nothing out.""" + from dokimi.process import run + + try: + top = run(["git", "-C", os.fspath(base), "rev-parse", "--show-toplevel"], timeout=60, env=_git_env()) + if not top.ok: + return None + top_dir = os.fsdecode(top.stdout_bytes).removesuffix("\n") # only git's newline: a name may end in " " or "\r" + ignored = _ignored_paths(top_dir) + except OSError: + return None + if ignored is None: + return None + top_real = Path(os.path.realpath(top_dir)) + try: + base_rel = Path(os.path.realpath(base)).relative_to(top_real).as_posix() + except ValueError: + return None + return GitDigestTree(top_real, "" if base_rel == "." else base_rel, ignored, *_index_blobs(top_dir)) + + +def _ignored_paths(top: str) -> frozenset[str] | None: + """The untracked, ignored paths of the work tree at ``top`` that git would not descend into (a directory by its + name), relative to ``top``; a tracked file is never listed. None if git fails; OSError if it cannot start.""" + from dokimi.process import run + + listed = run(["git", "-C", top, "ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], + timeout=120, env=_git_env(), capture_limit=None) + if not listed.ok: + return None + return frozenset(disk_path_text(name).rstrip("/") for name in listed.stdout_bytes.split(b"\0") if name) + + +def _index_blobs(top: str) -> tuple[dict[str, str], frozenset[str]]: + """The index's blob id for each tracked file that git finds unchanged in the work tree. ``hash-object`` does not read + the index, so it would fold a committed CRLF file under core.autocrlf. Flagged entries (skip-worktree, assume-unchanged) + are left out: git does not look at those files, so their disk content is hashed. Second, every path the index holds + and each directory above one (``GitDigestTree.tracked``). No blob id if any git call fails; no path if ``ls-files`` does.""" + from dokimi.process import run + + env = _git_env() + staged = run(["git", "-C", top, "ls-files", "-s", "-z"], timeout=120, env=env, capture_limit=None) + tags = run(["git", "-C", top, "ls-files", "-v", "-z"], timeout=120, env=env, capture_limit=None) + # --no-optional-locks: status refreshes its view in memory and does not rewrite the index + dirty = run(["git", "-C", top, "--no-optional-locks", "status", "--porcelain=v1", "-z", "-uno"], timeout=120, + env=env, capture_limit=None) + trusted = staged.ok and tags.ok and dirty.ok # a failed ls-files prints no entry, so ``held`` stays empty + changed = worktree_changed(dirty.stdout_bytes) | flagged(tags.stdout_bytes) + out: dict[str, str] = {} + held: set[str] = set() + for entry in staged.stdout_bytes.split(b"\0"): + meta, _, name = entry.partition(b"\t") + fields = meta.split() + if not name: + continue + rel = exact_path_text(name) + if rel is None: # a replaced name would stand for the real file that has it + continue + held.update(rel.rsplit("/", i)[0] for i in range(rel.count("/") + 1)) # the path and each directory above it + if trusted and len(fields) == 3 and fields[2] == b"0" and rel not in changed: + out[rel] = os.fsdecode(fields[1]) + return out, frozenset(held) + + +_ARG_BUDGET = 24_000 # bytes of path arguments per git call: under the smallest command line limit (Windows, 32 KB) + + +def _blob_ids(top: Path, rels: list[str], *, as_args: bool = False) -> list[str] | None: + """``git hash-object`` of each path (relative to ``top``) with the work tree's filters: on stdin in one call, or + with ``as_args`` on the command line in batches under ``_ARG_BUDGET``, for a name ``--stdin-paths`` misreads (it + splits lines, unquotes, drops a CR). A batch that fails fails them all.""" + if not as_args: + return _hash_objects(top, rels, as_args=False) + ids: list[str] = [] + batch: list[str] = [] + size = 0 + for rel in [*rels, None]: + if rel is None or (batch and size + len(os.fsencode(rel)) + 1 > _ARG_BUDGET): + got = _hash_objects(top, batch, as_args=True) + if got is None: + return None + ids += got + batch, size = [], 0 + if rel is not None: + batch.append(rel) + size += len(os.fsencode(rel)) + 1 + return ids + + +def _hash_objects(top: Path, rels: list[str], *, as_args: bool) -> list[str] | None: + from dokimi.process import run + + names = ["--", *rels] if as_args else ["--stdin-paths"] + data = None if as_args else b"".join(os.fsencode(rel) + b"\n" for rel in rels) + try: + done = run(["git", "-C", os.fspath(top), "hash-object", *names], timeout=600, env=_git_env(), + input=data, capture_limit=None) + except OSError: + return None + if not done.ok: # git's own words name the file or filter to fix + why = "timed out" if done.timed_out else done.stderr.strip() or f"exit code {done.returncode}" + raise OSError(errno.EIO, f"git hash-object failed: {why}", os.fspath(top)) + ids = [os.fsdecode(i) for i in done.stdout_bytes.split()] + return ids if len(ids) == len(rels) else None + + +def file_contents(paths: Iterable[Path], tree: GitDigestTree | None) -> dict[Path, bytes]: + """What a digest holds for each file: git's blob id for a file in ``tree`` (the index's when git finds it unchanged, + else ``hash-object``'s with the work tree's filters). Otherwise the sha256 of its bytes: no tree or a file outside + it. A ``hash-object`` that fails raises ``OSError``, as a repository git cannot read does.""" + found = list(dict.fromkeys(paths)) + out = _blob_contents(found, tree) if tree is not None else {} + for path in found: + if path not in out: + out[path] = hashlib.sha256(path.read_bytes()).digest() + return out + + +def _blob_contents(paths: list[Path], tree: GitDigestTree) -> dict[Path, bytes]: + out: dict[Path, bytes] = {} + plain: list[tuple[Path, str]] = [] + odd: list[tuple[Path, str]] = [] # names --stdin-paths misreads: hashed as arguments, so edited reads as committed + for path in paths: + rel = tree.top_rel(path) + if rel is None: + continue + if rel in tree.indexed: + out[path] = bytes.fromhex(tree.indexed[rel]) + else: + (odd if "\n" in rel or rel.startswith('"') or rel.endswith("\r") else plain).append((path, rel)) + for hashed, as_args in ((plain, False), (odd, True)): + ids = _blob_ids(tree.top, [rel for _, rel in hashed], as_args=as_args) if hashed else [] + if ids is None: # a sha256 of the bytes here would move the digest with the host load that failed git + raise OSError(errno.EIO, "git hash-object failed", os.fspath(tree.top)) + out.update({path: bytes.fromhex(blob) for (path, _), blob in zip(hashed, ids, strict=True)}) + return out + + +def file_digest(content: bytes, executable: bool) -> str: + """The digest of one file alone, as :func:`tree_digest` gives a file ``root`` (its path is ``.``).""" + return hashlib.sha256(b"F .\0" + f"{int(executable)}\0".encode() + content).hexdigest() + + +def link_text(link: Path, root: Path) -> str: + """A symlink's target as the digests hold it: as written, except an absolute target inside ``root``, which is + written relative to the link. So a tree digests the same at another checkout path (the link's text is the same). + A ``..`` in such a target is kept as written: after a link the kernel resolves it from the link's target, so + collapsing it lexically would hash two different files alike.""" + target = os.readlink(link) + if not os.path.isabs(target): + return _posix_separators(target) + target = _plain_path(target) + if link == root: # the root is hashed by its target, not walked: kept as written, so a loop through it stays a loop + return target + # the tree may be named by a path with links in it: match the target under the name as given and as resolved + # (a link that is the root itself is not resolved, or its own target would count as inside it) + anchors = [os.fspath(root)] if root.is_symlink() else [os.fspath(root), os.path.realpath(root)] + for anchor in anchors: + # Windows folds case in paths (and drive letters), so the comparison is on the normalized spelling; the target + # keeps its own spelling in the text it returns + key, key_anchor = os.path.normcase(target), os.path.normcase(anchor) + try: + inside = os.path.commonpath([key, key_anchor]) == key_anchor and key.startswith(key_anchor) + except ValueError: # different drives, or a relative path mixed in + continue + if inside: + rest = [part for part in target[len(anchor):].split(os.sep) if part not in ("", ".")] + depth = len(link.relative_to(root).parent.parts) # the link's directory, as the text is read from there + slash = "/" if target.endswith((os.sep, os.sep + ".")) else "" # "x/" and "x/." need a directory + if ".." in rest: + # a target whose ".." leads out of the tree (and does not come back in) is external: hashed as written, + # so two trees whose external targets differ do not digest alike + lexical = os.path.normcase(os.path.normpath(target)) + if lexical != key_anchor and not lexical.startswith(key_anchor.rstrip(os.sep) + os.sep): + return target + # a ".." that leaves the tree and comes back in (tree/../tree/x) is folded, so the name of the checkout's + # directory does not reach the digest; the ".." after a link stays, as the kernel reads it + settled = _settled(target) + key_settled = os.path.normcase(settled) + if key_settled != key_anchor and not key_settled.startswith(key_anchor.rstrip(os.sep) + os.sep): + return target + rest = [part for part in settled[len(anchor):].split(os.sep) if part not in ("", ".")] + return ("/".join([".."] * depth + rest) or ".") + slash # the root itself is "." before the slash + here = os.path.join(anchor, *link.relative_to(root).parent.parts) + return os.path.relpath(os.path.join(anchor, *rest), here).replace(os.sep, "/") + slash + return target # outside the tree: as written + + +def _tracked_modes(base: Path, spec: str) -> dict[str, bool]: + """The executable bit git records (mode 100755) for each file ``spec`` names under ``base``, keyed by the path + relative to ``base``. Empty when git cannot say (no git, or ``base`` is not in a repository).""" + from dokimi.process import Env, run + + # GIT_* variables (a hook's GIT_DIR or GIT_INDEX_FILE) would point git at some other repository's index + env = Env.only(allow=[k for k in os.environ if not k.startswith("GIT_")]) + try: + # literal: the name is a path, not a pattern; no capture limit: a large tree's listing must be read whole + done = run(["git", "--literal-pathspecs", "-C", os.fspath(base), "ls-files", "--stage", "-z", "--", spec], + timeout=60, env=env, capture_limit=None) + except OSError: + return {} + if not done.ok: + return {} + modes: dict[str, bool] = {} + for record in done.stdout_bytes.split(b"\0"): + meta, tab, name = record.partition(b"\t") + key = exact_path_text(name) + if tab and key is not None: # a name Windows cannot decode would take the key of a real file + modes[key] = meta.split()[0] == b"100755" + return modes + + +def _entries(root: Path, skip: tuple[str, ...], *, strict: bool, drop: Callable[[Path], bool] | None = None) -> list[Path]: + """Every entry under ``root``, directories included, a symlink as itself and never descended into. Entries under + a ``skip`` prefix, and those ``drop`` names, are not read. Non-strict is ``rglob``, which skips a directory it cannot + read (and the files behind it); strict raises that error, so a digest cannot leave out what it could not read.""" + if not strict: + return [p for p in root.rglob("*") if drop is None or not drop(p)] + found: list[Path] = [] + pending = [root] + while pending: + with os.scandir(pending.pop()) as it: + for entry in it: + path = Path(entry.path) + rel = path.relative_to(root).as_posix() + if any(rel == e or rel.startswith(e + "/") for e in skip) or (drop is not None and drop(path)): + continue + found.append(path) + if entry.is_dir(follow_symlinks=False): + pending.append(path) + return found + + +def tree_digest(root: Path, *, exclude: Iterable[str] = (), strict: bool = False, + tracked: Mapping[str, bool] | None = None, git: GitDigestTree | bool | None = False) -> str: + """sha256 (bare hex) over every path, mode bit and byte under ``root``; a link by its target. + + A file ``root`` digests as itself (its path is ``.``), and so does a symlink ``root`` + (by its target, dangling or not; it is not walked). Entries whose path, relative to + ``root``, equals one of ``exclude`` or sits under it are left out, so a skill's digest can + leave its eval directory out. Output is deterministic: sorted walk, no timestamps. + + The same tree digests the same on every OS: a file's mode bit is the one git records (the index, so a + Windows checkout with no exec bit still matches), and an untracked file takes its owner's exec bit + from the disk. A link inside ``root`` with an absolute target is hashed by a relative target (see + ``link_text``); one pointing outside ``root`` is hashed as written. + + ``strict``: a directory under ``root`` that cannot be read raises its OSError (the default skips it silently). + ``tracked``: the executable bits git records, keyed by path relative to ``root`` (to its parent for a file root), + as :func:`_tracked_modes` returns them; None reads them from git. A caller digesting many files reads them once. + ``git``: hash what git stores, not the bytes on disk. A file digests as its blob id (:func:`file_contents`), so a + CRLF checkout with core.autocrlf matches the LF one; what git leaves out (ignored paths, by a nested repository's + own rules too, and a nested ``.git``) is skipped, and so are directories, which git does not store. A ``GitDigestTree`` + is a work tree already read; True reads it from ``root``; None (or no work tree) hashes the bytes on disk and + leaves nothing out. + """ + skip = tuple(e.strip("/") for e in exclude) + # a symlink is never looked through here: its target may be unreadable (or gone), and it digests by its text + is_link = root.is_symlink() + as_file = not is_link and root.is_file() + if isinstance(git, GitDigestTree): + tree: GitDigestTree | None = git + else: + tree = git_tree(root.parent if is_link or as_file else root) if git else None + # sorted by the parts of the relative path, compared as code points: the same order on every OS (Path + # ordering folds case on Windows) + entries = ([root] if is_link or as_file + else sorted(_entries(root, skip, strict=strict, drop=tree.skipped if tree else None), + key=lambda p: p.relative_to(root).parts)) + if tree is not None: + entries = [p for p in entries if p.is_symlink() or not p.is_dir()] + base, spec = (root.parent, root.name) if as_file else (root, ".") + modes: Mapping[str, bool] + if tracked is None: + modes = _tracked_modes(base, spec) if any(not p.is_symlink() and p.is_file() for p in entries) else {} + else: # the caller read the index already: keyed as below, by the path relative to ``base`` + modes = tracked + holds = file_contents([p for p in entries if not p.is_symlink() and p.is_file()], tree) + h = hashlib.sha256() + for path in entries: + rel = "." if path == root else path.relative_to(root).as_posix() + if any(rel == e or rel.startswith(e + "/") for e in skip): + continue + # names and link targets are bytes on POSIX and may hold undecodable bytes: encode them as the OS does + name = os.fsencode(rel) + if path.is_symlink(): + h.update(b"L " + name + b"\0" + os.fsencode(link_text(path, root)) + b"\0") + elif path.is_file(): + key = path.relative_to(base).as_posix() + if key in modes: + executable = modes[key] + else: + executable = bool(os.lstat(path).st_mode & stat.S_IXUSR) + h.update(b"F " + name + f"\0{int(executable)}\0".encode()) + h.update(holds[path]) + elif path.is_dir(): + h.update(b"D " + name + b"\0") + return h.hexdigest() diff --git a/dokimi/dokimi/digest_entries.py b/dokimi/dokimi/digest_entries.py index d7cb020203..b5b4fddb92 100644 --- a/dokimi/dokimi/digest_entries.py +++ b/dokimi/dokimi/digest_entries.py @@ -13,7 +13,7 @@ from pathlib import Path from typing import Callable, Mapping -from dokimi.utils import _entries, _tracked_modes, file_digest, link_text +from dokimi.digest import _entries, _tracked_modes, file_digest, link_text def listed_entries(root: Path, drop: Callable[[Path], bool] | None = None) -> list[Path]: diff --git a/dokimi/dokimi/eval/answerer.py b/dokimi/dokimi/eval/answerer.py index 2bb9922499..941f71cf3e 100644 --- a/dokimi/dokimi/eval/answerer.py +++ b/dokimi/dokimi/eval/answerer.py @@ -13,7 +13,7 @@ logger = logging.getLogger(__name__) -from dokimi.utils import question_id +from dokimi.records import question_id from dokimi.artifacts import save_artifact from dokimi.eval.ask_outcome import outcome_fields from dokimi.defaults import ( diff --git a/dokimi/dokimi/eval/arm_runner.py b/dokimi/dokimi/eval/arm_runner.py index 1311738ad2..64f39841ba 100644 --- a/dokimi/dokimi/eval/arm_runner.py +++ b/dokimi/dokimi/eval/arm_runner.py @@ -19,7 +19,7 @@ from typing import Any, Callable, Dict, List, Optional, Sequence from dokimi.caching import is_empty_reply -from dokimi.utils import question_id # re-exported: callers import it from here +from dokimi.records import question_id # re-exported: callers import it from here from dokimi.artifacts import save_artifact from dokimi.llm import llm_call_with_usage from dokimi.defaults import DEFAULT_ANSWER_MODEL, DEFAULT_ANSWER_PROVIDER diff --git a/dokimi/dokimi/eval/arms_adapter.py b/dokimi/dokimi/eval/arms_adapter.py index ef1f2e60b0..f76d0d4cd1 100644 --- a/dokimi/dokimi/eval/arms_adapter.py +++ b/dokimi/dokimi/eval/arms_adapter.py @@ -41,7 +41,7 @@ ASK, BASELINE, CONTEXT, KNOWLEDGE_INTENT, PAIRED_INTENT, Answer, Record, RecordError, Run, arm_scores, knowledge_only, read, record, ) -from dokimi.utils import same_evaluator +from dokimi.model_names import same_evaluator logger = logging.getLogger(__name__) diff --git a/dokimi/dokimi/eval/arms_refusals.py b/dokimi/dokimi/eval/arms_refusals.py index d0a7c799cb..d424e483a2 100644 --- a/dokimi/dokimi/eval/arms_refusals.py +++ b/dokimi/dokimi/eval/arms_refusals.py @@ -11,7 +11,7 @@ from typing import TYPE_CHECKING -from dokimi.utils import InputError +from dokimi.files import InputError if TYPE_CHECKING: from dokimi.eval.arms_run import ArmsRunConfig diff --git a/dokimi/dokimi/eval/arms_run.py b/dokimi/dokimi/eval/arms_run.py index 2481341f87..ed861740a7 100644 --- a/dokimi/dokimi/eval/arms_run.py +++ b/dokimi/dokimi/eval/arms_run.py @@ -32,7 +32,9 @@ from dokimi.eval.question_text import EmptyQuestionError from dokimi.judge_rule import JudgeIsAnswerer, default_judge from dokimi.llm_cli import backend as cli_backend -from dokimi.utils import InputError, check_bedrock_model, question_id, same_model, warn_judge_independence +from dokimi.files import InputError +from dokimi.model_names import check_bedrock_model, same_model, warn_judge_independence +from dokimi.records import question_id if TYPE_CHECKING: from dokimi.eval import Judge, JudgePanel diff --git a/dokimi/dokimi/eval/checklist.py b/dokimi/dokimi/eval/checklist.py index 6864e9703a..07b59f4670 100644 --- a/dokimi/dokimi/eval/checklist.py +++ b/dokimi/dokimi/eval/checklist.py @@ -42,7 +42,7 @@ from dokimi.eval.question_text import require_question_text from dokimi.records import RecordLike, arm_answers, records as as_records from dokimi.eval.stats import mean_ci -from dokimi.utils import question_id +from dokimi.records import question_id logger = logging.getLogger(__name__) diff --git a/dokimi/dokimi/eval/cross_judge.py b/dokimi/dokimi/eval/cross_judge.py index 0a2a46a7d4..2e215f61df 100644 --- a/dokimi/dokimi/eval/cross_judge.py +++ b/dokimi/dokimi/eval/cross_judge.py @@ -66,7 +66,8 @@ from dokimi.records import record as as_record from dokimi.records import records as as_records from dokimi.eval.stats import adjust_pvalues, mean_ci -from dokimi.utils import InputError, digest_text +from dokimi.files import InputError +from dokimi.digest import digest_text logger = logging.getLogger(__name__) diff --git a/dokimi/dokimi/eval/judge_context.py b/dokimi/dokimi/eval/judge_context.py index 86ae2d781b..7a92bc6e63 100644 --- a/dokimi/dokimi/eval/judge_context.py +++ b/dokimi/dokimi/eval/judge_context.py @@ -38,7 +38,9 @@ from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Union from dokimi.records import arm_answers, read -from dokimi.utils import InputError, digest_text, question_id +from dokimi.files import InputError +from dokimi.digest import digest_text +from dokimi.records import question_id logger = logging.getLogger(__name__) diff --git a/dokimi/dokimi/eval/question_text.py b/dokimi/dokimi/eval/question_text.py index bdec0deb06..c04dc58672 100644 --- a/dokimi/dokimi/eval/question_text.py +++ b/dokimi/dokimi/eval/question_text.py @@ -17,7 +17,8 @@ from collections.abc import Mapping from typing import Any, Iterable, Optional -from dokimi.utils import InputError, question_id +from dokimi.files import InputError +from dokimi.records import question_id # answers.v1 writes ``question_text``; ``question``/``text`` are the # question-set spellings, accepted for hand-built inputs. @@ -27,7 +28,7 @@ class EmptyQuestionError(InputError): """A record handed to a judge has no question text. - An :class:`~dokimi.utils.InputError`: the CLI reports it as ``Error: ...`` with + An :class:`~dokimi.files.InputError`: the CLI reports it as ``Error: ...`` with exit 2, the code for bad input (1 is the verdict code of ``--strict`` gates and ``eval judge validate``). """ diff --git a/dokimi/dokimi/eval/session.py b/dokimi/dokimi/eval/session.py index 286fcae543..21ad956df3 100644 --- a/dokimi/dokimi/eval/session.py +++ b/dokimi/dokimi/eval/session.py @@ -22,7 +22,7 @@ from dokimi import caching from dokimi.eval.question_text import question_text_of from dokimi.llm import LLM -from dokimi.utils import question_id +from dokimi.records import question_id from dokimi.metrics.usage import UsageRecord logger = logging.getLogger(__name__) diff --git a/dokimi/dokimi/external/listing.py b/dokimi/dokimi/external/listing.py index 72fe5c84f0..f6ac2a49cf 100644 --- a/dokimi/dokimi/external/listing.py +++ b/dokimi/dokimi/external/listing.py @@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Optional -from dokimi.utils import parse_frontmatter +from dokimi.frontmatter import parse_frontmatter if TYPE_CHECKING: from dokimi.skills.loader import Skill diff --git a/dokimi/dokimi/external/online_checks.py b/dokimi/dokimi/external/online_checks.py index 1ea30c4c16..a24466a818 100644 --- a/dokimi/dokimi/external/online_checks.py +++ b/dokimi/dokimi/external/online_checks.py @@ -34,7 +34,7 @@ from dokimi.external.skill_markdown import outside_fences from dokimi.external.validate import Finding, SkillReview from dokimi.process_io import joined_pairs -from dokimi.utils import InputError +from dokimi.files import InputError if TYPE_CHECKING: from dokimi.skills import Skill diff --git a/dokimi/dokimi/external/trigger_set.py b/dokimi/dokimi/external/trigger_set.py index 8931b8e1e4..a224915ca8 100644 --- a/dokimi/dokimi/external/trigger_set.py +++ b/dokimi/dokimi/external/trigger_set.py @@ -38,7 +38,7 @@ from dataclasses import dataclass, field from typing import Any, Callable, Dict, List, Optional, Sequence, Union -from dokimi.utils import question_id +from dokimi.records import question_id from dokimi.skills import Skill ExpectedSkill = Union[str, List[str], None] diff --git a/dokimi/dokimi/external/upstream.py b/dokimi/dokimi/external/upstream.py index 601f88ad60..5ef7818017 100644 --- a/dokimi/dokimi/external/upstream.py +++ b/dokimi/dokimi/external/upstream.py @@ -36,7 +36,8 @@ from typing import Any, Iterable, Optional, Sequence from dokimi import process -from dokimi.utils import InputError, parse_frontmatter +from dokimi.files import InputError +from dokimi.frontmatter import parse_frontmatter from .catalog_git import _git diff --git a/dokimi/dokimi/external/upstream_findings.py b/dokimi/dokimi/external/upstream_findings.py index 9279e00c5d..a346ec967a 100644 --- a/dokimi/dokimi/external/upstream_findings.py +++ b/dokimi/dokimi/external/upstream_findings.py @@ -19,7 +19,7 @@ from typing import Optional, Sequence -from dokimi.utils import parse_frontmatter +from dokimi.frontmatter import parse_frontmatter from .allowed_tools import RISKY_COMMAND_CODES, grants_unrestricted_bash from .command_checks import skill_md_findings diff --git a/dokimi/dokimi/external/validate.py b/dokimi/dokimi/external/validate.py index c4411020ea..7ac0fc98b1 100644 --- a/dokimi/dokimi/external/validate.py +++ b/dokimi/dokimi/external/validate.py @@ -90,7 +90,7 @@ import yaml from dokimi.skills import Skill -from dokimi.utils import describe_yaml_error, parse_frontmatter_strict +from dokimi.frontmatter import describe_yaml_error, parse_frontmatter_strict from .description_overlap import (NEAR_DUPLICATE_JACCARD, NEAR_DUPLICATE_MIN_SHARED, SIMILAR_JACCARD, _candidate_pairs, _jaccard, _tokens) diff --git a/dokimi/dokimi/files.py b/dokimi/dokimi/files.py new file mode 100644 index 0000000000..ad50214639 --- /dev/null +++ b/dokimi/dokimi/files.py @@ -0,0 +1,91 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Files the CLI reads and walks: :class:`InputError` and the reads that raise it, the device refusal before +a read, the symlink-loop test a walker needs, and the rmtree retry a cleanup needs. +""" + +import errno +import json +import os +import stat +from pathlib import Path +from typing import Any + + +def is_symlink_loop(exc: OSError) -> bool: + """A symlink loop: ``ELOOP``, or on Windows EINVAL with WinError 1921 (ERROR_CANT_RESOLVE_FILENAME).""" + return exc.errno == errno.ELOOP or getattr(exc, "winerror", None) == 1921 + + +def retry_writable(func: Any, path: str, _exc: Any) -> None: + """``shutil.rmtree`` ``onerror`` hook: set the write bit on ``path`` and retry once. + + Windows will not delete a read-only file, and git leaves its object files + read-only. A symlink is left alone, since chmod would follow it out of the + tree. A retry that still fails is ignored; the caller checks what is left. + Only the delete calls are retried: on POSIX ``rmtree`` also reports a failed + ``os.open`` or ``os.scandir`` (an unreadable dir), which ``func(path)`` would + call with the wrong arguments and raise ``TypeError``. + """ + import stat + + try: + mode = os.lstat(path).st_mode + if not stat.S_ISLNK(mode): + os.chmod(path, stat.S_IMODE(mode) | stat.S_IWRITE) + if func in (os.unlink, os.remove, os.rmdir): + func(path) + except OSError: + pass + + +class InputError(ValueError): + """A user-supplied input that cannot be used: missing, unreadable, not UTF-8 or JSON, or the wrong shape. + + Library loaders raise it (or a subclass) with a message that names the file, and do not + print or exit. ``cli.main`` prints ``Error: `` and exits 2, the code for bad input; + exit 1 stays the verdict of ``--strict`` gates and ``eval judge-validity``. A ``ValueError``, + so code that already catches bad values keeps catching these. + """ + + +def refuse_device(path: str | os.PathLike[str], flag: str | None = None) -> None: + """:class:`InputError` `` : not a file`` for a device or a socket, before it is read whole. + + A regular file, a pipe (``<(cat x.json)``) and a directory pass; so does a path that cannot be + stat'ed, left to the read to report. ``/dev/zero`` would otherwise be read until memory runs out + (https://github.com/intel/dokimi/issues/504). The path is stat'ed as :class:`~pathlib.Path` spells it, + the way the callers read it: ``/dev/zero/`` and ``/dev/zero/.`` are ``/dev/zero`` to ``Path``. + """ + try: + mode = Path(path).stat().st_mode # not os.stat(path): ENOTDIR on /dev/zero/, which Path opens + except (OSError, ValueError): # missing, a path under a file, an embedded null byte + return + if not (stat.S_ISREG(mode) or stat.S_ISFIFO(mode) or stat.S_ISDIR(mode)): + raise InputError(f"{flag} {path}: not a file" if flag else f"{path}: not a file") + + +def read_json_input(path: str | os.PathLike[str], *, flag: str | None = None) -> Any: + """The parsed JSON at ``path``: :func:`read_json_input_bytes` without the bytes.""" + return read_json_input_bytes(path, flag=flag)[1] + + +def read_json_input_bytes(path: str | os.PathLike[str], *, flag: str | None = None) -> tuple[bytes, Any]: + """The bytes at ``path``, read once, and the JSON they hold, or :class:`InputError` naming the file and why: + missing or unreadable, a device (:func:`refuse_device`), not UTF-8, not JSON or nested too deeply to parse. + With ``flag`` (the option the file was given to) the message is `` : ``. An empty path is + refused first, quoted (``--answers "": no file given``), as ``Path("")`` would read the current directory.""" + if os.fspath(path) == "": + raise InputError(f'{flag} "": no file given' if flag else 'cannot read "": no file given') + refuse_device(path, flag) + try: + raw = Path(path).read_bytes() + return raw, json.loads(raw.decode("utf-8")) + except UnicodeDecodeError as exc: + raise InputError(f"{flag} {path}: {exc}" if flag else f"{path} is not UTF-8 text: {exc}") from exc + except (json.JSONDecodeError, RecursionError) as exc: # deep nesting is named as bad JSON, as on main + raise InputError(f"{flag} {path}: {exc}" if flag else f"{path} is not valid JSON: {exc}") from exc + except (OSError, ValueError) as exc: # ValueError: e.g. "embedded null byte" in the path, from pathlib + reason = getattr(exc, "strerror", None) or exc + raise InputError(f"{flag} {path}: {reason}" if flag else f"cannot read {path}: {reason}") from exc diff --git a/dokimi/dokimi/frontmatter.py b/dokimi/dokimi/frontmatter.py new file mode 100644 index 0000000000..0d279ab6b1 --- /dev/null +++ b/dokimi/dokimi/frontmatter.py @@ -0,0 +1,98 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Markdown frontmatter: the ``---`` YAML block that opens a skill, a task or a catalog file. + +:func:`parse_frontmatter` is the lenient reader, :func:`parse_frontmatter_strict` raises the YAML +error for a validator to name, and :func:`describe_yaml_error` words one error for a person. +""" + +from typing import Any, Dict, Tuple + +from dokimi.yaml_unique import load_unique_keys + + +def parse_frontmatter(text: str) -> "Tuple[Dict[str, Any], str]": + """Split a Markdown document into (frontmatter dict, body). + + Supports a leading YAML frontmatter block delimited by ``---`` lines, the + same convention used by Claude Code skill files and most static-site + generators. When no frontmatter is present, returns ``({}, text)``. Frontmatter + that is not valid YAML also returns ``{}``; use :func:`parse_frontmatter_strict` + to see that error. + + Args: + text: Raw file contents. + + Returns: + Tuple of (metadata dict, body string with frontmatter stripped). + """ + return _split_frontmatter(text, strict=False) + + +def parse_frontmatter_strict(text: str) -> "Tuple[Dict[str, Any], str]": + """Like :func:`parse_frontmatter`, but frontmatter that is not valid YAML raises. + + For a validator that must name the YAML error rather than read the document + as having no metadata. The lenient :func:`parse_frontmatter` is unchanged for + every other caller. + + Raises: + yaml.YAMLError: The frontmatter block is not valid YAML, repeats a key in one mapping, or + does not load: a value PyYAML cannot build (the date ``2026-99-99``) or nesting too + deep for the parser, raised by PyYAML as ``ValueError`` or ``RecursionError`` and re-raised as this. + """ + return _split_frontmatter(text, strict=True) + + +def describe_yaml_error(exc: Exception) -> str: + """One line for a frontmatter YAML error: the file line it is on, and a hint for the common case. + + ``yaml`` numbers the lines of the block it parsed, and that block starts on the file's second + line (the opening ``---`` is the first), so the file line is the YAML line plus two. The hint + covers the usual cause, an unquoted ``: `` inside a value such as ``Use when: a task``. + """ + problem = getattr(exc, "problem", None) or " ".join(str(exc).split()) or "not valid YAML" + mark = getattr(exc, "problem_mark", None) + where = f"line {mark.line + 2}" if mark is not None else "line unknown" + hint = "" + if "mapping values are not allowed" in problem: + hint = '; quote a value that contains ": ", e.g. description: "Use when: ..."' + return f"{where}: {problem}{hint}" + + +def _split_frontmatter(text: str, *, strict: bool) -> "Tuple[Dict[str, Any], str]": + import yaml + if not text: + return {}, "" + + stripped = text.lstrip("") # tolerate a UTF-8 BOM + lines = stripped.splitlines() + # Same rule as the closing fence: a line that is exactly ``---``. A thematic + # break (``-----``) or a ``--- title`` line opens nothing. + if not lines or lines[0].rstrip() != "---": + return {}, stripped + + # First line is the opening '---'; find the closing fence. + for idx in range(1, len(lines)): + if lines[idx].strip() == "---": + raw_meta = "\n".join(lines[1:idx]) + body = "\n".join(lines[idx + 1:]).lstrip("\n") + try: + meta = (load_unique_keys(raw_meta) if strict else yaml.safe_load(raw_meta)) or {} + except yaml.YAMLError: + if strict: + raise + meta = {} + except (AttributeError, IndexError, KeyError, TypeError, ValueError, RecursionError) as exc: + # PyYAML raises these, not YAMLError, for a value that does not fit its tag (2026-02-30, + # !!int with no value) or nesting too deep: that is invalid frontmatter, not a crash. + if strict: + raise yaml.YAMLError(str(exc)) from exc + meta = {} + if not isinstance(meta, dict): + meta = {} + return meta, body + + # No closing fence — treat the whole thing as body. + return {}, stripped diff --git a/dokimi/dokimi/gate/_numbers.py b/dokimi/dokimi/gate/_numbers.py index f652ecafa6..e83ed934bb 100644 --- a/dokimi/dokimi/gate/_numbers.py +++ b/dokimi/dokimi/gate/_numbers.py @@ -8,7 +8,7 @@ import math from typing import Any -from dokimi.utils import InputError +from dokimi.files import InputError def as_number(value: Any, where: str, *, finite: bool = False) -> float: diff --git a/dokimi/dokimi/gate/regression.py b/dokimi/dokimi/gate/regression.py index 32287fb83f..c6ad364fd6 100644 --- a/dokimi/dokimi/gate/regression.py +++ b/dokimi/dokimi/gate/regression.py @@ -10,7 +10,7 @@ from dokimi.gate._numbers import as_number from dokimi.gate.verdict import Check, Verdict -from dokimi.utils import InputError +from dokimi.files import InputError Severity = Literal["OK", "WARN", "CRITICAL"] diff --git a/dokimi/dokimi/harnesses/benchflow.py b/dokimi/dokimi/harnesses/benchflow.py index 87919a9cab..73a2d96f68 100644 --- a/dokimi/dokimi/harnesses/benchflow.py +++ b/dokimi/dokimi/harnesses/benchflow.py @@ -684,7 +684,7 @@ def treatment_names(skills_root: Path) -> Optional[frozenset[str]]: """Names the arm's treatment skills answer to: each pack's dir name and its frontmatter ``name``. ``None`` when the root holds no pack. Raises OSError when the root cannot be listed.""" from dokimi.digest_entries import pack_files - from dokimi.utils import parse_frontmatter + from dokimi.frontmatter import parse_frontmatter names: set[str] = set() for skill_md in pack_files(skills_root, "SKILL.md"): diff --git a/dokimi/dokimi/harnesses/command.py b/dokimi/dokimi/harnesses/command.py index 2d1172c379..abfe8e6886 100644 --- a/dokimi/dokimi/harnesses/command.py +++ b/dokimi/dokimi/harnesses/command.py @@ -15,7 +15,7 @@ from typing import Any from dokimi import process -from dokimi.utils import retry_writable +from dokimi.files import retry_writable from .models import HarnessResult, OperationRecord from .operations import load_operations diff --git a/dokimi/dokimi/harnesses/delivery.py b/dokimi/dokimi/harnesses/delivery.py index 6789b42613..a96bf8792a 100644 --- a/dokimi/dokimi/harnesses/delivery.py +++ b/dokimi/dokimi/harnesses/delivery.py @@ -22,7 +22,7 @@ from dokimi.gate.delivery import compare_pairs, evaluate, score from dokimi.llm_json import extract_json_object from dokimi.llm_providers import ANSWER_PROVIDERS, PROVIDER_ALIASES -from dokimi.utils import InputError, read_json_input_bytes +from dokimi.files import InputError, read_json_input_bytes def digest(data: bytes) -> str: diff --git a/dokimi/dokimi/harnesses/network_policy.py b/dokimi/dokimi/harnesses/network_policy.py index 1a8b9a7155..805bbbad26 100644 --- a/dokimi/dokimi/harnesses/network_policy.py +++ b/dokimi/dokimi/harnesses/network_policy.py @@ -47,7 +47,7 @@ from pathlib import Path from typing import Any, Callable, Iterable, Optional, Sequence -from dokimi.utils import parse_frontmatter +from dokimi.frontmatter import parse_frontmatter from .egress_proxy import normalize_entry diff --git a/dokimi/dokimi/harnesses/runner.py b/dokimi/dokimi/harnesses/runner.py index 5fce8e44d5..f6f170d47c 100644 --- a/dokimi/dokimi/harnesses/runner.py +++ b/dokimi/dokimi/harnesses/runner.py @@ -18,7 +18,7 @@ from dokimi.eval import binary_stats from dokimi.eval.stats import adjust_pvalues from dokimi.measure import as_float -from dokimi.utils import key_bytes +from dokimi.digest import key_bytes from .docker_solver import DockerSolverHarness from .models import HarnessResult, OperationRecord, TaskRunResult diff --git a/dokimi/dokimi/harnesses/skill_treatment.py b/dokimi/dokimi/harnesses/skill_treatment.py index 0f6e3b4f82..a54bb886db 100644 --- a/dokimi/dokimi/harnesses/skill_treatment.py +++ b/dokimi/dokimi/harnesses/skill_treatment.py @@ -47,7 +47,7 @@ from dokimi.skills import load_skill from dokimi.skills.listing import listing_description, listing_text_chars -from dokimi.utils import parse_frontmatter +from dokimi.frontmatter import parse_frontmatter TREATMENT_NOTICE = ( "A skill named `{skill_id}` is installed. Load it with the Skill tool before you " diff --git a/dokimi/dokimi/harnesses/verifier_reward.py b/dokimi/dokimi/harnesses/verifier_reward.py index ff339f2fb8..e364de8b1c 100644 --- a/dokimi/dokimi/harnesses/verifier_reward.py +++ b/dokimi/dokimi/harnesses/verifier_reward.py @@ -23,7 +23,7 @@ from dokimi import process from dokimi.docker_cmd import Docker -from dokimi.utils import retry_writable +from dokimi.files import retry_writable #: Harbor's order: ``reward.json`` first, ``reward.txt`` only when there is none. REWARD_FILES = ("reward.json", "reward.txt") diff --git a/dokimi/dokimi/ingest/docling_loader.py b/dokimi/dokimi/ingest/docling_loader.py index d85401cb78..89966e44f6 100644 --- a/dokimi/dokimi/ingest/docling_loader.py +++ b/dokimi/dokimi/ingest/docling_loader.py @@ -22,7 +22,7 @@ from dokimi.artifacts import load_artifact, save_artifact from dokimi.atomic_write import write_text_atomic -from dokimi.utils import InputError +from dokimi.files import InputError logger = logging.getLogger(__name__) diff --git a/dokimi/dokimi/judge_rule.py b/dokimi/dokimi/judge_rule.py index 38410de37b..3f86a06efc 100644 --- a/dokimi/dokimi/judge_rule.py +++ b/dokimi/dokimi/judge_rule.py @@ -3,8 +3,8 @@ """The one default-judge rule, shared by every surface that judges. -It lives beside :mod:`dokimi.utils` (for :func:`same_model`) rather than in -:mod:`dokimi.defaults`, which utils imports: a defaults module importing utils would close +It lives beside :mod:`dokimi.model_names` (for :func:`same_model`) rather than in +:mod:`dokimi.defaults`, which model_names imports: a defaults module importing model_names would close an import cycle. """ @@ -15,7 +15,7 @@ DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER, ) -from dokimi.utils import same_model +from dokimi.model_names import same_model #: The Claude CLI aliases, in the order a judge is picked from them. _CLI_ALIASES = ("opus", "sonnet", "haiku") diff --git a/dokimi/dokimi/mcp/factory.py b/dokimi/dokimi/mcp/factory.py index 449fd3e301..b1fbf6072f 100644 --- a/dokimi/dokimi/mcp/factory.py +++ b/dokimi/dokimi/mcp/factory.py @@ -8,7 +8,7 @@ from pathlib import Path from typing import Optional -from dokimi.utils import InputError +from dokimi.files import InputError from . import MCPClient diff --git a/dokimi/dokimi/mcp/url_client.py b/dokimi/dokimi/mcp/url_client.py index 4b96655f9a..021cfcb16c 100644 --- a/dokimi/dokimi/mcp/url_client.py +++ b/dokimi/dokimi/mcp/url_client.py @@ -10,7 +10,7 @@ import httpx -from dokimi.utils import key_bytes +from dokimi.digest import key_bytes from . import MCPClient, MCPConnectionError from .utils import read_cache_text, strip_html, score_chunk, split_paragraphs, write_cache_text diff --git a/dokimi/dokimi/model_names.py b/dokimi/dokimi/model_names.py new file mode 100644 index 0000000000..c6fc001456 --- /dev/null +++ b/dokimi/dokimi/model_names.py @@ -0,0 +1,182 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Model names: whether two names are one model, and the evaluator-independence warnings built on it. + +A name is reduced to its id and snapshot date, with its route, region profile, vendor prefix and Bedrock +revision dropped. :func:`check_bedrock_model` refuses a judge name Bedrock cannot run before a run pays +for answers. +""" + +import re +from typing import Any, Mapping, Sequence + +from dokimi import llm_cli +from dokimi.defaults import BEDROCK_MODEL_IDS +from dokimi.files import InputError + + +# Bedrock cross-region inference profiles: the same model served from another region. They are dropped +# from any provider's name, not only Bedrock's: no non-Bedrock id is known to start with one of them. +_REGION_PROFILES = ("us-gov.", "global.", "apac.", "us.", "eu.", "jp.", "au.", "ca.") + + +# Leading segments that name a route (provider or gateway: ``anthropic/``, ``openrouter/``), not a model; any other +# segment (an HF org such as ``meta-llama/``) is part of the id. Holds ``llm.ANSWER_PROVIDERS`` (test-pinned) + litellm routes. +_ROUTES = frozenset({ + "openai", "openai-codex", "anthropic", "google", "gemini", "google-vertex", "openrouter", "amazon-bedrock", + "bedrock", "converse", "vertex_ai", "azure", "azure_ai", "models", "groq", "ollama", "mistral", "deepseek", + "together_ai", "fireworks_ai", "xai", "cohere", "huggingface", "claude-cli", "codex-cli", "copilot-cli", +}) + + +# Vendors whose Bedrock ids start with ``vendor.`` (``anthropic.claude-...``, ``zai.glm-4.7``, ``xai.grok-4.6``). +_VENDORS = frozenset({ + "ai21", "amazon", "anthropic", "cohere", "deepseek", "google", "luma", "meta", "minimax", "mistral", + "moonshotai", "nvidia", "openai", "qwen", "stability", "twelvelabs", "writer", "xai", "zai", +}) + + +_VENDOR_SLUGS = {"z-ai": "zai", "x-ai": "xai", "mistralai": "mistral"} # OpenRouter's spelling of a vendor + + +_BEDROCK_ARN = re.compile(r"(?:^|/)arn:aws[a-z-]*:bedrock:[a-z0-9-]*:\d*:(?:inference-profile|foundation-model)/") + + +def _model_core(model: str) -> tuple[str, str | None]: + """A model name reduced to ``(id, snapshot date or None)``. A snapshot is ``-YYYYMMDD`` or OpenAI's ``-YYYY-MM-DD``. + + The route goes (``openrouter/anthropic/``, ``bedrock/``, ``vertex_ai/``, an ARN's + ``inference-profile/``), and so do the case, the region profile (``eu.``) and a Bedrock + revision (``-v1:0`` or ``-1:0``). Vertex's ``@20250929`` is the snapshot ``-20250929``. The organization of an + ``org/name`` id stays, so a re-upload under another organization is another model; a known vendor + (``qwen/``, ``z-ai/``) goes, as its Bedrock ``vendor.`` prefix does, unless a ``huggingface/`` route precedes it. + """ + # sonnet[1m] is the same model with a larger window: the 1M context form goes, and no other bracket + # (qwen3[8b] and qwen3[32b] are two models) + name = re.sub(r"\[1m\]$", "", (model or "").strip().lower()) + arn = _BEDROCK_ARN.search(name) # only a Bedrock ARN's tail: ``foundation-model/X`` alone is an org/name id + if arn: + name = name[arn.end():] + parts = name.split("/") + hub = False + while len(parts) > 1 and parts[0] in _ROUTES: + hub = parts.pop(0) == "huggingface" + if hub: # a Hub id: the route goes, its organization stays, even behind another route + break + if not hub and len(parts) > 1 and _VENDOR_SLUGS.get(parts[0], parts[0]) in _VENDORS: + parts.pop(0) # OpenRouter's ``qwen/X`` is Bedrock's ``qwen.X``: the vendor, not an organization + name = "/".join(parts) + name = re.sub(r"(? tuple[str | None, str | None]: + """``(id, snapshot date or None)`` of a model name with its route, region profile and vendor prefix dropped; + the id is ``None`` for a name with no id. Two names with equal identities are one model and one snapshot.""" + base, date = _model_core(model) + if not base: + return None, date + # a known vendor before the first dot (``anthropic.``, ``openai.``, as in Bedrock ids) is dropped; any other + # dotted name is part of the id (``alice.model``), and so is a dot after a digit or a dash (``gpt-4.1``) + head, dot, rest = base.partition(".") + ident = rest if dot and head in _VENDORS else base + return (ident if re.search(r"[a-z0-9]", ident) else None), date # separators alone name no model + + +def same_model(a: str, b: str) -> bool: + """Whether two model names are one model. + + The same id matches, and so does a dated snapshot and its undated alias (the alias runs + some snapshot of it), or the same id behind another route or region profile. Two dated + ids match only on the same date. A Claude CLI alias (``sonnet``, ``opus[1m]``) matches a + full id of its family, since the CLI runs the alias as one of them (which one is not known here). + + The provider is not part of the identity: the same weights on Bedrock and on the direct + API are still one model for the self-judge warning and for a baseline's model check. + """ + (base_a, date_a), (base_b, date_b) = model_identity(a), model_identity(b) + if base_a is None or base_b is None: + return False + # The alias rule applies only when neither side keeps an organization: ``myorg/sonnet`` is not the CLI's sonnet. + if "/" not in base_a and "/" not in base_b and (llm_cli.is_alias(a) or llm_cli.is_alias(b)): + family_a = llm_cli.family(a) + return family_a is not None and family_a == llm_cli.family(b) + if date_a and date_b and date_a != date_b: + return False + return base_a == base_b + + +def same_evaluator(answer_model: str, judge_model: str) -> bool: + """Whether the answer and judge are one model, for the independence warning and its stored flag.""" + return same_model(answer_model, judge_model) + + +def warn_judge_independence( + answer_provider: str, + answer_model: str, + judge_provider: str, + judge_model: str, + context: str = "run", + roles: tuple[str, str] = ("answer", "judge"), +) -> bool: + """Emit a non-fatal warning when answer and judge are the same model (on any provider route). + + ``roles`` names the two sides in the message, e.g. ``("generator", "reviewer")``. + """ + import sys + + same = same_evaluator(answer_model, judge_model) + if same: + first, second = roles + print( + "⚠ Evaluator independence warning " + f"({context}): {first} model equals {second} model " + f"[{answer_provider}/{answer_model}] and [{judge_provider}/{judge_model}] — potential self-referential bias.", + file=sys.stderr, + ) + return same + + +def warn_recorded_self_judge( + data: Any, + judges: Sequence[tuple[str, str]], + context: str, + roles: tuple[str, str] = ("answer", "judge"), +) -> bool: + """Warn (never refuse) for each ``(model, provider)`` judge that is the model a file records. + + ``data`` is a parsed answers or questions file; its top-level ``model`` and ``provider`` + name what produced it. Silent, and False, when either is missing. + """ + if not isinstance(data, Mapping): + return False + model, provider = data.get("model"), data.get("provider") + if not (isinstance(model, str) and isinstance(provider, str)): + return False + hits = [warn_judge_independence(provider, model, jp, jm, context=context, roles=roles) + for jm, jp in dict.fromkeys(judges)] + return any(hits) + + +_BEDROCK_ID = re.compile(r"[a-z0-9]+\.", re.IGNORECASE) + + +def check_bedrock_model(provider: str, model: str) -> None: + """Raise :class:`InputError` for a judge name Bedrock cannot run, before a run pays for answers. + + A Bedrock id starts with a region or vendor and a dot (``us.anthropic.``, ``amazon.``); a dot + after a hyphen is a version (``claude-sonnet-4.5``), not an id. An ARN or a litellm route has a + ``/``, and a bare name runs only when ``BEDROCK_MODEL_IDS`` maps it to a profile. + """ + if (provider == "amazon-bedrock" and "/" not in model and not _BEDROCK_ID.match(model) + and model not in BEDROCK_MODEL_IDS): + raise InputError(f"Bedrock has no model '{model}': pass its inference profile id " + f"(us.anthropic.) or an ARN; the bare names that run are " + f"{', '.join(BEDROCK_MODEL_IDS)}") diff --git a/dokimi/dokimi/novelty/artifact.py b/dokimi/dokimi/novelty/artifact.py index 133d5dbb7e..3b97a18196 100644 --- a/dokimi/dokimi/novelty/artifact.py +++ b/dokimi/dokimi/novelty/artifact.py @@ -12,7 +12,7 @@ from pathlib import Path -from dokimi.utils import InputError +from dokimi.files import InputError def load_artifact_text(ref: str) -> tuple[str, str, str, str, str]: @@ -42,7 +42,7 @@ def load_artifact_text(ref: str) -> tuple[str, str, str, str, str]: def load_artifact_ref(ref: str) -> tuple[str, str, str, str, str]: - """:func:`load_artifact_text` for a command's ``--artifact``: an :class:`~dokimi.utils.InputError` + """:func:`load_artifact_text` for a command's ``--artifact``: an :class:`~dokimi.files.InputError` naming ``ref`` when it is missing, unreadable, not UTF-8 or has no frontmatter to read.""" try: return load_artifact_text(ref) diff --git a/dokimi/dokimi/novelty/atom_labels.py b/dokimi/dokimi/novelty/atom_labels.py index 9f98dc6767..f20fa4ec2f 100644 --- a/dokimi/dokimi/novelty/atom_labels.py +++ b/dokimi/dokimi/novelty/atom_labels.py @@ -20,7 +20,7 @@ from pathlib import Path from typing import Any, Iterable -from dokimi.utils import InputError +from dokimi.files import InputError FIELDS = ("skill", "atom_id", "label") UNLABELLED = "unlabelled" diff --git a/dokimi/dokimi/novelty/atom_verdicts.py b/dokimi/dokimi/novelty/atom_verdicts.py index 5bf30a7043..8d7f6ef247 100644 --- a/dokimi/dokimi/novelty/atom_verdicts.py +++ b/dokimi/dokimi/novelty/atom_verdicts.py @@ -19,7 +19,7 @@ def analysis_digest(artifact: dict) -> str: import json from dokimi.artifacts import ENVELOPE_KEYS - from dokimi.utils import digest_text + from dokimi.digest import digest_text saved = json.loads(json.dumps(artifact)) body = {key: value for key, value in saved.items() if key not in ENVELOPE_KEYS and key != "schema_version"} diff --git a/dokimi/dokimi/novelty/atoms.py b/dokimi/dokimi/novelty/atoms.py index 5fe9a1b86e..c0010b8a9a 100644 --- a/dokimi/dokimi/novelty/atoms.py +++ b/dokimi/dokimi/novelty/atoms.py @@ -30,7 +30,7 @@ from dataclasses import dataclass, field from dokimi.atomic_write import write_text_atomic -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input from .atoms_refusal import partial_atoms_refusal from .batching import or_stop, retry_wording @@ -635,7 +635,7 @@ def load_atoms(path) -> tuple[list[Atom], list[Span]]: An ``atoms.json`` written before the ``extraction`` record existed marks nothing; it cannot say whether a span went unread. A ``sampled_atom_ids`` that names an atom the file does not hold, or names one twice, is not a valid atoms file (:func:`recorded_sample` reads - it). Raises :class:`~dokimi.utils.InputError`, see :func:`load_atoms_record`. + it). Raises :class:`~dokimi.files.InputError`, see :func:`load_atoms_record`. """ atoms, spans, _record = load_atoms_record(path) return atoms, spans @@ -771,7 +771,7 @@ def _check_bundle_shape(bundle) -> None: def load_atoms_record(path) -> tuple[list[Atom], list[Span], dict]: """The atoms, the spans and the parsed record of an atoms file: the one entry point to read it. - Raises :class:`~dokimi.utils.InputError` naming the file when it cannot be read, is not JSON, + Raises :class:`~dokimi.files.InputError` naming the file when it cannot be read, is not JSON, UTF-8 or an atom set (a ``bundle`` with mistyped fields included), or is marked partial. """ data = read_json_input(path) diff --git a/dokimi/dokimi/novelty/bundle.py b/dokimi/dokimi/novelty/bundle.py index 714d801d45..48a9fbfb6f 100644 --- a/dokimi/dokimi/novelty/bundle.py +++ b/dokimi/dokimi/novelty/bundle.py @@ -61,7 +61,7 @@ named_exclusions, ) from dokimi.digest_entries import listed_entries -from dokimi.utils import key_bytes +from dokimi.digest import key_bytes from .answer_key import ABSENT, AnswerKeyRecord, parse_answer_key, shown from .artifact import load_artifact_text diff --git a/dokimi/dokimi/novelty/client.py b/dokimi/dokimi/novelty/client.py index 3cd2f048a6..dee0197b20 100644 --- a/dokimi/dokimi/novelty/client.py +++ b/dokimi/dokimi/novelty/client.py @@ -280,7 +280,7 @@ def _cost_block(spend: Spend) -> dict[str, Any]: def same_client(a: LLMClient, b: LLMClient) -> bool: """Whether two clients run one model: the same name, or a CLI alias and a full id of its family.""" - from dokimi.utils import same_model + from dokimi.model_names import same_model return a.model == b.model or same_model(a.model, b.model) @@ -307,9 +307,9 @@ def extractor_judge_relation(extractor_model: str, judge: LLMClient, Takes a name, not a client: a saved atoms file records only the extractor's model id. """ - from dokimi.utils import same_model + from dokimi.model_names import same_model - # the same id behind a routing prefix or a Bedrock spelling is one model (utils.same_model, the one rule) + # the same id behind a routing prefix or a Bedrock spelling is one model (dokimi.model_names.same_model, the one rule) identical = extractor_model == judge.model or same_model(extractor_model, judge.model) vendor = vendor_of(extractor_model) return { diff --git a/dokimi/dokimi/novelty/cost.py b/dokimi/dokimi/novelty/cost.py index 681ac4984d..023ca981c7 100644 --- a/dokimi/dokimi/novelty/cost.py +++ b/dokimi/dokimi/novelty/cost.py @@ -13,13 +13,13 @@ import argparse import sys -from dokimi.utils import InputError +from dokimi.files import InputError def judge_refs(args: argparse.Namespace) -> list[tuple[str, str]]: """The ``--judge PROVIDER/MODEL`` list as (model, provider) pairs; empty without the flag.""" from dokimi.llm import ANSWER_PROVIDERS as PROVIDERS - from dokimi.utils import same_model + from dokimi.model_names import same_model refs = getattr(args, "judges", None) or [] if refs and (getattr(args, "judge_model", None) or getattr(args, "judge_provider", None)): diff --git a/dokimi/dokimi/novelty/grounding.py b/dokimi/dokimi/novelty/grounding.py index 2a7a5a1b4f..60a4151d29 100644 --- a/dokimi/dokimi/novelty/grounding.py +++ b/dokimi/dokimi/novelty/grounding.py @@ -22,7 +22,7 @@ from dokimi.eval.reference_checks import (LONG_FLAG, REGEX_TIMEOUT, grade_check, identifier_names, scope_options, scope_pairs, validate_grading) from dokimi.process import Env, run -from dokimi.utils import InputError +from dokimi.files import InputError #: A rejection names the unknown argument, and exit status cannot tell it from a listing #: (some tools exit nonzero after printing real help). A line opening with an option is a listing. diff --git a/dokimi/dokimi/novelty/judge2.py b/dokimi/dokimi/novelty/judge2.py index 14a68be1f4..aa16372a4f 100644 --- a/dokimi/dokimi/novelty/judge2.py +++ b/dokimi/dokimi/novelty/judge2.py @@ -13,7 +13,7 @@ import random from concurrent.futures import ThreadPoolExecutor -from dokimi.utils import InputError +from dokimi.files import InputError from .client import LLMClient, same_client from .measure import ERRORED, LENIENT_CORRECT, MeasureResult, _grade from .provenance import vendor_of diff --git a/dokimi/dokimi/novelty/measure.py b/dokimi/dokimi/novelty/measure.py index 58cc42e7ff..5053c2b411 100644 --- a/dokimi/dokimi/novelty/measure.py +++ b/dokimi/dokimi/novelty/measure.py @@ -30,7 +30,7 @@ from typing import Any from dokimi.eval.correlation import pearson -from dokimi.utils import InputError +from dokimi.files import InputError from .atoms import Atom from .client import LLMClient, SpendCapReached, parse_json_object, same_client from .controls import (REPEAT_ARM, clustered_ci, control_fields, reversal_by_arm, diff --git a/dokimi/dokimi/novelty/panel_grade.py b/dokimi/dokimi/novelty/panel_grade.py index 1f5f848b07..bb53ea4e6e 100644 --- a/dokimi/dokimi/novelty/panel_grade.py +++ b/dokimi/dokimi/novelty/panel_grade.py @@ -7,7 +7,7 @@ from collections.abc import Callable, Sequence -from dokimi.utils import InputError +from dokimi.files import InputError from .client import LLMClient, SpendCapReached, same_client from .panel import RULES, aggregate as aggregate_votes diff --git a/dokimi/dokimi/novelty/probes.py b/dokimi/dokimi/novelty/probes.py index a4404e288f..f53459b11d 100644 --- a/dokimi/dokimi/novelty/probes.py +++ b/dokimi/dokimi/novelty/probes.py @@ -37,7 +37,7 @@ from collections.abc import Iterator from dataclasses import dataclass, field -from dokimi.utils import InputError +from dokimi.files import InputError from .atoms import Atom from .client import LLMClient, SpendCapReached from .routing_stop import stop_if_run_wide diff --git a/dokimi/dokimi/novelty/retest.py b/dokimi/dokimi/novelty/retest.py index 513bac0702..8378f8ffbf 100644 --- a/dokimi/dokimi/novelty/retest.py +++ b/dokimi/dokimi/novelty/retest.py @@ -21,7 +21,7 @@ from dokimi.digest_entries import listed_entries from dokimi.eval.correlation import pearson from dokimi.novelty.measure import BASELINE_ARM -from dokimi.utils import InputError +from dokimi.files import InputError NOISE_Z = 1.96 # two-sided 95% SMALL_SAMPLE_N = 10 # below this many items the floor is a rough guide, not a bound diff --git a/dokimi/dokimi/novelty/routing.py b/dokimi/dokimi/novelty/routing.py index 5498ab0739..8e850e4a1a 100644 --- a/dokimi/dokimi/novelty/routing.py +++ b/dokimi/dokimi/novelty/routing.py @@ -23,9 +23,8 @@ which has been observed. Only a run inside the harness can settle that. The query set must come from outside the artifact. Deriving queries from the artifact's own -headings lets the artifact define both the problem scope and its own relevance; that mode -exists for triage, stamps ``queries_self_derived`` into the result, and must not be quoted -as a routing rate. +headings lets the artifact define both the problem scope and its own relevance; that mode exists +for triage, stamps ``queries_self_derived`` into the result, and must not be quoted as a routing rate. """ from __future__ import annotations @@ -43,7 +42,8 @@ from dokimi.external.listing import only_description_too_long from dokimi.skills import Skill -from dokimi.utils import InputError, parse_frontmatter, refuse_device +from dokimi.frontmatter import parse_frontmatter +from dokimi.files import InputError, refuse_device from .catalog_keep import check_keep_copies_under, keep_past_broken_copies, resolve_kept_copies from .client import LLMClient, OutputTruncated, SpendCapReached, parse_json_object diff --git a/dokimi/dokimi/novelty/sweep.py b/dokimi/dokimi/novelty/sweep.py index cdd9cde46f..d21951cff6 100644 --- a/dokimi/dokimi/novelty/sweep.py +++ b/dokimi/dokimi/novelty/sweep.py @@ -20,7 +20,7 @@ from pathlib import Path from typing import Any, Optional -from dokimi.utils import InputError +from dokimi.files import InputError #: The statuses a row can have. Only ``ok`` rows are measured and kept by a resumed run. STATUSES = ("ok", "partial", "error") diff --git a/dokimi/dokimi/novelty/symbols.py b/dokimi/dokimi/novelty/symbols.py index fa80bb113c..17ad682b90 100644 --- a/dokimi/dokimi/novelty/symbols.py +++ b/dokimi/dokimi/novelty/symbols.py @@ -16,7 +16,7 @@ from dokimi.pattern_glob import expand from dokimi.process import Env, run -from dokimi.utils import InputError +from dokimi.files import InputError #: A C identifier prefix: a C identifier that ends in an underscore (``cblas_``, ``LAPACKE_``). _PREFIX = re.compile(r"[A-Za-z_]\w*_") diff --git a/dokimi/dokimi/opportunities.py b/dokimi/dokimi/opportunities.py index e7748ba51e..662f007d95 100644 --- a/dokimi/dokimi/opportunities.py +++ b/dokimi/dokimi/opportunities.py @@ -15,7 +15,7 @@ from dataclasses import asdict, dataclass, field from dokimi.llms_txt import Finding -from dokimi.utils import InputError +from dokimi.files import InputError EFFORTS = ("low", "medium", "high") QUADRANTS = ("act_now", "plan", "if_capacity", "deprioritize") diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index 64e7d60bd8..35e8bf5734 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -15,7 +15,9 @@ answers_method_version as answers_method_version_of) from dokimi.eval.stats import paired_summary from dokimi.mcp.factory import create_doc_source_client, require_local_doc_source, resolve_library_id_for_product -from dokimi.utils import InputError, key_bytes, read_json_input, refuse_device, same_evaluator +from dokimi.files import InputError, read_json_input, refuse_device +from dokimi.digest import key_bytes +from dokimi.model_names import same_evaluator from dokimi.orchestrator.question_source import warn_unpinned_questions @@ -46,7 +48,7 @@ def _canonical(questions: List[Dict[str, Any]]) -> List[str]: Labels the run adds on reading (``source_type``, ``persona_id``) are left out, so a set is equal to what was read unless a record was added, dropped or reworded. """ - from dokimi.utils import question_id + from dokimi.records import question_id return sorted(json.dumps([repr(question_id(q)), q.get("question", q.get("text"))], default=str) for q in questions) @@ -776,7 +778,6 @@ def _generate_report( """Generate comprehensive report.""" from dokimi.report import ReportGenerator - # Load data eval_data = json.loads(self.eval_path.read_text(encoding="utf-8")) questions_data = { "product": self.product, @@ -791,7 +792,6 @@ def _generate_report( output_format="markdown" ) - # Save report write_bytes_in_place_or_atomic(self.report_path, text_file_bytes(report)) return report diff --git a/dokimi/dokimi/plugins.py b/dokimi/dokimi/plugins.py index 67cdc4f63b..54fe637837 100644 --- a/dokimi/dokimi/plugins.py +++ b/dokimi/dokimi/plugins.py @@ -26,7 +26,7 @@ from typing import Any, Dict, Iterable, List, Optional from dokimi.treatments.base import AgentConfig, Treatment -from dokimi.utils import digest_text +from dokimi.digest import digest_text EMPTY_PLUGIN_SET_ID = "sha256:e3b0c44298fc1c149afbf4c8996fb924" diff --git a/dokimi/dokimi/questions/artifact.py b/dokimi/dokimi/questions/artifact.py index f3049b66cc..4df3ce6149 100644 --- a/dokimi/dokimi/questions/artifact.py +++ b/dokimi/dokimi/questions/artifact.py @@ -47,7 +47,8 @@ ) from dokimi.provenance import ProvenanceError, parse_provenance, parse_version from dokimi.questions.normalizer import canonical_question, record_id -from dokimi.utils import question_id, read_json_input +from dokimi.records import question_id +from dokimi.files import read_json_input logger = logging.getLogger(__name__) @@ -256,8 +257,8 @@ def load_questions(path: Path | str, *, validate: bool = True, flag: str | None refuse the set. With ``flag`` (the option the file was given to) the file is read by - :func:`dokimi.utils.read_json_input`: an unreadable, non-UTF-8 or non-JSON file raises - :class:`~dokimi.utils.InputError` `` : ``. Without it the read is bare. + :func:`dokimi.files.read_json_input`: an unreadable, non-UTF-8 or non-JSON file raises + :class:`~dokimi.files.InputError` `` : ``. Without it the read is bare. """ # the raw value goes to the reader: ``Path("")`` is ``.``, which would hide an empty path raw = json.loads(Path(path).read_text(encoding="utf-8")) if flag is None else read_json_input(path, flag=flag) diff --git a/dokimi/dokimi/questions/normalizer.py b/dokimi/dokimi/questions/normalizer.py index afce97ae75..1d36b33af8 100644 --- a/dokimi/dokimi/questions/normalizer.py +++ b/dokimi/dokimi/questions/normalizer.py @@ -27,7 +27,7 @@ from typing import Any, Dict, List -from dokimi.utils import question_id +from dokimi.records import question_id _DIFFICULTY_MAP: Dict[Any, str] = { 1: "beginner", "1": "beginner", "beginner": "beginner", @@ -83,7 +83,7 @@ def canonical_question(q: Dict[str, Any]) -> Dict[str, Any]: def record_id(q: Dict[str, Any], idx: int) -> Any: """The id of the record at position ``idx`` of its set: its own, else ``q{idx:04d}``. - Its own is ``id``, else ``question_id`` (:func:`~dokimi.utils.question_id`; ``0`` is an id). + Its own is ``id``, else ``question_id`` (:func:`~dokimi.records.question_id`; ``0`` is an id). """ own = question_id(q) return f"q{idx:04d}" if own is None else own diff --git a/dokimi/dokimi/records.py b/dokimi/dokimi/records.py index 621ee50f83..e22c1cfb51 100644 --- a/dokimi/dokimi/records.py +++ b/dokimi/dokimi/records.py @@ -45,7 +45,7 @@ written as and an aggregate stays the ``int`` or ``float`` it was written as, so a report that prints them prints what the file says. -Errors: :class:`RecordError` (an :class:`~dokimi.utils.InputError`, so the CLI exits 2 with its message) for a missing or unparseable file, an +Errors: :class:`RecordError` (an :class:`~dokimi.files.InputError`, so the CLI exits 2 with its message) for a missing or unparseable file, an artifact with no record list, a record that is not an object, has no ``question_id`` or has one that is neither a string nor an integer, a condition payload that is neither an object nor ``null``, an ``arms``/``scores`` field that is not an object, an ``expected_skill`` that is not a @@ -60,9 +60,9 @@ from collections.abc import Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path -from typing import Any, Optional, Union +from typing import Any, Dict, Optional, Union -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input #: The binary context arm, under its persisted key. CONTEXT = "with_docs" @@ -86,7 +86,7 @@ class AskOutcomeError(InputError): """A record's ``expected_outcome`` is not a known value, or the path cannot judge it. - An :class:`~dokimi.utils.InputError`: the CLI reports ``Error: ...`` with exit 2. + An :class:`~dokimi.files.InputError`: the CLI reports ``Error: ...`` with exit 2. """ @@ -738,3 +738,15 @@ def _score(payload: Mapping[str, Any], *, key: str = "aggregate") -> Score: # A score block keeps its aggregate under ``aggregate``; the legacy inline # ``arms[name].evaluation`` kept it under ``aggregate_score``. return Score(aggregate=_number(payload.get(key)), error=_text(payload.get("error")), raw=payload) + + +def question_id(q: Dict[str, Any]) -> Any: + """The question's ``id`` or ``question_id``; ``None`` when neither is set. + + ``0`` is an id (``questions.v1`` allows integer ids), so ``q.get("id") or ...`` + — which reads it as missing — is not a substitute. + """ + for key in ("id", "question_id"): + if q.get(key) not in (None, ""): + return q[key] + return None diff --git a/dokimi/dokimi/repo_config.py b/dokimi/dokimi/repo_config.py index dd726cae1e..39aa472ff6 100644 --- a/dokimi/dokimi/repo_config.py +++ b/dokimi/dokimi/repo_config.py @@ -32,7 +32,8 @@ from dokimi.repo_glob import glob_links as _glob_links, glob_paths as _glob_paths from dokimi.repo_links import _declared_links, _hops, _inside, _real, _under, _walk, _within from dokimi.digest_entries import target_digest -from dokimi.utils import GitDigestTree, _tracked_modes, file_contents, git_tree, link_text, tree_digest +from dokimi.digest import (GitDigestTree, _tracked_modes, file_contents, git_tree, link_text, + tree_digest) KIND = "dokimi_config" CONFIG_CANDIDATES = (".github/dokimi/config.yaml", ".dokimi/config.yaml") diff --git a/dokimi/dokimi/repo_glob.py b/dokimi/dokimi/repo_glob.py index fb2ed987cd..2ddf39acb0 100644 --- a/dokimi/dokimi/repo_glob.py +++ b/dokimi/dokimi/repo_glob.py @@ -11,7 +11,7 @@ import os from pathlib import Path -from dokimi.utils import is_symlink_loop +from dokimi.files import is_symlink_loop def _missing(exc: OSError) -> bool: diff --git a/dokimi/dokimi/repo_links.py b/dokimi/dokimi/repo_links.py index c5a1e24735..8fe8561f2d 100644 --- a/dokimi/dokimi/repo_links.py +++ b/dokimi/dokimi/repo_links.py @@ -10,7 +10,8 @@ import os from pathlib import Path -from dokimi.utils import _plain_path, is_symlink_loop +from dokimi.digest import _plain_path +from dokimi.files import is_symlink_loop def _real(path: Path) -> Path | None: diff --git a/dokimi/dokimi/report/arms_file.py b/dokimi/dokimi/report/arms_file.py index b2d719897e..a1dfb0ac94 100644 --- a/dokimi/dokimi/report/arms_file.py +++ b/dokimi/dokimi/report/arms_file.py @@ -7,12 +7,12 @@ from typing import Any +from dokimi.files import InputError, read_json_input from dokimi.records import read -from dokimi.utils import InputError, read_json_input def read_arms_file(path: str) -> dict[str, Any]: - """The parsed arms JSON at *path*; an :class:`~dokimi.utils.InputError` naming it when it is not one. + """The parsed arms JSON at *path*; an :class:`~dokimi.files.InputError` naming it when it is not one. An arms file is a JSON object with readable ``answers``/``evaluations`` sections and a ``baseline_arm`` to pair each question's arms against. An eval file from ``evaluate`` has diff --git a/dokimi/dokimi/report/model_compare.py b/dokimi/dokimi/report/model_compare.py index 4d1c51019a..10b265549e 100644 --- a/dokimi/dokimi/report/model_compare.py +++ b/dokimi/dokimi/report/model_compare.py @@ -40,10 +40,10 @@ from dokimi.eval.judge_context import PROTOCOL_MIXED as JUDGE_CONTEXT_MIXED from dokimi.eval import finite_delta, stats as arm_stats from dokimi.eval.arm_summary import pooled_spend_fields +from dokimi.files import InputError from dokimi.report import fmt -from dokimi.report.compare_limits import no_delta_limitation from dokimi.report.arms_file import read_arms_file -from dokimi.utils import InputError +from dokimi.report.compare_limits import no_delta_limitation try: from zoneinfo import ZoneInfo @@ -59,7 +59,7 @@ def load_run(path: str) -> dict[str, Any]: - """Load a judged arms JSON file, an :class:`~dokimi.utils.InputError` naming it when it is not one.""" + """Load a judged arms JSON file, an :class:`~dokimi.files.InputError` naming it when it is not one.""" return read_arms_file(path) diff --git a/dokimi/dokimi/repos/budget.py b/dokimi/dokimi/repos/budget.py index 6f7fd9880e..85300f99bf 100644 --- a/dokimi/dokimi/repos/budget.py +++ b/dokimi/dokimi/repos/budget.py @@ -652,7 +652,7 @@ def _normalize(path: str) -> str: def _skills(tree: RepoTree, paths: list[str]) -> list[dict[str, Any]]: - from dokimi.utils import parse_frontmatter + from dokimi.frontmatter import parse_frontmatter out = [] for path in paths: diff --git a/dokimi/dokimi/repos/compare.py b/dokimi/dokimi/repos/compare.py index fb42570f8b..677231214f 100644 --- a/dokimi/dokimi/repos/compare.py +++ b/dokimi/dokimi/repos/compare.py @@ -126,7 +126,7 @@ ) from dokimi.eval.stats import correct_family from dokimi.eval.finite_delta import checked_delta, checked_mean -from dokimi.utils import same_model +from dokimi.model_names import same_model from .compare_judged import (check_reported, judge_names, judge_warnings, judged_cells, judged_lines, read_judged) diff --git a/dokimi/dokimi/repos/graph_tasks.py b/dokimi/dokimi/repos/graph_tasks.py index 8c98668eeb..2a9de5cf9e 100644 --- a/dokimi/dokimi/repos/graph_tasks.py +++ b/dokimi/dokimi/repos/graph_tasks.py @@ -32,7 +32,7 @@ from dokimi.repos.code_index.symbols import descriptor_names, descriptors from dokimi.repos.environment.files import is_generated, is_test_file from dokimi.repos.environment.structure import detect_prefix, function_like, is_protocol_name -from dokimi.utils import key_bytes +from dokimi.digest import key_bytes GOLD = "gold.json" GRADER = "dokimi:graph_enum" diff --git a/dokimi/dokimi/repos/reach.py b/dokimi/dokimi/repos/reach.py index 0a163e7b15..dcb7272d77 100644 --- a/dokimi/dokimi/repos/reach.py +++ b/dokimi/dokimi/repos/reach.py @@ -34,9 +34,8 @@ and not probed. The workspace is a skeleton: guidance files, one probe file per guidance -directory, and a one-commit git repository. Loading depends on paths and -names, not on the rest of the tree, and a skeleton keeps a blob-less clone -from fetching the whole repository. +directory, and a one-commit git repository. Loading depends on paths and names. +A skeleton keeps a blob-less clone from fetching the whole repository. """ from __future__ import annotations @@ -58,7 +57,8 @@ from dokimi import process from dokimi.atomic_write import write_bytes_in_place_or_atomic from dokimi.process_io import text_file_bytes -from dokimi.utils import key_bytes, retry_writable +from dokimi.digest import key_bytes +from dokimi.files import retry_writable from .events import convert from .transcript import Transcript diff --git a/dokimi/dokimi/repos/report.py b/dokimi/dokimi/repos/report.py index 14f04097a4..b61e77e6ef 100644 --- a/dokimi/dokimi/repos/report.py +++ b/dokimi/dokimi/repos/report.py @@ -61,7 +61,7 @@ from dokimi.eval.sign_flip import round_off_zero from dokimi.measure import as_float, is_number from dokimi.provenance import STATUSES, UNKNOWN -from dokimi.utils import same_model +from dokimi.model_names import same_model from .batch_ledger import recorded_execution from .grading import SCORE_BOUND, read_grade_json diff --git a/dokimi/dokimi/repos/skill_reach.py b/dokimi/dokimi/repos/skill_reach.py index d47e5f077f..998075f1e4 100644 --- a/dokimi/dokimi/repos/skill_reach.py +++ b/dokimi/dokimi/repos/skill_reach.py @@ -72,7 +72,8 @@ from dokimi import process from dokimi.process_io import joined_pairs -from dokimi.utils import key_bytes, retry_writable +from dokimi.digest import key_bytes +from dokimi.files import retry_writable from .events import convert from .harness_profile import HarnessProfile diff --git a/dokimi/dokimi/repos/source.py b/dokimi/dokimi/repos/source.py index d684110e0e..90dbc15fca 100644 --- a/dokimi/dokimi/repos/source.py +++ b/dokimi/dokimi/repos/source.py @@ -36,7 +36,7 @@ SourceError, _NoSuchPath, ) -from dokimi.utils import key_bytes +from dokimi.digest import key_bytes # A revision is a SHA, tag or branch (a "/" is allowed: origin/main, refs/heads/x), optionally # with ^ / ~N suffixes. No leading "-" (so a revision can never be read as a git option); diff --git a/dokimi/dokimi/runner/compare.py b/dokimi/dokimi/runner/compare.py index 973f5801fe..97a4e954ca 100644 --- a/dokimi/dokimi/runner/compare.py +++ b/dokimi/dokimi/runner/compare.py @@ -11,7 +11,7 @@ from typing import Any from dokimi.gate.regression import detect_regressions -from dokimi.utils import InputError +from dokimi.files import InputError _REQUIRED_SUMMARY_KEYS = {"docs", "score", "coverage", "freshness_lite", "readability"} diff --git a/dokimi/dokimi/runs/baseline.py b/dokimi/dokimi/runs/baseline.py index 89672693f4..7dd95cd319 100644 --- a/dokimi/dokimi/runs/baseline.py +++ b/dokimi/dokimi/runs/baseline.py @@ -27,6 +27,7 @@ from dokimi.artifacts import is_run_id from dokimi.atomic_write import write_text_atomic +from dokimi.files import InputError from dokimi.runs.scan import ( BASELINE_POINTERS, ScanResult, @@ -37,7 +38,6 @@ read_error_reason, scan, ) -from dokimi.utils import InputError LOCK = ".lock" #: What makes a ``--baseline`` value a baseline's name, not a path (#94 §2.3: ``compare RUN baseline:NAME``). diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index f462bb73ee..eeb452d1e3 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -43,7 +43,7 @@ from dokimi.runs import baseline from dokimi.runs.rundir import RUN_FILE from dokimi.runs.scan import artifact_version, inside, is_link, plain, read_error_reason, scan -from dokimi.utils import InputError +from dokimi.files import InputError MANIFEST = "bundle.json" SCHEMA = "run_bundle.v1" diff --git a/dokimi/dokimi/runs/rm.py b/dokimi/dokimi/runs/rm.py index 3d591a6f0c..8483890b49 100644 --- a/dokimi/dokimi/runs/rm.py +++ b/dokimi/dokimi/runs/rm.py @@ -35,7 +35,7 @@ timestamp, ) from dokimi.runs.show import contained, find_run -from dokimi.utils import InputError +from dokimi.files import InputError _AGE = re.compile(r"(\d{1,5})d") diff --git a/dokimi/dokimi/runs/rundir.py b/dokimi/dokimi/runs/rundir.py index bffae4b7db..7a664d9817 100644 --- a/dokimi/dokimi/runs/rundir.py +++ b/dokimi/dokimi/runs/rundir.py @@ -28,7 +28,7 @@ from dokimi.artifacts import SCHEMA_VERSIONS, is_run_id, run_id, save_artifact from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE from dokimi.runner.plan import STATUSES, completeness, plan_digest -from dokimi.utils import InputError +from dokimi.files import InputError #: The directory's own record, ``run.v1``. RUN_FILE = "run.json" diff --git a/dokimi/dokimi/runs/scan.py b/dokimi/dokimi/runs/scan.py index 66041d6326..06ab979b18 100644 --- a/dokimi/dokimi/runs/scan.py +++ b/dokimi/dokimi/runs/scan.py @@ -26,7 +26,7 @@ from dokimi.artifacts import INPUT_KINDS, is_run_id from dokimi.runs.kinds import FIELDS, VERSION_KINDS, read_field -from dokimi.utils import InputError, is_symlink_loop +from dokimi.files import InputError, is_symlink_loop ENV_VAR = "DOKIMI_RUNS_DIR" DEFAULT_ROOT = Path("results") @@ -68,7 +68,7 @@ class RunsRoot: def exists(self) -> bool: """True when the root is a directory; False when the default root is not there yet. - Raises :class:`~dokimi.utils.InputError` when ``DOKIMI_RUNS_DIR`` names a missing path, + Raises :class:`~dokimi.files.InputError` when ``DOKIMI_RUNS_DIR`` names a missing path, when the root is something other than a directory, or when it cannot be looked up. """ named = plain(f"{ENV_VAR}={self.path}" if self.from_env else str(self.path)) @@ -92,7 +92,7 @@ def runs_root(environ: Mapping[str, str] | None = None) -> RunsRoot: def existing_root() -> RunsRoot: - """The runs root, which must exist. Raises :class:`~dokimi.utils.InputError` otherwise.""" + """The runs root, which must exist. Raises :class:`~dokimi.files.InputError` otherwise.""" root = runs_root() if not root.exists(): raise InputError(f"no runs root: {plain(root.path.as_posix())}/ does not exist " diff --git a/dokimi/dokimi/runs/show.py b/dokimi/dokimi/runs/show.py index 4e464215d7..1f00c774cb 100644 --- a/dokimi/dokimi/runs/show.py +++ b/dokimi/dokimi/runs/show.py @@ -26,7 +26,7 @@ read_error_reason, scan, ) -from dokimi.utils import InputError +from dokimi.files import InputError #: Entries of the artifact's directory that ``runs show`` names; the rest are only counted. MAX_SIBLINGS = 20 diff --git a/dokimi/dokimi/skills/formats.py b/dokimi/dokimi/skills/formats.py index c94c70c60f..ea0b54f39f 100644 --- a/dokimi/dokimi/skills/formats.py +++ b/dokimi/dokimi/skills/formats.py @@ -38,7 +38,7 @@ from dokimi.digest_entries import listed_entries from dokimi.skills.loader import VENDORED_DIR_NAMES, skill_files -from dokimi.utils import parse_frontmatter +from dokimi.frontmatter import parse_frontmatter FORMAT_AGENT_SKILL = "agent-skill" FORMAT_CURSOR_RULE = "cursor-rule" diff --git a/dokimi/dokimi/skills/loader.py b/dokimi/dokimi/skills/loader.py index 80a6b9b782..ce1c0efc33 100644 --- a/dokimi/dokimi/skills/loader.py +++ b/dokimi/dokimi/skills/loader.py @@ -20,7 +20,7 @@ import yaml from dokimi.digest_entries import listed_entries -from dokimi.utils import describe_yaml_error, parse_frontmatter, parse_frontmatter_strict +from dokimi.frontmatter import describe_yaml_error, parse_frontmatter, parse_frontmatter_strict # Directory names that hold a scaffold to copy, not a skill to use (see discover_skills). TEMPLATE_DIR_NAMES = frozenset({"template", "templates"}) diff --git a/dokimi/dokimi/subjects/scorecard.py b/dokimi/dokimi/subjects/scorecard.py index 47485550c8..7a2ee54333 100644 --- a/dokimi/dokimi/subjects/scorecard.py +++ b/dokimi/dokimi/subjects/scorecard.py @@ -15,7 +15,7 @@ from typing import Any from dokimi import __version__ -from dokimi.utils import key_bytes +from dokimi.digest import key_bytes from .loader import awareness_arm_specs, work_arm_specs from .models import SubjectDescriptor @@ -248,7 +248,7 @@ def _digest_ref_kind(ref: str | None, *, base: Path) -> tuple[str | None, bytes] if _is_dir(path): kind = b"d" h.update(b"d") - # POSIX names, ordered by their parts as utils.tree_digest does, so the same tree digests the same on Windows + # POSIX names, ordered by their parts as dokimi.digest.tree_digest does, so the same tree digests the same on Windows files = [Path(top, name) for top, _, names in os.walk(path, onerror=_raise) for name in names] for child in sorted((p for p in files if _is_file(p)), key=lambda p: p.relative_to(path).parts): h.update(_field(child.relative_to(path).as_posix())) diff --git a/dokimi/dokimi/treatments/arms.py b/dokimi/dokimi/treatments/arms.py index d2f1daf70e..5e12b81422 100644 --- a/dokimi/dokimi/treatments/arms.py +++ b/dokimi/dokimi/treatments/arms.py @@ -8,7 +8,7 @@ from dokimi.agent_profiles import AgentProfile from dokimi.skills import Skill -from dokimi.utils import digest_text +from dokimi.digest import digest_text from .base import AgentConfig, Treatment from .specs import combined_name diff --git a/dokimi/dokimi/utils.py b/dokimi/dokimi/utils.py index 55004973e5..9120e502f3 100644 --- a/dokimi/dokimi/utils.py +++ b/dokimi/dokimi/utils.py @@ -1,800 +1,24 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -import errno -import hashlib -import json -import os -import re -import stat -from dataclasses import dataclass, field -from pathlib import Path -from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Mapping, Sequence, Tuple - -from dokimi import llm_cli -from dokimi.defaults import BEDROCK_MODEL_IDS -from dokimi.process_io import disk_path_text, exact_path_text, flagged, worktree_changed -from dokimi.yaml_unique import load_unique_keys - -if TYPE_CHECKING: - from dokimi.process import Env - - -def parse_frontmatter(text: str) -> "Tuple[Dict[str, Any], str]": - """Split a Markdown document into (frontmatter dict, body). - - Supports a leading YAML frontmatter block delimited by ``---`` lines, the - same convention used by Claude Code skill files and most static-site - generators. When no frontmatter is present, returns ``({}, text)``. Frontmatter - that is not valid YAML also returns ``{}``; use :func:`parse_frontmatter_strict` - to see that error. - - Args: - text: Raw file contents. - - Returns: - Tuple of (metadata dict, body string with frontmatter stripped). - """ - return _split_frontmatter(text, strict=False) - - -def parse_frontmatter_strict(text: str) -> "Tuple[Dict[str, Any], str]": - """Like :func:`parse_frontmatter`, but frontmatter that is not valid YAML raises. - - For a validator that must name the YAML error rather than read the document - as having no metadata. The lenient :func:`parse_frontmatter` is unchanged for - every other caller. - - Raises: - yaml.YAMLError: The frontmatter block is not valid YAML, repeats a key in one mapping, or - does not load: a value PyYAML cannot build (the date ``2026-99-99``) or nesting too - deep for the parser, raised by PyYAML as ``ValueError`` or ``RecursionError`` and re-raised as this. - """ - return _split_frontmatter(text, strict=True) - - -def describe_yaml_error(exc: Exception) -> str: - """One line for a frontmatter YAML error: the file line it is on, and a hint for the common case. - - ``yaml`` numbers the lines of the block it parsed, and that block starts on the file's second - line (the opening ``---`` is the first), so the file line is the YAML line plus two. The hint - covers the usual cause, an unquoted ``: `` inside a value such as ``Use when: a task``. - """ - problem = getattr(exc, "problem", None) or " ".join(str(exc).split()) or "not valid YAML" - mark = getattr(exc, "problem_mark", None) - where = f"line {mark.line + 2}" if mark is not None else "line unknown" - hint = "" - if "mapping values are not allowed" in problem: - hint = '; quote a value that contains ": ", e.g. description: "Use when: ..."' - return f"{where}: {problem}{hint}" - - -def _split_frontmatter(text: str, *, strict: bool) -> "Tuple[Dict[str, Any], str]": - import yaml - if not text: - return {}, "" - - stripped = text.lstrip("") # tolerate a UTF-8 BOM - lines = stripped.splitlines() - # Same rule as the closing fence: a line that is exactly ``---``. A thematic - # break (``-----``) or a ``--- title`` line opens nothing. - if not lines or lines[0].rstrip() != "---": - return {}, stripped - - # First line is the opening '---'; find the closing fence. - for idx in range(1, len(lines)): - if lines[idx].strip() == "---": - raw_meta = "\n".join(lines[1:idx]) - body = "\n".join(lines[idx + 1:]).lstrip("\n") - try: - meta = (load_unique_keys(raw_meta) if strict else yaml.safe_load(raw_meta)) or {} - except yaml.YAMLError: - if strict: - raise - meta = {} - except (AttributeError, IndexError, KeyError, TypeError, ValueError, RecursionError) as exc: - # PyYAML raises these, not YAMLError, for a value that does not fit its tag (2026-02-30, - # !!int with no value) or nesting too deep: that is invalid frontmatter, not a crash. - if strict: - raise yaml.YAMLError(str(exc)) from exc - meta = {} - if not isinstance(meta, dict): - meta = {} - return meta, body - - # No closing fence — treat the whole thing as body. - return {}, stripped - - -def digest_text(text: str) -> str: - """Content-digest a prompt or other text blob. - - Uses the ``sha256:`` prefix convention the plugin-set and subject - digests already use, so provenance fields read the same way across artifacts. - The digest itself is the full 64-char hex: the plugin-set digest is truncated - to 32, so the two are comparable in shape but never equal for the same input. - - Args: - text: The text to digest. - - Returns: - ``"sha256:"`` followed by the hex digest of the UTF-8 encoding. - """ - import hashlib - - return "sha256:" + hashlib.sha256((text or "").encode("utf-8", errors="surrogatepass")).hexdigest() - - -def key_bytes(text: str) -> bytes: - """Bytes a cache key hashes: ``surrogateescape``; NUL-led text gets ``\\0e``; a surrogate it cannot map (U+D800..U+DC7F, U+DD00..U+DFFF) tags the text ``\\0sp`` and uses ``surrogatepass``.""" - try: - return b"\0e" * text.startswith("\0") + text.encode("utf-8", "surrogateescape") - except UnicodeEncodeError: # a JSON `\ud800` has no escape - return b"\0sp" + text.encode("utf-8", "surrogatepass") - - -def _plain_path(text: str) -> str: - r"""A Windows absolute path without its extended-length prefix. os.readlink gives an absolute link target as - \\?\C:\... (or \\?\UNC\...), while the anchors are plain: the two read as different drives. - Any other text is returned unchanged.""" - if text.startswith("\\\\?\\UNC\\"): - return "\\\\" + text[len("\\\\?\\UNC\\"):] - if text.startswith("\\\\?\\"): - return text[len("\\\\?\\"):] - return text - - -def _settled(target: str) -> str: - """An absolute ``target`` with each ``..`` that follows a real directory folded into it, as the kernel reads the - path. A ``..`` that follows a link is kept: the kernel resolves it from the link's target, which a fold would miss.""" - anchor, *names = Path(target).parts - kept: list[str] = [] - for name in names: - if name == "..": - top = kept[-1] if kept else None - here = os.path.join(anchor, *kept) - if top not in (None, "..") and os.path.isdir(here) and not os.path.islink(here): - kept.pop() - continue - kept.append(name) - return os.path.join(anchor, *kept) - - -def _posix_separators(text: str, sep: str = os.sep) -> str: - """``text`` with its native separator ``sep`` written as ``/``, so a relative link target digests the same on Windows - (where os.readlink gives backslashes) as on POSIX. On POSIX a backslash is part of a name and is kept.""" - return text if sep == "/" else text.replace(sep, "/") - - -@dataclass(frozen=True) -class GitDigestTree: - """A work tree a digest reads through git: its top (a real path), the walk's base (top-relative, "" for the top), the - untracked, ignored paths git leaves out (top-relative, a directory by its name as ``ls-files --directory`` gives it), - and the blob ids of the tracked files git finds unchanged (their index entries). A tree is a snapshot: build one per - digest. ``indexed`` is left out of the hash only: a mapping cannot hash, and equality must see the snapshot. - ``tracked`` holds every path the top's index holds and each directory above one: git stores those, so a nested - repository's rules never leave them out. ``nested`` is filled as a walk meets directories: for one holding ``.git`` - (a nested repository or submodule), the paths its own git ignores, relative to it; None for any other. It is a - cache, so equality and the hash leave it out.""" - - top: Path - base: str - ignored: frozenset[str] - indexed: Mapping[str, str] = field(hash=False) - tracked: frozenset[str] = frozenset() - nested: dict[str, frozenset[str] | None] = field(default_factory=dict, hash=False, compare=False, repr=False) - - def top_rel(self, path: Path) -> str | None: - """``path`` relative to the top, as POSIX, its own link (if it is one) not followed; None outside the tree.""" - real = Path(os.path.realpath(path.parent)) / path.name - try: - return real.relative_to(self.top).as_posix() - except ValueError: - return None - - def skipped(self, path: Path) -> bool: - """True for what git leaves out: an ignored path below the base, by the top's rules or (unless the top tracks it) - by those of a nested repository holding it, or anything under a ``.git`` (a nested repository's own). An ignored - directory above the base is not this walk's to apply. OSError when git cannot read such a nested repository.""" - rel = self.top_rel(path) - if rel is None: - return False - parts = rel.split("/") - first = len(self.base.split("/")) + 1 if self.base else 1 - if ".git" in parts or any("/".join(parts[:i]) in self.ignored for i in range(first, len(parts) + 1)): - return True - return rel not in self.tracked and any(self._inner_skips(parts, j, first) for j in range(1, len(parts))) - - def _inner_skips(self, parts: list[str], j: int, first: int) -> bool: - """True when the directory ``parts[:j]`` is a nested repository that ignores ``parts[j:]`` or a directory of it - below the base (``first``: the walk's first own part).""" - inner = self._inner_ignored("/".join(parts[:j])) - if not inner: - return False - return any("/".join(parts[j:i]) in inner for i in range(max(first, j + 1), len(parts) + 1)) - - def _inner_ignored(self, rel: str) -> frozenset[str] | None: - if rel not in self.nested: # read once per nested repository, no git call for a directory without .git - here = self.top / rel - if not os.path.lexists(here / ".git"): - self.nested[rel] = None - elif (why := _not_own_top(here)) is not None: - raise OSError(errno.EIO, f"git cannot read this nested repository: {why}", os.fspath(here)) - elif (inner := _ignored_paths(os.fspath(here))) is not None: - self.nested[rel] = inner - else: # leaving nothing out would hash its ignored files only where git cannot read it - raise OSError(errno.EIO, "git cannot read this nested repository", os.fspath(here)) - return self.nested[rel] - - -def is_symlink_loop(exc: OSError) -> bool: - """A symlink loop: ``ELOOP``, or on Windows EINVAL with WinError 1921 (ERROR_CANT_RESOLVE_FILENAME).""" - return exc.errno == errno.ELOOP or getattr(exc, "winerror", None) == 1921 - - -def _not_own_top(here: Path) -> str | None: - """Why git does not read ``here`` as its own work tree's top: git's message, or the top it found instead (git skips - a ``.git`` it cannot read as a repository and walks up to the enclosing one). None when it does.""" - from dokimi.process import run - - top = run(["git", "-C", os.fspath(here), "rev-parse", "--show-toplevel"], timeout=60, env=_git_env()) - if not top.ok: - return top.stderr.strip() or f"exit {top.returncode}" - found = os.fsdecode(top.stdout_bytes).removesuffix("\n") # git ends the name with one newline - return None if Path(os.path.realpath(found)) == Path(os.path.realpath(here)) else f"git reads {found} instead" - - -def _git_env() -> "Env": - from dokimi.process import Env - - # GIT_* variables (a hook's GIT_DIR or GIT_INDEX_FILE) would point git at some other repository - return Env.only(allow=[k for k in os.environ if not k.startswith("GIT_")]) - - -def git_tree(base: Path) -> GitDigestTree | None: - """The work tree holding ``base``, with what git leaves out of it. None when ``base`` is in no work tree (or git - cannot say): the digest then hashes the bytes on disk and leaves nothing out.""" - from dokimi.process import run - - try: - top = run(["git", "-C", os.fspath(base), "rev-parse", "--show-toplevel"], timeout=60, env=_git_env()) - if not top.ok: - return None - top_dir = os.fsdecode(top.stdout_bytes).removesuffix("\n") # only git's newline: a name may end in " " or "\r" - ignored = _ignored_paths(top_dir) - except OSError: - return None - if ignored is None: - return None - top_real = Path(os.path.realpath(top_dir)) - try: - base_rel = Path(os.path.realpath(base)).relative_to(top_real).as_posix() - except ValueError: - return None - return GitDigestTree(top_real, "" if base_rel == "." else base_rel, ignored, *_index_blobs(top_dir)) - - -def _ignored_paths(top: str) -> frozenset[str] | None: - """The untracked, ignored paths of the work tree at ``top`` that git would not descend into (a directory by its - name), relative to ``top``; a tracked file is never listed. None if git fails; OSError if it cannot start.""" - from dokimi.process import run - - listed = run(["git", "-C", top, "ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], - timeout=120, env=_git_env(), capture_limit=None) - if not listed.ok: - return None - return frozenset(disk_path_text(name).rstrip("/") for name in listed.stdout_bytes.split(b"\0") if name) - - -def _index_blobs(top: str) -> tuple[dict[str, str], frozenset[str]]: - """The index's blob id for each tracked file that git finds unchanged in the work tree. ``hash-object`` does not read - the index, so it would fold a committed CRLF file under core.autocrlf. Flagged entries (skip-worktree, assume-unchanged) - are left out: git does not look at those files, so their disk content is hashed. Second, every path the index holds - and each directory above one (``GitDigestTree.tracked``). No blob id if any git call fails; no path if ``ls-files`` does.""" - from dokimi.process import run - - env = _git_env() - staged = run(["git", "-C", top, "ls-files", "-s", "-z"], timeout=120, env=env, capture_limit=None) - tags = run(["git", "-C", top, "ls-files", "-v", "-z"], timeout=120, env=env, capture_limit=None) - # --no-optional-locks: status refreshes its view in memory and does not rewrite the index - dirty = run(["git", "-C", top, "--no-optional-locks", "status", "--porcelain=v1", "-z", "-uno"], timeout=120, - env=env, capture_limit=None) - trusted = staged.ok and tags.ok and dirty.ok # a failed ls-files prints no entry, so ``held`` stays empty - changed = worktree_changed(dirty.stdout_bytes) | flagged(tags.stdout_bytes) - out: dict[str, str] = {} - held: set[str] = set() - for entry in staged.stdout_bytes.split(b"\0"): - meta, _, name = entry.partition(b"\t") - fields = meta.split() - if not name: - continue - rel = exact_path_text(name) - if rel is None: # a replaced name would stand for the real file that has it - continue - held.update(rel.rsplit("/", i)[0] for i in range(rel.count("/") + 1)) # the path and each directory above it - if trusted and len(fields) == 3 and fields[2] == b"0" and rel not in changed: - out[rel] = os.fsdecode(fields[1]) - return out, frozenset(held) - - -_ARG_BUDGET = 24_000 # bytes of path arguments per git call: under the smallest command line limit (Windows, 32 KB) - - -def _blob_ids(top: Path, rels: list[str], *, as_args: bool = False) -> list[str] | None: - """``git hash-object`` of each path (relative to ``top``) with the work tree's filters: on stdin in one call, or - with ``as_args`` on the command line in batches under ``_ARG_BUDGET``, for a name ``--stdin-paths`` misreads (it - splits lines, unquotes, drops a CR). A batch that fails fails them all.""" - if not as_args: - return _hash_objects(top, rels, as_args=False) - ids: list[str] = [] - batch: list[str] = [] - size = 0 - for rel in [*rels, None]: - if rel is None or (batch and size + len(os.fsencode(rel)) + 1 > _ARG_BUDGET): - got = _hash_objects(top, batch, as_args=True) - if got is None: - return None - ids += got - batch, size = [], 0 - if rel is not None: - batch.append(rel) - size += len(os.fsencode(rel)) + 1 - return ids - - -def _hash_objects(top: Path, rels: list[str], *, as_args: bool) -> list[str] | None: - from dokimi.process import run - - names = ["--", *rels] if as_args else ["--stdin-paths"] - data = None if as_args else b"".join(os.fsencode(rel) + b"\n" for rel in rels) - try: - done = run(["git", "-C", os.fspath(top), "hash-object", *names], timeout=600, env=_git_env(), - input=data, capture_limit=None) - except OSError: - return None - if not done.ok: # git's own words name the file or filter to fix - why = "timed out" if done.timed_out else done.stderr.strip() or f"exit code {done.returncode}" - raise OSError(errno.EIO, f"git hash-object failed: {why}", os.fspath(top)) - ids = [os.fsdecode(i) for i in done.stdout_bytes.split()] - return ids if len(ids) == len(rels) else None - - -def file_contents(paths: Iterable[Path], tree: GitDigestTree | None) -> dict[Path, bytes]: - """What a digest holds for each file: git's blob id for a file in ``tree`` (the index's when git finds it unchanged, - else ``hash-object``'s with the work tree's filters). Otherwise the sha256 of its bytes: no tree or a file outside - it. A ``hash-object`` that fails raises ``OSError``, as a repository git cannot read does.""" - found = list(dict.fromkeys(paths)) - out = _blob_contents(found, tree) if tree is not None else {} - for path in found: - if path not in out: - out[path] = hashlib.sha256(path.read_bytes()).digest() - return out - - -def _blob_contents(paths: list[Path], tree: GitDigestTree) -> dict[Path, bytes]: - out: dict[Path, bytes] = {} - plain: list[tuple[Path, str]] = [] - odd: list[tuple[Path, str]] = [] # names --stdin-paths misreads: hashed as arguments, so edited reads as committed - for path in paths: - rel = tree.top_rel(path) - if rel is None: - continue - if rel in tree.indexed: - out[path] = bytes.fromhex(tree.indexed[rel]) - else: - (odd if "\n" in rel or rel.startswith('"') or rel.endswith("\r") else plain).append((path, rel)) - for hashed, as_args in ((plain, False), (odd, True)): - ids = _blob_ids(tree.top, [rel for _, rel in hashed], as_args=as_args) if hashed else [] - if ids is None: # a sha256 of the bytes here would move the digest with the host load that failed git - raise OSError(errno.EIO, "git hash-object failed", os.fspath(tree.top)) - out.update({path: bytes.fromhex(blob) for (path, _), blob in zip(hashed, ids, strict=True)}) - return out - - -def file_digest(content: bytes, executable: bool) -> str: - """The digest of one file alone, as :func:`tree_digest` gives a file ``root`` (its path is ``.``).""" - return hashlib.sha256(b"F .\0" + f"{int(executable)}\0".encode() + content).hexdigest() - - -def link_text(link: Path, root: Path) -> str: - """A symlink's target as the digests hold it: as written, except an absolute target inside ``root``, which is - written relative to the link. So a tree digests the same at another checkout path (the link's text is the same). - A ``..`` in such a target is kept as written: after a link the kernel resolves it from the link's target, so - collapsing it lexically would hash two different files alike.""" - target = os.readlink(link) - if not os.path.isabs(target): - return _posix_separators(target) - target = _plain_path(target) - if link == root: # the root is hashed by its target, not walked: kept as written, so a loop through it stays a loop - return target - # the tree may be named by a path with links in it: match the target under the name as given and as resolved - # (a link that is the root itself is not resolved, or its own target would count as inside it) - anchors = [os.fspath(root)] if root.is_symlink() else [os.fspath(root), os.path.realpath(root)] - for anchor in anchors: - # Windows folds case in paths (and drive letters), so the comparison is on the normalized spelling; the target - # keeps its own spelling in the text it returns - key, key_anchor = os.path.normcase(target), os.path.normcase(anchor) - try: - inside = os.path.commonpath([key, key_anchor]) == key_anchor and key.startswith(key_anchor) - except ValueError: # different drives, or a relative path mixed in - continue - if inside: - rest = [part for part in target[len(anchor):].split(os.sep) if part not in ("", ".")] - depth = len(link.relative_to(root).parent.parts) # the link's directory, as the text is read from there - slash = "/" if target.endswith((os.sep, os.sep + ".")) else "" # "x/" and "x/." need a directory - if ".." in rest: - # a target whose ".." leads out of the tree (and does not come back in) is external: hashed as written, - # so two trees whose external targets differ do not digest alike - lexical = os.path.normcase(os.path.normpath(target)) - if lexical != key_anchor and not lexical.startswith(key_anchor.rstrip(os.sep) + os.sep): - return target - # a ".." that leaves the tree and comes back in (tree/../tree/x) is folded, so the name of the checkout's - # directory does not reach the digest; the ".." after a link stays, as the kernel reads it - settled = _settled(target) - key_settled = os.path.normcase(settled) - if key_settled != key_anchor and not key_settled.startswith(key_anchor.rstrip(os.sep) + os.sep): - return target - rest = [part for part in settled[len(anchor):].split(os.sep) if part not in ("", ".")] - return ("/".join([".."] * depth + rest) or ".") + slash # the root itself is "." before the slash - here = os.path.join(anchor, *link.relative_to(root).parent.parts) - return os.path.relpath(os.path.join(anchor, *rest), here).replace(os.sep, "/") + slash - return target # outside the tree: as written - - -def _tracked_modes(base: Path, spec: str) -> dict[str, bool]: - """The executable bit git records (mode 100755) for each file ``spec`` names under ``base``, keyed by the path - relative to ``base``. Empty when git cannot say (no git, or ``base`` is not in a repository).""" - from dokimi.process import Env, run - - # GIT_* variables (a hook's GIT_DIR or GIT_INDEX_FILE) would point git at some other repository's index - env = Env.only(allow=[k for k in os.environ if not k.startswith("GIT_")]) - try: - # literal: the name is a path, not a pattern; no capture limit: a large tree's listing must be read whole - done = run(["git", "--literal-pathspecs", "-C", os.fspath(base), "ls-files", "--stage", "-z", "--", spec], - timeout=60, env=env, capture_limit=None) - except OSError: - return {} - if not done.ok: - return {} - modes: dict[str, bool] = {} - for record in done.stdout_bytes.split(b"\0"): - meta, tab, name = record.partition(b"\t") - key = exact_path_text(name) - if tab and key is not None: # a name Windows cannot decode would take the key of a real file - modes[key] = meta.split()[0] == b"100755" - return modes - - -def _entries(root: Path, skip: tuple[str, ...], *, strict: bool, drop: Callable[[Path], bool] | None = None) -> list[Path]: - """Every entry under ``root``, directories included, a symlink as itself and never descended into. Entries under - a ``skip`` prefix, and those ``drop`` names, are not read. Non-strict is ``rglob``, which skips a directory it cannot - read (and the files behind it); strict raises that error, so a digest cannot leave out what it could not read.""" - if not strict: - return [p for p in root.rglob("*") if drop is None or not drop(p)] - found: list[Path] = [] - pending = [root] - while pending: - with os.scandir(pending.pop()) as it: - for entry in it: - path = Path(entry.path) - rel = path.relative_to(root).as_posix() - if any(rel == e or rel.startswith(e + "/") for e in skip) or (drop is not None and drop(path)): - continue - found.append(path) - if entry.is_dir(follow_symlinks=False): - pending.append(path) - return found - - -def tree_digest(root: Path, *, exclude: Iterable[str] = (), strict: bool = False, - tracked: Mapping[str, bool] | None = None, git: GitDigestTree | bool | None = False) -> str: - """sha256 (bare hex) over every path, mode bit and byte under ``root``; a link by its target. - - A file ``root`` digests as itself (its path is ``.``), and so does a symlink ``root`` - (by its target, dangling or not; it is not walked). Entries whose path, relative to - ``root``, equals one of ``exclude`` or sits under it are left out, so a skill's digest can - leave its eval directory out. Output is deterministic: sorted walk, no timestamps. - - The same tree digests the same on every OS: a file's mode bit is the one git records (the index, so a - Windows checkout with no exec bit still matches), and an untracked file takes its owner's exec bit - from the disk. A link inside ``root`` with an absolute target is hashed by a relative target (see - ``link_text``); one pointing outside ``root`` is hashed as written. - - ``strict``: a directory under ``root`` that cannot be read raises its OSError (the default skips it silently). - ``tracked``: the executable bits git records, keyed by path relative to ``root`` (to its parent for a file root), - as :func:`_tracked_modes` returns them; None reads them from git. A caller digesting many files reads them once. - ``git``: hash what git stores, not the bytes on disk. A file digests as its blob id (:func:`file_contents`), so a - CRLF checkout with core.autocrlf matches the LF one; what git leaves out (ignored paths, by a nested repository's - own rules too, and a nested ``.git``) is skipped, and so are directories, which git does not store. A ``GitDigestTree`` - is a work tree already read; True reads it from ``root``; None (or no work tree) hashes the bytes on disk and - leaves nothing out. - """ - skip = tuple(e.strip("/") for e in exclude) - # a symlink is never looked through here: its target may be unreadable (or gone), and it digests by its text - is_link = root.is_symlink() - as_file = not is_link and root.is_file() - if isinstance(git, GitDigestTree): - tree: GitDigestTree | None = git - else: - tree = git_tree(root.parent if is_link or as_file else root) if git else None - # sorted by the parts of the relative path, compared as code points: the same order on every OS (Path - # ordering folds case on Windows) - entries = ([root] if is_link or as_file - else sorted(_entries(root, skip, strict=strict, drop=tree.skipped if tree else None), - key=lambda p: p.relative_to(root).parts)) - if tree is not None: - entries = [p for p in entries if p.is_symlink() or not p.is_dir()] - base, spec = (root.parent, root.name) if as_file else (root, ".") - modes: Mapping[str, bool] - if tracked is None: - modes = _tracked_modes(base, spec) if any(not p.is_symlink() and p.is_file() for p in entries) else {} - else: # the caller read the index already: keyed as below, by the path relative to ``base`` - modes = tracked - holds = file_contents([p for p in entries if not p.is_symlink() and p.is_file()], tree) - h = hashlib.sha256() - for path in entries: - rel = "." if path == root else path.relative_to(root).as_posix() - if any(rel == e or rel.startswith(e + "/") for e in skip): - continue - # names and link targets are bytes on POSIX and may hold undecodable bytes: encode them as the OS does - name = os.fsencode(rel) - if path.is_symlink(): - h.update(b"L " + name + b"\0" + os.fsencode(link_text(path, root)) + b"\0") - elif path.is_file(): - key = path.relative_to(base).as_posix() - if key in modes: - executable = modes[key] - else: - executable = bool(os.lstat(path).st_mode & stat.S_IXUSR) - h.update(b"F " + name + f"\0{int(executable)}\0".encode()) - h.update(holds[path]) - elif path.is_dir(): - h.update(b"D " + name + b"\0") - return h.hexdigest() - - -def retry_writable(func: Any, path: str, _exc: Any) -> None: - """``shutil.rmtree`` ``onerror`` hook: set the write bit on ``path`` and retry once. - - Windows will not delete a read-only file, and git leaves its object files - read-only. A symlink is left alone, since chmod would follow it out of the - tree. A retry that still fails is ignored; the caller checks what is left. - Only the delete calls are retried: on POSIX ``rmtree`` also reports a failed - ``os.open`` or ``os.scandir`` (an unreadable dir), which ``func(path)`` would - call with the wrong arguments and raise ``TypeError``. - """ - import stat - - try: - mode = os.lstat(path).st_mode - if not stat.S_ISLNK(mode): - os.chmod(path, stat.S_IMODE(mode) | stat.S_IWRITE) - if func in (os.unlink, os.remove, os.rmdir): - func(path) - except OSError: - pass - - -# Bedrock cross-region inference profiles: the same model served from another region. They are dropped -# from any provider's name, not only Bedrock's: no non-Bedrock id is known to start with one of them. -_REGION_PROFILES = ("us-gov.", "global.", "apac.", "us.", "eu.", "jp.", "au.", "ca.") - - -# Leading segments that name a route (provider or gateway: ``anthropic/``, ``openrouter/``), not a model; any other -# segment (an HF org such as ``meta-llama/``) is part of the id. Holds ``llm.ANSWER_PROVIDERS`` (test-pinned) + litellm routes. -_ROUTES = frozenset({ - "openai", "openai-codex", "anthropic", "google", "gemini", "google-vertex", "openrouter", "amazon-bedrock", - "bedrock", "converse", "vertex_ai", "azure", "azure_ai", "models", "groq", "ollama", "mistral", "deepseek", - "together_ai", "fireworks_ai", "xai", "cohere", "huggingface", "claude-cli", "codex-cli", "copilot-cli", -}) - - -# Vendors whose Bedrock ids start with ``vendor.`` (``anthropic.claude-...``, ``zai.glm-4.7``, ``xai.grok-4.6``). -_VENDORS = frozenset({ - "ai21", "amazon", "anthropic", "cohere", "deepseek", "google", "luma", "meta", "minimax", "mistral", - "moonshotai", "nvidia", "openai", "qwen", "stability", "twelvelabs", "writer", "xai", "zai", -}) -_VENDOR_SLUGS = {"z-ai": "zai", "x-ai": "xai", "mistralai": "mistral"} # OpenRouter's spelling of a vendor -_BEDROCK_ARN = re.compile(r"(?:^|/)arn:aws[a-z-]*:bedrock:[a-z0-9-]*:\d*:(?:inference-profile|foundation-model)/") - - -def _model_core(model: str) -> tuple[str, str | None]: - """A model name reduced to ``(id, snapshot date or None)``. A snapshot is ``-YYYYMMDD`` or OpenAI's ``-YYYY-MM-DD``. - - The route goes (``openrouter/anthropic/``, ``bedrock/``, ``vertex_ai/``, an ARN's - ``inference-profile/``), and so do the case, the region profile (``eu.``) and a Bedrock - revision (``-v1:0`` or ``-1:0``). Vertex's ``@20250929`` is the snapshot ``-20250929``. The organization of an - ``org/name`` id stays, so a re-upload under another organization is another model; a known vendor - (``qwen/``, ``z-ai/``) goes, as its Bedrock ``vendor.`` prefix does, unless a ``huggingface/`` route precedes it. - """ - # sonnet[1m] is the same model with a larger window: the 1M context form goes, and no other bracket - # (qwen3[8b] and qwen3[32b] are two models) - name = re.sub(r"\[1m\]$", "", (model or "").strip().lower()) - arn = _BEDROCK_ARN.search(name) # only a Bedrock ARN's tail: ``foundation-model/X`` alone is an org/name id - if arn: - name = name[arn.end():] - parts = name.split("/") - hub = False - while len(parts) > 1 and parts[0] in _ROUTES: - hub = parts.pop(0) == "huggingface" - if hub: # a Hub id: the route goes, its organization stays, even behind another route - break - if not hub and len(parts) > 1 and _VENDOR_SLUGS.get(parts[0], parts[0]) in _VENDORS: - parts.pop(0) # OpenRouter's ``qwen/X`` is Bedrock's ``qwen.X``: the vendor, not an organization - name = "/".join(parts) - name = re.sub(r"(? tuple[str | None, str | None]: - """``(id, snapshot date or None)`` of a model name with its route, region profile and vendor prefix dropped; - the id is ``None`` for a name with no id. Two names with equal identities are one model and one snapshot.""" - base, date = _model_core(model) - if not base: - return None, date - # a known vendor before the first dot (``anthropic.``, ``openai.``, as in Bedrock ids) is dropped; any other - # dotted name is part of the id (``alice.model``), and so is a dot after a digit or a dash (``gpt-4.1``) - head, dot, rest = base.partition(".") - ident = rest if dot and head in _VENDORS else base - return (ident if re.search(r"[a-z0-9]", ident) else None), date # separators alone name no model - - -def same_model(a: str, b: str) -> bool: - """Whether two model names are one model. - - The same id matches, and so does a dated snapshot and its undated alias (the alias runs - some snapshot of it), or the same id behind another route or region profile. Two dated - ids match only on the same date. A Claude CLI alias (``sonnet``, ``opus[1m]``) matches a - full id of its family, since the CLI runs the alias as one of them (which one is not known here). - - The provider is not part of the identity: the same weights on Bedrock and on the direct - API are still one model for the self-judge warning and for a baseline's model check. - """ - (base_a, date_a), (base_b, date_b) = model_identity(a), model_identity(b) - if base_a is None or base_b is None: - return False - # The alias rule applies only when neither side keeps an organization: ``myorg/sonnet`` is not the CLI's sonnet. - if "/" not in base_a and "/" not in base_b and (llm_cli.is_alias(a) or llm_cli.is_alias(b)): - family_a = llm_cli.family(a) - return family_a is not None and family_a == llm_cli.family(b) - if date_a and date_b and date_a != date_b: - return False - return base_a == base_b - - -def same_evaluator(answer_model: str, judge_model: str) -> bool: - """Whether the answer and judge are one model, for the independence warning and its stored flag.""" - return same_model(answer_model, judge_model) - - -def warn_judge_independence( - answer_provider: str, - answer_model: str, - judge_provider: str, - judge_model: str, - context: str = "run", - roles: tuple[str, str] = ("answer", "judge"), -) -> bool: - """Emit a non-fatal warning when answer and judge are the same model (on any provider route). - - ``roles`` names the two sides in the message, e.g. ``("generator", "reviewer")``. - """ - import sys - - same = same_evaluator(answer_model, judge_model) - if same: - first, second = roles - print( - "⚠ Evaluator independence warning " - f"({context}): {first} model equals {second} model " - f"[{answer_provider}/{answer_model}] and [{judge_provider}/{judge_model}] — potential self-referential bias.", - file=sys.stderr, - ) - return same - - -def warn_recorded_self_judge( - data: Any, - judges: Sequence[tuple[str, str]], - context: str, - roles: tuple[str, str] = ("answer", "judge"), -) -> bool: - """Warn (never refuse) for each ``(model, provider)`` judge that is the model a file records. - - ``data`` is a parsed answers or questions file; its top-level ``model`` and ``provider`` - name what produced it. Silent, and False, when either is missing. - """ - if not isinstance(data, Mapping): - return False - model, provider = data.get("model"), data.get("provider") - if not (isinstance(model, str) and isinstance(provider, str)): - return False - hits = [warn_judge_independence(provider, model, jp, jm, context=context, roles=roles) - for jm, jp in dict.fromkeys(judges)] - return any(hits) - - -def question_id(q: Dict[str, Any]) -> Any: - """The question's ``id`` or ``question_id``; ``None`` when neither is set. - - ``0`` is an id (``questions.v1`` allows integer ids), so ``q.get("id") or ...`` - — which reads it as missing — is not a substitute. - """ - for key in ("id", "question_id"): - if q.get(key) not in (None, ""): - return q[key] - return None - - -class InputError(ValueError): - """A user-supplied input that cannot be used: missing, unreadable, not UTF-8 or JSON, or the wrong shape. - - Library loaders raise it (or a subclass) with a message that names the file, and do not - print or exit. ``cli.main`` prints ``Error: `` and exits 2, the code for bad input; - exit 1 stays the verdict of ``--strict`` gates and ``eval judge-validity``. A ``ValueError``, - so code that already catches bad values keeps catching these. - """ - - -_BEDROCK_ID = re.compile(r"[a-z0-9]+\.", re.IGNORECASE) - - -def check_bedrock_model(provider: str, model: str) -> None: - """Raise :class:`InputError` for a judge name Bedrock cannot run, before a run pays for answers. - - A Bedrock id starts with a region or vendor and a dot (``us.anthropic.``, ``amazon.``); a dot - after a hyphen is a version (``claude-sonnet-4.5``), not an id. An ARN or a litellm route has a - ``/``, and a bare name runs only when ``BEDROCK_MODEL_IDS`` maps it to a profile. - """ - if (provider == "amazon-bedrock" and "/" not in model and not _BEDROCK_ID.match(model) - and model not in BEDROCK_MODEL_IDS): - raise InputError(f"Bedrock has no model '{model}': pass its inference profile id " - f"(us.anthropic.) or an ARN; the bare names that run are " - f"{', '.join(BEDROCK_MODEL_IDS)}") - - -def refuse_device(path: str | os.PathLike[str], flag: str | None = None) -> None: - """:class:`InputError` `` : not a file`` for a device or a socket, before it is read whole. - - A regular file, a pipe (``<(cat x.json)``) and a directory pass; so does a path that cannot be - stat'ed, left to the read to report. ``/dev/zero`` would otherwise be read until memory runs out - (https://github.com/intel/dokimi/issues/504). The path is stat'ed as :class:`~pathlib.Path` spells it, - the way the callers read it: ``/dev/zero/`` and ``/dev/zero/.`` are ``/dev/zero`` to ``Path``. - """ - try: - mode = Path(path).stat().st_mode # not os.stat(path): ENOTDIR on /dev/zero/, which Path opens - except (OSError, ValueError): # missing, a path under a file, an embedded null byte - return - if not (stat.S_ISREG(mode) or stat.S_ISFIFO(mode) or stat.S_ISDIR(mode)): - raise InputError(f"{flag} {path}: not a file" if flag else f"{path}: not a file") - - -def read_json_input(path: str | os.PathLike[str], *, flag: str | None = None) -> Any: - """The parsed JSON at ``path``: :func:`read_json_input_bytes` without the bytes.""" - return read_json_input_bytes(path, flag=flag)[1] - - -def read_json_input_bytes(path: str | os.PathLike[str], *, flag: str | None = None) -> tuple[bytes, Any]: - """The bytes at ``path``, read once, and the JSON they hold, or :class:`InputError` naming the file and why: - missing or unreadable, a device (:func:`refuse_device`), not UTF-8, not JSON or nested too deeply to parse. - With ``flag`` (the option the file was given to) the message is `` : ``. An empty path is - refused first, quoted (``--answers "": no file given``), as ``Path("")`` would read the current directory.""" - if os.fspath(path) == "": - raise InputError(f'{flag} "": no file given' if flag else 'cannot read "": no file given') - refuse_device(path, flag) - try: - raw = Path(path).read_bytes() - return raw, json.loads(raw.decode("utf-8")) - except UnicodeDecodeError as exc: - raise InputError(f"{flag} {path}: {exc}" if flag else f"{path} is not UTF-8 text: {exc}") from exc - except (json.JSONDecodeError, RecursionError) as exc: # deep nesting is named as bad JSON, as on main - raise InputError(f"{flag} {path}: {exc}" if flag else f"{path} is not valid JSON: {exc}") from exc - except (OSError, ValueError) as exc: # ValueError: e.g. "embedded null byte" in the path, from pathlib - reason = getattr(exc, "strerror", None) or exc - raise InputError(f"{flag} {path}: {reason}" if flag else f"cannot read {path}: {reason}") from exc +"""Compatibility imports for the public utilities formerly defined here. + +Private helpers and test patch targets live in their defining modules, such as +``dokimi.digest`` and ``dokimi.files``. Reassigning a public name here only +changes this module's alias. +""" + +from dokimi.digest import GitDigestTree, digest_text, file_contents, file_digest, git_tree, key_bytes, link_text, tree_digest +from dokimi.files import InputError, is_symlink_loop, read_json_input, read_json_input_bytes, refuse_device, retry_writable +from dokimi.frontmatter import describe_yaml_error, parse_frontmatter, parse_frontmatter_strict +from dokimi.model_names import (check_bedrock_model, model_identity, same_evaluator, same_model, + warn_judge_independence, warn_recorded_self_judge) +from dokimi.records import question_id + +__all__ = [ + "GitDigestTree", "InputError", "check_bedrock_model", "describe_yaml_error", "digest_text", "file_contents", + "file_digest", "git_tree", "is_symlink_loop", "key_bytes", "link_text", "model_identity", "parse_frontmatter", + "parse_frontmatter_strict", "question_id", "read_json_input", "read_json_input_bytes", "refuse_device", + "retry_writable", "same_evaluator", "same_model", "tree_digest", "warn_judge_independence", + "warn_recorded_self_judge", +] diff --git a/dokimi/fuzz/targets.py b/dokimi/fuzz/targets.py index bd7f668ac2..0bd75aa31e 100644 --- a/dokimi/fuzz/targets.py +++ b/dokimi/fuzz/targets.py @@ -20,7 +20,7 @@ from dokimi.eval.reference_checks import parse_json from dokimi.llm_json import extract_json_array, extract_json_object from dokimi.novelty.retention import parse_verdict -from dokimi.utils import parse_frontmatter, parse_frontmatter_strict +from dokimi.frontmatter import parse_frontmatter, parse_frontmatter_strict def yes_no(text: str) -> None: diff --git a/dokimi/scripts/check_treatment_batch.py b/dokimi/scripts/check_treatment_batch.py index 32de9d6633..ab93bff4f4 100755 --- a/dokimi/scripts/check_treatment_batch.py +++ b/dokimi/scripts/check_treatment_batch.py @@ -112,7 +112,7 @@ def expected_n(path: Path, artifact: dict, sizes: dict[str, int]) -> tuple[int | def profile_digest(profile_path: Path) -> str: """The digest the artifacts must carry for *profile_path*'s current text.""" from dokimi.agent_profiles import load_agent_profile - from dokimi.utils import digest_text + from dokimi.digest import digest_text return digest_text(load_agent_profile(profile_path).system_prompt) diff --git a/dokimi/scripts/sync_skilltext_profile.py b/dokimi/scripts/sync_skilltext_profile.py index 9dea58174f..356c80d864 100755 --- a/dokimi/scripts/sync_skilltext_profile.py +++ b/dokimi/scripts/sync_skilltext_profile.py @@ -35,7 +35,7 @@ sys.path.insert(0, str(REPO_ROOT)) from dokimi.skills import load_skill # noqa: E402 -from dokimi.utils import parse_frontmatter # noqa: E402 +from dokimi.frontmatter import parse_frontmatter # noqa: E402 # Must match the cap the skill arm renders with, in `treatments/arms.py`. A different cap # here would make the control differ from the skill arm by content as well as channel. diff --git a/dokimi/tests/cli_refusal.py b/dokimi/tests/cli_refusal.py index ecae3324c5..e55239cdc8 100644 --- a/dokimi/tests/cli_refusal.py +++ b/dokimi/tests/cli_refusal.py @@ -11,7 +11,7 @@ from typing import Iterator from dokimi import llm_cli -from dokimi.utils import InputError +from dokimi.files import InputError class Outcome: diff --git a/dokimi/tests/test_687_low.py b/dokimi/tests/test_687_low.py index 52202ca040..873af30e95 100644 --- a/dokimi/tests/test_687_low.py +++ b/dokimi/tests/test_687_low.py @@ -20,7 +20,7 @@ from dokimi.ingest.docling_loader import SOURCES_NAME, materialize_markdown from dokimi.personas.analyzer import PersonaAnalyzer from dokimi.process import reply -from dokimi.utils import InputError +from dokimi.files import InputError # _hermetic is autouse: no operator Claude settings, provider env or host `claude` reach a test. from tests.test_docker_solver_harness import _fixture_task, _hermetic, _pipeline # noqa: F401 diff --git a/dokimi/tests/test_agent_profiles.py b/dokimi/tests/test_agent_profiles.py index 8d26cf12c6..2dbb49b254 100644 --- a/dokimi/tests/test_agent_profiles.py +++ b/dokimi/tests/test_agent_profiles.py @@ -16,7 +16,7 @@ SkillTreatment, ) from dokimi.treatments.factory import create_treatment, create_treatments -from dokimi.utils import digest_text +from dokimi.digest import digest_text PROFILE_DIR = Path(__file__).resolve().parents[1] / "data" / "agent_profiles" SKILL_DIR = Path(__file__).resolve().parents[1] / "data" / "skills" diff --git a/dokimi/tests/test_agent_run.py b/dokimi/tests/test_agent_run.py index b10b91c99d..34ca47c029 100644 --- a/dokimi/tests/test_agent_run.py +++ b/dokimi/tests/test_agent_run.py @@ -19,7 +19,7 @@ from dokimi.artifacts import ArtifactValidationError, save_artifact, validate_artifact from dokimi.harnesses.models import HarnessResult from dokimi.harnesses.tasks import TaskSpec -from dokimi.utils import InputError +from dokimi.files import InputError def _done(argv, *records, rc=0, stderr=""): diff --git a/dokimi/tests/test_arm_runner.py b/dokimi/tests/test_arm_runner.py index f360cc73bd..9f0e855930 100644 --- a/dokimi/tests/test_arm_runner.py +++ b/dokimi/tests/test_arm_runner.py @@ -1125,7 +1125,7 @@ def test_material_that_does_not_match_its_digest_is_not_used(monkeypatch, skill_ def test_an_artifact_without_materials_falls_back_as_before(): from dokimi.eval.judge_context import JudgeContextStore - from dokimi.utils import digest_text + from dokimi.digest import digest_text # No judge_materials key at all; record has digest but material is missing store = JudgeContextStore.from_artifact({ @@ -1138,7 +1138,7 @@ def test_an_artifact_without_materials_falls_back_as_before(): def test_judge_materials_guard_requires_material_for_stored_scores(caplog): """The guard against missing material does not skip records with no digest.""" from dokimi.eval.judge_context import JudgeContextStore - from dokimi.utils import digest_text + from dokimi.digest import digest_text # Record with no digest — should be skipped without error. store = JudgeContextStore.from_artifact({ diff --git a/dokimi/tests/test_arm_runner_incremental.py b/dokimi/tests/test_arm_runner_incremental.py index 9e6656e137..c7a382a70f 100644 --- a/dokimi/tests/test_arm_runner_incremental.py +++ b/dokimi/tests/test_arm_runner_incremental.py @@ -27,7 +27,7 @@ from dokimi.commands.arms import _Partial from dokimi.treatments import BaselineTreatment from dokimi.treatments.base import AgentConfig, Treatment -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_refusal import refusal PROJECT = Path(__file__).resolve().parents[1] diff --git a/dokimi/tests/test_artifacts.py b/dokimi/tests/test_artifacts.py index 5d5fd74031..f09eefb19d 100644 --- a/dokimi/tests/test_artifacts.py +++ b/dokimi/tests/test_artifacts.py @@ -670,7 +670,7 @@ def test_a_rejected_payload_with_a_surrogate_is_kept_as_utf8(tmp_path, value, lo def test_a_payload_kept_for_a_malformed_run_id_holds_a_surrogate_as_utf8(monkeypatch, tmp_path): from dokimi.artifacts import RUN_ID_ENV - from dokimi.utils import InputError + from dokimi.files import InputError monkeypatch.setenv(RUN_ID_ENV, "-bad") diff --git a/dokimi/tests/test_atoms_partial_status.py b/dokimi/tests/test_atoms_partial_status.py index 79ea716e6a..a72d575f70 100644 --- a/dokimi/tests/test_atoms_partial_status.py +++ b/dokimi/tests/test_atoms_partial_status.py @@ -12,7 +12,7 @@ from dokimi.novelty.atoms import load_atoms_record from dokimi.novelty.atoms_refusal import has_visible_text from dokimi.novelty.client import SpendCap, SpendCapReached -from dokimi.utils import InputError +from dokimi.files import InputError _BLOCK = {"reason": "spend_cap", "message": "stopped"} diff --git a/dokimi/tests/test_baseline_deep_nesting.py b/dokimi/tests/test_baseline_deep_nesting.py index 7de1ee32da..cb61e88595 100644 --- a/dokimi/tests/test_baseline_deep_nesting.py +++ b/dokimi/tests/test_baseline_deep_nesting.py @@ -9,7 +9,7 @@ import pytest from dokimi.commands.repo_scan import baseline_from -from dokimi.utils import InputError +from dokimi.files import InputError def _baseline_with_nesting(tmp_path, depth: int) -> argparse.Namespace: diff --git a/dokimi/tests/test_baseline_refs.py b/dokimi/tests/test_baseline_refs.py index e0a9a8b8b3..613751d3be 100644 --- a/dokimi/tests/test_baseline_refs.py +++ b/dokimi/tests/test_baseline_refs.py @@ -18,8 +18,8 @@ from dokimi.artifacts import save_artifact from dokimi.commands import baseline as manifest_baseline from dokimi.commands.repo_scan import baseline_from +from dokimi.files import InputError from dokimi.runs import baseline -from dokimi.utils import InputError from test_plugin_delta import _arms_artifact diff --git a/dokimi/tests/test_bedrock_model_ids.py b/dokimi/tests/test_bedrock_model_ids.py index d31acbdd30..08d8a3b63e 100644 --- a/dokimi/tests/test_bedrock_model_ids.py +++ b/dokimi/tests/test_bedrock_model_ids.py @@ -59,6 +59,6 @@ def test_the_default_judge_resolves_on_bedrock(monkeypatch): def test_an_unknown_bare_name_is_left_alone(monkeypatch): - # A judge run refuses it before any answer (utils.check_bedrock_model, test_llm_callers.py). + # A judge run refuses it before any answer (model_names.check_bedrock_model, test_llm_callers.py). monkeypatch.setenv("ANTHROPIC_DEFAULT_SONNET_MODEL", "us.anthropic.sonnet") assert bedrock("some-model") == "bedrock/some-model" diff --git a/dokimi/tests/test_bundled_skills.py b/dokimi/tests/test_bundled_skills.py index ad26b193bc..c0ec2981b5 100644 --- a/dokimi/tests/test_bundled_skills.py +++ b/dokimi/tests/test_bundled_skills.py @@ -20,7 +20,7 @@ from dokimi.harnesses.registry import known_harnesses from dokimi.harnesses.skill_treatment import check_skill from dokimi.repos.budget import LISTING_TEXT_CAP -from dokimi.utils import parse_frontmatter +from dokimi.frontmatter import parse_frontmatter SKILLS = Path(__file__).resolve().parents[1] / "data" / "skills" BUNDLED = sorted(d for d in SKILLS.iterdir() if (d / "SKILL.md").is_file()) diff --git a/dokimi/tests/test_cache_dir_label.py b/dokimi/tests/test_cache_dir_label.py index 4590e09ff0..e726a298c0 100644 --- a/dokimi/tests/test_cache_dir_label.py +++ b/dokimi/tests/test_cache_dir_label.py @@ -10,7 +10,7 @@ import pytest from dokimi.commands.cache_dir import CACHE_USE, RETENTION_USE, usable_cache_dir -from dokimi.utils import InputError +from dokimi.files import InputError def _message(raw, **kwargs) -> str: diff --git a/dokimi/tests/test_catalog_command.py b/dokimi/tests/test_catalog_command.py index 3bede71136..28e171ca78 100644 --- a/dokimi/tests/test_catalog_command.py +++ b/dokimi/tests/test_catalog_command.py @@ -10,7 +10,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.cli import build_parser _DEEP_FRONTMATTER = b"---\nname: " + b"[" * 100000 + b"\n---\nbody\n" diff --git a/dokimi/tests/test_catalog_ignore.py b/dokimi/tests/test_catalog_ignore.py index ac1b59397e..13ad0d4ac1 100644 --- a/dokimi/tests/test_catalog_ignore.py +++ b/dokimi/tests/test_catalog_ignore.py @@ -15,7 +15,7 @@ import dokimi.external as external from dokimi.cli import build_parser from dokimi.external.validate import FINDING_CODES -from dokimi.utils import InputError +from dokimi.files import InputError def _skill(root: Path, rel: str, name: str, description: str = "Use for things.") -> None: diff --git a/dokimi/tests/test_catalog_jsonl.py b/dokimi/tests/test_catalog_jsonl.py index aebb434194..b193aa76c5 100644 --- a/dokimi/tests/test_catalog_jsonl.py +++ b/dokimi/tests/test_catalog_jsonl.py @@ -12,7 +12,7 @@ import pytest from dokimi.cli import build_parser -from dokimi.utils import InputError +from dokimi.files import InputError def _skill(root: Path, name: str) -> None: diff --git a/dokimi/tests/test_catalog_listing_budget.py b/dokimi/tests/test_catalog_listing_budget.py index 7746e42f21..aa87c96111 100644 --- a/dokimi/tests/test_catalog_listing_budget.py +++ b/dokimi/tests/test_catalog_listing_budget.py @@ -11,7 +11,7 @@ import pytest from dokimi.cli import build_parser -from dokimi.utils import InputError +from dokimi.files import InputError ENTRY = "alpha: Use when alpha runs." # 27 characters: the name, ": ", the description diff --git a/dokimi/tests/test_catalog_no_frontmatter.py b/dokimi/tests/test_catalog_no_frontmatter.py index e83d179255..3417c28f99 100644 --- a/dokimi/tests/test_catalog_no_frontmatter.py +++ b/dokimi/tests/test_catalog_no_frontmatter.py @@ -19,7 +19,7 @@ from dokimi.cli import build_parser from dokimi.external import read_skill_manifest, review_skills from dokimi.external.no_frontmatter import no_frontmatter_message -from dokimi.utils import InputError +from dokimi.files import InputError from tests.growth_timing import GROWTH_LIMIT, growth diff --git a/dokimi/tests/test_catalog_novelty.py b/dokimi/tests/test_catalog_novelty.py index 1129d3e767..bfd13a72df 100644 --- a/dokimi/tests/test_catalog_novelty.py +++ b/dokimi/tests/test_catalog_novelty.py @@ -18,7 +18,7 @@ from dokimi.metrics.usage import UsageRecord from dokimi.novelty.client import SpendCapReached from dokimi.novelty import cost as novelty_cost -from dokimi.utils import InputError +from dokimi.files import InputError from tests.test_novelty_analyze import SKILL, _scripted from tests.waiting import wait_for_event, wait_until @@ -623,13 +623,13 @@ def test_identical_skill_copies_are_one_skill_and_the_help_says_so(tmp_path, cap def test_a_tree_digest_failure_leaves_no_digest_so_resume_runs_the_skill_again(tmp_path, monkeypatch): - import dokimi.utils as utils + import dokimi.digest as digest from dokimi.commands.catalog_novelty import _items def broken(*args, **kwargs): raise OSError("unreadable") - monkeypatch.setattr(utils, "tree_digest", broken) + monkeypatch.setattr(digest, "tree_digest", broken) items = _items(_root(tmp_path), None) assert [i.sha256 for i in items] == [None, None] diff --git a/dokimi/tests/test_catalog_online.py b/dokimi/tests/test_catalog_online.py index 4193ab0c0a..dfce86ca55 100644 --- a/dokimi/tests/test_catalog_online.py +++ b/dokimi/tests/test_catalog_online.py @@ -13,7 +13,7 @@ from dokimi.cli import build_parser from dokimi.external import online_checks, read_skill_manifest, review_skills -from dokimi.utils import InputError +from dokimi.files import InputError from tests.growth_timing import GROWTH_LIMIT, growth from tests.test_catalog_validate import _skill diff --git a/dokimi/tests/test_catalog_online_edges.py b/dokimi/tests/test_catalog_online_edges.py index bdd9ea71d5..85f9e97b33 100644 --- a/dokimi/tests/test_catalog_online_edges.py +++ b/dokimi/tests/test_catalog_online_edges.py @@ -11,7 +11,7 @@ import pytest from dokimi.external import online_checks -from dokimi.utils import InputError +from dokimi.files import InputError from tests.test_catalog_online import _no_environment_proxy # noqa: F401 (autouse) diff --git a/dokimi/tests/test_catalog_provenance.py b/dokimi/tests/test_catalog_provenance.py index e888940247..df99a1e014 100644 --- a/dokimi/tests/test_catalog_provenance.py +++ b/dokimi/tests/test_catalog_provenance.py @@ -19,7 +19,7 @@ from dokimi.cli import build_parser from dokimi.external import upstream -from dokimi.utils import InputError +from dokimi.files import InputError V1 = ( "---\nname: pdf\ndescription: Use when reading PDFs and forms.\nlicense: MIT\n---\n" diff --git a/dokimi/tests/test_catalog_repair_receipt.py b/dokimi/tests/test_catalog_repair_receipt.py index 1f79e86ed9..5931394672 100644 --- a/dokimi/tests/test_catalog_repair_receipt.py +++ b/dokimi/tests/test_catalog_repair_receipt.py @@ -12,7 +12,7 @@ from dokimi.cli import build_parser from dokimi.external import online_checks from dokimi.external.repair_receipt import repair_receipt -from dokimi.utils import InputError +from dokimi.files import InputError # `_no_environment_proxy` is an autouse fixture: importing it applies it to every test in this module. from tests.test_catalog_online import Web, _no_environment_proxy, _one_skill, _scan_capture # noqa: F401 from tests.test_catalog_validate import _scan_json, _skill diff --git a/dokimi/tests/test_catalog_routing_compare.py b/dokimi/tests/test_catalog_routing_compare.py index d0104378ea..5fb6a9aad7 100644 --- a/dokimi/tests/test_catalog_routing_compare.py +++ b/dokimi/tests/test_catalog_routing_compare.py @@ -14,7 +14,7 @@ from dokimi.novelty.client import LLMClient from dokimi.novelty.routing import Candidate, RoutingInputError from dokimi.novelty.routing_compare import compare_runs, load_run -from dokimi.utils import InputError +from dokimi.files import InputError def _row(query, pick, gold="g", **extra): diff --git a/dokimi/tests/test_catalog_scan_unlistable.py b/dokimi/tests/test_catalog_scan_unlistable.py index dd1fccb3e6..86aea087ba 100644 --- a/dokimi/tests/test_catalog_scan_unlistable.py +++ b/dokimi/tests/test_catalog_scan_unlistable.py @@ -17,7 +17,7 @@ from dokimi import __version__ from dokimi.commands.catalog_scan import _load_prior, skill_dir_digest -from dokimi.utils import tree_digest +from dokimi.digest import tree_digest def _skill(tmp_path: Path) -> Path: diff --git a/dokimi/tests/test_catalog_upstream_findings.py b/dokimi/tests/test_catalog_upstream_findings.py index 0322873d5f..9e55588652 100644 --- a/dokimi/tests/test_catalog_upstream_findings.py +++ b/dokimi/tests/test_catalog_upstream_findings.py @@ -14,7 +14,7 @@ import pytest from dokimi.cli import build_parser -from dokimi.utils import InputError +from dokimi.files import InputError HEAD_TEXT = ( "---\nname: pdf\ndescription: Use when reading PDFs and forms.\nlicense: MIT\nallowed-tools: Read\n---\n" diff --git a/dokimi/tests/test_catalog_validate.py b/dokimi/tests/test_catalog_validate.py index a7c3ab1f64..376c474420 100644 --- a/dokimi/tests/test_catalog_validate.py +++ b/dokimi/tests/test_catalog_validate.py @@ -14,7 +14,7 @@ from dokimi.cli import build_parser from dokimi.external import read_skill_manifest, review_skills from dokimi.skills import discover_skills -from dokimi.utils import parse_frontmatter, parse_frontmatter_strict +from dokimi.frontmatter import parse_frontmatter, parse_frontmatter_strict def _skill(root: Path, rel: str, name: str | None = None, description: str = "Use for things.", diff --git a/dokimi/tests/test_cli_m3_moves.py b/dokimi/tests/test_cli_m3_moves.py index aed3492177..2c1ca129f6 100644 --- a/dokimi/tests/test_cli_m3_moves.py +++ b/dokimi/tests/test_cli_m3_moves.py @@ -13,7 +13,7 @@ from dokimi.cli import build_parser, parse_args from dokimi.cli_routes import AmbiguousRetiredFlag, moved_argv from dokimi.commands.catalog import cmd_catalog_list, cmd_catalog_show -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_refusal import refusal diff --git a/dokimi/tests/test_cli_output.py b/dokimi/tests/test_cli_output.py index 4fe42d950f..2816905ddf 100644 --- a/dokimi/tests/test_cli_output.py +++ b/dokimi/tests/test_cli_output.py @@ -18,7 +18,7 @@ from dokimi import cli, cli_output from dokimi.artifacts import schema_errors -from dokimi.utils import InputError +from dokimi.files import InputError def _leaves(parser: argparse.ArgumentParser, prefix: tuple[str, ...] = ()): """Every leaf parser under ``parser`` as (path, parser); an alias is the same parser twice.""" diff --git a/dokimi/tests/test_context_consistency.py b/dokimi/tests/test_context_consistency.py index 629a244ddd..9414bab8ba 100644 --- a/dokimi/tests/test_context_consistency.py +++ b/dokimi/tests/test_context_consistency.py @@ -19,7 +19,7 @@ load_contract, load_outcomes, parse_contract, parse_run, pass_at, pass_hat, profile, run_from_events, seq_distance) from dokimi.context.shell import program as _program -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.context.shell import written as _written diff --git a/dokimi/tests/test_context_prefilter.py b/dokimi/tests/test_context_prefilter.py index 0b27efe493..2c1a142c41 100644 --- a/dokimi/tests/test_context_prefilter.py +++ b/dokimi/tests/test_context_prefilter.py @@ -29,7 +29,7 @@ status_of, ) from dokimi.context.session_log import parse_session -from dokimi.utils import InputError +from dokimi.files import InputError GUIDE = """# Guide diff --git a/dokimi/tests/test_context_prefilter_corpus.py b/dokimi/tests/test_context_prefilter_corpus.py index 679364539b..7473611a2f 100644 --- a/dokimi/tests/test_context_prefilter_corpus.py +++ b/dokimi/tests/test_context_prefilter_corpus.py @@ -14,7 +14,7 @@ from dokimi.cli import build_parser from dokimi.commands.context import _read_sessions from dokimi.context.session_log import read_session_tree -from dokimi.utils import InputError +from dokimi.files import InputError from tests.test_context_prefilter import GUIDE, _prompt, _report, _row, _tool, _write RULE = "- Run `make ci-local` when pushing a branch.\n" diff --git a/dokimi/tests/test_context_trace.py b/dokimi/tests/test_context_trace.py index 9f006333f2..96372b4e3c 100644 --- a/dokimi/tests/test_context_trace.py +++ b/dokimi/tests/test_context_trace.py @@ -11,7 +11,7 @@ from dokimi.cli import build_parser from dokimi.context import TraceError, read_trace -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.context.trace import parse_trace diff --git a/dokimi/tests/test_cross_judge_judge_errors.py b/dokimi/tests/test_cross_judge_judge_errors.py index 1cafad9b1c..2e09a18f8e 100644 --- a/dokimi/tests/test_cross_judge_judge_errors.py +++ b/dokimi/tests/test_cross_judge_judge_errors.py @@ -192,7 +192,7 @@ def test_agreement_skips_ask_rows_and_counts_them(tmp_path, monkeypatch, capsys) def test_agreement_with_only_ask_rows_refuses_before_building_a_judge(tmp_path, monkeypatch, capsys): - from dokimi.utils import InputError + from dokimi.files import InputError def unexpected_judge(**kwargs): pytest.fail("the ask-only file must not be sent to a judge") @@ -210,7 +210,7 @@ def unexpected_judge(**kwargs): def test_agreement_validates_later_entries_before_building_the_first_judge(tmp_path, monkeypatch): - from dokimi.utils import InputError + from dokimi.files import InputError monkeypatch.setattr(judge_mod, "Judge", lambda **kwargs: pytest.fail("built a judge before validating entries")) answers = tmp_path / "run.json" diff --git a/dokimi/tests/test_doc_caches.py b/dokimi/tests/test_doc_caches.py index 51bc1f213d..631e219e6c 100644 --- a/dokimi/tests/test_doc_caches.py +++ b/dokimi/tests/test_doc_caches.py @@ -17,7 +17,7 @@ from tests.exists_mock import exists_for_prefix -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.mcp.context7 import Context7Client from dokimi.mcp.url_client import URLClient from dokimi.questions.ragas_seed import RagasSeedExtractor diff --git a/dokimi/tests/test_doc_source_unlistable.py b/dokimi/tests/test_doc_source_unlistable.py index 0d37637970..7f84dbc8fa 100644 --- a/dokimi/tests/test_doc_source_unlistable.py +++ b/dokimi/tests/test_doc_source_unlistable.py @@ -20,7 +20,7 @@ from dokimi.mcp.factory import require_local_doc_source from dokimi.mcp.local_markdown import LocalMarkdownClient from dokimi.mcp.okf_client import OKFClient -from dokimi.utils import InputError +from dokimi.files import InputError CLIENTS = [(LocalMarkdownClient, "local"), (OKFClient, "okf")] diff --git a/dokimi/tests/test_docker_null_check.py b/dokimi/tests/test_docker_null_check.py index 555f426b87..8971fd4c4e 100644 --- a/dokimi/tests/test_docker_null_check.py +++ b/dokimi/tests/test_docker_null_check.py @@ -19,7 +19,7 @@ from dokimi.cli import build_parser from dokimi.harnesses import create_harness, known_harnesses, load_task, null_check from dokimi.harnesses.docker_solver import DockerSolverHarness -from dokimi.utils import InputError +from dokimi.files import InputError from docker_cli_fake import DockerCLI, reply diff --git a/dokimi/tests/test_eval_coverage.py b/dokimi/tests/test_eval_coverage.py index 863a0f6072..33fd310c23 100644 --- a/dokimi/tests/test_eval_coverage.py +++ b/dokimi/tests/test_eval_coverage.py @@ -16,7 +16,7 @@ from dokimi.eval_coverage import LabelledEval, coverage_report, exact_shares, graph_digest, load_graph, read_labels from dokimi.novelty.needs import NeedGraph, NeedNode from dokimi.novelty.needs import load_graph as novelty_load_graph -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_refusal import refusal NODES = [ diff --git a/dokimi/tests/test_eval_tasks_generate_history.py b/dokimi/tests/test_eval_tasks_generate_history.py index 1bd4e431ba..2594a5b0b2 100644 --- a/dokimi/tests/test_eval_tasks_generate_history.py +++ b/dokimi/tests/test_eval_tasks_generate_history.py @@ -17,7 +17,7 @@ from dokimi.cli import build_parser from dokimi.repos.replay import authoring_prompt -from dokimi.utils import InputError +from dokimi.files import InputError from repo_eval_fixture import FakeRunner, git, write MANIFEST = { diff --git a/dokimi/tests/test_evaluate_cli_inputs.py b/dokimi/tests/test_evaluate_cli_inputs.py index cbf2055504..fd8d427b18 100644 --- a/dokimi/tests/test_evaluate_cli_inputs.py +++ b/dokimi/tests/test_evaluate_cli_inputs.py @@ -21,7 +21,7 @@ from dokimi.cli import build_parser from dokimi.orchestrator.pipeline import EvaluationPipeline, load_questions_payload -from dokimi.utils import InputError +from dokimi.files import InputError def _evaluate(*extra: str): diff --git a/dokimi/tests/test_explore_track.py b/dokimi/tests/test_explore_track.py index 854d48ce87..2ed8c6371f 100644 --- a/dokimi/tests/test_explore_track.py +++ b/dokimi/tests/test_explore_track.py @@ -18,7 +18,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.artifacts import validate_artifact from dokimi.explore import ( ExploreRunner, diff --git a/dokimi/tests/test_fuzz_targets.py b/dokimi/tests/test_fuzz_targets.py index bc12fb87de..c3030de913 100644 --- a/dokimi/tests/test_fuzz_targets.py +++ b/dokimi/tests/test_fuzz_targets.py @@ -139,7 +139,7 @@ def test_a_date_that_is_not_real_is_invalid_frontmatter() -> None: # and the strict one raises the YAML error its docstring names. import yaml - from dokimi.utils import parse_frontmatter, parse_frontmatter_strict + from dokimi.frontmatter import parse_frontmatter, parse_frontmatter_strict text = "---\ndate: 2026-02-30\n---\nbody" assert parse_frontmatter(text) == ({}, "body") @@ -165,7 +165,7 @@ def test_a_malformed_tagged_scalar_is_invalid_frontmatter(text: str) -> None: # Lenient readers return no metadata; strict ones raise the YAML error the docstring names. import yaml - from dokimi.utils import parse_frontmatter, parse_frontmatter_strict + from dokimi.frontmatter import parse_frontmatter, parse_frontmatter_strict meta, body = parse_frontmatter(text) assert meta == {} diff --git a/dokimi/tests/test_git_paths_windows_decode.py b/dokimi/tests/test_git_paths_windows_decode.py index 62424e4bcd..9db109596e 100644 --- a/dokimi/tests/test_git_paths_windows_decode.py +++ b/dokimi/tests/test_git_paths_windows_decode.py @@ -16,7 +16,7 @@ import pytest -from dokimi import process_io, utils +from dokimi import digest, process_io from dokimi.external import catalog_git BAD = b"l\xffint/SKILL.md" @@ -65,15 +65,15 @@ def test_the_fixture_decodes_as_windows_does(windows_decoding): def test_git_tree_holds_a_path_that_is_not_utf8(repo, windows_decoding): - tree = utils.git_tree(repo / "skill") + tree = digest.git_tree(repo / "skill") assert tree is not None assert REPLACED not in tree.tracked and "skill/SKILL.md" in tree.tracked # the replaced name is no file's assert "skill/SKILL.md" in tree.indexed def test_tree_digest_with_git_reads_an_index_with_a_path_that_is_not_utf8(repo, windows_decoding): - digest = utils.tree_digest(repo / "skill", git=True) - assert len(digest) == 64 and digest == utils.tree_digest(repo / "skill", git=True) + first = digest.tree_digest(repo / "skill", git=True) + assert len(first) == 64 and first == digest.tree_digest(repo / "skill", git=True) @pytest.fixture @@ -91,18 +91,18 @@ def colliding_repo(tmp_path) -> Path: def test_a_name_that_collides_after_replacement_does_not_set_the_mode_of_a_real_file(colliding_repo, windows_decoding): - assert utils._tracked_modes(colliding_repo, ".") == {REPLACED: False} + assert digest._tracked_modes(colliding_repo, ".") == {REPLACED: False} def test_the_digest_ignores_the_mode_of_a_name_that_collides_after_replacement(colliding_repo, windows_decoding): - plain = utils.tree_digest(colliding_repo, git=True, tracked={REPLACED: False}) - assert utils.tree_digest(colliding_repo, git=True) == plain + plain = digest.tree_digest(colliding_repo, git=True, tracked={REPLACED: False}) + assert digest.tree_digest(colliding_repo, git=True) == plain def test_a_name_that_collides_after_replacement_gives_the_real_file_its_own_index_blob(colliding_repo, windows_decoding): """The missing file's status entry is not read as the real file's: the real file, unchanged, keeps its own blob, never the other entry's.""" - blobs, held = utils._index_blobs(os.fspath(colliding_repo)) + blobs, held = digest._index_blobs(os.fspath(colliding_repo)) assert blobs == {REPLACED: _git(colliding_repo, "hash-object", REPLACED).decode().strip()} assert REPLACED.split("/")[0] in held @@ -114,7 +114,7 @@ def test_a_changed_file_with_an_encoded_surrogate_name_takes_no_index_blob(tmp_p root.mkdir() _git(root, "init", "-q") _index_entry(root, "100644", b"skill/\xed\xa0\x80.sh") - assert utils._index_blobs(os.fspath(root))[0] == {} + assert digest._index_blobs(os.fspath(root))[0] == {} def test_the_status_and_flag_readers_name_a_file_with_an_encoded_surrogate_as_the_index_does(windows_decoding): @@ -127,7 +127,7 @@ def test_git_tree_holds_an_ignored_path_that_is_not_utf8(repo, windows_decoding) (repo / ".gitignore").write_text("*.tmp\n", encoding="utf-8") with open(os.fsencode(repo) + b"/skill/a\xff.tmp", "wb") as handle: handle.write(b"x") - tree = utils.git_tree(repo / "skill") + tree = digest.git_tree(repo / "skill") assert tree is not None and "skill/a�.tmp" in tree.ignored @@ -156,7 +156,7 @@ def test_git_tree_ignored_directory_with_a_lone_surrogate_name_keeps_its_name(re os.mkdir(os.fsencode(repo) + b"/skill/\xed\xa0\x80cache") with open(os.fsencode(repo) + b"/skill/\xed\xa0\x80cache/f", "wb") as handle: handle.write(b"x") - assert utils._ignored_paths(str(repo)) == {"skill/\ud800cache"} + assert digest._ignored_paths(str(repo)) == {"skill/\ud800cache"} def test_a_listed_name_windows_cannot_decode_is_still_replaced(windows_decoding): @@ -170,7 +170,7 @@ def test_the_index_readers_skip_a_name_that_is_not_utf8(windows_decoding): def test_tracked_modes_keeps_a_path_that_is_not_utf8(repo, windows_decoding): - assert utils._tracked_modes(repo, ".") == {"skill/SKILL.md": False} + assert digest._tracked_modes(repo, ".") == {"skill/SKILL.md": False} def test_catalog_paths_report_a_path_that_is_not_utf8(repo, windows_decoding): @@ -247,7 +247,7 @@ def nested_repo(tmp_path) -> Path: def test_an_index_name_that_collides_after_replacement_does_not_unignore_a_nested_file(nested_repo, windows_decoding): - tree = utils.git_tree(nested_repo) + tree = digest.git_tree(nested_repo) assert tree is not None and REPLACED not in tree.tracked assert tree.skipped(nested_repo / REPLACED) is True @@ -262,7 +262,7 @@ def test_tracked_modes_keeps_the_mode_of_a_name_with_an_encoded_surrogate(tmp_pa root.mkdir() _git(root, "init", "-q") _index_entry(root, "100755", b"skill/\xed\xa0\x80.sh") - assert utils._tracked_modes(root, ".") == {"skill/\ud800.sh": True} + assert digest._tracked_modes(root, ".") == {"skill/\ud800.sh": True} @pytest.mark.skipif(os.name != "posix", reason="POSIX keeps the byte; Windows replaces it") diff --git a/dokimi/tests/test_headroom_command.py b/dokimi/tests/test_headroom_command.py index 4901f68c7d..2101c10210 100644 --- a/dokimi/tests/test_headroom_command.py +++ b/dokimi/tests/test_headroom_command.py @@ -18,7 +18,7 @@ from dokimi import records from dokimi.cli import build_parser from dokimi.commands.headroom import cmd_eval_headroom -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.eval.headroom import ( CEILING, DEFAULT_CEILING, DEFAULT_FLOOR, DEFAULT_MIN_REPS, FLOOR, _fmt, check_thresholds, format_table, headroom, diff --git a/dokimi/tests/test_import_architecture.py b/dokimi/tests/test_import_architecture.py index b989ff2384..4b9438e119 100644 --- a/dokimi/tests/test_import_architecture.py +++ b/dokimi/tests/test_import_architecture.py @@ -80,7 +80,8 @@ "dokimi.intents", "dokimi.judged", "dokimi.llm", "dokimi.llm_cli", "dokimi.llm_json", "dokimi.llm_providers", "dokimi.llm_sampling", "dokimi.llm_turn", "dokimi.llm_pricing", "dokimi.measure", "dokimi.process", "dokimi.process_hooks", "dokimi.process_io", - "dokimi.atomic_write", "dokimi.provenance", "dokimi.records", "dokimi.registry", "dokimi.utils", "dokimi.write_probe", + "dokimi.atomic_write", "dokimi.digest", "dokimi.files", "dokimi.frontmatter", "dokimi.model_names", + "dokimi.provenance", "dokimi.records", "dokimi.registry", "dokimi.utils", "dokimi.write_probe", "dokimi.yaml_unique", "dokimi.pattern_glob", "dokimi.judge_rule", "dokimi.spend", "dokimi.text_spans", "dokimi.code_spans", "dokimi.dokimi_commit", @@ -458,7 +459,7 @@ def exit_problems(imports: Imports, baseline: Mapping[str, tuple[int, str]], for mod, lines in sorted(counts.items()): allowed = baseline.get(mod, (0, ""))[0] if len(lines) > allowed: - problems.append(f"{mod} ends the process at lines {lines}; raise InputError (dokimi.utils) " + problems.append(f"{mod} ends the process at lines {lines}; raise InputError (dokimi.files) " "and let cli.main exit 2") for mod, (allowed, _) in sorted(baseline.items()): now = len(counts.get(mod, [])) @@ -475,6 +476,30 @@ def imports() -> Imports: return build_imports(PROJECT) +def test_legacy_utils_exports_still_resolve(): + from dokimi import digest, files, frontmatter, model_names, records, utils + + modules = { + digest: ("GitDigestTree", "digest_text", "file_contents", "file_digest", "git_tree", "key_bytes", "link_text", + "tree_digest"), + files: ("InputError", "is_symlink_loop", "read_json_input", "read_json_input_bytes", "refuse_device", + "retry_writable"), + frontmatter: ("describe_yaml_error", "parse_frontmatter", "parse_frontmatter_strict"), + model_names: ("check_bedrock_model", "model_identity", "same_evaluator", "same_model", + "warn_judge_independence", "warn_recorded_self_judge"), + records: ("question_id",), + } + assert set(utils.__all__) == {name for names in modules.values() for name in names} + for module, names in modules.items(): + for name in names: + assert getattr(utils, name) is getattr(module, name) + + +def test_package_uses_the_new_modules(imports): + users = sorted(module for module, deps in imports.edges.items() if "dokimi.utils" in deps) + assert not users, f"{users} import dokimi.utils; import the names from their defining modules" + + def test_every_module_is_in_a_layer(imports): unplaced = sorted(m for m in imports.modules if layer_of(m) is None) assert not unplaced, f"{unplaced} are in no layer: add them to LAYERS in this test" diff --git a/dokimi/tests/test_input_devices.py b/dokimi/tests/test_input_devices.py index 35c9436592..200322e8db 100644 --- a/dokimi/tests/test_input_devices.py +++ b/dokimi/tests/test_input_devices.py @@ -22,7 +22,7 @@ from dokimi.commands.inputs import read_text_or_exit from dokimi.orchestrator.pipeline import EvaluationPipeline from dokimi.registry import ProductEntry -from dokimi.utils import InputError, read_json_input, refuse_device +from dokimi.files import InputError, read_json_input, refuse_device pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="/dev/null is a POSIX device") diff --git a/dokimi/tests/test_input_refusal_exit_sites.py b/dokimi/tests/test_input_refusal_exit_sites.py index 8462416c53..bfa98ba8ba 100644 --- a/dokimi/tests/test_input_refusal_exit_sites.py +++ b/dokimi/tests/test_input_refusal_exit_sites.py @@ -121,7 +121,7 @@ def literal_exit_2_problems(modules: dict[str, Path], baseline: dict[str, tuple[ lines = literal_exit_2_lines(path.read_text(encoding="utf-8")) allowed = baseline.get(mod, (0, ""))[0] if len(lines) > allowed: - problems.append(f"{mod} exits 2 at lines {lines}; raise InputError (dokimi.utils) with the message " + problems.append(f"{mod} exits 2 at lines {lines}; raise InputError (dokimi.files) with the message " "and let cli.main print it and exit 2") elif len(lines) < allowed: problems.append(f"{mod} has {len(lines)} literal exit(s) 2, baseline {allowed}: lower EXIT2_BASELINE") diff --git a/dokimi/tests/test_json_writers_equal_keys.py b/dokimi/tests/test_json_writers_equal_keys.py index a5ed410153..ba114b1621 100644 --- a/dokimi/tests/test_json_writers_equal_keys.py +++ b/dokimi/tests/test_json_writers_equal_keys.py @@ -17,7 +17,7 @@ from dokimi.commands.tools import _write_items from dokimi.novelty.atoms import save_atoms from dokimi.report.json_report import write_json -from dokimi.utils import InputError +from dokimi.files import InputError PAIR = chr(0xD83D) + chr(0xDE00) CHAR = "\U0001F600" diff --git a/dokimi/tests/test_judge_context_mode.py b/dokimi/tests/test_judge_context_mode.py index 4f0bcb56fd..964c44d5fc 100644 --- a/dokimi/tests/test_judge_context_mode.py +++ b/dokimi/tests/test_judge_context_mode.py @@ -22,7 +22,8 @@ from dokimi.skills import load_skill from dokimi.treatments import BaselineTreatment, SkillTreatment from dokimi.treatments.arms import SkillCatalogTreatment -from dokimi.utils import InputError, digest_text +from dokimi.files import InputError +from dokimi.digest import digest_text from tests.cli_refusal import refusal from tests.conftest import DEMO_SKILL_MARKER @@ -265,7 +266,7 @@ def test_a_withheld_run_without_a_judge_is_refused(): def test_matrix_run_refuses_the_flag_without_judge_as_an_input_error(capsys): from dokimi.commands.arms import cmd_arms_matrix_run - from dokimi.utils import InputError + from dokimi.files import InputError args = build_parser().parse_args(["arms", "matrix-run", "--arm", "baseline", "--product", "oneTBB", "--questions", "q.json", "--matrix-cells", "cells.json", diff --git a/dokimi/tests/test_judge_not_measured.py b/dokimi/tests/test_judge_not_measured.py index 8399b23946..a00a8d3545 100644 --- a/dokimi/tests/test_judge_not_measured.py +++ b/dokimi/tests/test_judge_not_measured.py @@ -285,7 +285,7 @@ def test_agreement_without_any_scores_names_the_live_judge_flag(tmp_path): from dokimi.commands.judge_reliability import cmd_eval_cross_judge from dokimi.cli import parse_args - from dokimi.utils import InputError + from dokimi.files import InputError path = tmp_path / "answers.json" path.write_text("[]") diff --git a/dokimi/tests/test_judge_provider_default.py b/dokimi/tests/test_judge_provider_default.py index a3e983cba1..f52297b2a9 100644 --- a/dokimi/tests/test_judge_provider_default.py +++ b/dokimi/tests/test_judge_provider_default.py @@ -380,7 +380,7 @@ def test_subjects_run_resolves_an_explicit_judge_model_once_the_descriptor_is_lo def test_subjects_run_refuses_a_judge_model_the_cli_judge_it_moves_to_cannot_take(): # parse_args checks the model before the descriptor moves the judge; the move is checked again here from dokimi.commands.subjects import resolve_judge - from dokimi.utils import InputError + from dokimi.files import InputError args = parse_args([*COMMANDS["subjects run"], "--judge", "--model", "claude-cli/sonnet", "--judge-model", "gpt-4o"]) with pytest.raises(InputError, match="the judge follows --model claude-cli: pass a judge from another family") as exc: @@ -420,7 +420,7 @@ def test_novelty_cli_judge_refusal_uses_the_separate_flags(command, capsys): def test_subjects_run_refuses_a_default_judge_that_is_the_implicit_cell_answerer(): from dokimi.commands.subjects import resolve_judge - from dokimi.utils import InputError + from dokimi.files import InputError argv = [*COMMANDS["subjects run"], "--judge", "--model", "claude-sonnet-5-5"] with pytest.raises(InputError, match="model under measurement"): diff --git a/dokimi/tests/test_judge_reliability.py b/dokimi/tests/test_judge_reliability.py index f597a1fb5a..6e6bf79454 100644 --- a/dokimi/tests/test_judge_reliability.py +++ b/dokimi/tests/test_judge_reliability.py @@ -447,7 +447,7 @@ def score(agg): def _material_run(body=BODY, n=8): """An arms file whose skill records and scores all cite ``body``, kept in judge_materials.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = _stamped_run() data["answers"], data["evaluations"] = data["answers"][:n], data["evaluations"][:n] @@ -618,7 +618,7 @@ def score_answer(self, **_): def test_cross_judge_judges_with_intact_materials_runs_end_to_end(tmp_path, monkeypatch, capsys): """--judges with intact judge_materials runs and gate passes.""" import json - from dokimi.utils import digest_text + from dokimi.digest import digest_text from dokimi.cli import build_parser from dokimi.eval import judge as judge_mod @@ -693,7 +693,7 @@ def score_answer(self, **_): def test_cross_judge_judges_with_int_question_ids(tmp_path, monkeypatch, capsys): """--judges with int question ids (including 0) works end to end.""" import json - from dokimi.utils import digest_text + from dokimi.digest import digest_text from dokimi.cli import build_parser from dokimi.eval import judge as judge_mod @@ -736,7 +736,7 @@ def score_answer(self, **kw): def test_cross_judge_judges_and_pairwise_refuse_together(tmp_path, monkeypatch, capsys): """--judges + --pairwise refuses even with intact materials.""" import json - from dokimi.utils import digest_text + from dokimi.digest import digest_text from dokimi.cli import build_parser from dokimi.eval import judge as judge_mod @@ -772,7 +772,7 @@ def score_answer(self, **_): def test_cross_judge_judges_refuses_altered_material_text(tmp_path, monkeypatch, capsys): """--judges refuses when judge_materials text doesn't match recorded digest.""" import json - from dokimi.utils import digest_text + from dokimi.digest import digest_text from dokimi.cli import build_parser from dokimi.eval import judge as judge_mod @@ -807,7 +807,7 @@ def score_answer(self, **_): def test_cross_judge_judges_refuses_records_without_digest(tmp_path, monkeypatch, capsys): """--judges refuses when arm records are missing the digest.""" import json - from dokimi.utils import digest_text + from dokimi.digest import digest_text from dokimi.cli import build_parser from dokimi.eval import judge as judge_mod @@ -845,7 +845,7 @@ def score_answer(self, **_): def test_cross_judge_judges_refuses_mismatched_digest_between_arms_and_scores(tmp_path, monkeypatch, capsys): """--judges refuses when arm records cite different digest than scores.""" import json - from dokimi.utils import digest_text + from dokimi.digest import digest_text from dokimi.cli import build_parser from dokimi.eval import judge as judge_mod @@ -995,7 +995,7 @@ def test_cross_judge_judges_refuses_a_score_citing_other_material_than_the_recor tmp_path, monkeypatch, capsys ): """Both digests are in judge_materials, so only comparing them catches it.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = _material_run() other = "OTHER SKILL BODY" @@ -1014,7 +1014,7 @@ def test_cross_judge_judges_refuses_one_damaged_question_among_eight( tmp_path, monkeypatch, capsys, damage ): """The gate must look past the first evaluation: question 5 alone is damaged.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = _material_run() other = "OTHER SKILL BODY" @@ -1048,7 +1048,7 @@ def test_cross_judge_judges_gates_an_arm_that_read_material_when_it_is_the_basel tmp_path, monkeypatch, capsys, damage ): """--baseline-arm skill picks the reference, it does not make the skill arm read nothing.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = _material_run() # As the arms run writes it: the baseline arm cites the empty text. @@ -1082,7 +1082,7 @@ def test_cross_judge_judges_skips_an_evaluation_with_no_answer_record(tmp_path, def test_cross_judge_judges_refuses_one_damaged_int_question_among_eight(tmp_path, monkeypatch, capsys): - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = _material_run() for i, (ans, ev) in enumerate(zip(data["answers"], data["evaluations"], strict=True)): @@ -1127,7 +1127,7 @@ def test_cross_judge_judges_on_an_answers_only_file_hands_the_judge_the_material def test_cross_judge_judges_with_no_stored_hands_the_judge_the_material(tmp_path, monkeypatch): - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = _material_run() # A stored score that would fail the gate: --no-stored skips it, not the reader. @@ -1170,7 +1170,7 @@ def test_cross_judge_judges_refuses_one_damaged_question_among_eight_int_ids( tmp_path, monkeypatch, capsys ): """The gate reads int ids too: question 5 alone is damaged, and its id is the int 5.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = _material_run() for i, (ans, ev) in enumerate(zip(data["answers"], data["evaluations"], strict=True)): @@ -1200,7 +1200,7 @@ def test_from_artifact_refuses_a_malformed_answer_list_and_non_scalar_ids(): def test_digest_text_tells_a_lone_surrogate_from_its_removal(): """errors="ignore" would hash a lone-surrogate text and its stripped form alike.""" from dokimi.eval.judge_context import JudgeContextStore - from dokimi.utils import digest_text + from dokimi.digest import digest_text assert digest_text("a\ud83db") != digest_text("ab") data = _material_run(body="a\ud83db", n=1) @@ -1238,7 +1238,7 @@ def test_significance_uses_the_unrounded_holm_p(): def test_digest_text_surrogatepass_handles_lone_surrogates(): """digest_text uses surrogatepass to handle lone surrogates without raising.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text # A lone surrogate pair should not raise but produce a digest result = digest_text("a\ud83db") @@ -1577,7 +1577,7 @@ def scorer(library, question, answer, ground_truth, context): def _material_arms_run(material="FULL SKILL BODY"): """An arms file that keeps its judge material, with digests on answers and stored scores.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text digest = digest_text(material) return { diff --git a/dokimi/tests/test_judge_temperature_entry_points.py b/dokimi/tests/test_judge_temperature_entry_points.py index 2ff9a8789c..b8def72603 100644 --- a/dokimi/tests/test_judge_temperature_entry_points.py +++ b/dokimi/tests/test_judge_temperature_entry_points.py @@ -302,7 +302,7 @@ def optional_params(*, model, custom_llm_provider, temperature): def test_benchmark_refuses_a_judge_temperature_the_route_refuses_before_any_call(haiku_requests): from dokimi.commands.benchmark import _refuse_judge_sampling - from dokimi.utils import InputError + from dokimi.files import InputError with pytest.raises(InputError, match="temperature"): _refuse_judge_sampling(SimpleNamespace(**_HAIKU_JUDGE)) @@ -311,7 +311,7 @@ def test_benchmark_refuses_a_judge_temperature_the_route_refuses_before_any_call def test_evaluate_refuses_a_judge_temperature_the_route_refuses_before_any_call(haiku_requests): from dokimi.commands.orchestrate import cmd_evaluate - from dokimi.utils import InputError + from dokimi.files import InputError with pytest.raises(InputError, match="temperature"): cmd_evaluate(SimpleNamespace(repo="owner/repo", description=None, product="p", diff --git a/dokimi/tests/test_judge_validity.py b/dokimi/tests/test_judge_validity.py index 6734bfb2f9..0e65814e0c 100644 --- a/dokimi/tests/test_judge_validity.py +++ b/dokimi/tests/test_judge_validity.py @@ -1428,7 +1428,7 @@ def test_wrong_numbers_survives_a_digit_run_too_long_for_a_float(tail): def _with_materials(skill_text="FULL SKILL BODY"): """`_answers()` as an arms artifact that keeps its judge materials.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = {"answers": _answers(), "judge_materials": {}} for rec in data["answers"]: @@ -1738,7 +1738,7 @@ def test_a_stored_validity_report_gates_the_rescored_judge_in_cross_judge(tmp_pa import json from dokimi.cli import build_parser - from dokimi.utils import digest_text + from dokimi.digest import digest_text # A judge that ranks the longer answer lower fails the gate (intact must win). failing = _stored_cli(tmp_path, monkeypatch, "--context", "stored", "--bases", "3", @@ -1796,7 +1796,7 @@ def test_sequential_stored_context_reports_pool_and_dropped_answers(): """Only answers with verified material count toward the pool, so an exhausted pool is 'pool'.""" from dokimi.eval.judge_context import JudgeContextStore from dokimi.eval.judge_sequential import run_sequential - from dokimi.utils import digest_text + from dokimi.digest import digest_text digest = digest_text("FULL SKILL BODY") answers = [{"question_id": f"Q{i:03d}", "question_text": f"q{i}?", @@ -1817,7 +1817,7 @@ def test_sequential_stored_context_reports_pool_and_dropped_answers(): def _starvable(n=30, with_material=3): """n baseline answers and n skill answers, of which only ``with_material`` hold material.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text empty, body = digest_text(""), digest_text("FULL SKILL BODY") answers = [{"question_id": f"Q{i:03d}", "question_text": f"q{i}?", "arms": { @@ -1855,7 +1855,7 @@ def test_an_arm_with_material_but_no_sampled_base_is_refused(): def test_a_scorer_without_a_context_argument_is_refused_before_pairs_are_built(): from dokimi.eval.judge_context import JudgeContextStore from dokimi.eval.judge_validity import NoUsablePairs - from dokimi.utils import digest_text + from dokimi.digest import digest_text digest = digest_text("FULL SKILL BODY") data = {"answers": [{"question_id": "Q0", "question_text": "q?", "arms": { @@ -1871,7 +1871,7 @@ def test_a_noop_variant_leaving_an_arm_unpaired_is_refused_before_scoring(): verified material, gets no pair. The refusal names it and no judge call is made.""" from dokimi.eval.judge_context import JudgeContextStore from dokimi.eval.judge_validity import NoUsablePairs - from dokimi.utils import digest_text + from dokimi.digest import digest_text digest = digest_text("FULL SKILL BODY") empty = digest_text("") @@ -1898,7 +1898,7 @@ def test_fixed_mode_arm_with_material_and_only_noop_bases_is_refused(): """A fixed-mode run where one arm gets no scored base refuses despite material.""" from dokimi.eval.judge_context import JudgeContextStore from dokimi.eval.judge_validity import NoUsablePairs - from dokimi.utils import digest_text + from dokimi.digest import digest_text digest = digest_text("FULL SKILL BODY") empty = digest_text("") @@ -1932,7 +1932,7 @@ def test_sequential_stopped_by_counts_kept_answers_not_sampled_ones(): """kept > max_bases: a higher --max-bases would add bases, so an undecided variant is 'cap'.""" from dokimi.eval.judge_context import JudgeContextStore from dokimi.eval.judge_sequential import run_sequential - from dokimi.utils import digest_text + from dokimi.digest import digest_text digest = digest_text("FULL SKILL BODY") plain = "Plain prose answer without any code block, long enough to count. " * 30 @@ -1971,7 +1971,7 @@ def test_sequential_reports_the_bases_scored_not_the_pool_built(): """An early SPRT stop scores fewer bases than --max-bases built; the summary says which.""" from dokimi.eval.judge_context import JudgeContextStore from dokimi.eval.judge_sequential import run_sequential - from dokimi.utils import digest_text + from dokimi.digest import digest_text digest = digest_text("FULL SKILL BODY") answers = [{"question_id": f"Q{i:03d}", "question_text": f"q{i}?", @@ -1994,7 +1994,7 @@ def test_sequential_per_arm_scored_counts_differ(): """Sequential mode tracks bases scored per arm, pinning the per-arm filter.""" from dokimi.eval.judge_context import JudgeContextStore from dokimi.eval.judge_sequential import run_sequential - from dokimi.utils import digest_text + from dokimi.digest import digest_text # Just verify that the "scored" field is populated per-arm in sequential mode. # The mutation is that the per-arm filter is removed, so all arms print the same total. @@ -2054,7 +2054,7 @@ def test_refusal_still_says_raise_the_sample_when_a_kept_base_was_not_drawn(): def _baseline_heavy_arms(): """100 baseline + 3 skill answers, each citing its verified material.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = {"answers": [], "judge_materials": {}} for i in range(103): @@ -2120,7 +2120,7 @@ def test_sequential_reports_a_fail_even_when_an_arm_was_never_scored(seed): def _fenced_baseline_arms(n_skill): """100 baseline answers with a code fence, ``n_skill`` skill answers without one.""" - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = {"answers": [], "judge_materials": {}} for i in range(100 + n_skill): @@ -2156,7 +2156,7 @@ def test_sequential_padding_alone_does_not_cover_an_arm(n_skill): def test_sequential_unscored_arm_refusal_names_every_arm_sorted(): from dokimi.eval.judge_context import JudgeContextStore from dokimi.eval.judge_sequential import run_sequential - from dokimi.utils import digest_text + from dokimi.digest import digest_text data = {"answers": [], "judge_materials": {}} for i in range(106): diff --git a/dokimi/tests/test_key_files.py b/dokimi/tests/test_key_files.py index 8d3d297ba2..a630b74792 100644 --- a/dokimi/tests/test_key_files.py +++ b/dokimi/tests/test_key_files.py @@ -317,7 +317,7 @@ def test_preflight_refuses_an_unreadable_key_file_on_a_keyless_route( @pytest.mark.parametrize("command", ["run", "batch"]) def test_run_and_batch_refuse_an_unreadable_key_file_on_a_vertex_route(command, tmp_path, monkeypatch): from dokimi.commands.benchmark import _refuse_missing_credentials - from dokimi.utils import InputError + from dokimi.files import InputError monkeypatch.setenv("GEMINI_API_KEY", f"file:{tmp_path / 'no-such-key'}") monkeypatch.setenv("OPENAI_API_KEY", "sk-judge") diff --git a/dokimi/tests/test_knowledge_run.py b/dokimi/tests/test_knowledge_run.py index 6fecaf0159..ce0c11c749 100644 --- a/dokimi/tests/test_knowledge_run.py +++ b/dokimi/tests/test_knowledge_run.py @@ -19,7 +19,7 @@ from dokimi.eval.arms_refusals import refuse_task_harness from dokimi.eval.arms_run import ArmsRunConfig, prepare_arms, run_arms from dokimi.process import FakeRunner, reply -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_refusal import refusal QUESTIONS = [ diff --git a/dokimi/tests/test_leak_command.py b/dokimi/tests/test_leak_command.py index 1951915650..f1e811621d 100644 --- a/dokimi/tests/test_leak_command.py +++ b/dokimi/tests/test_leak_command.py @@ -18,7 +18,7 @@ from dokimi.artifacts import schema_errors from dokimi.commands.leak import cmd_eval_leak -from dokimi.utils import InputError +from dokimi.files import InputError ANSWER = "the flag writes each kernel timing into the chrome trace file under the output directory" SPLIT = {"dev": ["1"], "val": ["2"], "test": ["3"]} diff --git a/dokimi/tests/test_llm_callers.py b/dokimi/tests/test_llm_callers.py index 75e2fa3d9f..5b32c2ea0d 100644 --- a/dokimi/tests/test_llm_callers.py +++ b/dokimi/tests/test_llm_callers.py @@ -20,7 +20,8 @@ from dokimi.personas.generator import PersonaGenerator from dokimi.questions.llm_gen import QuestionGenerator from dokimi.questions.validator import QuestionValidator -from dokimi.utils import InputError, check_bedrock_model +from dokimi.files import InputError +from dokimi.model_names import check_bedrock_model CALLERS = { "judge": lambda model, provider, api_key: Judge(model=model, provider=provider, api_key=api_key), diff --git a/dokimi/tests/test_llm_cli.py b/dokimi/tests/test_llm_cli.py index 211d80b069..8c12bf6c83 100644 --- a/dokimi/tests/test_llm_cli.py +++ b/dokimi/tests/test_llm_cli.py @@ -19,7 +19,7 @@ from dokimi import llm, llm_cli, process from dokimi.metrics.usage import UsageRecord from dokimi.process import FakeRunner, reply -from dokimi.utils import InputError +from dokimi.files import InputError def _ok(text: str = "PONG", **over) -> str: diff --git a/dokimi/tests/test_llm_cli_identity.py b/dokimi/tests/test_llm_cli_identity.py index 12192f5cac..f7809a59c8 100644 --- a/dokimi/tests/test_llm_cli_identity.py +++ b/dokimi/tests/test_llm_cli_identity.py @@ -8,7 +8,7 @@ import pytest from dokimi import llm_cli -from dokimi.utils import same_model +from dokimi.model_names import same_model def test_an_alias_and_its_full_id_are_one_model_for_the_identity_checks(): diff --git a/dokimi/tests/test_load_or_fail.py b/dokimi/tests/test_load_or_fail.py index db4e2de37a..6ba1af62f4 100644 --- a/dokimi/tests/test_load_or_fail.py +++ b/dokimi/tests/test_load_or_fail.py @@ -17,7 +17,7 @@ from dokimi.novelty.atoms import load_atoms_record from dokimi.records import load as load_records from dokimi.report.model_compare import load_run -from dokimi.utils import InputError +from dokimi.files import InputError MISSING, NOT_UTF8, BAD_JSON, NOT_AN_OBJECT, WRONG_SCHEMA = ( "missing", "not_utf8", "bad_json", "not_an_object", "wrong_schema") @@ -64,7 +64,7 @@ def test_a_bad_input_file_is_an_input_error_naming_it(tmp_path, loader, mode): def test_a_path_with_a_nul_byte_is_an_input_error_naming_it(): # Path.read_text raises a bare ValueError here; it must not escape as a traceback. - from dokimi.utils import read_json_input + from dokimi.files import read_json_input with pytest.raises(InputError) as exc: read_json_input("bad\x00name.json") @@ -76,7 +76,7 @@ def test_a_path_with_a_nul_byte_is_an_input_error_naming_it(): (None, 'cannot read "": no file given'), ]) def test_an_empty_path_is_refused_quoted_not_read_as_the_current_directory(flag, message): - from dokimi.utils import read_json_input + from dokimi.files import read_json_input with pytest.raises(InputError) as exc: read_json_input("", flag=flag) diff --git a/dokimi/tests/test_lone_surrogate_cache_keys.py b/dokimi/tests/test_lone_surrogate_cache_keys.py index 2242daf81d..e18cc1df7d 100644 --- a/dokimi/tests/test_lone_surrogate_cache_keys.py +++ b/dokimi/tests/test_lone_surrogate_cache_keys.py @@ -22,7 +22,7 @@ from dokimi.repos import WorkTree, load_manifest from dokimi.repos.reach import run_reach from dokimi.repos.harness_profile import load_profile -from dokimi.utils import key_bytes +from dokimi.digest import key_bytes from tests.test_repo_reach import _profile, _repo HIGH = "n\ud800" diff --git a/dokimi/tests/test_mcp_factory.py b/dokimi/tests/test_mcp_factory.py index 688e649123..66a7bfc753 100644 --- a/dokimi/tests/test_mcp_factory.py +++ b/dokimi/tests/test_mcp_factory.py @@ -293,7 +293,7 @@ def test_context7_keeps_defaults_when_config_has_no_keys(tmp_path, monkeypatch): ]) def test_context7_refuses_a_bad_configured_value(tmp_path, monkeypatch, body): """#1291: a value the client cannot use is an input error naming the config, not a silent default.""" - from dokimi.utils import InputError + from dokimi.files import InputError _local_config(tmp_path, monkeypatch, body) with pytest.raises(InputError, match="products.yaml"): create_doc_source_client("context7", cache_dir=tmp_path / "c") @@ -302,7 +302,7 @@ def test_context7_refuses_a_bad_configured_value(tmp_path, monkeypatch, body): @pytest.mark.parametrize("body", ["context7: [\n", "[1]\n", "[]\n", "false\n", "0\n", "products: 5\n"]) def test_context7_refuses_an_unreadable_config(tmp_path, monkeypatch, body): """#1291: a config that does not parse, or has the wrong root, is an input error, not a traceback.""" - from dokimi.utils import InputError + from dokimi.files import InputError _local_config(tmp_path, monkeypatch, body) with pytest.raises(InputError, match="products.yaml"): create_doc_source_client("context7", cache_dir=tmp_path / "c") diff --git a/dokimi/tests/test_missing_doc_source_refused.py b/dokimi/tests/test_missing_doc_source_refused.py index a0aa73a808..778620d78b 100644 --- a/dokimi/tests/test_missing_doc_source_refused.py +++ b/dokimi/tests/test_missing_doc_source_refused.py @@ -23,7 +23,7 @@ from dokimi.orchestrator import pipeline as pipeline_mod from dokimi.treatments import create_treatment from dokimi.treatments.arms import DocTreatment, MCPAgentTreatment -from dokimi.utils import InputError +from dokimi.files import InputError PREFIXES = ["local", "okf"] diff --git a/dokimi/tests/test_model_compare.py b/dokimi/tests/test_model_compare.py index f17a99e492..867a33a94c 100644 --- a/dokimi/tests/test_model_compare.py +++ b/dokimi/tests/test_model_compare.py @@ -19,7 +19,7 @@ prompt_digests, scored_arms, ) -from dokimi.utils import InputError +from dokimi.files import InputError # --------------------------------------------------------------------------- diff --git a/dokimi/tests/test_model_compare_eval_file.py b/dokimi/tests/test_model_compare_eval_file.py index a40a79a67e..fee63dc5bf 100644 --- a/dokimi/tests/test_model_compare_eval_file.py +++ b/dokimi/tests/test_model_compare_eval_file.py @@ -10,8 +10,8 @@ import pytest from dokimi import cli +from dokimi.files import InputError from dokimi.report.model_compare import load_run -from dokimi.utils import InputError _EVAL_FILE = {"evaluations": [ {"question_id": f"q{i}", "question_text": "Q?", "difficulty": "easy", diff --git a/dokimi/tests/test_model_compare_exit_codes.py b/dokimi/tests/test_model_compare_exit_codes.py index f1f7443a22..390be6c4fa 100644 --- a/dokimi/tests/test_model_compare_exit_codes.py +++ b/dokimi/tests/test_model_compare_exit_codes.py @@ -16,7 +16,7 @@ from dokimi import cli from dokimi.report.model_compare import check_run_consistency -from dokimi.utils import InputError +from dokimi.files import InputError from tests.test_model_compare import _V1, _run_pair, _stamped _NULL_ARM = {"baseline_arm": "baseline", "answers": [ diff --git a/dokimi/tests/test_model_compare_overflow.py b/dokimi/tests/test_model_compare_overflow.py index 6dea204da5..9353581cc5 100644 --- a/dokimi/tests/test_model_compare_overflow.py +++ b/dokimi/tests/test_model_compare_overflow.py @@ -8,7 +8,7 @@ import pytest from dokimi.report.model_compare import extract_scores, generate_section_report, pool_replicate_scores -from dokimi.utils import InputError +from dokimi.files import InputError def _run(baseline: float, treatment: float) -> dict: diff --git a/dokimi/tests/test_novelty_analyze_cap_partial.py b/dokimi/tests/test_novelty_analyze_cap_partial.py index 5afa491479..b064043664 100644 --- a/dokimi/tests/test_novelty_analyze_cap_partial.py +++ b/dokimi/tests/test_novelty_analyze_cap_partial.py @@ -23,7 +23,7 @@ from dokimi.novelty import cost as novelty_cost from dokimi.novelty.analyze import AnalyzeConfig, analyze, load_artifact_text from dokimi.novelty.client import LLMClient, SpendCap -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_paths import novelty_argv from tests.test_novelty_analyze import SKILL, _scripted diff --git a/dokimi/tests/test_novelty_answer_key_wiring.py b/dokimi/tests/test_novelty_answer_key_wiring.py index 175c2ecc86..c298d32b98 100644 --- a/dokimi/tests/test_novelty_answer_key_wiring.py +++ b/dokimi/tests/test_novelty_answer_key_wiring.py @@ -15,7 +15,7 @@ from dokimi.novelty.atoms import save_atoms from dokimi.novelty.bundle import load_bundle from dokimi.novelty.spans import segment -from dokimi.utils import InputError +from dokimi.files import InputError _SKILL = """\ --- diff --git a/dokimi/tests/test_novelty_atom_labels.py b/dokimi/tests/test_novelty_atom_labels.py index eb5593c421..f92bca273c 100644 --- a/dokimi/tests/test_novelty_atom_labels.py +++ b/dokimi/tests/test_novelty_atom_labels.py @@ -12,7 +12,7 @@ from dokimi.cli import build_parser from dokimi.novelty.atom_labels import label_shares, load_atom_labels -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_refusal import refusal from tests.test_novelty_atom_verdicts import _analyze, _run from tests.test_novelty_atom_verdicts import mixed_models as _mixed_models diff --git a/dokimi/tests/test_novelty_atom_verdicts.py b/dokimi/tests/test_novelty_atom_verdicts.py index 8217ec7103..051e50dbff 100644 --- a/dokimi/tests/test_novelty_atom_verdicts.py +++ b/dokimi/tests/test_novelty_atom_verdicts.py @@ -18,7 +18,7 @@ from dokimi.commands.novelty_view_inputs import load_atom_verdicts from dokimi.novelty import client as client_mod from dokimi.novelty.atoms import load_atoms_record -from dokimi.utils import InputError +from dokimi.files import InputError from tests.test_novelty_analyze import _scripted from tests.test_novelty_journey import _run from tests.test_novelty_journey import skill as _journey_skill diff --git a/dokimi/tests/test_novelty_atoms_input.py b/dokimi/tests/test_novelty_atoms_input.py index 7b4da29ae2..4867d1598c 100644 --- a/dokimi/tests/test_novelty_atoms_input.py +++ b/dokimi/tests/test_novelty_atoms_input.py @@ -9,7 +9,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_paths import novelty_argv diff --git a/dokimi/tests/test_novelty_atoms_sample.py b/dokimi/tests/test_novelty_atoms_sample.py index 7418ac66cd..29d7022969 100644 --- a/dokimi/tests/test_novelty_atoms_sample.py +++ b/dokimi/tests/test_novelty_atoms_sample.py @@ -22,7 +22,7 @@ from dokimi.novelty.client import LLMClient from dokimi.novelty.spans import segment from dokimi.novelty.tiers import resolve_settings -from dokimi.utils import InputError +from dokimi.files import InputError from tests import test_novelty_cli as novelty_cli from tests.cli_paths import novelty_argv from tests.test_novelty_analyze import _scripted diff --git a/dokimi/tests/test_novelty_cache_dir_usable.py b/dokimi/tests/test_novelty_cache_dir_usable.py index 2a77b07332..6a9d9f08cd 100644 --- a/dokimi/tests/test_novelty_cache_dir_usable.py +++ b/dokimi/tests/test_novelty_cache_dir_usable.py @@ -15,7 +15,7 @@ from dokimi.novelty import cost as novelty_cost from dokimi.novelty.atoms import Atom, save_atoms from dokimi.novelty.spans import segment -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_refusal import refusal diff --git a/dokimi/tests/test_novelty_cap_partial.py b/dokimi/tests/test_novelty_cap_partial.py index 195b4d4959..63c6da4382 100644 --- a/dokimi/tests/test_novelty_cap_partial.py +++ b/dokimi/tests/test_novelty_cap_partial.py @@ -21,7 +21,7 @@ from dokimi.cli import build_parser from dokimi.metrics.usage import UsageRecord from dokimi.novelty.client import LLMClient, SpendCap -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_paths import novelty_argv ROWS = "\n\n".join(f"Setting number {i} defaults to {i * 10}." for i in range(1, 201)) + "\n" diff --git a/dokimi/tests/test_novelty_checks.py b/dokimi/tests/test_novelty_checks.py index 215ac48c81..8f1f815a1b 100644 --- a/dokimi/tests/test_novelty_checks.py +++ b/dokimi/tests/test_novelty_checks.py @@ -19,7 +19,7 @@ verify_keys) from dokimi.novelty.measure import MeasureResult, ProbeRun, resolve_verdict, run_checks, run_measurement from dokimi.novelty.probes import build_probes -from dokimi.utils import InputError +from dokimi.files import InputError PERF_HELP = """ usage: perf report [] diff --git a/dokimi/tests/test_novelty_cli.py b/dokimi/tests/test_novelty_cli.py index 766b6fed90..0af4afb6fa 100644 --- a/dokimi/tests/test_novelty_cli.py +++ b/dokimi/tests/test_novelty_cli.py @@ -25,7 +25,7 @@ DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER, ) -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_paths import artifact_flag, novelty_argv @@ -98,7 +98,7 @@ def test_a_judge_provider_with_no_default_judge_there_exits(argv): @pytest.mark.parametrize("model", ["sonnet", "opus", "haiku", "claude-opus-5-5"]) def test_a_cli_answerer_with_no_judge_flags_is_judged_on_the_cli_by_another_family(model): - from dokimi.utils import same_model + from dokimi.model_names import same_model args = _parse("skill", "novelty", "analyze", "--artifact", "skill:x", "--model", f"claude-cli/{model}") _extractor, _answerer, judge = novelty_cost.clients(args) diff --git a/dokimi/tests/test_novelty_controls.py b/dokimi/tests/test_novelty_controls.py index 0ca87598de..6903c39b76 100644 --- a/dokimi/tests/test_novelty_controls.py +++ b/dokimi/tests/test_novelty_controls.py @@ -15,7 +15,7 @@ from dokimi.novelty.measure import ERRORED, ProbeRun, paired_outcomes, run_measurement from dokimi.novelty.probes import Probe from dokimi.novelty.report import build_probe_record -from dokimi.utils import InputError +from dokimi.files import InputError RIGHT, WRONG = "correct_complete", "wrong_other" diff --git a/dokimi/tests/test_novelty_gate.py b/dokimi/tests/test_novelty_gate.py index 74b58d7c70..ff8beb2738 100644 --- a/dokimi/tests/test_novelty_gate.py +++ b/dokimi/tests/test_novelty_gate.py @@ -231,7 +231,7 @@ def test_cell_warnings_reach_the_subject_warning_list(): def test_an_attached_artifact_must_validate(tmp_path): import json - from dokimi.utils import InputError + from dokimi.files import InputError bad = tmp_path / "novelty.json" bad.write_text(json.dumps({"schema_version": "novelty.v1"}), encoding="utf-8") diff --git a/dokimi/tests/test_novelty_ground_symbols.py b/dokimi/tests/test_novelty_ground_symbols.py index 5e8f67781b..3239119961 100644 --- a/dokimi/tests/test_novelty_ground_symbols.py +++ b/dokimi/tests/test_novelty_ground_symbols.py @@ -19,7 +19,7 @@ from dokimi.novelty.atoms import Atom, Span, load_atoms_record, save_atoms from dokimi.novelty.grounding import add_checks, identifiers_check, verify_keys from dokimi.novelty.symbols import header_names, nm_names, symbol_pattern, symbols_check -from dokimi.utils import InputError +from dokimi.files import InputError from tests.growth_timing import GROWTH_LIMIT, growth PREFIXES = ("cblas_", "LAPACKE_", "mkl_") diff --git a/dokimi/tests/test_novelty_journey.py b/dokimi/tests/test_novelty_journey.py index 8684ee3e95..2e3057df0a 100644 --- a/dokimi/tests/test_novelty_journey.py +++ b/dokimi/tests/test_novelty_journey.py @@ -22,7 +22,7 @@ from dokimi.cli import build_parser from dokimi.novelty import client as client_mod -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_paths import artifact_flag, novelty_argv from tests.test_novelty_analyze import SKILL, _scripted diff --git a/dokimi/tests/test_novelty_panel.py b/dokimi/tests/test_novelty_panel.py index f3591b4c48..bf7b1e46f9 100644 --- a/dokimi/tests/test_novelty_panel.py +++ b/dokimi/tests/test_novelty_panel.py @@ -26,7 +26,7 @@ from dokimi.novelty.panel import aggregate, panel_warnings, shared_vendors from dokimi.novelty.panel_record import panel_record from dokimi.novelty.probes import Probe -from dokimi.utils import InputError +from dokimi.files import InputError CC, CMQ, PC = "correct_complete", "correct_missing_qualifier", "partially_correct" WO, WR, AB = "wrong_other", "wrong_reversed", "abstained" diff --git a/dokimi/tests/test_novelty_permanent_stop.py b/dokimi/tests/test_novelty_permanent_stop.py index e8ab9cd9e6..b9686d416c 100644 --- a/dokimi/tests/test_novelty_permanent_stop.py +++ b/dokimi/tests/test_novelty_permanent_stop.py @@ -315,7 +315,7 @@ def test_analyze_keeps_a_partial_record_when_the_answerer_has_no_credentials(tmp def test_a_partial_file_of_a_provider_error_is_refused_with_advice_that_helps(tmp_path): from dokimi.artifacts import load_artifact from dokimi.novelty.atoms import load_atoms_record - from dokimi.utils import InputError + from dokimi.files import InputError block = {"reason": "permanent_error", "message": "permanent error: bad key"} atoms, novelty = tmp_path / "atoms.partial.json", tmp_path / "novelty.partial.json" diff --git a/dokimi/tests/test_novelty_provenance.py b/dokimi/tests/test_novelty_provenance.py index a2f838321f..14ad1491df 100644 --- a/dokimi/tests/test_novelty_provenance.py +++ b/dokimi/tests/test_novelty_provenance.py @@ -17,7 +17,7 @@ from dokimi.novelty.judge2 import agreement, cohen_kappa, regrade from dokimi.novelty.measure import ERRORED, MeasureResult, ProbeRun from dokimi.novelty.probes import Probe -from dokimi.utils import InputError +from dokimi.files import InputError RIGHT, WRONG, REVERSED = "correct_complete", "wrong_other", "wrong_reversed" diff --git a/dokimi/tests/test_novelty_retest.py b/dokimi/tests/test_novelty_retest.py index 96e17f9417..7d1e5352c3 100644 --- a/dokimi/tests/test_novelty_retest.py +++ b/dokimi/tests/test_novelty_retest.py @@ -18,7 +18,7 @@ from dokimi.cli import build_parser from dokimi.commands import novelty_retest as novelty_cmd from dokimi.novelty.retest import load_runs, pair_runs, render_markdown, retest_summary -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_paths import novelty_argv # (seed 0, seed 2) headline lenient K0 of the ten S2 skills (the 2026-11-09 retest). diff --git a/dokimi/tests/test_novelty_routing.py b/dokimi/tests/test_novelty_routing.py index 2cf8a52ae0..2ebf0e783d 100644 --- a/dokimi/tests/test_novelty_routing.py +++ b/dokimi/tests/test_novelty_routing.py @@ -11,7 +11,7 @@ import pytest from dokimi.novelty import cost as novelty_cost -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.cli import build_parser from dokimi.novelty.client import LLMClient from dokimi.novelty.routing import ( diff --git a/dokimi/tests/test_novelty_routing_acceptable.py b/dokimi/tests/test_novelty_routing_acceptable.py index 613e9f5616..f62572018e 100644 --- a/dokimi/tests/test_novelty_routing_acceptable.py +++ b/dokimi/tests/test_novelty_routing_acceptable.py @@ -19,7 +19,7 @@ ) from dokimi.novelty.client import LLMClient from dokimi.novelty.routing import Candidate, RoutingInputError -from dokimi.utils import InputError +from dokimi.files import InputError PERF = Candidate(name="linux-perf", description="Profile a slow Linux binary with perf") DB = Candidate(name="db-tuner", description="Tune a slow database query with an index") diff --git a/dokimi/tests/test_novelty_routing_all_vs_all.py b/dokimi/tests/test_novelty_routing_all_vs_all.py index 24a89a0e2f..7e264cd508 100644 --- a/dokimi/tests/test_novelty_routing_all_vs_all.py +++ b/dokimi/tests/test_novelty_routing_all_vs_all.py @@ -11,7 +11,7 @@ import pytest from dokimi.novelty import cost as novelty_cost -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.cli import build_parser from dokimi.novelty.client import LLMClient from dokimi.novelty.all_vs_all import all_vs_all, load_queries_by_skill diff --git a/dokimi/tests/test_novelty_routing_cli_gaps.py b/dokimi/tests/test_novelty_routing_cli_gaps.py index a1126d5843..69e87976a4 100644 --- a/dokimi/tests/test_novelty_routing_cli_gaps.py +++ b/dokimi/tests/test_novelty_routing_cli_gaps.py @@ -14,7 +14,7 @@ from dokimi.novelty import cost as novelty_cost from dokimi.cli import build_parser from dokimi.novelty.client import LLMClient -from dokimi.utils import InputError +from dokimi.files import InputError def _parse(*argv): diff --git a/dokimi/tests/test_novelty_routing_field.py b/dokimi/tests/test_novelty_routing_field.py index 23174fe293..75d9588c47 100644 --- a/dokimi/tests/test_novelty_routing_field.py +++ b/dokimi/tests/test_novelty_routing_field.py @@ -9,7 +9,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.cli import build_parser from dokimi.commands.novelty_routing_inputs import routing_field from dokimi.novelty.routing import ( diff --git a/dokimi/tests/test_novelty_routing_gaps.py b/dokimi/tests/test_novelty_routing_gaps.py index 3deb27006a..949a6d321b 100644 --- a/dokimi/tests/test_novelty_routing_gaps.py +++ b/dokimi/tests/test_novelty_routing_gaps.py @@ -15,7 +15,7 @@ from dokimi.cli import build_parser from dokimi.novelty.client import LLMClient from dokimi.novelty.routing import catalog_competitors -from dokimi.utils import InputError +from dokimi.files import InputError def _parse(*argv): diff --git a/dokimi/tests/test_novelty_settings_parity.py b/dokimi/tests/test_novelty_settings_parity.py index 462d27dd86..c1b6ab433c 100644 --- a/dokimi/tests/test_novelty_settings_parity.py +++ b/dokimi/tests/test_novelty_settings_parity.py @@ -37,7 +37,7 @@ from dokimi.novelty import cost as novelty_cost from dokimi.cli import build_parser -from dokimi.utils import InputError +from dokimi.files import InputError from tests.test_novelty_analyze import SKILL, _scripted GOLDEN = Path(__file__).resolve().parent / "fixtures" / "novelty_settings_main.json" diff --git a/dokimi/tests/test_novelty_shorten_artifact.py b/dokimi/tests/test_novelty_shorten_artifact.py index 3bc43f0317..d6d00256a9 100644 --- a/dokimi/tests/test_novelty_shorten_artifact.py +++ b/dokimi/tests/test_novelty_shorten_artifact.py @@ -10,7 +10,7 @@ from dokimi.cli import build_parser from dokimi.novelty.atoms import save_atoms from dokimi.novelty.spans import segment -from dokimi.utils import InputError +from dokimi.files import InputError from tests.cli_paths import artifact_flag, novelty_argv diff --git a/dokimi/tests/test_novelty_sweep.py b/dokimi/tests/test_novelty_sweep.py index df10f39583..fcac2d447f 100644 --- a/dokimi/tests/test_novelty_sweep.py +++ b/dokimi/tests/test_novelty_sweep.py @@ -15,7 +15,7 @@ ALL, UNASSIGNED, group_stats, load_strata, make_row, measured_fields, new_share, read_rows, resumable, stratum_of, summarize, summary_lines, ) -from dokimi.utils import InputError +from dokimi.files import InputError SETTINGS = {"max_atoms": 120} diff --git a/dokimi/tests/test_opportunities.py b/dokimi/tests/test_opportunities.py index 4704147091..3d33886e4d 100644 --- a/dokimi/tests/test_opportunities.py +++ b/dokimi/tests/test_opportunities.py @@ -4,7 +4,7 @@ import pytest from dokimi import llms_txt, opportunities as opp -from dokimi.utils import InputError +from dokimi.files import InputError NOVELTY = { "artifact": {"kind": "skill", "ref": "skill:skills/acme"}, diff --git a/dokimi/tests/test_opportunities_command.py b/dokimi/tests/test_opportunities_command.py index 6931a95d16..f71de3c635 100644 --- a/dokimi/tests/test_opportunities_command.py +++ b/dokimi/tests/test_opportunities_command.py @@ -9,7 +9,7 @@ from dokimi.artifacts import validate_artifact from dokimi.commands import opportunities as cmd -from dokimi.utils import InputError +from dokimi.files import InputError STATIC = {"schema": "repo_static.v1", "claims": [ {"file": "AGENTS.md", "line": 9, "status": "fail_missing_path"}, diff --git a/dokimi/tests/test_pattern_glob.py b/dokimi/tests/test_pattern_glob.py index 4cb242b1aa..5843edbd9f 100644 --- a/dokimi/tests/test_pattern_glob.py +++ b/dokimi/tests/test_pattern_glob.py @@ -17,7 +17,7 @@ from dokimi.cli import build_parser from dokimi.novelty.symbols import _files from dokimi.pattern_glob import expand, has_magic -from dokimi.utils import InputError +from dokimi.files import InputError needs_modes = pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") diff --git a/dokimi/tests/test_question_ids.py b/dokimi/tests/test_question_ids.py index 14295fe810..cf4f0d5cb4 100644 --- a/dokimi/tests/test_question_ids.py +++ b/dokimi/tests/test_question_ids.py @@ -6,12 +6,12 @@ `questions.v1` allows integer ids, and ``q.get("id") or ...`` reads ``0`` as missing: a question with id 0 was renamed, dropped, or given a fallback id depending on which module read it. Every site now goes through -``dokimi.utils.question_id``. +``dokimi.records.question_id``. """ import pytest -from dokimi.utils import question_id +from dokimi.records import question_id @pytest.mark.parametrize("q, expected", [ diff --git a/dokimi/tests/test_questions_artifact.py b/dokimi/tests/test_questions_artifact.py index 443508cb70..b1dbc7cf2c 100644 --- a/dokimi/tests/test_questions_artifact.py +++ b/dokimi/tests/test_questions_artifact.py @@ -24,7 +24,7 @@ from dokimi.datasets_export import export_artifact from dokimi.questions.artifact import load_questions, save_questions_artifact, upgrade_questions from dokimi.questions.normalizer import canonical_question, normalize_question -from dokimi.utils import InputError +from dokimi.files import InputError from tests.artifact_fixtures import artifact_fixture from tests.cli_refusal import refusal diff --git a/dokimi/tests/test_questions_generate_inputs.py b/dokimi/tests/test_questions_generate_inputs.py index fdd4358ae2..74da6997be 100644 --- a/dokimi/tests/test_questions_generate_inputs.py +++ b/dokimi/tests/test_questions_generate_inputs.py @@ -220,7 +220,7 @@ def test_require_local_doc_source_reports_a_permission_error_as_unreadable(monke from pathlib import Path from dokimi.mcp.factory import require_local_doc_source - from dokimi.utils import InputError + from dokimi.files import InputError def denied(self): raise PermissionError(13, "Permission denied", str(self)) @@ -237,7 +237,7 @@ def test_require_local_doc_source_reports_a_denied_directory_when_exists_answers from pathlib import Path from dokimi.mcp.factory import require_local_doc_source - from dokimi.utils import InputError + from dokimi.files import InputError restricted = tmp_path / "restricted" (restricted / "docs").mkdir(parents=True) @@ -293,7 +293,7 @@ def test_require_local_doc_source_reports_an_existing_unreadable_file_as_unreada import os from dokimi.mcp.factory import require_local_doc_source - from dokimi.utils import InputError + from dokimi.files import InputError doc = tmp_path / "docs.md" doc.write_text("# docs\n") @@ -312,7 +312,7 @@ def test_require_local_doc_source_reports_a_directory_without_search_permission_ import os from dokimi.mcp.factory import require_local_doc_source - from dokimi.utils import InputError + from dokimi.files import InputError docs = tmp_path / "docs" docs.mkdir() diff --git a/dokimi/tests/test_record_readers.py b/dokimi/tests/test_record_readers.py index bf5fde0521..3c810c9f5a 100644 --- a/dokimi/tests/test_record_readers.py +++ b/dokimi/tests/test_record_readers.py @@ -18,7 +18,7 @@ from dokimi.eval.panel import JudgePanel, PanelVerdict from dokimi.records import RecordError -from dokimi.utils import InputError +from dokimi.files import InputError from tests.artifact_fixtures import artifact_fixture diff --git a/dokimi/tests/test_records_readers.py b/dokimi/tests/test_records_readers.py index bb17ccad0d..61070d7f7a 100644 --- a/dokimi/tests/test_records_readers.py +++ b/dokimi/tests/test_records_readers.py @@ -22,7 +22,8 @@ from dokimi.records import RecordError from dokimi.report.arms_report import render_arms_report from dokimi.report.model_compare import check_run_consistency, extract_scores, load_run -from dokimi.utils import InputError, digest_text +from dokimi.files import InputError +from dokimi.digest import digest_text ARTIFACTS = Path(__file__).parent / "fixtures" / "artifacts" diff --git a/dokimi/tests/test_regression.py b/dokimi/tests/test_regression.py index 543a882435..8c174aff91 100644 --- a/dokimi/tests/test_regression.py +++ b/dokimi/tests/test_regression.py @@ -6,7 +6,7 @@ import pytest from dokimi.gate.regression import detect_regressions -from dokimi.utils import InputError +from dokimi.files import InputError def _score(result): diff --git a/dokimi/tests/test_replicates.py b/dokimi/tests/test_replicates.py index 73a2185c17..9fdc9882c1 100644 --- a/dokimi/tests/test_replicates.py +++ b/dokimi/tests/test_replicates.py @@ -10,7 +10,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.report.model_compare import ( check_run_consistency, group_replicates, diff --git a/dokimi/tests/test_repo_choices.py b/dokimi/tests/test_repo_choices.py index 902a700cf3..1a8bda0e3e 100644 --- a/dokimi/tests/test_repo_choices.py +++ b/dokimi/tests/test_repo_choices.py @@ -431,7 +431,7 @@ def test_a_deeply_nested_baseline_is_refused_as_input_not_a_crash(tmp_path): import argparse from dokimi.commands.repo_scan import baseline_from - from dokimi.utils import InputError + from dokimi.files import InputError path = tmp_path / "deep.json" path.write_text("[" * 5000 + "]" * 5000, encoding="utf-8") diff --git a/dokimi/tests/test_repo_config_git_blobs.py b/dokimi/tests/test_repo_config_git_blobs.py index 3d706099d8..a694895dee 100644 --- a/dokimi/tests/test_repo_config_git_blobs.py +++ b/dokimi/tests/test_repo_config_git_blobs.py @@ -15,9 +15,9 @@ import pytest -from dokimi import utils +from dokimi import digest from dokimi.repo_config import ConfigError, load_repo_config -from dokimi.utils import git_tree, tree_digest +from dokimi.digest import git_tree, tree_digest HEADER = "schema_version: dokimi_config.v1\n" CONFIG = HEADER + "subjects:\n - id: skill/a\n path: skills/a\n suite: skills/a/evals\n" @@ -164,7 +164,7 @@ def test_a_name_git_stdin_misreads_digests_the_same_edited_and_committed(tmp_pat @pytest.mark.skipif(shutil.which("git") is None, reason="needs git") @pytest.mark.skipif(os.name == "nt", reason="Windows file names cannot hold a newline") def test_odd_names_beyond_one_command_line_digest_the_same_edited_and_committed(tmp_path, monkeypatch): - monkeypatch.setattr("dokimi.utils._ARG_BUDGET", 120) # a few names per git call: several batches + monkeypatch.setattr("dokimi.digest._ARG_BUDGET", 120) # a few names per git call: several batches names = {f"we\nird{i}.txt": "one\n" for i in range(12)} root = _repo(tmp_path / "r", {**FILES, **names}) for name in names: @@ -177,13 +177,13 @@ def test_odd_names_beyond_one_command_line_digest_the_same_edited_and_committed( @pytest.mark.skipif(shutil.which("git") is None, reason="needs git") @pytest.mark.skipif(os.name == "nt", reason="Windows file names cannot hold a newline") def test_a_failed_batch_of_odd_names_raises_instead_of_hashing_their_bytes(tmp_path, monkeypatch): - monkeypatch.setattr("dokimi.utils._ARG_BUDGET", 30) + monkeypatch.setattr("dokimi.digest._ARG_BUDGET", 30) root = _repo(tmp_path / "r", {**FILES, **{f"we\nird{i}.txt": "one\n" for i in range(4)}}) odd = [p for p in root.iterdir() if "\n" in p.name] for path in odd: path.write_text("two\n") # edited: git's index no longer holds the blob id tree = git_tree(root) - real = utils._hash_objects + real = digest._hash_objects calls = [] def second_fails(top, rels, *, as_args): @@ -192,9 +192,9 @@ def second_fails(top, rels, *, as_args): return None return real(top, rels, as_args=as_args) - monkeypatch.setattr(utils, "_hash_objects", second_fails) + monkeypatch.setattr(digest, "_hash_objects", second_fails) with pytest.raises(OSError, match="hash-object"): - utils.file_contents(odd, tree) + digest.file_contents(odd, tree) assert calls.count(True) == 2 # the batches were tried in turn, and the failure stopped them @@ -203,9 +203,9 @@ def test_a_hash_object_that_fails_raises_instead_of_moving_the_digest(tmp_path, root = _repo(tmp_path / "r", FILES) (root / "skills/a/SKILL.md").write_text("edited\n") # not the index's blob: git must hash it tree = git_tree(root) - monkeypatch.setattr(utils, "_hash_objects", lambda *a, **k: None) + monkeypatch.setattr(digest, "_hash_objects", lambda *a, **k: None) with pytest.raises(OSError, match="hash-object"): - utils.file_contents([root / "skills/a/SKILL.md"], tree) + digest.file_contents([root / "skills/a/SKILL.md"], tree) @pytest.mark.skipif(shutil.which("git") is None, reason="needs git") @@ -217,7 +217,7 @@ def test_a_failed_hash_object_says_why_git_failed(tmp_path): (root / "skills/a/SKILL.md").write_text("edited\n") tree = git_tree(root) with pytest.raises(OSError, match="(?s)hash-object failed: .*clean filter .broken. failed"): - utils.file_contents([root / "skills/a/SKILL.md"], tree) + digest.file_contents([root / "skills/a/SKILL.md"], tree) def test_a_committed_lf_to_crlf_change_moves_suite_hash(tmp_path): @@ -512,9 +512,9 @@ def _owned_by_another_user(monkeypatch, repo: Path) -> None: """Git refuses the repository at ``repo`` as owned by another user (safe.directory), through git's own test knob, on every git call whose arguments name ``repo`` (or a path under it). An empty safe.directory entry clears any allow-list (a runner's global ``safe.directory = *`` would otherwise lift the refusal).""" - from dokimi import process, utils + from dokimi import digest, process - base = utils._git_env() + base = digest._git_env() named = re.compile(re.escape(str(repo)) + r"(?![\w.-])") real_run = process.run refuse = {"GIT_TEST_ASSUME_DIFFERENT_OWNER": "1", "LC_ALL": "C", "GIT_CONFIG_COUNT": "1", diff --git a/dokimi/tests/test_repo_config_links.py b/dokimi/tests/test_repo_config_links.py index eb0e2ea4b5..146f0a84f7 100644 --- a/dokimi/tests/test_repo_config_links.py +++ b/dokimi/tests/test_repo_config_links.py @@ -197,16 +197,16 @@ def folded(path): # Windows: the declared name is the directory, and it resolve @pytest.mark.parametrize("added", [True, False], ids=["tracked", "untracked"]) def test_a_suite_of_many_files_reads_the_git_index_once(tmp_path, monkeypatch, added): # each eval file used to start its own git ls-files: one per file, for every subject's suite hash - from dokimi import repo_config, utils + from dokimi import digest, repo_config calls: list[Path] = [] - read = utils._tracked_modes + read = digest._tracked_modes def counting(base, spec): calls.append(base) return read(base, spec) - monkeypatch.setattr(utils, "_tracked_modes", counting) + monkeypatch.setattr(digest, "_tracked_modes", counting) monkeypatch.setattr(repo_config, "_tracked_modes", counting) files = {"skills/a/SKILL.md": "a\n", **{f"evaluation/t{i}/q.json": "[]\n" for i in range(30)}} root = _tree(tmp_path / "repo", { diff --git a/dokimi/tests/test_repo_hits_judge_failures.py b/dokimi/tests/test_repo_hits_judge_failures.py index b53a6d8f27..305a18b9c6 100644 --- a/dokimi/tests/test_repo_hits_judge_failures.py +++ b/dokimi/tests/test_repo_hits_judge_failures.py @@ -37,7 +37,7 @@ def test_an_input_error_after_the_judge_calls_with_json_prints_an_input_document judge_llm, monkeypatch): # noqa: F811 # an InputError raised after the paid calls (here in summary) exits 2 with its document, and the cost of the calls import dokimi.repos.hits_judge as hits_judge - from dokimi.utils import InputError + from dokimi.files import InputError batch = _batch(tmp_path) _put(batch, "guidance:raw", 3, [_f(30, "mul adds")]) diff --git a/dokimi/tests/test_repo_run.py b/dokimi/tests/test_repo_run.py index 7235849a62..9af302d9b7 100644 --- a/dokimi/tests/test_repo_run.py +++ b/dokimi/tests/test_repo_run.py @@ -16,7 +16,7 @@ from dokimi.cli import build_parser from dokimi.repos.container import CONTENT_DIR, HARNESS_DIR, RUN_DIR, SOURCE_DIR, WORKSPACE from dokimi.repos.report import format_report, summarize, wilson -from dokimi.utils import same_model +from dokimi.model_names import same_model from repo_eval_fixture import FakeRunner, fake_harness, git, make_repo diff --git a/dokimi/tests/test_repo_scan_baseline_depth.py b/dokimi/tests/test_repo_scan_baseline_depth.py index 42ef8af300..10b6b8b10c 100644 --- a/dokimi/tests/test_repo_scan_baseline_depth.py +++ b/dokimi/tests/test_repo_scan_baseline_depth.py @@ -9,7 +9,7 @@ import pytest from dokimi.commands.repo_scan import baseline_from -from dokimi.utils import InputError +from dokimi.files import InputError def test_a_deeply_nested_baseline_is_an_input_error(tmp_path): diff --git a/dokimi/tests/test_repo_scan_deep_baseline.py b/dokimi/tests/test_repo_scan_deep_baseline.py index 00abc8791d..0bf1216a3e 100644 --- a/dokimi/tests/test_repo_scan_deep_baseline.py +++ b/dokimi/tests/test_repo_scan_deep_baseline.py @@ -10,7 +10,7 @@ import pytest from dokimi.commands.repo_scan import baseline_from -from dokimi.utils import InputError +from dokimi.files import InputError def test_a_deeply_nested_baseline_is_an_input_error(tmp_path): diff --git a/dokimi/tests/test_repo_security.py b/dokimi/tests/test_repo_security.py index d28fce15f3..9b7d10514a 100644 --- a/dokimi/tests/test_repo_security.py +++ b/dokimi/tests/test_repo_security.py @@ -570,7 +570,7 @@ def test_unreadable_input_is_a_usage_error_not_a_traceback(tmp_path, monkeypatch import argparse from dokimi.commands import repo_security - from dokimi.utils import InputError + from dokimi.files import InputError _cell(tmp_path, "t", BASE, 0, events=[_cmd("pytest")]) diff --git a/dokimi/tests/test_repo_skill_arms.py b/dokimi/tests/test_repo_skill_arms.py index 7b9006299c..422918434d 100644 --- a/dokimi/tests/test_repo_skill_arms.py +++ b/dokimi/tests/test_repo_skill_arms.py @@ -16,7 +16,7 @@ import pytest from dokimi.cli import build_parser -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.repos.arms import ArmError, Skill, check_arms, resolve_skills, skill_usage, tree_sha256 from dokimi.repos.events import convert from dokimi.repos.report import format_report, summarize diff --git a/dokimi/tests/test_repo_source_exit_2.py b/dokimi/tests/test_repo_source_exit_2.py index 3e38fb318a..608eabd41b 100644 --- a/dokimi/tests/test_repo_source_exit_2.py +++ b/dokimi/tests/test_repo_source_exit_2.py @@ -219,7 +219,7 @@ def test_a_windows_manifest_path_leaving_an_unpinned_tree_is_refused_as_typed(tm from types import SimpleNamespace from dokimi.commands import repo_run - from dokimi.utils import InputError + from dokimi.files import InputError source = SimpleNamespace(location=str(tmp_path), remote=False, rev=None, subdir=None) # What Windows does with `..\x`, written back with `/` so the posix tree compares. @@ -237,7 +237,7 @@ def test_a_windows_drive_manifest_is_refused_for_an_unpinned_tree(tmp_path, monk from types import SimpleNamespace from dokimi.commands import repo_run - from dokimi.utils import InputError + from dokimi.files import InputError source = SimpleNamespace(location=str(tmp_path), remote=False, rev=None, subdir=None) windows_path = SimpleNamespace(normpath=ntpath.normpath, sep="\\", splitdrive=ntpath.splitdrive) @@ -253,7 +253,7 @@ def test_a_windows_manifest_path_leaving_a_pinned_tree_is_refused_as_typed(monke from types import SimpleNamespace from dokimi.commands import repo_run - from dokimi.utils import InputError + from dokimi.files import InputError pinned = SimpleNamespace(location="https://example.invalid/r.git", remote=True, rev="a" * 40, subdir=None) windows_path = SimpleNamespace(normpath=ntpath.normpath, sep="\\", splitdrive=ntpath.splitdrive) # as Windows @@ -270,7 +270,7 @@ def test_a_pinned_source_gets_only_the_tree_path_check_for_a_manifest_that_stays from types import SimpleNamespace from dokimi.commands import repo_run - from dokimi.utils import InputError + from dokimi.files 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)) diff --git a/dokimi/tests/test_repo_suite.py b/dokimi/tests/test_repo_suite.py index 2b7cca520c..7bc6e762f2 100644 --- a/dokimi/tests/test_repo_suite.py +++ b/dokimi/tests/test_repo_suite.py @@ -16,7 +16,7 @@ from dokimi.cli import build_parser from dokimi.repos.source import RepoSource, open_source from dokimi.repos.suite import SuiteError, load_suite, parse_suite, resolve_suite -from dokimi.utils import InputError +from dokimi.files import InputError from repo_eval_fixture import PROFILE, FakeRunner, fake_harness, git, make_repo, write from test_repo_host import AMD_CPUINFO, HostRunner, _probe_out from test_repo_host import _check as _host_check diff --git a/dokimi/tests/test_run_envelope.py b/dokimi/tests/test_run_envelope.py index 574b5f173c..2d98d09bf7 100644 --- a/dokimi/tests/test_run_envelope.py +++ b/dokimi/tests/test_run_envelope.py @@ -32,7 +32,7 @@ from dokimi.dokimi_commit import dokimi_commit from dokimi.runner.plan import plan_digest from dokimi.runs.scan import scan -from dokimi.utils import InputError +from dokimi.files import InputError FIXTURES = Path(__file__).resolve().parent / "fixtures" / "artifacts" RUN_KINDS = sorted(set(SCHEMA_VERSIONS) - INPUT_KINDS) diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index ba43a373b8..f18672a952 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -23,7 +23,7 @@ from dokimi.runs import baseline, bundle from dokimi.runs.rundir import open_run from dokimi.runs.scan import RunsRoot, scan -from dokimi.utils import InputError +from dokimi.files import InputError FIXTURES = Path(__file__).resolve().parent / "fixtures" / "artifacts" RUN = "20261123T101500Z-1a2b3c4d" diff --git a/dokimi/tests/test_runs_rundir.py b/dokimi/tests/test_runs_rundir.py index 6b3faa9b08..e3a6785823 100644 --- a/dokimi/tests/test_runs_rundir.py +++ b/dokimi/tests/test_runs_rundir.py @@ -26,7 +26,7 @@ from dokimi.runner.plan import completeness from dokimi.runs import rundir from dokimi.runs.rundir import open_run -from dokimi.utils import InputError +from dokimi.files import InputError PROJECT = Path(__file__).resolve().parents[1] FIXTURES = PROJECT / "tests" / "fixtures" / "artifacts" diff --git a/dokimi/tests/test_runs_rundir_claims.py b/dokimi/tests/test_runs_rundir_claims.py index e463718fc5..2dd902239c 100644 --- a/dokimi/tests/test_runs_rundir_claims.py +++ b/dokimi/tests/test_runs_rundir_claims.py @@ -17,7 +17,7 @@ from dokimi.artifacts import RUN_ID_ENV, load_artifact, save_artifact from dokimi.runs import rm, rundir from dokimi.runs.rundir import open_run -from dokimi.utils import InputError +from dokimi.files import InputError @pytest.fixture diff --git a/dokimi/tests/test_runs_scan.py b/dokimi/tests/test_runs_scan.py index 6dcf0444ef..5eabf21a6c 100644 --- a/dokimi/tests/test_runs_scan.py +++ b/dokimi/tests/test_runs_scan.py @@ -18,7 +18,7 @@ from dokimi.artifacts import INPUT_KINDS, SCHEMA_VERSIONS, SUPERSEDED_VERSIONS, run_id, save_artifact from dokimi.runs import kinds, runs_root, scan from dokimi.runs.scan import HEAD_BYTES, RunsRoot -from dokimi.utils import InputError +from dokimi.files import InputError FIXTURES = Path(__file__).resolve().parent / "fixtures" / "artifacts" # The module, not the scan() that dokimi.runs re-exports under the same name. diff --git a/dokimi/tests/test_same_model.py b/dokimi/tests/test_same_model.py index fc5659711a..f6eb96869a 100644 --- a/dokimi/tests/test_same_model.py +++ b/dokimi/tests/test_same_model.py @@ -8,7 +8,7 @@ import pytest from dokimi.defaults import BEDROCK_MODEL_IDS -from dokimi.utils import model_identity, same_model +from dokimi.model_names import model_identity, same_model # (a, b, same) with a route-qualified name ("provider/model") where the route is part of the input. CASES = [ diff --git a/dokimi/tests/test_saved_self_judge_warning.py b/dokimi/tests/test_saved_self_judge_warning.py index c9de5ee78f..eb1ef09a3f 100644 --- a/dokimi/tests/test_saved_self_judge_warning.py +++ b/dokimi/tests/test_saved_self_judge_warning.py @@ -11,7 +11,7 @@ import pytest from dokimi.cli import parse_args -from dokimi.utils import warn_recorded_self_judge +from dokimi.model_names import warn_recorded_self_judge WARN = "Evaluator independence warning" SELF = {"model": "gpt-6.1-sol", "provider": "openai"} @@ -88,7 +88,7 @@ def _judge_argv(tmp_path): ["eval", "score", "ragas", "--answers", a, "--ragas-provider", "openai", "--ragas-model", "gpt-6.1-sol"], ], - "dokimi.utils": [ + "dokimi.commands.answer_formats": [ ["eval", "score", "reference", "--answers", a, "--questions", q, "--out", out, *j], ], "dokimi.commands.questions": [ @@ -105,7 +105,7 @@ def _judge_argv(tmp_path): ("dokimi.commands.judge_reliability", ("eval", "judge", "agreement")), ("dokimi.commands.evaluate", ("eval", "judge", "validate")), ("dokimi.commands.evaluate", ("eval", "score", "ragas")), - ("dokimi.utils", ("eval", "score", "reference")), + ("dokimi.model_names", ("eval", "score", "reference")), ("dokimi.commands.questions", ("eval", "questions", "analyze")), ("dokimi.commands.questions", ("eval", "questions", "review")), ] @@ -136,11 +136,11 @@ def stop(data, judges, context, roles=("answer", "judge")): def test_reference_with_no_judge_does_not_warn(tmp_path, monkeypatch): - from dokimi.utils import warn_recorded_self_judge as real - import dokimi.utils + from dokimi.model_names import warn_recorded_self_judge as real + import dokimi.model_names calls = [] - monkeypatch.setattr(dokimi.utils, "warn_recorded_self_judge", lambda *a, **k: calls.append(a) or real(*a, **k)) + monkeypatch.setattr(dokimi.model_names, "warn_recorded_self_judge", lambda *a, **k: calls.append(a) or real(*a, **k)) args = parse_args(["eval", "score", "reference", "--answers", str(_arms_file(tmp_path)), "--questions", str(_questions_file(tmp_path)), "--no-judge", "--out", str(tmp_path / "o.json")]) diff --git a/dokimi/tests/test_scan_gate.py b/dokimi/tests/test_scan_gate.py index 7e9e3d6e48..c12b58b127 100644 --- a/dokimi/tests/test_scan_gate.py +++ b/dokimi/tests/test_scan_gate.py @@ -139,7 +139,7 @@ def loop(self, path): # Path.resolve() raises this for a symlink loop before Py def test_an_unreadable_baseline_is_an_input_error(tmp_path, capsys): - from dokimi.utils import InputError + from dokimi.files import InputError (tmp_path / "b.json").write_text("{}", encoding="utf-8") with pytest.raises(InputError, match="not a repo_readiness.v1 report"): @@ -291,7 +291,7 @@ def test_a_static_claim_cannot_bring_its_own_baselined_mark(tmp_path, capsys): @pytest.mark.parametrize("claims", ["[null]", "[1]", '["a"]']) def test_a_baseline_claim_that_is_not_an_object_is_an_input_error(tmp_path, capsys, claims): - from dokimi.utils import InputError + from dokimi.files import InputError (tmp_path / "b.json").write_text('{"claims": %s}' % claims, encoding="utf-8") with pytest.raises(InputError, match="must be an object"): diff --git a/dokimi/tests/test_score_gate.py b/dokimi/tests/test_score_gate.py index 0e7a97dc61..335e4c977a 100644 --- a/dokimi/tests/test_score_gate.py +++ b/dokimi/tests/test_score_gate.py @@ -8,7 +8,7 @@ import pytest from dokimi.gate.score_gate import check_gate -from dokimi.utils import InputError +from dokimi.files import InputError KINDS = ("soft", "hard") diff --git a/dokimi/tests/test_seed_unsupported_route.py b/dokimi/tests/test_seed_unsupported_route.py index 45a2dfd997..55dcae54a0 100644 --- a/dokimi/tests/test_seed_unsupported_route.py +++ b/dokimi/tests/test_seed_unsupported_route.py @@ -113,7 +113,7 @@ def test_the_run_config_records_an_unsupported_seed_as_unsupported_not_as_seeded def test_runs_that_differ_only_in_the_dropped_seed_are_replicates_not_rival_models(): from dokimi.report.model_compare import check_run_consistency, replicate_key - from dokimi.utils import InputError + from dokimi.files import InputError def run(**cfg): return {"model": "m", "provider": "amazon-bedrock", "judge_model": "j", diff --git a/dokimi/tests/test_similar_skills.py b/dokimi/tests/test_similar_skills.py index fa3995e8d8..b935146415 100644 --- a/dokimi/tests/test_similar_skills.py +++ b/dokimi/tests/test_similar_skills.py @@ -28,7 +28,7 @@ _tokens, ) from dokimi.skills import Skill -from dokimi.utils import InputError +from dokimi.files import InputError def _skill(root: Path, rel: str, name: str, description: str) -> None: diff --git a/dokimi/tests/test_skill_coverage.py b/dokimi/tests/test_skill_coverage.py index 815def6b6b..4e6af2b657 100644 --- a/dokimi/tests/test_skill_coverage.py +++ b/dokimi/tests/test_skill_coverage.py @@ -17,7 +17,7 @@ import dokimi.skill_coverage as sc from dokimi.cli import build_parser from dokimi.novelty.client import LLMClient, SpendCap -from dokimi.utils import InputError +from dokimi.files import InputError class Transport: diff --git a/dokimi/tests/test_skill_selection.py b/dokimi/tests/test_skill_selection.py index dc5e06b4e9..00e4a41ad6 100644 --- a/dokimi/tests/test_skill_selection.py +++ b/dokimi/tests/test_skill_selection.py @@ -12,7 +12,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.cli import build_parser from dokimi.eval.agent_runner import _summarize_tool_usage from dokimi.eval.arm_summary import summarize_skill_selection @@ -302,7 +302,7 @@ def test_trigger_set_exits_2_with_a_message_on_an_unreadable_questions_file( def test_read_json_input_reports_a_json_recursion_error_as_an_input_error(tmp_path, monkeypatch): - from dokimi.utils import InputError, read_json_input + from dokimi.files import InputError, read_json_input qfile = tmp_path / "q.json" qfile.write_text("[]", encoding="utf-8") diff --git a/dokimi/tests/test_skill_sensitivity.py b/dokimi/tests/test_skill_sensitivity.py index 8b84b4c435..0f9980d18d 100644 --- a/dokimi/tests/test_skill_sensitivity.py +++ b/dokimi/tests/test_skill_sensitivity.py @@ -24,7 +24,7 @@ run_sensitivity, split_sentences, ) -from dokimi.utils import InputError +from dokimi.files import InputError GOLD_DESCRIPTION = ("Triage a failing build log. Use when CI fails on a merge request. " "Never for runtime profiling.") diff --git a/dokimi/tests/test_subjects.py b/dokimi/tests/test_subjects.py index 436bddcb45..3d5854925d 100644 --- a/dokimi/tests/test_subjects.py +++ b/dokimi/tests/test_subjects.py @@ -12,7 +12,7 @@ import dokimi.eval.arm_runner as arm_runner_mod from tests.cli_refusal import refusal -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi import __version__ from dokimi.artifacts import validate_artifact from dokimi.cli import build_parser diff --git a/dokimi/tests/test_subjects_long_name.py b/dokimi/tests/test_subjects_long_name.py index 1684147241..932f22fd1b 100644 --- a/dokimi/tests/test_subjects_long_name.py +++ b/dokimi/tests/test_subjects_long_name.py @@ -13,7 +13,7 @@ from dokimi.commands.subjects import cmd_subjects_list, cmd_subjects_show from dokimi.subjects import load_subject -from dokimi.utils import InputError +from dokimi.files import InputError def test_load_subject_reads_a_name_past_the_limit_as_a_missing_file(tmp_path: Path): diff --git a/dokimi/tests/test_swebench_tasks.py b/dokimi/tests/test_swebench_tasks.py index 7864bf73b5..a3a05a5098 100644 --- a/dokimi/tests/test_swebench_tasks.py +++ b/dokimi/tests/test_swebench_tasks.py @@ -19,7 +19,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.cli import build_parser from dokimi.harnesses import create_harness from dokimi.harnesses import swebench_grade as grader diff --git a/dokimi/tests/test_sync_skilltext_profile.py b/dokimi/tests/test_sync_skilltext_profile.py index ac6c99d1cd..ae514a142f 100644 --- a/dokimi/tests/test_sync_skilltext_profile.py +++ b/dokimi/tests/test_sync_skilltext_profile.py @@ -80,7 +80,7 @@ def test_unterminated_frontmatter_reads_as_empty(): ], ) def test_the_copied_block_and_the_parsed_block_agree(text): - from dokimi.utils import parse_frontmatter + from dokimi.frontmatter import parse_frontmatter header = sync.frontmatter_block(text) meta, body = parse_frontmatter(text) @@ -110,7 +110,7 @@ def test_a_bom_does_not_hide_the_frontmatter(): def test_a_fence_without_a_trailing_newline_still_ends_in_one(tmp_path): """Otherwise the body is spliced onto the fence line and the result has no frontmatter.""" - from dokimi.utils import parse_frontmatter + from dokimi.frontmatter import parse_frontmatter skill = write_skill(tmp_path, "Body.") profile = tmp_path / "tmp-skilltext.md" diff --git a/dokimi/tests/test_task_format_detect.py b/dokimi/tests/test_task_format_detect.py index 86ba25d251..8fc104c820 100644 --- a/dokimi/tests/test_task_format_detect.py +++ b/dokimi/tests/test_task_format_detect.py @@ -27,7 +27,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.cli import build_parser from dokimi.external.trigger_set import TriggerQuery, to_reach, to_skill_creator from dokimi.harnesses import discover_tasks diff --git a/dokimi/tests/test_tasks_command.py b/dokimi/tests/test_tasks_command.py index 167b29479c..f67fca097f 100644 --- a/dokimi/tests/test_tasks_command.py +++ b/dokimi/tests/test_tasks_command.py @@ -9,7 +9,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.cli import build_parser diff --git a/dokimi/tests/test_tool_preference.py b/dokimi/tests/test_tool_preference.py index 1ce2860ea0..4e45dddb33 100644 --- a/dokimi/tests/test_tool_preference.py +++ b/dokimi/tests/test_tool_preference.py @@ -14,7 +14,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi import tool_preference as tp from dokimi.artifacts import validate_artifact from tests.cli_refusal import refusal diff --git a/dokimi/tests/test_treatments.py b/dokimi/tests/test_treatments.py index 68d99e1dae..1ba11359af 100644 --- a/dokimi/tests/test_treatments.py +++ b/dokimi/tests/test_treatments.py @@ -6,7 +6,7 @@ import pytest from tests.conftest import DEMO_SKILL_MARKER -from dokimi.utils import parse_frontmatter +from dokimi.frontmatter import parse_frontmatter from dokimi.treatments import ( AgentConfig, BaselineTreatment, diff --git a/dokimi/tests/test_tree_digest.py b/dokimi/tests/test_tree_digest.py index 72723d4108..72a2067ce7 100644 --- a/dokimi/tests/test_tree_digest.py +++ b/dokimi/tests/test_tree_digest.py @@ -1,7 +1,7 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""dokimi.utils.tree_digest: the one tree hash the build context and the repo config share.""" +"""dokimi.digest.tree_digest: the one tree hash the build context and the repo config share.""" from __future__ import annotations @@ -13,7 +13,7 @@ import pytest -from dokimi.utils import tree_digest +from dokimi.digest import tree_digest symlinks = pytest.mark.skipif(os.name == "nt", reason="creating symlinks needs privileges on Windows") @@ -213,7 +213,7 @@ def test_a_root_link_through_a_subdirectory_to_the_root_digests_differently_from def test_a_windows_extended_path_prefix_is_read_as_the_plain_path(): # os.readlink on Windows returns the \\?\ form of an absolute link target; the containment check needs the plain one - from dokimi.utils import _plain_path + from dokimi.digest import _plain_path assert _plain_path("\\\\?\\C:\\checkout\\tree\\q.json") == "C:\\checkout\\tree\\q.json" assert _plain_path("\\\\?\\UNC\\srv\\share\\q.json") == "\\\\srv\\share\\q.json" @@ -333,7 +333,7 @@ def test_an_absolute_link_that_leaves_the_tree_and_comes_back_digests_the_same_a def test_an_absolute_link_in_a_subdirectory_that_leaves_the_tree_and_comes_back_is_read_from_its_directory(tmp_path): # sub/l -> /../t/x folds to the root's x, so the text climbs out of sub first: ../x, not x - from dokimi.utils import link_text + from dokimi.digest import link_text root = _write(tmp_path / "t", {"x": "x\n", "sub/x": "inner\n"}) try: @@ -345,7 +345,7 @@ def test_an_absolute_link_in_a_subdirectory_that_leaves_the_tree_and_comes_back_ def test_an_absolute_link_into_a_sibling_whose_name_starts_with_the_roots_is_outside_the_tree(tmp_path): # /t2/q.json shares the prefix /t but not the directory: it is external, not the relative 2/q.json - from dokimi.utils import link_text + from dokimi.digest import link_text root = _write(tmp_path / "t", {"2/q.json": "[]\n"}) sibling = _write(tmp_path / "t2", {"q.json": "[]\n"}) @@ -390,7 +390,7 @@ def test_crlf_text_digests_as_its_bytes_outside_git(tmp_path): def test_a_relative_link_target_is_hashed_with_forward_slashes_on_any_os(): - from dokimi.utils import _posix_separators + from dokimi.digest import _posix_separators assert _posix_separators("..\\vendor\\a", "\\") == "../vendor/a" # Windows: os.readlink gives the native separator assert _posix_separators("../vendor/a", "/") == "../vendor/a" diff --git a/dokimi/tests/test_trigger_probe.py b/dokimi/tests/test_trigger_probe.py index 28e9fd37e9..f5bd6e49e3 100644 --- a/dokimi/tests/test_trigger_probe.py +++ b/dokimi/tests/test_trigger_probe.py @@ -399,7 +399,7 @@ def test_max_turns_no_load_counts_only_capped_runs_without_a_skill_call(tmp_path def test_cli_refuses_a_bad_out_or_target_before_any_run(tmp_path, monkeypatch): - from dokimi.utils import InputError + from dokimi.files import InputError with pytest.raises(InputError, match="not a writable file path"): _cli(tmp_path, monkeypatch, "--out", "nodir/probe.json") @@ -408,7 +408,7 @@ def test_cli_refuses_a_bad_out_or_target_before_any_run(tmp_path, monkeypatch): def test_cli_refuses_a_label_that_names_no_catalog_skill(tmp_path, monkeypatch): - from dokimi.utils import InputError + from dokimi.files import InputError with pytest.raises(InputError, match="names no skill in --catalog: sum-fsat"): _cli(tmp_path, monkeypatch, "--out", "probe.json", expected="sum-fsat") @@ -606,7 +606,7 @@ def test_no_known_positive_skips_the_guard(tmp_path, monkeypatch): def test_cli_refuses_an_empty_catalog_before_the_guard_picks_a_skill(tmp_path, monkeypatch): # A negative-only set has no label naming a skill, so only the guard's default target could # name one; with no skill in the catalog that was an IndexError, not an input error. - from dokimi.utils import InputError + from dokimi.files import InputError (tmp_path / "cat").mkdir() with pytest.raises(InputError, match="--catalog holds no skills"): diff --git a/dokimi/tests/test_trigger_set_readers.py b/dokimi/tests/test_trigger_set_readers.py index 9c168fb933..bc2dc90090 100644 --- a/dokimi/tests/test_trigger_set_readers.py +++ b/dokimi/tests/test_trigger_set_readers.py @@ -14,7 +14,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.cli import build_parser from dokimi.external import trigger_set as ts from dokimi.questions.artifact import load_questions diff --git a/dokimi/tests/test_unlistable_readers.py b/dokimi/tests/test_unlistable_readers.py index bd23915b10..2b92df98e5 100644 --- a/dokimi/tests/test_unlistable_readers.py +++ b/dokimi/tests/test_unlistable_readers.py @@ -22,7 +22,7 @@ from dokimi.repos.workspace import Task, _install_skills from dokimi.runner.run import DocLoadError, run_benchmark from dokimi.skill_coverage import _module_code, check_files, load_checks -from dokimi.utils import InputError +from dokimi.files import InputError @contextmanager diff --git a/dokimi/tests/test_unlistable_sites.py b/dokimi/tests/test_unlistable_sites.py index e365f4b03b..303c98fa5b 100644 --- a/dokimi/tests/test_unlistable_sites.py +++ b/dokimi/tests/test_unlistable_sites.py @@ -26,7 +26,7 @@ from dokimi.skills.formats import detect_skill_packages from dokimi.skills.loader import _not_listed_as_resource, load_skill from dokimi.treatments.factory import create_treatment -from dokimi.utils import InputError +from dokimi.files import InputError FRONTMATTER = "---\nname: demo\ndescription: A demo skill.\n---\nBody.\n" diff --git a/dokimi/tests/test_windows_symlink_loop.py b/dokimi/tests/test_windows_symlink_loop.py index a0c7f34ee3..7262f6c2e8 100644 --- a/dokimi/tests/test_windows_symlink_loop.py +++ b/dokimi/tests/test_windows_symlink_loop.py @@ -12,7 +12,7 @@ import pytest -from dokimi.utils import InputError, is_symlink_loop +from dokimi.files import InputError, is_symlink_loop class _WindowsError(OSError): diff --git a/dokimi/tests/test_write_probe.py b/dokimi/tests/test_write_probe.py index beb6b22ae7..f7bc2d58c3 100644 --- a/dokimi/tests/test_write_probe.py +++ b/dokimi/tests/test_write_probe.py @@ -12,7 +12,7 @@ import pytest -from dokimi.utils import InputError +from dokimi.files import InputError from dokimi.write_probe import can_write