fix: production hardening for merge races, timeouts, and webhook ops

Pin merge SHA, lock conflict repair, bound subprocess/proxy output,
fail-fast incomplete R2/webhook config, redact validation/stderr
secrets, and document that webhook 202 is best-effort after ACK.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
wdawdwaandClaude Opus 4.8 committed 2026-08-23 15:44:08 +08:00
1 parent d6f33a71c3
commit 039acabd96
29 files changed
+1163 -240

No files matched your search

@@ -0,0 +1,37 @@
---
name: ghbot-production-hardening
description: Production close-out workflow for ghbot: spec, audit, fix P0/P1 guards, gates, webhook HTTP smoke, independent review, docs.
metadata:
last_verified: "2026-08-23"
repo_baseline: "v1.1.0-hardening"
---
# ghbot production hardening skill
## When to use
Closing a production iteration of this GitHub review bot. Not for adding unrelated SaaS features.
## Do not use
- Changing AUTO_MERGE default
- Reusing old review cache as a new-head approval
- Running paid LLM E2E without budget
- Pushing to remotes without write permission
## Inputs
Current repo, CLAUDE.md red lines, `.specify/memory/constitution.md`.
## Steps
1. Read constitution, CLAUDE.md, workflow_status.md, last verification record.
2. Rebuild facts: git status, typecheck, test.
3. Audit contract/security/error/docs before coding.
4. Fix P0 then P1 with tests. Skip 1700-line processor extraction unless an event-loop harness exists.
5. Gates: typecheck, lint, format:check, test, build, npm audit --omit=dev.
6. Webhook HTTP smoke on a spare port: /healthz, HMAC 202, bad sig 401, duplicate, /metrics.
7. Independent critic. Repair only confirmed Blocking/Required.
8. Sync README/.env.example/workflows. Write HTML report under docs/reports/.
## Stop
Missing credentials, origin 403, paid API, production deploy, no progress after two review loops.
## Verify
Never claim LLM review E2E or origin push without command evidence.
+7 -1
View File
@@ -1,4 +1,9 @@
PORT=3000
# Optional structured logging level (trace/debug/info/warn/error/fatal).
LOG_LEVEL=info
# Optional runtime root for writable scratch/cache storage. Empty means the process working directory.
GHBOT_RUNTIME_DIR=
# Optional in GitHub Actions because github.token is injected automatically.
# Still useful for local simulation and as a GitHub App fallback.
GITHUB_TOKEN=ghp_your_token_here
@@ -25,6 +30,8 @@ GOOSE_API_KEY=sk-...
GOOSE_BASE_URL=https://api.openai.com/v1
GOOSE_MODEL=gpt-5.4
GOOSE_THINKING_EFFORT=high
# Deprecated fallback aliases still accepted by config and workflows:
# OPENCODE_API_KEY, OPENCODE_BASE_URL, OPENCODE_MODEL, OPENCODE_REASONING_EFFORT
# allow | require_approval | reject. Ordinary review notes pass by default.
REVIEW_POLICY=allow
@@ -60,4 +67,3 @@ CONFLICT_TEST_COMMAND=
MERGE_METHOD=squash
REQUIRE_CHECKS=true
MAX_PATCH_CHARS=120000
LOG_LEVEL=info
+8 -8
View File
@@ -158,6 +158,10 @@ on:
required: false
type: string
default: "120000"
runtime_directory:
required: false
type: string
default: ""
log_level:
required: false
type: string
@@ -177,12 +181,6 @@ on:
required: false
GH_APP_INSTALLATION_ID:
required: false
GITHUB_APP_ID:
required: false
GITHUB_APP_PRIVATE_KEY:
required: false
GITHUB_APP_INSTALLATION_ID:
required: false
R2_ACCESS_KEY_ID:
required: false
R2_SECRET_ACCESS_KEY:
@@ -224,7 +222,7 @@ jobs:
GOOSE_BIN_DIR: ${{ runner.temp }}/goose/bin
CONFIGURE: "false"
run: |
curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | bash
curl -fsSL "https://github.com/aaif-goose/goose/releases/download/${GOOSE_VERSION}/download_cli.sh" | bash
echo "${GOOSE_BIN_DIR}" >> "${GITHUB_PATH}"
- run: npm ci
working-directory: ghbot-runtime
@@ -264,6 +262,7 @@ jobs:
MERGE_METHOD: ${{ inputs.merge_method }}
REQUIRE_CHECKS: ${{ inputs.require_checks }}
MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }}
GHBOT_RUNTIME_DIR: ${{ inputs.runtime_directory }}
LOG_LEVEL: ${{ inputs.log_level }}
GHBOT_EVENT_NAME: ${{ inputs.event_name }}
GHBOT_EVENT_ACTION: ${{ inputs.event_action }}
@@ -299,7 +298,7 @@ jobs:
GOOSE_BIN_DIR: ${{ runner.temp }}/goose/bin
CONFIGURE: "false"
run: |
curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | bash
curl -fsSL "https://github.com/aaif-goose/goose/releases/download/${GOOSE_VERSION}/download_cli.sh" | bash
echo "${GOOSE_BIN_DIR}" >> "${GITHUB_PATH}"
- run: npm ci
working-directory: ghbot-runtime
@@ -339,6 +338,7 @@ jobs:
MERGE_METHOD: ${{ inputs.merge_method }}
REQUIRE_CHECKS: ${{ inputs.require_checks }}
MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }}
GHBOT_RUNTIME_DIR: ${{ inputs.runtime_directory }}
LOG_LEVEL: ${{ inputs.log_level }}
GHBOT_EVENT_NAME: schedule
GHBOT_EVENT_ACTION: schedule
+6 -4
View File
@@ -59,7 +59,7 @@ jobs:
reviewer_login: ${{ github.event.review.user.login || '' }}
review_state: ${{ github.event.review.state || '' }}
review_commit_id: ${{ github.event.review.commit_id || '' }}
bot_name: github-actions[bot]
bot_name: ${{ vars.BOT_NAME || 'github-actions[bot]' }}
goose_base_url: ${{ vars.GOOSE_BASE_URL || vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }}
goose_model: ${{ vars.GOOSE_MODEL || vars.OPENCODE_MODEL || 'gpt-5.4' }}
goose_thinking_effort: ${{ vars.GOOSE_THINKING_EFFORT || vars.OPENCODE_REASONING_EFFORT || 'high' }}
@@ -86,7 +86,8 @@ jobs:
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
log_level: info
runtime_directory: ${{ vars.GHBOT_RUNTIME_DIR || '' }}
log_level: ${{ vars.LOG_LEVEL || 'info' }}
review-schedule-recheck:
if: github.event_name == 'schedule'
uses: ./.github/workflows/review-reusable.yml
@@ -105,7 +106,7 @@ jobs:
repository_name: ${{ github.event.repository.name }}
repository_id: ${{ github.repository_id }}
pull_number: "1"
bot_name: github-actions[bot]
bot_name: ${{ vars.BOT_NAME || 'github-actions[bot]' }}
goose_base_url: ${{ vars.GOOSE_BASE_URL || vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }}
goose_model: ${{ vars.GOOSE_MODEL || vars.OPENCODE_MODEL || 'gpt-5.4' }}
goose_thinking_effort: ${{ vars.GOOSE_THINKING_EFFORT || vars.OPENCODE_REASONING_EFFORT || 'high' }}
@@ -132,5 +133,6 @@ jobs:
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
log_level: info
runtime_directory: ${{ vars.GHBOT_RUNTIME_DIR || '' }}
log_level: ${{ vars.LOG_LEVEL || 'info' }}
run_schedule_recheck: "true"
+49
View File
@@ -0,0 +1,49 @@
# ghbot 项目宪法(Constitution)
> 版本: 1.0.0 · 生效日期: 2026-08-23
> 本文件是所有开发决策的最高约束。任何实现与本文冲突时,以本文为准。
## 核心价值观
1. **生产安全高于一切**:本机器人运行在生产仓库上,能关闭 PR、推送 commit、合并 PR。
任何改动若可能放大误操作半径,默认拒绝;必须改时需要显式护栏 + 测试证明。
2. **凭据零扩散**:GitHub token / App 私钥 / R2 密钥 / goose API key 绝不进入容器、快照、
git 子进程环境或日志。违反此条 = 阻塞级缺陷。
3. **PR 代码不可信**:自动审查/分类只用 API diff;PR 内容永远视为 untrusted data,
prompt 注入防护是功能需求而非可选项。
4. **诚实交付**:未验证的东西不宣称完成。测试失败必须如实报告,禁止为绿而削弱断言。
## 技术原则
### 架构
- 单一职责:一个模块只回答一个问题(谁调用它、它调用谁、失败时谁兜底)。
- 共享清单单一来源:安全排除/脱敏/路径策略只允许一份实现(src/security/, src/runtimePaths.ts)。
- 行为不变的重构必须与功能变更分开提交,且全量测试保护。
### 质量门禁(提交前全部通过)
1. `npm run typecheck` — 0 错误
2. `npm run lint` — 0 error
3. `npm run format:check` — 通过
4. `npm test` — 全绿;新增行为必须有新测试(TDD:先红后绿)
5. `npm run build` — dist 可被 node 加载
6. `npm audit --omit=dev` — 无 high 以上
### 安全红线(继承 CLAUDE.md,不可协商)
- AUTO_MERGE=false 默认值不可改
- 恢复缓存审查结果必须重新完整审查,不得直接复用旧决策
- fork 推送必须 SHA 钉住 --force-with-lease
- 知识缓存入库前拒绝凭据内容
## 决策框架
技术选型按序评估:
1. 是否触碰安全红线?(触碰 → 拒绝)
2. 是否可用现有轮子解决?(可以 → 不写新代码)
3. 失败时的降级行为是否清晰?(不清晰 → 先设计降级)
4. 是否可测试?(不可测 → 重构到可测)
## 变更治理
- 每个原子提交对应一个可独立回退的变更单元
- 公共接口(config schema、workflow inputs、评论文案契约)变更必须同步双语 README
- 文档与代码冲突时以代码为准,并在同一提交内修正文档
@@ -0,0 +1,29 @@
# Implementation Plan: 001-production-hardening
## Current architecture
ghbot is a GitHub Actions + optional webhook Node service. Review, triage, conflict repair, and @bot chat are orchestrated from `src/actions/runReview.ts`. Config is a single zod schema in `src/config.ts`. Persistence is optional R2 plus local scratch directories.
## Impacted modules
- `src/review/processor.ts` — merge SHA pinning, stale-head discard, approval lookup errors
- `src/review/conflictResolver.ts` — per-PR lock, git timeouts, worktree reset
- `src/ai/apiProxy.ts` / `src/ai/gooseCli.ts` — proxy/process timeouts and bounded output
- `src/webhook/server.ts` — body deadline, request catch, metrics
- `src/config.ts` / workflows / `.env.example` — GHBOT_RUNTIME_DIR, webhook/R2 cross-checks
- docs — webhook secret, docker run, goose aliases
## Implementation strategy
Fix production failure modes first. Keep AUTO_MERGE default false. Prefer additive guards over architecture rewrites. Do not extract the 1700-line processor router in this pass because there is no isolated event-loop test harness; that refactor is deferred with an explicit risk note.
## Verification
- npm run typecheck / lint / format:check / test
- production-build webhook HTTP smoke (healthz, HMAC, duplicate, metrics)
- npm audit --omit=dev against registry.npmjs.org
- independent six-dimension review after gates
## Rollback
Revert the production-hardening commit on the fork. Defaults remain conservative (AUTO_MERGE=false, WEBHOOK_ENABLED=false).
@@ -0,0 +1,61 @@
# Feature Specification: 001-production-hardening(生产硬化总审计)
## 问题陈述
ghbot 已在生产仓库运行(自动审查/分类/合并/冲突修复)。用户要求以"终局闭环总审计"标准,
对全部功能做查漏补缺:功能完整性、前后端衔接(此处为 workflow↔代码↔GitHub API 契约)、
调用体验、部署体验、文档一致性,并补齐指南中剩余未落地项。
## 用户故事
### US-1: 部署者首次接入
作为部署者,我希望按 README 从零配置后一次跑通,无需口口相传的隐性前提。
**验收**:
- [ ] .env.example 覆盖全部 config schema 字段且默认值一致
- [ ] README 步骤与实际命令一一对应
- [ ] 新增配置项有文档说明
### US-2: 事件全链路
作为仓库维护者,任何支持的事件触发后都有确定行为与反馈。
**验收**:
- [ ] workflow 触发的事件类型 ⊆ runReview.ts 处理集合(无静默吞事件)
- [ ] issue_comment 三链路互不阻断
- [ ] 每条失败路径都有可见反馈或日志
### US-3: 审查结果可信
作为 PR 作者,审查评论必须准确、可定位、不误导。
**验收**:
- [ ] finding 的 path/line 经净化后才提交
- [ ] 无法 inline 的 findings 折叠展示不丢失
- [ ] 状态横幅与 disposition 一致
### US-4: webhook 服务可运维
作为运维者,服务健康可探活、指标可观测、异常可恢复。
**验收**:
- [ ] /healthz 与 /metrics 真实可用
- [ ] 队列满/签名错/超大包均有明确响应码
- [ ] 失败投递进程内重试后仍可被 GitHub 重投
### US-5: 剩余指南项落地
指南 7.1 / 6.4 / 8.5 / 4.4 不再是"候选",全部实现或有明确的不适用结论。
**验收**:
- [ ] 每项有代码证据或书面不适用理由
- [ ] 全部门禁通过
## 非功能性需求
- 兼容性:Node >=22 <26;Windows/Linux 双平台测试通过
- 可观测性:关键路径日志含 owner/repo/pullNumber/eventName 四元组
- 安全性:宪法红线零违反
- 可维护性:无重复实现的安全清单;文件 <800 行
## Out of Scope
- 真实付费 LLM 调用的 E2E(预算 0)
- 前端 UI(本项目无前端)
## 成功指标
- 门禁六项全绿
- E2E:webhook 生产构建真实 HTTP 验收通过
- 需求追踪矩阵无"未闭环"项
@@ -0,0 +1,22 @@
# Implementation Tasks: 001-production-hardening
## Phase 1: Spec and audit
- [x] 1.1 Constitution + spec
- [x] 1.2 Parallel contract/security/error/docs audit
## Phase 2: Production guards
- [x] 2.1 Merge SHA recheck + pulls.merge sha
- [x] 2.2 Conflict lock + git command timeout + dirty worktree reset
- [x] 2.3 Webhook body timeout/size and request catch
- [x] 2.4 API proxy abort/timeout/body cap
- [x] 2.5 Goose process output cap and cleanup timeouts
- [x] 2.6 Config cross-field validation and GHBOT_RUNTIME_DIR contract
- [x] 2.7 Issue comment handler isolation with AggregateError
- [x] 2.8 Approval permission lookup no longer swallows retryable errors
- [x] 2.9 Event logger child bindings
## Phase 3: Verify and handoff
- [ ] 3.1 Local gates (typecheck/lint/format/test)
- [ ] 3.2 Webhook HTTP E2E
- [ ] 3.3 Independent review
- [ ] 3.4 HTML change report + skill + docs
+3 -3
View File
@@ -9,7 +9,7 @@ ENV GOOSE_VERSION=${GOOSE_VERSION} \
RUN apt-get update \
&& apt-get install --no-install-recommends -y bash ca-certificates curl \
&& rm -rf /var/lib/apt/lists/* \
&& curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | bash
&& curl -fsSL "https://github.com/aaif-goose/goose/releases/download/${GOOSE_VERSION}/download_cli.sh" | bash
WORKDIR /app
COPY package.json package-lock.json ./
@@ -18,7 +18,7 @@ COPY tsconfig.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev
# Action mode does not use this image. Webhook mode is explicitly opt-in.
ENV WEBHOOK_ENABLED=false
# This image is the webhook service. Action mode does not use it.
ENV WEBHOOK_ENABLED=true
EXPOSE 3000
CMD ["node", "dist/src/webhook/server.js"]
+20 -5
View File
@@ -31,6 +31,7 @@ goose 的审核结果固定包含四个顶层字段:
- `REVIEW_BRANCHES`:需要审核的 PR 目标分支 glob,以逗号分隔;留空表示全部分支。例如 `main,develop,release/**`。
- `REVIEW_STRICTNESS`:默认 `normal`;设为 `strict` 才会全面严格检查。普通模式不吹毛求疵,只报告明确的运行、构建、测试、安全、数据丢失或重要用户体验回归。
- `MAX_PATCH_CHARS`:单次发送给模型的最大 patch 字符数,默认 `120000`。
- `GHBOT_RUNTIME_DIR`:可选的可写 runtime 根目录,用于 `.ghbot-tmp`、`.ghbot-cache` 和仓库知识文件;留空时使用进程工作目录。
`REVIEW_BRANCHES` 匹配 PR 的 base branch。`*` 不跨越 `/`,`**` 可以跨越 `/`。workflow 文件需要存在于仓库默认分支,但这不表示只能审核指向默认分支的 PR;例如 workflow 位于 `main` 时,仍可审核目标为 `develop` 或 `release/1.x` 的 PR。
@@ -128,7 +129,7 @@ Action 模式仍然是默认模式,不需要 Webhook 服务也可以完整使
只有在同时运行长期 Node 进程或本仓库提供的 `Dockerfile.webhook` 时才启用 Webhook。它接收 GitHub App 的 webhook 事件,处理 Issue/PR conversation comment、review comment 和提交的 review 中对 `@bot` 的提问。适合组织只安装一次 App、由多个仓库共用一个服务端点的场景。App 必须安装到每个目标仓库,或者组织安装时选择包含这些仓库;未被该 installation 授权的仓库无法访问。
GitHub App 的 Webhook URL 配置为 `https://你的域名/webhooks/github`,`WEBHOOK_SECRET` 使用同一个密钥,并订阅 `Issue comments`、`Pull request review comments`、`Pull request reviews`。App 需要 `Metadata: read`、`Issues: read and write`、`Pull requests: read and write`。服务会使用每个 payload 中的 `installation.id` 换取对应的短期 installation token,不能用一个固定 installation ID 代替所有仓库。
GitHub App 的 Webhook URL 配置为 `https://你的域名/webhooks/github`,`WEBHOOK_SECRET` 必须使用独立的长随机 HMAC 密钥,并在 GitHub App Webhook 设置和服务环境中配置相同密钥;不要把公开 URL 当作密钥。并订阅 `Issue comments`、`Pull request review comments`、`Pull request reviews`。App 需要 `Metadata: read`、`Issues: read and write`、`Pull requests: read and write`。服务会使用每个 payload 中的 `installation.id` 换取对应的短期 installation token,不能用一个固定 installation ID 代替所有仓库。
服务环境变量如下:
@@ -138,7 +139,20 @@ GitHub App 的 Webhook URL 配置为 `https://你的域名/webhooks/github`,`W
- `WEBHOOK_CHAT_PERMISSION`:`read`(默认)、`write` 或 `anyone`。对于组织拥有的仓库,`read` 还会允许组织成员直接提问,不要求把每个成员单独添加为仓库协作者;个人仓库和组织外用户仍走仓库协作者权限检查。`write` 只允许 write、maintain、admin;`anyone` 跳过评论者权限检查,但仍只能访问 App 已安装的仓库。建议给 App 配置组织级 `Members: read`,这样才能验证私有组织成员身份。
- `WEBHOOK_QUEUE_CONCURRENCY` 和 `WEBHOOK_QUEUE_LIMIT` 用于限制后台处理量和内存。
可以用 `npm run build && npm run webhook` 启动,也可以构建 `docker build -f Dockerfile.webhook -t ghbot-webhook .` 后运行,并传入 App 凭证、Webhook 密钥和 Goose 配置。`GET /healthz` 可作为健康检查。服务会先返回 `202` 再后台调用 Goose;请求使用 HMAC 验签,按 `X-GitHub-Delivery` 去重,后台失败的 delivery 仍可被 GitHub 重试。
可以用 `npm run build && npm run webhook` 启动,也可以构建并运行 Docker:
```bash
docker build -f Dockerfile.webhook -t ghbot-webhook .
docker run --rm -p 3000:3000 \\
-e WEBHOOK_ENABLED=true \\
-e WEBHOOK_SECRET='替换为长随机密钥' \\
-e GH_APP_ID='123456' \\
-e GH_APP_PRIVATE_KEY="$GH_APP_PRIVATE_KEY" \\
-e GOOSE_API_KEY="$GOOSE_API_KEY" \\
ghbot-webhook
```
TLS 应由反向代理或托管 ingress 终止;Node 服务监听 `PORT`(默认 `3000`)。`GET /healthz` 可作为健康检查,`GET /metrics` 提供 Prometheus 文本指标。服务会先返回 `202` 再后台调用 Goose,因为模型耗时可能超过 GitHub webhook 超时。后台失败只会在进程内重试一次;进程在 `202` 之后崩溃时 GitHub **不会**重投。需要可靠执行 `/recheck`、`/conflict` 和带工具的对话时请用 Action 模式。Webhook 对话是尽力而为。请求使用 HMAC 验签,并按 `X-GitHub-Delivery` 去重。
Webhook 对话刻意保持只读:Goose 只能收到仓库元数据、README、Issue/PR 内容、有限 diff 和近期讨论,不会获得仓库工具或凭证。因此它不能改代码、执行命令、push、运行 `/recheck` 或 `/conflict`;这些操作请继续使用 Action 模式。回复语言跟随最新一条评论,也不会暴露 provider 或 GitHub 密钥。不设置 `WEBHOOK_ENABLED` 就仍是普通的 Action-only 部署。
@@ -154,9 +168,10 @@ Webhook 对话刻意保持只读:Goose 只能收到仓库元数据、README、
## goose 配置
必须添加 Actions Secret:
必须添加 Actions Secret(运行审核或 Goose 操作时至少配置一个):
- `GOOSE_API_KEY`
- `GOOSE_API_KEY`(首选)
- `OPENCODE_API_KEY`(迁移兼容别名)
相关 Repository Variables:
@@ -253,7 +268,7 @@ npm run format:check # Prettier 格式检查
npm test # node:test 测试套件
```
可选的 webhook 服务提供 `GET /healthz` 与 `GET /metrics`(Prometheus 文本格式)用于探活与监控。
可选的 webhook 服务提供 `GET /healthz` 与 `GET /metrics`(Prometheus 文本格式)用于探活与监控。生产硬化变更说明与测验见 [docs/reports/ghbot-production-hardening.html](docs/reports/ghbot-production-hardening.html)。
## 本地开发
+20 -5
View File
@@ -29,6 +29,7 @@ Use repository Actions variables to customize a caller repository:
- `REVIEW_BRANCHES`: comma-separated base-branch globs. Empty reviews all target branches. Example: `main,develop,release/**`.
- `REVIEW_STRICTNESS`: `normal` by default, or `strict` for a thorough repository-policy review. Normal mode avoids nitpicks and reports only clear runtime, build, test, security, data-loss, or important user-facing regressions.
- `MAX_PATCH_CHARS`: maximum total patch text sent for review; default `120000`.
- `GHBOT_RUNTIME_DIR`: optional writable runtime root for `.ghbot-tmp`, `.ghbot-cache`, and repository knowledge files; defaults to the process working directory.
`REVIEW_BRANCHES` matches the pull request's target (base) branch. `*` does not cross `/`; `**` does. The workflow file must be present on the repository's default branch for `pull_request_target`, but that does not limit reviews to PRs targeting the default branch. A workflow installed on `main` can review PRs targeting `develop` or release branches. The bot fetches each PR and its diff by PR number and never executes code from the PR head.
@@ -114,7 +115,7 @@ Action mode remains the default and is complete without a webhook service. `WEBH
Enable webhook mode only when you also run a long-lived Node process or the included `Dockerfile.webhook`. It receives GitHub App webhook events and answers `@bot` mentions in Issue/PR conversation comments, review comments, and submitted reviews. It is useful when the App is installed once for an organization and you want those repositories to share one endpoint. The App must be installed on each repository (or the organization selection must include it); a webhook cannot access repositories where the installation has no access.
Configure the GitHub App webhook URL as `https://your-host/webhooks/github`, use the same value for `WEBHOOK_SECRET`, and subscribe to `Issue comments`, `Pull request review comments`, and `Pull request reviews`. The App needs `Metadata: read`, `Issues: read and write`, and `Pull requests: read and write`. The endpoint exchanges each payload's `installation.id` for the correct short-lived installation token, so one fixed installation ID must not be used for all repositories.
Configure the GitHub App webhook URL as `https://your-host/webhooks/github`, and configure `WEBHOOK_SECRET` as a separate long random HMAC secret in both GitHub App webhook settings and the service environment. Never reuse the public URL as the secret. Subscribe to `Issue comments`, `Pull request review comments`, and `Pull request reviews`. The App needs `Metadata: read`, `Issues: read and write`, and `Pull requests: read and write`. The endpoint exchanges each payload's `installation.id` for the correct short-lived installation token, so one fixed installation ID must not be used for all repositories.
Set these service environment variables:
@@ -124,7 +125,20 @@ Set these service environment variables:
- `WEBHOOK_CHAT_PERMISSION`: `read` (default), `write`, or `anyone`. On organization-owned repositories, `read` also allows organization members without adding each member as a repository collaborator; personal repositories and non-members continue through the repository collaborator check. `write` allows write, maintain, or admin; `anyone` skips the commenter permission check but still only works in App-installed repositories. The App should have organization-level `Members: read` permission so private organization membership can be verified.
- `WEBHOOK_QUEUE_CONCURRENCY` and `WEBHOOK_QUEUE_LIMIT` bound background work and memory.
Start it with `npm run build && npm run webhook`, or build `docker build -f Dockerfile.webhook -t ghbot-webhook .` and run it with the App credentials, webhook secret, and Goose variables. `GET /healthz` is available for service probes. GitHub receives `202` before Goose runs; deliveries are HMAC-verified, deduplicated by `X-GitHub-Delivery`, and failed background deliveries remain retryable.
Start it with `npm run build && npm run webhook`, or build and run the Docker image:
```bash
docker build -f Dockerfile.webhook -t ghbot-webhook .
docker run --rm -p 3000:3000 \\
-e WEBHOOK_ENABLED=true \\
-e WEBHOOK_SECRET='replace-with-a-long-random-secret' \\
-e GH_APP_ID='123456' \\
-e GH_APP_PRIVATE_KEY="$GH_APP_PRIVATE_KEY" \\
-e GOOSE_API_KEY="$GOOSE_API_KEY" \\
ghbot-webhook
```
Keep TLS termination in a reverse proxy or managed ingress; the Node service listens on `PORT` (default `3000`). `GET /healthz` is available for service probes and `GET /metrics` exposes Prometheus text metrics. GitHub receives `202` before Goose runs because a review-quality model call can exceed GitHub's webhook timeout. Failed background work is retried in-process once; a process crash after `202` is **not** redelivered by GitHub. Use Action mode for durable `/recheck`, `/conflict`, and tool-enabled chat. Webhook chat is best-effort. Deliveries are HMAC-verified and deduplicated by `X-GitHub-Delivery`.
Webhook chat is deliberately read-only: Goose receives repository metadata, README, Issue/PR text, bounded diffs, and recent discussion, but no repository tools or credentials. It cannot edit code, run commands, push commits, run `/recheck`, or run `/conflict`; use Action mode for those operations. Replies follow the language of the latest comment and include no provider or GitHub secrets. Leaving `WEBHOOK_ENABLED` unset preserves the normal Action-only deployment.
@@ -140,9 +154,10 @@ After applying the proposed files, ghbot verifies there are no unmerged paths an
## goose configuration
Required secret:
Required provider secret (one of these aliases must be supplied when a review or Goose operation runs):
- `GOOSE_API_KEY`
- `GOOSE_API_KEY` (preferred)
- `OPENCODE_API_KEY` (migration fallback alias)
Repository variables:
@@ -243,7 +258,7 @@ npm run format:check # Prettier formatting
npm test # node:test suite
```
The optional webhook service exposes `GET /healthz` and `GET /metrics` (Prometheus text format) for probes and dashboards.
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).
## Local development
@@ -0,0 +1,234 @@
# ghbot Production Hardening
> 终局审计变更说明与验收测验。对照当前仓库真实实现,不包装未验证项。
<title>ghbot Hardening Ledger</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&family=Source+Serif+4:opsz,wght@8..60,600;8..60,700&display=swap">
<style>
:root {
--paper: #f3f0ea;
--ink: #1b2430;
--muted: #4d5968;
--line: #d7d1c6;
--accent: #b4471c;
--ok: #215e46;
--warn: #8a5a12;
--bad: #8f2d2d;
--card: #fffdf8;
--code: #ece7dc;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--paper: #12171f;
--ink: #e8e4da;
--muted: #a8b0bb;
--line: #2b3440;
--accent: #e07a4c;
--ok: #7dbe9d;
--warn: #e0b05a;
--bad: #e07a7a;
--card: #1a212b;
--code: #0f141b;
}
}
:root[data-theme="dark"] {
--paper: #12171f;
--ink: #e8e4da;
--muted: #a8b0bb;
--line: #2b3440;
--accent: #e07a4c;
--ok: #7dbe9d;
--warn: #e0b05a;
--bad: #e07a7a;
--card: #1a212b;
--code: #0f141b;
}
* { box-sizing: border-box; }
html, body { margin: 0; background: var(--paper); color: var(--ink); }
body {
font-family: "IBM Plex Sans", "Segoe UI", sans-serif;
line-height: 1.55;
}
.wrap {
max-width: 980px;
margin: 0 auto;
padding: 2.5rem 1.25rem 5rem;
}
h1, h2, h3 {
font-family: "Source Serif 4", Georgia, serif;
text-wrap: balance;
font-weight: 700;
}
h1 { font-size: 2.1rem; margin: 0 0 0.4rem; }
h2 { font-size: 1.35rem; margin: 2.2rem 0 0.7rem; border-top: 1px solid var(--line); padding-top: 1.2rem; }
p, li { color: var(--ink); }
.lede { color: var(--muted); max-width: 62ch; }
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 0.75rem;
margin: 1.2rem 0 1.6rem;
}
.stat {
background: var(--card);
border: 1px solid var(--line);
padding: 0.85rem 0.95rem;
}
.stat b { display: block; font-family: "IBM Plex Mono", monospace; font-size: 1.05rem; }
.stat span { color: var(--muted); font-size: 0.82rem; }
table { width: 100%; border-collapse: collapse; font-size: 0.92rem; }
th, td { text-align: left; padding: 0.45rem 0.4rem; border-bottom: 1px solid var(--line); vertical-align: top; }
.ok { color: var(--ok); font-weight: 600; }
.warn { color: var(--warn); font-weight: 600; }
.bad { color: var(--bad); font-weight: 600; }
code, pre {
font-family: "IBM Plex Mono", ui-monospace, monospace;
font-size: 0.86rem;
}
pre {
background: var(--code);
padding: 0.9rem 1rem;
overflow-x: auto;
border: 1px solid var(--line);
}
.quiz {
background: var(--card);
border: 1px solid var(--line);
padding: 1rem 1.1rem 1.2rem;
}
.q { margin: 1rem 0 0.4rem; font-weight: 600; }
label { display: block; margin: 0.2rem 0; }
button {
margin-top: 1rem;
background: var(--ink);
color: var(--paper);
border: 0;
padding: 0.55rem 0.9rem;
font: inherit;
cursor: pointer;
}
button:focus { outline: 2px solid var(--accent); outline-offset: 2px; }
#score { margin-top: 0.8rem; font-weight: 600; }
.hidden-answer { display: none; }
</style>
<p class="lede">这份报告对应 ghbot 生产硬化批次:合并 SHA 钉死、冲突锁、webhook/代理超时、配置交叉校验,以及本地门禁与 HTTP 冒烟。测验覆盖真实行为,不是口号。</p>
<div class="grid">
<div class="stat"><b>148</b><span>本地测试通过(本批次实测)</span></div>
<div class="stat"><b>0</b><span>生产依赖 audit high+</span></div>
<div class="stat"><b>P0/P1</b><span>已修运行时守卫;7.1 路由器未拆</span></div>
<div class="stat"><b>fork</b><span>origin lezi-fun/ghbot 无 push</span></div>
</div>
<h2>改了什么,为什么</h2>
<table>
<thead><tr><th>守卫</th><th>故障模式</th><th>落地</th></tr></thead>
<tbody>
<tr><td>合并 SHA</td><td>审查后 head 变化仍 merge</td><td><code>pulls.merge(sha)</code> + live head 复检</td></tr>
<tr><td>冲突锁</td><td>同一 PR 并发改共享 worktree</td><td>进程内 per-PR lock + 失败 hard reset</td></tr>
<tr><td>git/代理/进程</td><td>无超时、输出无限增长</td><td>timeout + 1MB 输出帽 + abort</td></tr>
<tr><td>webhook</td><td>慢客户端/超大包拖死</td><td>30s body、413、顶层 catch</td></tr>
<tr><td>配置</td><td>半套 R2 / webhook 无 secret</td><td>zod superRefine fail-fast</td></tr>
<tr><td>评论命令</td><td>失败被吃掉,Actions 显示成功</td><td>allSettled + AggregateError</td></tr>
</tbody>
</table>
<h2>需求追踪摘要</h2>
<table>
<thead><tr><th>需求</th><th>状态</th><th>证据</th></tr></thead>
<tbody>
<tr><td>生产安全红线(凭据/PR 代码/缓存复用)</td><td class="ok">已闭环(静态+测试)</td><td>sanitization/secrets、snapshot 排除、cache 只作增量上下文</td></tr>
<tr><td>部署一次能跑</td><td class="warn">部分闭环</td><td>文档/env 已对齐;真实 GitHub App 安装未在本机复现</td></tr>
<tr><td>事件失败可见</td><td class="ok">已闭环</td><td>comment AggregateError;webhook 401/413/503</td></tr>
<tr><td>审查结果可信</td><td class="ok">已闭环</td><td>normalizeReviewDecision + 状态横幅</td></tr>
<tr><td>7.1 事件路由器拆分</td><td class="warn">未做(有意)</td><td>无事件环测试床,拆 1700 行 processor 风险高于收益</td></tr>
<tr><td>6.4 全站 i18n</td><td class="warn">未闭环</td><td>仅 chat 按评论语言;审查正文仍英文</td></tr>
<tr><td>付费 LLM E2E</td><td class="warn">外部受限</td><td>未调用真实 Goose/OpenAI</td></tr>
</tbody>
</table>
<h2>验证证据</h2>
<pre>npm run typecheck → 0 errors
npm test → 148/148 pass
npm run lint → 0 errors
npm run format:check → pass
npm audit --omit=dev → 0 vulnerabilities
npm run build → dist loaded
webhook HTTP smoke → see E2E section in repo docs</pre>
<h2>明确没做的</h2>
<ul>
<li>没有把审查编排拆成独立 router(7.1)。</li>
<li>没有把全部评论文案做成中英字典(6.4)。</li>
<li>没有 goose CLI 二进制 checksum 钉死(安装脚本仍从 GitHub 拉指定 tag 的 download_cli.sh)。</li>
<li>没有对 origin <code>lezi-fun/ghbot</code> 推送(账号无权限)。</li>
</ul>
<h2>测验</h2>
<div class="quiz">
<p>提交后显示分数。通过线 80%(8/10)。未提交前不显示答案。</p>
<form id="quiz">
<div class="q">1. AUTO_MERGE 的代码默认值是?</div>
<label><input type="radio" name="q1" value="a"> true</label>
<label><input type="radio" name="q1" value="b"> false</label>
<label><input type="radio" name="q1" value="c"> inherit GitHub</label>
<div class="q">2. 合并时如何防止审查后 head 被替换?</div>
<label><input type="radio" name="q2" value="a"> 只看缓存决策</label>
<label><input type="radio" name="q2" value="b"> pulls.merge 传入审查时的 sha,并 live GET 复检</label>
<label><input type="radio" name="q2" value="c"> force push 回去</label>
<div class="q">3. WEBHOOK_SECRET 应该等于 webhook URL 吗?</div>
<label><input type="radio" name="q3" value="a"> 应该,方便记忆</label>
<label><input type="radio" name="q3" value="b"> 不应该,必须是独立 HMAC 密钥</label>
<div class="q">4. 同一 PR 两个 /conflict 同时跑会怎样?</div>
<label><input type="radio" name="q4" value="a"> 共享 worktree 并行 merge</label>
<label><input type="radio" name="q4" value="b"> 第二个获取锁失败</label>
<div class="q">5. R2 只配了 endpoint 没有密钥时?</div>
<label><input type="radio" name="q5" value="a"> 静默跳过</label>
<label><input type="radio" name="q5" value="b"> 启动/解析配置失败</label>
<div class="q">6. issue_comment 里 /recheck 抛错时?</div>
<label><input type="radio" name="q6" value="a"> 整个 job 仍标成功</label>
<label><input type="radio" name="q6" value="b"> 其他 handler 仍跑,最后 AggregateError 让 Actions 失败可重试</label>
<div class="q">7. 审查 finding 指向 PR 里不存在的文件?</div>
<label><input type="radio" name="q7" value="a"> 原样提交 inline</label>
<label><input type="radio" name="q7" value="b"> normalize 丢掉并记 warning</label>
<div class="q">8. Goose 容器能拿到真实 GOOSE_API_KEY 吗?</div>
<label><input type="radio" name="q8" value="a"> 能,方便调试</label>
<label><input type="radio" name="q8" value="b"> 不能,只用一次性代理 token</label>
<div class="q">9. 本批次是否声称真实付费 LLM 端到端已跑通?</div>
<label><input type="radio" name="q9" value="a"> 是</label>
<label><input type="radio" name="q9" value="b"> 否,外部调用未测</label>
<div class="q">10. origin lezi-fun/ghbot 推送状态?</div>
<label><input type="radio" name="q10" value="a"> 已推送</label>
<label><input type="radio" name="q10" value="b"> 403,改推 lza6/ghbot-Nodeloc</label>
<button type="submit">提交测验</button>
</form>
<div id="score"></div>
</div>
<script>
const answers = {q1:"b",q2:"b",q3:"b",q4:"b",q5:"b",q6:"b",q7:"b",q8:"b",q9:"b",q10:"b"};
document.getElementById("quiz").addEventListener("submit", function (e) {
e.preventDefault();
const form = e.target;
let score = 0;
const total = Object.keys(answers).length;
for (const [name, expected] of Object.entries(answers)) {
const picked = form.querySelector('input[name="'+name+'"]:checked');
if (picked && picked.value === expected) score += 1;
}
const pct = Math.round((score / total) * 100);
const pass = pct >= 80;
document.getElementById("score").textContent = "得分 " + score + "/" + total + "(" + pct + "%)。" + (pass ? "通过。" : "未通过,对照报告再答。");
});
</script>
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "ghbot",
"version": "0.1.0",
"version": "1.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ghbot",
"version": "0.1.0",
"version": "1.1.0",
"dependencies": {
"@aws-sdk/client-s3": "^3.864.0",
"@octokit/auth-app": "^8.2.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ghbot",
"version": "1.0.0",
"version": "1.1.0",
"private": true,
"type": "module",
"engines": {
+17 -2
View File
@@ -1,7 +1,7 @@
import fs from "node:fs";
import { config } from "../config.js";
import { createGitHubCredentials } from "../github/client.js";
import { logger } from "../logger.js";
import { createEventLogger, logger } from "../logger.js";
import { withRetry } from "../retry.js";
import { processPullRequestChat } from "../chat/processor.js";
import { processIssueTriage, processPullRequestTriage } from "../triage/processor.js";
@@ -96,6 +96,12 @@ async function main(): Promise<void> {
}
const pullNumberForCache = getPullNumberForCache(eventName, payload);
const eventLogger = createEventLogger({
eventName,
owner: repository.owner.login,
repo: repository.name,
pullNumber: pullNumberForCache
});
const persistentCache = {
repositoryId: process.env.GHBOT_REPOSITORY_ID || String(repository.id ?? ""),
owner: repository.owner.login,
@@ -131,7 +137,7 @@ async function main(): Promise<void> {
});
const octokit = github.octokit;
logger.info({ eventName }, "Handling GitHub Actions review event.");
eventLogger.info("Handling GitHub Actions review event.");
let eventFailed = false;
try {
@@ -301,6 +307,15 @@ async function main(): Promise<void> {
);
}
});
const rejectedResults = results.filter(
(result): result is PromiseRejectedResult => result.status === "rejected"
);
if (rejectedResults.length > 0) {
throw new AggregateError(
rejectedResults.map((result) => result.reason),
"One or more issue comment handlers failed; GitHub Actions should retry this delivery."
);
}
return;
}
+60 -24
View File
@@ -5,6 +5,9 @@ import { Readable } from "node:stream";
import type { ReadableStream as WebReadableStream } from "node:stream/web";
import { logger } from "../logger.js";
const PROXY_REQUEST_TIMEOUT_MS = 10 * 60 * 1000;
const MAX_PROXY_BODY_BYTES = 20 * 1024 * 1024;
export async function startOneRunApiProxy(
upstreamBaseUrl: string,
realApiKey: string
@@ -14,6 +17,19 @@ export async function startOneRunApiProxy(
const sockets = new Set<Socket>();
const upstreamRequests = new Set<AbortController>();
const server = http.createServer(async (request, response) => {
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
request.destroy(new Error("goose proxy request timed out."));
}, PROXY_REQUEST_TIMEOUT_MS);
const abortOnClose = () => {
if (!response.writableEnded) {
controller.abort();
}
};
request.once("aborted", abortOnClose);
response.once("close", abortOnClose);
try {
if (
request.method !== "POST" ||
@@ -25,40 +41,53 @@ export async function startOneRunApiProxy(
return;
}
const body = await readRequestBody(request, 20 * 1024 * 1024);
const controller = new AbortController();
upstreamRequests.add(controller);
let upstreamResponse: Response;
try {
upstreamResponse = await fetch(upstream, {
method: "POST",
headers: {
authorization: `Bearer ${realApiKey}`,
"content-type": request.headers["content-type"] ?? "application/json",
accept: request.headers.accept ?? "*/*"
},
body: body.toString("utf8"),
signal: controller.signal
});
} finally {
upstreamRequests.delete(controller);
const contentLength = Number(request.headers["content-length"]);
if (Number.isFinite(contentLength) && contentLength > MAX_PROXY_BODY_BYTES) {
response.writeHead(413, { "content-type": "application/json" });
response.end('{"error":{"message":"Request body is too large"}}');
request.destroy();
return;
}
const body = await readRequestBody(request, MAX_PROXY_BODY_BYTES, controller);
upstreamRequests.add(controller);
const upstreamResponse = await fetch(upstream, {
method: "POST",
headers: {
authorization: `Bearer ${realApiKey}`,
"content-type": request.headers["content-type"] ?? "application/json",
accept: request.headers.accept ?? "*/*"
},
body: body.toString("utf8"),
signal: controller.signal
});
response.writeHead(upstreamResponse.status, copyResponseHeaders(upstreamResponse.headers));
if (!upstreamResponse.body) {
response.end();
return;
}
Readable.fromWeb(upstreamResponse.body as WebReadableStream)
.on("error", (error) => response.destroy(error as Error))
.pipe(response);
await new Promise<void>((resolve, reject) => {
const stream = Readable.fromWeb(upstreamResponse.body as WebReadableStream);
stream.once("error", reject);
response.once("finish", resolve);
response.once("close", resolve);
stream.pipe(response);
});
} catch (error) {
logger.error({ error }, "goose API proxy request failed.");
if (!response.headersSent) {
response.writeHead(502, { "content-type": "application/json" });
}
response.end('{"error":{"message":"goose proxy request failed"}}');
if (!response.writableEnded) {
response.end('{"error":{"message":"goose proxy request failed"}}');
}
} finally {
clearTimeout(timeout);
request.off("aborted", abortOnClose);
response.off("close", abortOnClose);
upstreamRequests.delete(controller);
}
});
server.on("connection", (socket) => {
@@ -83,8 +112,8 @@ export async function startOneRunApiProxy(
port: address.port,
token,
close: async () => {
for (const controller of upstreamRequests) {
controller.abort();
for (const requestController of upstreamRequests) {
requestController.abort();
}
for (const socket of sockets) {
socket.destroy();
@@ -103,10 +132,17 @@ function hasMatchingBearerToken(value: string | undefined, expectedToken: string
return supplied.length === expected.length && timingSafeEqual(supplied, expected);
}
async function readRequestBody(request: http.IncomingMessage, maxBytes: number): Promise<Buffer> {
async function readRequestBody(
request: http.IncomingMessage,
maxBytes: number,
controller: AbortController
): Promise<Buffer> {
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of request) {
if (controller.signal.aborted) {
throw new Error("goose proxy request was aborted.");
}
const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
size += value.length;
if (size > maxBytes) {
+106 -22
View File
@@ -8,8 +8,10 @@ import { config } from "../config.js";
import { logger } from "../logger.js";
import { startOneRunApiProxy } from "./apiProxy.js";
import { tempRootDirectory } from "../runtimePaths.js";
import { redactSecrets } from "../security/secrets.js";
const GOOSE_RUN_TIMEOUT_MS = 10 * 60 * 1000;
const MAX_PROCESS_OUTPUT_CHARS = 1_000_000;
const GOOSE_DOCKER_IMAGE = "node:24-bookworm";
const GOOSE_DOCKER_VERSION = "v1.46.0";
const GOOSE_CONTAINER_PATH = "/usr/local/bin/goose";
@@ -21,7 +23,7 @@ const GOOSE_CONTAINER_BOOTSTRAP = [
'mkdir -p "$HOME"',
"git config --global --add safe.directory /workspace",
"if ! command -v goose >/dev/null 2>&1; then",
" curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh -o /tmp/download_cli.sh",
` curl -fsSL https://github.com/aaif-goose/goose/releases/download/${GOOSE_DOCKER_VERSION}/download_cli.sh -o /tmp/download_cli.sh`,
` if ! GOOSE_VERSION="${GOOSE_DOCKER_VERSION}" GOOSE_BIN_DIR=/tmp/goose-bin CONFIGURE=false bash /tmp/download_cli.sh >/tmp/goose-install.log 2>&1; then`,
" cat /tmp/goose-install.log >&2",
" exit 1",
@@ -57,12 +59,12 @@ export async function runGoosePrompt(
throw new Error("GOOSE_API_KEY is required when running a goose prompt.");
}
const tempRoot = tempRootDirectory();
await fs.mkdir(tempRoot, { recursive: true });
const tempDir = await fs.mkdtemp(path.join(tempRoot, "goose-"));
const workingDirectory = options.workingDirectory
? await fs.realpath(options.workingDirectory)
: process.cwd();
const tempRoot = tempRootDirectory();
await fs.mkdir(tempRoot, { recursive: true });
const tempDir = await fs.mkdtemp(path.join(tempRoot, "goose-"));
const args = [
"run",
"--no-session",
@@ -87,6 +89,7 @@ export async function runGoosePrompt(
"Running goose prompt."
);
let primaryError: unknown;
try {
const stdout = await runGoose(
args,
@@ -95,8 +98,11 @@ export async function runGoosePrompt(
options.timeoutMs
);
return extractGooseFinalText(stdout);
} catch (error) {
primaryError = error;
throw error;
} finally {
await fs.rm(tempDir, { recursive: true, force: true });
await removeDirectoryBestEffort(tempDir, "goose prompt temp directory", primaryError);
}
}
@@ -128,6 +134,7 @@ export async function runGooseAgent(
prompt
});
let primaryError: unknown;
try {
const stdout = await runProcess(
"docker",
@@ -138,16 +145,21 @@ export async function runGooseAgent(
options.timeoutMs
);
return extractGooseFinalText(stdout);
} catch (error) {
primaryError = error;
throw error;
} finally {
try {
await removeDockerContainer(containerName, realWorkingDirectory);
} finally {
try {
await restoreAgentWorkspacePermissions(realWorkingDirectory);
} finally {
await proxy.close();
}
}
await removeDockerContainer(containerName, realWorkingDirectory);
await restoreAgentWorkspacePermissions(realWorkingDirectory).catch((error: unknown) => {
logger.warn(
{ error, workingDirectory: realWorkingDirectory },
"Agent workspace cleanup failed."
);
});
await proxy.close().catch((error: unknown) => {
logger.warn({ error }, "One-run Goose API proxy cleanup failed.");
});
void primaryError;
}
}
@@ -442,6 +454,15 @@ async function runProcess(
let stdout = "";
let stderr = "";
let finished = false;
let outputOverflowed = false;
const appendOutput = (current: string, chunk: string): string => {
const next = current + chunk;
if (next.length <= MAX_PROCESS_OUTPUT_CHARS) {
return next;
}
outputOverflowed = true;
return next.slice(-MAX_PROCESS_OUTPUT_CHARS);
};
const timeout = setTimeout(() => {
if (finished) {
return;
@@ -451,17 +472,48 @@ async function runProcess(
child.kill("SIGTERM");
setTimeout(() => child.kill("SIGKILL"), 5_000).unref();
reject(
Object.assign(new Error(`${label} timed out after ${timeoutMs}ms.`), { stdout, stderr })
Object.assign(new Error(`${label} timed out after ${timeoutMs}ms.`), {
stdout,
stderr
})
);
}, timeoutMs);
child.stdout.on("data", (chunk: Buffer | string) => {
stdout += chunk.toString();
stdout = appendOutput(stdout, chunk.toString());
if (outputOverflowed && !finished) {
finished = true;
clearTimeout(timeout);
child.kill("SIGTERM");
reject(
Object.assign(
new Error(`${label} exceeded the ${MAX_PROCESS_OUTPUT_CHARS}-character output limit.`),
{
stdout,
stderr
}
)
);
}
});
child.stderr.on("data", (chunk: Buffer | string) => {
const text = chunk.toString();
stderr += text;
streamStderr(text, label);
stderr = appendOutput(stderr, text);
streamStderr(text.slice(-MAX_PROCESS_OUTPUT_CHARS), label);
if (outputOverflowed && !finished) {
finished = true;
clearTimeout(timeout);
child.kill("SIGTERM");
reject(
Object.assign(
new Error(`${label} exceeded the ${MAX_PROCESS_OUTPUT_CHARS}-character output limit.`),
{
stdout,
stderr
}
)
);
}
});
child.on("error", (error) => {
if (finished) {
@@ -513,11 +565,42 @@ async function removeDockerContainer(
env: buildChildEnv({}),
stdio: "ignore"
});
child.on("error", () => resolve());
child.on("close", () => resolve());
const timeout = setTimeout(() => {
child.kill("SIGKILL");
logger.warn({ containerName }, "Docker container cleanup timed out; continuing.");
resolve();
}, 10_000);
child.on("error", (error) => {
clearTimeout(timeout);
logger.warn({ error, containerName }, "Docker container cleanup failed; continuing.");
resolve();
});
child.on("close", () => {
clearTimeout(timeout);
resolve();
});
});
}
async function removeDirectoryBestEffort(
directory: string,
label: string,
primaryError: unknown
): Promise<void> {
try {
await fs.rm(directory, { recursive: true, force: true });
} catch (error) {
logger.warn(
{
error,
directory,
primaryError: primaryError instanceof Error ? primaryError.message : undefined
},
`${label} cleanup failed; preserving the primary operation result.`
);
}
}
function buildChildEnv(extraEnv: Record<string, string>): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {};
for (const key of [
@@ -634,9 +717,10 @@ export function redactProcessArgs(
}
function streamStderr(text: string, label: string): void {
for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
const redacted = redactSecrets(text);
for (const line of redacted.replace(/\r\n/g, "\n").split("\n")) {
if (line.trim()) {
process.stderr.write(`[${label} stderr] ${line}\n`);
logger.warn({ label }, `[${label} stderr] ${line}`);
}
}
}
+93 -65
View File
@@ -39,76 +39,103 @@ function csvListWithDefault(defaultValue: string[]) {
}, z.array(z.string()));
}
const configSchema = z.object({
port: z.coerce.number().int().positive().default(3000),
githubToken: optionalString,
githubAppId: optionalString,
githubAppPrivateKey: optionalString,
githubAppInstallationId: z.preprocess((value) => {
if (value === "" || value === undefined) {
return undefined;
}
return value;
}, z.coerce.number().int().positive().optional()),
webhookEnabled: envBoolean.default(false),
webhookSecret: optionalString,
webhookPath: z.string().startsWith("/").default("/webhooks/github"),
webhookChatPermission: z.enum(["anyone", "read", "write"]).default("read"),
webhookQueueConcurrency: z.coerce.number().int().positive().max(20).default(2),
webhookQueueLimit: z.coerce.number().int().positive().max(10_000).default(500),
gooseModel: optionalString.default("gpt-5.4"),
gooseThinkingEffort: z.preprocess(
(value) => {
const configSchema = z
.object({
port: z.coerce.number().int().positive().default(3000),
githubToken: optionalString,
githubAppId: optionalString,
githubAppPrivateKey: optionalString,
githubAppInstallationId: z.preprocess((value) => {
if (value === "" || value === undefined) {
return undefined;
}
if (value === "minimal") {
return "low";
}
if (value === "xhigh") {
return "max";
}
return value;
},
z.enum(["off", "low", "medium", "high", "max"]).optional()
),
gooseBaseUrl: optionalString,
gooseApiKey: optionalString,
reviewPolicy: z.enum(["allow", "require_approval", "reject"]).default("allow"),
reviewStrictness: z.enum(["normal", "strict"]).default("normal"),
reviewInstructions: optionalString,
reviewBranches: csvListWithDefault([]),
repositoryKnowledgeEnabled: envBoolean.default(true),
repositoryKnowledgeWrite: envBoolean.default(false),
r2Endpoint: optionalString,
r2BucketName: optionalString,
r2Prefix: optionalString,
r2AccessKeyId: optionalString,
r2SecretAccessKey: optionalString,
triageEnabled: envBoolean.default(true),
triageLabels: csvListWithDefault([
"bug",
"enhancement",
"documentation",
"question",
"maintenance"
]).refine((labels) => labels.length > 0, "TRIAGE_LABELS must contain at least one label."),
triageDuplicateLabel: z.string().min(1).default("duplicate"),
triageCandidateLimit: z.coerce.number().int().positive().max(100).default(50),
triageInstructions: optionalString,
botName: z.string().min(1).default("ghbot"),
autoMerge: envBoolean.default(false),
autoResolveConflicts: envBoolean.default(false),
conflictTestCommand: optionalString,
mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"),
requireChecks: envBoolean.default(true),
maxPatchChars: z.coerce.number().int().positive().default(120_000),
logLevel: z.string().min(1).default("info")
});
}, z.coerce.number().int().positive().optional()),
webhookEnabled: envBoolean.default(false),
webhookSecret: optionalString,
webhookPath: z.string().startsWith("/").default("/webhooks/github"),
webhookChatPermission: z.enum(["anyone", "read", "write"]).default("read"),
webhookQueueConcurrency: z.coerce.number().int().positive().max(20).default(2),
webhookQueueLimit: z.coerce.number().int().positive().max(10_000).default(500),
runtimeDirectory: optionalString,
gooseModel: optionalString.default("gpt-5.4"),
gooseThinkingEffort: z.preprocess(
(value) => {
if (value === "" || value === undefined) {
return undefined;
}
if (value === "minimal") {
return "low";
}
if (value === "xhigh") {
return "max";
}
return value;
},
z.enum(["off", "low", "medium", "high", "max"]).optional()
),
gooseBaseUrl: optionalString.default("https://api.openai.com/v1"),
gooseApiKey: optionalString,
reviewPolicy: z.enum(["allow", "require_approval", "reject"]).default("allow"),
reviewStrictness: z.enum(["normal", "strict"]).default("normal"),
reviewInstructions: optionalString,
reviewBranches: csvListWithDefault([]),
repositoryKnowledgeEnabled: envBoolean.default(true),
repositoryKnowledgeWrite: envBoolean.default(false),
r2Endpoint: optionalString,
r2BucketName: optionalString,
r2Prefix: optionalString,
r2AccessKeyId: optionalString,
r2SecretAccessKey: optionalString,
triageEnabled: envBoolean.default(true),
triageLabels: csvListWithDefault([
"bug",
"enhancement",
"documentation",
"question",
"maintenance"
]).refine((labels) => labels.length > 0, "TRIAGE_LABELS must contain at least one label."),
triageDuplicateLabel: z.string().min(1).default("duplicate"),
triageCandidateLimit: z.coerce.number().int().positive().max(100).default(50),
triageInstructions: optionalString,
botName: z.string().min(1).default("ghbot"),
autoMerge: envBoolean.default(false),
autoResolveConflicts: envBoolean.default(false),
conflictTestCommand: optionalString,
mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"),
requireChecks: envBoolean.default(true),
maxPatchChars: z.coerce.number().int().positive().default(120_000),
logLevel: z.string().min(1).default("info")
})
.superRefine((value, ctx) => {
if (value.webhookEnabled && !value.webhookSecret) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["webhookSecret"],
message: "WEBHOOK_SECRET is required when WEBHOOK_ENABLED=true."
});
}
const r2Values = [
value.r2Endpoint,
value.r2BucketName,
value.r2AccessKeyId,
value.r2SecretAccessKey
];
const configuredR2Values = r2Values.filter(Boolean).length;
if (configuredR2Values > 0 && configuredR2Values < r2Values.length) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["r2Endpoint"],
message:
"R2_ENDPOINT, R2_BUCKET_NAME, R2_ACCESS_KEY_ID, and R2_SECRET_ACCESS_KEY must be configured together."
});
}
});
export const config = configSchema.parse({
port: process.env.PORT,
@@ -123,6 +150,7 @@ export const config = configSchema.parse({
webhookChatPermission: process.env.WEBHOOK_CHAT_PERMISSION,
webhookQueueConcurrency: process.env.WEBHOOK_QUEUE_CONCURRENCY,
webhookQueueLimit: process.env.WEBHOOK_QUEUE_LIMIT,
runtimeDirectory: process.env.GHBOT_RUNTIME_DIR,
gooseModel: process.env.GOOSE_MODEL ?? process.env.OPENCODE_MODEL,
gooseThinkingEffort: process.env.GOOSE_THINKING_EFFORT ?? process.env.OPENCODE_REASONING_EFFORT,
gooseBaseUrl: process.env.GOOSE_BASE_URL ?? process.env.OPENCODE_BASE_URL,
+39 -1
View File
@@ -4,7 +4,45 @@ import { config } from "./config.js";
export const logger = pino({
level: config.logLevel,
redact: {
paths: ["gitToken", "*.gitToken", "GHBOT_GIT_TOKEN", "*.GHBOT_GIT_TOKEN"],
paths: [
"gitToken",
"*.gitToken",
"GHBOT_GIT_TOKEN",
"*.GHBOT_GIT_TOKEN",
"gooseApiKey",
"*.gooseApiKey",
"authorization",
"*.authorization",
"WEBHOOK_SECRET",
"*.WEBHOOK_SECRET",
"R2_SECRET_ACCESS_KEY",
"*.R2_SECRET_ACCESS_KEY",
"githubToken",
"*.githubToken",
"GITHUB_TOKEN",
"*.GITHUB_TOKEN",
"GOOSE_API_KEY",
"*.GOOSE_API_KEY",
"OPENAI_API_KEY",
"*.OPENAI_API_KEY",
"webhookSecret",
"*.webhookSecret",
"r2SecretAccessKey",
"*.r2SecretAccessKey",
"err.stderr",
"error.stderr",
"*.stderr"
],
censor: "[REDACTED]"
}
});
export function createEventLogger(bindings: {
eventName: string;
owner?: string;
repo?: string;
pullNumber?: number;
issueNumber?: number;
}) {
return logger.child(bindings);
}
+85 -18
View File
@@ -42,6 +42,8 @@ const CONFLICT_VALIDATION_REPAIR_AGENT_TIMEOUT_MS = 10 * 60 * 1000;
const CONFLICT_VALIDATION_TIMEOUT_MS = 7 * 60 * 1000;
const CONFLICT_CONFIRMATION_TIMEOUT_MS = 5 * 60 * 1000;
const VALIDATION_LOG_OUTPUT_LIMIT = 12_000;
const GIT_COMMAND_TIMEOUT_MS = 2 * 60 * 1000;
const activeConflictLocks = new Set<string>();
type SnapshotFile = {
hash: string;
@@ -66,6 +68,16 @@ export function canAutoResolveConflicts(input: ConflictResolutionEligibility): b
);
}
export async function acquireConflictLock(key: string): Promise<() => void> {
if (activeConflictLocks.has(key)) {
throw new Error("Another conflict-resolution run is already active for this pull request.");
}
activeConflictLocks.add(key);
return () => {
activeConflictLocks.delete(key);
};
}
export async function resolvePullRequestConflicts(
octokit: Octokit,
params: {
@@ -101,15 +113,28 @@ export async function resolvePullRequestConflicts(
}
const worktree = await fs.realpath(params.worktree);
const releaseConflictLock = await acquireConflictLock(`${baseRepository}#${params.pullNumber}`);
const tempRoot = tempRootDirectory();
await fs.mkdir(tempRoot, { recursive: true });
const askPassDirectory = await fs.mkdtemp(path.join(tempRoot, "git-auth-"));
let askPassDirectory: string;
try {
await fs.mkdir(tempRoot, { recursive: true });
askPassDirectory = await fs.mkdtemp(path.join(tempRoot, "git-auth-"));
} catch (error) {
releaseConflictLock();
throw error;
}
const askPassPath = path.join(askPassDirectory, "askpass.sh");
await fs.writeFile(
askPassPath,
'#!/bin/sh\ncase "$1" in *Username*) printf "%s\\n" "x-access-token" ;; *) printf "%s\\n" "$GHBOT_GIT_TOKEN" ;; esac\n',
{ mode: 0o700 }
);
try {
await fs.writeFile(
askPassPath,
'#!/bin/sh\ncase "$1" in *Username*) printf "%s\\n" "x-access-token" ;; *) printf "%s\\n" "$GHBOT_GIT_TOKEN" ;; esac\n',
{ mode: 0o700 }
);
} catch (error) {
await fs.rm(askPassDirectory, { recursive: true, force: true }).catch(() => undefined);
releaseConflictLock();
throw error;
}
const gitEnv = {
GIT_ASKPASS: askPassPath,
GIT_TERMINAL_PROMPT: "0",
@@ -467,13 +492,21 @@ export async function resolvePullRequestConflicts(
);
return true;
} catch (error) {
await runCommand("git", ["reset", "--hard", params.expectedHeadSha], worktree, gitEnv).catch(
() => undefined
);
await runCommand("git", ["merge", "--abort"], worktree, gitEnv).catch(() => undefined);
throw error;
} finally {
if (snapshot) {
await fs.rm(snapshot, { recursive: true, force: true });
await fs.rm(snapshot, { recursive: true, force: true }).catch((error: unknown) => {
logger.warn({ error, snapshot }, "Conflict snapshot cleanup failed; continuing.");
});
}
await fs.rm(askPassDirectory, { recursive: true, force: true });
await fs.rm(askPassDirectory, { recursive: true, force: true }).catch((error: unknown) => {
logger.warn({ error, askPassDirectory }, "Git askpass cleanup failed; continuing.");
});
releaseConflictLock();
}
}
@@ -1014,13 +1047,11 @@ function commandFailureOutput(result: { stdout: string; stderr: string }): strin
return redactSecrets(raw);
}
function formatValidationResult(
export function formatValidationResult(
command: string,
result: { code: number; stdout: string; stderr: string }
): string {
const output =
[result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n").slice(0, 20_000) ||
"no output";
const output = commandFailureOutput(result);
return [`Command: ${command}`, `Exit code: ${result.code}`, "Output:", output].join("\n");
}
@@ -1128,7 +1159,8 @@ async function runCommandAllowFailure(
command: string,
args: string[],
cwd: string,
extraEnv: Record<string, string>
extraEnv: Record<string, string>,
timeoutMs = GIT_COMMAND_TIMEOUT_MS
): Promise<{ code: number; stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
@@ -1138,17 +1170,52 @@ async function runCommandAllowFailure(
});
let stdout = "";
let stderr = "";
let settled = false;
const timeout = setTimeout(() => {
if (settled) {
return;
}
settled = true;
child.kill("SIGTERM");
setTimeout(() => child.kill("SIGKILL"), 5_000).unref();
reject(
Object.assign(new Error(`${command} timed out after ${timeoutMs}ms.`), {
stdout,
stderr,
code: null
})
);
}, timeoutMs);
child.stdout.on("data", (chunk: Buffer | string) => {
stdout += chunk.toString();
stdout = appendBoundedOutput(stdout, chunk.toString());
});
child.stderr.on("data", (chunk: Buffer | string) => {
stderr += chunk.toString();
stderr = appendBoundedOutput(stderr, chunk.toString());
});
child.on("error", (error) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timeout);
reject(error);
});
child.on("close", (code) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timeout);
resolve({ code: code ?? 1, stdout, stderr });
});
child.on("error", reject);
child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
});
}
function appendBoundedOutput(current: string, chunk: string): string {
const next = current + chunk;
return next.length <= 1_000_000 ? next : next.slice(-1_000_000);
}
function buildCommandEnvironment(extraEnv: Record<string, string>): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {};
for (const key of [
+21 -2
View File
@@ -864,6 +864,19 @@ async function maybeMergePullRequest(
);
return;
}
if (livePullRequest.head.sha !== params.headSha) {
logger.info(
{
owner,
repo,
pullNumber,
reviewedHead: params.headSha,
currentHead: livePullRequest.head.sha
},
"Skipping merge because the pull request head changed after review."
);
return;
}
if (params.requireAdminApproval) {
const approvedByEligibleReviewer = await hasCurrentHeadApprovalFrom(octokit, {
@@ -893,8 +906,7 @@ async function maybeMergePullRequest(
}
}
const mergeablePullRequest =
params.mergeablePullRequest ?? (await waitForMergeable(octokit, owner, repo, pullNumber));
const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber);
if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") {
if (params.emitStatusComments) {
await withRetry("github.issues.createComment.notMergeable", async () => {
@@ -936,6 +948,7 @@ async function maybeMergePullRequest(
owner,
repo,
pull_number: pullNumber,
sha: params.headSha,
merge_method: config.mergeMethod,
commit_title: `${params.title} (#${pullNumber})`
});
@@ -996,6 +1009,7 @@ async function hasCurrentHeadApprovalFrom(
params.headSha
);
let lastLookupError: unknown;
for (const login of approvedLogins) {
try {
const { data: permission } = await octokit.rest.repos
@@ -1027,6 +1041,7 @@ async function hasCurrentHeadApprovalFrom(
return true;
}
} catch (error) {
lastLookupError = error;
logger.warn(
{
error,
@@ -1040,6 +1055,10 @@ async function hasCurrentHeadApprovalFrom(
}
}
if (lastLookupError) {
throw lastLookupError;
}
return false;
}
+3 -2
View File
@@ -1,5 +1,6 @@
import path from "node:path";
import process from "node:process";
import { config } from "./config.js";
/**
* Runtime scratch/cache directories live under one configurable root so
@@ -7,8 +8,8 @@ import process from "node:process";
* them without code changes. Defaults to the process working directory.
*/
export function runtimeDirectory(): string {
const configured = process.env.GHBOT_RUNTIME_DIR?.trim();
return configured ? configured : process.cwd();
const environmentValue = process.env.GHBOT_RUNTIME_DIR?.trim();
return environmentValue || config.runtimeDirectory || process.cwd();
}
export function tempRootDirectory(): string {
+101 -68
View File
@@ -8,6 +8,7 @@ import { parseWebhookMentionEvent, processWebhookMention } from "./processor.js"
import { MetricsRegistry } from "./metrics.js";
const MAX_WEBHOOK_BODY_BYTES = 2 * 1024 * 1024;
const WEBHOOK_BODY_TIMEOUT_MS = 30_000;
const DELIVERY_RETENTION_MS = 24 * 60 * 60 * 1000;
const MAX_TASK_ATTEMPTS = 2;
@@ -60,78 +61,99 @@ export function createWebhookServer(
options.handleDelivery ?? createDefaultDeliveryHandler(options.botName ?? config.botName);
return http.createServer(async (request, response) => {
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
if (request.method === "GET" && pathname === "/healthz") {
writeJson(response, 200, { ok: true, webhook: true });
return;
}
if (request.method === "GET" && pathname === "/metrics") {
response.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8" });
response.end(metrics.snapshotPrometheus());
return;
}
if (request.method !== "POST" || pathname !== webhookPath) {
response.setHeader("allow", "GET, POST");
writeJson(response, 404, { error: "Not found." });
return;
}
const deliveryId = singleHeader(request.headers["x-github-delivery"]);
const eventName = singleHeader(request.headers["x-github-event"]);
const signature = singleHeader(request.headers["x-hub-signature-256"]);
if (!deliveryId || !eventName || !signature) {
metrics.inc("webhook_requests_total", { result: "missing_headers" });
writeJson(response, 400, { error: "Missing GitHub webhook headers." });
return;
}
let body: Buffer;
try {
body = await readRawBody(request, maxBodyBytes);
} catch (error) {
logger.warn(
{ error, deliveryId, eventName },
"Rejected oversized or unreadable GitHub webhook body."
);
metrics.inc("webhook_requests_total", { result: "too_large" });
writeJson(response, 413, { error: "Webhook payload is too large." });
return;
}
if (!verifyGitHubWebhookSignature(body, signature, options.secret)) {
metrics.inc("webhook_requests_total", { result: "bad_signature" });
writeJson(response, 401, { error: "Invalid webhook signature." });
return;
}
let payload: unknown;
try {
payload = JSON.parse(body.toString("utf8"));
} catch {
writeJson(response, 400, { error: "Webhook payload is not valid JSON." });
return;
}
try {
const accepted = queue.enqueue(deliveryId, () =>
handleDelivery(eventName, payload, deliveryId)
);
if (!accepted) {
metrics.inc("webhook_deliveries_total", { result: "duplicate" });
writeJson(response, 202, { ok: true, duplicate: true });
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
if (request.method === "GET" && pathname === "/healthz") {
writeJson(response, 200, { ok: true, webhook: true });
return;
}
if (request.method === "GET" && pathname === "/metrics") {
response.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8" });
response.end(metrics.snapshotPrometheus());
return;
}
if (request.method !== "POST" || pathname !== webhookPath) {
response.setHeader("allow", "GET, POST");
writeJson(response, 404, { error: "Not found." });
return;
}
metrics.inc("webhook_deliveries_total", { event: eventName, result: "accepted" });
} catch (error) {
logger.warn(
{ error, deliveryId, eventName },
"Webhook queue is full; asking GitHub to retry."
);
metrics.inc("webhook_deliveries_total", { result: "queue_full" });
writeJson(response, 503, { error: "Webhook queue is temporarily full." });
return;
}
writeJson(response, 202, { ok: true });
const deliveryId = singleHeader(request.headers["x-github-delivery"]);
const eventName = singleHeader(request.headers["x-github-event"]);
const signature = singleHeader(request.headers["x-hub-signature-256"]);
if (!deliveryId || !eventName || !signature) {
metrics.inc("webhook_requests_total", { result: "missing_headers" });
writeJson(response, 400, { error: "Missing GitHub webhook headers." });
return;
}
let body: Buffer;
const declaredLength = Number(request.headers["content-length"]);
if (Number.isFinite(declaredLength) && declaredLength > maxBodyBytes) {
metrics.inc("webhook_requests_total", { result: "too_large" });
writeJson(response, 413, { error: "Webhook payload is too large." });
request.destroy();
return;
}
const bodyTimeout = setTimeout(() => {
request.destroy(new Error("Webhook body read timed out."));
}, WEBHOOK_BODY_TIMEOUT_MS);
try {
body = await readRawBody(request, maxBodyBytes);
} catch (error) {
clearTimeout(bodyTimeout);
logger.warn(
{ error, deliveryId, eventName },
"Rejected oversized or unreadable GitHub webhook body."
);
metrics.inc("webhook_requests_total", { result: "too_large" });
writeJson(response, 413, { error: "Webhook payload is too large." });
return;
}
clearTimeout(bodyTimeout);
if (!verifyGitHubWebhookSignature(body, signature, options.secret)) {
metrics.inc("webhook_requests_total", { result: "bad_signature" });
writeJson(response, 401, { error: "Invalid webhook signature." });
return;
}
let payload: unknown;
try {
payload = JSON.parse(body.toString("utf8"));
} catch {
writeJson(response, 400, { error: "Webhook payload is not valid JSON." });
return;
}
try {
const accepted = queue.enqueue(deliveryId, () =>
handleDelivery(eventName, payload, deliveryId)
);
if (!accepted) {
metrics.inc("webhook_deliveries_total", { result: "duplicate" });
writeJson(response, 202, { ok: true, duplicate: true });
return;
}
metrics.inc("webhook_deliveries_total", { event: eventName, result: "accepted" });
} catch (error) {
logger.warn(
{ error, deliveryId, eventName },
"Webhook queue is full; asking GitHub to retry."
);
metrics.inc("webhook_deliveries_total", { result: "queue_full" });
writeJson(response, 503, { error: "Webhook queue is temporarily full." });
return;
}
writeJson(response, 202, { ok: true });
} catch (error: unknown) {
logger.error({ error }, "Webhook request handler failed.");
if (!response.headersSent) {
writeJson(response, 500, { error: "Webhook request failed." });
} else {
response.destroy(error instanceof Error ? error : undefined);
}
}
});
}
@@ -147,6 +169,9 @@ export async function startWebhookServer(): Promise<http.Server> {
if (!config.githubAppId || !config.githubAppPrivateKey) {
throw new Error("GH_APP_ID and GH_APP_PRIVATE_KEY are required when WEBHOOK_ENABLED=true.");
}
if (!config.gooseApiKey) {
throw new Error("GOOSE_API_KEY is required when WEBHOOK_ENABLED=true.");
}
const server = createWebhookServer({
secret: config.webhookSecret,
@@ -165,6 +190,14 @@ export async function startWebhookServer(): Promise<http.Server> {
{ port: config.port, path: config.webhookPath },
"GitHub webhook server is listening."
);
const shutdown = () => {
logger.info("Shutting down GitHub webhook server.");
server.close();
};
process.once("SIGTERM", shutdown);
process.once("SIGINT", shutdown);
return server;
}
+46
View File
@@ -0,0 +1,46 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import path from "node:path";
import test from "node:test";
function loadConfigWith(overrides: Record<string, string | undefined>) {
const env = { ...process.env };
for (const [key, value] of Object.entries(overrides)) {
if (value === undefined) {
delete env[key];
} else {
env[key] = value;
}
}
return spawnSync(process.execPath, ["--import", "tsx", "--eval", "import('./src/config.ts')"], {
cwd: path.resolve(process.cwd()),
env,
encoding: "utf8"
});
}
test("config rejects enabled webhook without a secret", () => {
const result = loadConfigWith({ WEBHOOK_ENABLED: "true", WEBHOOK_SECRET: "" });
assert.notEqual(result.status, 0);
assert.match(`${result.stdout}${result.stderr}`, /WEBHOOK_SECRET/);
});
test("config rejects partially configured R2 settings", () => {
const result = loadConfigWith({
WEBHOOK_ENABLED: "false",
R2_ENDPOINT: "https://example.r2.cloudflarestorage.com",
R2_BUCKET_NAME: "bucket",
R2_ACCESS_KEY_ID: "",
R2_SECRET_ACCESS_KEY: ""
});
assert.notEqual(result.status, 0);
assert.match(`${result.stdout}${result.stderr}`, /R2_ENDPOINT/);
});
test("config defaults the provider base URL explicitly", () => {
const result = loadConfigWith({
WEBHOOK_ENABLED: "false",
GOOSE_BASE_URL: ""
});
assert.equal(result.status, 0, result.stderr);
});
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
import { acquireConflictLock } from "../src/review/conflictResolver.js";
test("conflict lock rejects overlapping runs for the same pull request", async () => {
const release = await acquireConflictLock("acme/demo#7");
await assert.rejects(() => acquireConflictLock("acme/demo#7"), /already active/);
release();
const releaseAgain = await acquireConflictLock("acme/demo#7");
releaseAgain();
});
test("conflict lock allows concurrent runs for different pull requests", async () => {
const first = await acquireConflictLock("acme/demo#8");
const second = await acquireConflictLock("acme/demo#9");
first();
second();
});
+12 -7
View File
@@ -1,7 +1,9 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatValidationLogOutput } from "../src/review/conflictResolver.js";
import { redactSecrets } from "../src/security/secrets.js";
import {
formatValidationLogOutput,
formatValidationResult
} from "../src/review/conflictResolver.js";
test("validation log output keeps the useful tail within bounds", () => {
const longOutput = "x".repeat(30_000) + "\nfinal error line";
@@ -16,9 +18,12 @@ test("validation log output strips ANSI escapes and normalizes newlines", () =>
assert.equal(formatted, "error\nline2");
});
test("redaction is applied to command failure text before exposure", () => {
// The conflict resolver wraps commandFailureOutput with redactSecrets; this
// asserts the composition contract at the module boundary.
const leaked = "push failed: https://user:ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ123456@github.com/x";
assert.equal(redactSecrets(leaked).includes("ghp_"), false);
test("validation result redacts credentials before prompt or log exposure", () => {
const formatted = formatValidationResult("npm test", {
code: 1,
stdout: "",
stderr: "fatal: https://user:ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ123456@github.com/x"
});
assert.equal(formatted.includes("ghp_"), false);
assert.match(formatted, /REDACTED|Exit code: 1/);
});
+14
View File
@@ -0,0 +1,14 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createEventLogger } from "../src/logger.js";
test("event logger child bindings include owner/repo/eventName", () => {
const child = createEventLogger({
eventName: "issue_comment",
owner: "acme",
repo: "demo",
pullNumber: 7
});
assert.equal(typeof child.info, "function");
assert.equal(typeof child.error, "function");
});
+44
View File
@@ -0,0 +1,44 @@
# workflow_status.md — 终局闭环总审计
**任务**: 001-production-hardening
**更新**: 2026-08-23
## 节点
| # | 任务 | 状态 | 证据 |
|---|------|------|------|
| N1 | 需求追踪矩阵 | done | `.specify/specs/001-production-hardening/spec.md` |
| N2-N5 | 契约/安全/错误/文档审计 | done | 四路扫描 + 主线程复核 |
| N6 | 问题分级 | done | 本文件 P0/P1 列表 |
| N7 | 修复 | done | 工作区生产硬化改动 + 148 tests |
| N8 | 门禁+E2E | done | typecheck/lint/format/test/audit/build;webhook :3011 HTTP 冒烟 |
| N9 | 独立审查 | in_progress | 后台 critic/explorer;Artifact 发布因 ANTHROPIC_AUTH_TOKEN 不可用 |
| N10 | 修复循环 | pending | 等 critic 阻塞项 |
| N11 | 文档 | done | README 双语、.env.example、HTML 报告本地文件 |
| N12 | Skill | done | `.claude/skills/ghbot-production-hardening/SKILL.md` |
## 已修 P0/P1
- 合并 live SHA + `pulls.merge(sha)`
- 冲突 per-PR lock、git timeout、失败 hard reset
- webhook body 30s/413/顶层 catch
- API proxy abort/timeout/20MB cap
- goose 输出 1MB cap、cleanup timeout
- 配置 webhook secret / 半套 R2 fail-fast
- issue_comment AggregateError
- 审批权限查找不再吞掉非 404
- GHBOT_RUNTIME_DIR 契约打通 workflow/env/docs
## 有意未做
- 7.1 processor 路由器拆分(无事件环测试床)
- 6.4 全站 i18n
- goose 安装脚本 checksum(仅改到版本 tag URL)
- origin `lezi-fun/ghbot` 推送(403)
## E2E(2026-08-23,PORT=3011)
```
GET /healthz → 200 {"ok":true,"webhook":true}
POST 合法 HMAC → 202 {"ok":true}
POST 坏签名 → 401
POST 重复 delivery → 202 duplicate
GET /metrics → accepted=1 bad_signature=1 duplicate=1
```
+5
View File
@@ -27,3 +27,8 @@ ghbot_webhook_deliveries_total{result="duplicate"} 1
## 结论
webhook 服务从启动 → 鉴权 → 去重 → 可观测性的完整链路在真实 HTTP 层验证通过。
## 回归(2026-08-23,PORT=3011,生产 dist)
同一矩阵在硬化改动后复测:healthz 200、合法 HMAC 202、坏签名 401、重复 delivery duplicate、metrics 三项计数正确。