From c03a50d3ca7226ce74cfb93b09708e63a2a6ad20 Mon Sep 17 00:00:00 2001 From: Daniil Pokrovsky Date: Fri, 4 Dec 2026 22:17:59 +0700 Subject: [PATCH] feat: implement local-verify-review-agents-must-return-json-ve - Verify/review agents must return JSON verdict, not ReportFindings tool output --- .../src/harnesses/claude-code.ts | 4 ++ packages/agent-harness/src/types.ts | 8 ++++ .../agent-harness/tests/harnesses.test.ts | 12 ++++++ packages/code/prompts/review.md | 2 +- .../src/lib/agent/run-harness-finalize.ts | 10 ++--- packages/code/src/lib/agent/verify.ts | 20 ++++++++-- packages/code/src/lib/review/address.ts | 4 +- packages/code/src/lib/review/auto-merge.ts | 1 + .../code/src/lib/review/auto-review-loop.ts | 9 +++-- .../code/src/lib/review/verdict-delivery.ts | 16 ++++++++ .../code/src/lib/task/pipeline-registry.ts | 2 +- packages/code/tests/verify-step.test.ts | 37 +++++++++++++++++++ 12 files changed, 111 insertions(+), 14 deletions(-) create mode 100644 packages/code/src/lib/review/verdict-delivery.ts diff --git a/packages/agent-harness/src/harnesses/claude-code.ts b/packages/agent-harness/src/harnesses/claude-code.ts index f260c504f..625b8031f 100644 --- a/packages/agent-harness/src/harnesses/claude-code.ts +++ b/packages/agent-harness/src/harnesses/claude-code.ts @@ -151,6 +151,10 @@ export class ClaudeCodeHarness implements AgentHarness { args.push("--dangerously-skip-permissions"); } + if (options.disallowedTools && options.disallowedTools.length > 0) { + args.push("--disallowedTools", options.disallowedTools.join(",")); + } + if (options.model) { args.push("--model", options.model); } diff --git a/packages/agent-harness/src/types.ts b/packages/agent-harness/src/types.ts index 4e70bad4c..af18fd405 100644 --- a/packages/agent-harness/src/types.ts +++ b/packages/agent-harness/src/types.ts @@ -62,6 +62,14 @@ export interface AgentRunOptions { * MCP-side effects. Prefer per-tool entries where possible. */ allowedTools?: readonly string[]; + /** + * Tools to turn off for this run, using the harness's own tool naming. + * Honored by harnesses with a native deny flag (currently claude-code + * `--disallowedTools`); others ignore it. Used for turns whose answer must + * arrive as final-message text, e.g. review verdicts that must not go through + * a tool-based reporter such as `ReportFindings`. + */ + disallowedTools?: readonly string[]; /** Suppress non-essential console output. */ silent?: boolean; /** Enable verbose logging. */ diff --git a/packages/agent-harness/tests/harnesses.test.ts b/packages/agent-harness/tests/harnesses.test.ts index ab15a7b43..bf24907e7 100644 --- a/packages/agent-harness/tests/harnesses.test.ts +++ b/packages/agent-harness/tests/harnesses.test.ts @@ -1058,3 +1058,15 @@ describe("DeepSeekHarness (official dsh, experimental)", () => { expect(DEEPSEEK_HEADLESS_PROFILE_PATH).toContain("profiles/headless/cordis.patch.yml"); }); }); + +describe("ClaudeCodeHarness disallowedTools", () => { + test("emits --disallowedTools only when requested", () => { + const h = new ClaudeCodeHarness(); + expect(h.buildArgs({ disallowedTools: ["ReportFindings"] })).toEqual([ + "--disallowedTools", + "ReportFindings", + ]); + expect(h.buildArgs({ skipPermissions: true })).not.toContain("--disallowedTools"); + expect(h.buildArgs({ disallowedTools: [] })).toEqual([]); + }); +}); diff --git a/packages/code/prompts/review.md b/packages/code/prompts/review.md index 2260bad25..feb6c4b4e 100644 --- a/packages/code/prompts/review.md +++ b/packages/code/prompts/review.md @@ -103,4 +103,4 @@ Get each fact as far down that ladder as is cheap, and say where it stopped. A f 7. Be constructive and specific in your feedback. 8. Focus on actionable improvements. Never invent a caller, a consumer, or an API. -**IMPORTANT**: Return only the valid JSON object. Do not include Markdown fences or explanatory text. +**IMPORTANT**: Return only the valid JSON object. Do not include Markdown fences or explanatory text. The JSON object must be the final text of your response. Do not report findings through any tool (such as `ReportFindings`): tool-based reports are never read and count as no verdict. diff --git a/packages/code/src/lib/agent/run-harness-finalize.ts b/packages/code/src/lib/agent/run-harness-finalize.ts index 8b50f9f87..c45f7586f 100644 --- a/packages/code/src/lib/agent/run-harness-finalize.ts +++ b/packages/code/src/lib/agent/run-harness-finalize.ts @@ -360,11 +360,10 @@ export async function commitImplementation(state: DeliveryState): Promise runAgentPrompt(prompt, process.cwd(), ctx.harness, ctx.executablePath, { + ...options, label: options?.label ?? state.activeStep ?? "agent", }), getDiff: () => { diff --git a/packages/code/src/lib/agent/verify.ts b/packages/code/src/lib/agent/verify.ts index 45bb4fb33..37e490f5d 100644 --- a/packages/code/src/lib/agent/verify.ts +++ b/packages/code/src/lib/agent/verify.ts @@ -8,6 +8,7 @@ import { parseReviewFeedback, runAgentPrompt, } from "../review/auto-review-loop"; +import { buildVerdictFollowUpPrompt, VERDICT_DELIVERY_NOTE } from "../review/verdict-delivery"; import type { ReviewFeedback, ReviewFeedbackItem, ReviewPriority } from "../../types/auto-review"; import { isShuttingDown } from "../cli/shutdown-state"; import { untrustedContentBlock } from "../prompts/untrusted-content"; @@ -60,7 +61,7 @@ function buildVerifyPrompt(config: VerifyConfig, taskContent: string, diff: stri // external diff here; re-framing the task would nest frames and neutralize the // authentic inner boundary markers. const framedDiff = untrustedContentBlock(`\`\`\`diff\n${diff}\n\`\`\``, "implementation diff"); - return `${instructionsFor(config, cwd)}\n\n## Task\n${taskContent.trimEnd()}\n\n## Implementation diff\n${framedDiff}`; + return `${instructionsFor(config, cwd)}\n\n${VERDICT_DELIVERY_NOTE}\n\n## Task\n${taskContent.trimEnd()}\n\n## Implementation diff\n${framedDiff}`; } /** Build a focused repair prompt for the next implementation run. */ @@ -282,12 +283,25 @@ export async function verifyImplementation( workingDir, state.context.harness, state.context.executablePath, - { label }, + { label, verdict: true }, ); // Parse the verdict without the auto-review approval rule: this step owns // the policy (`minSeverity`), and resolving a contradiction below keeps a // deterministic rejection out of the transient-failure retry below. - feedback = deps.parseFeedback(output, { enforceApproval: false }); + try { + feedback = deps.parseFeedback(output, { enforceApproval: false }); + } catch { + // The review may be fine but its verdict missing or in prose. Ask only + // for the JSON instead of re-running the whole review. + output = await deps.runAgent( + buildVerdictFollowUpPrompt(output), + workingDir, + state.context.harness, + state.context.executablePath, + { label: `${label} verdict`, verdict: true }, + ); + feedback = deps.parseFeedback(output, { enforceApproval: false }); + } break; } catch (error) { if (error instanceof UsageLimitError) throw error; diff --git a/packages/code/src/lib/review/address.ts b/packages/code/src/lib/review/address.ts index 8c55a523d..2e41e6cca 100644 --- a/packages/code/src/lib/review/address.ts +++ b/packages/code/src/lib/review/address.ts @@ -1,3 +1,4 @@ +import { VERDICT_DISALLOWED_TOOLS } from "./verdict-delivery"; import { createReviewAdapter } from "../code-host/review-provider-factory"; import { assertCurrentGitLabOrigin } from "../code-host/change-origin"; /** @@ -121,7 +122,7 @@ export async function runAgent( prompt: string, workDir: string, verbose: boolean, - log: { label?: string; origin?: RunOrigin } = {}, + log: { label?: string; origin?: RunOrigin; verdict?: boolean } = {}, ): Promise { const { harness, path: executablePath } = resolveHarness(); // Wait out any in-progress CLI auto-update swap before spawning, so a @@ -143,6 +144,7 @@ export async function runAgent( workingDir: workDir, model: resolveAgentModel(harness.name), effort: resolveAgentEffort(), + ...(log.verdict ? { disallowedTools: VERDICT_DISALLOWED_TOOLS } : {}), }; const { args: agentArgs, env: agentEnv } = await buildHeadlessAgentInvocation( harness, diff --git a/packages/code/src/lib/review/auto-merge.ts b/packages/code/src/lib/review/auto-merge.ts index 353d15234..eebe74c13 100644 --- a/packages/code/src/lib/review/auto-merge.ts +++ b/packages/code/src/lib/review/auto-merge.ts @@ -953,6 +953,7 @@ async function reviewWithAgent(params: { : await runAgent(prompt, workDir, verbose, { label: MERGE_SAFETY_REVIEW_LOG_LABEL, origin: "auto_merge", + verdict: true, }); if (!run.success) { return { kind: "failed", ran: true, message: "merge-safety agent run failed" }; diff --git a/packages/code/src/lib/review/auto-review-loop.ts b/packages/code/src/lib/review/auto-review-loop.ts index 22455c61e..0f54884c8 100644 --- a/packages/code/src/lib/review/auto-review-loop.ts +++ b/packages/code/src/lib/review/auto-review-loop.ts @@ -10,6 +10,7 @@ * on a review */ +import { VERDICT_DISALLOWED_TOOLS } from "./verdict-delivery"; import { execFileSync } from "child_process"; import { join } from "path"; import { UsageLimitError, resolveExecutablePathWithRetry } from "@devintern/agent-harness"; @@ -341,7 +342,8 @@ export function parseReviewFeedback( * @param workingDir - Git working directory * @param harness - Resolved agent harness configuration * @param executablePath - Path to the agent CLI executable - * @param options - `label` names the transcript (e.g. `review #1`); defaults to `agent` + * @param options - `label` names the transcript (e.g. `review #1`); defaults to `agent`. + * `verdict` marks a turn whose JSON verdict is parsed from stdout, so tool-based reporters are disabled * @returns Agent stdout on success * @throws When the agent times out or exits with a non-zero code */ @@ -350,7 +352,7 @@ export async function runAgentPrompt( workingDir: string, harness: AgentHarness, executablePath: string, - options: { label?: string } = {}, + options: { label?: string; verdict?: boolean } = {}, ): Promise { // Wait out any in-progress CLI auto-update swap before spawning, so a // transient `spawn ENOENT` doesn't abort the review. @@ -370,6 +372,7 @@ export async function runAgentPrompt( workingDir, model: resolveAgentModel(harness.name), effort: resolveAgentEffort(), + ...(options.verdict ? { disallowedTools: VERDICT_DISALLOWED_TOOLS } : {}), }, ); const exit = await runAgentProcess( @@ -548,7 +551,7 @@ export async function runAutoReviewLoop( workingDir, harness, executablePath, - { label: harnessRoundLabel("review", iteration) }, + { label: harnessRoundLabel("review", iteration), verdict: true }, ); // Step 3: Parse feedback diff --git a/packages/code/src/lib/review/verdict-delivery.ts b/packages/code/src/lib/review/verdict-delivery.ts new file mode 100644 index 000000000..d96318df1 --- /dev/null +++ b/packages/code/src/lib/review/verdict-delivery.ts @@ -0,0 +1,16 @@ +/** + * Tools switched off for turns whose verdict is parsed from the final message. + * Claude Code's `ReportFindings` sends review output to a channel that never + * reaches stdout, so the JSON verdict would be missing. + */ +export const VERDICT_DISALLOWED_TOOLS = ["ReportFindings"] as const; + +/** Appended to JSON-verdict prompts: the verdict must be the final message text. */ +export const VERDICT_DELIVERY_NOTE = + "The JSON object must be the final text of your response. Do not report findings through any tool (such as ReportFindings): tool-based reports are not read and count as no verdict."; + +/** Short follow-up prompt used when a verdict reply contained no parseable JSON. */ +export function buildVerdictFollowUpPrompt(previousOutput: string): string { + const tail = previousOutput.trim().slice(-4000); + return `Your previous review reply did not contain the required JSON verdict. Using only the review below, reply with the JSON object and nothing else. Do not use any tools, and do not report through ReportFindings; the JSON must be the final text of your reply.\n\n--- previous reply ---\n${tail}`; +} diff --git a/packages/code/src/lib/task/pipeline-registry.ts b/packages/code/src/lib/task/pipeline-registry.ts index 620a47e9f..e6a0ae3e0 100644 --- a/packages/code/src/lib/task/pipeline-registry.ts +++ b/packages/code/src/lib/task/pipeline-registry.ts @@ -46,7 +46,7 @@ export interface PipelineContext { * names the run's transcript on the dashboard; it defaults to the name of * the step making the call. */ - runAgentPrompt(prompt: string, options?: { label?: string }): Promise; + runAgentPrompt(prompt: string, options?: { label?: string; verdict?: boolean }): Promise; /** Read the current diff against the configured PR target branch. */ getDiff(): string; /** Parse an agent review verdict and filter findings by priority. */ diff --git a/packages/code/tests/verify-step.test.ts b/packages/code/tests/verify-step.test.ts index 598728db5..50fe9de44 100644 --- a/packages/code/tests/verify-step.test.ts +++ b/packages/code/tests/verify-step.test.ts @@ -96,6 +96,43 @@ afterEach(() => { }); describe("verifyImplementation", () => { + test("tells the agent to end with JSON and not use ReportFindings, and flags a verdict turn", async () => { + const prompts: string[] = []; + const flags: Array = []; + await verifyImplementation(state({}), { + ...deps({ ...feedback, approved: true, items: [] }), + runAgent: async (prompt, _w, _h, _e, options) => { + prompts.push(prompt); + flags.push(options?.verdict); + return "ok"; + }, + }); + expect(prompts[0]).toContain("final text of your response"); + expect(prompts[0]).toContain("ReportFindings"); + expect(flags).toEqual([true]); + }); + + test("asks only for the JSON verdict when the first reply has none", async () => { + const prompts: string[] = []; + const verdict = { ...feedback, approved: true, items: [] }; + const run = state({}); + const result = await verifyImplementation(run, { + ...deps(verdict), + runAgent: async (prompt) => { + prompts.push(prompt); + return prompts.length === 1 ? "I reviewed the diff, all good." : '{"approved":true}'; + }, + parseFeedback: (output) => { + if (!output.includes("{")) throw new Error("no JSON"); + return verdict; + }, + }); + expect(result).toBeUndefined(); + expect(prompts).toHaveLength(2); + expect(prompts[1]).toContain("did not contain the required JSON verdict"); + expect(prompts[1]).not.toContain("## Implementation diff"); + }); + test("passes when the verdict has no blocking findings", async () => { const run = state({}); const verdict = { ...feedback, approved: true, items: [] };