From 76718244b1701acc8e1321593d96eeeac80037e0 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 11:16:26 +0530 Subject: [PATCH 01/32] feat(review): stop posting 36 noisy rule types once the AI lane runs - `rules-off.ts` ships `NOISY_RULES_OFF`: 36 rule ids whose findings were almost never real defects when judged on replayed public dbt PRs with the AI lane reviewing the same PRs - applied after the AI lane, only when it runs: the finder's grounding is unchanged, AI findings are never dropped, and a dropped finding does not count toward the verdict - `rulesOff` switch, on by default with the AI lane: `ai.rulesOff: false` or `ALTIMATE_REVIEW_RULES_OFF=0` keeps every type; `ai.rulesOn: [ids]` keeps single types; `ALTIMATE_REVIEW_RULES_OFF=` replaces the list with a JSON list of rule ids (an unreadable or malformed file is an error) - envelope: `rulesOff: {rule: count}`, summed across projects under `--all-projects` - tests: list shape, resolver (default, config, `rulesOn`, env `0` and file, bad files), `dropRulesOff`, orchestrator drop and counts with the finder input unchanged, AI lane off unchanged Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-switches.ts | 17 +- .../opencode/src/altimate/review/config.ts | 4 + .../src/altimate/review/multi-project.ts | 12 ++ .../src/altimate/review/orchestrate.ts | 17 +- .../opencode/src/altimate/review/rules-off.ts | 88 +++++++++ packages/opencode/src/altimate/review/run.ts | 4 + .../opencode/src/altimate/review/verdict.ts | 4 + .../test/altimate/review-rules-off.test.ts | 171 ++++++++++++++++++ 8 files changed, 313 insertions(+), 4 deletions(-) create mode 100644 packages/opencode/src/altimate/review/rules-off.ts create mode 100644 packages/opencode/test/altimate/review-rules-off.test.ts diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index aefb298fea..495bd73ac4 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -8,7 +8,15 @@ // env variable, as before, so an unset variable means off there. import type { ReviewConfig } from "./config" -export type AiSwitchName = "coverage" | "contextCard" | "focused" | "otherFiles" | "pythonFiles" | "verify" | "conventions" +export type AiSwitchName = + | "coverage" + | "contextCard" + | "focused" + | "otherFiles" + | "pythonFiles" + | "verify" + | "conventions" + | "rulesOff" export type AiSwitches = Record @@ -21,6 +29,7 @@ export const AI_SWITCH_ENV: Record = { pythonFiles: "ALTIMATE_REVIEW_AI_PYTHON_FILES", verify: "ALTIMATE_REVIEW_AI_VERIFY", conventions: "ALTIMATE_REVIEW_CONVENTIONS", + rulesOff: "ALTIMATE_REVIEW_RULES_OFF", } /** @@ -36,6 +45,7 @@ export const AI_SWITCH_DEFAULTS: AiSwitches = { pythonFiles: true, verify: true, conventions: true, + rulesOff: true, } type Env = Record @@ -46,7 +56,10 @@ const ENV_FALSE = new Set(["0", "false", "off", "no"]) /** The env override for a switch: true for `1`/`true`/`on`/`yes`, false for `0`/`false`/`off`/`no` * (case-insensitive), undefined otherwise. */ export function envSwitch(name: AiSwitchName, env: Env = process.env): boolean | undefined { - return envBool(env[AI_SWITCH_ENV[name]]) + const raw = env[AI_SWITCH_ENV[name]] + // `ALTIMATE_REVIEW_RULES_OFF=` names a replacement list: the switch is on. + if (name === "rulesOff" && raw && raw !== "0") return true + return envBool(raw) } /** An env value as a boolean: `1`/`true`/`on`/`yes` true, `0`/`false`/`off`/`no` false (trimmed, diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 30fb4a67ee..1abce7c828 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -53,6 +53,10 @@ export const ReviewConfig = z.object({ verify: z.boolean().optional(), /** Repo review instructions (AGENTS.md, CLAUDE.md, REVIEW.md, Cursor/CodeRabbit/Copilot rules, CONTRIBUTING.md) from the base branch. */ conventions: z.boolean().optional(), + /** Drop the rule types in `NOISY_RULES_OFF` (rules-off.ts) once the AI lane runs. */ + rulesOff: z.boolean().optional(), + /** Rule ids taken back out of that list (posted as before). */ + rulesOn: z.array(z.string()).optional(), }), ]) .default(true), diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 84ad004fa3..a77b6a2f2e 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -303,11 +303,23 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri })), }, ai: mergeAi(runs), + ...mergeRuleNoise(envs), generatedAt: first.generatedAt, } return signEnvelope(VerdictEnvelope.parse(merged)) } +/** Rule-noise counts summed over the projects (present only when some project has them). */ +function mergeRuleNoise(envs: VerdictEnvelope[]): Pick { + const out: Pick = {} + if (envs.some((e) => e.rulesOff)) { + const off: Record = {} + for (const e of envs) for (const [rule, n] of Object.entries(e.rulesOff ?? {})) off[rule] = (off[rule] ?? 0) + n + out.rulesOff = off + } + return out +} + /** Least-trusted source first: a policy the PR controls outranks the defaults, which outrank the base branch's. */ const POLICY_SOURCE_RANK = { base: 0, default: 1, working_tree: 2 } as const diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index dfa62937d6..4e7bc04cab 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -69,6 +69,7 @@ import { type AiSwitches, switchOn } from "./ai-switches" import { isAiOtherFile } from "./ai-other-files" import { AI_PYTHON_KIND, isAiPythonFile } from "./ai-python-files" import { type Convention, conventionTexts } from "./conventions" +import { dropRulesOff } from "./rules-off" import { type AiVerifyEvidence, numberedSlice } from "./ai-verify" import { holdsCredentials, isCredentialPath } from "./credentials" import type { ColumnReach } from "../native/dbt/column-reach" @@ -302,6 +303,8 @@ export interface OrchestrateInput { reviewDir?: string /** Team conventions from the base branch (`conventions` switch), for the AI finder. */ conventions?: Convention[] + /** Rule ids not posted when the AI lane runs (rules-off.ts); undefined keeps every type. */ + rulesOff?: Set /** Fixed-string search over the dbt project at head, for the verifier. */ grepProject?: AiVerifyEvidence["grepProject"] /** Every file the PR changes (repo-relative), including files outside the dbt project; the verifier may read them. */ @@ -2649,6 +2652,8 @@ export async function runReview(input: OrchestrateInput): Promise() let aiReviewedOutside: string[] = [] + // The AI lane runs in this review: rule types off apply only then. + const aiLaneOn = lanes.has("ai_review") && !!input.aiReview if (!lanes.has("ai_review")) { aiStatus = { state: "skipped", reason: `not part of the ${tier} tier` } } else if (!input.aiReview) { @@ -2833,9 +2838,16 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= minSev) + let findings = cleanFindings(validated).filter((f) => SEVERITY_ORDER[f.severity] >= minSev) // The verdict counts every instance; merging repeats is presentation only. - const verdictFindings = cleanFindings(validated, false).filter((f) => SEVERITY_ORDER[f.severity] >= minSev) + let verdictFindings = cleanFindings(validated, false).filter((f) => SEVERITY_ORDER[f.severity] >= minSev) + + // Rule types off, only when the AI lane runs. A finding not posted does not count toward the + // verdict either. AI findings are never dropped. + const rulesOff = aiLaneOn ? input.rulesOff : undefined + const off = dropRulesOff(findings, rulesOff) + findings = off.kept + verdictFindings = dropRulesOff(verdictFindings, rulesOff).kept // Lint-only means no changed model resolved against a manifest. A single // undecidable finding does not make the whole run lint-only; those findings @@ -2876,6 +2888,7 @@ export async function runReview(input: OrchestrateInput): Promise` replaces +// the list with a JSON list of rule ids. +import { readFileSync } from "node:fs" +import { type Finding, findingOrigin } from "./finding" +import type { ReviewConfig } from "./config" +import type { AiSwitches } from "./ai-switches" + +export const NOISY_RULES_OFF: readonly string[] = [ + "altimate-core.classify-pii:exposes", + "altimate-core.lexical:op-json-arrow1", + "altimate-core.lexical:op-pg-cast", + "altimate-core.structural-diff:removed-predicate", + "altimate-core.structural-diff:union-added", + "dbt-patterns:hardcoded-date", + "dbt-patterns:leading-wildcard", + "dbt-patterns:multi-count-distinct", + "dbt-patterns:partition-function", + "dbt-patterns:self-join", + "rule-catalog:adapter-call", + "rule-catalog:bq-datetime-vs-timestamp", + "rule-catalog:cast-chain", + "rule-catalog:count-distinct-large", + "rule-catalog:count-star-with-left-join", + "rule-catalog:dateadd-from-now", + "rule-catalog:datediff-arg-order", + "rule-catalog:distinct-and-group-by", + "rule-catalog:full-outer-join", + "rule-catalog:hardcoded-year-filter", + "rule-catalog:join-on-cast", + "rule-catalog:lateral-join", + "rule-catalog:multiple-left-joins", + "rule-catalog:nested-case", + "rule-catalog:now-in-filter", + "rule-catalog:ref-to-source-table", + "rule-catalog:regexp-heavy", + "rule-catalog:select-now-column", + "rule-catalog:select-pii-columns", + "rule-catalog:select-star-in-cte-final", + "rule-catalog:staging-as-table", + "rule-catalog:union-not-all", + "rule-catalog:union-select-star", + "rule-catalog:unqualified-column-multi-table", + "rule-catalog:where-1-eq-1", + "rule-catalog:where-cast-column", +] + +/** + * The rule ids to drop for this review, or undefined when the switch is off. A list file + * named by `ALTIMATE_REVIEW_RULES_OFF` replaces the shipped list (an unreadable or malformed + * file is an error); `ai.rulesOn` takes ids back out. + */ +export function resolveRulesOff( + cfg: Pick, + switches: Pick, + env: Record = process.env, +): Set | undefined { + if (!switches.rulesOff) return undefined + const file = env.ALTIMATE_REVIEW_RULES_OFF + let list: readonly string[] = NOISY_RULES_OFF + if (file && file !== "1" && file !== "0") { + const parsed: unknown = JSON.parse(readFileSync(file, "utf8")) + if (!Array.isArray(parsed) || parsed.some((r) => typeof r !== "string")) + throw new Error(`ALTIMATE_REVIEW_RULES_OFF must name a JSON list of rule ids: ${file}`) + list = parsed as string[] + } + const on = new Set(typeof cfg.ai === "object" ? (cfg.ai.rulesOn ?? []) : []) + return new Set(list.filter((r) => !on.has(r))) +} + +/** `findings` without the rule findings whose rule id is in `off`, and how many each rule lost. */ +export function dropRulesOff(findings: Finding[], off: Set | undefined): { kept: Finding[]; dropped: Record } { + const dropped: Record = {} + if (!off?.size) return { kept: findings, dropped } + const kept = findings.filter((f) => { + if (!f.rule || !off.has(f.rule) || findingOrigin(f) === "ai") return true + dropped[f.rule] = (dropped[f.rule] ?? 0) + 1 + return false + }) + return { kept, dropped } +} diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index bb38bf1216..cf440d4441 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -31,6 +31,7 @@ import { runAiReview } from "./ai-review" import { resolveAiSwitches } from "./ai-switches" import { isAiPythonFile } from "./ai-python-files" import { loadConventions } from "./conventions" +import { resolveRulesOff } from "./rules-off" import { loadConsumerLists } from "./consumer-lists" import type { ReviewMode, VerdictEnvelope } from "./verdict" import type { ChangedFile } from "./diff-filter" @@ -376,6 +377,8 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise else if (!aiLaneEnabled(config)) aiDisabledReason = "disabled in .altimate/review.yml" const aiOn = !aiDisabledReason const aiSwitches = resolveAiSwitches(config, process.env, { warn: aiOn }) + // Rule types off once the AI lane runs; a bad list file named by the env variable fails here. + const rulesOff = aiOn ? resolveRulesOff(config, aiSwitches) : undefined // `pythonFiles`: .py files outside the dbt project skip every lane but the AI lane. A file // renamed out of this project belongs to it (`--all-projects` assigns it here), so it is offered // at its new path whatever other projects took. @@ -540,6 +543,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise ...(aiOutsideFiles.length ? { aiOutsideFiles } : {}), reviewDir: gitRoot, ...(conventions.length ? { conventions } : {}), + ...(rulesOff ? { rulesOff } : {}), grepProject: (pattern, glob) => { // The project's dbt directories (repo-relative), or one glob inside the project. const dirs = layout diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index 52db97e55c..6db63c6142 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -372,6 +372,8 @@ export const VerdictEnvelope = z.object({ .optional(), }) .optional(), + /** Rule findings not posted because their rule type is off while the AI lane runs, per rule id. */ + rulesOff: z.record(z.string(), z.number().int().nonnegative()).optional(), /** ISO timestamp; injected by the caller (no clock access in pure code). */ generatedAt: z.string().optional(), /** Optional break-glass override record. */ @@ -437,6 +439,7 @@ export interface BuildEnvelopeInput { ai?: VerdictEnvelope["ai"] policy?: VerdictEnvelope["policy"] engineErrors?: VerdictEnvelope["engineErrors"] + rulesOff?: VerdictEnvelope["rulesOff"] } /** Severity tally of `findings` for the envelope summary. */ @@ -504,6 +507,7 @@ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { staleManifest: input.staleManifest ? true : undefined, scope: input.scope, ai: input.ai, + ...(input.rulesOff ? { rulesOff: input.rulesOff } : {}), policy: input.policy, engineErrors: input.engineErrors, generatedAt: input.generatedAt, diff --git a/packages/opencode/test/altimate/review-rules-off.test.ts b/packages/opencode/test/altimate/review-rules-off.test.ts new file mode 100644 index 0000000000..96323e3e12 --- /dev/null +++ b/packages/opencode/test/altimate/review-rules-off.test.ts @@ -0,0 +1,171 @@ +import { describe, test, expect, afterEach } from "bun:test" +import { mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG, parseReviewConfig } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { makeFinding, ruleId, type Finding } from "../../src/altimate/review/finding" +import { NOISY_RULES_OFF, dropRulesOff, resolveRulesOff } from "../../src/altimate/review/rules-off" +import { envSwitch, resolveAiSwitches } from "../../src/altimate/review/ai-switches" +import type { AiReviewInput } from "../../src/altimate/review/ai-review" + +// Rule types off: the shipped list drops those rule findings once the AI lane runs. + +const dirs: string[] = [] +afterEach(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) +}) + +function listFile(body: string): string { + const dir = mkdtempSync(join(tmpdir(), "rules-off-")) + dirs.push(dir) + const file = join(dir, "rules_off.json") + writeFileSync(file, body) + return file +} + +const finding = (rule: string, tool = "dbt-patterns", n = 1): Finding => + makeFinding({ + severity: "warning", + category: "sql_quality", + title: `m: ${rule} ${n}`, + body: "b", + file: "models/m.sql", + evidence: { tool, result: {} }, + ruleKey: `${rule}-${n}`, + rule, + }) + +describe("NOISY_RULES_OFF", () => { + test("36 distinct rule ids", () => { + expect(NOISY_RULES_OFF).toHaveLength(36) + expect(new Set(NOISY_RULES_OFF).size).toBe(36) + for (const r of NOISY_RULES_OFF) expect(r).toMatch(/^[a-z.-]+:[a-z0-9-]+$/) + }) +}) + +describe("resolveRulesOff", () => { + const on = { rulesOff: true } + + test("default: the shipped list; switch off: undefined", () => { + expect([...resolveRulesOff({ ai: true }, on, {})!]).toEqual([...NOISY_RULES_OFF]) + expect(resolveRulesOff({ ai: true }, { rulesOff: false }, {})).toBeUndefined() + }) + + test("`ai.rulesOn` takes single ids back out", () => { + const cfg = parseReviewConfig(`ai:\n rulesOn:\n - ${NOISY_RULES_OFF[0]}\n - not:in-the-list`) + const off = resolveRulesOff(cfg, resolveAiSwitches(cfg, {}), {})! + expect(off.has(NOISY_RULES_OFF[0])).toBe(false) + expect(off.size).toBe(NOISY_RULES_OFF.length - 1) + }) + + test("`ai.rulesOff: false` and `ALTIMATE_REVIEW_RULES_OFF=0` keep every type", () => { + const cfg = parseReviewConfig("ai:\n rulesOff: false") + expect(resolveRulesOff(cfg, resolveAiSwitches(cfg, {}), {})).toBeUndefined() + const env = { ALTIMATE_REVIEW_RULES_OFF: "0" } + expect(resolveRulesOff({ ai: true }, resolveAiSwitches({ ai: true }, env), env)).toBeUndefined() + }) + + test("`ALTIMATE_REVIEW_RULES_OFF=` replaces the list, even over `ai.rulesOff: false`; a bad file is an error", () => { + const file = listFile('["a:b", "c:d"]') + const env = { ALTIMATE_REVIEW_RULES_OFF: file } + expect(envSwitch("rulesOff", env)).toBe(true) + const cfg = parseReviewConfig("ai:\n rulesOff: false") + expect([...resolveRulesOff(cfg, resolveAiSwitches(cfg, env), env)!]).toEqual(["a:b", "c:d"]) + const bad = (body: string) => ({ ALTIMATE_REVIEW_RULES_OFF: listFile(body) }) + expect(() => resolveRulesOff({ ai: true }, on, bad('{"a": 1}'))).toThrow(/JSON list of rule ids/) + expect(() => resolveRulesOff({ ai: true }, on, bad("[1]"))).toThrow(/JSON list of rule ids/) + expect(() => resolveRulesOff({ ai: true }, on, { ALTIMATE_REVIEW_RULES_OFF: "/nonexistent/rules_off.json" })).toThrow() + }) +}) + +describe("dropRulesOff", () => { + test("drops listed rule findings and counts them per rule; AI findings and unlisted rules stay", () => { + const fs = [ + finding("dbt-patterns:select-star", "dbt-patterns", 1), + finding("dbt-patterns:select-star", "dbt-patterns", 2), + finding("rule-catalog:order-by", "rule-catalog"), + finding("dbt-patterns:kept"), + finding(ruleId("ai-review", "sql_quality"), "ai-review"), + ] + const off = new Set(["dbt-patterns:select-star", "rule-catalog:order-by", ruleId("ai-review", "sql_quality")]) + const r = dropRulesOff(fs, off) + expect(r.kept.map((f) => f.rule)).toEqual(["dbt-patterns:kept", ruleId("ai-review", "sql_quality")]) + expect(r.dropped).toEqual({ "dbt-patterns:select-star": 2, "rule-catalog:order-by": 1 }) + expect(dropRulesOff(fs, undefined)).toEqual({ kept: fs, dropped: {} }) + expect(dropRulesOff(fs, new Set())).toEqual({ kept: fs, dropped: {} }) + }) +}) + +describe("orchestrator: rule types off", () => { + const runner: ReviewRunner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } as ReviewRunner + const SQL = "select *\nfrom raw.orders\nwhere status = 'x'\norder by 1" + const run = (opts: { seen?: AiReviewInput[]; rulesOff?: Set; ai?: boolean }) => + runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + getContent: async (_f, side) => (side === "old" ? "select 1" : SQL), + generatedAt: "2026-11-25T00:00:00Z", + ...(opts.rulesOff ? { rulesOff: opts.rulesOff } : {}), + ...(opts.ai === false + ? {} + : { + aiReview: async (input: AiReviewInput) => { + opts.seen?.push(input) + return { findings: [], status: { state: "ok" as const } } + }, + }), + }) + + test("listed rule findings are dropped and counted; the finder's input is unchanged", async () => { + const offSeen: AiReviewInput[] = [] + const base = await run({ seen: offSeen }) + expect(base.rulesOff).toBeUndefined() + const rules = [...new Set(base.findings.map((f) => f.rule!))] + expect(rules.length).toBeGreaterThan(1) + const target = rules[0] + const n = base.findings.filter((f) => f.rule === target).length + + const onSeen: AiReviewInput[] = [] + const on = await run({ seen: onSeen, rulesOff: new Set([target, "dbt-patterns:not-in-this-pr"]) }) + expect(on.findings).toEqual(base.findings.filter((f) => f.rule !== target)) + expect(on.rulesOff).toEqual({ [target]: n }) + expect(on.summary.warning + on.summary.critical + on.summary.suggestion).toBe(base.findings.length - n) + // The finder's grounding is the same as without the list. + expect(onSeen[0]).toEqual(offSeen[0]) + + // A list that matches nothing: same findings, an empty record. + const none = await run({ rulesOff: new Set(["x:y"]) }) + expect(none.findings).toEqual(base.findings) + expect(none.rulesOff).toEqual({}) + }) + + test("AI lane off: the list is ignored and the envelope is unchanged", async () => { + const base = await run({ ai: false }) + const target = base.findings[0].rule! + const withList = await run({ ai: false, rulesOff: new Set([target]) }) + expect(withList).toEqual(base) + expect(withList.rulesOff).toBeUndefined() + }) +}) From 6c3aafc68fd947ba70142958393496e627582b1a Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 11:17:20 +0530 Subject: [PATCH 02/32] feat(review): verify the posted rule findings after the finder and drop the refuted ones - the AI verifier gets a rule mode (`rulesOnly`): it records a verdict for every rule finding (`ai.verifier.ruleVerdicts[]`, with per-batch outcomes in `ai.verifier.batches[]`) and applies no triage; a finding the model gave no verdict is recorded as `noVerdict` - `ai-verify-rules.ts` `runRuleVerify`: after the finder and its verifier, the rule findings the review would post (after rule types off) go to that mode; no evidence, no rule findings, no model or a dry run skip it and say why - the orchestrator drops rule findings with verdict `refuted`; AI findings, confirmed, unverifiable and unreviewed rule findings stay; a merged repeat's instances take the merged finding's verdict (`repeatGroupId`) - `verifyRules` switch, on by default when the AI lane and the verifier are on: `ai.verifyRules: false` or `ALTIMATE_REVIEW_AI_VERIFY_RULES=off` (or `0`) turns it off, `drop_refuted` (or `1`) turns it on - envelope: `ai.verifyRules: "drop_refuted"`, the rule run's outcome and spend under `ai.ruleVerifier` (the AI verifier's counters stay as they were), `rulesRefuted`; merged across projects under `--all-projects` - tests: switch, rule mode verdicts, batches and failure, skipped cases, finder then AI verifier then rule verifier order, orchestrator drop with the lane input otherwise unchanged, no run without the verifier's evidence, rule types off left out first Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-review.ts | 35 ++ .../src/altimate/review/ai-switches.ts | 11 +- .../src/altimate/review/ai-verify-rules.ts | 52 ++ .../opencode/src/altimate/review/ai-verify.ts | 97 ++++ .../opencode/src/altimate/review/config.ts | 2 + .../opencode/src/altimate/review/finding.ts | 16 +- .../src/altimate/review/multi-project.ts | 10 +- .../src/altimate/review/orchestrate.ts | 35 +- .../opencode/src/altimate/review/verdict.ts | 57 +++ .../altimate/review-ai-verify-rules.test.ts | 463 ++++++++++++++++++ 10 files changed, 769 insertions(+), 9 deletions(-) create mode 100644 packages/opencode/src/altimate/review/ai-verify-rules.ts create mode 100644 packages/opencode/test/altimate/review-ai-verify-rules.test.ts diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 7f961f10c1..0d08895f74 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -13,6 +13,7 @@ import { type Finding, type ReviewCategory, type Severity, makeFinding, ruleId } import { readStreamText } from "../llm/stream-text" import { type AiVerifyEvidence, type VerifierStatus, runAiVerify } from "./ai-verify" import { aiReplayPath, runAiReplay } from "./ai-replay" +import { runRuleVerify, skippedVerifier } from "./ai-verify-rules" import { walkDiffLines } from "./diff-filter" import { CARD_BATCH_MAX_CHARS } from "./ai-context-card" import { type AiSwitches, switchOn } from "./ai-switches" @@ -753,6 +754,8 @@ export interface AiReviewInput { reviewDir?: string /** Team conventions from the base branch (`conventions` switch); each call carries those for its files. */ conventions?: Convention[] + /** The rule findings the review would post, verified after the finder (`verifyRules` switch). */ + verifyRulesAfter?: Finding[] } /** What happened in the advisory lane, reported on the envelope and in the comment. */ @@ -787,7 +790,13 @@ export interface AiLaneStatus { failedFiles?: string[] /** The team conventions loaded from the base branch (no text), when any were given. */ conventions?: ConventionRecord[] + /** The rule findings were verified after the finder; refuted ones are not posted. */ + verifyRules?: "drop_refuted" + /** That rule run's own outcome and spend (its verdicts are in `verifier.ruleVerdicts`). */ + ruleVerifier?: RuleVerifierSummary } +/** The rule verifier run, without its per-finding records. */ +export type RuleVerifierSummary = Omit & { model?: string } /** One file as sent to the model. */ export interface AiInputRecord { path: string @@ -1003,6 +1012,32 @@ export function planAiInput(input: AiReviewInput, env: Record { + const res = await runFinderLane(input) + if (!input.verifyRulesAfter) return res + // The rule verifier over the rule findings the review would post, after the finder and its verifier. + return withRuleVerdicts(res, await runRuleVerify(input, input.verifyRulesAfter)) +} + +/** The finder lane's result with the rule run's verdicts (`verifier.ruleVerdicts`, `verifier.batches`) and its + * own outcome (`ruleVerifier`). The finder verifier's counters are left as they were. */ +export function withRuleVerdicts(res: AiReviewResult, rules: AiReviewResult): AiReviewResult { + const rv = rules.status.verifier ?? skippedVerifier(rules.status.reason ?? "the rule verifier did not run") + const { ruleVerdicts, batches, dropped: _d, decisions: _x, ...summary } = rv + const ruleVerifier: RuleVerifierSummary = { ...summary, ...(rules.status.model ? { model: rules.status.model } : {}) } + const verifier: VerifierStatus = res.status.verifier ?? skippedVerifier("the AI verifier did not run on the finder's findings") + return { + findings: res.findings, + status: { + ...res.status, + verifyRules: "drop_refuted", + verifier: { ...verifier, ...(ruleVerdicts ? { ruleVerdicts } : {}), ...(batches ? { batches } : {}) }, + ruleVerifier, + }, + } +} + +/** The finder lane: replay, or plan, call the finder and run its verifier as configured. */ +async function runFinderLane(input: AiReviewInput): Promise { const replay = aiReplayPath() const startedAt = Date.now() const plan = planAiInput(input) diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index 495bd73ac4..8e023d2083 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -17,6 +17,7 @@ export type AiSwitchName = | "verify" | "conventions" | "rulesOff" + | "verifyRules" export type AiSwitches = Record @@ -30,6 +31,7 @@ export const AI_SWITCH_ENV: Record = { verify: "ALTIMATE_REVIEW_AI_VERIFY", conventions: "ALTIMATE_REVIEW_CONVENTIONS", rulesOff: "ALTIMATE_REVIEW_RULES_OFF", + verifyRules: "ALTIMATE_REVIEW_AI_VERIFY_RULES", } /** @@ -46,19 +48,26 @@ export const AI_SWITCH_DEFAULTS: AiSwitches = { verify: true, conventions: true, rulesOff: true, + verifyRules: true, } type Env = Record const ENV_TRUE = new Set(["1", "true", "on", "yes"]) const ENV_FALSE = new Set(["0", "false", "off", "no"]) +/** Extra env spellings: `ALTIMATE_REVIEW_AI_VERIFY_RULES=drop_refuted|off`. */ +const ENV_ON: Partial> = { verifyRules: "drop_refuted" } +const ENV_OFF: Partial> = { verifyRules: "off" } /** The env override for a switch: true for `1`/`true`/`on`/`yes`, false for `0`/`false`/`off`/`no` - * (case-insensitive), undefined otherwise. */ + * (case-insensitive) or a switch's own spelling, undefined otherwise. */ export function envSwitch(name: AiSwitchName, env: Env = process.env): boolean | undefined { const raw = env[AI_SWITCH_ENV[name]] // `ALTIMATE_REVIEW_RULES_OFF=` names a replacement list: the switch is on. if (name === "rulesOff" && raw && raw !== "0") return true + const v = raw?.trim().toLowerCase() + if (v !== undefined && v === ENV_ON[name]) return true + if (v !== undefined && v === ENV_OFF[name]) return false return envBool(raw) } diff --git a/packages/opencode/src/altimate/review/ai-verify-rules.ts b/packages/opencode/src/altimate/review/ai-verify-rules.ts new file mode 100644 index 0000000000..c36088b92d --- /dev/null +++ b/packages/opencode/src/altimate/review/ai-verify-rules.ts @@ -0,0 +1,52 @@ +// altimate_change - new file: the dbt-grounded verifier over the deterministic rule findings +// +// After the finder (and its verifier), the rule findings the review would post go to the +// same verifier in its usual batches. Each one's verdict is recorded under +// `ai.verifier.ruleVerdicts`; the orchestrator drops the refuted ones (`verifyRules` +// switch) and applies the rule-post policy to the rest. Fail-open: no evidence, no model, +// a dry run or a failed call leaves every rule finding as it was. +import { Provider } from "@/provider/provider" +import { Log } from "@/altimate/util/log" +import type { Finding } from "./finding" +import { aiDryRunEnabled, safeReason, type AiLaneStatus, type AiReviewInput, type AiReviewResult } from "./ai-review" +import { runAiVerify, type VerifierLlm, type VerifierStatus } from "./ai-verify" + +const log = Log.create({ service: "ai-verify-rules" }) + +export const NO_RULE_FINDINGS_REASON = "nothing to verify: the PR has no rule findings" + +/** A verifier record for a rule run that made no model call. */ +export function skippedVerifier(reason: string): VerifierStatus { + return { state: "skipped", reason, durationMs: 0, turns: 0, toolCalls: 0, reviewed: 0, kept: 0, discarded: 0, summary: 0, unreviewed: 0 } +} + +/** Verify `rules` (never calls the finder, returns no findings): the verdicts are on `status.verifier`. */ +export async function runRuleVerify( + input: AiReviewInput, + rules: Finding[], + deps: { env?: Record; llm?: VerifierLlm } = {}, +): Promise { + const startedAt = Date.now() + const env = deps.env ?? process.env + const done = (status: Omit): AiReviewResult => ({ + findings: [], + status: { ...status, durationMs: Date.now() - startedAt }, + }) + const skip = (reason: string) => done({ state: "skipped", reason, verifier: skippedVerifier(reason) }) + if (!input.evidence) return skip("the verifier's evidence is unavailable") + if (!rules.length) return skip(NO_RULE_FINDINGS_REASON) + if (aiDryRunEnabled(env)) return skip("dry run (ALTIMATE_REVIEW_AI_DRYRUN=1): no model call") + let model: Provider.Model + try { + const chosen = input.model ? Provider.parseModel(input.model) : await Provider.defaultModel() + model = await Provider.getModel(chosen.providerID, chosen.modelID) + } catch (err) { + return skip(`no usable model: ${safeReason(err)}`) + } + log.info("verifying rule findings", { findings: rules.length }) + const v = await runAiVerify( + { findings: rules, grounding: input.grounding, evidence: input.evidence, model, rulesOnly: true }, + { env, ...(deps.llm ? { llm: deps.llm } : {}) }, + ) + return done({ state: "ok", model: `${model.providerID}/${model.id}`, verifier: v.status }) +} diff --git a/packages/opencode/src/altimate/review/ai-verify.ts b/packages/opencode/src/altimate/review/ai-verify.ts index 6319be2160..fd13c9bec7 100644 --- a/packages/opencode/src/altimate/review/ai-verify.ts +++ b/packages/opencode/src/altimate/review/ai-verify.ts @@ -97,6 +97,38 @@ export interface VerifierStatus { dropped?: DroppedFinding[] /** Every finding's triage inputs and outcome (uncapped), for offline re-triage with `retriage`. */ decisions?: VerifierDecision[] + /** Rule-finding run only: the verdict for every deterministic rule finding. */ + ruleVerdicts?: RuleVerdict[] + /** Rule-finding run only: each batch's outcome, in batch order. */ + batches?: VerifierBatchRecord[] +} + +/** What the verifier said about one deterministic rule finding. */ +export interface RuleVerdict { + id: string + file: string + title: string + rule?: string + /** null when the finding got no verdict (`noVerdict`). */ + verdict: ModelFeatures["verdict"] | null + claimType: ModelFeatures["claimType"] | null + value: ModelFeatures["value"] | null + evidence: string | null + toolsUsed: string[] + /** Omitted, unparsable, timeout, budget or error: the model returned nothing usable for this finding. */ + noVerdict: boolean + /** Index into `VerifierStatus.batches`. */ + batch: number +} + +/** One verifier batch's outcome. */ +export interface VerifierBatchRecord { + findings: number + state: "ok" | "timeout" | "error" | "budget" + reason?: string + turns: number + toolCalls: number + tokens?: AiTokens } export interface RunAiVerifyInput { @@ -108,6 +140,8 @@ export interface RunAiVerifyInput { model: Provider.Model /** Overrides the verifier system prompt (tests). */ system?: string + /** The findings are deterministic rule findings: record a verdict for each, apply no triage. */ + rulesOnly?: boolean } /** Most lines one `read_file` call returns. */ @@ -680,6 +714,68 @@ export function applyTriage( return { findings: out, dropped, decisions, counts } } +/** The status of a rule-finding run: a verdict per finding and per-batch outcomes; nothing dropped. */ +function ruleStatus( + findings: Finding[], + batches: Array<{ idx: number[] }>, + outcomes: BatchOutcome[], + model: Array, +): Pick & Partial { + const batchOf = new Map() + batches.forEach((b, k) => b.idx.forEach((i) => batchOf.set(i, k))) + const ruleVerdicts: RuleVerdict[] = findings.map((f, i) => { + const m = model[i] + return { + id: f.id, + file: f.file, + title: f.title, + rule: f.rule, + verdict: m?.verdict ?? null, + claimType: m?.claimType ?? null, + value: m?.value ?? null, + evidence: m ? m.evidence : null, + toolsUsed: m?.toolsUsed ?? [], + noVerdict: !m, + batch: batchOf.get(i) ?? -1, + } + }) + const records: VerifierBatchRecord[] = outcomes.map((o, k) => ({ + findings: batches[k].idx.length, + state: o.state, + ...(o.reason ? { reason: o.reason } : {}), + turns: o.turns, + toolCalls: o.toolCalls, + ...(o.usage ? { tokens: o.usage.tokens } : {}), + })) + const usage = outcomes.flatMap((o) => (o.usage ? [o.usage] : [])) + const spent = usage.length ? usage.reduce(addUsage) : undefined + const errors = outcomes.filter((o) => o.state === "error") + const timeout = outcomes.find((o) => o.state === "timeout") + let state: VerifierStatus["state"] = "ok" + let reason: string | undefined + if (timeout) [state, reason] = ["timeout", timeout.reason] + else if (errors.length === outcomes.length) [state, reason] = ["error", errors[0].reason] + else if (outcomes.some((o) => o.state === "budget")) + [state, reason] = ["budget", "answered early to stay within the token or tool-output budget"] + if (errors.length && state !== "error") + reason = [reason, `${errors.length} of ${outcomes.length} batches failed: ${errors[0].reason}`].filter(Boolean).join("; ") + const reviewed = ruleVerdicts.filter((v) => !v.noVerdict).length + return { + state, + ...(reason ? { reason } : {}), + ...(spent ? { tokens: spent.tokens, cost: spent.cost } : {}), + turns: outcomes.reduce((n, o) => n + o.turns, 0), + toolCalls: outcomes.reduce((n, o) => n + o.toolCalls, 0), + reviewed, + kept: findings.length, + discarded: 0, + summary: 0, + unreviewed: findings.length - reviewed, + ruleVerdicts, + batches: records, + } +} + // --------------------------------------------------------------------------- // Tool loop // --------------------------------------------------------------------------- @@ -1264,6 +1360,7 @@ export async function runAiVerify( const model: Array = input.findings.map(() => undefined) batches.forEach((b, k) => b.idx.forEach((i, j) => (model[i] = outcomes[k].verdicts.get(b.ids[j])))) + if (input.rulesOnly) return { findings: input.findings, status: status(ruleStatus(input.findings, batches, outcomes, model)) } const stopped: boolean[] = input.findings.map(() => false) batches.forEach((b, k) => { if (outcomes[k].state === "budget" || outcomes[k].state === "timeout") for (const i of b.idx) stopped[i] = true diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 1abce7c828..96b687bc6c 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -57,6 +57,8 @@ export const ReviewConfig = z.object({ rulesOff: z.boolean().optional(), /** Rule ids taken back out of that list (posted as before). */ rulesOn: z.array(z.string()).optional(), + /** Verify the rule findings after the finder and drop the refuted ones (needs `verify`). */ + verifyRules: z.boolean().optional(), }), ]) .default(true), diff --git a/packages/opencode/src/altimate/review/finding.ts b/packages/opencode/src/altimate/review/finding.ts index 2e9deee61f..cc09be52ee 100644 --- a/packages/opencode/src/altimate/review/finding.ts +++ b/packages/opencode/src/altimate/review/finding.ts @@ -290,6 +290,16 @@ function repeatLabel(f: Finding, first: Finding): string { * test, one per join onto the same kind of key) into a single finding that * lists every instance. Critical findings stay separate: each one can block. */ +/** The key `mergeRepeats` groups a finding by. */ +function repeatKey(f: Finding): string { + return [f.file, f.category, f.severity, !!f.degraded, !!f.preExisting, groupKeyTitle(f)].join("|") +} + +/** The id `mergeRepeats` gives the merged finding of `f`'s group (when the group has more than one). */ +export function repeatGroupId(f: Finding): string { + return "f_" + createHash("sha256").update(`merged ${repeatKey(f)}`).digest("hex").slice(0, 16) +} + export function mergeRepeats(findings: Finding[]): Finding[] { const groups = new Map() const out: Finding[] = [] @@ -298,7 +308,7 @@ export function mergeRepeats(findings: Finding[]): Finding[] { out.push(f) continue } - const key = [f.file, f.category, f.severity, !!f.degraded, !!f.preExisting, groupKeyTitle(f)].join("|") + const key = repeatKey(f) const g = groups.get(key) if (g) g.push(f) else groups.set(key, [f]) @@ -306,14 +316,14 @@ export function mergeRepeats(findings: Finding[]): Finding[] { // A merged comment replaces its members' ids: findings folded into a member (`groupedInto`) // follow it to the merged comment. const renamed = new Map() - for (const [key, g] of groups) { + for (const g of groups.values()) { if (g.length === 1) { out.push(g[0]) continue } g.sort((a, b) => tieKey(a).localeCompare(tieKey(b))) const [first, ...rest] = g - const id = "f_" + createHash("sha256").update(`merged ${key}`).digest("hex").slice(0, 16) + const id = repeatGroupId(first) for (const m of g) renamed.set(m.id, id) // Folded only when every member is folded into the same lead: a distinct finding merged in // must stay visible on its own. diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index a77b6a2f2e..6a5a80aed0 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -309,14 +309,15 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri return signEnvelope(VerdictEnvelope.parse(merged)) } -/** Rule-noise counts summed over the projects (present only when some project has them). */ -function mergeRuleNoise(envs: VerdictEnvelope[]): Pick { - const out: Pick = {} +/** Rule-noise counts summed over the projects (each present only when some project has it). */ +function mergeRuleNoise(envs: VerdictEnvelope[]): Pick { + const out: Pick = {} if (envs.some((e) => e.rulesOff)) { const off: Record = {} for (const e of envs) for (const [rule, n] of Object.entries(e.rulesOff ?? {})) off[rule] = (off[rule] ?? 0) + n out.rulesOff = off } + if (envs.some((e) => e.rulesRefuted !== undefined)) out.rulesRefuted = envs.reduce((n, e) => n + (e.rulesRefuted ?? 0), 0) return out } @@ -377,6 +378,7 @@ function mergeAi(runs: Array<{ root: string; env: VerdictEnvelope }>): VerdictEn failedFiles: failedFiles.length ? failedFiles : undefined, conventions: conventions.length ? conventions : undefined, verifier: mergeVerifier(lanes.map((r) => ({ root: r.root, v: r.env.ai!.verifier }))), + ruleVerifier: mergeVerifier(lanes.map((r) => ({ root: r.root, v: r.env.ai!.ruleVerifier as VerifierStatus | undefined }))), projects: lanes.map((r) => ({ root: r.root, state: r.env.ai!.state, reason: r.env.ai!.reason, calls: r.env.ai!.calls })), } } @@ -423,5 +425,7 @@ function mergeVerifier(runs: Array<{ root: string; v: AiStatus["verifier"] }>): unreviewed: sumOf(vs.map((v) => v.unreviewed)), dropped: dropped.length ? dropped.slice(0, VERIFIER_DROPPED_MAX) : undefined, decisions: decisions.length ? decisions : undefined, + ruleVerdicts: vs.some((v) => v.ruleVerdicts) ? vs.flatMap((v) => v.ruleVerdicts ?? []) : undefined, + batches: vs.some((v) => v.batches) ? vs.flatMap((v) => v.batches ?? []) : undefined, } } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 4e7bc04cab..9571ea2304 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -7,7 +7,9 @@ import { ReviewCategory as ReviewCategoryEnum, makeFinding, dedupe, + findingOrigin, mergeRepeats, + repeatGroupId, SEVERITY_ORDER, } from "./finding" import { @@ -2652,6 +2654,10 @@ export async function runReview(input: OrchestrateInput): Promise() let aiReviewedOutside: string[] = [] + // The rule verifier's verdict per posted rule finding (`verifyRules`). + const ruleVerdicts = new Map() + // The rule verifier was asked to run (it may still have skipped or failed). + let ruleVerifyAttempted = false // The AI lane runs in this review: rule types off apply only then. const aiLaneOn = lanes.has("ai_review") && !!input.aiReview if (!lanes.has("ai_review")) { @@ -2798,6 +2804,16 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && findingOrigin(f) !== "ai", + ), + input.rulesOff, + ).kept + : undefined try { const res = await input.aiReview({ files: aiFiles, @@ -2812,10 +2828,15 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= minSev) - // Rule types off, only when the AI lane runs. A finding not posted does not count toward the - // verdict either. AI findings are never dropped. + // Rule noise, only when the AI lane runs: rule types off, then rule findings the verifier + // refuted. A finding not posted does not count toward the verdict + // either; an unmerged instance takes the verdict of its merged group. AI findings are never + // dropped. const rulesOff = aiLaneOn ? input.rulesOff : undefined const off = dropRulesOff(findings, rulesOff) findings = off.kept verdictFindings = dropRulesOff(verdictFindings, rulesOff).kept + const verdictOf = (f: Finding) => ruleVerdicts.get(f.id) ?? ruleVerdicts.get(repeatGroupId(f)) + const refuted = (f: Finding) => findingOrigin(f) !== "ai" && verdictOf(f) === "refuted" + const rulesRefuted = ruleVerifyAttempted ? findings.filter(refuted).length : undefined + if (ruleVerdicts.size) { + findings = findings.filter((f) => !refuted(f)) + verdictFindings = verdictFindings.filter((f) => !refuted(f)) + } // Lint-only means no changed model resolved against a manifest. A single // undecidable finding does not make the whole run lint-only; those findings @@ -2889,6 +2919,7 @@ export async function runReview(input: OrchestrateInput): Promise [], downstreamModels: async () => [] } as any, + readFile: async (_p, side, start, end) => numberedSlice(side === "new" ? HEAD : undefined, start, end), + compiledSql: async () => HEAD, + } +} + +function ruleFinding(n: number): Finding { + return makeFinding({ + severity: "warning", + category: "sql_correctness", + title: `fct: rule finding ${n}`, + body: `Rule body ${n}.`, + file: "models/fct.sql", + model: "fct", + startLine: 11, + endLine: 11, + confidence: "high", + evidence: { tool: "dbt-patterns", result: { line: "coalesce(amount_cents, 0) / 100" } }, + ruleKey: `dbt-patterns:rule-${n}`, + rule: ruleId("dbt-patterns", `rule-${n}`), + }) +} + +const verdict = (id: string, over: Record = {}) => ({ + id, + claim_type: "code_fact", + verdict: "confirmed", + value: "actionable", + requires_assumed_input: false, + evidence: "line 11: coalesce(amount_cents, 0) / 100", + tools_used: ["compiled_sql"], + ...over, +}) + +function scripted(script: (req: VerifierStepRequest, turn: number) => Partial) { + const calls: VerifierStepRequest[] = [] + const llm: VerifierLlm = async (req) => { + calls.push(req) + return { text: "", finishReason: "stop", toolCalls: [], messages: [], ...script(req, calls.length) } + } + return { llm, calls } +} +const candidateIds = (req: VerifierStepRequest) => + [...String(req.messages[0].content).matchAll(/^id: (c\d+)$/gm)].map((m) => m[1]) + +const ENV_KEYS = [ + "ALTIMATE_REVIEW_AI_VERIFY", + "ALTIMATE_REVIEW_AI_VERIFY_RULES", + "ALTIMATE_REVIEW_AI_DRYRUN", + "ALTIMATE_REVIEW_AI_VERIFY_DRYRUN", + "ALTIMATE_REVIEW_RULES_OFF", + "ALTIMATE_REVIEW_RULE_POLICY", + "ALTIMATE_REVIEW_AI_TEST_GAP", +] +let saved: Record = {} +beforeEach(() => { + saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])) + for (const k of ENV_KEYS) delete process.env[k] +}) +afterEach(() => { + mock.restore() + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k] + else process.env[k] = saved[k] + } +}) + +/** The finder answers `finderItems`; each verifier refutes candidates whose title matches `refute`. */ +function scriptModels(finderItems: unknown[], refute: RegExp) { + spyOn(Provider, "defaultModel").mockResolvedValue({ providerID: "fake", modelID: "m" } as any) + spyOn(Provider, "getModel").mockResolvedValue(FAKE_MODEL as any) + spyOn(Dispatcher, "call").mockImplementation((async (method: string) => + method === "altimate_core.review_ai_prompt" + ? { success: true, data: { prompt: "FINDER SYSTEM" } } + : { success: true, data: { findings: finderItems } }) as any) + return spyOn(LLM, "stream").mockImplementation(async (input: any) => { + const content = String(input.messages[0].content) + let text = "[]" + if (input.agent.name === "dbt-ai-verifier") { + const blocks = content.split(/^id: /m).slice(1) + text = JSON.stringify( + blocks.map((b) => + verdict(b.split("\n")[0].trim(), { verdict: refute.test(/^title: (.*)$/m.exec(b)?.[1] ?? "") ? "refuted" : "confirmed" }), + ), + ) + } + return { + fullStream: (async function* () {})(), + text: Promise.resolve(text), + finishReason: Promise.resolve("stop"), + response: Promise.resolve({ messages: [{ role: "assistant", content: text }] }), + totalUsage: Promise.resolve({ inputTokens: 1_000, outputTokens: 100, totalTokens: 1_100 }), + providerMetadata: Promise.resolve(undefined), + } as any + }) +} + +describe("verifyRules switch", () => { + test("on by default; `drop_refuted`/`1` on, `off`/`0` off; `ai.verifyRules: false` off", () => { + expect(AI_SWITCH_DEFAULTS.verifyRules).toBe(true) + expect(envSwitch("verifyRules", { ALTIMATE_REVIEW_AI_VERIFY_RULES: "drop_refuted" })).toBe(true) + expect(envSwitch("verifyRules", { ALTIMATE_REVIEW_AI_VERIFY_RULES: "1" })).toBe(true) + expect(envSwitch("verifyRules", { ALTIMATE_REVIEW_AI_VERIFY_RULES: "off" })).toBe(false) + expect(envSwitch("verifyRules", { ALTIMATE_REVIEW_AI_VERIFY_RULES: "0" })).toBe(false) + expect(envSwitch("verifyRules", { ALTIMATE_REVIEW_AI_VERIFY_RULES: "only" })).toBeUndefined() + const cfg = parseReviewConfig("ai:\n verifyRules: false") + expect(resolveAiSwitches(cfg, {}).verifyRules).toBe(false) + expect(resolveAiSwitches(cfg, { ALTIMATE_REVIEW_AI_VERIFY_RULES: "drop_refuted" }).verifyRules).toBe(true) + }) +}) + +describe("runAiVerify with rulesOnly: verdicts recorded, nothing triaged", () => { + test("each rule finding gets a verdict record; refuted and unreviewed findings come back unchanged", async () => { + const rules = [ruleFinding(1), ruleFinding(2), ruleFinding(3)] + const { llm, calls } = scripted(() => ({ + text: JSON.stringify([ + verdict("c1"), + verdict("c2", { verdict: "refuted", claim_type: "convention", value: "nit", evidence: "line 11 has no division" }), + ]), + usage: { tokens: { input: 900, inputTotal: 1_000, output: 100, reasoning: 0, cacheRead: 100 }, cost: 0.01 }, + })) + const res = await runAiVerify( + { findings: rules, grounding: rules, evidence: evidence(), model: FAKE_MODEL, rulesOnly: true }, + { llm, env: {} }, + ) + expect(calls).toHaveLength(1) + expect(res.findings).toBe(rules) + expect(res.status).toMatchObject({ state: "ok", reviewed: 2, kept: 3, discarded: 0, summary: 0, unreviewed: 1 }) + expect(res.status.dropped).toBeUndefined() + expect(res.status.decisions).toBeUndefined() + expect(res.status.ruleVerdicts!.map((v) => [v.id, v.verdict, v.noVerdict, v.batch])).toEqual([ + [rules[0].id, "confirmed", false, 0], + [rules[1].id, "refuted", false, 0], + [rules[2].id, null, true, 0], + ]) + expect(res.status.ruleVerdicts![1]).toMatchObject({ claimType: "convention", value: "nit", rule: rules[1].rule }) + expect(res.status.batches).toEqual([ + { findings: 3, state: "ok", turns: 1, toolCalls: 0, tokens: { input: 900, inputTotal: 1_000, output: 100, reasoning: 0, cacheRead: 100 } }, + ]) + }) + + test("batches of at most 8; each verdict names its batch", async () => { + const rules = Array.from({ length: 11 }, (_, i) => ruleFinding(i + 1)) + const { llm, calls } = scripted((req) => ({ text: JSON.stringify(candidateIds(req).map((id) => verdict(id))) })) + const res = await runAiVerify( + { findings: rules, grounding: [], evidence: evidence(), model: FAKE_MODEL, rulesOnly: true }, + { llm, env: {} }, + ) + expect(calls.map((c) => candidateIds(c).length).sort()).toEqual([3, 8]) + expect(res.status.ruleVerdicts!.map((v) => v.batch)).toEqual([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]) + expect(res.status).toMatchObject({ reviewed: 11, unreviewed: 0 }) + }) + + test("a failed call: every finding without a verdict, state error", async () => { + const rules = [ruleFinding(1)] + const llm: VerifierLlm = async () => { + throw new Error("provider down") + } + const res = await runAiVerify( + { findings: rules, grounding: [], evidence: evidence(), model: FAKE_MODEL, rulesOnly: true }, + { llm, env: {} }, + ) + expect(res.findings).toBe(rules) + expect(res.status).toMatchObject({ state: "error", reviewed: 0, unreviewed: 1 }) + expect(res.status.ruleVerdicts!.map((v) => v.noVerdict)).toEqual([true]) + }) +}) + +describe("runRuleVerify", () => { + test("skips without a model call: no evidence, no rule findings, dry run", async () => { + const llm = scriptModels([], /x/) + const base: AiReviewInput = { files: [FILE], grounding: [] } + expect((await runRuleVerify(base, [ruleFinding(1)])).status.verifier).toMatchObject({ state: "skipped" }) + expect((await runRuleVerify({ ...base, evidence: evidence() }, [])).status.verifier).toMatchObject({ + state: "skipped", + reason: NO_RULE_FINDINGS_REASON, + }) + const dry = await runRuleVerify({ ...base, evidence: evidence() }, [ruleFinding(1)], { env: { ALTIMATE_REVIEW_AI_DRYRUN: "1" } }) + expect(dry.status.verifier?.state).toBe("skipped") + expect(llm).not.toHaveBeenCalled() + }) +}) + +describe("runAiReview with verifyRulesAfter", () => { + test("finder first, then the rule verifier; verdicts recorded, the finder's own status kept", async () => { + const llm = scriptModels([], /rule finding 1$/) + const rules = [ruleFinding(1), ruleFinding(2)] + const res = await runAiReview({ files: [FILE], grounding: rules, evidence: evidence(), verifyRulesAfter: rules }) + expect(llm.mock.calls.map((c: any) => c[0].agent.name)).toEqual(["dbt-ai-reviewer", "dbt-ai-verifier"]) + expect(res.findings).toEqual([]) + expect(res.status).toMatchObject({ state: "ok", calls: 1, verifyRules: "drop_refuted" }) + expect(res.status.verifier?.ruleVerdicts?.map((v) => [v.id, v.verdict])).toEqual([ + [rules[0].id, "refuted"], + [rules[1].id, "confirmed"], + ]) + // No AI verifier configured: its counters stay empty; the rule run's spend is under ruleVerifier. + expect(res.status.verifier).toMatchObject({ state: "skipped", turns: 0, reviewed: 0 }) + expect(res.status.ruleVerifier).toMatchObject({ state: "ok", model: "fake/m", turns: 1, reviewed: 2, unreviewed: 0 }) + expect(res.status.ruleVerifier).not.toHaveProperty("ruleVerdicts") + }) + + test("with the AI verifier on: it verifies the finder's findings first, the rule run comes after", async () => { + const finderItem = { file: "models/fct.sql", line: 11, severity: "warning", category: "sql_correctness", title: "ai claim", body: "AI body.", confidence: "high" } + const llm = scriptModels([finderItem], /rule finding 2$/) + const rules = [ruleFinding(1), ruleFinding(2)] + const res = await runAiReview({ + files: [FILE], + grounding: rules, + evidence: evidence(), + switches: { verify: true }, + verifyRulesAfter: rules, + }) + const calls = llm.mock.calls.map((c: any) => [c[0].agent.name, String(c[0].messages[0].content).includes("rule finding 1")]) + expect(calls).toEqual([ + ["dbt-ai-reviewer", true], + ["dbt-ai-verifier", false], + ["dbt-ai-verifier", true], + ]) + expect(res.findings.map((f) => f.title)).toEqual(["fct: ai claim"]) + expect(res.status.verifier).toMatchObject({ state: "ok", reviewed: 1 }) + expect(res.status.verifier?.ruleVerdicts?.map((v) => v.verdict)).toEqual(["confirmed", "refuted"]) + expect(res.status.ruleVerifier).toMatchObject({ state: "ok", reviewed: 2 }) + }) + + test("without verifyRulesAfter the lane is exactly the finder lane", async () => { + const llm = scriptModels([], /x/) + const res = await runAiReview({ files: [FILE], grounding: [ruleFinding(1)], evidence: evidence() }) + expect(llm.mock.calls.map((c: any) => c[0].agent.name)).toEqual(["dbt-ai-reviewer"]) + expect(res.status.verifyRules).toBeUndefined() + expect(res.status.ruleVerifier).toBeUndefined() + }) + + test("withRuleVerdicts on a skipped rule run: recorded as skipped, findings untouched", () => { + const res: AiReviewResult = { findings: [], status: { state: "ok", calls: 1 } } + const out = withRuleVerdicts(res, { findings: [], status: { state: "skipped", reason: "the verifier's evidence is unavailable", durationMs: 0 } }) + expect(out.findings).toBe(res.findings) + expect(out.status).toMatchObject({ + state: "ok", + calls: 1, + verifyRules: "drop_refuted", + ruleVerifier: { state: "skipped", reason: "the verifier's evidence is unavailable" }, + }) + expect(out.status.verifier?.ruleVerdicts).toBeUndefined() + }) +}) + +// --------------------------------------------------------------------------- +// Orchestrator +// --------------------------------------------------------------------------- + +const runner: ReviewRunner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, +} as ReviewRunner +const SQL = "select *\nfrom raw.orders\nwhere status = 'x'\norder by 1" +const aiFinding = makeFinding({ + severity: "warning", + category: "sql_correctness", + title: "m: ai claim", + body: "AI body.", + file: "models/marts/m.sql", + model: "m", + startLine: 2, + endLine: 2, + evidence: { tool: "ai-review", result: {} }, + ruleKey: "ai:sql_correctness:ai claim", + rule: ruleId("ai-review", "sql_correctness"), +}) + +function run(seen: AiReviewInput[], switches: Partial, refuteFirst = true) { + return runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiVerify: true, + aiSwitches: switches, + getContent: async (_f, side) => (side === "old" ? "select 1" : SQL), + generatedAt: "2026-11-25T00:00:00Z", + aiReview: async (input) => { + seen.push(input) + const rules = input.verifyRulesAfter + return { + findings: [aiFinding], + status: { + state: "ok", + ...(rules + ? { + verifyRules: "drop_refuted" as const, + verifier: { + state: "skipped" as const, + durationMs: 0, + turns: 0, + toolCalls: 0, + reviewed: 0, + kept: 0, + discarded: 0, + summary: 0, + unreviewed: 0, + ruleVerdicts: rules.map((f, i) => ({ + id: f.id, + file: f.file, + title: f.title, + rule: f.rule, + verdict: i === 0 && refuteFirst ? ("refuted" as const) : ("confirmed" as const), + claimType: "code_fact" as const, + value: "actionable" as const, + evidence: "quoted", + toolsUsed: [], + noVerdict: false, + batch: 0, + })), + batches: [{ findings: rules.length, state: "ok" as const, turns: 1, toolCalls: 0 }], + }, + ruleVerifier: { + state: "ok" as const, + durationMs: 1, + turns: 1, + toolCalls: 0, + reviewed: rules.length, + kept: rules.length, + discarded: 0, + summary: 0, + unreviewed: 0, + }, + } + : {}), + }, + } + }, + }) +} + +describe("orchestrator: drop_refuted", () => { + const OFF = { verifyRules: false, rulePolicy: false } + const ON = { verifyRules: true, rulePolicy: false } + + test("off: no verifyRulesAfter; on: same lane input plus the posted rule findings, refuted ones not posted", async () => { + const off: AiReviewInput[] = [] + const envOff = await run(off, OFF) + expect("verifyRulesAfter" in off[0]).toBe(false) + expect(envOff.rulesRefuted).toBeUndefined() + + const on: AiReviewInput[] = [] + const envOn = await run(on, ON) + const { verifyRulesAfter, ...rest } = on[0] + expect(Object.keys(rest).sort()).toEqual(Object.keys(off[0]).sort()) + // Exactly the rule findings the switch-off envelope posts. + const offRules = envOff.findings.filter((f) => f.origin !== "ai") + expect(offRules.length).toBeGreaterThan(1) + expect(verifyRulesAfter!.map((f) => f.id)).toEqual(offRules.map((f) => f.id)) + // The first is refuted: gone; the AI finding and the confirmed rule findings stay. + expect(envOn.findings).toEqual(envOff.findings.filter((f) => f.id !== verifyRulesAfter![0].id)) + expect(envOn.findings.some((f) => f.origin === "ai")).toBe(true) + expect(envOn.rulesRefuted).toBe(1) + expect(envOn.ai?.verifyRules).toBe("drop_refuted") + expect(envOn.ai?.ruleVerifier).toMatchObject({ state: "ok", reviewed: verifyRulesAfter!.length }) + + // Nothing refuted: nothing dropped. + const none = await run([], ON, false) + expect(none.findings).toEqual(envOff.findings) + expect(none.rulesRefuted).toBe(0) + }) + + test("without the AI verifier's evidence (`aiVerify` off) the rule verifier does not run", async () => { + const seen: AiReviewInput[] = [] + await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiSwitches: ON, + getContent: async (_f, side) => (side === "old" ? "select 1" : SQL), + aiReview: async (input) => { + seen.push(input) + return { findings: [], status: { state: "ok" } } + }, + }) + expect("verifyRulesAfter" in seen[0]).toBe(false) + }) + + test("rule types off are left out before verification", async () => { + const all: AiReviewInput[] = [] + await run(all, ON, false) + const first = all[0].verifyRulesAfter! + const less: AiReviewInput[] = [] + const seenRules = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiVerify: true, + aiSwitches: ON, + rulesOff: new Set([first[0].rule!]), + getContent: async (_f, side) => (side === "old" ? "select 1" : SQL), + aiReview: async (input) => { + less.push(input) + return { findings: [], status: { state: "ok" } } + }, + }) + expect(less[0].verifyRulesAfter).toEqual(first.filter((f) => f.rule !== first[0].rule)) + expect(seenRules.rulesOff).toEqual({ [first[0].rule!]: first.filter((f) => f.rule === first[0].rule).length }) + }) +}) From 0091b0269139d838726fd3cc3baea90bddca165e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 11:17:47 +0530 Subject: [PATCH 03/32] feat(review): rule-post policy over the verified rule findings - `rule-post-policy.ts`, pure `dropByRulePolicy(findings, verdictById, policy)`: after rule types off and the refuted filter, a rule finding is not posted when (1) its verdict is `unverifiable` and its severity is warning or critical, or (2) its rule type is on the noisy list and its verdict is not `confirmed`; a finding with no verdict counts as unverifiable; AI findings are never touched - `NOISY_RULE_TYPES`: the 7 rule types at least 30% wrong over at least 3 posted findings on replayed public dbt PRs, shipped as the default list - fail-open: when the rule verifier did not run at all (skipped, failed, or stopped on budget with nothing reviewed) the policy is skipped and every rule finding is posted as before - `rulePolicy` switch, on by default with the rule verifier: `ai.rulePolicy: false` or `ALTIMATE_REVIEW_RULE_POLICY=0` turns it off; `ai.rulePolicy: {noisyRules: [...]}` replaces the noisy list - envelope: `rulePolicy: {applied, dropped: {unverifiable_high_sev, noisy_type_not_confirmed}}` next to `rulesOff`, merged across projects under `--all-projects` - tests: both conditions, severities, missing verdicts, AI findings kept, custom list, fail-open states, config and env, orchestrator drops and counts, switches off and AI lane off unchanged Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-switches.ts | 11 +- .../opencode/src/altimate/review/config.ts | 2 + .../src/altimate/review/multi-project.ts | 13 +- .../src/altimate/review/orchestrate.ts | 22 +- .../src/altimate/review/rule-post-policy.ts | 72 ++++ packages/opencode/src/altimate/review/run.ts | 2 + .../opencode/src/altimate/review/verdict.ts | 12 + .../altimate/review-rule-post-policy.test.ts | 346 ++++++++++++++++++ 8 files changed, 474 insertions(+), 6 deletions(-) create mode 100644 packages/opencode/src/altimate/review/rule-post-policy.ts create mode 100644 packages/opencode/test/altimate/review-rule-post-policy.test.ts diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index 8e023d2083..f0cf4bd9fc 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -18,6 +18,7 @@ export type AiSwitchName = | "conventions" | "rulesOff" | "verifyRules" + | "rulePolicy" export type AiSwitches = Record @@ -32,6 +33,7 @@ export const AI_SWITCH_ENV: Record = { conventions: "ALTIMATE_REVIEW_CONVENTIONS", rulesOff: "ALTIMATE_REVIEW_RULES_OFF", verifyRules: "ALTIMATE_REVIEW_AI_VERIFY_RULES", + rulePolicy: "ALTIMATE_REVIEW_RULE_POLICY", } /** @@ -49,6 +51,7 @@ export const AI_SWITCH_DEFAULTS: AiSwitches = { conventions: true, rulesOff: true, verifyRules: true, + rulePolicy: true, } type Env = Record @@ -99,11 +102,17 @@ export function resolveAiSwitches( WARNED.add(warning) process.stderr.write(`⚠️ ignoring ${AI_SWITCH_ENV[name]}=${raw}: use 1/0 (or true/false, on/off, yes/no)\n`) } - out[name] = fromEnv ?? configured[name] ?? AI_SWITCH_DEFAULTS[name] + out[name] = fromEnv ?? configuredSwitch(configured[name as keyof typeof configured]) ?? AI_SWITCH_DEFAULTS[name] } return out } +/** A config value as a switch: a boolean as is, an object (settings for the switch) as on. */ +function configuredSwitch(v: unknown): boolean | undefined { + if (typeof v === "boolean") return v + return v && typeof v === "object" && !Array.isArray(v) ? true : undefined +} + /** A switch from resolved switches when given, else from its env variable alone (unset = off). */ export function switchOn(name: AiSwitchName, switches: Partial | undefined, env: Env = process.env): boolean { return switches?.[name] ?? envSwitch(name, env) ?? false diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 96b687bc6c..0a613603c9 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -59,6 +59,8 @@ export const ReviewConfig = z.object({ rulesOn: z.array(z.string()).optional(), /** Verify the rule findings after the finder and drop the refuted ones (needs `verify`). */ verifyRules: z.boolean().optional(), + /** The rule-post policy over verified rule findings (rule-post-policy.ts); an object changes its noisy list. */ + rulePolicy: z.union([z.boolean(), z.object({ noisyRules: z.array(z.string()).optional() })]).optional(), }), ]) .default(true), diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 6a5a80aed0..26347da972 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -310,14 +310,23 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri } /** Rule-noise counts summed over the projects (each present only when some project has it). */ -function mergeRuleNoise(envs: VerdictEnvelope[]): Pick { - const out: Pick = {} +function mergeRuleNoise(envs: VerdictEnvelope[]): Pick { + const out: Pick = {} if (envs.some((e) => e.rulesOff)) { const off: Record = {} for (const e of envs) for (const [rule, n] of Object.entries(e.rulesOff ?? {})) off[rule] = (off[rule] ?? 0) + n out.rulesOff = off } if (envs.some((e) => e.rulesRefuted !== undefined)) out.rulesRefuted = envs.reduce((n, e) => n + (e.rulesRefuted ?? 0), 0) + const policies = envs.flatMap((e) => (e.rulePolicy ? [e.rulePolicy] : [])) + if (policies.length) + out.rulePolicy = { + applied: policies.some((p) => p.applied), + dropped: { + unverifiable_high_sev: policies.reduce((n, p) => n + p.dropped.unverifiable_high_sev, 0), + noisy_type_not_confirmed: policies.reduce((n, p) => n + p.dropped.noisy_type_not_confirmed, 0), + }, + } return out } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 9571ea2304..e51f07bb2e 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -72,6 +72,7 @@ import { isAiOtherFile } from "./ai-other-files" import { AI_PYTHON_KIND, isAiPythonFile } from "./ai-python-files" import { type Convention, conventionTexts } from "./conventions" import { dropRulesOff } from "./rules-off" +import { type RulePolicyDrops, type RulePostPolicy, type RuleVerdictValue, dropByRulePolicy, rulePolicyApplies } from "./rule-post-policy" import { type AiVerifyEvidence, numberedSlice } from "./ai-verify" import { holdsCredentials, isCredentialPath } from "./credentials" import type { ColumnReach } from "../native/dbt/column-reach" @@ -307,6 +308,8 @@ export interface OrchestrateInput { conventions?: Convention[] /** Rule ids not posted when the AI lane runs (rules-off.ts); undefined keeps every type. */ rulesOff?: Set + /** The rule-post policy over verified rule findings (rule-post-policy.ts); undefined turns it off. */ + rulePolicy?: RulePostPolicy /** Fixed-string search over the dbt project at head, for the verifier. */ grepProject?: AiVerifyEvidence["grepProject"] /** Every file the PR changes (repo-relative), including files outside the dbt project; the verifier may read them. */ @@ -2654,8 +2657,9 @@ export async function runReview(input: OrchestrateInput): Promise() let aiReviewedOutside: string[] = [] - // The rule verifier's verdict per posted rule finding (`verifyRules`). - const ruleVerdicts = new Map() + // The rule verifier's verdict per posted rule finding (`verifyRules`), and whether it ran. + const ruleVerdicts = new Map() + let ruleVerifierRan = false // The rule verifier was asked to run (it may still have skipped or failed). let ruleVerifyAttempted = false // The AI lane runs in this review: rule types off apply only then. @@ -2836,6 +2840,7 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= minSev) // Rule noise, only when the AI lane runs: rule types off, then rule findings the verifier - // refuted. A finding not posted does not count toward the verdict + // refuted, then the rule-post policy. A finding not posted does not count toward the verdict // either; an unmerged instance takes the verdict of its merged group. AI findings are never // dropped. const rulesOff = aiLaneOn ? input.rulesOff : undefined @@ -2878,6 +2883,16 @@ export async function runReview(input: OrchestrateInput): Promise !refuted(f)) verdictFindings = verdictFindings.filter((f) => !refuted(f)) } + let rulePolicy: { applied: boolean; dropped: RulePolicyDrops } | undefined + if (aiLaneOn && input.rulePolicy && ruleVerifyAttempted) { + if (ruleVerifierRan) { + const byId = (list: Finding[]) => new Map(list.map((f) => [f.id, verdictOf(f) ?? null] as const)) + const posted = dropByRulePolicy(findings, byId(findings), input.rulePolicy) + findings = posted.kept + verdictFindings = dropByRulePolicy(verdictFindings, byId(verdictFindings), input.rulePolicy).kept + rulePolicy = { applied: true, dropped: posted.dropped } + } else rulePolicy = { applied: false, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } } + } // Lint-only means no changed model resolved against a manifest. A single // undecidable finding does not make the whole run lint-only; those findings @@ -2920,6 +2935,7 @@ export async function runReview(input: OrchestrateInput): Promise, + policy: RulePostPolicy = DEFAULT_RULE_POST_POLICY, +): { kept: Finding[]; dropped: RulePolicyDrops } { + const dropped: RulePolicyDrops = { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } + const kept = findings.filter((f) => { + const why = rulePolicyDrop(f, verdictById.get(f.id), policy) + if (why) dropped[why]++ + return !why + }) + return { kept, dropped } +} + +/** Whether the rule verifier ran enough for the policy: it reviewed at least one finding. */ +export function rulePolicyApplies(ruleVerifier: { state: string; reviewed?: number } | undefined): boolean { + return !!ruleVerifier && ruleVerifier.state !== "skipped" && (ruleVerifier.reviewed ?? 0) > 0 +} + +/** The policy configured under `ai.rulePolicy` (an object changes the noisy list). */ +export function configuredRulePolicy(cfg: { ai: unknown }): RulePostPolicy { + const rp = cfg.ai && typeof cfg.ai === "object" ? (cfg.ai as { rulePolicy?: unknown }).rulePolicy : undefined + const noisy = rp && typeof rp === "object" ? (rp as { noisyRules?: string[] }).noisyRules : undefined + return noisy ? { noisyRules: noisy } : DEFAULT_RULE_POST_POLICY +} diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index cf440d4441..f0588a6fc9 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -32,6 +32,7 @@ import { resolveAiSwitches } from "./ai-switches" import { isAiPythonFile } from "./ai-python-files" import { loadConventions } from "./conventions" import { resolveRulesOff } from "./rules-off" +import { configuredRulePolicy } from "./rule-post-policy" import { loadConsumerLists } from "./consumer-lists" import type { ReviewMode, VerdictEnvelope } from "./verdict" import type { ChangedFile } from "./diff-filter" @@ -544,6 +545,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise reviewDir: gitRoot, ...(conventions.length ? { conventions } : {}), ...(rulesOff ? { rulesOff } : {}), + ...(aiOn && aiSwitches.rulePolicy ? { rulePolicy: configuredRulePolicy(config) } : {}), grepProject: (pattern, glob) => { // The project's dbt directories (repo-relative), or one glob inside the project. const dirs = layout diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index 8ca316f4d4..05b262ea92 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -429,6 +429,16 @@ export const VerdictEnvelope = z.object({ rulesOff: z.record(z.string(), z.number().int().nonnegative()).optional(), /** Rule findings not posted because the rule verifier refuted them. */ rulesRefuted: z.number().int().nonnegative().optional(), + /** The rule-post policy: whether it applied (the rule verifier reviewed findings) and what it dropped. */ + rulePolicy: z + .object({ + applied: z.boolean(), + dropped: z.object({ + unverifiable_high_sev: z.number().int().nonnegative(), + noisy_type_not_confirmed: z.number().int().nonnegative(), + }), + }) + .optional(), /** ISO timestamp; injected by the caller (no clock access in pure code). */ generatedAt: z.string().optional(), /** Optional break-glass override record. */ @@ -496,6 +506,7 @@ export interface BuildEnvelopeInput { engineErrors?: VerdictEnvelope["engineErrors"] rulesOff?: VerdictEnvelope["rulesOff"] rulesRefuted?: VerdictEnvelope["rulesRefuted"] + rulePolicy?: VerdictEnvelope["rulePolicy"] } /** Severity tally of `findings` for the envelope summary. */ @@ -565,6 +576,7 @@ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { ai: input.ai, ...(input.rulesOff ? { rulesOff: input.rulesOff } : {}), ...(input.rulesRefuted !== undefined ? { rulesRefuted: input.rulesRefuted } : {}), + ...(input.rulePolicy ? { rulePolicy: input.rulePolicy } : {}), policy: input.policy, engineErrors: input.engineErrors, generatedAt: input.generatedAt, diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts new file mode 100644 index 0000000000..5b1f4f58c3 --- /dev/null +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -0,0 +1,346 @@ +import { describe, test, expect } from "bun:test" +import { + DEFAULT_RULE_POST_POLICY, + NOISY_RULE_TYPES, + configuredRulePolicy, + dropByRulePolicy, + rulePolicyApplies, + type RuleVerdictValue, +} from "../../src/altimate/review/rule-post-policy" +import { envSwitch, resolveAiSwitches, AI_SWITCH_DEFAULTS, type AiSwitches } from "../../src/altimate/review/ai-switches" +import { makeFinding, ruleId, type Finding, type Severity } from "../../src/altimate/review/finding" +import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG, parseReviewConfig } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import type { AiLaneStatus, AiReviewInput } from "../../src/altimate/review/ai-review" + +// The rule-post policy: after rule types off and refuted rule findings, a rule finding is not +// posted when its verdict is unverifiable at warning/critical, or its type is noisy and not confirmed. + +const NOISY = NOISY_RULE_TYPES[0] + +function rule(n: number, severity: Severity, r = ruleId("dbt-patterns", `rule-${n}`)): Finding { + return makeFinding({ + severity, + category: "sql_correctness", + title: `m: rule ${n}`, + body: "b", + file: "models/m.sql", + evidence: { tool: r.split(":")[0], result: {} }, + ruleKey: `${r}-${n}`, + rule: r, + }) +} +function ai(n: number, severity: Severity, r = ruleId("ai-review", "sql_correctness")): Finding { + return makeFinding({ + severity, + category: "sql_correctness", + title: `m: ai ${n}`, + body: "b", + file: "models/m.sql", + evidence: { tool: "ai-review", result: {} }, + ruleKey: `ai:${n}`, + rule: r, + }) +} +const verdicts = (pairs: Array<[Finding, RuleVerdictValue | null]>) => new Map(pairs.map(([f, v]) => [f.id, v] as const)) + +describe("dropByRulePolicy", () => { + test("condition 1: unverifiable at warning or critical is dropped; at suggestion it stays", () => { + const w = rule(1, "warning") + const c = rule(2, "critical") + const s = rule(3, "suggestion") + const r = dropByRulePolicy([w, c, s], verdicts([[w, "unverifiable"], [c, "unverifiable"], [s, "unverifiable"]])) + expect(r.kept).toEqual([s]) + expect(r.dropped).toEqual({ unverifiable_high_sev: 2, noisy_type_not_confirmed: 0 }) + }) + + test("condition 2: a noisy type stays only when confirmed", () => { + const confirmed = rule(1, "suggestion", NOISY) + const unverifiable = rule(2, "suggestion", NOISY) + const refuted = rule(3, "warning", NOISY) + const r = dropByRulePolicy( + [confirmed, unverifiable, refuted], + verdicts([[confirmed, "confirmed"], [unverifiable, "unverifiable"], [refuted, "refuted"]]), + ) + expect(r.kept).toEqual([confirmed]) + expect(r.dropped).toEqual({ unverifiable_high_sev: 0, noisy_type_not_confirmed: 2 }) + }) + + test("confirmed and refuted findings of other types stay (refuted ones are the refuted filter's job)", () => { + const a = rule(1, "warning") + const b = rule(2, "critical") + const r = dropByRulePolicy([a, b], verdicts([[a, "confirmed"], [b, "refuted"]])) + expect(r.kept).toEqual([a, b]) + }) + + test("a finding with no verdict (null or absent) counts as unverifiable", () => { + const nul = rule(1, "warning") + const absent = rule(2, "warning") + const noisySuggestion = rule(3, "suggestion", NOISY) + const plainSuggestion = rule(4, "suggestion") + const r = dropByRulePolicy([nul, absent, noisySuggestion, plainSuggestion], verdicts([[nul, null]])) + expect(r.kept).toEqual([plainSuggestion]) + expect(r.dropped).toEqual({ unverifiable_high_sev: 2, noisy_type_not_confirmed: 1 }) + }) + + test("AI findings are never dropped, whatever their verdict, severity or rule id", () => { + const fs = [ai(1, "warning"), ai(2, "critical"), ai(3, "suggestion", NOISY)] + const r = dropByRulePolicy(fs, new Map()) + expect(r.kept).toEqual(fs) + expect(r.dropped).toEqual({ unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 }) + }) + + test("a custom noisy list replaces the default", () => { + const f = rule(1, "suggestion", "x:custom") + expect(dropByRulePolicy([f], verdicts([[f, "unverifiable"]])).kept).toEqual([f]) + expect(dropByRulePolicy([f], verdicts([[f, "unverifiable"]]), { noisyRules: ["x:custom"] }).kept).toEqual([]) + }) +}) + +describe("rulePolicyApplies (fail-open)", () => { + test("only when the rule verifier ran and reviewed at least one finding", () => { + expect(rulePolicyApplies(undefined)).toBe(false) + expect(rulePolicyApplies({ state: "skipped", reviewed: 0 })).toBe(false) + expect(rulePolicyApplies({ state: "error", reviewed: 0 })).toBe(false) + expect(rulePolicyApplies({ state: "budget", reviewed: 0 })).toBe(false) + expect(rulePolicyApplies({ state: "timeout" })).toBe(false) + expect(rulePolicyApplies({ state: "budget", reviewed: 2 })).toBe(true) + expect(rulePolicyApplies({ state: "ok", reviewed: 1 })).toBe(true) + }) +}) + +describe("configuration", () => { + test("seven noisy types by default", () => { + expect(NOISY_RULE_TYPES).toHaveLength(7) + expect(DEFAULT_RULE_POST_POLICY.noisyRules).toBe(NOISY_RULE_TYPES) + }) + + test("`ai.rulePolicy`: false off, an object on with its noisy list; env `0` off", () => { + expect(AI_SWITCH_DEFAULTS.rulePolicy).toBe(true) + expect(resolveAiSwitches(parseReviewConfig("ai:\n rulePolicy: false"), {}).rulePolicy).toBe(false) + const obj = parseReviewConfig("ai:\n rulePolicy:\n noisyRules:\n - x:y") + expect(resolveAiSwitches(obj, {}).rulePolicy).toBe(true) + expect(configuredRulePolicy(obj)).toEqual({ noisyRules: ["x:y"] }) + expect(configuredRulePolicy(DEFAULT_REVIEW_CONFIG)).toBe(DEFAULT_RULE_POST_POLICY) + expect(envSwitch("rulePolicy", { ALTIMATE_REVIEW_RULE_POLICY: "0" })).toBe(false) + expect(resolveAiSwitches(obj, { ALTIMATE_REVIEW_RULE_POLICY: "0" }).rulePolicy).toBe(false) + }) +}) + +// --------------------------------------------------------------------------- +// Orchestrator +// --------------------------------------------------------------------------- + +const runner: ReviewRunner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + // One error-severity engine issue: a warning-severity rule finding. + async check() { + return { issues: [{ rule: "ambiguous-column", severity: "error", category: "correctness", message: "ambiguous column status", line: 3 }], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, +} as ReviewRunner +const SQL = "select *\nfrom raw.orders\nwhere status = 'x'\norder by 1" +const aiFinding = makeFinding({ + severity: "warning", + category: "sql_correctness", + title: "m: ai claim", + body: "AI body.", + file: "models/marts/m.sql", + model: "m", + startLine: 2, + endLine: 2, + evidence: { tool: "ai-review", result: {} }, + ruleKey: "ai:sql_correctness:ai claim", + rule: ruleId("ai-review", "sql_correctness"), +}) + +type RuleVerifierState = NonNullable["state"] +interface RunOpts { + switches?: Partial + /** The verdict per rule finding sent (by index); undefined leaves the finding without a verdict. */ + verdictAt?: (i: number) => RuleVerdictValue | undefined + ruleState?: RuleVerifierState + policy?: boolean + rulesOff?: Set + ai?: boolean +} + +function run(o: RunOpts = {}, seen: AiReviewInput[] = []) { + return runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiVerify: true, + aiSwitches: o.switches ?? { verifyRules: true, rulePolicy: true }, + getContent: async (_f, side) => (side === "old" ? "select 1" : SQL), + generatedAt: "2026-11-25T00:00:00Z", + ...(o.policy === false ? {} : { rulePolicy: DEFAULT_RULE_POST_POLICY }), + ...(o.rulesOff ? { rulesOff: o.rulesOff } : {}), + ...(o.ai === false + ? {} + : { + aiReview: async (input: AiReviewInput) => { + seen.push(input) + const rules = input.verifyRulesAfter + if (!rules) return { findings: [aiFinding], status: { state: "ok" as const } } + const at = o.verdictAt ?? (() => "confirmed" as const) + const records = rules.map((f, i) => { + const v = at(i) + return { + id: f.id, + file: f.file, + title: f.title, + rule: f.rule, + verdict: v ?? null, + claimType: v ? ("code_fact" as const) : null, + value: v ? ("actionable" as const) : null, + evidence: v ? "quoted" : null, + toolsUsed: [], + noVerdict: !v, + batch: 0, + } + }) + const reviewed = records.filter((r) => !r.noVerdict).length + const state = o.ruleState ?? "ok" + return { + findings: [aiFinding], + status: { + state: "ok" as const, + verifyRules: "drop_refuted" as const, + verifier: { + state: "skipped" as const, + durationMs: 0, + turns: 0, + toolCalls: 0, + reviewed: 0, + kept: 0, + discarded: 0, + summary: 0, + unreviewed: 0, + ...(state === "skipped" ? {} : { ruleVerdicts: records }), + }, + ruleVerifier: { + state, + durationMs: 1, + turns: 1, + toolCalls: 0, + reviewed: state === "skipped" ? 0 : reviewed, + kept: rules.length, + discarded: 0, + summary: 0, + unreviewed: rules.length - reviewed, + }, + }, + } + }, + }), + }) +} + +describe("orchestrator: rule-post policy", () => { + test("drops unverifiable warning rule findings, keeps the AI finding, records counts", async () => { + const base = await run({ switches: { verifyRules: false, rulePolicy: false }, policy: false }) + const seen: AiReviewInput[] = [] + // Every rule finding unverifiable. + const env = await run({ verdictAt: () => "unverifiable" }, seen) + const sent = seen[0].verifyRulesAfter! + const highSev = sent.filter((f) => f.severity !== "suggestion") + expect(highSev.length).toBeGreaterThan(0) + expect(env.findings.map((f) => f.id)).toEqual( + base.findings.filter((f) => !highSev.some((h) => h.id === f.id)).map((f) => f.id), + ) + expect(env.findings.some((f) => f.origin === "ai")).toBe(true) + expect(env.rulePolicy?.applied).toBe(true) + expect(env.rulePolicy?.dropped.unverifiable_high_sev).toBe(highSev.length) + expect(env.rulesRefuted).toBe(0) + }) + + test("a single rule finding with no verdict counts as unverifiable", async () => { + const seen: AiReviewInput[] = [] + const all = await run({}, seen) + const sent = seen[0].verifyRulesAfter! + const idx = sent.findIndex((f) => f.severity !== "suggestion") + expect(idx).toBeGreaterThanOrEqual(0) + const env = await run({ verdictAt: (i) => (i === idx ? undefined : "confirmed") }) + expect(env.findings).toEqual(all.findings.filter((f) => f.id !== sent[idx].id)) + expect(env.rulePolicy).toEqual({ applied: true, dropped: { unverifiable_high_sev: 1, noisy_type_not_confirmed: 0 } }) + }) + + test("all confirmed: nothing dropped, applied with zero counts", async () => { + const base = await run({ switches: { verifyRules: false, rulePolicy: false }, policy: false }) + const env = await run({ verdictAt: () => "confirmed" }) + expect(env.findings).toEqual(base.findings) + expect(env.rulePolicy).toEqual({ applied: true, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } }) + }) + + test("fail-open: the rule verifier skipped, failed, or stopped on budget with nothing reviewed", async () => { + const base = await run({ switches: { verifyRules: false, rulePolicy: false }, policy: false }) + for (const ruleState of ["skipped", "error", "budget"] as const) { + const env = await run({ verdictAt: () => undefined, ruleState }) + expect(env.findings).toEqual(base.findings) + expect(env.rulePolicy).toEqual({ applied: false, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } }) + } + }) + + test("budget with some findings reviewed: the policy applies, unreviewed findings count as unverifiable", async () => { + const seen: AiReviewInput[] = [] + const env = await run({ verdictAt: (i) => (i === 0 ? "confirmed" : undefined), ruleState: "budget" }, seen) + expect(env.rulePolicy?.applied).toBe(true) + const sent = seen[0].verifyRulesAfter! + const expected = sent.slice(1).filter((f) => f.severity !== "suggestion").length + expect(env.rulePolicy?.dropped.unverifiable_high_sev).toBe(expected) + }) + + test("policy off (switch or no policy given): only refuted findings are dropped", async () => { + const base = await run({ switches: { verifyRules: false, rulePolicy: false }, policy: false }) + const env = await run({ verdictAt: () => "unverifiable", policy: false }) + expect(env.findings).toEqual(base.findings) + expect(env.rulePolicy).toBeUndefined() + }) +}) + +describe("flags off: unchanged behaviour", () => { + test("AI lane on with every rule-noise switch off: the envelope equals a run without them", async () => { + const plain = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiVerify: true, + aiSwitches: {}, + getContent: async (_f, side) => (side === "old" ? "select 1" : SQL), + generatedAt: "2026-11-25T00:00:00Z", + aiReview: async () => ({ findings: [aiFinding], status: { state: "ok" as const } }), + }) + const off = await run({ switches: { verifyRules: false, rulePolicy: false }, policy: false }) + expect(off).toEqual(plain) + expect(off.rulesOff).toBeUndefined() + expect(off.rulesRefuted).toBeUndefined() + expect(off.rulePolicy).toBeUndefined() + }) + + test("AI lane off: rule types off, the rule verifier and the policy are all no-ops", async () => { + const plain = await run({ ai: false, switches: {}, policy: false }) + const first = plain.findings[0].rule! + const withAll = await run({ ai: false, rulesOff: new Set([first]) }) + expect(withAll).toEqual(plain) + expect(withAll.rulesOff).toBeUndefined() + expect(withAll.rulePolicy).toBeUndefined() + }) +}) From bbce328f6a7517b539099097262af0af09075f8c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 11:17:59 +0530 Subject: [PATCH 04/32] docs(review): rule types off, the rule verifier and the rule-post policy - the `ai:` keys `rulesOff`, `rulesOn`, `verifyRules`, `rulePolicy` and their env variables - what each step drops, the fail-open case, and the envelope counts - a critical rule finding the rule verifier refuted or could not check no longer blocks Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 0915998e97..2b824d9232 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -302,6 +302,10 @@ ai: true # the advisory AI lane; false turns it off. Or an # pythonFiles: true # changed Python files, inside or outside the project # verify: true # the dbt-grounded verifier over the AI comments # conventions: true # repo review instructions from the base branch (see below) +# rulesOff: true # stop posting 36 noisy rule types while the AI lane runs +# rulesOn: [] # rule ids taken back out of that list +# verifyRules: true # verify the posted rule findings; refuted ones are not posted +# rulePolicy: true # post-verification rule policy; or {noisyRules: [...]} dataDiff: # OFF by default — see "Data-diff in CI" below enabled: false warehouse: "" # connection name; empty = default connection @@ -669,11 +673,24 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne secret-named settings whose value looks like a credential are redacted; ordinary text such as `env_var('DBT_PASSWORD')` examples is left as written. The verifier reads a convention file's base-branch text, not the PR's edit of it. + While the AI lane runs, the rule findings are filtered too. 36 rule types that + were almost never real defects on public dbt PRs are not posted (`ai.rulesOff: + false` or `ALTIMATE_REVIEW_RULES_OFF=0` keeps them, `ai.rulesOn: [ids]` keeps + single types, `ALTIMATE_REVIEW_RULES_OFF=` replaces the list with a JSON + list of rule ids). With the verifier on, the rule findings that would be posted + are verified too and refuted ones are dropped (`ai.verifyRules: false` or + `ALTIMATE_REVIEW_AI_VERIFY_RULES=off`). Then a rule finding is not posted when + the verifier could not check it and it is a warning or critical, or when its + type is one of 7 noisy types and the verifier did not confirm it + (`ai.rulePolicy: false` or `ALTIMATE_REVIEW_RULE_POLICY=0`). If the rule + verifier did not run, every rule finding is posted as before. The envelope + counts what each step dropped (`rulesOff`, `rulesRefuted`, `rulePolicy`). 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → `APPROVE`. Only layer-1 findings reach `critical`, so only the engine can - block. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than + block (with the AI lane on, a critical rule finding the rule verifier refuted + or could not check is not posted and does not block). In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than blocking. 5. **Signed envelope.** The verdict is HMAC-signed (`ALTIMATE_REVIEW_SIGNING_KEY`) and includes the manifest hash, so it is replayable and tamper-evident. From e42a988c3153e53946ccc7793ad441b62ce0a35e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 11:35:53 +0530 Subject: [PATCH 05/32] fix(review): never drop `critical` rule findings in the refuted filter or the rule-post policy - a `critical` rule finding the rule verifier refuted is posted, as before the rule verifier - the rule-post policy skips `critical` rule findings: an unverifiable one, or one of a noisy type that was not confirmed, is posted; condition 1 now covers warnings only - `rulesRefuted` and `rulePolicy.dropped` count only the findings actually dropped - docs: critical rule findings are never dropped by the verifier or the policy - tests: a critical unverifiable and a critical refuted finding are kept, warning ones still follow the policy and the refuted filter Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 14 ++-- .../src/altimate/review/orchestrate.ts | 4 +- .../src/altimate/review/rule-post-policy.ts | 13 ++-- .../altimate/review-rule-post-policy.test.ts | 64 +++++++++++++++++-- 4 files changed, 74 insertions(+), 21 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 2b824d9232..350feb9047 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -680,17 +680,17 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne list of rule ids). With the verifier on, the rule findings that would be posted are verified too and refuted ones are dropped (`ai.verifyRules: false` or `ALTIMATE_REVIEW_AI_VERIFY_RULES=off`). Then a rule finding is not posted when - the verifier could not check it and it is a warning or critical, or when its - type is one of 7 noisy types and the verifier did not confirm it - (`ai.rulePolicy: false` or `ALTIMATE_REVIEW_RULE_POLICY=0`). If the rule - verifier did not run, every rule finding is posted as before. The envelope - counts what each step dropped (`rulesOff`, `rulesRefuted`, `rulePolicy`). + the verifier could not check it and it is a warning, or when its type is one + of 7 noisy types and the verifier did not confirm it (`ai.rulePolicy: false` + or `ALTIMATE_REVIEW_RULE_POLICY=0`). Critical rule findings are never dropped + by the verifier or the policy. If the rule verifier did not run, every rule + finding is posted as before. The envelope counts what each step dropped (`rulesOff`, `rulesRefuted`, `rulePolicy`). 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → `APPROVE`. Only layer-1 findings reach `critical`, so only the engine can - block (with the AI lane on, a critical rule finding the rule verifier refuted - or could not check is not posted and does not block). In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than + block (the rule verifier and the rule-post policy never drop a critical rule + finding). In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than blocking. 5. **Signed envelope.** The verdict is HMAC-signed (`ALTIMATE_REVIEW_SIGNING_KEY`) and includes the manifest hash, so it is replayable and tamper-evident. diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index e51f07bb2e..3f56a8fd72 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2871,13 +2871,13 @@ export async function runReview(input: OrchestrateInput): Promise ruleVerdicts.get(f.id) ?? ruleVerdicts.get(repeatGroupId(f)) - const refuted = (f: Finding) => findingOrigin(f) !== "ai" && verdictOf(f) === "refuted" + const refuted = (f: Finding) => findingOrigin(f) !== "ai" && f.severity !== "critical" && verdictOf(f) === "refuted" const rulesRefuted = ruleVerifyAttempted ? findings.filter(refuted).length : undefined if (ruleVerdicts.size) { findings = findings.filter((f) => !refuted(f)) diff --git a/packages/opencode/src/altimate/review/rule-post-policy.ts b/packages/opencode/src/altimate/review/rule-post-policy.ts index 53d0f7ee4d..18c822096a 100644 --- a/packages/opencode/src/altimate/review/rule-post-policy.ts +++ b/packages/opencode/src/altimate/review/rule-post-policy.ts @@ -1,10 +1,11 @@ // altimate_change - new file: which verified rule findings are posted // // After the rule types off and the refuted rule findings are dropped, a rule finding is not -// posted when (1) the verifier's verdict on it is `unverifiable` and its severity is warning -// or critical, or (2) its rule type is on the noisy list and the verdict is not `confirmed`. -// A finding with no verdict counts as unverifiable. AI findings are never touched. The -// caller skips the policy when the rule verifier did not run (fail-open). +// posted when (1) the verifier's verdict on it is `unverifiable` and its severity is warning, +// or (2) its rule type is on the noisy list and the verdict is not `confirmed`. A finding with +// no verdict counts as unverifiable. AI findings and critical rule findings are never touched: +// a critical rule finding is always posted. The caller skips the policy when the rule +// verifier did not run (fail-open). import { type Finding, findingOrigin } from "./finding" /** Rule types at least 30% wrong over at least 3 posted findings when judged on replayed public dbt PRs. */ @@ -37,9 +38,9 @@ export function rulePolicyDrop( verdict: RuleVerdictValue | null | undefined, policy: RulePostPolicy, ): keyof RulePolicyDrops | undefined { - if (findingOrigin(f) === "ai") return undefined + if (findingOrigin(f) === "ai" || f.severity === "critical") return undefined const v = verdict ?? "unverifiable" - if (v === "unverifiable" && (f.severity === "warning" || f.severity === "critical")) return "unverifiable_high_sev" + if (v === "unverifiable" && f.severity === "warning") return "unverifiable_high_sev" if (f.rule && policy.noisyRules.includes(f.rule) && v !== "confirmed") return "noisy_type_not_confirmed" return undefined } diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index 5b1f4f58c3..d8df997759 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -15,7 +15,8 @@ import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" import type { AiLaneStatus, AiReviewInput } from "../../src/altimate/review/ai-review" // The rule-post policy: after rule types off and refuted rule findings, a rule finding is not -// posted when its verdict is unverifiable at warning/critical, or its type is noisy and not confirmed. +// posted when its verdict is unverifiable at warning, or its type is noisy and not confirmed. +// Critical rule findings are never dropped by the policy or the refuted filter. const NOISY = NOISY_RULE_TYPES[0] @@ -46,13 +47,25 @@ function ai(n: number, severity: Severity, r = ruleId("ai-review", "sql_correctn const verdicts = (pairs: Array<[Finding, RuleVerdictValue | null]>) => new Map(pairs.map(([f, v]) => [f.id, v] as const)) describe("dropByRulePolicy", () => { - test("condition 1: unverifiable at warning or critical is dropped; at suggestion it stays", () => { + test("condition 1: unverifiable at warning is dropped; at suggestion it stays", () => { const w = rule(1, "warning") - const c = rule(2, "critical") const s = rule(3, "suggestion") - const r = dropByRulePolicy([w, c, s], verdicts([[w, "unverifiable"], [c, "unverifiable"], [s, "unverifiable"]])) + const r = dropByRulePolicy([w, s], verdicts([[w, "unverifiable"], [s, "unverifiable"]])) expect(r.kept).toEqual([s]) - expect(r.dropped).toEqual({ unverifiable_high_sev: 2, noisy_type_not_confirmed: 0 }) + expect(r.dropped).toEqual({ unverifiable_high_sev: 1, noisy_type_not_confirmed: 0 }) + }) + + test("critical rule findings are always kept: unverifiable, no verdict, or a noisy type not confirmed", () => { + const unverifiable = rule(1, "critical") + const none = rule(2, "critical") + const noisy = rule(3, "critical", NOISY) + const warning = rule(4, "warning") + const r = dropByRulePolicy( + [unverifiable, none, noisy, warning], + verdicts([[unverifiable, "unverifiable"], [noisy, "refuted"], [warning, "unverifiable"]]), + ) + expect(r.kept).toEqual([unverifiable, none, noisy]) + expect(r.dropped).toEqual({ unverifiable_high_sev: 1, noisy_type_not_confirmed: 0 }) }) test("condition 2: a noisy type stays only when confirmed", () => { @@ -150,6 +163,19 @@ const runner: ReviewRunner = { return { columns: [] } }, } as ReviewRunner +// Adds an error-severity contract issue: a critical rule finding. +const critRunner: ReviewRunner = { + ...runner, + async check() { + return { + issues: [ + { rule: "ambiguous-column", severity: "error", category: "correctness", message: "ambiguous column status", line: 3 }, + { rule: "contract-column-dropped", severity: "error", category: "contract", message: "contract column dropped", line: 2 }, + ], + ran: true, + } + }, +} as ReviewRunner const SQL = "select *\nfrom raw.orders\nwhere status = 'x'\norder by 1" const aiFinding = makeFinding({ severity: "warning", @@ -174,6 +200,7 @@ interface RunOpts { policy?: boolean rulesOff?: Set ai?: boolean + runner?: ReviewRunner } function run(o: RunOpts = {}, seen: AiReviewInput[] = []) { @@ -182,7 +209,7 @@ function run(o: RunOpts = {}, seen: AiReviewInput[] = []) { config: { ...DEFAULT_REVIEW_CONFIG }, rubric: DEFAULT_RUBRIC, mode: "comment", - runner, + runner: o.runner ?? runner, forceTier: "full", aiVerify: true, aiSwitches: o.switches ?? { verifyRules: true, rulePolicy: true }, @@ -305,6 +332,31 @@ describe("orchestrator: rule-post policy", () => { expect(env.rulePolicy?.dropped.unverifiable_high_sev).toBe(expected) }) + test("a critical rule finding the verifier could not check is posted; the warning one is not", async () => { + const seen: AiReviewInput[] = [] + const env = await run({ runner: critRunner, verdictAt: () => "unverifiable" }, seen) + const sent = seen[0].verifyRulesAfter! + const crit = sent.filter((f) => f.severity === "critical") + const warn = sent.filter((f) => f.severity === "warning") + expect(crit.length).toBe(1) + expect(warn.length).toBeGreaterThan(0) + expect(env.findings.some((f) => f.id === crit[0].id)).toBe(true) + expect(env.findings.some((f) => warn.some((w) => w.id === f.id))).toBe(false) + expect(env.rulePolicy?.dropped.unverifiable_high_sev).toBe(warn.length) + }) + + test("a critical rule finding the verifier refuted is posted; a refuted warning one is not", async () => { + const seen: AiReviewInput[] = [] + const env = await run({ runner: critRunner, verdictAt: () => "refuted" }, seen) + const sent = seen[0].verifyRulesAfter! + const crit = sent.filter((f) => f.severity === "critical") + const rest = sent.filter((f) => f.severity !== "critical") + expect(crit.length).toBe(1) + expect(env.findings.some((f) => f.id === crit[0].id)).toBe(true) + expect(env.findings.some((f) => rest.some((w) => w.id === f.id))).toBe(false) + expect(env.rulesRefuted).toBe(rest.length) + }) + test("policy off (switch or no policy given): only refuted findings are dropped", async () => { const base = await run({ switches: { verifyRules: false, rulePolicy: false }, policy: false }) const env = await run({ verdictAt: () => "unverifiable", policy: false }) From f3831f6361f84b35f99abad467a5f758c8ca094f Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 16:14:36 +0530 Subject: [PATCH 06/32] fix(review): rule types off never drop a critical finding and apply only when the AI lane answered - `dropRulesOff` keeps `critical` rule findings, like the refuted filter and the rule-post policy: `altimate-core.classify-pii:exposes` stays on the list for its warnings, but a new high-confidence PII column in a mart (critical, `pii_exposure`) is posted and blocks again - rules-off and the rule-post policy apply only when the AI lane ran and answered (state `ok`), not merely when it is configured: with no model, a dry run, a provider error or a timeout every rule finding is posted as before (fail-open, like the verifier) - a repeat-merged comment with an AI member is left alone by rules-off, the refuted filter and the policy, so a rule finding merged with an AI finding cannot take it down; unmerged instances of such a group are kept in the verdict findings too - `ALTIMATE_REVIEW_RULES_OFF` accepts `1`/`on`/`true` and `0`/`off`/`false` (any case); only a value that looks like a path (a slash or backslash, or `.json`) is read as a list file, so `off` no longer aborts the review on `readFileSync("off")` - rule ids in the list, in `ai.rulesOn` and in `ai.rulePolicy.noisyRules` compare in one spelling (`normalizeRuleId`): `dbt_patterns:self_join` matches `dbt-patterns:self-join` - `ai.rulePolicy` objects are strict, so a typo fails the load - tests: critical PII kept; skipped/failed/timed-out lane leaves the list unapplied; merged AI+rule comment survives; env spellings; normalised `rulesOn` and noisy ids; the list-file test uses the `tmpdir` fixture with `await using` Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-switches.ts | 5 +- .../opencode/src/altimate/review/config.ts | 2 +- .../src/altimate/review/orchestrate.ts | 50 ++++--- .../src/altimate/review/rule-post-policy.ts | 5 +- .../opencode/src/altimate/review/rules-off.ts | 47 +++++-- .../altimate/review-rule-post-policy.test.ts | 7 + .../test/altimate/review-rules-off.test.ts | 127 ++++++++++++++---- 7 files changed, 185 insertions(+), 58 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index f0cf4bd9fc..1068e9f504 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -7,6 +7,7 @@ // down; code called without them (direct callers, unit tests) reads only the // env variable, as before, so an unset variable means off there. import type { ReviewConfig } from "./config" +import { rulesOffEnv } from "./rules-off" export type AiSwitchName = | "coverage" @@ -66,8 +67,8 @@ const ENV_OFF: Partial> = { verifyRules: "off" } * (case-insensitive) or a switch's own spelling, undefined otherwise. */ export function envSwitch(name: AiSwitchName, env: Env = process.env): boolean | undefined { const raw = env[AI_SWITCH_ENV[name]] - // `ALTIMATE_REVIEW_RULES_OFF=` names a replacement list: the switch is on. - if (name === "rulesOff" && raw && raw !== "0") return true + // `ALTIMATE_REVIEW_RULES_OFF` also takes on/off/true/false, or a path naming a replacement list. + if (name === "rulesOff") return rulesOffEnv(raw).on const v = raw?.trim().toLowerCase() if (v !== undefined && v === ENV_ON[name]) return true if (v !== undefined && v === ENV_OFF[name]) return false diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 0a613603c9..f3320805f7 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -60,7 +60,7 @@ export const ReviewConfig = z.object({ /** Verify the rule findings after the finder and drop the refuted ones (needs `verify`). */ verifyRules: z.boolean().optional(), /** The rule-post policy over verified rule findings (rule-post-policy.ts); an object changes its noisy list. */ - rulePolicy: z.union([z.boolean(), z.object({ noisyRules: z.array(z.string()).optional() })]).optional(), + rulePolicy: z.union([z.boolean(), z.strictObject({ noisyRules: z.array(z.string()).optional() })]).optional(), }), ]) .default(true), diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 3f56a8fd72..08cb1dd172 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2662,8 +2662,6 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= minSev) - // Rule noise, only when the AI lane runs: rule types off, then rule findings the verifier - // refuted, then the rule-post policy. A finding not posted does not count toward the verdict - // either; an unmerged instance takes the verdict of its merged group. AI findings are never - // dropped by these steps, and neither verifier step drops a critical rule finding. - const rulesOff = aiLaneOn ? input.rulesOff : undefined - const off = dropRulesOff(findings, rulesOff) - findings = off.kept - verdictFindings = dropRulesOff(verdictFindings, rulesOff).kept + // Rule noise, only when the AI lane ran and answered (fail-open otherwise, like the + // verifier): rule types off, then rule findings the verifier refuted, then the rule-post + // policy. A finding not posted does not count toward the verdict either; an unmerged instance + // takes the verdict of its merged group. AI findings and critical rule findings are never + // dropped by these steps. A merged repeat group with an AI member is left alone too, so a + // rule finding it was merged with cannot take the AI finding down with it. + const aiLaneRan = lanes.has("ai_review") && !!input.aiReview && aiStatus?.state === "ok" + const mixedGroups = new Set(verdictFindings.filter((f) => findingOrigin(f) === "ai").map(repeatGroupId)) + // A merged finding of such a group (by id), or an unmerged instance of one (by its group id). + const inMixed = (f: Finding) => mixedGroups.has(f.id) || mixedGroups.has(repeatGroupId(f)) + const ruleStep = (list: Finding[], step: (rules: Finding[]) => Finding[]) => { + const kept = new Set(step(list.filter((f) => !inMixed(f)))) + return list.filter((f) => inMixed(f) || kept.has(f)) + } + const rulesOff = aiLaneRan ? input.rulesOff : undefined + let offDropped: Record = {} + findings = ruleStep(findings, (list) => { + const r = dropRulesOff(list, rulesOff) + offDropped = r.dropped + return r.kept + }) + verdictFindings = ruleStep(verdictFindings, (list) => dropRulesOff(list, rulesOff).kept) const verdictOf = (f: Finding) => ruleVerdicts.get(f.id) ?? ruleVerdicts.get(repeatGroupId(f)) - const refuted = (f: Finding) => findingOrigin(f) !== "ai" && f.severity !== "critical" && verdictOf(f) === "refuted" + const refuted = (f: Finding) => + findingOrigin(f) !== "ai" && !inMixed(f) && f.severity !== "critical" && verdictOf(f) === "refuted" const rulesRefuted = ruleVerifyAttempted ? findings.filter(refuted).length : undefined if (ruleVerdicts.size) { findings = findings.filter((f) => !refuted(f)) verdictFindings = verdictFindings.filter((f) => !refuted(f)) } let rulePolicy: { applied: boolean; dropped: RulePolicyDrops } | undefined - if (aiLaneOn && input.rulePolicy && ruleVerifyAttempted) { + if (aiLaneRan && input.rulePolicy && ruleVerifyAttempted) { if (ruleVerifierRan) { const byId = (list: Finding[]) => new Map(list.map((f) => [f.id, verdictOf(f) ?? null] as const)) - const posted = dropByRulePolicy(findings, byId(findings), input.rulePolicy) - findings = posted.kept - verdictFindings = dropByRulePolicy(verdictFindings, byId(verdictFindings), input.rulePolicy).kept + let postedDropped: RulePolicyDrops = { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } + findings = ruleStep(findings, (list) => { + const r = dropByRulePolicy(list, byId(list), input.rulePolicy) + postedDropped = r.dropped + return r.kept + }) + const posted = { dropped: postedDropped } + verdictFindings = ruleStep(verdictFindings, (list) => dropByRulePolicy(list, byId(list), input.rulePolicy).kept) rulePolicy = { applied: true, dropped: posted.dropped } } else rulePolicy = { applied: false, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } } } @@ -2933,7 +2951,7 @@ export async function runReview(input: OrchestrateInput): Promise normalizeRuleId(r) === normalizeRuleId(f.rule!))) + return "noisy_type_not_confirmed" return undefined } diff --git a/packages/opencode/src/altimate/review/rules-off.ts b/packages/opencode/src/altimate/review/rules-off.ts index 542807802d..fe100c9410 100644 --- a/packages/opencode/src/altimate/review/rules-off.ts +++ b/packages/opencode/src/altimate/review/rules-off.ts @@ -2,17 +2,34 @@ // // `NOISY_RULES_OFF` lists rule ids (`Finding.rule`) whose findings were almost never real // defects when judged on replayed public dbt PRs, with the AI lane reviewing the same PRs. -// When the AI lane runs, rule findings with one of these ids are dropped before the rule -// verifier and before posting, and counted per rule on the envelope (`rulesOff`). AI -// findings are never dropped, and the finder's grounding is left as it is. With the AI lane -// off nothing changes. `ai.rulesOff: false` or `ALTIMATE_REVIEW_RULES_OFF=0` keeps every -// type; `ai.rulesOn: [ids]` keeps single types; `ALTIMATE_REVIEW_RULES_OFF=` replaces -// the list with a JSON list of rule ids. +// When the AI lane runs and answers, rule findings with one of these ids are dropped before +// the rule verifier and before posting, and counted per rule on the envelope (`rulesOff`). +// AI findings and `critical` rule findings are never dropped (`classify-pii:exposes` is +// critical for a new high-confidence PII column in a mart), and the finder's grounding is +// left as it is. With the AI lane off, skipped or failed nothing changes (fail-open). +// `ai.rulesOff: false` or `ALTIMATE_REVIEW_RULES_OFF=0|off|false` keeps every type; +// `ai.rulesOn: [ids]` keeps single types; `ALTIMATE_REVIEW_RULES_OFF=` replaces the +// list with a JSON list of rule ids. Rule ids compare in one spelling (`normalizeRuleId`). import { readFileSync } from "node:fs" -import { type Finding, findingOrigin } from "./finding" +import { type Finding, findingOrigin, normalizeRuleId } from "./finding" import type { ReviewConfig } from "./config" import type { AiSwitches } from "./ai-switches" +/** + * `ALTIMATE_REVIEW_RULES_OFF` read: `1`/`on`/`true` and `0`/`off`/`false` (any case) set the + * switch; a value that looks like a path (has a slash or backslash, or ends in `.json`) names a list + * file and turns it on; anything else is ignored, so a natural spelling never reaches the + * file system. + */ +export function rulesOffEnv(v: string | undefined): { on?: boolean; file?: string } { + const t = v?.trim() + if (!t) return {} + if (/^(1|on|true)$/i.test(t)) return { on: true } + if (/^(0|off|false)$/i.test(t)) return { on: false } + if (/[\\/]/.test(t) || /\.json$/i.test(t)) return { on: true, file: t } + return {} +} + export const NOISY_RULES_OFF: readonly string[] = [ "altimate-core.classify-pii:exposes", "altimate-core.lexical:op-json-arrow1", @@ -63,24 +80,28 @@ export function resolveRulesOff( env: Record = process.env, ): Set | undefined { if (!switches.rulesOff) return undefined - const file = env.ALTIMATE_REVIEW_RULES_OFF + const { file } = rulesOffEnv(env.ALTIMATE_REVIEW_RULES_OFF) let list: readonly string[] = NOISY_RULES_OFF - if (file && file !== "1" && file !== "0") { + if (file) { const parsed: unknown = JSON.parse(readFileSync(file, "utf8")) if (!Array.isArray(parsed) || parsed.some((r) => typeof r !== "string")) throw new Error(`ALTIMATE_REVIEW_RULES_OFF must name a JSON list of rule ids: ${file}`) list = parsed as string[] } - const on = new Set(typeof cfg.ai === "object" ? (cfg.ai.rulesOn ?? []) : []) - return new Set(list.filter((r) => !on.has(r))) + const on = new Set((typeof cfg.ai === "object" ? (cfg.ai.rulesOn ?? []) : []).map(normalizeRuleId)) + return new Set(list.map(normalizeRuleId).filter((r) => !on.has(r))) } -/** `findings` without the rule findings whose rule id is in `off`, and how many each rule lost. */ +/** + * `findings` without the rule findings whose rule id is in `off`, and how many each rule lost. + * AI findings and `critical` rule findings are always kept. + */ export function dropRulesOff(findings: Finding[], off: Set | undefined): { kept: Finding[]; dropped: Record } { const dropped: Record = {} if (!off?.size) return { kept: findings, dropped } + const ids = new Set([...off].map(normalizeRuleId)) const kept = findings.filter((f) => { - if (!f.rule || !off.has(f.rule) || findingOrigin(f) === "ai") return true + if (!f.rule || !ids.has(normalizeRuleId(f.rule)) || findingOrigin(f) === "ai" || f.severity === "critical") return true dropped[f.rule] = (dropped[f.rule] ?? 0) + 1 return false }) diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index d8df997759..da5c26a66f 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -109,6 +109,11 @@ describe("dropByRulePolicy", () => { expect(dropByRulePolicy([f], verdicts([[f, "unverifiable"]])).kept).toEqual([f]) expect(dropByRulePolicy([f], verdicts([[f, "unverifiable"]]), { noisyRules: ["x:custom"] }).kept).toEqual([]) }) + + test("noisy rule ids match in either spelling", () => { + const f = rule(1, "suggestion", "dbt-patterns:fanout-join") + expect(dropByRulePolicy([f], verdicts([[f, "unverifiable"]]), { noisyRules: ["dbt_patterns:fanout_join"] }).kept).toEqual([]) + }) }) describe("rulePolicyApplies (fail-open)", () => { @@ -136,6 +141,8 @@ describe("configuration", () => { expect(resolveAiSwitches(obj, {}).rulePolicy).toBe(true) expect(configuredRulePolicy(obj)).toEqual({ noisyRules: ["x:y"] }) expect(configuredRulePolicy(DEFAULT_REVIEW_CONFIG)).toBe(DEFAULT_RULE_POST_POLICY) + // A typo under `rulePolicy` fails the load rather than leaving the default list. + expect(() => parseReviewConfig("ai:\n rulePolicy:\n noisyRule:\n - x:y")).toThrow(/unrecognized_keys/) expect(envSwitch("rulePolicy", { ALTIMATE_REVIEW_RULE_POLICY: "0" })).toBe(false) expect(resolveAiSwitches(obj, { ALTIMATE_REVIEW_RULE_POLICY: "0" }).rulePolicy).toBe(false) }) diff --git a/packages/opencode/test/altimate/review-rules-off.test.ts b/packages/opencode/test/altimate/review-rules-off.test.ts index 96323e3e12..0a44fa010a 100644 --- a/packages/opencode/test/altimate/review-rules-off.test.ts +++ b/packages/opencode/test/altimate/review-rules-off.test.ts @@ -1,33 +1,20 @@ -import { describe, test, expect, afterEach } from "bun:test" -import { mkdtempSync, rmSync, writeFileSync } from "node:fs" -import { tmpdir } from "node:os" +import { describe, test, expect } from "bun:test" +import { writeFileSync } from "node:fs" import { join } from "node:path" +import { tmpdir } from "../fixture/fixture" import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" import { DEFAULT_REVIEW_CONFIG, parseReviewConfig } from "../../src/altimate/review/config" import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" -import { makeFinding, ruleId, type Finding } from "../../src/altimate/review/finding" -import { NOISY_RULES_OFF, dropRulesOff, resolveRulesOff } from "../../src/altimate/review/rules-off" +import { makeFinding, repeatGroupId, ruleId, type Finding } from "../../src/altimate/review/finding" +import { NOISY_RULES_OFF, dropRulesOff, resolveRulesOff, rulesOffEnv } from "../../src/altimate/review/rules-off" import { envSwitch, resolveAiSwitches } from "../../src/altimate/review/ai-switches" -import type { AiReviewInput } from "../../src/altimate/review/ai-review" +import type { AiLaneStatus, AiReviewInput } from "../../src/altimate/review/ai-review" // Rule types off: the shipped list drops those rule findings once the AI lane runs. -const dirs: string[] = [] -afterEach(() => { - for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) -}) - -function listFile(body: string): string { - const dir = mkdtempSync(join(tmpdir(), "rules-off-")) - dirs.push(dir) - const file = join(dir, "rules_off.json") - writeFileSync(file, body) - return file -} - -const finding = (rule: string, tool = "dbt-patterns", n = 1): Finding => +const finding = (rule: string, tool = "dbt-patterns", n = 1, severity: Finding["severity"] = "warning"): Finding => makeFinding({ - severity: "warning", + severity, category: "sql_quality", title: `m: ${rule} ${n}`, body: "b", @@ -67,7 +54,14 @@ describe("resolveRulesOff", () => { expect(resolveRulesOff({ ai: true }, resolveAiSwitches({ ai: true }, env), env)).toBeUndefined() }) - test("`ALTIMATE_REVIEW_RULES_OFF=` replaces the list, even over `ai.rulesOff: false`; a bad file is an error", () => { + test("`ALTIMATE_REVIEW_RULES_OFF=` replaces the list, even over `ai.rulesOff: false`; a bad file is an error", async () => { + await using tmp = await tmpdir() + let n = 0 + const listFile = (body: string) => { + const file = join(tmp.path, `rules_off_${n++}.json`) + writeFileSync(file, body) + return file + } const file = listFile('["a:b", "c:d"]') const env = { ALTIMATE_REVIEW_RULES_OFF: file } expect(envSwitch("rulesOff", env)).toBe(true) @@ -78,6 +72,35 @@ describe("resolveRulesOff", () => { expect(() => resolveRulesOff({ ai: true }, on, bad("[1]"))).toThrow(/JSON list of rule ids/) expect(() => resolveRulesOff({ ai: true }, on, { ALTIMATE_REVIEW_RULES_OFF: "/nonexistent/rules_off.json" })).toThrow() }) + + test("`ALTIMATE_REVIEW_RULES_OFF` spellings: on/off/true/false switch; only a path-like value is a file", () => { + for (const v of ["0", "off", "OFF", "false", "False"]) { + const env = { ALTIMATE_REVIEW_RULES_OFF: v } + expect(envSwitch("rulesOff", env)).toBe(false) + expect(resolveRulesOff({ ai: true }, resolveAiSwitches({ ai: true }, env), env)).toBeUndefined() + } + for (const v of ["1", "on", "true", "TRUE"]) { + const env = { ALTIMATE_REVIEW_RULES_OFF: v } + expect(envSwitch("rulesOff", env)).toBe(true) + // The shipped list; no file is read. + expect([...resolveRulesOff({ ai: true }, resolveAiSwitches({ ai: true }, env), env)!]).toEqual([...NOISY_RULES_OFF]) + } + // Not a switch value and not a path: ignored (config and default decide), never read as a file. + const odd = { ALTIMATE_REVIEW_RULES_OFF: "yes please" } + expect(envSwitch("rulesOff", odd)).toBeUndefined() + expect([...resolveRulesOff({ ai: true }, resolveAiSwitches({ ai: true }, odd), odd)!]).toEqual([...NOISY_RULES_OFF]) + expect(rulesOffEnv("rules_off.json")).toEqual({ on: true, file: "rules_off.json" }) + expect(rulesOffEnv("./list")).toEqual({ on: true, file: "./list" }) + expect(rulesOffEnv("C:\\lists\\off")).toEqual({ on: true, file: "C:\\lists\\off" }) + }) + + test("`ai.rulesOn` ids match in either spelling", () => { + const cfg = parseReviewConfig("ai:\n rulesOn:\n - dbt_patterns:self_join\n - RULE-CATALOG:Nested_Case") + const off = resolveRulesOff(cfg, resolveAiSwitches(cfg, {}), {})! + expect(off.has("dbt-patterns:self-join")).toBe(false) + expect(off.has("rule-catalog:nested-case")).toBe(false) + expect(off.size).toBe(NOISY_RULES_OFF.length - 2) + }) }) describe("dropRulesOff", () => { @@ -96,6 +119,22 @@ describe("dropRulesOff", () => { expect(dropRulesOff(fs, undefined)).toEqual({ kept: fs, dropped: {} }) expect(dropRulesOff(fs, new Set())).toEqual({ kept: fs, dropped: {} }) }) + + test("critical rule findings are never dropped, e.g. a new high-confidence PII column in a mart", () => { + const pii = "altimate-core.classify-pii:exposes" + expect(NOISY_RULES_OFF).toContain(pii) + const critical = finding(pii, "altimate_core.classify_pii", 1, "critical") + const warning = finding(pii, "altimate_core.classify_pii", 2, "warning") + const r = dropRulesOff([critical, warning], new Set(NOISY_RULES_OFF)) + expect(r.kept).toEqual([critical]) + expect(r.dropped).toEqual({ [pii]: 1 }) + }) + + test("a finding's rule id matches the list in either spelling", () => { + const r = dropRulesOff([finding("dbt_patterns:self_join")], new Set(["dbt-patterns:self-join"])) + expect(r.kept).toEqual([]) + expect(r.dropped).toEqual({ "dbt_patterns:self_join": 1 }) + }) }) describe("orchestrator: rule types off", () => { @@ -117,7 +156,7 @@ describe("orchestrator: rule types off", () => { }, } as ReviewRunner const SQL = "select *\nfrom raw.orders\nwhere status = 'x'\norder by 1" - const run = (opts: { seen?: AiReviewInput[]; rulesOff?: Set; ai?: boolean }) => + const run = (opts: { seen?: AiReviewInput[]; rulesOff?: Set; ai?: boolean; status?: AiLaneStatus; aiFindings?: Finding[] }) => runReview({ changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }], config: { ...DEFAULT_REVIEW_CONFIG }, @@ -133,7 +172,7 @@ describe("orchestrator: rule types off", () => { : { aiReview: async (input: AiReviewInput) => { opts.seen?.push(input) - return { findings: [], status: { state: "ok" as const } } + return { findings: opts.aiFindings ?? [], status: opts.status ?? { state: "ok" as const } } }, }), }) @@ -161,6 +200,46 @@ describe("orchestrator: rule types off", () => { expect(none.rulesOff).toEqual({}) }) + test("AI lane configured but skipped or failed: the list is not applied (fail-open)", async () => { + const base = await run({}) + const target = base.findings[0].rule! + for (const status of [ + { state: "skipped", reason: "dry run (ALTIMATE_REVIEW_AI_DRYRUN=1): no model call" }, + { state: "skipped", reason: "no usable model: none configured" }, + { state: "error", reason: "provider unreachable" }, + { state: "timeout", reason: "slow" }, + ] as AiLaneStatus[]) { + const env = await run({ rulesOff: new Set([target]), status }) + expect(env.findings).toEqual(base.findings) + expect(env.rulesOff).toBeUndefined() + } + }) + + test("a repeat-merged comment with an AI member is not dropped with its rule finding", async () => { + const base = await run({}) + const rule = base.findings.find((f) => f.severity !== "critical" && f.startLine)! + // The same file, category, severity and title as the rule finding, so the two merge; its body + // sorts after the rule finding's, so the merged comment is led by the rule finding. + const ai = makeFinding({ + severity: rule.severity, + category: rule.category, + title: rule.title, + body: "zzz the AI finder's own catch", + file: rule.file, + startLine: rule.startLine, + endLine: rule.startLine, + confidence: "medium", + evidence: { tool: "ai-review", result: {} }, + ruleKey: "ai:merged-with-rule", + rule: ruleId("ai-review", rule.category), + }) + const merged = await run({ aiFindings: [ai] }) + const group = merged.findings.find((f) => f.id === repeatGroupId(rule)) + expect(group?.body).toContain("zzz the AI finder's own catch") + const off = await run({ aiFindings: [ai], rulesOff: new Set([rule.rule!]) }) + expect(off.findings.find((f) => f.id === repeatGroupId(rule))).toEqual(group) + }) + test("AI lane off: the list is ignored and the envelope is unchanged", async () => { const base = await run({ ai: false }) const target = base.findings[0].rule! From de3bfb5704fb1d245ec49d265d49fa3737c182fb Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 16:15:10 +0530 Subject: [PATCH 07/32] fix(review): rule verifier follows `ai.verify`, reports skipped runs, and merges across projects - `ai.verify: false` (or `ALTIMATE_REVIEW_AI_VERIFY=0`) turns `verifyRules` off too: the rule findings go to the same verifier - a skipped rule run (no evidence, no model, dry run) reports every rule finding as kept and unreviewed instead of zero - `--all-projects`: rule verdicts' `batch` is offset by the batches of earlier projects; `verifyRules` is set when any project verified its rule findings; `ruleVerifier.model` is kept - the deterministic findings validated for the rule verifier are not validated again after the AI lane; only the AI findings appended after it are - `batchOutcomeState` is the one reduction of batch outcomes to a verifier state and reason, used by the finder verifier and the rule run - docs: rules-off keeps critical findings and needs the AI lane to answer; rule verification needs `verify` and never drops critical findings; what is posted when the lane or only the rule verifier did not run - tests: `verify` off turns `verifyRules` off; skipped-run counts; merge offsets, marker and model Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 36 ++++++++------ .../src/altimate/review/ai-switches.ts | 2 + .../src/altimate/review/ai-verify-rules.ts | 19 ++++++-- .../opencode/src/altimate/review/ai-verify.ts | 46 +++++++++--------- .../src/altimate/review/multi-project.ts | 24 +++++++++- .../src/altimate/review/orchestrate.ts | 35 ++++++++------ .../altimate/review-ai-verify-rules.test.ts | 47 +++++++++++++++++++ 7 files changed, 150 insertions(+), 59 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 350feb9047..a836e1e7b0 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -302,9 +302,11 @@ ai: true # the advisory AI lane; false turns it off. Or an # pythonFiles: true # changed Python files, inside or outside the project # verify: true # the dbt-grounded verifier over the AI comments # conventions: true # repo review instructions from the base branch (see below) -# rulesOff: true # stop posting 36 noisy rule types while the AI lane runs +# rulesOff: true # stop posting 36 noisy rule types once the AI lane answers +# # (critical findings of those types are still posted) # rulesOn: [] # rule ids taken back out of that list -# verifyRules: true # verify the posted rule findings; refuted ones are not posted +# verifyRules: true # verify the posted rule findings with the verifier (needs +# # `verify`); refuted ones are not posted, except critical ones # rulePolicy: true # post-verification rule policy; or {noisyRules: [...]} dataDiff: # OFF by default — see "Data-diff in CI" below enabled: false @@ -673,18 +675,24 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne secret-named settings whose value looks like a credential are redacted; ordinary text such as `env_var('DBT_PASSWORD')` examples is left as written. The verifier reads a convention file's base-branch text, not the PR's edit of it. - While the AI lane runs, the rule findings are filtered too. 36 rule types that - were almost never real defects on public dbt PRs are not posted (`ai.rulesOff: - false` or `ALTIMATE_REVIEW_RULES_OFF=0` keeps them, `ai.rulesOn: [ids]` keeps - single types, `ALTIMATE_REVIEW_RULES_OFF=` replaces the list with a JSON - list of rule ids). With the verifier on, the rule findings that would be posted - are verified too and refuted ones are dropped (`ai.verifyRules: false` or - `ALTIMATE_REVIEW_AI_VERIFY_RULES=off`). Then a rule finding is not posted when - the verifier could not check it and it is a warning, or when its type is one - of 7 noisy types and the verifier did not confirm it (`ai.rulePolicy: false` - or `ALTIMATE_REVIEW_RULE_POLICY=0`). Critical rule findings are never dropped - by the verifier or the policy. If the rule verifier did not run, every rule - finding is posted as before. The envelope counts what each step dropped (`rulesOff`, `rulesRefuted`, `rulePolicy`). + When the AI lane runs and answers, the rule findings are filtered too. 36 rule + types that were almost never real defects on public dbt PRs are not posted + (`ai.rulesOff: false` or `ALTIMATE_REVIEW_RULES_OFF=0`/`off`/`false` keeps them, + `ai.rulesOn: [ids]` keeps single types, `ALTIMATE_REVIEW_RULES_OFF=.json` + replaces the list with a JSON list of rule ids; rule ids match in either + spelling, `dbt_patterns:self_join` or `dbt-patterns:self-join`). With the + verifier on (`ai.verify`), the rule findings that would be posted are verified + too and refuted ones are dropped (`ai.verifyRules: false` or + `ALTIMATE_REVIEW_AI_VERIFY_RULES=off`; `ai.verify: false` turns it off too). Then + a rule finding is not posted when the verifier could not check it and it is a + warning, or when its type is one of 7 noisy types and the verifier did not + confirm it (`ai.rulePolicy: false` or `ALTIMATE_REVIEW_RULE_POLICY=0`). Critical + rule findings are never dropped by any of these steps, nor is a repeat-merged + comment that includes an AI finding. When the AI lane is skipped or fails (no + model, dry run, provider error), none of the steps applies and every rule + finding is posted as before; when only the rule verifier did not run, the rule + types off still apply and every other rule finding is posted unchanged. The + envelope counts what each step dropped (`rulesOff`, `rulesRefuted`, `rulePolicy`). 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index 1068e9f504..ad3ca021db 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -105,6 +105,8 @@ export function resolveAiSwitches( } out[name] = fromEnv ?? configuredSwitch(configured[name as keyof typeof configured]) ?? AI_SWITCH_DEFAULTS[name] } + // The rule findings are verified by the same verifier: `verify` off turns `verifyRules` off too. + out.verifyRules &&= out.verify return out } diff --git a/packages/opencode/src/altimate/review/ai-verify-rules.ts b/packages/opencode/src/altimate/review/ai-verify-rules.ts index c36088b92d..f1ac89d7d2 100644 --- a/packages/opencode/src/altimate/review/ai-verify-rules.ts +++ b/packages/opencode/src/altimate/review/ai-verify-rules.ts @@ -15,9 +15,20 @@ const log = Log.create({ service: "ai-verify-rules" }) export const NO_RULE_FINDINGS_REASON = "nothing to verify: the PR has no rule findings" -/** A verifier record for a rule run that made no model call. */ -export function skippedVerifier(reason: string): VerifierStatus { - return { state: "skipped", reason, durationMs: 0, turns: 0, toolCalls: 0, reviewed: 0, kept: 0, discarded: 0, summary: 0, unreviewed: 0 } +/** A verifier record for a run that made no model call: its `findings` are all kept, unreviewed (fail-open). */ +export function skippedVerifier(reason: string, findings = 0): VerifierStatus { + return { + state: "skipped", + reason, + durationMs: 0, + turns: 0, + toolCalls: 0, + reviewed: 0, + kept: findings, + discarded: 0, + summary: 0, + unreviewed: findings, + } } /** Verify `rules` (never calls the finder, returns no findings): the verdicts are on `status.verifier`. */ @@ -32,7 +43,7 @@ export async function runRuleVerify( findings: [], status: { ...status, durationMs: Date.now() - startedAt }, }) - const skip = (reason: string) => done({ state: "skipped", reason, verifier: skippedVerifier(reason) }) + const skip = (reason: string) => done({ state: "skipped", reason, verifier: skippedVerifier(reason, rules.length) }) if (!input.evidence) return skip("the verifier's evidence is unavailable") if (!rules.length) return skip(NO_RULE_FINDINGS_REASON) if (aiDryRunEnabled(env)) return skip("dry run (ALTIMATE_REVIEW_AI_DRYRUN=1): no model call") diff --git a/packages/opencode/src/altimate/review/ai-verify.ts b/packages/opencode/src/altimate/review/ai-verify.ts index fd13c9bec7..8b06578799 100644 --- a/packages/opencode/src/altimate/review/ai-verify.ts +++ b/packages/opencode/src/altimate/review/ai-verify.ts @@ -749,16 +749,7 @@ function ruleStatus( })) const usage = outcomes.flatMap((o) => (o.usage ? [o.usage] : [])) const spent = usage.length ? usage.reduce(addUsage) : undefined - const errors = outcomes.filter((o) => o.state === "error") - const timeout = outcomes.find((o) => o.state === "timeout") - let state: VerifierStatus["state"] = "ok" - let reason: string | undefined - if (timeout) [state, reason] = ["timeout", timeout.reason] - else if (errors.length === outcomes.length) [state, reason] = ["error", errors[0].reason] - else if (outcomes.some((o) => o.state === "budget")) - [state, reason] = ["budget", "answered early to stay within the token or tool-output budget"] - if (errors.length && state !== "error") - reason = [reason, `${errors.length} of ${outcomes.length} batches failed: ${errors[0].reason}`].filter(Boolean).join("; ") + const { state, reason } = batchOutcomeState(outcomes) const reviewed = ruleVerdicts.filter((v) => !v.noVerdict).length return { state, @@ -1117,6 +1108,26 @@ function requestChars(fixedChars: number, messages: ModelMessage[]): number { return fixedChars + JSON.stringify(messages).length } +/** + * The verifier's state over its batches (pure): a timeout wins; every batch failing is an error; + * an early forced answer is budget. A partial failure is reported in the reason, not hidden. + */ +export function batchOutcomeState( + outcomes: Array>, +): { state: VerifierStatus["state"]; reason?: string } { + const errors = outcomes.filter((o) => o.state === "error") + const timeout = outcomes.find((o) => o.state === "timeout") + let state: VerifierStatus["state"] = "ok" + let reason: string | undefined + if (timeout) [state, reason] = ["timeout", timeout.reason] + else if (errors.length === outcomes.length) [state, reason] = ["error", errors[0].reason] + else if (outcomes.some((o) => o.state === "budget")) + [state, reason] = ["budget", "answered early to stay within the token or tool-output budget"] + if (errors.length && state !== "error") + reason = [reason, `${errors.length} of ${outcomes.length} batches failed: ${errors[0].reason}`].filter(Boolean).join("; ") + return reason ? { state, reason } : { state } +} + interface BatchOutcome { verdicts: Map state: "ok" | "timeout" | "error" | "budget" @@ -1371,20 +1382,7 @@ export async function runAiVerify( const usage = outcomes.flatMap((o) => (o.usage ? [o.usage] : [])) const spent = usage.length ? usage.reduce(addUsage) : undefined - // A timeout wins; every batch failing is an error; an early forced answer is budget. A - // partial failure is reported, not hidden. - const errors = outcomes.filter((o) => o.state === "error") - const timeout = outcomes.find((o) => o.state === "timeout") - let state: VerifierStatus["state"] = "ok" - let reason: string | undefined - if (timeout) [state, reason] = ["timeout", timeout.reason] - else if (errors.length === outcomes.length) [state, reason] = ["error", errors[0].reason] - else if (outcomes.some((o) => o.state === "budget")) - [state, reason] = ["budget", "answered early to stay within the token or tool-output budget"] - if (errors.length && state !== "error") - reason = [reason, `${errors.length} of ${outcomes.length} batches failed: ${errors[0].reason}`] - .filter(Boolean) - .join("; ") + const { state, reason } = batchOutcomeState(outcomes) return { findings: triaged.findings, status: status({ diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 26347da972..7366867b6a 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -387,11 +387,22 @@ function mergeAi(runs: Array<{ root: string; env: VerdictEnvelope }>): VerdictEn failedFiles: failedFiles.length ? failedFiles : undefined, conventions: conventions.length ? conventions : undefined, verifier: mergeVerifier(lanes.map((r) => ({ root: r.root, v: r.env.ai!.verifier }))), - ruleVerifier: mergeVerifier(lanes.map((r) => ({ root: r.root, v: r.env.ai!.ruleVerifier as VerifierStatus | undefined }))), + // Set when any project verified its rule findings, not only the project `base` came from. + verifyRules: ais.some((a) => a.verifyRules) ? "drop_refuted" : undefined, + ruleVerifier: mergeRuleVerifier(lanes.map((r) => ({ root: r.root, v: r.env.ai!.ruleVerifier }))), projects: lanes.map((r) => ({ root: r.root, state: r.env.ai!.state, reason: r.env.ai!.reason, calls: r.env.ai!.calls })), } } +function offsetRuleVerdicts(vs: VerifierStatus[]): NonNullable { + let offset = 0 + return vs.flatMap((v) => { + const out = (v.ruleVerdicts ?? []).map((r) => (r.batch >= 0 ? { ...r, batch: r.batch + offset } : r)) + offset += v.batches?.length ?? 0 + return out + }) +} + function sumOf(vals: Array): number | undefined { const nums = vals.filter((v): v is number => v !== undefined) return nums.length ? nums.reduce((a, b) => a + b, 0) : undefined @@ -410,6 +421,14 @@ function sumTokens(vals: Array): AiStatus["tokens"] { : undefined } +/** Every project's rule-verifier summary, merged like the verifier, keeping a model (the first project's that has one). */ +function mergeRuleVerifier(runs: Array<{ root: string; v: AiStatus["ruleVerifier"] }>): AiStatus["ruleVerifier"] { + const merged = mergeVerifier(runs.map((r) => ({ root: r.root, v: r.v as VerifierStatus | undefined }))) + if (!merged) return undefined + const model = runs.map((r) => r.v?.model).find((m) => m !== undefined) + return { ...merged, ...(model ? { model } : {}) } +} + /** Every project's verifier: the worst state (with its project's reason), summed usage and counters, all decisions. */ function mergeVerifier(runs: Array<{ root: string; v: AiStatus["verifier"] }>): AiStatus["verifier"] { const present = runs.filter((r): r is { root: string; v: VerifierStatus } => r.v !== undefined) @@ -434,7 +453,8 @@ function mergeVerifier(runs: Array<{ root: string; v: AiStatus["verifier"] }>): unreviewed: sumOf(vs.map((v) => v.unreviewed)), dropped: dropped.length ? dropped.slice(0, VERIFIER_DROPPED_MAX) : undefined, decisions: decisions.length ? decisions : undefined, - ruleVerdicts: vs.some((v) => v.ruleVerdicts) ? vs.flatMap((v) => v.ruleVerdicts ?? []) : undefined, + // A verdict's `batch` indexes its project's `batches`: offset by the batches merged before it. + ruleVerdicts: vs.some((v) => v.ruleVerdicts) ? offsetRuleVerdicts(vs) : undefined, batches: vs.some((v) => v.batches) ? vs.flatMap((v) => v.batches ?? []) : undefined, } } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 08cb1dd172..cc884658bf 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2662,6 +2662,8 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && findingOrigin(f) !== "ai", - ), - input.rulesOff, - ).kept - : undefined + if (evidence && switchOn("verifyRules", input.aiSwitches)) + preAiValidated = { + count: merged.length, + list: await validateSuggestions(merged, getContent, addedLinesByFile([...input.changedFiles, ...(input.aiOutsideFiles ?? [])])), + } + const verifyRulesAfter = preAiValidated + ? dropRulesOff( + cleanFindings(preAiValidated.list).filter( + (f) => SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && findingOrigin(f) !== "ai", + ), + input.rulesOff, + ).kept + : undefined try { const res = await input.aiReview({ files: aiFiles, @@ -2855,12 +2861,11 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= minSev) // The verdict counts every instance; merging repeats is presentation only. diff --git a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts index c1a5457277..cc471007a9 100644 --- a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts @@ -23,6 +23,7 @@ import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" import { Dispatcher } from "../../src/altimate/native" import { LLM } from "../../src/session/llm" import { Provider } from "../../src/provider/provider" +import { mergeProjectEnvelopes } from "../../src/altimate/review/multi-project" // The rule verifier: after the finder (and its verifier), the rule findings the review would post // are verified and the refuted ones are not posted. Every model here is scripted. @@ -147,6 +148,12 @@ describe("verifyRules switch", () => { expect(resolveAiSwitches(cfg, {}).verifyRules).toBe(false) expect(resolveAiSwitches(cfg, { ALTIMATE_REVIEW_AI_VERIFY_RULES: "drop_refuted" }).verifyRules).toBe(true) }) + + test("`ai.verify: false` (or its env `0`) turns rule verification off too", () => { + expect(resolveAiSwitches(parseReviewConfig("ai:\n verify: false"), {}).verifyRules).toBe(false) + expect(resolveAiSwitches({ ai: true }, { ALTIMATE_REVIEW_AI_VERIFY: "0" }).verifyRules).toBe(false) + expect(resolveAiSwitches({ ai: true }, { ALTIMATE_REVIEW_AI_VERIFY: "0", ALTIMATE_REVIEW_AI_VERIFY_RULES: "1" }).verifyRules).toBe(false) + }) }) describe("runAiVerify with rulesOnly: verdicts recorded, nothing triaged", () => { @@ -219,6 +226,14 @@ describe("runRuleVerify", () => { expect(dry.status.verifier?.state).toBe("skipped") expect(llm).not.toHaveBeenCalled() }) + + test("a skipped run reports every rule finding as kept and unreviewed (fail-open)", async () => { + const rules = [ruleFinding(1), ruleFinding(2), ruleFinding(3)] + const noEvidence = await runRuleVerify({ files: [FILE], grounding: [] }, rules) + expect(noEvidence.status.verifier).toMatchObject({ state: "skipped", reviewed: 0, kept: 3, unreviewed: 3, discarded: 0 }) + const dry = await runRuleVerify({ files: [FILE], grounding: [], evidence: evidence() }, rules, { env: { ALTIMATE_REVIEW_AI_DRYRUN: "1" } }) + expect(dry.status.verifier).toMatchObject({ kept: 3, unreviewed: 3 }) + }) }) describe("runAiReview with verifyRulesAfter", () => { @@ -461,3 +476,35 @@ describe("orchestrator: drop_refuted", () => { expect(seenRules.rulesOff).toEqual({ [first[0].rule!]: first.filter((f) => f.rule === first[0].rule).length }) }) }) + +describe("--all-projects merge of the rule verifier", () => { + const ON = { verifyRules: true, rulePolicy: false } + const OFF = { verifyRules: false, rulePolicy: false } + + test("verdict batches are offset by the batches of earlier projects; the model is kept", async () => { + const a = await run([], ON) + const b = await run([], ON) + a.ai!.ruleVerifier!.model = "fake/a" + const merged = mergeProjectEnvelopes([ + { root: "a", paths: ["a/models/m.sql"], env: a }, + { root: "b", paths: ["b/models/m.sql"], env: b }, + ]) + const v = merged.ai!.verifier! + const na = a.ai!.verifier!.ruleVerdicts!.length + expect(v.batches).toHaveLength(2) + expect(v.ruleVerdicts!.slice(0, na).every((r) => r.batch === 0)).toBe(true) + expect(v.ruleVerdicts!.slice(na).every((r) => r.batch === 1)).toBe(true) + expect(merged.ai!.ruleVerifier?.model).toBe("fake/a") + }) + + test("verifyRules is set when only a later project verified its rule findings", async () => { + const a = await run([], OFF) + const b = await run([], ON) + expect(a.ai!.verifyRules).toBeUndefined() + const merged = mergeProjectEnvelopes([ + { root: "a", paths: ["a/models/m.sql"], env: a }, + { root: "b", paths: ["b/models/m.sql"], env: b }, + ]) + expect(merged.ai!.verifyRules).toBe("drop_refuted") + }) +}) From 2a8ebafa368f817b04cfebb4a26f17cf16cb694b Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 17:20:14 +0530 Subject: [PATCH 08/32] fix(review): clear errors for a bad rules-off list file; guard the policy list and empty batch outcomes - `ALTIMATE_REVIEW_RULES_OFF=`: a missing or unparsable file throws an error naming the variable and the file instead of a bare ENOENT or SyntaxError; the read stays synchronous (once per review, before it starts, from a synchronous resolver) - `configuredRulePolicy` uses `noisyRules` only when it is a list of strings, else the default - `batchOutcomeState([])` is `ok` instead of reading a missing first error - `buildEnvelope` assigns `rulesOff`, `rulesRefuted` and `rulePolicy` directly like the other optional fields (undefined is dropped by the schema output and the canonical body) - tests: missing and invalid list files, non-list `noisyRules`, empty batch outcomes Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/ai-verify.ts | 2 +- .../opencode/src/altimate/review/rule-post-policy.ts | 5 +++-- packages/opencode/src/altimate/review/rules-off.ts | 9 ++++++++- packages/opencode/src/altimate/review/verdict.ts | 6 +++--- .../test/altimate/review-ai-verify-rules.test.ts | 9 +++++++++ .../test/altimate/review-rule-post-policy.test.ts | 3 +++ packages/opencode/test/altimate/review-rules-off.test.ts | 9 ++++++++- 7 files changed, 35 insertions(+), 8 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-verify.ts b/packages/opencode/src/altimate/review/ai-verify.ts index 8b06578799..3ecc65d58a 100644 --- a/packages/opencode/src/altimate/review/ai-verify.ts +++ b/packages/opencode/src/altimate/review/ai-verify.ts @@ -1120,7 +1120,7 @@ export function batchOutcomeState( let state: VerifierStatus["state"] = "ok" let reason: string | undefined if (timeout) [state, reason] = ["timeout", timeout.reason] - else if (errors.length === outcomes.length) [state, reason] = ["error", errors[0].reason] + else if (errors.length > 0 && errors.length === outcomes.length) [state, reason] = ["error", errors[0].reason] else if (outcomes.some((o) => o.state === "budget")) [state, reason] = ["budget", "answered early to stay within the token or tool-output budget"] if (errors.length && state !== "error") diff --git a/packages/opencode/src/altimate/review/rule-post-policy.ts b/packages/opencode/src/altimate/review/rule-post-policy.ts index b024314f6a..02e9f5dd8f 100644 --- a/packages/opencode/src/altimate/review/rule-post-policy.ts +++ b/packages/opencode/src/altimate/review/rule-post-policy.ts @@ -69,6 +69,7 @@ export function rulePolicyApplies(ruleVerifier: { state: string; reviewed?: numb /** The policy configured under `ai.rulePolicy` (an object changes the noisy list). */ export function configuredRulePolicy(cfg: { ai: unknown }): RulePostPolicy { const rp = cfg.ai && typeof cfg.ai === "object" ? (cfg.ai as { rulePolicy?: unknown }).rulePolicy : undefined - const noisy = rp && typeof rp === "object" ? (rp as { noisyRules?: string[] }).noisyRules : undefined - return noisy ? { noisyRules: noisy } : DEFAULT_RULE_POST_POLICY + const noisy = rp && typeof rp === "object" ? (rp as { noisyRules?: unknown }).noisyRules : undefined + // The config schema already requires a list of strings; anything else (a direct caller) keeps the default list. + return Array.isArray(noisy) && noisy.every((r) => typeof r === "string") ? { noisyRules: noisy } : DEFAULT_RULE_POST_POLICY } diff --git a/packages/opencode/src/altimate/review/rules-off.ts b/packages/opencode/src/altimate/review/rules-off.ts index fe100c9410..0ab45128c4 100644 --- a/packages/opencode/src/altimate/review/rules-off.ts +++ b/packages/opencode/src/altimate/review/rules-off.ts @@ -83,7 +83,14 @@ export function resolveRulesOff( const { file } = rulesOffEnv(env.ALTIMATE_REVIEW_RULES_OFF) let list: readonly string[] = NOISY_RULES_OFF if (file) { - const parsed: unknown = JSON.parse(readFileSync(file, "utf8")) + // Synchronous: read once per review, before it starts, from a synchronous resolver; a small local file. + let parsed: unknown + try { + parsed = JSON.parse(readFileSync(file, "utf8")) + } catch (e) { + const why = (e as NodeJS.ErrnoException)?.code === "ENOENT" ? "file not found" : e instanceof Error ? e.message : String(e) + throw new Error(`ALTIMATE_REVIEW_RULES_OFF: cannot read the rule list ${file}: ${why}`) + } if (!Array.isArray(parsed) || parsed.some((r) => typeof r !== "string")) throw new Error(`ALTIMATE_REVIEW_RULES_OFF must name a JSON list of rule ids: ${file}`) list = parsed as string[] diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index 05b262ea92..f20f11c942 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -574,9 +574,9 @@ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { staleManifest: input.staleManifest ? true : undefined, scope: input.scope, ai: input.ai, - ...(input.rulesOff ? { rulesOff: input.rulesOff } : {}), - ...(input.rulesRefuted !== undefined ? { rulesRefuted: input.rulesRefuted } : {}), - ...(input.rulePolicy ? { rulePolicy: input.rulePolicy } : {}), + rulesOff: input.rulesOff, + rulesRefuted: input.rulesRefuted, + rulePolicy: input.rulePolicy, policy: input.policy, engineErrors: input.engineErrors, generatedAt: input.generatedAt, diff --git a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts index cc471007a9..cb68a2ef7f 100644 --- a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts @@ -1,5 +1,6 @@ import { describe, test, expect, spyOn, mock, afterEach, beforeEach } from "bun:test" import { + batchOutcomeState, numberedSlice, runAiVerify, type AiVerifyEvidence, @@ -508,3 +509,11 @@ describe("--all-projects merge of the rule verifier", () => { expect(merged.ai!.verifyRules).toBe("drop_refuted") }) }) + +describe("batchOutcomeState", () => { + test("no batches is ok, not an error read from a missing batch", () => { + expect(batchOutcomeState([])).toEqual({ state: "ok" }) + expect(batchOutcomeState([{ state: "error", reason: "boom" }])).toEqual({ state: "error", reason: "boom" }) + expect(batchOutcomeState([{ state: "ok" }, { state: "error", reason: "boom" }])).toEqual({ state: "ok", reason: "1 of 2 batches failed: boom" }) + }) +}) diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index da5c26a66f..3a9b800407 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -141,6 +141,9 @@ describe("configuration", () => { expect(resolveAiSwitches(obj, {}).rulePolicy).toBe(true) expect(configuredRulePolicy(obj)).toEqual({ noisyRules: ["x:y"] }) expect(configuredRulePolicy(DEFAULT_REVIEW_CONFIG)).toBe(DEFAULT_RULE_POST_POLICY) + // A direct caller passing a non-list keeps the default list instead of failing later. + expect(configuredRulePolicy({ ai: { rulePolicy: { noisyRules: "x:y" } } })).toBe(DEFAULT_RULE_POST_POLICY) + expect(configuredRulePolicy({ ai: { rulePolicy: { noisyRules: [1] } } })).toBe(DEFAULT_RULE_POST_POLICY) // A typo under `rulePolicy` fails the load rather than leaving the default list. expect(() => parseReviewConfig("ai:\n rulePolicy:\n noisyRule:\n - x:y")).toThrow(/unrecognized_keys/) expect(envSwitch("rulePolicy", { ALTIMATE_REVIEW_RULE_POLICY: "0" })).toBe(false) diff --git a/packages/opencode/test/altimate/review-rules-off.test.ts b/packages/opencode/test/altimate/review-rules-off.test.ts index 0a44fa010a..d8c40ab4ab 100644 --- a/packages/opencode/test/altimate/review-rules-off.test.ts +++ b/packages/opencode/test/altimate/review-rules-off.test.ts @@ -70,7 +70,14 @@ describe("resolveRulesOff", () => { const bad = (body: string) => ({ ALTIMATE_REVIEW_RULES_OFF: listFile(body) }) expect(() => resolveRulesOff({ ai: true }, on, bad('{"a": 1}'))).toThrow(/JSON list of rule ids/) expect(() => resolveRulesOff({ ai: true }, on, bad("[1]"))).toThrow(/JSON list of rule ids/) - expect(() => resolveRulesOff({ ai: true }, on, { ALTIMATE_REVIEW_RULES_OFF: "/nonexistent/rules_off.json" })).toThrow() + // A missing or unparsable file names the variable and the file, not a bare ENOENT or SyntaxError. + expect(() => resolveRulesOff({ ai: true }, on, { ALTIMATE_REVIEW_RULES_OFF: "/nonexistent/rules_off.json" })).toThrow( + "ALTIMATE_REVIEW_RULES_OFF: cannot read the rule list /nonexistent/rules_off.json: file not found", + ) + const broken = listFile("[not json") + expect(() => resolveRulesOff({ ai: true }, on, { ALTIMATE_REVIEW_RULES_OFF: broken })).toThrow( + new RegExp(`^ALTIMATE_REVIEW_RULES_OFF: cannot read the rule list ${broken.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}: `), + ) }) test("`ALTIMATE_REVIEW_RULES_OFF` spellings: on/off/true/false switch; only a path-like value is a file", () => { From 299548dbd2e0b953102b56082db3df10492edd8a Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:43:26 +0530 Subject: [PATCH 09/32] fix(review): rule-noise filtering fails open when the finder or a verifier batch did not answer - `runAiReview` runs the rule verifier only when the finder lane answered (`state: ok`): no extra model call after a provider error or timeout. - The refuted filter and `rulesRefuted` are gated on `aiLaneRan`, like rule types off and the rule-post policy, so a failed finder lane never drops rule findings. - The rule-post policy keeps a rule finding with no verdict (its batch errored or timed out, the answer omitted it, or it was not sent): only a model-returned `unverifiable` triggers condition 1, and condition 2 needs a verdict too. A transient error on one batch can no longer turn REQUEST_CHANGES into COMMENT. - Rule types off apply only to findings on files the AI lane reviewed (sent in a call that answered); the reason they are off is that the AI lane reviewed the same file. - Rule findings on credential-like paths are not sent to the rule verifier. - `rulePolicyDrop` normalizes the finding's rule id once. Changed expectations (the reported defect): three policy tests that counted a finding with no verdict as unverifiable now expect it kept. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-review.ts | 5 +- .../src/altimate/review/orchestrate.ts | 20 ++++-- .../src/altimate/review/rule-post-policy.ts | 14 ++-- .../altimate/review-ai-verify-rules.test.ts | 61 +++++++++++++++++ .../altimate/review-rule-post-policy.test.ts | 66 ++++++++++++++----- .../test/altimate/review-rules-off.test.ts | 43 ++++++++++++ 6 files changed, 180 insertions(+), 29 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 0d08895f74..e9a43cf314 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -1013,8 +1013,9 @@ export function planAiInput(input: AiReviewInput, env: Record { const res = await runFinderLane(input) - if (!input.verifyRulesAfter) return res - // The rule verifier over the rule findings the review would post, after the finder and its verifier. + // The rule verifier over the rule findings the review would post, after the finder and its verifier; + // only when the finder answered, since the orchestrator applies rule noise only then (fail-open). + if (!input.verifyRulesAfter || res.status.state !== "ok") return res return withRuleVerdicts(res, await runRuleVerify(input, input.verifyRulesAfter)) } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index cc884658bf..1a8319e6ca 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2820,7 +2820,7 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && findingOrigin(f) !== "ai", ), input.rulesOff, - ).kept + ).kept.filter((f) => !mayHoldCredentials(f.file)) : undefined try { const res = await input.aiReview({ @@ -2886,18 +2886,25 @@ export async function runReview(input: OrchestrateInput): Promise inMixed(f) || kept.has(f)) } const rulesOff = aiLaneRan ? input.rulesOff : undefined + // Rule types off stand on the AI lane having reviewed the same file: a finding on a file the + // lane did not review (not sent, or its call failed) is posted. + const offStep = (list: Finding[]) => { + const r = dropRulesOff(list.filter((f) => aiReviewed.has(f.file)), rulesOff) + const kept = new Set(r.kept) + return { kept: list.filter((f) => !aiReviewed.has(f.file) || kept.has(f)), dropped: r.dropped } + } let offDropped: Record = {} findings = ruleStep(findings, (list) => { - const r = dropRulesOff(list, rulesOff) + const r = offStep(list) offDropped = r.dropped return r.kept }) - verdictFindings = ruleStep(verdictFindings, (list) => dropRulesOff(list, rulesOff).kept) + verdictFindings = ruleStep(verdictFindings, (list) => offStep(list).kept) const verdictOf = (f: Finding) => ruleVerdicts.get(f.id) ?? ruleVerdicts.get(repeatGroupId(f)) const refuted = (f: Finding) => findingOrigin(f) !== "ai" && !inMixed(f) && f.severity !== "critical" && verdictOf(f) === "refuted" - const rulesRefuted = ruleVerifyAttempted ? findings.filter(refuted).length : undefined - if (ruleVerdicts.size) { + const rulesRefuted = aiLaneRan && ruleVerifyAttempted ? findings.filter(refuted).length : undefined + if (aiLaneRan && ruleVerdicts.size) { findings = findings.filter((f) => !refuted(f)) verdictFindings = verdictFindings.filter((f) => !refuted(f)) } @@ -2911,9 +2918,8 @@ export async function runReview(input: OrchestrateInput): Promise dropByRulePolicy(list, byId(list), input.rulePolicy).kept) - rulePolicy = { applied: true, dropped: posted.dropped } + rulePolicy = { applied: true, dropped: postedDropped } } else rulePolicy = { applied: false, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } } } diff --git a/packages/opencode/src/altimate/review/rule-post-policy.ts b/packages/opencode/src/altimate/review/rule-post-policy.ts index 02e9f5dd8f..5461c9d8ae 100644 --- a/packages/opencode/src/altimate/review/rule-post-policy.ts +++ b/packages/opencode/src/altimate/review/rule-post-policy.ts @@ -3,7 +3,8 @@ // After the rule types off and the refuted rule findings are dropped, a rule finding is not // posted when (1) the verifier's verdict on it is `unverifiable` and its severity is warning, // or (2) its rule type is on the noisy list and the verdict is not `confirmed`. A finding with -// no verdict counts as unverifiable. AI findings and critical rule findings are never touched: +// no verdict (its batch failed or timed out, the answer omitted it, or it was never sent) was +// not judged and is kept. AI findings and critical rule findings are never touched: // a critical rule finding is always posted. The caller skips the policy when the rule // verifier did not run (fail-open). import { type Finding, findingOrigin, normalizeRuleId } from "./finding" @@ -39,10 +40,13 @@ export function rulePolicyDrop( policy: RulePostPolicy, ): keyof RulePolicyDrops | undefined { if (findingOrigin(f) === "ai" || f.severity === "critical") return undefined - const v = verdict ?? "unverifiable" - if (v === "unverifiable" && f.severity === "warning") return "unverifiable_high_sev" - if (f.rule && v !== "confirmed" && policy.noisyRules.some((r) => normalizeRuleId(r) === normalizeRuleId(f.rule!))) - return "noisy_type_not_confirmed" + // No verdict is an infrastructure outcome, not a model judgement: keep the finding. + if (verdict == null) return undefined + if (verdict === "unverifiable" && f.severity === "warning") return "unverifiable_high_sev" + if (f.rule && verdict !== "confirmed") { + const rule = normalizeRuleId(f.rule) + if (policy.noisyRules.some((r) => normalizeRuleId(r) === rule)) return "noisy_type_not_confirmed" + } return undefined } diff --git a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts index cb68a2ef7f..2a0a0fbfc1 100644 --- a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts @@ -517,3 +517,64 @@ describe("batchOutcomeState", () => { expect(batchOutcomeState([{ state: "ok" }, { state: "error", reason: "boom" }])).toEqual({ state: "ok", reason: "1 of 2 batches failed: boom" }) }) }) + +describe("round 2: the rule verifier runs only after a finder that answered, under a per-PR ceiling", () => { + test("the finder failed: no rule-verifier call, no verdicts, no drop_refuted", async () => { + const llm = scriptModels([], /x/) + spyOn(Dispatcher, "call").mockResolvedValue({ success: true, data: {} } as any) + const rules = [ruleFinding(1)] + const res = await runAiReview({ files: [FILE], grounding: rules, evidence: evidence(), verifyRulesAfter: rules }) + expect(res.status.state).toBe("error") + expect(res.status.verifyRules).toBeUndefined() + expect(res.status.ruleVerifier).toBeUndefined() + expect(llm).not.toHaveBeenCalled() + }) + + +}) + +describe("round 2: credential-like paths", () => { + test("rule findings on a file named like a credential file are not sent to the rule verifier", async () => { + const runner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [{ rule: "ambiguous-column", severity: "error", category: "correctness", message: "ambiguous column status", line: 3 }], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } as unknown as ReviewRunner + const SQL = "select *\nfrom raw.orders\nwhere status = 'x'\norder by 1" + const seen: AiReviewInput[] = [] + const changed = (p: string) => ({ path: p, status: "modified" as const, diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }) + const env = await runReview({ + changedFiles: [changed("models/marts/m.sql"), { path: "models/secrets.yml", status: "modified" as const, diff: "@@ -1 +1 @@\n-a: 1\n+a: [\n" }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiVerify: true, + aiSwitches: { verifyRules: true }, + getContent: async (f, side) => (f.endsWith(".yml") ? (side === "old" ? "a: 1\n" : "a: [\n") : side === "old" ? "select 1" : SQL), + generatedAt: "2026-11-27T00:00:00Z", + aiReview: async (input) => { + seen.push(input) + return { findings: [], status: { state: "ok" } } + }, + }) + const files = new Set((seen[0].verifyRulesAfter ?? []).map((f) => f.file)) + expect(files.has("models/marts/m.sql")).toBe(true) + // The deterministic lanes still report the file; only the model never sees its findings. + expect(env.findings.some((f) => f.file === "models/secrets.yml")).toBe(true) + expect(files.has("models/secrets.yml")).toBe(false) + }) +}) diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index 3a9b800407..24297bc6dc 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -87,14 +87,14 @@ describe("dropByRulePolicy", () => { expect(r.kept).toEqual([a, b]) }) - test("a finding with no verdict (null or absent) counts as unverifiable", () => { + test("a finding with no verdict (null or absent) was not judged: it is kept", () => { const nul = rule(1, "warning") const absent = rule(2, "warning") const noisySuggestion = rule(3, "suggestion", NOISY) const plainSuggestion = rule(4, "suggestion") const r = dropByRulePolicy([nul, absent, noisySuggestion, plainSuggestion], verdicts([[nul, null]])) - expect(r.kept).toEqual([plainSuggestion]) - expect(r.dropped).toEqual({ unverifiable_high_sev: 2, noisy_type_not_confirmed: 1 }) + expect(r.kept).toEqual([nul, absent, noisySuggestion, plainSuggestion]) + expect(r.dropped).toEqual({ unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 }) }) test("AI findings are never dropped, whatever their verdict, severity or rule id", () => { @@ -211,6 +211,9 @@ interface RunOpts { rulesOff?: Set ai?: boolean runner?: ReviewRunner + /** The finder lane's state (the rule verdicts are recorded whatever it is). */ + finderState?: "ok" | "timeout" | "error" + mode?: "comment" | "gate" } function run(o: RunOpts = {}, seen: AiReviewInput[] = []) { @@ -218,7 +221,7 @@ function run(o: RunOpts = {}, seen: AiReviewInput[] = []) { changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }], config: { ...DEFAULT_REVIEW_CONFIG }, rubric: DEFAULT_RUBRIC, - mode: "comment", + mode: o.mode ?? "comment", runner: o.runner ?? runner, forceTier: "full", aiVerify: true, @@ -254,9 +257,9 @@ function run(o: RunOpts = {}, seen: AiReviewInput[] = []) { const reviewed = records.filter((r) => !r.noVerdict).length const state = o.ruleState ?? "ok" return { - findings: [aiFinding], + findings: o.finderState && o.finderState !== "ok" ? [] : [aiFinding], status: { - state: "ok" as const, + state: o.finderState ?? ("ok" as const), verifyRules: "drop_refuted" as const, verifier: { state: "skipped" as const, @@ -306,15 +309,15 @@ describe("orchestrator: rule-post policy", () => { expect(env.rulesRefuted).toBe(0) }) - test("a single rule finding with no verdict counts as unverifiable", async () => { + test("a single rule finding with no verdict is posted (the verifier never judged it)", async () => { const seen: AiReviewInput[] = [] const all = await run({}, seen) const sent = seen[0].verifyRulesAfter! const idx = sent.findIndex((f) => f.severity !== "suggestion") expect(idx).toBeGreaterThanOrEqual(0) const env = await run({ verdictAt: (i) => (i === idx ? undefined : "confirmed") }) - expect(env.findings).toEqual(all.findings.filter((f) => f.id !== sent[idx].id)) - expect(env.rulePolicy).toEqual({ applied: true, dropped: { unverifiable_high_sev: 1, noisy_type_not_confirmed: 0 } }) + expect(env.findings).toEqual(all.findings) + expect(env.rulePolicy).toEqual({ applied: true, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } }) }) test("all confirmed: nothing dropped, applied with zero counts", async () => { @@ -333,13 +336,12 @@ describe("orchestrator: rule-post policy", () => { } }) - test("budget with some findings reviewed: the policy applies, unreviewed findings count as unverifiable", async () => { - const seen: AiReviewInput[] = [] - const env = await run({ verdictAt: (i) => (i === 0 ? "confirmed" : undefined), ruleState: "budget" }, seen) + test("budget with some findings reviewed: the policy applies, unreviewed findings are posted", async () => { + const base = await run({ switches: { verifyRules: false, rulePolicy: false }, policy: false }) + const env = await run({ verdictAt: (i) => (i === 0 ? "confirmed" : undefined), ruleState: "budget" }) expect(env.rulePolicy?.applied).toBe(true) - const sent = seen[0].verifyRulesAfter! - const expected = sent.slice(1).filter((f) => f.severity !== "suggestion").length - expect(env.rulePolicy?.dropped.unverifiable_high_sev).toBe(expected) + expect(env.rulePolicy?.dropped.unverifiable_high_sev).toBe(0) + expect(env.findings).toEqual(base.findings) }) test("a critical rule finding the verifier could not check is posted; the warning one is not", async () => { @@ -406,3 +408,37 @@ describe("flags off: unchanged behaviour", () => { expect(withAll.rulePolicy).toBeUndefined() }) }) + +describe("round 2: rule noise fails open", () => { + test("finder timed out or failed: refuted rule findings are posted and not counted as refuted", async () => { + // The deterministic review alone: the rule findings a failed AI lane must leave untouched. + const off = await run({ ai: false }) + for (const finderState of ["timeout", "error"] as const) { + const env = await run({ verdictAt: () => "refuted", finderState }) + expect(env.findings).toEqual(off.findings) + expect(env.rulesRefuted).toBeUndefined() + } + }) + + test("a rule-verifier batch that errored while others answered: its warnings are posted", async () => { + const seen: AiReviewInput[] = [] + const all = await run({ runner: critRunner }, seen) + const sent = seen[0].verifyRulesAfter! + // The critical finding's batch answered; the warning's batch failed (no verdict), run state ok. + const env = await run({ runner: critRunner, verdictAt: (i) => (sent[i].severity === "critical" ? "confirmed" : undefined) }) + expect(sent.some((f) => f.severity === "warning")).toBe(true) + expect(env.rulePolicy?.applied).toBe(true) + expect(env.findings).toEqual(all.findings) + expect(env.rulePolicy?.dropped.unverifiable_high_sev).toBe(0) + }) + + test("verdict: refuted engine warnings no longer count toward the warning block; a critical one still blocks", async () => { + const gate = { mode: "gate" as const } + const confirmed = await run({ ...gate, runner: critRunner, verdictAt: () => "confirmed" }) + expect(confirmed.verdict).toBe("REQUEST_CHANGES") + const refuted = await run({ ...gate, runner: critRunner, verdictAt: () => "refuted" }) + // The critical contract finding is never dropped, so the PR still blocks. + expect(refuted.findings.some((f) => f.severity === "critical")).toBe(true) + expect(refuted.verdict).toBe("REQUEST_CHANGES") + }) +}) diff --git a/packages/opencode/test/altimate/review-rules-off.test.ts b/packages/opencode/test/altimate/review-rules-off.test.ts index d8c40ab4ab..90674c8652 100644 --- a/packages/opencode/test/altimate/review-rules-off.test.ts +++ b/packages/opencode/test/altimate/review-rules-off.test.ts @@ -255,3 +255,46 @@ describe("orchestrator: rule types off", () => { expect(withList.rulesOff).toBeUndefined() }) }) + +describe("round 2: rule types off apply only to files the AI lane reviewed", () => { + const runner: ReviewRunner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } as ReviewRunner + const SQL = "select *\nfrom raw.orders\nwhere status = 'x'\norder by 1" + const run = (rulesOff: Set | undefined, status: AiLaneStatus) => + runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + getContent: async (_f, side) => (side === "old" ? "select 1" : SQL), + generatedAt: "2026-11-27T00:00:00Z", + ...(rulesOff ? { rulesOff } : {}), + aiReview: async () => ({ findings: [], status }), + }) + + test("the file's call failed while others answered: its rule findings of off types are posted", async () => { + const base = await run(undefined, { state: "ok" }) + const target = base.findings[0].rule! + const reviewed = await run(new Set([target]), { state: "ok" }) + expect(reviewed.findings.length).toBeLessThan(base.findings.length) + const failed = await run(new Set([target]), { state: "ok", reason: "1 of 2 calls failed: boom", failedFiles: ["models/marts/m.sql"] }) + expect(failed.findings).toEqual(base.findings) + }) +}) From ec57267a849146d9caa3b47fc7a9ba9b8c3f36b8 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:43:39 +0530 Subject: [PATCH 10/32] fix(review): a per-PR ceiling on the rule findings the rule verifier checks The rule run is a second `runAiVerify` call with its own token budget and timeout, and every batch of 8 makes at least one forced call, so its calls grew with the number of rule findings. At most 40 rule findings per PR are now verified, most severe first (`ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS` overrides). Findings past the ceiling get no verdict and are posted unchanged; the verifier's `reason` says how many. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-verify-rules.ts | 19 ++++++++++++++++--- .../altimate/review-ai-verify-rules.test.ts | 11 ++++++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-verify-rules.ts b/packages/opencode/src/altimate/review/ai-verify-rules.ts index f1ac89d7d2..f0b4ec44f2 100644 --- a/packages/opencode/src/altimate/review/ai-verify-rules.ts +++ b/packages/opencode/src/altimate/review/ai-verify-rules.ts @@ -15,6 +15,11 @@ const log = Log.create({ service: "ai-verify-rules" }) export const NO_RULE_FINDINGS_REASON = "nothing to verify: the PR has no rule findings" +/** Rule findings verified per PR at most (`ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS`): the run + * has its own verifier budget and each batch of 8 makes at least one call, so this bounds its + * calls. Findings past it, most severe first, get no verdict and are posted unchanged. */ +export const RULE_VERIFY_MAX_FINDINGS = 40 + /** A verifier record for a run that made no model call: its `findings` are all kept, unreviewed (fail-open). */ export function skippedVerifier(reason: string, findings = 0): VerifierStatus { return { @@ -54,10 +59,18 @@ export async function runRuleVerify( } catch (err) { return skip(`no usable model: ${safeReason(err)}`) } - log.info("verifying rule findings", { findings: rules.length }) + const max = Number(env.ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS) + const cap = Number.isInteger(max) && max > 0 ? max : RULE_VERIFY_MAX_FINDINGS + // Most severe first, so the warnings the policy acts on are verified before suggestions. + const order = { critical: 2, warning: 1, suggestion: 0 } as const + const sent = [...rules].sort((a, b) => order[b.severity] - order[a.severity]).slice(0, cap) + log.info("verifying rule findings", { findings: sent.length, total: rules.length }) const v = await runAiVerify( - { findings: rules, grounding: input.grounding, evidence: input.evidence, model, rulesOnly: true }, + { findings: sent, grounding: input.grounding, evidence: input.evidence, model, rulesOnly: true }, { env, ...(deps.llm ? { llm: deps.llm } : {}) }, ) - return done({ state: "ok", model: `${model.providerID}/${model.id}`, verifier: v.status }) + const over = rules.length - sent.length + const note = `${over} of ${rules.length} rule findings over the per-PR ceiling of ${cap} were not verified` + const verifier = over ? { ...v.status, reason: v.status.reason ? `${v.status.reason}; ${note}` : note } : v.status + return done({ state: "ok", model: `${model.providerID}/${model.id}`, verifier }) } diff --git a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts index 2a0a0fbfc1..f2ee95aa34 100644 --- a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts @@ -530,7 +530,16 @@ describe("round 2: the rule verifier runs only after a finder that answered, und expect(llm).not.toHaveBeenCalled() }) - + test("at most 40 rule findings are verified per PR (env override); the rest keep no verdict", async () => { + scriptModels([], /x/) + const rules = Array.from({ length: 50 }, (_, i) => ruleFinding(i)) + const capped = await runRuleVerify({ files: [FILE], grounding: [], evidence: evidence() }, rules) + expect(capped.status.verifier?.ruleVerdicts).toHaveLength(40) + expect(capped.status.verifier?.reason).toContain("10 of 50") + const env = { ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS: "8" } + const small = await runRuleVerify({ files: [FILE], grounding: [], evidence: evidence() }, rules, { env }) + expect(small.status.verifier?.ruleVerdicts).toHaveLength(8) + }) }) describe("round 2: credential-like paths", () => { From d9bc82540258641c27bf926ccf11c8ff938d49a3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:43:40 +0530 Subject: [PATCH 11/32] fix(review): rules-off counts use the normalized rule id; the list file must live outside the checkout - `dropRulesOff` counts drops under `normalizeRuleId(f.rule)`, so two spellings of one rule add up instead of splitting. - `ALTIMATE_REVIEW_RULES_OFF=` must be an absolute path whose realpath is outside the git work tree of the current directory (the PR checkout in CI); a relative path would let a PR choose which rule findings are posted. Changed expectation: the "either spelling" test now expects the count under the normalized id. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/rules-off.ts | 43 +++++++++++++++++-- .../test/altimate/review-rules-off.test.ts | 20 ++++++++- 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/review/rules-off.ts b/packages/opencode/src/altimate/review/rules-off.ts index 0ab45128c4..c3825005ba 100644 --- a/packages/opencode/src/altimate/review/rules-off.ts +++ b/packages/opencode/src/altimate/review/rules-off.ts @@ -10,7 +10,8 @@ // `ai.rulesOff: false` or `ALTIMATE_REVIEW_RULES_OFF=0|off|false` keeps every type; // `ai.rulesOn: [ids]` keeps single types; `ALTIMATE_REVIEW_RULES_OFF=` replaces the // list with a JSON list of rule ids. Rule ids compare in one spelling (`normalizeRuleId`). -import { readFileSync } from "node:fs" +import { existsSync, readFileSync, realpathSync } from "node:fs" +import { dirname, isAbsolute, join, relative } from "node:path" import { type Finding, findingOrigin, normalizeRuleId } from "./finding" import type { ReviewConfig } from "./config" import type { AiSwitches } from "./ai-switches" @@ -30,6 +31,27 @@ export function rulesOffEnv(v: string | undefined): { on?: boolean; file?: strin return {} } +/** The git work tree containing `dir` (the nearest ancestor with a `.git` entry), realpath'd; undefined outside one. */ +function workTreeOf(dir: string): string | undefined { + let d: string + try { + d = realpathSync(dir) + } catch { + return undefined + } + for (;;) { + if (existsSync(join(d, ".git"))) return d + const up = dirname(d) + if (up === d) return undefined + d = up + } +} + +function isInsideDir(p: string, dir: string): boolean { + const rel = relative(dir, p) + return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)) +} + export const NOISY_RULES_OFF: readonly string[] = [ "altimate-core.classify-pii:exposes", "altimate-core.lexical:op-json-arrow1", @@ -78,11 +100,24 @@ export function resolveRulesOff( cfg: Pick, switches: Pick, env: Record = process.env, + cwd: string = process.cwd(), ): Set | undefined { if (!switches.rulesOff) return undefined const { file } = rulesOffEnv(env.ALTIMATE_REVIEW_RULES_OFF) let list: readonly string[] = NOISY_RULES_OFF if (file) { + // The list decides which rule findings are posted: a file in the PR checkout would let a PR choose. + if (!isAbsolute(file)) throw new Error("ALTIMATE_REVIEW_RULES_OFF must name an absolute path outside the repository") + const tree = workTreeOf(cwd) + const real = (() => { + try { + return realpathSync(file) + } catch { + return file + } + })() + if (tree && isInsideDir(real, tree)) + throw new Error(`ALTIMATE_REVIEW_RULES_OFF: the rule list ${file} is inside the git work tree; place it outside the checkout`) // Synchronous: read once per review, before it starts, from a synchronous resolver; a small local file. let parsed: unknown try { @@ -108,8 +143,10 @@ export function dropRulesOff(findings: Finding[], off: Set | undefined): if (!off?.size) return { kept: findings, dropped } const ids = new Set([...off].map(normalizeRuleId)) const kept = findings.filter((f) => { - if (!f.rule || !ids.has(normalizeRuleId(f.rule)) || findingOrigin(f) === "ai" || f.severity === "critical") return true - dropped[f.rule] = (dropped[f.rule] ?? 0) + 1 + if (!f.rule || findingOrigin(f) === "ai" || f.severity === "critical") return true + const rule = normalizeRuleId(f.rule) + if (!ids.has(rule)) return true + dropped[rule] = (dropped[rule] ?? 0) + 1 return false }) return { kept, dropped } diff --git a/packages/opencode/test/altimate/review-rules-off.test.ts b/packages/opencode/test/altimate/review-rules-off.test.ts index 90674c8652..b868a5e8c7 100644 --- a/packages/opencode/test/altimate/review-rules-off.test.ts +++ b/packages/opencode/test/altimate/review-rules-off.test.ts @@ -140,7 +140,8 @@ describe("dropRulesOff", () => { test("a finding's rule id matches the list in either spelling", () => { const r = dropRulesOff([finding("dbt_patterns:self_join")], new Set(["dbt-patterns:self-join"])) expect(r.kept).toEqual([]) - expect(r.dropped).toEqual({ "dbt_patterns:self_join": 1 }) + // Counted under the normalized id, so two spellings of one rule add up. + expect(r.dropped).toEqual({ "dbt-patterns:self-join": 1 }) }) }) @@ -256,6 +257,23 @@ describe("orchestrator: rule types off", () => { }) }) +describe("round 2: rule types off", () => { + test("counts are keyed by the normalized rule id, so two spellings add up", () => { + const a = finding("dbt_patterns:self_join", "dbt-patterns", 1) + const b = finding("dbt-patterns:self-join", "dbt-patterns", 2) + expect(dropRulesOff([a, b], new Set(["dbt-patterns:self-join"])).dropped).toEqual({ "dbt-patterns:self-join": 2 }) + }) + + test("ALTIMATE_REVIEW_RULES_OFF= must be absolute and outside the git work tree", async () => { + const on = { rulesOff: true } + expect(() => resolveRulesOff({ ai: true }, on, { ALTIMATE_REVIEW_RULES_OFF: "rules_off.json" })).toThrow("absolute path") + await using repo = await tmpdir({ git: true }) + const inside = join(repo.path, "rules_off.json") + writeFileSync(inside, '["a:b"]') + expect(() => resolveRulesOff({ ai: true }, on, { ALTIMATE_REVIEW_RULES_OFF: inside }, repo.path)).toThrow("inside the git work tree") + }) +}) + describe("round 2: rule types off apply only to files the AI lane reviewed", () => { const runner: ReviewRunner = { async impact() { From c434662005d9301b2f4ae849248305ecd27b64f0 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:43:40 +0530 Subject: [PATCH 12/32] fix(review): show withheld rule findings in the PR comment and telemetry; document the verdict effect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The summary's coverage notes give the number of rule findings not posted, per step (rule types off, refuted, rule-post policy). - `review_run` telemetry adds the rule verifier's state, tokens, cost and findings reviewed, and the three drop counts. - Docs: rule types off apply on files the AI lane reviewed; the list path rule and that a bad list file stops the review; the rule-verifier ceiling and its own budget; no-verdict findings are posted; the verifier and the policy can lower a ≥3-warning REQUEST_CHANGES (never drop a critical). - `mergeRepeats` gets its JSDoc back. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 45 +++++++++++-------- .../opencode/src/altimate/review/finding.ts | 10 ++--- .../opencode/src/altimate/review/format.ts | 8 ++++ .../opencode/src/altimate/review/telemetry.ts | 11 +++++ .../opencode/src/altimate/telemetry/index.ts | 9 ++++ .../altimate/review-rule-post-policy.test.ts | 30 +++++++++++++ 6 files changed, 90 insertions(+), 23 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index a836e1e7b0..997b52134c 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -676,29 +676,38 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne text such as `env_var('DBT_PASSWORD')` examples is left as written. The verifier reads a convention file's base-branch text, not the PR's edit of it. When the AI lane runs and answers, the rule findings are filtered too. 36 rule - types that were almost never real defects on public dbt PRs are not posted - (`ai.rulesOff: false` or `ALTIMATE_REVIEW_RULES_OFF=0`/`off`/`false` keeps them, - `ai.rulesOn: [ids]` keeps single types, `ALTIMATE_REVIEW_RULES_OFF=.json` - replaces the list with a JSON list of rule ids; rule ids match in either - spelling, `dbt_patterns:self_join` or `dbt-patterns:self-join`). With the - verifier on (`ai.verify`), the rule findings that would be posted are verified - too and refuted ones are dropped (`ai.verifyRules: false` or - `ALTIMATE_REVIEW_AI_VERIFY_RULES=off`; `ai.verify: false` turns it off too). Then - a rule finding is not posted when the verifier could not check it and it is a - warning, or when its type is one of 7 noisy types and the verifier did not - confirm it (`ai.rulePolicy: false` or `ALTIMATE_REVIEW_RULE_POLICY=0`). Critical - rule findings are never dropped by any of these steps, nor is a repeat-merged - comment that includes an AI finding. When the AI lane is skipped or fails (no - model, dry run, provider error), none of the steps applies and every rule - finding is posted as before; when only the rule verifier did not run, the rule - types off still apply and every other rule finding is posted unchanged. The - envelope counts what each step dropped (`rulesOff`, `rulesRefuted`, `rulePolicy`). + types that were almost never real defects on public dbt PRs are not posted on + files the AI lane reviewed (`ai.rulesOff: false` or + `ALTIMATE_REVIEW_RULES_OFF=0`/`off`/`false` keeps them, `ai.rulesOn: [ids]` keeps + single types, `ALTIMATE_REVIEW_RULES_OFF=.json` replaces the list with a + JSON list of rule ids; the path must be absolute and outside the repository + checkout, and a missing, unreadable or malformed list file stops the review + before any lane runs; rule ids match in either spelling, `dbt_patterns:self_join` + or `dbt-patterns:self-join`). With the verifier on (`ai.verify`), the rule + findings that would be posted are verified too, up to 40 per PR, most severe + first (`ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS`), in a second verifier run + with its own token budget, and refuted ones are dropped (`ai.verifyRules: false` + or `ALTIMATE_REVIEW_AI_VERIFY_RULES=off`; `ai.verify: false` turns it off too). + Then a rule finding is not posted when the verifier answered that it could not + check it and it is a warning, or when its type is one of 7 noisy types and the + verifier did not confirm it (`ai.rulePolicy: false` or + `ALTIMATE_REVIEW_RULE_POLICY=0`). A rule finding that got no verdict (its batch + failed or timed out, or it was over the ceiling) is posted. Critical rule + findings are never dropped by any of these steps, nor is a repeat-merged comment + that includes an AI finding. When the AI lane is skipped or fails (no model, dry + run, provider error, timeout), the rule verifier does not run, none of the steps + applies and every rule finding is posted as before; when only the rule verifier + did not run, the rule types off still apply and every other rule finding is + posted unchanged. The envelope counts what each step dropped (`rulesOff`, + `rulesRefuted`, `rulePolicy`), and the PR comment gives the total per step. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → `APPROVE`. Only layer-1 findings reach `critical`, so only the engine can block (the rule verifier and the rule-post policy never drop a critical rule - finding). In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than + finding). They can unblock, though: an engine warning that is refuted, turned + off or dropped by the policy is not posted and does not count toward the ≥3 + warnings, so it can lower that `REQUEST_CHANGES` to `COMMENT`. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than blocking. 5. **Signed envelope.** The verdict is HMAC-signed (`ALTIMATE_REVIEW_SIGNING_KEY`) and includes the manifest hash, so it is replayable and tamper-evident. diff --git a/packages/opencode/src/altimate/review/finding.ts b/packages/opencode/src/altimate/review/finding.ts index cc09be52ee..18b944e8bd 100644 --- a/packages/opencode/src/altimate/review/finding.ts +++ b/packages/opencode/src/altimate/review/finding.ts @@ -285,11 +285,6 @@ function repeatLabel(f: Finding, first: Finding): string { return f.startLine ? `${label} (line ${f.startLine})` : label } -/** - * Merge repeats of one rule within one file (one finding per column of a grain - * test, one per join onto the same kind of key) into a single finding that - * lists every instance. Critical findings stay separate: each one can block. - */ /** The key `mergeRepeats` groups a finding by. */ function repeatKey(f: Finding): string { return [f.file, f.category, f.severity, !!f.degraded, !!f.preExisting, groupKeyTitle(f)].join("|") @@ -300,6 +295,11 @@ export function repeatGroupId(f: Finding): string { return "f_" + createHash("sha256").update(`merged ${repeatKey(f)}`).digest("hex").slice(0, 16) } +/** + * Merge repeats of one rule within one file (one finding per column of a grain + * test, one per join onto the same kind of key) into a single finding that + * lists every instance. Critical findings stay separate: each one can block. + */ export function mergeRepeats(findings: Finding[]): Finding[] { const groups = new Map() const out: Finding[] = [] diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 86747641aa..339ad9f194 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -318,6 +318,14 @@ export function coverageNotes(env: VerdictEnvelope): string[] { `${aiUnsent.length} file(s) were not sent to the advisory AI review (file quota); the deterministic checks still ran on them: ${head}${more}.`, ) } + // Rule findings the rule-noise steps withheld (rule types off, refuted, the rule-post policy). + const offCount = Object.values(env.rulesOff ?? {}).reduce((a, b) => a + b, 0) + const refutedCount = env.rulesRefuted ?? 0 + const policyCount = env.rulePolicy ? env.rulePolicy.dropped.unverifiable_high_sev + env.rulePolicy.dropped.noisy_type_not_confirmed : 0 + if (offCount + refutedCount + policyCount) + notes.push( + `${offCount + refutedCount + policyCount} rule finding(s) not posted (rule types off: ${offCount}, refuted by the verifier: ${refutedCount}, rule-post policy: ${policyCount}); the envelope lists the counts.`, + ) const out = notes.length ? [...notes.map((n) => `> ℹ️ ${n}`), ""] : [] return [...out, ...ledgerBlock(ledger)] } diff --git a/packages/opencode/src/altimate/review/telemetry.ts b/packages/opencode/src/altimate/review/telemetry.ts index 3d9da966f4..7f89df912f 100644 --- a/packages/opencode/src/altimate/review/telemetry.ts +++ b/packages/opencode/src/altimate/review/telemetry.ts @@ -128,6 +128,17 @@ export function emitReviewRun(input: { ai_verify_tool_calls: env.ai?.verifier?.toolCalls, ai_verify_kept: env.ai?.verifier?.kept, ai_verify_discarded: env.ai?.verifier?.discarded, + ai_rule_verify_state: env.ai?.ruleVerifier?.state, + ai_rule_verify_tokens_total: env.ai?.ruleVerifier?.tokens + ? env.ai.ruleVerifier.tokens.inputTotal + env.ai.ruleVerifier.tokens.output + : undefined, + ai_rule_verify_cost: env.ai?.ruleVerifier?.cost, + ai_rule_verify_reviewed: env.ai?.ruleVerifier?.reviewed, + rules_off_dropped: env.rulesOff ? Object.values(env.rulesOff).reduce((a, b) => a + b, 0) : undefined, + rules_refuted: env.rulesRefuted, + rule_policy_dropped: env.rulePolicy + ? env.rulePolicy.dropped.unverifiable_high_sev + env.rulePolicy.dropped.noisy_type_not_confirmed + : undefined, base_source: env.scope?.baseSource, out_of_scope_files: env.scope?.outOfScopeFiles ?? 0, ai_reviewed_outside_files: env.scope?.aiReviewedOutside?.length ?? 0, diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 5b673f3e7c..1e14c758df 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -1679,6 +1679,15 @@ export namespace Telemetry { /** AI findings the verifier kept and discarded; `kept` includes those moved to the summary (summary and unreviewed counts are not emitted). */ ai_verify_kept?: number ai_verify_discarded?: number + /** The rule verifier's run (`verifyRules`): state, tokens (input incl. cached plus output), cost, findings reviewed. */ + ai_rule_verify_state?: string + ai_rule_verify_tokens_total?: number + ai_rule_verify_cost?: number + ai_rule_verify_reviewed?: number + /** Rule findings not posted by rule types off, the refuted filter and the rule-post policy. */ + rules_off_dropped?: number + rules_refuted?: number + rule_policy_dropped?: number /** Where the review base came from (flag, github_event, default_branch, …). */ base_source?: string /** Changed files outside the dbt project that no lane reviewed (outside-project Python files the AI lane reviewed are not counted; see `ai_reviewed_outside_files`). */ diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index 24297bc6dc..0f969e4f43 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -442,3 +442,33 @@ describe("round 2: rule noise fails open", () => { expect(refuted.verdict).toBe("REQUEST_CHANGES") }) }) + +describe("round 2: suppressed rule findings are visible", () => { + test("the PR comment says how many rule findings were not posted, by step", async () => { + const { renderSummary } = await import("../../src/altimate/review/format") + const env = await run({ verdictAt: (i) => (i === 0 ? "refuted" : "unverifiable") }) + const refuted = env.rulesRefuted ?? 0 + const policy = (env.rulePolicy?.dropped.unverifiable_high_sev ?? 0) + (env.rulePolicy?.dropped.noisy_type_not_confirmed ?? 0) + expect(refuted + policy).toBeGreaterThan(0) + const text = renderSummary(env, { allowSilent: false, maxChars: Infinity }) + expect(text).toContain(`${refuted + policy} rule finding(s) not posted`) + }) + + test("telemetry carries the rule verifier's state and spend and the drop counts", async () => { + const { spyOn } = await import("bun:test") + const { emitReviewRun } = await import("../../src/altimate/review/telemetry") + const { Telemetry } = await import("../../src/altimate/telemetry") + const env = await run({ verdictAt: () => "refuted", rulesOff: new Set(["x:y"]) }) + const events: any[] = [] + const spy = spyOn(Telemetry, "track").mockImplementation((e: any) => { + events.push(e) + }) + try { + emitReviewRun({ invocation: "cli", durationMs: 1, sessionID: "", envelope: env }) + } finally { + spy.mockRestore() + } + expect(events[0]).toMatchObject({ ai_rule_verify_state: "ok", rules_refuted: env.rulesRefuted, rule_policy_dropped: 0 }) + expect(events[0].rules_off_dropped).toBe(0) + }) +}) From 8d0b710fe96d093a2058c28b60070e3eae0a44b3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:12:16 +0530 Subject: [PATCH 13/32] fix(review): rule-noise steps filter posting only; forced verdicts count as no verdict MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Verdict: rule types off, the refuted filter and the rule-post policy no longer remove findings from the verdict list. The rule verifier reads author text (the PR description), so a refutation could unblock a gate; now a withheld engine warning still counts toward the ≥3-warning block (and the summary tally), and the PR comment's note says how many were not posted. - A verdict from a rule-verifier batch that stopped on its budget or timeout was forced without tools (`ANSWER_DIRECT`), so it is recorded as no verdict: the policy keeps the finding, and the refuted filter does not act on a forced `refuted` either. - Critical rule findings are not sent to the rule verifier (neither by the orchestrator nor by `runRuleVerify`): they are never dropped, so they would only use the 40-finding ceiling and the budget. Changed expectations: two critical-finding tests asserted the critical finding was in `verifyRulesAfter`; they now assert it is not sent and is posted. The rules-off orchestrator test's summary tally now equals the unfiltered run (the summary counts the verdict's findings). The round-2 batch-failure test answers a non-warning finding instead of the critical one, which is no longer sent. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 23 +++--- .../src/altimate/review/ai-verify-rules.ts | 11 +-- .../src/altimate/review/orchestrate.ts | 18 +++-- .../altimate/review-ai-verify-rules.test.ts | 10 +++ .../altimate/review-rule-post-policy.test.ts | 71 ++++++++++++++++--- .../test/altimate/review-rules-off.test.ts | 3 +- 6 files changed, 106 insertions(+), 30 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 997b52134c..4c0c96696f 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -678,21 +678,24 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne When the AI lane runs and answers, the rule findings are filtered too. 36 rule types that were almost never real defects on public dbt PRs are not posted on files the AI lane reviewed (`ai.rulesOff: false` or - `ALTIMATE_REVIEW_RULES_OFF=0`/`off`/`false` keeps them, `ai.rulesOn: [ids]` keeps + `ALTIMATE_REVIEW_RULES_OFF=0`/`off`/`false`/`no` keeps them, `ai.rulesOn: [ids]` keeps single types, `ALTIMATE_REVIEW_RULES_OFF=.json` replaces the list with a - JSON list of rule ids; the path must be absolute and outside the repository - checkout, and a missing, unreadable or malformed list file stops the review + JSON list of rule ids; the path must be absolute and outside the reviewed + repository and the current directory's work tree, and is refused when neither + resolves to a work tree, and a missing, unreadable or malformed list file stops the review before any lane runs; rule ids match in either spelling, `dbt_patterns:self_join` or `dbt-patterns:self-join`). With the verifier on (`ai.verify`), the rule - findings that would be posted are verified too, up to 40 per PR, most severe - first (`ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS`), in a second verifier run + findings that would be posted are verified too (critical ones are never + dropped, so they are not sent), up to 40 per PR, warnings first (`ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS`), in a second verifier run with its own token budget, and refuted ones are dropped (`ai.verifyRules: false` or `ALTIMATE_REVIEW_AI_VERIFY_RULES=off`; `ai.verify: false` turns it off too). Then a rule finding is not posted when the verifier answered that it could not check it and it is a warning, or when its type is one of 7 noisy types and the verifier did not confirm it (`ai.rulePolicy: false` or `ALTIMATE_REVIEW_RULE_POLICY=0`). A rule finding that got no verdict (its batch - failed or timed out, or it was over the ceiling) is posted. Critical rule + failed, or it was over the ceiling) is posted, and so is one whose verdict came + from a batch that stopped on its budget or timeout (a forced answer without the + verifier's tools counts as no verdict, refuted included). Critical rule findings are never dropped by any of these steps, nor is a repeat-merged comment that includes an AI finding. When the AI lane is skipped or fails (no model, dry run, provider error, timeout), the rule verifier does not run, none of the steps @@ -705,9 +708,11 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → `APPROVE`. Only layer-1 findings reach `critical`, so only the engine can block (the rule verifier and the rule-post policy never drop a critical rule - finding). They can unblock, though: an engine warning that is refuted, turned - off or dropped by the policy is not posted and does not count toward the ≥3 - warnings, so it can lower that `REQUEST_CHANGES` to `COMMENT`. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than + finding). The rule-noise steps change what is posted, never the verdict: an + engine warning that is refuted, turned off or dropped by the policy is not + posted but still counts toward the ≥3 warnings (the summary counts it too), so + neither the verifier nor text it reads, such as the PR description, can unblock + a gate. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than blocking. 5. **Signed envelope.** The verdict is HMAC-signed (`ALTIMATE_REVIEW_SIGNING_KEY`) and includes the manifest hash, so it is replayable and tamper-evident. diff --git a/packages/opencode/src/altimate/review/ai-verify-rules.ts b/packages/opencode/src/altimate/review/ai-verify-rules.ts index f0b4ec44f2..6d19956283 100644 --- a/packages/opencode/src/altimate/review/ai-verify-rules.ts +++ b/packages/opencode/src/altimate/review/ai-verify-rules.ts @@ -50,7 +50,8 @@ export async function runRuleVerify( }) const skip = (reason: string) => done({ state: "skipped", reason, verifier: skippedVerifier(reason, rules.length) }) if (!input.evidence) return skip("the verifier's evidence is unavailable") - if (!rules.length) return skip(NO_RULE_FINDINGS_REASON) + const candidates = rules.filter((f) => f.severity !== "critical") + if (!candidates.length) return skip(NO_RULE_FINDINGS_REASON) if (aiDryRunEnabled(env)) return skip("dry run (ALTIMATE_REVIEW_AI_DRYRUN=1): no model call") let model: Provider.Model try { @@ -61,16 +62,16 @@ export async function runRuleVerify( } const max = Number(env.ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS) const cap = Number.isInteger(max) && max > 0 ? max : RULE_VERIFY_MAX_FINDINGS - // Most severe first, so the warnings the policy acts on are verified before suggestions. + // Critical findings are never dropped, so they are not verified; warnings first, since the policy acts on them. const order = { critical: 2, warning: 1, suggestion: 0 } as const - const sent = [...rules].sort((a, b) => order[b.severity] - order[a.severity]).slice(0, cap) + const sent = [...candidates].sort((a, b) => order[b.severity] - order[a.severity]).slice(0, cap) log.info("verifying rule findings", { findings: sent.length, total: rules.length }) const v = await runAiVerify( { findings: sent, grounding: input.grounding, evidence: input.evidence, model, rulesOnly: true }, { env, ...(deps.llm ? { llm: deps.llm } : {}) }, ) - const over = rules.length - sent.length - const note = `${over} of ${rules.length} rule findings over the per-PR ceiling of ${cap} were not verified` + const over = candidates.length - sent.length + const note = `${over} of ${candidates.length} rule findings over the per-PR ceiling of ${cap} were not verified` const verifier = over ? { ...v.status, reason: v.status.reason ? `${v.status.reason}; ${note}` : note } : v.status return done({ state: "ok", model: `${model.providerID}/${model.id}`, verifier }) } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 1a8319e6ca..f9122f4271 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2820,7 +2820,7 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && findingOrigin(f) !== "ai", ), input.rulesOff, - ).kept.filter((f) => !mayHoldCredentials(f.file)) + ).kept.filter((f) => f.severity !== "critical" && !mayHoldCredentials(f.file)) : undefined try { const res = await input.aiReview({ @@ -2843,7 +2843,13 @@ export async function runReview(input: OrchestrateInput): Promise offStep(list).kept) const verdictOf = (f: Finding) => ruleVerdicts.get(f.id) ?? ruleVerdicts.get(repeatGroupId(f)) const refuted = (f: Finding) => findingOrigin(f) !== "ai" && !inMixed(f) && f.severity !== "critical" && verdictOf(f) === "refuted" const rulesRefuted = aiLaneRan && ruleVerifyAttempted ? findings.filter(refuted).length : undefined if (aiLaneRan && ruleVerdicts.size) { findings = findings.filter((f) => !refuted(f)) - verdictFindings = verdictFindings.filter((f) => !refuted(f)) } let rulePolicy: { applied: boolean; dropped: RulePolicyDrops } | undefined if (aiLaneRan && input.rulePolicy && ruleVerifyAttempted) { @@ -2918,7 +2923,6 @@ export async function runReview(input: OrchestrateInput): Promise dropByRulePolicy(list, byId(list), input.rulePolicy).kept) rulePolicy = { applied: true, dropped: postedDropped } } else rulePolicy = { applied: false, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } } } diff --git a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts index f2ee95aa34..fe45f29202 100644 --- a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts @@ -587,3 +587,13 @@ describe("round 2: credential-like paths", () => { expect(files.has("models/secrets.yml")).toBe(false) }) }) + +describe("round 2b: critical rule findings", () => { + test("runRuleVerify skips critical findings: only critical ones means nothing to verify", async () => { + const llm = scriptModels([], /x/) + const crit = { ...ruleFinding(1), severity: "critical" as const } + const res = await runRuleVerify({ files: [FILE], grounding: [], evidence: evidence() }, [crit]) + expect(res.status.verifier).toMatchObject({ state: "skipped", reason: NO_RULE_FINDINGS_REASON }) + expect(llm).not.toHaveBeenCalled() + }) +}) diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index 0f969e4f43..266000bf7d 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -213,6 +213,8 @@ interface RunOpts { runner?: ReviewRunner /** The finder lane's state (the rule verdicts are recorded whatever it is). */ finderState?: "ok" | "timeout" | "error" + /** The rule run's single batch state (every verdict names batch 0). */ + batchState?: "ok" | "timeout" | "error" | "budget" mode?: "comment" | "gate" } @@ -272,6 +274,7 @@ function run(o: RunOpts = {}, seen: AiReviewInput[] = []) { summary: 0, unreviewed: 0, ...(state === "skipped" ? {} : { ruleVerdicts: records }), + ...(o.batchState ? { batches: [{ findings: rules.length, state: o.batchState, turns: 1, toolCalls: 0 }] } : {}), }, ruleVerifier: { state, @@ -348,11 +351,12 @@ describe("orchestrator: rule-post policy", () => { const seen: AiReviewInput[] = [] const env = await run({ runner: critRunner, verdictAt: () => "unverifiable" }, seen) const sent = seen[0].verifyRulesAfter! - const crit = sent.filter((f) => f.severity === "critical") + // Critical rule findings are not sent to the rule verifier at all; they are posted. + const crit = env.findings.filter((f) => f.severity === "critical") const warn = sent.filter((f) => f.severity === "warning") expect(crit.length).toBe(1) + expect(sent.some((f) => f.severity === "critical")).toBe(false) expect(warn.length).toBeGreaterThan(0) - expect(env.findings.some((f) => f.id === crit[0].id)).toBe(true) expect(env.findings.some((f) => warn.some((w) => w.id === f.id))).toBe(false) expect(env.rulePolicy?.dropped.unverifiable_high_sev).toBe(warn.length) }) @@ -361,10 +365,10 @@ describe("orchestrator: rule-post policy", () => { const seen: AiReviewInput[] = [] const env = await run({ runner: critRunner, verdictAt: () => "refuted" }, seen) const sent = seen[0].verifyRulesAfter! - const crit = sent.filter((f) => f.severity === "critical") - const rest = sent.filter((f) => f.severity !== "critical") + const crit = env.findings.filter((f) => f.severity === "critical") + const rest = sent expect(crit.length).toBe(1) - expect(env.findings.some((f) => f.id === crit[0].id)).toBe(true) + expect(sent.some((f) => f.severity === "critical")).toBe(false) expect(env.findings.some((f) => rest.some((w) => w.id === f.id))).toBe(false) expect(env.rulesRefuted).toBe(rest.length) }) @@ -424,15 +428,16 @@ describe("round 2: rule noise fails open", () => { const seen: AiReviewInput[] = [] const all = await run({ runner: critRunner }, seen) const sent = seen[0].verifyRulesAfter! - // The critical finding's batch answered; the warning's batch failed (no verdict), run state ok. - const env = await run({ runner: critRunner, verdictAt: (i) => (sent[i].severity === "critical" ? "confirmed" : undefined) }) + // One finding's batch answered; the warnings' batch failed (no verdict), run state ok. + const env = await run({ runner: critRunner, verdictAt: (i) => (sent[i].severity === "warning" ? undefined : "confirmed") }) expect(sent.some((f) => f.severity === "warning")).toBe(true) + expect(sent.some((f) => f.severity !== "warning")).toBe(true) expect(env.rulePolicy?.applied).toBe(true) expect(env.findings).toEqual(all.findings) expect(env.rulePolicy?.dropped.unverifiable_high_sev).toBe(0) }) - test("verdict: refuted engine warnings no longer count toward the warning block; a critical one still blocks", async () => { + test("verdict: a refuted critical rule finding is posted and still blocks", async () => { const gate = { mode: "gate" as const } const confirmed = await run({ ...gate, runner: critRunner, verdictAt: () => "confirmed" }) expect(confirmed.verdict).toBe("REQUEST_CHANGES") @@ -472,3 +477,53 @@ describe("round 2: suppressed rule findings are visible", () => { expect(events[0].rules_off_dropped).toBe(0) }) }) + +// Three error-severity engine issues on different rules: three warning rule findings, no critical. +const threeWarnRunner: ReviewRunner = { + ...runner, + async check() { + return { + issues: [ + { rule: "ambiguous-column", severity: "error", category: "correctness", message: "ambiguous column status", line: 3 }, + { rule: "implicit-cartesian", severity: "error", category: "correctness", message: "implicit cross join", line: 2 }, + { rule: "order-by-ordinal", severity: "error", category: "correctness", message: "order by ordinal", line: 4 }, + ], + ran: true, + } + }, +} as ReviewRunner + +describe("round 2b: forced verdicts and the verdict", () => { + test("a verdict from a batch that stopped on budget or timeout counts as no verdict", async () => { + const base = await run({ switches: { verifyRules: false, rulePolicy: false }, policy: false }) + for (const batchState of ["budget", "timeout"] as const) { + for (const v of ["unverifiable", "refuted"] as const) { + const env = await run({ verdictAt: () => v, batchState }) + expect(env.findings).toEqual(base.findings) + expect(env.rulesRefuted).toBe(0) + } + } + // The same verdicts from a batch that answered are acted on. + const answered = await run({ verdictAt: () => "refuted", batchState: "ok" }) + expect(answered.rulesRefuted).toBeGreaterThan(0) + }) + + test("refuted or policy-dropped engine warnings are not posted but still block in gate mode", async () => { + const seen: AiReviewInput[] = [] + const kept = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => "confirmed" }, seen) + expect(seen[0].verifyRulesAfter!.filter((f) => f.severity === "warning").length).toBeGreaterThanOrEqual(3) + expect(kept.verdict).toBe("REQUEST_CHANGES") + for (const v of ["refuted", "unverifiable"] as const) { + const env = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => v }) + expect(env.findings.filter((f) => f.severity === "warning" && f.origin !== "ai").length).toBe(0) + expect(env.verdict).toBe("REQUEST_CHANGES") + } + }) + + test("critical rule findings are not sent to the rule verifier", async () => { + const seen: AiReviewInput[] = [] + const env = await run({ runner: critRunner }, seen) + expect(env.findings.some((f) => f.severity === "critical")).toBe(true) + expect(seen[0].verifyRulesAfter!.some((f) => f.severity === "critical")).toBe(false) + }) +}) diff --git a/packages/opencode/test/altimate/review-rules-off.test.ts b/packages/opencode/test/altimate/review-rules-off.test.ts index b868a5e8c7..038d76b59a 100644 --- a/packages/opencode/test/altimate/review-rules-off.test.ts +++ b/packages/opencode/test/altimate/review-rules-off.test.ts @@ -198,7 +198,8 @@ describe("orchestrator: rule types off", () => { const on = await run({ seen: onSeen, rulesOff: new Set([target, "dbt-patterns:not-in-this-pr"]) }) expect(on.findings).toEqual(base.findings.filter((f) => f.rule !== target)) expect(on.rulesOff).toEqual({ [target]: n }) - expect(on.summary.warning + on.summary.critical + on.summary.suggestion).toBe(base.findings.length - n) + // The summary tallies the verdict's findings, which rule-noise steps do not filter. + expect(on.summary).toEqual(base.summary) // The finder's grounding is the same as without the list. expect(onSeen[0]).toEqual(offSeen[0]) From cb6c286033898f0ee4c4d99b2f28797f8f1c3296 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:12:16 +0530 Subject: [PATCH 14/32] fix(review): `ALTIMATE_REVIEW_RULES_OFF` takes every boolean spelling; its list file uses the shared outside-the-checkout check - `rulesOffEnv` reads booleans through the shared `envBool`, so `no`/`yes` work (before, `=no` was ignored and the switch stayed on while the warning listed `no` as valid). - The ignored-value warning names the extra spellings of `verifyRules` (`drop_refuted/off`) and `rulesOff` (a list path). - The list file goes through `trustedFilePath` with the review's git root (`run.ts` passes it): absolute, outside the reviewed repository and the process's work tree, refused when neither resolves, correct `..` prefix test, and the checked realpath is read. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-switches.ts | 7 ++- .../opencode/src/altimate/review/rules-off.ts | 58 +++++-------------- packages/opencode/src/altimate/review/run.ts | 2 +- .../test/altimate/review-rules-off.test.ts | 39 +++++++++++++ 4 files changed, 61 insertions(+), 45 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index ad3ca021db..1ce4a105ba 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -84,6 +84,11 @@ export function envBool(raw: string | undefined): boolean | undefined { } const WARNED = new Set() +/** What else a switch's env variable accepts, for the warning. */ +const ENV_EXTRA: Partial> = { + verifyRules: ", drop_refuted/off", + rulesOff: ", or an absolute path to a JSON list of rule ids", +} /** Every switch for one review: env, then the `ai:` config object, then the default. */ export function resolveAiSwitches( @@ -101,7 +106,7 @@ export function resolveAiSwitches( // No warning for a lane that will not run (`warn: false`). if (opts.warn !== false && fromEnv === undefined && raw?.trim() && !WARNED.has(warning)) { WARNED.add(warning) - process.stderr.write(`⚠️ ignoring ${AI_SWITCH_ENV[name]}=${raw}: use 1/0 (or true/false, on/off, yes/no)\n`) + process.stderr.write(`⚠️ ignoring ${AI_SWITCH_ENV[name]}=${raw}: use 1/0 (or true/false, on/off, yes/no${ENV_EXTRA[name] ?? ""})\n`) } out[name] = fromEnv ?? configuredSwitch(configured[name as keyof typeof configured]) ?? AI_SWITCH_DEFAULTS[name] } diff --git a/packages/opencode/src/altimate/review/rules-off.ts b/packages/opencode/src/altimate/review/rules-off.ts index c3825005ba..cdf5f0847e 100644 --- a/packages/opencode/src/altimate/review/rules-off.ts +++ b/packages/opencode/src/altimate/review/rules-off.ts @@ -7,51 +7,31 @@ // AI findings and `critical` rule findings are never dropped (`classify-pii:exposes` is // critical for a new high-confidence PII column in a mart), and the finder's grounding is // left as it is. With the AI lane off, skipped or failed nothing changes (fail-open). -// `ai.rulesOff: false` or `ALTIMATE_REVIEW_RULES_OFF=0|off|false` keeps every type; +// `ai.rulesOff: false` or `ALTIMATE_REVIEW_RULES_OFF=0|off|false|no` keeps every type; // `ai.rulesOn: [ids]` keeps single types; `ALTIMATE_REVIEW_RULES_OFF=` replaces the // list with a JSON list of rule ids. Rule ids compare in one spelling (`normalizeRuleId`). -import { existsSync, readFileSync, realpathSync } from "node:fs" -import { dirname, isAbsolute, join, relative } from "node:path" +import { readFileSync } from "node:fs" +import { trustedFilePath } from "./trusted-file" +import { envBool } from "./ai-switches" import { type Finding, findingOrigin, normalizeRuleId } from "./finding" import type { ReviewConfig } from "./config" import type { AiSwitches } from "./ai-switches" /** - * `ALTIMATE_REVIEW_RULES_OFF` read: `1`/`on`/`true` and `0`/`off`/`false` (any case) set the - * switch; a value that looks like a path (has a slash or backslash, or ends in `.json`) names a list + * `ALTIMATE_REVIEW_RULES_OFF` read: the boolean spellings every switch takes (`envBool`: + * `1`/`true`/`on`/`yes`, `0`/`false`/`off`/`no`, any case) set the switch; a value that looks like a path (has a slash or backslash, or ends in `.json`) names a list * file and turns it on; anything else is ignored, so a natural spelling never reaches the * file system. */ export function rulesOffEnv(v: string | undefined): { on?: boolean; file?: string } { const t = v?.trim() if (!t) return {} - if (/^(1|on|true)$/i.test(t)) return { on: true } - if (/^(0|off|false)$/i.test(t)) return { on: false } + const on = envBool(t) + if (on !== undefined) return { on } if (/[\\/]/.test(t) || /\.json$/i.test(t)) return { on: true, file: t } return {} } -/** The git work tree containing `dir` (the nearest ancestor with a `.git` entry), realpath'd; undefined outside one. */ -function workTreeOf(dir: string): string | undefined { - let d: string - try { - d = realpathSync(dir) - } catch { - return undefined - } - for (;;) { - if (existsSync(join(d, ".git"))) return d - const up = dirname(d) - if (up === d) return undefined - d = up - } -} - -function isInsideDir(p: string, dir: string): boolean { - const rel = relative(dir, p) - return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)) -} - export const NOISY_RULES_OFF: readonly string[] = [ "altimate-core.classify-pii:exposes", "altimate-core.lexical:op-json-arrow1", @@ -100,29 +80,21 @@ export function resolveRulesOff( cfg: Pick, switches: Pick, env: Record = process.env, - cwd: string = process.cwd(), + reviewDir?: string, ): Set | undefined { if (!switches.rulesOff) return undefined const { file } = rulesOffEnv(env.ALTIMATE_REVIEW_RULES_OFF) let list: readonly string[] = NOISY_RULES_OFF if (file) { - // The list decides which rule findings are posted: a file in the PR checkout would let a PR choose. - if (!isAbsolute(file)) throw new Error("ALTIMATE_REVIEW_RULES_OFF must name an absolute path outside the repository") - const tree = workTreeOf(cwd) - const real = (() => { - try { - return realpathSync(file) - } catch { - return file - } - })() - if (tree && isInsideDir(real, tree)) - throw new Error(`ALTIMATE_REVIEW_RULES_OFF: the rule list ${file} is inside the git work tree; place it outside the checkout`) - // Synchronous: read once per review, before it starts, from a synchronous resolver; a small local file. + // The list decides which rule findings are posted: a file in the PR checkout would let a PR + // choose. `trustedFilePath` checks it against the review's repository and the process's work + // tree and fails closed; the realpath it checked is the one read. let parsed: unknown try { - parsed = JSON.parse(readFileSync(file, "utf8")) + // Synchronous: read once per review, before it starts, from a synchronous resolver; a small local file. + parsed = JSON.parse(readFileSync(trustedFilePath("ALTIMATE_REVIEW_RULES_OFF", file, [reviewDir]), "utf8")) } catch (e) { + if ((e as NodeJS.ErrnoException)?.code !== "ENOENT" && e instanceof Error && e.message.startsWith("ALTIMATE_REVIEW_RULES_OFF")) throw e const why = (e as NodeJS.ErrnoException)?.code === "ENOENT" ? "file not found" : e instanceof Error ? e.message : String(e) throw new Error(`ALTIMATE_REVIEW_RULES_OFF: cannot read the rule list ${file}: ${why}`) } diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index f0588a6fc9..b5b84f960b 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -379,7 +379,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise const aiOn = !aiDisabledReason const aiSwitches = resolveAiSwitches(config, process.env, { warn: aiOn }) // Rule types off once the AI lane runs; a bad list file named by the env variable fails here. - const rulesOff = aiOn ? resolveRulesOff(config, aiSwitches) : undefined + const rulesOff = aiOn ? resolveRulesOff(config, aiSwitches, process.env, gitRoot) : undefined // `pythonFiles`: .py files outside the dbt project skip every lane but the AI lane. A file // renamed out of this project belongs to it (`--all-projects` assigns it here), so it is offered // at its new path whatever other projects took. diff --git a/packages/opencode/test/altimate/review-rules-off.test.ts b/packages/opencode/test/altimate/review-rules-off.test.ts index 038d76b59a..3502721e62 100644 --- a/packages/opencode/test/altimate/review-rules-off.test.ts +++ b/packages/opencode/test/altimate/review-rules-off.test.ts @@ -317,3 +317,42 @@ describe("round 2: rule types off apply only to files the AI lane reviewed", () expect(failed.findings).toEqual(base.findings) }) }) + +describe("round 2b: rules-off env and list file", () => { + test("`yes`/`no` work like the other switches; the warning names the extra spellings", () => { + expect(rulesOffEnv("no").on).toBe(false) + expect(rulesOffEnv("YES").on).toBe(true) + expect(resolveAiSwitches({ ai: true }, { ALTIMATE_REVIEW_RULES_OFF: "no" }).rulesOff).toBe(false) + const write0 = process.stderr.write + let err = "" + ;(process.stderr as any).write = (s: string) => ((err += s), true) + try { + resolveAiSwitches({ ai: true }, { ALTIMATE_REVIEW_AI_VERIFY_RULES: "sometimes-2b" }) + } finally { + ;(process.stderr as any).write = write0 + } + expect(err).toContain("drop_refuted/off") + }) + + test("a list named `..x.json` inside the review's repository is refused", async () => { + await using repo = await tmpdir({ git: true }) + const file = join(repo.path, "..rules.json") + writeFileSync(file, '["a:b"]') + expect(() => resolveRulesOff({ ai: true }, { rulesOff: true }, { ALTIMATE_REVIEW_RULES_OFF: file }, repo.path)).toThrow("inside the git work tree") + }) + + test("fails closed when no work tree resolves; the review's repository is checked from anywhere", async () => { + await using repo = await tmpdir({ git: true }) + await using elsewhere = await tmpdir() + const file = join(repo.path, "rules.json") + writeFileSync(file, '["a:b"]') + const cwd = process.cwd() + process.chdir(elsewhere.path) + try { + expect(() => resolveRulesOff({ ai: true }, { rulesOff: true }, { ALTIMATE_REVIEW_RULES_OFF: file })).toThrow("refusing it") + expect(() => resolveRulesOff({ ai: true }, { rulesOff: true }, { ALTIMATE_REVIEW_RULES_OFF: file }, repo.path)).toThrow("inside the git work tree") + } finally { + process.chdir(cwd) + } + }) +}) From e8b6a16d74fb27ab03333b1ddfc3cbcde113ad66 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:26:11 +0530 Subject: [PATCH 15/32] fix(review): list withheld rule findings that count toward a blocking verdict Since the rule-noise steps filter posting only, a gate could block on warnings nobody could see. The orchestrator now records the withheld rule findings that can block (confident, verdict-eligible engine warnings), each with why it was not posted (rule type off, refuted, unverifiable, noisy type not confirmed). The envelope keeps the list (`withheld`) only when the verdict is REQUEST_CHANGES, and the summary shows it as "Withheld rule findings that count toward this verdict", with file:line, title and reason. Docs updated. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 4 ++- .../opencode/src/altimate/review/format.ts | 17 +++++++++ .../src/altimate/review/orchestrate.ts | 35 ++++++++++++++++++- .../opencode/src/altimate/review/verdict.ts | 17 +++++++++ .../altimate/review-rule-post-policy.test.ts | 19 ++++++++++ 5 files changed, 90 insertions(+), 2 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 4c0c96696f..04af92461e 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -712,7 +712,9 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne engine warning that is refuted, turned off or dropped by the policy is not posted but still counts toward the ≥3 warnings (the summary counts it too), so neither the verifier nor text it reads, such as the PR description, can unblock - a gate. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than + a gate. When the verdict is `REQUEST_CHANGES`, the summary lists the withheld + engine warnings that count toward it (file and line, title, and why each was not + posted), and the envelope records them under `withheld`. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than blocking. 5. **Signed envelope.** The verdict is HMAC-signed (`ALTIMATE_REVIEW_SIGNING_KEY`) and includes the manifest hash, so it is replayable and tamper-evident. diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 339ad9f194..df5f31783c 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -87,6 +87,16 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s ) } lines.push(...notes) + // A blocking verdict must be explainable from the comment: rule findings that were not posted + // but still count toward it are listed with why they were withheld. + if (env.withheld?.length) { + lines.push( + `### Withheld rule findings that count toward this verdict (${env.withheld.length})`, + "", + ...env.withheld.map((w) => `- \`${w.file}${w.startLine ? `:${w.startLine}` : ""}\` — ${w.title} (${WITHHELD_REASON[w.reason]})`), + "", + ) + } const tail: string[] = [] // G1 (Round 18) — surface classifier reasons when --explain-tier populated @@ -261,6 +271,13 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou * the advisory AI lane when it did not run. Kept separate from the lint-only * banner so one undecidable finding never mislabels a manifest-backed run. */ +const WITHHELD_REASON: Record[number]["reason"], string> = { + rule_type_off: "rule type not posted while the AI review runs", + refuted: "refuted by the verifier", + unverifiable_high_sev: "the verifier could not check it", + noisy_type_not_confirmed: "noisy rule type the verifier did not confirm", +} + export function coverageNotes(env: VerdictEnvelope): string[] { const notes: string[] = [] const undecided = env.findings.filter((f) => f.degraded).length diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index f9122f4271..bdddc79bc3 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -39,6 +39,7 @@ import { errorReason, isOutsideProjectReason, signEnvelope, + verdictEligible, } from "./verdict" import { detectMacroPatterns, detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" import { type SelectItemColumn, normalizeSelectLine } from "./rule-catalog" @@ -72,7 +73,14 @@ import { isAiOtherFile } from "./ai-other-files" import { AI_PYTHON_KIND, isAiPythonFile } from "./ai-python-files" import { type Convention, conventionTexts } from "./conventions" import { dropRulesOff } from "./rules-off" -import { type RulePolicyDrops, type RulePostPolicy, type RuleVerdictValue, dropByRulePolicy, rulePolicyApplies } from "./rule-post-policy" +import { + type RulePolicyDrops, + type RulePostPolicy, + type RuleVerdictValue, + dropByRulePolicy, + rulePolicyApplies, + rulePolicyDrop, +} from "./rule-post-policy" import { type AiVerifyEvidence, numberedSlice } from "./ai-verify" import { holdsCredentials, isCredentialPath } from "./credentials" import type { ColumnReach } from "../native/dbt/column-reach" @@ -2926,6 +2934,30 @@ export async function runReview(input: OrchestrateInput): Promise = [] + { + const blocking = (f: Finding) => f.severity === "warning" && f.confidence !== "unknown" && verdictEligible(f, input.rubric) + const note = (f: Finding, reason: NonNullable[number]["reason"]) => { + if (blocking(f)) + withheld.push({ id: f.id, title: f.title, file: f.file, ...(f.startLine ? { startLine: f.startLine } : {}), severity: f.severity, reason }) + } + let rest = verdictFindings + const offKept = new Set(ruleStep(rest, (list) => offStep(list).kept)) + for (const f of rest) if (!offKept.has(f)) note(f, "rule_type_off") + rest = rest.filter((f) => offKept.has(f)) + if (aiLaneRan && ruleVerdicts.size) { + for (const f of rest) if (refuted(f)) note(f, "refuted") + rest = rest.filter((f) => !refuted(f)) + } + if (rulePolicy?.applied && input.rulePolicy) + for (const f of rest) { + const why = inMixed(f) ? undefined : rulePolicyDrop(f, verdictOf(f) ?? null, input.rulePolicy) + if (why) note(f, why) + } + } // Lint-only means no changed model resolved against a manifest. A single // undecidable finding does not make the whole run lint-only; those findings @@ -2969,6 +3001,7 @@ export async function runReview(input: OrchestrateInput): Promise { expect(seen[0].verifyRulesAfter!.some((f) => f.severity === "critical")).toBe(false) }) }) + +describe("round 2c: a block on withheld findings is explainable", () => { + test("gate mode, three refuted engine warnings: REQUEST_CHANGES and the summary lists them with why", async () => { + const { renderSummary } = await import("../../src/altimate/review/format") + const env = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => "refuted" }) + expect(env.verdict).toBe("REQUEST_CHANGES") + expect(env.withheld?.length).toBeGreaterThanOrEqual(3) + expect(env.withheld!.every((w) => w.reason === "refuted" && w.severity === "warning")).toBe(true) + const text = renderSummary(env, { maxChars: Infinity }) + expect(text).toContain(`### Withheld rule findings that count toward this verdict (${env.withheld!.length})`) + for (const w of env.withheld!) expect(text).toContain(`\`${w.file}${w.startLine ? `:${w.startLine}` : ""}\` — ${w.title} (refuted by the verifier)`) + }) + + test("no blocking verdict: nothing is listed", async () => { + const env = await run({ verdictAt: () => "refuted" }) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + expect(env.withheld).toBeUndefined() + }) +}) From 3ac8a36f24280d781d4df9d003f845db2939afdb Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 13:30:24 +0530 Subject: [PATCH 16/32] fix(review): budget-forced rule verdicts count again; only a timed-out batch's verdict is discarded `331a8601ed` treated every verdict from a rule-verifier batch that stopped on its budget or timeout as no verdict. Under the default 12k budget split over batches of 8, almost every rule batch is forced to answer at the budget (103 of 108 on the 90-PR parity rerun, 20 of 20 in the release run), so the refuted filter and the rule-post policy almost never fired, and the wrong share of posted comments went back to its pre-policy level or worse. The policy was tuned and validated on exactly these forced answers. Budget-forced verdicts count again for the refuted filter and the policy. This is safe now that the rule-noise steps filter posting only: a forced or author-influenced verdict can withhold a comment but cannot unblock a gate. A verdict from a batch that timed out still counts as no verdict, and findings with no verdict are still posted (fail open). Changed expectations: the round-2b test that expected budget-forced verdicts to be ignored now expects a refuted one to be withheld from posting, with the timeout case unchanged. A new test checks that a budget-forced refuted warning still counts in the verdict. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 12 ++++---- .../altimate/review-rule-post-policy.test.ts | 28 ++++++++++++------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index bdddc79bc3..468eb12dc6 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2851,13 +2851,13 @@ export async function runReview(input: OrchestrateInput): Promise { - test("a verdict from a batch that stopped on budget or timeout counts as no verdict", async () => { + test("a budget-forced verdict is acted on for posting; a timed-out batch's verdict counts as no verdict", async () => { const base = await run({ switches: { verifyRules: false, rulePolicy: false }, policy: false }) - for (const batchState of ["budget", "timeout"] as const) { - for (const v of ["unverifiable", "refuted"] as const) { - const env = await run({ verdictAt: () => v, batchState }) - expect(env.findings).toEqual(base.findings) - expect(env.rulesRefuted).toBe(0) - } + // Budget: the rule run's usual mode; the refuted findings are not posted. + const budget = await run({ verdictAt: () => "refuted", batchState: "budget" }) + expect(budget.rulesRefuted).toBeGreaterThan(0) + expect(budget.findings.length).toBeLessThan(base.findings.length) + // Timeout: no verdict, everything posted. + for (const v of ["unverifiable", "refuted"] as const) { + const env = await run({ verdictAt: () => v, batchState: "timeout" }) + expect(env.findings).toEqual(base.findings) + expect(env.rulesRefuted).toBe(0) } - // The same verdicts from a batch that answered are acted on. - const answered = await run({ verdictAt: () => "refuted", batchState: "ok" }) - expect(answered.rulesRefuted).toBeGreaterThan(0) + }) + + test("a budget-forced refuted warning is not posted but still counts in the verdict", async () => { + const confirmed = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => "confirmed", batchState: "budget" }) + const refuted = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => "refuted", batchState: "budget" }) + expect(refuted.findings.filter((f) => f.severity === "warning" && f.origin !== "ai").length).toBe(0) + expect(refuted.verdict).toBe(confirmed.verdict) + expect(refuted.verdict).toBe("REQUEST_CHANGES") }) test("refuted or policy-dropped engine warnings are not posted but still block in gate mode", async () => { From 557bf89a099c60dce5edd717d0c67616115e18c9 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 13:30:37 +0530 Subject: [PATCH 17/32] fix(review): verify rules-off findings on files the AI lane does not send; noisy types first under the ceiling - `verifyRulesAfter` left out rules-off types on every file, but posting drops them only on files the AI lane reviewed, so a rules-off finding on any other file was posted without ever being verified (9 on the parity rerun). They are now left out only on files the lane sends. - Under the 40-finding ceiling, the default noisy types go first within a severity, since their posting depends on a verdict. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-verify-rules.ts | 10 ++-- .../src/altimate/review/orchestrate.ts | 14 +++-- .../test/altimate/review-rules-off.test.ts | 52 +++++++++++++++++++ 3 files changed, 68 insertions(+), 8 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-verify-rules.ts b/packages/opencode/src/altimate/review/ai-verify-rules.ts index 6d19956283..59aa4ca9b7 100644 --- a/packages/opencode/src/altimate/review/ai-verify-rules.ts +++ b/packages/opencode/src/altimate/review/ai-verify-rules.ts @@ -7,7 +7,8 @@ // a dry run or a failed call leaves every rule finding as it was. import { Provider } from "@/provider/provider" import { Log } from "@/altimate/util/log" -import type { Finding } from "./finding" +import { type Finding, normalizeRuleId } from "./finding" +import { NOISY_RULE_TYPES } from "./rule-post-policy" import { aiDryRunEnabled, safeReason, type AiLaneStatus, type AiReviewInput, type AiReviewResult } from "./ai-review" import { runAiVerify, type VerifierLlm, type VerifierStatus } from "./ai-verify" @@ -62,9 +63,12 @@ export async function runRuleVerify( } const max = Number(env.ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS) const cap = Number.isInteger(max) && max > 0 ? max : RULE_VERIFY_MAX_FINDINGS - // Critical findings are never dropped, so they are not verified; warnings first, since the policy acts on them. + // Critical findings are never dropped, so they are not verified. Warnings first, since the policy + // acts on them, and within a severity the default noisy types, whose posting depends on a verdict. const order = { critical: 2, warning: 1, suggestion: 0 } as const - const sent = [...candidates].sort((a, b) => order[b.severity] - order[a.severity]).slice(0, cap) + const noisy = new Set(NOISY_RULE_TYPES.map(normalizeRuleId)) + const isNoisy = (f: Finding) => (f.rule && noisy.has(normalizeRuleId(f.rule)) ? 1 : 0) + const sent = [...candidates].sort((a, b) => order[b.severity] - order[a.severity] || isNoisy(b) - isNoisy(a)).slice(0, cap) log.info("verifying rule findings", { findings: sent.length, total: rules.length }) const v = await runAiVerify( { findings: sent, grounding: input.grounding, evidence: input.evidence, model, rulesOnly: true }, diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 468eb12dc6..8338b6065c 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2822,13 +2822,17 @@ export async function runReview(input: OrchestrateInput): Promise { + const posted = cleanFindings(preAiValidated.list).filter( (f) => SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && findingOrigin(f) !== "ai", - ), - input.rulesOff, - ).kept.filter((f) => f.severity !== "critical" && !mayHoldCredentials(f.file)) + ) + const offKept = new Set(dropRulesOff(posted.filter((f) => sentSet.has(f.file)), input.rulesOff).kept) + return posted.filter((f) => (!sentSet.has(f.file) || offKept.has(f)) && f.severity !== "critical" && !mayHoldCredentials(f.file)) + })() : undefined try { const res = await input.aiReview({ diff --git a/packages/opencode/test/altimate/review-rules-off.test.ts b/packages/opencode/test/altimate/review-rules-off.test.ts index 3502721e62..71c8d33150 100644 --- a/packages/opencode/test/altimate/review-rules-off.test.ts +++ b/packages/opencode/test/altimate/review-rules-off.test.ts @@ -356,3 +356,55 @@ describe("round 2b: rules-off env and list file", () => { } }) }) + +describe("round 3: rules-off, verification and explainable verdicts", () => { + const runner: ReviewRunner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } as ReviewRunner + const SQL = "select *\nfrom raw.orders\nwhere status = 'x'\norder by 1" + const model = { path: "models/marts/m.sql", status: "modified" as const, diff: `@@ -1 +1,4 @@\n-select 1\n+${SQL.split("\n").join("\n+")}\n` } + const yml = { path: "config/extra.yml", status: "modified" as const, diff: "@@ -1 +1 @@\n-a: 1\n+a: [\n" } + const run = (changed: any[], rulesOff: Set | undefined, seen: AiReviewInput[] = []) => + runReview({ + changedFiles: changed, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiVerify: true, + aiSwitches: { verifyRules: true, otherFiles: false }, + getContent: async (f, side) => (f.endsWith(".yml") ? (side === "old" ? "a: 1\n" : "a: [\n") : side === "old" ? "select 1" : SQL), + generatedAt: "2026-11-27T00:00:00Z", + ...(rulesOff ? { rulesOff } : {}), + aiReview: async (input: AiReviewInput) => { + seen.push(input) + return { findings: [], status: { state: "ok" as const } } + }, + }) + + test("a rules-off finding on a file the AI lane does not send is verified (it will be posted)", async () => { + const base = await run([model, yml], undefined) + const ymlRule = base.findings.find((f) => f.file === "config/extra.yml")?.rule + expect(ymlRule).toBeDefined() + const seen: AiReviewInput[] = [] + await run([model, yml], new Set([ymlRule!]), seen) + expect(seen[0].files.map((f) => f.path)).not.toContain("config/extra.yml") + expect((seen[0].verifyRulesAfter ?? []).some((f) => f.file === "config/extra.yml")).toBe(true) + }) + +}) From 90e7f7f4be9ff8f8249fbab3d81f038d38b39aa6 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 13:30:37 +0530 Subject: [PATCH 18/32] fix(review): list withheld findings whenever they change the verdict, including away from APPROVE A PR could get COMMENT with nothing posted (all of its findings withheld by rule types off). The orchestrator now compares the verdict over every instance with the verdict over the posted ones. Toward REQUEST_CHANGES it lists the withheld confident engine warnings, as before. When the withheld findings alone keep the verdict from APPROVE, it lists every one of them. `buildEnvelope` keeps whatever list it is given, the summary section says the findings were not posted but are counted, and the docs say that findings over the 40-finding ceiling are posted unverified. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 20 ++++++---- .../opencode/src/altimate/review/format.ts | 2 + .../src/altimate/review/orchestrate.ts | 40 +++++++++++++------ .../opencode/src/altimate/review/verdict.ts | 9 +++-- .../test/altimate/review-rules-off.test.ts | 11 +++++ 5 files changed, 58 insertions(+), 24 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 04af92461e..7c056d4b8a 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -686,16 +686,19 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne before any lane runs; rule ids match in either spelling, `dbt_patterns:self_join` or `dbt-patterns:self-join`). With the verifier on (`ai.verify`), the rule findings that would be posted are verified too (critical ones are never - dropped, so they are not sent), up to 40 per PR, warnings first (`ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS`), in a second verifier run - with its own token budget, and refuted ones are dropped (`ai.verifyRules: false` + dropped, so they are not sent; rule types off are sent too on files the AI lane + does not review, where they are posted), up to 40 per PR, warnings and the noisy + types first (`ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS`); findings over the + ceiling are posted unverified. The rule run is a second verifier run with its own + token budget; on the default budget most of its batches answer without tools + (forced at the budget), and those verdicts count. Refuted ones are dropped (`ai.verifyRules: false` or `ALTIMATE_REVIEW_AI_VERIFY_RULES=off`; `ai.verify: false` turns it off too). Then a rule finding is not posted when the verifier answered that it could not check it and it is a warning, or when its type is one of 7 noisy types and the verifier did not confirm it (`ai.rulePolicy: false` or `ALTIMATE_REVIEW_RULE_POLICY=0`). A rule finding that got no verdict (its batch - failed, or it was over the ceiling) is posted, and so is one whose verdict came - from a batch that stopped on its budget or timeout (a forced answer without the - verifier's tools counts as no verdict, refuted included). Critical rule + failed, or it was over the ceiling) is posted, and so is one whose batch timed + out (its verdict counts as no verdict). Critical rule findings are never dropped by any of these steps, nor is a repeat-merged comment that includes an AI finding. When the AI lane is skipped or fails (no model, dry run, provider error, timeout), the rule verifier does not run, none of the steps @@ -712,9 +715,10 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne engine warning that is refuted, turned off or dropped by the policy is not posted but still counts toward the ≥3 warnings (the summary counts it too), so neither the verifier nor text it reads, such as the PR description, can unblock - a gate. When the verdict is `REQUEST_CHANGES`, the summary lists the withheld - engine warnings that count toward it (file and line, title, and why each was not - posted), and the envelope records them under `withheld`. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than + a gate. When withheld findings change the verdict, the summary lists them (file + and line, title, and why each was not posted) and the envelope records them under + `withheld`: the engine warnings that count toward a `REQUEST_CHANGES`, or every + withheld finding when they alone keep the verdict from `APPROVE`. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than blocking. 5. **Signed envelope.** The verdict is HMAC-signed (`ALTIMATE_REVIEW_SIGNING_KEY`) and includes the manifest hash, so it is replayable and tamper-evident. diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index df5f31783c..04da5b3837 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -93,6 +93,8 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s lines.push( `### Withheld rule findings that count toward this verdict (${env.withheld.length})`, "", + "Not posted as comments, but the verdict counts them:", + "", ...env.withheld.map((w) => `- \`${w.file}${w.startLine ? `:${w.startLine}` : ""}\` — ${w.title} (${WITHHELD_REASON[w.reason]})`), "", ) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 8338b6065c..274092a750 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -39,6 +39,7 @@ import { errorReason, isOutsideProjectReason, signEnvelope, + computeIdealVerdict, verdictEligible, } from "./verdict" import { detectMacroPatterns, detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" @@ -2938,30 +2939,45 @@ export async function runReview(input: OrchestrateInput): Promise = [] + // The verdict counts the rule findings these steps did not post. When they change it — toward + // REQUEST_CHANGES (a confident engine warning toward the ≥3-warning pattern), or away from APPROVE + // with nothing else to show — they are listed with why they were withheld, so every verdict is + // explainable from the comment. + type Withheld = NonNullable[number] + const withheldAll: Array<{ f: Finding; reason: Withheld["reason"] }> = [] { - const blocking = (f: Finding) => f.severity === "warning" && f.confidence !== "unknown" && verdictEligible(f, input.rubric) - const note = (f: Finding, reason: NonNullable[number]["reason"]) => { - if (blocking(f)) - withheld.push({ id: f.id, title: f.title, file: f.file, ...(f.startLine ? { startLine: f.startLine } : {}), severity: f.severity, reason }) - } let rest = verdictFindings const offKept = new Set(ruleStep(rest, (list) => offStep(list).kept)) - for (const f of rest) if (!offKept.has(f)) note(f, "rule_type_off") + for (const f of rest) if (!offKept.has(f)) withheldAll.push({ f, reason: "rule_type_off" }) rest = rest.filter((f) => offKept.has(f)) if (aiLaneRan && ruleVerdicts.size) { - for (const f of rest) if (refuted(f)) note(f, "refuted") + for (const f of rest) if (refuted(f)) withheldAll.push({ f, reason: "refuted" }) rest = rest.filter((f) => !refuted(f)) } if (rulePolicy?.applied && input.rulePolicy) for (const f of rest) { const why = inMixed(f) ? undefined : rulePolicyDrop(f, verdictOf(f) ?? null, input.rulePolicy) - if (why) note(f, why) + if (why) withheldAll.push({ f, reason: why }) } } + const withheldIds = new Set(withheldAll.map((w) => w.f)) + const idealAll = computeIdealVerdict(verdictFindings, input.rubric) + const idealPosted = computeIdealVerdict(verdictFindings.filter((f) => !withheldIds.has(f)), input.rubric) + const blocking = (f: Finding) => f.severity === "warning" && f.confidence !== "unknown" && verdictEligible(f, input.rubric) + const listed = + idealAll === "REQUEST_CHANGES" + ? withheldAll.filter((w) => blocking(w.f)) + : idealAll !== "APPROVE" && idealPosted === "APPROVE" + ? withheldAll + : [] + const withheld: Withheld[] = listed.map(({ f, reason }) => ({ + id: f.id, + title: f.title, + file: f.file, + ...(f.startLine ? { startLine: f.startLine } : {}), + severity: f.severity, + reason, + })) // Lint-only means no changed model resolved against a manifest. A single // undecidable finding does not make the whole run lint-only; those findings diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index a70ad6cc72..196c1e60c8 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -439,8 +439,9 @@ export const VerdictEnvelope = z.object({ }), }) .optional(), - /** Rule findings the rule-noise steps did not post that still count toward a REQUEST_CHANGES - * verdict (listed so the block is explainable); only when the verdict blocks. */ + /** Rule findings the rule-noise steps did not post that the verdict still counts, with why: + * those toward a REQUEST_CHANGES block, or every one when they alone keep the verdict from + * APPROVE. Absent when they do not change the verdict. */ withheld: z .array( z.object({ @@ -592,8 +593,8 @@ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { rulesOff: input.rulesOff, rulesRefuted: input.rulesRefuted, rulePolicy: input.rulePolicy, - // Listed only when the verdict blocks: then a withheld finding may be part of the reason. - withheld: ideal === "REQUEST_CHANGES" && input.withheld?.length ? input.withheld : undefined, + // The orchestrator lists them only when they change the verdict. + withheld: input.withheld?.length ? input.withheld : undefined, policy: input.policy, engineErrors: input.engineErrors, generatedAt: input.generatedAt, diff --git a/packages/opencode/test/altimate/review-rules-off.test.ts b/packages/opencode/test/altimate/review-rules-off.test.ts index 71c8d33150..5030b6bf13 100644 --- a/packages/opencode/test/altimate/review-rules-off.test.ts +++ b/packages/opencode/test/altimate/review-rules-off.test.ts @@ -407,4 +407,15 @@ describe("round 3: rules-off, verification and explainable verdicts", () => { expect((seen[0].verifyRulesAfter ?? []).some((f) => f.file === "config/extra.yml")).toBe(true) }) + test("nothing posted but the verdict is COMMENT: the withheld findings are listed", async () => { + const { renderSummary } = await import("../../src/altimate/review/format") + const base = await run([model], undefined) + const rules = new Set(base.findings.map((f) => f.rule!)) + const env = await run([model], rules) + expect(env.findings).toEqual([]) + expect(env.verdict).toBe("COMMENT") + expect(env.withheld?.length).toBeGreaterThan(0) + expect(env.withheld!.every((w) => w.reason === "rule_type_off")).toBe(true) + expect(renderSummary(env, { maxChars: Infinity })).toContain("### Withheld rule findings that count toward this verdict") + }) }) From e81c0db44fa7ec9d5cfa171fe38abf4b93868311 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:53:02 +0530 Subject: [PATCH 19/32] fix(review): withheld findings survive `--all-projects`, stay within the summary budget, and never read as a clean run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `mergeProjectEnvelopes` dropped `withheld`, so a merged run that blocked through one project's withheld engine warnings had no explanation. The projects' lists are now merged (deduplicated by id). - The withheld list was unbounded and sat outside the summary budget, so a large list could push the posted findings out of the comment. It now shows at most 10 entries and points to the envelope for the rest. - A run whose findings were all withheld ended with "No issues found ... 🎉" under a blocking headline. It now says no findings were posted and that the verdict rests on the withheld findings. - `WITHHELD_REASON` no longer sits between `coverageNotes` and its doc. Tests (review-rule-post-policy.test.ts): `a run whose findings were all withheld does not say no issues were found`, `several hundred withheld findings: the list is capped and the summary stays within its budget`, `--all-projects: a project that blocks only through withheld findings keeps them in the merged envelope`. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 30 ++++++++++---- .../src/altimate/review/multi-project.ts | 11 +++-- .../altimate/review-rule-post-policy.test.ts | 40 +++++++++++++++++++ 3 files changed, 70 insertions(+), 11 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 04da5b3837..c0b34746c7 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -95,7 +95,12 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s "", "Not posted as comments, but the verdict counts them:", "", - ...env.withheld.map((w) => `- \`${w.file}${w.startLine ? `:${w.startLine}` : ""}\` — ${w.title} (${WITHHELD_REASON[w.reason]})`), + ...env.withheld + .slice(0, WITHHELD_RENDER_CAP) + .map((w) => `- \`${w.file}${w.startLine ? `:${w.startLine}` : ""}\` — ${w.title} (${WITHHELD_REASON[w.reason]})`), + ...(env.withheld.length > WITHHELD_RENDER_CAP + ? [`- … and ${env.withheld.length - WITHHELD_RENDER_CAP} more in the verdict envelope`] + : []), "", ) } @@ -139,7 +144,12 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s ) if (!env.findings.length) { - lines.push("No issues found in the changed dbt models. 🎉", "") + lines.push( + env.withheld?.length + ? "No findings posted; the verdict rests on the withheld rule findings above." + : "No issues found in the changed dbt models. 🎉", + "", + ) return [...lines, ...tail].join("\n") } @@ -267,12 +277,6 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou return out } -/** - * What the review could not fully check, each on its own line: undecidable - * findings, models without compiled SQL, files outside the dbt project, and - * the advisory AI lane when it did not run. Kept separate from the lint-only - * banner so one undecidable finding never mislabels a manifest-backed run. - */ const WITHHELD_REASON: Record[number]["reason"], string> = { rule_type_off: "rule type not posted while the AI review runs", refuted: "refuted by the verifier", @@ -280,6 +284,16 @@ const WITHHELD_REASON: Record[number][" noisy_type_not_confirmed: "noisy rule type the verifier did not confirm", } +/** Withheld findings listed in the summary at most; the envelope keeps every one. */ +const WITHHELD_RENDER_CAP = 10 + +/** + * What the review could not fully check, each on its own line: undecidable + * findings, models without compiled SQL, files outside the dbt project, and + * the advisory AI lane when it did not run. Kept separate from the lint-only + * banner so one undecidable finding never mislabels a manifest-backed run. + */ + export function coverageNotes(env: VerdictEnvelope): string[] { const notes: string[] = [] const undecided = env.findings.filter((f) => f.degraded).length diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 7366867b6a..170367a1e3 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -309,9 +309,11 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri return signEnvelope(VerdictEnvelope.parse(merged)) } -/** Rule-noise counts summed over the projects (each present only when some project has it). */ -function mergeRuleNoise(envs: VerdictEnvelope[]): Pick { - const out: Pick = {} +/** Rule-noise counts summed over the projects (each present only when some project has it), and + * every project's withheld findings: each project lists them only when they change its verdict, + * so the merged verdict, the worst of the projects', stays explainable from the comment. */ +function mergeRuleNoise(envs: VerdictEnvelope[]): Pick { + const out: Pick = {} if (envs.some((e) => e.rulesOff)) { const off: Record = {} for (const e of envs) for (const [rule, n] of Object.entries(e.rulesOff ?? {})) off[rule] = (off[rule] ?? 0) + n @@ -327,6 +329,9 @@ function mergeRuleNoise(envs: VerdictEnvelope[]): Pick n + p.dropped.noisy_type_not_confirmed, 0), }, } + const seen = new Set() + const withheld = envs.flatMap((e) => e.withheld ?? []).filter((w) => !seen.has(w.id) && !!seen.add(w.id)) + if (withheld.length) out.withheld = withheld return out } diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index 4eb19ebdcc..f9839b2baf 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -554,3 +554,43 @@ describe("round 2c: a block on withheld findings is explainable", () => { expect(env.withheld).toBeUndefined() }) }) + +describe("round 4: withheld findings in the comment and the merge", () => { + test("a run whose findings were all withheld does not say no issues were found", async () => { + const { renderSummary } = await import("../../src/altimate/review/format") + const env = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => "refuted" }) + expect(env.withheld?.length).toBeGreaterThan(0) + // Nothing posted at all (the AI finding removed too): the verdict rests on the withheld list. + const text = renderSummary({ ...env, findings: [] }, { maxChars: Infinity }) + expect(text).not.toContain("No issues found") + expect(text).toContain("No findings posted") + }) + + test("several hundred withheld findings: the list is capped and the summary stays within its budget", async () => { + const { renderSummary, SUMMARY_BUDGET_CHARS } = await import("../../src/altimate/review/format") + const env = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => "refuted" }) + const w = env.withheld![0] + const many = Array.from({ length: 300 }, (_, i) => ({ ...w, id: `${w.id}-${i}`, startLine: i + 1 })) + const text = renderSummary({ ...env, withheld: many }) + expect(text.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) + expect(text).toContain("### Withheld rule findings that count toward this verdict (300)") + expect(text).toContain("more in the verdict envelope") + // The posted AI finding is still in the comment. + expect(text).toContain(aiFinding.title) + }) + + test("--all-projects: a project that blocks only through withheld findings keeps them in the merged envelope", async () => { + const { mergeProjectEnvelopes } = await import("../../src/altimate/review/multi-project") + const { renderSummary } = await import("../../src/altimate/review/format") + const a = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => "refuted" }) + const b = await run({ mode: "gate" }) + expect(a.withheld?.length).toBeGreaterThan(0) + const merged = mergeProjectEnvelopes([ + { root: "a", paths: ["a/models/marts/m.sql"], env: a }, + { root: "b", paths: ["b/models/marts/m.sql"], env: b }, + ]) + expect(merged.idealVerdict).toBe("REQUEST_CHANGES") + expect(merged.withheld?.map((x) => x.id).sort()).toEqual(a.withheld!.map((x) => x.id).sort()) + expect(renderSummary(merged, { maxChars: Infinity })).toContain("### Withheld rule findings that count toward this verdict") + }) +}) From faa06d191fd8f23561dc0818405822fe088b8c31 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:53:02 +0530 Subject: [PATCH 20/32] fix(review): count the rule-noise steps over instances, like the withheld list and the verdict `rulesOff`, `rulesRefuted` and `rulePolicy.dropped` were counted over the repeat-merged comments, while `withheld`, the summary counts and the verdict use the instances. For one refuted comment covering three instances, the coverage note said 1 while the withheld section listed 3. The counts are now taken in the withheld pass, over the instances. What is posted is unchanged. Test (review-rule-post-policy.test.ts): `the per-step counts are instances, like the withheld list and the verdict`. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 37 ++++++++++--------- .../altimate/review-rule-post-policy.test.ts | 23 ++++++++++++ 2 files changed, 43 insertions(+), 17 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 274092a750..57f096d93f 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2913,16 +2913,10 @@ export async function runReview(input: OrchestrateInput): Promise !aiReviewed.has(f.file) || kept.has(f)), dropped: r.dropped } } - let offDropped: Record = {} - findings = ruleStep(findings, (list) => { - const r = offStep(list) - offDropped = r.dropped - return r.kept - }) + findings = ruleStep(findings, (list) => offStep(list).kept) const verdictOf = (f: Finding) => ruleVerdicts.get(f.id) ?? ruleVerdicts.get(repeatGroupId(f)) const refuted = (f: Finding) => findingOrigin(f) !== "ai" && !inMixed(f) && f.severity !== "critical" && verdictOf(f) === "refuted" - const rulesRefuted = aiLaneRan && ruleVerifyAttempted ? findings.filter(refuted).length : undefined if (aiLaneRan && ruleVerdicts.size) { findings = findings.filter((f) => !refuted(f)) } @@ -2930,24 +2924,29 @@ export async function runReview(input: OrchestrateInput): Promise new Map(list.map((f) => [f.id, verdictOf(f) ?? null] as const)) - let postedDropped: RulePolicyDrops = { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } - findings = ruleStep(findings, (list) => { - const r = dropByRulePolicy(list, byId(list), input.rulePolicy) - postedDropped = r.dropped - return r.kept - }) - rulePolicy = { applied: true, dropped: postedDropped } + findings = ruleStep(findings, (list) => dropByRulePolicy(list, byId(list), input.rulePolicy).kept) + // The counts are taken over the instances below. + rulePolicy = { applied: true, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } } } else rulePolicy = { applied: false, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } } } // The verdict counts the rule findings these steps did not post. When they change it — toward // REQUEST_CHANGES (a confident engine warning toward the ≥3-warning pattern), or away from APPROVE // with nothing else to show — they are listed with why they were withheld, so every verdict is - // explainable from the comment. + // explainable from the comment. The per-step counts (`rulesOff`, `rulesRefuted`, `rulePolicy`) are + // taken here over the instances, the unit the verdict, the summary and this list use; a merged + // comment of three instances counts three. type Withheld = NonNullable[number] const withheldAll: Array<{ f: Finding; reason: Withheld["reason"] }> = [] + let offDropped: Record = {} { let rest = verdictFindings - const offKept = new Set(ruleStep(rest, (list) => offStep(list).kept)) + const offKept = new Set( + ruleStep(rest, (list) => { + const r = offStep(list) + offDropped = r.dropped + return r.kept + }), + ) for (const f of rest) if (!offKept.has(f)) withheldAll.push({ f, reason: "rule_type_off" }) rest = rest.filter((f) => offKept.has(f)) if (aiLaneRan && ruleVerdicts.size) { @@ -2957,9 +2956,13 @@ export async function runReview(input: OrchestrateInput): Promise w.reason === "refuted").length : undefined const withheldIds = new Set(withheldAll.map((w) => w.f)) const idealAll = computeIdealVerdict(verdictFindings, input.rubric) const idealPosted = computeIdealVerdict(verdictFindings.filter((f) => !withheldIds.has(f)), input.rubric) diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index f9839b2baf..8b9ff4d165 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -555,6 +555,17 @@ describe("round 2c: a block on withheld findings is explainable", () => { }) }) +// The same engine warning on three lines of one file: one merged comment, three instances. +const repeatRunner: ReviewRunner = { + ...runner, + async check() { + return { + issues: ["status", "amount", "region"].map((col, i) => ({ rule: "ambiguous-column", severity: "error", category: "correctness", message: `ambiguous column \`${col}\``, line: i + 2 })), + ran: true, + } + }, +} as ReviewRunner + describe("round 4: withheld findings in the comment and the merge", () => { test("a run whose findings were all withheld does not say no issues were found", async () => { const { renderSummary } = await import("../../src/altimate/review/format") @@ -593,4 +604,16 @@ describe("round 4: withheld findings in the comment and the merge", () => { expect(merged.withheld?.map((x) => x.id).sort()).toEqual(a.withheld!.map((x) => x.id).sort()) expect(renderSummary(merged, { maxChars: Infinity })).toContain("### Withheld rule findings that count toward this verdict") }) + + test("the per-step counts are instances, like the withheld list and the verdict", async () => { + const { renderSummary } = await import("../../src/altimate/review/format") + const env = await run({ mode: "gate", runner: repeatRunner, verdictAt: () => "refuted" }) + // Three instances of one merged warning comment, all listed as withheld (they block)... + expect(env.withheld?.filter((x) => x.reason === "refuted")).toHaveLength(3) + // ...and three suggestion findings: six refuted instances, not four comments. + expect(env.findings.filter((f) => f.origin !== "ai")).toHaveLength(0) + expect(env.summary).toMatchObject({ warning: 4, suggestion: 3 }) + expect(env.rulesRefuted).toBe(6) + expect(renderSummary(env, { maxChars: Infinity })).toContain("6 rule finding(s) not posted") + }) }) From 19e742cc9a08976497c89ce88cf10229c7660c0e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:55:22 +0530 Subject: [PATCH 21/32] fix(review): verify a rules-off finding when the finder call for its file failed Rule types off were left out of rule verification on every file the AI lane sends, but rules-off drops them only where the lane answered. On a sent file whose call failed (lane state `ok` with `failedFiles`), such a finding was posted without a verdict. The orchestrator now hands these findings to the lane as `verifyRulesIfUnreviewed`, and the lane verifies them once the finder has answered and only for files in `failedFiles` (`rulesToVerify`). Test (review-rules-off.test.ts): `a rules-off finding on a file the AI lane sends is verified if that file's call fails`. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-review.ts | 19 +++++++++++++++++-- .../src/altimate/review/orchestrate.ts | 18 +++++++++++++----- .../test/altimate/review-rules-off.test.ts | 15 +++++++++++++++ 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index e9a43cf314..1e11f9e7aa 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -756,6 +756,9 @@ export interface AiReviewInput { conventions?: Convention[] /** The rule findings the review would post, verified after the finder (`verifyRules` switch). */ verifyRulesAfter?: Finding[] + /** Rule findings verified only when the finder's call for their file failed: rule types off on + * sent files, which are posted only then (the orchestrator drops them where the lane answered). */ + verifyRulesIfUnreviewed?: Finding[] } /** What happened in the advisory lane, reported on the envelope and in the comment. */ @@ -1015,8 +1018,20 @@ export async function runAiReview(input: AiReviewInput): Promise const res = await runFinderLane(input) // The rule verifier over the rule findings the review would post, after the finder and its verifier; // only when the finder answered, since the orchestrator applies rule noise only then (fail-open). - if (!input.verifyRulesAfter || res.status.state !== "ok") return res - return withRuleVerdicts(res, await runRuleVerify(input, input.verifyRulesAfter)) + if (res.status.state !== "ok") return res + const rules = rulesToVerify(input, res.status) + if (!input.verifyRulesAfter && !rules.length) return res + return withRuleVerdicts(res, await runRuleVerify(input, rules)) +} + +/** The rule findings to verify once the finder answered: those the review would post, plus the + * conditional ones (`verifyRulesIfUnreviewed`) on files whose finder call failed. */ +export function rulesToVerify( + input: Pick, + status: Pick, +): Finding[] { + const failed = new Set(status.failedFiles ?? []) + return [...(input.verifyRulesAfter ?? []), ...(input.verifyRulesIfUnreviewed ?? []).filter((f) => failed.has(f.file))] } /** The finder lane's result with the rule run's verdicts (`verifier.ruleVerdicts`, `verifier.batches`) and its diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 57f096d93f..1718c27042 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2823,18 +2823,25 @@ export async function runReview(input: OrchestrateInput): Promise { const posted = cleanFindings(preAiValidated.list).filter( - (f) => SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && findingOrigin(f) !== "ai", + (f) => + SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && + findingOrigin(f) !== "ai" && + f.severity !== "critical" && + !mayHoldCredentials(f.file), ) const offKept = new Set(dropRulesOff(posted.filter((f) => sentSet.has(f.file)), input.rulesOff).kept) - return posted.filter((f) => (!sentSet.has(f.file) || offKept.has(f)) && f.severity !== "critical" && !mayHoldCredentials(f.file)) + const offOnSent = (f: Finding) => sentSet.has(f.file) && !offKept.has(f) + return { after: posted.filter((f) => !offOnSent(f)), ifUnreviewed: posted.filter(offOnSent) } })() : undefined + const verifyRulesAfter = ruleCandidates?.after try { const res = await input.aiReview({ files: aiFiles, @@ -2850,6 +2857,7 @@ export async function runReview(input: OrchestrateInput): Promise { expect((seen[0].verifyRulesAfter ?? []).some((f) => f.file === "config/extra.yml")).toBe(true) }) + test("a rules-off finding on a file the AI lane sends is verified if that file's call fails", async () => { + const base = await run([model], undefined) + const rule = base.findings.find((f) => f.file === "models/marts/m.sql" && f.severity !== "critical")! + const seen: AiReviewInput[] = [] + await run([model], new Set([rule.rule!]), seen) + expect(seen[0].files.map((f) => f.path)).toContain("models/marts/m.sql") + expect((seen[0].verifyRulesAfter ?? []).some((f) => f.rule === rule.rule)).toBe(false) + expect((seen[0].verifyRulesIfUnreviewed ?? []).some((f) => f.rule === rule.rule)).toBe(true) + // The lane verifies it only when the finder's call for its file failed. + const { rulesToVerify } = await import("../../src/altimate/review/ai-review") + const cond = seen[0].verifyRulesIfUnreviewed! + expect(rulesToVerify(seen[0], {})).toEqual(seen[0].verifyRulesAfter ?? []) + expect(rulesToVerify(seen[0], { failedFiles: ["models/marts/m.sql"] })).toEqual([...(seen[0].verifyRulesAfter ?? []), ...cond]) + }) + test("nothing posted but the verdict is COMMENT: the withheld findings are listed", async () => { const { renderSummary } = await import("../../src/altimate/review/format") const base = await run([model], undefined) From 5f86bd02414b11dcdde5bf0bdaf48b41a5f49720 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:57:15 +0530 Subject: [PATCH 22/32] test(review): the rule-verifier tests clear an exported `ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS` The 40-finding ceiling test calls `runRuleVerify` without `deps.env`, so it read the override from `process.env`; with it exported (say `=8`) the test failed. The variable is now in `ENV_KEYS`, cleared before and restored after each test. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/test/altimate/review-ai-verify-rules.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts index fe45f29202..e99e880899 100644 --- a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts @@ -93,6 +93,8 @@ const ENV_KEYS = [ "ALTIMATE_REVIEW_RULES_OFF", "ALTIMATE_REVIEW_RULE_POLICY", "ALTIMATE_REVIEW_AI_TEST_GAP", + // The 40-finding ceiling test reads it from process.env. + "ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS", ] let saved: Record = {} beforeEach(() => { From f2ef89ec11ad5491923c679591955b92b95b782d Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:57:15 +0530 Subject: [PATCH 23/32] fix(review): a rule answer without a valid verdict is no verdict; a refutation without evidence is unverifiable `parseVerifierOutput` supplies `unverifiable` when an answer names no valid verdict, and `ruleStatus` passed that on as a real verdict, so the rule-post policy withheld a warning that was never judged. It also passed on a `refuted` with no evidence, which `triage` refuses for finder findings. The parser now marks a supplied verdict (`verdictMissing`), `ruleStatus` records such an answer as no verdict (posted), and turns an evidence-less refutation into `unverifiable`. On the release run's 35 refuted rule verdicts none had empty evidence, so the measured behaviour is unchanged. Test (review-ai-verify-rules.test.ts): `an answer without a valid verdict is no verdict; a refutation without evidence is unverifiable`. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-verify.ts | 10 +++++++- .../altimate/review-ai-verify-rules.test.ts | 25 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/ai-verify.ts b/packages/opencode/src/altimate/review/ai-verify.ts index 3ecc65d58a..9cbd4b0883 100644 --- a/packages/opencode/src/altimate/review/ai-verify.ts +++ b/packages/opencode/src/altimate/review/ai-verify.ts @@ -285,6 +285,8 @@ export interface ModelFeatures { /** At most 240 characters citing a tool result or a quoted line. */ evidence: string toolsUsed: string[] + /** The answer named no valid verdict, so the parser supplied `unverifiable`. */ + verdictMissing?: true } const CLAIM_TYPES: ModelFeatures["claimType"][] = [ @@ -377,6 +379,9 @@ export function parseVerifierOutput(text: string, ids: Set): Map t.slice(0, 40)), + ...(typeof r.verdict === "string" && (VERDICTS as string[]).includes(r.verdict.trim().toLowerCase()) + ? {} + : { verdictMissing: true as const }), }) } return out @@ -724,7 +729,10 @@ function ruleStatus( const batchOf = new Map() batches.forEach((b, k) => b.idx.forEach((i) => batchOf.set(i, k))) const ruleVerdicts: RuleVerdict[] = findings.map((f, i) => { - const m = model[i] + // An answer without a valid verdict is no verdict, and a refutation without evidence is no + // verification (as in `triage`): it counts as unverifiable. + const raw = model[i]?.verdictMissing ? undefined : model[i] + const m = raw?.verdict === "refuted" && !raw.evidence.trim() ? { ...raw, verdict: "unverifiable" as const } : raw return { id: f.id, file: f.file, diff --git a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts index e99e880899..f0395eb414 100644 --- a/packages/opencode/test/altimate/review-ai-verify-rules.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify-rules.test.ts @@ -599,3 +599,28 @@ describe("round 2b: critical rule findings", () => { expect(llm).not.toHaveBeenCalled() }) }) + +describe("round 4: what counts as a rule verdict; which findings go first under the ceiling", () => { + test("an answer without a valid verdict is no verdict; a refutation without evidence is unverifiable", async () => { + const rules = [ruleFinding(1), ruleFinding(2), ruleFinding(3), ruleFinding(4)] + const { llm } = scripted(() => ({ + text: JSON.stringify([ + { id: "c1", evidence: "line 11" }, + verdict("c2", { verdict: "refuted", evidence: "" }), + verdict("c3", { verdict: "maybe" }), + verdict("c4", { verdict: "refuted", evidence: "line 11 has no division" }), + ]), + })) + const res = await runAiVerify( + { findings: rules, grounding: [], evidence: evidence(), model: FAKE_MODEL, rulesOnly: true }, + { llm, env: {} }, + ) + expect(res.status.ruleVerdicts!.map((v) => [v.verdict, v.noVerdict])).toEqual([ + [null, true], + ["unverifiable", false], + [null, true], + ["refuted", false], + ]) + expect(res.status).toMatchObject({ reviewed: 2, unreviewed: 2 }) + }) +}) From aa1c6ff4d5fbb14556de8bc61c8932a44e42c748 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:57:15 +0530 Subject: [PATCH 24/32] fix(review): the configured noisy rule types go first under the rule-verifier ceiling `runRuleVerify` ordered the findings under the 40-finding ceiling by the default noisy list, so types added under `ai.rulePolicy.noisyRules` could fall past the ceiling, get no verdict and be posted, bypassing the configured policy. The orchestrator now passes the policy's noisy types to the lane (`noisyRules`), and the ordering uses them. Tests: `the configured noisy types (`ai.rulePolicy.noisyRules`) go first under the ceiling` (review-ai-verify-rules.test.ts), `the orchestrator passes `ai.rulePolicy.noisyRules` to the rule verifier` (review-rule-post-policy.test.ts). Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/ai-review.ts | 3 +++ .../opencode/src/altimate/review/ai-verify-rules.ts | 4 ++-- packages/opencode/src/altimate/review/orchestrate.ts | 1 + .../test/altimate/review-ai-verify-rules.test.ts | 12 ++++++++++++ .../test/altimate/review-rule-post-policy.test.ts | 8 ++++++++ 5 files changed, 26 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 1e11f9e7aa..2001e02cb2 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -759,6 +759,9 @@ export interface AiReviewInput { /** Rule findings verified only when the finder's call for their file failed: rule types off on * sent files, which are posted only then (the orchestrator drops them where the lane answered). */ verifyRulesIfUnreviewed?: Finding[] + /** The rule-post policy's noisy types (`ai.rulePolicy.noisyRules`, else the default list): verified + * first under the per-PR ceiling, since their posting depends on a verdict. */ + noisyRules?: readonly string[] } /** What happened in the advisory lane, reported on the envelope and in the comment. */ diff --git a/packages/opencode/src/altimate/review/ai-verify-rules.ts b/packages/opencode/src/altimate/review/ai-verify-rules.ts index 59aa4ca9b7..9b6ce928ef 100644 --- a/packages/opencode/src/altimate/review/ai-verify-rules.ts +++ b/packages/opencode/src/altimate/review/ai-verify-rules.ts @@ -64,9 +64,9 @@ export async function runRuleVerify( const max = Number(env.ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS) const cap = Number.isInteger(max) && max > 0 ? max : RULE_VERIFY_MAX_FINDINGS // Critical findings are never dropped, so they are not verified. Warnings first, since the policy - // acts on them, and within a severity the default noisy types, whose posting depends on a verdict. + // acts on them, and within a severity the policy's noisy types, whose posting depends on a verdict. const order = { critical: 2, warning: 1, suggestion: 0 } as const - const noisy = new Set(NOISY_RULE_TYPES.map(normalizeRuleId)) + const noisy = new Set((input.noisyRules ?? NOISY_RULE_TYPES).map(normalizeRuleId)) const isNoisy = (f: Finding) => (f.rule && noisy.has(normalizeRuleId(f.rule)) ? 1 : 0) const sent = [...candidates].sort((a, b) => order[b.severity] - order[a.severity] || isNoisy(b) - isNoisy(a)).slice(0, cap) log.info("verifying rule findings", { findings: sent.length, total: rules.length }) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 1718c27042..b2306db96d 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2858,6 +2858,7 @@ export async function runReview(input: OrchestrateInput): Promise { + scriptModels([], /x/) + const custom = { ...ruleFinding(9), rule: ruleId("dbt-patterns", "custom-noisy") } + const rules = [ruleFinding(1), ruleFinding(2), custom] + const env = { ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS: "1" } + const input = { files: [FILE], grounding: [], evidence: evidence() } + const byDefault = await runRuleVerify(input, rules, { env }) + expect(byDefault.status.verifier?.ruleVerdicts?.map((v) => v.id)).toEqual([rules[0].id]) + const configured = await runRuleVerify({ ...input, noisyRules: ["dbt_patterns:custom_noisy"] }, rules, { env }) + expect(configured.status.verifier?.ruleVerdicts?.map((v) => v.id)).toEqual([custom.id]) + }) }) diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index 8b9ff4d165..c8cf7cf91d 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -617,3 +617,11 @@ describe("round 4: withheld findings in the comment and the merge", () => { expect(renderSummary(env, { maxChars: Infinity })).toContain("6 rule finding(s) not posted") }) }) + +describe("round 4: the lane gets the policy's noisy types", () => { + test("the orchestrator passes `ai.rulePolicy.noisyRules` to the rule verifier", async () => { + const seen: AiReviewInput[] = [] + await run({}, seen) + expect(seen[0].noisyRules).toEqual(DEFAULT_RULE_POST_POLICY.noisyRules) + }) +}) From bc78b4e885570083edbc03ea3b2fb5f89728931d Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:57:40 +0530 Subject: [PATCH 25/32] fix(review): docs say the rule-verifier ceiling is per project, what `verifyRules: false` does, and that the withheld list is capped - The 40-finding ceiling is per reviewed dbt project: `--all-projects` verifies each project on its own. - `ai.verifyRules: false` / `=off` turns the refuted step off; the old parenthetical read as if it dropped findings. - Rule types off are verified on a sent file whose finder call failed. - The per-step counts are per instance, and the summary lists the first 10 withheld findings. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 7c056d4b8a..4d4b7bfe9b 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -687,12 +687,15 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne or `dbt-patterns:self-join`). With the verifier on (`ai.verify`), the rule findings that would be posted are verified too (critical ones are never dropped, so they are not sent; rule types off are sent too on files the AI lane - does not review, where they are posted), up to 40 per PR, warnings and the noisy + does not send, and on a sent file whose finder call failed, since they are posted + there), up to 40 per reviewed dbt project (`--all-projects` verifies each project + on its own), warnings and the noisy types first (`ALTIMATE_REVIEW_AI_VERIFY_RULES_MAX_FINDINGS`); findings over the ceiling are posted unverified. The rule run is a second verifier run with its own token budget; on the default budget most of its batches answer without tools - (forced at the budget), and those verdicts count. Refuted ones are dropped (`ai.verifyRules: false` - or `ALTIMATE_REVIEW_AI_VERIFY_RULES=off`; `ai.verify: false` turns it off too). + (forced at the budget), and those verdicts count. Refuted ones are not posted. + `ai.verifyRules: false` or `ALTIMATE_REVIEW_AI_VERIFY_RULES=off` turns this step off + (no rule finding is verified or dropped as refuted), and so does `ai.verify: false`. Then a rule finding is not posted when the verifier answered that it could not check it and it is a warning, or when its type is one of 7 noisy types and the verifier did not confirm it (`ai.rulePolicy: false` or @@ -704,8 +707,9 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne run, provider error, timeout), the rule verifier does not run, none of the steps applies and every rule finding is posted as before; when only the rule verifier did not run, the rule types off still apply and every other rule finding is - posted unchanged. The envelope counts what each step dropped (`rulesOff`, - `rulesRefuted`, `rulePolicy`), and the PR comment gives the total per step. + posted unchanged. The envelope counts what each step withheld, per instance as the + verdict counts them (`rulesOff`, `rulesRefuted`, `rulePolicy`), and the PR comment + gives the total per step. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → @@ -716,7 +720,8 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne posted but still counts toward the ≥3 warnings (the summary counts it too), so neither the verifier nor text it reads, such as the PR description, can unblock a gate. When withheld findings change the verdict, the summary lists them (file - and line, title, and why each was not posted) and the envelope records them under + and line, title, and why each was not posted; the first 10, the rest are in the + envelope) and the envelope records them under `withheld`: the engine warnings that count toward a `REQUEST_CHANGES`, or every withheld finding when they alone keep the verdict from `APPROVE`. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than blocking. From 8f9fe757e63591863f2656948e2a5155bfa795c5 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:10:49 +0530 Subject: [PATCH 26/32] fix(review): the `--all-projects` tally counts what each project's verdict counted The merged `summary` was recomputed from the posted findings only, so a merged run that blocked on one project's withheld engine warnings showed a headline with fewer warnings than its verdict counted. The merged tally is now the merged findings plus, per project, what its own tally counts beyond its posted findings (withheld rule findings and repeat-merged instances). A finding both projects carry still counts once. Test (review-rule-post-policy.test.ts): `--all-projects: a project that blocks only through withheld findings keeps them in the merged envelope`, now also checking the tally. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/multi-project.ts | 14 +++++++++++++- .../test/altimate/review-rule-post-policy.test.ts | 8 ++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 170367a1e3..270180000e 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -275,7 +275,7 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri ? classified.reduce((a, b) => (TIER_RANK[b!] > TIER_RANK[a!] ? b : a)) : undefined, findings, - summary: summarize(findings, envs.some((e) => e.summary.degraded)), + summary: mergedSummary(findings, envs), engine: first.engine, manifestHash: shared(envs.map((e) => e.manifestHash)), staleManifest: envs.some((e) => e.staleManifest) ? true : undefined, @@ -309,6 +309,18 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri return signEnvelope(VerdictEnvelope.parse(merged)) } +/** The merged tally: the merged (deduplicated) findings, plus what each project's tally counts + * beyond its own posted findings (withheld rule findings, the instances of repeat-merged comments), + * so the headline counts what the verdict counts. */ +function mergedSummary(findings: VerdictEnvelope["findings"], envs: VerdictEnvelope[]): VerdictEnvelope["summary"] { + const out = summarize(findings, envs.some((e) => e.summary.degraded)) + for (const e of envs) { + const posted = summarize(e.findings, false) + for (const sev of ["critical", "warning", "suggestion"] as const) out[sev] += Math.max(0, e.summary[sev] - posted[sev]) + } + return out +} + /** Rule-noise counts summed over the projects (each present only when some project has it), and * every project's withheld findings: each project lists them only when they change its verdict, * so the merged verdict, the worst of the projects', stays explainable from the comment. */ diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index c8cf7cf91d..33398cae46 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -603,6 +603,14 @@ describe("round 4: withheld findings in the comment and the merge", () => { expect(merged.idealVerdict).toBe("REQUEST_CHANGES") expect(merged.withheld?.map((x) => x.id).sort()).toEqual(a.withheld!.map((x) => x.id).sort()) expect(renderSummary(merged, { maxChars: Infinity })).toContain("### Withheld rule findings that count toward this verdict") + // The merged tally counts what each project's verdict counted, withheld instances included; + // a finding both envelopes carry (same id, here the scripted AI finding) counts once. + const bIds = new Set(b.findings.map((f) => f.id)) + for (const sev of ["critical", "warning", "suggestion"] as const) { + const shared = a.findings.filter((f) => f.severity === sev && bIds.has(f.id)).length + expect(merged.summary[sev]).toBe(a.summary[sev] + b.summary[sev] - shared) + } + expect(merged.summary.warning).toBeGreaterThan(merged.findings.filter((f) => f.severity === "warning").length) }) test("the per-step counts are instances, like the withheld list and the verdict", async () => { From 2f99b51b423214849ccc966166bca7a26f6e7b7c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:10:49 +0530 Subject: [PATCH 27/32] fix(review): list withheld findings only when they change the verdict, not when posted findings already block `withheld[]` listed the blocking withheld findings whenever the verdict was REQUEST_CHANGES, including when the posted findings blocked on their own (a posted critical plus a refuted engine warning). The docs and the PR text say they are listed when they change the verdict. They are now listed only when the posted findings alone would not block. Test (review-rule-post-policy.test.ts): `posted findings already block: the withheld ones did not change the verdict and are not listed`. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/orchestrate.ts | 2 +- .../test/altimate/review-rule-post-policy.test.ts | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index b2306db96d..e4bcdfc766 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2977,7 +2977,7 @@ export async function runReview(input: OrchestrateInput): Promise !withheldIds.has(f)), input.rubric) const blocking = (f: Finding) => f.severity === "warning" && f.confidence !== "unknown" && verdictEligible(f, input.rubric) const listed = - idealAll === "REQUEST_CHANGES" + idealAll === "REQUEST_CHANGES" && idealPosted !== "REQUEST_CHANGES" ? withheldAll.filter((w) => blocking(w.f)) : idealAll !== "APPROVE" && idealPosted === "APPROVE" ? withheldAll diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index 33398cae46..d5144b3c69 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -613,6 +613,14 @@ describe("round 4: withheld findings in the comment and the merge", () => { expect(merged.summary.warning).toBeGreaterThan(merged.findings.filter((f) => f.severity === "warning").length) }) + test("posted findings already block: the withheld ones did not change the verdict and are not listed", async () => { + const env = await run({ mode: "gate", runner: critRunner, verdictAt: () => "refuted" }) + expect(env.verdict).toBe("REQUEST_CHANGES") + expect(env.findings.some((f) => f.severity === "critical")).toBe(true) + expect(env.rulesRefuted).toBeGreaterThan(0) + expect(env.withheld).toBeUndefined() + }) + test("the per-step counts are instances, like the withheld list and the verdict", async () => { const { renderSummary } = await import("../../src/altimate/review/format") const env = await run({ mode: "gate", runner: repeatRunner, verdictAt: () => "refuted" }) From 6beb17627cb391eabedb4b53ce3bb7f5169eda0e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:12:21 +0530 Subject: [PATCH 28/32] fix(review): `--all-projects` keeps only the withheld lists that drive the merged verdict Each project lists withheld findings against its own verdict. `mergeRuleNoise` now keeps no list when a project at the merged verdict reaches it on its posted findings alone (it has no list), and otherwise keeps only the lists of projects at the merged verdict. A project whose withheld findings moved it to COMMENT no longer shows them under a merged REQUEST_CHANGES. `mergedSummary` notes that per-project instance counts are not deduplicated because each changed path is assigned to exactly one project. Docs: the summary lists withheld findings that change the merged verdict. Test: `--all-projects: withheld lists that do not drive the merged verdict are not kept`. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 3 +- .../src/altimate/review/multi-project.ts | 21 ++++++++++---- .../altimate/review-rule-post-policy.test.ts | 28 +++++++++++++++++++ 3 files changed, 46 insertions(+), 6 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 4d4b7bfe9b..84ef6592fd 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -719,7 +719,8 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne engine warning that is refuted, turned off or dropped by the policy is not posted but still counts toward the ≥3 warnings (the summary counts it too), so neither the verifier nor text it reads, such as the PR description, can unblock - a gate. When withheld findings change the verdict, the summary lists them (file + a gate. When withheld findings change the verdict (with `--all-projects`, the + merged verdict), the summary lists them (file and line, title, and why each was not posted; the first 10, the rest are in the envelope) and the envelope records them under `withheld`: the engine warnings that count toward a `REQUEST_CHANGES`, or every diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 270180000e..1edbb9da31 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -303,7 +303,7 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri })), }, ai: mergeAi(runs), - ...mergeRuleNoise(envs), + ...mergeRuleNoise(envs, idealVerdict), generatedAt: first.generatedAt, } return signEnvelope(VerdictEnvelope.parse(merged)) @@ -314,6 +314,8 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri * so the headline counts what the verdict counts. */ function mergedSummary(findings: VerdictEnvelope["findings"], envs: VerdictEnvelope[]): VerdictEnvelope["summary"] { const out = summarize(findings, envs.some((e) => e.summary.degraded)) + // Not deduplicated across projects like `withheld` is: each changed path is assigned to exactly + // one project (`assignToProjects`), so no instance is counted by two projects. for (const e of envs) { const posted = summarize(e.findings, false) for (const sev of ["critical", "warning", "suggestion"] as const) out[sev] += Math.max(0, e.summary[sev] - posted[sev]) @@ -322,9 +324,14 @@ function mergedSummary(findings: VerdictEnvelope["findings"], envs: VerdictEnvel } /** Rule-noise counts summed over the projects (each present only when some project has it), and - * every project's withheld findings: each project lists them only when they change its verdict, - * so the merged verdict, the worst of the projects', stays explainable from the comment. */ -function mergeRuleNoise(envs: VerdictEnvelope[]): Pick { + * the withheld findings that change the merged verdict (`idealVerdict`, the worst of the + * projects'). Each project lists its withheld findings only when they change its own verdict, so + * a project without a list at the merged verdict blocks (or comments) on its posted findings + * alone: then no list is kept. Otherwise only the lists of projects at the merged verdict are. */ +function mergeRuleNoise( + envs: VerdictEnvelope[], + idealVerdict: Verdict, +): Pick { const out: Pick = {} if (envs.some((e) => e.rulesOff)) { const off: Record = {} @@ -341,8 +348,12 @@ function mergeRuleNoise(envs: VerdictEnvelope[]): Pick n + p.dropped.noisy_type_not_confirmed, 0), }, } + const atMerged = envs.filter((e) => e.idealVerdict === idealVerdict) + const postedReach = atMerged.some((e) => !e.withheld?.length) const seen = new Set() - const withheld = envs.flatMap((e) => e.withheld ?? []).filter((w) => !seen.has(w.id) && !!seen.add(w.id)) + const withheld = postedReach + ? [] + : atMerged.flatMap((e) => e.withheld ?? []).filter((w) => !seen.has(w.id) && !!seen.add(w.id)) if (withheld.length) out.withheld = withheld return out } diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index d5144b3c69..10b3c52690 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -613,6 +613,34 @@ describe("round 4: withheld findings in the comment and the merge", () => { expect(merged.summary.warning).toBeGreaterThan(merged.findings.filter((f) => f.severity === "warning").length) }) + test("--all-projects: withheld lists that do not drive the merged verdict are not kept", async () => { + const { mergeProjectEnvelopes } = await import("../../src/altimate/review/multi-project") + const { renderSummary } = await import("../../src/altimate/review/format") + const withheldOnly = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => "refuted" }) + const postedCritical = await run({ mode: "gate", runner: critRunner }) + expect(withheldOnly.withheld?.length).toBeGreaterThan(0) + expect(postedCritical.idealVerdict).toBe("REQUEST_CHANGES") + expect(postedCritical.withheld).toBeUndefined() + // A project whose withheld findings moved it only to COMMENT, next to one blocking on posted findings. + const toComment = { ...withheldOnly, verdict: "COMMENT" as const, idealVerdict: "COMMENT" as const } + // A project at the merged verdict that blocks on its posted findings alone: no list is kept. + for (const other of [toComment, withheldOnly]) { + const merged = mergeProjectEnvelopes([ + { root: "a", paths: ["a/models/marts/m.sql"], env: other }, + { root: "b", paths: ["b/models/marts/m.sql"], env: postedCritical }, + ]) + expect(merged.idealVerdict).toBe("REQUEST_CHANGES") + expect(merged.withheld).toBeUndefined() + expect(renderSummary(merged, { maxChars: Infinity })).not.toContain("### Withheld rule findings") + } + // A withheld-only project below the merged verdict is left out; the one at it is kept. + const merged = mergeProjectEnvelopes([ + { root: "a", paths: ["a/models/marts/m.sql"], env: withheldOnly }, + { root: "c", paths: ["c/models/marts/m.sql"], env: { ...toComment, withheld: [{ ...withheldOnly.withheld![0], id: "below" }] } }, + ]) + expect(merged.withheld?.map((x) => x.id).sort()).toEqual(withheldOnly.withheld!.map((x) => x.id).sort()) + }) + test("posted findings already block: the withheld ones did not change the verdict and are not listed", async () => { const env = await run({ mode: "gate", runner: critRunner, verdictAt: () => "refuted" }) expect(env.verdict).toBe("REQUEST_CHANGES") From 47ff72946134ed19d0b88f469122e3b7f796a521 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:23:12 +0530 Subject: [PATCH 29/32] docs(review): the merged tally comment states which paths reach one project only Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/multi-project.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 1edbb9da31..007e18b83b 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -314,8 +314,9 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri * so the headline counts what the verdict counts. */ function mergedSummary(findings: VerdictEnvelope["findings"], envs: VerdictEnvelope[]): VerdictEnvelope["summary"] { const out = summarize(findings, envs.some((e) => e.summary.degraded)) - // Not deduplicated across projects like `withheld` is: each changed path is assigned to exactly - // one project (`assignToProjects`), so no instance is counted by two projects. + // Not deduplicated across projects like `withheld` is: each in-scope path belongs to exactly one + // project (`assignToProjects`), and files outside every project, though passed to each project, + // are scoped out there and taken by one AI lane only, so no instance is counted by two projects. for (const e of envs) { const posted = summarize(e.findings, false) for (const sev of ["critical", "warning", "suggestion"] as const) out[sev] += Math.max(0, e.summary[sev] - posted[sev]) From 2f781eb0c81c0d6f66d5c72c7c98b9f258f79364 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 20:17:28 +0530 Subject: [PATCH 30/32] fix(review): `--all-projects` picks withheld lists by the applied merged verdict and by posted findings `mergeRuleNoise` compared projects by `idealVerdict` and treated any project without a list as reaching the merged verdict on posted findings. Two cases broke: - A `gate` project blocking only on withheld findings next to a `comment`-mode project with a posted critical (ideal REQUEST_CHANGES, applied COMMENT): the second counted as reaching the merged REQUEST_CHANGES, so the block was shown without the findings behind it. - A project whose only findings are withheld next to one at COMMENT only because a check did not run: the list was dropped while the tally still counted the withheld findings, so the comment read "2 warning" and "No issues found". Projects are now compared by their applied verdict (the one the comment shows), and a project reaches the merged verdict on posted findings only when it has posted findings that give it: none give APPROVE, posted findings next to a list give COMMENT, otherwise its verdict. The merged verdict is unchanged. Test: `review-merge-withheld-matrix.test.ts` builds every two-project combination of mode, posted level, withheld level and an incomplete review (1296) and checks that a verdict resting on withheld findings lists them, that a non-zero tally never sits next to "No issues found", and that a list is shown only under a verdict it raises its project to with no posted findings reaching it. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/multi-project.ts | 20 ++- .../review-merge-withheld-matrix.test.ts | 145 ++++++++++++++++++ 2 files changed, 157 insertions(+), 8 deletions(-) create mode 100644 packages/opencode/test/altimate/review-merge-withheld-matrix.test.ts diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 007e18b83b..7d073fb1f9 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -303,7 +303,7 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri })), }, ai: mergeAi(runs), - ...mergeRuleNoise(envs, idealVerdict), + ...mergeRuleNoise(envs, verdict), generatedAt: first.generatedAt, } return signEnvelope(VerdictEnvelope.parse(merged)) @@ -325,13 +325,14 @@ function mergedSummary(findings: VerdictEnvelope["findings"], envs: VerdictEnvel } /** Rule-noise counts summed over the projects (each present only when some project has it), and - * the withheld findings that change the merged verdict (`idealVerdict`, the worst of the - * projects'). Each project lists its withheld findings only when they change its own verdict, so - * a project without a list at the merged verdict blocks (or comments) on its posted findings - * alone: then no list is kept. Otherwise only the lists of projects at the merged verdict are. */ + * the withheld findings behind the merged verdict (`verdict`, the applied one the comment shows). + * When a project's posted findings alone reach that verdict, no list is kept. Otherwise the lists + * of the projects at that verdict are: their withheld findings raised them to it. A project that + * reaches it only because a check did not run (`reviewIncomplete`) does not drop them, so the + * withheld findings the tally counts are listed whenever nothing is posted. */ function mergeRuleNoise( envs: VerdictEnvelope[], - idealVerdict: Verdict, + verdict: Verdict, ): Pick { const out: Pick = {} if (envs.some((e) => e.rulesOff)) { @@ -349,8 +350,11 @@ function mergeRuleNoise( noisy_type_not_confirmed: policies.reduce((n, p) => n + p.dropped.noisy_type_not_confirmed, 0), }, } - const atMerged = envs.filter((e) => e.idealVerdict === idealVerdict) - const postedReach = atMerged.some((e) => !e.withheld?.length) + // A project's verdict on its posted findings alone: none give APPROVE; with a list (its withheld + // findings changed its verdict, so its posted ones stop below REQUEST_CHANGES) COMMENT; else its verdict. + const postedVerdict = (e: VerdictEnvelope): Verdict => (!e.findings.length ? "APPROVE" : e.withheld?.length ? "COMMENT" : e.verdict) + const atMerged = envs.filter((e) => e.verdict === verdict) + const postedReach = atMerged.some((e) => postedVerdict(e) === verdict) const seen = new Set() const withheld = postedReach ? [] diff --git a/packages/opencode/test/altimate/review-merge-withheld-matrix.test.ts b/packages/opencode/test/altimate/review-merge-withheld-matrix.test.ts new file mode 100644 index 0000000000..1b49638e3b --- /dev/null +++ b/packages/opencode/test/altimate/review-merge-withheld-matrix.test.ts @@ -0,0 +1,145 @@ +import { describe, test, expect } from "bun:test" +import { mergeProjectEnvelopes } from "../../src/altimate/review/multi-project" +import { renderSummary } from "../../src/altimate/review/format" +import { makeFinding, type Finding } from "../../src/altimate/review/finding" +import { + applyMode, + buildEnvelope, + computeIdealVerdict, + verdictEligible, + type ReviewMode, + type Verdict, + type VerdictEnvelope, +} from "../../src/altimate/review/verdict" + +// `--all-projects` withheld lists over every two-project combination of mode, posted findings, +// withheld findings and an incomplete review. Each project's envelope is built the way runReview +// builds it: the verdict counts posted and withheld findings, and the withheld ones are listed only +// when they change the project's own verdict (orchestrate.ts, `listed`). + +type Level = "rc" | "comment" | "none" +interface Spec { + mode: ReviewMode + posted: Level + withheld: Level + incomplete: boolean +} + +const RANK: Record = { APPROVE: 0, COMMENT: 1, REQUEST_CHANGES: 2 } +const worst = (vs: Verdict[]) => vs.reduce((a, b) => (RANK[b] > RANK[a] ? b : a)) + +function engine(file: string, key: string, severity: Finding["severity"]): Finding { + return makeFinding({ + severity, + category: "lineage_breakage", + title: `m: ${key}`, + body: "b", + file, + evidence: { tool: "impact_analysis", result: {} }, + ruleKey: `${file}:${key}`, + }) +} + +function project(root: string, spec: Spec) { + const file = `${root}/models/m.sql` + // A blocking critical reaches REQUEST_CHANGES; a suggestion only COMMENT. + const posted = + spec.posted === "rc" ? [engine(file, "crit", "critical")] : spec.posted === "comment" ? [engine(file, "sugg", "suggestion")] : [] + // Three confident warnings reach REQUEST_CHANGES (the pattern threshold); two only COMMENT. + const n = spec.withheld === "rc" ? 3 : spec.withheld === "comment" ? 2 : 0 + const withheld = Array.from({ length: n }, (_, i) => engine(file, `warn-${i}`, "warning")) + const idealAll = computeIdealVerdict([...posted, ...withheld]) + const idealPosted = computeIdealVerdict(posted) + const blocking = (f: Finding) => f.severity === "warning" && f.confidence !== "unknown" && verdictEligible(f) + const listed = + idealAll === "REQUEST_CHANGES" && idealPosted !== "REQUEST_CHANGES" + ? withheld.filter(blocking) + : idealAll !== "APPROVE" && idealPosted === "APPROVE" + ? withheld + : [] + const env = buildEnvelope({ + findings: posted, + verdictFindings: [...posted, ...withheld], + withheld: listed.map((f) => ({ id: f.id, title: f.title, file: f.file, severity: f.severity, reason: "refuted" as const })), + mode: spec.mode, + tier: "full", + scope: { + notReviewed: [], + ...(spec.incomplete ? { unverified: [{ path: file, reason: "no compiled SQL", kind: "not_compiled" as const, side: "head" as const }] } : {}), + }, + }) + // The verdict on the posted findings alone, with and without the incomplete-review raise. + const postedOnly = applyMode(idealPosted, spec.mode) + const withoutWithheld = applyMode(idealPosted === "APPROVE" && spec.incomplete ? "COMMENT" : idealPosted, spec.mode) + return { root, file, spec, env, postedOnly, withoutWithheld } +} + +const specs: Spec[] = (["gate", "comment"] as const).flatMap((mode) => + (["rc", "comment", "none"] as const).flatMap((posted) => + (["rc", "comment", "none"] as const).flatMap((withheld) => + [true, false].map((incomplete) => ({ mode, posted, withheld, incomplete })), + ), + ), +) + +const label = (s: Spec) => `${s.mode}/posted:${s.posted}/withheld:${s.withheld}${s.incomplete ? "/incomplete" : ""}` + +/** The invariants one merged envelope breaks, as readable strings (empty when it keeps them all). */ +function violations(a: Spec, b: Spec): string[] { + const ps = [project("a", a), project("b", b)] + const merged: VerdictEnvelope = mergeProjectEnvelopes(ps.map((p) => ({ root: p.root, paths: [p.file], env: p.env }))) + const vm = merged.verdict + const listedIds = new Set((merged.withheld ?? []).map((w) => w.id)) + const out: string[] = [] + // (i) A merged verdict that rests on withheld findings (lower without every project's) lists + // them: every list of a project at that verdict is kept. + if (RANK[worst(ps.map((p) => p.withoutWithheld))] < RANK[vm]) + for (const p of ps) + if (p.env.verdict === vm) + for (const w of p.env.withheld ?? []) if (!listedIds.has(w.id)) out.push(`(i) ${p.root}'s ${w.id} not listed under ${vm}`) + // (ii) The comment never shows a non-zero tally next to "No issues found". + const tally = merged.summary.critical + merged.summary.warning + merged.summary.suggestion + if (tally > 0 && renderSummary(merged, { maxChars: Infinity }).includes("No issues found")) + out.push(`(ii) tally ${tally} with "No issues found"`) + // (iii) A list is shown only under a verdict it drives: its project is at the merged verdict, + // its withheld findings raised it there, and no project's posted findings reach it on their own. + const postedReach = ps.some((p) => p.postedOnly === vm) + for (const p of ps) { + const shown = (p.env.withheld ?? []).filter((w) => listedIds.has(w.id)) + if (!shown.length) continue + if (p.env.verdict !== vm) out.push(`(iii) ${p.root}'s list (at ${p.env.verdict}) shown under ${vm}`) + else if (RANK[p.postedOnly] >= RANK[p.env.verdict]) out.push(`(iii) ${p.root}'s list does not raise its verdict`) + else if (postedReach) out.push(`(iii) ${p.root}'s list shown though posted findings reach ${vm}`) + } + return out +} + +describe("--all-projects: withheld lists over every two-project combination", () => { + test("the listed withheld findings explain the merged verdict and the tally, and only lists that drive it are shown", () => { + const failures: string[] = [] + for (const a of specs) + for (const b of specs) for (const v of violations(a, b)) failures.push(`a=${label(a)} b=${label(b)}: ${v}`) + expect(specs.length).toBe(36) + expect(failures).toEqual([]) + }) + + test("a gate project blocking on withheld findings keeps its list next to a comment-mode posted critical", () => { + const a = project("a", { mode: "gate", posted: "none", withheld: "rc", incomplete: false }) + const b = project("b", { mode: "comment", posted: "rc", withheld: "none", incomplete: false }) + const merged = mergeProjectEnvelopes([a, b].map((p) => ({ root: p.root, paths: [p.file], env: p.env }))) + expect(merged.verdict).toBe("REQUEST_CHANGES") + expect(merged.withheld?.map((w) => w.id).sort()).toEqual(a.env.withheld!.map((w) => w.id).sort()) + }) + + test("withheld-only warnings next to a project at COMMENT only because a check did not run are listed", () => { + const a = project("a", { mode: "gate", posted: "none", withheld: "comment", incomplete: false }) + const b = project("b", { mode: "gate", posted: "none", withheld: "none", incomplete: true }) + const merged = mergeProjectEnvelopes([a, b].map((p) => ({ root: p.root, paths: [p.file], env: p.env }))) + expect(merged.verdict).toBe("COMMENT") + expect(merged.summary.warning).toBe(2) + expect(merged.withheld).toHaveLength(2) + const body = renderSummary(merged, { maxChars: Infinity }) + expect(body).toContain("### Withheld rule findings") + expect(body).not.toContain("No issues found") + }) +}) From cad25bcb4498b886ae1ecce263716132f840def3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 20:33:03 +0530 Subject: [PATCH 31/32] fix(review): `--all-projects` shows each project's own withheld list at the merged verdict The previous change dropped every list when some project's posted findings reached the merged verdict. In the default `comment` mode, a project posting 4 suggestions and withholding 3 warnings (ideal REQUEST_CHANGES, applied COMMENT) next to a clean project then showed "3 warning, 4 suggestion" in the headline but never the 3 warnings, which its own review lists. `mergeRuleNoise` now keeps the lists of exactly the projects whose applied verdict equals the merged applied verdict, each as its own comment shows it. A project below the merged verdict still has its list left out, and `mergedSummary` now leaves its listed withheld findings out of the tally too, so the merged comment never counts a finding it hides that the project's own comment would list. The merged verdict is unchanged. Tests: the matrix adds invariant (iv) (every counted finding is posted or listed, apart from what a project's own comment counts without listing) and checks that each shown list is the project's own; `comment mode: posted suggestions and withheld warnings next to a clean project keep the list`. The round-4 merge test now expects a project at the merged verdict to keep its list next to a posted critical, and a project below it to be neither listed nor counted. Docs describe the merged rule. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 8 +++-- .../src/altimate/review/multi-project.ts | 32 ++++++++--------- .../review-merge-withheld-matrix.test.ts | 35 +++++++++++++------ .../altimate/review-rule-post-policy.test.ts | 25 +++++++------ 4 files changed, 59 insertions(+), 41 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 84ef6592fd..0b5a83960b 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -719,12 +719,14 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne engine warning that is refuted, turned off or dropped by the policy is not posted but still counts toward the ≥3 warnings (the summary counts it too), so neither the verifier nor text it reads, such as the PR description, can unblock - a gate. When withheld findings change the verdict (with `--all-projects`, the - merged verdict), the summary lists them (file + a gate. When withheld findings change a project's verdict, the summary lists them (file and line, title, and why each was not posted; the first 10, the rest are in the envelope) and the envelope records them under `withheld`: the engine warnings that count toward a `REQUEST_CHANGES`, or every - withheld finding when they alone keep the verdict from `APPROVE`. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than + withheld finding when they alone keep the verdict from `APPROVE`. With + `--all-projects`, the merged summary shows the lists of the projects whose verdict + equals the merged one; a project below it has its withheld findings neither + listed nor counted. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than blocking. 5. **Signed envelope.** The verdict is HMAC-signed (`ALTIMATE_REVIEW_SIGNING_KEY`) and includes the manifest hash, so it is replayable and tamper-evident. diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 7d073fb1f9..81fecf43d8 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -275,7 +275,7 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri ? classified.reduce((a, b) => (TIER_RANK[b!] > TIER_RANK[a!] ? b : a)) : undefined, findings, - summary: mergedSummary(findings, envs), + summary: mergedSummary(findings, envs, verdict), engine: first.engine, manifestHash: shared(envs.map((e) => e.manifestHash)), staleManifest: envs.some((e) => e.staleManifest) ? true : undefined, @@ -311,25 +311,27 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri /** The merged tally: the merged (deduplicated) findings, plus what each project's tally counts * beyond its own posted findings (withheld rule findings, the instances of repeat-merged comments), - * so the headline counts what the verdict counts. */ -function mergedSummary(findings: VerdictEnvelope["findings"], envs: VerdictEnvelope[]): VerdictEnvelope["summary"] { + * so the headline counts what the verdict counts. The withheld list of a project below the merged + * `verdict` is left out (mergeRuleNoise), and so are its findings from the tally: the merged + * comment never counts a finding it hides that the project's own comment would list. */ +function mergedSummary(findings: VerdictEnvelope["findings"], envs: VerdictEnvelope[], verdict: Verdict): VerdictEnvelope["summary"] { const out = summarize(findings, envs.some((e) => e.summary.degraded)) // Not deduplicated across projects like `withheld` is: each in-scope path belongs to exactly one // project (`assignToProjects`), and files outside every project, though passed to each project, // are scoped out there and taken by one AI lane only, so no instance is counted by two projects. for (const e of envs) { const posted = summarize(e.findings, false) - for (const sev of ["critical", "warning", "suggestion"] as const) out[sev] += Math.max(0, e.summary[sev] - posted[sev]) + const unlisted = e.verdict === verdict ? [] : (e.withheld ?? []) + for (const sev of ["critical", "warning", "suggestion"] as const) + out[sev] += Math.max(0, e.summary[sev] - posted[sev] - unlisted.filter((w) => w.severity === sev).length) } return out } /** Rule-noise counts summed over the projects (each present only when some project has it), and - * the withheld findings behind the merged verdict (`verdict`, the applied one the comment shows). - * When a project's posted findings alone reach that verdict, no list is kept. Otherwise the lists - * of the projects at that verdict are: their withheld findings raised them to it. A project that - * reaches it only because a check did not run (`reviewIncomplete`) does not drop them, so the - * withheld findings the tally counts are listed whenever nothing is posted. */ + * the withheld lists of the projects at the merged `verdict` (the applied one the comment shows), + * each as that project's own comment shows it. A list of a project below the merged verdict did + * not raise it there: it is left out, and so are its findings from the tally (mergedSummary). */ function mergeRuleNoise( envs: VerdictEnvelope[], verdict: Verdict, @@ -350,15 +352,11 @@ function mergeRuleNoise( noisy_type_not_confirmed: policies.reduce((n, p) => n + p.dropped.noisy_type_not_confirmed, 0), }, } - // A project's verdict on its posted findings alone: none give APPROVE; with a list (its withheld - // findings changed its verdict, so its posted ones stop below REQUEST_CHANGES) COMMENT; else its verdict. - const postedVerdict = (e: VerdictEnvelope): Verdict => (!e.findings.length ? "APPROVE" : e.withheld?.length ? "COMMENT" : e.verdict) - const atMerged = envs.filter((e) => e.verdict === verdict) - const postedReach = atMerged.some((e) => postedVerdict(e) === verdict) const seen = new Set() - const withheld = postedReach - ? [] - : atMerged.flatMap((e) => e.withheld ?? []).filter((w) => !seen.has(w.id) && !!seen.add(w.id)) + const withheld = envs + .filter((e) => e.verdict === verdict) + .flatMap((e) => e.withheld ?? []) + .filter((w) => !seen.has(w.id) && !!seen.add(w.id)) if (withheld.length) out.withheld = withheld return out } diff --git a/packages/opencode/test/altimate/review-merge-withheld-matrix.test.ts b/packages/opencode/test/altimate/review-merge-withheld-matrix.test.ts index 1b49638e3b..eedbdc9d51 100644 --- a/packages/opencode/test/altimate/review-merge-withheld-matrix.test.ts +++ b/packages/opencode/test/altimate/review-merge-withheld-matrix.test.ts @@ -69,9 +69,8 @@ function project(root: string, spec: Spec) { }, }) // The verdict on the posted findings alone, with and without the incomplete-review raise. - const postedOnly = applyMode(idealPosted, spec.mode) const withoutWithheld = applyMode(idealPosted === "APPROVE" && spec.incomplete ? "COMMENT" : idealPosted, spec.mode) - return { root, file, spec, env, postedOnly, withoutWithheld } + return { root, file, spec, env, withoutWithheld } } const specs: Spec[] = (["gate", "comment"] as const).flatMap((mode) => @@ -101,21 +100,26 @@ function violations(a: Spec, b: Spec): string[] { const tally = merged.summary.critical + merged.summary.warning + merged.summary.suggestion if (tally > 0 && renderSummary(merged, { maxChars: Infinity }).includes("No issues found")) out.push(`(ii) tally ${tally} with "No issues found"`) - // (iii) A list is shown only under a verdict it drives: its project is at the merged verdict, - // its withheld findings raised it there, and no project's posted findings reach it on their own. - const postedReach = ps.some((p) => p.postedOnly === vm) + // (iii) Lists are those of the projects at the merged verdict, each as its own comment shows it; + // a list of a project below the merged verdict is not shown under it. for (const p of ps) { - const shown = (p.env.withheld ?? []).filter((w) => listedIds.has(w.id)) - if (!shown.length) continue - if (p.env.verdict !== vm) out.push(`(iii) ${p.root}'s list (at ${p.env.verdict}) shown under ${vm}`) - else if (RANK[p.postedOnly] >= RANK[p.env.verdict]) out.push(`(iii) ${p.root}'s list does not raise its verdict`) - else if (postedReach) out.push(`(iii) ${p.root}'s list shown though posted findings reach ${vm}`) + const own = p.env.withheld ?? [] + const shown = own.filter((w) => listedIds.has(w.id)) + if (p.env.verdict !== vm && shown.length) out.push(`(iii) ${p.root}'s list (at ${p.env.verdict}) shown under ${vm}`) + if (p.env.verdict === vm && shown.length !== own.length) out.push(`(iii) ${p.root}'s own list not shown under ${vm}`) } + // (iv) Every finding the merged tally counts is posted or listed, apart from the withheld findings + // a project's own comment counts without listing: merging hides no counted finding. + const count = (t: VerdictEnvelope["summary"]) => t.critical + t.warning + t.suggestion + const hidden = (e: VerdictEnvelope, listed: number) => count(e.summary) - e.findings.length - listed + const ownHidden = ps.reduce((n, p) => n + hidden(p.env, p.env.withheld?.length ?? 0), 0) + if (hidden(merged, listedIds.size) !== ownHidden) + out.push(`(iv) ${hidden(merged, listedIds.size)} counted findings neither posted nor listed (the projects' own comments: ${ownHidden})`) return out } describe("--all-projects: withheld lists over every two-project combination", () => { - test("the listed withheld findings explain the merged verdict and the tally, and only lists that drive it are shown", () => { + test("the listed withheld findings explain the merged verdict and the tally; lists below the merged verdict are not shown", () => { const failures: string[] = [] for (const a of specs) for (const b of specs) for (const v of violations(a, b)) failures.push(`a=${label(a)} b=${label(b)}: ${v}`) @@ -131,6 +135,15 @@ describe("--all-projects: withheld lists over every two-project combination", () expect(merged.withheld?.map((w) => w.id).sort()).toEqual(a.env.withheld!.map((w) => w.id).sort()) }) + test("comment mode: posted suggestions and withheld warnings next to a clean project keep the list", () => { + const a = project("a", { mode: "comment", posted: "comment", withheld: "rc", incomplete: false }) + const b = project("b", { mode: "comment", posted: "none", withheld: "none", incomplete: false }) + const merged = mergeProjectEnvelopes([a, b].map((p) => ({ root: p.root, paths: [p.file], env: p.env }))) + expect(merged.verdict).toBe("COMMENT") + expect(merged.summary.warning).toBe(3) + expect(merged.withheld?.map((w) => w.id).sort()).toEqual(a.env.withheld!.map((w) => w.id).sort()) + }) + test("withheld-only warnings next to a project at COMMENT only because a check did not run are listed", () => { const a = project("a", { mode: "gate", posted: "none", withheld: "comment", incomplete: false }) const b = project("b", { mode: "gate", posted: "none", withheld: "none", incomplete: true }) diff --git a/packages/opencode/test/altimate/review-rule-post-policy.test.ts b/packages/opencode/test/altimate/review-rule-post-policy.test.ts index 10b3c52690..a4e39c8b0a 100644 --- a/packages/opencode/test/altimate/review-rule-post-policy.test.ts +++ b/packages/opencode/test/altimate/review-rule-post-policy.test.ts @@ -613,7 +613,7 @@ describe("round 4: withheld findings in the comment and the merge", () => { expect(merged.summary.warning).toBeGreaterThan(merged.findings.filter((f) => f.severity === "warning").length) }) - test("--all-projects: withheld lists that do not drive the merged verdict are not kept", async () => { + test("--all-projects: withheld lists of projects below the merged verdict are not kept, nor counted", async () => { const { mergeProjectEnvelopes } = await import("../../src/altimate/review/multi-project") const { renderSummary } = await import("../../src/altimate/review/format") const withheldOnly = await run({ mode: "gate", runner: threeWarnRunner, verdictAt: () => "refuted" }) @@ -621,18 +621,23 @@ describe("round 4: withheld findings in the comment and the merge", () => { expect(withheldOnly.withheld?.length).toBeGreaterThan(0) expect(postedCritical.idealVerdict).toBe("REQUEST_CHANGES") expect(postedCritical.withheld).toBeUndefined() - // A project whose withheld findings moved it only to COMMENT, next to one blocking on posted findings. - const toComment = { ...withheldOnly, verdict: "COMMENT" as const, idealVerdict: "COMMENT" as const } - // A project at the merged verdict that blocks on its posted findings alone: no list is kept. - for (const other of [toComment, withheldOnly]) { - const merged = mergeProjectEnvelopes([ + const pair = (other: typeof postedCritical) => + mergeProjectEnvelopes([ { root: "a", paths: ["a/models/marts/m.sql"], env: other }, { root: "b", paths: ["b/models/marts/m.sql"], env: postedCritical }, ]) - expect(merged.idealVerdict).toBe("REQUEST_CHANGES") - expect(merged.withheld).toBeUndefined() - expect(renderSummary(merged, { maxChars: Infinity })).not.toContain("### Withheld rule findings") - } + // A project whose withheld findings moved it only to COMMENT, next to one blocking on posted + // findings: its list is left out, and its withheld findings are not counted. + const toComment = { ...withheldOnly, verdict: "COMMENT" as const, idealVerdict: "COMMENT" as const } + const below = pair(toComment) + expect(below.verdict).toBe("REQUEST_CHANGES") + expect(below.withheld).toBeUndefined() + expect(renderSummary(below, { maxChars: Infinity })).not.toContain("### Withheld rule findings") + // The same posted findings at the merged verdict: only the withheld ones are counted on top. + expect(pair(withheldOnly).summary.warning).toBe(below.summary.warning + withheldOnly.withheld!.length) + // A project at the merged verdict keeps its list, as its own comment shows it. + const at = pair(withheldOnly) + expect(at.withheld?.map((x) => x.id).sort()).toEqual(withheldOnly.withheld!.map((x) => x.id).sort()) // A withheld-only project below the merged verdict is left out; the one at it is kept. const merged = mergeProjectEnvelopes([ { root: "a", paths: ["a/models/marts/m.sql"], env: withheldOnly }, From b676851df977f00dcfd8bf822cf4a0e6b0214ff3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Sat, 28 Nov 2026 00:46:35 +0530 Subject: [PATCH 32/32] docs(review): a project below the merged verdict has its withheld list left out and not counted The sentence said its withheld findings are neither listed nor counted. Only the findings on its list are left out of the merged tally; withheld findings a project's own summary counts without listing are still counted. Co-Authored-By: Claude --- docs/docs/usage/dbt-pr-review.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 0b5a83960b..a50addfc7a 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -725,8 +725,8 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne `withheld`: the engine warnings that count toward a `REQUEST_CHANGES`, or every withheld finding when they alone keep the verdict from `APPROVE`. With `--all-projects`, the merged summary shows the lists of the projects whose verdict - equals the merged one; a project below it has its withheld findings neither - listed nor counted. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than + equals the merged one; a project below it has its list left out, and the findings + on that list are not counted. In `comment` mode, `REQUEST_CHANGES` is posted as comments rather than blocking. 5. **Signed envelope.** The verdict is HMAC-signed (`ALTIMATE_REVIEW_SIGNING_KEY`) and includes the manifest hash, so it is replayable and tamper-evident.