From 859596b03002ec4ae255475f16b8093eebecfe25 Mon Sep 17 00:00:00 2001 From: hermes Date: Sun, 1 Nov 2026 20:04:26 +0000 Subject: [PATCH] =?UTF-8?q?ci(wiki):=20=D0=BF=D1=83=D0=B1=D0=BB=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=D1=86=D0=B8=D1=8F=20docs/wiki=20=D0=B2=20=D0=B2?= =?UTF-8?q?=D0=B8=D0=BA=D0=B8=20Gitea=20=D0=BD=D0=B0=20push;=20=D0=B8?= =?UTF-8?q?=D0=BD=D0=B4=D0=B5=D0=BA=D1=81=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B2?= =?UTF-8?q?=D0=B8=D0=BA=D0=B8=20=D0=B2=20Qdrant?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - .gitea/workflows/wiki.yml: на push в docs/wiki/** (и правки скриптов) запускается scripts/wiki_publish.py с секретом WIKI_TOKEN (runs-on ubuntu-24.04) - scripts/wiki_ingest_qdrant.py: страницы docs/wiki → коллекция knowledge_base (dense bge-m3 1024, payload как у индексатора vault + source для очистки), режим --search для проверки - scripts/wiki_publish.py: токен берётся также из WIKI_TOKEN (для CI) --- .gitea/workflows/wiki.yml | 39 ++++++++ scripts/wiki_ingest_qdrant.py | 161 ++++++++++++++++++++++++++++++++++ scripts/wiki_publish.py | 3 +- 3 files changed, 202 insertions(+), 1 deletion(-) create mode 100644 .gitea/workflows/wiki.yml create mode 100644 scripts/wiki_ingest_qdrant.py diff --git a/.gitea/workflows/wiki.yml b/.gitea/workflows/wiki.yml new file mode 100644 index 0000000..7fc0130 --- /dev/null +++ b/.gitea/workflows/wiki.yml @@ -0,0 +1,39 @@ +name: wiki-sync + +# Публикация docs/wiki/ в вики репозитория на gitea.nixg.ru. +# Отдельный workflow: падение синка вики не влияет на остальное. +# Источник истины — docs/wiki/ в репозитории; страницы в Gitea обновляет +# scripts/wiki_publish.py (плоские имена, index.md → Home). + +on: + push: + branches: + - master + paths: + - 'docs/wiki/**' + - 'scripts/wiki_publish.py' + - '.gitea/workflows/wiki.yml' + workflow_dispatch: + +jobs: + wiki-sync: + name: Publish docs/wiki to Gitea wiki + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install dependencies + run: | + apt-get update -qq + apt-get install -y -qq python3 git + + - name: Publish wiki + env: + WIKI_TOKEN: ${{ secrets.WIKI_TOKEN }} + GITEA_HOST: https://gitea.nixg.ru + GITEA_WIKI_REPO: hermes/email-assistant + run: | + set -e + test -n "$WIKI_TOKEN" || { echo "ОШИБКА: в настройках репозитория не задан секрет WIKI_TOKEN (Settings -> Actions -> Secrets)"; exit 1; } + python3 scripts/wiki_publish.py diff --git a/scripts/wiki_ingest_qdrant.py b/scripts/wiki_ingest_qdrant.py new file mode 100644 index 0000000..61bb0ef --- /dev/null +++ b/scripts/wiki_ingest_qdrant.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +""" +wiki_ingest_qdrant.py — индексация docs/wiki проекта в Qdrant (knowledge_base). + +Страницы вики проекта попадают в ту же коллекцию, что использует memory-os +search_api, поэтому агент находит их обычным recall-ом (контекст +«[qdrant] knowledge base»). + +Схема payload — как у индексатора vault: filename, path, content, length, title, +chunk_index, chunk_total, indexed_at + source (по нему чистим старые точки). + +Запуск: + python3 scripts/wiki_ingest_qdrant.py --dry-run + python3 scripts/wiki_ingest_qdrant.py + python3 scripts/wiki_ingest_qdrant.py --search "fail2ban Connect" # проверка + +Окружение: OLLAMA_URL (default http://127.0.0.1:11434), +WIKI_EMBED_MODEL (default bge-m3:latest), QDRANT_URL (default http://127.0.0.1:6333), +QDRANT_COLLECTION (default knowledge_base). +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +import urllib.error +import urllib.parse +import urllib.request +import uuid +from datetime import datetime, timezone +from pathlib import Path + +BASE_DIR = Path(__file__).resolve().parents[1] +WIKI_DIR = BASE_DIR / "docs" / "wiki" +SOURCE = "email-assistant/docs/wiki" +NAMESPACE = uuid.UUID("6f9619ff-8b86-d011-b42d-00cf4fc964ff") + +OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434").rstrip("/") +EMBED_MODEL = os.environ.get("WIKI_EMBED_MODEL", "bge-m3:latest") +QDRANT_URL = os.environ.get("QDRANT_URL", "http://127.0.0.1:6333").rstrip("/") +COLLECTION = os.environ.get("QDRANT_COLLECTION", "knowledge_base") + +CHUNK_CHARS = int(os.environ.get("WIKI_CHUNK_CHARS", "1800")) + + +def _request(method: str, url: str, payload: dict | None = None) -> dict: + data = json.dumps(payload).encode("utf-8") if payload is not None else None + request = urllib.request.Request(url, data=data, method=method, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=120) as response: + body = response.read().decode("utf-8") or "{}" + return json.loads(body) + + +def embed(text: str) -> list[float]: + data = _request("POST", f"{OLLAMA_URL}/api/embeddings", + {"model": EMBED_MODEL, "prompt": text}) + vector = data.get("embedding") or [] + if not vector: + raise RuntimeError(f"пустой эмбеддинг от {EMBED_MODEL}") + return vector + + +def split_chunks(text: str) -> list[str]: + """Резать по абзацам, склеивая до CHUNK_CHARS.""" + paragraphs = [p.strip() for p in re.split(r"\n{2,}", text) if p.strip()] + chunks: list[str] = [] + current = "" + for paragraph in paragraphs: + if current and len(current) + len(paragraph) + 2 > CHUNK_CHARS: + chunks.append(current) + current = paragraph + else: + current = f"{current}\n\n{paragraph}" if current else paragraph + if current: + chunks.append(current) + return chunks or [text] + + +def title_of(path: Path, text: str) -> str: + match = re.search(r"^title:\s*(.+)$", text, re.M) + if match: + return match.group(1).strip().strip('"') + for line in text.splitlines(): + if line.startswith("# "): + return line[2:].strip() + return path.stem + + +def delete_old() -> int: + _request("POST", f"{QDRANT_URL}/collections/{COLLECTION}/points/delete?wait=true", + {"filter": {"must": [{"key": "source", "match": {"value": SOURCE}}]}}) + return 0 + + +def search(query: str, limit: int = 5) -> None: + vector = embed(query) + data = _request("POST", f"{QDRANT_URL}/collections/{COLLECTION}/points/search", + {"vector": {"name": "dense", "vector": vector}, + "limit": limit, "with_payload": True, "with_vector": False}) + for point in data.get("result", []): + payload = point.get("payload") or {} + print(f"{point.get('score', 0):.3f} {payload.get('title', '?')} " + f"[{payload.get('source', 'vault')}] {payload.get('path', '')}") + + +def main() -> int: + parser = argparse.ArgumentParser(description="Индексация docs/wiki в Qdrant") + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--search", default="", help="Проверочный поиск по коллекции") + args = parser.parse_args() + + if args.search: + search(args.search) + return 0 + + files = sorted(WIKI_DIR.rglob("*.md")) + if not files: + print(f"В {WIKI_DIR} нет .md", file=sys.stderr) + return 1 + + points: list[dict] = [] + for path in files: + text = path.read_text(encoding="utf-8") + chunks = split_chunks(text) + title = title_of(path, text) + for index, chunk in enumerate(chunks): + points.append({ + "id": str(uuid.uuid5(NAMESPACE, f"{path.relative_to(BASE_DIR)}#{index}")), + "vector": {"dense": embed(chunk)}, + "payload": { + "filename": path.name, + "path": str(path), + "content": chunk, + "length": str(len(chunk)), + "title": title, + "chunk_index": str(index), + "chunk_total": str(len(chunks)), + "indexed_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "source": SOURCE, + }, + }) + + if args.dry_run: + print(f"[dry] файлов={len(files)}, чанков={len(points)}") + for path in files: + print(f" • {path.relative_to(WIKI_DIR)}") + return 0 + + delete_old() + _request("PUT", f"{QDRANT_URL}/collections/{COLLECTION}/points?wait=true", + {"points": points}) + print(f"Проиндексировано: файлов={len(files)}, чанков={len(points)} " + f"(коллекция {COLLECTION}, модель {EMBED_MODEL})") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/wiki_publish.py b/scripts/wiki_publish.py index 07b8d7f..555b593 100755 --- a/scripts/wiki_publish.py +++ b/scripts/wiki_publish.py @@ -56,7 +56,8 @@ _WIKILINK = re.compile(r"\[\[([^\]]+)\]\]") def token() -> str: - value = os.environ.get("GITEA_NIXG_TOKEN") or os.environ.get("GITEA_TOKEN") + value = (os.environ.get("WIKI_TOKEN") or os.environ.get("GITEA_NIXG_TOKEN") + or os.environ.get("GITEA_TOKEN")) if value: return value.strip() try: