From a6e3fd2fc5d753796ca3a22535646755e34164ac Mon Sep 17 00:00:00 2001 From: lezi-fun <177434121+lezi-fun@users.noreply.github.com> Date: Sat, 22 Aug 2026 11:36:46 +0800 Subject: [PATCH] feat: bring webhook mode closer to action mode Webhook deliveries now run the same issue and PR triage as action mode on open/edit/reopen events, gated by WEBHOOK_TRIAGE_ENABLED; @bot answers embed the host-curated repository knowledge cache from R2 (never the uninitialized scaffold); exact /recheck and /conflict commands get a guidance reply pointing to action mode instead of silence. Cache restores write through a temporary file and rename so concurrent webhook work never reads a partial object. Documents that all webhook local writes stay inside the current working directory. --- .env.example | 4 + .gitignore | 1 + README-zh.md | 6 +- README.md | 6 +- src/config.ts | 2 + src/repository/knowledge.ts | 9 ++ src/storage/cacheStore.ts | 7 +- src/webhook/processor.ts | 169 +++++++++++++++++++++++++++++++++++- src/webhook/server.ts | 26 +++++- test/webhook-parity.test.ts | 119 +++++++++++++++++++++++++ 10 files changed, 336 insertions(+), 13 deletions(-) create mode 100644 test/webhook-parity.test.ts diff --git a/.env.example b/.env.example index 2cc4680..7b38cb3 100644 --- a/.env.example +++ b/.env.example @@ -17,6 +17,8 @@ WEBHOOK_PATH=/webhooks/github WEBHOOK_CHAT_PERMISSION=read WEBHOOK_QUEUE_CONCURRENCY=2 WEBHOOK_QUEUE_LIMIT=500 +# Automatic issue/PR triage (labels + duplicate detection) in webhook mode. +WEBHOOK_TRIAGE_ENABLED=true # GitHub App login or slug used in @mentions, e.g. forumlify[bot]. BOT_NAME=ghbot @@ -25,6 +27,8 @@ GOOSE_API_KEY=sk-... GOOSE_BASE_URL=https://api.openai.com/v1 GOOSE_MODEL=gpt-5.4 GOOSE_THINKING_EFFORT=high +# Optional: the pinned goose CLI version, shown in the runtime environment block. +# GOOSE_VERSION=v1.46.0 # allow | require_approval | reject. Ordinary review notes pass by default. REVIEW_POLICY=allow diff --git a/.gitignore b/.gitignore index d326775..a617c6d 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ pnpm-debug.log* .ghbot-tmp/ .ghbot-cache/ .ghbot-knowledge/ +.playwright-cli/ diff --git a/README-zh.md b/README-zh.md index a4b6284..06adaf0 100644 --- a/README-zh.md +++ b/README-zh.md @@ -46,7 +46,7 @@ goose 的审核结果固定包含四个顶层字段: 新 commit 触发 `synchronize` 后,workflow 会恢复该 PR 最新的缓存。goose 同时收到旧审核结果和当前完整 PR diff,重新验证所有旧问题、移除已经修复的问题,并检查新 commit 引入的回归。旧的合并结论不会在没有新审核的情况下直接复用。 -每次 `synchronize` 都会先发布一条绑定当前 commit 的“开始审核”进度评论;审核完成、失败,或因为 PR 再次变化而过期时,会更新同一条评论。新审核成功发布后,ghbot 会把旧机器人审核中的逐行 `review` 和 `change` 线程标记为 resolved,并把这些已解决评论折叠隐藏,dismiss 仍然生效的旧审核结论,并把旧审核正文压缩为 superseded 占位说明。如果 GitHub 无法通过 GraphQL 暴露某个旧线程,ghbot 才会删除这条无法映射的逐行评论作为降级处理。GitHub 不允许删除已经提交的 review 记录本身,因此最终只有最新审核保留完整正文和有效状态。 +每次 `synchronize` 都会先发布一条绑定当前 commit 的“开始审核”进度评论;审核完成、失败,或因为 PR 再次变化而过期时,会更新同一条评论。机器人宣布开始或完成操作的每条评论末尾都带有一个折叠的“运行环境”块(触发事件、运行器、goose 模型、审查策略、自动化开关、缓存状态),以及指回本仓库的 `Created By GHBot` 署名。新审核成功发布后,ghbot 会把旧机器人审核中的逐行 `review` 和 `change` 线程标记为 resolved,并把这些已解决评论折叠隐藏,dismiss 仍然生效的旧审核结论,并把旧审核正文压缩为 superseded 占位说明。如果 GitHub 无法通过 GraphQL 暴露某个旧线程,ghbot 才会删除这条无法映射的逐行评论作为降级处理。GitHub 不允许删除已经提交的 review 记录本身,因此最终只有最新审核保留完整正文和有效状态。 PR 标题、描述或 base branch 变化触发 `edited` 时也会重新审核。对象按仓库 ID 和 PR 编号隔离;`latest.json` 用于加速下一次审核,`reviews/.json` 留存每个成功审核过的 head。关闭或合并 PR 不会主动删除这些对象。缓存不保存 API key、完整 diff 或 prompt。 @@ -128,7 +128,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` 使用同一个密钥,并订阅 `Issue comments`、`Pull request review comments`、`Pull request reviews`,自动分类还需要 `Issues` 和 `Pull requests` 事件。App 需要 `Metadata: read`、`Issues: read and write`、`Pull requests: read and write`。服务会使用每个 payload 中的 `installation.id` 换取对应的短期 installation token,不能用一个固定 installation ID 代替所有仓库。 服务环境变量如下: @@ -140,7 +140,7 @@ GitHub App 的 Webhook URL 配置为 `https://你的域名/webhooks/github`,`W 可以用 `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 重试。 -Webhook 对话刻意保持只读:Goose 只能收到仓库元数据、README、Issue/PR 内容、有限 diff 和近期讨论,不会获得仓库工具或凭证。因此它不能改代码、执行命令、push、运行 `/recheck` 或 `/conflict`;这些操作请继续使用 Action 模式。回复语言跟随最新一条评论,也不会暴露 provider 或 GitHub 密钥。不设置 `WEBHOOK_ENABLED` 就仍是普通的 Action-only 部署。 +Webhook 对话刻意保持只读:Goose 只能收到仓库元数据、README、Issue/PR 内容、有限 diff、近期讨论,以及配置 R2 后的仓库知识缓存,不会获得仓库工具或凭证。因此它不能改代码、执行命令、push,也不能执行 `/recheck` 或 `/conflict`——收到精确命令时会回复引导信息,指向 Action 模式。对安装了 App 的仓库,webhook 服务也会在 `opened`、`edited`、`reopened` 事件上运行与 Action 模式相同的 Issue/PR 自动分类(打标签与查重);设置 `WEBHOOK_TRIAGE_ENABLED=false` 可在 Webhook 模式关闭该功能。Webhook 模式的所有本地写入都保持在当前工作目录内:按仓库隔离的知识缓存位于 `.ghbot-tmp/webhook-knowledge/<仓库 ID>/`。回复语言跟随最新一条评论,也不会暴露 provider 或 GitHub 密钥。不设置 `WEBHOOK_ENABLED` 就仍是普通的 Action-only 部署。 ## 自动解决合并冲突 diff --git a/README.md b/README.md index 265db04..3d023a3 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ When Cloudflare R2 is configured, each successful review stores this metadata in When a new commit triggers `synchronize`, or PR metadata/base changes trigger `edited`, the latest cache for that PR is restored. goose receives an earlier-head result plus the current complete PR patch, revalidates old findings, removes fixed findings, and checks the newest content. The previous merge decision is never reused without a fresh review. An `edited` event on the same head still runs a fresh complete review so title, description, and base-branch changes are respected. -For every `synchronize` event, ghbot posts a commit-scoped progress comment when review starts and updates that same comment when the run completes, fails, or becomes stale because the PR changed again. After the new review is published successfully, ghbot marks inline `review` and `change` threads from earlier bot reviews as resolved and minimizes those resolved comments, dismisses any earlier active bot decision, and reduces its old summary to a superseded marker. If GitHub cannot expose a legacy thread through GraphQL, ghbot deletes only that unmappable inline comment as a fallback. GitHub does not allow a submitted review record itself to be deleted, so the newest review is the only full and active automated result. +For every `synchronize` event, ghbot posts a commit-scoped progress comment when review starts and updates that same comment when the run completes, fails, or becomes stale because the PR changed again. Every comment in which the bot starts or completes an operation ends with a collapsed `Runtime environment` block (trigger, runner, goose model, review policy, automation, cache) and a `Created By GHBot` signature linking back to this repository. After the new review is published successfully, ghbot marks inline `review` and `change` threads from earlier bot reviews as resolved and minimizes those resolved comments, dismisses any earlier active bot decision, and reduces its old summary to a superseded marker. If GitHub cannot expose a legacy thread through GraphQL, ghbot deletes only that unmappable inline comment as a fallback. GitHub does not allow a submitted review record itself to be deleted, so the newest review is the only full and active automated result. Objects are isolated by repository ID and PR number. `latest.json` accelerates the next review, while `reviews/.json` preserves each successful head result. Closing or merging a PR does not proactively delete these objects. Cache data contains no API keys, full diff, or prompt. @@ -114,7 +114,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`, use the same value for `WEBHOOK_SECRET`, and subscribe to `Issue comments`, `Pull request review comments`, and `Pull request reviews`, plus `Issues` and `Pull requests` for automatic triage. 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: @@ -126,7 +126,7 @@ Set these service environment variables: 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. -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. +Webhook chat is deliberately read-only: Goose receives repository metadata, README, Issue/PR text, bounded diffs, recent discussion, and the host-curated repository knowledge cache when R2 is configured, but no repository tools or credentials. It cannot edit code, run commands, push commits, or execute `/recheck` and `/conflict`; an exact `/recheck` or `/conflict` command receives a guidance reply pointing to Action mode instead of silence. The webhook service also runs the same automatic issue and pull-request triage as Action mode on `opened`, `edited`, and `reopened` events for App-installed repositories; set `WEBHOOK_TRIAGE_ENABLED=false` to disable it there. All webhook-mode local writes stay inside the current working directory: the per-repository knowledge cache lives at `.ghbot-tmp/webhook-knowledge//`. 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. ## Automatic conflict resolution diff --git a/src/config.ts b/src/config.ts index 37e0338..f7317aa 100644 --- a/src/config.ts +++ b/src/config.ts @@ -57,6 +57,7 @@ const configSchema = z.object({ 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), + webhookTriageEnabled: envBoolean.default(true), gooseModel: optionalString.default("gpt-5.4"), gooseThinkingEffort: z.preprocess((value) => { if (value === "" || value === undefined) { @@ -114,6 +115,7 @@ export const config = configSchema.parse({ webhookChatPermission: process.env.WEBHOOK_CHAT_PERMISSION, webhookQueueConcurrency: process.env.WEBHOOK_QUEUE_CONCURRENCY, webhookQueueLimit: process.env.WEBHOOK_QUEUE_LIMIT, + webhookTriageEnabled: process.env.WEBHOOK_TRIAGE_ENABLED, gooseModel: process.env.GOOSE_MODEL ?? process.env.OPENCODE_MODEL, gooseThinkingEffort: process.env.GOOSE_THINKING_EFFORT ?? process.env.OPENCODE_REASONING_EFFORT, diff --git a/src/repository/knowledge.ts b/src/repository/knowledge.ts index aec9534..9aa74b6 100644 --- a/src/repository/knowledge.ts +++ b/src/repository/knowledge.ts @@ -87,6 +87,15 @@ export function normalizeKnowledge(content: string): string { return `${content.trim()}\n`; } +/** + * True when the content is still the initial scaffold that + * loadRepositoryKnowledge creates on first read, meaning no real knowledge + * has been persisted for this repository yet. + */ +export function isUninitializedRepositoryKnowledge(content: string): boolean { + return normalizeKnowledge(content) === normalizeKnowledge(EMPTY_KNOWLEDGE); +} + function isNotFoundError(error: unknown): boolean { return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; } diff --git a/src/storage/cacheStore.ts b/src/storage/cacheStore.ts index 9642b25..d0906d3 100644 --- a/src/storage/cacheStore.ts +++ b/src/storage/cacheStore.ts @@ -164,7 +164,12 @@ async function restoreObject(params: { } params.validate(content); await fs.mkdir(path.dirname(params.target), { recursive: true }); - await fs.writeFile(params.target, content, { mode: 0o600 }); + // Write through a temporary file so a concurrent reader (the webhook + // service serves several repositories concurrently) never observes a + // partially written cache object. + const temporaryTarget = `${params.target}.tmp-${process.pid}-${Date.now()}`; + await fs.writeFile(temporaryTarget, content, { mode: 0o600 }); + await fs.rename(temporaryTarget, params.target); logger.info({ key: params.key, bytes: content.byteLength }, "Restored persistent cache object from R2."); } diff --git a/src/webhook/processor.ts b/src/webhook/processor.ts index 4f4b145..04c8d96 100644 --- a/src/webhook/processor.ts +++ b/src/webhook/processor.ts @@ -1,10 +1,18 @@ import type { Octokit } from "@octokit/rest"; +import path from "node:path"; import { runGoosePrompt } from "../ai/gooseCli.js"; import { config } from "../config.js"; import { containsBotMention, chatReplyLanguageInstruction } from "../chat/processor.js"; +import { formatBotSignature, formatRuntimeEnvironmentDetails } from "../github/runtimeInfo.js"; +import { + isUninitializedRepositoryKnowledge, + loadRepositoryKnowledge +} from "../repository/knowledge.js"; import { logger } from "../logger.js"; import { withRetry } from "../retry.js"; import { compactFilesForReview } from "../review/prompt.js"; +import { restorePersistentCache } from "../storage/cacheStore.js"; +import { isR2Configured } from "../storage/r2.js"; import type { PullRequestFile } from "../types.js"; const WEBHOOK_CHAT_MARKER = "