feat(ai-review): frontend-аудит через Gitea Actions + DeepSeek V4.1 Flash (21.09.2026)
This commit is contained in:
@@ -0,0 +1,442 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AI Code Review for Filwords PL Frontend (JSON-контракт)
|
||||
|
||||
Читает TypeScript/React файлы проекта, отправляет в DeepSeek V4.1 Flash
|
||||
(Together AI), получает структурированный JSON с находками, проверяет
|
||||
snippet по диску, фильтрует по confidence и создаёт Issue в Gitea.
|
||||
|
||||
Запускается через Gitea Actions (workflow_dispatch — вручную из UI).
|
||||
|
||||
(21.09.2026) Первая версия для frontend — адаптация backend-скрипта.
|
||||
Читает .ts/.tsx/.js/.jsx, игнорирует node_modules/dist/public.
|
||||
"""
|
||||
|
||||
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-frontend")
|
||||
|
||||
MODEL = "deepseek-ai/DeepSeek-V4.1-Flash"
|
||||
MAX_OUTPUT_TOKENS = 16000
|
||||
|
||||
# Что игнорировать при сборе кода
|
||||
IGNORE_DIRS = {
|
||||
"node_modules", "dist", "build", ".git", ".gitea",
|
||||
"public", "coverage", ".vite", ".cache",
|
||||
}
|
||||
IGNORE_FILES = {"ai_review.py", "vite-env.d.ts"}
|
||||
|
||||
# Расширения, которые читаем
|
||||
INCLUDE_EXTENSIONS = {".ts", ".tsx", ".js", ".jsx"}
|
||||
|
||||
# Максимальный размер одного файла (символов)
|
||||
MAX_FILE_SIZE = 100_000
|
||||
|
||||
# Фильтр находок
|
||||
MIN_CONFIDENCE = 0.7
|
||||
ALLOWED_SEVERITY = {"user_impact", "data_risk", "maintainability"}
|
||||
|
||||
|
||||
# ============ Проверка окружения ============
|
||||
|
||||
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]]:
|
||||
"""Собирает все .ts/.tsx/.js/.jsx файлы в один текст + словарь для 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
|
||||
# Пропускаем .d.ts (типы — не критичны для ревью)
|
||||
if path.name.endswith(".d.ts"):
|
||||
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("\\", "/")
|
||||
# Определяем язык для markdown-обёртки
|
||||
lang = "typescript" if path.suffix in (".ts", ".tsx") else "javascript"
|
||||
chunks.append(f"### FILE: {rel_str}\n```{lang}\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 = """Ты — опытный техлид и ревьюер React + TypeScript кода (Telegram Mini App).
|
||||
|
||||
Твоя задача — проанализировать код и вернуть СТРОГО JSON-массив находок.
|
||||
|
||||
ФОРМАТ ОТВЕТА (только JSON, без markdown, без пояснений):
|
||||
|
||||
[
|
||||
{
|
||||
"id": "КРАТКОЕ_ИМЯ_БАГА",
|
||||
"file": "src/components/FeedModal.tsx",
|
||||
"line": 120,
|
||||
"snippet": "точное цитирование 1-3 строк из файла",
|
||||
"severity": "user_impact",
|
||||
"user_effect": "что видит пользователь: модалка не закрывается, картинка обрезается",
|
||||
"repro": "открыть Feed → кликнуть по посту → модалка не реагирует на Escape",
|
||||
"fix_hint": "добавить обработчик onKeyDown для Escape в useEffect",
|
||||
"confidence": 0.86
|
||||
}
|
||||
]
|
||||
|
||||
ПРАВИЛА:
|
||||
1. severity — только одно из: "user_impact", "data_risk", "maintainability".
|
||||
- user_impact: пользователь видит баг, ломается UX, не работает кнопка
|
||||
- data_risk: утечка данных, неверная валидация, XSS, утечка токенов в UI
|
||||
- maintainability: дубликат компонента, мёртвый код, устаревший API
|
||||
2. snippet — ТОЧНАЯ цитата 1-3 строк из файла. Не перефразируй.
|
||||
3. confidence — число от 0 до 1. Если меньше 0.7 — не включай.
|
||||
4. Максимум 15 находок.
|
||||
5. НЕ переписывай код. Только описывай, что не так.
|
||||
6. НЕ включай проблемы, которые относятся к дизайну/стилю (отступы, цвета) — только функционал, безопасность, UX.
|
||||
7. Если проблем нет — верни пустой массив: []
|
||||
|
||||
Отвечай ТОЛЬКО JSON, без markdown-обёрток.
|
||||
"""
|
||||
|
||||
|
||||
USER_PROMPT_TEMPLATE = """Проанализируй код frontend проекта Filwords PL (Telegram Mini App).
|
||||
|
||||
Это React 19 + TypeScript + Vite + React Router.
|
||||
Есть:
|
||||
- components/ — модалки, формы, UI-компоненты (Feed, AdminDashboard, LessonEditor, WordsEditor, ...)
|
||||
- pages/ — страницы (17 штук)
|
||||
- api.ts — все запросы к backend
|
||||
- telegram.ts — работа с Telegram WebApp
|
||||
- i18n/ — локализация (PL, RU, UK, EN)
|
||||
- hooks/ — кастомные хуки
|
||||
- styles/ — тема, стили
|
||||
|
||||
Ищи:
|
||||
1. Баги и логические ошибки (React hooks, useEffect, state)
|
||||
2. Проблемы безопасности (XSS, утечки токенов, невалидные URL)
|
||||
3. Проблемы UX (модалки не закрываются, кнопки не работают, скролл)
|
||||
4. Утечки памяти (неотписанные слушатели, таймеры)
|
||||
5. N+1 запросы к API
|
||||
6. Отсутствие обработки ошибок (fetch без catch, loading без finally)
|
||||
7. Дублирование кода и компонентов
|
||||
8. Мёртвый код (неиспользуемые импорты, старые модалки)
|
||||
|
||||
Верни 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")
|
||||
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-массив из ответа модели."""
|
||||
text = text.strip()
|
||||
if text.startswith("```"):
|
||||
text = re.sub(r"^```(?:json)?\s*", "", text)
|
||||
text = re.sub(r"\s*```$", "", text)
|
||||
|
||||
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 совпал, confidence ≥ 0.7, severity валидна."""
|
||||
stats = {
|
||||
"total": len(findings),
|
||||
"no_file": 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
|
||||
|
||||
if not snippet:
|
||||
stats["snippet_mismatch"] += 1
|
||||
print(f" ⏭ Отброшено (нет snippet): {file_path}")
|
||||
continue
|
||||
|
||||
file_content = files_map[file_path]
|
||||
if snippet not in file_content:
|
||||
stats["snippet_mismatch"] += 1
|
||||
print(f" ⏭ Отброшено (snippet не найден): {file_path}")
|
||||
continue
|
||||
|
||||
if severity not in ALLOWED_SEVERITY:
|
||||
stats["bad_severity"] += 1
|
||||
print(f" ⏭ Отброшено (severity={severity}): {file_path}")
|
||||
continue
|
||||
|
||||
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
|
||||
|
||||
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("# 🤖 AI Code Review (Frontend)")
|
||||
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("✅ **После фильтрации не осталось находок.**")
|
||||
else:
|
||||
by_severity: dict[str, list[dict]] = {"user_impact": [], "data_risk": [], "maintainability": []}
|
||||
for f in findings:
|
||||
by_severity.setdefault(f.get("severity", "maintainability"), []).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)
|
||||
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']}")
|
||||
|
||||
date_str = datetime.now(__import__("datetime").UTC).strftime("%Y-%m-%d %H:%M UTC")
|
||||
title = f"🤖 AI Review (frontend): {stats['passed']} задач ({date_str})"
|
||||
body = format_issue_body(filtered, stats, date_str)
|
||||
|
||||
create_issue(title, body)
|
||||
print("🎉 Готово!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user