Files
themiz/themiz-next/progress.py
T

89 lines
4.3 KiB
Python

"""Ход Фемиды Next для строки состояния: задачи плана, живые прогоны дел, скачанное законодательство.
Только диск, без сети.
python3 themiz-next/progress.py -> JSON {"plan": {...}, "runs": [{"case", "done", "total", "pct", "phase"}], "laws": {"done", "total"}}
"""
from __future__ import annotations
import json
import sqlite3
from contextlib import closing
from pathlib import Path
import board
import core
# Задача плана docs/PLAN.md готова, когда на диске есть ее улика. 1-8 - тест-файлы задачи (весь набор зеленый
# проверяет pytest, не строка состояния); 9-10 - пилот с итогом ok; 11 - запись о приемке в PILOT.md.
TESTS = [
("Каркас", ["test_next_board.py", "test_next_dry_run.py"]),
("Вызов агента и прибора", ["test_next_core.py", "test_next_tools.py"]),
("Прием", ["test_next_priem.py"]),
("Карта", ["test_next_karta.py"]),
("Практика", ["test_next_praktika.py"]),
("Позиция и черновик", ["test_next_dokument.py"]),
("Кони", ["test_next_koni.py"]),
("Сборка и PDF приложений", ["test_next_sborka.py"]),
]
ACCEPTED = "Приемка пройдена"
def _states(base: Path) -> list[tuple[Path, dict]]:
result = []
for path in sorted(base.glob("*/*/.agent/next/*/state.json")):
try:
result.append((path.parent, json.loads(path.read_text(encoding="utf-8"))))
except (OSError, json.JSONDecodeError): # state.json переписывается атомарно, но читать могли до первой записи
pass
return result
def plan(root: Path) -> list[tuple[str, bool]]:
tests = root / "themiz-next" / "tests"
pilots = [state for _, state in _states(root / "themiz-next" / "pilot" / "cases")]
pilot_md = root / "themiz-next" / "docs" / "PILOT.md"
return [(title, all((tests / name).is_file() for name in names)) for title, names in TESTS] + [
("Пилот FAST", any(s.get("status") == "ok" and s.get("track") == "FAST" for s in pilots)),
("FULL", any(s.get("status") == "ok" and s.get("track") == "FULL" for s in pilots)),
("Приемка", pilot_md.is_file() and ACCEPTED in pilot_md.read_text(encoding="utf-8")),
]
def live(root: Path) -> list[dict]:
"""Идущие прогоны дел и пилотов: running и замок дела держат. Умершие без итога не показываются."""
result = []
for base in (root / "cases", root / "themiz-next" / "pilot" / "cases"):
for run_dir, state in _states(base):
if state.get("status") != "running" or board.is_dead(run_dir.parents[2], state):
continue
ok, total = board.done(state)
current = next((title for pid, title, _ in core.PHASES
if (state.get("phases", {}).get(pid) or {}).get("status") not in ("ok",)), "")
result.append({"case": run_dir.parents[2].name, "done": ok, "total": total,
"pct": round(ok * 100 / total), "phase": current})
return result
def laws(root: Path) -> dict:
"""Очередь законов background_corpus: скачаны current и updated; deferred, blocked, failed - нет."""
db = root / ".agent" / "maintenance" / "background" / "queue.sqlite3"
if not db.is_file():
return {"done": 0, "total": 0}
with closing(sqlite3.connect(db.as_uri() + "?mode=ro", uri=True, timeout=0.5)) as conn:
total, done = conn.execute("select count(*), count(*) filter (where state in ('current', 'updated')) "
"from jobs").fetchone()
return {"done": done, "total": total}
def main() -> int:
tasks = plan(core.ROOT)
ok = sum(flag for _, flag in tasks)
print(json.dumps({"plan": {"done": ok, "total": len(tasks), "pct": round(ok * 100 / len(tasks)),
"next": next((title for title, flag in tasks if not flag), "")},
"runs": live(core.ROOT), "laws": laws(core.ROOT)}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())