Compare commits

...

42 Commits

Author SHA1 Message Date
jiantw83 2193bdd4d6 fix: 改回 Gitea API commit,修正 URL encode 與 JSON.stringify 2026-05-11 10:30:07 +00:00
jiantw83 af51ffacee fix: 換用 node:20 完整版(內建 git,不需要 apt-get) 2026-05-11 10:24:24 +00:00
jiantw83 d9c55ca347 chore: add newline at end of TODO.md for better formatting 2026-05-11 10:18:34 +00:00
jiantw83 21fb9c1d94 fix: 改回 git commit/push,強制 Dockerfile rebuild 確保 git binary 存在 2026-05-11 10:15:36 +00:00
jiantw83 607c9b82ea debug: log content_len,改用 JSON.stringify 2026-05-11 10:13:57 +00:00
jiantw83 8acea007e7 chore: remove duplicate log assistance note in TODO.md 2026-05-11 10:12:47 +00:00
jiantw83 953951145f chore: remove test findings 2026-05-11 10:11:56 +00:00
jiantw83 1576e783fb test 2026-05-11 10:11:40 +00:00
jiantw83 e017705c64 chore: remove test findings 2026-05-11 10:10:27 +00:00
jiantw83 5f77b83a0f debug: commitFile 加上詳細 log 2026-05-11 10:09:16 +00:00
jiantw83 da43cb02b0 chore: update ai-review findings [skip ci] 2026-05-11 10:08:57 +00:00
AI Review Bot 577a930438 chore: update ai-review findings [skip ci] 2026-05-11 10:08:26 +00:00
jiantw83 121f66b0b3 debug: git.js 加上參數 log 2026-05-11 10:06:28 +00:00
jiantw83 faa808bb5f test update 2026-05-11 10:06:05 +00:00
jiantw83 07df3ef4a5 test 2026-05-11 10:05:57 +00:00
jiantw83 fc537958ca debug: commit/push 失敗時顯示詳細錯誤 2026-05-11 10:01:40 +00:00
jiantw83 1c321b7ba2 fix: commitAndPush 加上 await 2026-05-11 10:00:08 +00:00
jiantw83 710cd7308e fix: 改用 Gitea API commit findings.json,不依賴 git binary 2026-05-11 09:57:49 +00:00
jiantw83 59978c6fb5 fix: add newline at end of TODO.md for proper formatting 2026-05-11 09:56:10 +00:00
jiantw83 519e04691d fix: git.js 改用 spawnSync 直接呼叫 git binary(避免 /bin/sh ENOENT) 2026-05-11 09:51:28 +00:00
jiantw83 5ae0549453 feat: 階段五六 - findings commit/push 到來源分支,critical 問題 exit 1 2026-05-11 09:49:07 +00:00
jiantw83 81e38de649 feat: 階段四 - findings 寫入與 comment 依序發布(舊問題→非嚴重→嚴重) 2026-05-11 09:44:45 +00:00
jiantw83 4a67dec32a feat: 階段三 - AI 語意去重,失敗時降級保留所有問題 2026-05-11 09:40:38 +00:00
jiantw83 5c5660a34b feat: update OpenAI base URL to use OpenRouter API 2026-05-11 09:37:53 +00:00
jiantw83 6ecb018ef4 feat: update OpenAI base URL to use OpenRouter API 2026-05-11 09:37:01 +00:00
jiantw83 02529a4ec9 feat: update OpenAI API key in README.md 2026-05-11 09:34:43 +00:00
jiantw83 624a71836c feat: update AI Code Review step to use OpenAI API key and base URL 2026-05-11 09:31:01 +00:00
jiantw83 fb1254aa32 feat: refactor AI Code Review step to use OLLAMA_BASE_URL and OLLAMA_MODEL
Co-authored-by: Copilot <copilot@github.com>
2026-05-11 09:10:20 +00:00
jiantw83 6eae6eb0ce feat: add OPENAI_MODEL parameter to AI Code Review step 2026-05-11 09:07:21 +00:00
jiantw83 ed1f2bea15 feat: update AI Code Review step to use DeepSeek API and correct API key
Co-authored-by: Copilot <copilot@github.com>
2026-05-11 09:03:03 +00:00
jiantw83 9a11d25c00 revert: 移除 DeepSeek-R1 特別處理 2026-05-11 08:58:59 +00:00
jiantw83 64b904dd07 fix: 支援不接受 system role 的模型(DeepSeek-R1) 2026-05-11 08:56:48 +00:00
jiantw83 73c11129ab feat: update AI Code Review step to use new OpenAI base URL and model 2026-05-11 08:55:53 +00:00
jiantw83 7ba2af3384 feat: update OPENAI_MODEL to use DeepSeek-R1-Distill-Qwen-32B for improved performance 2026-05-11 08:54:13 +00:00
jiantw83 aca76f23af feat: add OPENAI_MODEL parameter to AI Code Review step 2026-05-11 08:53:03 +00:00
jiantw83 bdf8d8a797 feat: update AI Code Review step to use OpenAI API key and base URL 2026-05-11 08:47:34 +00:00
jiantw83 e183e31ce0 fix: 忽略 SSL 憑證驗證(支援自簽憑證的 Ollama/Gitea) 2026-05-11 08:34:04 +00:00
jiantw83 7b5decf46a feat: update AI Code Review step to use vars instead of secrets for improved flexibility 2026-05-11 08:31:02 +00:00
jiantw83 0609e7fe7f feat: update OLLAMA configuration to use vars instead of secrets for improved flexibility 2026-05-11 08:29:59 +00:00
jiantw83 d20300eec7 feat: format AI Code Review step for improved readability 2026-05-11 08:27:51 +00:00
jiantw83 a9163cdfda feat: update AI Code Review action inputs to use OLLAMA configuration and set default OpenAI base URL 2026-05-11 08:24:47 +00:00
jiantw83 06303f784a feat: update workflow configurations for version calculation and API integration 2026-05-11 08:20:57 +00:00
12 changed files with 207 additions and 25 deletions
+4 -3
View File
@@ -1,10 +1,11 @@
name: CD
on:
push:
branches:
- master
jobs:
version:
name: "CD > 計算版本號"
name: 計算版本號
runs-on: ubuntu
outputs:
version: ${{ steps.version.outputs.version }}
@@ -13,14 +14,14 @@ jobs:
id: version
uses: https://gitea.jsc.idv.tw/actions/calculate-version@${{ vars.ACTION_CALCULATE_VERSION }}
release:
name: "CD > 發布專案"
name: 發布專案
runs-on: ubuntu
needs: version
steps:
- name: 發布專案
uses: akkuman/gitea-release-action@${{ vars.ACTION_RELEASE_VERSION }}
with:
tag_name: "v${{ needs.version.outputs.version }}"
tag_name: v${{ needs.version.outputs.version }}
- name: 清理成品
uses: https://gitea.jsc.idv.tw/actions/cleanup-release@${{ vars.ACTION_CLEANUP_RELEASE_VERSION }}
with:
+2 -2
View File
@@ -21,7 +21,7 @@ jobs:
tag_name: v${{ steps.version.outputs.version }}
target_commitish: ${{ github.head_ref }}
code-review:
name: Code Review
name: 'Code Review'
runs-on: ubuntu
needs: [version]
steps:
@@ -29,7 +29,7 @@ jobs:
uses: https://gitea.jsc.idv.tw/jiantw83/code-review@v${{ needs.version.outputs.version }}
with:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
OPENAI_BASE_URL: https://api.openai.com/v1
OPENAI_BASE_URL: https://openrouter.ai/api/v1
permissions:
contents: write
pull-requests: write
+1 -5
View File
@@ -1,8 +1,4 @@
FROM node:20-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
git \
&& rm -rf /var/lib/apt/lists/*
FROM node:20
WORKDIR /action
+5 -3
View File
@@ -41,8 +41,10 @@ jobs:
- name: AI Code Review
uses: https://gitea.jsc.idv.tw/jiantw83/code-review@${{ vars.ACTION_CODE_REVIEW_VERSION }}
with:
# Github (h3285@evertrust.com.tw)
# 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
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
OPENAI_BASE_URL: https://api.openai.com/v1
OPENAI_BASE_URL: https://openrouter.ai/api/v1
permissions:
contents: write
pull-requests: write
@@ -262,8 +264,8 @@ jobs:
- name: AI Code Review
uses: https://gitea.jsc.idv.tw/jiantw83/code-review@${{ vars.ACTION_CODE_REVIEW_VERSION }}
with:
OLLAMA_BASE_URL: ${{ secrets.OLLAMA_BASE_URL }}
OLLAMA_MODEL: ${{ secrets.OLLAMA_MODEL }}
OLLAMA_BASE_URL: ${{ vars.OLLAMA_BASE_URL }}
OLLAMA_MODEL: ${{ vars.OLLAMA_MODEL }}
permissions:
contents: write
pull-requests: write
+1
View File
@@ -27,6 +27,7 @@
---
每個階段都會加上明確的 log,並確保即使部分功能未完成也能降級執行、不會中斷 pipeline。
每次執行後請貼 log,我會協助 debug。
+1
View File
@@ -29,6 +29,7 @@ inputs:
OPENAI_BASE_URL:
description: 'OpenAI-compatible Base URL'
required: false
default: 'https://openrouter.ai/api/v1'
OPENAI_MODEL:
description: 'OpenAI-compatible Model Name'
required: false
+70
View File
@@ -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}`);
}
}
+32
View File
@@ -61,3 +61,35 @@ export function mergeFindings(oldFindings, newFindings) {
export function sortByLevel(findings) {
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;
}
}
+49
View File
@@ -0,0 +1,49 @@
import fs from 'fs';
import path from 'path';
import axios from 'axios';
import https from 'https';
import { GITEA_TOKEN, GITEA_SERVER_URL, GITEA_REPOSITORY, PR_HEAD_BRANCH, FINDINGS_PATH } from './config.js';
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
const headers = () => ({ Authorization: `token ${GITEA_TOKEN}`, 'Content-Type': 'application/json' });
const api = (p) => `${GITEA_SERVER_URL.replace(/\/$/, '')}/api/v1${p}`;
export async function commitAndPush(workspace) {
try {
const fullPath = path.join(workspace, GITEA_REPOSITORY, FINDINGS_PATH);
const content = fs.readFileSync(fullPath, 'utf8');
const encoded = Buffer.from(content).toString('base64');
const url = api(`/repos/${GITEA_REPOSITORY}/contents/${FINDINGS_PATH}`);
// 取得現有檔案 SHA(若存在)
let sha;
try {
const res = await axios.get(`${url}?ref=${encodeURIComponent(PR_HEAD_BRANCH)}`, { headers: headers(), httpsAgent, timeout: 15000 });
sha = res.data.sha;
} catch {
sha = undefined;
}
const payload = JSON.stringify({
message: 'chore: update ai-review findings [skip ci]',
content: encoded,
branch: PR_HEAD_BRANCH,
...(sha ? { sha } : {}),
});
const resp = await axios.request({
method: sha ? 'put' : 'post',
url,
headers: { ...headers(), 'Content-Type': 'application/json' },
httpsAgent,
timeout: 30000,
data: payload,
});
const commitHash = resp.data.commit?.sha?.slice(0, 7) || 'unknown';
console.log(` ✅ persisted findings commit=${commitHash} push=${PR_HEAD_BRANCH}`);
} catch (e) {
const detail = e.response?.data ? JSON.stringify(e.response.data) : e.message;
console.log(` ⚠️ Runner failed: commit/push 失敗: ${e.response?.status || ''} ${detail}`);
}
}
+4 -2
View File
@@ -1,15 +1,17 @@
import axios from 'axios';
import https from 'https';
import { GITEA_TOKEN, GITEA_SERVER_URL, GITEA_REPOSITORY, PR_NUMBER } from './config.js';
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
const headers = () => ({ Authorization: `token ${GITEA_TOKEN}`, 'Content-Type': 'application/json' });
const api = (path) => `${GITEA_SERVER_URL.replace(/\/$/, '')}/api/v1${path}`;
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;
}
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;
}
+4 -1
View File
@@ -1,6 +1,9 @@
import axios from 'axios';
import https from 'https';
import { getLLMConfig } from './config.js';
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
export async function chat(systemPrompt, userContent) {
const { provider, apiKey, baseURL, model } = getLLMConfig();
if (!provider) throw new Error('未設定任何 LLM API Key');
@@ -16,7 +19,7 @@ export async function chat(systemPrompt, userContent) {
const resp = await axios.post(
`${baseURL.replace(/\/$/, '')}/chat/completions`,
{ 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;
}
+34 -9
View File
@@ -1,7 +1,9 @@
import { GITEA_REPOSITORY, PR_NUMBER, PR_HEAD_BRANCH, PR_BASE_BRANCH, getLLMConfig } from './config.js';
import { loadRoles, getRoleIntro } from './roles.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';
@@ -66,17 +68,40 @@ async function main() {
console.log('\n🔀 Step3: Findings 合併');
const oldFindings = loadOldFindings(WORKSPACE);
const mergedFindings = mergeFindings(oldFindings, newFindings);
const sorted = sortByLevel(mergedFindings);
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(` Step3 merged findings total=${mergedFindings.length}`);
console.log('\n📝 Step4: Findings 寫入與 Comment 發布(待實作)');
console.log(' [stub] 寫入 findings.json,發布 comment...');
// Step3b: AI 語意去重
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(待實作)');
console.log(' [stub] commit & push findings.json...');
// Step4: 寫入 findings.json,依序發布 comment
console.log('\n📝 Step4: Findings 寫入與 Comment 發布');
saveFindings(WORKSPACE, sorted);
console.log('\n🚦 Step6: 嚴重問題檢查(待實作)');
console.log(' [stub] 檢查 critical findings...');
try {
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('='.repeat(60));