"""Read models and disposable local search index over the Themiz registry. Only registered public corpus paths enter this database. Search queries are never recorded. Published in-memory views stay readable during indexing. """ from __future__ import annotations import difflib import hashlib import json import re import sqlite3 import threading import time import zlib from bisect import bisect_left from datetime import UTC, datetime, timedelta from pathlib import Path import background_corpus import corpus_registry import legal_graph from cite import CODE_SLUGS def stamp(): return datetime.now(UTC).isoformat().replace('+00:00', 'Z') def normalized(text): return re.sub(r'\s+', ' ', re.sub(r'(?m)^#{1,6}\s+', '', text)).strip() def fragments(resource_id, body): """Stable graph-compatible anchors, with complete non-overlapping text.""" base = legal_graph._graph_id(resource_id) headings = [{'start': match.start(), 'end': match.end(), 'label': match.group(2)} for match in legal_graph.HEADING_RE.finditer(body)] # Synthetic and legacy sources often use plain ``Статья N.`` lines. Keep # them as real fragments so reader/diff selectors do not fall back to the # whole document. Markdown headings remain authoritative on overlap. if not headings: for match in legal_graph.ARTICLE_RE.finditer(body): tail = match.group(2).strip() headings.append({'start': match.start(), 'end': match.end(), 'label': f'Статья {match.group(1)}{(". " + tail) if tail else "."}'}) headings.sort(key=lambda item: item['start']) result = [] for ordinal, match in enumerate(headings, 1): label = match['label'] article = re.match(r'Статья\s+(\d+(?:\.\d+)*(?:-\d+)?)', label, re.I) point = re.match(r'(?:Пункт|п\.)\s*(\d+(?:\.\d+)*)', label, re.I) ident = (f"{base}_article_{article[1].replace('.', '_').replace('-', '_')}" if article else f"{base}_point_{point[1].replace('.', '_')}" if point else f'{base}_heading_{ordinal}') end = headings[ordinal]['start'] if ordinal < len(headings) else len(body) text = body[match['start']:end].strip() anchors = [] if article: for p in legal_graph.POINT_RE.finditer(text): anchor = f"{ident}_point_{p[1].replace('.', '_')}" suffix = 1 while any(a['id'] == anchor for a in anchors): suffix += 1 anchor = f"{ident}_point_{p[1].replace('.', '_')}_{suffix}" anchors.append({'id': anchor, 'number': p[1], 'label': f"{p[1]}.", 'offset': p.start(), 'body_offset': match['start'] + p.start()}) elif len(resource_id.split(':')) > 1 and resource_id.split(':')[1] in {'plenum', 'review'}: for p in legal_graph.POINT_RE.finditer(text): anchor = f"{ident}_point_{p[1].replace('.', '_')}" suffix = 1 while any(a['id'] == anchor for a in anchors): suffix += 1 anchor = f"{ident}_point_{p[1].replace('.', '_')}_{suffix}" anchors.append({'id': anchor, 'number': p[1], 'label': f"{p[1]}.", 'offset': p.start(), 'body_offset': match['start'] + p.start()}) result.append({'id': ident, 'label': label, 'kind': 'article' if article else 'point' if point else 'heading', 'text': text, 'anchors': anchors}) if not result: result = [{'id': base, 'label': 'Текст документа', 'kind': 'document', 'text': body}] elif headings[0]['start'] > 0 and body[:headings[0]['start']].strip(): result.insert(0, {'id': base, 'label': 'Преамбула', 'kind': 'document', 'text': body[:headings[0]['start']]}) return result class Library: def __init__(self, root): self.root = Path(root).resolve() self.state = self.root / '.agent/maintenance/eunomia' self.state.mkdir(parents=True, exist_ok=True) self.db = self.state / 'library.sqlite3' self.lock = threading.Lock() self.documents = {} self.error = None self.indexed_at = None self.signature = None with self.connect() as conn: conn.execute('PRAGMA journal_mode=WAL') conn.execute('CREATE TABLE IF NOT EXISTS versions (id TEXT PRIMARY KEY, resource_id TEXT, raw BLOB, meta TEXT, observed_at TEXT)') conn.execute('CREATE INDEX IF NOT EXISTS versions_resource ON versions(resource_id)') conn.execute('CREATE VIRTUAL TABLE IF NOT EXISTS search USING fts5(resource_id UNINDEXED, fragment_id UNINDEXED, title, label, body, aliases, tokenize="unicode61")') def connect(self): conn = sqlite3.connect(self.db, timeout=10) conn.row_factory = sqlite3.Row return conn def _read(self, resource, raw=None): path = legal_graph._source_path(self.root, resource['output']) if raw is None: if path.stat().st_size > legal_graph.MAX_DOCUMENT_BYTES: raise ValueError('Текст превышает допустимый размер') raw = path.read_bytes() meta, body = legal_graph._frontmatter(raw)[:2] declared = meta.get('sha256', '').removeprefix('sha256:') digest = hashlib.sha256(body.encode()).hexdigest() integrity = declared == digest return raw, meta, body, integrity def _summary(self, resource, meta, body, integrity): headings = fragments(resource['id'], body) if body else [] title = next((x['label'] for x in headings if x['text'].startswith('# ')), None) title = title or resource.get('title') or resource.get('label') or resource.get('entry', {}).get('title') or resource['id'] # Act identity comes from the title/identity line, never the revision date. identity = ' '.join(str(v or '') for v in (resource.get('date'), meta.get('дата_акта'), meta.get('закон'), title)) date_match = re.search(r'\b(\d{2}\.\d{2}\.\d{4})\b', identity) act_date = None if date_match: try: act_date = datetime.strptime(date_match[1], '%d.%m.%Y').strftime('%d.%m.%Y') except ValueError: pass number_match = re.search(r'(?:№|\bN)\s*([\d]+(?:[-/][\w\d]+)*)', identity) number = resource.get('number') or (number_match[1] if number_match else None) paragraphs = [p.strip() for p in body.split('\n\n') if p.strip()] subject = '' if resource['kind'] in {'plenum', 'review'}: for para in paragraphs[1:5]: subject_match = re.search(r'(?:^|\s)(О\s+|Об\s+|По вопросам\s+)(.+)', para) if subject_match and len(para) < 1500: subject = re.sub(r'\s+', ' ', subject_match[0]).strip(' "«»') if subject.isupper(): subject = subject.capitalize() break missing = bool(re.search(r'(?i)НЕ СКАЧАН|не удалось (?:скачать|загрузить)|текст статьи отсутствует', body)) scope = resource.get('entry', {}).get('chapter_scope') coverage = meta.get('coverage', '') full = coverage in {'full', 'complete'} and not missing and integrity status = 'full' if full else 'partial' if missing or scope or coverage in {'partial', 'headings_complete'} else 'unknown' warnings = [] if not integrity and body: warnings.append('Контрольная сумма не подтверждена: требуется сверка') if status == 'partial': warnings.append('Частичный корпус: полнота документа не подтверждена') if status == 'unknown' and body: warnings.append('Полнота текста не подтверждена') checked = meta.get('last_checked') parsed = legal_graph._parse_time(checked) if not parsed or datetime.now(UTC) - parsed > timedelta(days=7) or parsed > datetime.now(UTC): warnings.append('Нет успешной проверки за последние семь дней') if meta.get('source_freshness') == 'mixed_legacy_cache': warnings.append('Смешанная выгрузка: редакции фрагментов могут различаться') kind = resource['kind'] if kind == 'code' and (resource.get('entry', {}).get('slug', '').startswith('fz-') or resource.get('entry', {}).get('slug') == 'zozpp'): kind = 'federal-law' units = [x for x in headings if x['kind'] in {'article', 'point'}] loaded = sum(not re.search(r'(?i)НЕ СКАЧАН|текст статьи отсутствует', x['text']) for x in units) return {'id': resource['id'], 'title': title, 'subject': subject, 'kind': kind, 'source_url': resource['url'], 'revision': meta.get('дата_редакции'), 'act_date': act_date, 'number': number, 'last_checked': checked, 'retrieved_at': meta.get('дата_выгрузки') or meta.get('retrieved_at'), 'effective_date': None, 'available': bool(body), 'integrity': integrity, 'coverage': {'status': status if body else 'missing', 'loaded': loaded, 'total': len(units) or None, 'scope': f'Только глава {scope}' if scope else None}, 'warnings': warnings, 'update': {}} def _save_version(self, conn, resource, raw, *, current=False): try: _, meta, body, integrity = self._read(resource, raw) except (ValueError, UnicodeError, OSError): return # Keep snapshots even when old integrity metadata is absent; disclose it. # A snapshot id must retain whitespace-only revisions: diff() reports # those as formatting changes instead of silently deduplicating them. version_id = hashlib.sha256((resource['id'] + '\n' + body + '\n' + str(meta.get('дата_редакции', ''))).encode()).hexdigest() details = {'id': version_id, 'revision': meta.get('дата_редакции'), 'retrieved_at': meta.get('дата_выгрузки') or meta.get('retrieved_at'), 'effective_date': None, 'source_url': resource['url'], 'integrity': integrity} conn.execute('INSERT OR IGNORE INTO versions VALUES(?,?,?,?,?)', (version_id, resource['id'], zlib.compress(raw), json.dumps(details, ensure_ascii=False), stamp())) return version_id def refresh(self): if not self.lock.acquire(blocking=False): return False try: resources = [r for r in corpus_registry.registry(self.root) if r['kind'] != 'catalog'] stats = [] for r in resources: try: p = legal_graph._source_path(self.root, r['output']) st = p.stat() stats.append((r, st.st_size, st.st_mtime_ns)) except OSError: stats.append((r, None)) signature = hashlib.sha256(json.dumps(stats, sort_keys=True).encode()).hexdigest() if signature == self.signature: return False view = {} with self.connect() as conn: conn.execute('DELETE FROM search') for resource in resources: raw, meta, body, integrity = b'', {}, '', False try: raw, meta, body, integrity = self._read(resource) except (OSError, ValueError, UnicodeError) as exc: problem = str(exc) if not isinstance(exc, FileNotFoundError) else 'Рабочая копия пока отсутствует' else: problem = None summary = self._summary(resource, meta, body, integrity) if problem: summary['warnings'].append(problem) parts = fragments(resource['id'], body) if body else [] version_id = self._save_version(conn, resource, raw, current=True) if raw else None # Import only backups for this exact registered output; never cases/. output = Path(resource['output']) job = self.root / '.agent/maintenance/background/jobs' / hashlib.sha256(resource['id'].encode()).hexdigest() archives = list((job / 'backups' / output.stem).glob('*.md')) archives += list((self.root / 'knowledge/_corpus_archive').glob('*/' + output.name)) for archive in archives: if archive.is_symlink() or archive.stat().st_size > legal_graph.MAX_DOCUMENT_BYTES: continue self._save_version(conn, resource, archive.read_bytes()) aliases = ' '.join(k for k, v in CODE_SLUGS.items() if v == output.stem) search_title = ' '.join(str(x or '') for x in (summary['title'], summary['number'], summary['act_date'])) if not parts: parts_for_index = [{'id': legal_graph._graph_id(resource['id']), 'label': summary['title'], 'text': ''}] else: parts_for_index = parts conn.executemany('INSERT INTO search VALUES(?,?,?,?,?,?)', [(resource['id'], p['id'], search_title, p['label'], p['text'], aliases) for p in parts_for_index]) view[resource['id']] = {'document': summary, 'body': body, 'fragments': parts, 'resource': resource, 'version_id': version_id} self.documents = view self.signature = signature self.indexed_at = stamp() self.error = None return True except Exception as exc: self.error = f'Индекс: {type(exc).__name__}: {exc}' return False finally: self.lock.release() def summaries(self): try: jobs = {j['id']: j for j in background_corpus.status(self.root)['jobs']} except Exception: jobs = {} return [{**v['document'], 'update': jobs.get(k, {})} for k, v in self.documents.items()] def document(self, resource_id): item = self.documents.get(resource_id) if not item: raise KeyError('Документ не зарегистрирован') return {k: v for k, v in item.items() if k in {'document', 'body', 'fragments'}} def resolve_fragment(self, resource_id, location=''): """Resolve an opaque part/anchor ID to its containing fragment.""" item = self.documents.get(resource_id) if not item: raise KeyError('Документ не зарегистрирован') if not location: return None, None for part in item['fragments']: if part['id'] == location: return part, part['id'] if any(anchor.get('id') == location for anchor in part.get('anchors', [])): return part, location return None, None def reader_location(self, resource_id, label, source_location=''): """Resolve a graph label to one exact part or numbered anchor. A bare duplicated point number is intentionally rejected. ``L123`` refers to the source line and is used only to disambiguate candidates. """ item = self.documents.get(resource_id) if not item: raise KeyError('Документ не зарегистрирован') wanted = str(label or '').strip() article_match = re.fullmatch(r'(?i)\s*(?:статья|ст\.)\s*(\d+(?:\.\d+)*)\.?\s*.*', wanted) if article_match: number = article_match[1].replace('.', '_') candidates = [p for p in item['fragments'] if p['id'].endswith(f'_article_{number}')] return candidates[0]['id'] if len(candidates) == 1 else None point_match = re.fullmatch(r'(?i)\s*(?:пункт|п\.)?\s*(\d+(?:\.\d+)*)\.?\s*.*', wanted) if not point_match: return None number = point_match[1].replace('.', '_') part_candidates = [p for p in item['fragments'] if p['kind'] == 'point' and re.search( rf'(?i)^(?:пункт|п\.)\s*{re.escape(point_match[1])}(?:\.|\s|$)', p['label'])] if len(part_candidates) == 1: return part_candidates[0]['id'] candidates = [ (part, anchor) for part in item['fragments'] for anchor in part.get('anchors', []) if anchor.get('number', '').replace('.', '_') == number ] if len(candidates) == 1: return candidates[0][1]['id'] if source_location: line_match = re.search(r'(?i)L(\d+)', str(source_location)) if not line_match: return None line = int(line_match[1]) newline_offsets = item.get('_newline_offsets') if newline_offsets is None: newline_offsets = [match.start() for match in re.finditer('\\n', item['body'])] item['_newline_offsets'] = newline_offsets candidates = [(part, anchor) for part, anchor in candidates if bisect_left(newline_offsets, anchor.get('body_offset', anchor['offset'])) + 1 == line] if len(candidates) != 1: return None return candidates[0][1]['id'] def reader(self, resource_id, fragment=''): """Компактный reader payload: оглавление и один фрагмент по запросу. ``document`` сохраняет прежний payload для совместимости. Reader нужен UI для больших кодексов: повторная выдача всего текста не требуется при переходе к статье. """ item = self.documents.get(resource_id) if not item: raise KeyError('Документ не зарегистрирован') parts = item['fragments'] toc = [] for part in parts: entry = {k: part[k] for k in ('id', 'label', 'kind') if k in part} entry['anchors'] = [ {k: anchor[k] for k in ('id', 'label') if k in anchor} for anchor in part.get('anchors', []) ] toc.append(entry) selected, selected_id = self.resolve_fragment(resource_id, fragment) if not fragment and parts: selected, selected_id = parts[0], parts[0]['id'] return {'document': item['document'], 'toc': toc, 'fragment': selected, 'selected_id': selected_id} def search(self, query, kind='', limit=80): if len(query) > 500: raise ValueError('Запрос длиннее 500 символов') # Quoted phrases stay phrases. Everything else is a literal token, never FTS syntax. terms = re.findall(r'"([^"]+)"|([\w.-]+)', query.lower().replace('ё', 'е')) tokens = [a or b for a, b in terms] tokens = [{'ст.': 'статья', 'ст': 'статья', 'п.': 'пункт', 'п': 'пункт'}.get(t, t) for t in tokens] tokens = [t for t in tokens if t not in {'рф', 'от', '№', 'n'}] if not tokens: return {'results': [], 'total': 0} expression = ' AND '.join('"' + t.replace('"', '""') + '"' for t in tokens) with self.connect() as conn: rows = conn.execute('SELECT resource_id,fragment_id,title,label,body,bm25(search,0,0,5,8,1,6) AS rank FROM search WHERE search MATCH ? ORDER BY rank LIMIT 1500', (expression,)).fetchall() results = [] for row in rows: item = self.documents.get(row['resource_id']) if not item or (kind and item['document']['kind'] != kind): continue doc = item['document'] body = row['body'] body_lower = body.lower() positions = [body_lower.find(t) for t in tokens if body_lower.find(t) >= 0] start = max(0, min(positions or [0]) - 90) excerpt = body[start:start + 380] results.append({'resource_id': doc['id'], 'document': doc['title'], 'title': doc['title'], 'id': row['fragment_id'], 'label': row['label'], 'kind': doc['kind'], 'text': excerpt, 'snippet': excerpt, 'revision': doc['revision'], 'warnings': doc['warnings'], 'source_url': doc['source_url']}) return {'results': results[:limit], 'total': len(results)} def history(self, resource_id): item = self.documents.get(resource_id) if not item: raise KeyError('Документ не зарегистрирован') with self.connect() as conn: rows = conn.execute('SELECT id,meta,observed_at FROM versions WHERE resource_id=? ORDER BY observed_at,id', (resource_id,)).fetchall() versions = [{**json.loads(r['meta']), 'observed_at': r['observed_at'], 'current': r['id'] == item['version_id']} for r in rows] def date_key(v): value = v.get('retrieved_at') or v['observed_at'] try: return datetime.strptime(value, '%d.%m.%Y').isoformat() except ValueError: return value versions.sort(key=date_key) return {'versions': versions, 'observation_started': min((v['observed_at'] for v in versions), default=None), 'note': 'Показаны только доступные копии. Дата получения не означает вступление изменений в силу. Разница текстов сама по себе не подтверждает изменение закона.'} def diff(self, resource_id, before, after, fragment=''): item = self.documents.get(resource_id) if not item: raise KeyError('Документ не зарегистрирован') with self.connect() as conn: rows = [conn.execute('SELECT raw,meta FROM versions WHERE resource_id=? AND id=?', (resource_id, v)).fetchone() for v in (before, after)] if not all(rows): raise KeyError('Снимок не найден') bodies = [legal_graph._frontmatter(zlib.decompress(r['raw']))[1] for r in rows] parts = [{p['id']: p for p in fragments(resource_id, b)} for b in bodies] changes = [] for key in dict.fromkeys([*parts[0], *parts[1]]): old, new = parts[0].get(key), parts[1].get(key) if fragment: selector = fragment.lower() label = (new or old)['label'].lower() selector_match = selector in key.lower() or selector in label match = re.fullmatch(r'(article|point|heading):([\d._-]+)', selector) if match: number = match[2].replace('.', '_').replace('-', '_') selector_match = selector_match or bool(re.search(rf'_{match[1]}_{re.escape(number)}(?:_|$)', key.lower())) if match[1] == 'article': selector_match = selector_match or bool(re.search(rf'(?i)\bСтатья\s+{re.escape(match[2])}(?:\.|\s|$)', (old or {}).get('text', '') + '\n' + (new or {}).get('text', ''))) elif match[1] == 'point': selector_match = selector_match or bool(re.search(rf'(?i)\b(?:Пункт|п\.)\s*{re.escape(match[2])}(?:\.|\s|$)', (old or {}).get('text', '') + '\n' + (new or {}).get('text', ''))) if not selector_match: continue a, b = old['text'] if old else '', new['text'] if new else '' if normalized(a) == normalized(b): continue changes.append({'id': key, 'label': (new or old)['label'], 'kind': 'added' if not old else 'removed' if not new else 'changed', 'before': a, 'after': b, 'lines': list(difflib.unified_diff(a.splitlines(), b.splitlines(), lineterm=''))}) return {'changes': changes, 'before': json.loads(rows[0]['meta']), 'after': json.loads(rows[1]['meta']), 'formatting_only': bodies[0] != bodies[1] and normalized(bodies[0]) == normalized(bodies[1]), 'note': 'Сравнение локальных копий. Дата, когда происходит вступление изменений в силу, и сам текст требуют сверки с актом, который внёс изменения.'}