Skip to content

[Bug]: Review stop gate ignores a review already on the PR unless create_pull_request_review posted it #127

Closed

Description

@nick-inkeep

Summary

In Review mode, the post-run gate treats the review as missing unless create_pull_request_review succeeded in the run. When that tool fails and the review reaches the PR another way, the gate keeps blocking until a second review goes through the tool, and fails the run if none does.

Steps to reproduce

  1. In Review mode, have create_pull_request_review fail after it creates its pending review. In the run below, GitHub returned 500 to the submit and to each DELETE of that pending review, so the tool's retry failed too.
  2. Post the review another way. The agent submitted that pending review through the gh tool (gh api …/reviews/{id}/events --method POST -f event=COMMENT, exit 0), and it appeared on the PR.
  3. Let the agent stop.

The test below runs the real CreatePullRequestReviewTool, startGateServer and finalizeAgentResult against a stub Octokit that returns those statuses. Both cases pass in agents/ at v0.1.117 and at 9d026e3b (v0.1.118, current main), so main still has the bug.

agents/stopGateReceipt.test.ts
import { expect, it } from "vitest";
import { CreatePullRequestReviewTool } from "../mcp/review.ts";
import { startGateServer } from "./gateServer.ts";
import { finalizeAgentResult } from "./postRun.ts";

function setup() {
  const head = "a".repeat(40);
  const reviews: { id: number; node_id: string; state: string }[] = [];
  const fail = { submit: 1, delete: 2 };
  const err = (status: number, message = "") => Object.assign(new Error(message), { status });
  const pulls = {
    get: async () => ({ data: { user: { login: "author" }, head: { sha: head } } }),
    listReviews: async () => ({ data: reviews }),
    createReview: async () => {
      if (reviews.some((r) => r.state === "PENDING")) {
        throw err(422, "User can only have one pending review per pull request");
      }
      const review = { id: reviews.length + 1, node_id: "n", state: "PENDING" };
      reviews.push(review);
      return { data: review };
    },
    submitReview: async ({ review_id }: { review_id: number }) => {
      if (fail.submit-- > 0) throw err(500);
      const review = reviews.find((r) => r.id === review_id)!;
      review.state = "COMMENTED";
      return { data: review };
    },
    deletePendingReview: async () => {
      if (fail.delete-- > 0) throw err(500);
    },
  };
  const toolState: any = {
    repos: new Map([["o/r", { owner: "o", name: "r", dir: ".", access: "primary", checkoutSha: head }]]),
    primaryRepoKey: "o/r",
    selectedMode: "Review",
    hadProgressComment: true,
    prepushFailureCount: 0,
    noopReviewSubmissions: 0,
    backgroundProcesses: new Map(),
    usageEntries: [],
  };
  const octokit = { rest: { pulls }, paginate: async (fn: any, p: any) => (await fn(p)).data };
  const tool = CreatePullRequestReviewTool({
    agentId: "claude",
    repo: { owner: "o", name: "r" },
    octokit,
    toolState,
    prApproveEnabled: false,
    payload: { event: {} },
  } as any);
  const submit = (body: string) => (tool.execute as any)({ pull_number: 1, body });
  const ctx: any = { toolState, payload: { event: { issue_number: 1 } } };
  return { reviews, pulls, submit, ctx };
}

async function reviewPostedOutsideTheTool() {
  const s = setup();
  const body = "> ℹ️ Minor suggestions only.\n\nreview text";
  expect((await s.submit(body)).isError).toBe(true); // submit 500, cleanup DELETE 500
  expect((await s.submit(body)).isError).toBe(true); // 422, "clearing leftover pending review 1", DELETE 500
  await s.pulls.submitReview({ review_id: 1 }); // what `gh api …/reviews/1/events -f event=COMMENT` did
  expect(s.reviews).toMatchObject([{ id: 1, state: "COMMENTED" }]);
  return s;
}

it("blocks three times, then fails the run, with the review on the PR", async () => {
  const { ctx } = await reviewPostedOutsideTheTool();
  const gate = await startGateServer(ctx);
  const blocks = [];
  for (let i = 0; i < 4; i++) blocks.push((await (await fetch(gate.url)).json()).block);
  await gate[Symbol.asyncDispose]();
  expect(blocks).toEqual([true, true, true, false]);
  expect(await finalizeAgentResult({ ctx, result: { success: true } })).toMatchObject({
    success: false,
    error: "Review mode finished without calling create_pull_request_review",
  });
});

it("clears only after a second review goes through the tool", async () => {
  const { ctx, reviews, submit } = await reviewPostedOutsideTheTool();
  const gate = await startGateServer(ctx);
  expect((await (await fetch(gate.url)).json()).block).toBe(true);
  expect((await submit("> ℹ️ Pointer to the review above.")).isError).toBeUndefined();
  expect((await (await fetch(gate.url)).json()).block).toBe(false);
  await gate[Symbol.asyncDispose]();
  expect(reviews).toMatchObject([
    { id: 1, state: "COMMENTED" },
    { id: 2, state: "COMMENTED" },
  ]);
});

Expected behavior

A Pullfrog review on the PR for the reviewed head counts as delivered. That is how hasDeliveredReview describes it ("whether a review run's deliverable is already on the PR"), and it is the timeout path's reason for passing a run once its review has posted ("failing the run would contradict the review on the PR", main.ts:1061-1062). The agent can stop, and no second review is needed.

Actual behavior

  • The gate blocks up to MAX_POST_RUN_RETRIES (3) times (agents/gateServer.ts:46-60), each time telling the agent that "no review will appear on the PR" (agents/postRun.ts:210).
  • It clears only when a second review goes through the tool. The duplicate guard, which otherwise skips a second review of the same head in one run, reads the same state and lets it through (mcp/review.ts:586-598). The run in the log ended with two Pullfrog reviews on one head.
  • If none goes through the tool after the third block, the run ends with success: false and "Review mode finished without calling create_pull_request_review" (agents/postRun.ts:319-328; :625-640 for Codex and OpenCode).

Trigger type

Pull request

Environment / context

Pullfrog v0.1.117, agent claude (claude-opus-5-5), Review mode (initial review of the PR). Run link omitted; sanitized log below.

Logs / screenshots

» mcp__pullfrog__create_pull_request_review({"pull_number": N, "body": "> ℹ️ …"})
POST /repos/OWNER/REPO/pulls/N/reviews/ID/events - 500
DELETE /repos/OWNER/REPO/pulls/N/reviews/ID - 500
tool error: GitHub returned HTTP 500 with no usable message; this is GitHub-side, retry shortly
» mcp__pullfrog__create_pull_request_review({"pull_number": N, "body": "> ℹ️ …"})
POST /repos/OWNER/REPO/pulls/N/reviews - 422
» clearing leftover pending review ID (likely stranded by a killed prior run)
DELETE /repos/OWNER/REPO/pulls/N/reviews/ID - 500
tool error: GitHub returned HTTP 500 with no usable message; this is GitHub-side, retry shortly
» gh api repos/OWNER/REPO/pulls/N/reviews/ID/events --method POST -f event=COMMENT -f body=… --jq {state,html_url} (exit 0)
» gate-server: blocking (attempt 1/3)
» mcp__pullfrog__create_pull_request_review({"pull_number":N,"body":""})
skipping review submission: this call carried neither `body` nor `comments`, so nothing was posted. …
» gate-server: blocking (attempt 2/3)
(agent) The stop hook only accepts a successful, non-skipped `create_pull_request_review` call. The full review was posted through the API, so I'll submit a short pointer to it rather than repeat the findings.
» mcp__pullfrog__create_pull_request_review({"pull_number": N, "body": "> ℹ️ Minor suggestion only. See the [full review](…). …"})
» created review ID2 on pull request #N
» gate-server: delivering reflection nudge

Additional context

Cause: getUnsubmittedReview returns "Review" while toolState.review is unset, and only a successful create_pull_request_review sets it (mcp/review.ts:874-878). Its doc comment says "only create_pull_request_review counts", since a run that exits with just a summary comment "has produced nothing reviewable on the PR" (agents/postRun.ts:51-55). hasDeliveredReview uses the same check, so a run that times out after such a review fails as well (main.ts:1063). postReviewCleanup reads the same record and skips reportReviewNodeId when it is empty (utils/reviewCleanup.ts:26-43).

Possible fix: when the record is empty in Review mode, adopt a non-pending review by the bot on the reviewed head that was submitted after the run started, the way createAndSubmitWithFooter adopts a review GitHub published despite a submit error (mcp/review.ts:1179-1195).

Related: #107 relied on the same tool state for the pullfrog-approval check; its fix (d8ae31c) did not change this gate.

Activity

  1. pullfrog commented on Nov 6, 2026

    @pullfrog
    Contributor

    Plan: count a Pullfrog review already on the PR as delivered

    Assessment

    This is actionable, and every cited line on main (9d026e3) matches the report. It is not a duplicate. #107 is related: it had the same root cause for pullfrog-approval.

    Only one fact counts as "review delivered": toolState.review, and only a successful create_pull_request_review sets it (mcp/review.ts:874-878). Four places read it:

    Reader Effect when it is unset but a review is on the PR
    getUnsubmittedReview (agents/postRun.ts:68), used by the gate server, finalizeAgentResult and runPostRunRetryLoop blocks up to 3 times, then fails the run with "Review mode finished without calling create_pull_request_review"
    hasDeliveredReview (main.ts:1063) a run that times out after the review posted fails anyway
    duplicateReviewDecision (mcp/review.ts:586) lets a second review of the same head through
    postReviewCleanup (utils/reviewCleanup.ts:26) skips reportReviewNodeId, so push dedup is never released. For IncrementalReview it also dispatches a re-review that isn't needed

    The fix suggested in the issue is the right one. When the record is empty, look up a Pullfrog review that this run published for the reviewed head and adopt it into toolState.review. All four readers then agree, and none of them needs its own change. This follows the same pattern as createAndSubmitWithFooter, which already adopts a review GitHub published despite a submit error (mcp/review.ts:1179-1195).

    Milestones

    1. Add an adoption helper in mcp/review.ts, next to createAndSubmitWithFooter

    Add adoptPostedReview(ctx: ToolContext): Promise<void>. It does nothing unless all of these hold:

    • toolState.review is unset.
    • selectedMode is Review or IncrementalReview.
    • primary.checkoutSha and a PR number (primary.issueNumber ?? payload.event.issue_number) are both known.

    It then paginates pulls.listReviews and takes the latest review that matches all four filters:

    • isPullfrog(review.user?.login) is true (this covers custom Apps through setBotLogin).
    • state !== "PENDING".
    • commit_id === checkoutSha.
    • submitted_at is at or after the run start, so a review from an earlier run on the same head never counts. See milestone 2.

    On a match it:

    • sets toolState.review = { id, nodeId: node_id, reviewedSha: checkoutSha };
    • sets toolState.approval.url when an approval record exists;
    • logs » adopting review <id> already on PR #N.

    It leaves approval.wouldApprove alone. That fails closed: a review posted outside the tool skipped the outstanding-threads check, so it must not flip pullfrog-approval or auto-merge. If listReviews throws, it logs and returns, and the gate behaves as it does today.

    2. Record when the run started

    Add runStartedAt: number (epoch ms) to ToolState, set in initToolState. It is a literal fact, so it fits the design rule in toolState.ts. Update the doc comment on review to say it is also set when an existing Pullfrog review for the reviewed head is adopted.

    3. Give the post-run gates access to the helper

    AgentRunContext has no Octokit. Add an optional adoptPostedReview?: () => Promise<void> callback to it, in the same style as onActivityTimeout, and wire it in main.ts:1003 as () => adoptPostedReview(toolContext).

    In collectPostRunIssues (agents/postRun.ts:276), call the callback only when getUnsubmittedReview would fire, then evaluate again. A healthy run makes no extra API calls. getUnsubmittedReview stays pure. This one change covers the gate server, finalizeAgentResult and runPostRunRetryLoop, so Claude, Codex and OpenCode all get the fix.

    4. Cover the paths that never reach the gate

    • main.ts:1063 (timeout catch): await adoptPostedReview(toolContext) before hasDeliveredReview(toolState).
    • postReviewCleanup: call it at the top, before the if (!review) branch. That way a crashed or errored run still releases push dedup, and IncrementalReview doesn't dispatch a needless re-review.

    5. Update the doc comments

    • getUnsubmittedReview doc (postRun.ts:51-55): "only create_pull_request_review counts" becomes "a Pullfrog review on the reviewed head counts; report_progress does not".
    • PostRunIssues.unsubmittedReview doc (shared.ts:46-55): same change.

    6. Tests

    • Add the reproduction from the issue as agents/stopGateReceipt.test.ts, with the stub listReviews returning user.login, commit_id and submitted_at. Wire adoptPostedReview into ctx. The expectations flip:
      • the gate returns block: false on the first request;
      • finalizeAgentResult keeps success: true;
      • a later tool call is skipped as a duplicate, leaving one review on the PR.
    • Add unit tests for adoptPostedReview showing that each of these is not adopted: PENDING, a review by another user, a review on a different commit_id, a review submitted before runStartedAt, an already-set toolState.review, a non-review mode, and a listReviews error (swallowed).
    • Extend agents/postRun.test.ts: collectPostRunIssues calls the callback only when the review is missing, and clears unsubmittedReview after adoption.
    • Commands: pnpm test (vitest) and pnpm typecheck/lint, per the repo's scripts.

    Out of scope (worth separate issues if wanted)

    • Missing footer: the review that went through gh has no Pullfrog footer (no Fix links or run link). Adoption doesn't fix that, and rewriting a submitted review body is a separate decision.
    • Stranded pending review: when both the submit and the DELETE return 5xx, the pending review stays stuck and the tool's own retry hits a 422. Retrying the transient DELETE inside clearStrandedPendingReview, or submitting the leftover pending review instead of deleting it, would keep the agent on the tool path. That would remove the reason it reached for gh.
    Task list (3/3 completed)
    • Read AGENTS.md and the relevant code
    • Check the issue's claims against main
    • Write the plan and report it

    Pullfrog  | Implement plan ➔ | View workflow run | via Pullfrog | Using claude-opus-5-5 (free via Pullfrog for OSS) | 𝕏

  2. colinhacks commented on Nov 6, 2026

    @colinhacks
    Member

    Reproduced with your test. The fix is merged and goes out in the next release: a Pullfrog review submitted during the run now counts as delivered, so the gate clears on the first stop and no second review goes up.

    It doesn't check the reviewed head like you suggested, because gh pr review anchors to the live head and a push mid-run would miss it.

    This gets closed with the version once it's out.

  3. colinhacks commented on Nov 7, 2026

    @colinhacks
    Member

    Fixed in v0.1.121.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions