release: Themiz на Gitea
This commit is contained in:
+498
-34
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Локальный Graphify-граф нормативного корпуса. Сеть и LLM не используются."""
|
||||
"""Локальный Graphify-граф нормативного корпуса и индекса практики. Сеть и LLM не используются."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
@@ -18,6 +18,9 @@ from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
WEEK = timedelta(days=7)
|
||||
# .build-* — это stage-каталоги активной сборки; живут минуты. Убираем
|
||||
# только те, что зависли (процесс убит по таймауту/краш) — старше суток.
|
||||
STALE_BUILD_AGE = timedelta(hours=24)
|
||||
MAX_DOCUMENT_BYTES = 10 * 1024 * 1024
|
||||
ALLOWED_KINDS = frozenset({"code", "plenum", "review", "federal-law", "bylaw"})
|
||||
STATE_REL = Path(".agent/maintenance/legal-graph")
|
||||
@@ -41,11 +44,140 @@ WORD_RE = re.compile(r"[0-9a-zа-я]+", re.I)
|
||||
# действительно присутствуют в реестре, чтобы похожее слово не стало ссылкой.
|
||||
CODE_ALIASES = {
|
||||
"гпк рф": "gpk-rf", "апк рф": "apk-rf", "гк рф": "gk-rf",
|
||||
"кас рф": "kas-rf", "упк рф": "upk-rf", "коап рф": "koap-rf",
|
||||
"тк рф": "tk-rf", "жк рф": "zhk-rf", "зк рф": "zk-rf",
|
||||
"ук рф": "uk-rf", "нк рф": "nk-rf-gosposhlina",
|
||||
"ск рф": "sk-rf", "кас рф": "kas-rf", "упк рф": "upk-rf",
|
||||
"коап рф": "koap-rf", "тк рф": "tk-rf", "жк рф": "zhk-rf",
|
||||
"зк рф": "zk-rf", "ук рф": "uk-rf", "нк рф": "nk-rf",
|
||||
}
|
||||
|
||||
# Акты чаще пишут кодекс полным именем: «статьей 333 Гражданского кодекса
|
||||
# Российской Федерации». article_refs знает сокращения, поэтому имя сводится
|
||||
# к ним до разбора. Замер 01.10.2026 на 2 701 акте: 25 408 ссылок без свода,
|
||||
# 49 845 со сводом. Порядок важен: процессуальные кодексы раньше материальных.
|
||||
CODE_NAMES = (
|
||||
(r"гражданск\w*\s+процессуальн\w*\s+кодекс\w*", "ГПК"),
|
||||
(r"арбитражн\w*\s+процессуальн\w*\s+кодекс\w*", "АПК"),
|
||||
(r"уголовно-процессуальн\w*\s+кодекс\w*", "УПК"),
|
||||
(r"кодекс\w*\s+административного\s+судопроизводства", "КАС"),
|
||||
(r"кодекс\w*\s+(?:российской\s+федерации\s+)?об\s+административных\s+правонарушениях", "КоАП"),
|
||||
(r"гражданск\w*\s+кодекс\w*", "ГК"), (r"семейн\w*\s+кодекс\w*", "СК"),
|
||||
(r"трудов\w*\s+кодекс\w*", "ТК"), (r"жилищн\w*\s+кодекс\w*", "ЖК"),
|
||||
(r"земельн\w*\s+кодекс\w*", "ЗК"), (r"уголовн\w*\s+кодекс\w*", "УК"),
|
||||
(r"налогов\w*\s+кодекс\w*", "НК"),
|
||||
)
|
||||
# Опережающая проверка первой буквы ускоряет свод в 2,5 раза (замер 01.10.2026).
|
||||
CODE_NAME_RE = re.compile(r"(?iu)\b(?=[гаукстжзн])(?:" + "|".join(f"({p})" for p, _ in CODE_NAMES)
|
||||
+ r")(?:\s+(?:российской\s+федерации|рф)\b)?")
|
||||
|
||||
|
||||
def short_codes(text: str) -> tuple[str, list[tuple[int, int, int, int]]]:
|
||||
"""Полные имена кодексов → «ГК РФ». Метки переводят позицию обратно в исходный текст."""
|
||||
parts, marks, last, length = [], [], 0, 0
|
||||
for match in CODE_NAME_RE.finditer(text):
|
||||
short = CODE_NAMES[match.lastindex - 1][1] + " РФ"
|
||||
parts.append(text[last:match.start()])
|
||||
length += match.start() - last
|
||||
marks.append((length, length + len(short), match.start(), match.end()))
|
||||
parts.append(short)
|
||||
length += len(short)
|
||||
last = match.end()
|
||||
parts.append(text[last:])
|
||||
return "".join(parts), marks
|
||||
|
||||
|
||||
def _original(pos: int, marks: list[tuple[int, int, int, int]]) -> int:
|
||||
delta = 0
|
||||
for start, end, ostart, oend in marks:
|
||||
if pos < start:
|
||||
break
|
||||
if pos <= end:
|
||||
return oend if pos > start else ostart
|
||||
delta = oend - end
|
||||
return pos + delta
|
||||
|
||||
# Индекс проверенной практики — не ресурс реестра (живой gitignored-файл без
|
||||
# frontmatter), а второй класс источника графа. Читается локально, как есть.
|
||||
PRACTICE_KIND = "practice"
|
||||
PRACTICE_ID = "practice:index"
|
||||
PRACTICE_REL = "knowledge/practice_index.md"
|
||||
# Свежий клон: живого индекса еще нет, граф строится из шаблона и честно
|
||||
# помечается needs_review. Без этого fallback вся сборка отказывала бы на
|
||||
# чистой копии, где корпус еще не выгружен.
|
||||
PRACTICE_DEFAULT_REL = "config/knowledge-defaults/practice_index.md"
|
||||
PRACTICE_ENTRY_RE = re.compile(r"^###\s+(.+?)\s*$", re.M)
|
||||
PRACTICE_SECTION_RE = re.compile(r"^##\s+(.+?)\s*$", re.M)
|
||||
# Ссылка на норму — ОДНА грамматика на весь дом: запись практики, строка
|
||||
# якоря и карта дела (case_graph) читают ссылку только через article_refs.
|
||||
# Три копии регулярки по-разному решали, чей кодекс у ссылки (замечание
|
||||
# приемки T312, круг 5). Формы: «статья» в любом падеже и числе или «ст.»;
|
||||
# номер, список («ст. 34, 35», «ст. 34 и 35») или диапазон («ст. 34–35»,
|
||||
# «ст. 34-35»); кодекс после номера («ГК РФ», «ГК») относится к КАЖДОМУ
|
||||
# номеру и сильнее кодекса раздела; тег «#ст-34-ск» кодекс называет всегда.
|
||||
_CODES = r"(гпк|апк|гк|ск|кас|упк|коап|тк|жк|зк|ук|нк)"
|
||||
ARTICLE_REF_RE = re.compile(
|
||||
r"(?iu)\b(?:стат(?:ья|ьи|ье|ью|ьей|ей|ьям|ьями|ьях)|ст\.)\s*"
|
||||
r"(\d+(?:\.\d+)*(?:\s*(?:,|\bи\b|[—–-])\s*\d+(?:\.\d+)*)*)"
|
||||
rf"(?:\s+{_CODES}(?:\s*рф)?\b)?"
|
||||
rf"|#ст-(\d+(?:\.\d+)*)-{_CODES}\b")
|
||||
ARTICLE_SEP_RE = re.compile(r"(?iu)\s*(,|\bи\b|[—–-])\s*")
|
||||
# ponytail: диапазон шире 50 статей — опечатка, а не ссылка; берутся концы.
|
||||
RANGE_CAP = 50
|
||||
|
||||
|
||||
def _article_numbers(group: str) -> list[str]:
|
||||
"""«34, 35» → [34, 35]; «34–36» → [34, 35, 36]; «34.1-34.3» → концы."""
|
||||
tokens = ARTICLE_SEP_RE.split(group)
|
||||
numbers = [tokens[0]]
|
||||
for sep, num in zip(tokens[1::2], tokens[2::2]):
|
||||
prev = numbers[-1]
|
||||
if (sep in "—–-" and prev.isdigit() and num.isdigit()
|
||||
and 0 < int(num) - int(prev) <= RANGE_CAP):
|
||||
numbers += [str(n) for n in range(int(prev) + 1, int(num) + 1)]
|
||||
else:
|
||||
numbers.append(num)
|
||||
return numbers
|
||||
|
||||
|
||||
def article_refs(text: str, section_slug: str | None = None
|
||||
) -> list[tuple[int, int, str, str | None]]:
|
||||
"""[(начало, конец, номер, слаг кодекса)] каждой ссылки на статью в text.
|
||||
|
||||
Кодекс, названный при номере или списке, сильнее кодекса раздела; голая
|
||||
ссылка берет `section_slug`, а без раздела получает None (не разрешена).
|
||||
"""
|
||||
refs = []
|
||||
for m in ARTICLE_REF_RE.finditer(text):
|
||||
if m.group(3):
|
||||
numbers, code = [m.group(3)], m.group(4)
|
||||
else:
|
||||
numbers, code = _article_numbers(m.group(1)), m.group(2)
|
||||
slug = CODE_ALIASES.get(f"{code.casefold()} рф") if code else section_slug
|
||||
refs += [(m.start(), m.end(), number, slug) for number in numbers]
|
||||
return refs
|
||||
|
||||
|
||||
# Тематический раздел индекса практики: «СК РФ», «СК — Раздел имущества»,
|
||||
# «ГК РФ: договоры». Кодексом считается только ВЕДУЩИЙ кодекс раздела:
|
||||
# раздел «Семейные споры» кодексом не является, голая ссылка там не
|
||||
# атрибутируется (замечание приемки T312, круг 3).
|
||||
SECTION_CODE_RE = re.compile(
|
||||
r"(?iu)^\s*(гпк|апк|гк|ск|кас|упк|коап|тк|жк|зк|ук|нк)(?:\s+рф)?"
|
||||
r"(?:\s*[—–\-:;]|\s*$)")
|
||||
|
||||
|
||||
def _section_code(section: object) -> str | None:
|
||||
"""Слаг кодекса тематического раздела индекса практики или None.
|
||||
|
||||
Точный алиас («СК РФ») или ведущий кодекс с суффиксом темы («СК —
|
||||
Раздел имущества»). CODE_ALIASES применяется ровно один раз — двойное
|
||||
применение теряло связь голой «ст. 34» (замечание приемки T312, круг 2).
|
||||
"""
|
||||
text = str(section or "").casefold()
|
||||
if text in CODE_ALIASES:
|
||||
return CODE_ALIASES[text]
|
||||
match = SECTION_CODE_RE.match(text)
|
||||
return CODE_ALIASES.get(f"{match.group(1)} рф") if match else None
|
||||
PRACTICE_UPDATED_RE = re.compile(r"Обновлено:\s*(\d{2}\.\d{2}\.\d{4})")
|
||||
|
||||
|
||||
class SourceChanged(RuntimeError):
|
||||
"""Источник изменился между чтением и публикацией snapshot."""
|
||||
@@ -129,9 +261,12 @@ def status(root: Path | str) -> dict:
|
||||
checked = _parse_time(report.get("checked_at"))
|
||||
age = _now() - checked if checked else None
|
||||
due = age is None or age > WEEK or age < timedelta(0)
|
||||
# Граф старше недели доступен, но требует сверки: статус needs_review, срок — в поле due (REQ-18).
|
||||
return {
|
||||
"status": "due" if due else "current", "available": True, "due": due,
|
||||
"status": "needs_review" if due else "current", "available": True, "due": due,
|
||||
"needs_review": due or bool(report.get("needs_review")),
|
||||
"review_reasons": ([{"resource_id": None, "reason": "снимок старше недели"}] if due else [])
|
||||
+ list(report.get("review_reasons") or []),
|
||||
"snapshot": snapshot.name, "built_at": report.get("built_at"),
|
||||
"checked_at": report.get("checked_at"),
|
||||
"source_fingerprint": report.get("source_fingerprint"),
|
||||
@@ -237,7 +372,26 @@ def _source_path(root: Path, output: object) -> Path:
|
||||
return current
|
||||
|
||||
|
||||
def _read_source(root: Path, resource: dict) -> dict:
|
||||
def _queue_jobs(root: Path) -> tuple[dict[str, dict], str | None]:
|
||||
"""Свежесть документов - из очереди загрузчика (background_corpus): frontmatter ее не хранит."""
|
||||
try:
|
||||
import background_corpus
|
||||
return {job["id"]: job for job in background_corpus.status(root)["jobs"]}, None
|
||||
except Exception as exc: # noqa: BLE001 - нет очереди: свежесть неизвестна, причина в отчете
|
||||
return {}, f"очередь загрузчика недоступна: {type(exc).__name__}"
|
||||
|
||||
|
||||
def _queue_reason(job: dict | None) -> str | None:
|
||||
"""None - документ свежий: задание current/updated, проверка не старше недели."""
|
||||
if job is None:
|
||||
return "нет в очереди загрузчика"
|
||||
if job.get("state") in {"current", "updated"} and job.get("freshness") == "current":
|
||||
return None
|
||||
detail = " ".join(str(job.get("detail") or "").split())[:120]
|
||||
return f"очередь: {job.get('state')}, свежесть {job.get('freshness')}" + (f" - {detail}" if detail else "")
|
||||
|
||||
|
||||
def _read_source(root: Path, resource: dict, queue: dict[str, dict] | None = None) -> dict:
|
||||
path = _source_path(root, resource.get("output"))
|
||||
stat = path.stat()
|
||||
if not path.is_file() or stat.st_size > MAX_DOCUMENT_BYTES:
|
||||
@@ -250,11 +404,8 @@ def _read_source(root: Path, resource: dict) -> dict:
|
||||
body_sha = _sha(body.encode("utf-8"))
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", declared) or declared != body_sha:
|
||||
raise ValueError("body sha256 отсутствует или не совпадает")
|
||||
freshness = meta.get("статус_свежести") or meta.get("source_freshness")
|
||||
last_checked = meta.get("last_checked")
|
||||
checked = _parse_time(last_checked)
|
||||
checked_age = _now() - checked if checked else None
|
||||
checked_stale = checked_age is None or checked_age > WEEK or checked_age < timedelta(0)
|
||||
job = (queue or {}).get(resource.get("id"))
|
||||
reason = _queue_reason(job)
|
||||
return {
|
||||
"resource": resource, "path": path, "relative_path": path.relative_to(root).as_posix(),
|
||||
"raw_sha256": _sha(raw), "body_sha256": body_sha, "size": len(raw),
|
||||
@@ -262,11 +413,116 @@ def _read_source(root: Path, resource: dict) -> dict:
|
||||
"body_offset": len(full_text) - len(body),
|
||||
"source_url": resource.get("url") or meta.get("источник") or None,
|
||||
"revision": meta.get("дата_редакции") or meta.get("дата_акта") or None,
|
||||
"last_checked": last_checked,
|
||||
"needs_review": freshness != "current" or checked_stale,
|
||||
"last_checked": job.get("last_checked") if job else None,
|
||||
"needs_review": reason is not None, "review_reason": reason,
|
||||
}
|
||||
|
||||
|
||||
def _read_practice(root: Path) -> dict | None:
|
||||
"""Индекс практики как источник графа. Файл живой (gitignored), без
|
||||
frontmatter-контракта корпуса — читаем как есть. Живого нет — берем
|
||||
шаблон чистого клона и честно помечаем needs_review: граф на чистой
|
||||
копии строится, но потребитель видит, что практика еще не наполнена."""
|
||||
path = root / PRACTICE_REL
|
||||
from_default = False
|
||||
if not path.is_file() or path.is_symlink():
|
||||
path = root / PRACTICE_DEFAULT_REL
|
||||
from_default = True
|
||||
if not path.is_file() or path.is_symlink():
|
||||
return None
|
||||
stat = path.stat()
|
||||
# Пустой или раздутый индекс — отказ с причиной, а не тихий пропуск
|
||||
# практики из графа (замечание приемки T312, круг 5).
|
||||
if not stat.st_size or stat.st_size > MAX_DOCUMENT_BYTES:
|
||||
raise ValueError(f"индекс практики пуст или больше лимита: {stat.st_size} байт")
|
||||
raw = path.read_bytes()
|
||||
body = raw.decode("utf-8", errors="replace")
|
||||
updated = PRACTICE_UPDATED_RE.search(body)
|
||||
if updated:
|
||||
checked = datetime.strptime(updated.group(1), "%d.%m.%Y").replace(tzinfo=UTC)
|
||||
else:
|
||||
checked = datetime.fromtimestamp(stat.st_mtime, UTC)
|
||||
return {
|
||||
"resource": {"id": PRACTICE_ID, "kind": PRACTICE_KIND,
|
||||
"label": "Индекс проверенной практики"},
|
||||
"path": path, "relative_path": path.relative_to(root).as_posix(),
|
||||
"raw_sha256": _sha(raw), "body_sha256": _sha(raw), "size": len(raw),
|
||||
"mtime_ns": stat.st_mtime_ns, "body": body, "full_text": body,
|
||||
"body_offset": 0, "source_url": None,
|
||||
"revision": updated.group(1) if updated else None,
|
||||
"last_checked": _stamp(checked),
|
||||
"needs_review": from_default,
|
||||
"review_reason": "индекс практики - шаблон чистого клона" if from_default else None,
|
||||
}
|
||||
|
||||
|
||||
def _extract_practice(source: dict) -> tuple[list[dict], list[dict]]:
|
||||
"""Записи «### Тема» → узлы kind=practice. Поле «Источник:» в текст узла
|
||||
не попадает: там встречается слаг дела доверителя, а граф — не место
|
||||
для него (замер graph_pd_check 03.09.2026, LIM-01). Строка глушится,
|
||||
а не вырезается: число переводов строк сохраняется, иначе якоря
|
||||
(_node_line) съезжали бы на число вырезанных строк."""
|
||||
body = source["body"]
|
||||
doc_id = _graph_id(PRACTICE_ID)
|
||||
# Документный узел тоже без строк «Источник:»: он несет body целиком, и
|
||||
# слаг дела уезжал бы в Graphify через него (замечание приемки T312).
|
||||
safe_body = "\n".join("" if line.strip().startswith("- **Источник:**") else line
|
||||
for line in body.splitlines())
|
||||
nodes = [_node(doc_id, source["resource"]["label"], source, "document", safe_body, 0)]
|
||||
edges = []
|
||||
marks = [(m.start(), m.group(1), m.group(2))
|
||||
for m in re.finditer(r"(?m)^(##|###)\s+(.+?)\s*$", body)]
|
||||
section = ""
|
||||
for i, (pos, level, title) in enumerate(marks):
|
||||
end = marks[i + 1][0] if i + 1 < len(marks) else len(body)
|
||||
if level == "##":
|
||||
section = title
|
||||
continue
|
||||
text = "\n".join("" if line.strip().startswith("- **Источник:**") else line
|
||||
for line in body[pos:end].splitlines())
|
||||
entry_id = f"{doc_id}:entry:{i}"
|
||||
node = _node(entry_id, title, source, PRACTICE_KIND, text, pos)
|
||||
node["section"] = section
|
||||
nodes.append(node)
|
||||
edges.append(_edge(doc_id, entry_id, "contains", source["relative_path"],
|
||||
line=_source_line(source, pos)))
|
||||
return nodes, edges
|
||||
|
||||
|
||||
def _practice_reference_edges(sources: list[dict], nodes: list[dict]) -> list[dict]:
|
||||
"""Запись практики → статья нормы. Кодекс из строки («ст. 34 СК РФ»,
|
||||
«статье 34 СК РФ», тег «#ст-34-ск»), а когда не назван — из раздела
|
||||
индекса («## ГК РФ», тематический «## СК — Раздел имущества»). Список
|
||||
номеров с хвостовым кодексом («ст. 34 и 35 ГК РФ») дает ребро КАЖДОМУ
|
||||
номеру и именно в названный кодекс — не в кодекс раздела (замечание
|
||||
приемки T312, круг 4). Связываемся только со статьями, реально
|
||||
присутствующими в графе."""
|
||||
by_article: dict[tuple[str, str], str] = {}
|
||||
for node in nodes:
|
||||
match = re.match(r"(?iu)^статья\s+(\d+(?:\.\d+)*)", node.get("label", ""))
|
||||
if node["kind"] == "article" and match:
|
||||
by_article[(node["resource_id"], match.group(1))] = node["id"]
|
||||
slug_to_resource = {_code_slug(source["resource"]): source["resource"]["id"]
|
||||
for source in sources if _code_slug(source["resource"])}
|
||||
result = []
|
||||
for node in nodes:
|
||||
if node["kind"] != PRACTICE_KIND:
|
||||
continue
|
||||
text = node.get("text", "")
|
||||
for start, end, number, slug in article_refs(
|
||||
text, _section_code(node.get("section"))):
|
||||
target_resource = slug_to_resource.get(slug or "")
|
||||
target = (by_article.get((target_resource, number))
|
||||
if target_resource else None)
|
||||
if target and target != node["id"]:
|
||||
result.append(_edge(
|
||||
node["id"], target, "references", node["source_file"],
|
||||
excerpt=_evidence_excerpt(text, start, end),
|
||||
source_url=node.get("source_url"), revision=node.get("revision"),
|
||||
line=_node_line(node, start)))
|
||||
return result
|
||||
|
||||
|
||||
def _line(text: str, pos: int) -> int:
|
||||
return text.count("\n", 0, pos) + 1
|
||||
|
||||
@@ -351,7 +607,8 @@ def _extract(source: dict) -> tuple[list[dict], list[dict]]:
|
||||
nodes = [_node(doc_id, label, source, "document", body, 0)]
|
||||
node_ids = {doc_id}
|
||||
edges, articles = [], []
|
||||
matches = list(ARTICLE_RE.finditer(body))
|
||||
# Статей у обзора нет: строка «статья 57 СК РФ)…» после переноса - цитата, а не статья обзора.
|
||||
matches = [] if resource.get("kind") == "review" else list(ARTICLE_RE.finditer(body))
|
||||
for index, match in enumerate(matches):
|
||||
number = match.group(1)
|
||||
text = body[match.start():matches[index + 1].start() if index + 1 < len(matches) else len(body)]
|
||||
@@ -387,6 +644,14 @@ def _extract(source: dict) -> tuple[list[dict], list[dict]]:
|
||||
# Пленумы и обзоры часто состоят из пунктов без единой статьи.
|
||||
if resource.get("kind") in {"plenum", "review"}:
|
||||
point_matches = list(POINT_RE.finditer(body))
|
||||
if resource.get("kind") == "review":
|
||||
# Пункты обзора ВС идут подряд с заглавной буквы: «1. Противоправное…». Сноски, номера
|
||||
# страниц и переносы («статьи\n12.24 КоАП») вне ряда, иначе резали бы текст пункта.
|
||||
sequence = []
|
||||
for point in point_matches:
|
||||
if point.group(1) == str(len(sequence) + 1) and (point.group(2) or "")[:1].isupper():
|
||||
sequence.append(point)
|
||||
point_matches = sequence
|
||||
for point_index, point in enumerate(point_matches):
|
||||
point_no = point.group(1)
|
||||
point_id = f"{doc_id}:point:{point_no}"
|
||||
@@ -456,22 +721,26 @@ def _cross_document_edges(sources: list[dict], nodes: list[dict]) -> list[dict]:
|
||||
if node["kind"] not in {"article", "point", "heading"}:
|
||||
continue
|
||||
text = node.get("text", "")
|
||||
# Обзоры ВС пишут кодекс полным именем («статьей 158 Уголовного кодекса Российской Федерации»):
|
||||
# ссылки ищутся в тексте со сводом к «УК РФ», позиции excerpt и line - в исходном тексте.
|
||||
short, marks = short_codes(text)
|
||||
# Форма «ст. 131 ГПК РФ» / «пункт 5 ГПК РФ».
|
||||
combined = re.compile(
|
||||
r"(?iu)\b(?:статья|статьи|статье|статью|статьей|статей|ст\.)\s*"
|
||||
r"(\d+(?:\.\d+)*)\s+(гпк|апк|гк|кас|упк|коап|тк|жк|зк|ук|нк)\s*рф\b")
|
||||
for match in combined.finditer(text):
|
||||
for match in combined.finditer(short):
|
||||
slug = CODE_ALIASES[f"{match.group(2).casefold()} рф"]
|
||||
target_resource = slug_to_resource.get(slug)
|
||||
target = by_article.get((target_resource, match.group(1))) if target_resource else None
|
||||
if target and target != node["id"]:
|
||||
start = _original(match.start(), marks)
|
||||
result.append(_edge(node["id"], target, "references", node["source_file"],
|
||||
excerpt=_evidence_excerpt(text, match.start(), match.end()),
|
||||
excerpt=_evidence_excerpt(text, start, _original(match.end(), marks)),
|
||||
source_url=node.get("source_url"), revision=node.get("revision"),
|
||||
line=_node_line(node, match.start())))
|
||||
line=_node_line(node, start)))
|
||||
# «статьи 1, 2 ГПК РФ»: сохраняем каждую явно названную статью.
|
||||
for match in ARTICLE_LIST_REF_RE.finditer(text):
|
||||
tail = text[match.end():match.end() + 40]
|
||||
for match in ARTICLE_LIST_REF_RE.finditer(short):
|
||||
tail = short[match.end():match.end() + 40]
|
||||
code = re.match(
|
||||
r"(?iu)\s+(гпк|апк|гк|кас|упк|коап|тк|жк|зк|ук|нк)\s*рф\b", tail)
|
||||
if not code:
|
||||
@@ -479,13 +748,14 @@ def _cross_document_edges(sources: list[dict], nodes: list[dict]) -> list[dict]:
|
||||
target_resource = slug_to_resource.get(
|
||||
CODE_ALIASES.get(f"{code.group(1).casefold()} рф"))
|
||||
numbers = re.findall(r"\d+(?:\.\d+)*", match.group(0))
|
||||
start, end = _original(match.start(), marks), _original(match.end() + code.end(), marks)
|
||||
for number in numbers:
|
||||
target = by_article.get((target_resource, number)) if target_resource else None
|
||||
if target and target != node["id"]:
|
||||
result.append(_edge(node["id"], target, "references", node["source_file"],
|
||||
excerpt=_evidence_excerpt(text, match.start(), match.end() + code.end()),
|
||||
excerpt=_evidence_excerpt(text, start, end),
|
||||
source_url=node.get("source_url"), revision=node.get("revision"),
|
||||
line=_node_line(node, match.start())))
|
||||
line=_node_line(node, start)))
|
||||
for match in ARTICLE_REF_RE.finditer(text):
|
||||
# Без квалификатора нельзя приписывать ссылку текущему акту.
|
||||
tail = text[match.end():match.end() + 80]
|
||||
@@ -516,13 +786,17 @@ def _cross_document_edges(sources: list[dict], nodes: list[dict]) -> list[dict]:
|
||||
def _snapshot_data(sources: list[dict]) -> tuple[dict, dict]:
|
||||
nodes, edges = [], []
|
||||
for source in sources:
|
||||
new_nodes, new_edges = _extract(source)
|
||||
if source["resource"].get("kind") == PRACTICE_KIND:
|
||||
new_nodes, new_edges = _extract_practice(source)
|
||||
else:
|
||||
new_nodes, new_edges = _extract(source)
|
||||
nodes.extend(new_nodes)
|
||||
edges.extend(new_edges)
|
||||
# NetworkX оставляет последнюю запись при повторном ID; индекс обязан
|
||||
# повторять ровно ту же семантику, иначе UI покажет узел, которого нет в графе.
|
||||
nodes = list({node["id"]: node for node in nodes}.values())
|
||||
edges.extend(_cross_document_edges(sources, nodes))
|
||||
edges.extend(_practice_reference_edges(sources, nodes))
|
||||
unique = {(edge["source"], edge["target"], edge["relation"]): edge for edge in edges}
|
||||
edges = [unique[key] for key in sorted(unique)]
|
||||
extraction = {"nodes": nodes, "edges": edges, "hyperedges": [],
|
||||
@@ -615,6 +889,35 @@ def _sqlite_candidates(snapshot: Path, tokens: set[str], limit: int) -> tuple[li
|
||||
return nodes, neighbors
|
||||
|
||||
|
||||
def _sqlite_nodes_by_id(snapshot: Path, ids: set[str]) -> dict | None:
|
||||
"""Узлы по id из статического FTS-индекса. None — индекса нет.
|
||||
|
||||
Соседи хитов (практика, поднятая по ребрам) читаются отсюда, а не
|
||||
перечитыванием всего search-index.json поверх SQLite.
|
||||
"""
|
||||
if not ids:
|
||||
return {}
|
||||
path = snapshot / "search.sqlite3"
|
||||
if not path.exists():
|
||||
return None
|
||||
if path.is_symlink():
|
||||
raise ValueError("search.sqlite3 не может быть symlink")
|
||||
path.resolve().relative_to(snapshot.resolve())
|
||||
uri = path.resolve().as_uri() + "?mode=ro&immutable=1"
|
||||
marks = ",".join("?" for _ in ids)
|
||||
with contextlib.closing(sqlite3.connect(uri, uri=True)) as db:
|
||||
rows = db.execute(
|
||||
f"SELECT id,label,aliases,text,metadata FROM nodes WHERE id IN ({marks})",
|
||||
sorted(ids)).fetchall()
|
||||
out = {}
|
||||
for node_id, label, aliases, text, metadata in rows:
|
||||
node = json.loads(metadata)
|
||||
node.update({"id": node_id, "label": label,
|
||||
"aliases": aliases.split(), "text": text})
|
||||
out[node_id] = node
|
||||
return out
|
||||
|
||||
|
||||
def _source_unchanged(source: dict) -> bool:
|
||||
try:
|
||||
path, before = source["path"], (source["size"], source["mtime_ns"], source["raw_sha256"])
|
||||
@@ -626,7 +929,8 @@ def _source_unchanged(source: dict) -> bool:
|
||||
|
||||
def _fingerprint(sources: list[dict], warnings: list[dict]) -> str:
|
||||
value = {
|
||||
"documents": sorted((source["resource"]["id"], source["raw_sha256"])
|
||||
# Свежесть - флагом, без текста причины: деталь задания меняется каждый тик и гоняла бы пересборку.
|
||||
"documents": sorted((source["resource"]["id"], source["raw_sha256"], bool(source.get("needs_review")))
|
||||
for source in sources),
|
||||
"warnings": sorted((str(item.get("resource_id")), str(item.get("problem")))
|
||||
for item in warnings),
|
||||
@@ -634,6 +938,31 @@ def _fingerprint(sources: list[dict], warnings: list[dict]) -> str:
|
||||
return _sha(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode())
|
||||
|
||||
|
||||
def _review_reasons(sources: list[dict], warnings: list[dict]) -> list[dict]:
|
||||
"""Почему граф требует проверки: несвежие документы очереди и документы, которых нет в корпусе."""
|
||||
return ([{"resource_id": source["resource"]["id"], "reason": source["review_reason"]}
|
||||
for source in sources if source.get("review_reason")]
|
||||
+ [{"resource_id": item.get("resource_id"), "reason": str(item.get("problem"))[:200]}
|
||||
for item in warnings])
|
||||
|
||||
|
||||
def _sweep_stale_builds(state: Path) -> int:
|
||||
"""Удалить зависшие .build-* (убитые сборки). Вызывать только под flock .lock."""
|
||||
removed = 0
|
||||
cutoff = _now() - STALE_BUILD_AGE
|
||||
for stage in state.glob(".build-*"):
|
||||
try:
|
||||
if stage.is_symlink() or not stage.is_dir():
|
||||
continue
|
||||
mtime = datetime.fromtimestamp(stage.stat().st_mtime, UTC)
|
||||
if mtime < cutoff:
|
||||
shutil.rmtree(stage)
|
||||
removed += 1
|
||||
except OSError:
|
||||
continue
|
||||
return removed
|
||||
|
||||
|
||||
def _build_snapshot(state: Path, sources: list[dict], warnings: list[dict], now: datetime) -> tuple[str, dict]:
|
||||
try:
|
||||
from graphify.build import build_from_json
|
||||
@@ -663,7 +992,7 @@ def _build_snapshot(state: Path, sources: list[dict], warnings: list[dict], now:
|
||||
"schema": 1, "built_at": _stamp(now), "source_fingerprint": fingerprint,
|
||||
"documents": [{key: source[key] for key in (
|
||||
"relative_path", "raw_sha256", "body_sha256", "size", "mtime_ns",
|
||||
"source_url", "revision", "last_checked", "needs_review")}
|
||||
"source_url", "revision", "last_checked", "needs_review", "review_reason")}
|
||||
| {"resource_id": source["resource"]["id"],
|
||||
"kind": source["resource"]["kind"]} for source in sources],
|
||||
"warnings": warnings,
|
||||
@@ -675,6 +1004,7 @@ def _build_snapshot(state: Path, sources: list[dict], warnings: list[dict], now:
|
||||
"edges": graph.number_of_edges(), "communities": len(communities),
|
||||
"raw_cohesion": {str(key): value for key, value in cohesion.items()},
|
||||
"needs_review": any(source["needs_review"] for source in sources) or bool(warnings),
|
||||
"review_reasons": _review_reasons(sources, warnings),
|
||||
"warnings": warnings, "input_tokens": 0, "output_tokens": 0,
|
||||
"html_generated": False,
|
||||
}
|
||||
@@ -715,8 +1045,13 @@ def refresh(root: Path | str, force: bool = False) -> dict:
|
||||
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return {"status": "busy", "updated": False, "lkg": status(root)}
|
||||
swept = _sweep_stale_builds(state)
|
||||
if swept:
|
||||
print(f"legal_graph: удалено зависших .build-*: {swept}", file=sys.stderr)
|
||||
current = status(root)
|
||||
if current["available"] and not current["due"] and not force:
|
||||
# Снимок с needs_review пересчитывает отпечаток (дешево): иначе флаг держался бы неделю
|
||||
# после того, как загрузчик докачал корпус.
|
||||
if current["available"] and not current["due"] and not current["needs_review"] and not force:
|
||||
return {**current, "status": "current", "updated": False, "skipped": True}
|
||||
try:
|
||||
import corpus_registry
|
||||
@@ -725,6 +1060,9 @@ def refresh(root: Path | str, force: bool = False) -> dict:
|
||||
return {"status": "failed", "updated": False,
|
||||
"error": f"registry: {type(exc).__name__}: {exc}", "lkg": current}
|
||||
sources, warnings = [], []
|
||||
queue, queue_problem = _queue_jobs(root)
|
||||
if queue_problem:
|
||||
warnings.append({"resource_id": "background:queue", "problem": queue_problem})
|
||||
for resource in resources:
|
||||
if resource.get("kind") == "catalog":
|
||||
continue
|
||||
@@ -732,10 +1070,20 @@ def refresh(root: Path | str, force: bool = False) -> dict:
|
||||
warnings.append({"resource_id": resource.get("id"), "problem": "kind не разрешен"})
|
||||
continue
|
||||
try:
|
||||
sources.append(_read_source(root, resource))
|
||||
sources.append(_read_source(root, resource, queue))
|
||||
except (OSError, UnicodeError, ValueError) as exc:
|
||||
warnings.append({"resource_id": resource.get("id"),
|
||||
"output": resource.get("output"), "problem": str(exc)})
|
||||
# Индекс практики — второй класс источника: живет вне реестра, но без
|
||||
# него чистый клон (корпус еще не выгружен) не построил бы ничего.
|
||||
try:
|
||||
practice = _read_practice(root)
|
||||
except (OSError, UnicodeError, ValueError) as exc:
|
||||
practice = None
|
||||
warnings.append({"resource_id": PRACTICE_ID, "output": PRACTICE_REL,
|
||||
"problem": str(exc)})
|
||||
if practice:
|
||||
sources.append(practice)
|
||||
if not sources:
|
||||
return {"status": "failed", "updated": False,
|
||||
"error": "нет ни одного целого зарегистрированного документа",
|
||||
@@ -769,6 +1117,48 @@ def _normalize(text: object) -> str:
|
||||
return " ".join(WORD_RE.findall(str(text).casefold().replace("ё", "е")))
|
||||
|
||||
|
||||
def practice_cite_line(node: dict, code_slug: str | None, number: str) -> str | None:
|
||||
"""Строка записи практики, которая ссылается на норму `number` кодекса
|
||||
`code_slug` (слаг из CODE_ALIASES, None — кодекс неизвестен).
|
||||
|
||||
Якорь шагов 4-5 ведет на строку с текстом нормы, а не на заголовок
|
||||
записи. Номер точный («34» не совпадает с «34.1»), и кодекс, названный
|
||||
при номере, обязан быть кодексом нормы — иначе якорь вел бы на чужую
|
||||
ссылку (замечание приемки T312: ст. 34 СК путалась со ст. 34 ГК и 34.1).
|
||||
Голый номер без кодекса в строке наследует кодекс РАЗДЕЛА записи
|
||||
(«## СК РФ», тематический «## СК — Раздел имущества») — та же логика,
|
||||
что в _practice_reference_edges; раздел чужого кодекса или его
|
||||
отсутствие отвергают строку (замечание приемки T312, круг 2: голая
|
||||
«ст. 34» принималась для любого code_slug). Формы ссылки — те же, что
|
||||
у ребер: падежи «статьи», «ст.», тег «#ст-34-ск» (круг 3), список
|
||||
«ст. 34 и 35 ГК РФ», где хвостовой кодекс относится к каждому номеру
|
||||
(круг 4: «ст. 34» из такого списка приписывалась разделу, хотя кодекс
|
||||
назван в самой строке).
|
||||
Строки «- **Источник:**» в text заглушены пустыми строками, поэтому
|
||||
смещение по text совпадает с номером строки в файле индекса.
|
||||
"""
|
||||
base = re.fullmatch(r"L(\d+)", str(node.get("source_location") or ""))
|
||||
if not base:
|
||||
return None
|
||||
# Разбор по всему тексту записи, как у ребер: ссылка, разорванная
|
||||
# переносом («ст. 34\nГК РФ»), построчно читалась бы кодексом раздела,
|
||||
# и ребро с якорем расходились (замечание приемки T312, круг 5).
|
||||
# Номер точный («34» не входит ни в «34.1», ни в «134»).
|
||||
text = str(node.get("text") or "")
|
||||
for start, _end, num, slug in article_refs(text, _section_code(node.get("section"))):
|
||||
if num == number and slug == code_slug:
|
||||
return f"L{int(base.group(1)) + text.count(chr(10), 0, start)}"
|
||||
return None
|
||||
|
||||
|
||||
def _norm_cite_line(node: dict, article_id: str) -> str | None:
|
||||
"""Строка записи практики для via-ребра «…:code:<slug>:article:<N>»."""
|
||||
match = re.search(r":code:([^:]+):article:(\d+(?:\.\d+)*)$", str(article_id))
|
||||
if not match:
|
||||
return None
|
||||
return practice_cite_line(node, match.group(1), match.group(2))
|
||||
|
||||
|
||||
def search(root: Path | str, query: str, limit: int = 10) -> dict:
|
||||
"""Бесплатный Unicode full-text поиск с соседями графа и проверкой источников hits."""
|
||||
if not isinstance(query, str) or not query.strip() or not 1 <= limit <= 100:
|
||||
@@ -787,12 +1177,15 @@ def search(root: Path | str, query: str, limit: int = 10) -> dict:
|
||||
index = json.loads((snapshot / "search-index.json").read_text(encoding="utf-8"))
|
||||
graph = json.loads((snapshot / "graphify-out/graph.json").read_text(encoding="utf-8"))
|
||||
candidate_nodes = index.get("nodes", [])
|
||||
# Индекс уже загружен целиком — соседи берутся из него бесплатно.
|
||||
by_id_all: dict | None = {node.get("id"): node for node in candidate_nodes}
|
||||
neighbors: dict[str, set[str]] = {}
|
||||
for edge in graph.get("links", graph.get("edges", [])):
|
||||
neighbors.setdefault(edge.get("source"), set()).add(edge.get("target"))
|
||||
neighbors.setdefault(edge.get("target"), set()).add(edge.get("source"))
|
||||
else:
|
||||
candidate_nodes, neighbors = sqlite_result
|
||||
by_id_all = None
|
||||
except (OSError, ValueError, sqlite3.Error):
|
||||
return {"status": "failed", "query": query, "hits": [], "needs_review": True}
|
||||
scored = []
|
||||
@@ -811,9 +1204,13 @@ def search(root: Path | str, query: str, limit: int = 10) -> dict:
|
||||
scored.append((score, node.get("id", ""), node))
|
||||
scored.sort(key=lambda item: (-item[0], item[1]))
|
||||
documents = {item.get("resource_id"): item for item in manifest.get("documents", [])}
|
||||
verified = {}
|
||||
hits, out_of_sync = [], False
|
||||
for score, _, node in scored[:limit]:
|
||||
verified: dict[str, bool] = {}
|
||||
|
||||
def source_state(node: dict) -> tuple[bool, bool]:
|
||||
"""(источник разошелся с манифестом, истек срок проверки источника).
|
||||
|
||||
Одна проверка для прямых хитов и для практики, поднятой по ребрам:
|
||||
измененный индекс практики не должен выдаваться за актуальный."""
|
||||
resource_id = node.get("resource_id")
|
||||
if resource_id not in verified:
|
||||
item = documents.get(resource_id, {})
|
||||
@@ -822,15 +1219,24 @@ def search(root: Path | str, query: str, limit: int = 10) -> dict:
|
||||
verified[resource_id] = _sha(path.read_bytes()) == item.get("raw_sha256")
|
||||
except (OSError, ValueError):
|
||||
verified[resource_id] = False
|
||||
stale = not verified[resource_id]
|
||||
out_of_sync |= stale
|
||||
checked = _parse_time(node.get("last_checked"))
|
||||
checked_age = _now() - checked if checked else None
|
||||
source_due = checked_age is None or checked_age > WEEK or checked_age < timedelta(0)
|
||||
return (not verified[resource_id],
|
||||
checked_age is None or checked_age > WEEK or checked_age < timedelta(0))
|
||||
|
||||
hits, out_of_sync = [], False
|
||||
for score, _, node in scored[:limit]:
|
||||
stale, source_due = source_state(node)
|
||||
out_of_sync |= stale
|
||||
hits.append({
|
||||
"id": node.get("id"), "label": node.get("label"), "kind": node.get("kind"),
|
||||
"text": node.get("text"), "score": score,
|
||||
"resource_id": resource_id, "source_file": node.get("source_file"),
|
||||
"resource_id": node.get("resource_id"),
|
||||
"source_file": node.get("source_file"),
|
||||
"source_location": node.get("source_location"),
|
||||
# Раздел записи практики нужен practice_cite_line: голая ссылка
|
||||
# наследует кодекс раздела (замечание приемки T312, круг 2).
|
||||
"section": node.get("section"),
|
||||
"source_url": node.get("source_url"), "revision": node.get("revision"),
|
||||
"last_checked": node.get("last_checked"),
|
||||
"needs_review": bool(node.get("needs_review")) or stale or source_due,
|
||||
@@ -841,7 +1247,59 @@ def search(root: Path | str, query: str, limit: int = 10) -> dict:
|
||||
built = _parse_time(report.get("built_at"))
|
||||
graph_age = _now() - built if built else None
|
||||
graph_due = graph_age is None or graph_age > WEEK or graph_age < timedelta(0)
|
||||
needs_review = graph_due or out_of_sync or any(hit["needs_review"] for hit in hits)
|
||||
# Запрос по норме обязан вернуть и связанную практику: записи индекса не
|
||||
# несут слова «статья», поэтому прямым FTS они не берутся — поднимаем их
|
||||
# по ребрам от найденных статей. Пометка via: это связь, а не текстовый хит.
|
||||
# Практика — полноправный хит: ее источник проверен выше через
|
||||
# source_state, а итоговый needs_review считается ПОСЛЕ этого блока.
|
||||
seen = {hit["id"] for hit in hits}
|
||||
wanted: set[str] = set()
|
||||
for hit in hits:
|
||||
if hit["kind"] in {"article", "point"}:
|
||||
wanted.update(hit.get("neighbors", []))
|
||||
wanted -= seen
|
||||
if by_id_all is not None:
|
||||
by_id = by_id_all
|
||||
else:
|
||||
# Сбой чтения соседей — отказ, а не пустой словарь: иначе выдача
|
||||
# теряла связанную практику молча (замечание приемки T312, круг 5).
|
||||
try:
|
||||
by_id = _sqlite_nodes_by_id(snapshot, wanted)
|
||||
except (OSError, ValueError, sqlite3.Error):
|
||||
by_id = None
|
||||
if by_id is None:
|
||||
return {"status": "failed", "query": query, "hits": [],
|
||||
"needs_review": True,
|
||||
"error": "соседи хитов не читаются из search.sqlite3"}
|
||||
for hit in list(hits):
|
||||
if hit["kind"] not in {"article", "point"}:
|
||||
continue
|
||||
for neighbor in hit.get("neighbors", []):
|
||||
node = by_id.get(neighbor)
|
||||
if not node or node.get("kind") != PRACTICE_KIND or neighbor in seen:
|
||||
continue
|
||||
seen.add(neighbor)
|
||||
stale, source_due = source_state(node)
|
||||
out_of_sync |= stale
|
||||
hits.append({
|
||||
"id": node["id"], "label": node.get("label"), "kind": PRACTICE_KIND,
|
||||
"text": node.get("text"), "score": hit["score"] - 1,
|
||||
"via": hit["id"],
|
||||
"via_location": _norm_cite_line(node, hit["id"]),
|
||||
"resource_id": node.get("resource_id"),
|
||||
"source_file": node.get("source_file"),
|
||||
"source_location": node.get("source_location"),
|
||||
"section": node.get("section"),
|
||||
"source_url": node.get("source_url"),
|
||||
"revision": node.get("revision"),
|
||||
"last_checked": node.get("last_checked"),
|
||||
"needs_review": (bool(node.get("needs_review")) or stale
|
||||
or source_due),
|
||||
"source_due": source_due, "source_out_of_sync": stale,
|
||||
"neighbors": sorted(neighbors.get(neighbor, set())),
|
||||
})
|
||||
needs_review = (graph_due or out_of_sync or bool(report.get("needs_review"))
|
||||
or any(hit["needs_review"] for hit in hits))
|
||||
return {
|
||||
"status": "needs_review" if needs_review else "ok", "query": query,
|
||||
"snapshot": snapshot.name, "hits": hits, "source_out_of_sync": out_of_sync,
|
||||
@@ -866,6 +1324,12 @@ def main(argv: list[str] | None = None) -> int:
|
||||
ap.error("--force применяется только с --refresh")
|
||||
result = (refresh(args.root, args.force) if args.refresh else status(args.root)
|
||||
if args.status else search(args.root, args.query, args.limit))
|
||||
# Чистый клон: snapshot еще не строился. Строим локально и повторяем —
|
||||
# REQ-18: --status и --query обязаны давать код 0 без ручного --refresh.
|
||||
if result.get("status") == "missing" and not args.refresh:
|
||||
if refresh(args.root).get("status") in {"updated", "current"}:
|
||||
result = (status(args.root) if args.status
|
||||
else search(args.root, args.query, args.limit))
|
||||
if args.json:
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
|
||||
Reference in New Issue
Block a user