523 lines
25 KiB
Python
523 lines
25 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 _codex_stream(text='{"fakty": []}', usage=None):
|
||
usage = usage or {"input_tokens": 3, "output_tokens": 2}
|
||
return "\n".join([
|
||
json.dumps({"type": "thread.started"}),
|
||
json.dumps({"type": "turn.started"}),
|
||
json.dumps({"type": "item.completed", "item": {"type": "agent_message", "text": text}}),
|
||
json.dumps({"type": "turn.completed", "usage": usage}),
|
||
])
|
||
|
||
|
||
def test_codex_jsonl_parser_requires_completed_turn_and_collects_usage():
|
||
answer, usage = core._decode_jsonl_events(_codex_stream())
|
||
assert json.loads(answer) == {"fakty": []}
|
||
assert usage == {"input_tokens": 3, "output_tokens": 2}
|
||
with pytest.raises(ValueError):
|
||
core._decode_jsonl_events(json.dumps({"type": "thread.started"}))
|
||
|
||
|
||
@pytest.mark.parametrize("event", [
|
||
"not-json",
|
||
json.dumps({"type": "error", "message": "bad"}),
|
||
_codex_stream().replace(json.dumps({"type": "turn.completed", "usage": {"input_tokens": 3, "output_tokens": 2}}), ""),
|
||
])
|
||
def test_codex_jsonl_parser_rejects_malformed_or_failed_stream(event):
|
||
with pytest.raises(ValueError):
|
||
core._decode_jsonl_events(event)
|
||
|
||
|
||
def test_strict_schema_closes_objects_and_makes_optional_nullable():
|
||
strict = core._strict_schema({"type": "object", "properties": {
|
||
"a": {"type": "string"}, "b": {"type": "object", "properties": {"c": {"type": "number"}}}
|
||
}, "required": ["a"]})
|
||
assert strict["additionalProperties"] is False and strict["required"] == ["a", "b"]
|
||
assert strict["properties"]["b"]["type"] == ["object", "null"]
|
||
assert strict["properties"]["b"]["additionalProperties"] is False
|
||
|
||
|
||
def test_codex_agent_uses_native_output_schema_and_jsonl(fake, run_, monkeypatch):
|
||
calls = []
|
||
monkeypatch.setattr(core, "route", lambda role: ("codex", ("codex", "exec", "--json"), "m", "jsonl-events",
|
||
("-c", 'model_reasoning_effort="{effort}"')))
|
||
monkeypatch.setattr(core, "_exec", lambda argv, cwd, timeout, stdin="", env=None: (
|
||
calls.append((argv, cwd, stdin)) or __import__("subprocess").CompletedProcess(argv, 0, _codex_stream(), "")
|
||
))
|
||
assert ask(run_) == {"fakty": []}
|
||
argv, cwd, _ = calls[0]
|
||
assert "--output-schema" in argv and "--json-schema" not in argv
|
||
assert "-c" in argv and 'model_reasoning_effort="low"' in argv
|
||
schema_path = Path(argv[argv.index("--output-schema") + 1])
|
||
assert schema_path.is_file() and json.loads(schema_path.read_text())["additionalProperties"] is False
|
||
ok = [e for e in events(run_) if e["state"] == "ok"][-1]
|
||
assert ok["tokens"] == {"input_tokens": 3, "output_tokens": 2}
|
||
|
||
|
||
def test_codex_schema_paths_are_unique_for_parallel_calls(run_, monkeypatch):
|
||
paths = []
|
||
monkeypatch.setattr(core, "route", lambda role: ("codex", ("codex", "exec", "--json"), "m", "jsonl-events", ()))
|
||
def execute(argv, cwd, timeout, stdin="", env=None):
|
||
paths.append(argv[argv.index("--output-schema") + 1])
|
||
return __import__("subprocess").CompletedProcess(argv, 0, _codex_stream(), "")
|
||
monkeypatch.setattr(core, "_exec", execute)
|
||
from concurrent.futures import ThreadPoolExecutor
|
||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||
list(pool.map(lambda _: ask(run_), range(2)))
|
||
assert len(paths) == 2 and len(set(paths)) == 2
|
||
|
||
|
||
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"
|
||
|
||
|
||
# ── kimi: stream-json протокол и argv-контракт (05.11.2026) ──────────────────
|
||
|
||
def _kimi_stream(text='{"fakty": []}'):
|
||
return "\n".join([
|
||
json.dumps({"role": "meta", "type": "system.version", "version": "2.4.1"}),
|
||
json.dumps({"role": "assistant", "content": text}),
|
||
json.dumps({"role": "meta", "type": "session.resume_hint", "session_id": "s"}),
|
||
])
|
||
|
||
|
||
def test_kimi_stream_parser_takes_assistant_content():
|
||
assert json.loads(core._decode_kimi_stream(_kimi_stream())) == {"fakty": []}
|
||
two = "\n".join([json.dumps({"role": "assistant", "content": "a"}),
|
||
json.dumps({"role": "assistant", "content": "b"})])
|
||
assert core._decode_kimi_stream(two) == "a\n\nb"
|
||
|
||
|
||
def test_kimi_stream_parser_rejects_meta_only_stream():
|
||
"""kimi ретраит 429 внутри себя и выходит нулем без ответа агента (зонд 04.11.2026)."""
|
||
meta_only = "\n".join([
|
||
json.dumps({"role": "meta", "type": "system.version", "version": "2.4.1"}),
|
||
json.dumps({"role": "meta", "type": "turn.step.retrying",
|
||
"error_name": "APIProviderRateLimitError", "status_code": 429}),
|
||
json.dumps({"role": "meta", "type": "session.resume_hint", "session_id": "s"}),
|
||
])
|
||
with pytest.raises(ValueError):
|
||
core._decode_kimi_stream(meta_only)
|
||
with pytest.raises(ValueError):
|
||
core._decode_kimi_stream("not JSON")
|
||
with pytest.raises(ValueError):
|
||
core._decode_kimi_stream(json.dumps({"role": "assistant", "content": 42}))
|
||
|
||
|
||
def _kimi_route(role):
|
||
return ("kimi", ("kimi", "--skills-dir", ".", "--output-format", "stream-json", "-p"),
|
||
"kimi-code/k3-256k", "kimi-stream-json", ())
|
||
|
||
|
||
def test_kimi_agent_argv_prompt_poslednim_argumentom(run_, monkeypatch):
|
||
"""-p жадно берет следующий токен: --model до -p, промпт — значением -p (проба 04.11.2026)."""
|
||
calls = []
|
||
monkeypatch.setattr(core, "route", lambda role: _kimi_route(role))
|
||
monkeypatch.setattr(core, "_exec", lambda argv, cwd, timeout, stdin="", env=None: (
|
||
calls.append((argv, stdin, timeout)) or __import__("subprocess").CompletedProcess(argv, 0, _kimi_stream(), "")))
|
||
assert ask(run_, role="inbox-triage") == {"fakty": []}
|
||
argv, stdin, timeout = calls[0]
|
||
assert argv[0] == "kimi" and argv[-2] == "-p"
|
||
assert argv.index("--model") < argv.index("-p"), "флаг модели после -p съедается как текст промпта"
|
||
assert argv[argv.index("--model") + 1] == "kimi-code/k3-256k"
|
||
assert "Ответь одним JSON-объектом" in argv[-1] and argv[-1].endswith("\n\nт")
|
||
assert stdin == "", "stdin kimi не читает"
|
||
# inbox-triage — легкая роль (290 с): пустой ответ kimi занимает 55-260 с, пол в 780 с обязателен
|
||
assert timeout == core.HEAVY_TIMEOUT, "обычный таймаут режет живые вызовы kimi"
|
||
|
||
|
||
def test_kimi_agent_429_bez_otveta_idet_v_retry(run_, monkeypatch):
|
||
"""Код 0 без сообщения assistant при маркере перегрузки — повтор, а не стоп."""
|
||
calls = []
|
||
monkeypatch.setattr(core, "route", lambda role: _kimi_route(role))
|
||
monkeypatch.setattr(core.time, "sleep", lambda s: None)
|
||
meta_429 = json.dumps({"role": "meta", "type": "turn.step.retrying", "status_code": 429})
|
||
answers = iter([meta_429, _kimi_stream()])
|
||
|
||
def execute(argv, cwd, timeout, stdin="", env=None):
|
||
calls.append(argv)
|
||
return __import__("subprocess").CompletedProcess(argv, 0, next(answers), "")
|
||
|
||
monkeypatch.setattr(core, "_exec", execute)
|
||
assert ask(run_) == {"fakty": []}
|
||
assert len(calls) == 2
|
||
|
||
|
||
def test_kimi_agent_otkazyvayet_pereroshshemu_promptu(run_, monkeypatch):
|
||
monkeypatch.setattr(core, "route", lambda role: _kimi_route(role))
|
||
with pytest.raises(core.Stop):
|
||
core.agent(run_, "karta", "docx-reader", "РОЛЬ: x", "я" * core.MAX_ARGV_PROMPT, SCHEMA, "читает")
|
||
|
||
|
||
def test_kimi_argv_trebuet_p_v_invoke():
|
||
with pytest.raises(core.Stop):
|
||
core._kimi_argv(("kimi", "--output-format", "stream-json"), "m", "промпт")
|
||
|
||
|
||
def test_kimi_agent_slomannyy_json_idet_v_retry(run_, monkeypatch):
|
||
"""У kimi нет схемы на стороне API: модель изредка ломает JSON структурно
|
||
(07.11.2026, прогон 20261107-144743, лог 343). Ответ не JSON — один повтор,
|
||
как «мимо схемы» у claude, а не стоп прогона."""
|
||
calls = []
|
||
monkeypatch.setattr(core, "route", lambda role: _kimi_route(role))
|
||
monkeypatch.setattr(core.time, "sleep", lambda s: None)
|
||
broken = json.dumps({"role": "assistant", "content": '```json\n{"fakty": [\n {"tema": "x"},\n "tema": "y"\n```'})
|
||
answers = iter([broken, _kimi_stream()])
|
||
|
||
def execute(argv, cwd, timeout, stdin="", env=None):
|
||
calls.append(argv)
|
||
return __import__("subprocess").CompletedProcess(argv, 0, next(answers), "")
|
||
|
||
monkeypatch.setattr(core, "_exec", execute)
|
||
assert ask(run_) == {"fakty": []}
|
||
assert len(calls) == 2
|
||
assert [e["state"] for e in events(run_) if e["who"] == "docx-reader"].count("retry") == 1
|
||
|
||
|
||
def test_kimi_agent_dva_slomannyh_json_stoyat_progon(run_, monkeypatch):
|
||
monkeypatch.setattr(core, "route", lambda role: _kimi_route(role))
|
||
monkeypatch.setattr(core.time, "sleep", lambda s: None)
|
||
broken = json.dumps({"role": "assistant", "content": "не json вовсе"})
|
||
monkeypatch.setattr(core, "_exec", lambda argv, cwd, timeout, stdin="", env=None:
|
||
__import__("subprocess").CompletedProcess(argv, 0, broken, ""))
|
||
with pytest.raises(core.Stop):
|
||
ask(run_)
|
||
|
||
|
||
def test_kimi_env_stavit_usiliе_po_klassu_roli():
|
||
"""Читатель не должен думать на max: low/medium -> low, high -> high, xhigh -> max
|
||
(замер 07.11.2026: low 23 с против 55-260 с на max)."""
|
||
assert core.kimi_env("docx-reader")["KIMI_MODEL_THINKING_EFFORT"] == "low"
|
||
assert core.kimi_env("pdf-reader")["KIMI_MODEL_THINKING_EFFORT"] == "low"
|
||
assert core.kimi_env("doc-drafter")["KIMI_MODEL_THINKING_EFFORT"] == "high"
|
||
assert core.kimi_env("doc-reviewer")["KIMI_MODEL_THINKING_EFFORT"] == "max"
|
||
assert core.kimi_env("koni-normy")["KIMI_MODEL_THINKING_EFFORT"] == "max" # вне политики — безопасно
|