From f9c632e6aba04b3354faa1cde86d02c6da63e23c Mon Sep 17 00:00:00 2001 From: lezi-fun <177434121+lezi-fun@users.noreply.github.com> Date: Thu, 13 Aug 2026 21:54:50 +0800 Subject: [PATCH] Add configurable review modes and conflict recovery --- .env.example | 13 +- .github/workflows/review-reusable.yml | 50 ++- .github/workflows/review.yml | 14 +- .gitignore | 1 + README-zh.md | 35 +- README.md | 35 +- src/actions/runReview.ts | 23 +- src/chat/processor.ts | 50 ++- src/config.ts | 12 +- src/github/client.ts | 21 +- src/repository/knowledge.ts | 88 +++++ src/review/conflictResolver.ts | 493 ++++++++++++++++++++++++++ src/review/format.ts | 6 +- src/review/gooseReviewer.ts | 16 +- src/review/policy.ts | 12 +- src/review/processor.ts | 280 ++++++--------- src/types.ts | 2 +- test/chat-mention.test.ts | 3 + test/conflict-resolver.test.ts | 43 +++ test/repository-knowledge.test.ts | 41 +++ test/review-policy.test.ts | 27 +- 21 files changed, 1035 insertions(+), 230 deletions(-) create mode 100644 src/repository/knowledge.ts create mode 100644 src/review/conflictResolver.ts create mode 100644 test/conflict-resolver.test.ts create mode 100644 test/repository-knowledge.test.ts diff --git a/.env.example b/.env.example index 661be55..020d7e9 100644 --- a/.env.example +++ b/.env.example @@ -12,12 +12,18 @@ GOOSE_BASE_URL=https://api.openai.com/v1 GOOSE_MODEL=gpt-5.4 GOOSE_THINKING_EFFORT=high -# allow | require_approval | reject -REVIEW_POLICY=require_approval +# allow | require_approval | reject. Ordinary review notes pass by default. +REVIEW_POLICY=allow +# normal | strict. Only strict enables the thorough review prompt. +REVIEW_STRICTNESS=normal # Optional repository-specific review rules. REVIEW_INSTRUCTIONS= # Comma-separated PR base-branch globs. Empty means all base branches. REVIEW_BRANCHES= +# Persist repository knowledge in GitHub Actions cache. Authorized @bot agents +# can improve it only when write is explicitly enabled. +REPOSITORY_KNOWLEDGE_ENABLED=true +REPOSITORY_KNOWLEDGE_WRITE=false TRIAGE_ENABLED=true TRIAGE_LABELS=bug,enhancement,documentation,question,maintenance @@ -27,6 +33,9 @@ TRIAGE_INSTRUCTIONS= BOT_NAME=github-actions[bot] AUTO_MERGE=false +AUTO_RESOLVE_CONFLICTS=false +# Optional trusted shell command run after AI conflict resolution and before push. +CONFLICT_TEST_COMMAND= MERGE_METHOD=squash REQUIRE_CHECKS=true MAX_PATCH_CHARS=120000 diff --git a/.github/workflows/review-reusable.yml b/.github/workflows/review-reusable.yml index 3d601d5..21c657a 100644 --- a/.github/workflows/review-reusable.yml +++ b/.github/workflows/review-reusable.yml @@ -77,7 +77,11 @@ on: review_policy: required: false type: string - default: require_approval + default: allow + review_strictness: + required: false + type: string + default: normal review_instructions: required: false type: string @@ -86,6 +90,14 @@ on: required: false type: string default: "" + repository_knowledge_enabled: + required: false + type: string + default: "true" + repository_knowledge_write: + required: false + type: string + default: "false" triage_enabled: required: false type: string @@ -110,6 +122,14 @@ on: required: false type: string default: "false" + auto_resolve_conflicts: + required: false + type: string + default: "false" + conflict_test_command: + required: false + type: string + default: "" merge_method: required: false type: string @@ -167,8 +187,8 @@ jobs: repository: lezi-fun/ghbot ref: main path: ghbot-runtime - - name: Check out current PR source for comment chat - if: ${{ inputs.event_name == 'issue_comment' }} + - name: Check out current PR source for agent tasks + if: ${{ inputs.event_name == 'issue_comment' || (inputs.event_name == 'pull_request_target' && inputs.event_action != 'closed' && inputs.auto_resolve_conflicts == 'true') }} uses: actions/checkout@v4 with: repository: ${{ inputs.repository_owner }}/${{ inputs.repository_name }} @@ -193,6 +213,13 @@ jobs: working-directory: ghbot-runtime - run: npm run build working-directory: ghbot-runtime + - name: Restore repository knowledge + uses: actions/cache@v4 + with: + path: ghbot-runtime/.ghbot-knowledge/repository.md + key: ghbot-knowledge-${{ github.repository_id }}-${{ github.run_id }} + restore-keys: | + ghbot-knowledge-${{ github.repository_id }}- - name: Restore previous PR review if: ${{ inputs.event_name == 'pull_request_target' && inputs.event_action != 'closed' }} uses: actions/cache@v4 @@ -213,8 +240,11 @@ jobs: GOOSE_MODEL: ${{ inputs.goose_model || inputs.opencode_model }} GOOSE_THINKING_EFFORT: ${{ inputs.goose_thinking_effort || inputs.opencode_reasoning_effort }} REVIEW_POLICY: ${{ inputs.review_policy }} + REVIEW_STRICTNESS: ${{ inputs.review_strictness }} REVIEW_INSTRUCTIONS: ${{ inputs.review_instructions }} REVIEW_BRANCHES: ${{ inputs.review_branches }} + REPOSITORY_KNOWLEDGE_ENABLED: ${{ inputs.repository_knowledge_enabled }} + REPOSITORY_KNOWLEDGE_WRITE: ${{ inputs.repository_knowledge_write }} TRIAGE_ENABLED: ${{ inputs.triage_enabled }} TRIAGE_LABELS: ${{ inputs.triage_labels }} TRIAGE_DUPLICATE_LABEL: ${{ inputs.triage_duplicate_label }} @@ -222,6 +252,8 @@ jobs: TRIAGE_INSTRUCTIONS: ${{ inputs.triage_instructions }} BOT_NAME: ${{ inputs.bot_name }} AUTO_MERGE: ${{ inputs.auto_merge }} + AUTO_RESOLVE_CONFLICTS: ${{ inputs.auto_resolve_conflicts }} + CONFLICT_TEST_COMMAND: ${{ inputs.conflict_test_command }} MERGE_METHOD: ${{ inputs.merge_method }} REQUIRE_CHECKS: ${{ inputs.require_checks }} MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }} @@ -266,6 +298,13 @@ jobs: working-directory: ghbot-runtime - run: npm run build working-directory: ghbot-runtime + - name: Restore repository knowledge + uses: actions/cache@v4 + with: + path: ghbot-runtime/.ghbot-knowledge/repository.md + key: ghbot-knowledge-${{ github.repository_id }}-${{ github.run_id }} + restore-keys: | + ghbot-knowledge-${{ github.repository_id }}- - run: node dist/src/actions/runReview.js working-directory: ghbot-runtime env: @@ -278,8 +317,11 @@ jobs: GOOSE_MODEL: ${{ inputs.goose_model || inputs.opencode_model }} GOOSE_THINKING_EFFORT: ${{ inputs.goose_thinking_effort || inputs.opencode_reasoning_effort }} REVIEW_POLICY: ${{ inputs.review_policy }} + REVIEW_STRICTNESS: ${{ inputs.review_strictness }} REVIEW_INSTRUCTIONS: ${{ inputs.review_instructions }} REVIEW_BRANCHES: ${{ inputs.review_branches }} + REPOSITORY_KNOWLEDGE_ENABLED: ${{ inputs.repository_knowledge_enabled }} + REPOSITORY_KNOWLEDGE_WRITE: ${{ inputs.repository_knowledge_write }} TRIAGE_ENABLED: ${{ inputs.triage_enabled }} TRIAGE_LABELS: ${{ inputs.triage_labels }} TRIAGE_DUPLICATE_LABEL: ${{ inputs.triage_duplicate_label }} @@ -287,6 +329,8 @@ jobs: TRIAGE_INSTRUCTIONS: ${{ inputs.triage_instructions }} BOT_NAME: ${{ inputs.bot_name }} AUTO_MERGE: ${{ inputs.auto_merge }} + AUTO_RESOLVE_CONFLICTS: ${{ inputs.auto_resolve_conflicts }} + CONFLICT_TEST_COMMAND: ${{ inputs.conflict_test_command }} MERGE_METHOD: ${{ inputs.merge_method }} REQUIRE_CHECKS: ${{ inputs.require_checks }} MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }} diff --git a/.github/workflows/review.yml b/.github/workflows/review.yml index 90e9d70..250918e 100644 --- a/.github/workflows/review.yml +++ b/.github/workflows/review.yml @@ -65,15 +65,20 @@ jobs: opencode_base_url: ${{ vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }} opencode_model: ${{ vars.OPENCODE_MODEL || 'gpt-5.4' }} opencode_reasoning_effort: ${{ vars.OPENCODE_REASONING_EFFORT || 'high' }} - review_policy: ${{ vars.REVIEW_POLICY || 'require_approval' }} + review_policy: ${{ vars.REVIEW_POLICY || 'allow' }} + review_strictness: ${{ vars.REVIEW_STRICTNESS || 'normal' }} review_instructions: ${{ vars.REVIEW_INSTRUCTIONS || '' }} review_branches: ${{ vars.REVIEW_BRANCHES || '' }} + repository_knowledge_enabled: ${{ vars.REPOSITORY_KNOWLEDGE_ENABLED || 'true' }} + repository_knowledge_write: ${{ vars.REPOSITORY_KNOWLEDGE_WRITE || 'false' }} triage_enabled: ${{ vars.TRIAGE_ENABLED || 'true' }} triage_labels: ${{ vars.TRIAGE_LABELS || 'bug,enhancement,documentation,question,maintenance' }} triage_duplicate_label: ${{ vars.TRIAGE_DUPLICATE_LABEL || 'duplicate' }} triage_candidate_limit: ${{ vars.TRIAGE_CANDIDATE_LIMIT || '50' }} triage_instructions: ${{ vars.TRIAGE_INSTRUCTIONS || '' }} auto_merge: ${{ vars.AUTO_MERGE || 'false' }} + auto_resolve_conflicts: ${{ vars.AUTO_RESOLVE_CONFLICTS || 'false' }} + conflict_test_command: ${{ vars.CONFLICT_TEST_COMMAND || '' }} merge_method: ${{ vars.MERGE_METHOD || 'squash' }} require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }} max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }} @@ -101,15 +106,20 @@ jobs: opencode_base_url: ${{ vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }} opencode_model: ${{ vars.OPENCODE_MODEL || 'gpt-5.4' }} opencode_reasoning_effort: ${{ vars.OPENCODE_REASONING_EFFORT || 'high' }} - review_policy: ${{ vars.REVIEW_POLICY || 'require_approval' }} + review_policy: ${{ vars.REVIEW_POLICY || 'allow' }} + review_strictness: ${{ vars.REVIEW_STRICTNESS || 'normal' }} review_instructions: ${{ vars.REVIEW_INSTRUCTIONS || '' }} review_branches: ${{ vars.REVIEW_BRANCHES || '' }} + repository_knowledge_enabled: ${{ vars.REPOSITORY_KNOWLEDGE_ENABLED || 'true' }} + repository_knowledge_write: ${{ vars.REPOSITORY_KNOWLEDGE_WRITE || 'false' }} triage_enabled: ${{ vars.TRIAGE_ENABLED || 'true' }} triage_labels: ${{ vars.TRIAGE_LABELS || 'bug,enhancement,documentation,question,maintenance' }} triage_duplicate_label: ${{ vars.TRIAGE_DUPLICATE_LABEL || 'duplicate' }} triage_candidate_limit: ${{ vars.TRIAGE_CANDIDATE_LIMIT || '50' }} triage_instructions: ${{ vars.TRIAGE_INSTRUCTIONS || '' }} auto_merge: ${{ vars.AUTO_MERGE || 'false' }} + auto_resolve_conflicts: ${{ vars.AUTO_RESOLVE_CONFLICTS || 'false' }} + conflict_test_command: ${{ vars.CONFLICT_TEST_COMMAND || '' }} merge_method: ${{ vars.MERGE_METHOD || 'squash' }} require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }} max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }} diff --git a/.gitignore b/.gitignore index a9e9d42..d326775 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ pnpm-debug.log* .vercel .ghbot-tmp/ .ghbot-cache/ +.ghbot-knowledge/ diff --git a/README-zh.md b/README-zh.md index 38376f8..569f0f2 100644 --- a/README-zh.md +++ b/README-zh.md @@ -16,10 +16,10 @@ goose 的审核结果固定包含四个顶层字段: `change` 在任何策略下都会阻止合并。普通 `review` 如何影响合并由仓库 Actions Variable `REVIEW_POLICY` 决定: - `allow`:允许存在普通审核意见;没有 `change` 时提交 `APPROVE`。 -- `require_approval`:默认值。允许存在普通审核意见,但 `ghbot review` check 保持 `action_required`,直到仓库管理员批准当前 head commit。 +- `require_approval`:允许存在普通审核意见,但 `ghbot review` check 保持 `action_required`,直到仓库管理员批准当前 head commit。 - `reject`:只要存在普通审核意见就提交 `REQUEST_CHANGES` 并阻止合并。 -如果模型识别到明确的后门、凭证窃取、恶意持久化、破坏命令或供应链攻击,机器人可以评论原因并自动关闭 PR。普通 bug、测试失败或可疑但无法证明恶意的代码不会触发自动关闭。建议先保持 `AUTO_MERGE=false`,确认审核质量后再开启自动合并。 +默认策略是 `allow`。如果模型识别到明确的后门、凭证窃取、恶意持久化、破坏命令或供应链攻击,机器人可以评论原因并自动关闭 PR。普通 bug、测试失败或可疑但无法证明恶意的代码不会触发自动关闭。建议先保持 `AUTO_MERGE=false`,确认审核质量后再开启自动合并。 要让 `require_approval` 或 `reject` 同时阻止人工合并,需要在目标分支的 Ruleset 或 Branch protection 中把 `ghbot review` 设置为 required status check。否则机器人仍会报告 `action_required`,但 GitHub 可能允许有权限的用户手工合并。 @@ -29,11 +29,12 @@ goose 的审核结果固定包含四个顶层字段: - `REVIEW_INSTRUCTIONS`:该仓库额外的测试、兼容性、架构或发布审核规则。 - `REVIEW_BRANCHES`:需要审核的 PR 目标分支 glob,以逗号分隔;留空表示全部分支。例如 `main,develop,release/**`。 +- `REVIEW_STRICTNESS`:默认 `normal`;设为 `strict` 才会全面严格检查。普通模式不吹毛求疵,只报告明确的运行、构建、测试、安全、数据丢失或重要用户体验回归。 - `MAX_PATCH_CHARS`:单次发送给模型的最大 patch 字符数,默认 `120000`。 `REVIEW_BRANCHES` 匹配 PR 的 base branch。`*` 不跨越 `/`,`**` 可以跨越 `/`。workflow 文件需要存在于仓库默认分支,但这不表示只能审核指向默认分支的 PR;例如 workflow 位于 `main` 时,仍可审核目标为 `develop` 或 `release/1.x` 的 PR。 -ghbot 使用 GitHub API 按 PR 编号读取 metadata、完整文件列表和 diff,不会在自动审核路径中 checkout 或执行不可信 PR 代码。来自 fork 或没有仓库权限的外部贡献者也会正常得到自动审核。 +普通自动审核使用 GitHub API 按 PR 编号读取 metadata、完整文件列表和 diff,不执行不可信 PR 代码。只有显式开启冲突修复时才 checkout PR head,而且执行和测试都在无 GitHub 凭据的一次性净化容器中完成。来自 fork 或没有仓库权限的外部贡献者仍会正常得到自动审核,但不会被自动推送冲突修复。 ## 增量审核缓存 @@ -47,6 +48,15 @@ ghbot 使用 GitHub API 按 PR 编号读取 metadata、完整文件列表和 dif PR 标题、描述或 base branch 变化触发 `edited` 时也会重新审核。PR 被关闭或合并后,机器人会删除本地缓存文件,并通过 Actions Cache API 删除该 PR 的远端缓存。缓存不保存 API key、完整 diff 或 prompt。 +## 可自我改进的仓库认知缓存 + +ghbot 可以把一份简洁的仓库认知文件保存在 GitHub Actions cache 中。它按仓库 ID 隔离,与单个 PR 的审核缓存分开,因此 PR 关闭或合并时不会删除。自动审核可以参考其中长期有效的架构、支持环境、可信测试命令、代码约定和常见坑。 + +- `REPOSITORY_KNOWLEDGE_ENABLED`:恢复并使用仓库认知,默认 `true`。 +- `REPOSITORY_KNOWLEDGE_WRITE`:允许有权限的 `@bot` goose Agent 改进认知缓存,默认 `false`。 + +Agent 只能编辑临时快照中的 `.ghbot/repository-knowledge.md` 草稿。ghbot 会校验内容,拒绝凭证、私钥和超过 32 KiB 的内容,再把它复制到 reusable workflow runtime 的 `.ghbot-knowledge/repository.md`,由 `actions/cache` 用仓库级 key 持久化。它不会提交到业务仓库,Agent 仍然拿不到 GitHub 凭证。 + ## Issue 和 PR 分类 在 Issue 或 PR 的 `opened`、`edited`、`reopened` 事件中,ghbot 可以: @@ -92,6 +102,16 @@ Agent 在一次性 Docker 容器中运行: 每条回复都按源评论 ID 去重,workflow 重跑不会重复回答;机器人自己的回复会被忽略,避免自触发循环。 +启用认知写入后,Agent 只有发现已验证、长期有效的仓库事实时才能更新草稿。仓库会持续变化,因此当前代码、测试或配置证明旧记录已经过时、被替代、互相冲突或不再成立时,必须主动修改或删除旧条目,而不是只追加历史。不得记录临时 PR 结论、推测、凭证、个人信息或降低安全性的指令;当前仓库证据始终优先于缓存认知。 + +## 自动解决合并冲突 + +设置 `AUTO_RESOLVE_CONFLICTS=true` 后,如果 AI 审核已经通过,但 GitHub 报告 `mergeable=false` 且 `mergeable_state=dirty`,goose 可以自动解决冲突。它与 `AUTO_MERGE` 相互独立,因此可以只开启冲突修复而继续禁止自动合并。 + +仅处理当前 head 未变化且 PR 分支位于同一仓库的情况;外部 fork、旧 head、非冲突状态和未通过审核的 PR 都会跳过。ghbot 在宿主生成本地 merge,再把无 `.git`、无凭据的净化快照交给 goose。goose 可以修改直接冲突文件,也可以在兼容性确有需要时调整相关调用方、类型、测试、lockfile、配置或文档;受保护的 Agent 配置和凭证路径会被拒绝。 + +应用改动后,ghbot 检查未合并路径和 `git diff --check`。第二次隔离 goose 会审核完整 staged diff,并在配置后运行可信的 `CONFLICT_TEST_COMMAND`。只有第二次确认明确返回 `safeToCommit=true`,且远端 PR head 仍与审核 SHA 相同,才会创建普通 merge commit 并 push;绝不 force-push。新 commit 会触发 `synchronize` 并重新完整审核,不会把修复前的结论直接当作批准。 + ## goose 配置 必须添加 Actions Secret: @@ -104,7 +124,7 @@ Agent 在一次性 Docker 容器中运行: - `GOOSE_MODEL`:默认 `gpt-5.4`。 - `GOOSE_THINKING_EFFORT`:可选 `off`、`low`、`medium`、`high`、`max`,workflow 默认 `high`。 -workflow 安装固定版本 goose CLI `v1.46.0`。普通审核和分类使用 `GOOSE_MODE=chat`,不加载扩展也不执行工具;只有通过权限检查的 PR comment Agent 在一次性 Docker 容器中启用 Developer 扩展和自动工具权限。 +workflow 安装固定版本 goose CLI `v1.46.0`。普通审核和分类使用 `GOOSE_MODE=chat`,不加载扩展也不执行工具;通过权限检查的 PR comment Agent,以及冲突修复和最终确认,会在一次性 Docker 容器中启用 Developer 扩展。 迁移期间仍兼容 `OPENCODE_API_KEY`、`OPENCODE_BASE_URL`、`OPENCODE_MODEL`、`OPENCODE_REASONING_EFFORT`,但新仓库应使用 `GOOSE_*` 名称。 @@ -130,6 +150,7 @@ GitHub App 建议配置以下 Repository permissions: - Checks:Read and write - Commit statuses:Read-only - Metadata:Read-only +- Workflows:仅当允许冲突修复修改 workflow 文件时设为 Read and write 可选 App Secrets: @@ -161,15 +182,15 @@ secrets: 完整的 `with:` 输入和 Repository Variables 映射请参考仓库内的 wrapper workflow。 -## 宽松审核 +## 手动重新审核 有资格的仓库用户可以在 PR 中评论: ```text -/lenient-check +/recheck ``` -机器人会重新运行一个只关注危险改动、运行时错误、崩溃、构建或测试破坏、数据丢失和明确安全问题的审核。如果最近 24 小时内有管理员在 PR 中评论或 review,则只有管理员可以请求或批准宽松结果;否则 `write`、`maintain` 或 `admin` 用户都可以操作。每小时 schedule 会重新检查等待批准的 PR。 +机器人会按照仓库当前的 `REVIEW_STRICTNESS` 对最新完整 PR 重新审核。只有具有 `write`、`maintain` 或 `admin` 权限的用户可以触发;旧 `/lenient-check` 命令不再生效。 ## 本地开发 diff --git a/README.md b/README.md index f4f75e6..8df5d87 100644 --- a/README.md +++ b/README.md @@ -16,10 +16,10 @@ goose returns exactly four sections: Only `change` is always a required change. How ordinary `review` notes affect merge is configured with `REVIEW_POLICY`: - `allow`: review notes do not block merge. A clean result is submitted as `APPROVE`. -- `require_approval` (default): review notes are submitted as `COMMENT`; the `ghbot review` check remains `action_required` until a repository administrator approves the current head commit. +- `require_approval`: review notes are submitted as `COMMENT`; the `ghbot review` check remains `action_required` until a repository administrator approves the current head commit. - `reject`: any review note is submitted as `REQUEST_CHANGES` and blocks merge. -Required changes and malicious code block under every policy. Clearly malicious pull requests can be commented on and closed automatically. Start with `AUTO_MERGE=false` until the review behavior is trusted. +The default is `allow`. Required changes and malicious code block under every policy. Clearly malicious pull requests can be commented on and closed automatically. Start with `AUTO_MERGE=false` until the review behavior is trusted. ### Repository-specific rules @@ -27,6 +27,7 @@ Use repository Actions variables to customize a caller repository: - `REVIEW_INSTRUCTIONS`: additional repository-specific review requirements, such as testing, compatibility, architecture, or release rules. - `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`. `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. @@ -45,6 +46,15 @@ When a new commit triggers `synchronize`, or PR metadata/base changes trigger `e Cache keys are isolated by repository ID and PR number. A `closed` event, including a merged PR, deletes all remote caches for that PR and removes the local cache file. Cache data contains no API keys, full diff, or prompt. +### Self-improving repository knowledge cache + +ghbot can retain a concise repository knowledge file in GitHub Actions cache. It is isolated by repository ID and separate from each PR review cache, so it survives PR close and merge events. Automatic review can use durable facts such as architecture, supported environments, trusted validation commands, conventions, and recurring pitfalls. + +- `REPOSITORY_KNOWLEDGE_ENABLED`: restore and use repository knowledge; default `true`. +- `REPOSITORY_KNOWLEDGE_WRITE`: allow an authorized `@bot` goose Agent to improve the cached knowledge; default `false`. + +The Agent edits only a scratch copy at `.ghbot/repository-knowledge.md`. ghbot validates the result, rejects credentials/private keys and content over 32 KiB, then copies it to `.ghbot-knowledge/repository.md` in the reusable-workflow runtime. `actions/cache` persists that file under a repository-scoped key. It is never committed to the caller repository, and the Agent still receives no GitHub credentials. + ## Issue and PR triage On `issues` and `pull_request_target` open/edit/reopen events, ghbot can: @@ -78,6 +88,16 @@ The snapshot excludes Git metadata, repository goose/OpenCode/agent instruction Replies are keyed to the source comment so a workflow rerun does not post the same answer twice, and bot-authored replies are ignored to prevent loops. +When repository knowledge writing is enabled, the Agent may improve its scratch knowledge file only with verified, durable repository facts. Repositories evolve, so it must revise or delete entries that current code, tests, or configuration prove outdated, replaced, contradictory, or no longer true instead of only appending history. Temporary PR conclusions, speculative claims, credentials, personal data, and instructions that weaken security are forbidden. Current repository evidence always takes precedence over cached knowledge. + +## Automatic conflict resolution + +Set `AUTO_RESOLVE_CONFLICTS=true` to allow goose to repair a PR that passed review but GitHub reports as `mergeable=false` with `mergeable_state=dirty`. This is independent of `AUTO_MERGE`; conflict repair can be enabled while automatic merging remains disabled. + +Conflict repair applies only to a current-head PR branch in the same repository. External forks, stale heads, non-dirty states, and failed reviews are skipped. ghbot creates the merge locally, gives goose a sanitized credential-free snapshot, and allows it to change direct conflict files plus related callers, types, tests, lockfiles, configuration, or documentation when necessary for compatibility. Protected agent/configuration and credential paths are rejected. + +After applying the proposed files, ghbot verifies there are no unmerged paths and runs `git diff --check`. A second isolated goose pass reviews the complete staged diff and, when configured, runs the trusted `CONFLICT_TEST_COMMAND`. The result is committed and pushed only when that final pass returns `safeToCommit=true` and the remote PR head still matches the reviewed SHA. ghbot never force-pushes. The new commit triggers a fresh `synchronize` review; the old decision is not reused as approval. + ## goose configuration Required secret: @@ -96,7 +116,7 @@ The workflow installs the pinned goose CLI `v1.46.0`. Review and triage run with goose run --no-session --no-profile --quiet --output-format json --provider openai --model --text ``` -The goose process gets isolated home/config/data/state directories, disables profiles and repository context files, and uses `GOOSE_MODE=chat` for automatic review and triage so no tools can run. Only authorized PR comment chat uses the Developer extension inside the disposable container. +The goose process gets isolated home/config/data/state directories, disables profiles and repository context files, and uses `GOOSE_MODE=chat` for automatic review and triage so no tools can run. Authorized PR comment chat and the two conflict-resolution passes use the Developer extension inside disposable containers. For migration, the runtime and workflows still accept `OPENCODE_API_KEY`, `OPENCODE_BASE_URL`, `OPENCODE_MODEL`, and `OPENCODE_REASONING_EFFORT` as fallback aliases. New repositories should use the `GOOSE_*` names. @@ -122,6 +142,7 @@ For a GitHub App, configure these repository permissions: - Checks: read and write - Commit statuses: read-only - Metadata: read-only +- Workflows: read and write only if conflict resolution may update workflow files Add App credentials as optional repository secrets: @@ -151,15 +172,15 @@ secrets: See the checked-in wrapper for all `with:` inputs and repository-variable mappings. -## Lenient review +## Manual recheck An eligible repository user can comment: ```text -/lenient-check +/recheck ``` -The bot reruns review with runtime, build, data-loss, and security focus. If an administrator has responded within the previous 24 hours, only an administrator may request or approve the lenient result; otherwise users with `write`, `maintain`, or `admin` permission are eligible. An hourly scheduled job rechecks pending approvals. +The bot reruns the complete current PR review using the repository's configured `REVIEW_STRICTNESS`. Only users with `write`, `maintain`, or `admin` permission can request it. The old `/lenient-check` command is no longer accepted. ## Local development @@ -175,4 +196,4 @@ For local event simulation, install goose `v1.46.0` and export the variables in node dist/src/actions/runReview.js ``` -The bot reviews GitHub-provided diffs and status data. It intentionally does not check out or execute untrusted pull request code under `pull_request_target`. +Normal automatic review and triage use GitHub-provided diffs without executing PR code. When conflict resolution is explicitly enabled, PR code and the configured validation command run only inside sanitized disposable containers without GitHub credentials. diff --git a/src/actions/runReview.ts b/src/actions/runReview.ts index 45f619b..4749ef3 100644 --- a/src/actions/runReview.ts +++ b/src/actions/runReview.ts @@ -1,6 +1,6 @@ import fs from "node:fs"; import { config } from "../config.js"; -import { createGitHubClient } from "../github/client.js"; +import { createGitHubCredentials } from "../github/client.js"; import { logger } from "../logger.js"; import { withRetry } from "../retry.js"; import { processPullRequestChat } from "../chat/processor.js"; @@ -8,9 +8,9 @@ import { processIssueTriage, processPullRequestTriage } from "../triage/processo import { deleteLocalReviewCache } from "../review/cache.js"; import { cleanupPullRequestReviewCache, - processLenientCheckComment, + processRecheckComment, processPullRequest, - processScheduledLenientMerges, + processScheduledPendingMerges, processPullRequestReviewApproval, shouldReviewPullRequest } from "../review/processor.js"; @@ -83,10 +83,11 @@ async function main(): Promise { ? buildPayloadFromWorkflowCallEnv(workflowCallEventName) : readPayloadFromGitHubEventPath(); const repository = payload.repository; - const octokit = await createGitHubClient({ + const github = await createGitHubCredentials({ owner: repository.owner.login, repo: repository.name }); + const octokit = github.octokit; const eventName = workflowCallEventName ?? process.env.GITHUB_EVENT_NAME; if (!eventName) { @@ -146,7 +147,12 @@ async function main(): Promise { }); } - await processPullRequest(octokit, ref, "strict"); + await processPullRequest( + octokit, + ref, + config.reviewStrictness === "strict" ? "strict" : "normal", + github.token + ); return; } @@ -169,12 +175,13 @@ async function main(): Promise { return; } - await processLenientCheckComment(octokit, { + await processRecheckComment(octokit, { owner: commentPayload.repository.owner.login, repo: commentPayload.repository.name, pullNumber: commentPayload.issue.number, commenterLogin: commentPayload.comment.user.login, - commentBody: commentPayload.comment.body + commentBody: commentPayload.comment.body, + gitToken: github.token }); await processPullRequestChat(octokit, { owner: commentPayload.repository.owner.login, @@ -208,7 +215,7 @@ async function main(): Promise { if (eventName === "schedule") { const scheduledPayload = payload as ScheduledPayload; - await processScheduledLenientMerges(octokit, { + await processScheduledPendingMerges(octokit, { owner: scheduledPayload.repository.owner.login, repo: scheduledPayload.repository.name }); diff --git a/src/chat/processor.ts b/src/chat/processor.ts index e13844e..ca6d632 100644 --- a/src/chat/processor.ts +++ b/src/chat/processor.ts @@ -7,6 +7,14 @@ import { logger } from "../logger.js"; import { withRetry } from "../retry.js"; import { compactFilesForReview } from "../review/prompt.js"; import type { PullRequestFile } from "../types.js"; +import { + loadRepositoryKnowledge, + normalizeKnowledge, + readKnowledgeScratch, + REPOSITORY_KNOWLEDGE_SCRATCH_PATH, + saveRepositoryKnowledgeCache, + writeKnowledgeScratch +} from "../repository/knowledge.js"; const CHAT_MARKER_PREFIX = "/.exec(body); + const match = //.exec(body); if (!match) { return null; } return { - mode: match[1] as ReviewMode, + mode: normalizeReviewMode(match[1]), outcome: match[2] as "pass" | "block", requiresAdminApproval: match[3] === "true" }; } +function normalizeReviewMode(value: string): ReviewMode { + return value === "strict" ? "strict" : "normal"; +} + export function branchPatternToRegExp(pattern: string): RegExp { let source = "^"; diff --git a/src/review/processor.ts b/src/review/processor.ts index 3e5f60a..19e5b26 100644 --- a/src/review/processor.ts +++ b/src/review/processor.ts @@ -22,13 +22,19 @@ import { parseReviewStateMarker } from "./policy.js"; import { compactFilesForReview } from "./prompt.js"; +import { loadRepositoryKnowledge } from "../repository/knowledge.js"; +import { canAutoResolveConflicts, resolvePullRequestConflicts } from "./conflictResolver.js"; const reviewer = new GooseReviewer(); const CHECK_RUN_NAME = "ghbot review"; -export const LENIENT_COMMENT_COMMAND = "/lenient-check"; -const ADMIN_RESPONSE_WINDOW_MS = 24 * 60 * 60 * 1000; +export const RECHECK_COMMENT_COMMAND = "/recheck"; -export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, mode: ReviewMode = "strict"): Promise { +export async function processPullRequest( + octokit: Octokit, + ref: PullRequestRef, + mode: ReviewMode = "normal", + gitToken?: string +): Promise { const { owner, repo, pullNumber } = ref; const { data: pullRequest } = await octokit.rest.pulls.get({ @@ -63,12 +69,19 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, pullNumber, currentHeadSha: pullRequest.head.sha }); + const repositoryKnowledge = config.repositoryKnowledgeEnabled + ? await loadRepositoryKnowledge().catch((error: unknown) => { + logger.warn({ error, owner, repo, pullNumber }, "Ignoring unavailable repository knowledge."); + return undefined; + }) + : undefined; const decision = await reviewer.review({ title: pullRequest.title, body: pullRequest.body, files: compactFiles, mode, - previousReview + previousReview, + repositoryKnowledge }); const { data: currentPullRequest } = await octokit.rest.pulls.get({ @@ -149,6 +162,64 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, return; } + const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber); + const conflictResolutionEligible = canAutoResolveConflicts({ + enabled: config.autoResolveConflicts, + reviewPassed: true, + mergeable: mergeablePullRequest.mergeable, + mergeableState: mergeablePullRequest.mergeable_state, + baseRepository: `${owner}/${repo}`, + headRepository: pullRequest.head.repo?.full_name ?? null, + expectedHeadSha: pullRequest.head.sha, + currentHeadSha: currentPullRequest.head.sha + }); + if (conflictResolutionEligible) { + const worktree = process.env.GHBOT_PR_WORKTREE; + if (!gitToken || !worktree) { + logger.warn( + { owner, repo, pullNumber, hasGitToken: Boolean(gitToken), hasWorktree: Boolean(worktree) }, + "Cannot resolve pull request conflicts without a git token and PR worktree." + ); + } else { + try { + const resolved = await resolvePullRequestConflicts(octokit, { + owner, + repo, + pullNumber, + expectedHeadSha: pullRequest.head.sha, + baseBranch: pullRequest.base.ref, + headBranch: pullRequest.head.ref, + headRepository: pullRequest.head.repo?.full_name ?? null, + worktree, + gitToken, + repositoryKnowledge + }); + if (resolved) { + await withRetry("github.issues.createComment.conflictsResolved", async () => { + return octokit.rest.issues.createComment({ + owner, + repo, + issue_number: pullNumber, + body: "goose resolved the merge conflicts, validated the final changes, and pushed a new commit. The new head will be reviewed again before any merge decision." + }); + }); + return; + } + } catch (error) { + logger.error({ error, owner, repo, pullNumber }, "Automatic conflict resolution failed safely."); + await withRetry("github.issues.createComment.conflictResolutionFailed", async () => { + return octokit.rest.issues.createComment({ + owner, + repo, + issue_number: pullNumber, + body: "Automated review passed, but goose could not safely resolve and validate the merge conflicts. No conflict-resolution commit was pushed." + }); + }); + return; + } + } + } + await maybeMergePullRequest(octokit, { owner, repo, @@ -157,11 +228,12 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, headSha: pullRequest.head.sha, mode, requireAdminApproval: disposition.requiresAdminApproval, - emitStatusComments: true + emitStatusComments: true, + mergeablePullRequest }); } -export async function processScheduledLenientMerges( +export async function processScheduledPendingMerges( octokit: Octokit, params: { owner: string; @@ -169,7 +241,7 @@ export async function processScheduledLenientMerges( } ): Promise { if (!config.autoMerge) { - logger.info({ owner: params.owner, repo: params.repo }, "Skipping scheduled lenient recheck because AUTO_MERGE is disabled."); + logger.info({ owner: params.owner, repo: params.repo }, "Skipping scheduled pending merge check because AUTO_MERGE is disabled."); return; } @@ -196,22 +268,16 @@ export async function processScheduledLenientMerges( continue; } - if (latestReviewOutcome.mode !== "lenient" && !latestReviewOutcome.requiresAdminApproval) { + if (!latestReviewOutcome.requiresAdminApproval) { continue; } - const adminRecentlyResponded = await hasRecentAdminResponse(octokit, { - owner: params.owner, - repo: params.repo, - pullNumber: pullRequest.number - }); - const approvedByEligibleReviewer = await hasCurrentHeadApprovalFrom(octokit, { owner: params.owner, repo: params.repo, pullNumber: pullRequest.number, headSha: pullRequest.head.sha, - requireAdmin: latestReviewOutcome.requiresAdminApproval || adminRecentlyResponded + requireAdmin: true }); if (!approvedByEligibleReviewer) { @@ -324,33 +390,6 @@ export async function processPullRequestReviewApproval( return; } - const hasSuccessfulLenientReview = await hasSuccessfulLenientReviewForHead(octokit, { - owner: params.owner, - repo: params.repo, - pullNumber: params.pullNumber, - headSha: params.commitId - }); - - if (latestReviewOutcome.mode === "lenient" && !hasSuccessfulLenientReview) { - logger.info( - { - owner: params.owner, - repo: params.repo, - pullNumber: params.pullNumber, - reviewerLogin: params.reviewerLogin, - commitId: params.commitId - }, - "Ignoring lenient approval because there is no successful lenient review for the current head." - ); - return; - } - - const adminRecentlyResponded = await hasRecentAdminResponse(octokit, { - owner: params.owner, - repo: params.repo, - pullNumber: params.pullNumber - }); - const { data: permission } = await octokit.rest.repos.getCollaboratorPermissionLevel({ owner: params.owner, repo: params.repo, @@ -363,7 +402,7 @@ export async function processPullRequestReviewApproval( throw error; }); - const requireAdmin = latestReviewOutcome.requiresAdminApproval || adminRecentlyResponded; + const requireAdmin = latestReviewOutcome.requiresAdminApproval; const allowedPermissions = requireAdmin ? new Set(["admin"]) : new Set(["admin", "maintain", "write"]); @@ -376,10 +415,9 @@ export async function processPullRequestReviewApproval( pullNumber: params.pullNumber, reviewerLogin: params.reviewerLogin, permission: permission.permission, - adminRecentlyResponded, requireAdmin }, - "Ignoring lenient approval because reviewer does not meet the current permission threshold." + "Ignoring approval because reviewer does not meet the current permission threshold." ); return; } @@ -405,7 +443,7 @@ export async function processPullRequestReviewApproval( }); } -export async function processLenientCheckComment( +export async function processRecheckComment( octokit: Octokit, params: { owner: string; @@ -413,9 +451,10 @@ export async function processLenientCheckComment( pullNumber: number; commenterLogin: string; commentBody: string; + gitToken?: string; } ): Promise { - if (!isLenientCheckComment(params.commentBody)) { + if (!isRecheckComment(params.commentBody)) { return; } @@ -428,17 +467,11 @@ export async function processLenientCheckComment( if (!isReviewBranchEnabled(pullRequest.base.ref)) { logger.info( { owner: params.owner, repo: params.repo, pullNumber: params.pullNumber, baseBranch: pullRequest.base.ref }, - "Ignoring lenient check outside REVIEW_BRANCHES." + "Ignoring recheck outside REVIEW_BRANCHES." ); return; } - const adminRecentlyResponded = await hasRecentAdminResponse(octokit, { - owner: params.owner, - repo: params.repo, - pullNumber: params.pullNumber - }); - const { data: permission } = await octokit.rest.repos.getCollaboratorPermissionLevel({ owner: params.owner, repo: params.repo, @@ -451,9 +484,7 @@ export async function processLenientCheckComment( throw error; }); - const allowedPermissions = adminRecentlyResponded - ? new Set(["admin"]) - : new Set(["admin", "maintain", "write"]); + const allowedPermissions = new Set(["admin", "maintain", "write"]); if (!permission.permission || !allowedPermissions.has(permission.permission)) { logger.info( @@ -463,9 +494,8 @@ export async function processLenientCheckComment( pullNumber: params.pullNumber, commenterLogin: params.commenterLogin, permission: permission.permission, - adminRecentlyResponded }, - "Ignoring lenient check comment because commenter does not meet the current permission threshold." + "Ignoring recheck comment because commenter does not have write permission." ); return; } @@ -476,18 +506,17 @@ export async function processLenientCheckComment( repo: params.repo, pullNumber: params.pullNumber, commenterLogin: params.commenterLogin, - adminRecentlyResponded, permission: permission.permission }, - "Processing lenient check comment command." + "Processing recheck comment command." ); - await withRetry("github.issues.createComment.lenientRequested", async () => { + await withRetry("github.issues.createComment.recheckRequested", async () => { return octokit.rest.issues.createComment({ owner: params.owner, repo: params.repo, issue_number: params.pullNumber, - body: `Lenient check requested by @${params.commenterLogin}. Re-running the review with runtime and security focus only.` + body: `Recheck requested by @${params.commenterLogin}. Re-running the review with the repository's current strictness settings.` }); }); @@ -498,7 +527,8 @@ export async function processLenientCheckComment( repo: params.repo, pullNumber: params.pullNumber }, - "lenient" + config.reviewStrictness === "strict" ? "strict" : "normal", + params.gitToken ); } @@ -513,6 +543,7 @@ async function maybeMergePullRequest( mode: ReviewMode; requireAdminApproval: boolean; emitStatusComments: boolean; + mergeablePullRequest?: Awaited>; } ): Promise { const { owner, repo, pullNumber } = params; @@ -522,43 +553,32 @@ async function maybeMergePullRequest( return; } - if (params.mode === "lenient" || params.requireAdminApproval) { - const adminRecentlyResponded = await hasRecentAdminResponse(octokit, { - owner, - repo, - pullNumber - }); - - const requireAdmin = params.requireAdminApproval || adminRecentlyResponded; - const approvalRequirement = requireAdmin - ? "a repository administrator" - : "a repository user with write permission or above"; - + if (params.requireAdminApproval) { const approvedByEligibleReviewer = await hasCurrentHeadApprovalFrom(octokit, { owner, repo, pullNumber, headSha: params.headSha, - requireAdmin + requireAdmin: true }); if (!approvedByEligibleReviewer) { if (params.emitStatusComments) { - await withRetry("github.issues.createComment.awaitLenientApproval", async () => { + await withRetry("github.issues.createComment.awaitAdminApproval", async () => { return octokit.rest.issues.createComment({ owner, repo, issue_number: pullNumber, - body: `Automated review passed, but this PR will not be merged until ${approvalRequirement} approves the current head commit.\n\nNext step: in the GitHub pull request UI, click "Review changes" and submit an "Approve" review. No extra command is needed.` + body: `Automated review passed, but this PR will not be merged until a repository administrator approves the current head commit.\n\nNext step: in the GitHub pull request UI, click "Review changes" and submit an "Approve" review. No extra command is needed.` }); }); } - logger.info({ owner, repo, pullNumber, requireAdmin }, "Waiting for eligible approval before merging."); + logger.info({ owner, repo, pullNumber }, "Waiting for administrator approval before merging."); return; } } - const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber); + const mergeablePullRequest = params.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 () => { @@ -670,7 +690,7 @@ async function hasCurrentHeadApprovalFrom( pullNumber: params.pullNumber, login }, - "Failed to resolve collaborator permission while checking lenient approval eligibility." + "Failed to resolve collaborator permission while checking approval eligibility." ); } } @@ -682,19 +702,6 @@ function isNotFoundError(error: unknown): boolean { return typeof error === "object" && error !== null && "status" in error && error.status === 404; } -async function hasSuccessfulLenientReviewForHead( - octokit: Octokit, - params: { - owner: string; - repo: string; - pullNumber: number; - headSha: string; - } -): Promise { - const outcome = await getLatestBotReviewOutcomeForHead(octokit, params); - return outcome?.mode === "lenient" && outcome.outcome === "pass"; -} - async function getLatestBotReviewOutcomeForHead( octokit: Octokit, params: { @@ -878,9 +885,7 @@ async function upsertReviewCheckRun( ? "Malicious code detected" : disposition.requiresAdminApproval ? "Review notes require administrator approval" - : params.mode === "lenient" - ? "Lenient review completed" - : "Strict review completed", + : `${params.mode === "strict" ? "Strict" : "Normal"} review completed`, summary: params.decision.result.shouldClosePullRequest ? `${params.decision.result.summary}\n\nClose reason: ${params.decision.result.closeReason}` : params.decision.result.summary @@ -926,8 +931,8 @@ async function markReviewCheckApproved( }); } -export function isLenientCheckComment(body: string): boolean { - return body.trim().startsWith(LENIENT_COMMENT_COMMAND); +export function isRecheckComment(body: string): boolean { + return body.trim() === RECHECK_COMMENT_COMMAND; } async function closeMaliciousPullRequest( @@ -1049,78 +1054,3 @@ function shouldFallbackToCommentReview(error: unknown, event: "APPROVE" | "COMME return error.message.includes("GitHub Actions is not permitted to approve pull requests."); } - -async function hasRecentAdminResponse( - octokit: Octokit, - params: { - owner: string; - repo: string; - pullNumber: number; - } -): Promise { - const threshold = Date.now() - ADMIN_RESPONSE_WINDOW_MS; - - const [comments, reviews] = await Promise.all([ - octokit.paginate(octokit.rest.issues.listComments, { - owner: params.owner, - repo: params.repo, - issue_number: params.pullNumber, - per_page: 100 - }), - octokit.paginate(octokit.rest.pulls.listReviews, { - owner: params.owner, - repo: params.repo, - pull_number: params.pullNumber, - per_page: 100 - }) - ]); - - const actors = new Map(); - - for (const comment of comments) { - const login = comment.user?.login; - const createdAt = comment.created_at ? Date.parse(comment.created_at) : NaN; - if (!login || Number.isNaN(createdAt) || createdAt < threshold) { - continue; - } - - actors.set(login, Math.max(actors.get(login) ?? 0, createdAt)); - } - - for (const review of reviews) { - const login = review.user?.login; - const submittedAt = review.submitted_at ? Date.parse(review.submitted_at) : NaN; - if (!login || Number.isNaN(submittedAt) || submittedAt < threshold) { - continue; - } - - actors.set(login, Math.max(actors.get(login) ?? 0, submittedAt)); - } - - for (const login of actors.keys()) { - try { - const { data: permission } = await octokit.rest.repos.getCollaboratorPermissionLevel({ - owner: params.owner, - repo: params.repo, - username: login - }); - - if (permission.permission === "admin") { - return true; - } - } catch (error) { - logger.warn( - { - error, - owner: params.owner, - repo: params.repo, - pullNumber: params.pullNumber, - login - }, - "Failed to resolve collaborator permission while checking for recent admin response." - ); - } - } - - return false; -} diff --git a/src/types.ts b/src/types.ts index 980c258..decc141 100644 --- a/src/types.ts +++ b/src/types.ts @@ -31,7 +31,7 @@ export type ReviewDecision = { }; }; -export type ReviewMode = "strict" | "lenient"; +export type ReviewMode = "strict" | "normal"; export type DiffPosition = { path: string; diff --git a/test/chat-mention.test.ts b/test/chat-mention.test.ts index e3f86be..fd6d426 100644 --- a/test/chat-mention.test.ts +++ b/test/chat-mention.test.ts @@ -38,12 +38,14 @@ test("PR chat snapshot excludes repository instructions, secrets, git data, and await fs.mkdir(path.join(source, ".goose")); await fs.mkdir(path.join(source, ".opencode")); await fs.mkdir(path.join(source, ".agents")); + await fs.mkdir(path.join(source, ".ghbot")); await fs.mkdir(path.join(source, "src")); await Promise.all([ fs.writeFile(path.join(source, ".git", "config"), "credential data"), fs.writeFile(path.join(source, ".goose", "config.yaml"), "untrusted goose config"), fs.writeFile(path.join(source, ".opencode", "plugin.ts"), "untrusted plugin"), fs.writeFile(path.join(source, ".agents", "SKILL.md"), "untrusted skill"), + fs.writeFile(path.join(source, ".ghbot", "repository-knowledge.md"), "untrusted knowledge"), fs.writeFile(path.join(source, ".env"), "TOKEN=secret"), fs.writeFile(path.join(source, ".env.local"), "TOKEN=local-secret"), fs.writeFile(path.join(source, "AGENTS.md"), "untrusted instructions"), @@ -60,6 +62,7 @@ test("PR chat snapshot excludes repository instructions, secrets, git data, and ".goose", ".opencode", ".agents", + ".ghbot", ".env", ".env.local", "AGENTS.md", diff --git a/test/conflict-resolver.test.ts b/test/conflict-resolver.test.ts new file mode 100644 index 0000000..778547d --- /dev/null +++ b/test/conflict-resolver.test.ts @@ -0,0 +1,43 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + canAutoResolveConflicts, + diffSnapshotInventories +} from "../src/review/conflictResolver.js"; + +const eligible = { + enabled: true, + reviewPassed: true, + mergeable: false, + mergeableState: "dirty", + baseRepository: "forumlify/public", + headRepository: "forumlify/public", + expectedHeadSha: "abc", + currentHeadSha: "abc" +} as const; + +test("only a passing conflicted same-repository current head is eligible", () => { + assert.equal(canAutoResolveConflicts(eligible), true); + assert.equal(canAutoResolveConflicts({ ...eligible, reviewPassed: false }), false); + assert.equal(canAutoResolveConflicts({ ...eligible, mergeable: true, mergeableState: "clean" }), false); + assert.equal(canAutoResolveConflicts({ ...eligible, headRepository: "contributor/fork" }), false); + assert.equal(canAutoResolveConflicts({ ...eligible, currentHeadSha: "new-head" }), false); + assert.equal(canAutoResolveConflicts({ ...eligible, enabled: false }), false); +}); + +test("snapshot inventory detects related file additions, changes, and deletions", () => { + const before = new Map([ + ["conflicted.ts", { hash: "old", size: 10 }], + ["caller.ts", { hash: "same", size: 20 }], + ["removed.test.ts", { hash: "remove", size: 30 }] + ]); + const after = new Map([ + ["conflicted.ts", { hash: "resolved", size: 12 }], + ["caller.ts", { hash: "same", size: 20 }], + ["compatibility.test.ts", { hash: "new", size: 40 }] + ]); + assert.deepEqual( + diffSnapshotInventories(before, after), + ["compatibility.test.ts", "conflicted.ts", "removed.test.ts"] + ); +}); diff --git a/test/repository-knowledge.test.ts b/test/repository-knowledge.test.ts new file mode 100644 index 0000000..96cd470 --- /dev/null +++ b/test/repository-knowledge.test.ts @@ -0,0 +1,41 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { + loadRepositoryKnowledge, + readKnowledgeScratch, + saveRepositoryKnowledgeCache, + validateRepositoryKnowledge, + writeKnowledgeScratch +} from "../src/repository/knowledge.js"; + +test("repository knowledge round trips through the agent scratch file", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "ghbot-knowledge-")); + try { + await writeKnowledgeScratch(root, "# Architecture\n\nUse npm test.\n"); + assert.equal(await readKnowledgeScratch(root), "# Architecture\n\nUse npm test.\n"); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } +}); + +test("repository knowledge persists in a repository-level cache file", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "ghbot-knowledge-cache-")); + try { + await saveRepositoryKnowledgeCache("# Tests\n\nRun npm test.\n", root); + assert.equal(await loadRepositoryKnowledge(root), "# Tests\n\nRun npm test.\n"); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } +}); + +test("repository knowledge rejects credentials and oversized content", () => { + assert.throws( + () => validateRepositoryKnowledge("-----BEGIN PRIVATE KEY-----\nsecret"), + /credential or private key/ + ); + assert.throws(() => validateRepositoryKnowledge(`sk-${"a".repeat(40)}`), /credential/); + assert.throws(() => validateRepositoryKnowledge("x".repeat(33 * 1024)), /1-32768 bytes/); +}); diff --git a/test/review-policy.test.ts b/test/review-policy.test.ts index 247fe06..8afd15d 100644 --- a/test/review-policy.test.ts +++ b/test/review-policy.test.ts @@ -11,6 +11,7 @@ import { parseReviewStateMarker } from "../src/review/policy.js"; import { config } from "../src/config.js"; +import { isRecheckComment } from "../src/review/processor.js"; const cleanDecision: ReviewDecision = { review: [], @@ -25,7 +26,8 @@ const cleanDecision: ReviewDecision = { }; test("clean reviews approve under the default policy", () => { - assert.equal(config.reviewPolicy, "require_approval"); + assert.equal(config.reviewPolicy, "allow"); + assert.equal(config.reviewStrictness, "normal"); assert.deepEqual(evaluateReviewDecision(cleanDecision), { event: "APPROVE", blocksMerge: false, @@ -34,15 +36,15 @@ test("clean reviews approve under the default policy", () => { }); }); -test("ordinary review notes require administrator approval by default", () => { +test("ordinary review notes approve under the default policy", () => { const decision = { ...cleanDecision, review: [{ path: "src/a.ts", line: 1, title: "Check this", body: "Concrete note" }] }; assert.deepEqual(evaluateReviewDecision(decision), { - event: "COMMENT", + event: "APPROVE", blocksMerge: false, - requiresAdminApproval: true, + requiresAdminApproval: false, outcome: "pass" }); }); @@ -94,11 +96,15 @@ test("review state markers round trip", () => { }); assert.deepEqual( parseReviewStateMarker(formatReviewStateMarker("strict", disposition, 1, 0)), - { mode: "strict", outcome: "pass", requiresAdminApproval: true } + { mode: "strict", outcome: "pass", requiresAdminApproval: false } ); assert.deepEqual( - parseReviewExternalId(formatReviewExternalId("lenient", disposition)), - { mode: "lenient", outcome: "pass", requiresAdminApproval: true } + parseReviewExternalId(formatReviewExternalId("normal", disposition)), + { mode: "normal", outcome: "pass", requiresAdminApproval: false } + ); + assert.deepEqual( + parseReviewExternalId("ghbot-review:v1:mode=lenient:outcome=pass:requires-admin=false"), + { mode: "normal", outcome: "pass", requiresAdminApproval: false } ); }); @@ -110,6 +116,13 @@ test("branch glob stars respect slash boundaries", () => { assert.equal(branchPatternToRegExp("release/?.x").test("release/1.x"), true); }); +test("only the exact recheck command triggers a manual review", () => { + assert.equal(isRecheckComment("/recheck"), true); + assert.equal(isRecheckComment(" /recheck\n"), true); + assert.equal(isRecheckComment("/lenient-check"), false); + assert.equal(isRecheckComment("/recheck something"), false); +}); + test("only the latest decisive review per user can approve the current head", () => { assert.deepEqual( approvedLoginsForHead(