#!/usr/bin/env python3 """komplekt.py — комплект по делу одной командой: норма, пункты Пленумов ВС, обзоры ВС и судебная практика с источниками (решение владельца 03.10.2026). Все локально, без сети: снимок графа права (scripts/legal_graph.py, ребра «references» от пунктов Пленумов и обзоров к статьям) и скачанный корпус СудАкта на Mac (eunomia/practice.py, ссылки актов на статьи). python3 scripts/komplekt.py "ст. 333 ГК РФ" "ст. 395 ГК РФ" по статьям python3 scripts/komplekt.py --case cases/{клиент}/{дело} по статьям карты дела python3 scripts/komplekt.py "текст описания дела" --json статьи из текста Норму и цитату Пленума комплект только находит: дословность и редакцию сверяет cite.py, акт — verify_act.py. Код возврата: 0 — комплект собран; 1 — в запросе нет статьи с кодексом или нет графа права; 2 — ошибка вызова. """ from __future__ import annotations import argparse import contextlib import json import re import sqlite3 import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) import legal_graph # noqa: E402 TEXT_CAP = 4000 # знаков нормы в комплекте: длиннее — читать по адресу source_file:строка POINTS, ACTS, TOGETHER = 5, 5, 5 KINDS = {"plenum": "plenums", "review": "reviews"} SHORT = {slug: alias.upper() for alias, slug in legal_graph.CODE_ALIASES.items()} def refs_of(texts: list[str]) -> list[tuple[str, str]]: """Статьи с кодексом из запроса: [(слаг, номер)] без повторов. Ссылка без кодекса не угадывается.""" found = [] for text in texts: found += [(slug, number) for _, _, number, slug in legal_graph.article_refs(text) if slug] return list(dict.fromkeys(found)) def _db(snapshot: Path) -> sqlite3.Connection: uri = (snapshot / "search.sqlite3").resolve().as_uri() + "?mode=ro&immutable=1" return sqlite3.connect(uri, uri=True) def _nodes(db: sqlite3.Connection, ids: list[str]) -> dict[str, dict]: if not ids: return {} marks = ",".join("?" * len(ids)) out = {} for node_id, label, text, metadata in db.execute( f"SELECT id, label, text, metadata FROM nodes WHERE id IN ({marks})", ids): out[node_id] = {**json.loads(metadata), "id": node_id, "label": label, "text": text} return out def _at(node: dict) -> str: return f"{node.get('source_file', '')}:{node.get('source_location', '')}" def _excerpt(text: str, code: str, article: str) -> str: for start, end, number, slug in legal_graph.article_refs(text): if slug == code and number == article: return " ".join(legal_graph._evidence_excerpt(text, start, end).split())[:600] return "" def interpretations(db: sqlite3.Connection, article_id: str, code: str, article: str) -> dict[str, list]: """Пункты Пленумов и обзоров, которые ссылаются на статью: документ, пункты, выдержка, адрес, источник.""" sources = [row[0] for row in db.execute( "SELECT DISTINCT source FROM edges WHERE target = ? AND relation = 'references'", (article_id,))] points = _nodes(db, sources) documents = _nodes(db, sorted({f"doc:{node['resource_id']}" for node in points.values() if node.get("resource_id")})) grouped: dict[str, dict] = {} for node in sorted(points.values(), key=lambda item: item["id"]): kind = str(node.get("resource_id", "")).split(":")[1:2] if not kind or kind[0] not in KINDS: continue doc = documents.get(f"doc:{node['resource_id']}", {}) item = grouped.setdefault(node["resource_id"], { "kind": kind[0], "document": doc.get("label") or node["resource_id"], "source_url": node.get("source_url"), "revision": node.get("revision"), "points": []}) item["points"].append({"label": node["label"], "at": _at(node), "excerpt": _excerpt(node["text"], code, article)}) result = {"plenums": [], "reviews": []} number = lambda point: [int(part) for part in re.findall(r"\d+", point["label"])] or [0] for item in sorted(grouped.values(), key=lambda value: -len(value["points"])): item["points"] = sorted(item["points"], key=number)[:POINTS] result[KINDS[item["kind"]]].append(item) return result def practice(store, code: str, article: str) -> dict: """Акты корпуса СудАкта на Mac, цитирующие статью: сколько всего, Верховный Суд первым, затем новые; статьи, которые цитируют вместе с ней, и отрасли.""" if store is None or not store.path.is_file(): return {"total": 0, "acts": [], "together": [], "areas": [], "note": "корпус СудАкта на Mac не скачан"} first = store.browse({"code": code, "article": article, "section": "vsrf"}) rest = store.browse({"code": code, "article": article}) acts, seen = [], set() for item in first["items"] + rest["items"]: if item["url"] not in seen and len(acts) < ACTS: seen.add(item["url"]) acts.append({key: item[key] for key in ("title", "number", "act_date", "court", "url", "excerpt")}) from eunomia.practice import _nodes as areas_of, label titles = areas_of() with contextlib.closing(store._db()) as conn: together = conn.execute( "SELECT b.code, b.article, count(*) FROM refs a JOIN refs b ON b.act = a.act " "WHERE a.code = ? AND a.article = ? AND NOT (b.code = a.code AND b.article = a.article) " "GROUP BY 1, 2 ORDER BY 3 DESC LIMIT ?", (code, article, TOGETHER)).fetchall() areas = conn.execute( "SELECT c.node, count(*) FROM cats c JOIN refs r ON r.act = c.act WHERE r.code = ? AND r.article = ? " "GROUP BY 1 ORDER BY 2 DESC LIMIT 3", (code, article)).fetchall() return {"total": rest["total"], "supreme": first["total"], "acts": acts, "together": [{"article": label(c, a), "acts": n} for c, a, n in together], "areas": [{"area": (titles.get(node) or {}).get("title", node), "acts": n} for node, n in areas]} def komplekt(root: Path, refs: list[tuple[str, str]]) -> dict: """Комплект по статьям: норма, Пленумы, обзоры, практика. Без графа права — отказ с причиной.""" snapshot, _ = legal_graph._current(Path(root) / legal_graph.STATE_REL) if snapshot is None or not (snapshot / "search.sqlite3").is_file(): return {"status": "missing", "detail": "графа права нет: python3 scripts/legal_graph.py --refresh", "articles": []} if str(root) not in sys.path[:1]: # scripts/eunomia.py (запуск сервера) не должен заслонять пакет eunomia/ sys.path.insert(0, str(root)) try: from eunomia.practice import Practice store = Practice(Path(root)) except Exception: # noqa: BLE001 - нет Эвномии в копии дома: комплект без практики, причина в note store = None articles = [] with contextlib.closing(_db(snapshot)) as db: for code, article in refs: article_id = f"doc:legal-corpus:code:{code}:article:{article}" norm = _nodes(db, [article_id]).get(article_id) entry = {"article": f"ст. {article} {SHORT.get(code, code)}", "code": code, "number": article, "norm": None if norm is None else { "title": norm["label"], "text": norm["text"][:TEXT_CAP], "at": _at(norm), "source_url": norm.get("source_url"), "revision": norm.get("revision"), "needs_review": bool(norm.get("needs_review"))}} if norm is None: entry["norm_note"] = "статьи нет в корпусе права: кодекс не скачан или номер разобран неверно" entry.update(interpretations(db, article_id, code, article)) entry["practice"] = practice(store, code, article) articles.append(entry) state = legal_graph.status(root) return {"status": "ok", "snapshot": snapshot.name, "graph_needs_review": bool(state.get("needs_review")), "articles": articles} def case_refs(case: Path) -> list[tuple[str, str]]: """Статьи карты дела (.agent/context/knowledge-map.md) — той же грамматикой, что якоря case_graph.""" path = Path(case) / ".agent" / "context" / "knowledge-map.md" return refs_of([path.read_text(encoding="utf-8", errors="replace")]) if path.is_file() else [] def render(result: dict) -> str: if result["status"] != "ok": return result["detail"] lines = [f"Граф права: снимок {result['snapshot']}" + (" · требует проверки" if result["graph_needs_review"] else "")] for item in result["articles"]: norm = item["norm"] lines.append(f"\n{item['article']} — {norm['title'] if norm else item.get('norm_note')}") if norm: lines.append(f" норма: {norm['at']} · редакция {norm['revision'] or 'не указана'} · {norm['source_url'] or 'нет адреса'}") for key, name in (("plenums", "Пленум"), ("reviews", "обзор ВС")): for doc in item[key][:3]: points = ", ".join(point["label"].lower() for point in doc["points"]) lines.append(f" {name}: {doc['document']} — {points} · {doc['source_url'] or doc['points'][0]['at']}") if not item[key]: lines.append(f" {name}: ссылок на статью в корпусе нет") found = item["practice"] lines.append(f" практика на Mac: {found['total']} актов, из них ВС {found.get('supreme', 0)}" + (f" ({found['note']})" if found.get("note") else "")) for act in found["acts"]: lines.append(f" {act['title']} · {act['court'] or ''} · {act['url']}") if found["together"]: lines.append(" цитируют вместе: " + ", ".join(f"{x['article']} ({x['acts']})" for x in found["together"])) return "\n".join(lines) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Комплект по делу: нормы, Пленумы, обзоры, практика") parser.add_argument("text", nargs="*", help="статьи («ст. 333 ГК РФ») или описание дела") parser.add_argument("--case", type=Path, help="папка дела: статьи из карты knowledge-map.md") parser.add_argument("--root", type=Path, default=ROOT) parser.add_argument("--json", action="store_true") args = parser.parse_args(argv) if not args.text and not args.case: parser.error("нужны статьи, описание дела или --case") refs = refs_of(args.text) + (case_refs(args.case) if args.case else []) if not refs: print("в запросе нет статьи с кодексом («ст. 333 ГК РФ»)", file=sys.stderr) return 1 result = komplekt(args.root.resolve(), list(dict.fromkeys(refs))) print(json.dumps(result, ensure_ascii=False, indent=1) if args.json else render(result)) return 0 if result["status"] == "ok" else 1 if __name__ == "__main__": raise SystemExit(main())