Files
themiz/themiz-next/tests/test_next_core.py
T

333 lines
15 KiB
Python

import os
import hashlib
import json
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import core # noqa: E402
from next_helpers import events, make_case # noqa: E402
SCHEMA = {"type": "object", "properties": {"fakty": {"type": "array"}}, "required": ["fakty"]}
OK = {"structured_output": {"fakty": []}}
def ask(run_, role="docx-reader", **kwargs):
return core.agent(run_, "karta", role, f"РОЛЬ: {role}", "т", SCHEMA, "читает", **kwargs)
def test_agent_argv_contract(fake, run_):
"""Живой прогон держится на каждом из этих флагов: пропавший флаг должен краснить тест."""
system = "РОЛЬ: docx-reader\nИзвлеки факты."
fake.plan({"docx-reader": [{"structured_output": {"fakty": []}}]})
out = core.agent(run_, "karta", "docx-reader", system, "ТЕКСТ", SCHEMA, "читает 01.md")
a = fake.calls()[0]["argv"]
assert out == {"fakty": []}
assert a[0] == "-p" # режим печати: без него claude ждет терминала
assert a[a.index("--model") + 1] == "m-cheap" and a[a.index("--tools") + 1] == ""
assert "--safe-mode" in a and "--strict-mcp-config" in a and "--no-session-persistence" in a
assert a[a.index("--output-format") + 1] == "json"
assert a[a.index("--system-prompt") + 1] == system
assert json.loads(a[a.index("--json-schema") + 1]) == SCHEMA
assert fake.calls()[0]["stdin"] == "ТЕКСТ"
assert not Path(fake.calls()[0]["cwd"]).resolve().is_relative_to(core.ROOT)
def test_agent_retries_overload_then_ok(fake, run_, monkeypatch):
monkeypatch.setattr(core.time, "sleep", lambda s: None)
fake.plan({"docx-reader": ["529", {"structured_output": {"fakty": []}}]})
core.agent(run_, "karta", "docx-reader", "РОЛЬ: docx-reader", "т", SCHEMA, "читает")
assert len(fake.calls()) == 2
assert [e["state"] for e in events(run_) if e["who"] == "docx-reader"].count("retry") == 1
def test_agent_third_overload_stops(fake, run_, monkeypatch):
monkeypatch.setattr(core.time, "sleep", lambda s: None)
fake.plan({"docx-reader": ["529", "529"]})
with pytest.raises(core.Stop):
core.agent(run_, "karta", "docx-reader", "РОЛЬ: docx-reader", "т", SCHEMA, "читает")
@pytest.mark.parametrize("bad", ["garbage", {"structured_output": {"chto-to": 1}}])
def test_agent_invalid_answer_stops(fake, run_, bad):
fake.plan({"docx-reader": [bad]})
with pytest.raises(core.Stop):
core.agent(run_, "karta", "docx-reader", "РОЛЬ: docx-reader", "т", SCHEMA, "читает")
def test_material_text_stays_out_of_events(fake, run_):
fake.plan({"docx-reader": [{"structured_output": {"fakty": []}}]})
core.agent(run_, "karta", "docx-reader", "РОЛЬ: docx-reader", "КАНАРЕЙКА-ПД", SCHEMA, "читает")
assert "КАНАРЕЙКА-ПД" not in (run_.dir / "events.jsonl").read_text(encoding="utf-8")
assert any("КАНАРЕЙКА-ПД" in p.read_text(encoding="utf-8") for p in (run_.dir / "logs").iterdir())
def test_tool_red_code_stops(run_, monkeypatch):
monkeypatch.setitem(core.TOOLS, "x", [sys.executable, "-c", "print('вывод'); raise SystemExit(1)"])
with pytest.raises(core.Stop):
core.tool(run_, "karta", "x", [])
def test_slug():
assert core.slug("Исковое заявление о разделе имущества") == "iskovoe-zayavlenie-o-razdele-imushchestva"
def test_agent_pauses_between_overloads(fake, run_, monkeypatch):
pauses = []
monkeypatch.setattr(core.time, "sleep", pauses.append)
fake.plan({"docx-reader": ["529", "529"]})
with pytest.raises(core.Stop):
ask(run_)
assert pauses == [20] and len(fake.calls()) == 2 # T449: две попытки
assert [e["state"] for e in events(run_) if e["who"] == "docx-reader"] == ["start", "retry", "fail"]
def test_agent_ok_event_has_ms_and_tokens(fake, run_):
fake.plan({"docx-reader": [OK]})
ask(run_)
start, ok = [e for e in events(run_) if e["who"] == "docx-reader"]
assert (start["state"], ok["state"]) == ("start", "ok")
assert ok["tokens"] == {"input_tokens": 1, "output_tokens": 1} and isinstance(ok["ms"], int)
def test_agent_overload_text_in_normal_answer_not_retried(fake, run_):
fake.plan({"docx-reader": [{"structured_output": {"fakty": ["долг 529 рублей, дело 503"]}}]})
assert ask(run_) == {"fakty": ["долг 529 рублей, дело 503"]}
assert len(fake.calls()) == 1
@pytest.mark.parametrize("bad", [
{"code": 2, "stdout": "сбой"},
{"code": 0, "stdout": json.dumps({"type": "result", "is_error": True, "result": "плохо"})},
{"code": 0, "stdout": json.dumps({"type": "result", "is_error": False, "structured_output": "не объект"})},
])
def test_agent_other_failures_stop_without_retry(fake, run_, bad):
fake.plan({"docx-reader": [bad]})
with pytest.raises(core.Stop, match="docx-reader"):
ask(run_)
assert len(fake.calls()) == 1
assert events(run_)[-1]["state"] == "fail" and "ms" in events(run_)[-1]
def test_agent_unplanned_role_stops(fake, run_):
with pytest.raises(core.Stop, match="код 3"):
ask(run_)
def test_parallel_agents_take_each_outcome_once(fake, run_):
fake.plan({"docx-reader": [{"structured_output": {"fakty": [n]}} for n in range(8)]})
with ThreadPoolExecutor(max_workers=4) as pool:
answers = list(pool.map(lambda _: ask(run_), range(8)))
assert sorted(answer["fakty"][0] for answer in answers) == list(range(8))
assert len(fake.calls()) == 8 and len(list((run_.dir / "logs").iterdir())) == 8
assert [e["state"] for e in events(run_) if e["who"] == "docx-reader"].count("ok") == 8
HANG = {"sleep": 5, "structured_output": {"fakty": []}}
def test_agent_timeout_is_retried_like_overload(fake, run_, monkeypatch):
"""Зависание шлюза не стоит прогона: таймаут повторяется через паузы PAUSES, как перегрузка."""
pauses = []
monkeypatch.setattr(core.time, "sleep", pauses.append)
fake.plan({"docx-reader": [HANG, OK]})
assert ask(run_, timeout=0.5) == {"fakty": []}
assert pauses == [20] and len(fake.calls()) == 2
mine = [e for e in events(run_) if e["who"] == "docx-reader"]
assert [e["state"] for e in mine] == ["start", "retry", "ok"] and "таймаут" in mine[1]["action"]
def test_agent_second_timeout_stops(fake, run_, monkeypatch):
pauses = []
monkeypatch.setattr(core.time, "sleep", pauses.append)
fake.plan({"docx-reader": [HANG, HANG]})
with pytest.raises(core.Stop, match="таймаут") as stop:
ask(run_, timeout=0.5)
assert pauses == [20] and len(fake.calls()) == 2 and "docx-reader" in str(stop.value) # T449: две попытки
assert [e["state"] for e in events(run_) if e["who"] == "docx-reader"] == ["start", "retry", "fail"]
assert "ms" in events(run_)[-1]
def test_agent_timeout_then_other_failure_stops_without_more_retries(fake, run_, monkeypatch):
monkeypatch.setattr(core.time, "sleep", lambda s: None)
fake.plan({"docx-reader": [HANG, {"code": 2, "stdout": "сбой"}]})
with pytest.raises(core.Stop, match="код 2"):
ask(run_, timeout=0.5)
assert len(fake.calls()) == 2
def test_agent_unknown_role_stops_with_role_name(fake, run_):
with pytest.raises(core.Stop, match="ghost-role"):
ask(run_, role="ghost-role")
assert fake.calls() == []
def test_models_follow_constraints():
assert {core.STRENGTH[role] for role in core.CHEAP} == {"cheap"}
assert {core.STRENGTH[role] for role in ("case-mapper", "doc-drafter", "koni-normy", "position-council/taktik")} == {"work"}
assert [role for role, strength in core.STRENGTH.items() if strength == "review"] == ["doc-reviewer"]
def test_agent_cwd_is_one_per_run_and_removed_on_finish(fake, run_):
fake.plan({"docx-reader": [OK, OK]})
ask(run_)
ask(run_)
first, second = fake.calls()
assert first["cwd"] == second["cwd"] and Path(first["cwd"]).name.startswith("themiz-next-agent-")
run_.finish("ok")
assert not Path(first["cwd"]).exists()
def test_first_event_carries_tool_sha(run_):
first = events(run_)[0]
assert first["state"] == "info" and set(first["tool_sha"]) == set(core.TOOLS)
case_paths = Path(core.TOOLS["case_paths"][-1])
assert first["tool_sha"]["case_paths"] == hashlib.sha256(case_paths.read_bytes()).hexdigest()
def test_tool_returns_done_and_logs_full_output(run_, monkeypatch):
monkeypatch.setitem(core.TOOLS, "x", [sys.executable, "-c", "import sys; print('вывод', sys.argv[1]); print('ошибка', file=sys.stderr)"])
done = core.tool(run_, "karta", "x", ["арг"])
assert (done.code, done.out.strip(), done.err.strip()) == (0, "вывод арг", "ошибка") and isinstance(done.ms, int)
assert "вывод арг" in next((run_.dir / "logs").glob("*-x.log")).read_text(encoding="utf-8")
assert [e["state"] for e in events(run_) if e["who"] == "x"] == ["start", "ok"]
def test_tool_listed_code_is_accepted(run_, monkeypatch):
monkeypatch.setitem(core.TOOLS, "x", [sys.executable, "-c", "raise SystemExit(1)"])
assert core.tool(run_, "karta", "x", [], ok=(0, 1)).code == 1
def test_tool_red_code_message_and_fail_event(run_, monkeypatch):
monkeypatch.setitem(core.TOOLS, "x", [sys.executable, "-c", "raise SystemExit(7)"])
with pytest.raises(core.Stop) as error:
core.tool(run_, "karta", "x", [])
assert str(error.value) == "x: код 7"
assert events(run_)[-1]["state"] == "fail" and "ms" in events(run_)[-1]
def test_tool_timeout_stops(run_, monkeypatch):
monkeypatch.setitem(core.TOOLS, "x", [sys.executable, "-c", "import time; time.sleep(5)"])
with pytest.raises(core.Stop, match="таймаут"):
core.tool(run_, "karta", "x", [], timeout=1)
def test_prompt_reads_role_file(tmp_path, monkeypatch):
(tmp_path / "chitatel.md").write_text("РОЛЬ: docx-reader\nФакты только из текста.\n", encoding="utf-8")
monkeypatch.setattr(core, "PROMPTS", tmp_path)
assert core.prompt("chitatel").splitlines()[0] == "РОЛЬ: docx-reader"
def test_keep_copies_the_file_into_the_run_folder(run_, tmp_path):
"""Файл дела лежит вне git: перед перезаписью его копия остается в папке прогона."""
old = tmp_path / "positions.md"
old.write_text("# позиция прошлого прогона\n", encoding="utf-8")
core.keep(old, run_)
assert (run_.dir / "positions.prev.md").read_text(encoding="utf-8") == "# позиция прошлого прогона\n"
old.write_text("новая\n", encoding="utf-8") # копия не ссылка: перезапись оригинала ее не трогает
assert (run_.dir / "positions.prev.md").read_text(encoding="utf-8") == "# позиция прошлого прогона\n"
def test_keep_without_the_file_is_silent(run_, tmp_path):
core.keep(tmp_path / "нет-такого.md", run_)
assert not list(run_.dir.glob("*.prev*"))
def test_keep_keeps_the_suffix(run_, tmp_path):
(tmp_path / "isk.docx").write_bytes(b"PK")
core.keep(tmp_path / "isk.docx", run_)
assert (run_.dir / "isk.prev.docx").read_bytes() == b"PK"
def test_context_dir():
assert core.context(Path("дело")) == Path("дело/.agent/context")
@pytest.mark.parametrize("title, expected", [
("Съемка: объем «подъезд»", "semka-obem-podezd"),
("Ёлка и ЭХО, ыть-ЙОГУРТ", "elka-i-ekho-ytyogurt"),
("Щука, жук, цапля, чайка, шарф, юла, яма", "shchuka-zhuk-tsaplya-chayka-sharf-yula-yama"),
("иск № 5 к ООО", "isk-5-k-ooo"),
])
def test_slug_rules(title, expected):
assert core.slug(title) == expected
def test_slug_without_letters_stops():
with pytest.raises(core.Stop):
core.slug(" «№» ")
def test_run_waits_out_brief_shared_lock(tmp_path):
# ревью 07.10.2026, LOW: строка состояния на миг берет LOCK_SH, новый прогон не должен видеть «уже идет»
import fcntl
import threading
case = make_case(tmp_path / "cases" / "c" / "d")
lock_path = case / ".agent" / "next" / ".lock"
lock_path.parent.mkdir(parents=True)
holder = lock_path.open("a+", encoding="utf-8")
fcntl.flock(holder.fileno(), fcntl.LOCK_SH)
threading.Timer(0.3, holder.close).start()
with core.Run(case, "FAST", "иск"):
pass
def test_agent_passes_policy_effort(fake, run_):
"""Приемка 08.10.2026: без --effort читатель скана думал 45 тыс. токенов (11 мин). Сила размышления - из политики."""
fake.plan({"docx-reader": [OK], "position-council/taktik": [OK], "koni-normy": [OK]})
ask(run_)
ask(run_, role="position-council/taktik")
ask(run_, role="koni-normy")
first, second, third = (call["argv"] for call in fake.calls())
assert first[first.index("--effort") + 1] == "low"
assert second[second.index("--effort") + 1] == "high" # решение владельца 08.10.2026
assert "--effort" not in third # роли нет ни в политике, ни в решениях: сила по умолчанию CLI
def test_effort_table_matches_model_policy():
sys.path.insert(0, str(core.ROOT / "scripts"))
import model_policy
shared = set(core.EFFORT) - core.EFFORT_VNE_POLITIKI
assert {role: core.EFFORT[role] for role in shared} == {role: model_policy.ROLE_EFFORT[role] for role in shared}
assert shared == set(model_policy.ROLE_EFFORT) & set(core.STRENGTH)
assert not core.EFFORT_VNE_POLITIKI & set(model_policy.ROLE_EFFORT)
def test_host_auth_drops_host_mark_without_token(monkeypatch):
monkeypatch.setenv("CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST", "1")
monkeypatch.setenv("CLAUDE_CODE_HOST_AUTH_ENV_VAR", "ANTHROPIC_AUTH_TOKEN")
monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False)
monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://host")
assert core.host_auth() is True
for key in ("CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST", "CLAUDE_CODE_HOST_AUTH_ENV_VAR", "ANTHROPIC_BASE_URL"):
assert key not in os.environ
def test_host_auth_keeps_env_when_token_present(monkeypatch):
monkeypatch.setenv("CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST", "1")
monkeypatch.setenv("CLAUDE_CODE_HOST_AUTH_ENV_VAR", "ANTHROPIC_AUTH_TOKEN")
monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "x")
monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://host")
assert core.host_auth() is False
assert os.environ["ANTHROPIC_BASE_URL"] == "http://host"
def test_claude_env_drops_no_proxy_behind_sandbox_proxy(monkeypatch):
monkeypatch.setenv("HTTPS_PROXY", "http://localhost:1")
monkeypatch.setenv("NO_PROXY", "localhost")
monkeypatch.setenv("no_proxy", "localhost")
env = core.claude_env()
assert "NO_PROXY" not in env and "no_proxy" not in env
assert os.environ["NO_PROXY"] == "localhost" # своя среда прогона не меняется
def test_claude_env_keeps_no_proxy_without_proxy(monkeypatch):
monkeypatch.delenv("HTTPS_PROXY", raising=False)
monkeypatch.delenv("https_proxy", raising=False)
monkeypatch.setenv("NO_PROXY", "localhost")
assert core.claude_env()["NO_PROXY"] == "localhost"