Compare commits
79 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0aefa66224 | |||
| 66d93abe24 | |||
| a4b87f9108 | |||
| 09533ff741 | |||
| e217b18c62 | |||
| cd0ced1b7f | |||
| 65cf45c558 | |||
| 09c78835e7 | |||
| ec05ce7869 | |||
| 323be94a72 | |||
| 0063f3282f | |||
| d7336dbe6c | |||
| c1f8aa3c72 | |||
| 8a28d1f1ef | |||
| d04f4dd2bb | |||
| f5cf5950bd | |||
| 8c3d0d9a6d | |||
| eae73092ad | |||
| 69624a542e | |||
| 8aa273b8bd | |||
| 3849bb2168 | |||
| 00458d4eb2 | |||
| 379938d6dc | |||
| 894ece033b | |||
| 5bf39966d0 | |||
| fe2a513fbb | |||
| 2193bdd4d6 | |||
| af51ffacee | |||
| 3509a882e1 | |||
| d9c55ca347 | |||
| 1d2e8236de | |||
| 21fb9c1d94 | |||
| 607c9b82ea | |||
| 8acea007e7 | |||
| d8423c74b1 | |||
| 953951145f | |||
| 1576e783fb | |||
| e017705c64 | |||
| 94e974b5dc | |||
| 5f77b83a0f | |||
| da43cb02b0 | |||
| 577a930438 | |||
| 121f66b0b3 | |||
| faa808bb5f | |||
| 07df3ef4a5 | |||
| a9a0b43ea5 | |||
| fc537958ca | |||
| aa8234b5c7 | |||
| 1c321b7ba2 | |||
| b0f2d45c11 | |||
| 710cd7308e | |||
| 59978c6fb5 | |||
| 3fd9a7e13d | |||
| 519e04691d | |||
| 5ae0549453 | |||
| 39cc5c932c | |||
| 81e38de649 | |||
| 255adbabe4 | |||
| 4a67dec32a | |||
| a10fc8f176 | |||
| 5c5660a34b | |||
| 6ecb018ef4 | |||
| 02529a4ec9 | |||
| 624a71836c | |||
| fb1254aa32 | |||
| 6eae6eb0ce | |||
| ed1f2bea15 | |||
| 9a11d25c00 | |||
| 64b904dd07 | |||
| 73c11129ab | |||
| 7ba2af3384 | |||
| aca76f23af | |||
| bdf8d8a797 | |||
| e183e31ce0 | |||
| 7b5decf46a | |||
| 0609e7fe7f | |||
| d20300eec7 | |||
| a9163cdfda | |||
| 9b39908394 |
@@ -0,0 +1,58 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"level": "critical",
|
||||||
|
"role": "Leo",
|
||||||
|
"location": "app/git.js:11",
|
||||||
|
"suggestion": "GITEA_TOKEN 直接嵌入 URL 中,可能導致憑證洩漏。建議使用環境變數或安全的憑證管理方式來處理敏感資訊。",
|
||||||
|
"is_new": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"level": "critical",
|
||||||
|
"role": "Maya",
|
||||||
|
"location": "app/git.js:1",
|
||||||
|
"suggestion": "缺少對 commitAndPush 函數的單元測試,應該為其添加測試以確保其正確性。",
|
||||||
|
"is_new": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"level": "warning",
|
||||||
|
"role": "Leo",
|
||||||
|
"location": "app/git.js:25",
|
||||||
|
"suggestion": "在使用 fs.existsSync 檢查目錄是否存在時,應考慮使用非同步方法以避免阻塞事件循環。",
|
||||||
|
"is_new": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"level": "warning",
|
||||||
|
"role": "Leo",
|
||||||
|
"location": "app/git.js:29",
|
||||||
|
"suggestion": "在 git clone 時使用 --depth=1 可能會導致未來需要完整歷史紀錄時的性能問題,建議根據實際需求調整。",
|
||||||
|
"is_new": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"level": "warning",
|
||||||
|
"role": "Leo",
|
||||||
|
"location": "app/git.js:11",
|
||||||
|
"suggestion": "在使用 fs.copyFileSync 時,未檢查目標檔案是否存在,可能會覆蓋重要資料。建議在複製之前檢查檔案是否存在。",
|
||||||
|
"is_new": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"level": "warning",
|
||||||
|
"role": "Leo",
|
||||||
|
"location": "app/git.js:11",
|
||||||
|
"suggestion": "在 commitAndPush 函數中,對於 git 操作的錯誤處理不夠完善,應該添加更多的測試來驗證不同情況下的行為。",
|
||||||
|
"is_new": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"level": "info",
|
||||||
|
"role": "Leo",
|
||||||
|
"location": ".gitea/workflows/review.yaml:5",
|
||||||
|
"suggestion": "建議在 'branches-ignore' 前加上空行,以提高可讀性。",
|
||||||
|
"is_new": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"level": "info",
|
||||||
|
"role": "Leo",
|
||||||
|
"location": "app/git.js:45",
|
||||||
|
"suggestion": "考慮使用 async/await 來處理 fs.copyFileSync,以提高可讀性和錯誤處理能力。",
|
||||||
|
"is_new": true
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
name: AI
|
name: AI
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.head_ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
|
branches-ignore:
|
||||||
|
- master
|
||||||
types: [opened, synchronize]
|
types: [opened, synchronize]
|
||||||
jobs:
|
jobs:
|
||||||
version:
|
version:
|
||||||
@@ -21,14 +26,13 @@ jobs:
|
|||||||
tag_name: v${{ steps.version.outputs.version }}
|
tag_name: v${{ steps.version.outputs.version }}
|
||||||
target_commitish: ${{ github.head_ref }}
|
target_commitish: ${{ github.head_ref }}
|
||||||
code-review:
|
code-review:
|
||||||
name: Code Review
|
name: 'Code Review'
|
||||||
runs-on: ubuntu
|
runs-on: ubuntu
|
||||||
needs: [version]
|
needs: [version]
|
||||||
steps:
|
steps:
|
||||||
- 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:
|
||||||
# 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
|
|
||||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||||
OPENAI_BASE_URL: https://openrouter.ai/api/v1
|
OPENAI_BASE_URL: https://openrouter.ai/api/v1
|
||||||
permissions:
|
permissions:
|
||||||
|
|||||||
+5
-4
@@ -1,8 +1,9 @@
|
|||||||
FROM node:20-slim
|
FROM alpine
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apk add --no-cache bash nodejs npm git \
|
||||||
git \
|
&& node --version \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& npm --version \
|
||||||
|
&& git --version
|
||||||
|
|
||||||
WORKDIR /action
|
WORKDIR /action
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -27,6 +27,7 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
每個階段都會加上明確的 log,並確保即使部分功能未完成也能降級執行、不會中斷 pipeline。
|
每個階段都會加上明確的 log,並確保即使部分功能未完成也能降級執行、不會中斷 pipeline。
|
||||||
|
|
||||||
每次執行後請貼 log,我會協助 debug。
|
每次執行後請貼 log,我會協助 debug。
|
||||||
@@ -29,6 +29,7 @@ inputs:
|
|||||||
OPENAI_BASE_URL:
|
OPENAI_BASE_URL:
|
||||||
description: 'OpenAI-compatible Base URL'
|
description: 'OpenAI-compatible Base URL'
|
||||||
required: false
|
required: false
|
||||||
|
default: 'https://openrouter.ai/api/v1'
|
||||||
OPENAI_MODEL:
|
OPENAI_MODEL:
|
||||||
description: 'OpenAI-compatible Model Name'
|
description: 'OpenAI-compatible Model Name'
|
||||||
required: false
|
required: false
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+63
@@ -0,0 +1,63 @@
|
|||||||
|
import { spawnSync } from 'child_process';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { GITEA_SERVER_URL, GITEA_REPOSITORY, GITEA_TOKEN, PR_HEAD_BRANCH, FINDINGS_PATH } from './config.js';
|
||||||
|
|
||||||
|
function makeRunner(spawn) {
|
||||||
|
return function run(args, cwd, env) {
|
||||||
|
const opts = { cwd, encoding: 'utf8' };
|
||||||
|
if (env) opts.env = env;
|
||||||
|
const result = spawn('git', args, opts);
|
||||||
|
if (result.error) throw result.error;
|
||||||
|
if (result.status !== 0) throw new Error((result.stderr || result.stdout || '').trim());
|
||||||
|
return (result.stdout || '').trim();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function commitAndPush(workspace, _spawnSync = spawnSync) {
|
||||||
|
const run = makeRunner(_spawnSync);
|
||||||
|
|
||||||
|
const baseUrl = GITEA_SERVER_URL.replace(/\/$/, '');
|
||||||
|
const remoteUrl = `${baseUrl}/${GITEA_REPOSITORY}.git`;
|
||||||
|
const repoDir = path.join(workspace, 'repo');
|
||||||
|
|
||||||
|
// Write a temporary askpass script so the token never appears in the URL or process list
|
||||||
|
const askpassScript = path.join(workspace, '.git-askpass.sh');
|
||||||
|
fs.writeFileSync(askpassScript, `#!/bin/sh\necho "${GITEA_TOKEN}"\n`, { mode: 0o700 });
|
||||||
|
|
||||||
|
const credEnv = { ...process.env, GIT_ASKPASS: askpassScript, GIT_USERNAME: 'x-token' };
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!fs.existsSync(repoDir)) {
|
||||||
|
run(['clone', '--depth=1', '--branch', PR_HEAD_BRANCH, remoteUrl, repoDir], workspace, credEnv);
|
||||||
|
}
|
||||||
|
|
||||||
|
run(['config', 'user.email', 'ai-review[bot]@gitea'], repoDir);
|
||||||
|
run(['config', 'user.name', 'AI Review Bot'], repoDir);
|
||||||
|
run(['fetch', 'origin', PR_HEAD_BRANCH], repoDir, credEnv);
|
||||||
|
run(['checkout', PR_HEAD_BRANCH], repoDir);
|
||||||
|
|
||||||
|
// 將 findings.json 從 workspace 複製到 clone 的 repo
|
||||||
|
const srcFindings = path.join(workspace, FINDINGS_PATH);
|
||||||
|
const destFindings = path.join(repoDir, FINDINGS_PATH);
|
||||||
|
fs.mkdirSync(path.dirname(destFindings), { recursive: true });
|
||||||
|
fs.copyFileSync(srcFindings, destFindings);
|
||||||
|
|
||||||
|
run(['add', FINDINGS_PATH], repoDir);
|
||||||
|
|
||||||
|
const status = run(['status', '--porcelain'], repoDir);
|
||||||
|
if (!status) {
|
||||||
|
console.log(' findings.json 無變更,跳過 commit');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const out = run(['commit', '-m', 'chore: update ai-review findings [skip ci]'], repoDir);
|
||||||
|
const commitHash = out.match(/\[.+ ([a-f0-9]+)\]/)?.[1] || 'unknown';
|
||||||
|
run(['push', remoteUrl, PR_HEAD_BRANCH], repoDir, credEnv);
|
||||||
|
console.log(` ✅ persisted findings commit=${commitHash} push=${PR_HEAD_BRANCH}`);
|
||||||
|
} catch (e) {
|
||||||
|
console.log(` ⚠️ Runner failed: commit/push 失敗: ${e.message}`);
|
||||||
|
} finally {
|
||||||
|
try { fs.unlinkSync(askpassScript); } catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import { describe, it, before, after, beforeEach } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'fs';
|
||||||
|
import os from 'os';
|
||||||
|
import path from 'path';
|
||||||
|
import { commitAndPush } from './git.js';
|
||||||
|
|
||||||
|
// --- helpers ---
|
||||||
|
function makeTmpWorkspace() {
|
||||||
|
const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'git-test-'));
|
||||||
|
// Pre-create repo dir so clone branch is skipped
|
||||||
|
fs.mkdirSync(path.join(ws, 'repo'), { recursive: true });
|
||||||
|
// Create a findings.json to copy
|
||||||
|
const findingsDir = path.join(ws, '.gitea/ai-review');
|
||||||
|
fs.mkdirSync(findingsDir, { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(findingsDir, 'findings.json'), '[]');
|
||||||
|
return ws;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default stub: all commands succeed, status returns changes
|
||||||
|
function makeSpawn(overrides = {}) {
|
||||||
|
const calls = [];
|
||||||
|
const spawn = (cmd, args, opts) => {
|
||||||
|
const key = args[0];
|
||||||
|
calls.push({ cmd, args, opts });
|
||||||
|
if (overrides[key]) return overrides[key](args, opts);
|
||||||
|
if (key === 'status') return { status: 0, stdout: 'M .gitea/ai-review/findings.json', stderr: '', error: null };
|
||||||
|
if (key === 'commit') return { status: 0, stdout: '[feature-branch abc1234] chore', stderr: '', error: null };
|
||||||
|
return { status: 0, stdout: '', stderr: '', error: null };
|
||||||
|
};
|
||||||
|
spawn.calls = calls;
|
||||||
|
return spawn;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('commitAndPush', () => {
|
||||||
|
let workspace;
|
||||||
|
|
||||||
|
before(() => { workspace = makeTmpWorkspace(); });
|
||||||
|
after(() => { fs.rmSync(workspace, { recursive: true, force: true }); });
|
||||||
|
beforeEach(() => {
|
||||||
|
// Remove leftover askpass scripts between tests
|
||||||
|
for (const f of fs.readdirSync(workspace)) {
|
||||||
|
if (f.endsWith('.git-askpass.sh')) fs.unlinkSync(path.join(workspace, f));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not embed token in any git command argument', async () => {
|
||||||
|
const spawn = makeSpawn();
|
||||||
|
await commitAndPush(workspace, spawn);
|
||||||
|
|
||||||
|
for (const { args } of spawn.calls) {
|
||||||
|
assert.ok(!args.join(' ').includes('test-token'), `Token leaked in git args: ${args.join(' ')}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses GIT_ASKPASS env for network operations (fetch, push, clone)', async () => {
|
||||||
|
const spawn = makeSpawn();
|
||||||
|
await commitAndPush(workspace, spawn);
|
||||||
|
|
||||||
|
const networkOps = ['fetch', 'push', 'clone'];
|
||||||
|
const networkCalls = spawn.calls.filter(c => networkOps.includes(c.args[0]));
|
||||||
|
assert.ok(networkCalls.length > 0, 'expected at least one network git call');
|
||||||
|
|
||||||
|
for (const { args, opts } of networkCalls) {
|
||||||
|
assert.ok(opts?.env?.GIT_ASKPASS, `GIT_ASKPASS missing for git ${args[0]}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cleans up askpass script after successful run', async () => {
|
||||||
|
await commitAndPush(workspace, makeSpawn());
|
||||||
|
const leftover = fs.readdirSync(workspace).filter(f => f.endsWith('.git-askpass.sh'));
|
||||||
|
assert.equal(leftover.length, 0, 'askpass script was not cleaned up');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cleans up askpass script even when git fails', async () => {
|
||||||
|
const failSpawn = () => ({ status: 1, stdout: '', stderr: 'fatal: error', error: null });
|
||||||
|
await commitAndPush(workspace, failSpawn);
|
||||||
|
const leftover = fs.readdirSync(workspace).filter(f => f.endsWith('.git-askpass.sh'));
|
||||||
|
assert.equal(leftover.length, 0, 'askpass script was not cleaned up after failure');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips commit when status shows no changes', async () => {
|
||||||
|
const spawn = makeSpawn({ status: () => ({ status: 0, stdout: '', stderr: '', error: null }) });
|
||||||
|
await commitAndPush(workspace, spawn);
|
||||||
|
const commitCalled = spawn.calls.some(c => c.args[0] === 'commit');
|
||||||
|
assert.equal(commitCalled, false, 'commit should not run when there are no changes');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not throw when git command fails', async () => {
|
||||||
|
const failSpawn = () => ({ status: 1, stdout: '', stderr: 'fatal: error', error: null });
|
||||||
|
await assert.doesNotReject(() => commitAndPush(workspace, failSpawn));
|
||||||
|
});
|
||||||
|
});
|
||||||
+4
-2
@@ -1,15 +1,17 @@
|
|||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
import https from 'https';
|
||||||
import { GITEA_TOKEN, GITEA_SERVER_URL, GITEA_REPOSITORY, PR_NUMBER } from './config.js';
|
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 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;
|
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));
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
"name": "ai-code-review",
|
"name": "ai-code-review",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"test": "node --test app/git.test.js"
|
||||||
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.6.7",
|
"axios": "^1.6.7",
|
||||||
"js-yaml": "^4.1.0",
|
"js-yaml": "^4.1.0",
|
||||||
|
|||||||
Reference in New Issue
Block a user