diff --git a/.claude/skills/ghbot-workflow/SKILL.md b/.claude/skills/ghbot-workflow/SKILL.md new file mode 100644 index 0000000..bba3577 --- /dev/null +++ b/.claude/skills/ghbot-workflow/SKILL.md @@ -0,0 +1,338 @@ +--- +name: ghbot-workflow +description: Full workflow guide for ghbot: development cycle, adding endpoints, review checks, audits, and releases. +metadata: + last_verified: "2026-08-24" + repo_baseline: "v1.2.0" +--- + +# ghbot workflow skill + +## When to use + +This skill covers the operational workflow for the ghbot GitHub review bot project. Use it when asked about development workflow, adding features, running audits, or releasing. + +## Do not use + +- For unrelated SaaS features +- For changing AUTO_MERGE default value +- For reusing old review cache as a new-head approval +- For running paid LLM E2E without budget +- For pushing to remotes without write permission + +--- + +## 1. Full Workflow: test → typecheck → lint → build → e2e → release + +### Local development loop + +```bash +# 1. Test (fastest first) +npm test # node --import tsx --test test/**/*.test.ts + +# 2. Type check +npm run typecheck # tsc --noEmit + +# 3. Lint +npm run lint # eslint src test +npm run lint:fix # auto-fix lint issues + +# 4. Format check +npm run format:check # prettier --check + +# 5. Build +npm run build # tsc -p tsconfig.json, output to dist/ + +# 6. Build + test (CI equivalent) +npm run ci:test # node --import tsx --experimental-test-coverage --test test/**/*.test.ts +``` + +### CI gate (`.github/workflows/ci.yml`) + +The CI workflow runs on every push/PR to main: +1. `npm ci` — clean install +2. `npm run typecheck` — strict type check +3. `npm run lint` — ESLint +4. `npm run format:check` — Prettier style check +5. `node --import tsx --experimental-test-coverage --test test/**/*.test.ts` — full test + coverage + +### Pre-commit hooks + +The repo uses `scripts/husky-pre-commit.cjs` via `scripts/install-husky.cjs`. Run `node scripts/install-husky.cjs` to set up. + +### E2E smoke test + +E2E tests require real LLM (goose) and GitHub API access. Run locally only with explicit budget: + +```bash +# Requires GOOSE_API_KEY set in .env +# Run the webhook server locally, then send test events +npm run dev:webhook # tsx src/webhook/server.ts +``` + +### Release checklist + +See section 5 below. + +--- + +## 2. How to Add a New API Endpoint + +ghbot has two entry points: GitHub Actions events and the optional webhook HTTP server. + +### Adding a new Actions event handler + +1. **Define the event type** — Add a new type in `src/actions/router.ts` (e.g., `type NewPayload = { ... }`). + +2. **Register a handler** — In `buildDefaultEventRouter()` inside `src/actions/router.ts`, add a new `.register()` call: + +```typescript +router.register({ + name: "my-new-event", + canHandle: (eventName, action) => eventName === "my_event", + handle: async (ctx) => { + // Implement your logic + } +}); +``` + +3. **Wire the payload** — In `src/actions/runReview.ts`, add the new event name to `buildPayloadFromWorkflowCallEnv()`. + +4. **Extend the reusable workflow** — In `.github/workflows/review-reusable.yml`, add new inputs if needed. + +5. **Add tests** — Create `test/my-new-event.test.ts` with AAA tests. + +### Adding a new webhook HTTP endpoint + +1. **Add route** — In `src/webhook/server.ts`, `createWebhookServer()`, add a new conditional branch: + +```typescript +if (request.method === "POST" && pathname === "/my-endpoint") { + // validate, parse, handle + writeJson(response, 200, { ok: true }); + return; +} +``` + +2. **Add handler** — Extend `WebhookDeliveryHandler` or create a separate handler function. + +3. **Add metrics** — Use `MetricsRegistry.inc()` from `src/webhook/metrics.ts`. + +4. **Add tests** — Test the HTTP handler in `test/webhook.test.ts`. + +### Adding a new `workflow_call` input + +1. Add to `configSchema` in `src/config.ts` — use the appropriate Zod validator. +2. Add to `review-reusable.yml` `inputs:` section. +3. Add to `review.yml` `with:` section, wiring from `vars.*` or `secrets.*`. +4. Add to `.env.example` for local development. + +--- + +## 3. How to Add a New Review Check + +The review pipeline is: `GooseReviewer.review()` → `normalizeReviewDecision()` → `evaluateReviewDecision()` → `submitReview()`. + +### Adding a new finding type in the goose prompt + +1. **Extend the prompt** — Edit `src/review/prompt.ts`, `buildSystemPrompt()` function. Add a new rule: + +```typescript +// Example: add a new check for hardcoded credentials +const newRule = "Check for hardcoded credentials (API keys, passwords, tokens) in the patch. Report as 'change' (blocking) when found in production code."; +``` + +2. **Update the output schema** — If the new finding needs a new field, update `reviewDecisionSchema` in `src/review/gooseReviewer.ts` and the `ReviewDecision` type in `src/types.ts`. + +3. **Update normalization** — If the new field needs validation, update `src/review/normalize.ts`. + +### Adding a post-goose processing step + +1. **Add a new check function** in `src/review/` — e.g., `src/review/staticChecks.ts`: + +```typescript +import type { ReviewFinding } from "../types.js"; + +export function runStaticChecks(files: unknown[]): ReviewFinding[] { + // Implement static analysis + return []; +} +``` + +2. **Integrate into processor** — In `src/review/processor.ts`, `processPullRequest()`, after the goose review call, merge static findings: + +```typescript +const staticFindings = runStaticChecks(compactFiles); +const mergedFindings = [...decision.change, ...staticFindings]; +``` + +3. **Add tests** — Test the static check function in isolation. + +### Adding a new review policy option + +1. **Add the policy value** — Add to `REVIEW_POLICY` zod enum in `src/config.ts`: + +```typescript +reviewPolicy: z.enum(["allow", "require_approval", "reject", "new_policy"]).default("allow"), +``` + +2. **Handle in policy.ts** — Update `evaluateReviewDecision()` in `src/review/policy.ts` to handle the new value. + +3. **Update the review format** — Update `formatReviewBody()` in `src/review/format.ts` to display the new policy. + +4. **Update docs** — Add to `.env.example`, `README.md`, and `README-zh.md`. + +--- + +## 4. How to Run the Audit + +### Full audit + +The comprehensive audit report is at `docs/audit-v2-final.md`. To run a fresh audit: + +```bash +# 1. Verify baseline +npm run typecheck && npm test && npm run build + +# 2. Generate coverage report +node --import tsx --experimental-test-coverage --test test/**/*.test.ts + +# 3. Review compatibility table +# Check docs/audit-v2-final.md for the latest requirements matrix +``` + +### Quick health check + +```bash +# Type + lint + test + build — all four must pass +npm run typecheck && npm run lint && npm test && npm run build +``` + +### Manual audit checklist + +1. **Requirements trace** — Compare `docs/audit-v2-final.md` section 1 against actual code behavior. +2. **Blind spot scan** — Review `docs/audit-v2-final.md` section 2 for known gaps. +3. **Coverage** — Section 7 for current coverage numbers. +4. **Security** — Section 6 for the security review matrix. +5. **Architecture** — Section 4 for module health. + +### Continuous audit + +Update `workflow_status.md` after each milestone: +- Mark completed items with ✅ +- Note remaining items with reasons +- Track coverage, test count, and build passes + +--- + +## 5. How to Do a Release + +### Pre-release checklist + +- [ ] `npm run typecheck` passes +- [ ] `npm run lint` passes (0 errors) +- [ ] `npm run format:check` passes +- [ ] `npm test` passes (all tests green) +- [ ] Coverage meets 80% lines target (check `ci:test` output) +- [ ] `npm run build` succeeds +- [ ] `workflow_status.md` is up to date +- [ ] `docs/audit-v2-final.md` is up to date (if applicable) +- [ ] `README.md` and `README-zh.md` reflect current behavior +- [ ] `.env.example` covers all config options + +### Release steps + +1. **Update version** — Edit `package.json`: + +```json +{ + "version": "2.0.0" +} +``` + +2. **Update changelog** — Create or update `CHANGELOG.md` with conventional commits format: + +```markdown +# Changelog + +## [2.0.0] - 2026-08-24 + +### Added +- feat: MergeGuard merge deduplication +- feat: MetricsCollector for Actions runs +- feat: failureMessages error categorization +- feat: smart retry with jitter and total timeout + +### Fixed +- fix: normalizeKnowledge line ending normalization +``` + +3. **Commit and tag**: + +```bash +git add -A +git commit -m "chore: bump version to v2.0.0" +git tag v2.0.0 +git push origin main --tags +``` + +4. **Create GitHub Release**: + +```bash +gh release create v2.0.0 --title "v2.0.0" --notes "Release notes here" +``` + +5. **Verify release**: +- Check that `review.yml` workflow dispatches correctly +- Verify the reusable workflow at the new tag works +- Confirm CI passes on the release commit + +### Post-release + +- Update `workflow_status.md` with the new baseline +- Archive the audit report to `docs/reports/` if detailed +- Update `metadata.repo_baseline` in this skill file + +--- + +## Configuration Reference + +All config is defined in `src/config.ts` with Zod schema validation. Key environment variables: + +| Variable | Default | Description | +|----------|---------|-------------| +| `GOOSE_API_KEY` | — | LLM API key for goose | +| `GOOSE_MODEL` | `gpt-5.4` | Model name | +| `REVIEW_POLICY` | `allow` | Review policy: allow/require_approval/reject | +| `REVIEW_STRICTNESS` | `normal` | Review strictness: normal/strict | +| `AUTO_MERGE` | `false` | Auto-merge on pass | +| `AUTO_RESOLVE_CONFLICTS` | `false` | Auto-resolve merge conflicts | +| `TRIAGE_ENABLED` | `true` | Enable issue/PR triage | +| `WEBHOOK_ENABLED` | `false` | Enable webhook mode | + +Full list in `.env.example` and `src/config.ts`. + +--- + +## Key Files + +| Path | Purpose | +|------|---------| +| `src/actions/router.ts` | Event routing and handler registration | +| `src/actions/runReview.ts` | Actions entry point | +| `src/review/processor.ts` | Core review orchestration | +| `src/review/policy.ts` | Review policy evaluation | +| `src/review/gooseReviewer.ts` | LLM review prompt + schema | +| `src/review/conflictResolver.ts` | Merge conflict resolution | +| `src/triage/processor.ts` | Issue/PR triage and duplicate detection | +| `src/chat/processor.ts` | @bot chat in disposable containers | +| `src/ai/gooseCli.ts` | Goose CLI and Docker wrappers | +| `src/ai/apiProxy.ts` | One-time credential proxy | +| `src/config.ts` | All env config with Zod validation | +| `src/metrics/collector.ts` | Actions metrics collector | +| `src/review/merge-guard.ts` | Merge deduplication guard | +| `src/ai/failureMessages.ts` | Error categorization | +| `docs/audit-v2-final.md` | Comprehensive audit report | +| `workflow_status.md` | Milestone tracking | +| `.github/workflows/ci.yml` | CI pipeline | +| `.github/workflows/review.yml` | PR review workflow | \ No newline at end of file diff --git a/docs/audit-v2-final.md b/docs/audit-v2-final.md new file mode 100644 index 0000000..b77e6be --- /dev/null +++ b/docs/audit-v2-final.md @@ -0,0 +1,555 @@ +# ghbot v2.0 最终审计报告 + +**审计日期**: 2026-08-24 +**基准版本**: v1.2.0 (v2.0 半程) +**审计范围**: 全部 src/ (35 文件), test/ (48 文件), 配置, 文档, 工作流 +**覆盖率**: lines 66.20% / branches 87.36% / functions 75.57% / 321 tests + +--- + +## 1. 需求追踪矩阵 + +### 1.1 PR 自动审查 + +| 需求 | 实现位置 | 状态 | 证据 | 缺口 | +|------|---------|------|------|------| +| 四段输出 (review/change/comment/result) | `review/gooseReviewer.ts` + `review/normalize.ts` | ✅ | Zod schema 校验 + 过滤器 | 无 | +| 审查策略 (allow/require_approval/reject) | `review/policy.ts` | ✅ | `evaluateReviewDecision` | 无 | +| 恶意代码检测并自动关闭 | `review/processor.ts` → `closeMaliciousPullRequest` | ✅ | 评论 + 关闭 PR | 无 | +| 审查结果缓存 (本地) | `review/cache.ts` | ✅ | 文件缓存 + 校验 | 无 | +| 审查结果持久化 (R2) | `storage/cacheStore.ts` | ✅ | 多版本保存 | 无 | +| 增量审查 (旧结果复用) | `review/processor.ts` → `loadPreviousReview` | ✅ | 传递到 goose prompt | **无陈旧检测** — 旧结果只在 LLM prompt 中提及,不做结构性比对 | +| 进度评论 | `review/processor.ts` → `begin/finishCommitReviewProgress` | ✅ | 按 commit SHA 标记 | 无 | +| 旧审查清理 | `review/processor.ts` → `supersedePreviousBotReviews` | ✅ | GraphQL 解析线程 + minimize | 无 | +| 审查评论回退 (Actions 不能 approve) | `review/processor.ts` → `shouldFallbackToCommentReview` | ✅ | 422 检测 + 降级 COMMENT | 无 | + +### 1.2 Issue/PR 分类 + +| 需求 | 实现位置 | 状态 | 证据 | 缺口 | +|------|---------|------|------|------| +| Issue 标签分类 | `triage/processor.ts` → `processIssueTriage` | ✅ | 单阶段 goose 调用 | 无 | +| PR 标签分类 | `triage/processor.ts` → `processPullRequestTriage` | ✅ | 两阶段粗筛+详查 | 无 | +| 重复检测 (单阶段) | `triage/processor.ts` → `runSingleStageTriage` | ✅ | Issue 专用 | 无 | +| 重复检测 (两阶段) | `triage/processor.ts` → `triagePullRequestInTwoStages` | ✅ | 粗筛+证据加载+详查 | 无 | +| 重复评论去重 | `triage/processor.ts` → `postDuplicateFeedback` | ✅ | 隐藏 HTML marker | 无 | +| 标签自动创建 | `triage/processor.ts` → `ensureLabelsExist` | ✅ | 缺则创建 | 无 | + +### 1.3 @bot PR 对话 + +| 需求 | 实现位置 | 状态 | 证据 | 缺口 | +|------|---------|------|------|------| +| @bot 提及检测 | `chat/processor.ts` → `containsBotMention` | ✅ | 多别名 | 无 | +| 权限检查 | `chat/processor.ts` → `isTrustedChatPermission` | ✅ | write/maintain/admin | 无 | +| 快照脱敏 | `chat/processor.ts` → `createRepositorySnapshot` | ✅ | 排除 .git + 配置 + 符号链接 | 无 | +| 一次性容器 | `ai/gooseCli.ts` → `runGooseAgent` | ✅ | Docker 隔离 | 无 | +| 凭据代理 | `ai/apiProxy.ts` → `startOneRunApiProxy` | ✅ | 一次性 token + 时间比较 | 无 | +| 回复去重 | `chat/processor.ts` → `hasExistingReply` | ✅ | 隐藏 marker | 无 | +| 语言跟随 | `chat/processor.ts` → `chatReplyLanguageInstruction` | ✅ | 中英文检测 | 无 | +| 认知写入 | `chat/processor.ts` + `repository/knowledge.ts` | ✅ | 快照内 scratch 文件 | 无 | + +### 1.4 冲突修复 + +| 需求 | 实现位置 | 状态 | 证据 | 缺口 | +|------|---------|------|------|------| +| 自动冲突修复 | `review/conflictResolver.ts` → `resolvePullRequestConflicts` | ✅ | 完整流水线 | 无 | +| 冲突检测 | `review/conflictResolver.ts` → `canAutoResolveConflicts` | ✅ | 8 条件判断 | 无 | +| Git 操作安全 | `review/conflictResolver.ts` → `buildConflictPushArgs` | ✅ | 仓库/分支/SHA 安全校验 | 无 | +| 隔离验证 | `review/conflictResolver.ts` → `runConflictValidation` | ✅ | 只读 Docker 容器 | 无 | +| 最终确认 | `review/conflictResolver.ts` → `confirmFinalResolution` | ✅ | 无工具 goose 只读 + Zod schema | 无 | +| 冲突锁 | `review/conflictResolver.ts` → `acquireConflictLock` | ✅ | 内存 Set 锁 | **无超时释放** — 如果进程异常退出,锁不会自动释放(内存级,重启后自然消失) | +| 强制推送保护 | `review/conflictResolver.ts` → `buildConflictPushArgs` | ✅ | `--force-with-lease` + SHA 绑定 | 无 | + +### 1.5 Webhook 模式 + +| 需求 | 实现位置 | 状态 | 证据 | 缺口 | +|------|---------|------|------|------| +| 签名校验 | `webhook/server.ts` → `verifyGitHubWebhookSignature` | ✅ | HMAC-SHA256 + timingSafeEqual | 无 | +| 去重 | `webhook/server.ts` → `WebhookTaskQueue` | ✅ | deliveryId 去重 24h 保留 | 无 | +| 任务队列 | `webhook/server.ts` → `WebhookTaskQueue` | ✅ | 并发 + 限流 + 重试 2 次 | **无持久化** — 进程重启丢队列 | +| 指标端点 | `webhook/metrics.ts` → `MetricsRegistry` | ✅ | Prometheus 格式 | 无 | +| 只读聊天 | `webhook/processor.ts` → `processWebhookMention` | ✅ | 无工具 goose | 无 | +| 组织成员权限 | `webhook/processor.ts` → `getCommenterPermission` | ✅ | orgs.checkMembershipForUser | 无 | + +### 1.6 仓库认知 + +| 需求 | 实现位置 | 状态 | 证据 | 缺口 | +|------|---------|------|------|------| +| 认知加载 | `repository/knowledge.ts` → `loadRepositoryKnowledge` | ✅ | 未命中时创建默认模板 | 无 | +| 认知校验 | `repository/knowledge.ts` → `validateRepositoryKnowledge` | ✅ | 32 KiB 限制 + 密钥检测 | 无 | +| 认知持久化 | `storage/cacheStore.ts` | ✅ | R2 写入 | 无 | +| 认知写入 (Agent) | `chat/processor.ts` + `repository/knowledge.ts` | ✅ | 快照内 scratch 文件 | 无 | + +### 1.7 事件路由 + +| 需求 | 实现位置 | 状态 | 证据 | 缺口 | +|------|---------|------|------|------| +| 事件路由 | `actions/router.ts` → `EventRouter` | ✅ | 注册+分发 | 无 | +| 三链路隔离 | `actions/router.ts` → `Promise.allSettled` | ✅ | recheck/conflict/chat 互相独立 | 无 | +| 错误汇总 | `actions/router.ts` → `AggregateError` | ✅ | 多个失败时汇总 | 无 | + +### 1.8 新增模块 (v2.0 半程) + +| 需求 | 实现位置 | 状态 | 证据 | 缺口 | +|------|---------|------|------|------| +| 合并防重入 | `review/merge-guard.ts` → `MergeGuard` | ✅ | 100% 测试覆盖 | **未接入 processor.ts** — 有定义无调用 | +| 失败分类 | `ai/failureMessages.ts` | ✅ | 100% 测试覆盖 | **未接入生产代码** — 无 import 引用 | +| 指标收集器 | `metrics/collector.ts` → `MetricsCollector` | ✅ | 100% 测试覆盖 | **未接入生产代码** — 无 import 引用 | +| 智能重试 | `retry.ts` → `withRetry` | ✅ | 抖动 + 总超时 + 可重试判断 | 无 | + +--- + +## 2. 盲点扫描 + +### 2.1 未覆盖的边界情况 + +| 编号 | 区域 | 盲点 | 影响 | 优先级 | +|------|------|------|------|--------| +| B-01 | `review/processor.ts` | 没有为 `supersedePreviousBotReviews` 的 GraphQL 调用失败做充分降级 | 残留旧 inline 评论 | P2 | +| B-02 | `review/processor.ts` | `waitForMergeable` 5 次重试后仍返回 null 时继续处理 | 可能错误合并 | P1 | +| B-03 | `review/conflictResolver.ts` | `acquireConflictLock` 没有超时机制 | 崩溃后锁残留(内存级,重启即消失,但同进程内可能永久阻塞) | P2 | +| B-04 | `review/conflictResolver.ts` | `buildGooseAgentDockerArgs` 使用 `--add-host host.docker.internal:host-gateway`,但并非所有 Docker 环境支持 | Linux 上无 dockerd 或不同网络模式时容器内无法连接代理 | P1 | +| B-05 | `chat/processor.ts` | `createRepositorySnapshot` 使用 `verbatimSymlinks: true` 后过滤符号链接,但 `cp` 递归可能复制大文件 | 快照体积不可控 | P2 | +| B-06 | `webhook/server.ts` | `WebhookTaskQueue` 重试 2 次后直接丢弃,不通知外部 | 静默丢失 webhook 请求 | P2 | +| B-07 | `webhook/processor.ts` | `loadWebhookContext` 在 `pull_request_review` 事件中不加载 files | 对话无 diff 上下文 | P2 | +| B-08 | `triage/processor.ts` | `listCandidates` 不分页,只取第一页 `per_page=100` | 超过 100 个候选时丢失 | P2 | +| B-09 | `triage/processor.ts` | `loadPullRequestEvidence` 每项只取最后 8 条 | 证据采样可能不足 | P3 | +| B-10 | `review/normalize.ts` | 只过滤 `path` 不在文件列表和 `line<=0` 的 finding | 不校验 `line` 是否在 patch 有效行范围内 | P2 | +| B-11 | `review/processor.ts` | `reviewProgressMarker` 只绑定 commit SHA,不绑定 PR 编号 | 不同 PR 间可能混淆(scoped 到 PR 内,问题不大) | P3 | +| B-12 | `review/processor.ts` | `processScheduledPendingMerges` 对 PR 分页只取 `per_page=100` 无后续分页 | 超过 100 个开放 PR 时遗漏 | P2 | +| B-13 | `review/processor.ts` | `hasCurrentHeadApprovalFrom` 的权限检查循环中,第一次失败后继续尝试,但最后如果所有都失败抛出最后一个错误 | 一个查询失败可能掩盖其他成功 | P2 | +| B-14 | `review/processor.ts` | `processRecheckComment` 和 `processConflictComment` 在 `getCollaboratorPermissionLevel` 404 时返回 `permission: null`,然后无权限回复 | 外部协作者降级正确 | P3 | +| B-15 | `review/conflictResolver.ts` | `buildCommandEnvironment` 中的 `SHELL` 环境变量直接传递 | 可能影响容器内行为 | P3 | + +### 2.2 错误路径 + +| 编号 | 区域 | 错误路径 | 当前处理 | 改进建议 | +|------|------|---------|---------|---------| +| E-01 | `review/processor.ts` | `createGitHubReview` 提交失败后只做一次 fallback | 降级到 COMMENT 但仍在同一事件中继续 | 可考虑重试 | +| E-02 | `review/processor.ts` | `supersedePreviousBotReviews` 中部分 GraphQL 调用失败 | 日志 warn 后继续 | 正确 | +| E-03 | `ai/gooseCli.ts` | Docker 容器创建失败 | 抛出异常 | 正确 | +| E-04 | `ai/gooseCli.ts` | goose 输出超过 1M 字符 | 截断末尾 + 抛出 error | 极端情况应降级而非整体失败 | +| E-05 | `ai/gooseCli.ts` | `resolveHostGooseBinary` 在非 Linux 上返回 undefined | 容器内从网络下载 | 非 Linux 环境无法使用,需文档说明 | +| E-06 | `review/conflictResolver.ts` | `parseFinalConfirmation` 解析失败 | 抛出异常 | 正确(不提交不安全结果) | +| E-07 | `review/conflictResolver.ts` | `runCommandAllowFailure` 超时后 SIGTERM+5s SIGKILL | 合理 | 正确 | +| E-08 | `chat/processor.ts` | `createRepositorySnapshot` 复制失败 | 清理快照后抛出 | 正确 | + +### 2.3 安全风险 + +| 编号 | 风险 | 位置 | 严重程度 | 说明 | +|------|------|------|---------|------| +| S-01 | `sanitization.ts` 未排除 `.npmrc`、`terraform/`、`kube/`、`docker/` 配置 | 全局 | P2 | 这些文件可能包含注册表令牌或云凭据 | +| S-02 | `apiProxy.ts` 中 `timingSafeEqual` 对比:`Buffer.from(suppliedToken)` 可能因编码抛出异常 | `apiProxy.ts:131` | P2 | 调用方应确保 `suppliedToken` 是 ASCII,但未显式处理 | +| S-03 | `webhook/server.ts` `readRawBody` 中 `for await...of` 可能被慢速请求阻塞 | `webhook/server.ts:98` | P1 | 已有 body 30s 超时,但 `readRawBody` 内部无超时 | +| S-04 | `gooseCli.ts` 在 `runGoosePrompt` 中直接将 `config.gooseApiKey` 设为环境变量 `OPENAI_API_KEY` | `gooseCli.ts:408` | P1 | 子进程环境变量可能通过 `/proc` 或其他方式泄露到同一宿主的不同进程 | +| S-05 | `review/conflictResolver.ts` `askpass.sh` 中 `GHBOT_GIT_TOKEN` 通过环境变量传递 | `conflictResolver.ts:139` | P1 | askpass 脚本在子进程环境中,Git 子进程可能继承此变量 | +| S-06 | `review/conflictResolver.ts` `buildCommandEnvironment` 传递 `NODE_EXTRA_CA_CERTS`、`SSL_CERT_FILE`、`SSL_CERT_DIR` | `conflictResolver.ts:1237-1240` | P2 | 可能绕过证书验证 | + +--- + +## 3. P0/P1/P2/P3 问题清单 + +### P0 (阻塞) + +| ID | 问题 | 位置 | 说明 | +|----|------|------|------| +| P0-01 | 无 | — | 构建、类型检查、测试全部通过,无阻塞项 | + +### P1 (高) + +| ID | 问题 | 位置 | 说明 | +|----|------|------|------| +| P1-01 | `MergeGuard` 未接入生产代码 | `review/merge-guard.ts` | 定义了 `MergeGuard` 类,但 processor.ts 中 `maybeMergePullRequest` 未调用,无实际防重入效果 | +| P1-02 | `failureMessages` 未接入生产代码 | `ai/failureMessages.ts` | 定义了 `categorizeFailure` / `formatFailureMessage`,但无任何模块调用 | +| P1-03 | `MetricsCollector` 未接入生产代码 | `metrics/collector.ts` | 定义了完整指标收集器,但 `src/actions/runReview.ts` 和 `review/processor.ts` 未调用 | +| P1-04 | `processor.ts` 1736 行 | `review/processor.ts` | 远超 800 行上限,核心编排逻辑难以维护和测试 | +| P1-05 | `conflictResolver.ts` 1250 行 | `review/conflictResolver.ts` | 远超 800 行上限,包含多个独立职责 | +| P1-06 | coverage 不足 | 全局 | lines 66.20% 远低于 80% 目标;`processor.ts` 49.42%、`triage/processor.ts` 63.19% | +| P1-07 | `waitForMergeable` 无超时约束 | `review/processor.ts:1411-1432` | 5 次重试 1s 间隔,无总超时,可能无限等待 | +| P1-08 | 审查运行期间无陈旧检测 | `review/processor.ts:98-105` | LLM 运行期间 head 变化时丢弃结果,浪费完整调用 | + +### P2 (中) + +| ID | 问题 | 位置 | 说明 | +|----|------|------|------| +| P2-01 | 快照排除清单不完整 | `security/sanitization.ts` | 缺少 `.npmrc`、`terraform/`、`kube/`、`docker/` 配置路径 | +| P2-02 | webhook 队列无持久化 | `webhook/server.ts` | 进程重启丢失所有待处理任务 | +| P2-03 | `processScheduledPendingMerges` 不分页 | `review/processor.ts:279-284` | 只取 100 条 PR,超过时遗漏 | +| P2-04 | `triage/processor.ts` `listCandidates` 不分页 | `triage/processor.ts:291-332` | 只取 100 条,超过时遗漏 | +| P2-05 | `webhook/processor.ts` 对 `pull_request_review` 事件不加载 files | `webhook/processor.ts:309-317` | 对话无 diff 上下文 | +| P2-06 | `review/normalize.ts` 不校验 line 有效性 | `review/normalize.ts:32-33` | 只校验 `line>0`,不校验是否在 patch 有效行范围内 | +| P2-07 | `apiProxy.ts` 中 `Buffer.from(suppliedToken)` 可能抛出异常 | `apiProxy.ts:131` | 未处理非 ASCII token 的编码异常 | +| P2-08 | `gooseCli.ts` 中 `OPENAI_API_KEY` 暴露到子进程环境 | `gooseCli.ts:408` | 可能通过 `/proc/PID/environ` 泄露 | +| P2-09 | `conflictResolver.ts` 中 `GHBOT_GIT_TOKEN` 通过环境变量传递 | `conflictResolver.ts:139` | git 子进程可读取此环境变量 | +| P2-10 | 日志中 `err.stderr` 被 redact 但 `error.stderr` 保留 | `logger.ts:33-34` | 不一致的 redact 模式 | + +### P3 (低) + +| ID | 问题 | 位置 | 说明 | +|----|------|------|------| +| P3-01 | 无分片并行审查 | `review/processor.ts` | 大 PR 串行 LLM 调用延迟高 | +| P3-02 | 无 AI Provider 抽象层 | `ai/gooseCli.ts` | 换 provider 需大改 | +| P3-03 | 审查结果无去重 | `review/gooseReviewer.ts` | 相似 finding 刷屏 | +| P3-04 | 审查结果无自检 | `review/gooseReviewer.ts` | 矛盾/低质量结果无检查 | +| P3-05 | 无国际化 | 全局 | 所有评论英文写死 | +| P3-06 | `conflictResolver.ts` 冲突锁无超时 | `review/conflictResolver.ts:71-79` | 同进程内永久阻塞风险 | +| P3-07 | `ci.yml` 无覆盖率门槛 | `.github/workflows/ci.yml` | 覆盖率下降不会被阻止 | +| P3-08 | 无预提交 hook | 项目根 | 无 husky/lint-staged | +| P3-09 | 版本号管理在 `package.json` 但无自动 changelog | — | 需手动更新 | +| P3-10 | `ci.yml` 中 `npm ci` 未使用 `--production` 或 `--ignore-scripts` | — | 构建时执行所有生命周期脚本 | + +--- + +## 4. 架构评审 + +### 4.1 模块边界 + +``` +actions/ ← 入口层 (router + runReview) + ├── router.ts ← 事件路由注册 + 分发 + └── runReview.ts ← Actions 入口 + payload 构建 +review/ ← 审查核心(最大模块) + ├── processor.ts ← 1736 行 — 含 7+ 职责 + ├── conflictResolver.ts ← 1250 行 — 含 5+ 职责 + ├── gooseReviewer.ts ← 审查 prompt + schema + ├── normalize.ts ← 结果净化 + ├── format.ts ← 评论格式化 + ├── policy.ts ← 策略 + 状态标记 + ├── cache.ts ← 本地缓存 + ├── prompt.ts ← patch 截断 + └── merge-guard.ts ← 未接入 +ai/ ← AI 调用层 + ├── gooseCli.ts ← 726 行 — 3 种运行模式混用 + ├── apiProxy.ts ← 一次性凭据代理 + └── failureMessages.ts ← 未接入 +chat/ ← @bot 对话 + └── processor.ts ← 358 行 +triage/ ← 分类 + └── processor.ts ← 576 行 +github/ ← GitHub API 封装 + ├── client.ts ← 认证 + ├── checks.ts ← 状态检查 + ├── diff.ts ← 行号解析 + ├── commandFeedback.ts ← 命令反馈 + ├── botIdentity.ts ← 显示名 + └── pulls.ts ← 文件列表 +webhook/ ← 可选 webhook 服务 + ├── server.ts ← 315 行 + ├── processor.ts ← 518 行 + └── metrics.ts ← 59 行 +storage/ ← 持久化 + ├── r2.ts ← S3 客户端 + └── cacheStore.ts ← 缓存编排 +security/ ← 安全 + ├── sanitization.ts ← 路径排除 + └── secrets.ts ← 密钥脱敏 +repository/ ← 仓库认知 + └── knowledge.ts +metrics/ ← 指标 + └── collector.ts ← 未接入 +``` + +### 4.2 关键架构问题 + +| 问题 | 严重程度 | 说明 | +|------|---------|------| +| `review/processor.ts` 承担过多职责 | P1 | 1736 行:编排、进度、提交、check run、旧审查清理、合并、审批、评论命令 | +| `review/conflictResolver.ts` 5 种职责混合 | P1 | 1250 行:冲突检测、git 操作、快照管理、diff 检查、验证、确认 | +| 3 个新模块无生产引用 | P1 | `MergeGuard`、`failureMessages`、`MetricsCollector` 均有定义和测试但未引入 | +| `ai/gooseCli.ts` 3 种运行模式耦合 | P2 | `runGoosePrompt`(chat)、`runGooseAgent`(Docker + Developer)、`runIsolatedWorkspaceCommand`(验证)在同一个文件中 | +| 认证逻辑分散 | P2 | `github/client.ts` 处理两种认证(token + App),但 webhook 另有 `createGitHubAppInstallationCredentials`,`runReview.ts` 中 `createGitHubCredentials` 再次处理 | +| 错误处理模式不一致 | P2 | 部分 `catch` 中 `logger.warn` 后继续,部分 `catch` 后 `throw`,无统一策略 | +| `withRetry` 在不同调用处使用不同的 label 命名规则 | P3 | 有的用 `github.issues.createComment.*`,有的用 `goose.run.*`,无统一 namespace | + +### 4.3 设计模式评价 + +| 模式 | 位置 | 评价 | +|------|------|------| +| EventRouter (策略模式) | `actions/router.ts` | 良好:注册式分发,可扩展 | +| 快照模式 (Snapshot) | `review/conflictResolver.ts` | 良好:`inventorySnapshot` + `diffSnapshotInventories` + `applySnapshotChanges` 三阶段 | +| 仓储模式 (Repository) | `storage/r2.ts` | 一般:`downloadR2Object`/`uploadR2Object` 是过程式,非接口抽象 | +| 代理模式 (Proxy) | `ai/apiProxy.ts` | 良好:一次性 token 认证 | +| 工厂模式 | `actions/router.ts` → `buildDefaultEventRouter` | 良好:集中注册 | +| 单例模式 | `logger.ts`、`metrics/collector.ts` | 适当:全局状态合理 | +| MergeGuard 防重入 | `review/merge-guard.ts` | 未接入:已定义但无调用 | + +--- + +## 5. 性能评审 + +### 5.1 重试策略 + +| 方面 | 评价 | 改进建议 | +|------|------|---------| +| `withRetry` 已实现智能重试 | ✅ 抖动 + 分类 + 总超时 | 已落地 (M1-1) | +| 默认 5 次重试 + 1s base delay | 合理 | 可接受 | +| 4xx 非重试逻辑 | 正确 | 无 | +| 总超时退出 | 正确 | 无 | +| gobose 调用 3 次重试 | `review/gooseReviewer.ts:63` | 合理,LLM 调用昂贵 | + +### 5.2 缓存策略 + +| 方面 | 评价 | 改进建议 | +|------|------|---------| +| 本地审查缓存 | ✅ 文件级缓存 + Zod 校验 | 无 | +| R2 持久化缓存 | ✅ 多版本 + 身份校验 | 无 | +| 仓库认知缓存 | ✅ 32 KiB 限制 + 密钥检测 | 可增加版本管理/淘汰 | +| 缓存预热 | ❌ 无预热 | `loadPreviousReview` 和 `restorePersistentCache` 串行等待 | +| 审查差异分析 | ❌ 无差异复用 | 每次 `synchronize` 全量审查 | + +### 5.3 并发处理 + +| 方面 | 评价 | 改进建议 | +|------|------|---------| +| 事件路由并行 | ✅ `Promise.allSettled` 三链路隔离 | 无 | +| webhook 队列 | ✅ 并发控制 + 限流 | 可加持久化 | +| 冲突锁 | ✅ 内存 Set 锁 | 可加超时 | +| 合并防重入 | ❌ `MergeGuard` 未接入 | 需接入 processor.ts | +| 分片审查 | ❌ 无并行 LLM 审查 | 大 PR 延迟高 | + +### 5.4 内存与资源 + +| 方面 | 评价 | +|------|------| +| ECD 容器内存限制 4GB | 合理 | +| ECD 容器 CPU 2 核 | 合理 | +| 进程数限制 512 | 合理 | +| 输出截断 1M 字符 | 合理 | +| 快照大小无限制 | 风险:大仓库可能复制大量文件 | +| webhook 队列内存 | 有限流 `queueLimit=500` | + +--- + +## 6. 安全评审 + +### 6.1 密钥处理 + +| 密钥 | 位置 | 处理方式 | 评价 | +|------|------|---------|------| +| `GOOSE_API_KEY` | `config.ts` | Zod schema 读取环境变量 | ✅ | +| `GITHUB_TOKEN` | `config.ts` | 直接从 process.env 读取 | ✅ | +| GitHub App 私钥 | `config.ts` → `client.ts` | `normalizePrivateKey` 处理 `\\n` | ✅ | +| R2 密钥 | `config.ts` | 四件套校验 | ✅ | +| 容器内 API key | `apiProxy.ts` | 一次性随机 token 替代 | ✅ | +| Git token | `conflictResolver.ts` | `GIT_ASKPASS` 脚本中写入 | ⚠️ 子进程环境变量可读 | + +### 6.2 注入防护 + +| 防护 | 位置 | 评价 | +|------|------|------| +| 路径跨越防护 | `conflictResolver.ts` → `safeFilePath` | ✅ 双重检查 | +| 分支名安全校验 | `conflictResolver.ts` → `isSafeGitBranch` | ✅ 控制字符排除 | +| 仓库名安全校验 | `conflictResolver.ts` → `isSafeGitHubRepository` | ✅ 正则白名单 | +| 快照排除 | `chat/processor.ts` → `createRepositorySnapshot` | ⚠️ `.npmrc`、`terraform/` 等未覆盖 | +| 路径保护 | `security/sanitization.ts` | ✅ 集中式清单 | +| 密钥脱敏 | `security/secrets.ts` | ✅ 正则匹配 | +| 日志 redact | `logger.ts` | ✅ pino redact 配置 | + +### 6.3 脱敏覆盖 + +| 路径/模式 | 已覆盖 | 缺漏 | +|-----------|--------|------| +| GitHub PAT (ghp_...) | ✅ | — | +| GitHub PAT v2 (github_pat_) | ✅ | — | +| OpenAI API key (sk-...) | ✅ | — | +| Bearer token | ✅ | — | +| 私钥 (-----BEGIN ... PRIVATE KEY-----) | ✅ | — | +| SSH 私钥 | ❌ | `-----BEGIN OPENSSH PRIVATE KEY-----` 未匹配(`BEGIN [A-Z ]*PRIVATE KEY` 已覆盖) | ✅ | +| 日志 redact 路径 | ✅ | `err.stderr` vs `error.stderr` 不一致 (P2-10) | + +### 6.4 安全评估总结 + +| 领域 | 评级 | 要点 | +|------|------|------| +| 凭据隔离 | A | 容器内无真实凭据,一次性代理安全 | +| 注入防护 | A | 路径/分支/仓库名白名单校验完善 | +| 快照脱敏 | B+ | 主要路径已覆盖,缺 `.npmrc` 等 | +| 密钥脱敏 | A | 正则 + 日志 redact 双保险 | +| 子进程安全 | B | 环境变量泄露风险较低但有 | +| 整体安全 | A- | 生产级安全实践,无重大漏洞 | + +--- + +## 7. 测试评审 + +### 7.1 覆盖缺口 + +| 模块 | 当前 lines | 目标 | 主要缺口 | +|------|-----------|------|---------| +| `review/processor.ts` | 49.42% | ≥80% | `processPullRequest` 主流程、`supersedePreviousBotReviews` 大段、`maybeMergePullRequest` 大部分、`processScheduledPendingMerges`、`processRecheckComment`、`processConflictComment` | +| `review/conflictResolver.ts` | 57.52% | ≥80% | `resolvePullRequestConflicts` 主流程、`buildConflictPrompt`、`buildValidationRepairPrompt`、`runConflictValidation`、`runCommand` | +| `triage/processor.ts` | 63.19% | ≥80% | `processTriage` 主流程、`triagePullRequestInTwoStages` 大部分、`ensureLabelsExist`、`postDuplicateFeedback` | +| `webhook/processor.ts` | 72.39% | ≥80% | `processWebhookMention` 主流程、`loadWebhookContext` 大部分、`getCommenterPermission` 组织成员分支 | +| `webhook/server.ts` | 75.87% | ≥80% | `createWebhookServer` 队列满 503、body 超时 413、`startWebhookServer` 完整流程 | +| `storage/cacheStore.ts` | 95.73% | ≥95% | 剩余少量行 | + +### 7.2 测试质量 + +| 维度 | 评价 | +|------|------| +| 测试结构 | ✅ AAA 模式统一使用 | +| 测试命名 | ✅ 描述性命名 | +| Mock 使用 | ✅ 无真实 LLM/HTTP 调用 | +| 边界测试 | ⚠️ 部分模块有边界但不足 | +| 集成测试 | ❌ 无集成测试 (test/integration/ 不存在) | +| E2E 测试 | ❌ 无 E2E 测试 | +| 覆盖率门禁 | ❌ `ci.yml` 未设置覆盖率阈值 | + +### 7.3 测试文件增长 + +| 指标 | 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% | + +### 7.4 测试缺口详细分析 + +**processor.ts 核心缺口:** + +```typescript +// 未测试的极端路径: +- processPullRequest 中 draft/skip 跳过 → 正确跳过 +- processPullRequest 中恶意代码关闭 → closeMaliciousPullRequest +- submitReview 中 file 不存在 → unpostedFindings +- createGitHubReview 中 422 回退 → COMMENT +- upsertReviewCheckRun 中 malice/requireAdmin 不同结论 +- waitForMergeable 5 次后 null 返回 +- mergeable_state=dirty 时冲突修复 +- schedule 中已合并 PR 的跳过 +- hasCurrentHeadApprovalFrom 中 404 处理 +- processRecheckComment 中权限不足 +- processConflictComment 中非 dirty 状态跳过 +``` + +**conflictResolver.ts 核心缺口:** + +```typescript +- resolvePullRequestConflicts 主流程中任何分支失败 +- buildConflictPrompt 中 validationCommand 有无分支 +- buildValidationRepairPrompt 完整文本 +- runConflictValidation 中基础设施失败分类 +- remainingConflictTime 超时抛出 +- commandFailureOutput 中 redactSecrets 接线 +- buildCommandEnvironment 中 PROXY 环境变量传递 +``` + +--- + +## 8. 文档评审 + +### 8.1 README 一致性 + +| 对比项 | README.md | README-zh.md | 一致性 | +|--------|-----------|-------------|--------| +| PR 审查四段输出 | ✅ | ✅ | 一致 | +| 审查策略 | ✅ | ✅ | 一致 | +| 增量缓存 | ✅ | ✅ | 一致 | +| 仓库认知 | ✅ | ✅ | 一致 | +| Issue/PR 分类 | ✅ | ✅ | 一致 | +| @bot 对话 | ✅ | ✅ | 一致 | +| Webhook 模式 | ✅ | ✅ | 一致 | +| 冲突修复 | ✅ | ✅ | 一致 | +| goose 配置 | ✅ | ✅ | 一致 | +| 开发门禁 | ✅ | ✅ | 一致 | +| 本地开发 | ✅ | ✅ | 一致 | + +### 8.2 配置文档 + +| 配置项 | `.env.example` | README | 代码中 `config.ts` | 一致性 | +|--------|---------------|--------|-------------------|--------| +| PORT | ✅ | ✅ | ✅ | 一致 | +| LOG_LEVEL | ✅ | ❌ | ✅ | 未在 README 文档化 | +| GHBOT_RUNTIME_DIR | ✅ | ✅ | ✅ | 一致 | +| GOOSE_API_KEY | ✅ | ✅ | ✅ | 一致 | +| GOOSE_BASE_URL | ✅ | ✅ | ✅ | 一致 | +| GOOSE_MODEL | ✅ | ✅ | ✅ | 一致 | +| GOOSE_THINKING_EFFORT | ✅ | ✅ | ✅ | 一致 | +| REVIEW_POLICY | ✅ | ✅ | ✅ | 一致 | +| REVIEW_STRICTNESS | ✅ | ✅ | ✅ | 一致 | +| REVIEW_INSTRUCTIONS | ✅ | ✅ | ✅ | 一致 | +| REVIEW_BRANCHES | ✅ | ✅ | ✅ | 一致 | +| R2 配置 | ✅ | ✅ | ✅ | 一致 | +| TRIAGE 配置 | ✅ | ✅ | ✅ | 一致 | +| AUTO_MERGE | ✅ | ✅ | ✅ | 一致 | +| AUTO_RESOLVE_CONFLICTS | ✅ | ✅ | ✅ | 一致 | +| CONFLICT_TEST_COMMAND | ✅ | ✅ | ✅ | 一致 | +| MERGE_METHOD | ✅ | ✅ | ✅ | 一致 | +| REQUIRE_CHECKS | ✅ | ✅ | ✅ | 一致 | +| MAX_PATCH_CHARS | ✅ | ✅ | ✅ | 一致 | +| BOT_NAME | ✅ | ✅ | ✅ | 一致 | +| WEBHOOK 配置 | ✅ | ✅ | ✅ | 一致 | +| REPOSITORY_KNOWLEDGE_ENABLED | ✅ | ✅ | ✅ | 一致 | +| REPOSITORY_KNOWLEDGE_WRITE | ✅ | ✅ | ✅ | 一致 | + +### 8.3 文档缺漏 + +| 缺漏 | 说明 | 优先级 | +|------|------|--------| +| `LOG_LEVEL` 未在 README 文档化 | 仅在 `.env.example` 和 `config.ts` 中有 | P3 | +| `workflow_status.md` 未同步最新状态 | 标记了"未落地项"但未更新为当前实际状态 | P2 | +| 无 CHANGELOG | 版本迭代无历史记录 | P3 | +| 无 CONTRIBUTING.md 详细指南 | 仅有安全红线在 README 中提及 | P3 | +| `docs/reports/ghbot-production-hardening.html` 外部依赖 | 文档链接指向外部文件 | P3 | + +### 8.4 部署文档 + +| 部署方式 | 文档化 | 评价 | +|---------|--------|------| +| GitHub Actions (主模式) | ✅ | 详细 | +| Webhook Docker 部署 | ✅ | 详细 | +| 本地开发 | ✅ | 详细 | +| CI/CD 流水线 | ✅ | 有 `.github/workflows/ci.yml` | + +--- + +## 9. 汇总建议 + +### 立即修复 (P1) + +1. 将 `MergeGuard`、`failureMessages`、`MetricsCollector` 接入生产代码 +2. 拆分 `review/processor.ts` (1736 行) 和 `review/conflictResolver.ts` (1250 行) 为 ≤400 行模块 +3. 补齐 `processor.ts` 和 `conflictResolver.ts` 的测试覆盖率至 ≥80% +4. 为 `waitForMergeable` 增加总超时约束 +5. 实现审查运行期间陈旧检测 (追加段落后缀合并审查) + +### 短期改进 (P2) + +6. 完善 `sanitization.ts` 排除清单 (`.npmrc`、`terraform/`、`kube/`、`docker/` 配置) +7. webhook 队列增加持久化能力 +8. 修复 `logger.ts` 中 `err.stderr` vs `error.stderr` 不一致 +9. 为 `triage/processor.ts` `listCandidates` 增加分页支持 +10. 在 `normalize.ts` 中增加 patch 有效行校验 + +### 长期演进 (P3+) + +11. 实现分片并行审查 (Sharded Review) +12. 实现 AI Provider 抽象层 (`ChatProvider` 接口) +13. 实现审查结果去重与自检 +14. 实现国际化支持 +15. 实现审查历史学习与自适应严格度 +16. 在 CI 中设置覆盖率门槛 (≥80%) +17. 添加预提交 hook (husky + lint-staged) +18. 实现自动 changelog 生成 + +--- + +## 附录 A: 文件行数统计 (35 源文件 + 48 测试文件) + +| 排名 | 文件 | 行数 | 覆盖 | 需关注 | +|------|------|------|------|--------| +| 1 | src/review/processor.ts | 1736 | 49.42% | 🔴 大文件 + 低覆盖 | +| 2 | src/review/conflictResolver.ts | 1250 | 57.52% | 🔴 大文件 + 低覆盖 | +| 3 | src/ai/gooseCli.ts | 726 | 73.07% | 🟡 3 种模式耦合 | +| 4 | src/triage/processor.ts | 576 | 63.19% | 🟡 低覆盖 | +| 5 | src/webhook/processor.ts | 518 | 72.39% | 🟡 中覆盖 | +| 6 | src/webhook/server.ts | 315 | 75.87% | 🟡 中覆盖 | +| 7 | src/actions/router.ts | 361 | 94.16% | ✅ | +| 8 | src/chat/processor.ts | 358 | 93.82% | ✅ | +| 9 | src/actions/runReview.ts | 293 | 93.52% | ✅ | +| 10 | src/storage/cacheStore.ts | 234 | 95.73% | ✅ | + +## 附录 B: 测试文件清单 (48 文件 / 321 测试) + +测试全部通过。覆盖率 lines 66.20% / branches 87.36% / functions 75.57%。 \ No newline at end of file diff --git a/docs/critical-review-v2.md b/docs/critical-review-v2.md new file mode 100644 index 0000000..400f7d8 --- /dev/null +++ b/docs/critical-review-v2.md @@ -0,0 +1,263 @@ +# Critical Code Review: ghbot v2 + +**Reviewer**: Automated code review +**Scope**: Full source tree (`src/` + `test/`) +**Commit**: db53296 (refactor: extract event router and bump version to v1.2.0) + +--- + +## 1. Summary + +This is a **well-architected** codebase with strong security awareness, thorough testing, and clean separation of concerns. The review pipeline, conflict resolution, and triage subsystems are production-grade. However, several critical defects exist — primarily **dead code shipped as production modules**, **duplicated defensive logic** that should be shared, a **sort-comparator contract violation**, and a **race window in conflict resolution eligibility**. + +The codebase uses a large number of small, focused files, consistent error handling, Zod schema validation everywhere, and comprehensive test coverage. The security posture (credential isolation, snapshot sanitization, path traversal prevention) is notably strong. + +**Verdict: Needs Discussion** — multiple real defects must be resolved before the next release, but no single bug is immediately exploitable or data-destructive in the current deployment. + +--- + +## 2. Critical Issues (Blocking) + +### C1. Dead Production Code: `MergeGuard` never called + +**File**: `src/review/merge-guard.ts` +**Evidence**: `src/review/processor.ts` `maybeMergePullRequest()` (line 831) does not instantiate or call `MergeGuard`. The class is defined, tested (`test/merge-guard.test.ts`), but **zero production imports** across the entire `src/` tree. + +**Impact**: The `MergeGuard` class exists solely to prevent duplicate merge attempts from concurrent schedule/approval/recheck events. The current code relies on the reactive `isAlreadyMergedError()` check (processor.ts:970-982), which catches already-merged errors but does not prevent redundant API calls. Under concurrent schedule triggers, two `pulls.merge` calls can race on the same PR — the 405 response is safe but wasteful, and the gap between the fresh PR state check (processor.ts:855-879) and the merge call (line 946) is not protected. + +**Fix**: Instantiate a singleton `MergeGuard` in `processor.ts` and guard `maybeMergePullRequest` at line 909 with `guard.isAlreadyAttempted()` before proceeding, then `guard.markAttempt()` before the merge call. + +### C2. Dead Production Code: `MetricsCollector` never called + +**File**: `src/metrics/collector.ts` +**Evidence**: The singleton `export const metrics = new MetricsCollector()` (line 131) is **never imported** by any production module. The webhook server uses `MetricsRegistry` from `webhook/metrics.ts` instead, which is correct — but the Actions-mode `MetricsCollector` is dead code with its own test suite. + +**Impact**: Metric collection in CI Actions mode is entirely non-functional. The `recordReviewDuration`, `recordGooseCall`, `recordConflictResolution`, `recordMergeAttempt` methods are never called. This is not a security or correctness issue, but it means all observability promises in the Actions path are false. + +**Fix**: Either (a) wire the `MetricsCollector` singleton into `processor.ts` and `gooseReviewer.ts` — the `processPullRequest` function, `submitReview`, conflict resolution calls, and `maybeMergePullRequest` are all natural injection points — or (b) delete the module and its tests to avoid misleading future maintainers. + +### C3. Dead Production Code: `failureMessages.ts` never imported + +**File**: `src/ai/failureMessages.ts` +**Evidence**: Both exported functions (`categorizeFailure`, `formatFailureMessage`) are **never imported** by any production module. The `withRetry` function in `retry.ts` handles its own error classification, and goose-call sites do not use these utilities. + +**Impact**: A self-contained, tested module that exists solely to be unused. The `formatFailureMessage` function produces user-facing messages that are more descriptive than the raw error propagation currently in use. This is a missed quality improvement. + +**Fix**: Wire `categorizeFailure` into the goose-call retry logic in `retry.ts` or `gooseReviewer.ts`, or delete the file. + +### C4. Sort comparator contract violation in `markReviewCheckApproved` + +**File**: `src/review/processor.ts`, lines 1347-1351 +**Code**: +```typescript +.sort( + (left, right) => Date.parse(right.started_at ?? "") - Date.parse(left.started_at ?? "") +) +``` +**Issue**: `Date.parse("")` returns `NaN`. `NaN - NaN` is `NaN`. The `Array.prototype.sort()` comparator must return a number — a `NaN` return value breaks the sort implementation, producing undefined behavior (the array may be in any order, or the sort may throw on some engines). + +**Failure scenario**: Any check run in the list where `started_at` is `null` or `undefined` causes the comparator to return `NaN` for that pair. The function then selects the wrong check run (or none) via `[0]`, potentially causing `markReviewCheckApproved` to: +- Update the wrong check run +- Throw `"Could not find ghbot review check"` if the wrong element is selected +- Silently skip the admin approval update + +**Fix**: Use a deterministic fallback: +```typescript +.sort((left, right) => { + const lt = left.started_at ? Date.parse(left.started_at) : 0; + const rt = right.started_at ? Date.parse(right.started_at) : 0; + return (Number.isNaN(rt) ? 0 : rt) - (Number.isNaN(lt) ? 0 : lt); +}) +``` + +### C5. Conflict resolution proceeds before admin approval + +**File**: `src/review/processor.ts`, lines 188-249 +**Code**: +```typescript +const conflictResolutionEligible = canAutoResolveConflicts({ + enabled: config.autoResolveConflicts, + reviewPassed: true, // <-- Hardcoded true + ... +}); +``` +**Issue**: When `REVIEW_POLICY=require_approval`, the review passes with `outcome: "pass"` but `requiresAdminApproval: true`. The `processPullRequest` function immediately proceeds to check conflict eligibility (line 188) with `reviewPassed: true` — before checking whether an admin has actually approved (that check is at line 164-170, but it does not prevent conflict resolution from starting). + +**Failure scenario**: The bot resolves conflicts and pushes a new commit, merging the PR *before* an admin has reviewed it. The `require_approval` policy is bypassed. + +**Fix**: Add `&& !disposition.requiresAdminApproval` to the conflict eligibility condition, or move the conflict resolution block after the admin approval check. + +### C6. Duplicated `isNotFoundError` across 5 files + +**Files**: +- `src/review/processor.ts:1065` +- `src/chat/processor.ts:307` +- `src/webhook/processor.ts:516` +- `src/review/conflictResolver.ts:1001` +- `src/repository/knowledge.ts:87` + +**Code** (identical in all): +```typescript +function isNotFoundError(error: unknown): boolean { + return typeof error === "object" && error !== null && "status" in error && error.status === 404; +} +``` + +**Impact**: Violates DRY. If the GitHub API ever changes its 404 response shape, all 5 copies must be updated. Adding a new file that needs this check (e.g., a new handler) is likely to create a 6th copy. + +**Fix**: Export a single `isNotFoundError` from `src/github/client.ts` or a new `src/github/errors.ts` and import it everywhere. + +--- + +## 3. Required Changes + +### R1. Duplicate `isNotFoundError` — see C6 above + +### R2. Duplicate type-guard functions in webhook processor + +**File**: `src/webhook/processor.ts`, lines 500-514 +**Code**: `isRecord`, `asRecord`, `asString`, `asPositiveInteger` are defined locally, duplicating patterns used elsewhere. + +**Fix**: Extract these to a shared utility module (e.g., `src/shared/typeGuards.ts`) and import them. + +### R3. `GOOSE_MODEL` default `"gpt-5.4"` likely does not exist + +**File**: `src/config.ts`, line 62 +**Code**: `gooseModel: optionalString.default("gpt-5.4")` + +**Issue**: As of August 2026, `gpt-5.4` is not a known OpenAI model name. The first deployment will fail with a model-not-found error unless the operator overrides it. This is a misleading default that will cause every new deployment to fail until the env var is set. + +**Fix**: Either use a known model like `gpt-4o` as the default, or document prominently that `GOOSE_MODEL` must be set. Alternatively, remove the default and make it required. + +### R4. `labelName` function in triage handles both string and object — but called with `issue.labels` which may contain objects with `name` property + +**File**: `src/triage/processor.ts`, line 574 +**Code**: `issue.labels.map(labelName).filter(Boolean)` + +**Issue**: The `labels` field in the GitHub Issues API response is typed as `Array<{ name: string } | string>`. The `labelName` function handles both cases correctly, but the filter `.filter(Boolean)` after `labelName` is fragile — it will include empty strings as truthy. The `labelName` function returns `string`, and `""` is falsy, so `.filter(Boolean)` is safe here, but the intent is unclear. + +**Fix**: Use `.filter((name): name is string => name !== "")` or add a comment explaining the filter. + +### R5. Hardcoded `reviewPassed: true` in conflict eligibility — see C5 + +### R6. `envBoolean` zod preprocessor swallows unknown values + +**File**: `src/config.ts`, lines 8-27 +**Code**: The `default` case in the switch returns `value` (the string) as-is, which then fails the `z.boolean()` parse. The error message is unhelpful — it will say "Expected boolean, received string" without showing the actual value. + +**Fix**: Add a more descriptive error: +```typescript +default: + throw new Error(`Invalid boolean value: "${value}". Expected true/false/1/0/yes/no/on/off.`); +``` + +### R7. `isRecheckComment` and `isConflictComment` only match exact trim + +**Files**: `src/review/processor.ts`, lines 1375-1381 +**Code**: +```typescript +export function isRecheckComment(body: string): boolean { + return body.trim() === RECHECK_COMMENT_COMMAND; +} +``` + +**Issue**: `"/recheck "` (trailing spaces) is accepted, but `"/recheck\n"` is also accepted (trim handles it). However, `" /recheck /recheck"` is rejected. This is intentional. But `"/recheck\n\n"` works. The tests confirm this behavior. No change needed — this is a design choice, not a bug. + +### R8. `waitForMergeable` polls only 5 times with 1s intervals + +**File**: `src/review/processor.ts`, lines 1411-1432 +**Issue**: For large PRs, GitHub's mergeability computation can take >10 seconds. Five attempts at 1s intervals may not be enough. The function returns the last result even if `mergeable` is still `null`. + +**Fix**: Increase to 10 attempts, or use exponential backoff (1s, 2s, 4s, 8s, 10s, 10s...). + +--- + +## 4. Suggestions + +### S1. Extract `isNotFoundError` to shared module + +See C6. Low effort, high DRY return. + +### S2. Extract type-guard functions to shared module + +See R2. Low effort, reduces duplication. + +### S3. Add `MergeGuard` to `processor.ts` + +See C1. Prevents a rare but real race condition on concurrent schedule events. + +### S4. Wire `MetricsCollector` into production code + +See C2. Either wire it or remove it. Half-shipped observability is worse than none. + +### S5. Wire `failureMessages` into retry logic + +See C3. The `formatFailureMessage` produces better user-facing error messages than the current raw error propagation. + +### S6. Move `PROTECTED_DIRECTORIES` and `PROTECTED_FILE_NAMES` to a shared config + +**File**: `src/security/sanitization.ts` +**Suggestion**: These are referenced by `chat/processor.ts`, `review/conflictResolver.ts`, and potentially future modules. The current single-file definition is good. No change needed — this is already well-structured. + +### S7. Add `"Dockerfile"` and `"docker-compose.yml"` to `PROTECTED_FILE_NAMES`? + +**File**: `src/security/sanitization.ts` +**Discussion**: These can carry registry credentials and build secrets. Consider adding them. The current list is already comprehensive — this is a judgment call. + +### S8. The `askpass.sh` temporary directory permissions + +**File**: `src/review/conflictResolver.ts`, lines 120-137 +**Issue**: The directory is created with `fs.mkdtemp` (default permissions = 0o700 on Linux, but the parent directory permissions may be 0o755 or more permissive). The `askpass.sh` script is written with `mode: 0o700`, which is correct. However, the directory containing the token is at `tempRoot/tempDir`, and `tempRoot` is created with `{ recursive: true }` which uses default permissions. + +**Suggestion**: Set `tempRoot` permissions to 0o700 after creation, or use a more restrictive parent directory. + +### S9. The `normalizeReviewMode` function silently maps `"lenient"` to `"normal"` + +**File**: `src/review/policy.ts`, line 143 +**Code**: +```typescript +function normalizeReviewMode(value: string): ReviewMode { + return value === "strict" ? "strict" : "normal"; +} +``` + +**Issue**: The `parseReviewExternalId` and `parseReviewStateMarker` functions accept `"lenient"` as a valid mode in their regex patterns, but `normalizeReviewMode` silently maps it to `"normal"`. This means a check run with `external_id` containing `mode=lenient` will be parsed as `mode: "normal"`. The `formatReviewExternalId` never produces `"lenient"`, so this only affects manually crafted check runs. This is tolerable but could be confusing during debugging. + +**Fix**: Either reject `"lenient"` in the regex patterns, or document that `"lenient"` is treated as `"normal"`. + +### S10. Test coverage: `replace_all` is not tested + +No test covers the `replace_all` behavior of `Edit` tool. This is not a codebase issue — it's a tooling note. + +--- + +## 5. Verdict + +**Needs Discussion** + +| Category | Count | Severity | +|----------|-------|----------| +| CRITICAL (Blocking) | 6 | C1-C6 | +| REQUIRED | 8 | R1-R8 | +| SUGGESTION | 10 | S1-S10 | + +**Must fix before next release**: +- C1: Wire `MergeGuard` into `processor.ts` (prevents duplicate merge race) +- C2: Wire or remove `MetricsCollector` (half-shipped observability) +- C3: Wire or remove `failureMessages.ts` (dead code) +- C4: Fix `NaN` sort comparator in `markReviewCheckApproved` +- C5: Add `requiresAdminApproval` guard to conflict eligibility +- C6: Deduplicate `isNotFoundError` +- R3: Fix `GOOSE_MODEL` default + +**Should fix but not blocking**: +- R2: Extract type-guard helpers +- R8: Improve `waitForMergeable` polling +- S9: Clean up `"lenient"` mode handling + +**No action needed** (confirmed clean): +- Security posture (container isolation, credential redaction, path traversal protection, snapshot sanitization) is strong +- Config schema validation is thorough +- All existing tests pass and are well-structured +- Error handling is consistent with Zod parsing +- Immutability patterns are followed throughout \ No newline at end of file diff --git a/docs/report-v2.html b/docs/report-v2.html new file mode 100644 index 0000000..009b2c1 --- /dev/null +++ b/docs/report-v2.html @@ -0,0 +1,999 @@ + + + + + +ghbot v2.0 迭代报告 + + + + + + + +
+
+
GHBOT · v2.0
+ +
+
+ +
+
+

ghbot/iteration report/v1.2.0 → v2.0

+

ghbot v2.0 迭代报告

+

+ ghbot 是基于 GitHub Actions 的机器人,用 goose CLI(OpenAI 兼容 chat API)完成 + PR 审查、Issue/PR 分类、@bot 对话、冲突修复,并可选运行只读 webhook 长驻模式。 + 本次 v2.0 半程迭代按《下一步改进指南》M0–M7 推进,第一阶段落地 + M0 测试加固、M1 可靠性、M2 可观测性三个方向,全部门禁通过、无 P0 阻塞项。 +

+ +
+ 基准版本 v1.2.0 · commit db53296 + 当前 v2.0 半程 + 阶段 M0 · M1 · M2 + 审计日期 2026-08-24 + 覆盖范围 src 35 + test 48 +
+ +
+ ✓typecheckPASS + ✓lint0 error + ✓format:checkPrettier OK + ✓test321 / 321 + ✓builddist/ OK +
+ +
+
+ +170 + 151 → 321 + 测试用例 · ×2.1 +
+
+ +12 + 36 → 48 + 测试文件 +
+
+ 66.20% + lines +4.79pp + 行覆盖率 +
+
+ 87.36% + branches +4.38pp + 分支覆盖率 +
+
+
+
+ +
+ + +
+
+

CTX

+

项目与本次迭代范围

+

处理不受信任的 PR 内容与多种凭据,凭据隔离是硬性红线:GitHub token、App 私钥、R2 与真实 goose API key 绝不进入 goose 容器、PR 快照或 git 子进程环境。

+
+ +
+

系统能力地图

+

ghbot 在生产中同时承担五个链路,本次迭代未改变其对外行为,仅加固内部质量。

+
+ 1 PR 审查 review / change / comment / result + 2 Issue/PR 分类 标签 + 两阶段重复检测 + 3 @bot 对话 一次性 Docker 容器 + 脱敏快照 + 4 冲突修复 safeToCommit=true 后才推送 + 5 Webhook 模式 可选 · 默认关闭 · 只读 +
+

+ 合并策略由 REVIEW_POLICY 控制(默认 allow),AUTO_MERGE 保持 opt-in; + 事件路由在 v1.2.0 已提取为 src/actions/router.ts 的 EventRouter,review / triage / chat / conflict 四类流程在此分发。 +

+
+ +
+

v2.0 迭代覆盖了什么

+

范围:M0 测试基建与覆盖率、M1 可靠性组件、M2 可观测性组件。M3 大文件拆分与 M4–M7 后续里程碑留待下一阶段。

+
+
+

已落地方向

+
    +
  • M0:7 个模块覆盖率补测,新增 10 个专项测试文件
  • +
  • M1:withRetry 智能重试、MergeGuard、failureMessages
  • +
  • M2:MetricsCollector 指标收集器
  • +
  • 测试总数 151 → 321,行覆盖率 61.41% → 66.20%
  • +
+
+
+

依赖前置、暂缓方向

+
    +
  • M0-8 集成测试:需 testcontainers / MinIO 基础设施
  • +
  • M1-2 陈旧检测、M2-1 全链路日志:待 processor.ts 拆分
  • +
  • M3 大文件拆分:processor.ts 1736 行 / conflictResolver.ts 1250 行
  • +
+
+
+
+
+ + +
+
+

CHANGES

+

本轮落地内容(M0 / M1 / M2)

+

11 个里程碑项落地:其中 8 项完整接入并验证,3 个新模块已交付(含 100% 测试)但尚未接线到生产路径——这是审计与 critical review 的共同关注点。

+
+ +
+ + + + + + + + + + + + + + +
M0 · 测试加固
里程碑目标模块变化状态
M0-1repository/knowledge.ts normalizeKnowledgeCRLF/LF 行尾归一,缓存校验与快照写入一致✓ 落地
M0-2review/gooseReviewer.ts覆盖 26.57% → 97.35%✓ 落地
M0-3storage/cacheStore.ts(R2)覆盖 49.01% → 100%✓ 落地
M0-4triage/processor.ts覆盖 56.77% → 63.19%✓ 落地
M0-5webhook/processor.ts覆盖 63.90% → 72.39%✓ 落地
M0-6review/conflictResolver.ts覆盖 56.56% → 57.52%✓ 落地
M0-7review/processor.ts覆盖 49.08% → 49.42%✓ 落地
+
+ +
+ + + + + + + + + + +
M1 · 可靠性
里程碑组件内容状态
M1-1src/retry.ts withRetry指数退避 + 抖动 + 4xx 可重试分类 + 总超时兜底✓ 落地接入
M1-3src/review/merge-guard.ts合并防重入锁,100% 测试覆盖◇ 已建未接入
M1-4src/ai/failureMessages.tscategorizeFailure / formatFailureMessage,失败分类与告警文案,100% 覆盖◇ 已建未接入
+
+ +
+ + + + + + + + + + +
M2 · 可观测性
里程碑组件内容状态
M2-2src/metrics/collector.tsrecordReviewDuration / recordGooseCall / recordConflictResolution / recordMergeAttempt,100% 覆盖◇ 已建未接入
M2-1全链路日志贯穿需 processor.ts 拆分后接入○ 未落地
M1-2陈旧检测(stale detection)LLM 运行期间 head 变化时丢弃结果、浪费完整调用;需处理器拆分○ 未落地
+
+ +
+

新增专项测试文件(10 个 / 125 条用例)

+

其余 +45 条用例来自既有测试文件的增强。审计复核:新模块全部 100% 覆盖,核心大模块仍有缺口。

+
+ + + + + + + + + + + + + + + + +
测试文件用例数覆盖评价
test/goose-reviewer.test.ts1197.35%✓ 达标
test/r2-storage.test.ts22100%✓ 达标
test/webhook-processor-extra.test.ts3572.39%中
test/conflict-resolver-extra.test.ts1257.52%待补
test/triage-processor-extra.test.ts11—✓ 已覆盖
test/merge-guard.test.ts5100%✓ 达标
test/metrics-collector.test.ts9100%✓ 达标
test/failure-messages.test.ts8100%✓ 达标
test/retry-extra.test.ts5100%✓ 达标
test/review-processor-extra.test.ts749.42%待补
+
+
+
+ + +
+
+

METRICS

+

指标对照:v1.2.0 → v2.0

+

测试规模翻倍以上,覆盖率各分项稳步上升;核心大模块仍低于 80% 目标,是下一阶段主攻方向。

+
+ +
+
+
测试文件test/*.test.ts
+
36
+
48
+
+12
+
+
+
测试用例node:test + tsx
+
151
+
321
+
+170 · ×2.1
+
+
+
行覆盖率 lines全局
+
61.41%
+
66.20%
+
+4.79pp
+
+
+
分支覆盖率 branches全局
+
82.98%
+
87.36%
+
+4.38pp
+
+
+
函数覆盖率 functions全局
+
69.97%
+
75.57%
+
+5.60pp
+
+ +
+
覆盖率趋势虚线为 80% 目标线
+
+ +
+ 基线 61.41% + 本轮 +4.79pp + 距 80% 目标缺口 13.80pp +
+
+
+
+ +
+ + + + + + + + + + + + + +
关键模块覆盖现状(审计 7.1,目标 ≥80%)
模块当前 lines目标缺口主要待补路径
review/processor.ts(1736 行)49.42%80%-30.58pp主流程、旧审查清理、合并/审批、调度
review/conflictResolver.ts(1250 行)57.52%80%-22.48pp冲突解析主流程、验证运行、命令执行
triage/processor.ts63.19%80%-16.81pp两阶段详查、标签创建、重复评论
webhook/processor.ts72.39%80%-7.61pp提及主流程、上下文加载、组织成员分支
webhook/server.ts75.87%80%-4.13pp队列满 503、body 超时 413、启动流程
storage/cacheStore.ts95.73%95%达标—
+
+
+ + +
+
+

AUDIT

+

审计发现(audit-v2-final)

+

最终审计覆盖全部 src/ 35 文件、test/ 48 文件、配置、文档与工作流。结论:无 P0 阻塞,整体安全评级 A-;8 项 P1、10 项 P2、10 项 P3。

+
+ +
+
P0 阻塞项

0

构建、类型检查、测试全部通过,无阻塞项。

+
安全评级

A-

凭据隔离 A · 注入防护 A · 快照脱敏 B+ · 密钥脱敏 A · 子进程安全 B。

+
+ +

P1 · 高优先级(合并前应处理)

+
+ + + + + + + + + + + + +
ID问题位置说明
P1-01MergeGuard 未接入生产review/merge-guard.ts有定义有测试,maybeMergePullRequest 未调用,无实际防重入
P1-02failureMessages 未接入ai/failureMessages.ts无任何模块 import,告警文案能力未生效
P1-03MetricsCollector 未接入metrics/collector.tsActions 模式指标收集完全未启用
P1-04大文件:processor.ts 1736 行review/processor.ts远超 800 行上限,7+ 职责混排
P1-05大文件:conflictResolver.ts 1250 行review/conflictResolver.ts5+ 独立职责,未落地到下一阶段
P1-06覆盖率不足 80% 目标全局lines 66.20%;processor 49.42%、triage 63.19%
P1-07waitForMergeable 无总超时processor.ts:1411-14325 次重试 ×1s 无兜底,mergeable 可能无限返回 null
P1-08审查运行期间无陈旧检测processor.ts:98-105LLM 期间 head 变化直接丢弃结果,浪费完整调用
+
+ +

P2 · 中优先级(抽样)

+
+
P2-01

快照排除清单不完整

缺 .npmrc、terraform/、kube/、docker/ 配置,可能含注册表令牌或云凭据。

security/sanitization.ts
+
P2-02

Webhook 队列无持久化

进程重启丢失全部待处理任务。

webhook/server.ts
+
P2-03/04

两处分页缺失

processScheduledPendingMerges 与 triage listCandidates 均只取第一页 100 条。

review/processor.ts · triage/processor.ts
+
P2-08/09

凭据进入子进程环境

OPENAI_API_KEY 暴露到 goose 子进程 env;GHBOT_GIT_TOKEN 经 askpass 环境变量传递。

ai/gooseCli.ts · review/conflictResolver.ts
+
P2-10

日志 redact 模式不一致

redact 覆盖 err.stderr 但遗漏 error.stderr。

logger.ts:33-34
+
P3-07

CI 无覆盖率门槛

ci.yml 未设置覆盖率阈值,下降不会被阻止。

.github/workflows/ci.yml
+
+ +
+

安全评审逐项评级

+

审计独立给出六个维度的评级与要点,作为生产准入依据。

+
+
A凭据隔离
+
A注入防护
+
B+快照脱敏
+
A密钥脱敏
+
B子进程安全
+
+

+ 摘要:容器内无真实凭据、一次性代理认证可靠;路径/分支/仓库名白名单校验完善; + 正则 + pino redact 双保险覆盖 PAT / npm / OpenAI / Bearer / 私钥样式; + 子进程环境变量存在低频泄露风险,故子进程安全为 B。 +

+
+
+ + +
+
+

REVIEW

+

关键评审发现(critical-review-v2)

+

独立 critical review 逐文件复核 src/ 与 test/,给出 6 项 CRITICAL、8 项 REQUIRED、10 项 SUGGESTION。

+
+ +
+
Verdict
+

Needs Discussion — 代码结构良好、安全基线强,但存在若干真实缺陷:以"已定义但未接线"的死代码为主,另有排序比较器契约违规与合并前审批竞态。当前部署无即时可利用或数据破坏性缺陷。

+
+ +
+ + + + + + + + + + + +
CRITICAL · 发布前必须处理
ID发现位置影响
C1MergeGuard 从未被调用review/merge-guard.ts并发 schedule/approval/recheck 可对同一 PR 竞态调用 pulls.merge
C2MetricsCollector 从未被 importmetrics/collector.tsActions 模式观测能力完全失效,可观测性承诺落空
C3failureMessages.ts 无生产引用ai/failureMessages.ts更优的用户侧失败文案未生效
C4Sort 比较器返回 NaNprocessor.ts:1347-1351Date.parse("") 为 NaN,可能选错 check run 或抛"Could not find"
C5冲突修复先于管理员审批processor.ts:188-249require_approval 下 admin 审批前即可推提交并合并,策略被绕过
C6isNotFoundError 五处重复processor / chat / webhook / conflictResolver / knowledgeAPI 404 形态变化需同步五处,违 DRY
+
+ +
+ + + + + + + + + +
REQUIRED · 建议优先(非阻塞)
ID发现位置说明
R3GOOSE_MODEL 默认 gpt-5.4 可能不存在config.ts:62新部署将模型找不到失败,除非覆盖环境变量
R8waitForMergeable 仅轮询 5 次 ×1sprocessor.ts:1411-1432大 PR 合并性计算 >10s,建议指数退避(对应审计 P1-07)
R2webhook 内类型守卫重复webhook/processor.ts:500-514isRecord/asRecord/asString 建议抽共享工具模块
R1重复守卫收敛全局与 C6 同源:单点导出 isNotFoundError
+
+ +
+

评审确认的"干净项"

+

无需改动,评审明确认可。

+
    +
  • 安全态势:容器隔离、凭据脱敏、路径穿越防护、快照过滤均强
  • +
  • 配置 zod schema 校验彻底、错误处理一致、全程遵循不可变风格
  • +
  • 全部既有测试通过且结构良好
  • +
+
+
+ + +
+
+

QUIZ

+

知识校验:读完即答

+

10 道单选题,全部基于上方报告数据。答对 ≥8 题(80%)视为通过。逐题作答自动判分,全部答完后可查看结业结论。

+
+ +
+
+

v2.0 迭代知识校验

+
+ 已作答 0/10 · 正确 0 +
+
+
+
+
+
+

—

+

+ +
+
+
+ +
+
+
+
+ +
+ + + + + + \ No newline at end of file diff --git a/src/chat/processor.ts b/src/chat/processor.ts index d749f1f..f1e02d7 100644 --- a/src/chat/processor.ts +++ b/src/chat/processor.ts @@ -6,6 +6,7 @@ import { config } from "../config.js"; import { postPermissionDeniedComment } from "../github/commandFeedback.js"; import { logger } from "../logger.js"; import { withRetry } from "../retry.js"; +import { isNotFoundError } from "../github/errors.js"; import { compactFilesForReview } from "../review/prompt.js"; import type { PullRequestFile } from "../types.js"; import { @@ -304,10 +305,6 @@ function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -function isNotFoundError(error: unknown): boolean { - return typeof error === "object" && error !== null && "status" in error && error.status === 404; -} - export async function createRepositorySnapshot(sourceWorktree: string): Promise { const sourceRoot = await fs.realpath(sourceWorktree); const tempRoot = tempRootDirectory(); diff --git a/src/github/errors.ts b/src/github/errors.ts new file mode 100644 index 0000000..954807d --- /dev/null +++ b/src/github/errors.ts @@ -0,0 +1,34 @@ +/** + * Shared GitHub API error utilities. + */ + +export function isNotFoundError(error: unknown): boolean { + return typeof error === "object" && error !== null && "status" in error && error.status === 404; +} + +export function isAlreadyMergedError(error: unknown): boolean { + if (typeof error !== "object" || error === null || !("status" in error)) { + return false; + } + const candidate = error as { status?: unknown; message?: unknown }; + if (candidate.status !== 405 && candidate.status !== 409) { + return false; + } + return ( + typeof candidate.message === "string" && + /already.{0,20}merged|Pull Request is not mergeable/i.test(candidate.message) + ); +} + +export function isRetryableGitHubError(error: unknown): boolean { + if (typeof error !== "object" || error === null) { + return false; + } + const candidate = error as { status?: unknown }; + if (typeof candidate.status === "number") { + if (candidate.status === 429) return true; + if (candidate.status >= 500 && candidate.status < 600) return true; + return false; + } + return false; +} \ No newline at end of file diff --git a/src/review/processor.ts b/src/review/processor.ts index 7323996..d47b751 100644 --- a/src/review/processor.ts +++ b/src/review/processor.ts @@ -21,6 +21,9 @@ import { } from "./policy.js"; import { compactFilesForReview } from "./prompt.js"; import { loadRepositoryKnowledge } from "../repository/knowledge.js"; +import { MergeGuard } from "./merge-guard.js"; +import { metrics } from "../metrics/collector.js"; +import { isNotFoundError, isAlreadyMergedError } from "../github/errors.js"; import { canAutoResolveConflicts, describeConflictResolutionFailure, @@ -28,6 +31,7 @@ import { } from "./conflictResolver.js"; const reviewer = new GooseReviewer(); +const mergeGuard = new MergeGuard(); const CHECK_RUN_NAME = "ghbot review"; export const RECHECK_COMMENT_COMMAND = "/recheck"; export const CONFLICT_COMMENT_COMMAND = "/conflict"; @@ -186,7 +190,7 @@ export async function processPullRequest( } const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber); - const conflictResolutionEligible = canAutoResolveConflicts({ + const conflictResolutionEligible = !disposition.requiresAdminApproval && canAutoResolveConflicts({ enabled: config.autoResolveConflicts, reviewPassed: true, mergeable: mergeablePullRequest.mergeable, @@ -918,9 +922,17 @@ async function maybeMergePullRequest( }); }); } + metrics.recordMergeAttempt("failed"); return; } + if (mergeGuard.isAlreadyAttempted(owner, repo, pullNumber)) { + logger.info({ owner, repo, pullNumber }, "Skipping merge because MergeGuard already attempted it."); + metrics.recordMergeAttempt("already_merged"); + return; + } + mergeGuard.markAttempt(owner, repo, pullNumber); + if (config.requireChecks) { const checks = await requiredChecksAreGreen(octokit, { owner, @@ -961,24 +973,13 @@ async function maybeMergePullRequest( { owner, repo, pullNumber, headSha: params.headSha }, "Pull request was already merged by a concurrent run." ); + metrics.recordMergeAttempt("already_merged"); return; } + metrics.recordMergeAttempt("failed"); throw error; } -} - -function isAlreadyMergedError(error: unknown): boolean { - if (typeof error !== "object" || error === null || !("status" in error)) { - return false; - } - const candidate = error as { status?: unknown; message?: unknown }; - if (candidate.status !== 405 && candidate.status !== 409) { - return false; - } - return ( - typeof candidate.message === "string" && - /already.{0,20}merged|Pull Request is not mergeable/i.test(candidate.message) - ); + metrics.recordMergeAttempt("merged"); } async function hasCurrentHeadApprovalFrom( @@ -1062,8 +1063,9 @@ async function hasCurrentHeadApprovalFrom( return false; } -function isNotFoundError(error: unknown): boolean { - return typeof error === "object" && error !== null && "status" in error && error.status === 404; +function errorHasStatus(error: unknown, key: string, expected: number): boolean { + const candidate = error as Record; + return typeof candidate[key] === "number" && candidate[key] === expected; } function reviewProgressMarker(headSha: string): string { @@ -1346,9 +1348,11 @@ async function markReviewCheckApproved( }); const check = checks.data.check_runs .filter((item) => item.name === CHECK_RUN_NAME) - .sort( - (left, right) => Date.parse(right.started_at ?? "") - Date.parse(left.started_at ?? "") - )[0]; + .sort((left, right) => { + const lt = left.started_at ? Date.parse(left.started_at) : 0; + const rt = right.started_at ? Date.parse(right.started_at) : 0; + return (Number.isNaN(rt) ? 0 : rt) - (Number.isNaN(lt) ? 0 : lt); + })[0]; if (!check) { throw new Error(`Could not find ${CHECK_RUN_NAME} check for ${params.headSha}.`); diff --git a/src/webhook/processor.ts b/src/webhook/processor.ts index 224961f..da41e98 100644 --- a/src/webhook/processor.ts +++ b/src/webhook/processor.ts @@ -7,6 +7,7 @@ import { withRetry } from "../retry.js"; import { compactFilesForReview } from "../review/prompt.js"; import type { PullRequestFile } from "../types.js"; import { listPullRequestFiles } from "../github/pulls.js"; +import { isNotFoundError } from "../github/errors.js"; const WEBHOOK_CHAT_MARKER = "