diff --git a/.github/scripts/ai_review.py b/.github/scripts/ai_review.py new file mode 100644 index 0000000..a1c5d04 --- /dev/null +++ b/.github/scripts/ai_review.py @@ -0,0 +1,414 @@ +#!/usr/bin/env python3 +"""AI code review gate — được reusable-ai-review.yml gọi. Xem đầu file workflow để biết luồng. + +Tách khỏi `run: |` của YAML vì 2 lẽ: (1) GHA nội suy MỌI biểu thức đô-la-ngoặc-nhọn trong +run-block kể cả trong heredoc — sự cố 15/07 làm vỡ parse cả 16 repo; (2) test được ở local. + +Không phụ thuộc `gh` CLI (self-hosted trần không có): gọi GitHub REST bằng urllib + GH_TOKEN. +""" +import json +import os +import re +import subprocess +import sys +import urllib.error +import urllib.request + +E = os.environ.get +EVENT = E("EVENT", "") +REPO = E("REPO", "") +PROFILE = E("PROFILE", "code") +PR = E("PR", "") +PR_HEAD = E("PR_HEAD_SHA", "") +BEFORE = E("BEFORE", "") +AFTER = E("AFTER", "") or "HEAD" +MODEL = E("MODEL", "") or "ai-review" + +DIFF_LIMIT = 45000 # ký tự diff gửi LLM (~12k token) — trước là 60KB diff + 50KB full file +MAX_TOKENS = 4096 +BLOCK_CONFIDENCE = 0.8 # blocker dưới ngưỡng này chỉ là cảnh báo, không chặn + +MARKER_RE = re.compile(r"") + + +class LLMDown(Exception): + """LLM không trả được kết quả dùng được → fail-open CÓ cảnh báo.""" + + +# ---------------------------------------------------------------- tiện ích +def run_git(*args): + r = subprocess.run(["git", *args], capture_output=True, text=True) + return r.returncode, r.stdout + + +def git(*args): + code, out = run_git(*args) + return out if code == 0 else "" + + +def gh(path, method="GET", data=None): + url = (E("GITHUB_API_URL") or "https://api.github.com") + path + body = json.dumps(data).encode() if data is not None else None + req = urllib.request.Request(url, data=body, method=method, headers={ + "Authorization": "Bearer " + E("GH_TOKEN", ""), + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read() + return json.loads(raw) if raw else None + except Exception as e: # comment/dedupe là phụ — lỗi API không được làm chết gate + print("GitHub API lỗi (bỏ qua):", method, path, str(e)[:150]) + return None + + +# ---------------------------------------------------------------- chọn file +_EXCL_SUFFIX = (".lock", "-lock.json", "lock.yaml", "lock.yml", "go.sum", ".min.js", ".min.css", ".map", + ".svg", ".png", ".jpg", ".jpeg", ".ico", ".gif", ".webp", ".woff", ".woff2", ".ttf", + ".pdf", ".lockb", ".md", ".mdx", ".snap") +_EXCL_PART = ("/dist/", "/build/", "/vendor/", "/node_modules/", "/__generated__/", ".generated.", "/gen/", + "/__snapshots__/") + + +def excluded(path): + """CI/workflow, docs, lock, generated, binary, bản dịch: không đáng tốn token, và review nhầm chính + gate CI (ci-cd.yml) từng làm FAIL oan.""" + q = "/" + path.lower() + if q.startswith(("/.github/", "/docs/")): + return True + if q.endswith(_EXCL_SUFFIX) or any(s in q for s in _EXCL_PART): + return True + return q.endswith(".json") and ("/locales/" in q or "/i18n/" in q) + + +_TAG_LINE = re.compile(r"^[+-]\s*(?:-\s*)?(?PnewTag|tag|image)\s*:\s*['\"]?(?P\S+?)['\"]?\s*$") + + +def tag_only(diff_u0): + """Profile deploy: commit CHỈ đổi tag image (CI ghi newTag) → PASS không cần LLM. + `image:` mới phải giữ nguyên repo/registry của dòng bị thay — đổi sang image lạ vẫn đi LLM.""" + changed = [ln for ln in diff_u0.splitlines() + if ln[:1] in "+-" and not ln.startswith(("+++", "---"))] + if not changed: + return False + old_repos, new_repos = set(), set() + for ln in changed: + m = _TAG_LINE.match(ln) + if not m: + return False + if m["k"] == "image": + repo = m["v"].rsplit("@", 1)[0] + repo = repo.rsplit(":", 1)[0] if ":" in repo.rsplit("/", 1)[-1] else repo + (old_repos if ln[0] == "-" else new_repos).add(repo) + return new_repos <= old_repos + + +# ---------------------------------------------------------------- verdict +_COMPILE_CLAIM = re.compile( + r"(kh[oô]ng\s+(?:compile|build|bi[êe]n\s*d[ịi]ch)|compile[\s-]*error|syntax[\s-]*error|" + r"sai\s*c[uú]\s*ph[áa]p|l[oô]i\s*c[uú]\s*ph[áa]p|build[\s-]*fail|" + r"(?:won'?t|cannot|does\s*not|will\s*not)\s*compile|kh[oô]ng\s*bi[êe]n\s*d[ịi]ch\s*[đd][ưuơợ]?[ơợ]c)", re.I) + + +def normalize_issues(raw): + out = [] + for it in raw if isinstance(raw, list) else []: + if isinstance(it, str): # model trả kiểu cũ (chuỗi) → coi là góp ý + it = {"severity": "minor", "problem": it} + if not isinstance(it, dict): + continue + sev = str(it.get("severity", "minor")).lower() + try: + conf = float(it.get("confidence", 0.5)) + except (TypeError, ValueError): + conf = 0.5 + out.append({ + "severity": sev if sev in ("blocker", "major", "minor") else "minor", + "file": str(it.get("file") or ""), + "line": it.get("line"), + "problem": str(it.get("problem") or "").strip(), + "fix": str(it.get("fix") or "").strip(), + "confidence": conf, + }) + return [i for i in out if i["problem"]] + + +def decide(issues): + """Verdict tính bằng code, KHÔNG tin field verdict của model. + - Bỏ claim compile/syntax: bước build mới là nguồn sự thật (model hay nhầm cú pháp, vd Go elision). + - FAIL ⇔ còn blocker có confidence ≥ ngưỡng.""" + dropped = [i for i in issues if _COMPILE_CLAIM.search(i["problem"] + " " + i["fix"])] + for d in dropped: + print("⏭️ DROP claim compile/syntax (build đã lo):", d["problem"][:180]) + kept = [i for i in issues if i not in dropped] + for i in kept: + if i["severity"] == "blocker" and i["confidence"] < BLOCK_CONFIDENCE: + i["severity"] = "major" # nghi ngờ → cảnh báo, không chặn + verdict = "FAIL" if any(i["severity"] == "blocker" for i in kept) else "PASS" + return verdict, kept + + +# ---------------------------------------------------------------- prompt +CODE_RULES = ( + "BUG/LOGIC: null/None, off-by-one, race, sai điều kiện, thiếu await, sai kiểu dữ liệu runtime. " + "SECURITY: injection (SQL/XSS/command), secret/credential hardcode, thiếu validate input, path traversal, lộ dữ liệu. " + "ERROR-HANDLING: nuốt lỗi, thiếu cleanup/rollback, resource leak. " + "ARCHITECTURE: breaking-change API không migrate, trùng lặp đáng tách." +) +DEPLOY_RULES = ( + "AN TOÀN DEPLOY (manifest k8s / config): không hạ replicas về 0 ngoài ý muốn, không thêm secret cleartext mới, " + "không giảm resource limit/request vô lý (OOM/thiếu), đổi image NÊN chỉ là đổi TAG (đổi image-name/registry lạ phải nghi ngờ), " + "sửa ConfigMap/env phải khớp app (không xoá key app đang dùng), migration/job DB phải an toàn (không mất dữ liệu)." +) +EXAMPLE = ('{"summary":"Thêm API xoá lớp; thiếu kiểm quyền.","issues":[{"severity":"blocker","file":"api/class.go",' + '"line":42,"problem":"DeleteClass không kiểm role admin, user thường xoá được lớp của trường khác.",' + '"fix":"Gọi requireRole(ctx, \\"admin\\") trước khi xoá.","confidence":0.9}]}') + + +def system_prompt(profile): + """Phần TĨNH theo profile — để đầu prompt cho vLLM prefix-cache dùng lại giữa các lần review.""" + role = "senior DevOps review manifest triển khai" if profile == "deploy" else "senior code reviewer" + rules = DEPLOY_RULES if profile == "deploy" else CODE_RULES + return ( + "Bạn là " + role + ". Review DIFF (git diff kèm nguyên hàm bao quanh) theo RULES. " + "Truy vết tác động: data flow, null, edge case, side-effect, tương tác giữa các hàm — không chỉ dòng đổi bề mặt.\n" + "RULES: " + rules + "\n" + "MỨC ĐỘ:\n" + "- blocker: CHẮC CHẮN gây hỏng/nguy hiểm khi chạy (bug rõ, lỗ hổng thật, mất dữ liệu, breaking-change không migrate).\n" + "- major: rủi ro đáng sửa nhưng chưa chắc gây hỏng.\n" + "- minor: góp ý nhỏ.\n" + "KHÔNG báo: style/format/naming, thiếu test, nghi ngờ mơ hồ. " + "KHÔNG báo lỗi compile/cú pháp: pipeline đã build trước bước này, nghĩ là sai cú pháp thì gần như chắc bạn nhầm. " + "File CI/config: chỉ báo lỗ hổng thật; reusable `Techainer/.github/...@main` là nội bộ, tin cậy. " + "confidence (0-1) = độ chắc chắn lỗi là THẬT. Mỗi issue phải nêu file, dòng, vấn đề, cách sửa cụ thể. " + "Không có lỗi → issues rỗng.\n" + "Trả về DUY NHẤT 1 JSON, tiếng Việt có dấu, đúng dạng: " + '{"summary":"1-2 câu: thay đổi làm gì + đánh giá","issues":[{"severity":"blocker|major|minor","file":"...",' + '"line":0,"problem":"...","fix":"...","confidence":0.0}]}\n' + "Ví dụ: " + EXAMPLE + ) + + +def call_llm(system, user): + base = (E("OPENAI_BASE_URL") or "").rstrip("/") + key = E("OPENAI_API_KEY") or "" + if not base or not key: + raise LLMDown("thiếu secret OPENAI_BASE_URL/OPENAI_API_KEY") + payload = {"model": MODEL, "temperature": 0, "max_tokens": MAX_TOKENS, + "response_format": {"type": "json_object"}, + "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]} + try: + payload.update(json.loads(E("LLM_EXTRA_BODY") or "{}")) + except ValueError: + print("LLM_EXTRA_BODY không phải JSON — bỏ qua") + + def post(p): + req = urllib.request.Request(base + "/chat/completions", data=json.dumps(p).encode(), headers={ + "Authorization": "Bearer " + key, "Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=170) as r: + return json.load(r) + + try: + try: + resp = post(payload) + except urllib.error.HTTPError as e: + if e.code != 400: + raise + # backend không nhận tham số phụ (response_format / extra) → thử lại bản tối giản + print("LLM 400 với tham số phụ → thử lại không kèm:", e.read()[:200]) + resp = post({k: payload[k] for k in ("model", "temperature", "max_tokens", "messages")}) + except urllib.error.HTTPError as e: + raise LLMDown("HTTP %s: %s" % (e.code, e.read()[:200].decode("utf-8", "ignore"))) + except Exception as e: + raise LLMDown(type(e).__name__ + ": " + str(e)[:200]) + + choice = (resp.get("choices") or [{}])[0] + content = (choice.get("message") or {}).get("content") or "" + usage = resp.get("usage") or {} + print("LLM usage: prompt=%s completion=%s finish=%s" % ( + usage.get("prompt_tokens"), usage.get("completion_tokens"), choice.get("finish_reason"))) + m = re.search(r"\{.*\}", content, re.S) + try: + return json.loads(m.group(0)) if m else {} + except ValueError: + return {} + + +# ---------------------------------------------------------------- comment +def fmt_issue(n, i): + loc = i["file"] + (":" + str(i["line"]) if i["line"] else "") + s = str(n) + ". " + (("`" + loc + "` — ") if loc else "") + i["problem"] + return s + ((" → **Sửa:** " + i["fix"]) if i["fix"] else "") + + +def render(head, summary, issues, marker_sha, verdict, ref, role, collapse_minor): + parts = ["## 🤖 AI Review — " + head, "", "> " + summary, ""] + groups = [("⛔ Chặn deploy", "blocker"), ("⚠️ Nên sửa", "major"), ("💡 Góp ý", "minor")] + for title, sev in groups: + items = [i for i in issues if i["severity"] == sev] + if not items: + continue + body = "\n".join(fmt_issue(n, i) for n, i in enumerate(items, 1)) + if sev == "minor" and collapse_minor: + parts += ["
" + title + " (" + str(len(items)) + ")", "", body, "
", ""] + else: + parts += ["### " + title + " (" + str(len(items)) + ")", body, ""] + if not issues: + parts += ["_Không có vấn đề._", ""] + parts.append("" + role + " · model `" + MODEL + "` · " + ref + " · profile `" + PROFILE + "`") + parts.append("") + return "\n".join(parts) + + +def publish(comment): + if EVENT == "pull_request": + # 1 comment/PR, sửa tại chỗ thay vì đẻ comment mới mỗi lần push vào PR + mine = [c for c in (gh("/repos/%s/issues/%s/comments?per_page=100" % (REPO, PR)) or []) + if MARKER_RE.search(c.get("body") or "")] + if mine: + gh("/repos/%s/issues/comments/%s" % (REPO, mine[-1]["id"]), "PATCH", {"body": comment}) + else: + gh("/repos/%s/issues/%s/comments" % (REPO, PR), "POST", {"body": comment}) + else: + # notify-push (deploy repo) đọc comment trên commit để đưa vào card CHỜ DUYỆT + gh("/repos/%s/commits/%s/comments" % (REPO, AFTER), "POST", {"body": comment}) + + +def summary_and_log(comment, head, ref): + gs = E("GITHUB_STEP_SUMMARY") + if gs: + try: + with open(gs, "a", encoding="utf-8") as f: + f.write(comment + "\n") + except OSError: + pass + bar = "─" * 66 + print("\n" + bar + "\n🤖 AI REVIEW — " + head + " [" + ref.replace("`", "") + " · profile " + PROFILE + "]\n" + bar) + print(MARKER_RE.sub("", comment)) + print(bar) + + +# ---------------------------------------------------------------- dedupe +def prior_review(): + """Push: commit này đã được review chưa? (a) đã có comment marker trên chính SHA (cùng SHA đẩy + staging rồi production, hoặc standalone + build-gate cùng chạy); (b) SHA thuộc PR đã merge mà + head cuối của PR đã review. Trả (verdict, nguồn, body) hoặc None.""" + for c in reversed(gh("/repos/%s/commits/%s/comments?per_page=100" % (REPO, AFTER)) or []): + m = MARKER_RE.search(c.get("body") or "") + if m and AFTER.startswith(m["sha"]) and m["verdict"] in ("PASS", "FAIL"): + return m["verdict"], "commit `" + AFTER[:7] + "` đã review trước đó", c["body"] + for pr in gh("/repos/%s/commits/%s/pulls" % (REPO, AFTER)) or []: + if not pr.get("merged_at"): + continue + head_sha = (pr.get("head") or {}).get("sha", "") + for c in reversed(gh("/repos/%s/issues/%s/comments?per_page=100" % (REPO, pr["number"])) or []): + m = MARKER_RE.search(c.get("body") or "") + if m and head_sha.startswith(m["sha"]) and m["verdict"] in ("PASS", "FAIL"): + return m["verdict"], "PR #%s (head `%s`)" % (pr["number"], head_sha[:7]), c["body"] + return None + + +# ---------------------------------------------------------------- validate deploy +def validate_config(names): + errors, checked = [], [] + if not all(any(os.access(os.path.join(p, b), os.X_OK) for p in os.environ.get("PATH", "").split(os.pathsep)) + for b in ("kustomize", "kubeconform")): + print("::warning::thiếu kustomize/kubeconform — bỏ qua validate cứng") + return errors + for d in sorted({os.path.dirname(f) for f in names if f.endswith((".yaml", ".yml"))}): + if not d or not any(os.path.exists(os.path.join(d, k)) for k in ("kustomization.yaml", "kustomization.yml")): + continue + checked.append(d) + kb = subprocess.run(["kustomize", "build", d], capture_output=True, text=True) + if kb.returncode != 0: + errors.append(d + " — kustomize build LỖI: " + kb.stderr.strip()[:300]) + continue + kc = subprocess.run(["kubeconform", "-strict", "-ignore-missing-schemas", "-summary", "-"], + input=kb.stdout, capture_output=True, text=True) + if kc.returncode != 0: + errors.append(d + " — kubeconform LỖI (schema k8s không hợp lệ): " + (kc.stdout + kc.stderr).strip()[:300]) + print("Validate config dirs:", checked, "| errors:", len(errors)) + return errors + + +# ---------------------------------------------------------------- main +def main(): + role = "senior DevOps review manifest triển khai" if PROFILE == "deploy" else "senior code reviewer" + is_pr = EVENT == "pull_request" + marker_sha = PR_HEAD if is_pr and PR_HEAD else AFTER + ref = ("PR #" + PR) if is_pr else ("commit `" + AFTER[:7] + "`") + + def finish(verdict, head, summary, issues): + comment = render(head, summary, issues, marker_sha, verdict, ref, role, collapse_minor=is_pr) + summary_and_log(comment, head, ref) + publish(comment) + print("Verdict:", verdict, "| issues:", len(issues)) + sys.exit(1 if verdict == "FAIL" else 0) + + if not is_pr: + prior = prior_review() + if prior: + verdict, source, body = prior + body = MARKER_RE.sub("", body).strip() + head = "✅ PASS" if verdict == "PASS" else "⚠️ FAIL — cần sửa" + comment = ("♻️ Dùng lại kết quả đã review ở " + source + " — không gọi lại AI.\n\n" + body + + "\n") + summary_and_log(comment, head, ref) + if source.startswith("PR"): # (a) đã có comment trên chính commit thì không đăng trùng + publish(comment) + print("Verdict:", verdict, "(dùng lại) |", source) + sys.exit(1 if verdict == "FAIL" else 0) + + # ---- phạm vi diff ---- + if is_pr: + rng = ["HEAD^1", "HEAD"] # checkout@v4 ở pull_request = merge commit, parent 1 = base + elif BEFORE and set(BEFORE) != {"0"} and run_git("cat-file", "-e", BEFORE + "^{commit}")[0] == 0: + rng = [BEFORE, AFTER] + else: + rng = ["HEAD~1", "HEAD"] + names = [n for n in git("diff", "--name-only", *rng).splitlines() if n] + kept = [n for n in names if not excluded(n)] + if not kept: + finish("PASS", "✅ PASS", "Chỉ đổi file CI/docs/lock/generated — không cần review.", []) + + val_errors = validate_config(kept) if PROFILE == "deploy" else [] + if val_errors: + finish("FAIL", "⚠️ FAIL — cần sửa", + "Config KHÔNG build được / sai schema k8s — CHẶN deploy (kustomize build + kubeconform).", + [{"severity": "blocker", "file": "", "line": None, "problem": "🔧 " + e, "fix": "", "confidence": 1.0} + for e in val_errors]) + + if PROFILE == "deploy" and tag_only(git("diff", "-U0", *rng, "--", *kept)): + finish("PASS", "✅ PASS", "Chỉ đổi tag image (cùng repo image) — an toàn, không cần AI review.", []) + + diff = git("diff", "-W", *rng, "--", *kept) # -W: kèm nguyên hàm bao quanh thay cho gửi full file + if len(diff) > DIFF_LIMIT: + diff = git("diff", "-U5", *rng, "--", *kept) + truncated = len(diff) > DIFF_LIMIT + diff = diff[:DIFF_LIMIT] + skipped = len(names) - len(kept) + user = ("File đổi (" + str(len(kept)) + "): " + ", ".join(kept[:60]) + + (("\n(bỏ qua " + str(skipped) + " file CI/docs/lock/generated)") if skipped else "") + + ("\n(DIFF bị cắt ở " + str(DIFF_LIMIT) + " ký tự — chỉ đánh giá phần thấy được)" if truncated else "") + + "\n\nDIFF:\n" + diff) + + try: + out = call_llm(system_prompt(PROFILE), user) + if not isinstance(out, dict) or "issues" not in out: + raise LLMDown("model trả sai định dạng JSON") + except LLMDown as e: + reason = str(e) + print("::warning title=AI review KHÔNG chạy::" + reason + " — commit này CHƯA được review (fail-open).") + finish("ERROR", "⚠️ KHÔNG CHẠY ĐƯỢC", + "AI review lỗi (" + reason + ") — commit này **CHƯA được review**, không chặn build. " + "Tự rà diff trước khi Duyệt.", []) + + verdict, issues = decide(normalize_issues(out.get("issues"))) + head = "✅ PASS" if verdict == "PASS" else "⚠️ FAIL — cần sửa" + finish(verdict, head, str(out.get("summary") or "").strip() or "(không có tóm tắt)", issues) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/test_ai_review.py b/.github/scripts/test_ai_review.py new file mode 100644 index 0000000..b4a933b --- /dev/null +++ b/.github/scripts/test_ai_review.py @@ -0,0 +1,81 @@ +"""Test các hàm thuần của ai_review.py: python3 -m unittest discover -s .github/scripts""" +import unittest + +import ai_review as ar + + +class Excluded(unittest.TestCase): + def test_skip(self): + for p in (".github/workflows/ci-cd.yml", "docs/a.go", "README.md", "yarn.lock", "go.sum", + "web/dist/app.js", "src/locales/vi.json", "public/i18n/en.json", "a/__snapshots__/x.snap"): + self.assertTrue(ar.excluded(p), p) + + def test_keep(self): + for p in ("src/app.ts", "cmd/main.go", "k8s/main/app/kustomization.yaml", "src/i18n/index.ts", + "package.json"): + self.assertFalse(ar.excluded(p), p) + + +class TagOnly(unittest.TestCase): + def test_newtag(self): + d = "--- a/k\n+++ b/k\n@@ -5 +5 @@\n- newTag: production-abc1234\n+ newTag: production-def5678\n" + self.assertTrue(ar.tag_only(d)) + + def test_image_same_repo(self): + d = "- image: techainer1t/app:prod-1\n+ image: techainer1t/app:prod-2\n" + self.assertTrue(ar.tag_only(d)) + + def test_image_other_repo(self): + d = "- image: techainer1t/app:prod-1\n+ image: evil/app:prod-2\n" + self.assertFalse(ar.tag_only(d)) + + def test_registry_with_port(self): + d = "- image: reg.local:5000/app:1\n+ image: reg.local:5000/app:2\n" + self.assertTrue(ar.tag_only(d)) + + def test_other_change(self): + d = "- newTag: a\n+ newTag: b\n- replicas: 2\n+ replicas: 0\n" + self.assertFalse(ar.tag_only(d)) + + def test_empty(self): + self.assertFalse(ar.tag_only("")) + + +class Decide(unittest.TestCase): + def issues(self, *items): + return ar.normalize_issues(list(items)) + + def test_blocker_fails(self): + v, _ = ar.decide(self.issues({"severity": "blocker", "problem": "null deref", "confidence": 0.9})) + self.assertEqual(v, "FAIL") + + def test_low_confidence_blocker_downgraded(self): + v, kept = ar.decide(self.issues({"severity": "blocker", "problem": "có thể race", "confidence": 0.5})) + self.assertEqual((v, kept[0]["severity"]), ("PASS", "major")) + + def test_compile_claim_dropped(self): + v, kept = ar.decide(self.issues({"severity": "blocker", "problem": "Code không compile được", "confidence": 1})) + self.assertEqual((v, kept), ("PASS", [])) + + def test_legacy_string_issue(self): + v, kept = ar.decide(self.issues("file.go — thiếu kiểm lỗi")) + self.assertEqual((v, kept[0]["severity"]), ("PASS", "minor")) + + def test_bad_values(self): + kept = ar.normalize_issues([{"severity": "CRITICAL", "problem": "x", "confidence": "?"}, 3, {"problem": ""}]) + self.assertEqual(len(kept), 1) + self.assertEqual(kept[0]["severity"], "minor") + + +class Marker(unittest.TestCase): + def test_roundtrip(self): + iss = ar.normalize_issues([{"severity": "minor", "problem": "p", "file": "a.go", "line": 3}]) + body = ar.render("✅ PASS", "ok", iss, "abc1234def", "PASS", "PR #1", "r", collapse_minor=True) + m = ar.MARKER_RE.search(body) + self.assertEqual((m["sha"], m["verdict"]), ("abc1234def", "PASS")) + self.assertIn("AI Review", body) # notify-push lọc comment theo chuỗi này + self.assertIn("
", body) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ecf7967 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,19 @@ +# Kiểm chính repo này trước khi merge: mọi repo app gọi reusable `@main`, nên 1 file vỡ = vỡ CI cả org +# (sự cố 15/07: biểu thức GHA literal trong run-block → "failed to parse workflow" trên 16 repo, ~8h). +# Repo public → runner GitHub-hosted miễn phí, không chiếm runner self-hosted. +name: ci +on: + pull_request: + push: + branches: [main] +jobs: + lint-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: actionlint + run: | + bash <(curl -sSfL https://raw.githubusercontent.com/rhysd/actionlint/v1.7.7/scripts/download-actionlint.bash) 1.7.7 + ./actionlint -color -shellcheck= .github/workflows/*.yml + - name: unit test ai_review.py + run: python3 -m unittest discover -s .github/scripts -v diff --git a/.github/workflows/reusable-ai-review.yml b/.github/workflows/reusable-ai-review.yml index dd510a3..dc36d2e 100644 --- a/.github/workflows/reusable-ai-review.yml +++ b/.github/workflows/reusable-ai-review.yml @@ -1,10 +1,14 @@ # AI code review gate — chấm diff bằng LLM (OpenAI-compatible) theo rules THS. -# CHẠY cả PR lẫn PUSH: -# - pull_request → diff cả PR, comment lên PR, FAIL = chặn merge (nếu bật branch protection). -# - push → diff các commit vừa push, comment lên commit, FAIL = commit đỏ (cờ cảnh báo). -# profile: -# - code (mặc định) → review CODE (bug/security/error-handling/architecture). -# - deploy → review CONFIG/K8S an toàn deploy (dùng cho repo deployment). +# Logic nằm ở .github/scripts/ai_review.py (repo này public → job tự checkout script). +# CHỈ review khi đáng tiền (chốt 27/10, sau vụ getnexai 402): +# - pull_request (không draft) → comment 1 lần/PR (sửa tại chỗ), FAIL = chặn merge nếu bật protection. +# - push vào nhánh trong `review_branches` (staging/prod/master) → comment lên commit, FAIL = commit đỏ. +# SHA đã review ở PR đã merge / đã có comment review → DÙNG LẠI verdict, không gọi LLM. +# - mọi event khác (push develop/feature, workflow_dispatch…) → job vẫn SUCCESS nhưng không gọi LLM. +# Skip ở STEP chứ không ở `if:` của job: ci-cd.yml có `build-develop: needs: review` không kèm +# !cancelled() → job skipped sẽ kéo build develop skip theo. +# profile: code (mặc định, app repo) | deploy (repo deployment: kustomize+kubeconform cứng, commit chỉ đổi tag = PASS). +# LLM lỗi → fail-open CÓ cảnh báo (::warning + comment "KHÔNG CHẠY ĐƯỢC"), không chặn build. # Caller truyền tường minh 2 secret (least-privilege): OPENAI_API_KEY, OPENAI_BASE_URL. name: reusable-ai-review on: @@ -13,25 +17,29 @@ on: profile: type: string default: code + # Tên trung tính; LiteLLM map alias → model thật (đổi backend không phải sửa CI). model: type: string - default: claude-sonnet-4-6 - # Job này chỉ gọi HTTP + chạy python (~31s), KHÔNG đụng docker daemon → không cần ghim đúng - # box build. Ghim 'techainer-gkebooks-1' làm nó xếp hàng sau build 40 phút của repo khác. - # 'self-hosted' là label tự động mọi runner self-hosted đều có → hôm nay vẫn về đúng box đó, - # nhưng khi thêm runner nhẹ vào pool thì tự chảy sang runner rảnh. Ghim lại bằng input nếu cần. + default: ai-review + # Tham số phụ gộp vào body request (JSON). Mặc định tắt thinking của Qwen3: review cần JSON gọn, + # thinking làm chậm gấp nhiều lần và dễ chạm timeout 100s của Cloudflare. + llm_extra_body: + type: string + default: '{"chat_template_kwargs":{"enable_thinking":false}}' + review_branches: + type: string + default: production,production-staging,staging,master,main + # Job chỉ gọi HTTP + chạy python, KHÔNG đụng docker → không ghim box build. runner: type: string default: self-hosted secrets: OPENAI_API_KEY: - required: false # thiếu → python fail-open skip (không chặn build oan) + required: false # thiếu → fail-open có cảnh báo (không chặn build oan) OPENAI_BASE_URL: required: false jobs: ai-review: - # chạy mọi event (push, workflow_dispatch, …) TRỪ PR draft. - # (Trước đây chỉ 'push' → workflow_dispatch bị skip → build needs:review cũng skip → GÃY staging deploy.) if: github.event_name != 'pull_request' || github.event.pull_request.draft == false runs-on: ${{ inputs.runner }} # Push dồn dập cùng nhánh → chỉ review commit MỚI NHẤT, huỷ run cũ đang chờ/chạy (tránh ngập hàng đợi runner). @@ -49,253 +57,65 @@ jobs: env: AI_REVIEW_ENABLED: 'false' steps: - - name: AI review đang TẠM TẮT - if: env.AI_REVIEW_ENABLED != 'true' - run: echo "::notice title=AI review tạm tắt::Hết token LLM — commit/PR này KHÔNG được AI review." + - name: Có cần review không? + id: decide + env: + EVENT: ${{ github.event_name }} + BRANCH: ${{ github.ref_name }} + BRANCHES: ${{ inputs.review_branches }} + ENABLED: ${{ env.AI_REVIEW_ENABLED }} + run: | + run=false + # Công tắc tạm tắt (27/10/2026, main): 'false' thì không review gì cả, job vẫn SUCCESS để build needs: review chạy tiếp. + [ "$ENABLED" = true ] || { echo "run=false" >> "$GITHUB_OUTPUT"; echo "::notice title=AI review tạm tắt::Hết token LLM: commit/PR này KHÔNG được AI review."; exit 0; } + case "$EVENT" in + pull_request) run=true ;; + push) case ",${BRANCHES// /}," in *",$BRANCH,"*) run=true ;; esac ;; + esac + echo "run=$run" >> "$GITHUB_OUTPUT" + [ "$run" = true ] || echo "::notice title=Bỏ qua AI review::$EVENT trên '$BRANCH' — chỉ review PR và push vào: $BRANCHES" - uses: actions/checkout@v4 - if: env.AI_REVIEW_ENABLED == 'true' + if: steps.decide.outputs.run == 'true' with: fetch-depth: 0 - # runs-on giờ là input → job có thể rơi vào BẤT KỲ runner nào trong pool. 2 step dưới gỡ nốt các - # phụ thuộc ngầm vào riêng box build (sudo không mật khẩu, python3 cài sẵn) để "chảy sang runner rảnh" - # không biến thành "fail trên runner mới". + - uses: actions/checkout@v4 + if: steps.decide.outputs.run == 'true' + with: + repository: Techainer/.github + ref: main + path: .ai-review-tool + sparse-checkout: .github/scripts + persist-credentials: false - name: Đảm bảo có python3 (runner trần chưa chắc có) id: py - if: env.AI_REVIEW_ENABLED == 'true' + if: steps.decide.outputs.run == 'true' run: command -v python3 >/dev/null || echo "need=1" >> "$GITHUB_OUTPUT" - uses: actions/setup-python@v5 - if: env.AI_REVIEW_ENABLED == 'true' && steps.py.outputs.need == '1' + if: steps.decide.outputs.run == 'true' && steps.py.outputs.need == '1' with: python-version: "3.12" - name: Cài kustomize + kubeconform (validate config cứng — chỉ profile deploy) - if: env.AI_REVIEW_ENABLED == 'true' && inputs.profile == 'deploy' + if: steps.decide.outputs.run == 'true' && inputs.profile == 'deploy' run: | set -euo pipefail - # Cài vào RUNNER_TEMP + GITHUB_PATH thay vì `sudo tar -C /usr/local/bin`: sudo-không-mật-khẩu - # KHÔNG phải thứ mọi self-hosted runner đều có, mà chỉ để chạy 2 binary dùng-một-lần. + # RUNNER_TEMP + GITHUB_PATH thay vì sudo: không phải self-hosted nào cũng có sudo không mật khẩu. mkdir -p "$RUNNER_TEMP/bin" curl -sL https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2Fv5.4.3/kustomize_v5.4.3_linux_amd64.tar.gz | tar xz -C "$RUNNER_TEMP/bin" kustomize curl -sL https://github.com/yannh/kubeconform/releases/download/v0.6.7/kubeconform-linux-amd64.tar.gz | tar xz -C "$RUNNER_TEMP/bin" kubeconform echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH" - "$RUNNER_TEMP/bin/kustomize" version && "$RUNNER_TEMP/bin/kubeconform" -v - name: AI review - if: env.AI_REVIEW_ENABLED == 'true' + if: steps.decide.outputs.run == 'true' env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} OPENAI_BASE_URL: ${{ secrets.OPENAI_BASE_URL }} MODEL: ${{ inputs.model }} + LLM_EXTRA_BODY: ${{ inputs.llm_extra_body }} PROFILE: ${{ inputs.profile }} GH_TOKEN: ${{ github.token }} EVENT: ${{ github.event_name }} REPO: ${{ github.repository }} PR: ${{ github.event.pull_request.number }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} BEFORE: ${{ github.event.before }} AFTER: ${{ github.sha }} - run: | - python3 - <<'PY' - import os, json, re, subprocess, urllib.request - event = os.environ.get("EVENT","") - repo = os.environ.get("REPO","") - profile = os.environ.get("PROFILE","code") - - def sh(cmd): - # gh CLI có sẵn trên runner GitHub-hosted nhưng KHÔNG trên self-hosted trần. Job này chạy - # runs-on: inputs.runner nên có thể rơi vào runner bất kỳ → thiếu gh phải fallback git, - # KHÔNG được để FileNotFoundError làm chết gate (chết = chặn build oan mọi repo). - try: - return subprocess.run(cmd, capture_output=True, text=True).stdout - except FileNotFoundError: - print("⚠️ runner thiếu binary '" + cmd[0] + "' -> fallback") - return "" - - # ---- lấy diff theo loại sự kiện ---- - if event == "pull_request": - # checkout@v4 ở event pull_request lấy MERGE COMMIT (parent1 = base) → `HEAD^1 HEAD` - # chính là diff của PR, dùng khi runner không có gh. - diff = sh(["gh","pr","diff",os.environ.get("PR","")]) or sh(["git","diff","HEAD^1","HEAD"]) - else: # push - before = os.environ.get("BEFORE","") or "" - after = os.environ.get("AFTER","") or "HEAD" - if (not before) or set(before) <= {"0"}: - diff = sh(["git","diff","HEAD~1..HEAD"]) or sh(["git","show","--format=","HEAD"]) - else: - diff = sh(["git","diff",before+".."+after]) - # ---- LỌC diff: chỉ review CODE substantive (best-practice). Bỏ CI/workflow (.github), lock, generated, binary. ---- - # Tránh review nhầm chính gate CI (ci-cd.yml) rồi FAIL oan; tránh nitpick file sinh tự động. - def _excluded(p): - p = p.lower() - if p.startswith(".github/"): return True - if any(p.endswith(x) for x in (".lock","-lock.json","lock.yaml","lock.yml","go.sum",".min.js",".min.css",".map",".svg",".png",".jpg",".jpeg",".ico",".gif",".webp",".woff",".woff2",".ttf",".pdf",".lockb")): return True - if any(s in p for s in ("/dist/","/build/","/vendor/","/node_modules/","/__generated__/",".generated.","/gen/")): return True - return False - _blocks = re.split(r'(?m)^(?=diff --git )', diff) - _kept = [b for b in _blocks if not (re.match(r'diff --git a/\S+ b/(\S+)', b) and _excluded(re.match(r'diff --git a/\S+ b/(\S+)', b).group(1)))] - diff = "".join(_kept)[:60000] - if not diff.strip(): - print("Diff chỉ gồm file loại trừ (CI/lock/generated) hoặc rỗng — skip, PASS."); raise SystemExit(0) - - # ---- NỘI DUNG FILE đổi (full context → review SÂU, không chỉ hunks) ---- - _changed = [m.group(1) for b in _kept for m in [re.match(r'diff --git a/\S+ b/(\S+)', b)] if m] - _SRC = (".py",".js",".jsx",".ts",".tsx",".go",".java",".rb",".php",".vue",".yaml",".yml",".sh",".sql",".rs",".c",".cpp",".h",".cs",".kt") - _fc = []; _tot = 0 - for _p in _changed[:20]: - if not _p.lower().endswith(_SRC): continue - try: _c = open(_p, encoding="utf-8", errors="ignore").read()[:15000] - except Exception: continue - if _tot + len(_c) > 50000: break - _tot += len(_c); _fc.append("=== FILE: " + _p + " ===\n" + _c) - files_blob = "\n\n".join(_fc) - - # ---- VALIDATE CỨNG config toàn commit (profile deploy): kustomize build + kubeconform (schema k8s) ---- - val_errors = [] - if profile == "deploy": - if event == "pull_request": - files = (sh(["gh","pr","diff",os.environ.get("PR",""),"--name-only"]) - or sh(["git","diff","--name-only","HEAD^1","HEAD"])).split() - else: - before = os.environ.get("BEFORE","") or ""; after = os.environ.get("AFTER","") or "HEAD" - rng = "HEAD~1..HEAD" if (not before or set(before) <= {"0"}) else before+".."+after - files = sh(["git","diff","--name-only",rng]).split() - dirs = sorted({os.path.dirname(f) for f in files if f.endswith((".yaml",".yml"))}) - checked = [] - for d in dirs: - if not d: continue - if os.path.exists(os.path.join(d,"kustomization.yaml")) or os.path.exists(os.path.join(d,"kustomization.yml")): - checked.append(d) - kb = subprocess.run(["kustomize","build",d], capture_output=True, text=True) - if kb.returncode != 0: - val_errors.append(d+" — kustomize build LỖI: "+kb.stderr.strip()[:300]); continue - kc = subprocess.run(["kubeconform","-strict","-ignore-missing-schemas","-summary","-"], - input=kb.stdout, capture_output=True, text=True) - if kc.returncode != 0: - val_errors.append(d+" — kubeconform LỖI (schema k8s không hợp lệ): "+(kc.stdout+kc.stderr).strip()[:300]) - print("Validate config dirs:", checked, "| errors:", len(val_errors)) - - # ---- rules theo profile ---- - CODE_RULES = ( - "BUG/LOGIC: syntax, type, null/None, off-by-one, race, thiếu import, sai điều kiện. " - "SECURITY: injection (SQL/XSS/command), secret/credential hardcode, thiếu validate input, path traversal. " - "ERROR-HANDLING: bare except, nuốt lỗi, thiếu cleanup/rollback, sai propagate, resource leak. " - "ARCHITECTURE: vi phạm convention/CLAUDE.md, trùng lặp nên tách, breaking-change API không migrate." - ) - DEPLOY_RULES = ( - "AN TOÀN DEPLOY (manifest k8s / config): KHÔNG hạ replicas về 0 ngoài ý muốn, " - "KHÔNG thêm secret/credential cleartext mới, KHÔNG giảm resource limit/request vô lý (gây OOM/thiếu), " - "thay đổi image NÊN chỉ là đổi TAG (đổi image-name/registry lạ phải nghi ngờ), " - "sửa ConfigMap/env phải khớp app (không xoá key app đang dùng), " - "migration/job DB phải an toàn (không phá/mất dữ liệu). Diff YAML phải hợp lệ." - ) - RULES = DEPLOY_RULES if profile == "deploy" else CODE_RULES - role = ("senior DevOps review manifest triển khai" if profile == "deploy" - else "senior code reviewer") - - prompt = ( - "Bạn là " + role + ". Review thay đổi (DIFF) theo RULES; ĐỌC KỸ NỘI DUNG FILE kèm dưới để hiểu ngữ cảnh + TRUY VẾT tác động (data flow, null, edge case, side-effect, tương tác giữa các hàm) — KHÔNG chỉ nhìn dòng đổi bề mặt. " - "Trả về DUY NHẤT 1 JSON hợp lệ: {\"verdict\":\"PASS\"|\"FAIL\",\"summary\":\"1-2 câu tiếng Việt\",\"issues\":[\"file — vấn đề + gợi ý sửa\"]}. " - "NGUYÊN TẮC (best-practice code review): " - "(1) Ưu tiên theo mức độ: correctness + security TRƯỚC, rồi bug-logic/error-handling, rồi architecture. " - "(2) FAIL CHỈ khi có lỗi CHẮC CHẮN gây hỏng/nguy hiểm (bug rõ ràng, security thật, mất dữ liệu, breaking-change không migrate). " - "KHÔNG FAIL vì: style/format/naming/preference, thiếu test, hay nghi-ngờ mơ hồ — những thứ đó = PASS + ghi vào issues như góp ý. " - "TUYỆT ĐỐI KHÔNG phán lỗi COMPILE/SYNTAX/BUILD-FAIL: pipeline đã `build` (biên dịch) TRƯỚC bước này, nên nếu code đã tồn tại trong commit thì nó CHẮC CHẮN compile được — bạn nghĩ 'không compile/sai cú pháp' thì gần như chắc BẠN nhầm cú pháp ngôn ngữ (vd Go composite-literal elision `map[string][]string{k:{v}}` HỢP LỆ = `[]string{v}`; Go generics; Python f-string; TS satisfies). Gặp nghi-ngờ cú pháp → BỎ QUA, coi như PASS, KHÔNG đưa vào issues. " - "(3) Với CI/config: chỉ flag lỗ hổng THẬT (secret hardcode bị lộ, script-injection biểu thức GHA nhúng trong run, permissions quá rộng, pull_request_target checkout code PR) — " - "KHÔNG flag pattern chuẩn NỘI BỘ (reusable `Techainer/.github/...@main` là tin cậy; truyền secret cho workflow nội bộ là bình thường). " - "(4) issues phải CỤ THỂ: nêu file + vấn đề + cách sửa; đừng chung chung. Không có lỗi rõ → PASS.\n\n" - "RULES: " + RULES + "\n\nDIFF:\n" + diff + (("\n\nNỘI DUNG FILE (đọc để review sâu):\n" + files_blob) if files_blob else "") - ) - if val_errors: - # Validate CỨNG thắng: config không build/sai schema = FAIL, KHÔNG cần hỏi LLM (kể cả thiếu key) - content = json.dumps({"verdict":"FAIL", - "summary":"Config KHÔNG build được / sai schema k8s — CHẶN deploy (validate cứng: kustomize build + kubeconform).", - "issues":["🔧 "+e for e in val_errors]}) - else: - base = (os.environ.get("OPENAI_BASE_URL","") or "").rstrip("/") - if not base or not os.environ.get("OPENAI_API_KEY"): - print("Thiếu OPENAI_BASE_URL/OPENAI_API_KEY — skip (fail-open)."); raise SystemExit(0) - body = json.dumps({"model":os.environ.get("MODEL","claude-sonnet-4-6"),"temperature":0, - "messages":[{"role":"user","content":prompt}]}).encode() - req = urllib.request.Request(base + "/chat/completions", data=body, - headers={"Authorization":"Bearer "+os.environ["OPENAI_API_KEY"],"Content-Type":"application/json"}) - try: - resp = json.load(urllib.request.urlopen(req, timeout=150)) - content = resp["choices"][0]["message"]["content"] - except Exception as e: - print("LLM lỗi (fail-open, không chặn CI):", e); raise SystemExit(0) - - m = re.search(r'\{.*\}', content, re.S) - v = {} - try: v = json.loads(m.group(0)) if m else {} - except Exception: pass - if v.get("verdict"): - verdict = str(v["verdict"]).upper() - issues = v.get("issues") or [] - summary = v.get("summary", content[:300]) - else: - # Model KHÔNG trả JSON verdict hợp lệ (định dạng lạ / cắt output) → KHÔNG chặn deploy - # (fail-open: gate Telegram Duyệt vẫn gác cuối). Ghi rõ để người xem tự rà tay. - verdict = "PASS"; issues = [] - summary = "⚠️ AI review chưa phản hồi đúng định dạng JSON — BỎ QUA, không chặn (nên tự rà tay diff)." - - # ---- BACKSTOP CỨNG chống false-positive compile/syntax (không dựa vào LLM tự tuân prompt) ---- - # Lý do: bước `build` của pipeline mới là nguồn sự thật về biên dịch; nếu code THẬT lỗi compile - # thì workflow build FAIL và chặn deploy độc lập. Reviewer LLM hay nhầm cú pháp (vd Go elision - # map[K][]T{k:{v}} hợp lệ) → tuyệt đối không để nó FAIL vì lý do compile/syntax. - # KHÔNG áp cho val_errors (kustomize/kubeconform) vì đó là lỗi build config THẬT, deterministic. - if not val_errors and issues: - _cpat = re.compile(r"(kh[oô]ng\s+(?:compile|build|bi[êe]n\s*d[ịi]ch)|compile[\s-]*error|" - r"syntax[\s-]*error|sai\s*c[uú]\s*ph[áa]p|l[oô]i\s*c[uú]\s*ph[áa]p|" - r"build[\s-]*fail|(?:won'?t|cannot|does\s*not|will\s*not)\s*compile|" - r"kh[oô]ng\s*bi[êe]n\s*d[ịi]ch\s*[đd][ưuơợ]?[ơợ]c)", re.I) - _drop = [i for i in issues if _cpat.search(str(i))] - if _drop: - issues = [i for i in issues if i not in _drop] - for _d in _drop: - print("⏭️ DROP claim compile/syntax (build đã lo, reviewer không tính):", str(_d)[:180]) - if verdict == "FAIL" and not issues: - verdict = "PASS" - summary = ("Đã loại " + str(len(_drop)) + " cảnh báo compile/syntax (build lo biên dịch) " - "→ không còn lỗi chặn. " + summary) - - head = "✅ PASS" if verdict == "PASS" else "⚠️ FAIL — cần sửa" - _ref = ("PR #" + os.environ.get("PR","")) if event == "pull_request" else ("commit `" + os.environ.get("AFTER","")[:7] + "`") - _issues_md = "\n".join(str(n) + ". " + str(i) for n, i in enumerate(issues, 1)) - comment = ("## 🤖 AI Review — " + head + "\n\n" - + "> " + summary + "\n\n" - + (("### 🔎 Vấn đề (" + str(len(issues)) + ")\n" + _issues_md) if issues else "_Không có vấn đề._") - + "\n\n" + role + " · model `" + os.environ.get("MODEL","") + "` · " + _ref + " · profile `" + profile + "`") - - # (a) Job Summary — Actions UI render markdown ĐẸP (tab "Summary" của run). - gs = os.environ.get("GITHUB_STEP_SUMMARY") - if gs: - try: open(gs, "a", encoding="utf-8").write(comment + "\n") - except Exception: pass - # (b) IN ĐẦY ĐỦ ra LOG (stdout) — dev thấy NGAY tại step, khỏi mò Summary/commit-comment. - _bar = "─" * 66 - print("\n" + _bar) - print("🤖 AI REVIEW — " + head + " [" + _ref.replace("`","") + " · profile " + profile + "]") - print(_bar) - print(summary) - if issues: - print("\n🔎 Vấn đề (" + str(len(issues)) + "):") - for _n, _i in enumerate(issues, 1): - print(" " + str(_n) + ". " + str(_i)) - else: - print("\n✅ Không có vấn đề.") - print(_bar) - if verdict != "PASS": - print("→ Chi tiết render đẹp ở tab 'Summary' của run này, và comment trên " + _ref.replace("`","")) - print("Verdict:", verdict, "| issues:", len(issues)) - - # ---- đăng comment theo loại sự kiện (fail-open, NUỐT output JSON) ---- - try: - if event == "pull_request": - subprocess.run(["gh","pr","comment",os.environ["PR"],"--body",comment], capture_output=True) - else: - subprocess.run(["gh","api","-X","POST", - "repos/%s/commits/%s/comments" % (repo, os.environ.get("AFTER","")), - "-f","body="+comment, "--silent"], capture_output=True) - except Exception as e: - print("đăng comment lỗi (bỏ qua):", str(e)[:120]) - - if verdict != "PASS": - raise SystemExit(1) - PY + run: python3 .ai-review-tool/.github/scripts/ai_review.py