Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c321b7ba2 | |||
| 710cd7308e | |||
| 59978c6fb5 | |||
| 519e04691d | |||
| 5ae0549453 | |||
| 81e38de649 | |||
| 4a67dec32a | |||
| 5c5660a34b | |||
| 6ecb018ef4 | |||
| 02529a4ec9 | |||
| 624a71836c | |||
| fb1254aa32 | |||
| 6eae6eb0ce | |||
| ed1f2bea15 | |||
| 9a11d25c00 | |||
| 64b904dd07 | |||
| 73c11129ab | |||
| 7ba2af3384 | |||
| aca76f23af | |||
| bdf8d8a797 | |||
| e183e31ce0 | |||
| 7b5decf46a | |||
| 0609e7fe7f |
@@ -28,8 +28,8 @@ jobs:
|
|||||||
- name: AI Code Review
|
- name: AI Code Review
|
||||||
uses: https://gitea.jsc.idv.tw/jiantw83/code-review@v${{ needs.version.outputs.version }}
|
uses: https://gitea.jsc.idv.tw/jiantw83/code-review@v${{ needs.version.outputs.version }}
|
||||||
with:
|
with:
|
||||||
OLLAMA_BASE_URL: ${{ secrets.OLLAMA_BASE_URL }}
|
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||||
OLLAMA_MODEL: ${{ secrets.OLLAMA_MODEL }}
|
OPENAI_BASE_URL: https://openrouter.ai/api/v1
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
|
|||||||
@@ -41,8 +41,10 @@ jobs:
|
|||||||
- name: AI Code Review
|
- name: AI Code Review
|
||||||
uses: https://gitea.jsc.idv.tw/jiantw83/code-review@${{ vars.ACTION_CODE_REVIEW_VERSION }}
|
uses: https://gitea.jsc.idv.tw/jiantw83/code-review@${{ vars.ACTION_CODE_REVIEW_VERSION }}
|
||||||
with:
|
with:
|
||||||
|
# Github (h3285@evertrust.com.tw)
|
||||||
|
# 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
|
||||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||||
OPENAI_BASE_URL: https://api.openai.com/v1
|
OPENAI_BASE_URL: https://openrouter.ai/api/v1
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
@@ -262,8 +264,8 @@ jobs:
|
|||||||
- name: AI Code Review
|
- name: AI Code Review
|
||||||
uses: https://gitea.jsc.idv.tw/jiantw83/code-review@${{ vars.ACTION_CODE_REVIEW_VERSION }}
|
uses: https://gitea.jsc.idv.tw/jiantw83/code-review@${{ vars.ACTION_CODE_REVIEW_VERSION }}
|
||||||
with:
|
with:
|
||||||
OLLAMA_BASE_URL: ${{ secrets.OLLAMA_BASE_URL }}
|
OLLAMA_BASE_URL: ${{ vars.OLLAMA_BASE_URL }}
|
||||||
OLLAMA_MODEL: ${{ secrets.OLLAMA_MODEL }}
|
OLLAMA_MODEL: ${{ vars.OLLAMA_MODEL }}
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
|
|||||||
@@ -29,4 +29,5 @@
|
|||||||
|
|
||||||
每個階段都會加上明確的 log,並確保即使部分功能未完成也能降級執行、不會中斷 pipeline。
|
每個階段都會加上明確的 log,並確保即使部分功能未完成也能降級執行、不會中斷 pipeline。
|
||||||
|
|
||||||
每次執行後請貼 log,我會協助 debug。
|
每次執行後請貼 log,我會協助 debug。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { postComment } from './gitea.js';
|
||||||
|
import { FINDINGS_PATH } from './config.js';
|
||||||
|
|
||||||
|
const LEVEL_EMOJI = { critical: '🔴', warning: '🟡', info: '🔵' };
|
||||||
|
const LEVEL_LABEL = { critical: '嚴重', warning: '警告', info: '建議' };
|
||||||
|
|
||||||
|
function findingRow(f) {
|
||||||
|
return `| ${LEVEL_EMOJI[f.level] || ''} ${LEVEL_LABEL[f.level] || f.level} | ${f.role} | ${f.location} | ${f.suggestion} |`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildTable(findings) {
|
||||||
|
const rows = findings.map(findingRow).join('\n');
|
||||||
|
return `| 等級 | 審查員 | 位置 | 建議 |\n|------|--------|------|------|\n${rows}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 寫入 findings.json 到 workspace
|
||||||
|
*/
|
||||||
|
export function saveFindings(workspace, findings) {
|
||||||
|
const fullPath = path.join(workspace, FINDINGS_PATH);
|
||||||
|
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
||||||
|
fs.writeFileSync(fullPath, JSON.stringify(findings, null, 2), 'utf8');
|
||||||
|
console.log(` ✅ findings 寫入: ${fullPath} (${findings.length} 筆)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 發布所有舊問題 comment(一次發布,依等級排序)
|
||||||
|
*/
|
||||||
|
export async function postOldFindingsComment(findings) {
|
||||||
|
const old = findings.filter(f => !f.is_new);
|
||||||
|
if (old.length === 0) {
|
||||||
|
console.log(' 無舊問題,跳過');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const body = `## 📋 舊有未解決問題(${old.length} 筆)\n\n${buildTable(old)}`;
|
||||||
|
await postComment(body);
|
||||||
|
console.log(` ✅ 舊問題 comment 發布 (${old.length} 筆)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 發布新問題中非 critical 的 comment(一次發布)
|
||||||
|
*/
|
||||||
|
export async function postNewNonCriticalComment(findings) {
|
||||||
|
const items = findings.filter(f => f.is_new && f.level !== 'critical');
|
||||||
|
if (items.length === 0) {
|
||||||
|
console.log(' 無新的非嚴重問題,跳過');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const body = `## 🔍 新發現問題(${items.length} 筆)\n\n${buildTable(items)}`;
|
||||||
|
await postComment(body);
|
||||||
|
console.log(` ✅ 新問題(非嚴重)comment 發布 (${items.length} 筆)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每個新 critical 問題各發一個 comment
|
||||||
|
*/
|
||||||
|
export async function postNewCriticalComments(findings) {
|
||||||
|
const criticals = findings.filter(f => f.is_new && f.level === 'critical');
|
||||||
|
if (criticals.length === 0) {
|
||||||
|
console.log(' 無新的嚴重問題,跳過');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const f of criticals) {
|
||||||
|
const body = `## 🚨 嚴重問題\n\n| 審查員 | 位置 | 建議 |\n|--------|------|------|\n| ${f.role} | ${f.location} | ${f.suggestion} |`;
|
||||||
|
await postComment(body);
|
||||||
|
console.log(` ✅ 嚴重問題 comment 發布: [${f.role}] ${f.location}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,3 +61,35 @@ export function mergeFindings(oldFindings, newFindings) {
|
|||||||
export function sortByLevel(findings) {
|
export function sortByLevel(findings) {
|
||||||
return [...findings].sort((a, b) => LEVELS.indexOf(a.level) - LEVELS.indexOf(b.level));
|
return [...findings].sort((a, b) => LEVELS.indexOf(a.level) - LEVELS.indexOf(b.level));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 呼叫 LLM 進行語意去重,回傳去重後的 findings
|
||||||
|
* 失敗時降級回傳原始 findings
|
||||||
|
*/
|
||||||
|
export async function deduplicateWithAI(findings) {
|
||||||
|
if (findings.length === 0) return findings;
|
||||||
|
|
||||||
|
const systemPrompt = `你是一位程式碼審查問題去重專家。
|
||||||
|
給你一份問題清單(JSON 陣列),請移除語意重複的問題(即使描述文字不同,但指的是同一個問題)。
|
||||||
|
保留等級較高的版本,優先保留 critical > warning > info。
|
||||||
|
只回傳去重後的 JSON 陣列,不要有其他文字。`;
|
||||||
|
|
||||||
|
const userContent = `以下是問題清單,請去除語意重複的項目:\n\n${JSON.stringify(findings, null, 2)}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await chatJSON(systemPrompt, userContent);
|
||||||
|
if (Array.isArray(result) && result.length > 0) {
|
||||||
|
console.log(` AI 去重: ${findings.length} -> ${result.length} 筆`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
throw new Error('AI 回傳空陣列');
|
||||||
|
} catch (e) {
|
||||||
|
const status = e.response?.status;
|
||||||
|
if (status === 402 || status === 429) {
|
||||||
|
console.log(` ⚠️ AI 去重失敗(${status} 額度/限流),降級:保留所有問題`);
|
||||||
|
} else {
|
||||||
|
console.log(` ⚠️ AI 去重失敗(${e.message}),降級:保留所有問題`);
|
||||||
|
}
|
||||||
|
return findings;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { commitFile } from './gitea.js';
|
||||||
|
import { FINDINGS_PATH } from './config.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 透過 Gitea API 將 findings.json push 到來源分支(不需要 git binary)
|
||||||
|
*/
|
||||||
|
export async function commitAndPush(workspace) {
|
||||||
|
try {
|
||||||
|
const fullPath = path.join(workspace, FINDINGS_PATH);
|
||||||
|
const content = fs.readFileSync(fullPath, 'utf8');
|
||||||
|
const result = await commitFile(
|
||||||
|
FINDINGS_PATH,
|
||||||
|
content,
|
||||||
|
'chore: update ai-review findings [skip ci]'
|
||||||
|
);
|
||||||
|
const commitHash = result.commit?.sha?.slice(0, 7) || 'unknown';
|
||||||
|
console.log(` ✅ persisted findings commit=${commitHash} push=${process.env.PR_HEAD_BRANCH}`);
|
||||||
|
} catch (e) {
|
||||||
|
console.log(` ⚠️ Runner failed: commit/push 失敗: ${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
+39
-3
@@ -1,15 +1,51 @@
|
|||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { GITEA_TOKEN, GITEA_SERVER_URL, GITEA_REPOSITORY, PR_NUMBER } from './config.js';
|
import https from 'https';
|
||||||
|
import { GITEA_TOKEN, GITEA_SERVER_URL, GITEA_REPOSITORY, PR_NUMBER, PR_HEAD_BRANCH } from './config.js';
|
||||||
|
|
||||||
|
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
|
||||||
const headers = () => ({ Authorization: `token ${GITEA_TOKEN}`, 'Content-Type': 'application/json' });
|
const headers = () => ({ Authorization: `token ${GITEA_TOKEN}`, 'Content-Type': 'application/json' });
|
||||||
const api = (path) => `${GITEA_SERVER_URL.replace(/\/$/, '')}/api/v1${path}`;
|
const api = (path) => `${GITEA_SERVER_URL.replace(/\/$/, '')}/api/v1${path}`;
|
||||||
|
|
||||||
export async function getPRDiff() {
|
export async function getPRDiff() {
|
||||||
const resp = await axios.get(api(`/repos/${GITEA_REPOSITORY}/pulls/${PR_NUMBER}.diff`), { headers: headers(), timeout: 60000 });
|
const resp = await axios.get(api(`/repos/${GITEA_REPOSITORY}/pulls/${PR_NUMBER}.diff`), { headers: headers(), timeout: 60000, httpsAgent });
|
||||||
return resp.data;
|
return resp.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function postComment(body) {
|
export async function postComment(body) {
|
||||||
const resp = await axios.post(api(`/repos/${GITEA_REPOSITORY}/issues/${PR_NUMBER}/comments`), { body }, { headers: headers(), timeout: 30000 });
|
const resp = await axios.post(api(`/repos/${GITEA_REPOSITORY}/issues/${PR_NUMBER}/comments`), { body }, { headers: headers(), timeout: 30000, httpsAgent });
|
||||||
|
return resp.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 透過 Gitea API 建立或更新檔案(不需要 git binary)
|
||||||
|
*/
|
||||||
|
export async function commitFile(filePath, content, message) {
|
||||||
|
const encoded = Buffer.from(content).toString('base64');
|
||||||
|
const url = api(`/repos/${GITEA_REPOSITORY}/contents/${filePath}`);
|
||||||
|
|
||||||
|
// 先嘗試取得現有檔案的 SHA
|
||||||
|
let sha;
|
||||||
|
try {
|
||||||
|
const existing = await axios.get(`${url}?ref=${PR_HEAD_BRANCH}`, { headers: headers(), httpsAgent, timeout: 15000 });
|
||||||
|
sha = existing.data.sha;
|
||||||
|
} catch {
|
||||||
|
sha = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
message,
|
||||||
|
content: encoded,
|
||||||
|
branch: PR_HEAD_BRANCH,
|
||||||
|
...(sha ? { sha } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const resp = await axios.request({
|
||||||
|
method: sha ? 'put' : 'post',
|
||||||
|
url,
|
||||||
|
headers: headers(),
|
||||||
|
httpsAgent,
|
||||||
|
timeout: 30000,
|
||||||
|
data: payload,
|
||||||
|
});
|
||||||
return resp.data;
|
return resp.data;
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-1
@@ -1,6 +1,9 @@
|
|||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
import https from 'https';
|
||||||
import { getLLMConfig } from './config.js';
|
import { getLLMConfig } from './config.js';
|
||||||
|
|
||||||
|
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
|
||||||
|
|
||||||
export async function chat(systemPrompt, userContent) {
|
export async function chat(systemPrompt, userContent) {
|
||||||
const { provider, apiKey, baseURL, model } = getLLMConfig();
|
const { provider, apiKey, baseURL, model } = getLLMConfig();
|
||||||
if (!provider) throw new Error('未設定任何 LLM API Key');
|
if (!provider) throw new Error('未設定任何 LLM API Key');
|
||||||
@@ -16,7 +19,7 @@ export async function chat(systemPrompt, userContent) {
|
|||||||
const resp = await axios.post(
|
const resp = await axios.post(
|
||||||
`${baseURL.replace(/\/$/, '')}/chat/completions`,
|
`${baseURL.replace(/\/$/, '')}/chat/completions`,
|
||||||
{ model, messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: userContent }], temperature: 0.2 },
|
{ model, messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: userContent }], temperature: 0.2 },
|
||||||
{ headers, timeout: 120000 }
|
{ headers, timeout: 120000, httpsAgent }
|
||||||
);
|
);
|
||||||
return resp.data.choices[0].message.content;
|
return resp.data.choices[0].message.content;
|
||||||
}
|
}
|
||||||
|
|||||||
+34
-9
@@ -1,7 +1,9 @@
|
|||||||
import { GITEA_REPOSITORY, PR_NUMBER, PR_HEAD_BRANCH, PR_BASE_BRANCH, getLLMConfig } from './config.js';
|
import { GITEA_REPOSITORY, PR_NUMBER, PR_HEAD_BRANCH, PR_BASE_BRANCH, getLLMConfig } from './config.js';
|
||||||
import { loadRoles, getRoleIntro } from './roles.js';
|
import { loadRoles, getRoleIntro } from './roles.js';
|
||||||
import { getPRDiff, postComment } from './gitea.js';
|
import { getPRDiff, postComment } from './gitea.js';
|
||||||
import { analyzeWithRole, loadOldFindings, mergeFindings, sortByLevel } from './findings.js';
|
import { analyzeWithRole, loadOldFindings, mergeFindings, sortByLevel, deduplicateWithAI } from './findings.js';
|
||||||
|
import { saveFindings, postOldFindingsComment, postNewNonCriticalComment, postNewCriticalComments } from './comments.js';
|
||||||
|
import { commitAndPush } from './git.js';
|
||||||
|
|
||||||
const WORKSPACE = process.env.GITHUB_WORKSPACE || '/workspace';
|
const WORKSPACE = process.env.GITHUB_WORKSPACE || '/workspace';
|
||||||
|
|
||||||
@@ -66,17 +68,40 @@ async function main() {
|
|||||||
console.log('\n🔀 Step3: Findings 合併');
|
console.log('\n🔀 Step3: Findings 合併');
|
||||||
const oldFindings = loadOldFindings(WORKSPACE);
|
const oldFindings = loadOldFindings(WORKSPACE);
|
||||||
const mergedFindings = mergeFindings(oldFindings, newFindings);
|
const mergedFindings = mergeFindings(oldFindings, newFindings);
|
||||||
const sorted = sortByLevel(mergedFindings);
|
console.log(` Step3 merged findings total=${mergedFindings.length}`);
|
||||||
console.log(` Step3 merged findings total=${sorted.length} (critical=${sorted.filter(f=>f.level==='critical').length} warning=${sorted.filter(f=>f.level==='warning').length} info=${sorted.filter(f=>f.level==='info').length})`);
|
|
||||||
|
|
||||||
console.log('\n📝 Step4: Findings 寫入與 Comment 發布(待實作)');
|
// Step3b: AI 語意去重
|
||||||
console.log(' [stub] 寫入 findings.json,發布 comment...');
|
console.log('\n🤖 Step3b: AI 語意去重');
|
||||||
|
const deduped = await deduplicateWithAI(mergedFindings);
|
||||||
|
const sorted = sortByLevel(deduped);
|
||||||
|
console.log(` Step3b dedup findings total=${sorted.length} (critical=${sorted.filter(f=>f.level==='critical').length} warning=${sorted.filter(f=>f.level==='warning').length} info=${sorted.filter(f=>f.level==='info').length})`);
|
||||||
|
|
||||||
console.log('\n💾 Step5: 記憶區 Commit/Push(待實作)');
|
// Step4: 寫入 findings.json,依序發布 comment
|
||||||
console.log(' [stub] commit & push findings.json...');
|
console.log('\n📝 Step4: Findings 寫入與 Comment 發布');
|
||||||
|
saveFindings(WORKSPACE, sorted);
|
||||||
|
|
||||||
console.log('\n🚦 Step6: 嚴重問題檢查(待實作)');
|
try {
|
||||||
console.log(' [stub] 檢查 critical findings...');
|
await postOldFindingsComment(sorted);
|
||||||
|
await postNewNonCriticalComment(sorted);
|
||||||
|
await postNewCriticalComments(sorted);
|
||||||
|
console.log(' Step4 完成');
|
||||||
|
} catch (e) {
|
||||||
|
console.log(` ⚠️ comment 發布失敗(繼續執行): ${e.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step5: commit/push findings.json 到來源分支
|
||||||
|
console.log('\n💾 Step5: 記憶區 Commit/Push');
|
||||||
|
await commitAndPush(WORKSPACE);
|
||||||
|
|
||||||
|
// Step6: 有 critical 問題則 exit 1
|
||||||
|
console.log('\n🚦 Step6: 嚴重問題檢查');
|
||||||
|
const criticalCount = sorted.filter(f => f.level === 'critical').length;
|
||||||
|
if (criticalCount > 0) {
|
||||||
|
console.log(` ❌ 發現 ${criticalCount} 個嚴重問題,workflow 結束(exit 1)`);
|
||||||
|
console.log('='.repeat(60));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
console.log(' ✅ 無嚴重問題');
|
||||||
|
|
||||||
console.log('\n✅ Pipeline 完成');
|
console.log('\n✅ Pipeline 完成');
|
||||||
console.log('='.repeat(60));
|
console.log('='.repeat(60));
|
||||||
|
|||||||
Reference in New Issue
Block a user