Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions dokimi/changelog.d/20261125_170000_napetrov_arch-r6-6.md
Original file line number Diff line number Diff line change
@@ -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 `--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 `<flag> <path>: 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 `<flag> <path>: <reason>` form: `cannot read <path>: <reason>` and `<path> is not valid JSON: <reason>` become `<flag> <path>: <reason>`, `File not found: <path>`, `Cannot read <path>` and `Cannot parse <path>` (`personas validate`) become `--file <path>: <reason>`, `cannot load matrix run inputs: <reason>` (`matrix-run --questions` on an unreadable file) becomes `--questions <path>: <reason>`, and `--trigger-set <path>: <reason>` names the file, and a shape error inside the set keeps its `--trigger-set: <reason>` 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 `<flag> "": 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.
14 changes: 6 additions & 8 deletions dokimi/dokimi/commands/arms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.utils import InputError, question_id
from dokimi.utils import InputError, question_id, read_json_input
from dokimi.write_probe import can_write
from dokimi.eval.judge import JUDGE_PROVIDERS
from dokimi.defaults import (
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -521,7 +521,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.
Expand All @@ -538,13 +538,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:
Expand Down
4 changes: 2 additions & 2 deletions dokimi/dokimi/commands/catalog_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.utils import InputError, read_json_input
from dokimi.write_probe import can_write


Expand Down Expand Up @@ -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
Expand Down
14 changes: 2 additions & 12 deletions dokimi/dokimi/commands/personas.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

Expand All @@ -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.utils import InputError, refuse_device
from dokimi.utils import InputError, read_json_input


def _usd_text(usd: float) -> str:
Expand Down Expand Up @@ -139,17 +138,8 @@ 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}")
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):
Expand Down
23 changes: 5 additions & 18 deletions dokimi/dokimi/commands/questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,19 @@

import argparse
import hashlib
import json
import sys
from pathlib import Path
from typing import Any, Dict

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.utils import InputError, key_bytes, read_json_input, 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:
Expand All @@ -39,18 +35,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")
Expand Down Expand Up @@ -299,7 +286,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:
Expand Down
8 changes: 2 additions & 6 deletions dokimi/dokimi/commands/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
9 changes: 2 additions & 7 deletions dokimi/dokimi/commands/repo_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.utils import InputError
from dokimi.utils import InputError, read_json_input


def _typecheck_or_exit(args: argparse.Namespace):
Expand Down Expand Up @@ -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)")
Expand Down
10 changes: 2 additions & 8 deletions dokimi/dokimi/commands/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.utils import InputError
from dokimi.utils import InputError, read_json_input


def _write_combined_report(args, regular_runs, golden_runs, run_ids, warnings) -> None:
Expand Down Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions dokimi/dokimi/commands/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.utils import InputError, read_json_input

PROVIDERS = list(API_PROVIDERS) # tool calling: no CLI backend

Expand Down Expand Up @@ -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))
Expand Down
4 changes: 2 additions & 2 deletions dokimi/tests/test_arms_output_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand All @@ -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__)
Expand Down
4 changes: 2 additions & 2 deletions dokimi/tests/test_cli_refusal_parity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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"])
Expand Down
47 changes: 47 additions & 0 deletions dokimi/tests/test_input_devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -162,6 +169,29 @@ 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"),
(["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"),
]


@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
Expand Down Expand Up @@ -281,3 +311,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
Loading
Loading