feat: add role management and usage tracking for AI code review

- Implemented role parsing and loading from markdown files, including attributes like name, side, focus, badge, color, and personality.
- Created functions to build prompts for analysis, line location, and verdicts based on roles.
- Added tests for role management functionalities to ensure correct parsing and loading of roles.
- Developed usage tracking for AI assistant interactions, including token usage and rate limits.
- Implemented functions to extract and record usage data from various LLM providers.
- Added tests for usage tracking functionalities to validate correct accumulation and reporting of usage statistics.
This commit is contained in:
2026-06-25 09:34:59 +00:00
parent 120b83c904
commit 525f6f9350
37 changed files with 6405 additions and 23 deletions
+207
View File
@@ -0,0 +1,207 @@
import axios from 'axios';
import https from 'https';
import { GITEA_TOKEN, GITEA_COMMENT_TOKEN, GITEA_SERVER_URL, GITEA_REPOSITORY, GITEA_SKIP_TLS_VERIFY, PR_NUMBER, PR_HEAD_SHA, PR_HEAD_BRANCH } from './config.js';
import { line, warn } from './log.js';
const httpsAgent = GITEA_SKIP_TLS_VERIFY ? new https.Agent({ rejectUnauthorized: false }) : undefined;
const headers = (token = GITEA_TOKEN) => ({ Authorization: `token ${token}`, 'Content-Type': 'application/json' });
const api = (path) => `${GITEA_SERVER_URL.replace(/\/$/, '')}/api/v1${path}`;
function extractCommitMessage(payload) {
return payload?.message
|| payload?.commit?.message
|| payload?.commit?.commit?.message
|| '';
}
export function getBotReviewOutcome(message) {
const match = String(message || '').match(/\[ai-review-bot\](?:\[(success|failure)\])?/i);
return match?.[1]?.toLowerCase() || 'unknown';
}
/**
* 取得 PR 的 Git Diff 內容,已自動排除 .gitea/ 資料夾。
*/
export async function getPRDiff() {
const resp = await axios.get(api(`/repos/${GITEA_REPOSITORY}/pulls/${PR_NUMBER}.diff`), { headers: headers(), timeout: 60000, httpsAgent });
return filterDiff(resp.data, [
'.gitea/',
'.github/',
'README.md',
'TODO.md',
]);
}
export async function getCommitMessageBySha(sha) {
if (!sha) return '';
try {
const resp = await axios.get(api(`/repos/${GITEA_REPOSITORY}/git/commits/${encodeURIComponent(sha)}`), {
headers: headers(),
timeout: 30000,
httpsAgent,
});
return extractCommitMessage(resp.data);
} catch (e) {
warn(`取得 commit 訊息失敗: sha=${sha} error=${e.message}`);
return '';
}
}
export async function getBranchHeadCommitMessage(branch = PR_HEAD_BRANCH) {
if (!branch) return '';
try {
const resp = await axios.get(api(`/repos/${GITEA_REPOSITORY}/branches/${encodeURIComponent(branch)}`), {
headers: headers(),
timeout: 30000,
httpsAgent,
});
const sha = resp.data?.commit?.id || resp.data?.commit?.sha || '';
return await getCommitMessageBySha(sha);
} catch (e) {
warn(`取得分支 head 訊息失敗: branch=${branch} error=${e.message}`);
return '';
}
}
/** 檢查 PR headcommit sha 或分支 head)的訊息是否帶 [ai-review-bot] 標記,是則代表本次是自動提交、應跳過審查。 */
export async function shouldSkipBotCommit({ sha = PR_HEAD_SHA || process.env.GITHUB_SHA, branch = PR_HEAD_BRANCH } = {}) {
const shaMessage = await getCommitMessageBySha(sha);
if (sha && shaMessage.includes('[ai-review-bot]')) return true;
const branchMessage = await getBranchHeadCommitMessage(branch);
if (branch && branchMessage.includes('[ai-review-bot]')) return true;
return false;
}
/**
* 過濾 diff 內容,移除路徑符合 excludePrefixes 的區塊。
* 每個區塊以 "diff --git a/<prefix>" 開頭判斷,使用 startsWith 精確比對前綴。
*/
export function filterDiff(diff, excludePrefixes) {
return diff.split(/(?=^diff --git )/m)
.filter(block => !excludePrefixes.some(p => {
const prefix = `diff --git a/${p}`;
const singleFile = `diff --git a/${p} b/${p}`;
return block.startsWith(prefix) || block.startsWith(singleFile);
}))
.join('');
}
export async function postComment(body) {
const resp = await axios.post(
api(`/repos/${GITEA_REPOSITORY}/issues/${PR_NUMBER}/comments`),
{ body },
{ headers: headers(GITEA_COMMENT_TOKEN || GITEA_TOKEN), timeout: 30000, httpsAgent },
);
return resp.data;
}
/**
* 在 PR 指定檔案的指定行數發布行內 review comment(標註程式碼位置)。
* 透過 Gitea 的 pull reviews API,以 new_position 對應新版檔案的行號。
* 若該行不在 diff 範圍內,Gitea 會回傳錯誤,由呼叫端決定是否降級為一般 comment。
*/
export async function postPullReviewComment({ path: filePath, line, body }) {
const resp = await axios.post(
api(`/repos/${GITEA_REPOSITORY}/pulls/${PR_NUMBER}/reviews`),
{
commit_id: PR_HEAD_SHA || undefined,
event: 'COMMENT',
body: '',
comments: [{ path: filePath, body, new_position: line }],
},
{ headers: headers(GITEA_COMMENT_TOKEN || GITEA_TOKEN), timeout: 30000, httpsAgent },
);
return resp.data;
}
/**
* 建立一個 PR review,本文放統計摘要,comments 放多筆行內 review comments。
*/
export async function postPullReview({ body, comments = [] }) {
const resp = await axios.post(
api(`/repos/${GITEA_REPOSITORY}/pulls/${PR_NUMBER}/reviews`),
{
commit_id: PR_HEAD_SHA || undefined,
event: 'COMMENT',
body,
comments,
},
{ headers: headers(GITEA_COMMENT_TOKEN || GITEA_TOKEN), timeout: 30000, httpsAgent },
);
return resp.data;
}
/**
* 取得 PR 上所有的 review(每個 review 可含多個行內 comment)。
*/
export async function listPullReviews() {
const resp = await axios.get(
api(`/repos/${GITEA_REPOSITORY}/pulls/${PR_NUMBER}/reviews`),
{ headers: headers(), timeout: 30000, httpsAgent },
);
return Array.isArray(resp.data) ? resp.data : [];
}
/**
* 取得單一 review 底下的所有行內 comment。
*/
export async function getPullReviewComments(reviewId) {
const resp = await axios.get(
api(`/repos/${GITEA_REPOSITORY}/pulls/${PR_NUMBER}/reviews/${reviewId}/comments`),
{ headers: headers(), timeout: 30000, httpsAgent },
);
return Array.isArray(resp.data) ? resp.data : [];
}
/**
* 取得 PR 上所有 review 的行內 comment,展平成單一陣列。
* 單一 review 取 comment 失敗時記錄警告並略過,不中斷整體流程。
*/
export async function listAllReviewComments() {
const reviews = await listPullReviews();
const all = [];
for (const review of reviews) {
if (!review?.id) continue;
try {
all.push(...await getPullReviewComments(review.id));
} catch (e) {
warn(`取得 review #${review.id} 的 comments 失敗(略過): ${e.message}`);
}
}
line(`取得 PR review comments: reviews=${reviews.length} comments=${all.length}`);
return all;
}
/**
* 解決(resolve)一個 review comment 所屬的對話。
* 對應 Gitea 官方 APIPOST /repos/{repo}/pulls/comments/{id}/resolve。
*/
export async function resolvePullReviewComment(commentId) {
const resp = await axios.post(
api(`/repos/${GITEA_REPOSITORY}/pulls/comments/${commentId}/resolve`),
{},
{ headers: headers(GITEA_COMMENT_TOKEN || GITEA_TOKEN), timeout: 30000, httpsAgent },
);
return resp.data;
}
/**
* 取得指定 ref(預設 PR head)下某檔案的最新文字內容;
* Gitea contents API 回傳 base64,這裡解碼成字串。檔案不存在或非文字時回傳空字串。
*/
export async function getFileContentAtRef(filePath, ref = PR_HEAD_SHA || PR_HEAD_BRANCH) {
try {
const resp = await axios.get(
api(`/repos/${GITEA_REPOSITORY}/contents/${encodeURIComponent(filePath).replace(/%2F/g, '/')}`),
{ headers: headers(), params: ref ? { ref } : undefined, timeout: 30000, httpsAgent },
);
const { content, encoding } = resp.data || {};
if (typeof content !== 'string') return '';
return encoding === 'base64' ? Buffer.from(content, 'base64').toString('utf8') : content;
} catch (e) {
warn(`取得檔案內容失敗(視為空): ${filePath}@${ref || 'head'} error=${e.message}`);
return '';
}
}