From 15dd86fc5674a194cc2ee47d577ef4fd979f8f07 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 24 Nov 2026 22:42:39 -0800 Subject: [PATCH 1/8] refactor(utils): split dokimi/utils.py into frontmatter, files, digest, model_names Pure move, no logic edits. The 800-line utils module is split by concern: - dokimi.frontmatter: markdown frontmatter parsing - dokimi.files: InputError, device refusal, JSON input reads, symlink-loop and rmtree-retry helpers - dokimi.digest: text, file and git-aware tree digests - dokimi.model_names: model identity, same-model/evaluator checks and the judge-independence warnings - dokimi.records: question_id moves here beside the record helpers Importers in the package, scripts, fuzz targets and tests point at the new homes directly. dokimi.utils has no shim: it is not public API. The layer map in tests/test_import_architecture.py lists the new foundation modules. Signed-off-by: Nikolay Petrov --- .github/workflows/fuzz.yml | 6 +- .../20261124_120000_napetrov_arch-c14.md | 3 + dokimi/docs/architecture.md | 4 +- dokimi/docs/judge-panel-study.md | 2 +- dokimi/dokimi/agent_profiles/loader.py | 2 +- dokimi/dokimi/artifacts.py | 8 +- dokimi/dokimi/cli.py | 2 +- dokimi/dokimi/cli_output.py | 2 +- dokimi/dokimi/commands/answer_formats.py | 4 +- dokimi/dokimi/commands/answers.py | 2 +- dokimi/dokimi/commands/arms.py | 3 +- dokimi/dokimi/commands/baseline.py | 4 +- dokimi/dokimi/commands/baseline_regression.py | 2 +- dokimi/dokimi/commands/benchmark.py | 5 +- dokimi/dokimi/commands/cache_dir.py | 4 +- dokimi/dokimi/commands/catalog.py | 6 +- dokimi/dokimi/commands/catalog_eval.py | 2 +- dokimi/dokimi/commands/catalog_novelty.py | 4 +- dokimi/dokimi/commands/catalog_probe.py | 2 +- dokimi/dokimi/commands/catalog_provenance.py | 2 +- dokimi/dokimi/commands/catalog_scan.py | 6 +- dokimi/dokimi/commands/context.py | 2 +- dokimi/dokimi/commands/dashboard.py | 2 +- dokimi/dokimi/commands/dataset.py | 2 +- dokimi/dokimi/commands/delivery.py | 2 +- dokimi/dokimi/commands/eval_coverage.py | 2 +- dokimi/dokimi/commands/eval_graph.py | 2 +- dokimi/dokimi/commands/evaluate.py | 3 +- dokimi/dokimi/commands/explore.py | 2 +- dokimi/dokimi/commands/headroom.py | 2 +- dokimi/dokimi/commands/ingest.py | 2 +- dokimi/dokimi/commands/inputs.py | 2 +- dokimi/dokimi/commands/judge_reliability.py | 5 +- dokimi/dokimi/commands/leak.py | 2 +- dokimi/dokimi/commands/library.py | 2 +- dokimi/dokimi/commands/llms_txt.py | 2 +- dokimi/dokimi/commands/memory.py | 2 +- dokimi/dokimi/commands/novelty.py | 2 +- dokimi/dokimi/commands/novelty_atoms_file.py | 4 +- dokimi/dokimi/commands/novelty_budget.py | 2 +- dokimi/dokimi/commands/novelty_ground.py | 2 +- dokimi/dokimi/commands/novelty_retest.py | 2 +- dokimi/dokimi/commands/novelty_routing.py | 2 +- .../dokimi/commands/novelty_routing_inputs.py | 2 +- .../dokimi/commands/novelty_routing_report.py | 2 +- dokimi/dokimi/commands/novelty_run.py | 2 +- dokimi/dokimi/commands/novelty_view_inputs.py | 2 +- dokimi/dokimi/commands/opportunities.py | 2 +- dokimi/dokimi/commands/orchestrate.py | 6 +- dokimi/dokimi/commands/personas.py | 2 +- dokimi/dokimi/commands/questions.py | 4 +- dokimi/dokimi/commands/redteam.py | 2 +- dokimi/dokimi/commands/repair_receipt.py | 2 +- dokimi/dokimi/commands/repo.py | 2 +- dokimi/dokimi/commands/repo_hits.py | 2 +- dokimi/dokimi/commands/repo_reach.py | 2 +- dokimi/dokimi/commands/repo_run.py | 4 +- dokimi/dokimi/commands/repo_scan.py | 2 +- dokimi/dokimi/commands/repo_security.py | 2 +- dokimi/dokimi/commands/repo_skill_reach.py | 2 +- dokimi/dokimi/commands/report.py | 2 +- dokimi/dokimi/commands/routing_compare.py | 2 +- dokimi/dokimi/commands/run.py | 2 +- dokimi/dokimi/commands/runs.py | 2 +- dokimi/dokimi/commands/skill_coverage.py | 2 +- dokimi/dokimi/commands/subjects.py | 2 +- dokimi/dokimi/commands/tasks.py | 2 +- dokimi/dokimi/commands/tasks_generate.py | 2 +- dokimi/dokimi/commands/tools.py | 2 +- dokimi/dokimi/context/consistency.py | 2 +- dokimi/dokimi/context/session_log.py | 2 +- dokimi/dokimi/context/trace.py | 2 +- dokimi/dokimi/{utils.py => digest.py} | 352 +----------------- dokimi/dokimi/digest_entries.py | 2 +- dokimi/dokimi/eval/answerer.py | 2 +- dokimi/dokimi/eval/arm_runner.py | 2 +- dokimi/dokimi/eval/arms_adapter.py | 2 +- dokimi/dokimi/eval/arms_refusals.py | 2 +- dokimi/dokimi/eval/arms_run.py | 4 +- dokimi/dokimi/eval/checklist.py | 2 +- dokimi/dokimi/eval/cross_judge.py | 3 +- dokimi/dokimi/eval/judge_context.py | 4 +- dokimi/dokimi/eval/question_text.py | 5 +- dokimi/dokimi/eval/session.py | 2 +- dokimi/dokimi/external/listing.py | 2 +- dokimi/dokimi/external/online_checks.py | 2 +- dokimi/dokimi/external/trigger_set.py | 2 +- dokimi/dokimi/external/upstream.py | 3 +- dokimi/dokimi/external/upstream_findings.py | 2 +- dokimi/dokimi/external/validate.py | 2 +- dokimi/dokimi/files.py | 91 +++++ dokimi/dokimi/frontmatter.py | 98 +++++ dokimi/dokimi/harnesses/benchflow.py | 2 +- dokimi/dokimi/harnesses/command.py | 2 +- dokimi/dokimi/harnesses/delivery.py | 2 +- dokimi/dokimi/harnesses/network_policy.py | 2 +- dokimi/dokimi/harnesses/runner.py | 2 +- dokimi/dokimi/harnesses/skill_treatment.py | 2 +- dokimi/dokimi/harnesses/verifier_reward.py | 2 +- dokimi/dokimi/ingest/docling_loader.py | 2 +- dokimi/dokimi/judge_rule.py | 6 +- dokimi/dokimi/mcp/factory.py | 2 +- dokimi/dokimi/mcp/url_client.py | 2 +- dokimi/dokimi/model_names.py | 182 +++++++++ dokimi/dokimi/novelty/artifact.py | 4 +- dokimi/dokimi/novelty/atom_labels.py | 2 +- dokimi/dokimi/novelty/atom_verdicts.py | 2 +- dokimi/dokimi/novelty/atoms.py | 6 +- dokimi/dokimi/novelty/bundle.py | 2 +- dokimi/dokimi/novelty/client.py | 6 +- dokimi/dokimi/novelty/cost.py | 4 +- dokimi/dokimi/novelty/grounding.py | 2 +- dokimi/dokimi/novelty/judge2.py | 2 +- dokimi/dokimi/novelty/measure.py | 2 +- dokimi/dokimi/novelty/panel_grade.py | 2 +- dokimi/dokimi/novelty/probes.py | 2 +- dokimi/dokimi/novelty/retest.py | 2 +- dokimi/dokimi/novelty/routing.py | 3 +- dokimi/dokimi/novelty/sweep.py | 2 +- dokimi/dokimi/novelty/symbols.py | 2 +- dokimi/dokimi/opportunities.py | 2 +- dokimi/dokimi/orchestrator/pipeline.py | 26 +- dokimi/dokimi/plugins.py | 2 +- dokimi/dokimi/questions/artifact.py | 7 +- dokimi/dokimi/questions/normalizer.py | 4 +- dokimi/dokimi/records.py | 18 +- dokimi/dokimi/repo_config.py | 3 +- dokimi/dokimi/repo_glob.py | 2 +- dokimi/dokimi/repo_links.py | 3 +- dokimi/dokimi/report/model_compare.py | 4 +- dokimi/dokimi/repos/budget.py | 2 +- dokimi/dokimi/repos/compare.py | 2 +- dokimi/dokimi/repos/graph_tasks.py | 2 +- dokimi/dokimi/repos/reach.py | 3 +- dokimi/dokimi/repos/report.py | 2 +- dokimi/dokimi/repos/skill_reach.py | 3 +- dokimi/dokimi/repos/source.py | 2 +- dokimi/dokimi/runner/compare.py | 2 +- dokimi/dokimi/runs/rm.py | 2 +- dokimi/dokimi/runs/rundir.py | 2 +- dokimi/dokimi/runs/scan.py | 4 +- dokimi/dokimi/runs/show.py | 2 +- dokimi/dokimi/skills/formats.py | 2 +- dokimi/dokimi/skills/loader.py | 2 +- dokimi/dokimi/subjects/scorecard.py | 4 +- dokimi/dokimi/treatments/arms.py | 2 +- dokimi/fuzz/targets.py | 2 +- dokimi/scripts/check_treatment_batch.py | 2 +- dokimi/scripts/sync_skilltext_profile.py | 2 +- dokimi/tests/cli_refusal.py | 2 +- dokimi/tests/test_687_low.py | 2 +- dokimi/tests/test_agent_profiles.py | 2 +- dokimi/tests/test_arm_runner.py | 4 +- dokimi/tests/test_arm_runner_incremental.py | 2 +- dokimi/tests/test_artifacts.py | 2 +- dokimi/tests/test_atoms_partial_status.py | 2 +- dokimi/tests/test_baseline_deep_nesting.py | 2 +- dokimi/tests/test_bedrock_model_ids.py | 2 +- dokimi/tests/test_bundled_skills.py | 2 +- dokimi/tests/test_cache_dir_label.py | 2 +- dokimi/tests/test_catalog_command.py | 2 +- dokimi/tests/test_catalog_ignore.py | 2 +- dokimi/tests/test_catalog_jsonl.py | 2 +- dokimi/tests/test_catalog_listing_budget.py | 2 +- dokimi/tests/test_catalog_no_frontmatter.py | 2 +- dokimi/tests/test_catalog_novelty.py | 6 +- dokimi/tests/test_catalog_online.py | 2 +- dokimi/tests/test_catalog_online_edges.py | 2 +- dokimi/tests/test_catalog_provenance.py | 2 +- dokimi/tests/test_catalog_repair_receipt.py | 2 +- dokimi/tests/test_catalog_routing_compare.py | 2 +- dokimi/tests/test_catalog_scan_unlistable.py | 2 +- .../tests/test_catalog_upstream_findings.py | 2 +- dokimi/tests/test_catalog_validate.py | 2 +- dokimi/tests/test_cli_m3_moves.py | 2 +- dokimi/tests/test_cli_output.py | 2 +- dokimi/tests/test_context_consistency.py | 2 +- dokimi/tests/test_context_prefilter.py | 2 +- dokimi/tests/test_context_prefilter_corpus.py | 2 +- dokimi/tests/test_context_trace.py | 2 +- dokimi/tests/test_doc_caches.py | 2 +- dokimi/tests/test_doc_source_unlistable.py | 2 +- dokimi/tests/test_docker_null_check.py | 2 +- dokimi/tests/test_eval_coverage.py | 2 +- .../tests/test_eval_tasks_generate_history.py | 2 +- dokimi/tests/test_evaluate_cli_inputs.py | 5 +- dokimi/tests/test_explore_track.py | 2 +- dokimi/tests/test_fuzz_targets.py | 4 +- dokimi/tests/test_git_paths_windows_decode.py | 28 +- dokimi/tests/test_headroom_command.py | 2 +- dokimi/tests/test_import_architecture.py | 5 +- dokimi/tests/test_input_devices.py | 2 +- dokimi/tests/test_input_refusal_exit_sites.py | 2 +- dokimi/tests/test_json_writers_equal_keys.py | 2 +- dokimi/tests/test_judge_context_mode.py | 5 +- dokimi/tests/test_judge_provider_default.py | 4 +- dokimi/tests/test_judge_reliability.py | 32 +- .../test_judge_temperature_entry_points.py | 6 +- dokimi/tests/test_judge_validity.py | 26 +- dokimi/tests/test_key_files.py | 2 +- dokimi/tests/test_knowledge_run.py | 2 +- dokimi/tests/test_leak_command.py | 2 +- dokimi/tests/test_llm_callers.py | 3 +- dokimi/tests/test_llm_cli.py | 2 +- dokimi/tests/test_llm_cli_identity.py | 2 +- dokimi/tests/test_load_or_fail.py | 6 +- .../tests/test_lone_surrogate_cache_keys.py | 2 +- dokimi/tests/test_model_compare.py | 2 +- dokimi/tests/test_model_compare_exit_codes.py | 2 +- dokimi/tests/test_model_compare_overflow.py | 2 +- .../tests/test_novelty_analyze_cap_partial.py | 2 +- .../tests/test_novelty_answer_key_wiring.py | 2 +- dokimi/tests/test_novelty_atom_labels.py | 2 +- dokimi/tests/test_novelty_atom_verdicts.py | 2 +- dokimi/tests/test_novelty_atoms_input.py | 2 +- dokimi/tests/test_novelty_atoms_sample.py | 2 +- dokimi/tests/test_novelty_cache_dir_usable.py | 2 +- dokimi/tests/test_novelty_cap_partial.py | 2 +- dokimi/tests/test_novelty_checks.py | 2 +- dokimi/tests/test_novelty_cli.py | 4 +- dokimi/tests/test_novelty_controls.py | 2 +- dokimi/tests/test_novelty_gate.py | 2 +- dokimi/tests/test_novelty_ground_symbols.py | 2 +- dokimi/tests/test_novelty_journey.py | 2 +- dokimi/tests/test_novelty_panel.py | 2 +- dokimi/tests/test_novelty_permanent_stop.py | 2 +- dokimi/tests/test_novelty_provenance.py | 2 +- dokimi/tests/test_novelty_retest.py | 2 +- dokimi/tests/test_novelty_routing.py | 2 +- .../tests/test_novelty_routing_acceptable.py | 2 +- .../tests/test_novelty_routing_all_vs_all.py | 2 +- dokimi/tests/test_novelty_routing_cli_gaps.py | 2 +- dokimi/tests/test_novelty_routing_field.py | 2 +- dokimi/tests/test_novelty_routing_gaps.py | 2 +- dokimi/tests/test_novelty_settings_parity.py | 2 +- dokimi/tests/test_novelty_shorten_artifact.py | 2 +- dokimi/tests/test_novelty_sweep.py | 2 +- dokimi/tests/test_opportunities.py | 2 +- dokimi/tests/test_opportunities_command.py | 2 +- dokimi/tests/test_question_ids.py | 4 +- dokimi/tests/test_questions_artifact.py | 2 +- .../tests/test_questions_generate_inputs.py | 8 +- dokimi/tests/test_record_readers.py | 2 +- dokimi/tests/test_records_readers.py | 3 +- dokimi/tests/test_replicates.py | 2 +- dokimi/tests/test_repo_choices.py | 2 +- dokimi/tests/test_repo_config_git_blobs.py | 24 +- dokimi/tests/test_repo_config_links.py | 6 +- dokimi/tests/test_repo_hits_judge_failures.py | 2 +- dokimi/tests/test_repo_run.py | 2 +- dokimi/tests/test_repo_scan_baseline_depth.py | 2 +- dokimi/tests/test_repo_scan_deep_baseline.py | 2 +- dokimi/tests/test_repo_security.py | 2 +- dokimi/tests/test_repo_skill_arms.py | 2 +- dokimi/tests/test_repo_source_exit_2.py | 8 +- dokimi/tests/test_repo_suite.py | 2 +- dokimi/tests/test_run_envelope.py | 2 +- dokimi/tests/test_runs_rundir.py | 2 +- dokimi/tests/test_runs_rundir_claims.py | 2 +- dokimi/tests/test_runs_scan.py | 2 +- dokimi/tests/test_same_model.py | 2 +- dokimi/tests/test_saved_self_judge_warning.py | 12 +- dokimi/tests/test_scan_gate.py | 4 +- dokimi/tests/test_seed_unsupported_route.py | 2 +- dokimi/tests/test_similar_skills.py | 2 +- dokimi/tests/test_skill_coverage.py | 2 +- dokimi/tests/test_skill_selection.py | 4 +- dokimi/tests/test_subjects.py | 2 +- dokimi/tests/test_subjects_long_name.py | 2 +- dokimi/tests/test_swebench_tasks.py | 2 +- dokimi/tests/test_sync_skilltext_profile.py | 4 +- dokimi/tests/test_task_format_detect.py | 2 +- dokimi/tests/test_tasks_command.py | 2 +- dokimi/tests/test_tool_preference.py | 2 +- dokimi/tests/test_treatments.py | 2 +- dokimi/tests/test_tree_digest.py | 12 +- dokimi/tests/test_trigger_probe.py | 6 +- dokimi/tests/test_trigger_set_readers.py | 2 +- dokimi/tests/test_unlistable_readers.py | 2 +- dokimi/tests/test_windows_symlink_loop.py | 2 +- dokimi/tests/test_write_probe.py | 2 +- 281 files changed, 833 insertions(+), 755 deletions(-) create mode 100644 dokimi/changelog.d/20261124_120000_napetrov_arch-c14.md rename dokimi/dokimi/{utils.py => digest.py} (59%) create mode 100644 dokimi/dokimi/files.py create mode 100644 dokimi/dokimi/frontmatter.py create mode 100644 dokimi/dokimi/model_names.py 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..70e1c091f2 --- /dev/null +++ b/dokimi/changelog.d/20261124_120000_napetrov_arch-c14.md @@ -0,0 +1,3 @@ +### Removed + +- **`dokimi.utils` module removed; its names moved to focused modules.** Import from the new home: `parse_frontmatter`, `parse_frontmatter_strict`, `describe_yaml_error` from `dokimi.frontmatter`; `InputError`, `read_json_input`, `read_json_input_bytes`, `refuse_device`, `is_symlink_loop`, `retry_writable` from `dokimi.files`; `key_bytes`, `digest_text`, `file_digest`, `tree_digest`, `file_contents`, `link_text`, `git_tree`, `GitDigestTree` from `dokimi.digest`; `model_identity`, `same_model`, `same_evaluator`, `warn_judge_independence`, `warn_recorded_self_judge`, `check_bedrock_model` from `dokimi.model_names`; `question_id` from `dokimi.records`. No behavior changes. Code that imported `dokimi.utils` directly must update its imports. diff --git a/dokimi/docs/architecture.md b/dokimi/docs/architecture.md index 3383c6eea6..0478d7cb8a 100644 --- a/dokimi/docs/architecture.md +++ b/dokimi/docs/architecture.md @@ -73,7 +73,7 @@ points up: | tracks | `runner`, `runs`, `report`, `subjects`, `novelty`, `harnesses`, `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`, `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`, `process`, `container_policy`, `docker_cmd`, `caching`, `config`, `registry`, `intents`, `defaults`, `console`, `digest`, `files`, `frontmatter`, `model_names`, `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. @@ -478,7 +478,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 d34acca97c..8d1a8b68b6 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 0d20a91cc8..04d91a7032 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/artifacts.py b/dokimi/dokimi/artifacts.py index e374cbd757..c9678e5909 100644 --- a/dokimi/dokimi/artifacts.py +++ b/dokimi/dokimi/artifacts.py @@ -54,7 +54,7 @@ from dokimi._version import __version__ from dokimi.atomic_write import write_bytes_in_place_or_atomic 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__) @@ -294,14 +294,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`. @@ -391,7 +391,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 bc9f47b4fc..453352803a 100755 --- a/dokimi/dokimi/cli.py +++ b/dokimi/dokimi/cli.py @@ -442,7 +442,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 753f4852bd..bf9cace6b7 100644 --- a/dokimi/dokimi/cli_output.py +++ b/dokimi/dokimi/cli_output.py @@ -16,7 +16,7 @@ from dokimi._version import __version__ from dokimi import artifacts from dokimi.artifacts import SCHEMA_DIR -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/answer_formats.py b/dokimi/dokimi/commands/answer_formats.py index db9a620879..d162426807 100644 --- a/dokimi/dokimi/commands/answer_formats.py +++ b/dokimi/dokimi/commands/answer_formats.py @@ -14,7 +14,7 @@ import argparse import json from pathlib import Path -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input def cmd_questions_import(args: argparse.Namespace) -> None: @@ -50,7 +50,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 02e6e5e658..3523d8063f 100644 --- a/dokimi/dokimi/commands/answers.py +++ b/dokimi/dokimi/commands/answers.py @@ -24,7 +24,7 @@ DEFAULT_MAX_TOKENS_PER_QUESTION, DEFAULT_RETRIEVAL_TOP_K, ) -from dokimi.utils import InputError +from dokimi.files import InputError def _load_runtime_config() -> dict: diff --git a/dokimi/dokimi/commands/arms.py b/dokimi/dokimi/commands/arms.py index 97703dc195..55edae6b32 100644 --- a/dokimi/dokimi/commands/arms.py +++ b/dokimi/dokimi/commands/arms.py @@ -16,7 +16,8 @@ from dokimi.commands.novelty_budget import fresh_partial_destination from dokimi.exit_codes import EXIT_FAILURE, EXIT_USAGE from dokimi.llm import ANSWER_PROVIDERS -from dokimi.utils import InputError, question_id +from dokimi.files import InputError +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 a9e0118edd..22b7d40579 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 92cd22664e..692b7d2c3f 100644 --- a/dokimi/dokimi/commands/benchmark.py +++ b/dokimi/dokimi/commands/benchmark.py @@ -14,7 +14,7 @@ from dokimi import cli_flags 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, @@ -30,7 +30,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 6d73fb5843..57c1b49f53 100644 --- a/dokimi/dokimi/commands/catalog.py +++ b/dokimi/dokimi/commands/catalog.py @@ -24,7 +24,7 @@ ok_text, plain_note, print_skill_row, skill_row, skipped_note, unrestricted_and_risky, ) from dokimi.external.catalog_rates import RateTally, text_lines -from dokimi.utils import InputError +from dokimi.files import InputError def _print_strict_reasons(rows: list, strict: bool) -> None: @@ -491,7 +491,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: @@ -514,7 +514,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 331f30c700..7b68b396cd 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 b9ce48b270..9a548eb321 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 +from dokimi.files import InputError 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 942fe53b0e..51923c24d9 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 @@ -175,7 +175,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 8815795379..5006a3b74d 100644 --- a/dokimi/dokimi/commands/context.py +++ b/dokimi/dokimi/commands/context.py @@ -13,7 +13,7 @@ from typing import NoReturn from dokimi.cli_types import non_negative_int, unit_interval -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 a24dffb56d..338938d035 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 8dba91e174..7e58d31593 100644 --- a/dokimi/dokimi/commands/delivery.py +++ b/dokimi/dokimi/commands/delivery.py @@ -11,7 +11,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 81a7c87bfd..2136014a3d 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 34c2c3df3d..f5e9232060 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 _warn_judge_independence = warn_judge_independence diff --git a/dokimi/dokimi/commands/explore.py b/dokimi/dokimi/commands/explore.py index e0dc946276..cb437df13c 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 74227e09ce..7a30ca6c3a 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 6bcd7f9b3e..1fdeeed501 100644 --- a/dokimi/dokimi/commands/judge_reliability.py +++ b/dokimi/dokimi/commands/judge_reliability.py @@ -18,7 +18,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 @@ -308,7 +309,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.utils import question_id + from dokimi.records import question_id # What the arms run's judge saw, when the file keeps it (judge_materials). Built # once and only for --judges: 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 10e0aada45..57de76c74b 100644 --- a/dokimi/dokimi/commands/leak.py +++ b/dokimi/dokimi/commands/leak.py @@ -32,7 +32,7 @@ from dokimi.cli_types import positive_fraction, positive_int 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 75c6d78f8f..a7e157440c 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 e503796313..6d362da02f 100644 --- a/dokimi/dokimi/commands/novelty.py +++ b/dokimi/dokimi/commands/novelty.py @@ -21,7 +21,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 if TYPE_CHECKING: from dokimi.novelty.tiers import RunSettings diff --git a/dokimi/dokimi/commands/novelty_atoms_file.py b/dokimi/dokimi/commands/novelty_atoms_file.py index 1ccc7eed1a..3416815f54 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 885275bdc4..3a7fe9ce81 100644 --- a/dokimi/dokimi/commands/novelty_budget.py +++ b/dokimi/dokimi/commands/novelty_budget.py @@ -208,7 +208,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_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 51a7a554c0..1d73a34a38 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 5fcb68be48..0360af3d71 100644 --- a/dokimi/dokimi/commands/novelty_routing_report.py +++ b/dokimi/dokimi/commands/novelty_routing_report.py @@ -20,7 +20,7 @@ from pathlib import Path from typing import TYPE_CHECKING, NoReturn -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 7f5617e1fd..f51743d48c 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 3da0c63092..a75d4aee5c 100644 --- a/dokimi/dokimi/commands/orchestrate.py +++ b/dokimi/dokimi/commands/orchestrate.py @@ -13,8 +13,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, @@ -23,7 +23,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 5cb4125561..3adc23a818 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, refuse_device +from dokimi.files import InputError, refuse_device def _usd_text(usd: float) -> str: diff --git a/dokimi/dokimi/commands/questions.py b/dokimi/dokimi/commands/questions.py index cd25be6aa7..b7a8a9c15e 100644 --- a/dokimi/dokimi/commands/questions.py +++ b/dokimi/dokimi/commands/questions.py @@ -15,7 +15,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, refuse_device, warn_recorded_self_judge +from dokimi.files import InputError, refuse_device +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 bb7bb806d2..7de21b3e3c 100644 --- a/dokimi/dokimi/commands/repo.py +++ b/dokimi/dokimi/commands/repo.py @@ -21,7 +21,7 @@ from dokimi.exit_codes import EXIT_USAGE from dokimi.commands.repo_scan import (_loaded_with_default, _print_scan_text, _scan_gate, _scan_reason, _typecheck_or_exit) -from dokimi.utils import InputError +from dokimi.files import InputError def _normalize_whitespace(text: str, max_len: int | None = 100) -> str: diff --git a/dokimi/dokimi/commands/repo_hits.py b/dokimi/dokimi/commands/repo_hits.py index c8fab76298..b345013aab 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_USAGE -from dokimi.utils import InputError +from dokimi.files import InputError from ._output import exit_on_unwritable diff --git a/dokimi/dokimi/commands/repo_reach.py b/dokimi/dokimi/commands/repo_reach.py index 013aa2bb5a..7927019529 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 dd7ba924cf..c31ca93c5d 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_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 def _refuse_typed(source, args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/repo_scan.py b/dokimi/dokimi/commands/repo_scan.py index d032f0de78..1771c5c9f9 100644 --- a/dokimi/dokimi/commands/repo_scan.py +++ b/dokimi/dokimi/commands/repo_scan.py @@ -16,7 +16,7 @@ import shutil from dokimi.repos.l0.config import new_failures -from dokimi.utils import InputError +from dokimi.files import InputError def _typecheck_or_exit(args: argparse.Namespace): 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 1eb6615573..e31b14c8f8 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 f3ef4dddaa..a65d3ef725 100644 --- a/dokimi/dokimi/commands/report.py +++ b/dokimi/dokimi/commands/report.py @@ -12,7 +12,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 +from dokimi.files import InputError 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 a13c313701..87d46d7e63 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 8c2a64fb37..9910acc76c 100644 --- a/dokimi/dokimi/commands/runs.py +++ b/dokimi/dokimi/commands/runs.py @@ -31,7 +31,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/skill_coverage.py b/dokimi/dokimi/commands/skill_coverage.py index b4a4828d5a..266d5589f5 100644 --- a/dokimi/dokimi/commands/skill_coverage.py +++ b/dokimi/dokimi/commands/skill_coverage.py @@ -19,7 +19,7 @@ from dokimi.cli_types import positive_usd from dokimi.exit_codes import EXIT_FAILURE -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/subjects.py b/dokimi/dokimi/commands/subjects.py index f3b7c0b6d0..753d982d45 100644 --- a/dokimi/dokimi/commands/subjects.py +++ b/dokimi/dokimi/commands/subjects.py @@ -22,7 +22,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 def cmd_subjects_list(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/commands/tasks.py b/dokimi/dokimi/commands/tasks.py index 4e43f3f3ce..42615bd878 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 cf91a39531..17d85a6ba8 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 f6a8c3ba76..c413c307ae 100644 --- a/dokimi/dokimi/commands/tools.py +++ b/dokimi/dokimi/commands/tools.py @@ -18,7 +18,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 +from dokimi.files import InputError PROVIDERS = list(API_PROVIDERS) # tool calling: no CLI backend diff --git a/dokimi/dokimi/context/consistency.py b/dokimi/dokimi/context/consistency.py index 2eae3414aa..8d61bcb421 100644 --- a/dokimi/dokimi/context/consistency.py +++ b/dokimi/dokimi/context/consistency.py @@ -52,7 +52,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 _WRITE_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} RULES = ("requires", "forbids", "before", "after_last", "last_ok") 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 ada9cabeef..e4307080e0 100644 --- a/dokimi/dokimi/context/trace.py +++ b/dokimi/dokimi/context/trace.py @@ -37,7 +37,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/utils.py b/dokimi/dokimi/digest.py similarity index 59% rename from dokimi/dokimi/utils.py rename to dokimi/dokimi/digest.py index 55004973e5..39bea112eb 100644 --- a/dokimi/dokimi/utils.py +++ b/dokimi/dokimi/digest.py @@ -1,111 +1,27 @@ # 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 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 typing import TYPE_CHECKING, Callable, Iterable, Mapping -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. @@ -227,11 +143,6 @@ def _inner_ignored(self, rel: str) -> frozenset[str] | None: 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.""" @@ -551,250 +462,3 @@ def tree_digest(root: Path, *, exclude: Iterable[str] = (), strict: bool = False 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 diff --git a/dokimi/dokimi/digest_entries.py b/dokimi/dokimi/digest_entries.py index 50c8a5ae34..c5abb6ed04 100644 --- a/dokimi/dokimi/digest_entries.py +++ b/dokimi/dokimi/digest_entries.py @@ -11,7 +11,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 0e72b66f39..00773c1c41 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.defaults import ( ANSWERING_METHOD_VERSION, diff --git a/dokimi/dokimi/eval/arm_runner.py b/dokimi/dokimi/eval/arm_runner.py index 8b6b363296..093e81a223 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 a5cb135c75..f8ca5f7dee 100644 --- a/dokimi/dokimi/eval/arms_adapter.py +++ b/dokimi/dokimi/eval/arms_adapter.py @@ -40,7 +40,7 @@ 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 #: The ``arm_kind`` of a ``DocTreatment`` arm (``treatments/factory.py``): retrieval into the prompt. _DOC_KINDS = frozenset({"docs", "mcp_doc"}) diff --git a/dokimi/dokimi/eval/arms_refusals.py b/dokimi/dokimi/eval/arms_refusals.py index 8992d90900..861bb23ace 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 63aaa561fb..969d923873 100644 --- a/dokimi/dokimi/eval/checklist.py +++ b/dokimi/dokimi/eval/checklist.py @@ -41,7 +41,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 c1afb3ef13..fdd579291b 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 3fe0e39a15..0b3f52b960 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/harnesses/benchflow.py b/dokimi/dokimi/harnesses/benchflow.py index 19de15c194..b3555aed47 100644 --- a/dokimi/dokimi/harnesses/benchflow.py +++ b/dokimi/dokimi/harnesses/benchflow.py @@ -677,7 +677,7 @@ def _trajectory_events(rollout_dir: Path) -> list[dict[str, Any]]: 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.""" - from dokimi.utils import parse_frontmatter + from dokimi.frontmatter import parse_frontmatter names: set[str] = set() for skill_md in sorted(skills_root.glob("*/SKILL.md")): diff --git a/dokimi/dokimi/harnesses/command.py b/dokimi/dokimi/harnesses/command.py index 6ad00c86ae..0c0f38204a 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 6d44db7b78..14e30769bd 100644 --- a/dokimi/dokimi/harnesses/delivery.py +++ b/dokimi/dokimi/harnesses/delivery.py @@ -21,7 +21,7 @@ from dokimi.container_policy import ContainerPolicy from dokimi.gate.delivery import compare_pairs, evaluate, score from dokimi.llm_json import extract_json_object -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 9b84944245..ca744a13bf 100644 --- a/dokimi/dokimi/harnesses/runner.py +++ b/dokimi/dokimi/harnesses/runner.py @@ -17,7 +17,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 3f669c47be..0ca0b5ece6 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 817567698f..76e3fbdd58 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 4714bfb99f..be9cc1e9a5 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 c0b2f992d5..bdfaf4d687 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 c53278680a..d5b7e17ffe 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 bb1c7bdc9e..3fd4195970 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 21d09bb2ac..0a5c969880 100644 --- a/dokimi/dokimi/novelty/routing.py +++ b/dokimi/dokimi/novelty/routing.py @@ -43,7 +43,8 @@ from dokimi.external.listing import only_description_too_long from dokimi.skills import Skill -from dokimi.utils import InputError, parse_frontmatter +from dokimi.files import InputError +from dokimi.frontmatter import parse_frontmatter 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 28712896ad..c69572b0a0 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 d4186bfde0..a605b3b5fe 100644 --- a/dokimi/dokimi/novelty/symbols.py +++ b/dokimi/dokimi/novelty/symbols.py @@ -16,7 +16,7 @@ from typing import Sequence 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 52c621a592..542bfa5cd5 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -15,7 +15,7 @@ answers_method_version as answers_method_version_of) from dokimi.eval.stats import paired_summary from dokimi.mcp.factory import create_doc_source_client, resolve_library_id_for_product -from dokimi.utils import InputError, key_bytes, read_json_input, refuse_device, same_evaluator +from dokimi import digest, files, model_names logger = logging.getLogger(__name__) @@ -44,7 +44,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) @@ -69,7 +69,7 @@ def _read_input_set(path: Path, what: str, fix: str = "") -> List[Dict[str, Any] return load_questions_payload(path) except (ValueError, RecursionError, OSError) as exc: # refused by the schema, not JSON or UTF-8, unreadable named = "" if str(path) in str(exc) else f" {path}" # a schema refusal already names the file - raise InputError(f"{what}{named} cannot be used: {exc}" + (f"\n({fix})" if fix else "")) from exc + raise files.InputError(f"{what}{named} cannot be used: {exc}" + (f"\n({fix})" if fix else "")) from exc def _check_custom_questions(path: Path, parse: bool = True) -> None: @@ -80,16 +80,16 @@ def _check_custom_questions(path: Path, parse: bool = True) -> None: """ if not path.exists(): raise FileNotFoundError(f"--custom-questions path does not exist: {path}") - refuse_device(path, "--custom-questions") + files.refuse_device(path, "--custom-questions") if path.is_dir(): # refuse_device lets a directory pass; reading it ends in IsADirectoryError - raise InputError(f"--custom-questions {path}: not a file") + raise files.InputError(f"--custom-questions {path}: not a file") try: # a regular file only: opening a named pipe here would take the writer's one read if path.is_file(): path.open("rb").close() except OSError as exc: # unreadable: refused here, before the output directories exist - raise InputError(f"--custom-questions {path}: {exc.strerror or exc}") from exc + raise files.InputError(f"--custom-questions {path}: {exc.strerror or exc}") from exc if parse and path.is_file(): # the run reads it again through the same function, with the same flag - read_json_input(path, flag="--custom-questions") + files.read_json_input(path, flag="--custom-questions") class EvaluationPipeline: @@ -253,9 +253,9 @@ def __init__( raise FileNotFoundError( f"--questions-from: questions file not found: {qf}" ) - refuse_device(qf, "--questions-from") + files.refuse_device(qf, "--questions-from") if qf.is_file(): - read_json_input(qf, flag="--questions-from") + files.read_json_input(qf, flag="--questions-from") self.external_questions_path: Optional[Path] = qf logger.info(f"Will reuse questions from: {qf}") else: @@ -511,7 +511,7 @@ def _generate_questions(self, personas: Dict[str, Any]) -> List[Dict[str, Any]]: library_id = self._library_id(mcp_client) # The id is the registry's for every source, so the topics cache is also keyed on the source. - source_key = hashlib.sha256(key_bytes(self.doc_source)).hexdigest()[:16] + source_key = hashlib.sha256(digest.key_bytes(self.doc_source)).hexdigest()[:16] extractor = RagasSeedExtractor(mcp_client=mcp_client, cache_dir=Path(".cache/topics") / source_key) topics = extractor.extract_topics( @@ -582,7 +582,7 @@ def _read_question_inputs(self) -> Optional[List[Dict[str, Any]]]: self._custom_questions = self._load_custom_questions() return None if not reused: # an empty reused set is a bad input (exit 2), refused before persona discovery - raise InputError(f"No questions to answer: {path} has no questions") + raise files.InputError(f"No questions to answer: {path} has no questions") return reused def _load_custom_questions(self) -> List[Dict[str, Any]]: @@ -595,7 +595,7 @@ def _load_custom_questions(self) -> List[Dict[str, Any]]: path = self.custom_questions_path if not (path and path.exists()): return [] - refuse_device(path, "--custom-questions") + files.refuse_device(path, "--custom-questions") if getattr(self, "golden_pinned", False): # the golden set of --questions-root: no flag to name custom_questions = _read_input_set(path, "the golden set") else: @@ -760,7 +760,7 @@ def _evaluate_answers(self, answers: Optional[List[Dict[str, Any]] | Dict[str, A "judge_model": self.judge_model, "judge_provider": self.judge_provider, "question_set_hash": question_set_hash, - "evaluator_independence_warning": same_evaluator(str(self.model), str(self.judge_model)), + "evaluator_independence_warning": model_names.same_evaluator(str(self.model), str(self.judge_model)), }, ) 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 bee309f7ca..4a2ce18826 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 70f4a0695a..1eee5373ee 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" @@ -691,3 +691,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 32c3a228e1..eab3fa620c 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/model_compare.py b/dokimi/dokimi/report/model_compare.py index 55718d8bce..596c248e97 100644 --- a/dokimi/dokimi/report/model_compare.py +++ b/dokimi/dokimi/report/model_compare.py @@ -41,7 +41,7 @@ from dokimi.eval import finite_delta, stats as arm_stats from dokimi.report import fmt from dokimi.report.compare_limits import no_delta_limitation -from dokimi.utils import InputError, read_json_input +from dokimi.files import InputError, read_json_input try: from zoneinfo import ZoneInfo @@ -57,7 +57,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.""" data = read_json_input(path) if not isinstance(data, dict): raise InputError(f"{path} is not a judged arms file: expected a JSON object, got {type(data).__name__}") diff --git a/dokimi/dokimi/repos/budget.py b/dokimi/dokimi/repos/budget.py index f7f27785c0..34ba5147f4 100644 --- a/dokimi/dokimi/repos/budget.py +++ b/dokimi/dokimi/repos/budget.py @@ -648,7 +648,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 70e8b90211..513385b48f 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 85a3eb782a..3d32ab9dd6 100644 --- a/dokimi/dokimi/repos/reach.py +++ b/dokimi/dokimi/repos/reach.py @@ -58,7 +58,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 c6b12670d8..8dfecc36a6 100644 --- a/dokimi/dokimi/repos/report.py +++ b/dokimi/dokimi/repos/report.py @@ -60,7 +60,7 @@ 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 a50f46cb38..899f74e7b4 100644 --- a/dokimi/dokimi/repos/source.py +++ b/dokimi/dokimi/repos/source.py @@ -30,7 +30,7 @@ from dokimi import process from dokimi.repos.links import _LinkLoop, _names_dir, _require_dir, _walk_links from dokimi.repos.source_errors import SourceArgumentError, 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 006977afa2..bcc8ef8793 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/rm.py b/dokimi/dokimi/runs/rm.py index 4ab340f43f..bac2eec81a 100644 --- a/dokimi/dokimi/runs/rm.py +++ b/dokimi/dokimi/runs/rm.py @@ -33,7 +33,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 b7b6ffd2cc..bbfdb2090d 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 dd8c835fd7..a2117a7909 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") @@ -63,7 +63,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)) 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 8ff56f5f8a..9475f80dc7 100644 --- a/dokimi/dokimi/skills/formats.py +++ b/dokimi/dokimi/skills/formats.py @@ -37,7 +37,7 @@ from typing import Any, Dict, List, Optional 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 f3b943902f..0957334dcf 100644 --- a/dokimi/dokimi/skills/loader.py +++ b/dokimi/dokimi/skills/loader.py @@ -19,7 +19,7 @@ import yaml -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/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_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_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 71c24770d9..fe8a596ee9 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 b61aa25889..1329c159d3 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 b768f58cb2..1ccea42044 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 b8f3a06713..5d94819847 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 f6b21d5b7e..3b9b1acf6e 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_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 6626d95d5f..49d18290b5 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): @@ -131,10 +131,11 @@ def test_an_unparseable_questions_from_file_names_the_flag(tmp_path): @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="needs named pipes") def test_a_named_pipe_as_custom_questions_or_questions_from_is_not_read_up_front(tmp_path, monkeypatch): """The early parse is for regular files: reading a pipe there would take the one read its writer gets.""" + from dokimi import files from dokimi.orchestrator import pipeline read = [] - monkeypatch.setattr(pipeline, "read_json_input", lambda path, **kw: read.append(path)) + monkeypatch.setattr(files, "read_json_input", lambda path, **kw: read.append(path)) fifo = tmp_path / "q.json" os.mkfifo(fifo) diff --git a/dokimi/tests/test_explore_track.py b/dokimi/tests/test_explore_track.py index ac5bbb72b0..8f5fdd6115 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 115c955d92..d87f238f15 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_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.write_probe", "dokimi.yaml_unique", "dokimi.judge_rule", "dokimi.spend", "dokimi.text_spans", "dokimi.code_spans", @@ -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, [])) diff --git a/dokimi/tests/test_input_devices.py b/dokimi/tests/test_input_devices.py index 1528b6068f..9d5f0cf818 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 c6c7e7f2b4..dfe111ba7f 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_provider_default.py b/dokimi/tests/test_judge_provider_default.py index 691c5d0ca1..e4e186171c 100644 --- a/dokimi/tests/test_judge_provider_default.py +++ b/dokimi/tests/test_judge_provider_default.py @@ -352,7 +352,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", "--provider", "claude-cli", "--model", "sonnet", "--judge-model", "gpt-4o"]) @@ -375,7 +375,7 @@ def test_a_judge_model_refusal_does_not_name_a_judge_provider_that_was_not_passe 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 bbb4567bd1..1b169f640c 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 74453d66ec..427ee575e6 100644 --- a/dokimi/tests/test_judge_temperature_entry_points.py +++ b/dokimi/tests/test_judge_temperature_entry_points.py @@ -305,7 +305,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)) @@ -314,7 +314,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", @@ -329,7 +329,7 @@ def test_evaluate_refuses_a_judge_temperature_the_route_refuses_before_any_call( def test_an_empty_bedrock_judge_model_is_reported_before_sampling(monkeypatch, argv): import litellm - from dokimi.utils import InputError + from dokimi.files import InputError monkeypatch.setattr(litellm, "get_supported_openai_params", lambda **_: ["max_tokens"]) args = build_parser().parse_args([*argv, "--judge-provider", "amazon-bedrock", "--judge-model", "", diff --git a/dokimi/tests/test_judge_validity.py b/dokimi/tests/test_judge_validity.py index a3803633bc..ab9cd522dd 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"]: @@ -1739,7 +1739,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", @@ -1797,7 +1797,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}?", @@ -1818,7 +1818,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": { @@ -1856,7 +1856,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": { @@ -1872,7 +1872,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("") @@ -1899,7 +1899,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("") @@ -1933,7 +1933,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 @@ -1972,7 +1972,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}?", @@ -1995,7 +1995,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. @@ -2055,7 +2055,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): @@ -2121,7 +2121,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): @@ -2157,7 +2157,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 f5e7744f39..8ad90cfe2f 100644 --- a/dokimi/tests/test_key_files.py +++ b/dokimi/tests/test_key_files.py @@ -318,7 +318,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 61b52fb54b..c8e10de8fe 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 b0ef5e1a6e..f159fe92db 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 09d9316d2e..6707c443a3 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_model_compare.py b/dokimi/tests/test_model_compare.py index 4ddb7f19d1..0858a67ec3 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_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 741783957f..65472b6148 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 a3f536ddcc..89dec6600d 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 651bfcb0fc..3e700ed552 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 95900df87e..db82f65ef2 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 afbbd8c8bc..a1d4297207 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 155a69fcb1..a87660b293 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 @@ -100,7 +100,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", model, "--provider", "claude-cli") 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 e09057dd33..d11e661062 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 39a2f1929d..93bf207ac4 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 c470d14758..85720e32cd 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 0df39e6aac..b316c8cba4 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 b202580d53..682f6f413f 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_question_ids.py b/dokimi/tests/test_question_ids.py index f30f3ce282..a3e6b5fc09 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 b20ee50f2f..af643d90ec 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 dc9ebda52a..e45df79f72 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 03b96d7fc7..3343b9d074 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_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 a2df1ab886..30adc6f872 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 87f2d184ff..082b9ff3ff 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 975c0345a8..96392d48cc 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 6c95bdaced..4836435ff6 100644 --- a/dokimi/tests/test_run_envelope.py +++ b/dokimi/tests/test_run_envelope.py @@ -31,7 +31,7 @@ ) 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_rundir.py b/dokimi/tests/test_runs_rundir.py index e103ed65a3..60e69b7584 100644 --- a/dokimi/tests/test_runs_rundir.py +++ b/dokimi/tests/test_runs_rundir.py @@ -25,7 +25,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 fd61ae752a..7f4b6bb5f6 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 f4b9aa9bf6..13132a9ebf 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.model_names": [ ["eval", "score", "reference", "--answers", a, "--questions", q, "--output", 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")), ] @@ -135,11 +135,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", "--output", 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_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_subjects.py b/dokimi/tests/test_subjects.py index cf2d6f5c54..5c77f05e4c 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 d46bb4335e..034a3d6ef6 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 e4391e4878..e9edd3cb10 100644 --- a/dokimi/tests/test_trigger_probe.py +++ b/dokimi/tests/test_trigger_probe.py @@ -381,7 +381,7 @@ def test_cli_passes_every_flag_to_the_probe(tmp_path, monkeypatch): 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") @@ -390,7 +390,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") @@ -588,7 +588,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_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 From 027e3f8d8b7bc1d98aa09066e65a53d201982fe4 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Wed, 25 Nov 2026 11:13:48 -0800 Subject: [PATCH 2/8] Use direct imports in the evaluation pipeline Thread: PRRT_kwDOVBg7g8673s4q Signed-off-by: Nikolay Petrov --- dokimi/dokimi/orchestrator/pipeline.py | 26 +++++++++++++----------- dokimi/tests/test_evaluate_cli_inputs.py | 3 +-- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index 542bfa5cd5..f499676a20 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, resolve_library_id_for_product -from dokimi import digest, files, model_names +from dokimi.digest import key_bytes +from dokimi.files import InputError, read_json_input, refuse_device +from dokimi.model_names import same_evaluator logger = logging.getLogger(__name__) @@ -69,7 +71,7 @@ def _read_input_set(path: Path, what: str, fix: str = "") -> List[Dict[str, Any] return load_questions_payload(path) except (ValueError, RecursionError, OSError) as exc: # refused by the schema, not JSON or UTF-8, unreadable named = "" if str(path) in str(exc) else f" {path}" # a schema refusal already names the file - raise files.InputError(f"{what}{named} cannot be used: {exc}" + (f"\n({fix})" if fix else "")) from exc + raise InputError(f"{what}{named} cannot be used: {exc}" + (f"\n({fix})" if fix else "")) from exc def _check_custom_questions(path: Path, parse: bool = True) -> None: @@ -80,16 +82,16 @@ def _check_custom_questions(path: Path, parse: bool = True) -> None: """ if not path.exists(): raise FileNotFoundError(f"--custom-questions path does not exist: {path}") - files.refuse_device(path, "--custom-questions") + refuse_device(path, "--custom-questions") if path.is_dir(): # refuse_device lets a directory pass; reading it ends in IsADirectoryError - raise files.InputError(f"--custom-questions {path}: not a file") + raise InputError(f"--custom-questions {path}: not a file") try: # a regular file only: opening a named pipe here would take the writer's one read if path.is_file(): path.open("rb").close() except OSError as exc: # unreadable: refused here, before the output directories exist - raise files.InputError(f"--custom-questions {path}: {exc.strerror or exc}") from exc + raise InputError(f"--custom-questions {path}: {exc.strerror or exc}") from exc if parse and path.is_file(): # the run reads it again through the same function, with the same flag - files.read_json_input(path, flag="--custom-questions") + read_json_input(path, flag="--custom-questions") class EvaluationPipeline: @@ -253,9 +255,9 @@ def __init__( raise FileNotFoundError( f"--questions-from: questions file not found: {qf}" ) - files.refuse_device(qf, "--questions-from") + refuse_device(qf, "--questions-from") if qf.is_file(): - files.read_json_input(qf, flag="--questions-from") + read_json_input(qf, flag="--questions-from") self.external_questions_path: Optional[Path] = qf logger.info(f"Will reuse questions from: {qf}") else: @@ -511,7 +513,7 @@ def _generate_questions(self, personas: Dict[str, Any]) -> List[Dict[str, Any]]: library_id = self._library_id(mcp_client) # The id is the registry's for every source, so the topics cache is also keyed on the source. - source_key = hashlib.sha256(digest.key_bytes(self.doc_source)).hexdigest()[:16] + source_key = hashlib.sha256(key_bytes(self.doc_source)).hexdigest()[:16] extractor = RagasSeedExtractor(mcp_client=mcp_client, cache_dir=Path(".cache/topics") / source_key) topics = extractor.extract_topics( @@ -582,7 +584,7 @@ def _read_question_inputs(self) -> Optional[List[Dict[str, Any]]]: self._custom_questions = self._load_custom_questions() return None if not reused: # an empty reused set is a bad input (exit 2), refused before persona discovery - raise files.InputError(f"No questions to answer: {path} has no questions") + raise InputError(f"No questions to answer: {path} has no questions") return reused def _load_custom_questions(self) -> List[Dict[str, Any]]: @@ -595,7 +597,7 @@ def _load_custom_questions(self) -> List[Dict[str, Any]]: path = self.custom_questions_path if not (path and path.exists()): return [] - files.refuse_device(path, "--custom-questions") + refuse_device(path, "--custom-questions") if getattr(self, "golden_pinned", False): # the golden set of --questions-root: no flag to name custom_questions = _read_input_set(path, "the golden set") else: @@ -760,7 +762,7 @@ def _evaluate_answers(self, answers: Optional[List[Dict[str, Any]] | Dict[str, A "judge_model": self.judge_model, "judge_provider": self.judge_provider, "question_set_hash": question_set_hash, - "evaluator_independence_warning": model_names.same_evaluator(str(self.model), str(self.judge_model)), + "evaluator_independence_warning": same_evaluator(str(self.model), str(self.judge_model)), }, ) diff --git a/dokimi/tests/test_evaluate_cli_inputs.py b/dokimi/tests/test_evaluate_cli_inputs.py index 49d18290b5..d5658a47fa 100644 --- a/dokimi/tests/test_evaluate_cli_inputs.py +++ b/dokimi/tests/test_evaluate_cli_inputs.py @@ -131,11 +131,10 @@ def test_an_unparseable_questions_from_file_names_the_flag(tmp_path): @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="needs named pipes") def test_a_named_pipe_as_custom_questions_or_questions_from_is_not_read_up_front(tmp_path, monkeypatch): """The early parse is for regular files: reading a pipe there would take the one read its writer gets.""" - from dokimi import files from dokimi.orchestrator import pipeline read = [] - monkeypatch.setattr(files, "read_json_input", lambda path, **kw: read.append(path)) + monkeypatch.setattr(pipeline, "read_json_input", lambda path, **kw: read.append(path)) fifo = tmp_path / "q.json" os.mkfifo(fifo) From 7e84b118b839d4ef4f131a0586af5b294c1d4bee Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Wed, 25 Nov 2026 11:37:24 -0800 Subject: [PATCH 3/8] Keep the pipeline within its source growth cap Signed-off-by: Nikolay Petrov --- dokimi/dokimi/orchestrator/pipeline.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index f499676a20..423010759b 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -781,7 +781,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, @@ -796,7 +795,6 @@ def _generate_report( output_format="markdown" ) - # Save report write_bytes_in_place_or_atomic(self.report_path, text_file_bytes(report)) return report From 78ee484b4053e93c486bb07cb448c76bbbdcbfa0 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Wed, 25 Nov 2026 20:34:27 -0800 Subject: [PATCH 4/8] refactor(commands): route the JSON file flags through read_json_input Eight command sites hand-rolled "read JSON or InputError": arms _refuse_external_trigger_set, questions _load_questions_json and _read_json_input, personas validate, catalog trigger-probe, report generate, repo scan --baseline and tools preference --groups. Each now calls read_json_input(path, flag=...), so a device or socket is refused with " : not a file" before it is read, and the messages share one shape. Exit codes stay 2 except one: a JSON file nested past the decoder's recursion limit now exits 2 naming the file. Four of these sites used to let the RecursionError escape to exit 5 with a traceback. Messages change; the Changed fragment lists them. Tests pin the new text, the device refusal for each newly routed flag, and deep nesting. Signed-off-by: Nikolay Petrov --- .../20261125_170000_napetrov_arch-r6-6.md | 3 ++ dokimi/dokimi/commands/arms.py | 10 ++-- dokimi/dokimi/commands/catalog_probe.py | 4 +- dokimi/dokimi/commands/personas.py | 11 +---- dokimi/dokimi/commands/questions.py | 23 ++-------- dokimi/dokimi/commands/repo_scan.py | 9 +--- dokimi/dokimi/commands/report.py | 10 +--- dokimi/dokimi/commands/tools.py | 7 +-- dokimi/tests/test_arms_output_errors.py | 2 +- dokimi/tests/test_cli_refusal_parity.py | 2 +- dokimi/tests/test_input_devices.py | 46 +++++++++++++++++++ dokimi/tests/test_personas_approve.py | 4 +- dokimi/tests/test_report_cli_inputs.py | 12 ++--- 13 files changed, 80 insertions(+), 63 deletions(-) create mode 100644 dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md diff --git a/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md b/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md new file mode 100644 index 0000000000..d8632781a6 --- /dev/null +++ b/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md @@ -0,0 +1,3 @@ +### Changed + +- **The JSON input flags share one reader and refuse a device.** `eval personas validate --file`, `eval questions generate --personas` and `--topics`, `eval questions analyze` and `review --questions`, `arms run` and `matrix-run --questions`, `report generate --eval`, `tools preference --groups`, `repo scan --baseline` and `catalog trigger-probe --trigger-set` now read their file with `read_json_input`. A device or socket given to one of them (`/dev/zero`, `/dev/null`) exits 2 with ` : not a file`, before it is read; it used to be read in full, and `/dev/null` used to fail as invalid JSON. (`personas validate --file` and `questions generate --personas/--topics` already refused a device; only their message changes.) Their messages take the ` : ` form: `cannot read : ` and ` is not valid JSON: ` become ` : `, `Cannot read ` and `Cannot parse ` (`personas validate`) become `--file : `, `cannot load matrix run inputs: ` (`matrix-run --questions` on an unreadable file) becomes `--questions : `, and `--trigger-set : ` names the file, and a shape error inside the set keeps its `--trigger-set: ` form. The reason is the OS error text (`No such file or directory`), not the full `[Errno 2] ...` string. An empty path exits 2 with ` "": no file given`. Exit codes stay 2, with one exception: a JSON file nested past the decoder's recursion limit now exits 2 naming the file, where `personas validate`, `report generate`, `catalog trigger-probe` and `questions generate --personas/--topics` used to exit 5 with a traceback. diff --git a/dokimi/dokimi/commands/arms.py b/dokimi/dokimi/commands/arms.py index 55edae6b32..b70df1a966 100644 --- a/dokimi/dokimi/commands/arms.py +++ b/dokimi/dokimi/commands/arms.py @@ -16,7 +16,7 @@ from dokimi.commands.novelty_budget import fresh_partial_destination from dokimi.exit_codes import EXIT_FAILURE, EXIT_USAGE from dokimi.llm import ANSWER_PROVIDERS -from dokimi.files import InputError +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 @@ -522,7 +522,7 @@ def _load_questions(path: str) -> list[dict]: from dokimi.questions.artifact import load_questions _refuse_external_trigger_set(path) - questions = load_questions(path).questions + questions = load_questions(path, flag="--questions").questions # a device is refused here, not read whole ids = [question_id(q) for q in questions] for i, qid in enumerate(ids): # The records reader refuses any other id, so a run with one would be paid for and lost. @@ -539,13 +539,11 @@ def _refuse_external_trigger_set(path: str) -> None: lints them against the catalog the arm will offer; a questions loader that guessed at them would drop that lint and, for skill-creator, the target skill. """ - import json - from dokimi.external.trigger_set import FORMAT_QUESTIONS, detect_trigger_format try: - data = json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError, RecursionError): + data = read_json_input(path) + except InputError: return # the questions loader reports it fmt = detect_trigger_format(data) if fmt and fmt != FORMAT_QUESTIONS: diff --git a/dokimi/dokimi/commands/catalog_probe.py b/dokimi/dokimi/commands/catalog_probe.py index 9a548eb321..dcd76cac9e 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.files import InputError +from dokimi.files import InputError, read_json_input from dokimi.write_probe import can_write @@ -156,8 +156,8 @@ def _labelled_queries(args: argparse.Namespace, names: set) -> list: """The labelled queries to run; a label naming no *names* skill is an input error.""" from dokimi.external import trigger_set as ts + data = read_json_input(args.trigger_set, flag="--trigger-set") # InputError names the file try: - data = json.loads(Path(args.trigger_set).read_text(encoding="utf-8")) _fmt, queries = ts.read_trigger_set(data, target=args.target) except (OSError, ValueError) as exc: raise InputError(f"--trigger-set: {exc}") from exc diff --git a/dokimi/dokimi/commands/personas.py b/dokimi/dokimi/commands/personas.py index 3adc23a818..23ae0806d1 100644 --- a/dokimi/dokimi/commands/personas.py +++ b/dokimi/dokimi/commands/personas.py @@ -6,7 +6,6 @@ from __future__ import annotations import argparse -import json import sys from pathlib import Path @@ -18,7 +17,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.files import InputError, refuse_device +from dokimi.files import InputError, read_json_input def _usd_text(usd: float) -> str: @@ -141,15 +140,9 @@ def cmd_personas_approve(args: argparse.Namespace) -> None: if not persona_file.exists(): raise InputError(f"File not found: {persona_file}") - refuse_device(persona_file, "--file") # Validate JSON structure - try: - personas = json.loads(persona_file.read_text(encoding="utf-8")) - except OSError as e: - raise InputError(f"Cannot read {persona_file}: {e}") from e - except ValueError as e: # JSONDecodeError and bad UTF-8 - raise InputError(f"Cannot parse {persona_file}: {e}") from e + personas = read_json_input(args.file, flag="--file") # the raw argument: "" is refused, not read as "." required_keys = {"product", "personas"} if not isinstance(personas, dict): diff --git a/dokimi/dokimi/commands/questions.py b/dokimi/dokimi/commands/questions.py index b7a8a9c15e..a81bfb23fb 100644 --- a/dokimi/dokimi/commands/questions.py +++ b/dokimi/dokimi/commands/questions.py @@ -7,7 +7,6 @@ import argparse import hashlib -import json import sys from pathlib import Path from typing import Any, Dict @@ -15,17 +14,14 @@ 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.files import InputError, refuse_device +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): - """Parse the questions file, or exit 2 naming it when it is missing, unreadable or not JSON.""" - try: - return json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError, RecursionError) as exc: - raise InputError(f"cannot read questions from {path}: {exc}") from exc + """Parse the questions file, or exit 2 naming it when it is missing, unreadable, a device or not JSON.""" + return read_json_input(path, flag="--questions") def _extract_questions(questions_data, source: str) -> list: @@ -41,18 +37,9 @@ def _extract_questions(questions_data, source: str) -> list: return raw -def _read_json_input(path: str, flag: str): - """The parsed JSON at ``path``, or exit 2 with a message naming the file (and ``flag``, for a device).""" - refuse_device(path, flag) # InputError: cli.main prints it and exits 2 - try: - return json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: # ValueError covers JSONDecodeError and bad UTF-8 - raise InputError(f"cannot read {path}: {exc}") from exc - - def _load_personas(path: str) -> list: """The ``personas`` list of a personas file, or exit 2 with a message naming the file.""" - data = _read_json_input(path, "--personas") + data = read_json_input(path, flag="--personas") personas = data.get("personas") if isinstance(data, dict) else None if not isinstance(personas, list): raise InputError(f"{path} must be a JSON object with a 'personas' list") @@ -301,7 +288,7 @@ def cmd_questions_generate(args: argparse.Namespace) -> None: # Get or extract topics if args.topics: - topics = _read_json_input(args.topics, "--topics") + topics = read_json_input(args.topics, flag="--topics") if not isinstance(topics, list): raise InputError(f"{args.topics} must be a JSON list of topics") else: diff --git a/dokimi/dokimi/commands/repo_scan.py b/dokimi/dokimi/commands/repo_scan.py index 1771c5c9f9..92daffa3b5 100644 --- a/dokimi/dokimi/commands/repo_scan.py +++ b/dokimi/dokimi/commands/repo_scan.py @@ -7,16 +7,14 @@ from __future__ import annotations import argparse -import json import os -from pathlib import Path import posixpath import re import sys import shutil from dokimi.repos.l0.config import new_failures -from dokimi.files import InputError +from dokimi.files import InputError, read_json_input def _typecheck_or_exit(args: argparse.Namespace): @@ -279,10 +277,7 @@ def baseline_from(args: argparse.Namespace, payload: dict) -> None: if not getattr(args, "baseline", None): return - try: - doc = json.loads(Path(args.baseline).read_text(encoding="utf-8")) - except (OSError, ValueError, RecursionError) as exc: # RecursionError: nesting past the decoder's limit - raise InputError(f"--baseline {args.baseline}: {exc}") from None + doc = read_json_input(args.baseline, flag="--baseline") doc = doc.get("data", doc) if isinstance(doc, dict) and doc.get("schema_version") == "cli_output.v1" else doc if not isinstance(doc, dict) or not isinstance(doc.get("claims"), list): raise InputError(f"--baseline {args.baseline}: not a repo_readiness.v1 report (no claims list)") diff --git a/dokimi/dokimi/commands/report.py b/dokimi/dokimi/commands/report.py index a65d3ef725..9ccaac5c59 100644 --- a/dokimi/dokimi/commands/report.py +++ b/dokimi/dokimi/commands/report.py @@ -7,12 +7,11 @@ import argparse import sys -import json from pathlib import Path from dokimi import cli_flags from dokimi.commands._output import exit_on_rejected from dokimi.exit_codes import EXIT_USAGE -from dokimi.files import InputError +from dokimi.files import InputError, read_json_input def _write_combined_report(args, regular_runs, golden_runs, run_ids, warnings) -> None: @@ -119,12 +118,7 @@ def cmd_report_generate(args: argparse.Namespace) -> None: from dokimi.report import ReportGenerator # Load eval and questions - try: - eval_data = json.loads(Path(args.eval).read_text(encoding="utf-8")) - except OSError as exc: - raise InputError(f"cannot read {args.eval}: {exc}") from exc - except ValueError as exc: # not UTF-8 or not JSON - raise InputError(f"{args.eval} is not valid JSON: {exc}") from exc + eval_data = read_json_input(args.eval, flag="--eval") # Every --format: a report of no evaluations has nothing to show, and an empty # eval means the run that wrote it judged nothing: a failed run, exit 1. evaluations = eval_data.get("evaluations", []) if isinstance(eval_data, dict) else eval_data diff --git a/dokimi/dokimi/commands/tools.py b/dokimi/dokimi/commands/tools.py index c413c307ae..104269f35a 100644 --- a/dokimi/dokimi/commands/tools.py +++ b/dokimi/dokimi/commands/tools.py @@ -18,7 +18,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.files import InputError +from dokimi.files import InputError, read_json_input PROVIDERS = list(API_PROVIDERS) # tool calling: no CLI backend @@ -143,9 +143,10 @@ def _check_out_json_writable(path: str) -> None: def cmd_tools_preference(args: argparse.Namespace) -> None: from dokimi import tool_preference as tp + data = read_json_input(args.groups, flag="--groups") # InputError names the file try: - doc = tp.load_groups(json.loads(Path(args.groups).read_text(encoding="utf-8"))) - except (OSError, RecursionError, ValueError, tp.GroupsError) as exc: + doc = tp.load_groups(data) + except (ValueError, tp.GroupsError) as exc: raise InputError(f"--groups {args.groups}: {exc}") from exc factors = list(dict.fromkeys(f for f in args.factors.split(",") if f)) if args.factors else list(tp.FACTORS) unknown = sorted(set(factors) - set(tp.FACTORS)) diff --git a/dokimi/tests/test_arms_output_errors.py b/dokimi/tests/test_arms_output_errors.py index e3ef28cd02..2f487b7086 100644 --- a/dokimi/tests/test_arms_output_errors.py +++ b/dokimi/tests/test_arms_output_errors.py @@ -187,7 +187,7 @@ def test_matrix_run_exits_2_on_an_unreadable_questions_file(tmp_path, capsys, ki with refusal() as exc: args.func(args) assert exc.code == 2 - assert capsys.readouterr().err.startswith("Error: cannot load matrix run inputs:") + assert capsys.readouterr().err.startswith(f"Error: --questions {args.questions}: ") @pytest.mark.parametrize("error", [PermissionError("denied"), RecursionError("deep")], ids=lambda e: type(e).__name__) diff --git a/dokimi/tests/test_cli_refusal_parity.py b/dokimi/tests/test_cli_refusal_parity.py index 6ec611fc12..0b097687eb 100644 --- a/dokimi/tests/test_cli_refusal_parity.py +++ b/dokimi/tests/test_cli_refusal_parity.py @@ -118,7 +118,7 @@ def _subject_run(d): (_subject_run, "no-such-harness"), (lambda d: ["catalog", "trigger-probe", "--catalog", str(_skill_catalog(d)), "--trigger-set", str(d / "missing.json"), "--claude", "python3", "--out", str(d / "probe.json")], - "--trigger-set: "), + "--trigger-set "), ], ids=["catalog-formats-root", "explore-run-command-arm-without-template", "explore-run-unknown-arm", "explore-run-no-arms", "explore-run-empty-arm", "tasks-run-no-tasks", "tasks-run-swebench-no-tasks", "tasks-run-no-harnesses", "subjects-run-unknown-work-harness", "trigger-probe-unreadable-trigger-set"]) diff --git a/dokimi/tests/test_input_devices.py b/dokimi/tests/test_input_devices.py index 9d5f0cf818..dde19b3923 100644 --- a/dokimi/tests/test_input_devices.py +++ b/dokimi/tests/test_input_devices.py @@ -113,6 +113,13 @@ def test_evaluate_refuses_a_device_as_custom_questions(monkeypatch, tmp_path, ca assert "Error: --custom-questions /dev/null: not a file" in capsys.readouterr().err +def test_arms_questions_loader_refuses_a_device_with_its_flag_name(): + from dokimi.commands.arms import _load_questions + + with pytest.raises(InputError, match=r"^--questions /dev/null: not a file$"): + _load_questions(DEVICE) + + def test_the_pipeline_refuses_a_device_as_questions_from(tmp_path): with pytest.raises(InputError, match=r"^--questions-from /dev/null: not a file$"): EvaluationPipeline(product="Demo", output_dir=tmp_path / "out", description="d", questions_from=DEVICE) @@ -162,6 +169,28 @@ def test_questions_generate_refuses_a_device_as_topics(monkeypatch, tmp_path, ca assert capsys.readouterr().err.strip() == "Error: --topics /dev/null: not a file" +# The file flags that read JSON through read_json_input: each refuses a device with its own flag name, before a read. +_JSON_FLAG_DEVICES = [ + (["report", "generate", "--product", "p", "--questions", "q.json", "--eval", DEVICE, + "--format", "markdown", "--out", "r.md"], "--eval"), + (["tools", "preference", "--groups", DEVICE, "--out", "x.json"], "--groups"), + (["eval", "questions", "analyze", "--product", "p", "--questions", DEVICE], "--questions"), + (["eval", "questions", "review", "--product", "p", "--questions", DEVICE], "--questions"), + (["repo", "scan", ".", "--baseline", DEVICE], "--baseline"), + (["catalog", "trigger-probe", "--catalog", ".", "--trigger-set", DEVICE, "--claude", "python3", + "--out", "p.json"], "--trigger-set"), + (["eval", "personas", "validate", "--file", DEVICE], "--file"), +] + + +@pytest.mark.parametrize("argv, flag", _JSON_FLAG_DEVICES, ids=["-".join(argv[:3]) for argv, _flag in _JSON_FLAG_DEVICES]) +def test_json_file_flags_refuse_a_device_with_their_flag_name(monkeypatch, tmp_path, capsys, argv, flag): + monkeypatch.chdir(tmp_path) + assert _main(monkeypatch, *argv) == 2 + err = capsys.readouterr().err + assert f"Error: {flag} {DEVICE}: not a file" in err and "Traceback" not in err + + def test_novelty_analyze_refuses_a_device_as_placebo_text(monkeypatch, capsys): assert _main(monkeypatch, "skill", "novelty", "analyze", "--artifact", "skill:data/skills/fastcontext", "--arms", "no_artifact,full,placebo", "--placebo-text", DEVICE) == 2 @@ -281,3 +310,20 @@ def test_trace_consistency_refuses_a_device_as_outcomes_or_contract(monkeypatch, good = _trace(tmp_path) assert _main(monkeypatch, "trace", "consistency", flag, DEVICE, good) == 2 assert f"Error: {flag} /dev/null: not a file" in capsys.readouterr().err + + +@pytest.mark.parametrize("argv, flag", [ + (["eval", "personas", "validate", "--file"], "--file"), + (["report", "generate", "--product", "p", "--questions", "q.json", "--format", "markdown", "--out", "r.md", + "--eval"], "--eval"), +], ids=["personas-validate", "report-generate"]) +def test_json_nested_past_the_decoder_limit_is_bad_json_not_a_crash(monkeypatch, tmp_path, capsys, argv, flag): + """Nesting past the JSON decoder's recursion limit exits 2 naming the file (the shared reader's contract); + it used to escape as a RecursionError, exit 5, at these sites.""" + deep = tmp_path / "deep.json" + deep.write_text("[" * 200000 + "]" * 200000, encoding="utf-8") + monkeypatch.chdir(tmp_path) + assert _main(monkeypatch, *argv, str(deep)) == 2 + err = capsys.readouterr().err + # The decoder's own words for the overflow vary by Python (3.14 says "Stack overflow"), so pin the file and the exit only. + assert f"Error: {flag} {deep}: " in err and "Traceback" not in err diff --git a/dokimi/tests/test_personas_approve.py b/dokimi/tests/test_personas_approve.py index afd7c72d19..fb720ce6ff 100644 --- a/dokimi/tests/test_personas_approve.py +++ b/dokimi/tests/test_personas_approve.py @@ -46,11 +46,11 @@ def test_approve_exits_2_with_a_message_on_an_invalid_file(tmp_path, monkeypatch err = capsys.readouterr().err assert err.startswith("Error: ") and "Traceback" not in err if content.startswith(b"\xff"): - assert f"Cannot parse {f}" in err + assert f"Error: --file {f}: 'utf-8' codec can't decode" in err if content.endswith(b'["not-an-object"]}'): assert "'not-an-object'" in err def test_approve_exits_2_when_the_path_is_a_directory(tmp_path, monkeypatch, capsys): assert _approve(tmp_path, monkeypatch) == 2 - assert f"Cannot read {tmp_path}" in capsys.readouterr().err + assert f"Error: --file {tmp_path}: Is a directory" in capsys.readouterr().err diff --git a/dokimi/tests/test_report_cli_inputs.py b/dokimi/tests/test_report_cli_inputs.py index d395790396..641f737ef7 100644 --- a/dokimi/tests/test_report_cli_inputs.py +++ b/dokimi/tests/test_report_cli_inputs.py @@ -36,24 +36,24 @@ def _err(tmp_path, eval_path, capsys, fmt="markdown", code=2): def test_a_missing_eval_file_is_reported_as_unreadable(tmp_path, capsys): missing = tmp_path / "missing.json" - assert f"Error: cannot read {missing}" in _err(tmp_path, missing, capsys) + assert f"Error: --eval {missing}: No such file or directory" in _err(tmp_path, missing, capsys) def test_a_directory_as_eval_is_reported_as_unreadable(tmp_path, capsys): - assert f"Error: cannot read {tmp_path}" in _err(tmp_path, tmp_path, capsys) + assert f"Error: --eval {tmp_path}: Is a directory" in _err(tmp_path, tmp_path, capsys) -@pytest.mark.parametrize("text", ["", "{not json"]) -def test_an_eval_file_that_is_not_json_is_reported_as_invalid_json(tmp_path, capsys, text): +@pytest.mark.parametrize("text, reason", [("", "Expecting value"), ("{not json", "Expecting property name")]) +def test_an_eval_file_that_is_not_json_is_reported_as_invalid_json(tmp_path, capsys, text, reason): bad = tmp_path / "bad.json" bad.write_text(text, encoding="utf-8") - assert f"Error: {bad} is not valid JSON" in _err(tmp_path, bad, capsys) + assert f"Error: --eval {bad}: {reason}" in _err(tmp_path, bad, capsys) def test_a_non_utf8_eval_file_is_reported_as_invalid_utf8_json(tmp_path, capsys): binary = tmp_path / "bin.json" binary.write_bytes(bytes([0xFF, 0xFE])) - assert f"Error: {binary} is not valid JSON" in _err(tmp_path, binary, capsys) + assert f"Error: --eval {binary}: 'utf-8' codec can't decode" in _err(tmp_path, binary, capsys) @pytest.mark.parametrize("text", ["[1, 2]", "null", "5", '"x"']) From 9781a604e7edbe690e47c6ba96131133d283b507 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Mon, 30 Nov 2026 06:14:13 -0700 Subject: [PATCH 5/8] fix(arms): arms run --questions reports an unreadable file as --questions Signed-off-by: Vladislav Perevezentsev --- dokimi/dokimi/commands/arms.py | 4 ++-- dokimi/tests/test_arms_output_errors.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dokimi/dokimi/commands/arms.py b/dokimi/dokimi/commands/arms.py index 16d789924a..93b77bee20 100644 --- a/dokimi/dokimi/commands/arms.py +++ b/dokimi/dokimi/commands/arms.py @@ -85,8 +85,8 @@ def cmd_arms_run(args: argparse.Namespace) -> None: questions = _load_questions(args.questions) config = _with_named_cell(config, args.matrix_cells, args.matrix_cell) prepared = prepare_arms(config, specs, questions) - except EmptyQuestionError: - raise # a bad input record, not an arm setup error: cli.main reports it (exit 2) + except InputError: # EmptyQuestionError is one + raise # a bad input record or an unreadable file, not an arm setup error: cli.main reports it (exit 2) except ProbeError as exc: print(f"Error running arms: {exc}", file=sys.stderr) sys.exit(EXIT_FAILURE) diff --git a/dokimi/tests/test_arms_output_errors.py b/dokimi/tests/test_arms_output_errors.py index 2f487b7086..c33f0846a6 100644 --- a/dokimi/tests/test_arms_output_errors.py +++ b/dokimi/tests/test_arms_output_errors.py @@ -172,7 +172,7 @@ def test_arms_run_exits_2_on_an_unreadable_questions_file(tmp_path, capsys, kind with refusal() as exc: args.func(args) assert exc.code == 2 - assert capsys.readouterr().err.startswith("Error: cannot build arms/plugins:") + assert capsys.readouterr().err.startswith(f"Error: --questions {questions}: ") @pytest.mark.parametrize("kind", ["directory", "deep"]) From 117da95a618586fd54676d04616a429b99ec9fb4 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Mon, 30 Nov 2026 06:15:08 -0700 Subject: [PATCH 6/8] fix(repo): repo scan --static reads its file with read_json_input Signed-off-by: Vladislav Perevezentsev --- dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md | 2 +- dokimi/dokimi/commands/repo.py | 8 ++------ dokimi/tests/test_input_devices.py | 1 + 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md b/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md index d8632781a6..98eab81372 100644 --- a/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md +++ b/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md @@ -1,3 +1,3 @@ ### Changed -- **The JSON input flags share one reader and refuse a device.** `eval personas validate --file`, `eval questions generate --personas` and `--topics`, `eval questions analyze` and `review --questions`, `arms run` and `matrix-run --questions`, `report generate --eval`, `tools preference --groups`, `repo scan --baseline` and `catalog trigger-probe --trigger-set` now read their file with `read_json_input`. A device or socket given to one of them (`/dev/zero`, `/dev/null`) exits 2 with ` : not a file`, before it is read; it used to be read in full, and `/dev/null` used to fail as invalid JSON. (`personas validate --file` and `questions generate --personas/--topics` already refused a device; only their message changes.) Their messages take the ` : ` form: `cannot read : ` and ` is not valid JSON: ` become ` : `, `Cannot read ` and `Cannot parse ` (`personas validate`) become `--file : `, `cannot load matrix run inputs: ` (`matrix-run --questions` on an unreadable file) becomes `--questions : `, and `--trigger-set : ` names the file, and a shape error inside the set keeps its `--trigger-set: ` form. The reason is the OS error text (`No such file or directory`), not the full `[Errno 2] ...` string. An empty path exits 2 with ` "": no file given`. Exit codes stay 2, with one exception: a JSON file nested past the decoder's recursion limit now exits 2 naming the file, where `personas validate`, `report generate`, `catalog trigger-probe` and `questions generate --personas/--topics` used to exit 5 with a traceback. +- **The JSON input flags share one reader and refuse a device.** `eval personas validate --file`, `eval questions generate --personas` and `--topics`, `eval questions analyze` and `review --questions`, `arms run` and `matrix-run --questions`, `report generate --eval`, `tools preference --groups`, `repo scan --baseline` and `--static` and `catalog trigger-probe --trigger-set` now read their file with `read_json_input`. A device or socket given to one of them (`/dev/zero`, `/dev/null`) exits 2 with ` : not a file`, before it is read; it used to be read in full, and `/dev/null` used to fail as invalid JSON. (`personas validate --file` and `questions generate --personas/--topics` already refused a device; only their message changes.) Their messages take the ` : ` form: `cannot read : ` and ` is not valid JSON: ` become ` : `, `Cannot read ` and `Cannot parse ` (`personas validate`) become `--file : `, `cannot load matrix run inputs: ` (`matrix-run --questions` on an unreadable file) becomes `--questions : `, and `--trigger-set : ` names the file, and a shape error inside the set keeps its `--trigger-set: ` form. The reason is the OS error text (`No such file or directory`), not the full `[Errno 2] ...` string. An empty path exits 2 with ` "": no file given`. Exit codes stay 2, with one exception: a JSON file nested past the decoder's recursion limit now exits 2 naming the file, where `personas validate`, `report generate`, `catalog trigger-probe` and `questions generate --personas/--topics` used to exit 5 with a traceback. diff --git a/dokimi/dokimi/commands/repo.py b/dokimi/dokimi/commands/repo.py index bb7bb806d2..94a68ddcf0 100644 --- a/dokimi/dokimi/commands/repo.py +++ b/dokimi/dokimi/commands/repo.py @@ -6,7 +6,6 @@ from __future__ import annotations import argparse -import json import re import sys from pathlib import Path @@ -21,7 +20,7 @@ from dokimi.exit_codes import EXIT_USAGE from dokimi.commands.repo_scan import (_loaded_with_default, _print_scan_text, _scan_gate, _scan_reason, _typecheck_or_exit) -from dokimi.utils import InputError +from dokimi.utils import InputError, read_json_input def _normalize_whitespace(text: str, max_len: int | None = 100) -> str: @@ -127,10 +126,7 @@ def cmd_repo_validate(args: argparse.Namespace) -> None: def _read_static(path: str) -> Any: - try: - return json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError, RecursionError) as exc: # ValueError: bad JSON or UTF-8 - raise InputError(f"--static {path}: {exc}") from exc + return read_json_input(path, flag="--static") def cmd_repo_scan(args: argparse.Namespace) -> None: diff --git a/dokimi/tests/test_input_devices.py b/dokimi/tests/test_input_devices.py index 0c9ad4737b..c8a9ead93c 100644 --- a/dokimi/tests/test_input_devices.py +++ b/dokimi/tests/test_input_devices.py @@ -177,6 +177,7 @@ def test_questions_generate_refuses_a_device_as_topics(monkeypatch, tmp_path, ca (["eval", "questions", "analyze", "--product", "p", "--questions", DEVICE], "--questions"), (["eval", "questions", "review", "--product", "p", "--questions", DEVICE], "--questions"), (["repo", "scan", ".", "--baseline", DEVICE], "--baseline"), + (["repo", "scan", ".", "--static", DEVICE], "--static"), (["catalog", "trigger-probe", "--catalog", ".", "--trigger-set", DEVICE, "--claude", "python3", "--out", "p.json"], "--trigger-set"), (["eval", "personas", "validate", "--file", DEVICE], "--file"), From e05c626c364bce0a6a3d5789f381e3c2a1b6cabc Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Mon, 30 Nov 2026 06:15:53 -0700 Subject: [PATCH 7/8] fix(personas): personas validate reports a missing or unreachable --file by flag Signed-off-by: Vladislav Perevezentsev --- dokimi/dokimi/commands/personas.py | 3 --- dokimi/tests/test_cli_refusal_parity.py | 2 +- dokimi/tests/test_personas_approve.py | 21 +++++++++++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/dokimi/dokimi/commands/personas.py b/dokimi/dokimi/commands/personas.py index a63cf3c89f..3d868d04c8 100644 --- a/dokimi/dokimi/commands/personas.py +++ b/dokimi/dokimi/commands/personas.py @@ -138,9 +138,6 @@ def cmd_personas_approve(args: argparse.Namespace) -> None: """Mark persona file as approved (ready for question generation).""" persona_file = Path(args.file) - if not persona_file.exists(): - raise InputError(f"File not found: {persona_file}") - # Validate JSON structure personas = read_json_input(args.file, flag="--file") # the raw argument: "" is refused, not read as "." diff --git a/dokimi/tests/test_cli_refusal_parity.py b/dokimi/tests/test_cli_refusal_parity.py index 0b097687eb..2c105bcfca 100644 --- a/dokimi/tests/test_cli_refusal_parity.py +++ b/dokimi/tests/test_cli_refusal_parity.py @@ -46,7 +46,7 @@ def _assert_helper_matches_main(argv, monkeypatch, capsys, expect): (lambda d: ["catalog", "check", "--root", str(d / "missing")], "--root is not a directory"), (lambda d: ["catalog", "list", "--kind", "subject", "--subjects-root", str(d / "missing")], "--subjects-root is not a directory"), - (lambda d: ["eval", "personas", "validate", "--file", str(d / "missing.json")], "File not found"), + (lambda d: ["eval", "personas", "validate", "--file", str(d / "missing.json")], "No such file or directory"), (lambda d: ["catalog", "list", "--kind", "product", "--registry", str(d / "missing.yaml")], "not a file"), ], ids=["data-export-missing-input", "judge-validate-escalation-needs-pairwise", "eval-tasks-list-root", "explore-list-root", "catalog-check-root", "catalog-list-subject-root", "personas-validate-missing-file", diff --git a/dokimi/tests/test_personas_approve.py b/dokimi/tests/test_personas_approve.py index fb720ce6ff..43322da63b 100644 --- a/dokimi/tests/test_personas_approve.py +++ b/dokimi/tests/test_personas_approve.py @@ -6,6 +6,7 @@ from __future__ import annotations import json +import os import pytest @@ -54,3 +55,23 @@ def test_approve_exits_2_with_a_message_on_an_invalid_file(tmp_path, monkeypatch def test_approve_exits_2_when_the_path_is_a_directory(tmp_path, monkeypatch, capsys): assert _approve(tmp_path, monkeypatch) == 2 assert f"Error: --file {tmp_path}: Is a directory" in capsys.readouterr().err + + +@pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root reads under a mode 000 directory") +def test_approve_exits_2_naming_the_flag_on_a_file_it_cannot_reach(tmp_path, monkeypatch, capsys): + locked = tmp_path / "locked" + locked.mkdir() + f = locked / "personas.json" + f.write_text("{}", encoding="utf-8") + locked.chmod(0) + try: + assert _approve(f, monkeypatch) == 2 + finally: + locked.chmod(0o755) + assert capsys.readouterr().err.strip() == f"Error: --file {f}: Permission denied" + + +def test_approve_exits_2_naming_the_flag_on_a_missing_file(tmp_path, monkeypatch, capsys): + f = tmp_path / "missing.json" + assert _approve(f, monkeypatch) == 2 + assert capsys.readouterr().err.strip() == f"Error: --file {f}: No such file or directory" From 587963468bc518a6d4de22675688d6a097abaee8 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Mon, 30 Nov 2026 06:15:53 -0700 Subject: [PATCH 8/8] docs(changelog): personas validate no longer says File not found Signed-off-by: Vladislav Perevezentsev --- dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md b/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md index 98eab81372..9fdc212b62 100644 --- a/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md +++ b/dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md @@ -1,3 +1,3 @@ ### Changed -- **The JSON input flags share one reader and refuse a device.** `eval personas validate --file`, `eval questions generate --personas` and `--topics`, `eval questions analyze` and `review --questions`, `arms run` and `matrix-run --questions`, `report generate --eval`, `tools preference --groups`, `repo scan --baseline` and `--static` and `catalog trigger-probe --trigger-set` now read their file with `read_json_input`. A device or socket given to one of them (`/dev/zero`, `/dev/null`) exits 2 with ` : not a file`, before it is read; it used to be read in full, and `/dev/null` used to fail as invalid JSON. (`personas validate --file` and `questions generate --personas/--topics` already refused a device; only their message changes.) Their messages take the ` : ` form: `cannot read : ` and ` is not valid JSON: ` become ` : `, `Cannot read ` and `Cannot parse ` (`personas validate`) become `--file : `, `cannot load matrix run inputs: ` (`matrix-run --questions` on an unreadable file) becomes `--questions : `, and `--trigger-set : ` names the file, and a shape error inside the set keeps its `--trigger-set: ` form. The reason is the OS error text (`No such file or directory`), not the full `[Errno 2] ...` string. An empty path exits 2 with ` "": no file given`. Exit codes stay 2, with one exception: a JSON file nested past the decoder's recursion limit now exits 2 naming the file, where `personas validate`, `report generate`, `catalog trigger-probe` and `questions generate --personas/--topics` used to exit 5 with a traceback. +- **The JSON input flags share one reader and refuse a device.** `eval personas validate --file`, `eval questions generate --personas` and `--topics`, `eval questions analyze` and `review --questions`, `arms run` and `matrix-run --questions`, `report generate --eval`, `tools preference --groups`, `repo scan --baseline` and `--static` and `catalog trigger-probe --trigger-set` now read their file with `read_json_input`. A device or socket given to one of them (`/dev/zero`, `/dev/null`) exits 2 with ` : not a file`, before it is read; it used to be read in full, and `/dev/null` used to fail as invalid JSON. (`personas validate --file` and `questions generate --personas/--topics` already refused a device; only their message changes.) Their messages take the ` : ` form: `cannot read : ` and ` is not valid JSON: ` become ` : `, `File not found: `, `Cannot read ` and `Cannot parse ` (`personas validate`) become `--file : `, `cannot load matrix run inputs: ` (`matrix-run --questions` on an unreadable file) becomes `--questions : `, and `--trigger-set : ` names the file, and a shape error inside the set keeps its `--trigger-set: ` form. The reason is the OS error text (`No such file or directory`), not the full `[Errno 2] ...` string. An empty path exits 2 with ` "": no file given`. Exit codes stay 2, with one exception: a JSON file nested past the decoder's recursion limit now exits 2 naming the file, where `personas validate`, `report generate`, `catalog trigger-probe` and `questions generate --personas/--topics` used to exit 5 with a traceback.