Files
smeta-web/tests/test_norm_registry.py
T
anorandClaude Opus 4.8 e49cf892cf feat(norms): ретро-сметы «на дату X» — темпоральное ядро реестра (Фаза 1 плана Fable)
Поправка к Задаче А: смету иногда считают задним числом — по нормативам, действовавшим на ту
дату (смета на 2019 → ГСН 81-05-02-2007, на 2026 → 325/пр). Реестр знал только «на сегодня».

- Записи norm_registry получили topic + полуинтервал действия [valid_from, valid_to) (null =
  издавна/поныне). Обратная совместимость: миграция-на-чтении выводит интервал из старых дат;
  status («на сегодня») сохранён — prompt_block() без даты байт-идентичен прежнему.
- API as-of: doc_status_on(id,date) [active|repealed|not_yet|unknown], active_on(date),
  pick(topic,date), as_of_block(date). Дата вне подтверждённых интервалов → unknown → честный
  отказ (money-safe: не подставляем норму не той эпохи наугад).
- 4 теста: граница 07↔08.08.2021, pick по эпохам (winter/temp_buildings 2019 vs 2026),
  as_of_block, prompt_block() без даты не изменился.

Осталось Ф2 (агент извлекает дату + tool norms_as_of), Ф3 (движок: % по периодам), Ф4 (сверка
с кварталом цен). Ф0: подтвердить интервалы прочих ключевых норм через human-gate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 17:26:30 +10:00

127 lines
6.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Реестр статусов нормативных документов: засев, prompt_block, human-gate, fail-soft."""
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import ext_state as es # noqa: E402
import norm_registry as nr # noqa: E402
@pytest.fixture(autouse=True)
def _tmp(monkeypatch, tmp_path):
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path))
return tmp_path
def test_seed_on_first_load(_tmp):
reg = nr.load()
assert "gsn-81-05-02-2007" in reg["docs"] and reg["docs"]["gsn-81-05-02-2007"]["status"] == "repealed"
assert (_tmp / "norm_registry.json").exists() # засев записан на диск
def test_prompt_block_marks_repealed_and_active(_tmp):
b = nr.prompt_block()
# отменённые ГСН — с явной пометкой, действующие методики — как действующие
assert "ГСН 81-05-02-2007" in b and "ОТМЕНЁН" in b
assert "325/пр" in b and "332/пр" in b
assert "ФРСН" in b # правило про неизвестные документы
def test_failsoft_corrupt_file_keeps_base_facts(_tmp):
(_tmp / "norm_registry.json").write_text("{битый", encoding="utf-8")
b = nr.prompt_block() # не падает
assert "ГСН 81-05-02-2007" in b and "ОТМЕНЁН" in b # базовые факты из SEED всё равно есть
def test_pending_candidate_not_in_prompt_until_confirmed(_tmp):
"""Money-gate: авто-кандидат НЕ влияет на промпт до подтверждения оператором."""
cand = {"doc_id": "gsn-99-test", "basis": "999/пр", "title": "ГСН-99 тестовый",
"status": "repealed"}
nr.propose(cand)
assert "ГСН-99" not in nr.prompt_block() # pending → в промпт НЕ идёт
assert any(c["doc_id"] == "gsn-99-test" for c in nr.pending())
# оператор подтвердил → теперь в реестре и в промпте
assert nr.confirm("999/пр", "gsn-99-test", "approve", "yuri") is True
assert "ГСН-99" in nr.prompt_block()
assert not nr.pending() # из очереди убран
def test_reject_candidate_not_applied(_tmp):
nr.propose({"doc_id": "x-reject", "basis": "111/пр", "title": "X отклонён", "status": "repealed"})
assert nr.confirm("111/пр", "x-reject", "reject", "yuri") is True
assert "x-reject" not in nr.load()["docs"] and "X отклонён" not in nr.prompt_block()
def test_propose_dedup(_tmp):
c = {"doc_id": "d1", "basis": "222/пр", "title": "Дубль", "status": "repealed"}
nr.propose(c)
nr.propose(c)
assert sum(1 for x in nr.pending() if x["doc_id"] == "d1") == 1 # дедуп по (basis, doc_id)
def test_writer_does_not_clobber_corrupt_file(_tmp):
"""Д1: битый файл (мог хранить подтверждённые записи) — propose/confirm НЕ затирают его SEED-ом,
а падают (fail-loud), чтобы оператор восстановил вручную."""
(_tmp / "norm_registry.json").write_text("{битый json", encoding="utf-8")
with pytest.raises(RuntimeError):
nr.propose({"doc_id": "x", "basis": "1/пр", "title": "t", "status": "repealed"})
# файл не перезаписан
assert (_tmp / "norm_registry.json").read_text(encoding="utf-8").startswith("{битый")
def test_confirm_rejects_bad_decision(_tmp):
"""Д2: опечатка в decision не должна тихо стать reject."""
nr.propose({"doc_id": "y", "basis": "2/пр", "title": "t", "status": "repealed"})
with pytest.raises(ValueError):
nr.confirm("2/пр", "y", "aprove", "yuri") # опечатка → ошибка, не тихий reject
assert any(c["doc_id"] == "y" for c in nr.pending()) # кандидат на месте
def test_stub_when_registry_empty_or_broken(_tmp):
"""Д3: пустой/битый реестр → ограничительная заглушка (НЕ пусто), иначе агент вернётся к весам."""
(_tmp / "norm_registry.json").write_text('{"docs": {}, "pending": []}', encoding="utf-8")
s = nr.prompt_block_or_stub()
assert s and "НЕ утверждай" in s and "ФРСН" in s # заглушка, не пустая строка
def test_asof_boundary_winter(_tmp):
"""Граница действия зимнего удорожания: 07.08.2021 — ещё ГСН-2007, 08.08.2021 — уже 325/пр."""
assert nr.doc_status_on("gsn-81-05-02-2007", "2021-08-07") == "active"
assert nr.doc_status_on("gsn-81-05-02-2007", "2021-08-08") == "repealed"
assert nr.doc_status_on("prikaz-325-pr", "2021-08-07") == "not_yet"
assert nr.doc_status_on("prikaz-325-pr", "2021-08-08") == "active"
def test_pick_by_epoch(_tmp):
"""Ретро-выбор документа по теме и дате — та эпоха, что действовала."""
assert nr.pick("winter", "2019-06-01") == "gsn-81-05-02-2007"
assert nr.pick("winter", "2026-01-01") == "prikaz-325-pr"
assert nr.pick("temp_buildings", "2019-06-01") == "gsn-81-05-01-2001"
assert nr.pick("temp_buildings", "2026-01-01") == "prikaz-332-pr"
def test_as_of_block_epochs(_tmp):
b2019 = nr.as_of_block("2019-06-01")
assert "ГСН 81-05-02-2007" in b2019 and "ГСН 81-05-01-2001" in b2019
assert "325/пр" not in b2019 # ещё не действовал
b2026 = nr.as_of_block("2026-01-01")
assert "325/пр" in b2026 and "332/пр" in b2026 and "ГСН 81-05-02-2007" not in b2026
def test_prompt_block_default_unchanged_by_temporal(_tmp):
"""Обратная совместимость: prompt_block() без даты по-прежнему даёт статус «на сегодня»."""
b = nr.prompt_block()
assert "325/пр" in b and "ОТМЕНЁН" in b and "ГСН 81-05-02-2007" in b
def test_prompt_block_survives_nondict_successor(_tmp):
"""Запись-не-dict в successor не роняет блок (load валидирует только верхний уровень)."""
import json as _j
(_tmp / "norm_registry.json").write_text(_j.dumps({
"docs": {"a": {"title": "A", "status": "repealed", "successor": "b"}, "b": "не-dict"},
"pending": []}, ensure_ascii=False), encoding="utf-8")
b = nr.prompt_block() # не падает
assert "A" in b and "ОТМЕНЁН" in b