Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/agent-harness/src/harnesses/claude-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
8 changes: 8 additions & 0 deletions packages/agent-harness/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
12 changes: 12 additions & 0 deletions packages/agent-harness/tests/harnesses.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([]);
});
});
2 changes: 1 addition & 1 deletion packages/code/prompts/review.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
10 changes: 5 additions & 5 deletions packages/code/src/lib/agent/run-harness-finalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,11 +360,10 @@ export async function commitImplementation(state: DeliveryState): Promise<boolea
}

if (noChanges) {
// Fallback for runs where the pre-run HEAD could not be captured: agents
// sometimes commit their own work. The pipeline creates the branch from the
// PR target, so commits ahead of it are this run's implementation; deliver
// them instead of requiring an extra commit just to satisfy the clean-tree
// assumption. A protected or target branch is never accepted.
// Fallback when the pre-run HEAD could not be captured: agents sometimes
// commit their own work. The branch starts at the PR target, so commits
// ahead of it are this run's implementation; deliver them rather than
// requiring an extra commit. A protected or target branch is never accepted.
const currentBranch = await Utils.getCurrentBranch();
const targetBranch = ctx.prTargetBranch.replace(/^origin\//, "");
if (
Expand Down Expand Up @@ -923,6 +922,7 @@ export function finalizeAgentRun(ctx: FinalizeContext): void {
agentRounds: new Map(),
runAgentPrompt: (prompt, options) =>
runAgentPrompt(prompt, process.cwd(), ctx.harness, ctx.executablePath, {
...options,
label: options?.label ?? state.activeStep ?? "agent",
}),
getDiff: () => {
Expand Down
20 changes: 17 additions & 3 deletions packages/code/src/lib/agent/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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;
Expand Down
4 changes: 3 additions & 1 deletion packages/code/src/lib/review/address.ts
Original file line number Diff line number Diff line change
@@ -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";
/**
Expand Down Expand Up @@ -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<AgentRunResult> {
const { harness, path: executablePath } = resolveHarness();
// Wait out any in-progress CLI auto-update swap before spawning, so a
Expand All @@ -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,
Expand Down
1 change: 1 addition & 0 deletions packages/code/src/lib/review/auto-merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" };
Expand Down
9 changes: 6 additions & 3 deletions packages/code/src/lib/review/auto-review-loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
*/
Expand All @@ -350,7 +352,7 @@ export async function runAgentPrompt(
workingDir: string,
harness: AgentHarness,
executablePath: string,
options: { label?: string } = {},
options: { label?: string; verdict?: boolean } = {},
): Promise<string> {
// Wait out any in-progress CLI auto-update swap before spawning, so a
// transient `spawn ENOENT` doesn't abort the review.
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions packages/code/src/lib/review/verdict-delivery.ts
Original file line number Diff line number Diff line change
@@ -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}`;
}
2 changes: 1 addition & 1 deletion packages/code/src/lib/task/pipeline-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>;
runAgentPrompt(prompt: string, options?: { label?: string; verdict?: boolean }): Promise<string>;
/** Read the current diff against the configured PR target branch. */
getDiff(): string;
/** Parse an agent review verdict and filter findings by priority. */
Expand Down
37 changes: 37 additions & 0 deletions packages/code/tests/verify-step.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean | undefined> = [];
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: [] };
Expand Down
Loading