diff --git a/README-zh.md b/README-zh.md index 27cc66c..6f32e5c 100644 --- a/README-zh.md +++ b/README-zh.md @@ -128,7 +128,7 @@ prompt 还会收到由宿主通过 GitHub 验证的请求者上下文:评论 自动冲突修复仅处理当前 head 未变化的同仓库 PR。外部 fork 的 `pull_request_target` 仍保持纯 GitHub API 审核,不 checkout 贡献者代码;贡献者启用 **Allow edits from maintainers** 后,maintainer 可以显式评论 `/conflict`,由可信的评论 workflow checkout PR head,并使用绑定已审核 head SHA 的 `--force-with-lease` 推送,因此贡献者新提交的 commit 不会被覆盖。旧 head、非冲突状态、关闭 maintainer edits 和未通过审核的 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` 并重新完整审核,不会把修复前的结论直接当作批准。 +应用改动后,ghbot 检查未合并路径,并且只对 AI 修改过的文件运行 `git diff --check`。配置验证命令后,无凭据容器会以只读方式挂载候选内容,复制到一次性的工作目录,再运行 `CONFLICT_TEST_COMMAND`。基础设施错误会直接报告,不再误交给 goose 当作代码问题修复;只有真实的 merge 相关验证失败才允许一次聚焦修改,随后由宿主权威重跑一次。最后再由不带工具权限的 goose 纯对话调用对完整 staged diff 做只读确认。只有确认返回 `safeToCommit=true`,且远端 PR head 仍与审核 SHA 相同,才会 commit 并 push;同仓库分支普通 push,外部 fork 使用上文所述绑定 SHA 的 force-with-lease。新 commit 会触发 `synchronize` 并重新完整审核,不会把修复前的结论直接当作批准。 ## goose 配置 diff --git a/README.md b/README.md index cf0e161..0359fbd 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ A collaborator with `write`, `maintain`, or `admin` permission can also explicit Automatic conflict repair applies to current same-repository PR heads. External fork commits remain API-only during `pull_request_target`; a maintainer can explicitly run `/conflict` when the contributor enabled **Allow edits from maintainers**. That trusted comment workflow checks out the PR head without persisted credentials and pushes with an explicit `--force-with-lease` tied to the reviewed head SHA, so a newly pushed contributor commit is never overwritten. Stale heads, non-dirty states, disabled maintainer edits, 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. +After applying the proposed files, ghbot verifies there are no unmerged paths and runs `git diff --check` only on AI-touched files. When configured, a credential-free validation container mounts the candidate read-only, copies it to a disposable workspace, and runs `CONFLICT_TEST_COMMAND` there. Infrastructure failures are reported directly instead of being sent to goose as code-repair requests; a genuine merge-related validation failure permits one focused edit pass followed by one authoritative host rerun. A separate tool-free goose prompt then performs the final read-only staged-diff confirmation. The result is committed and pushed only when that confirmation returns `safeToCommit=true` and the remote PR head still matches the reviewed SHA. Same-repository heads use a normal push; external forks use the SHA-pinned force lease described above. The new commit triggers a fresh `synchronize` review; the old decision is not reused as approval. ## goose configuration diff --git a/src/ai/gooseCli.ts b/src/ai/gooseCli.ts index 2ecac38..a8e2fa0 100644 --- a/src/ai/gooseCli.ts +++ b/src/ai/gooseCli.ts @@ -12,10 +12,13 @@ const GOOSE_RUN_TIMEOUT_MS = 10 * 60 * 1000; const GOOSE_DOCKER_IMAGE = "node:24-bookworm"; const GOOSE_DOCKER_VERSION = "v1.46.0"; const GOOSE_CONTAINER_PATH = "/usr/local/bin/goose"; +const ISOLATED_VALIDATION_WORKSPACE = "/tmp/ghbot-validation-workspace"; const GOOSE_CONTAINER_BOOTSTRAP = [ "set -eu", "cleanup_workspace() { chmod -R a+rwX /workspace 2>/dev/null || true; }", "trap cleanup_workspace EXIT", + '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", ` 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`, @@ -30,11 +33,23 @@ const GOOSE_WORKSPACE_PERMISSION_SCRIPT = [ "set -eu", "find /workspace \\( -type d -o -type f \\) -uid 0 -exec chmod a+rwX {} +" ].join("\n"); +const ISOLATED_VALIDATION_BOOTSTRAP = [ + "set -eu", + 'mkdir -p "$HOME"', + `validation_workspace="${ISOLATED_VALIDATION_WORKSPACE}"`, + 'mkdir -p "$validation_workspace"', + 'cp -R --no-preserve=ownership /workspace/. "$validation_workspace/"', + 'chmod -R u+rwX "$validation_workspace"', + 'cd "$validation_workspace"', + 'git config --global --add safe.directory "$validation_workspace"', + 'exec sh -lc "$1"' +].join("\n"); export async function runGoosePrompt( prompt: string, options: { workingDirectory?: string; + timeoutMs?: number; } = {} ): Promise { if (!config.gooseApiKey) { @@ -72,7 +87,12 @@ export async function runGoosePrompt( ); try { - const stdout = await runGoose(args, buildGooseEnv(tempDir), workingDirectory); + const stdout = await runGoose( + args, + buildGooseEnv(tempDir), + workingDirectory, + options.timeoutMs + ); return extractGooseFinalText(stdout); } finally { await fs.rm(tempDir, { recursive: true, force: true }); @@ -163,11 +183,7 @@ export async function runIsolatedWorkspaceCommand( } throw error; } finally { - try { - await removeDockerContainer(containerName, realWorkingDirectory); - } finally { - await restoreAgentWorkspacePermissions(realWorkingDirectory); - } + await removeDockerContainer(containerName, realWorkingDirectory); } } @@ -310,7 +326,7 @@ export function buildIsolatedWorkspaceCommandDockerArgs(params: { "--cap-drop", "ALL", "--mount", - `type=bind,source=${params.realWorkingDirectory},target=/workspace`, + `type=bind,source=${params.realWorkingDirectory},target=/workspace,readonly`, "--workdir", "/workspace", "--env", @@ -320,6 +336,8 @@ export function buildIsolatedWorkspaceCommandDockerArgs(params: { GOOSE_DOCKER_IMAGE, "sh", "-lc", + ISOLATED_VALIDATION_BOOTSTRAP, + "ghbot-validation", params.command ]; } @@ -389,9 +407,10 @@ function normalizeBaseUrl(value: string | undefined): string { async function runGoose( args: string[], extraEnv: Record, - workingDirectory: string + workingDirectory: string, + timeoutMs?: number ): Promise { - return runProcess("goose", args, extraEnv, workingDirectory, "goose process"); + return runProcess("goose", args, extraEnv, workingDirectory, "goose process", timeoutMs); } async function runProcess( @@ -407,7 +426,7 @@ async function runProcess( logger.info( { cmd: command, - args: redactPrompt(args), + args: redactProcessArgs(args, label), timeoutMs }, `Spawning ${label}.` @@ -429,7 +448,10 @@ async function runProcess( finished = true; child.kill("SIGTERM"); setTimeout(() => child.kill("SIGKILL"), 5_000).unref(); - reject(new Error(`${label} timed out after ${timeoutMs}ms.`)); + reject(Object.assign( + new Error(`${label} timed out after ${timeoutMs}ms.`), + { stdout, stderr } + )); }, timeoutMs); child.stdout.on("data", (chunk: Buffer | string) => { @@ -438,7 +460,7 @@ async function runProcess( child.stderr.on("data", (chunk: Buffer | string) => { const text = chunk.toString(); stderr += text; - streamStderr(text); + streamStderr(text, label); }); child.on("error", (error) => { if (finished) { @@ -464,7 +486,7 @@ async function runProcess( reject( Object.assign( - new Error(`goose exited with code ${code ?? "null"} and signal ${signal ?? "null"}.`), + new Error(`${label} exited with code ${code ?? "null"} and signal ${signal ?? "null"}.`), { code, signal, stdout, stderr } ) ); @@ -587,16 +609,29 @@ function stripMarkdownFence(value: string): string { } function redactPrompt(args: string[]): string[] { - const promptIndex = args.indexOf("--text") + 1; + const textIndex = args.indexOf("--text"); + if (textIndex < 0) { + return [...args]; + } + const promptIndex = textIndex + 1; return args.map((arg, index) => index === promptIndex ? `[goose prompt: ${arg.length} chars]` : arg ); } -function streamStderr(text: string): void { +export function redactProcessArgs(args: string[], label: string): string[] { + const redacted = redactPrompt(args); + if (label === "isolated repository validation" && redacted.length > 0) { + const commandIndex = redacted.length - 1; + redacted[commandIndex] = `[validation command: ${args[commandIndex]?.length ?? 0} chars]`; + } + return redacted; +} + +function streamStderr(text: string, label: string): void { for (const line of text.replace(/\r\n/g, "\n").split("\n")) { if (line.trim()) { - process.stderr.write(`[goose stderr] ${line}\n`); + process.stderr.write(`[${label} stderr] ${line}\n`); } } } diff --git a/src/github/botIdentity.ts b/src/github/botIdentity.ts new file mode 100644 index 0000000..d2396a5 --- /dev/null +++ b/src/github/botIdentity.ts @@ -0,0 +1,8 @@ +export function formatBotDisplayName(value: string | undefined): string { + const trimmed = value?.trim().replace(/^@/, ""); + if (!trimmed || trimmed.toLowerCase() === "ghbot") { + return "goose"; + } + const botLogin = /^(.*?)\[bot\]$/i.exec(trimmed); + return botLogin?.[1]?.trim() ? `${botLogin[1].trim()} bot` : trimmed; +} diff --git a/src/review/conflictResolver.ts b/src/review/conflictResolver.ts index 28a9bf0..e8ac316 100644 --- a/src/review/conflictResolver.ts +++ b/src/review/conflictResolver.ts @@ -4,7 +4,7 @@ import fs from "node:fs/promises"; import path from "node:path"; import type { Octokit } from "@octokit/rest"; import { z } from "zod"; -import { runGooseAgent, runIsolatedWorkspaceCommand } from "../ai/gooseCli.js"; +import { runGooseAgent, runGoosePrompt, runIsolatedWorkspaceCommand } from "../ai/gooseCli.js"; import { createRepositorySnapshot } from "../chat/processor.js"; import { config } from "../config.js"; import { logger } from "../logger.js"; @@ -283,20 +283,27 @@ export async function resolvePullRequestConflicts( let validationSummary: string | undefined; if (config.conflictTestCommand) { - let validation = await runIsolatedWorkspaceCommand( + let validation = await runConflictValidation( config.conflictTestCommand, snapshot, - { timeoutMs: remainingConflictTime(resolutionStartedAt, CONFLICT_VALIDATION_TIMEOUT_MS) } + resolutionStartedAt ); validationSummary = formatValidationResult(config.conflictTestCommand, validation); if (validation.code !== 0) { const previousAgent = afterAgent; - await runGooseAgent(buildValidationRepairPrompt({ - testCommand: config.conflictTestCommand, - output: validationSummary - }), snapshot, { - timeoutMs: remainingConflictTime(resolutionStartedAt, CONFLICT_CORRECTION_AGENT_TIMEOUT_MS) - }); + try { + await runGooseAgent(buildValidationRepairPrompt({ + testCommand: config.conflictTestCommand, + output: validationSummary + }), snapshot, { + timeoutMs: remainingConflictTime(resolutionStartedAt, CONFLICT_CORRECTION_AGENT_TIMEOUT_MS) + }); + } catch (error) { + if (error instanceof Error && error.message.toLowerCase().includes("timed out")) { + throw new Error("validation goose correction timed out.", { cause: error }); + } + throw error; + } afterAgent = await inventorySnapshot(snapshot); const validationRepairChanges = diffSnapshotInventories(previousAgent, afterAgent); if (validationRepairChanges.length === 0) { @@ -327,10 +334,10 @@ export async function resolvePullRequestConflicts( `git diff --check failed after goose validation correction: ${commandFailureOutput(repairedDiffCheck)}` ); } - validation = await runIsolatedWorkspaceCommand( + validation = await runConflictValidation( config.conflictTestCommand, snapshot, - { timeoutMs: remainingConflictTime(resolutionStartedAt, CONFLICT_VALIDATION_TIMEOUT_MS) } + resolutionStartedAt ); validationSummary = formatValidationResult(config.conflictTestCommand, validation); if (validation.code !== 0) { @@ -352,17 +359,25 @@ export async function resolvePullRequestConflicts( } const finalStatus = await runCommand("git", ["status", "--short"], worktree, gitEnv); const beforeConfirmation = await inventorySnapshot(snapshot); - const confirmation = await confirmFinalResolution({ - pullNumber: params.pullNumber, - baseBranch: params.baseBranch, - headBranch: params.headBranch, - conflictFiles, - changedFiles: agentChanges, - status: finalStatus, - diff: finalDiff, - repositoryKnowledge: knowledge, - validationSummary - }, snapshot, remainingConflictTime(resolutionStartedAt, CONFLICT_CONFIRMATION_TIMEOUT_MS)); + let confirmation; + try { + confirmation = await confirmFinalResolution({ + pullNumber: params.pullNumber, + baseBranch: params.baseBranch, + headBranch: params.headBranch, + conflictFiles, + changedFiles: agentChanges, + status: finalStatus, + diff: finalDiff, + repositoryKnowledge: knowledge, + validationSummary + }, remainingConflictTime(resolutionStartedAt, CONFLICT_CONFIRMATION_TIMEOUT_MS)); + } catch (error) { + if (error instanceof Error && error.message.toLowerCase().includes("timed out")) { + throw new Error("final goose confirmation timed out.", { cause: error }); + } + throw error; + } const afterConfirmation = await inventorySnapshot(snapshot); if (diffSnapshotInventories(beforeConfirmation, afterConfirmation).length > 0) { throw new Error("Final goose confirmation modified the workspace during its read-only pass."); @@ -485,7 +500,7 @@ export function buildConflictDiffCheckArgs(changedFiles: string[]): string[] { return ["diff", "--check", "--cached", "--", ...changedFiles]; } -export function describeConflictResolutionFailure(error: unknown): string { +export function describeConflictResolutionFailure(error: unknown, actorName = "goose"): string { const message = error instanceof Error ? error.message.toLowerCase() : ""; if (message.includes("refusing to merge unrelated histories") || message.includes("shallow")) { return "Conflict repair could not prepare the merge because the PR checkout did not contain enough Git history. No commit was pushed."; @@ -509,8 +524,23 @@ export function describeConflictResolutionFailure(error: unknown): string { ) { return "The contributor branch changed before the resolved commit could be pushed, so the safe force lease rejected the update. Run /conflict again on the latest head. No commit was pushed."; } + if (message.includes("conflict validation infrastructure failed")) { + return "The isolated validation environment failed before repository checks could complete. No code-repair pass was attempted and no commit was pushed."; + } + if (message.includes("isolated conflict validation timed out")) { + return "The isolated repository validation exceeded its 7-minute limit. No commit was pushed."; + } + if (message.includes("validation goose correction timed out")) { + return "The focused validation-repair pass exceeded its 5-minute limit. No commit was pushed."; + } + if (message.includes("final goose confirmation timed out")) { + return "The final read-only safety confirmation exceeded its 5-minute limit. No commit was pushed."; + } + if (message.includes("final goose confirmation did not return")) { + return "The final read-only safety confirmation returned an invalid result. No commit was pushed."; + } if (message.includes("final goose confirmation rejected") || message.includes("validation command")) { - return "goose produced a candidate resolution, but the configured validation or final safety confirmation rejected it. No commit was pushed."; + return `${actorName} produced a candidate resolution, but the configured validation or final safety confirmation rejected it. No commit was pushed.`; } if (message.includes("conflict resolution timed out")) { return "Conflict repair exceeded its 25-minute total time budget and stopped safely. No commit was pushed."; @@ -527,7 +557,7 @@ export function describeConflictResolutionFailure(error: unknown): string { if (message.includes("resolved staged diff contains")) { return "The AI-touched conflict-resolution diff exceeded the configured patch-size limit, so final confirmation was not attempted. No commit was pushed."; } - return "goose could not safely complete and validate the conflict resolution. The Actions log contains the exact failure stage, and no commit was pushed."; + return `${actorName} could not safely complete and validate the conflict resolution. The Actions log contains the exact failure stage, and no commit was pushed.`; } function isSafeGitHubRepository(value: string): boolean { @@ -587,7 +617,8 @@ export function buildValidationRepairPrompt(input: { return [ "Correct the current conflict-resolution workspace using the final safety review below.", "Fix only merge-related validation failures, compatibility problems, callers, tests, generated lockfiles, configuration, or documentation needed to make the merged result coherent. Preserve the pull request intent and the target branch behavior; do not add unrelated features or refactors.", - `Run this exact trusted repository validation command after editing and keep correcting the relevant files until it passes: ${input.testCommand}`, + `After this focused edit pass, the host will rerun this exact trusted repository validation command in a fresh isolated copy: ${input.testCommand}`, + "Do not install dependencies or run the full validation command yourself. Use the supplied failure output to make only the directly relevant corrections; the host owns the authoritative rerun.", "Do not commit, push, change Git configuration, modify repository knowledge, or weaken/delete tests merely to hide a real regression.", "Trusted isolated validation result:", input.output.slice(0, 20_000), @@ -690,8 +721,8 @@ async function confirmFinalResolution(input: { diff: string; repositoryKnowledge: string; validationSummary?: string; -}, snapshot: string, timeoutMs: number) { - const raw = await runGooseAgent([ +}, timeoutMs: number) { + const raw = await runGoosePrompt([ "You are the final safety reviewer for an automated Git conflict resolution.", "This is a read-only confirmation pass. Do not edit, add, delete, format, install dependencies, or rerun tests.", "Review the staged diff below. Confirm only when the merge conflict is correctly resolved, related compatibility edits are coherent, no unrelated or suspicious changes are present, and committing this exact result is safe.", @@ -723,7 +754,7 @@ async function confirmFinalResolution(input: { "", "Complete staged diff:", input.diff - ].join("\n"), snapshot, { timeoutMs }); + ].join("\n"), { timeoutMs }); return parseFinalConfirmation(raw); } @@ -925,6 +956,69 @@ function formatValidationResult( ].join("\n"); } +export function isValidationInfrastructureFailure(result: { + code: number; + stdout: string; + stderr: string; +}): boolean { + if ([125, 137, 143].includes(result.code)) { + return true; + } + const output = [result.stderr, result.stdout].join("\n").toLowerCase(); + return [ + "detected dubious ownership", + "cannot connect to the docker daemon", + "permission denied while trying to connect to the docker api", + "permission denied while trying to connect to the docker daemon socket", + "docker.sock: connect: permission denied", + "error response from daemon", + "oci runtime", + "no space left on device", + "temporary failure in name resolution", + "network is unreachable", + "getaddrinfo eai_again", + "npm error code eai_again", + "npm err! code eai_again", + "npm error code enetwork", + "npm err! code enetwork", + "npm error code econnreset", + "npm err! code econnreset", + "npm error code etimedout", + "npm err! code etimedout", + "npm error code e401", + "npm err! code e401", + "npm error code e403", + "npm err! code e403", + "unable to get local issuer certificate", + "self-signed certificate", + "certificate has expired", + "pull access denied", + "toomanyrequests" + ].some((pattern) => output.includes(pattern)); +} + +async function runConflictValidation( + command: string, + snapshot: string, + resolutionStartedAt: number +): Promise<{ code: number; stdout: string; stderr: string }> { + let result: { code: number; stdout: string; stderr: string }; + try { + result = await runIsolatedWorkspaceCommand(command, snapshot, { + timeoutMs: remainingConflictTime(resolutionStartedAt, CONFLICT_VALIDATION_TIMEOUT_MS) + }); + } catch (error) { + if (error instanceof Error && error.message.toLowerCase().includes("timed out")) { + throw new Error("isolated conflict validation timed out.", { cause: error }); + } + throw error; + } + if (isValidationInfrastructureFailure(result)) { + throw new Error(`Conflict validation infrastructure failed: ${commandFailureOutput(result)}`); + } + return result; +} + function remainingConflictTime(startedAt: number, perOperationLimitMs: number): number { const remaining = CONFLICT_TOTAL_TIMEOUT_MS - (Date.now() - startedAt); if (remaining <= 0) { diff --git a/src/review/processor.ts b/src/review/processor.ts index b72e73b..2a14d0a 100644 --- a/src/review/processor.ts +++ b/src/review/processor.ts @@ -2,6 +2,7 @@ import type { Octokit } from "@octokit/rest"; import { config } from "../config.js"; import { requiredChecksAreGreen } from "../github/checks.js"; import { postPermissionDeniedComment } from "../github/commandFeedback.js"; +import { formatBotDisplayName } from "../github/botIdentity.js"; import { collectValidNewLines, toDiffPosition } from "../github/diff.js"; import { logger } from "../logger.js"; import { withRetry } from "../retry.js"; @@ -35,6 +36,10 @@ export const RECHECK_COMMENT_COMMAND = "/recheck"; export const CONFLICT_COMMENT_COMMAND = "/conflict"; const REVIEW_PROGRESS_MARKER_PREFIX = "