499 lines
18 KiB
Python
499 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
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).
|
|
|
|
(20.09.2026) Первая версия — конвейер без tool-calling, предсказуемо по токенам.
|
|
(20.09.2026, вечер) Фикс: max_tokens=16000, fallback на reasoning_content.
|
|
(21.09.2026, вечер) JSON-контракт + snippet-проверка + фильтр confidence.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
|
|
|
|
# ============ Настройки ============
|
|
|
|
TOGETHER_API_KEY = os.environ.get("TOGETHER_API_KEY")
|
|
GITEA_BOT_TOKEN = os.environ.get("BOT_TOKEN")
|
|
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
|
|
|
|
# Что игнорировать при сборе кода
|
|
IGNORE_DIRS = {
|
|
"venv", ".venv", "__pycache__", ".git", ".gitea",
|
|
"tests", "archive", "uploads", "tts_cache",
|
|
"node_modules", "dist",
|
|
}
|
|
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"}
|
|
|
|
|
|
# ============ Проверка окружения ============
|
|
|
|
def check_env() -> None:
|
|
missing = []
|
|
if not TOGETHER_API_KEY:
|
|
missing.append("TOGETHER_API_KEY")
|
|
if not GITEA_BOT_TOKEN:
|
|
missing.append("BOT_TOKEN")
|
|
if missing:
|
|
print(f"❌ Отсутствуют переменные окружения: {', '.join(missing)}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
|
|
# ============ Сбор кода ============
|
|
|
|
def collect_code(repo_root: Path) -> tuple[str, dict[str, str]]:
|
|
"""
|
|
Собирает все .py файлы в один текст с заголовками.
|
|
Возвращает (собранный_текст, словарь {относительный_путь: содержимое}).
|
|
Словарь нужен для snippet-проверки.
|
|
"""
|
|
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:
|
|
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
|
|
|
|
try:
|
|
content = path.read_text(encoding="utf-8")
|
|
except Exception as e:
|
|
print(f"⚠️ Не прочитал {rel}: {e}", file=sys.stderr)
|
|
continue
|
|
|
|
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:,}")
|
|
return "\n".join(chunks), files_map
|
|
|
|
|
|
# ============ Промпт для модели ============
|
|
|
|
SYSTEM_PROMPT = """Ты — опытный техлид и ревьюер Python-кода (FastAPI, asyncpg, PostgreSQL).
|
|
|
|
Твоя задача — проанализировать код и вернуть СТРОГО JSON-массив находок.
|
|
|
|
ФОРМАТ ОТВЕТА (только JSON, без markdown, без пояснений):
|
|
|
|
[
|
|
{
|
|
"id": "КРАТКОЕ_ИМЯ_БАГА",
|
|
"file": "routers/hints.py",
|
|
"line": 20,
|
|
"snippet": "точное цитирование 1-3 строк из файла",
|
|
"severity": "user_impact",
|
|
"user_effect": "что видит ученик: подсказка не списывается, очки завышены",
|
|
"repro": "открыть игру → взять подсказку → hints_used в БД не растёт",
|
|
"fix_hint": "UPDATE ... hints_used = hints_used + 1 в той же транзакции",
|
|
"confidence": 0.86
|
|
}
|
|
]
|
|
|
|
ПРАВИЛА:
|
|
1. severity — только одно из: "user_impact", "data_risk", "maintainability".
|
|
- user_impact: ученик видит баг, теряет прогресс, очки, доступ
|
|
- data_risk: порча БД, утечка, неверный auth/rate-limit
|
|
- maintainability: запах, дубль, устаревший API
|
|
2. snippet — ТОЧНАЯ цитата 1-3 строк из файла. Не перефразируй. Если не уверен — не включай находку.
|
|
3. confidence — число от 0 до 1. Если меньше 0.7 — не включай.
|
|
4. Максимум 15 находок. Только самое важное.
|
|
5. НЕ переписывай код. Только описывай, что не так и что сделать.
|
|
6. Без воды. Без общих слов.
|
|
7. Если проблем нет — верни пустой массив: []
|
|
|
|
Отвечай ТОЛЬКО JSON, без markdown-обёрток.
|
|
"""
|
|
|
|
|
|
USER_PROMPT_TEMPLATE = """Проанализируй код проекта Filwords PL (backend).
|
|
|
|
Это FastAPI + PostgreSQL + asyncpg. Есть:
|
|
- routers/ — эндпоинты
|
|
- services/ — бизнес-логика
|
|
- database.py — схема БД
|
|
- auth.py — HMAC-SHA256 initData
|
|
|
|
Ищи:
|
|
1. Баги и логические ошибки
|
|
2. Проблемы безопасности (утечки, инъекции, неправильная валидация)
|
|
3. N+1 запросы к БД
|
|
4. Отсутствие обработки ошибок
|
|
5. Дублирование кода
|
|
6. Мёртвый код
|
|
7. Слабые места архитектуры
|
|
|
|
Верни JSON-массив находок по формату выше.
|
|
|
|
Вот код:
|
|
|
|
{code}
|
|
"""
|
|
|
|
|
|
# ============ Запрос к Together AI ============
|
|
|
|
def call_together(code: str) -> str:
|
|
"""Отправляет код в DeepSeek V4.1 Flash, возвращает текст ответа."""
|
|
print("🤖 Отправляю код в DeepSeek V4.1 Flash...")
|
|
|
|
user_prompt = USER_PROMPT_TEMPLATE.format(code=code)
|
|
|
|
response = httpx.post(
|
|
"https://api.together.xyz/v1/chat/completions",
|
|
headers={
|
|
"Authorization": f"Bearer {TOGETHER_API_KEY}",
|
|
"Content-Type": "application/json",
|
|
},
|
|
json={
|
|
"model": MODEL,
|
|
"messages": [
|
|
{"role": "system", "content": SYSTEM_PROMPT},
|
|
{"role": "user", "content": user_prompt},
|
|
],
|
|
"max_tokens": MAX_OUTPUT_TOKENS,
|
|
"temperature": 0.2,
|
|
},
|
|
timeout=300.0,
|
|
)
|
|
|
|
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)
|
|
|
|
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 пустые")
|
|
except (KeyError, IndexError, TypeError) as e:
|
|
print(f"❌ Неожиданный формат ответа: {e}", file=sys.stderr)
|
|
print(f"Полный ответ: {data}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
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}"
|
|
)
|
|
|
|
return result
|
|
|
|
|
|
# ============ Парсинг и фильтрация JSON ============
|
|
|
|
def extract_json(text: str) -> list[dict]:
|
|
"""
|
|
Извлекает JSON-массив из ответа модели.
|
|
Модель может обернуть в ```json ... ``` или добавить текст — чистим.
|
|
"""
|
|
# Убираем markdown-обёртки
|
|
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)
|
|
return []
|
|
|
|
json_str = text[start:end + 1]
|
|
|
|
try:
|
|
parsed = json.loads(json_str)
|
|
if not isinstance(parsed, list):
|
|
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)
|
|
return []
|
|
|
|
|
|
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)
|
|
Возвращает (отфильтрованные, статистика).
|
|
"""
|
|
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,
|
|
}
|
|
passed: list[dict] = []
|
|
|
|
for f in findings:
|
|
if not isinstance(f, dict):
|
|
continue
|
|
|
|
file_path = (f.get("file") or "").strip().replace("\\", "/")
|
|
snippet = (f.get("snippet") or "").strip()
|
|
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:
|
|
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
|
|
|
|
return passed, stats
|
|
|
|
|
|
# ============ Форматирование Issue ============
|
|
|
|
SEVERITY_EMOJI = {
|
|
"user_impact": "🔴",
|
|
"data_risk": "🟠",
|
|
"maintainability": "🟡",
|
|
}
|
|
|
|
SEVERITY_LABEL = {
|
|
"user_impact": "Влияет на ученика",
|
|
"data_risk": "Риск для данных",
|
|
"maintainability": "Качество кода",
|
|
}
|
|
|
|
|
|
def format_issue_body(findings: list[dict], stats: dict[str, int], date_str: str) -> str:
|
|
"""Формирует markdown-тело Issue из отфильтрованных находок."""
|
|
lines: list[str] = []
|
|
lines.append(f"# 🤖 AI Code Review")
|
|
lines.append("")
|
|
lines.append(f"**Дата:** {date_str}")
|
|
lines.append(f"**Модель:** `{MODEL}`")
|
|
lines.append(f"**Репозиторий:** `{GITEA_REPO}`")
|
|
lines.append("")
|
|
lines.append("---")
|
|
lines.append("")
|
|
|
|
if not 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)
|
|
|
|
counter = 0
|
|
for sev in ["user_impact", "data_risk", "maintainability"]:
|
|
items = by_severity.get(sev, [])
|
|
if not items:
|
|
continue
|
|
lines.append(f"## {SEVERITY_EMOJI[sev]} {SEVERITY_LABEL[sev]} ({len(items)})")
|
|
lines.append("")
|
|
for f in items:
|
|
counter += 1
|
|
lines.append(f"### {counter}. {f.get('id', 'без имени')}")
|
|
lines.append("")
|
|
lines.append(f"- **Файл:** `{f.get('file')}:{f.get('line', '?')}`")
|
|
lines.append(f"- **Snippet:** `{f.get('snippet', '').strip()[:120]}`")
|
|
lines.append(f"- **Проблема:** {f.get('user_effect', '—')}")
|
|
lines.append(f"- **Как воспроизвести:** {f.get('repro', '—')}")
|
|
lines.append(f"- **Что сделать:** {f.get('fix_hint', '—')}")
|
|
lines.append(f"- **Confidence:** {f.get('confidence', '?')}")
|
|
lines.append("")
|
|
|
|
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("")
|
|
lines.append("_Этот Issue создан автоматически. Исправления делаются вручную._")
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
# ============ Создание Issue в Gitea ============
|
|
|
|
def create_issue(title: str, body: str) -> str:
|
|
"""Создаёт Issue в Gitea, возвращает URL."""
|
|
print("📝 Создаю Issue в Gitea...")
|
|
|
|
response = httpx.post(
|
|
f"{GITEA_INSTANCE}/api/v1/repos/{GITEA_REPO}/issues",
|
|
headers={
|
|
"Authorization": f"token {GITEA_BOT_TOKEN}",
|
|
"Content-Type": "application/json",
|
|
},
|
|
json={
|
|
"title": title,
|
|
"body": body,
|
|
},
|
|
timeout=30.0,
|
|
)
|
|
|
|
if response.status_code not in (200, 201):
|
|
print(f"❌ Gitea вернул {response.status_code}: {response.text[:500]}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
data = response.json()
|
|
issue_url = data.get("html_url", "")
|
|
print(f"✅ Issue создан: {issue_url}")
|
|
return issue_url
|
|
|
|
|
|
# ============ Main ============
|
|
|
|
def main() -> None:
|
|
check_env()
|
|
|
|
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)
|
|
|
|
raw_response = call_together(code)
|
|
|
|
# Парсим JSON
|
|
findings = extract_json(raw_response)
|
|
print(f"📊 Модель вернула находок: {len(findings)}")
|
|
|
|
# Фильтруем
|
|
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']}")
|
|
|
|
# Формируем 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)
|
|
|
|
create_issue(title, body)
|
|
print("🎉 Готово!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |