205 lines
8.6 KiB
Python
205 lines
8.6 KiB
Python
"""Фаза «Прием»: проверка дела, окно инбокса, перенос группы."""
|
||
import os
|
||
import sys
|
||
import time
|
||
import unicodedata
|
||
from datetime import date
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
|
||
import core # noqa: E402
|
||
import faza_priem # noqa: E402
|
||
from next_helpers import events # noqa: E402
|
||
|
||
ROLE = "inbox-triage"
|
||
FOLDER = f"postuplenie-{date.today().isoformat()}"
|
||
|
||
|
||
def put(folder: Path, name: str, age_min: int = 0, text: str = "материал\n") -> Path:
|
||
"""Кладет файл и сдвигает его mtime на age_min минут назад."""
|
||
folder.mkdir(parents=True, exist_ok=True)
|
||
path = folder / name
|
||
path.write_text(text, encoding="utf-8")
|
||
stamp = time.time() - age_min * 60
|
||
os.utime(path, (stamp, stamp))
|
||
return path
|
||
|
||
|
||
def reply(*taken: str, vague: bool = False, why: str = "") -> dict:
|
||
"""Исход заглушки: ответ Грузенберга по схеме."""
|
||
return {"structured_output": {"berem": list(taken), "neodnoznachno": vague, "prichina": why}}
|
||
|
||
|
||
@pytest.fixture
|
||
def inbox(tmp_path):
|
||
return tmp_path / "inbox"
|
||
|
||
|
||
# fake в тестах остановок: регресс, дошедший до агента, ушел бы в заглушку, а не в живой claude
|
||
def test_missing_case_md_stops(fake, run_):
|
||
(run_.case / "_case.md").unlink()
|
||
with pytest.raises(core.Stop, match="_case.md"):
|
||
faza_priem.priem(run_, {})
|
||
assert fake.calls() == []
|
||
|
||
|
||
def test_empty_intake_stops(fake, run_):
|
||
(run_.case / "00_intake" / "01.md").unlink()
|
||
with pytest.raises(core.Stop, match="00_intake"):
|
||
faza_priem.priem(run_, {})
|
||
assert fake.calls() == []
|
||
|
||
|
||
def test_missing_intake_dir_stops_and_is_not_created(fake, run_, inbox):
|
||
(run_.case / "00_intake" / "01.md").unlink()
|
||
(run_.case / "00_intake").rmdir()
|
||
put(inbox, "a.pdf")
|
||
with pytest.raises(core.Stop, match="00_intake"):
|
||
faza_priem.priem(run_, {"inbox": str(inbox)})
|
||
assert not (run_.case / "00_intake").exists() and fake.calls() == []
|
||
|
||
|
||
def test_intake_lists_sorted_files_without_hidden_and_sidecars(fake, run_):
|
||
intake = run_.case / "00_intake"
|
||
put(intake / "b", "02.md")
|
||
put(intake, ".DS_Store")
|
||
put(intake, "01.md.requisites.json")
|
||
put(intake / ".tmp", "03.md")
|
||
ctx = {"inbox": None}
|
||
faza_priem.priem(run_, ctx)
|
||
assert ctx["intake"] == [intake / "01.md", intake / "b" / "02.md"]
|
||
assert fake.calls() == []
|
||
|
||
|
||
def test_kandidaty_window(inbox):
|
||
put(inbox, ".hidden") # самый новый, но скрытый: окно от него не считается
|
||
new = put(inbox, "new.pdf", 50)
|
||
inside = put(inbox, "inside.pdf", 100)
|
||
put(inbox, "old.pdf", 200) # двухчасовой давности относительно нового
|
||
(inbox / "unsorted").mkdir()
|
||
assert faza_priem.kandidaty(inbox) == sorted([new, inside])
|
||
assert faza_priem.kandidaty(inbox, 15) == [new]
|
||
|
||
|
||
def test_kandidaty_empty_and_missing_inbox(tmp_path):
|
||
(tmp_path / "empty").mkdir()
|
||
assert faza_priem.kandidaty(tmp_path / "empty") == []
|
||
with pytest.raises(core.Stop):
|
||
faza_priem.kandidaty(tmp_path / "net")
|
||
|
||
|
||
def test_empty_inbox_calls_no_agent(fake, run_, inbox):
|
||
inbox.mkdir()
|
||
assert faza_priem.perenos(run_, inbox) == []
|
||
assert fake.calls() == []
|
||
|
||
|
||
def test_ambiguous_group_moves_nothing(fake, run_, inbox):
|
||
put(inbox, "a.pdf")
|
||
put(inbox, "b.pdf")
|
||
before = sorted(inbox.iterdir())
|
||
fake.plan({ROLE: [reply("a.pdf", vague=True, why="две темы")]})
|
||
with pytest.raises(core.Stop, match="неоднозначна") as info:
|
||
faza_priem.perenos(run_, inbox)
|
||
assert "две темы" not in str(info.value) # причина модели не идет в state/табло
|
||
assert sorted(inbox.iterdir()) == before
|
||
assert not (run_.case / "00_intake" / FOLDER).exists()
|
||
|
||
|
||
def test_group_moved_others_untouched(fake, run_, inbox):
|
||
(run_.case / "_case.md").write_text("".join(f"строка {n}\n" for n in range(1, 51)), encoding="utf-8")
|
||
put(inbox, "a.pdf", text="КАНАРЕЙКА-ПД\n")
|
||
put(inbox, "b.pdf")
|
||
stranger = put(inbox, "c.pdf")
|
||
fake.plan({ROLE: [reply("a.pdf", "b.pdf")]})
|
||
ctx = {"inbox": str(inbox)}
|
||
faza_priem.priem(run_, ctx)
|
||
intake = run_.case / "00_intake"
|
||
folder = intake / FOLDER
|
||
assert sorted(p.name for p in folder.iterdir()) == ["a.pdf", "b.pdf"]
|
||
assert stranger.is_file() and not (inbox / "a.pdf").exists() and not (inbox / "b.pdf").exists()
|
||
assert ctx["intake"] == sorted([intake / "01.md", folder / "a.pdf", folder / "b.pdf"])
|
||
stdin = fake.calls()[0]["stdin"]
|
||
assert "строка 40" in stdin and "строка 41" not in stdin
|
||
assert all(name in stdin for name in ("a.pdf", "b.pdf", "c.pdf")) and "КАНАРЕЙКА-ПД" not in stdin
|
||
assert any("перенесено 2, оставлено 1" in e["action"] for e in events(run_))
|
||
|
||
|
||
def test_perenos_returns_new_paths(fake, run_, inbox):
|
||
put(inbox, "b.pdf")
|
||
put(inbox, "a.pdf")
|
||
fake.plan({ROLE: [reply("b.pdf", "a.pdf")]})
|
||
folder = run_.case / "00_intake" / FOLDER
|
||
assert faza_priem.perenos(run_, inbox) == [folder / "a.pdf", folder / "b.pdf"]
|
||
|
||
|
||
@pytest.mark.parametrize("where", [".", FOLDER])
|
||
def test_name_collision_stops(fake, run_, inbox, where):
|
||
old = put(run_.case / "00_intake" / where, "b.pdf", text="старый\n")
|
||
new = put(inbox, "b.pdf", text="новый\n")
|
||
free = put(inbox, "a.pdf") # первый по порядку и свободный: проверка по одному файлу успела бы его перенести
|
||
fake.plan({ROLE: [reply("a.pdf", "b.pdf")]})
|
||
with pytest.raises(core.Stop, match="b.pdf"):
|
||
faza_priem.perenos(run_, inbox)
|
||
assert old.read_text(encoding="utf-8") == "старый\n" and new.read_text(encoding="utf-8") == "новый\n"
|
||
assert free.is_file() and not (run_.case / "00_intake" / FOLDER / "a.pdf").exists()
|
||
|
||
|
||
def test_name_taken_by_folder_stops(fake, run_, inbox):
|
||
(run_.case / "00_intake" / FOLDER / "a.pdf").mkdir(parents=True)
|
||
new = put(inbox, "a.pdf")
|
||
fake.plan({ROLE: [reply("a.pdf")]})
|
||
with pytest.raises(core.Stop, match="a.pdf"):
|
||
faza_priem.perenos(run_, inbox)
|
||
assert new.is_file() and not list((run_.case / "00_intake" / FOLDER / "a.pdf").iterdir())
|
||
|
||
|
||
def test_names_outside_candidates_are_ignored(fake, run_, inbox):
|
||
put(inbox, "a.pdf")
|
||
outside = put(inbox.parent, "outside.md")
|
||
fake.plan({ROLE: [reply("a.pdf", "../outside.md", "ghost.pdf", "a.pdf")]})
|
||
moved = faza_priem.perenos(run_, inbox)
|
||
assert [p.name for p in moved] == ["a.pdf"] and outside.is_file()
|
||
|
||
|
||
def test_names_match_despite_normalization_and_narrow_space(fake, run_, inbox):
|
||
on_disk = unicodedata.normalize("NFD", "Выписка за май 10.15 AM.pdf")
|
||
put(inbox, on_disk)
|
||
from_model = unicodedata.normalize("NFC", on_disk).replace(" ", " ")
|
||
fake.plan({ROLE: [reply(from_model)]})
|
||
(moved,) = faza_priem.perenos(run_, inbox)
|
||
assert moved.is_file() and not list(inbox.iterdir())
|
||
|
||
|
||
def test_empty_group_moves_nothing_and_stops(fake, run_, inbox):
|
||
"""T442: инбокс задан, перенесено 0 файлов - стоп, а не тихое продолжение на старых материалах."""
|
||
put(inbox, "a.pdf")
|
||
fake.plan({ROLE: [reply(why="другое дело")]})
|
||
with pytest.raises(core.Stop, match="перенесено 0"):
|
||
faza_priem.priem(run_, {"inbox": str(inbox)})
|
||
assert (inbox / "a.pdf").is_file() and not (run_.case / "00_intake" / FOLDER).exists()
|
||
|
||
|
||
def test_berem_not_a_list_stops(fake, run_, inbox):
|
||
put(inbox, "a.pdf")
|
||
fake.plan({ROLE: [{"structured_output": {"berem": "a.pdf", "neodnoznachno": False, "prichina": ""}}]})
|
||
with pytest.raises(core.Stop, match="berem"):
|
||
faza_priem.perenos(run_, inbox)
|
||
assert (inbox / "a.pdf").is_file()
|
||
|
||
|
||
def test_priem_writes_brief_track_for_guard(fake, run_):
|
||
"""Класс themiz-runpy-vs-guard-markers: прием кладет brief.md с треком; бриф владельца не переписывается."""
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))
|
||
import case_paths
|
||
put(run_.case / "00_intake", "a.md")
|
||
faza_priem.priem(run_, {})
|
||
brief = case_paths.brief(run_.case)
|
||
assert f"Трек: {run_.track}" in brief.read_text(encoding="utf-8")
|
||
brief.write_text("бриф владельца\n", encoding="utf-8")
|
||
faza_priem.priem(run_, {})
|
||
assert brief.read_text(encoding="utf-8") == "бриф владельца\n"
|