release: Евномия, новая версия, линейка юристов

This commit is contained in:
public-repo-gate
2026-10-19 17:43:00 +03:00
parent 067c6c2414
commit bf1edc117c
239 changed files with 245397 additions and 36598 deletions
+347
View File
@@ -0,0 +1,347 @@
"""Цена иска и госпошлина: стоимости объектов называет позиция дословно из фактов, считают код и прибор gosposhlina."""
import json
import sys
import textwrap
from decimal import Decimal
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import core # noqa: E402
import faza_dokument # noqa: E402
from next_helpers import events # noqa: E402
FLAT, CAR, DACHA = "5 200 000 руб.", "1 234 567,89 руб.", "6 000 000 руб."
FAKTY = [
{"tema": "срок брака", "znachenie": "с 10.06.2012 по 10.02.2026", "fail": "01.md", "str": 1, "status": "ок"},
{"tema": "стоимость квартиры", "znachenie": f"кадастровая стоимость {FLAT} (выписка ЕГРН)", "fail": "02.pdf", "str": 2, "status": "ок"},
{"tema": "стоимость автомобиля", "znachenie": f"оценка {CAR}", "fail": "02.pdf", "str": 3, "status": "ок"},
{"tema": "стоимость участка", "znachenie": "9 999 999 руб.", "fail": "02.pdf", "str": 4, "status": "ОСПОРЕНО"},
{"tema": "стоимость дачи", "znachenie": f"рыночная оценка {DACHA}", "fail": "02.pdf", "str": 5, "status": "ок"},
]
# как у настоящего gosposhlina.py: рубли в «К УПЛАТЕ», разряды пробелом; аргументы вызова пишет в журнал
STUB = textwrap.dedent(
"""
import json, os, sys
with open(os.environ["STUB_LOG"], "a", encoding="utf-8") as log:
log.write(json.dumps(sys.argv[1:], ensure_ascii=False) + "\\n")
print("Источник: ст. 333.19 НК РФ, корпус от 04.08.2026 (СОЮ, мировые судьи, ВС РФ)")
print("Цена иска: " + sys.argv[sys.argv.index("--cena") + 1] + " руб.")
print("")
print("К УПЛАТЕ: 44 200 руб.")
"""
)
def row(obekt, stoimost="", trebovanie="Признать право на долю", dolya="1"):
return {"obekt": obekt, "trebovanie": trebovanie, "osnovanie": "п. 1 ст. 39 СК РФ", "stoimost": stoimost, "dolya": dolya}
def position(*rows):
return {"trebovaniya": list(rows), "dovody": [{"tezis": "Имущество нажито в браке", "istochnik": "п. 1 ст. 34 СК РФ"}],
"riski": ["Довод о личных деньгах"]}
@pytest.fixture
def gosposhlina(monkeypatch, tmp_path):
"""Заглушка прибора; возвращает функцию: аргументы всех вызовов."""
log = tmp_path / "gosposhlina-calls.jsonl"
script = tmp_path / "stub_gosposhlina.py"
script.write_text(STUB, encoding="utf-8")
monkeypatch.setenv("STUB_LOG", str(log))
monkeypatch.setitem(core.TOOLS, "gosposhlina", [sys.executable, str(script)])
return lambda: [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.is_file() else []
def ctx_of(*rows, fakty=FAKTY):
return {"fakty": fakty, "pozitsiya": position(*rows)}
def full_ctx():
"""Вход фазы «Позиция»: вопросы, факты и акты карты и практики."""
return {"voprosy": [{"id": "В1", "vopros": "Нажита ли квартира в браке?", "fakty": [0]}], "fakty": FAKTY, "akty": []}
# --- разбор суммы ---
@pytest.mark.parametrize("text, expected", [
("1 234 567,89 руб.", Decimal("1234567.89")),
("5200000 рублей", Decimal("5200000")),
("5 200 000 руб.", Decimal("5200000")),
("5 200 000 ₽", Decimal("5200000")),
("5 200 000 (пять миллионов двести тысяч) рублей", Decimal("5200000")),
("5 200 000 руб. (5 200 000 рублей)", Decimal("5200000")), # то же число дважды
("кадастровая стоимость 5 200 000 руб., дата 10.06.2012", Decimal("5200000")),
("100 000.5 руб", Decimal("100000.5")),
("5,2 млн руб.", None), # множитель не угадываем
("5 200 тыс. руб.", None),
("от 3 000 000 до 4 000 000 руб.", None), # два разных числа
("5 200 000", None), # без рублей
("0 руб.", None),
("", None),
])
def test_summa_parses_only_unambiguous_rubles(text, expected):
assert faza_dokument._summa(text) == expected
def test_rub_formats_like_gosposhlina():
assert faza_dokument._rub(Decimal("1234567.89")) == "1 234 567,89"
assert faza_dokument._rub(Decimal("5200000")) == "5 200 000"
assert faza_dokument._rub(44200) == "44 200"
# --- расчет ---
def test_cena_sums_objects_and_asks_the_tool(run_, gosposhlina):
ctx = ctx_of(row("квартира", FLAT), row("автомобиль", CAR))
faza_dokument._cena(run_, ctx)
assert ctx["cena"] == Decimal("6434567.89") and ctx["poshlina"] == 44200 and ctx["nedostaet"] == []
assert gosposhlina() == [["--cena", "6434567.89", "--status", "fiz", "--sud", "soyu"]]
assert faza_dokument.cena_text(ctx) == "Цена иска: 6 434 567,89 руб.; госпошлина: 44 200 руб. (подп. 1 п. 1 ст. 333.19 НК РФ; рассчитана прибором; в документе - сумма и эта ссылка, шкалу ставок не пересказывать)"
def test_cena_counts_an_object_once_across_its_requirements(run_, gosposhlina):
ctx = ctx_of(row("квартира", FLAT), row("квартира", FLAT, "Взыскать компенсацию"), row("квартира", ""))
faza_dokument._cena(run_, ctx)
assert ctx["cena"] == Decimal("5200000") and gosposhlina() == [["--cena", "5200000", "--status", "fiz", "--sud", "soyu"]]
@pytest.mark.parametrize("rows", [
[row("квартира", FLAT), row("автомобиль", "")], # у объекта нет стоимости
[row("квартира", FLAT), row("автомобиль")],
[row("квартира", FLAT), row("автомобиль", "1 111 111 руб.")], # такого числа в фактах нет
[row("квартира", FLAT), row("участок", "9 999 999 руб.")], # число стоит в факте со статусом ОСПОРЕНО
[row("квартира", FLAT), row("автомобиль", "1,2 млн руб.")], # множитель
[row("квартира", FLAT), row("квартира", "1 234 567,89 руб.")], # у одного объекта две разные стоимости
])
def test_cena_not_counted_without_a_grounded_cost(run_, gosposhlina, rows):
ctx = ctx_of(*rows)
faza_dokument._cena(run_, ctx)
assert "cena" not in ctx and "poshlina" not in ctx and gosposhlina() == []
assert len(ctx["nedostaet"]) == 1 and ctx["nedostaet"][0].startswith("стоимость объекта ") # доля у этих строк названа
assert faza_dokument.cena_text(ctx) == ""
assert [e["action"] for e in events(run_) if e["state"] == "info" and "цена иска не считается" in e["action"]]
def test_cena_names_every_object_without_cost(run_, gosposhlina):
ctx = ctx_of(row("квартира", FLAT), row("автомобиль"), row("дача и\nучасток"))
faza_dokument._cena(run_, ctx)
assert ctx["nedostaet"] == ["стоимость объекта автомобиль", "стоимость объекта дача и участок"]
# --- R39: цена иска - стоимость заявленного, а не всего объекта ---
def test_cena_is_cost_times_claimed_share(run_, gosposhlina):
ctx = ctx_of(row("дача", DACHA, dolya="1/2"))
faza_dokument._cena(run_, ctx)
assert ctx["cena"] == Decimal("3000000") and ctx["poshlina"] == 44200 and ctx["nedostaet"] == []
assert gosposhlina() == [["--cena", "3000000", "--status", "fiz", "--sud", "soyu"]]
assert faza_dokument.cena_text(ctx).startswith("Цена иска: 3 000 000 руб.; госпошлина: 44 200 руб.")
def test_cena_whole_object_share_one(run_, gosposhlina):
ctx = ctx_of(row("дача", DACHA, dolya="1"))
faza_dokument._cena(run_, ctx)
assert ctx["cena"] == Decimal("6000000") and gosposhlina() == [["--cena", "6000000", "--status", "fiz", "--sud", "soyu"]]
def test_cena_sums_shares_of_different_objects(run_, gosposhlina):
ctx = ctx_of(row("квартира", FLAT, dolya="1/2"), row("автомобиль", CAR, dolya="1"))
faza_dokument._cena(run_, ctx)
assert ctx["cena"] == Decimal("3834567.89") and gosposhlina() == [["--cena", "3834567.89", "--status", "fiz", "--sud", "soyu"]]
@pytest.mark.parametrize("cost, share, expected", [
(FLAT, "1/3", "1733333.33"), # 1 733 333,333...: вниз
(CAR, "1/2", "617283.95"), # 617 283,945: половина копейки округляется вверх, не к четному
(FLAT, "03/06", "2600000"), # дробь с ведущими нулями и сокращаемая
(FLAT, " 1 / 4 ", "1300000"), # пробелы вокруг черты
])
def test_cena_rounds_to_kopecks_once_at_the_end(run_, gosposhlina, cost, share, expected):
ctx = ctx_of(row("объект", cost, dolya=share))
faza_dokument._cena(run_, ctx)
assert ctx["cena"] == Decimal(expected) and gosposhlina() == [["--cena", expected, "--status", "fiz", "--sud", "soyu"]]
def test_cena_rounds_the_sum_not_each_part(run_, gosposhlina):
"""Две трети копейки по двум объектам: 1/3 от 5 200 000 и 1/3 от 5 200 000 вместе 3 466 666,666...: округляется итог."""
ctx = ctx_of(row("квартира", FLAT, dolya="1/3"), row("дом", FLAT, dolya="1/3"))
faza_dokument._cena(run_, ctx)
assert ctx["cena"] == Decimal("3466666.67") # по частям вышло бы 1733333,33 + 1733333,33 = 3466666,66
@pytest.mark.parametrize("share", [
"", "много", "1/2 доли", "0", "0/5", "3/2", "2", "1/0", "0,5", "0.5", "½", "-1/2", "1e999999999",
pytest.param("1/" + "9" * 5000, id="huge-denominator"),
])
def test_cena_unrecognized_share_is_a_named_gap(run_, gosposhlina, share):
"""Мусор, нуль, больше единицы, десятичная запись и деление на нуль: доля не распознана, цена и пошлина не считаются."""
ctx = ctx_of(row("квартира", FLAT, dolya=share), row("автомобиль", CAR))
faza_dokument._cena(run_, ctx)
assert ctx["nedostaet"] == ["доля объекта квартира"] and "cena" not in ctx and "poshlina" not in ctx
assert gosposhlina() == [] and faza_dokument.cena_text(ctx) == ""
assert [e for e in events(run_) if e["state"] == "info" and "цена иска не считается" in e["action"]]
def test_cena_names_cost_and_share_gaps_per_object(run_, gosposhlina):
ctx = ctx_of(row("квартира", FLAT, dolya="1/2"), row("автомобиль", "", dolya="?"), row("дача", DACHA, dolya=""))
faza_dokument._cena(run_, ctx)
assert ctx["nedostaet"] == ["стоимость объекта автомобиль", "доля объекта автомобиль", "доля объекта дача"]
def test_cena_one_object_two_requirements_same_share_counted_once(run_, gosposhlina):
ctx = ctx_of(row("квартира", FLAT, dolya="1/2"), row("квартира", FLAT, "Выделить в натуре", dolya="1/2"))
faza_dokument._cena(run_, ctx)
assert ctx["cena"] == Decimal("2600000")
def test_cena_one_object_different_shares_is_a_gap(run_, gosposhlina):
"""Доли одного объекта в разных требованиях код не складывает: пересекающиеся от непересекающихся он не отличит."""
ctx = ctx_of(row("квартира", FLAT, dolya="1/2"), row("квартира", FLAT, "Взыскать компенсацию", dolya="1/4"))
faza_dokument._cena(run_, ctx)
assert ctx["nedostaet"] == ["доля объекта квартира"] and gosposhlina() == []
def test_cena_requirement_without_dolya_key_is_a_gap(run_, gosposhlina):
"""Ответ старой схемы без поля dolya: доли нет, расчета нет."""
item = row("квартира", FLAT)
del item["dolya"]
ctx = ctx_of(item)
faza_dokument._cena(run_, ctx)
assert ctx["nedostaet"] == ["доля объекта квартира"] and gosposhlina() == []
def test_cena_tool_failure_stops(run_, monkeypatch):
monkeypatch.setitem(core.TOOLS, "gosposhlina", [sys.executable, "-c", "raise SystemExit(1)"])
with pytest.raises(core.Stop, match="gosposhlina"):
faza_dokument._cena(run_, ctx_of(row("квартира", FLAT)))
def test_cena_tool_without_total_stops(run_, monkeypatch):
monkeypatch.setitem(core.TOOLS, "gosposhlina", [sys.executable, "-c", "print('нет итога')"])
with pytest.raises(core.Stop, match="К УПЛАТЕ"):
faza_dokument._cena(run_, ctx_of(row("квартира", FLAT)))
GOSPOSHLINA_CORPUS = core.ROOT / "knowledge" / "kodeksy" / "nk-rf-gosposhlina.md"
@pytest.mark.skipif(not GOSPOSHLINA_CORPUS.is_file(), reason="корпус НК лежит вне git; на этой машине его нет")
def test_real_gosposhlina_cli_contract(run_):
"""Флаги и строка «К УПЛАТЕ» настоящего прибора: 100 000 руб. дают 4 000, копейки принимаются."""
assert faza_dokument._poshlina(run_, Decimal("100000")) == 4000
assert faza_dokument._poshlina(run_, Decimal("1234567.89")) == 27346
# --- фаза «Позиция» ---
def test_position_prompts_and_schema_ask_for_cost(fake, run_, gosposhlina):
for name in ("position", "areopag"):
system = core.prompt(name)
assert "`stoimost`" in system and "дословно" in system
assert "`dolya`" in system and "не вычисляй" in system # доля переписывается из требования, считает код
fake.plan({"position-council/taktik": [{"structured_output": position(row("квартира", FLAT))}]})
faza_dokument.pozitsiya(run_, full_ctx())
call = fake.calls()[0]
schema = json.loads(call["argv"][call["argv"].index("--json-schema") + 1])
item = schema["properties"]["trebovaniya"]["items"]
assert "stoimost" in item["required"] and item["properties"]["stoimost"] == {"type": "string"}
assert "dolya" in item["required"] and item["properties"]["dolya"] == {"type": "string"}
def test_position_phase_computes_and_records_numbers(fake, run_, gosposhlina):
ctx = full_ctx()
fake.plan({"position-council/taktik": [{"structured_output": position(row("квартира", FLAT), row("автомобиль", CAR))}]})
faza_dokument.pozitsiya(run_, ctx)
line = "Цена иска: 6 434 567,89 руб.; госпошлина: 44 200 руб. (подп. 1 п. 1 ст. 333.19 НК РФ; рассчитана прибором; в документе - сумма и эта ссылка, шкалу ставок не пересказывать)"
assert ctx["cena"] == Decimal("6434567.89") and ctx["poshlina"] == 44200 and ctx["nedostaet"] == []
md = (core.context(run_.case) / "positions.md").read_text(encoding="utf-8")
assert f"## Цена иска и госпошлина\n\n{line}\n" in md # числа в источнике: quality_gate принимает их в черновике
assert faza_dokument.FAST_MARKER in md.splitlines()
def test_position_phase_prices_the_claimed_share(fake, run_, gosposhlina):
"""Фаза в сборе: в требовании доля 1/2 от 6 000 000 дает цену иска 3 000 000, и это число идет в positions.md."""
ctx = full_ctx()
fake.plan({"position-council/taktik": [{"structured_output": position(row("дача", DACHA, dolya="1/2"))}]})
faza_dokument.pozitsiya(run_, ctx)
assert ctx["cena"] == Decimal("3000000") and ctx["nedostaet"] == []
md = (core.context(run_.case) / "positions.md").read_text(encoding="utf-8")
assert "Цена иска: 3 000 000 руб.; госпошлина: 44 200 руб. (подп. 1 п. 1 ст. 333.19 НК РФ; рассчитана прибором; в документе - сумма и эта ссылка, шкалу ставок не пересказывать)" in md
def test_position_phase_with_unclear_share_names_the_gap(fake, run_, gosposhlina):
ctx = full_ctx()
fake.plan({"position-council/taktik": [{"structured_output": position(row("дача", DACHA, dolya=""))}]})
faza_dokument.pozitsiya(run_, ctx)
assert ctx["nedostaet"] == ["доля объекта дача"] and "cena" not in ctx and gosposhlina() == []
assert "Цена иска" not in (core.context(run_.case) / "positions.md").read_text(encoding="utf-8")
def test_position_phase_without_cost_names_the_gap(fake, run_, gosposhlina):
ctx = full_ctx()
fake.plan({"position-council/taktik": [{"structured_output": position(row("квартира", FLAT), row("автомобиль"))}]})
faza_dokument.pozitsiya(run_, ctx)
assert ctx["nedostaet"] == ["стоимость объекта автомобиль"] and "cena" not in ctx and gosposhlina() == []
assert "Цена иска" not in (core.context(run_.case) / "positions.md").read_text(encoding="utf-8")
def test_event_log_carries_no_amounts(fake, run_, gosposhlina):
fake.plan({"position-council/taktik": [{"structured_output": position(row("квартира", FLAT))}]})
faza_dokument.pozitsiya(run_, full_ctx())
assert "5 200 000" not in (run_.dir / "events.jsonl").read_text(encoding="utf-8")
# --- база цены: кадастровая, без нее договорная (решение владельца 06.10.2026) ---
DOGOVOR = "4 100 000 руб."
DVE_BAZY = [*FAKTY[:2], {"tema": "цена квартиры по договору", "znachenie": f"цена {DOGOVOR}", "fail": "03.pdf", "str": 1,
"status": "ок"}]
def test_object_named_twice_with_remarks_is_one_object(run_, gosposhlina):
"""Пилот: позиция назвала квартиру «(кадастровый номер …)» и «(запись о праве …)» - это один объект, а не два."""
ctx = ctx_of(row("квартира (кадастровый номер 1)", FLAT, dolya="1/2"), row("квартира (запись ЕГРН)", FLAT, dolya="1/2"))
faza_dokument._cena(run_, ctx)
assert ctx["cena"] == Decimal("2600000") and ctx["nedostaet"] == []
def test_position_gets_cadastral_rule_and_prices_by_it(fake, run_, gosposhlina):
"""Решение владельца 06.10.2026: базу цены не спрашивать, кадастровая стоимость, без нее договорная."""
ctx = {**full_ctx(), "fakty": DVE_BAZY}
fake.plan({"position-council/taktik": [{"structured_output": position(row("квартира", FLAT, dolya="1/2"))}]})
faza_dokument.pozitsiya(run_, ctx)
assert ctx["cena"] == Decimal("2600000") and ctx["nedostaet"] == []
assert faza_dokument.BAZA_RULE in fake.calls()[0]["stdin"]
def test_without_cadastral_contract_price_counts(fake, run_, gosposhlina):
fakty = [FAKTY[0], {**FAKTY[1], "znachenie": "рыночная оценка 5 200 000 руб."}, DVE_BAZY[2]]
ctx = {**full_ctx(), "fakty": fakty}
fake.plan({"position-council/taktik": [{"structured_output": position(row("квартира", DOGOVOR, dolya="1/2"))}]})
faza_dokument.pozitsiya(run_, ctx)
assert ctx["cena"] == Decimal("2050000") and ctx["nedostaet"] == []
def test_one_cost_fact_prices_it(fake, run_, gosposhlina):
ctx = {**full_ctx(), "fakty": FAKTY[:2]}
fake.plan({"position-council/taktik": [{"structured_output": position(row("квартира", FLAT))}]})
faza_dokument.pozitsiya(run_, ctx)
assert ctx["cena"] == Decimal("5200000")
@pytest.mark.parametrize("doc, counted", [
("исковое заявление о разделе имущества", True),
("встречное исковое заявление", True),
("ходатайство о передаче дела по подсудности", False),
("возражения на иск", False),
("отзыв на исковое заявление", False),
])
def test_cena_only_for_claims(run_, gosposhlina, doc, counted):
"""Первое реальное дело 07.10.2026: цена иска и пошлина попали в ходатайство о подсудности, Кони: «к делу не относится»."""
run_.doc = doc
ctx = ctx_of(row("квартира", FLAT))
faza_dokument._cena(run_, ctx)
assert ("poshlina" in ctx) is counted and ctx["nedostaet"] == []