feat(ai-review): пак-подход для frontend — 4 пака вместо одного запроса (21.09.2026)
This commit is contained in:
+169
-107
@@ -1,22 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AI Code Review for Filwords PL Frontend (JSON-контракт)
|
||||
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).
|
||||
Frontend слишком большой (1M+ символов) для одного запроса — модель уходит
|
||||
в reasoning и не успевает выдать JSON. Решение: разбиваем файлы на паки
|
||||
по папкам, делаем отдельный запрос на каждый пак, объединяем находки.
|
||||
|
||||
(21.09.2026) Первая версия для frontend — адаптация backend-скрипта.
|
||||
Читает .ts/.tsx/.js/.jsx, игнорирует node_modules/dist/public.
|
||||
(21.09.2026, вечер) Пак-подход: 4 пака (components, pages, core, admin).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
@@ -30,7 +28,7 @@ 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
|
||||
MAX_OUTPUT_TOKENS = 12000
|
||||
|
||||
# Что игнорировать при сборе кода
|
||||
IGNORE_DIRS = {
|
||||
@@ -50,6 +48,34 @@ MIN_CONFIDENCE = 0.7
|
||||
ALLOWED_SEVERITY = {"user_impact", "data_risk", "maintainability"}
|
||||
|
||||
|
||||
# 🔧 НОВОЕ (21.09.2026): паки для frontend
|
||||
# Каждый пак — отдельный запрос к модели. Файлы одного пака собираются в один текст.
|
||||
# Если пак получается > 500K символов — модель может не успеть. В таком случае
|
||||
# дроби ещё мельче (например, по подпапкам components/).
|
||||
PACKS = [
|
||||
{
|
||||
"name": "components",
|
||||
"paths": ["src/components/"],
|
||||
"description": "UI-компоненты: модалки, редакторы, формы",
|
||||
},
|
||||
{
|
||||
"name": "pages",
|
||||
"paths": ["src/pages/"],
|
||||
"description": "Страницы приложения (17 штук)",
|
||||
},
|
||||
{
|
||||
"name": "core",
|
||||
"paths": ["src/App.tsx", "src/api.ts", "src/telegram.ts", "src/main.tsx"],
|
||||
"description": "Ядро: App, api, telegram, входная точка",
|
||||
},
|
||||
{
|
||||
"name": "infra",
|
||||
"paths": ["src/hooks/", "src/i18n/", "src/styles/", "src/data/", "src/types/"],
|
||||
"description": "Инфраструктура: хуки, локализация, стили, данные, типы",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# ============ Проверка окружения ============
|
||||
|
||||
def check_env() -> None:
|
||||
@@ -65,47 +91,65 @@ def check_env() -> None:
|
||||
|
||||
# ============ Сбор кода ============
|
||||
|
||||
def collect_code(repo_root: Path) -> tuple[str, dict[str, str]]:
|
||||
"""Собирает все .ts/.tsx/.js/.jsx файлы в один текст + словарь для 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
|
||||
# Пропускаем .d.ts (типы — не критичны для ревью)
|
||||
if path.name.endswith(".d.ts"):
|
||||
continue
|
||||
if target.is_file():
|
||||
result = read_file(target, repo_root)
|
||||
if result:
|
||||
rel_str, content = result
|
||||
lang = "typescript" if target.suffix in (".ts", ".tsx") else "javascript"
|
||||
chunks.append(f"### FILE: {rel_str}\n```{lang}\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 f.name.endswith(".d.ts"):
|
||||
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
|
||||
lang = "typescript" if f.suffix in (".ts", ".tsx") else "javascript"
|
||||
chunks.append(f"### FILE: {rel_str}\n```{lang}\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("\\", "/")
|
||||
# Определяем язык для 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:,}")
|
||||
print(f" 📦 Пак '{pack['name']}': {len(files_map)} файлов, {total_size:,} символов")
|
||||
return "\n".join(chunks), files_map
|
||||
|
||||
|
||||
@@ -138,26 +182,20 @@ SYSTEM_PROMPT = """Ты — опытный техлид и ревьюер React
|
||||
- maintainability: дубликат компонента, мёртвый код, устаревший API
|
||||
2. snippet — ТОЧНАЯ цитата 1-3 строк из файла. Не перефразируй.
|
||||
3. confidence — число от 0 до 1. Если меньше 0.7 — не включай.
|
||||
4. Максимум 15 находок.
|
||||
4. Максимум 10 находок за этот пак.
|
||||
5. НЕ переписывай код. Только описывай, что не так.
|
||||
6. НЕ включай проблемы, которые относятся к дизайну/стилю (отступы, цвета) — только функционал, безопасность, UX.
|
||||
6. НЕ включай проблемы дизайна/стиля (отступы, цвета) — только функционал, безопасность, UX.
|
||||
7. Если проблем нет — верни пустой массив: []
|
||||
|
||||
Отвечай ТОЛЬКО JSON, без markdown-обёрток.
|
||||
"""
|
||||
|
||||
|
||||
USER_PROMPT_TEMPLATE = """Проанализируй код frontend проекта Filwords PL (Telegram Mini App).
|
||||
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/ — тема, стили
|
||||
|
||||
Пак: **{pack_name}** — {pack_description}
|
||||
|
||||
Ищи:
|
||||
1. Баги и логические ошибки (React hooks, useEffect, state)
|
||||
@@ -179,11 +217,15 @@ USER_PROMPT_TEMPLATE = """Проанализируй код frontend проек
|
||||
|
||||
# ============ Запрос к 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,9 +246,9 @@ 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()
|
||||
|
||||
@@ -216,18 +258,16 @@ def call_together(code: str) -> str:
|
||||
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
|
||||
@@ -237,6 +277,8 @@ def call_together(code: str) -> str:
|
||||
|
||||
def extract_json(text: str) -> list[dict]:
|
||||
"""Извлекает JSON-массив из ответа модели."""
|
||||
if not text:
|
||||
return []
|
||||
text = text.strip()
|
||||
if text.startswith("```"):
|
||||
text = re.sub(r"^```(?:json)?\s*", "", text)
|
||||
@@ -245,7 +287,7 @@ def extract_json(text: str) -> list[dict]:
|
||||
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]
|
||||
@@ -253,17 +295,16 @@ 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 []
|
||||
|
||||
|
||||
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,
|
||||
@@ -282,23 +323,14 @@ def validate_and_filter(findings: list[dict], files_map: dict[str, str]) -> tupl
|
||||
|
||||
if file_path not in files_map:
|
||||
stats["no_file"] += 1
|
||||
print(f" ⏭ Отброшено (нет файла): {file_path}")
|
||||
continue
|
||||
|
||||
if not snippet:
|
||||
if not snippet or snippet not in files_map[file_path]:
|
||||
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:
|
||||
@@ -307,13 +339,11 @@ def validate_and_filter(findings: list[dict], files_map: dict[str, str]) -> tupl
|
||||
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)
|
||||
@@ -332,7 +362,12 @@ SEVERITY_LABEL = {
|
||||
}
|
||||
|
||||
|
||||
def format_issue_body(findings: list[dict], stats: dict[str, int], date_str: str) -> str:
|
||||
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("# 🤖 AI Code Review (Frontend)")
|
||||
@@ -341,14 +376,20 @@ def format_issue_body(findings: list[dict], stats: dict[str, int], date_str: 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("✅ **После фильтрации не осталось находок.**")
|
||||
else:
|
||||
by_severity: dict[str, list[dict]] = {"user_impact": [], "data_risk": [], "maintainability": []}
|
||||
for f in findings:
|
||||
for f in all_findings:
|
||||
by_severity.setdefault(f.get("severity", "maintainability"), []).append(f)
|
||||
|
||||
counter = 0
|
||||
@@ -372,19 +413,19 @@ 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 создан автоматически. Исправления делаются вручную._")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ============ Создание Issue в Gitea ============
|
||||
# ============ Создание Issue ============
|
||||
|
||||
def create_issue(title: str, body: str) -> str:
|
||||
"""Создаёт Issue в Gitea, возвращает URL."""
|
||||
print("📝 Создаю Issue в Gitea...")
|
||||
|
||||
response = httpx.post(
|
||||
@@ -415,24 +456,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)
|
||||
findings = extract_json(raw_response)
|
||||
print(f"📊 Модель вернула находок: {len(findings)}")
|
||||
for pack in PACKS:
|
||||
print(f"\n📦 Обрабатываю пак: {pack['name']}")
|
||||
code, files_map = collect_pack(repo_root, pack)
|
||||
|
||||
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']}")
|
||||
if not code:
|
||||
print(f" ⚠️ Пак '{pack['name']}' пуст — пропускаю")
|
||||
pack_stats.append({"name": pack["name"], "files": 0, "symbols": 0, "findings": 0})
|
||||
continue
|
||||
|
||||
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)
|
||||
raw = call_together(code, pack)
|
||||
findings = extract_json(raw)
|
||||
filtered, stats = validate_and_filter(findings, files_map)
|
||||
|
||||
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 (frontend): {total_stats['passed']} задач ({date_str})"
|
||||
body = format_issue_body(all_passed, pack_stats, total_stats, date_str)
|
||||
|
||||
create_issue(title, body)
|
||||
print("🎉 Готово!")
|
||||
|
||||
Reference in New Issue
Block a user