Skip to content
Merged
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
18 changes: 18 additions & 0 deletions script/agent.agy-review.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,24 @@ describe("runLocal pipeline (stub agy)", () => {
expect(existsSync(join(result.isolation.workdir, "inputs", "00-shot.png"))).toBe(true);
});

it("recovers the verdict when the response duplicates the JSON object", async () => {
// Observed with claude-sonnet-5-5-high: agy returns two complete verdict
// objects concatenated; the last one is the final answer (#227).
const dupResponse = [
JSON.stringify({ verdict: "approve", summary: "draft", findings: [] }),
JSON.stringify({
verdict: "request-changes",
summary: "final",
findings: [{ severity: "minor", description: "x", location: "top-left" }],
}),
].join("\n");
const dup = JSON.stringify({ status: "SUCCESS", response: dupResponse, denied_actions: [] });
const stub = makeStub("dup.sh", `cat <<'EOF'\n${dup}\nEOF`);
const result = await runAgyReview({ ...base(), agyBin: stub });
expect(result.classification).toBe("review-completed");
expect(result.verdict).toMatchObject({ verdict: "request-changes", summary: "final" });
});

it("readonly-violation when the model hits deny rules", async () => {
const denied = JSON.stringify({
status: "SUCCESS",
Expand Down
57 changes: 52 additions & 5 deletions script/agent/agy-review.ts
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,50 @@ export function releaseReviewLock(path: string, id: string): void {
}
}

/**
* Extract every complete top-level `{...}` JSON value from `text`, in
* order. Tolerates prose/fences/duplicated objects around the payload;
* unparseable candidates are skipped.
*/
export function extractJsonValues(text: string): unknown[] {
const values: unknown[] = [];
let i = 0;
while (i < text.length) {
const start = text.indexOf("{", i);
if (start === -1) break;
let depth = 0;
let inStr = false;
let esc = false;
let end = -1;
for (let j = start; j < text.length; j++) {
const c = text[j];
if (inStr) {
if (esc) esc = false;
else if (c === "\\") esc = true;
else if (c === '"') inStr = false;
continue;
}
if (c === '"') inStr = true;
else if (c === "{") depth++;
else if (c === "}") {
depth--;
if (depth === 0) {
end = j;
break;
}
}
}
if (end === -1) break;
try {
values.push(JSON.parse(text.slice(start, end + 1)));
} catch {
// Not a complete JSON object — skip past it.
}
i = end + 1;
}
return values;
}

// ---------------------------------------------------------------------------
// Orchestration
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -871,20 +915,23 @@ async function runLocal(
let verdict: unknown = null;
let schemaValid = false;
if (envelope?.response) {
try {
const parsed = JSON.parse(envelope.response);
// Some models (observed: claude-sonnet via agy) emit the verdict object
// more than once in one response. Take the LAST complete top-level JSON
// value — earlier copies are drafts/duplicates — and keep failing closed
// when nothing parses.
const candidates = extractJsonValues(envelope.response);
const parsed = candidates.length > 0 ? candidates[candidates.length - 1] : null;
if (parsed !== null) {
// Minimal schema check: required keys present with right primitive types.
// The model-facing --json-schema enforces the full contract; this layer
// guards against a harness/CLI drift producing plausible-but-wrong JSON.
if (isPlainObject(schema) && Array.isArray((schema as Record<string, unknown>)["required"])) {
const required = (schema as Record<string, unknown>)["required"] as string[];
schemaValid = required.every((k) => k in parsed);
schemaValid = required.every((k) => k in (parsed as Record<string, unknown>));
} else {
schemaValid = true;
}
verdict = schemaValid ? parsed : null;
} catch {
schemaValid = false;
}
}
result.verdict = verdict;
Expand Down
Loading