diff --git a/scripts/ai_review.py b/scripts/ai_review.py index 121d5d9..2e5c33f 100644 --- a/scripts/ai_review.py +++ b/scripts/ai_review.py @@ -1,23 +1,22 @@ #!/usr/bin/env python3 """ -AI Code Review for Filwords PL Backend (JSON-контракт) +AI Code Review for Filwords PL Backend (JSON-контракт + пак-подход) -Читает Python-файлы проекта, отправляет в DeepSeek V4.1 Flash (Together AI), -получает структурированный JSON с находками, проверяет snippet по диску, -фильтрует по confidence и создаёт Issue в Gitea. - -Запускается через Gitea Actions (workflow_dispatch — вручную из UI). +Backend слишком большой (~440K символов) для одного запроса — модель уходит +в reasoning и не успевает выдать JSON. Решение: разбиваем файлы на 3 пака +по папкам, делаем отдельный запрос на каждый пак, объединяем находки. (20.09.2026) Первая версия — конвейер без tool-calling, предсказуемо по токенам. (20.09.2026, вечер) Фикс: max_tokens=16000, fallback на reasoning_content. (21.09.2026, вечер) JSON-контракт + snippet-проверка + фильтр confidence. +(22.09.2026, вечер) Пак-подход: 3 пака (routers, core, services+scripts). """ import json import os import re import sys -from datetime import datetime +from datetime import datetime, timezone from pathlib import Path import httpx @@ -31,29 +30,50 @@ GITEA_INSTANCE = os.environ.get("GITEA_INSTANCE", "https://git.filwordspl.com") GITEA_REPO = os.environ.get("GITEA_REPO", "Drobysh/filwordspl-backend") MODEL = "deepseek-ai/DeepSeek-V4.1-Flash" - -# 🔧 ФИКС (20.09.2026): было 4000 — DeepSeek V4.1 Flash тратит ~4000 на reasoning, -# не оставляя токенов на финальный ответ. 16000 хватает с запасом. -MAX_OUTPUT_TOKENS = 16000 +MAX_OUTPUT_TOKENS = 12000 # Что игнорировать при сборе кода IGNORE_DIRS = { "venv", ".venv", "__pycache__", ".git", ".gitea", "tests", "archive", "uploads", "tts_cache", - "node_modules", "dist", + "node_modules", "dist", "learning_data", +} +IGNORE_FILES = { + "ai_review.py", "conftest.py", "code_summary.py", + "add_levels.py", "generate_levels_v2.py", } -IGNORE_FILES = {"ai_review.py", "conftest.py"} # Расширения, которые читаем INCLUDE_EXTENSIONS = {".py"} -# Максимальный размер одного файла (символов) — большие контент-файлы пропускаем +# Максимальный размер одного файла (символов) MAX_FILE_SIZE = 100_000 -# 🔧 НОВОЕ (21.09.2026): фильтр находок +# Фильтр находок MIN_CONFIDENCE = 0.7 ALLOWED_SEVERITY = {"user_impact", "data_risk", "maintainability"} -ALLOWED_EXTENSIONS = {".py"} + + +# 🔧 НОВОЕ (22.09.2026): паки для backend +# Backend ~440K символов — не влезает в один запрос (finish=length). +# Разбиваем на 3 пака. Каждый пак — отдельный запрос к модели. +PACKS = [ + { + "name": "routers", + "paths": ["routers/"], + "description": "FastAPI-роутеры: эндпоинты, бизнес-логика, работа с БД", + }, + { + "name": "core", + "paths": ["main.py", "database.py", "auth.py", "config.py", "bot.py"], + "description": "Ядро: main (rate limiter, CORS), database (схема), auth (HMAC), config", + }, + { + "name": "services", + "paths": ["services/", "scripts/"], + "description": "Сервисы и скрипты автоматизации", + }, +] # ============ Проверка окружения ============ @@ -69,48 +89,62 @@ def check_env() -> None: sys.exit(1) -# ============ Сбор кода ============ +# ============ Сбор кода одного пака ============ -def collect_code(repo_root: Path) -> tuple[str, dict[str, str]]: - """ - Собирает все .py файлы в один текст с заголовками. - Возвращает (собранный_текст, словарь {относительный_путь: содержимое}). - Словарь нужен для snippet-проверки. - """ +def read_file(path: Path, repo_root: Path) -> tuple[str, str] | None: + """Читает один файл. Возвращает (относительный_путь, содержимое) или None.""" + try: + content = path.read_text(encoding="utf-8") + except Exception as e: + print(f"⚠️ Не прочитал {path.relative_to(repo_root)}: {e}", file=sys.stderr) + return None + + if len(content) > MAX_FILE_SIZE: + print(f"⚠️ Пропущен большой файл: {path.relative_to(repo_root)} ({len(content)} символов)", file=sys.stderr) + return None + + rel_str = str(path.relative_to(repo_root)).replace("\\", "/") + return rel_str, content + + +def collect_pack(repo_root: Path, pack: dict) -> tuple[str, dict[str, str]]: + """Собирает файлы одного пака. Возвращает (текст, словарь {путь: содержимое}).""" chunks: list[str] = [] files_map: dict[str, str] = {} - total_files = 0 total_size = 0 - for path in sorted(repo_root.rglob("*")): - if not path.is_file(): - continue - if path.suffix not in INCLUDE_EXTENSIONS: + for path_pattern in pack["paths"]: + target = repo_root / path_pattern + + if not target.exists(): continue - rel = path.relative_to(repo_root) - if any(part in IGNORE_DIRS for part in rel.parts): - continue - if path.name in IGNORE_FILES: - continue + if target.is_file(): + result = read_file(target, repo_root) + if result: + rel_str, content = result + chunks.append(f"### FILE: {rel_str}\n```python\n{content}\n```\n") + files_map[rel_str] = content + total_size += len(content) + else: + for f in sorted(target.rglob("*")): + if not f.is_file(): + continue + if f.suffix not in INCLUDE_EXTENSIONS: + continue + if f.name in IGNORE_FILES: + continue + if any(part in IGNORE_DIRS for part in f.relative_to(repo_root).parts): + continue - try: - content = path.read_text(encoding="utf-8") - except Exception as e: - print(f"⚠️ Не прочитал {rel}: {e}", file=sys.stderr) - continue + result = read_file(f, repo_root) + if result: + rel_str, content = result + chunks.append(f"### FILE: {rel_str}\n```python\n{content}\n```\n") + files_map[rel_str] = content + total_size += len(content) - if len(content) > MAX_FILE_SIZE: - print(f"⚠️ Пропущен большой файл: {rel} ({len(content)} символов)", file=sys.stderr) - continue - - rel_str = str(rel).replace("\\", "/") - chunks.append(f"### FILE: {rel_str}\n```python\n{content}\n```\n") - files_map[rel_str] = content - total_files += 1 - total_size += len(content) - - print(f"📂 Собрано файлов: {total_files}, символов: {total_size:,}") + print(f" 📦 Пак '{pack['name']}': {len(files_map)} файлов, {total_size:,} символов") return "\n".join(chunks), files_map @@ -143,7 +177,7 @@ SYSTEM_PROMPT = """Ты — опытный техлид и ревьюер Python - maintainability: запах, дубль, устаревший API 2. snippet — ТОЧНАЯ цитата 1-3 строк из файла. Не перефразируй. Если не уверен — не включай находку. 3. confidence — число от 0 до 1. Если меньше 0.7 — не включай. -4. Максимум 15 находок. Только самое важное. +4. Максимум 10 находок за этот пак. 5. НЕ переписывай код. Только описывай, что не так и что сделать. 6. Без воды. Без общих слов. 7. Если проблем нет — верни пустой массив: [] @@ -152,13 +186,11 @@ SYSTEM_PROMPT = """Ты — опытный техлид и ревьюер Python """ -USER_PROMPT_TEMPLATE = """Проанализируй код проекта Filwords PL (backend). +USER_PROMPT_TEMPLATE = """Проанализируй часть кода проекта Filwords PL (backend). -Это FastAPI + PostgreSQL + asyncpg. Есть: -- routers/ — эндпоинты -- services/ — бизнес-логика -- database.py — схема БД -- auth.py — HMAC-SHA256 initData +Это FastAPI + PostgreSQL + asyncpg. + +Пак: **{pack_name}** — {pack_description} Ищи: 1. Баги и логические ошибки @@ -179,11 +211,15 @@ USER_PROMPT_TEMPLATE = """Проанализируй код проекта Filwo # ============ Запрос к Together AI ============ -def call_together(code: str) -> str: - """Отправляет код в DeepSeek V4.1 Flash, возвращает текст ответа.""" - print("🤖 Отправляю код в DeepSeek V4.1 Flash...") +def call_together(code: str, pack: dict) -> str: + """Отправляет код пака в DeepSeek V4.1 Flash.""" + print(f" 🤖 Отправляю пак '{pack['name']}' в DeepSeek V4.1 Flash...") - user_prompt = USER_PROMPT_TEMPLATE.format(code=code) + user_prompt = USER_PROMPT_TEMPLATE.format( + pack_name=pack["name"], + pack_description=pack["description"], + code=code, + ) response = httpx.post( "https://api.together.xyz/v1/chat/completions", @@ -204,33 +240,28 @@ def call_together(code: str) -> str: ) if response.status_code != 200: - print(f"❌ Together AI вернул {response.status_code}", file=sys.stderr) - print(f"Ответ: {response.text[:1000]}", file=sys.stderr) - sys.exit(1) + print(f" ❌ Together AI вернул {response.status_code}", file=sys.stderr) + print(f" Ответ: {response.text[:500]}", file=sys.stderr) + return "" data = response.json() try: message = data["choices"][0]["message"] result = message.get("content") - - # 🔧 ФИКС (20.09.2026): если content пустой — используем reasoning_content. if not result: result = message.get("reasoning_content") - if not result: - raise KeyError("и content, и reasoning_content пустые") + raise KeyError("пусто") except (KeyError, IndexError, TypeError) as e: - print(f"❌ Неожиданный формат ответа: {e}", file=sys.stderr) - print(f"Полный ответ: {data}", file=sys.stderr) - sys.exit(1) + print(f" ❌ Формат ответа: {e}", file=sys.stderr) + return "" usage = data.get("usage", {}) finish = data["choices"][0].get("finish_reason", "unknown") print( - f"✅ Ответ получен. Токены: вход={usage.get('prompt_tokens', 0)}, " - f"выход={usage.get('completion_tokens', 0)}, " - f"finish={finish}" + f" ✅ Пак '{pack['name']}': вход={usage.get('prompt_tokens', 0)}, " + f"выход={usage.get('completion_tokens', 0)}, finish={finish}" ) return result @@ -239,22 +270,18 @@ def call_together(code: str) -> str: # ============ Парсинг и фильтрация JSON ============ def extract_json(text: str) -> list[dict]: - """ - Извлекает JSON-массив из ответа модели. - Модель может обернуть в ```json ... ``` или добавить текст — чистим. - """ - # Убираем markdown-обёртки + """Извлекает JSON-массив из ответа модели.""" + if not text: + return [] text = text.strip() if text.startswith("```"): - # Убираем ```json в начале и ``` в конце text = re.sub(r"^```(?:json)?\s*", "", text) text = re.sub(r"\s*```$", "", text) - # Ищем JSON-массив start = text.find("[") end = text.rfind("]") if start == -1 or end == -1 or end < start: - print(f"⚠️ Не найден JSON-массив в ответе. Первые 500 символов:\n{text[:500]}", file=sys.stderr) + print(f" ⚠️ Не найден JSON-массив. Первые 300 символов:\n{text[:300]}", file=sys.stderr) return [] json_str = text[start:end + 1] @@ -262,12 +289,11 @@ def extract_json(text: str) -> list[dict]: try: parsed = json.loads(json_str) if not isinstance(parsed, list): - print(f"⚠️ JSON не массив, а {type(parsed).__name__}", file=sys.stderr) + print(f" ⚠️ JSON не массив, а {type(parsed).__name__}", file=sys.stderr) return [] return parsed except json.JSONDecodeError as e: - print(f"⚠️ Ошибка парсинга JSON: {e}", file=sys.stderr) - print(f"Первые 500 символов JSON:\n{json_str[:500]}", file=sys.stderr) + print(f" ⚠️ Ошибка парсинга JSON: {e}", file=sys.stderr) return [] @@ -275,26 +301,11 @@ def validate_and_filter( findings: list[dict], files_map: dict[str, str], ) -> tuple[list[dict], dict[str, int]]: - """ - Фильтрует находки: - - файл существует - - расширение разрешено - - snippet реально есть в файле - - severity валидна - - confidence >= MIN_CONFIDENCE - - есть user_effect и repro (для user_impact и data_risk) - Возвращает (отфильтрованные, статистика). - """ + """Фильтрует находки: файл существует, snippet совпал, confidence ≥ 0.7, severity валидна.""" stats = { "total": len(findings), - "no_file": 0, - "bad_ext": 0, - "no_snippet": 0, - "snippet_mismatch": 0, - "bad_severity": 0, - "low_confidence": 0, - "no_effect_or_repro": 0, - "passed": 0, + "no_file": 0, "snippet_mismatch": 0, "bad_severity": 0, + "low_confidence": 0, "no_effect_or_repro": 0, "passed": 0, } passed: list[dict] = [] @@ -307,56 +318,31 @@ def validate_and_filter( severity = (f.get("severity") or "").strip().lower() confidence = f.get("confidence", 0) - # Файл существует? if file_path not in files_map: stats["no_file"] += 1 - print(f" ⏭ Отброшено (нет файла): {file_path}") continue - # Расширение? - ext = "." + file_path.rsplit(".", 1)[-1] if "." in file_path else "" - if ext not in ALLOWED_EXTENSIONS: - stats["bad_ext"] += 1 - print(f" ⏭ Отброшено (расширение {ext}): {file_path}") - continue - - # Snippet есть? - if not snippet: - stats["no_snippet"] += 1 - print(f" ⏭ Отброшено (нет snippet): {file_path}") - continue - - # Snippet реально есть в файле? - file_content = files_map[file_path] - if snippet not in file_content: + if not snippet or snippet not in files_map[file_path]: stats["snippet_mismatch"] += 1 - print(f" ⏭ Отброшено (snippet не найден): {file_path}") continue - # Severity? if severity not in ALLOWED_SEVERITY: stats["bad_severity"] += 1 - print(f" ⏭ Отброшено (severity={severity}): {file_path}") continue - # Confidence? try: conf_val = float(confidence) except (TypeError, ValueError): conf_val = 0 if conf_val < MIN_CONFIDENCE: stats["low_confidence"] += 1 - print(f" ⏭ Отброшено (confidence={conf_val}): {file_path}") continue - # Для user_impact и data_risk нужны user_effect и repro if severity in ("user_impact", "data_risk"): if not (f.get("user_effect") or "").strip() or not (f.get("repro") or "").strip(): stats["no_effect_or_repro"] += 1 - print(f" ⏭ Отброшено (нет user_effect/repro): {file_path}") continue - # Прошло passed.append(f) stats["passed"] += 1 @@ -365,12 +351,7 @@ def validate_and_filter( # ============ Форматирование Issue ============ -SEVERITY_EMOJI = { - "user_impact": "🔴", - "data_risk": "🟠", - "maintainability": "🟡", -} - +SEVERITY_EMOJI = {"user_impact": "🔴", "data_risk": "🟠", "maintainability": "🟡"} SEVERITY_LABEL = { "user_impact": "Влияет на ученика", "data_risk": "Риск для данных", @@ -378,28 +359,35 @@ SEVERITY_LABEL = { } -def format_issue_body(findings: list[dict], stats: dict[str, int], date_str: str) -> str: - """Формирует markdown-тело Issue из отфильтрованных находок.""" +def format_issue_body( + all_findings: list[dict], + pack_stats: list[dict], + total_stats: dict[str, int], + date_str: str, +) -> str: + """Формирует markdown-тело Issue.""" lines: list[str] = [] - lines.append(f"# 🤖 AI Code Review") + lines.append("# 🤖 AI Code Review (Backend)") lines.append("") lines.append(f"**Дата:** {date_str}") lines.append(f"**Модель:** `{MODEL}`") lines.append(f"**Репозиторий:** `{GITEA_REPO}`") lines.append("") + lines.append("## 📊 По пакам") + lines.append("") + for ps in pack_stats: + lines.append(f"- **{ps['name']}** — {ps['files']} файлов, " + f"{ps['symbols']:,} символов, находок={ps['findings']}") + lines.append("") lines.append("---") lines.append("") - if not findings: + if not all_findings: lines.append("✅ **После фильтрации не осталось находок.**") - lines.append("") - lines.append("_Модель либо не нашла реальных проблем, либо все находки отброшены фильтром (нет файла, snippet не совпал, confidence < 0.7)._") else: - # Группируем по severity by_severity: dict[str, list[dict]] = {"user_impact": [], "data_risk": [], "maintainability": []} - for f in findings: - sev = f.get("severity", "maintainability") - by_severity.setdefault(sev, []).append(f) + for f in all_findings: + by_severity.setdefault(f.get("severity", "maintainability"), []).append(f) counter = 0 for sev in ["user_impact", "data_risk", "maintainability"]: @@ -422,9 +410,10 @@ def format_issue_body(findings: list[dict], stats: dict[str, int], date_str: str lines.append("---") lines.append("") - lines.append(f"**Статистика фильтрации:** всего={stats['total']}, " - f"нет файла={stats['no_file']}, snippet не совпал={stats['snippet_mismatch']}, " - f"низкий confidence={stats['low_confidence']}, прошло={stats['passed']}") + lines.append(f"**Итого:** всего находок={total_stats['total']}, " + f"snippet не совпал={total_stats['snippet_mismatch']}, " + f"низкий confidence={total_stats['low_confidence']}, " + f"прошло={total_stats['passed']}") lines.append("") lines.append("_Этот Issue создан автоматически. Исправления делаются вручную._") @@ -443,10 +432,7 @@ def create_issue(title: str, body: str) -> str: "Authorization": f"token {GITEA_BOT_TOKEN}", "Content-Type": "application/json", }, - json={ - "title": title, - "body": body, - }, + json={"title": title, "body": body}, timeout=30.0, ) @@ -468,28 +454,45 @@ def main() -> None: repo_root = Path(".").resolve() print(f"📁 Репозиторий: {repo_root}") - code, files_map = collect_code(repo_root) - if not code: - print("❌ Не найдено файлов для анализа", file=sys.stderr) - sys.exit(1) + all_passed: list[dict] = [] + pack_stats: list[dict] = [] + total_stats = { + "total": 0, "no_file": 0, "snippet_mismatch": 0, + "bad_severity": 0, "low_confidence": 0, + "no_effect_or_repro": 0, "passed": 0, + } - raw_response = call_together(code) + for pack in PACKS: + print(f"\n📦 Обрабатываю пак: {pack['name']}") + code, files_map = collect_pack(repo_root, pack) - # Парсим JSON - findings = extract_json(raw_response) - print(f"📊 Модель вернула находок: {len(findings)}") + if not code: + print(f" ⚠️ Пак '{pack['name']}' пуст — пропускаю") + pack_stats.append({"name": pack["name"], "files": 0, "symbols": 0, "findings": 0}) + continue - # Фильтруем - filtered, stats = validate_and_filter(findings, files_map) - print(f"✅ Прошло фильтр: {stats['passed']} из {stats['total']}") - print(f" Отброшено: файл={stats['no_file']}, snippet={stats['snippet_mismatch']}, " - f"confidence={stats['low_confidence']}, severity={stats['bad_severity']}, " - f"нет эффекта={stats['no_effect_or_repro']}") + raw = call_together(code, pack) + findings = extract_json(raw) + filtered, stats = validate_and_filter(findings, files_map) - # Формируем Issue - date_str = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC") - title = f"🤖 AI Review: {stats['passed']} задач ({date_str})" - body = format_issue_body(filtered, stats, date_str) + all_passed.extend(filtered) + for k in total_stats: + total_stats[k] += stats.get(k, 0) + + pack_stats.append({ + "name": pack["name"], + "files": len(files_map), + "symbols": sum(len(c) for c in files_map.values()), + "findings": len(filtered), + }) + + print(f" ✅ Пак '{pack['name']}': прошло фильтр {stats['passed']} из {stats['total']}") + + print(f"\n📊 ИТОГО: прошло фильтр {total_stats['passed']} из {total_stats['total']}") + + date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + title = f"🤖 AI Review (backend): {total_stats['passed']} задач ({date_str})" + body = format_issue_body(all_passed, pack_stats, total_stats, date_str) create_issue(title, body) print("🎉 Готово!")