docs: finalize v2.0 — SOP, optimization record, staleness, README sync

- README: v2.0 observability/reliability additions section
- docs/SOP.md: standard operating procedure for dev/deploy/troubleshoot
- docs/optimization-record.md: optimized ranges + next-starting point
- src/review/staleness.ts: head-change detection (append/discard, 5 tests)
- workflow_status.md: final audit state with all C1-C6 closed
This commit is contained in:
ghbot committed 2026-08-24 20:25:33 +08:00
1 parent 472003ae6a
commit 9c97516b2d
6 files changed
+453 -83

No files matched your search

+14 -1
View File
@@ -255,11 +255,24 @@ All changes must pass the local gates before push; CI ([.github/workflows/ci.yml
npm run typecheck # TypeScript strict check
npm run lint # ESLint (flat config)
npm run format:check # Prettier formatting
npm test # node:test suite
npm test # node:test suite (currently 329 passing)
```
The optional webhook service exposes `GET /healthz` and `GET /metrics` (Prometheus text format) for probes and dashboards. The production-hardening change ledger and quiz live at [docs/reports/ghbot-production-hardening.html](docs/reports/ghbot-production-hardening.html).
### v2.0 observability and reliability additions
v2.0 added three supporting modules and hardened the merge/review pipeline:
- **`src/metrics/collector.ts`** — `MetricsCollector` for Actions runs (review duration, outcomes, goose calls, conflict resolutions, merge attempts, cache hits). `snapshot()` and `formatMarkdown()` render a GitHub-flavored summary table.
- **`src/ai/failureMessages.ts`** — `categorizeFailure` (timeout / auth / rate_limit / network / model / validation / unknown) and `formatFailureMessage` produce actionable failure text; wired into the goose error path.
- **`src/review/merge-guard.ts`** — in-process duplicate-merge prevention used around `pulls.merge`.
- **`src/review/staleness.ts`** — `evaluateReviewStaleness` decides whether a head-sha change during a review should be appended or discarded.
- **`src/github/errors.ts`** — shared `isNotFoundError` / `isAlreadyMergedError` helpers, replacing five local duplicates.
- **`src/webhook/queueStore.ts`** — optional durable delivery queue (default off) so webhook tasks survive a process restart.
These were introduced by the changes documented in [docs/audit-v2-final.md](docs/audit-v2-final.md) and [docs/report-v2.html](docs/report-v2.html).
## Local development
```bash
+161
View File
@@ -0,0 +1,161 @@
# ghbot 标准操作流程(SOP)
## 目标
确保 ghbot 的部署、维护、排障和交接有统一标准,新成员可独立操作。
## 1. 开发环境搭建
### 1.1 前置条件
- Node.js >=22 <26
- npm >=10
- Git
- 推荐:VS Code + ESLint + Prettier 插件
### 1.2 首次安装
```bash
git clone <repo-url>
cd ghbot
npm install
npm run typecheck # 确认类型检查通过
npm test # 确认 329 测试全绿
npm run build # 确认编译成功
```
### 1.3 环境变量
复制 `.env.example` 到 `.env`,按需填写:
```bash
cp .env.example .env
# 编辑 .env 填入必要配置
```
## 2. 开发循环
### 2.1 标准流程
```bash
# 1. TypeScript 类型检查
npm run typecheck
# 2. ESLint 检查
npm run lint
# 3. 格式化检查
npm run format:check
# 4. 运行测试
npm test
# 5. 构建
npm run build
```
### 2.2 提交前检查清单
- [ ] `npm run typecheck` 通过
- [ ] `npm run lint` 0 error
- [ ] `npm run format:check` 通过
- [ ] `npm test` 全部通过
- [ ] 新功能有对应测试
- [ ] README 已同步更新
## 3. 新增功能流程
### 3.1 新增 API 端点
1. 在 `src/` 下新建模块文件
2. 在 `src/actions/router.ts` 注册新 EventHandler
3. 在 `test/` 下新建测试文件
4. 运行 `npm test` 确认全绿
### 3.2 新增审查检查
1. 修改 `src/review/gooseReviewer.ts` 的 `buildPrompt` 内容
2. 更新 `src/review/normalize.ts` 的校验规则(如需)
3. 更新测试文件
### 3.3 新增配置项
1. 在 `src/config.ts` 的 `configSchema` 中添加新字段
2. 在 `.env.example` 中添加示例
3. 在 README 中文档化
## 4. 发布流程
### 4.1 版本号规则
- 大版本:`v1.0.0` → `v2.0.0`(破坏性变更)
- 小版本:`v1.2.0` → `v1.3.0`(新功能)
- 补丁:`v1.2.0` → `v1.2.1`(bug 修复)
### 4.2 发布命令
```bash
# 1. 确认所有门禁通过
npm run typecheck && npm run lint && npm run format:check && npm test && npm run build
# 2. 提交
git add -A
git commit -m "feat: description"
# 3. 打标签
git tag -a v2.0.0 -m "v2.0.0 — description"
# 4. 推送
git push origin main
git push origin v2.0.0
```
## 5. 排障指南
### 5.1 测试失败
```bash
# 单独运行失败的测试文件
node --import tsx --test test/<file>.test.ts
# 查看详细错误
node --import tsx --test test/<file>.test.ts 2>&1 | grep -A 20 "fail"
```
### 5.2 类型错误
```bash
npm run typecheck 2>&1 | grep "error TS"
```
### 5.3 Webhook 启动失败
```bash
# 确认环境变量完整
WEBHOOK_ENABLED=true
WEBHOOK_SECRET=<secret>
# 检查端口占用
netstat -ano | findstr :3000
```
## 6. 关键文件索引
| 文件 | 用途 |
| ----------------------------- | ----------------------- |
| `src/config.ts` | 所有环境变量 zod schema |
| `src/actions/router.ts` | 事件路由注册 |
| `src/review/processor.ts` | 审查编排核心 |
| `src/review/gooseReviewer.ts` | 审查 prompt + schema |
| `src/review/policy.ts` | 审查策略逻辑 |
| `src/ai/gooseCli.ts` | goose CLI 封装 |
| `src/webhook/server.ts` | webhook HTTP 服务 |
| `src/logger.ts` | pino 日志配置 |
| `src/retry.ts` | 指数退避重试 |
| `src/github/errors.ts` | 共享错误工具 |
| `src/metrics/collector.ts` | 指标收集器 |
| `src/ai/failureMessages.ts` | 失败分类告警 |
| `src/review/merge-guard.ts` | 合并防重入 |
| `src/review/staleness.ts` | 陈旧检测 |
| `src/webhook/queueStore.ts` | 队列持久化 |
| `docs/optimization-record.md` | 优化验证记录 |
+84
View File
@@ -0,0 +1,84 @@
---
name: ghbot-v2-optimization-record
description: ghbot v2.0 迭代优化验证记录,记录已优化的范围和下一次起始点
metadata:
type: reference
version: "2.0.0"
last_updated: "2026-08-24"
---
# ghbot v2.0 迭代优化验证记录
## 已优化的范围(下次直接跳过,不再重复检查)
### 测试覆盖(M0)
- `gooseReviewer.ts`:97.35% 覆盖(已补 11 测试)
- `r2.ts`:100% 覆盖(已补 22 测试)
- `triage/processor.ts`:63.19% 覆盖(已补 11 测试)
- `webhook/processor.ts`:72.39% 覆盖(已补 35 测试)
- `conflictResolver.ts`:57.52% 覆盖(已补 12 测试)
- `review/processor.ts`:49.42% 覆盖(已补 7 测试)
- `retry.ts`:100% 覆盖(已补 5 测试)
- `merge-guard.ts`:100% 覆盖(5 测试)
- `failureMessages.ts`:100% 覆盖(8 测试)
- `metrics/collector.ts`:100% 覆盖(11 测试)
- `queueStore.ts`:100% 覆盖(3 测试)
- `staleness.ts`:100% 覆盖(5 测试)
### 可靠性(M1)
- `withRetry` 抖动 + 总超时 + 自定义重试谓词
- `MergeGuard` 合并防重入锁(已接入 processor.ts)
- `failureMessages` 失败分类(已接入 gooseCli.ts)
- `waitForMergeable` 30s 超时 + 20 轮询上限
### 可观测性(M2)
- `MetricsCollector` 指标收集器
- `recordMergeAttempt` 已接入合并路径
### 审查修复(Critical Review C1-C6)
- C1: MergeGuard 接入 `maybeMergePullRequest`
- C2: MetricsCollector 接入 merge 路径
- C3: failureMessages 接入 goose 错误路径
- C4: `markReviewCheckApproved` sort NaN 修复
- C5: 冲突绕过 admin 审批防护
- C6: `isNotFoundError` 5 处重复 → `github/errors.ts` 共享
### 新增模块
- `src/webhook/queueStore.ts` 持久队列
- `src/review/staleness.ts` 陈旧检测
- `src/github/errors.ts` 共享错误工具
### 文档
- `docs/audit-v2-final.md` 审计报告
- `docs/critical-review-v2.md` 关键审查
- `docs/report-v2.html` HTML 报告(含 10 题测验)
- `spec/v2-finalization-spec.md` 规范
- `tasks/plan.md` + `tasks/todo.md` 任务计划
- `README.md` 已更新 v2.0 新增模块说明
## 未优化的范围(下次起始点)
### 尚未处理
- M0-8:集成测试(需 testcontainers/MinIO 基础设施)
- M1-2:陈旧检测接 processor.ts(staleness.ts 已定义,未接入主流程)
- processor.ts 1736 行 / conflictResolver.ts 1250 行(用户明确"严禁重构")
- 无 Redis/Cache-Aside 缓存层
- 无 Rate Limiting 中间件
- 无 Circuit Breaker 模式
- 无 Message Queue(Kafka/RabbitMQ)集成
- 无 SQL 数据库(项目无数据库依赖,无需慢查询优化)
- 无国际化(i18n)
- 无 AI Provider 抽象层
## 下次启动时优先读取此文件
- 跳过 v2.0 已优化的所有模块
- 从"未优化的范围"列表中选择最高优先级项开始
- 关注 `processor.ts` 的增量补强而非拆分
+63
View File
@@ -0,0 +1,63 @@
import type { PullRequestFile } from "../types.js";
export type StalenessDecision =
{ action: "unchanged" } | { action: "append"; additionalPrompt: string } | { action: "discard" };
/**
* Evaluate whether a head SH change during LLM review should be:
* - "unchanged": head did not change; proceed normally
* - "append": head changed with a small additive delta; append a suffix to a
* new prompt so the model re-checks without a full re-run
* - "discard": head changed with a large or non-additive delta; drop the
* stale result and re-review from scratch
*/
export function evaluateReviewStaleness(params: {
beforeFiles: PullRequestFile[];
afterFiles: PullRequestFile[];
oldHeadSha: string;
newHeadSha: string;
maxPatchChars: number;
}): StalenessDecision {
if (params.oldHeadSha === params.newHeadSha) {
return { action: "unchanged" };
}
const beforeNames = new Set(params.beforeFiles.map((file) => file.filename));
// Detect any file that was removed or modified beyond addition. If a file
// existed before and its patch differs, it is not a pure additive delta.
for (const file of params.afterFiles) {
if (!beforeNames.has(file.filename)) {
continue;
}
const before = params.beforeFiles.find((item) => item.filename === file.filename);
if (!before || before.patch !== file.patch) {
return { action: "discard" };
}
}
// Collect newly added files only (files that did not exist before).
const addedFiles = params.afterFiles.filter((file) => !beforeNames.has(file.filename));
const addedPatchChars = addedFiles.reduce((total, file) => total + (file.patch?.length ?? 0), 0);
if (addedPatchChars > params.maxPatchChars / 2) {
return { action: "discard" };
}
const addedSuffix = addedFiles
.map((file) => ({ path: file.filename, patch: file.patch ?? "" }))
.filter((file) => file.patch.length > 0);
if (addedSuffix.length === 0) {
return { action: "discard" };
}
return {
action: "append",
additionalPrompt: [
"Additional changes were pushed while the review was running.",
"Re-evaluate only the additions below against the existing review context.",
JSON.stringify(addedSuffix, null, 2)
].join("\n")
};
}
+72
View File
@@ -0,0 +1,72 @@
import assert from "node:assert/strict";
import test from "node:test";
import { evaluateReviewStaleness } from "../src/review/staleness.js";
import type { PullRequestFile } from "../src/types.js";
const SHA_A = "a".repeat(40);
const SHA_B = "b".repeat(40);
function file(filename: string, patch: string): PullRequestFile {
return { filename, patch, status: "modified", additions: 0, deletions: 0 };
}
test("returns unchanged when heads match", () => {
const result = evaluateReviewStaleness({
beforeFiles: [file("a.ts", "+1")],
afterFiles: [file("a.ts", "+1")],
oldHeadSha: SHA_A,
newHeadSha: SHA_A,
maxPatchChars: 1000
});
assert.deepEqual(result, { action: "unchanged" });
});
test("returns discard when an existing file's patch changed", () => {
const result = evaluateReviewStaleness({
beforeFiles: [file("a.ts", "+1")],
afterFiles: [file("a.ts", "+changed")],
oldHeadSha: SHA_A,
newHeadSha: SHA_B,
maxPatchChars: 1000
});
assert.deepEqual(result, { action: "discard" });
});
test("returns discard when delta exceeds half the max patch", () => {
const big = "+".repeat(600);
const result = evaluateReviewStaleness({
beforeFiles: [file("a.ts", "+1")],
afterFiles: [file("a.ts", "+1"), file("big.ts", big)],
oldHeadSha: SHA_A,
newHeadSha: SHA_B,
maxPatchChars: 1000
});
assert.deepEqual(result, { action: "discard" });
});
test("returns append when only small additive files were added", () => {
const result = evaluateReviewStaleness({
beforeFiles: [file("a.ts", "+1")],
afterFiles: [file("a.ts", "+1"), file("b.ts", "+2")],
oldHeadSha: SHA_A,
newHeadSha: SHA_B,
maxPatchChars: 1000
});
assert.equal(result.action, "append");
if (result.action === "append") {
assert.ok(result.additionalPrompt.includes("b.ts"));
assert.ok(result.additionalPrompt.includes("+2"));
assert.ok(!result.additionalPrompt.includes("a.ts"));
}
});
test("returns discard when added files have no patch content", () => {
const result = evaluateReviewStaleness({
beforeFiles: [file("a.ts", "+1")],
afterFiles: [file("a.ts", "+1"), file("empty.ts", "")],
oldHeadSha: SHA_A,
newHeadSha: SHA_B,
maxPatchChars: 1000
});
assert.deepEqual(result, { action: "discard" });
});
+59 -82
View File
@@ -1,96 +1,73 @@
# workflow_status.md — v2.0 迭代执行审计
# workflow_status.md — ghbot v2.0 终局闭环总审计
**任务**: 下一步改进指南 M0-M7 完整落地(第一阶段已执行)
**当前版本**: v1.2.0 → v2.0 半程
**更新**: 2026-08-24
**任务**: 下一步改进指南 M0-M7 落地 → v2.0 终局闭环
**当前版本**: v1.2.0 → **v2.0.0**(已推送 + tag)
**更新**: 2026-08-24(最终)
## 执行结果总览
## 门禁验证(实测)
| 门禁 | 状态 |
| -------------------- | ---------------------------------------------------------------------------- |
| npm run typecheck | ✅ 通过 |
| npm run lint | ✅ 0 error |
| npm run format:check | ✅ All matched files use Prettier code style! |
| npm test | ✅ 321 tests / 321 pass / 0 fail |
| npm run build | ✅ dist/ 构建成功 |
| 覆盖率 | 66.20% lines / 87.36% branches / 75.57% functions |
| 审计报告 | ✅ docs/audit-v2-final.md 已生成(含盲点扫描、安全评审、架构评审、测试评审) |
```text
npm run typecheck → ✅ 通过
npm run lint → ✅ 0 error
npm run format:check → ✅ All matched files use Prettier code style!
npm test → ✅ 329 tests / 329 pass / 0 fail
npm run build → ✅ dist/ 构建成功
```
## 测试规模增长
| 指标 | 之前(v1.2.0) | 现在 | 增长 |
| ---------------- | -------------- | ------ | ------ |
| 测试文件 | 36 | 48 | +12 |
| 测试数 | 151 | 321 | +170 |
| 覆盖率 lines | 61.41% | 66.20% | +4.79% |
| 覆盖率 branches | 82.98% | 87.36% | +4.38% |
| 覆盖率 functions | 69.97% | 75.57% | +5.60% |
| 指标 | v1.2.0 | v2.0.0 | 增长 |
|------|--------|--------|------|
| 测试数 | 151 | **329** | +178 |
| 测试文件 | 36 | **55** | +19 |
| 覆盖率 lines | 61.41% | **~66%** | +4.8pp |
## 新增文件清单
## 里程碑状态
### 源文件(新模块)
| 里程碑 | 状态 | 证据 |
|--------|------|------|
| M0 覆盖补齐 | ✅ | gooseReviewer 97%/r2 100%/triage 63%/webhook 72%/conflict 57%/processor 49% |
| M1 可靠性 | ✅ | withRetry 抖动+超时、MergeGuard、failureMessages、waitForMergeable 30s 超时 |
| M2 可观测性 | ✅ | MetricsCollector + recordMergeAttempt 接入 |
| M3 大文件拆分 | ⏸️ 明确不做 | 用户红线"严禁重构任何文件",改为增量补强 |
| M4-M7 后续 | 📋 已挂账 | 见 optimization-record.md |
| 审计 | ✅ | docs/audit-v2-final.md |
| 关键审查 | ✅ | docs/critical-review-v2.md(C1-C6 全部修复) |
| 报告+测验 | ✅ | docs/report-v2.html(10 题交互测验) |
| 文件 | 功能 | 覆盖 | 生产接入 |
| --------------------------- | ---------------------- | ---- | --------- |
| `src/ai/failureMessages.ts` | 失败分类与告警文案 | 100% | ❌ 未接入 |
| `src/review/merge-guard.ts` | 合并防重入锁 | 100% | ❌ 未接入 |
| `src/metrics/collector.ts` | Actions 运行指标收集器 | 100% | ❌ 未接入 |
## 终局闭环清单
### 测试文件(新)
| 交付物 | 状态 | 说明 |
|--------|------|------|
| v2.0.0 推送 + tag | ✅ | fork (lza6/ghbot-Nodeloc) |
| Critical Review C1-C6 | ✅ 全修 | MergeGuard/Metrics/failureMessages 接线 + sort NaN + conflict 绕过 + DRY errors |
| src/github/errors.ts | ✅ | 消除 5 处 isNotFoundError 重复 |
| staleness.ts 陈旧检测 | ✅ | 5 测试,追加/丢弃决策 |
| queueStore.ts 持久队列 | ✅ | 3 测试 |
| spec-driven 规范 | ✅ | spec/v2-finalization-spec.md |
| tasks 计划 | ✅ | tasks/plan.md + tasks/todo.md |
| Spec Kit + agent-skills | ✅ | 28 技能已安装 |
| README 同步 | ✅ | v2.0 新增模块说明 |
| SOP 文档 | ✅ | docs/SOP.md |
| 优化验证记录 | ✅ | docs/optimization-record.md |
| 文件 | 测试数 | 覆盖范围 |
| -------------------------------------- | ------ | -------- |
| `test/goose-reviewer.test.ts` | 11 | 97.35% |
| `test/r2-storage.test.ts` | 22 | 100% |
| `test/triage-processor-extra.test.ts` | 11 | 已覆盖 |
| `test/webhook-processor-extra.test.ts` | 35 | 72.39% |
| `test/conflict-resolver-extra.test.ts` | 12 | 57.52% |
| `test/review-processor-extra.test.ts` | 7 | 49.42% |
| `test/retry-extra.test.ts` | 5 | 100% |
| `test/merge-guard.test.ts` | 5 | 100% |
| `test/failure-messages.test.ts` | 8 | 100% |
| `test/metrics-collector.test.ts` | 9 | 100% |
## 审计发现修复状态
## 已落地项
| 发现 | 严重度 | 状态 | 修复 |
|------|--------|------|------|
| C1: MergeGuard 未接入 | P1 | ✅ 已修 | 接入 processor.ts maybeMergePullRequest |
| C2: MetricsCollector 未接入 | P1 | ✅ 已修 | 接入 merge 路径 |
| C3: failureMessages 未接入 | P1 | ✅ 已修 | 接入 gooseCli.ts 错误路径 |
| C4: sort NaN 比较器 | P1 | ✅ 已修 | markReviewCheckApproved |
| C5: conflict 绕过 admin 审批 | P1 | ✅ 已修 | 加 requiresAdminApproval 守卫 |
| C6: 5 处重复 isNotFoundError | P1 | ✅ 已修 | 提取到 github/errors.ts |
| 里程碑 | 任务 | 状态 |
| ------ | ---------------------------------------- | --------------------------- |
| M0-1 | normalizeKnowledge 行尾归一 | ✅ |
| M0-2 | gooseReviewer 测试(26.57%→97.35%) | ✅ |
| M0-3 | r2 测试(49.01%→100%) | ✅ |
| M0-4 | triage 测试(56.77%→63.19%) | ✅ |
| M0-5 | webhook-processor 测试(63.90%→72.39%) | ✅ |
| M0-6 | conflict-resolver 测试(56.56%→57.52%) | ✅ |
| M0-7 | processor 测试(49.08%→49.42%) | ✅ |
| M1-1 | withRetry 智能重试(抖动+总超时) | ✅ |
| M1-3 | MergeGuard 合并防重入(定义+测试) | ✅ 定义完成,待接入生产代码 |
| M1-4 | failureMessages 失败分类(定义+测试) | ✅ 定义完成,待接入生产代码 |
| M2-2 | MetricsCollector 指标收集器(定义+测试) | ✅ 定义完成,待接入生产代码 |
| 审计 | 完整审计报告 | ✅ docs/audit-v2-final.md |
## 剩余真实风险与边界
## 未落地项
| 里程碑 | 任务 | 原因 |
| ------ | ---------------------------------------- | ---------------------------------- |
| M0-8 | 集成测试 | 需 testcontainers/MinIO 等基础设施 |
| M1-2 | 陈旧检测(stale detection) | processor.ts 未拆分前修改风险高 |
| M1-3 | MergeGuard 接 processor.ts | 需处理器拆分后接入 |
| M2-1 | 全链路日志贯穿 | 需处理器拆分后接入 |
| M3 | 大文件拆分(processor/conflictResolver) | 单独里程碑 |
| M4-M7 | 后续里程碑 | 逐步推进 |
## 审计发现摘要(详见 docs/audit-v2-final.md)
| 类别 | 计数 | 关键项 |
| ---- | ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| P0 | 0 | 无阻塞项 |
| P1 | 8 | MergeGuard/failureMessages/MetricsCollector 未接入、processor.ts 1736行、conflictResolver.ts 1250行、覆盖率不足、waitForMergeable 无超时、无陈旧检测 |
| P2 | 10 | sanitization 排除清单不完整、webhook 队列无持久化、分页缺失等 |
| P3 | 10 | 分片审查、AI Provider 抽象、国际化等 |
## 下一阶段建议
1. 先提交当前成果,推送到 origin
2. **第二阶段**:接入 3 个新模块到生产代码(MergeGuard→processor.ts, failureMessages→gooseCli.ts, MetricsCollector→runReview.ts)
3. **第三阶段**:拆分 processor.ts 和 conflictResolver.ts(M3),再补 M1-2 陈旧检测
4. **第四阶段**:做集成测试(M0-8)
| 项 | 状态 | 说明 |
|----|------|------|
| M0-8 集成测试 | 未落地 | 需 testcontainers/MinIO 基础设施 |
| 全覆盖到 90% | 未达成 | 大文件红线导致核心 processor 覆盖仍 49% |
| E2E 真实 goose 调用 | 未跑 | 需真实 GOOSE_API_KEY 预算 |
| webhook 队列持久化 | 定义未接 | QueueStore 默认关闭 |
| 陈旧检测接入主流程 | 定义未接 | staleness.ts 已定义未接入 processPullRequest |