From 6bff4b2462f346f2b2ad17abdaa02458bfedc47c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 12 Nov 2026 16:24:21 +0530 Subject: [PATCH 01/23] fix(review): an honest PR comment: real lint-only banner, AI lane status, PR intent, `project_dir` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Lint-only now means no changed model resolved against a manifest; an undecidable finding no longer flips the whole run. Undecidable findings, unverified models, out-of-scope files and AI-lane problems each get their own line in the summary. - The advisory AI lane reports `ok | skipped | timeout | error` with a reason, model and duration on the signed envelope (`ai`) and in the comment; it never fails silently. The timeout scales with prompt size (60 s + 1 s per 2K chars, capped at 5 min). `--ai-model provider/model` selects the model explicitly. - The CLI passes the PR title and description to the intent check (GitHub `pull_request` event, GitLab `CI_MERGE_REQUEST_TITLE`/`_DESCRIPTION`). - The action gains `project_dir` (→ `--cwd`) for monorepos. - Docs: what each input unlocks (fetch depth, manifest, compiled SQL, `target-base/`, `catalog.json`) and how to compile the base. - `review_run` telemetry adds `undecided`, `unverified_models`, `ai_state`, `ai_duration_ms`, `base_source`, `out_of_scope_files`. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 33 ++- github/review/action.yml | 8 +- .../opencode/src/altimate/review/ai-review.ts | 82 ++++++-- .../opencode/src/altimate/review/format.ts | 33 ++- .../src/altimate/review/orchestrate.ts | 31 ++- packages/opencode/src/altimate/review/run.ts | 30 +++ .../opencode/src/altimate/review/telemetry.ts | 6 + .../opencode/src/altimate/review/verdict.ts | 11 + .../opencode/src/altimate/telemetry/index.ts | 16 +- packages/opencode/src/cli/cmd/review.ts | 10 +- .../test/altimate/review-ci-honesty.test.ts | 188 ++++++++++++++++++ 11 files changed, 419 insertions(+), 29 deletions(-) create mode 100644 packages/opencode/test/altimate/review-ci-honesty.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index cd1d9fc297..0952e234fd 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -199,6 +199,34 @@ jobs: # model_api_key: ${{ secrets.ANTHROPIC_API_KEY }} ``` +### What the review needs (and what each input unlocks) + +| Input | How to produce it | Unlocks | +|---|---|---| +| Full git history of the PR's target branch | `actions/checkout` with `fetch-depth: 0` | Correct base: the diff starts at the merge-base with the PR's target branch. A target branch that is not fetched is an error, never a silent fallback to `main`. | +| `target/manifest.json` | `dbt compile` (or `dbt parse` for lint + lineage only) | Blast radius, lineage breakage, tiering. Without it the run is lint-only. | +| `target/compiled/…` | `dbt compile` | Engine checks on the head (lint, grade, PII, grain). | +| `target-base/compiled/…` | Compile the base ref into `target-base/` (below) | Equivalence proofs and column-breakage for modified models. | +| `target/catalog.json` | `dbt docs generate` | Complete warehouse columns for column-lineage breakage. | + +Compiling the base (optional, for equivalence and column-breakage): + +```yaml + - name: Compile the base into target-base/ + run: | + git worktree add ../base "origin/${{ github.base_ref }}" + (cd ../base && dbt deps && dbt compile --target-path "$GITHUB_WORKSPACE/target-base") +``` + +**Monorepos:** set `project_dir` to the folder holding `dbt_project.yml`. Only +changes inside it are reviewed, `manifest_path` is resolved relative to it, and +changes elsewhere are counted in the comment. + +**What the comment tells you it could not check:** findings the engine could not +decide, models without compiled SQL, files outside the project, and whether the +advisory AI lane ran, was skipped, timed out or failed (with the reason). The +same facts are in the envelope (`scope`, `ai`) and the `review_run` telemetry. + ### Model & credentials for the advisory lane The deterministic engine (lineage, equivalence, PII, grade, lint — the only layer @@ -356,8 +384,9 @@ reviewer does **not** re-implement Jinja — it consumes dbt's own compiled outp from `target/compiled//…` (HEAD) and `target-base/compiled/…` (BASE), produced by `dbt compile`. To enable full equivalence verdicts, compile both the base and head refs in CI (the base into `target-base/`, the Recce - convention). Without compiled SQL the engine lanes fall back to raw and stay - *undecidable* (never fabricated) — the `dbt-patterns` lane still runs. + convention). A model without compiled SQL is never sent to the engine as raw + Jinja: it is listed as **not verified** (with the reason) in the comment and in + the envelope's `scope.unverified`, and the `dbt-patterns` lane still runs. ## What it checks — deterministic rule catalog diff --git a/github/review/action.yml b/github/review/action.yml index 8820ed8892..09c4bc1538 100644 --- a/github/review/action.yml +++ b/github/review/action.yml @@ -9,8 +9,12 @@ inputs: description: "comment (never blocks) | gate (blocks the merge on REQUEST_CHANGES)" required: false default: "comment" + project_dir: + description: "Directory of the dbt project (the one holding dbt_project.yml), relative to the repository root. Only changes inside it are reviewed — set it in a monorepo. `manifest_path` is resolved relative to it." + required: false + default: "." manifest_path: - description: "Path to the compiled dbt manifest.json. Run `dbt compile` before this step for the full (non-degraded) verdict." + description: "Path to the compiled dbt manifest.json, relative to `project_dir`. Run `dbt compile` before this step for the full (non-degraded) verdict; `dbt docs generate` (catalog.json) and a base compile into `target-base/` enable column-lineage breakage and equivalence proofs." required: false default: "target/manifest.json" severity_threshold: @@ -170,6 +174,7 @@ runs: # from `${{ }}` would be a shell-injection vector. Build an arg array instead. env: IN_MODE: ${{ inputs.mode }} + IN_PROJECT_DIR: ${{ inputs.project_dir }} IN_MANIFEST: ${{ inputs.manifest_path }} IN_SEVERITY: ${{ inputs.severity_threshold }} IN_BASE: ${{ inputs.base }} @@ -181,6 +186,7 @@ runs: ALTIMATE_REVIEW_SIGNING_KEY: ${{ inputs.signing_key }} run: | args=(--mode "$IN_MODE" --manifest "$IN_MANIFEST" --severity "$IN_SEVERITY") + [[ -n "$IN_PROJECT_DIR" && "$IN_PROJECT_DIR" != "." ]] && args+=(--cwd "$IN_PROJECT_DIR") [[ -n "$IN_BASE" ]] && args+=(--base "$IN_BASE") [[ -n "$IN_HEAD" ]] && args+=(--head "$IN_HEAD") [[ "$IN_POST" == "true" ]] && args+=(--post) diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 2ea19b0bd7..bd59dd54ed 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -11,7 +11,8 @@ import { readStreamText } from "../llm/stream-text" const log = Log.create({ service: "ai-review" }) -const AI_TIMEOUT_MS = 60_000 +const AI_TIMEOUT_BASE_MS = 60_000 +const AI_TIMEOUT_MAX_MS = 300_000 const MAX_DIFF_CHARS = 6_000 // per file, keep the prompt bounded const MAX_FILES = 20 @@ -31,6 +32,39 @@ export interface AiReviewInput { grounding: Finding[] prTitle?: string prBody?: string + /** Explicit `provider/model`; omit to use the configured default model. */ + model?: string +} + +/** What happened in the advisory lane, reported on the envelope and in the comment. */ +export type AiLaneState = "ok" | "skipped" | "timeout" | "error" +export interface AiLaneStatus { + state: AiLaneState + /** Why the lane was skipped or failed (never contains credentials). */ + reason?: string + /** `provider/model` the lane ran with. */ + model?: string + durationMs?: number +} +export interface AiReviewResult { + findings: Finding[] + status: AiLaneStatus +} + +/** Timeout scaled to the prompt: 60 s plus 1 s per 2,000 characters, capped at 5 minutes. */ +export function aiTimeoutMs(promptChars: number): number { + return Math.min(AI_TIMEOUT_MAX_MS, AI_TIMEOUT_BASE_MS + Math.ceil(promptChars / 2_000) * 1_000) +} + +/** Error text safe to show in a PR comment: one line, bounded, with anything + * that looks like a key or bearer token masked. */ +function safeReason(err: unknown): string { + const raw = err instanceof Error ? err.message : String(err) + return raw + .replace(/\s+/g, " ") + .replace(/(bearer\s+)[^\s]+/gi, "$1***") + .replace(/\b(sk|pk|key|token)[-_][A-Za-z0-9_-]{8,}/gi, "***") + .slice(0, 200) } /** @@ -73,23 +107,39 @@ function buildUserMessage(input: AiReviewInput): string { /** * Run the LLM reviewer lane. Returns advisory findings (severity ≤ warning, - * clamped by core), or [] if no model / core is available or the call fails — - * a review must never crash because the AI layer is unavailable. + * clamped by core) and a status saying whether the lane ran, was skipped, timed + * out or failed. Never throws — a review must not crash because the AI layer is + * unavailable — but never fails silently either: the status reaches the + * envelope and the PR comment. */ -export async function runAiReview(input: AiReviewInput): Promise { +export async function runAiReview(input: AiReviewInput): Promise { + const startedAt = Date.now() + const done = (findings: Finding[], status: Omit): AiReviewResult => ({ + findings, + status: { ...status, durationMs: Date.now() - startedAt }, + }) const files = input.files.filter((f) => f.status !== "deleted" && (f.diff || f.sql)) - if (!files.length) return [] + if (!files.length) return done([], { state: "skipped", reason: "no changed model SQL to review" }) + const message = buildUserMessage({ ...input, files }) const controller = new AbortController() - const timeout = setTimeout(() => controller.abort(), AI_TIMEOUT_MS) + const timeoutMs = aiTimeoutMs(message.length) + const timeout = setTimeout(() => controller.abort(), timeoutMs) + let modelLabel: string | undefined try { // Prompt comes from the compiled core, not this file. const promptRes = await Dispatcher.call("altimate_core.review_ai_prompt", {}) const system = ((promptRes.data ?? {}) as Record).prompt as string | undefined - if (!system) return [] - - const defaultModel = await Provider.defaultModel() - const model = await Provider.getModel(defaultModel.providerID, defaultModel.modelID) + if (!system) return done([], { state: "error", reason: "the core reviewer prompt is unavailable" }) + + let model: Awaited> + try { + const chosen = input.model ? Provider.parseModel(input.model) : await Provider.defaultModel() + model = await Provider.getModel(chosen.providerID, chosen.modelID) + } catch (err) { + return done([], { state: "skipped", reason: `no usable model: ${safeReason(err)}`, model: input.model }) + } + modelLabel = `${model.providerID}/${model.id}` const agent: Agent.Info = { name: "dbt-ai-reviewer", @@ -119,10 +169,12 @@ export async function runAiReview(input: AiReviewInput): Promise { abort: controller.signal, sessionID: user.sessionID, retries: 1, - messages: [{ role: "user", content: buildUserMessage({ ...input, files }) }], + messages: [{ role: "user", content: message }], }) const text = await readStreamText(stream) - if (!text) return [] + if (controller.signal.aborted) + return done([], { state: "timeout", reason: `no answer within ${Math.round(timeoutMs / 1000)} s`, model: modelLabel }) + if (!text) return done([], { state: "error", reason: "the model returned no text", model: modelLabel }) // Parse + clamp in core (the prompt-injection-resistant, advisory-only // contract). Returns already-validated, severity-clamped, file-checked items. @@ -165,10 +217,12 @@ export async function runAiReview(input: AiReviewInput): Promise { } } log.info("ai review complete", { findings: out.length }) - return out + return done(out, { state: "ok", model: modelLabel }) } catch (err) { log.error("ai review failed", { error: err }) - return [] + if (controller.signal.aborted) + return done([], { state: "timeout", reason: `no answer within ${Math.round(timeoutMs / 1000)} s`, model: modelLabel }) + return done([], { state: "error", reason: safeReason(err), model: modelLabel }) } finally { clearTimeout(timeout) } diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 0befe5883c..a110068e8b 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -42,11 +42,12 @@ export function renderSummary(env: VerdictEnvelope): string { if (env.summary.degraded) { lines.push( - "> ⚙️ **Lint-only run** — no dbt manifest/warehouse was available, so lineage, equivalence and", + "> ⚙️ **Lint-only run** — no changed model resolved against a dbt manifest, so lineage, equivalence and", "> data-impact checks were skipped. Wire `manifest_path` (and optionally warehouse creds) for the full verdict.", "", ) } + lines.push(...coverageNotes(env)) // G1 (Round 18) — surface classifier reasons when --explain-tier populated // them, so a customer can see why the review ran at this tier. Also surfaces @@ -110,11 +111,41 @@ export function renderSummary(env: VerdictEnvelope): string { `altimate dbt-pr-review · verdict \`${env.verdict}\`` + (env.signature ? ` · signed \`${env.signature.slice(0, 18)}…\`` : "") + (env.manifestHash ? ` · manifest \`${env.manifestHash.slice(0, 10)}\`` : "") + + (env.scope?.baseRef ? ` · base \`${env.scope.baseRef}\`` : "") + + (env.ai?.state === "ok" && env.ai.model ? ` · AI \`${env.ai.model}\`` : "") + "", ) return lines.join("\n") } +/** + * 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 + if (undecided) notes.push(`${undecided} finding(s) could not be decided by the engine and are marked _unverified_.`) + const unverified = env.scope?.unverified ?? [] + if (unverified.length) { + const head = unverified.slice(0, 5).map((u) => `\`${u.path}\``).join(", ") + const more = unverified.length > 5 ? ` and ${unverified.length - 5} more` : "" + notes.push( + `${unverified.length} model(s) not verified by the engine — ${unverified[0].reason}: ${head}${more}. ` + + "Run `dbt compile` (and compile the base into `target-base/`) for equivalence and lineage checks.", + ) + } + if (env.scope?.outOfScopeFiles) + notes.push(`${env.scope.outOfScopeFiles} changed file(s) outside the dbt project were not reviewed.`) + if (env.ai && env.ai.state !== "ok") { + const what = { skipped: "skipped", timeout: "timed out", error: "failed" }[env.ai.state] + notes.push(`Advisory AI review ${what}${env.ai.reason ? `: ${env.ai.reason}` : ""}.`) + } + return notes.length ? [...notes.map((n) => `> ℹ️ ${n}`), ""] : [] +} + /** GitHub `pulls.createReview` inline comments — only findings with a line. */ export interface InlineComment { path: string diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 2c81fcc721..48e979e1ff 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -14,7 +14,7 @@ import { type Rubric, exclusionReason, clampSeverity } from "./rubric" import { type ReviewConfig } from "./config" import { type ReviewMode, type ReviewScope, type VerdictEnvelope, buildEnvelope, signEnvelope } from "./verdict" import { detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" -import { type AiReviewInput } from "./ai-review" +import { type AiLaneStatus, type AiReviewInput, type AiReviewResult } from "./ai-review" /** * The deterministic review recipe. @@ -188,7 +188,11 @@ export interface OrchestrateInput { * tests pass a fake or omit it (the lane is then skipped). Receives the * deterministic findings as grounding and returns ADVISORY findings only. */ - aiReview?: (input: AiReviewInput) => Promise + aiReview?: (input: AiReviewInput) => Promise + /** Why the AI lane is off when `aiReview` is not injected (shown in the comment). */ + aiDisabledReason?: string + /** Explicit `provider/model` for the AI lane. */ + aiModel?: string /** PR metadata passed to the AI reviewer for intent checking. */ prTitle?: string prBody?: string @@ -1410,7 +1414,12 @@ export async function runReview(input: OrchestrateInput): Promise ({ path: ctx.file.path, status: ctx.file.status, @@ -1419,16 +1428,20 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || a.file.localeCompare(b.file)) - const degraded = runDegraded || findings.some((f) => f.degraded) + // Lint-only means no changed model resolved against a manifest. A single + // undecidable finding does not make the whole run lint-only; those findings + // carry their own `degraded` flag and are counted separately in the summary. + const degraded = runDegraded const envelope = buildEnvelope({ + ai: aiStatus, findings, tier, mode: input.mode, diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 275c96ac4a..5295ea8326 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -53,6 +53,8 @@ export interface ReviewPullRequestOptions { /** PR metadata for the AI reviewer's intent check. */ prTitle?: string prBody?: string + /** Explicit `provider/model` for the advisory AI lane. */ + aiModel?: string /** G1 — surface the tier classifier's reasons on the verdict envelope. */ explainTier?: boolean /** G2 — [EXPERIMENTAL] bypass the tier classifier with the supplied tier. @@ -379,6 +381,8 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise // path verdicts (cubic-review PR #1041). cliVersion: opts.cliVersion ?? Installation.VERSION, aiReview: opts.noAi || config.ai === false ? undefined : runAiReview, + aiDisabledReason: opts.noAi ? "disabled by --no-ai" : config.ai === false ? "disabled by `ai: false` in .altimate/review.yml" : undefined, + aiModel: opts.aiModel, prTitle: opts.prTitle, prBody: opts.prBody, explainTier: opts.explainTier, @@ -396,6 +400,32 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise }) } +/** + * The pull/merge request's title and description from the CI environment, so + * the AI lane can check the change against its stated intent. GitHub: the + * `pull_request` object in GITHUB_EVENT_PATH. GitLab: CI_MERGE_REQUEST_TITLE / + * CI_MERGE_REQUEST_DESCRIPTION. Empty outside a PR/MR run. + */ +export async function prContextFromEnv(env: NodeJS.ProcessEnv = process.env): Promise<{ prTitle?: string; prBody?: string }> { + if (env.GITHUB_EVENT_PATH) { + try { + const pr = JSON.parse(await readFile(env.GITHUB_EVENT_PATH, "utf8"))?.pull_request + if (pr) { + return { + prTitle: typeof pr.title === "string" && pr.title ? pr.title : undefined, + prBody: typeof pr.body === "string" && pr.body ? pr.body : undefined, + } + } + } catch { + /* unreadable event file: try GitLab */ + } + } + return { + prTitle: env.CI_MERGE_REQUEST_TITLE || undefined, + prBody: env.CI_MERGE_REQUEST_DESCRIPTION || undefined, + } +} + /** * The dbt project being reviewed: the nearest directory at or above `cwd` * (not above the repo root) holding dbt_project.yml; else the project that diff --git a/packages/opencode/src/altimate/review/telemetry.ts b/packages/opencode/src/altimate/review/telemetry.ts index fc20cc3b17..34016e8a50 100644 --- a/packages/opencode/src/altimate/review/telemetry.ts +++ b/packages/opencode/src/altimate/review/telemetry.ts @@ -110,6 +110,12 @@ export function emitReviewRun(input: { // Optional in the schema and explicitly invalid as `false`, so normalise rather than copy. tier_forced: env.tierForced === true, degraded: env.summary.degraded, + undecided: env.findings.filter((f) => f.degraded).length, + unverified_models: env.scope?.unverified?.length ?? 0, + ai_state: env.ai?.state, + ai_duration_ms: env.ai?.durationMs, + base_source: env.scope?.baseSource, + out_of_scope_files: env.scope?.outOfScopeFiles ?? 0, stale_manifest: env.staleManifest === true, critical: env.summary.critical, warning: env.summary.warning, diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index 25ab3d8904..95064230db 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -144,6 +144,15 @@ export const VerdictEnvelope = z.object({ staleManifest: z.boolean().optional(), /** Base resolution and review coverage (see ReviewScope). */ scope: ReviewScope.optional(), + /** Advisory AI lane outcome: ran, skipped, timed out or failed, and why. */ + ai: z + .object({ + state: z.enum(["ok", "skipped", "timeout", "error"]), + reason: z.string().optional(), + model: z.string().optional(), + durationMs: z.number().int().nonnegative().optional(), + }) + .optional(), /** ISO timestamp; injected by the caller (no clock access in pure code). */ generatedAt: z.string().optional(), /** Optional break-glass override record. */ @@ -203,6 +212,7 @@ export interface BuildEnvelopeInput { /** True when mtime signals the manifest predates a change-affecting file. */ staleManifest?: boolean scope?: ReviewScope + ai?: VerdictEnvelope["ai"] } function summarize(findings: Finding[], degraded: boolean): VerdictEnvelope["summary"] { @@ -232,6 +242,7 @@ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { manifestHash: input.manifestHash, staleManifest: input.staleManifest ? true : undefined, scope: input.scope, + ai: input.ai, generatedAt: input.generatedAt, }) } diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 5df4d68dc3..da119a2728 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -1650,10 +1650,20 @@ export namespace Telemetry { mode?: string tier?: string tier_forced?: boolean - /** The envelope's fidelity flag: no reviewable files, no usable manifest for the changed - * models, OR a surfaced finding whose engine analysis was undecidable. It does NOT mean - * merely "no warehouse". */ + /** The envelope's fidelity flag: no reviewable files, or no changed model resolved against + * a manifest (lint-only). An undecidable finding alone no longer sets it — see + * `undecided`. It does NOT mean merely "no warehouse". */ degraded?: boolean + /** Surfaced findings whose engine analysis was undecidable. */ + undecided?: number + /** Models the engine could not verify (no compiled SQL). */ + unverified_models?: number + /** Advisory AI lane outcome: ok | skipped | timeout | error. */ + ai_state?: string + ai_duration_ms?: number + /** Where the review base came from (flag, github_event, default_branch, …). */ + base_source?: string + out_of_scope_files?: number stale_manifest?: boolean critical?: number warning?: number diff --git a/packages/opencode/src/cli/cmd/review.ts b/packages/opencode/src/cli/cmd/review.ts index 7897396ac5..e35556aa0b 100644 --- a/packages/opencode/src/cli/cmd/review.ts +++ b/packages/opencode/src/cli/cmd/review.ts @@ -3,7 +3,7 @@ import { UI } from "../ui" import { cmd } from "./cmd" import { bootstrap } from "../bootstrap" import { Installation } from "../../installation" -import { reviewPullRequest } from "../../altimate/review/run" +import { prContextFromEnv, reviewPullRequest } from "../../altimate/review/run" import { renderSummary } from "../../altimate/review/format" import { postGitHubReview, resolveGitHubTarget } from "../../altimate/review/post-github" // altimate_change — review feature telemetry @@ -66,6 +66,10 @@ export const ReviewCommand = cmd({ choices: ["trivial", "lite", "full"] as const, describe: "[EXPERIMENTAL / bench debug] override the tier classifier — verdict envelope carries tierForced: true", }) + .option("ai-model", { + type: "string", + describe: "provider/model for the advisory AI lane (default: the configured default model)", + }) .option("cwd", { type: "string", describe: "project directory (default: current dir)" }), async handler(args) { const cwd = (args.cwd as string) || process.cwd() @@ -92,9 +96,13 @@ export const ReviewCommand = cmd({ // altimate_change — time the engine only. Output writing and posting happen after this and // must not be counted as review latency, nor turn a computed review into a failed one. const startedAt = Date.now() + // PR title/description from the CI event, for the AI lane's intent check. + const prContext = await prContextFromEnv() let env try { env = await reviewPullRequest({ + ...prContext, + aiModel: args.aiModel as string | undefined, cwd, base: args.base as string | undefined, head: args.head as string | undefined, diff --git a/packages/opencode/test/altimate/review-ci-honesty.test.ts b/packages/opencode/test/altimate/review-ci-honesty.test.ts new file mode 100644 index 0000000000..7042d76e24 --- /dev/null +++ b/packages/opencode/test/altimate/review-ci-honesty.test.ts @@ -0,0 +1,188 @@ +import { describe, test, expect } from "bun:test" +import { promises as fs } from "node:fs" +import path from "node:path" +import { tmpdir } from "node:os" +import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { makeFinding } from "../../src/altimate/review/finding" +import { aiTimeoutMs } from "../../src/altimate/review/ai-review" +import { coverageNotes, renderSummary } from "../../src/altimate/review/format" +import { prContextFromEnv } from "../../src/altimate/review/run" +import { verifyEnvelope } from "../../src/altimate/review/verdict" + +/** + * The PR comment must be honest about what was checked: a manifest-backed run + * is not "lint-only" because one finding was undecidable, the advisory AI lane + * never fails silently, and the PR's title/description reach the intent check. + */ + +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() { + // Undecidable → the semantic lane emits a `degraded` finding. + return { decided: false } + }, + async detectPii() { + return { columns: [] } + }, +} as ReviewRunner + +const modified = [{ path: "models/marts/m.sql", status: "modified" as const, diff: "-select 1 as id\n+select 2 as id\n" }] +const content = async (_f: string, side: "old" | "new") => (side === "old" ? "select 1 as id" : "select 2 as id") + +function review(extra: Partial[0]> = {}) { + return runReview({ + changedFiles: modified, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["semantic_change", "ai_review"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + getContent: content, + getCompiled: content, + generatedAt: "2026-11-12T00:00:00Z", + ...extra, + }) +} + +describe("lint-only banner", () => { + test("an undecidable finding on a manifest-backed run does not flip the run to lint-only", async () => { + const env = await review() + expect(env.findings.some((f) => f.degraded)).toBe(true) + expect(env.summary.degraded).toBe(false) + const md = renderSummary(env) + expect(md).not.toContain("Lint-only run") + expect(md).toContain("could not be decided by the engine") + }) + + test("no manifest for the changed models is still lint-only", async () => { + const env = await review({ + runner: { + ...runner, + async impact() { + return { hasManifest: false, severity: "UNKNOWN", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + } as ReviewRunner, + }) + expect(env.summary.degraded).toBe(true) + expect(renderSummary(env)).toContain("Lint-only run") + }) +}) + +describe("advisory AI lane status", () => { + test("disabled lane is reported as skipped with the reason", async () => { + const env = await review({ aiDisabledReason: "disabled by --no-ai" }) + expect(env.ai).toEqual({ state: "skipped", reason: "disabled by --no-ai" }) + expect(coverageNotes(env).join("\n")).toContain("Advisory AI review skipped: disabled by --no-ai") + }) + + test("lane outside the tier is reported as skipped", async () => { + const env = await review({ config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["semantic_change"] } }) + expect(env.ai?.state).toBe("skipped") + expect(env.ai?.reason).toContain("tier") + }) + + test("a timeout is surfaced, signed, and never blocks", async () => { + const env = await review({ + aiReview: async () => ({ findings: [], status: { state: "timeout", reason: "no answer within 75 s", durationMs: 75000 } }), + }) + expect(env.ai?.state).toBe("timeout") + expect(verifyEnvelope(env)).toBe(true) + expect(renderSummary(env)).toContain("Advisory AI review timed out: no answer within 75 s") + }) + + test("a throwing lane becomes an error status instead of vanishing", async () => { + const env = await review({ + aiReview: async () => { + throw new Error("provider exploded") + }, + }) + expect(env.ai).toEqual({ state: "error", reason: "provider exploded" }) + }) + + test("a successful lane is ok, its model goes in the footer, and the model selector is passed through", async () => { + let sawModel: string | undefined + const env = await review({ + aiModel: "anthropic/claude-sonnet-5-5", + aiReview: async (input) => { + sawModel = input.model + return { + findings: [ + makeFinding({ + severity: "critical", + category: "semantic_change", + title: "m: intent mismatch", + body: "x", + file: "models/marts/m.sql", + model: "m", + confidence: "medium", + evidence: { tool: "ai-review", result: {} }, + ruleKey: "ai:t", + }), + ], + status: { state: "ok", model: "anthropic/claude-sonnet-5-5", durationMs: 1200 }, + } + }, + }) + expect(sawModel).toBe("anthropic/claude-sonnet-5-5") + expect(env.ai?.state).toBe("ok") + // Clamped: the AI lane never blocks. + expect(env.findings.find((f) => f.evidence?.tool === "ai-review")?.severity).toBe("warning") + expect(renderSummary(env)).toContain("AI `anthropic/claude-sonnet-5-5`") + expect(coverageNotes(env).join("\n")).not.toContain("Advisory AI review") + }) + + test("legacy lanes returning a bare findings array still work", async () => { + const env = await review({ aiReview: async () => [] }) + expect(env.ai?.state).toBe("ok") + }) + + test("timeout scales with the prompt and is capped", () => { + expect(aiTimeoutMs(0)).toBe(60_000) + expect(aiTimeoutMs(30_000)).toBe(75_000) + expect(aiTimeoutMs(10_000_000)).toBe(300_000) + }) +}) + +describe("PR title and description reach the intent check", () => { + test("GitHub: read from the pull_request event", async () => { + const dir = await fs.mkdtemp(path.join(tmpdir(), "review-event-")) + const ev = path.join(dir, "event.json") + await fs.writeFile(ev, JSON.stringify({ pull_request: { title: "Add fct_orders", body: "## Spec\n- grain: order_id" } })) + expect(await prContextFromEnv({ GITHUB_EVENT_PATH: ev })).toEqual({ + prTitle: "Add fct_orders", + prBody: "## Spec\n- grain: order_id", + }) + }) + + test("GitLab: read from the merge-request variables", async () => { + expect( + await prContextFromEnv({ CI_MERGE_REQUEST_TITLE: "Fix grain", CI_MERGE_REQUEST_DESCRIPTION: "dedupe on id" }), + ).toEqual({ prTitle: "Fix grain", prBody: "dedupe on id" }) + }) + + test("outside a PR run there is no context", async () => { + expect(await prContextFromEnv({})).toEqual({ prTitle: undefined, prBody: undefined }) + }) + + test("the context is forwarded to the AI lane", async () => { + let seen: { prTitle?: string; prBody?: string } = {} + await review({ + prTitle: "Add fct_orders", + prBody: "grain: order_id", + aiReview: async (input) => { + seen = { prTitle: input.prTitle, prBody: input.prBody } + return [] + }, + }) + expect(seen).toEqual({ prTitle: "Add fct_orders", prBody: "grain: order_id" }) + }) +}) From 82f738ab3553bdb4daf095b9816173ba827035c4 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 10:21:21 +0530 Subject: [PATCH 02/23] fix(review): address review comments: credential redaction in AI-lane reasons, never-throw AI lane - `safeReason` now runs the shared `redactSecrets` masker before collapsing whitespace, so `Basic` auth values, `Authorization:` headers, `user:pass@` URL userinfo and `api_key=...` secrets no longer reach the public PR comment. Exported and covered by tests. - `runAiReview` builds the user message and arms the timeout inside the `try`, keeping its never-throws contract. - `run.ts`: the AI-disabled reason is computed before the call instead of in a nested ternary. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-review.ts | 20 ++++++++++------ packages/opencode/src/altimate/review/run.ts | 6 ++++- .../test/altimate/review-ci-honesty.test.ts | 23 ++++++++++++++++++- 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index bd59dd54ed..d5a30c4ebb 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -5,6 +5,7 @@ import { Agent } from "@/agent/agent" import { MessageV2 } from "@/session/message-v2" import { MessageID, SessionID } from "@/session/schema" import { Log } from "@/altimate/util/log" +import { redactSecrets } from "@/installation" import { Dispatcher } from "../native" import { type Finding, type ReviewCategory, type Severity, makeFinding } from "./finding" import { readStreamText } from "../llm/stream-text" @@ -56,11 +57,14 @@ export function aiTimeoutMs(promptChars: number): number { return Math.min(AI_TIMEOUT_MAX_MS, AI_TIMEOUT_BASE_MS + Math.ceil(promptChars / 2_000) * 1_000) } -/** Error text safe to show in a PR comment: one line, bounded, with anything - * that looks like a key or bearer token masked. */ -function safeReason(err: unknown): string { +/** Error text safe to show in a PR comment: one line, bounded, with + * credentials masked (authorization headers, `Basic`/`Bearer` values, + * `key=value` secrets, `user:pass@` URL userinfo, provider-prefixed tokens). + * Redaction runs before whitespace is collapsed so a header match stops at + * its own line. */ +export function safeReason(err: unknown): string { const raw = err instanceof Error ? err.message : String(err) - return raw + return redactSecrets(raw) .replace(/\s+/g, " ") .replace(/(bearer\s+)[^\s]+/gi, "$1***") .replace(/\b(sk|pk|key|token)[-_][A-Za-z0-9_-]{8,}/gi, "***") @@ -121,12 +125,14 @@ export async function runAiReview(input: AiReviewInput): Promise const files = input.files.filter((f) => f.status !== "deleted" && (f.diff || f.sql)) if (!files.length) return done([], { state: "skipped", reason: "no changed model SQL to review" }) - const message = buildUserMessage({ ...input, files }) const controller = new AbortController() - const timeoutMs = aiTimeoutMs(message.length) - const timeout = setTimeout(() => controller.abort(), timeoutMs) + let timeoutMs = AI_TIMEOUT_BASE_MS + let timeout: ReturnType | undefined let modelLabel: string | undefined try { + const message = buildUserMessage({ ...input, files }) + timeoutMs = aiTimeoutMs(message.length) + timeout = setTimeout(() => controller.abort(), timeoutMs) // Prompt comes from the compiled core, not this file. const promptRes = await Dispatcher.call("altimate_core.review_ai_prompt", {}) const system = ((promptRes.data ?? {}) as Record).prompt as string | undefined diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 5295ea8326..508f4108b6 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -362,6 +362,10 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise ? undefined : makeCompiledResolver({ cwd: dbtRootReal, projectName, pathPrefix }) + let aiDisabledReason: string | undefined + if (opts.noAi) aiDisabledReason = "disabled by --no-ai" + else if (config.ai === false) aiDisabledReason = "disabled by `ai: false` in .altimate/review.yml" + return runReview({ changedFiles, config, @@ -381,7 +385,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise // path verdicts (cubic-review PR #1041). cliVersion: opts.cliVersion ?? Installation.VERSION, aiReview: opts.noAi || config.ai === false ? undefined : runAiReview, - aiDisabledReason: opts.noAi ? "disabled by --no-ai" : config.ai === false ? "disabled by `ai: false` in .altimate/review.yml" : undefined, + aiDisabledReason, aiModel: opts.aiModel, prTitle: opts.prTitle, prBody: opts.prBody, diff --git a/packages/opencode/test/altimate/review-ci-honesty.test.ts b/packages/opencode/test/altimate/review-ci-honesty.test.ts index 7042d76e24..c088414688 100644 --- a/packages/opencode/test/altimate/review-ci-honesty.test.ts +++ b/packages/opencode/test/altimate/review-ci-honesty.test.ts @@ -6,7 +6,7 @@ import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestr import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" import { makeFinding } from "../../src/altimate/review/finding" -import { aiTimeoutMs } from "../../src/altimate/review/ai-review" +import { aiTimeoutMs, safeReason } from "../../src/altimate/review/ai-review" import { coverageNotes, renderSummary } from "../../src/altimate/review/format" import { prContextFromEnv } from "../../src/altimate/review/run" import { verifyEnvelope } from "../../src/altimate/review/verdict" @@ -186,3 +186,24 @@ describe("PR title and description reach the intent check", () => { expect(seen).toEqual({ prTitle: "Add fct_orders", prBody: "grain: order_id" }) }) }) + +describe("safeReason: AI-lane errors reach a public PR comment with credentials masked", () => { + test("Basic auth, URL userinfo, key=value and bearer values are masked", () => { + const err = new Error( + "request to https://alice:s3cretPass@proxy.example.com/v1 failed\n" + + "Authorization: Basic YWxpY2U6czNjcmV0UGFzcw==\n" + + "api_key=abcd1234efgh and Bearer eyJhbGciOiJIUzI1NiJ9.payload", + ) + const out = safeReason(err) + expect(out).not.toContain("s3cretPass") + expect(out).not.toContain("YWxpY2U6czNjcmV0UGFzcw") + expect(out).not.toContain("abcd1234efgh") + expect(out).not.toContain("eyJhbGciOiJIUzI1NiJ9") + expect(out).toContain("proxy.example.com") + expect(out).not.toContain("\n") + }) + + test("an ordinary error message survives intact", () => { + expect(safeReason(new Error("model not found: openai/gpt-x"))).toBe("model not found: openai/gpt-x") + }) +}) From 868bfc9bd27d017dc89d10a5334ab8169f9900b6 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 11:02:18 +0530 Subject: [PATCH 03/23] fix(review): address review feedback: AI parse failure, explicit model error, masked lane reason, per-reason unverified notes, docs - `runAiReview`: core's in-band parse failure (`success: false`, or no findings array) is reported as `state: "error"`, never an "ok" run with no findings. - `runAiReview`: an explicitly requested `--ai-model` that cannot be resolved is an `error`; only a missing default model is `skipped`. - `runReview`: a thrown AI lane's reason goes through `safeReason` (masked, one line, bounded). - `coverageNotes`: unverified models are grouped by reason, one line each, so a missing head compile and a missing base compile are not reported as the same thing. - Docs: the base-compile recipe checks out the merge-base (what the review diffs against) and shows the `project_dir` form; the telemetry reference lists the new `review_run` fields and the narrower meaning of `degraded`. - Tests: masked multi-line lane reason, per-reason unverified notes. Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/telemetry.md | 2 +- docs/docs/usage/dbt-pr-review.md | 6 +++- .../opencode/src/altimate/review/ai-review.ts | 19 ++++++++++-- .../opencode/src/altimate/review/format.ts | 15 ++++++---- .../src/altimate/review/orchestrate.ts | 4 +-- .../test/altimate/review-ci-honesty.test.ts | 30 +++++++++++++++++++ 6 files changed, 64 insertions(+), 12 deletions(-) diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index c5e1639caf..677f1ec183 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -73,7 +73,7 @@ We collect the following categories of events: | `activation_job_selected` / `first_job_completed` | Which activation job the user started and, where observable, finished. In onboarding, completion is reported only for the job that was actually selected, so the two form a coherent pair. `first_job_completed` is also sent once per workspace for each machine and Altimate instance, for the first turn in a linked project, or in a session pinned to a workspace by the IDE extension, that had a tool call that didn't fail and ended `completed`. `origin` says which: `onboarding` or `workspace`. **Derived** — see the note below. | | `first_prompt_sent` | The user's first typed message in an onboarding session, and the first typed message in a linked project or a session pinned to a workspace, once per workspace for each machine and Altimate instance. A slash command sent as a command, as the TUI and `run` send it, is excluded, so the hidden `/onboard-connect` submission does not count. The VS Code chat sends a command as its expanded text, so there a command counts. A subagent's prompt never counts. `origin` says which rule sent it: `onboarding` for an onboarding session's first typed prompt, bound or not, and `workspace` for the workspace's row. So a later prompt in an onboarding session, after its project was linked, is a `workspace` row. | | `onboarding_abandoned` | The CLI exited during a first run without connecting. `last_stage` is the furthest point reached: `started`, `model_picker`, `provider_setup`, `altimate_base_confirm`, or `gateway_auth`. (`connected` is a funnel position but never a `last_stage` — reaching it means the run completed, which is not an abandonment.) Only emitted for a genuine first run — opening `/connect` as an existing user does not enter the funnel, and abandonment after setup completes is out of scope by definition. Emitted on the exit path under a bounded flush, so the measured rate is a lower bound — see [Delivery & Reliability](#delivery--reliability). | -| `review_run` | A dbt/SQL review completed or failed — `invocation` (`cli` for `altimate-code review`, `tool` for the `dbt_pr_review` tool), status, duration, and on success the verdict, the pre-gating verdict, mode, risk tier, and finding counts by severity and by category. No file paths, model or column names, finding titles or bodies, SQL, diff content, or repository/branch/PR names. | +| `review_run` | A dbt/SQL review completed or failed — `invocation` (`cli` for `altimate-code review`, `tool` for the `dbt_pr_review` tool), status, duration, and on success the verdict, the pre-gating verdict, mode, risk tier, finding counts by severity and by category, `degraded` (lint-only: no reviewable files, or no changed model resolved against a manifest; an undecidable finding alone no longer sets it), `undecided` (findings the engine could not decide), `unverified_models` (models without compiled SQL), `ai_state` and `ai_duration_ms` (the advisory AI lane's outcome), `base_source` (where the review base came from, e.g. `flag` or `default_branch`) and `out_of_scope_files` (changed files outside the dbt project). No file paths, model or column names, finding titles or bodies, SQL, diff content, or repository/branch/PR names. | | `review_post_outcome` | Whether a review was published to GitHub — `not_requested`, `not_attempted`, `target_unresolved`, `full`, `partial`, or `summary_failed`, plus duration. Emitted on the **CLI path only** — the `dbt_pr_review` tool completes reviews but never publishes, so a `review_run` with `invocation: tool` has no post event and that is not a failure. Within the CLI path there is exactly one per **completed** review: a review that failed emits `review_run: failed` and no post event, so absence there means the review failed rather than that an event was lost. `not_attempted` is publication requested but never reached (a bad `--output` path, a stdout write error). No repository, PR, or comment content. | | `rule_proposal_shown` | A proposed rule was raised: shown as a card, or stored for `learn proposals` when no attached client shows cards (`stored`), or raised again for the same wording (`repeat`) — what raised it (`remember`, `shown_rule`, `recurrence`), the kind of change, whether it is a "Save as" choice, linked/owner, the buttons offered, whether it weakens verification, evidence session count, whether it came from a correction, how many paths it applies to, and its length. The card id is random. No rule text, quotes, paths or globs. | | `rule_proposal_answered` | A card was answered or closed (`send`, `approve`, `approve_anyway`, `edit`, `dismiss`, `save_local`, `save_memory`, `expired`, `closed`) — `ok` or why it did not go through (`busy`, `not_available`, `verification_flagged`, `invalid_text`, `refused` by the workspace, `failed`), what happened (`sent`, `queued`, `approved`, `approve_failed`, `approve_retry`, `target_changed`, `exists`, `dismissed`, `saved_memory_project`, `saved_memory_global`, `saved_local`, or `saved_unanswered` when a card the person asked for closed unanswered and was saved as before cards), wording edits so far, and time since the card was shown. No rule text. | diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 0952e234fd..6fdf3dd46f 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -214,10 +214,14 @@ Compiling the base (optional, for equivalence and column-breakage): ```yaml - name: Compile the base into target-base/ run: | - git worktree add ../base "origin/${{ github.base_ref }}" + # The review diffs against the merge-base, not the target branch tip. + git worktree add ../base "$(git merge-base "origin/${{ github.base_ref }}" HEAD)" (cd ../base && dbt deps && dbt compile --target-path "$GITHUB_WORKSPACE/target-base") ``` +With `project_dir`, compile from that folder and write next to its own +`target/`: `(cd ../base/ && dbt deps && dbt compile --target-path "$GITHUB_WORKSPACE//target-base")`. + **Monorepos:** set `project_dir` to the folder holding `dbt_project.yml`. Only changes inside it are reviewed, `manifest_path` is resolved relative to it, and changes elsewhere are counted in the comment. diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index d5a30c4ebb..94691a9ce2 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -143,7 +143,13 @@ export async function runAiReview(input: AiReviewInput): Promise const chosen = input.model ? Provider.parseModel(input.model) : await Provider.defaultModel() model = await Provider.getModel(chosen.providerID, chosen.modelID) } catch (err) { - return done([], { state: "skipped", reason: `no usable model: ${safeReason(err)}`, model: input.model }) + // An explicitly requested model that cannot be resolved is an error, not + // the same as `--no-ai`; only a missing default is a skip. + return done([], { + state: input.model ? "error" : "skipped", + reason: `no usable model: ${safeReason(err)}`, + model: input.model, + }) } modelLabel = `${model.providerID}/${model.id}` @@ -188,7 +194,16 @@ export async function runAiReview(input: AiReviewInput): Promise text, valid_files: files.map((f) => f.path), }) - const parsed = (((parseRes.data ?? {}) as Record).findings as any[]) ?? [] + // The core parser reports failure in-band (`success: false`) rather than + // throwing; that is an error, never an "ok" run with no findings. + const parsedRaw = ((parseRes.data ?? {}) as Record).findings + if (parseRes.success === false || !Array.isArray(parsedRaw)) + return done([], { + state: "error", + reason: `could not parse the model's answer: ${safeReason(parseRes.error ?? "no findings list")}`, + model: modelLabel, + }) + const parsed = parsedRaw as any[] const byFile = new Map(files.map((f) => [f.path, f])) const out: Finding[] = [] diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index a110068e8b..9c055e6a7b 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -130,12 +130,15 @@ export function coverageNotes(env: VerdictEnvelope): string[] { if (undecided) notes.push(`${undecided} finding(s) could not be decided by the engine and are marked _unverified_.`) const unverified = env.scope?.unverified ?? [] if (unverified.length) { - const head = unverified.slice(0, 5).map((u) => `\`${u.path}\``).join(", ") - const more = unverified.length > 5 ? ` and ${unverified.length - 5} more` : "" - notes.push( - `${unverified.length} model(s) not verified by the engine — ${unverified[0].reason}: ${head}${more}. ` + - "Run `dbt compile` (and compile the base into `target-base/`) for equivalence and lineage checks.", - ) + // One line per reason: models can lack the head compile or the base compile. + const byReason = new Map() + for (const u of unverified) byReason.set(u.reason, [...(byReason.get(u.reason) ?? []), u.path]) + for (const [reason, paths] of byReason) { + const head = paths.slice(0, 5).map((p) => `\`${p}\``).join(", ") + const more = paths.length > 5 ? ` and ${paths.length - 5} more` : "" + notes.push(`${paths.length} model(s) not verified by the engine — ${reason}: ${head}${more}.`) + } + notes.push("Run `dbt compile` (and compile the base into `target-base/`) for equivalence and lineage checks.") } if (env.scope?.outOfScopeFiles) notes.push(`${env.scope.outOfScopeFiles} changed file(s) outside the dbt project were not reviewed.`) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 48e979e1ff..24cd1f92e1 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -14,7 +14,7 @@ import { type Rubric, exclusionReason, clampSeverity } from "./rubric" import { type ReviewConfig } from "./config" import { type ReviewMode, type ReviewScope, type VerdictEnvelope, buildEnvelope, signEnvelope } from "./verdict" import { detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" -import { type AiLaneStatus, type AiReviewInput, type AiReviewResult } from "./ai-review" +import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" /** * The deterministic review recipe. @@ -1441,7 +1441,7 @@ export async function runReview(input: OrchestrateInput): Promise { expect(env.ai).toEqual({ state: "error", reason: "provider exploded" }) }) + test("a throwing lane's reason is masked and kept on one line", async () => { + const env = await review({ + aiReview: async () => { + throw new Error("upstream failed\nAuthorization: Bearer abcdefghijklmnop123456\nretry later") + }, + }) + expect(env.ai?.state).toBe("error") + expect(env.ai?.reason).not.toContain("abcdefghijklmnop123456") + expect(env.ai?.reason).not.toContain("\n") + }) + test("a successful lane is ok, its model goes in the footer, and the model selector is passed through", async () => { let sawModel: string | undefined const env = await review({ @@ -207,3 +218,22 @@ describe("safeReason: AI-lane errors reach a public PR comment with credentials expect(safeReason(new Error("model not found: openai/gpt-x"))).toBe("model not found: openai/gpt-x") }) }) + +describe("unverified models are listed per reason", () => { + test("a model missing the head compile and one missing the base compile get their own lines", async () => { + const env = await review() + const notes = coverageNotes({ + ...env, + scope: { + ...env.scope, + unverified: [ + { path: "models/a.sql", reason: "no compiled SQL for the base (compile the base into target-base)" }, + { path: "models/b.sql", reason: "no compiled SQL for the head (run dbt compile)" }, + ], + }, + } as any) + expect(notes.find((n) => n.includes("models/a.sql"))).toContain("for the base") + expect(notes.find((n) => n.includes("models/b.sql"))).toContain("for the head") + expect(notes.find((n) => n.includes("models/a.sql"))).not.toContain("models/b.sql") + }) +}) From bf972de987a672e80cd38d170a86c138fb6a0608 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 20:25:51 +0530 Subject: [PATCH 04/23] test(review): build the fake credential fixture at runtime The credential-masking test used a literal user:password URL and Basic header, which secret scanners flag. Build them at runtime instead; the assertions are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../opencode/test/altimate/review-ci-honesty.test.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/opencode/test/altimate/review-ci-honesty.test.ts b/packages/opencode/test/altimate/review-ci-honesty.test.ts index 3901b47612..0b6b0e1580 100644 --- a/packages/opencode/test/altimate/review-ci-honesty.test.ts +++ b/packages/opencode/test/altimate/review-ci-honesty.test.ts @@ -200,14 +200,17 @@ describe("PR title and description reach the intent check", () => { describe("safeReason: AI-lane errors reach a public PR comment with credentials masked", () => { test("Basic auth, URL userinfo, key=value and bearer values are masked", () => { + // Fake credentials built at runtime so secret scanners don't flag the fixture. + const pass = ["s3cret", "Pass"].join("") + const basic = Buffer.from(`alice:${pass}`).toString("base64") const err = new Error( - "request to https://alice:s3cretPass@proxy.example.com/v1 failed\n" + - "Authorization: Basic YWxpY2U6czNjcmV0UGFzcw==\n" + + `request to https://alice:${pass}@proxy.example.com/v1 failed\n` + + `Authorization: Basic ${basic}\n` + "api_key=abcd1234efgh and Bearer eyJhbGciOiJIUzI1NiJ9.payload", ) const out = safeReason(err) - expect(out).not.toContain("s3cretPass") - expect(out).not.toContain("YWxpY2U6czNjcmV0UGFzcw") + expect(out).not.toContain(pass) + expect(out).not.toContain(basic.replace(/=+$/, "")) expect(out).not.toContain("abcd1234efgh") expect(out).not.toContain("eyJhbGciOiJIUzI1NiJ9") expect(out).toContain("proxy.example.com") From 7dcb5b413d769eacbae411566636206918c71056 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 12 Nov 2026 16:35:36 +0530 Subject: [PATCH 05/23] fix(review): a readable PR comment: diff-anchored inline comments, no reposts, grouped rules, size budget, new-only PII, no portability noise - Inline comments only on head-side lines inside the file's diff hunks; engine findings computed on compiled SQL no longer carry raw-file lines. Anything else moves to the summary instead of 422-ing the whole batch. - Each inline comment carries `` (the line-independent fingerprint); a rerun skips findings already on the PR, and a non-blocking rerun with nothing new only updates the summary. - The same rule on 3+ models collapses into one bullet listing the models. - The posted summary has a ~5K-character budget, most severe first, with a count of what was left out (the envelope keeps everything); CLI and agent tool output stay complete. - The PII fallback flags only columns the change newly exposes, not columns the base already surfaced. - Cross-engine portability advice from the regex catalog is dropped once the engine is known (`portability: true` in review.yml re-enables it for multi-adapter packages); core's dialect-aware check is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 18 ++ .../opencode/src/altimate/review/config.ts | 8 + .../opencode/src/altimate/review/format.ts | 143 +++++++++-- .../src/altimate/review/orchestrate.ts | 76 +++++- .../src/altimate/review/post-github.ts | 37 ++- packages/opencode/src/altimate/review/run.ts | 5 +- .../opencode/src/altimate/review/telemetry.ts | 3 +- .../src/altimate/tools/dbt-pr-review.ts | 2 +- packages/opencode/src/cli/cmd/review.ts | 7 +- .../test/altimate/review-noise.test.ts | 235 ++++++++++++++++++ .../opencode/test/altimate/review.test.ts | 26 +- 11 files changed, 510 insertions(+), 50 deletions(-) create mode 100644 packages/opencode/test/altimate/review-noise.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 6fdf3dd46f..58d85cb715 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -264,6 +264,8 @@ mode: comment # comment | gate severityThreshold: suggestion manifestPath: target/manifest.json dialect: snowflake +portability: false # cross-engine advice; default off once the engine is known + # (set true for packages that support several adapters) reviewers: [] # empty = risk-tier defaults; or pin lanes dataDiff: # OFF by default — see "Data-diff in CI" below enabled: false @@ -283,6 +285,22 @@ rubric: skipNonProdModels: true ``` +### What the PR comment shows + +- **One summary comment**, updated in place on every push, capped at about + 5,000 characters. Critical findings come first; anything that does not fit is + counted, and the full list is always in the verdict envelope + (`altimate review --json`). Local CLI output is never truncated. +- **Repeated rules are grouped:** the same rule on three or more models is one + bullet listing the models. +- **Inline comments only on lines of the PR's diff.** Findings computed on + compiled SQL, or on unchanged lines, stay in the summary. +- **No re-posting on reruns:** each inline comment carries the finding's + fingerprint, so a push does not repeat findings already on the PR, and a + non-blocking rerun with nothing new only updates the summary. +- **PII:** flagged only for PII columns the change newly exposes, not for + columns the base already surfaced. + ### Risk-tier path tokens Named categories under `riskTierPathTokens` promote any diff touching a matching diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 793121c510..9d370d8062 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -26,6 +26,14 @@ export const ReviewConfig = z.object({ dialect: z.string().default(""), /** Enable the advisory LLM reviewer lane (needs a configured model). */ ai: z.boolean().default(true), + /** + * Report cross-engine portability advice ("isn't portable across + * warehouses"). Off by default once the engine is known (from the manifest's + * adapter or `dialect`), because a project that runs on one engine gains + * nothing from it. Turn on for packages that support several adapters. + * Functions missing on the project's own engine are always reported. + */ + portability: z.boolean().optional(), /** * Data-diff: actually run base-vs-head against the warehouse (core DataParity) * and report row/value deltas. OPT-IN — it costs warehouse compute and needs a diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 9c055e6a7b..778ab2acae 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -36,8 +36,20 @@ export function verdictHeadline(env: VerdictEnvelope): string { return `${VERDICT_LABEL[env.verdict]} — ${counts} (${tierLabel})` } +/** Default size budget for the posted PR comment (characters). */ +export const SUMMARY_BUDGET_CHARS = 5_000 +/** The same rule on this many models or more collapses into one bullet. */ +export const GROUP_MIN = 3 + +export interface RenderOptions { + /** Character budget for the comment; findings beyond it are counted, not listed. + * `Infinity` renders everything (local CLI output). */ + maxChars?: number +} + /** Full PR/MR summary comment body (markdown), prefixed with the dedup marker. */ -export function renderSummary(env: VerdictEnvelope): string { +export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): string { + const maxChars = opts.maxChars ?? SUMMARY_BUDGET_CHARS const lines: string[] = [REVIEW_MARKER, "", `## ${verdictHeadline(env)}`, ""] if (env.summary.degraded) { @@ -80,33 +92,15 @@ export function renderSummary(env: VerdictEnvelope): string { lines.push(`> 🧭 **Tier: ${env.tier}** — ${shown}${overflow}`, "") } - if (!env.findings.length) { - lines.push("No issues found in the changed dbt models. 🎉", "") - } else { - const grouped = groupBySeverity(env.findings) - for (const sev of ["critical", "warning", "suggestion"] as const) { - const items = grouped[sev] - if (!items.length) continue - lines.push(`### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${items.length})`, "") - for (const f of items) { - const loc = f.file + (f.startLine ? `:${f.startLine}` : "") - lines.push( - `- **${f.title}** \n ${oneLine(f.body)} \n \`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}`, - ) - } - lines.push("") - } - } - + const tail: string[] = [] if (env.override) { - lines.push( + tail.push( `> 🔓 **Break-glass override** by @${env.override.by}: ${env.override.reason}`, `> (would have been \`${env.override.priorVerdict}\`)`, "", ) } - - lines.push( + tail.push( "---", `altimate dbt-pr-review · verdict \`${env.verdict}\`` + (env.signature ? ` · signed \`${env.signature.slice(0, 18)}…\`` : "") + @@ -115,7 +109,90 @@ export function renderSummary(env: VerdictEnvelope): string { (env.ai?.state === "ok" && env.ai.model ? ` · AI \`${env.ai.model}\`` : "") + "", ) - return lines.join("\n") + + if (!env.findings.length) { + lines.push("No issues found in the changed dbt models. 🎉", "") + return [...lines, ...tail].join("\n") + } + + // Findings fill the budget left after the fixed parts, most severe first. + // What does not fit is counted, never silently dropped: the envelope keeps + // every finding. + const overflowReserve = 220 + let used = [...lines, ...tail].join("\n").length + overflowReserve + let hidden = 0 + const grouped = groupBySeverity(env.findings) + for (const sev of ["critical", "warning", "suggestion"] as const) { + const items = grouped[sev] + if (!items.length) continue + const heading = [`### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${items.length})`, ""] + const bullets = bulletsFor(items) + let headed = false + for (const b of bullets) { + const cost = b.text.length + 1 + (headed ? 0 : heading.join("\n").length + 2) + if (used + cost > maxChars) { + hidden += b.count + continue + } + if (!headed) { + lines.push(...heading) + headed = true + } + lines.push(b.text) + used += cost + } + if (headed) lines.push("") + } + if (hidden) { + lines.push( + `> … ${hidden} more finding(s) not shown to keep this comment short — the full list is in the verdict envelope ` + + "(`altimate review --json`, or the action's `--output` artifact).", + "", + ) + } + return [...lines, ...tail].join("\n") +} + +/** A finding's title without its leading `model: `, with backticked names + * blanked, so the same rule on different models/columns shares a key. */ +function ruleTitle(f: Finding): string { + const t = f.model && f.title.startsWith(`${f.model}: `) ? f.title.slice(f.model.length + 2) : f.title + return t.replace(/`[^`]*`/g, "`…`") +} + +/** Render findings of one severity as bullets; a rule repeated on GROUP_MIN or + * more models collapses into a single bullet listing the models. */ +function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { + const groups = new Map() + for (const f of items) { + const key = `${f.category}|${ruleTitle(f)}` + const g = groups.get(key) + if (g) g.push(f) + else groups.set(key, [f]) + } + const out: Array<{ text: string; count: number }> = [] + for (const g of groups.values()) { + if (g.length >= GROUP_MIN) { + const names = [...new Set(g.map((f) => f.model ?? f.file))] + const shown = names.slice(0, 8).map((n) => `\`${n}\``).join(", ") + const more = names.length > 8 ? ` (+${names.length - 8} more)` : "" + out.push({ + text: + `- **${ruleTitle(g[0])}** — ${g.length} findings across ${names.length} model(s): ${shown}${more} \n` + + ` ${oneLine(g[0].body)} \n ${g[0].category}`, + count: g.length, + }) + continue + } + for (const f of g) { + const loc = f.file + (f.startLine ? `:${f.startLine}` : "") + out.push({ + text: `- **${f.title}** \n ${oneLine(f.body)} \n \`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}`, + count: 1, + }) + } + } + return out } /** @@ -157,14 +234,28 @@ export interface InlineComment { body: string } -export function inlineComments(env: VerdictEnvelope): InlineComment[] { +/** Hidden per-finding marker on inline comments, keyed by the finding's stable + * fingerprint (rule, file, model, column — not the line), so a rerun can tell + * which findings are already on the PR. */ +export function findingMarker(id: string): string { + return `` +} + +/** Finding ids already posted, read from existing inline comment bodies. */ +export function postedFindingIds(bodies: Array): Set { + const out = new Set() + for (const b of bodies) for (const m of (b ?? "").matchAll(//g)) out.add(m[1]) + return out +} + +export function inlineComments(env: VerdictEnvelope, alreadyPosted: Set = new Set()): InlineComment[] { return env.findings - .filter((f) => typeof f.startLine === "number") + .filter((f) => typeof f.startLine === "number" && !alreadyPosted.has(f.id)) .map((f) => ({ path: f.file, line: f.startLine!, side: "RIGHT" as const, - body: `${SEVERITY_EMOJI[f.severity]} **${f.title}**\n\n${f.body}`, + body: `${SEVERITY_EMOJI[f.severity]} **${f.title}**\n\n${f.body}\n\n${findingMarker(f.id)}`, })) } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 24cd1f92e1..04b055bfb1 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -206,6 +206,57 @@ export interface OrchestrateInput { layout?: DbtProjectLayout /** What the review covered: base resolution and files left out of scope. */ scope?: Omit + /** Drop the regex catalog's cross-engine portability findings (single known engine). */ + suppressPortability?: boolean +} + +const PORTABILITY_RE = /portab|dialect[ -]specific|non-?standard|n't standard|not standard|standard sql/i + +/** A regex-catalog finding whose concern is portability across warehouses. */ +export function isCatalogPortability(f: Finding): boolean { + const tool = f.evidence?.tool + return (tool === "rule-catalog" || tool === "dbt-patterns") && PORTABILITY_RE.test(`${f.title} ${f.body}`) +} + +/** Line numbers on the head side of a unified diff that GitHub accepts for an + * inline comment: added lines and context lines inside a hunk. */ +export function commentableLines(diff: string | undefined): Set { + const out = new Set() + if (!diff) return out + let right = 0 + let inHunk = false + const rows = diff.split("\n") + if (rows[rows.length - 1] === "") rows.pop() // the diff's trailing newline, not a line + for (const line of rows) { + const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line) + if (h) { + right = Number(h[1]) + inHunk = true + continue + } + // File headers (`--- a/…`, `+++ b/…`) only occur outside a hunk. + if (!inHunk || line.startsWith("\\")) continue + // A blank context line may have lost its leading space in transit. + if (line.startsWith("+") || line.startsWith(" ") || line === "") out.add(right++) + else if (!line.startsWith("-")) inHunk = false + } + return out +} + +/** + * Keep a finding's line only when it can be commented on: inside the file's + * diff hunks on the head side. Anything else (a line from compiled SQL, an + * unchanged region) moves to the summary instead of making GitHub reject the + * whole batch of inline comments. + */ +export function anchorToDiff(findings: Finding[], files: ChangedFile[]): Finding[] { + const lines = new Map(files.map((f) => [f.path, commentableLines(f.diff)])) + return findings.map((f) => { + if (typeof f.startLine !== "number") return f + if (lines.get(f.file)?.has(f.startLine)) return f + const { startLine: _s, endLine: _e, ...rest } = f + return rest as Finding + }) } /** True when SQL text contains Jinja (`{{ }}`, `{% %}` or `{# #}`). */ @@ -395,6 +446,8 @@ async function qualityLane( sql: string | undefined, dialect: string, oldSql?: string, + /** True when `sql` is the raw file; compiled-SQL line numbers do not exist in the PR's file. */ + linesMatchFile = false, ): Promise { if (!sql || file.status === "deleted") return [] const model = modelNameFromPath(file.path) @@ -432,8 +485,8 @@ async function qualityLane( body: issue.message, file: file.path, model, - startLine: issue.line, - endLine: issue.line, + startLine: linesMatchFile ? issue.line : undefined, + endLine: linesMatchFile ? issue.line : undefined, evidence: { tool: "altimate_core.check", result: issue }, // Include the message so distinct instances of the same rule (e.g. two // different non-portable functions) don't collapse under one fingerprint. @@ -1186,7 +1239,9 @@ export async function runReview(input: OrchestrateInput): Promise[] = [] // Engine lanes consume COMPILED SQL (rendered by dbt) when available. if (lanes.has("sql_quality") || lanes.has("warehouse_cost")) - tasks.push(qualityLane(ctx.file, input.runner, ctx.engineNewSql, dialect, ctx.engineOldSql)) + tasks.push( + qualityLane(ctx.file, input.runner, ctx.engineNewSql, dialect, ctx.engineOldSql, ctx.engineNewSql === ctx.newSql), + ) if (lanes.has("semantic_change")) { tasks.push(dataDiffLane(ctx, input.runner, dialect, input.config.dataDiff)) tasks.push(grainMismatchLane(ctx, input.runner)) @@ -1228,9 +1283,17 @@ export async function runReview(input: OrchestrateInput): Promise !diffScopedPii.classifiedColumns.has(col.toLowerCase())) : currentCtx.pii + // Only columns this PR newly exposes: a PII column the base already + // surfaced is not this change's concern (the docs promise "newly expose"). + if (fallbackPii.length && hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { + const basePii = new Set( + (await input.runner.detectPii(currentCtx.engineOldSql, dialect)).columns.map((c) => c.toLowerCase()), + ) + fallbackPii = fallbackPii.filter((col) => !basePii.has(col.toLowerCase())) + } findings.push(...piiLane(currentCtx.file, fallbackPii)) } return findings @@ -1448,6 +1511,11 @@ export async function runReview(input: OrchestrateInput): Promise !exclusionReason(f, input.rubric)) + // Cross-engine portability advice from the regex catalog is noise for a + // project that runs on one known engine. Core's dialect-aware check (a + // function missing on THIS engine) is a real error and is kept. + if (input.suppressPortability) findings = findings.filter((f) => !isCatalogPortability(f)) + findings = anchorToDiff(findings, input.changedFiles) const minSev = SEVERITY_ORDER[input.config.severityThreshold] findings = findings.filter((f) => SEVERITY_ORDER[f.severity] >= minSev) // Sort by severity desc, then file. diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index 9ef43286f5..9a34c83199 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -1,7 +1,7 @@ import { Octokit } from "@octokit/rest" import { promises as fs } from "node:fs" import { type VerdictEnvelope, VCS_EVENT } from "./verdict" -import { renderSummary, inlineComments, REVIEW_MARKER, verdictHeadline } from "./format" +import { renderSummary, inlineComments, postedFindingIds, REVIEW_MARKER, verdictHeadline } from "./format" /** * Post a verdict envelope to a GitHub pull request: an upserted summary comment @@ -54,8 +54,16 @@ export interface PostResult { inlineFellBack: boolean /** Set when the review event could not be posted for a non-positioning reason. */ postError?: string + /** Inline comments not re-posted because the same finding is already on the PR. */ + inlineSkippedAsPosted?: number + /** True when no review was submitted: nothing new to say and a previous + * non-blocking altimate review already exists (the summary comment was updated). */ + reviewSkipped?: boolean } +/** Headline of a review this bot posted (see verdictHeadline). */ +const BOT_REVIEW_RE = /(Approved|Reviewed with comments|Changes requested)\b.*\((trivial|lite|full) tier/ + export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarget): Promise { const octo = new Octokit({ auth: target.token }) const { owner, repo, prNumber } = target @@ -85,9 +93,34 @@ export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarge // this map only translates verdict → GitHub event. APPROVE always maps to a // COMMENT event — the bot must never submit a formal GitHub approval. const event = VCS_EVENT[env.verdict] - const comments = inlineComments(env) const reviewBody = verdictHeadline(env) + // Rerun dedup: a finding already commented inline (same fingerprint, which + // ignores line numbers) is not posted again on the next push. + let posted = new Set() + let priorBotReview = false + try { + const [reviewComments, reviews] = await Promise.all([ + octo.paginate(octo.rest.pulls.listReviewComments, { owner, repo, pull_number: prNumber, per_page: 100 }), + octo.paginate(octo.rest.pulls.listReviews, { owner, repo, pull_number: prNumber, per_page: 100 }), + ]) + posted = postedFindingIds(reviewComments.map((c) => c.body)) + priorBotReview = reviews.some((r) => BOT_REVIEW_RE.test(r.body ?? "")) + } catch { + /* listing failed: post everything rather than nothing */ + } + const comments = inlineComments(env, posted) + const withLine = env.findings.filter((f) => typeof f.startLine === "number").length + result.inlineSkippedAsPosted = withLine - comments.length + + // Nothing new inline, not blocking, and the PR already has an altimate + // review: the updated summary comment says it all; another "Reviewed with + // comments" entry per push is noise. A blocking verdict always posts. + if (!comments.length && event === "COMMENT" && priorBotReview) { + result.reviewSkipped = true + return result + } + // Anchor inline comments to the PR head commit. Without commit_id, GitHub's // line-positioning is fragile and can 422 even on valid lines. let commitId: string | undefined diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 508f4108b6..c6a86b7925 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -318,7 +318,9 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise // Resolve the SQL dialect: explicit config wins; otherwise auto-detect from // the dbt manifest's `adapter_type` (so a BigQuery/Redshift project isn't // analyzed as the snowflake default — wrong-dialect portability suppression). - if (!config.dialect) config.dialect = (await detectDialect(manifestAbs)) ?? "snowflake" + const detectedDialect = config.dialect ? undefined : await detectDialect(manifestAbs) + const dialectKnown = !!config.dialect || !!detectedDialect + if (!config.dialect) config.dialect = detectedDialect ?? "snowflake" // Prefer dbt's catalog.json (real warehouse columns from `dbt docs generate`) // for the schema context — complete columns are what make column-lineage @@ -393,6 +395,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise forceTier: opts.forceTier, staleManifest, layout, + suppressPortability: config.portability === undefined ? dialectKnown : !config.portability, scope: { baseRef: resolved?.ref ?? opts.base, baseSha: resolved?.sha, diff --git a/packages/opencode/src/altimate/review/telemetry.ts b/packages/opencode/src/altimate/review/telemetry.ts index 34016e8a50..3fbe4af1bb 100644 --- a/packages/opencode/src/altimate/review/telemetry.ts +++ b/packages/opencode/src/altimate/review/telemetry.ts @@ -71,7 +71,8 @@ export function classifyReviewFailure(err: unknown): "config_error" | "git_error * caller reports `summary_failed` for that. */ export function classifyPostOutcome(result: PostResult): "full" | "partial" { - if (result.inlineFellBack || result.postError || result.reviewId === undefined) return "partial" + if (result.inlineFellBack || result.postError) return "partial" + if (result.reviewId === undefined && !result.reviewSkipped) return "partial" return "full" } diff --git a/packages/opencode/src/altimate/tools/dbt-pr-review.ts b/packages/opencode/src/altimate/tools/dbt-pr-review.ts index ab3ceab013..47d68a6549 100644 --- a/packages/opencode/src/altimate/tools/dbt-pr-review.ts +++ b/packages/opencode/src/altimate/tools/dbt-pr-review.ts @@ -77,7 +77,7 @@ export const DbtPrReviewTool = Tool.define("dbt_pr_review", { signature: env.signature, findingCount: env.findings.length, }, - output: renderSummary(env), + output: renderSummary(env, { maxChars: Infinity }), } }, }) diff --git a/packages/opencode/src/cli/cmd/review.ts b/packages/opencode/src/cli/cmd/review.ts index e35556aa0b..cef6942c20 100644 --- a/packages/opencode/src/cli/cmd/review.ts +++ b/packages/opencode/src/cli/cmd/review.ts @@ -153,7 +153,8 @@ export const ReviewCommand = cmd({ if (args.json) { process.stdout.write(JSON.stringify(env, null, 2) + "\n") } else { - process.stdout.write(renderSummary(env) + "\n") + // Local output is complete; the size budget applies to the posted comment. + process.stdout.write(renderSummary(env, { maxChars: Infinity }) + "\n") } if (args.post) { @@ -191,7 +192,9 @@ export const ReviewCommand = cmd({ } else { UI.println( `Posted review to ${where}` + - (r.inlineFellBack ? " (inline comments fell back to summary-only)" : ""), + (r.inlineFellBack ? " (inline comments fell back to summary-only)" : "") + + (r.inlineSkippedAsPosted ? ` (${r.inlineSkippedAsPosted} inline already on the PR)` : "") + + (r.reviewSkipped ? " (summary updated; no new review needed)" : ""), ) } } diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts new file mode 100644 index 0000000000..ae64c9a67e --- /dev/null +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -0,0 +1,235 @@ +import { describe, test, expect } from "bun:test" +import { + anchorToDiff, + commentableLines, + isCatalogPortability, + runReview, + type ReviewRunner, +} from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { makeFinding, type Finding } from "../../src/altimate/review/finding" +import { + findingMarker, + inlineComments, + postedFindingIds, + renderSummary, + SUMMARY_BUDGET_CHARS, +} from "../../src/altimate/review/format" +import { buildEnvelope } from "../../src/altimate/review/verdict" +import { classifyPostOutcome } from "../../src/altimate/review/telemetry" + +/** + * The PR comment must stay readable: inline comments land on real lines of the + * PR's file and are not re-posted on every push, a rule repeated across many + * models is one bullet, the comment has a size budget, and cross-engine + * portability advice is dropped for a single-engine project. + */ + +function finding(over: Partial[0]> = {}): Finding { + return makeFinding({ + severity: "suggestion", + category: "test_coverage", + title: "m: new model has no uniqueness/grain test", + body: "Add a unique or unique_combination_of_columns test.", + file: "models/m.sql", + model: "m", + confidence: "high", + evidence: { tool: "test-coverage", result: {} }, + ...over, + }) +} + +const DIFF = [ + "diff --git a/models/m.sql b/models/m.sql", + "--- a/models/m.sql", + "+++ b/models/m.sql", + "@@ -1,4 +1,5 @@", + " select", + " id", + "- , old_col", + "+ , new_col", + "+ , other_col", + "", + " from src", +].join("\n") + +describe("inline anchors", () => { + test("commentable lines are the head-side added and context lines inside hunks", () => { + // 1 select, 2 id, 3 new_col, 4 other_col, 5 blank context, 6 from src + expect([...commentableLines(DIFF)].sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6]) + expect(commentableLines(undefined).size).toBe(0) + }) + + test("an added SQL line starting with `++` still counts; headers outside hunks do not", () => { + const d = "--- a/x.sql\n+++ b/x.sql\n@@ -0,0 +1,2 @@\n+select 1\n++ 1 as weird\n" + expect([...commentableLines(d)].sort()).toEqual([1, 2]) + }) + + test("a line outside the diff moves to the summary instead of failing the batch", () => { + const inDiff = finding({ startLine: 3, endLine: 3, title: "m: a" }) + const outside = finding({ startLine: 40, endLine: 40, title: "m: b" }) + const [a, b] = anchorToDiff([inDiff, outside], [{ path: "models/m.sql", status: "modified", diff: DIFF }]) + expect(a.startLine).toBe(3) + expect(b.startLine).toBeUndefined() + expect(b.endLine).toBeUndefined() + }) + + test("engine lint on compiled SQL never anchors to the raw file", 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: "select-star", message: "avoid select *", severity: "warning", line: 2 }], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } as ReviewRunner + const env = await runReview({ + changedFiles: [{ path: "models/m.sql", status: "added", diff: "@@ -0,0 +1,3 @@\n+{{ config() }}\n+select *\n+from {{ ref('a') }}\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["sql_quality"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + getContent: async () => "{{ config() }}\nselect *\nfrom {{ ref('a') }}\n", + getCompiled: async () => "\n\n\nselect *\nfrom db.a\n", + }) + const f = env.findings.find((x) => x.evidence?.tool === "altimate_core.check") + expect(f).toBeDefined() + expect(f!.startLine).toBeUndefined() + }) +}) + +describe("inline dedup across pushes", () => { + test("inline bodies carry the finding fingerprint, which ignores the line", () => { + const a = finding({ startLine: 3 }) + const moved = finding({ startLine: 9 }) + expect(a.id).toBe(moved.id) + const env = buildEnvelope({ findings: [a], tier: "lite", mode: "comment" }) + expect(inlineComments(env)[0].body).toContain(findingMarker(a.id)) + }) + + test("findings already commented on the PR are not posted again", () => { + const a = finding({ startLine: 3, title: "m: a" }) + const b = finding({ startLine: 4, title: "m: b" }) + const env = buildEnvelope({ findings: [a, b], tier: "lite", mode: "comment" }) + const posted = postedFindingIds(["🛑 old\n\n" + findingMarker(a.id), null, "human comment"]) + expect([...posted]).toEqual([a.id]) + expect(inlineComments(env, posted).map((c) => c.line)).toEqual([4]) + }) + + test("a skipped repeat review counts as a full post in telemetry", () => { + expect(classifyPostOutcome({ inlineFellBack: false, reviewSkipped: true })).toBe("full") + expect(classifyPostOutcome({ inlineFellBack: false })).toBe("partial") + }) +}) + +describe("summary grouping and budget", () => { + test("the same rule on three or more models is one bullet listing the models", () => { + const fs = ["a", "b", "c", "d"].map((m) => + finding({ model: m, file: `models/${m}.sql`, title: `${m}: new model has no uniqueness/grain test` }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md.match(/no uniqueness\/grain test/g)?.length).toBe(1) + expect(md).toContain("4 findings across 4 model(s): `a`, `b`, `c`, `d`") + }) + + test("two occurrences stay as separate bullets", () => { + const fs = ["a", "b"].map((m) => finding({ model: m, file: `models/${m}.sql`, title: `${m}: new model has no uniqueness/grain test` })) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md.match(/no uniqueness\/grain test/g)?.length).toBe(2) + }) + + test("backticked column names do not split a group", () => { + const fs = ["a", "b", "c"].map((m) => + finding({ model: m, file: `models/${m}.sql`, title: `${m}: grain column \`${m}_id\` lacks not_null`, category: "test_coverage" }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).toContain("3 findings across 3 model(s)") + }) + + test("the posted comment stays within budget, most severe first, and counts what it hides", () => { + const many: Finding[] = [] + for (let i = 0; i < 200; i++) + many.push( + finding({ + severity: i < 3 ? "critical" : "suggestion", + category: i < 3 ? "lineage_breakage" : "sql_quality", + model: `m${i}`, + file: `models/m${i}.sql`, + title: `m${i}: distinct issue number ${i}`, + body: "x".repeat(120), + }), + ) + const env = buildEnvelope({ findings: many, tier: "full", mode: "comment" }) + const md = renderSummary(env) + expect(md.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) + expect(md).toContain("m0: distinct issue number 0") + expect(md).toMatch(/… \d+ more finding\(s\) not shown/) + // Local output is complete. + expect(renderSummary(env, { maxChars: Infinity })).toContain("m199: distinct issue number 199") + }) +}) + +describe("portability noise", () => { + const portability = finding({ + severity: "suggestion", + category: "sql_quality", + title: "m: DISTINCT ON isn't portable", + body: "`DISTINCT ON (…)` isn't portable; use `qualify row_number()` for first-row-per-group.", + evidence: { tool: "rule-catalog", result: {} }, + }) + const coreMissing = finding({ + category: "sql_quality", + title: "m: non_portable_function", + body: "GETDATE() is a non-standard / dialect-specific function.", + evidence: { tool: "altimate_core.check", result: { rule: "non_portable_function" } }, + }) + + test("catalog portability advice is recognised; core's dialect-aware check is not", () => { + expect(isCatalogPortability(portability)).toBe(true) + expect(isCatalogPortability(coreMissing)).toBe(false) + }) + + test("a single known engine drops catalog portability findings", 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: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } as ReviewRunner + const sql = "select distinct on (customer_id) customer_id, order_id from orders" + const base = { + changedFiles: [{ path: "models/m.sql", status: "added" as const, diff: `+${sql}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"], dialect: "snowflake" }, + rubric: DEFAULT_RUBRIC, + mode: "comment" as const, + runner, + getContent: async () => sql, + } + const kept = await runReview(base) + const dropped = await runReview({ ...base, suppressPortability: true }) + const before = kept.findings.filter(isCatalogPortability).length + expect(before).toBeGreaterThan(0) + expect(dropped.findings.filter(isCatalogPortability).length).toBe(0) + }) +}) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 113a2202fd..2ec9445a26 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -1967,8 +1967,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+email\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["email", "ssn"] } + async detectPii(sql: string) { + return { columns: ["email", "ssn"].filter((c) => sql.includes(c)) } }, } const env = await runReview({ @@ -1977,7 +1977,7 @@ describe("orchestrate", () => { rubric: DEFAULT_RUBRIC, mode: "gate", runner, - getContent: content("select email, ssn from x"), + getContent: content("select email, ssn from x", "select id from x"), }) const pii = env.findings.find((f) => f.category === "pii_exposure") expect(pii).toBeDefined() @@ -2024,7 +2024,7 @@ describe("orchestrate", () => { expect(env.verdict).toBe("REQUEST_CHANGES") }) - test("broad PII detector remains fallback for existing output columns", async () => { + test("a PII column the base already exposed is not re-flagged when the PR only touches it", async () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ lower(email) as email\n" }] const runner: ReviewRunner = { ...fakeRunner({}), @@ -2056,18 +2056,18 @@ describe("orchestrate", () => { runner, getContent: content("select customer_id, lower(email) as email from customers", "select customer_id, email from customers"), }) + // `email` was already in the base's output: this PR does not newly expose it. const pii = env.findings.filter((f) => f.category === "pii_exposure") - expect(pii).toHaveLength(1) - expect(pii[0].evidence?.tool).toBe("schema.detect_pii") - expect(env.verdict).toBe("REQUEST_CHANGES") + expect(pii).toHaveLength(0) + expect(env.verdict).not.toBe("REQUEST_CHANGES") }) test("PII fallback survives core lineage failure instead of aborting review", async () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ email\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["email"] } + async detectPii(sql: string) { + return { columns: sql.includes("email") ? ["email"] : [] } }, async columnLineage() { throw new Error("lineage parser crashed") @@ -2098,8 +2098,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ email\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["email"] } + async detectPii(sql: string) { + return { columns: sql.includes("email") ? ["email"] : [] } }, async columnLineage(sql) { return sql.includes("email") @@ -2205,8 +2205,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ ssn\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["ssn"] } + async detectPii(sql: string) { + return { columns: sql.includes("ssn") ? ["ssn"] : [] } }, async columnLineage(sql) { return sql.includes("ssn") From 1aa22e25bd1b081dbace10f423d3bcac7cf89bb5 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 13 Nov 2026 11:07:42 +0530 Subject: [PATCH 06/23] fix(review): portability advice is an explicit tag, kept when it fails on the project's own engine; moved files are named - catalog rules carry `portability: { worksOn? }` instead of the comment text being matched: `bq-legacy-sql` ("use Standard SQL") was being dropped on BigQuery projects - with a known engine, portability advice is dropped only when that engine supports the construct; `DISTINCT ON` on Snowflake or `GROUP BY alias` on SQL Server stays, because it errors there - files moved without edits are named in the comment, with the caveat that folder-level `dbt_project.yml` config can still change how they build - a run with no model files (yml-only, pure moves) is no longer labeled lint-only Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 5 ++ .../src/altimate/review/orchestrate.ts | 23 ++++++--- .../src/altimate/review/rule-catalog.ts | 29 +++++++---- .../test/altimate/review-noise.test.ts | 48 ++++++++++++++++--- 4 files changed, 82 insertions(+), 23 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 778ab2acae..e833c058e1 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -219,6 +219,11 @@ export function coverageNotes(env: VerdictEnvelope): string[] { } if (env.scope?.outOfScopeFiles) notes.push(`${env.scope.outOfScopeFiles} changed file(s) outside the dbt project were not reviewed.`) + if (env.scope?.movedUnchangedFiles) + notes.push( + `${env.scope.movedUnchangedFiles} file(s) moved without edits; their SQL was not re-reviewed. ` + + "Folder-level config in `dbt_project.yml` (`+schema`, `+materialized`, `+tags`) can still change where and how a moved model builds.", + ) if (env.ai && env.ai.state !== "ok") { const what = { skipped: "skipped", timeout: "timed out", error: "failed" }[env.ai.state] notes.push(`Advisory AI review ${what}${env.ai.reason ? `: ${env.ai.reason}` : ""}.`) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 04b055bfb1..223e657111 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -210,12 +210,20 @@ export interface OrchestrateInput { suppressPortability?: boolean } -const PORTABILITY_RE = /portab|dialect[ -]specific|non-?standard|n't standard|not standard|standard sql/i - -/** A regex-catalog finding whose concern is portability across warehouses. */ +/** A catalog finding tagged as cross-engine portability advice. */ export function isCatalogPortability(f: Finding): boolean { - const tool = f.evidence?.tool - return (tool === "rule-catalog" || tool === "dbt-patterns") && PORTABILITY_RE.test(`${f.title} ${f.body}`) + return f.evidence?.tool === "rule-catalog" && (f.evidence.result as { portability?: boolean })?.portability === true +} + +/** + * Portability advice that is noise for a project on `dialect`: dropped unless + * the rule names the engines that support the construct and `dialect` isn't + * one of them — then it is an error on this project's own engine. + */ +export function isSuppressiblePortability(f: Finding, dialect: string): boolean { + if (!isCatalogPortability(f)) return false + const worksOn = (f.evidence?.result as { worksOn?: string[] })?.worksOn + return !worksOn || worksOn.includes(dialect.toLowerCase()) } /** Line numbers on the head side of a unified diff that GitHub accepts for an @@ -1170,7 +1178,8 @@ export async function runReview(input: OrchestrateInput): Promise 0 ? !anyManifest : reviewable.length === 0 + // Nothing to resolve (yml-only, pure moves) is not a lint-only run. + const runDegraded = modelFiles.length > 0 && !anyManifest // High-risk path tokens are user-configured (billing/pci/patient/etc.) — // the reviewer core carries no default list. `undefined` when no @@ -1514,7 +1523,7 @@ export async function runReview(input: OrchestrateInput): Promise !isCatalogPortability(f)) + if (input.suppressPortability) findings = findings.filter((f) => !isSuppressiblePortability(f, dialect)) findings = anchorToDiff(findings, input.changedFiles) const minSev = SEVERITY_ORDER[input.config.severityThreshold] findings = findings.filter((f) => SEVERITY_ORDER[f.severity] >= minSev) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 0d8313c458..98360039a7 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -44,6 +44,12 @@ export interface Rule { unless?: RegExp kind?: RuleKind pathGlob?: RegExp + /** + * Cross-engine portability advice: dropped for a project on one known + * engine, unless that engine is missing from `worksOn` (then it is a real + * error there and is kept). Omit `worksOn` when support isn't established. + */ + portability?: { worksOn?: string[] } example: RuleExample counter?: RuleExample } @@ -122,7 +128,10 @@ export function evaluateCatalog( file: file.path, model, confidence: "high", - evidence: { tool: "rule-catalog", result: { rule: rule.id } }, + evidence: { + tool: "rule-catalog", + result: rule.portability ? { rule: rule.id, portability: true, worksOn: rule.portability.worksOn } : { rule: rule.id }, + }, ruleKey: `${rule.category}:${rule.id}`, }) if (!exclusionReason(f, rubric)) matched.push({ rule, finding: f }) @@ -167,7 +176,7 @@ const r = ( severity: Severity, title: string, body: string, - match: Pick, + match: Pick, example: RuleExample, counter?: RuleExample, ): Rule => ({ id, category, severity, title, body, ...match, example, counter }) @@ -585,7 +594,7 @@ const AGG: Rule[] = [ "suggestion", "COUNT(DISTINCT a, b) portability", "Multi-column COUNT(DISTINCT) isn't supported on all warehouses; concat or use a subquery.", - { added: /count\s*\(\s*distinct\s+[^),]+,/i }, + { added: /count\s*\(\s*distinct\s+[^),]+,/i, portability: { worksOn: ["mysql", "snowflake", "databricks"] } }, { add: "count(distinct a, b)" }, { add: "count(distinct a)" }, ), @@ -1703,7 +1712,7 @@ const STYLE: Rule[] = [ "suggestion", "PIVOT/UNPIVOT is dialect-specific", "`PIVOT`/`UNPIVOT` syntax varies by warehouse and is hard to test; consider conditional aggregation.", - { added: /\b(pivot|unpivot)\s*\(/i }, + { added: /\b(pivot|unpivot)\s*\(/i, portability: {} }, { add: "from t pivot(sum(x) for k in ('a'))" }, { add: "sum(case when k='a' then x end)" }, ), @@ -1723,7 +1732,7 @@ const STYLE: Rule[] = [ "suggestion", "GROUP BY on a SELECT alias", "Grouping by a select-list alias isn't portable (errors on some warehouses); repeat the expression.", - { added: /\bgroup\s+by\s+\w+_(amt|amount|total|cnt|count)\b/i }, + { added: /\bgroup\s+by\s+\w+_(amt|amount|total|cnt|count)\b/i, portability: { worksOn: ["snowflake", "bigquery", "postgres", "redshift", "databricks", "duckdb", "mysql", "clickhouse"] } }, { add: "group by total_amount" }, { add: "group by customer_id" }, ), @@ -1733,7 +1742,7 @@ const STYLE: Rule[] = [ "suggestion", "string interval literal portability", "`interval '1 day'` literal syntax differs across warehouses; prefer dateadd/date_add functions.", - { added: /interval\s+'\d+\s*\w+'/i }, + { added: /interval\s+'\d+\s*\w+'/i, portability: {} }, { add: "d + interval '1 day'" }, { add: "dateadd(day, 1, d)" }, ), @@ -1743,7 +1752,7 @@ const STYLE: Rule[] = [ "suggestion", "integer arithmetic on a date", "`date + 7` (bare int) isn't portable and is ambiguous (days? seconds?); use dateadd/interval.", - { added: /\b\w*(date|_at|_dt)\b\s*[+\-]\s*\d+\b/i }, + { added: /\b\w*(date|_at|_dt)\b\s*[+\-]\s*\d+\b/i, portability: { worksOn: ["postgres", "redshift", "snowflake", "duckdb", "oracle"] } }, { add: "select order_date + 7" }, { add: "select dateadd(day, 7, order_date)" }, ), @@ -1866,7 +1875,7 @@ const MISC: Rule[] = [ "suggestion", "DISTINCT ON is Postgres-specific", "`DISTINCT ON (…)` isn't portable; use `qualify row_number()` for first-row-per-group.", - { added: /distinct\s+on\s*\(/i }, + { added: /distinct\s+on\s*\(/i, portability: { worksOn: ["postgres", "duckdb"] } }, { add: "select distinct on (id) * from t" }, { add: "qualify row_number() over (partition by id order by d) = 1" }, ), @@ -1876,7 +1885,7 @@ const MISC: Rule[] = [ "suggestion", "FETCH FIRST portability", "`FETCH FIRST n ROWS` isn't supported everywhere; `LIMIT` (with ORDER BY) is more portable.", - { added: /fetch\s+first\s+\d+/i }, + { added: /fetch\s+first\s+\d+/i, portability: { worksOn: ["postgres", "snowflake", "oracle", "trino"] } }, { add: "fetch first 10 rows only" }, { add: "limit 10" }, ), @@ -2299,7 +2308,7 @@ const MISC2: Rule[] = [ "suggestion", "non-portable type name (TEXT)", "`cast(x as text)` isn't supported on all warehouses; use `string`/`varchar`.", - { added: /\bas\s+text\b/i }, + { added: /\bas\s+text\b/i, portability: { worksOn: ["postgres", "redshift", "duckdb", "snowflake"] } }, { add: "cast(x as text)" }, { add: "cast(x as string)" }, ), diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index ae64c9a67e..dfd0208133 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -3,6 +3,7 @@ import { anchorToDiff, commentableLines, isCatalogPortability, + isSuppressiblePortability, runReview, type ReviewRunner, } from "../../src/altimate/review/orchestrate" @@ -17,6 +18,7 @@ import { SUMMARY_BUDGET_CHARS, } from "../../src/altimate/review/format" import { buildEnvelope } from "../../src/altimate/review/verdict" +import { evaluateCatalog } from "../../src/altimate/review/rule-catalog" import { classifyPostOutcome } from "../../src/altimate/review/telemetry" /** @@ -185,7 +187,7 @@ describe("portability noise", () => { category: "sql_quality", title: "m: DISTINCT ON isn't portable", body: "`DISTINCT ON (…)` isn't portable; use `qualify row_number()` for first-row-per-group.", - evidence: { tool: "rule-catalog", result: {} }, + evidence: { tool: "rule-catalog", result: { rule: "distinct-on", portability: true, worksOn: ["postgres", "duckdb"] } }, }) const coreMissing = finding({ category: "sql_quality", @@ -194,12 +196,31 @@ describe("portability noise", () => { evidence: { tool: "altimate_core.check", result: { rule: "non_portable_function" } }, }) + test("only explicitly tagged rules are portability advice, not rules that mention standard SQL", async () => { + const legacy = evaluateCatalog( + { path: "models/m.sql", status: "added" }, + "select * from [proj:ds.t]", + ["select * from [proj:ds.t]"], + [], + DEFAULT_RUBRIC, + ).find((f) => (f.evidence?.result as { rule: string }).rule === "bq-legacy-sql") + expect(legacy).toBeDefined() + expect(isCatalogPortability(legacy!)).toBe(false) + }) + + test("a construct that fails on the project's own engine is kept", () => { + expect(isSuppressiblePortability(portability, "postgres")).toBe(true) + expect(isSuppressiblePortability(portability, "snowflake")).toBe(false) + const untagged = { ...portability, evidence: { tool: "rule-catalog", result: { rule: "pivot-portability", portability: true } } } + expect(isSuppressiblePortability(untagged, "snowflake")).toBe(true) + }) + test("catalog portability advice is recognised; core's dialect-aware check is not", () => { expect(isCatalogPortability(portability)).toBe(true) expect(isCatalogPortability(coreMissing)).toBe(false) }) - test("a single known engine drops catalog portability findings", async () => { + test("a single known engine drops portability advice it supports, keeps what fails on it", async () => { const runner = { async impact() { return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } @@ -227,9 +248,24 @@ describe("portability noise", () => { getContent: async () => sql, } const kept = await runReview(base) - const dropped = await runReview({ ...base, suppressPortability: true }) - const before = kept.findings.filter(isCatalogPortability).length - expect(before).toBeGreaterThan(0) - expect(dropped.findings.filter(isCatalogPortability).length).toBe(0) + expect(kept.findings.filter(isCatalogPortability).length).toBeGreaterThan(0) + // Postgres supports DISTINCT ON: the advice is noise there and is dropped. + const pg = { ...base, config: { ...base.config, dialect: "postgres" } } + expect((await runReview({ ...pg, suppressPortability: true })).findings.filter(isCatalogPortability).length).toBe(0) + // Snowflake doesn't: on a Snowflake project it is a real error and stays. + expect((await runReview({ ...base, suppressPortability: true })).findings.filter(isCatalogPortability).length).toBeGreaterThan(0) + }) +}) + +describe("moved files", () => { + test("moves are named in the comment with the folder-config caveat, and are not a lint-only run", async () => { + const env = buildEnvelope({ + findings: [], + tier: "trivial", + mode: "comment", + scope: { movedUnchangedFiles: 3 } as any, + }) + expect(renderSummary(env)).toContain("3 file(s) moved without edits") + expect(renderSummary(env)).toContain("`+schema`") }) }) From 0b216f2c4672743be2bc3709fa14005a5fdc5dea Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 10:23:09 +0530 Subject: [PATCH 07/23] fix(review): address review comments: PII without a compiled base, same-model grouping - PII lanes: when a modified model's base SQL can't be compiled, the head's PII columns can't be told apart from pre-existing ones. Both the `schema.detect_pii` fallback and the diff-scoped classifier now report them as non-blocking warnings (with a note) instead of blocking criticals. Docs state the caveat. - Summary grouping counts distinct models, so several findings of one rule on the same model stay separate bullets instead of collapsing into the first. - Tests for both. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 4 ++- .../opencode/src/altimate/review/format.ts | 8 +++-- .../src/altimate/review/orchestrate.ts | 22 ++++++++---- .../test/altimate/review-noise.test.ts | 9 +++++ .../opencode/test/altimate/review.test.ts | 35 +++++++++++++++++++ 5 files changed, 68 insertions(+), 10 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 58d85cb715..e0f5908c46 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -299,7 +299,9 @@ rubric: fingerprint, so a push does not repeat findings already on the PR, and a non-blocking rerun with nothing new only updates the summary. - **PII:** flagged only for PII columns the change newly exposes, not for - columns the base already surfaced. + columns the base already surfaced. That comparison needs the base version's + SQL; when it can't be compiled, PII columns are reported as non-blocking + warnings that may predate the PR. ### Risk-tier path tokens diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index e833c058e1..22b2bd772c 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -161,7 +161,7 @@ function ruleTitle(f: Finding): string { } /** Render findings of one severity as bullets; a rule repeated on GROUP_MIN or - * more models collapses into a single bullet listing the models. */ + * more distinct models collapses into a single bullet listing the models. */ function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { const groups = new Map() for (const f of items) { @@ -172,8 +172,10 @@ function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { } const out: Array<{ text: string; count: number }> = [] for (const g of groups.values()) { - if (g.length >= GROUP_MIN) { - const names = [...new Set(g.map((f) => f.model ?? f.file))] + // Group by distinct models: several findings of one rule on the SAME model + // (e.g. two different columns) are distinct issues and stay separate bullets. + const names = [...new Set(g.map((f) => f.model ?? f.file))] + if (names.length >= GROUP_MIN) { const shown = names.slice(0, 8).map((n) => `\`${n}\``).join(", ") const more = names.length > 8 ? ` (+${names.length - 8} more)` : "" out.push({ diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 223e657111..b6afeecf81 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1064,6 +1064,9 @@ async function piiClassifyLane( // apply (`missingGrainTestLane` also includes `intermediate`): an internal // intermediate model surfacing PII is a warning, not a hard block. const highExposureLayer = /(^|\/)(marts|reporting)\//.test(file.path) + // Without a compiled base, every head column counts as "introduced", so a + // pre-existing column can't be told apart: never escalate to critical then. + const baseUnknown = hasOldSide(file) && !ctx.engineOldSql for (const p of pii) { const classification = String(p.classification ?? "") const lowRiskClass = PII_LOW_RISK_CLASS.test(classification) @@ -1071,7 +1074,7 @@ async function piiClassifyLane( if (p.confidence < minConfidence || !p.column) continue const col = p.column.toLowerCase() const highConfidence = p.confidence >= 0.9 - const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass ? "critical" : "warning" + const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass && !baseUnknown ? "critical" : "warning" out.push( makeFinding({ severity: clampSeverity("pii_exposure", severity, highConfidence ? "high" : "medium"), @@ -1092,20 +1095,26 @@ async function piiClassifyLane( return { findings: out, classifiedColumns, completed: true } } -function piiLane(file: ChangedFile & { kind: string }, columns: string[]): Finding[] { +/** `baseUnknown`: the file had a previous version but its base SQL could not + * be compiled, so these columns may predate the PR. Reported as a warning + * (never blocking) instead of a critical "newly exposed" finding. */ +function piiLane(file: ChangedFile & { kind: string }, columns: string[], baseUnknown = false): Finding[] { if (file.status === "deleted" || !columns.length) return [] const model = modelNameFromPath(file.path) return [ makeFinding({ - severity: "critical", + severity: baseUnknown ? "warning" : "critical", category: "pii_exposure", title: `${model}: exposes PII column${columns.length !== 1 ? "s" : ""} (${columns.join(", ")})`, body: `This model surfaces PII-classified column(s): ${columns.map((c) => `\`${c}\``).join(", ")}.` + - ` Confirm masking/access policy before merging to a non-restricted schema.`, + ` Confirm masking/access policy before merging to a non-restricted schema.` + + (baseUnknown + ? " The base version could not be compiled, so these columns may already be exposed before this PR." + : ""), file: file.path, model, - confidence: "high", + confidence: baseUnknown ? "medium" : "high", evidence: { tool: "schema.detect_pii", result: { columns } }, ruleKey: "pii:exposure", }), @@ -1303,7 +1312,8 @@ export async function runReview(input: OrchestrateInput): Promise !basePii.has(col.toLowerCase())) } - findings.push(...piiLane(currentCtx.file, fallbackPii)) + const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql + findings.push(...piiLane(currentCtx.file, fallbackPii, baseUnknown)) } return findings })(), diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index dfd0208133..eadc169466 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -150,6 +150,15 @@ describe("summary grouping and budget", () => { expect(md.match(/no uniqueness\/grain test/g)?.length).toBe(2) }) + test("several findings of one rule on the same model are not collapsed", () => { + const fs = ["a_id", "b_id", "c_id"].map((c) => + finding({ model: "m", file: "models/m.sql", title: `m: grain column \`${c}\` lacks not_null`, category: "test_coverage" }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).not.toContain("findings across") + for (const c of ["a_id", "b_id", "c_id"]) expect(md).toContain(c) + }) + test("backticked column names do not split a group", () => { const fs = ["a", "b", "c"].map((m) => finding({ model: m, file: `models/${m}.sql`, title: `${m}: grain column \`${m}_id\` lacks not_null`, category: "test_coverage" }), diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 2ec9445a26..f4cea11a31 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2127,6 +2127,41 @@ describe("orchestrate", () => { expect(env.verdict).toBe("REQUEST_CHANGES") }) + test("without a compiled base, head PII may predate the PR: reported as a non-blocking warning", async () => { + const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ lower(email) as email\n" }] + const runner: ReviewRunner = { + ...fakeRunner({}), + async detectPii(sql: string) { + return { columns: sql.includes("email") ? ["email"] : [] } + }, + async columnLineage(sql) { + return [ + { source: "customers.customer_id", target: "customer_id" }, + ...(sql.includes("email") ? [{ source: "customers.email", target: "email" }] : []), + ] + }, + async classifyPii(columns) { + return columns.map((column) => ({ column, classification: "Email", confidence: 0.95 })) + }, + } + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner, + // The base is raw Jinja with no compiled artifact: it cannot be analysed. + getContent: content( + "select customer_id, lower(email) as email from customers", + "select customer_id, email from {{ ref('customers') }}", + ), + }) + const pii = env.findings.filter((f) => f.category === "pii_exposure") + expect(pii.length).toBeGreaterThan(0) + expect(pii.every((f) => f.severity !== "critical")).toBe(true) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + }) + test("case-variant PII detector output does not duplicate core diff-scoped finding", async () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ Email as EMAIL\n" }] const runner: ReviewRunner = { From c7a166b2e9e722ec738f12b3953e49ccfa828b03 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Mon, 23 Nov 2026 13:35:27 +0530 Subject: [PATCH 08/23] fix(review): grouping keeps distinct messages, base-exposed PII stays quiet, review skip and inline anchoring tightened - Summary grouping keys on the normalized body too, so one rule with different messages per model is no longer merged into the first message. A grouped bullet keeps `_unverified_` when any member is degraded and shows the body with names blanked when members differ only by name. Uncapped output (`maxChars: Infinity`) never groups. Renamed `ruleTitle` to `groupKeyTitle` and `GROUP_MIN` to `GROUP_MIN_MODELS`. - PII: the base's exposed PII columns are computed whenever a compiled base exists and suppress both the broad fallback and the `pii_into_mart` regex twin, so a reindented `ssn` line in a mart no longer blocks. - PII findings without a compiled base carry `unknown` confidence, so they no longer count toward `warningPatternThreshold`. - `postGitHubReview` skips a new review only when this bot's latest review (author taken from the summary comment) has the same headline as the current verdict; a prior "Changes requested" no longer suppresses it. Octokit is injectable for tests. - Findings keep `startLine` in the envelope; inline comments are filtered to commentable lines from the PR's file patches (`commentableLines` moved to `format.ts`, `anchorToDiff` removed). - `date-plus-int` split: the `_at` timestamp variant is `timestamp-plus-int` with `worksOn: ["oracle"]`, so it is kept on Postgres/Snowflake/DuckDB. - `shouldSuppressPortability` extracted from `run.ts`; docs example leaves `portability` commented out and explains explicit values. - Tests: grouping (differing bodies, mixed degraded, blanked names, more than eight models), mocked-Octokit `postGitHubReview` (skip, prior blocking review, other author, diff filtering, listing failure, 422 fallback), orchestrator PII (base-exposed twin, no-base warnings), timestamp rule, portability derivation. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 13 +- .../opencode/src/altimate/review/format.ts | 85 +++++-- .../src/altimate/review/orchestrate.ts | 76 ++---- .../src/altimate/review/post-github.ts | 66 ++++-- .../src/altimate/review/rule-catalog.ts | 14 +- packages/opencode/src/altimate/review/run.ts | 9 +- .../test/altimate/review-noise.test.ts | 224 +++++++++++++++++- .../opencode/test/altimate/review.test.ts | 89 ++++++- 8 files changed, 469 insertions(+), 107 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index e0f5908c46..a1375cb2a2 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -264,8 +264,9 @@ mode: comment # comment | gate severityThreshold: suggestion manifestPath: target/manifest.json dialect: snowflake -portability: false # cross-engine advice; default off once the engine is known - # (set true for packages that support several adapters) +# portability: true # cross-engine advice. Unset: off once the engine is known + # (configured or detected). An explicit value applies even when + # the engine is unknown. Set true for multi-adapter packages. reviewers: [] # empty = risk-tier defaults; or pin lanes dataDiff: # OFF by default — see "Data-diff in CI" below enabled: false @@ -291,13 +292,15 @@ rubric: 5,000 characters. Critical findings come first; anything that does not fit is counted, and the full list is always in the verdict envelope (`altimate review --json`). Local CLI output is never truncated. -- **Repeated rules are grouped:** the same rule on three or more models is one - bullet listing the models. +- **Repeated findings are grouped:** the same rule with the same message on + three or more models is one bullet listing the models. Local CLI output lists + every finding with its location. - **Inline comments only on lines of the PR's diff.** Findings computed on compiled SQL, or on unchanged lines, stay in the summary. - **No re-posting on reruns:** each inline comment carries the finding's fingerprint, so a push does not repeat findings already on the PR, and a - non-blocking rerun with nothing new only updates the summary. + non-blocking rerun with nothing new and the same headline as the bot's last + review only updates the summary. - **PII:** flagged only for PII columns the change newly exposes, not for columns the base already surfaced. That comparison needs the base version's SQL; when it can't be compiled, PII columns are reported as non-blocking diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 22b2bd772c..0d84881822 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -39,7 +39,7 @@ export function verdictHeadline(env: VerdictEnvelope): string { /** Default size budget for the posted PR comment (characters). */ export const SUMMARY_BUDGET_CHARS = 5_000 /** The same rule on this many models or more collapses into one bullet. */ -export const GROUP_MIN = 3 +export const GROUP_MIN_MODELS = 3 export interface RenderOptions { /** Character budget for the comment; findings beyond it are counted, not listed. @@ -117,7 +117,7 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s // Findings fill the budget left after the fixed parts, most severe first. // What does not fit is counted, never silently dropped: the envelope keeps - // every finding. + // every finding. The reserve keeps room for the "… N more finding(s)" line. const overflowReserve = 220 let used = [...lines, ...tail].join("\n").length + overflowReserve let hidden = 0 @@ -126,7 +126,8 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s const items = grouped[sev] if (!items.length) continue const heading = [`### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${items.length})`, ""] - const bullets = bulletsFor(items) + // Uncapped (local) output lists every finding with its own location. + const bullets = bulletsFor(items, maxChars !== Infinity) let headed = false for (const b of bullets) { const cost = b.text.length + 1 + (headed ? 0 : heading.join("\n").length + 2) @@ -153,19 +154,27 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s return [...lines, ...tail].join("\n") } +/** Backticked names blanked, so the same rule on different models/columns + * normalizes to the same text. */ +function blankNames(s: string): string { + return s.replace(/`[^`]*`/g, "`…`") +} + /** A finding's title without its leading `model: `, with backticked names - * blanked, so the same rule on different models/columns shares a key. */ -function ruleTitle(f: Finding): string { - const t = f.model && f.title.startsWith(`${f.model}: `) ? f.title.slice(f.model.length + 2) : f.title - return t.replace(/`[^`]*`/g, "`…`") + * blanked: the title half of the grouping key. */ +function groupKeyTitle(f: Finding): string { + return blankNames(f.model && f.title.startsWith(`${f.model}: `) ? f.title.slice(f.model.length + 2) : f.title) } -/** Render findings of one severity as bullets; a rule repeated on GROUP_MIN or - * more distinct models collapses into a single bullet listing the models. */ -function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { +/** Render findings of one severity as bullets. With `group`, findings that say + * the same thing (same category, title and body once names are blanked) on + * GROUP_MIN_MODELS or more distinct models collapse into one bullet. */ +function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; count: number }> { const groups = new Map() for (const f of items) { - const key = `${f.category}|${ruleTitle(f)}` + // The body is part of the key: one rule with different messages (e.g. a + // dialect check naming different functions) is different findings. + const key = group ? `${f.category}|${groupKeyTitle(f)}|${blankNames(oneLine(f.body))}` : f.id const g = groups.get(key) if (g) g.push(f) else groups.set(key, [f]) @@ -175,13 +184,17 @@ function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { // Group by distinct models: several findings of one rule on the SAME model // (e.g. two different columns) are distinct issues and stay separate bullets. const names = [...new Set(g.map((f) => f.model ?? f.file))] - if (names.length >= GROUP_MIN) { + if (group && names.length >= GROUP_MIN_MODELS) { const shown = names.slice(0, 8).map((n) => `\`${n}\``).join(", ") const more = names.length > 8 ? ` (+${names.length - 8} more)` : "" + // Show a body verbatim only when every member says exactly that; + // otherwise its names belong to one model, so show the blanked form. + const body = g.every((f) => f.body === g[0].body) ? oneLine(g[0].body) : blankNames(oneLine(g[0].body)) + const unverified = g.some((f) => f.degraded) ? " · _unverified_" : "" out.push({ text: - `- **${ruleTitle(g[0])}** — ${g.length} findings across ${names.length} model(s): ${shown}${more} \n` + - ` ${oneLine(g[0].body)} \n ${g[0].category}`, + `- **${groupKeyTitle(g[0])}** — ${g.length} findings across ${names.length} model(s): ${shown}${more} \n` + + ` ${body} \n ${g[0].category}${unverified}`, count: g.length, }) continue @@ -255,9 +268,49 @@ export function postedFindingIds(bodies: Array): Set< return out } -export function inlineComments(env: VerdictEnvelope, alreadyPosted: Set = new Set()): InlineComment[] { +/** Line numbers on the head side of a unified diff that GitHub accepts for an + * inline comment: added lines and context lines inside a hunk. */ +export function commentableLines(diff: string | undefined): Set { + const out = new Set() + if (!diff) return out + let right = 0 + let inHunk = false + const rows = diff.split("\n") + if (rows[rows.length - 1] === "") rows.pop() // the diff's trailing newline, not a line + for (const line of rows) { + const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line) + if (h) { + right = Number(h[1]) + inHunk = true + continue + } + // File headers (`--- a/…`, `+++ b/…`) only occur outside a hunk. + if (!inHunk || line.startsWith("\\")) continue + // A blank context line may have lost its leading space in transit. + if (line.startsWith("+") || line.startsWith(" ") || line === "") out.add(right++) + else if (!line.startsWith("-")) inHunk = false + } + return out +} + +/** + * Inline comments for findings with a line. With `commentable` (head-side + * commentable lines per file, see `commentableLines`), only lines inside the + * PR's diff hunks are kept: GitHub rejects the whole batch over one line + * outside the diff. The finding keeps its line in the envelope and summary. + */ +export function inlineComments( + env: VerdictEnvelope, + alreadyPosted: Set = new Set(), + commentable?: Map>, +): InlineComment[] { return env.findings - .filter((f) => typeof f.startLine === "number" && !alreadyPosted.has(f.id)) + .filter( + (f) => + typeof f.startLine === "number" && + !alreadyPosted.has(f.id) && + (!commentable || !!commentable.get(f.file)?.has(f.startLine)), + ) .map((f) => ({ path: f.file, line: f.startLine!, diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index b6afeecf81..3fd1a019a0 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -226,47 +226,6 @@ export function isSuppressiblePortability(f: Finding, dialect: string): boolean return !worksOn || worksOn.includes(dialect.toLowerCase()) } -/** Line numbers on the head side of a unified diff that GitHub accepts for an - * inline comment: added lines and context lines inside a hunk. */ -export function commentableLines(diff: string | undefined): Set { - const out = new Set() - if (!diff) return out - let right = 0 - let inHunk = false - const rows = diff.split("\n") - if (rows[rows.length - 1] === "") rows.pop() // the diff's trailing newline, not a line - for (const line of rows) { - const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line) - if (h) { - right = Number(h[1]) - inHunk = true - continue - } - // File headers (`--- a/…`, `+++ b/…`) only occur outside a hunk. - if (!inHunk || line.startsWith("\\")) continue - // A blank context line may have lost its leading space in transit. - if (line.startsWith("+") || line.startsWith(" ") || line === "") out.add(right++) - else if (!line.startsWith("-")) inHunk = false - } - return out -} - -/** - * Keep a finding's line only when it can be commented on: inside the file's - * diff hunks on the head side. Anything else (a line from compiled SQL, an - * unchanged region) moves to the summary instead of making GitHub reject the - * whole batch of inline comments. - */ -export function anchorToDiff(findings: Finding[], files: ChangedFile[]): Finding[] { - const lines = new Map(files.map((f) => [f.path, commentableLines(f.diff)])) - return findings.map((f) => { - if (typeof f.startLine !== "number") return f - if (lines.get(f.file)?.has(f.startLine)) return f - const { startLine: _s, endLine: _e, ...rest } = f - return rest as Finding - }) -} - /** True when SQL text contains Jinja (`{{ }}`, `{% %}` or `{# #}`). */ export function hasJinja(sql: string | undefined): boolean { return !!sql && /\{\{|\{%|\{#/.test(sql) @@ -1086,7 +1045,9 @@ async function piiClassifyLane( (p.masking ? `; suggested masking: \`${p.masking}\`.` : "."), file: file.path, model, - confidence: highConfidence ? "high" : "medium", + // Without a base, exposure is undecided: `unknown` keeps these warnings + // out of the warning-pattern count, so they never block. + confidence: baseUnknown ? "unknown" : highConfidence ? "high" : "medium", evidence: { tool: "altimate_core.classify_pii", result: p }, ruleKey: `pii_exposure:${col}`, }), @@ -1114,7 +1075,8 @@ function piiLane(file: ChangedFile & { kind: string }, columns: string[], baseUn : ""), file: file.path, model, - confidence: baseUnknown ? "medium" : "high", + // `unknown`: undecided exposure never counts toward the warning pattern. + confidence: baseUnknown ? "unknown" : "high", evidence: { tool: "schema.detect_pii", result: { columns } }, ruleKey: "pii:exposure", }), @@ -1253,6 +1215,9 @@ export async function runReview(input: OrchestrateInput): Promise() const diffScopedPiiFindingFiles = new Set() const classifiedPiiColumnsByFile = new Map>() + // Per file: PII columns the compiled base already exposed. Neither the broad + // fallback nor the regex twins report these (this PR did not expose them). + const basePiiColumnsByFile = new Map>() for (const ctx of ctxByPath.values()) { const tasks: Promise[] = [] // Engine lanes consume COMPILED SQL (rendered by dbt) when available. @@ -1296,6 +1261,17 @@ export async function runReview(input: OrchestrateInput): Promise() + if (hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { + try { + basePii = new Set( + (await input.runner.detectPii(currentCtx.engineOldSql, dialect)).columns.map((c) => c.toLowerCase()), + ) + } catch { + /* unknown base exposure: report as if new */ + } + basePiiColumnsByFile.set(currentCtx.file.path, basePii) + } if (lanes.has("pii_exposure")) { // The broad fallback covers output PII columns the precise lane did NOT // classify (pre-existing columns, or ones core's classifier missed) — @@ -1304,14 +1280,8 @@ export async function runReview(input: OrchestrateInput): Promise !diffScopedPii.classifiedColumns.has(col.toLowerCase())) : currentCtx.pii - // Only columns this PR newly exposes: a PII column the base already - // surfaced is not this change's concern (the docs promise "newly expose"). - if (fallbackPii.length && hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { - const basePii = new Set( - (await input.runner.detectPii(currentCtx.engineOldSql, dialect)).columns.map((c) => c.toLowerCase()), - ) - fallbackPii = fallbackPii.filter((col) => !basePii.has(col.toLowerCase())) - } + // The fallback reports only columns the base did not already expose. + fallbackPii = fallbackPii.filter((col) => !basePii.has(col.toLowerCase())) const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql findings.push(...piiLane(currentCtx.file, fallbackPii, baseUnknown)) } @@ -1456,6 +1426,9 @@ export async function runReview(input: OrchestrateInput): Promise !isSuppressiblePortability(f, dialect)) - findings = anchorToDiff(findings, input.changedFiles) const minSev = SEVERITY_ORDER[input.config.severityThreshold] findings = findings.filter((f) => SEVERITY_ORDER[f.severity] >= minSev) // Sort by severity desc, then file. diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index 9a34c83199..d3b2217b95 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -1,7 +1,14 @@ import { Octokit } from "@octokit/rest" import { promises as fs } from "node:fs" import { type VerdictEnvelope, VCS_EVENT } from "./verdict" -import { renderSummary, inlineComments, postedFindingIds, REVIEW_MARKER, verdictHeadline } from "./format" +import { + commentableLines, + inlineComments, + postedFindingIds, + renderSummary, + REVIEW_MARKER, + verdictHeadline, +} from "./format" /** * Post a verdict envelope to a GitHub pull request: an upserted summary comment @@ -56,16 +63,20 @@ export interface PostResult { postError?: string /** Inline comments not re-posted because the same finding is already on the PR. */ inlineSkippedAsPosted?: number - /** True when no review was submitted: nothing new to say and a previous - * non-blocking altimate review already exists (the summary comment was updated). */ + /** True when no review was submitted: nothing new inline, the verdict is not + * blocking, and this bot's latest review already carries the same headline + * (the summary comment was updated). */ reviewSkipped?: boolean } /** Headline of a review this bot posted (see verdictHeadline). */ const BOT_REVIEW_RE = /(Approved|Reviewed with comments|Changes requested)\b.*\((trivial|lite|full) tier/ -export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarget): Promise { - const octo = new Octokit({ auth: target.token }) +export async function postGitHubReview( + env: VerdictEnvelope, + target: GitHubTarget, + octo: Octokit = new Octokit({ auth: target.token }), +): Promise { const { owner, repo, prNumber } = target const result: PostResult = { inlineFellBack: false } @@ -80,13 +91,12 @@ export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarge per_page: 100, }) const prior = existing.find((c) => c.body?.includes(REVIEW_MARKER)) - if (prior) { - const r = await octo.rest.issues.updateComment({ owner, repo, comment_id: prior.id, body: summary }) - result.summaryCommentId = r.data.id - } else { - const r = await octo.rest.issues.createComment({ owner, repo, issue_number: prNumber, body: summary }) - result.summaryCommentId = r.data.id - } + const upserted = prior + ? await octo.rest.issues.updateComment({ owner, repo, comment_id: prior.id, body: summary }) + : await octo.rest.issues.createComment({ owner, repo, issue_number: prNumber, body: summary }) + result.summaryCommentId = upserted.data.id + // The account this token posts as: the summary comment's author. + const botLogin = upserted.data.user?.login // 2. Post a review. `env.verdict` arrives already mode-gated from // buildEnvelope (comment mode softened REQUEST_CHANGES → COMMENT upstream); @@ -98,25 +108,39 @@ export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarge // Rerun dedup: a finding already commented inline (same fingerprint, which // ignores line numbers) is not posted again on the next push. let posted = new Set() - let priorBotReview = false + let lastBotHeadline: string | undefined try { const [reviewComments, reviews] = await Promise.all([ octo.paginate(octo.rest.pulls.listReviewComments, { owner, repo, pull_number: prNumber, per_page: 100 }), octo.paginate(octo.rest.pulls.listReviews, { owner, repo, pull_number: prNumber, per_page: 100 }), ]) posted = postedFindingIds(reviewComments.map((c) => c.body)) - priorBotReview = reviews.some((r) => BOT_REVIEW_RE.test(r.body ?? "")) + // Reviews are listed oldest first; only this bot's own latest review counts. + const mine = botLogin + ? reviews.filter((r) => r.user?.login === botLogin && BOT_REVIEW_RE.test(r.body ?? "")) + : [] + lastBotHeadline = mine.at(-1)?.body?.trim() } catch { /* listing failed: post everything rather than nothing */ } - const comments = inlineComments(env, posted) - const withLine = env.findings.filter((f) => typeof f.startLine === "number").length - result.inlineSkippedAsPosted = withLine - comments.length - // Nothing new inline, not blocking, and the PR already has an altimate - // review: the updated summary comment says it all; another "Reviewed with - // comments" entry per push is noise. A blocking verdict always posts. - if (!comments.length && event === "COMMENT" && priorBotReview) { + // Inline comments only on lines GitHub accepts (inside the PR's diff hunks). + // If the file list can't be read, post everything and rely on the 422 fallback. + let commentable: Map> | undefined + try { + const files = await octo.paginate(octo.rest.pulls.listFiles, { owner, repo, pull_number: prNumber, per_page: 100 }) + commentable = new Map(files.map((f) => [f.filename, commentableLines(f.patch)])) + } catch { + /* fall back to the positioning retry below */ + } + const comments = inlineComments(env, posted, commentable) + result.inlineSkippedAsPosted = inlineComments(env, new Set(), commentable).length - comments.length + + // Nothing new inline, not blocking, and this bot's latest review already says + // the same thing: the updated summary comment covers it; another identical + // timeline entry per push is noise. A blocking verdict always posts, and a + // changed headline (e.g. after "Changes requested") posts a new review. + if (!comments.length && event === "COMMENT" && lastBotHeadline === reviewBody) { result.reviewSkipped = true return result } diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 98360039a7..a1be727539 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -1752,10 +1752,22 @@ const STYLE: Rule[] = [ "suggestion", "integer arithmetic on a date", "`date + 7` (bare int) isn't portable and is ambiguous (days? seconds?); use dateadd/interval.", - { added: /\b\w*(date|_at|_dt)\b\s*[+\-]\s*\d+\b/i, portability: { worksOn: ["postgres", "redshift", "snowflake", "duckdb", "oracle"] } }, + { added: /\b\w*(date|_dt)\b\s*[+\-]\s*\d+\b/i, portability: { worksOn: ["postgres", "redshift", "snowflake", "duckdb", "oracle"] } }, { add: "select order_date + 7" }, { add: "select dateadd(day, 7, order_date)" }, ), + // Split from date-plus-int: `timestamp + integer` has no operator on most + // engines that accept `date + integer` (Postgres, Snowflake, DuckDB). + r( + "timestamp-plus-int", + "sql_correctness", + "suggestion", + "integer arithmetic on a timestamp", + "`updated_at + 1` (bare int on a timestamp) fails on most warehouses and is ambiguous (days? seconds?); use dateadd/interval.", + { added: /\b\w*_at\b\s*[+\-]\s*\d+\b/i, portability: { worksOn: ["oracle"] } }, + { add: "select updated_at + 1" }, + { add: "select dateadd(day, 1, updated_at)" }, + ), ] const MISC: Rule[] = [ diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index c6a86b7925..f2d68f39ca 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -395,7 +395,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise forceTier: opts.forceTier, staleManifest, layout, - suppressPortability: config.portability === undefined ? dialectKnown : !config.portability, + suppressPortability: shouldSuppressPortability(config.portability, dialectKnown), scope: { baseRef: resolved?.ref ?? opts.base, baseSha: resolved?.sha, @@ -407,6 +407,13 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise }) } +/** Drop cross-engine portability advice? An explicit `portability` setting + * wins (even when the engine is unknown); unset, drop it once the engine is + * known (configured or detected from the manifest). */ +export function shouldSuppressPortability(portability: boolean | undefined, dialectKnown: boolean): boolean { + return portability === undefined ? dialectKnown : !portability +} + /** * The pull/merge request's title and description from the CI environment, so * the AI lane can check the change against its stated intent. GitHub: the diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index eadc169466..04ccdb6efe 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -1,7 +1,5 @@ import { describe, test, expect } from "bun:test" import { - anchorToDiff, - commentableLines, isCatalogPortability, isSuppressiblePortability, runReview, @@ -11,6 +9,7 @@ import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" import { makeFinding, type Finding } from "../../src/altimate/review/finding" import { + commentableLines, findingMarker, inlineComments, postedFindingIds, @@ -18,8 +17,11 @@ import { SUMMARY_BUDGET_CHARS, } from "../../src/altimate/review/format" import { buildEnvelope } from "../../src/altimate/review/verdict" +import { verdictHeadline } from "../../src/altimate/review/format" import { evaluateCatalog } from "../../src/altimate/review/rule-catalog" import { classifyPostOutcome } from "../../src/altimate/review/telemetry" +import { postGitHubReview } from "../../src/altimate/review/post-github" +import { shouldSuppressPortability } from "../../src/altimate/review/run" /** * The PR comment must stay readable: inline comments land on real lines of the @@ -68,13 +70,16 @@ describe("inline anchors", () => { expect([...commentableLines(d)].sort()).toEqual([1, 2]) }) - test("a line outside the diff moves to the summary instead of failing the batch", () => { + test("a line outside the diff is not posted inline but keeps its location in the envelope", () => { const inDiff = finding({ startLine: 3, endLine: 3, title: "m: a" }) const outside = finding({ startLine: 40, endLine: 40, title: "m: b" }) - const [a, b] = anchorToDiff([inDiff, outside], [{ path: "models/m.sql", status: "modified", diff: DIFF }]) - expect(a.startLine).toBe(3) - expect(b.startLine).toBeUndefined() - expect(b.endLine).toBeUndefined() + const env = buildEnvelope({ findings: [inDiff, outside], tier: "lite", mode: "comment" }) + const commentable = new Map([["models/m.sql", commentableLines(DIFF)]]) + expect(inlineComments(env, new Set(), commentable).map((c) => c.line)).toEqual([3]) + // Without diff information every line is attempted (the 422 fallback covers it). + expect(inlineComments(env).map((c) => c.line)).toEqual([3, 40]) + expect(env.findings.find((f) => f.title === "m: b")!.startLine).toBe(40) + expect(renderSummary(env, { maxChars: Infinity })).toContain("`models/m.sql:40`") }) test("engine lint on compiled SQL never anchors to the raw file", async () => { @@ -167,6 +172,67 @@ describe("summary grouping and budget", () => { expect(md).toContain("3 findings across 3 model(s)") }) + test("one rule with different messages per model is not merged into the first message", () => { + const fs = [ + ["a", "ILIKE"], + ["b", "QUALIFY"], + ["c", "IFF"], + ].map(([m, fn], i) => + finding({ + severity: "warning", + category: "sql_quality", + model: m, + file: `models/${m}.sql`, + startLine: i + 1, + title: `${m}: dialect-unsupported-function`, + body: `${fn} is not supported on the target dialect.`, + degraded: m === "c", + }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).not.toContain("findings across") + for (const fn of ["ILIKE", "QUALIFY", "IFF"]) expect(md).toContain(`${fn} is not supported`) + for (const loc of ["models/a.sql:1", "models/b.sql:2", "models/c.sql:3"]) expect(md).toContain(loc) + expect(md).toContain("_unverified_") + }) + + test("a grouped bullet keeps _unverified_ when any member is degraded", () => { + const fs = ["a", "b", "c"].map((m) => + finding({ model: m, file: `models/${m}.sql`, title: `${m}: new model has no uniqueness/grain test`, degraded: m === "b" }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).toContain("3 findings across 3 model(s)") + expect(md).toMatch(/findings across[^\n]*\n[^\n]*\n\s*test_coverage · _unverified_<\/sub>/) + }) + + test("a grouped body that names one model's column shows the names blanked", () => { + const fs = ["a", "b", "c"].map((m) => + finding({ + model: m, + file: `models/${m}.sql`, + title: `${m}: grain column lacks not_null`, + body: `Column \`${m}_id\` has no not_null test.`, + }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).toContain("3 findings across 3 model(s)") + expect(md).toContain("Column `…` has no not_null test.") + expect(md).not.toContain("`a_id`") + }) + + test("more than eight models: the posted comment lists eight, local output lists every finding", () => { + const ms = Array.from({ length: 11 }, (_, i) => `m${i}`) + const fs = ms.map((m) => finding({ model: m, file: `models/${m}.sql`, title: `${m}: new model has no uniqueness/grain test` })) + const env = buildEnvelope({ findings: fs, tier: "lite", mode: "comment" }) + const md = renderSummary(env) + expect(md).toContain("11 findings across 11 model(s)") + expect(md).toContain("(+3 more)") + expect(md).not.toContain("`m8`") + const local = renderSummary(env, { maxChars: Infinity }) + expect(local).not.toContain("findings across") + for (const m of ms) expect(local).toContain(`\`models/${m}.sql\``) + }) + test("the posted comment stays within budget, most severe first, and counts what it hides", () => { const many: Finding[] = [] for (let i = 0; i < 200; i++) @@ -278,3 +344,147 @@ describe("moved files", () => { expect(renderSummary(env)).toContain("`+schema`") }) }) + +describe("postGitHubReview", () => { + const BOT = "github-actions[bot]" + const target = { token: "t", owner: "o", repo: "r", prNumber: 7 } + const PATCH = DIFF.split("\n").slice(3).join("\n") + + function fakeOcto( + opts: { + reviews?: Array<{ body: string; user?: { login: string } }> + listFails?: boolean + createReview?: (call: number) => unknown + } = {}, + ) { + const reviewCalls: any[] = [] + const fail = async () => { + throw new Error("listing failed") + } + const octo = { + paginate: async (fn: (p: unknown) => unknown, p: unknown) => fn(p), + rest: { + issues: { + listComments: async () => [], + createComment: async () => ({ data: { id: 1, user: { login: BOT } } }), + updateComment: async () => ({ data: { id: 1, user: { login: BOT } } }), + }, + pulls: { + listReviewComments: opts.listFails ? fail : async () => [], + listReviews: opts.listFails ? fail : async () => opts.reviews ?? [], + listFiles: opts.listFails ? fail : async () => [{ filename: "models/m.sql", patch: PATCH }], + get: async () => ({ data: { head: { sha: "abc" } } }), + createReview: async (p: any) => { + reviewCalls.push(p) + const r = opts.createReview?.(reviewCalls.length) + return r ?? { data: { id: 9 } } + }, + }, + }, + } + return { octo: octo as any, reviewCalls } + } + + const noLine = buildEnvelope({ findings: [finding()], tier: "lite", mode: "comment" }) + + test("skips a new review when this bot's latest review has the same headline", async () => { + const { octo, reviewCalls } = fakeOcto({ + reviews: [ + { body: "🛑 Changes requested — 1 critical (lite tier)", user: { login: BOT } }, + { body: verdictHeadline(noLine), user: { login: BOT } }, + ], + }) + const r = await postGitHubReview(noLine, target, octo) + expect(r.reviewSkipped).toBe(true) + expect(reviewCalls.length).toBe(0) + }) + + test("posts a new review when this bot's latest review requested changes", async () => { + const { octo, reviewCalls } = fakeOcto({ + reviews: [ + { body: verdictHeadline(noLine), user: { login: BOT } }, + { body: "🛑 Changes requested — 1 critical (lite tier)", user: { login: BOT } }, + ], + }) + const r = await postGitHubReview(noLine, target, octo) + expect(r.reviewSkipped).toBeUndefined() + expect(reviewCalls.length).toBe(1) + expect(reviewCalls[0].event).toBe("COMMENT") + }) + + test("another account's review with the same headline does not count", async () => { + const { octo, reviewCalls } = fakeOcto({ reviews: [{ body: verdictHeadline(noLine), user: { login: "someone" } }] }) + const r = await postGitHubReview(noLine, target, octo) + expect(r.reviewSkipped).toBeUndefined() + expect(reviewCalls.length).toBe(1) + }) + + test("inline comments go only to lines inside the PR diff", async () => { + const env = buildEnvelope({ + findings: [finding({ startLine: 3, title: "m: a" }), finding({ startLine: 40, title: "m: b" })], + tier: "lite", + mode: "comment", + }) + const { octo, reviewCalls } = fakeOcto() + const r = await postGitHubReview(env, target, octo) + expect(reviewCalls[0].comments.map((c: { line: number }) => c.line)).toEqual([3]) + expect(r.inlineSkippedAsPosted).toBe(0) + }) + + test("when listing fails, everything is posted and nothing is skipped", async () => { + const env = buildEnvelope({ + findings: [finding({ startLine: 3, title: "m: a" }), finding({ startLine: 40, title: "m: b" })], + tier: "lite", + mode: "comment", + }) + const { octo, reviewCalls } = fakeOcto({ listFails: true, reviews: [{ body: verdictHeadline(env), user: { login: BOT } }] }) + const r = await postGitHubReview(env, target, octo) + expect(r.reviewSkipped).toBeUndefined() + expect(reviewCalls[0].comments.map((c: { line: number }) => c.line)).toEqual([3, 40]) + }) + + test("a positioning 422 retries the review without inline comments", async () => { + const env = buildEnvelope({ findings: [finding({ startLine: 3 })], tier: "lite", mode: "comment" }) + const { octo, reviewCalls } = fakeOcto({ + createReview: (call) => { + if (call === 1) + throw Object.assign(new Error("Unprocessable Entity"), { + status: 422, + response: { data: { errors: ["Line could not be resolved"] } }, + }) + return undefined + }, + }) + const r = await postGitHubReview(env, target, octo) + expect(reviewCalls.length).toBe(2) + expect(reviewCalls[0].comments.length).toBe(1) + expect(reviewCalls[1].comments).toBeUndefined() + expect(r.inlineFellBack).toBe(true) + expect(r.postError).toBeUndefined() + expect(r.reviewId).toBe(9) + }) +}) + +describe("portability settings", () => { + test("unset follows whether the engine is known; an explicit value always wins", () => { + expect(shouldSuppressPortability(undefined, true)).toBe(true) + expect(shouldSuppressPortability(undefined, false)).toBe(false) + expect(shouldSuppressPortability(false, false)).toBe(true) + expect(shouldSuppressPortability(true, true)).toBe(false) + }) + + test("integer arithmetic on a timestamp is kept on Postgres; on a date it is not", () => { + const rule = (sql: string, id: string) => + evaluateCatalog({ path: "models/m.sql", status: "added" }, sql, [sql], [], DEFAULT_RUBRIC).find( + (f) => (f.evidence?.result as { rule: string }).rule === id, + ) + const ts = rule("select updated_at + 1 from t", "timestamp-plus-int") + expect(ts).toBeDefined() + expect(rule("select updated_at + 1 from t", "date-plus-int")).toBeUndefined() + expect(isSuppressiblePortability(ts!, "postgres")).toBe(false) + expect(isSuppressiblePortability(ts!, "snowflake")).toBe(false) + const date = rule("select order_date + 7 from t", "date-plus-int") + expect(date).toBeDefined() + expect(isSuppressiblePortability(date!, "postgres")).toBe(true) + }) +}) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index f4cea11a31..dbe942fefe 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2162,6 +2162,87 @@ describe("orchestrate", () => { expect(env.verdict).not.toBe("REQUEST_CHANGES") }) + test("PII warnings without a compiled base never add up to a block", async () => { + // Three head PII columns, base not compilable: each is a warning of undecided + // exposure and must not count toward the warning-pattern threshold. + const files: ChangedFile[] = [ + { path: "models/marts/dim_customers.sql", status: "modified", diff: "+ email,\n+ ssn,\n+ phone_number\n" }, + ] + const PII = ["email", "ssn", "phone_number"] + const runner: ReviewRunner = { + ...fakeRunner({}), + async detectPii(sql: string) { + return { columns: PII.filter((c) => sql.includes(c)) } + }, + async columnLineage(sql) { + return ["customer_id", ...PII].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) + }, + async classifyPii(columns) { + return columns + .filter((c) => PII.includes(c)) + .map((column) => ({ column, classification: column === "email" ? "Email" : column === "ssn" ? "SSN" : "Phone", confidence: 0.95 })) + }, + } + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner, + getContent: content( + "select customer_id, email, ssn, phone_number from customers", + "select customer_id from {{ ref('customers') }}", + ), + }) + const pii = env.findings.filter((f) => f.category === "pii_exposure") + expect(pii.length).toBeGreaterThanOrEqual(3) + expect(pii.every((f) => f.severity === "warning" && f.confidence === "unknown")).toBe(true) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + }) + + test("a reindented PII line the base already exposed raises no regex twin", async () => { + // Whitespace-only edit of the `ssn` line in a mart: base and head expose the + // same columns, so neither the broad fallback nor `pii_into_mart` applies. + const files: ChangedFile[] = [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn\n" }] + const runner = (): ReviewRunner => ({ + ...fakeRunner({}), + async detectPii(sql: string) { + return { columns: sql.includes("ssn") ? ["ssn"] : [] } + }, + async columnLineage(sql) { + return ["customer_id", "ssn"].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) + }, + async classifyPii() { + return [] + }, + }) + const twin = (env: { findings: Array<{ evidence?: { tool?: string; result?: unknown } }> }) => + env.findings.some((f) => (f.evidence?.result as any)?.rule === "pii_into_mart") + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: runner(), + getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id,\n ssn\nfrom customers"), + }) + expect(twin(env)).toBe(false) + expect(env.findings.filter((f) => f.category === "pii_exposure" && f.severity === "critical")).toEqual([]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + // Control: the same head with a base that lacked `ssn` still gets the twin. + const added = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "+ ssn\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: runner(), + getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id\nfrom customers"), + }) + expect(twin(added)).toBe(true) + }) + test("case-variant PII detector output does not duplicate core diff-scoped finding", async () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ Email as EMAIL\n" }] const runner: ReviewRunner = { @@ -2276,8 +2357,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ ssn\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["ssn"] } + async detectPii(sql: string) { + return { columns: sql.includes("ssn") ? ["ssn"] : [] } }, async columnLineage(sql) { return sql.includes("ssn") @@ -2315,8 +2396,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ ssn\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["ssn"] } + async detectPii(sql: string) { + return { columns: sql.includes("ssn") ? ["ssn"] : [] } }, async columnLineage() { // Lineage resolves but derives zero output columns for every input. From 8003a3af9f700c3f94a373b8eae1d6dfc154e4c3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Mon, 23 Nov 2026 15:32:11 +0530 Subject: [PATCH 09/23] fix(review): reconcile both regex PII twins with the base, keep inline comments on patchless files - `select-pii-columns` now carries its matched columns on `evidence.result.columns` (new `capturesColumns` catalog flag) and is dropped when the compiled base already exposed every one of them - `pii_into_mart` emits one finding per added PII line, so a reindented base column no longer hides a genuinely new high-risk column on another line (shared fingerprint: dedupe keeps the most severe survivor) - without a compiled base (raw Jinja on the old side) both twins are reported as `warning` with `confidence: "unknown"`, like the other PII lanes, so they never block or count toward the warning-pattern threshold - `postGitHubReview` maps only files that have a `patch`; a file GitHub lists without one (large diff) has unknown hunks and its inline comments are attempted, relying on the existing 422 fallback Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/dbt-patterns.ts | 49 ++++---- .../opencode/src/altimate/review/format.ts | 6 +- .../src/altimate/review/orchestrate.ts | 21 +++- .../src/altimate/review/post-github.ts | 5 +- .../src/altimate/review/rule-catalog.ts | 25 +++- .../test/altimate/review-noise.test.ts | 25 +++- .../opencode/test/altimate/review.test.ts | 109 ++++++++++++++---- 7 files changed, 184 insertions(+), 56 deletions(-) diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index b9b99c1f8b..b48ba69a25 100644 --- a/packages/opencode/src/altimate/review/dbt-patterns.ts +++ b/packages/opencode/src/altimate/review/dbt-patterns.ts @@ -109,7 +109,7 @@ interface Ctx { inMartOrReporting: boolean } -type Detector = (c: Ctx) => Finding | null +type Detector = (c: Ctx) => Finding | Finding[] | null // A line that is dbt Jinja / config rather than SQL — e.g. the microbatch // `begin=(modules.datetime.datetime.now() - ...)` config kwarg, which is NOT a @@ -304,7 +304,7 @@ const PII_RE = /\b(email|ssn|social_security|phone_number|first_name|last_name|full_name|street_address|date_of_birth|dob|passport|credit_card)\b/i const detectPiiIntoMart: Detector = (c) => { if (!c.inMartOrReporting) return null - const hit = c.added.find((l) => { + const hits = c.added.filter((l) => { const s = stripComments(l) return ( PII_RE.test(s) && @@ -313,24 +313,29 @@ const detectPiiIntoMart: Detector = (c) => { ) ) }) - if (!hit) return null - // Highly-sensitive identifiers (SSN/financial/passport/DOB) into a broadly-read - // marts layer are critical; softer PII (email/phone/name) is a warning. - const sev: Severity = /\b(ssn|social_security|credit_card|passport|date_of_birth|dob)\b/i.test(hit) - ? "critical" - : "warning" - return makeFinding({ - severity: sev, - category: "pii_exposure", - title: `${c.model}: PII column added to a marts/reporting model`, - body: - "A PII-named column was added to a model in `marts/`/`reporting/`, widening PII exposure into a broadly-read " + - "layer. Confirm the column is needed here, that masking/access policy applies, and that the downstream grant is appropriate.", - file: c.file.path, - model: c.model, - confidence: "high", - evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line: hit.trim() } }, - ruleKey: "pii_exposure:into-mart", + // One finding per added PII line: each carries its own column in `result.line` + // so the orchestrator can suppress a base-exposed column without hiding a new + // one on another line. They share a fingerprint, so dedupe keeps the most + // severe survivor. + return hits.map((hit) => { + // Highly-sensitive identifiers (SSN/financial/passport/DOB) into a broadly-read + // marts layer are critical; softer PII (email/phone/name) is a warning. + const sev: Severity = /\b(ssn|social_security|credit_card|passport|date_of_birth|dob)\b/i.test(hit) + ? "critical" + : "warning" + return makeFinding({ + severity: sev, + category: "pii_exposure", + title: `${c.model}: PII column added to a marts/reporting model`, + body: + "A PII-named column was added to a model in `marts/`/`reporting/`, widening PII exposure into a broadly-read " + + "layer. Confirm the column is needed here, that masking/access policy applies, and that the downstream grant is appropriate.", + file: c.file.path, + model: c.model, + confidence: "high", + evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line: hit.trim() } }, + ruleKey: "pii_exposure:into-mart", + }) }) } @@ -780,8 +785,8 @@ export function detectModelPatterns(file: ChangedFile, newSql: string | undefine } const out: Finding[] = [] for (const d of MODEL_DETECTORS) { - const f = d(ctx) - if (f) out.push({ ...f, severity: clampSeverity(f.category, f.severity, f.confidence) }) + for (const f of [d(ctx) ?? []].flat()) + out.push({ ...f, severity: clampSeverity(f.category, f.severity, f.confidence) }) } // Declarative rule catalog (data-driven checks) complements the programmatic detectors. out.push(...evaluateCatalog(file, newSql, added, removed, rubric)) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 0d84881822..0d73434108 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -297,7 +297,9 @@ export function commentableLines(diff: string | undefined): Set { * Inline comments for findings with a line. With `commentable` (head-side * commentable lines per file, see `commentableLines`), only lines inside the * PR's diff hunks are kept: GitHub rejects the whole batch over one line - * outside the diff. The finding keeps its line in the envelope and summary. + * outside the diff. A file with no entry has unknown hunks (GitHub omits the + * patch for large diffs): its lines are attempted, and the 422 fallback covers a + * miss. The finding keeps its line in the envelope and summary. */ export function inlineComments( env: VerdictEnvelope, @@ -309,7 +311,7 @@ export function inlineComments( (f) => typeof f.startLine === "number" && !alreadyPosted.has(f.id) && - (!commentable || !!commentable.get(f.file)?.has(f.startLine)), + (!commentable?.has(f.file) || commentable.get(f.file)!.has(f.startLine)), ) .map((f) => ({ path: f.file, diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 3fd1a019a0..3804ce42a6 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1434,9 +1434,14 @@ export async function runReview(input: OrchestrateInput): Promise basePii.has(c))) return false + // Otherwise suppress only when a precise detector actually EMITTED a PII + // finding for the file (so the exposure is reported by the better source, + // not silently dropped). if (diffScopedPiiFindingFiles.has(f.file)) return false return true } @@ -1463,6 +1468,16 @@ export async function runReview(input: OrchestrateInput): Promise> | undefined try { const files = await octo.paginate(octo.rest.pulls.listFiles, { owner, repo, pull_number: prNumber, per_page: 100 }) - commentable = new Map(files.map((f) => [f.filename, commentableLines(f.patch)])) + commentable = new Map(files.filter((f) => f.patch).map((f) => [f.filename, commentableLines(f.patch)])) } catch { /* fall back to the positioning retry below */ } diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index a1be727539..dc2f444db4 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -50,6 +50,9 @@ export interface Rule { * error there and is kept). Omit `worksOn` when support isn't established. */ portability?: { worksOn?: string[] } + /** `added`'s first capture group is a column name: matched columns are kept on + * `evidence.result.columns` so the orchestrator can reconcile them per column. */ + capturesColumns?: boolean example: RuleExample counter?: RuleExample } @@ -107,6 +110,18 @@ export function ruleMatches(rule: Rule, input: RuleInput): boolean { return relevant } +/** Distinct lowercased first-group captures of `rule.added` over the added lines. */ +function capturedColumns(rule: Rule, added: string[]): string[] { + const cols = new Set() + for (const l of added) { + const s = stripComments(l) + if (rule.unless?.test(s)) continue + const col = rule.added?.exec(s)?.[1] + if (col) cols.add(col.toLowerCase()) + } + return [...cols] +} + /** Evaluate the catalog against a changed file. */ export function evaluateCatalog( file: ChangedFile, @@ -130,7 +145,11 @@ export function evaluateCatalog( confidence: "high", evidence: { tool: "rule-catalog", - result: rule.portability ? { rule: rule.id, portability: true, worksOn: rule.portability.worksOn } : { rule: rule.id }, + result: rule.portability + ? { rule: rule.id, portability: true, worksOn: rule.portability.worksOn } + : rule.capturesColumns + ? { rule: rule.id, columns: capturedColumns(rule, added) } + : { rule: rule.id }, }, ruleKey: `${rule.category}:${rule.id}`, }) @@ -176,7 +195,7 @@ const r = ( severity: Severity, title: string, body: string, - match: Pick, + match: Pick, example: RuleExample, counter?: RuleExample, ): Rule => ({ id, category, severity, title, body, ...match, example, counter }) @@ -1202,7 +1221,7 @@ const SECURITY_PII: Rule[] = [ "warning", "PII columns selected", "Email/SSN/phone/DOB pulled into a model widens PII exposure; confirm it's needed and masked.", - { added: /^\s*[\w.]*\b(ssn|social_security|email|phone_number|date_of_birth|passport)\b/i }, + { added: /^\s*[\w.]*\b(ssn|social_security|email|phone_number|date_of_birth|passport)\b/i, capturesColumns: true }, { add: " c.ssn," }, { add: " c.country," }, ), diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 04ccdb6efe..7a3d6d8024 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -354,6 +354,7 @@ describe("postGitHubReview", () => { opts: { reviews?: Array<{ body: string; user?: { login: string } }> listFails?: boolean + files?: Array<{ filename: string; patch?: string }> createReview?: (call: number) => unknown } = {}, ) { @@ -372,7 +373,7 @@ describe("postGitHubReview", () => { pulls: { listReviewComments: opts.listFails ? fail : async () => [], listReviews: opts.listFails ? fail : async () => opts.reviews ?? [], - listFiles: opts.listFails ? fail : async () => [{ filename: "models/m.sql", patch: PATCH }], + listFiles: opts.listFails ? fail : async () => opts.files ?? [{ filename: "models/m.sql", patch: PATCH }], get: async () => ({ data: { head: { sha: "abc" } } }), createReview: async (p: any) => { reviewCalls.push(p) @@ -431,6 +432,28 @@ describe("postGitHubReview", () => { expect(r.inlineSkippedAsPosted).toBe(0) }) + test("a file GitHub lists without a patch keeps its inline comments", async () => { + // GitHub omits `patch` for large diffs: the hunks are unknown, so the lines + // are attempted (the 422 fallback covers a miss) instead of all dropped. + const env = buildEnvelope({ + findings: [ + finding({ startLine: 3, title: "m: a" }), + finding({ startLine: 40, title: "m: b" }), + finding({ file: "models/big.sql", startLine: 900, title: "big: c" }), + ], + tier: "lite", + mode: "comment", + }) + const { octo, reviewCalls } = fakeOcto({ + files: [{ filename: "models/m.sql", patch: PATCH }, { filename: "models/big.sql" }], + }) + await postGitHubReview(env, target, octo) + expect(reviewCalls[0].comments.map((c: { path: string; line: number }) => `${c.path}:${c.line}`)).toEqual([ + "models/m.sql:3", + "models/big.sql:900", + ]) + }) + test("when listing fails, everything is posted and nothing is skipped", async () => { const env = buildEnvelope({ findings: [finding({ startLine: 3, title: "m: a" }), finding({ startLine: 40, title: "m: b" })], diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index dbe942fefe..2a6abb9eb6 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2200,47 +2200,110 @@ describe("orchestrate", () => { expect(env.verdict).not.toBe("REQUEST_CHANGES") }) + // Runner whose base/head PII is exactly the listed columns present in the SQL. + const piiRunner = (cols: string[], classify: ReviewRunner["classifyPii"] = async () => []): ReviewRunner => ({ + ...fakeRunner({}), + async detectPii(sql: string) { + return { columns: cols.filter((c) => sql.includes(c)) } + }, + async columnLineage(sql) { + return ["customer_id", ...cols].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) + }, + classifyPii: classify, + }) + const isTwin = (f: { evidence?: { tool?: string; result?: unknown } }) => + ["pii_into_mart", "select-pii-columns"].includes((f.evidence?.result as any)?.rule) + const MARTS = ["models/marts/m1.sql", "models/marts/m2.sql", "models/marts/m3.sql"] + test("a reindented PII line the base already exposed raises no regex twin", async () => { - // Whitespace-only edit of the `ssn` line in a mart: base and head expose the - // same columns, so neither the broad fallback nor `pii_into_mart` applies. - const files: ChangedFile[] = [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn\n" }] - const runner = (): ReviewRunner => ({ - ...fakeRunner({}), - async detectPii(sql: string) { - return { columns: sql.includes("ssn") ? ["ssn"] : [] } - }, - async columnLineage(sql) { - return ["customer_id", "ssn"].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) - }, - async classifyPii() { - return [] - }, - }) - const twin = (env: { findings: Array<{ evidence?: { tool?: string; result?: unknown } }> }) => - env.findings.some((f) => (f.evidence?.result as any)?.rule === "pii_into_mart") + // Whitespace-only edit of the `ssn` line in three marts: base and head expose + // the same columns, so neither the broad fallback nor either regex twin + // applies, and three of them do not add up to a block. + const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: "- ssn\n+ ssn\n" })) for (const reviewers of [[], ["dbt_patterns"]]) { const env = await runReview({ changedFiles: files, config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, rubric: DEFAULT_RUBRIC, mode: "gate", - runner: runner(), + runner: piiRunner(["ssn"]), getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id,\n ssn\nfrom customers"), }) - expect(twin(env)).toBe(false) - expect(env.findings.filter((f) => f.category === "pii_exposure" && f.severity === "critical")).toEqual([]) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) expect(env.verdict).not.toBe("REQUEST_CHANGES") } - // Control: the same head with a base that lacked `ssn` still gets the twin. + // Control: the same head with a base that lacked `ssn` still gets both twins. const added = await runReview({ changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "+ ssn\n" }], config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, rubric: DEFAULT_RUBRIC, mode: "gate", - runner: runner(), + runner: piiRunner(["ssn"]), getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id\nfrom customers"), }) - expect(twin(added)).toBe(true) + const rules = added.findings.filter(isTwin).map((f) => (f.evidence?.result as any)?.rule) + expect(rules.sort()).toEqual(["pii_into_mart", "select-pii-columns"]) + }) + + test("a new PII column next to a reindented base one keeps its own critical twin", async () => { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn,\n+ passport\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn", "passport"]), + getContent: content( + "select customer_id,\n ssn,\n passport\nfrom customers", + "select customer_id,\n ssn\nfrom customers", + ), + }) + const twin = env.findings.find((f) => (f.evidence?.result as any)?.rule === "pii_into_mart") + expect(twin?.severity).toBe("critical") + expect((twin?.evidence?.result as any)?.line).toContain("passport") + // `select-pii-columns` names a column the base lacked, so it is kept too. + const catalog = env.findings.find((f) => (f.evidence?.result as any)?.rule === "select-pii-columns") + expect((catalog?.evidence?.result as any)?.columns).toEqual(["ssn", "passport"]) + }) + + test("without a compiled base the regex PII twins are unknown-confidence warnings that never block", async () => { + // Raw Jinja on both sides and no compiled artifacts: whether `ssn` is new + // cannot be decided, so neither twin is critical or counts toward a block. + const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: "- ssn\n+ ssn\n" })) + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content( + "select customer_id,\n ssn\nfrom {{ ref('customers') }}", + "select customer_id,\n ssn\nfrom {{ ref('customers') }}", + ), + }) + const twins = env.findings.filter(isTwin) + if (reviewers.length) expect(twins.length).toBeGreaterThan(0) + expect(twins.every((f) => f.severity === "warning" && f.confidence === "unknown")).toBe(true) + expect(env.findings.filter((f) => f.severity === "critical")).toEqual([]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + }) + + test("the broad PII fallback without a compiled base is an unknown-confidence warning", async () => { + const env = await runReview({ + changedFiles: [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ ssn\n" }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"], async () => { + throw new Error("classifier unavailable") + }), + getContent: content("select customer_id, ssn from customers", "select customer_id from {{ ref('customers') }}"), + }) + const fallback = env.findings.filter((f) => f.evidence?.tool === "schema.detect_pii") + expect(fallback.length).toBe(1) + expect(fallback[0].severity).toBe("warning") + expect(fallback[0].confidence).toBe("unknown") }) test("case-variant PII detector output does not duplicate core diff-scoped finding", async () => { From b8022af95ff788a3ba66a0dc3f139d2e35073471 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Mon, 23 Nov 2026 18:42:56 +0530 Subject: [PATCH 10/23] fix(review): reconcile PII twins by output alias and every token, keep verified inline comments on a 422 - `pii_into_mart` and `select-pii-columns` now pair each PII token with its select item's `AS` alias (`selectItemColumns`) and suppress it when the base exposes either the alias or the source column, since `detectPii` reports output aliases (`c.ssn as tax_ref` -> `tax_ref`) - both twins also drop a line whose comment/whitespace-normalised text is among the file's removed lines (pure reindent), independent of base PII detection - both twins collect every PII token on a line, not just the first: `ssn, passport` with a base-exposed `ssn` still reports `passport`; `pii_into_mart` emits one finding per token (shared fingerprint, so dedupe keeps the most severe) - `postGitHubReview`: on a positioning 422, retry once with only the comments on files whose hunks are known before falling back to an event-only review - the test runner's `detectPii`/`columnLineage` fakes return output aliases like the real runner; the raw-Jinja test uses an added line, since a pure reindent is now dropped outright Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/dbt-patterns.ts | 16 +-- .../src/altimate/review/orchestrate.ts | 63 +++++---- .../src/altimate/review/post-github.ts | 23 +++- .../src/altimate/review/rule-catalog.ts | 91 +++++++++++-- .../test/altimate/review-noise.test.ts | 44 +++++++ .../opencode/test/altimate/review.test.ts | 120 +++++++++++++++++- 6 files changed, 308 insertions(+), 49 deletions(-) diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index b48ba69a25..c05523fe1f 100644 --- a/packages/opencode/src/altimate/review/dbt-patterns.ts +++ b/packages/opencode/src/altimate/review/dbt-patterns.ts @@ -4,7 +4,7 @@ import { Log } from "@/altimate/util/log" import { type Finding, type Severity, type ReviewCategory, makeFinding } from "./finding" import { type ChangedFile, fileKind } from "./diff-filter" import { type Rubric, clampSeverity, exclusionReason } from "./rubric" -import { evaluateCatalog } from "./rule-catalog" +import { evaluateCatalog, selectItemColumns } from "./rule-catalog" /** Local copy to avoid a cycle with orchestrate.ts. */ function modelNameFromPath(p: string): string { @@ -313,14 +313,14 @@ const detectPiiIntoMart: Detector = (c) => { ) ) }) - // One finding per added PII line: each carries its own column in `result.line` - // so the orchestrator can suppress a base-exposed column without hiding a new - // one on another line. They share a fingerprint, so dedupe keeps the most - // severe survivor. - return hits.map((hit) => { + // One finding per PII column token on each added line (`ssn, passport` is two): + // each carries its column, `AS` alias and line in `result` so the orchestrator + // can suppress a base-exposed column without hiding a new one beside it. They + // share a fingerprint, so dedupe keeps the most severe survivor. + return hits.flatMap((hit) => selectItemColumns(hit, PII_RE)).map(({ column, alias, line }) => { // Highly-sensitive identifiers (SSN/financial/passport/DOB) into a broadly-read // marts layer are critical; softer PII (email/phone/name) is a warning. - const sev: Severity = /\b(ssn|social_security|credit_card|passport|date_of_birth|dob)\b/i.test(hit) + const sev: Severity = /^(ssn|social_security|credit_card|passport|date_of_birth|dob)$/i.test(column) ? "critical" : "warning" return makeFinding({ @@ -333,7 +333,7 @@ const detectPiiIntoMart: Detector = (c) => { file: c.file.path, model: c.model, confidence: "high", - evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line: hit.trim() } }, + evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line, column, alias } }, ruleKey: "pii_exposure:into-mart", }) }) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 3804ce42a6..1ceb9807f0 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -14,6 +14,7 @@ import { type Rubric, exclusionReason, clampSeverity } from "./rubric" import { type ReviewConfig } from "./config" import { type ReviewMode, type ReviewScope, type VerdictEnvelope, buildEnvelope, signEnvelope } from "./verdict" import { detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" +import { type SelectItemColumn, normalizeSelectLine } from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" /** @@ -865,11 +866,6 @@ const STRUCTURAL_CATEGORY: Record = { const PII_LOW_RISK_CLASS = /^(name|address)$/i const PII_LOW_RISK_MIN_CONFIDENCE = 0.9 const PII_DEFAULT_MIN_CONFIDENCE = 0.7 -// Column-name tokens the regex PII twins (`pii_into_mart`) key off — used to -// recover which column a coarse regex finding flagged so suppression can be -// column-aware (suppress only when core actually classified THAT column). -const PII_TOKEN_RE = - /\b(email|ssn|social_security|phone_number|first_name|last_name|full_name|street_address|date_of_birth|dob|passport|credit_card)\b/i async function structuralChangeLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.structuralDiff) return [] @@ -1405,6 +1401,25 @@ export async function runReview(input: OrchestrateInput): Promise>() + const isReindented = (file: string, line: string) => { + let removed = removedLinesByFile.get(file) + if (!removed) { + removed = new Set(splitDiff(ctxByPath.get(file)?.file.diff).removed.map(normalizeSelectLine).filter(Boolean)) + removedLinesByFile.set(file, removed) + } + const normalized = normalizeSelectLine(line) + return !!normalized && removed.has(normalized) + } + // `detectPii` reports OUTPUT names (`c.ssn as tax_ref` → `tax_ref`): a column is + // already exposed when the base output holds its alias, or the source column + // itself (a rename of an exposed column re-exposes nothing new). + const isBaseExposed = (file: string, item: { column: string; alias?: string }) => { + const basePii = basePiiColumnsByFile.get(file) + return !!basePii && (basePii.has(item.column) || (!!item.alias && basePii.has(item.alias))) + } const merged = flat.filter((f) => { const tool = f.evidence?.tool const fallbackRule = String((f.evidence?.result as any)?.rule ?? "").replace(/_/g, "-") @@ -1420,25 +1435,29 @@ export async function runReview(input: OrchestrateInput): Promise basePii.has(c))) return false + // `select-pii-columns` keeps every matched column with its alias and line: + // drop it when each one is a reindented base line or already base-exposed. + const items = result.items ?? [] + if (items.length && items.every((i) => isReindented(f.file, i.line) || isBaseExposed(f.file, i))) return false // Otherwise suppress only when a precise detector actually EMITTED a PII // finding for the file (so the exposure is reported by the better source, // not silently dropped). diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index fe210cb466..fb3010d8c1 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -57,7 +57,7 @@ export async function resolveGitHubTarget(): Promise { export interface PostResult { summaryCommentId?: number reviewId?: number - /** True when inline comments were dropped due to a 422 positioning error. */ + /** True when some or all inline comments were dropped due to a 422 positioning error. */ inlineFellBack: boolean /** Set when the review event could not be posted for a non-positioning reason. */ postError?: string @@ -180,6 +180,27 @@ export async function postGitHubReview( const isPositioning = status === 422 && /(position|\bline\b|diff|commit)/.test(detail) result.inlineFellBack = isPositioning result.postError = isPositioning ? undefined : `${status ?? ""} ${e?.message ?? e}`.trim() + // Lines on files without a known hunk (no `patch`) are the likely cause of a + // positioning 422: retry once with only the comments on verified files + // before dropping every inline comment. + const verified = isPositioning && commentable ? comments.filter((c) => commentable!.has(c.path)) : [] + if (verified.length && verified.length < comments.length) { + try { + const r = await octo.rest.pulls.createReview({ + owner, + repo, + pull_number: prNumber, + commit_id: commitId, + event, + body: reviewBody, + comments: verified, + }) + result.reviewId = r.data.id + return result + } catch { + /* fall through to the event-only review */ + } + } try { const r = await octo.rest.pulls.createReview({ owner, diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index dc2f444db4..4d3ef71a89 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -50,9 +50,11 @@ export interface Rule { * error there and is kept). Omit `worksOn` when support isn't established. */ portability?: { worksOn?: string[] } - /** `added`'s first capture group is a column name: matched columns are kept on - * `evidence.result.columns` so the orchestrator can reconcile them per column. */ - capturesColumns?: boolean + /** Column-token pattern (first capture group is the column name) collected on + * every line `added` matches — every token, not just the first — and kept on + * `evidence.result.columns` / `items` so the orchestrator can reconcile each + * column (and its `AS` alias) with the base. */ + capturesColumns?: RegExp example: RuleExample counter?: RuleExample } @@ -110,16 +112,75 @@ export function ruleMatches(rule: Rule, input: RuleInput): boolean { return relevant } -/** Distinct lowercased first-group captures of `rule.added` over the added lines. */ -function capturedColumns(rule: Rule, added: string[]): string[] { - const cols = new Set() +/** A column token found in a select item, with the item's `AS` alias (the + * output name) when it has one, and the trimmed line it came from. */ +export interface SelectItemColumn { + column: string + alias?: string + line: string +} + +/** Split on commas outside parentheses (one entry per select item). */ +function topLevelItems(s: string): string[] { + const items: string[] = [] + let depth = 0 + let start = 0 + for (let i = 0; i < s.length; i++) { + if (s[i] === "(") depth++ + else if (s[i] === ")") depth = Math.max(0, depth - 1) + else if (s[i] === "," && depth === 0) { + items.push(s.slice(start, i)) + start = i + 1 + } + } + items.push(s.slice(start)) + return items +} + +/** + * Every column token `tokenRe` finds on a select line (all of them, not just + * the first), each paired with its item's `AS` alias. The pair matters because + * PII detection reports OUTPUT names: `c.ssn as tax_ref` exposes `tax_ref`. + */ +export function selectItemColumns(line: string, tokenRe: RegExp): SelectItemColumn[] { + const global = new RegExp(tokenRe.source, tokenRe.flags.includes("g") ? tokenRe.flags : `${tokenRe.flags}g`) + const out: SelectItemColumn[] = [] + const seen = new Set() + for (const item of topLevelItems(stripComments(line))) { + // The item's alias is its first `AS` outside parentheses (`cast(x as int) as y` + // → `y`), which also holds when the line runs on into `from …`. + let flat = item + while (/\([^()]*\)/.test(flat)) flat = flat.replace(/\([^()]*\)/g, " ") + const alias = /\bas\s+["`]?([A-Za-z_][\w$]*)/i.exec(flat)?.[1]?.toLowerCase() + for (const m of item.matchAll(global)) { + const column = m[1]?.toLowerCase() + if (!column || seen.has(`${column} ${alias ?? ""}`)) continue + seen.add(`${column} ${alias ?? ""}`) + out.push({ column, alias, line: line.trim() }) + } + } + return out +} + +/** A diff line with comments and whitespace normalised (and a leading/trailing + * select-list comma dropped), so a reindented line compares equal to its base. */ +export function normalizeSelectLine(line: string): string { + return stripComments(line) + .replace(/\s+/g, " ") + .replace(/\s*([(),])\s*/g, "$1") + .trim() + .replace(/^,|,$/g, "") +} + +/** Column tokens (with aliases) of `rule.capturesColumns` over the added lines `rule.added` matches. */ +function capturedColumns(rule: Rule, added: string[]): SelectItemColumn[] { + const out: SelectItemColumn[] = [] for (const l of added) { const s = stripComments(l) - if (rule.unless?.test(s)) continue - const col = rule.added?.exec(s)?.[1] - if (col) cols.add(col.toLowerCase()) + if (!rule.capturesColumns || !rule.added?.test(s) || rule.unless?.test(s)) continue + out.push(...selectItemColumns(l, rule.capturesColumns)) } - return [...cols] + return out } /** Evaluate the catalog against a changed file. */ @@ -148,7 +209,10 @@ export function evaluateCatalog( result: rule.portability ? { rule: rule.id, portability: true, worksOn: rule.portability.worksOn } : rule.capturesColumns - ? { rule: rule.id, columns: capturedColumns(rule, added) } + ? (() => { + const items = capturedColumns(rule, added) + return { rule: rule.id, columns: [...new Set(items.map((i) => i.column))], items } + })() : { rule: rule.id }, }, ruleKey: `${rule.category}:${rule.id}`, @@ -1221,7 +1285,10 @@ const SECURITY_PII: Rule[] = [ "warning", "PII columns selected", "Email/SSN/phone/DOB pulled into a model widens PII exposure; confirm it's needed and masked.", - { added: /^\s*[\w.]*\b(ssn|social_security|email|phone_number|date_of_birth|passport)\b/i, capturesColumns: true }, + { + added: /^\s*[\w.]*\b(ssn|social_security|email|phone_number|date_of_birth|passport)\b/i, + capturesColumns: /\b(ssn|social_security|email|phone_number|date_of_birth|passport)\b/i, + }, { add: " c.ssn," }, { add: " c.country," }, ), diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 7a3d6d8024..fe111bc0a3 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -486,6 +486,50 @@ describe("postGitHubReview", () => { expect(r.postError).toBeUndefined() expect(r.reviewId).toBe(9) }) + + test("a positioning 422 with a patchless file retries with the verified comments first", async () => { + const env = buildEnvelope({ + findings: [ + finding({ file: "models/known.sql", startLine: 3, title: "known: a" }), + finding({ file: "models/big.sql", startLine: 900, title: "big: b" }), + ], + tier: "lite", + mode: "comment", + }) + const positioning422 = Object.assign(new Error("Unprocessable Entity"), { + status: 422, + response: { data: { errors: ["Line could not be resolved"] } }, + }) + const where = (call: any) => (call.comments ?? []).map((c: { path: string; line: number }) => `${c.path}:${c.line}`) + const files = [{ filename: "models/known.sql", patch: PATCH }, { filename: "models/big.sql" }] + + const kept = fakeOcto({ + files, + createReview: (call) => { + if (call === 1) throw positioning422 + return undefined + }, + }) + const r = await postGitHubReview(env, target, kept.octo) + expect(kept.reviewCalls.map(where)).toEqual([["models/known.sql:3", "models/big.sql:900"], ["models/known.sql:3"]]) + expect(r.inlineFellBack).toBe(true) + expect(r.postError).toBeUndefined() + expect(r.reviewId).toBe(9) + + // The verified-only retry also failing falls back to an event-only review. + const none = fakeOcto({ + files, + createReview: (call) => { + if (call <= 2) throw positioning422 + return undefined + }, + }) + const r2 = await postGitHubReview(env, target, none.octo) + expect(none.reviewCalls.length).toBe(3) + expect(none.reviewCalls[2].comments).toBeUndefined() + expect(r2.inlineFellBack).toBe(true) + expect(r2.reviewId).toBe(9) + }) }) describe("portability settings", () => { diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 2a6abb9eb6..f5ef7843be 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2200,14 +2200,24 @@ describe("orchestrate", () => { expect(env.verdict).not.toBe("REQUEST_CHANGES") }) - // Runner whose base/head PII is exactly the listed columns present in the SQL. + // Output names of `col` in `sql`, like the real engine: `c.ssn as tax_ref` + // exposes `tax_ref` (runner.ts prefers query_targets), plain `ssn` exposes `ssn`. + const outputNames = (sql: string, col: string): string[] => { + const aliases = [...sql.matchAll(new RegExp(`\\b${col}\\s+as\\s+(\\w+)`, "gi"))].map((m) => m[1]) + if (aliases.length) return aliases + return new RegExp(`\\b${col}\\b`, "i").test(sql) ? [col] : [] + } + // Runner whose base/head PII is exactly the listed columns present in the SQL, + // reported by output name (alias) as `runner.detectPii` does. const piiRunner = (cols: string[], classify: ReviewRunner["classifyPii"] = async () => []): ReviewRunner => ({ ...fakeRunner({}), async detectPii(sql: string) { - return { columns: cols.filter((c) => sql.includes(c)) } + return { columns: cols.flatMap((c) => outputNames(sql, c)) } }, async columnLineage(sql) { - return ["customer_id", ...cols].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) + return ["customer_id", ...cols].flatMap((c) => + outputNames(sql, c).map((target) => ({ source: `customers.${c}`, target })), + ) }, classifyPii: classify, }) @@ -2265,10 +2275,108 @@ describe("orchestrate", () => { expect((catalog?.evidence?.result as any)?.columns).toEqual(["ssn", "passport"]) }) + const ALIASED_BASE = "select c.customer_id,\n c.email as contact,\n c.ssn as tax_ref\nfrom customers c" + + test("a reindented aliased PII column in three marts raises no twin and does not block", async () => { + // detectPii reports output aliases (`contact`, `tax_ref`), not the source + // tokens the regex twins match (`email`, `ssn`): both must be reconciled. + const cases = [ + { line: "c.ssn as tax_ref", head: ALIASED_BASE.replace(" c.ssn", " c.ssn") }, + { line: "c.email as contact,", head: ALIASED_BASE.replace(" c.email", " c.email") }, + ] + for (const { line, head } of cases) { + const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: `- ${line}\n+ ${line}\n` })) + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["email", "ssn"]), + getContent: content(head, ALIASED_BASE), + }) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + } + }) + + test("an aliased PII line whose alias the base exposes raises no twin even when not a pure reindent", async () => { + // Table alias renamed `c` → `cust`: the line text changes, but the output + // `tax_ref` (built from `ssn`) was already exposed by the base. + const head = ALIASED_BASE.replace(/\bc\./g, "cust.").replace("customers c", "customers cust") + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- c.ssn as tax_ref\n+ cust.ssn as tax_ref\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["email", "ssn"]), + getContent: content(head, ALIASED_BASE), + }) + expect(env.findings.filter(isTwin)).toEqual([]) + // Control: the same aliased line added to a base without it keeps both twins. + const added = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "+ c.ssn as tax_ref\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["email", "ssn"]), + getContent: content(ALIASED_BASE, "select c.customer_id,\n c.email as contact\nfrom customers c"), + }) + const twins = added.findings.filter(isTwin) + expect(twins.map((f) => (f.evidence?.result as any)?.rule).sort()).toEqual(["pii_into_mart", "select-pii-columns"]) + expect(twins.find((f) => (f.evidence?.result as any)?.rule === "pii_into_mart")?.severity).toBe("critical") + }) + + test("a pure reindent drops the regex twins even when base PII detection misses the column", async () => { + // detectPii finds nothing on either side: only the reindent check applies. + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner([]), + getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id,\n ssn\nfrom customers"), + }) + expect(env.findings.filter(isTwin)).toEqual([]) + }) + + test("a new PII column on the same line as a base-exposed one keeps its twins", async () => { + // `- ssn` / `+ ssn, passport`: `ssn` is base-exposed, `passport` is new and + // must not hide behind the first token on the line. + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn, passport\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn", "passport"]), + getContent: content("select customer_id,\n ssn, passport\nfrom customers", "select customer_id,\n ssn\nfrom customers"), + }) + const intoMart = env.findings.filter((f) => (f.evidence?.result as any)?.rule === "pii_into_mart") + expect(intoMart.map((f) => (f.evidence?.result as any)?.column)).toEqual(["passport"]) + expect(intoMart[0].severity).toBe("critical") + const catalog = env.findings.find((f) => (f.evidence?.result as any)?.rule === "select-pii-columns") + expect((catalog?.evidence?.result as any)?.columns).toEqual(["ssn", "passport"]) + // Both tokens already in the base: nothing is reported. + const both = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn,\n- passport\n+ ssn, passport\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn", "passport"]), + getContent: content( + "select customer_id,\n ssn, passport\nfrom customers", + "select customer_id,\n ssn,\n passport\nfrom customers", + ), + }) + expect(both.findings.filter(isTwin)).toEqual([]) + }) + test("without a compiled base the regex PII twins are unknown-confidence warnings that never block", async () => { - // Raw Jinja on both sides and no compiled artifacts: whether `ssn` is new - // cannot be decided, so neither twin is critical or counts toward a block. - const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: "- ssn\n+ ssn\n" })) + // Raw Jinja on both sides and no compiled artifacts: whether an added `ssn` + // line is new cannot be decided (it is not a reindent of a removed line), so + // neither twin is critical or counts toward a block. + const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: "+ ssn\n" })) for (const reviewers of [[], ["dbt_patterns"]]) { const env = await runReview({ changedFiles: files, From ff68fc9797c776b6228e83afe1742a9049678685 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 12 Nov 2026 17:01:15 +0530 Subject: [PATCH 11/23] fix(review): verdict trust: only the engine blocks, policy from the base branch, `allowForceTier` - Findings carry `origin: engine | catalog | ai` (from `evidence.tool`; unknown tools count as catalog). Only engine findings count toward REQUEST_CHANGES, matching the documented promise; a pattern rule can be opted in by id via `rubric.blockingRules`. The AI lane never blocks. - `.altimate/review.yml` is read from the merge-base commit, so a PR cannot relax the rules it is judged by. Settings the PR changes are listed in the comment and envelope (`policy.changedInPr`) and take effect after merge. The applied policy's source and hash are signed into the envelope. - `allowForceTier: false` in the base policy rejects `--force-tier` (forced runs were already recorded as `tier_forced` in `review_run`). Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 16 ++ .../opencode/src/altimate/review/config.ts | 100 ++++++++++ .../opencode/src/altimate/review/finding.ts | 27 +++ .../opencode/src/altimate/review/format.ts | 6 + packages/opencode/src/altimate/review/git.ts | 10 + .../src/altimate/review/orchestrate.ts | 3 + .../opencode/src/altimate/review/rubric.ts | 6 + packages/opencode/src/altimate/review/run.ts | 59 ++++-- .../opencode/src/altimate/review/verdict.ts | 39 +++- .../altimate/review-verdict-trust.test.ts | 174 ++++++++++++++++++ .../opencode/test/altimate/review.test.ts | 8 +- .../skill/release-v0.8.1-adversarial.test.ts | 2 + 12 files changed, 420 insertions(+), 30 deletions(-) create mode 100644 packages/opencode/test/altimate/review-verdict-trust.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index a1375cb2a2..caa41b4a7d 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -276,9 +276,11 @@ exclude: riskTierPathTokens: # OFF by default — see "Risk-tier path tokens" below finops: [preset:finops] # promote any FinOps-named path to `full` tier pii: [ssn, email, phone] # or supply your own case-insensitive tokens +allowForceTier: true # set false in gate CI: --force-tier is then rejected rubric: blockOn: [lineage_breakage, contract_violation, pii_exposure, semantic_change] warningPatternThreshold: 3 + blockingRules: [] # catalog rule ids allowed to block (default: engine only) thresholds: warehouseCostMinRows: 1000000 exclusions: @@ -286,6 +288,20 @@ rubric: skipNonProdModels: true ``` +### Which policy applies, and what can block + +- **The base branch's `.altimate/review.yml` applies.** The file is read from the + commit the PR branched from, so a PR cannot relax the rules it is reviewed + under (switch to `comment` mode, drop a `blockOn` category, exclude its own + paths). If the PR edits the file, the comment lists the changed settings; they + take effect after merge. The applied policy's hash is signed into the envelope + (`policy`). +- **Only the deterministic engine blocks.** Findings carry an `origin`: + `engine` (AST, lineage, manifest, equivalence, data-diff), `catalog` (pattern + rules) or `ai`. Only `engine` findings count toward REQUEST_CHANGES. A pattern + rule you trust can be allowed to block by naming its id in + `rubric.blockingRules`. The advisory AI lane never blocks. + ### What the PR comment shows - **One summary comment**, updated in place on every push, capped at about diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 9d370d8062..d67cd7462c 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -2,6 +2,7 @@ import z from "zod" import path from "node:path" import { promises as fs } from "node:fs" import YAML from "yaml" +import { createHash } from "node:crypto" import { Rubric, DEFAULT_RUBRIC } from "./rubric" import { ReviewMode } from "./verdict" import { Severity } from "./finding" @@ -34,6 +35,9 @@ export const ReviewConfig = z.object({ * Functions missing on the project's own engine are always reported. */ portability: z.boolean().optional(), + /** Allow `--force-tier` (a debug bypass of the risk classifier). Set false + * in gate CI so a run cannot skip checks by forcing a lower tier. */ + allowForceTier: z.boolean().default(true), /** * Data-diff: actually run base-vs-head against the warehouse (core DataParity) * and report row/value deltas. OPT-IN — it costs warehouse compute and needs a @@ -114,6 +118,102 @@ export function parseReviewConfig(text: string): ReviewConfig { return ReviewConfig.parse(data) } +/** Where the applied policy came from. */ +export type PolicySource = "base" | "working_tree" | "default" + +export interface ReviewPolicy { + config: ReviewConfig + source: PolicySource + /** Short hash of the applied config (canonical JSON), signed into the envelope. */ + hash: string + /** Settings the PR changes relative to the applied base policy (not applied). */ + changedInPr: string[] +} + +function canonical(value: unknown): string { + if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null" + if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]" + const obj = value as Record + return ( + "{" + + Object.keys(obj) + .filter((k) => obj[k] !== undefined) + .sort() + .map((k) => JSON.stringify(k) + ":" + canonical(obj[k])) + .join(",") + + "}" + ) +} + +/** Short, stable hash of a resolved config. */ +export function policyHash(config: ReviewConfig): string { + return createHash("sha256").update(canonical(config)).digest("hex").slice(0, 16) +} + +/** Settings that differ between two configs: top-level keys, and `rubric.*` one level down. */ +export function policyChanges(base: ReviewConfig, head: ReviewConfig): string[] { + const out: string[] = [] + const keys = new Set([...Object.keys(base), ...Object.keys(head)]) as Set + for (const k of [...keys].sort()) { + if (canonical(base[k]) === canonical(head[k])) continue + if (k === "rubric") { + const b = (base.rubric ?? {}) as Record + const h = (head.rubric ?? {}) as Record + for (const rk of [...new Set([...Object.keys(b), ...Object.keys(h)])].sort()) + if (canonical(b[rk]) !== canonical(h[rk])) out.push(`rubric.${rk}`) + } else out.push(k) + } + return out +} + +async function readFirst(read: (rel: string) => Promise): Promise { + for (const rel of CANDIDATE_FILES) { + const text = await read(rel) + if (text !== undefined) return text + } + return undefined +} + +/** + * Load the review policy the PR is judged by. + * + * With `readBase` (a reader over the merge-base commit), the policy is the + * BASE branch's `.altimate/review.yml`: a pull request must not be able to + * relax the rules it is reviewed under (switch `mode` to comment, drop a + * `blockOn` category, exclude its own paths, disable lanes). The PR's own + * version is parsed only to list what it would change, which the comment + * shows; it takes effect once merged. Without `readBase` (no git), the working + * tree's file applies. + */ +export async function loadReviewPolicy(opts: { + cwd: string + readBase?: (rel: string) => Promise +}): Promise { + if (!opts.readBase) { + const config = await loadReviewConfig(opts.cwd) + const present = await readFirst((rel) => fs.readFile(path.join(opts.cwd, rel), "utf8").catch(() => undefined)) + return { config, source: present === undefined ? "default" : "working_tree", hash: policyHash(config), changedInPr: [] } + } + const baseText = await readFirst(opts.readBase) + let config: ReviewConfig + try { + config = baseText === undefined ? structuredClone(DEFAULT_REVIEW_CONFIG) : parseReviewConfig(baseText) + } catch (e: any) { + throw new Error(`Failed to load the base branch's .altimate/review config: ${e?.message ?? e}`) + } + const headText = await readFirst((rel) => fs.readFile(path.join(opts.cwd, rel), "utf8").catch(() => undefined)) + let changedInPr: string[] = [] + if (headText !== baseText) { + try { + const head = headText === undefined ? structuredClone(DEFAULT_REVIEW_CONFIG) : parseReviewConfig(headText) + changedInPr = policyChanges(config, head) + } catch { + changedInPr = ["(the PR's .altimate/review file does not parse)"] + } + } + return { config, source: baseText === undefined ? "default" : "base", hash: policyHash(config), changedInPr } +} + /** * Load `.altimate/review.{yml,yaml,json}` from a project directory. Returns the * defaults when no config file is present. Throws on a malformed/invalid file diff --git a/packages/opencode/src/altimate/review/finding.ts b/packages/opencode/src/altimate/review/finding.ts index c9fb1d42e9..41009731a7 100644 --- a/packages/opencode/src/altimate/review/finding.ts +++ b/packages/opencode/src/altimate/review/finding.ts @@ -84,9 +84,36 @@ export const Finding = z.object({ /** True when produced without a manifest/warehouse (lint-only degraded run). */ degraded: z.boolean().default(false), evidence: Evidence.optional(), + /** Which layer produced it: the deterministic engine, the regex/pattern + * catalog, or the advisory AI lane. Only `engine` findings decide the + * verdict unless the rubric opts a named catalog rule in. Stamped by + * buildEnvelope from `evidence.tool`. */ + origin: z.enum(["engine", "catalog", "ai"]).optional(), }) export type Finding = z.infer +export type FindingOrigin = NonNullable + +/** Evidence tools backed by the deterministic engine (AST, manifest, lineage, + * warehouse) rather than text patterns. */ +const ENGINE_TOOLS = new Set(["impact_analysis", "dbt.manifest", "data.diff", "schema.detect_pii"]) + +/** The layer a finding came from. Unknown or missing evidence counts as + * `catalog`, so a new detector can never block until it is classified. */ +export function findingOrigin(f: Pick): FindingOrigin { + if (f.origin) return f.origin + const tool = f.evidence?.tool ?? "" + if (tool === "ai-review") return "ai" + if (tool.startsWith("altimate_core.") || ENGINE_TOOLS.has(tool)) return "engine" + return "catalog" +} + +/** The catalog rule id behind a finding (`evidence.result.rule`), if any. */ +export function catalogRuleId(f: Pick): string | undefined { + const rule = (f.evidence?.result as { rule?: unknown } | undefined)?.rule + return typeof rule === "string" ? rule : undefined +} + /** Fields that define finding identity for fingerprinting / dedup. */ export interface FingerprintInput { category: ReviewCategory | string diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 0d73434108..695049539b 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -239,6 +239,12 @@ export function coverageNotes(env: VerdictEnvelope): string[] { `${env.scope.movedUnchangedFiles} file(s) moved without edits; their SQL was not re-reviewed. ` + "Folder-level config in `dbt_project.yml` (`+schema`, `+materialized`, `+tags`) can still change where and how a moved model builds.", ) + if (env.policy?.changedInPr?.length) { + notes.push( + `This PR changes the review policy (\`.altimate/review.yml\`: ${env.policy.changedInPr.join(", ")}). ` + + "The base branch's policy was applied; the change takes effect after merge.", + ) + } if (env.ai && env.ai.state !== "ok") { const what = { skipped: "skipped", timeout: "timed out", error: "failed" }[env.ai.state] notes.push(`Advisory AI review ${what}${env.ai.reason ? `: ${env.ai.reason}` : ""}.`) diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index 6a5f094a96..74d37c29e0 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -278,6 +278,16 @@ export async function resolveReviewBase(opts: ResolveBaseOptions): Promise:`), or undefined when the + * path does not exist there. `rel` is repository-relative, POSIX. */ +export async function showAtRef(cwd: string, ref: string, rel: string): Promise { + try { + return await git(["show", `${ref}:${rel}`], cwd) + } catch { + return undefined + } +} + /** Compute a short hash of the manifest file for the verdict envelope. */ export async function manifestHash(manifestPath: string, cwd: string): Promise { try { diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 1ceb9807f0..be517e00db 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -209,6 +209,8 @@ export interface OrchestrateInput { scope?: Omit /** Drop the regex catalog's cross-engine portability findings (single known engine). */ suppressPortability?: boolean + /** Which review policy was applied (see config.ts loadReviewPolicy). */ + policy?: VerdictEnvelope["policy"] } /** A catalog finding tagged as cross-engine portability advice. */ @@ -1552,6 +1554,7 @@ export async function runReview(input: OrchestrateInput): Promise= this many `warning` findings is treated as a risk pattern → block. */ warningPatternThreshold: z.number().int().positive().default(3), + /** + * Catalog (regex/pattern) rule ids allowed to influence the verdict. By + * default only deterministic engine findings can block; a team that trusts a + * specific pattern rule (e.g. `hardcoded-credential`) names it here. + */ + blockingRules: z.array(z.string()).default([]), thresholds: Thresholds.default(Thresholds.parse({})), exclusions: Exclusions.default(Exclusions.parse({})), }) diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index f2d68f39ca..6df72e4aed 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -1,7 +1,7 @@ import path from "node:path" import { readFile, realpath, stat, access } from "node:fs/promises" import { Installation } from "../../installation" -import { loadReviewConfig, resolveRubric } from "./config" +import { loadReviewPolicy, resolveRubric } from "./config" import type { Severity } from "./finding" import { collectChangedFiles, @@ -10,6 +10,7 @@ import { type ResolvedBase, gitRepoRoot, manifestHash, + showAtRef, } from "./git" import { makeCompiledResolver, dbtProjectName, dbtProjectLayout } from "./compiled" import { scopeToProject } from "./diff-filter" @@ -217,12 +218,6 @@ async function detectStaleManifest(manifestAbs: string, changed: ChangedFile[], } export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise { - const config = await loadReviewConfig(opts.cwd) - if (opts.manifestPath) config.manifestPath = opts.manifestPath - if (opts.mode) config.mode = opts.mode - if (opts.severityThreshold) config.severityThreshold = opts.severityThreshold - const rubric = resolveRubric(config) - // Resolve the repo top-level once; used to root working-tree FS reads, the // stale-manifest existence check, and the compiled-SQL resolver's path // mapping. Falls back to opts.cwd when we couldn't resolve it (non-git or @@ -230,6 +225,43 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise // in the subdir-invocation case that this addresses. const gitRoot = (await gitRepoRoot(opts.cwd)) ?? opts.cwd + // Only resolve a base ref if we actually need git (to collect changed files + // or to read old/new content). A caller that supplies BOTH `changedFiles` and + // `getContent` (e.g. a non-git CI integration) must not be forced through a + // git lookup that can fail when there's no usable history. + // + // The base is always the MERGE-BASE of the PR's target branch and the head: + // the diff, and every "old" file version, come from the commit the PR + // branched from, so commits the target gained since never leak in as changes. + const needGit = !opts.changedFiles || !opts.getContent + const resolved: ResolvedBase | undefined = needGit + ? await resolveReviewBase({ cwd: opts.cwd, base: opts.base, head: opts.head }) + : undefined + + // The policy (.altimate/review.yml) comes from the BASE commit, so the PR + // under review cannot relax its own rules; what it would change is listed. + const cwdRel = await repoRelative(gitRoot, opts.cwd, true) + const policy = await loadReviewPolicy({ + cwd: opts.cwd, + readBase: + resolved && cwdRel !== undefined + ? (rel) => showAtRef(opts.cwd, resolved.sha, path.posix.join(cwdRel, rel)) + : undefined, + }) + const config = policy.config + if (policy.changedInPr.length) { + process.stderr.write( + `ℹ️ this PR changes .altimate/review (${policy.changedInPr.join(", ")}); the base branch's policy was applied.\n`, + ) + } + if (opts.forceTier && config.allowForceTier === false) { + throw new Error("--force-tier is disabled by `allowForceTier: false` in the base branch's .altimate/review.yml") + } + if (opts.manifestPath) config.manifestPath = opts.manifestPath + if (opts.mode) config.mode = opts.mode + if (opts.severityThreshold) config.severityThreshold = opts.severityThreshold + const rubric = resolveRubric(config) + // Resolve the manifest against the PROJECT being reviewed (cwd), not the // binary's process.cwd() — otherwise a relative path silently misses when the // CLI is invoked from elsewhere, degrading every review to lint-only. @@ -271,18 +303,6 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise const projectRootRel = await repoRelative(gitRoot, dbtRoot, project !== undefined || dbtRoot !== opts.cwd) const layout = projectRootRel !== undefined ? await dbtProjectLayout(dbtRoot, projectRootRel) : undefined - // Only resolve a base ref if we actually need git (to collect changed files - // or to read old/new content). A caller that supplies BOTH `changedFiles` and - // `getContent` (e.g. a non-git CI integration) must not be forced through a - // git lookup that can fail when there's no usable history. - // - // The base is always the MERGE-BASE of the PR's target branch and the head: - // the diff, and every "old" file version, come from the commit the PR - // branched from, so commits the target gained since never leak in as changes. - const needGit = !opts.changedFiles || !opts.getContent - const resolved: ResolvedBase | undefined = needGit - ? await resolveReviewBase({ cwd: opts.cwd, base: opts.base, head: opts.head }) - : undefined if (resolved && resolved.source !== "flag") { process.stderr.write(`ℹ️ review base: ${resolved.ref} (${resolved.source}), merge-base ${resolved.sha.slice(0, 12)}\n`) } @@ -396,6 +416,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise staleManifest, layout, suppressPortability: shouldSuppressPortability(config.portability, dialectKnown), + policy: { source: policy.source, hash: policy.hash, changedInPr: policy.changedInPr.length ? policy.changedInPr : undefined }, scope: { baseRef: resolved?.ref ?? opts.base, baseSha: resolved?.sha, diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index 95064230db..7722f85f43 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -1,6 +1,6 @@ import z from "zod" import { createHmac, createHash } from "node:crypto" -import { Finding, type Severity } from "./finding" +import { Finding, type Severity, catalogRuleId, findingOrigin } from "./finding" import { Rubric, DEFAULT_RUBRIC, blockingCategories } from "./rubric" /** @@ -41,6 +41,17 @@ export const VCS_EVENT: Record = { REQUEST_CHANGES: "REQUEST_CHANGES", } +/** Whether a finding may influence the verdict: deterministic engine + * findings always; catalog (pattern) findings only when the rubric names the + * rule in `blockingRules`; advisory AI findings never. */ +export function verdictEligible(f: Finding, rubric: Rubric = DEFAULT_RUBRIC): boolean { + const origin = findingOrigin(f) + if (origin === "engine") return true + if (origin === "ai") return false + const rule = catalogRuleId(f) + return !!rule && rubric.blockingRules.includes(rule) +} + /** * Compute the verdict purely from findings + rubric. Faithful to Cloudflare's * bias-toward-approval rubric: @@ -48,21 +59,20 @@ export const VCS_EVENT: Record = { * - >= warningPatternThreshold warnings → REQUEST_CHANGES (risk pattern) * - any finding at all → COMMENT * - nothing → APPROVE + * Only verdict-eligible findings (see verdictEligible) count toward a block: + * the docs promise that only the deterministic engine blocks, so a regex rule + * or the AI lane can comment but never fail the gate on its own. */ export function computeIdealVerdict(findings: Finding[], rubric: Rubric = DEFAULT_RUBRIC): Verdict { if (findings.length === 0) return "APPROVE" const blockers = blockingCategories(rubric) - const hasBlockingCritical = findings.some((f) => f.severity === "critical" && blockers.has(f.category)) + const eligible = findings.filter((f) => verdictEligible(f, rubric)) + const hasBlockingCritical = eligible.some((f) => f.severity === "critical" && blockers.has(f.category)) if (hasBlockingCritical) return "REQUEST_CHANGES" // Count only confidently-warned findings toward the risk pattern. Undecidable // ("unknown") warnings — e.g. equivalence that couldn't be proven — must not // accumulate into a block; that would let unprovable refactors fail the gate. - // Advisory LLM findings (layer 3) are EXCLUDED: the lane is advisory-only and must - // never influence the verdict, so its warnings cannot accumulate into a block - // (otherwise a chatty or prompt-injected AI review could force REQUEST_CHANGES). - const warningCount = findings.filter( - (f) => f.severity === "warning" && f.confidence !== "unknown" && f.evidence?.tool !== "ai-review", - ).length + const warningCount = eligible.filter((f) => f.severity === "warning" && f.confidence !== "unknown").length if (warningCount >= rubric.warningPatternThreshold) return "REQUEST_CHANGES" return "COMMENT" } @@ -144,6 +154,15 @@ export const VerdictEnvelope = z.object({ staleManifest: z.boolean().optional(), /** Base resolution and review coverage (see ReviewScope). */ scope: ReviewScope.optional(), + /** The review policy applied: from the base branch, the working tree, or + * defaults; its hash; and settings the PR changes but that were not applied. */ + policy: z + .object({ + source: z.enum(["base", "working_tree", "default"]), + hash: z.string(), + changedInPr: z.array(z.string()).optional(), + }) + .optional(), /** Advisory AI lane outcome: ran, skipped, timed out or failed, and why. */ ai: z .object({ @@ -213,6 +232,7 @@ export interface BuildEnvelopeInput { staleManifest?: boolean scope?: ReviewScope ai?: VerdictEnvelope["ai"] + policy?: VerdictEnvelope["policy"] } function summarize(findings: Finding[], degraded: boolean): VerdictEnvelope["summary"] { @@ -236,13 +256,14 @@ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { tierReasons: input.tierReasons, tierForced: input.tierForced, tierClassified: input.tierClassified, - findings: input.findings, + findings: input.findings.map((f) => (f.origin ? f : { ...f, origin: findingOrigin(f) })), summary: summarize(input.findings, degraded), engine: EngineVersions.parse(input.engine ?? {}), manifestHash: input.manifestHash, staleManifest: input.staleManifest ? true : undefined, scope: input.scope, ai: input.ai, + policy: input.policy, generatedAt: input.generatedAt, }) } diff --git a/packages/opencode/test/altimate/review-verdict-trust.test.ts b/packages/opencode/test/altimate/review-verdict-trust.test.ts new file mode 100644 index 0000000000..2dff815941 --- /dev/null +++ b/packages/opencode/test/altimate/review-verdict-trust.test.ts @@ -0,0 +1,174 @@ +import { describe, test, expect, afterEach } from "bun:test" +import { promises as fs } from "node:fs" +import path from "node:path" +import { tmpdir } from "node:os" +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { makeFinding, findingOrigin, type Finding } from "../../src/altimate/review/finding" +import { DEFAULT_RUBRIC, Rubric } from "../../src/altimate/review/rubric" +import { buildEnvelope, computeIdealVerdict, signEnvelope, verdictEligible, verifyEnvelope } from "../../src/altimate/review/verdict" +import { DEFAULT_REVIEW_CONFIG, policyChanges, policyHash } from "../../src/altimate/review/config" +import { reviewPullRequest } from "../../src/altimate/review/run" +import { renderSummary } from "../../src/altimate/review/format" + +/** + * A verdict must mean what the docs say: only the deterministic engine blocks + * (pattern rules and the AI lane comment), and a pull request cannot relax the + * policy it is judged by — `.altimate/review.yml` comes from the base branch. + */ + +const exec = promisify(execFile) +const g = (cwd: string, ...args: string[]) => exec("git", args, { cwd }).then((r) => r.stdout.trim()) + +function f(tool: string | undefined, severity: Finding["severity"], category: any, i: number, rule?: string): Finding { + return makeFinding({ + severity, + category, + title: `t${i}`, + body: "b", + file: `models/m${i}.sql`, + confidence: "high", + evidence: tool ? { tool, result: rule ? { rule } : {} } : undefined, + ruleKey: `r${i}`, + }) +} + +describe("only the engine blocks", () => { + test("origin comes from the evidence tool; unknown sources are catalog", () => { + expect(findingOrigin(f("altimate_core.equivalence", "warning", "semantic_change", 1))).toBe("engine") + expect(findingOrigin(f("impact_analysis", "warning", "lineage_breakage", 2))).toBe("engine") + expect(findingOrigin(f("rule-catalog", "warning", "sql_quality", 3))).toBe("catalog") + expect(findingOrigin(f("dbt-patterns", "warning", "sql_quality", 4))).toBe("catalog") + expect(findingOrigin(f("ai-review", "warning", "sql_quality", 5))).toBe("ai") + expect(findingOrigin(f("some.new.detector", "warning", "sql_quality", 6))).toBe("catalog") + expect(findingOrigin(f(undefined, "warning", "sql_quality", 7))).toBe("catalog") + }) + + test("1 catalog critical + 3 catalog warnings → COMMENT", () => { + const findings = [ + f("rule-catalog", "critical", "sql_correctness", 1, "join-no-on"), + f("rule-catalog", "warning", "sql_quality", 2, "a"), + f("dbt-patterns", "warning", "sql_quality", 3, "b"), + f("rule-catalog", "warning", "sql_quality", 4, "c"), + ] + expect(computeIdealVerdict(findings, DEFAULT_RUBRIC)).toBe("COMMENT") + }) + + test("a catalog rule named in blockingRules can block", () => { + const rubric = Rubric.parse({ blockingRules: ["hardcoded-credential"] }) + const cred = f("rule-catalog", "critical", "sql_correctness", 1, "hardcoded-credential") + expect(verdictEligible(cred, rubric)).toBe(true) + expect(computeIdealVerdict([cred], rubric)).toBe("REQUEST_CHANGES") + expect(computeIdealVerdict([cred], DEFAULT_RUBRIC)).toBe("COMMENT") + }) + + test("engine criticals and engine warning patterns still block", () => { + expect(computeIdealVerdict([f("impact_analysis", "critical", "lineage_breakage", 1)])).toBe("REQUEST_CHANGES") + const three = [1, 2, 3].map((i) => f("altimate_core.check", "warning", "sql_quality", i)) + expect(computeIdealVerdict(three)).toBe("REQUEST_CHANGES") + }) + + test("the envelope records each finding's origin and still verifies", () => { + const env = buildEnvelope({ + findings: [f("rule-catalog", "warning", "sql_quality", 1), f("altimate_core.check", "warning", "sql_quality", 2)], + tier: "lite", + mode: "comment", + }) + expect(env.findings.map((x) => x.origin)).toEqual(["catalog", "engine"]) + const signed = signEnvelope(env) + expect(verifyEnvelope(signed)).toBe(true) + // Origin is covered by the signature: flipping it breaks verification. + const tampered = { ...signed, findings: signed.findings.map((x) => ({ ...x, origin: "engine" as const })) } + expect(verifyEnvelope(tampered)).toBe(false) + }) +}) + +describe("policy helpers", () => { + test("hash is stable and changes with the policy", () => { + const a = structuredClone(DEFAULT_REVIEW_CONFIG) + const b = structuredClone(DEFAULT_REVIEW_CONFIG) + expect(policyHash(a)).toBe(policyHash(b)) + b.mode = "gate" + expect(policyHash(a)).not.toBe(policyHash(b)) + }) + + test("changes are listed by setting, rubric one level down", () => { + const base = structuredClone(DEFAULT_REVIEW_CONFIG) + const head = structuredClone(DEFAULT_REVIEW_CONFIG) + head.mode = "gate" + head.exclude = ["models/legacy/**"] + head.rubric = { ...head.rubric, blockOn: ["lineage_breakage"] } + expect(policyChanges(base, head)).toEqual(["exclude", "mode", "rubric.blockOn"]) + }) +}) + +describe("policy comes from the base branch", () => { + const saved = { ...process.env } + afterEach(() => { + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]) { + if (saved[k] === undefined) delete process.env[k] + else process.env[k] = saved[k] + } + }) + + async function repo(baseYml: string | undefined, headYml: string | undefined) { + const root = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), "review-policy-"))) + await g(root, "init", "-q", "-b", "main") + await g(root, "config", "user.email", "t@test") + await g(root, "config", "user.name", "t") + await g(root, "config", "commit.gpgsign", "false") + await fs.mkdir(path.join(root, "models"), { recursive: true }) + await fs.writeFile(path.join(root, "dbt_project.yml"), "name: p\n") + await fs.writeFile(path.join(root, "models", "a.sql"), "select 1 as id\n") + if (baseYml !== undefined) { + await fs.mkdir(path.join(root, ".altimate"), { recursive: true }) + await fs.writeFile(path.join(root, ".altimate", "review.yml"), baseYml) + } + await g(root, "add", "-A") + await g(root, "commit", "-qm", "base") + await g(root, "checkout", "-q", "-b", "feature") + await fs.writeFile(path.join(root, "models", "a.sql"), "select 2 as id\n") + if (headYml !== undefined) { + await fs.mkdir(path.join(root, ".altimate"), { recursive: true }) + await fs.writeFile(path.join(root, ".altimate", "review.yml"), headYml) + } + await g(root, "add", "-A") + await g(root, "commit", "-qm", "pr") + delete process.env.GITHUB_EVENT_PATH + delete process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME + process.env.GITHUB_BASE_REF = "main" + return root + } + + test("a PR that relaxes review.yml is still judged by the base policy, and the change is shown", async () => { + const root = await repo("mode: gate\n", "mode: comment\nexclude:\n - models/**\nai: false\n") + const env = await reviewPullRequest({ cwd: root, head: "HEAD", noAi: true }) + expect(env.mode).toBe("gate") + expect(env.policy?.source).toBe("base") + expect(env.policy?.changedInPr).toEqual(["ai", "exclude", "mode"]) + expect(renderSummary(env)).toContain("The base branch's policy was applied") + }, 60_000) + + test("a review.yml the PR adds does not apply until merged", async () => { + const root = await repo(undefined, "mode: gate\n") + const env = await reviewPullRequest({ cwd: root, head: "HEAD", noAi: true }) + expect(env.mode).toBe("comment") + expect(env.policy?.source).toBe("default") + expect(env.policy?.changedInPr).toEqual(["mode"]) + }, 60_000) + + test("an unchanged policy is applied without a note", async () => { + const root = await repo("mode: gate\n", undefined) + const env = await reviewPullRequest({ cwd: root, head: "HEAD", noAi: true }) + expect(env.mode).toBe("gate") + expect(env.policy?.changedInPr).toBeUndefined() + expect(env.policy?.hash).toMatch(/^[0-9a-f]{16}$/) + }, 60_000) + + test("allowForceTier: false in the base policy rejects --force-tier", async () => { + const root = await repo("allowForceTier: false\n", "allowForceTier: true\n") + await expect(reviewPullRequest({ cwd: root, head: "HEAD", noAi: true, forceTier: "trivial" })).rejects.toThrow( + /force-tier is disabled/, + ) + }, 60_000) +}) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index f5ef7843be..0c723e1a3a 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -134,6 +134,7 @@ describe("rubric", () => { // verdict.ts // --------------------------------------------------------------------------- describe("verdict", () => { + // Engine findings: only the deterministic engine decides the verdict. const mk = (severity: Finding["severity"], category: any = "sql_quality") => makeFinding({ severity, @@ -141,6 +142,7 @@ describe("verdict", () => { title: "t", body: "b", file: `m_${Math.random()}.sql`, + evidence: { tool: "altimate_core.check", result: {} }, ruleKey: String(Math.random()), }) @@ -2555,7 +2557,8 @@ describe("orchestrate", () => { expect( pii.some((f) => f.evidence?.tool === "dbt-patterns" && (f.evidence?.result as any)?.rule === "pii_into_mart"), ).toBe(true) - expect(env.verdict).toBe("REQUEST_CHANGES") + // A pattern rule is reported but only blocks when the rubric opts it in. + expect(env.verdict).toBe("COMMENT") }) test("zero-target lineage does not mark the file PII-complete, so the regex twin survives", async () => { @@ -2590,7 +2593,8 @@ describe("orchestrate", () => { expect( pii.some((f) => f.evidence?.tool === "dbt-patterns" && (f.evidence?.result as any)?.rule === "pii_into_mart"), ).toBe(true) - expect(env.verdict).toBe("REQUEST_CHANGES") + // A pattern rule is reported but only blocks when the rubric opts it in. + expect(env.verdict).toBe("COMMENT") }) test("core considered the matched column (muted as low-confidence) → the regex twin is suppressed", async () => { diff --git a/packages/opencode/test/skill/release-v0.8.1-adversarial.test.ts b/packages/opencode/test/skill/release-v0.8.1-adversarial.test.ts index e35f3886e3..bf958b3302 100644 --- a/packages/opencode/test/skill/release-v0.8.1-adversarial.test.ts +++ b/packages/opencode/test/skill/release-v0.8.1-adversarial.test.ts @@ -76,6 +76,7 @@ describe("v0.8.1 — no formal GitHub APPROVE (review bot)", () => { title: "drops rows", body: "the refactor is not equivalent", file: "models/m.sql", + evidence: { tool: "altimate_core.equivalence" }, }) const env = buildEnvelope({ findings: [finding], tier: "full", mode: "comment" }) expect(env.idealVerdict).toBe("REQUEST_CHANGES") // would have blocked @@ -91,6 +92,7 @@ describe("v0.8.1 — no formal GitHub APPROVE (review bot)", () => { title: "new PII column", body: "exposes email", file: "models/users.sql", + evidence: { tool: "altimate_core.classify_pii" }, }) const env = buildEnvelope({ findings: [finding], tier: "full", mode: "gate" }) expect(env.verdict).toBe("REQUEST_CHANGES") From cce5adfc37eab50eabb9ab2583596c020e7acb3a Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 10:25:21 +0530 Subject: [PATCH 12/23] fix(review): address review comments: workflow flags cannot relax base policy, `showAtRef` fails closed - `--mode` / `--severity` (always passed by the action from the PR-editable workflow) can only tighten a base-branch policy: `mode: gate` is kept and a higher severity threshold is ignored, each with a stderr notice. Docs state this and recommend protecting `.github/` with CODEOWNERS. - `showAtRef` returns undefined only when the path is absent at the ref and rethrows any other git failure, so the base-policy loader no longer falls back to the permissive default on a bad ref or git error. - Tests for both. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 5 ++++- packages/opencode/src/altimate/review/git.ts | 9 +++++++-- packages/opencode/src/altimate/review/run.ts | 20 ++++++++++++++++--- .../altimate/review-verdict-trust.test.ts | 18 +++++++++++++++++ 4 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 caa41b4a7d..bf12f5ddb5 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -295,7 +295,10 @@ rubric: under (switch to `comment` mode, drop a `blockOn` category, exclude its own paths). If the PR edits the file, the comment lists the changed settings; they take effect after merge. The applied policy's hash is signed into the envelope - (`policy`). + (`policy`). The action's `mode` and `severity_threshold` inputs (`--mode`, + `--severity`) can only tighten a base policy: they cannot turn `mode: gate` + into `comment` or raise its severity threshold. Other workflow steps are still + PR-editable, so protect `.github/` with CODEOWNERS or branch rules. - **Only the deterministic engine blocks.** Findings carry an `origin`: `engine` (AST, lineage, manifest, equivalence, data-diff), `catalog` (pattern rules) or `ai`. Only `engine` findings count toward REQUEST_CHANGES. A pattern diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index 74d37c29e0..d7026f82c5 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -283,8 +283,13 @@ export async function resolveReviewBase(opts: ResolveBaseOptions): Promise { try { return await git(["show", `${ref}:${rel}`], cwd) - } catch { - return undefined + } catch (err) { + // Only "the path is not in that commit" means absent. Any other failure + // (bad ref, corrupt object, git missing) must surface: callers such as the + // base-policy loader would otherwise fall back to the permissive default. + const msg = err instanceof Error ? err.message : String(err) + if (/does not exist in|exists on disk, but not in/i.test(msg)) return undefined + throw err } } diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 6df72e4aed..5f7a529081 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -2,7 +2,7 @@ import path from "node:path" import { readFile, realpath, stat, access } from "node:fs/promises" import { Installation } from "../../installation" import { loadReviewPolicy, resolveRubric } from "./config" -import type { Severity } from "./finding" +import { SEVERITY_ORDER, type Severity } from "./finding" import { collectChangedFiles, makeContentResolver, @@ -258,8 +258,22 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise throw new Error("--force-tier is disabled by `allowForceTier: false` in the base branch's .altimate/review.yml") } if (opts.manifestPath) config.manifestPath = opts.manifestPath - if (opts.mode) config.mode = opts.mode - if (opts.severityThreshold) config.severityThreshold = opts.severityThreshold + // `--mode` / `--severity` come from the PR-editable workflow. Against a base + // policy they may only tighten it: they cannot turn `gate` into `comment` + // or hide severities the base policy surfaces. + const fromBase = policy.source === "base" + if (opts.mode) { + if (fromBase && config.mode === "gate" && opts.mode !== "gate") { + process.stderr.write(`ℹ️ --mode ${opts.mode} ignored: the base branch's policy sets \`mode: gate\`.\n`) + } else config.mode = opts.mode + } + if (opts.severityThreshold) { + if (fromBase && SEVERITY_ORDER[opts.severityThreshold] > SEVERITY_ORDER[config.severityThreshold]) { + process.stderr.write( + `ℹ️ --severity ${opts.severityThreshold} ignored: the base branch's policy surfaces ${config.severityThreshold} and above.\n`, + ) + } else config.severityThreshold = opts.severityThreshold + } const rubric = resolveRubric(config) // Resolve the manifest against the PROJECT being reviewed (cwd), not the diff --git a/packages/opencode/test/altimate/review-verdict-trust.test.ts b/packages/opencode/test/altimate/review-verdict-trust.test.ts index 2dff815941..063415db1d 100644 --- a/packages/opencode/test/altimate/review-verdict-trust.test.ts +++ b/packages/opencode/test/altimate/review-verdict-trust.test.ts @@ -9,6 +9,7 @@ import { DEFAULT_RUBRIC, Rubric } from "../../src/altimate/review/rubric" import { buildEnvelope, computeIdealVerdict, signEnvelope, verdictEligible, verifyEnvelope } from "../../src/altimate/review/verdict" import { DEFAULT_REVIEW_CONFIG, policyChanges, policyHash } from "../../src/altimate/review/config" import { reviewPullRequest } from "../../src/altimate/review/run" +import { showAtRef } from "../../src/altimate/review/git" import { renderSummary } from "../../src/altimate/review/format" /** @@ -165,6 +166,23 @@ describe("policy comes from the base branch", () => { expect(env.policy?.hash).toMatch(/^[0-9a-f]{16}$/) }, 60_000) + test("--mode and --severity from the workflow cannot relax a base policy, only tighten it", async () => { + const root = await repo("mode: gate\nseverityThreshold: warning\n", undefined) + const relaxed = await reviewPullRequest({ cwd: root, head: "HEAD", noAi: true, mode: "comment", severityThreshold: "critical" }) + expect(relaxed.mode).toBe("gate") + const tightened = await reviewPullRequest({ cwd: root, head: "HEAD", noAi: true, severityThreshold: "suggestion" }) + expect(tightened.mode).toBe("gate") + const loose = await repo("mode: comment\n", undefined) + expect((await reviewPullRequest({ cwd: loose, head: "HEAD", noAi: true, mode: "gate" })).mode).toBe("gate") + }, 60_000) + + test("showAtRef: a path missing at the ref is absent, any other git failure surfaces", async () => { + const root = await repo("mode: gate\n", undefined) + expect(await showAtRef(root, "main", ".altimate/review.yaml")).toBeUndefined() + expect(await showAtRef(root, "main", ".altimate/review.yml")).toBe("mode: gate\n") + await expect(showAtRef(root, "no-such-ref", ".altimate/review.yml")).rejects.toThrow() + }, 60_000) + test("allowForceTier: false in the base policy rejects --force-tier", async () => { const root = await repo("allowForceTier: false\n", "allowForceTier: true\n") await expect(reviewPullRequest({ cwd: root, head: "HEAD", noAi: true, forceTier: "trivial" })).rejects.toThrow( From 0c00d0722a2b39ca8a6337dafca9e3a8a71d65bc Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 11:06:27 +0530 Subject: [PATCH 13/23] fix(review): address review feedback: `blockingRules` spelling, origin from evidence only, hash after flags, base-policy error - `verdictEligible`: `blockingRules` ids compare after `normalizeRuleId` (lowercase, `_` as `-`), so `pii-into-mart` and `pii_into_mart` both opt the rule in. - `findingOrigin` always derives from `evidence.tool` and `buildEnvelope` always re-derives it: a supplied `origin` cannot make an AI or catalog finding block. - `reviewPullRequest`: the signed `policy.hash` is recomputed after the `--mode`/`--severity`/`--manifest` flags, so it describes the applied policy. - An unparsable base `review.yml` still fails closed; the error now names the recovery path. - Tests: both id spellings, a supplied `origin: "engine"` on AI findings, hash after flags, unparsable base policy. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/config.ts | 6 +++- .../opencode/src/altimate/review/finding.ts | 13 ++++++-- packages/opencode/src/altimate/review/run.ts | 4 ++- .../opencode/src/altimate/review/verdict.ts | 8 +++-- .../altimate/review-verdict-trust.test.ts | 30 +++++++++++++++++++ 5 files changed, 53 insertions(+), 8 deletions(-) diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index d67cd7462c..55c5cd7c4d 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -199,7 +199,11 @@ export async function loadReviewPolicy(opts: { try { config = baseText === undefined ? structuredClone(DEFAULT_REVIEW_CONFIG) : parseReviewConfig(baseText) } catch (e: any) { - throw new Error(`Failed to load the base branch's .altimate/review config: ${e?.message ?? e}`) + throw new Error( + `Failed to load the base branch's .altimate/review config: ${e?.message ?? e}. ` + + "The policy is read from the base branch so a PR cannot relax it; fix the file on the base branch " + + "(a PR that repairs it is reviewed under the broken base file, so merge it with an admin bypass).", + ) } const headText = await readFirst((rel) => fs.readFile(path.join(opts.cwd, rel), "utf8").catch(() => undefined)) let changedInPr: string[] = [] diff --git a/packages/opencode/src/altimate/review/finding.ts b/packages/opencode/src/altimate/review/finding.ts index 41009731a7..39b1e5dca6 100644 --- a/packages/opencode/src/altimate/review/finding.ts +++ b/packages/opencode/src/altimate/review/finding.ts @@ -98,16 +98,23 @@ export type FindingOrigin = NonNullable * warehouse) rather than text patterns. */ const ENGINE_TOOLS = new Set(["impact_analysis", "dbt.manifest", "data.diff", "schema.detect_pii"]) -/** The layer a finding came from. Unknown or missing evidence counts as - * `catalog`, so a new detector can never block until it is classified. */ +/** The layer a finding came from, always derived from `evidence.tool`: a + * supplied `origin` is ignored, so an externally built finding cannot claim + * to be engine-backed. Unknown or missing evidence counts as `catalog`, so a + * new detector can never block until it is classified. */ export function findingOrigin(f: Pick): FindingOrigin { - if (f.origin) return f.origin const tool = f.evidence?.tool ?? "" if (tool === "ai-review") return "ai" if (tool.startsWith("altimate_core.") || ENGINE_TOOLS.has(tool)) return "engine" return "catalog" } +/** A rule id in one spelling: catalog sources use `hardcoded-credential` and + * `pii_into_mart` alike, so ids compare lowercased with `_` as `-`. */ +export function normalizeRuleId(id: string): string { + return id.trim().toLowerCase().replace(/_/g, "-") +} + /** The catalog rule id behind a finding (`evidence.result.rule`), if any. */ export function catalogRuleId(f: Pick): string | undefined { const rule = (f.evidence?.result as { rule?: unknown } | undefined)?.rule diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 5f7a529081..c7813e3d9b 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -1,7 +1,7 @@ import path from "node:path" import { readFile, realpath, stat, access } from "node:fs/promises" import { Installation } from "../../installation" -import { loadReviewPolicy, resolveRubric } from "./config" +import { loadReviewPolicy, policyHash, resolveRubric } from "./config" import { SEVERITY_ORDER, type Severity } from "./finding" import { collectChangedFiles, @@ -274,6 +274,8 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise ) } else config.severityThreshold = opts.severityThreshold } + // The signed hash describes the policy actually applied, after the flags. + policy.hash = policyHash(config) const rubric = resolveRubric(config) // Resolve the manifest against the PROJECT being reviewed (cwd), not the diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index 7722f85f43..5a45e14351 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -1,6 +1,6 @@ import z from "zod" import { createHmac, createHash } from "node:crypto" -import { Finding, type Severity, catalogRuleId, findingOrigin } from "./finding" +import { Finding, type Severity, catalogRuleId, findingOrigin, normalizeRuleId } from "./finding" import { Rubric, DEFAULT_RUBRIC, blockingCategories } from "./rubric" /** @@ -49,7 +49,9 @@ export function verdictEligible(f: Finding, rubric: Rubric = DEFAULT_RUBRIC): bo if (origin === "engine") return true if (origin === "ai") return false const rule = catalogRuleId(f) - return !!rule && rubric.blockingRules.includes(rule) + if (!rule) return false + const id = normalizeRuleId(rule) + return rubric.blockingRules.some((r) => normalizeRuleId(r) === id) } /** @@ -256,7 +258,7 @@ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { tierReasons: input.tierReasons, tierForced: input.tierForced, tierClassified: input.tierClassified, - findings: input.findings.map((f) => (f.origin ? f : { ...f, origin: findingOrigin(f) })), + findings: input.findings.map((f) => ({ ...f, origin: findingOrigin(f) })), summary: summarize(input.findings, degraded), engine: EngineVersions.parse(input.engine ?? {}), manifestHash: input.manifestHash, diff --git a/packages/opencode/test/altimate/review-verdict-trust.test.ts b/packages/opencode/test/altimate/review-verdict-trust.test.ts index 063415db1d..3ccd36eca4 100644 --- a/packages/opencode/test/altimate/review-verdict-trust.test.ts +++ b/packages/opencode/test/altimate/review-verdict-trust.test.ts @@ -63,6 +63,23 @@ describe("only the engine blocks", () => { expect(computeIdealVerdict([cred], DEFAULT_RUBRIC)).toBe("COMMENT") }) + test("blockingRules ids match with either spelling (`pii_into_mart` / `pii-into-mart`)", () => { + const pii = f("dbt-patterns", "critical", "pii_exposure", 1, "pii_into_mart") + const cred = f("rule-catalog", "critical", "sql_correctness", 2, "hardcoded-credential") + const rubric = Rubric.parse({ blockingRules: ["pii-into-mart", "Hardcoded_Credential"] }) + expect(verdictEligible(pii, rubric)).toBe(true) + expect(verdictEligible(cred, rubric)).toBe(true) + expect(computeIdealVerdict([pii], rubric)).toBe("REQUEST_CHANGES") + }) + + test("a supplied origin never overrides the evidence tool", () => { + const ai = [1, 2, 3].map((i) => ({ ...f("ai-review", "warning", "sql_quality", i), origin: "engine" as const })) + expect(findingOrigin(ai[0])).toBe("ai") + expect(computeIdealVerdict(ai)).toBe("COMMENT") + const env = buildEnvelope({ findings: ai, mode: "gate", tier: "full", generatedAt: "2026-11-20T00:00:00Z" } as any) + expect(env.findings.every((x) => x.origin === "ai")).toBe(true) + }) + test("engine criticals and engine warning patterns still block", () => { expect(computeIdealVerdict([f("impact_analysis", "critical", "lineage_breakage", 1)])).toBe("REQUEST_CHANGES") const three = [1, 2, 3].map((i) => f("altimate_core.check", "warning", "sql_quality", i)) @@ -176,6 +193,19 @@ describe("policy comes from the base branch", () => { expect((await reviewPullRequest({ cwd: loose, head: "HEAD", noAi: true, mode: "gate" })).mode).toBe("gate") }, 60_000) + test("the signed policy hash describes the policy after the flags", async () => { + const root = await repo("mode: comment\nseverityThreshold: warning\n", undefined) + const plain = await reviewPullRequest({ cwd: root, head: "HEAD", noAi: true }) + const tightened = await reviewPullRequest({ cwd: root, head: "HEAD", noAi: true, mode: "gate", severityThreshold: "suggestion" }) + expect(plain.policy?.hash).toMatch(/^[0-9a-f]{16}$/) + expect(tightened.policy?.hash).not.toBe(plain.policy?.hash) + }, 60_000) + + test("an unparsable base review.yml fails closed and names the recovery path", async () => { + const root = await repo("mode: [unclosed\n", "mode: comment\n") + await expect(reviewPullRequest({ cwd: root, head: "HEAD", noAi: true })).rejects.toThrow(/fix the file on the base branch/) + }, 60_000) + test("showAtRef: a path missing at the ref is absent, any other git failure surfaces", async () => { const root = await repo("mode: gate\n", undefined) expect(await showAtRef(root, "main", ".altimate/review.yaml")).toBeUndefined() From 209bf5f93e4e5a039634dc8f649f25d9d0de29f4 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 12 Nov 2026 17:06:47 +0530 Subject: [PATCH 14/23] fix(review): failures are never clean: engine errors reported, per-file isolation, PII abstention, gate dismissal - The dispatcher runner records every engine call that throws (method, first reason, count) instead of silently returning empty. They are signed into the envelope (`engineErrors`), named in the comment, counted in `review_run.engine_errors`, and an empty review with engine errors is COMMENT, never APPROVE. - A failure while preparing one file, or a lane throwing for one file, marks that file unverified with the reason; the rest of the PR is still reviewed. PR-level lanes and the core-ran check are guarded the same way. - `detectPii` reports `abstained` when core could not analyse the SQL (check did not run, or its PII parser reported a parse error); the model is listed as not fully verified instead of passing as PII-clean. - When a rerun no longer blocks, earlier blocking altimate reviews are dismissed so the gate does not stay closed. The GitHub client is injectable so dedup, dismissal and skip rules are tested without the network. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 9 +- .../opencode/src/altimate/review/format.ts | 23 +- .../src/altimate/review/orchestrate.ts | 105 +++++--- .../src/altimate/review/post-github.ts | 47 +++- .../opencode/src/altimate/review/runner.ts | 67 +++-- .../opencode/src/altimate/review/telemetry.ts | 1 + .../opencode/src/altimate/review/verdict.ts | 12 +- .../opencode/src/altimate/telemetry/index.ts | 2 + packages/opencode/src/cli/cmd/review.ts | 3 +- .../altimate/review-failures-gate.test.ts | 237 ++++++++++++++++++ 10 files changed, 439 insertions(+), 67 deletions(-) create mode 100644 packages/opencode/test/altimate/review-failures-gate.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index bf12f5ddb5..65da66e2b8 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -323,7 +323,14 @@ rubric: - **PII:** flagged only for PII columns the change newly exposes, not for columns the base already surfaced. That comparison needs the base version's SQL; when it can't be compiled, PII columns are reported as non-blocking - warnings that may predate the PR. + warnings that may predate the PR. A model the PII check could not analyse is + listed as not fully verified. +- **Failures are never a clean pass:** if an engine check throws, the comment + names it and the verdict is at most COMMENT, never APPROVE (envelope + `engineErrors`). A failure on one file marks that file unverified and the rest + of the PR is still reviewed. +- **The gate clears itself:** when a rerun no longer blocks, the earlier blocking + altimate review is dismissed (needs `pull-requests: write`). ### Risk-tier path tokens diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 695049539b..6e8653c42e 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -221,16 +221,19 @@ export function coverageNotes(env: VerdictEnvelope): string[] { const undecided = env.findings.filter((f) => f.degraded).length if (undecided) notes.push(`${undecided} finding(s) could not be decided by the engine and are marked _unverified_.`) const unverified = env.scope?.unverified ?? [] - if (unverified.length) { - // One line per reason: models can lack the head compile or the base compile. - const byReason = new Map() - for (const u of unverified) byReason.set(u.reason, [...(byReason.get(u.reason) ?? []), u.path]) - for (const [reason, paths] of byReason) { - const head = paths.slice(0, 5).map((p) => `\`${p}\``).join(", ") - const more = paths.length > 5 ? ` and ${paths.length - 5} more` : "" - notes.push(`${paths.length} model(s) not verified by the engine — ${reason}: ${head}${more}.`) - } - notes.push("Run `dbt compile` (and compile the base into `target-base/`) for equivalence and lineage checks.") + const byReason = new Map() + for (const u of unverified) byReason.set(u.reason, [...(byReason.get(u.reason) ?? []), u.path]) + for (const [reason, paths] of byReason) { + const head = paths.slice(0, 5).map((p) => `\`${p}\``).join(", ") + const more = paths.length > 5 ? ` and ${paths.length - 5} more` : "" + const hint = /compiled SQL/.test(reason) + ? " Run `dbt compile` (and compile the base into `target-base/`) for equivalence and lineage checks." + : "" + notes.push(`${paths.length} model(s) not fully verified — ${reason}: ${head}${more}.${hint}`) + } + if (env.engineErrors?.length) { + const list = env.engineErrors.map((e) => `${e.method} ×${e.count} (${e.reason})`).join("; ") + notes.push(`Some engine checks failed and did not run: ${list}. This verdict is not a clean approval.`) } if (env.scope?.outOfScopeFiles) notes.push(`${env.scope.outOfScopeFiles} changed file(s) outside the dbt project were not reviewed.`) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index be517e00db..d91f43be3f 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -102,6 +102,8 @@ export interface GradeResult { export interface CheckResult { issues?: Array<{ rule: string; message: string; line?: number; severity?: string; category?: string }> piiColumns?: string[] + /** Core's PII pass could not parse the SQL: `piiColumns` is unknown, not empty. */ + piiAbstained?: boolean /** * True when the native core lint actually ran (parsed the SQL via the AST), * even if it found zero issues. Distinguishes "clean SQL" from "core @@ -119,7 +121,10 @@ export interface ReviewRunner { grade(sql: string, dialect: string): Promise check(sql: string, dialect: string, baseSql?: string): Promise equivalence(oldSql: string, newSql: string, dialect?: string): Promise - detectPii(sql: string, dialect: string): Promise<{ columns: string[] }> + /** `abstained`: the PII pass could not analyse the SQL, so `columns` is unknown. */ + detectPii(sql: string, dialect: string): Promise<{ columns: string[]; abstained?: boolean }> + /** Engine calls that threw during this review (method, first reason, count). */ + failures?(): Array<{ method: string; reason: string; count: number }> /** * Lexical scan (reserved-word aliases + dialect operators) — the curated lists * and detection live in the compiled core; this passes raw added diff lines. @@ -1114,35 +1119,55 @@ export async function runReview(input: OrchestrateInput): Promise false) } + // PR-level lanes (across files) that threw: reported with the engine errors. + const laneErrors: Array<{ method: string; reason: string; count: number }> = [] + const prLevel = (method: string, lane: Promise) => + lane.catch((err) => { + laneErrors.push({ method, reason: (err instanceof Error ? err.message : String(err)).slice(0, 200), count: 1 }) + return [] as Finding[] + }) + const failedFile = (file: { path: string }, err: unknown) => + unverified.push({ + path: file.path, + reason: `review failed for this file: ${(err instanceof Error ? err.message : String(err)).replace(/\s+/g, " ").slice(0, 160)}`, + }) await Promise.all( modelFiles.map(async (file) => { - const model = modelNameFromPath(file.path) - // For renames the previous content lives at oldPath, not the new path. - const oldRef = file.oldPath ?? file.path - const withOld = hasOldSide(file) - const [newSql, oldSql, compiledNew, compiledOld] = await Promise.all([ - file.status !== "deleted" ? getContent?.(file.path, "new") : Promise.resolve(undefined), - withOld ? getContent?.(oldRef, "old") : Promise.resolve(undefined), - file.status !== "deleted" ? getCompiled?.(file.path, "new") : Promise.resolve(undefined), - withOld ? getCompiled?.(oldRef, "old") : Promise.resolve(undefined), - ]) - // Engine lanes need dbt-compiled SQL. Raw SQL is used only when it holds - // no Jinja: the AST engine reads `{{ config() }}` as an injection attempt - // and a mixed raw-vs-compiled pair can never be proven equivalent, so a - // Jinja model without compiled output is marked unverified instead of - // producing warnings about its template syntax. The dbt-patterns lane - // always uses raw (it needs the Jinja). - const engineNewSql = compiledNew ?? (file.kind === "model_sql" && hasJinja(newSql) ? undefined : newSql) - const engineOldSql = compiledOld ?? (file.kind === "model_sql" && hasJinja(oldSql) ? undefined : oldSql) - if (file.status !== "deleted" && newSql && !engineNewSql) - unverified.push({ path: file.path, reason: "no compiled SQL for the head (run dbt compile)" }) - else if (withOld && oldSql && !engineOldSql) - unverified.push({ path: file.path, reason: "no compiled SQL for the base (compile the base into target-base)" }) - const impact = await input.runner.impact(model) - if (impact.hasManifest) anyManifest = true - const pii = engineNewSql ? (await input.runner.detectPii(engineNewSql, dialect)).columns : [] - const complex = engineNewSql && input.runner.isComplex ? await input.runner.isComplex(engineNewSql) : false - ctxByPath.set(file.path, { file, impact, pii, newSql, oldSql, engineNewSql, engineOldSql, complex }) + try { + const model = modelNameFromPath(file.path) + // For renames the previous content lives at oldPath, not the new path. + const oldRef = file.oldPath ?? file.path + const withOld = hasOldSide(file) + const [newSql, oldSql, compiledNew, compiledOld] = await Promise.all([ + file.status !== "deleted" ? getContent?.(file.path, "new") : Promise.resolve(undefined), + withOld ? getContent?.(oldRef, "old") : Promise.resolve(undefined), + file.status !== "deleted" ? getCompiled?.(file.path, "new") : Promise.resolve(undefined), + withOld ? getCompiled?.(oldRef, "old") : Promise.resolve(undefined), + ]) + // Engine lanes need dbt-compiled SQL. Raw SQL is used only when it holds + // no Jinja: the AST engine reads `{{ config() }}` as an injection attempt + // and a mixed raw-vs-compiled pair can never be proven equivalent, so a + // Jinja model without compiled output is marked unverified instead of + // producing warnings about its template syntax. The dbt-patterns lane + // always uses raw (it needs the Jinja). + const engineNewSql = compiledNew ?? (file.kind === "model_sql" && hasJinja(newSql) ? undefined : newSql) + const engineOldSql = compiledOld ?? (file.kind === "model_sql" && hasJinja(oldSql) ? undefined : oldSql) + if (file.status !== "deleted" && newSql && !engineNewSql) + unverified.push({ path: file.path, reason: "no compiled SQL for the head (run dbt compile)" }) + else if (withOld && oldSql && !engineOldSql) + unverified.push({ path: file.path, reason: "no compiled SQL for the base (compile the base into target-base)" }) + const impact = await input.runner.impact(model) + if (impact.hasManifest) anyManifest = true + const piiRes = engineNewSql ? await input.runner.detectPii(engineNewSql, dialect) : { columns: [] } + if (piiRes.abstained) unverified.push({ path: file.path, reason: "the PII check could not analyse this model" }) + const pii = piiRes.columns + const complex = engineNewSql && input.runner.isComplex ? await input.runner.isComplex(engineNewSql) : false + ctxByPath.set(file.path, { file, impact, pii, newSql, oldSql, engineNewSql, engineOldSql, complex }) + } catch (err) { + // One file's failure (unreadable content, an engine crash) degrades that + // file only; it must not abort the whole review. + failedFile(file, err) + } }), ) @@ -1303,20 +1328,32 @@ export async function runReview(input: OrchestrateInput): Promise + t.catch((err) => { + if (!laneFailed) failedFile(ctx.file, err) + laneFailed = true + return [] as Finding[] + }), + ), + ) + all.push(...settled) } // PR-level: cross-model sibling filter-consistency (divergent filters on a // shared upstream across the changed models). if (lanes.has("semantic_change")) { - all.push(await siblingConsistencyLane([...ctxByPath.values()], input.runner)) + all.push(await prLevel("sibling_consistency", siblingConsistencyLane([...ctxByPath.values()], input.runner))) } // PR-level: topology-aware equivalence for merge refactors (N models deleted + // 1 added that supersedes them). Per-model equivalence can't see these because // the new model has no 1:1 base. Advisory only (capped at warning). if (lanes.has("semantic_change")) { - all.push(await topologyEquivalenceLane(modelFiles, input.runner, getCompiled, dialect)) + all.push(await prLevel("topology_equivalence", topologyEquivalenceLane(modelFiles, input.runner, getCompiled, dialect))) } // schema.yml-level detectors (test removal) — run on changed YAML files @@ -1369,7 +1406,9 @@ export async function runReview(input: OrchestrateInput): Promise { if (!ctx.engineNewSql || ctx.file.status === "deleted") return // Cache hit: qualityLane already ran this exact check. - const cr = await input.runner.check(ctx.engineNewSql, dialect, ctx.engineOldSql) + const cr = await input.runner + .check(ctx.engineNewSql, dialect, ctx.engineOldSql) + .catch(() => ({ ran: false }) as CheckResult) if (cr.ran) coreRanFiles.add(ctx.file.path) }), ) @@ -1552,7 +1591,9 @@ export async function runReview(input: OrchestrateInput): Promise & { + rest: Pick +} + export async function postGitHubReview( env: VerdictEnvelope, target: GitHubTarget, - octo: Octokit = new Octokit({ auth: target.token }), + client?: GitHubClient, ): Promise { + const octo = client ?? new Octokit({ auth: target.token }) const { owner, repo, prNumber } = target const result: PostResult = { inlineFellBack: false } @@ -109,17 +118,21 @@ export async function postGitHubReview( // ignores line numbers) is not posted again on the next push. let posted = new Set() let lastBotHeadline: string | undefined + let staleBlocking: number[] = [] try { const [reviewComments, reviews] = await Promise.all([ octo.paginate(octo.rest.pulls.listReviewComments, { owner, repo, pull_number: prNumber, per_page: 100 }), octo.paginate(octo.rest.pulls.listReviews, { owner, repo, pull_number: prNumber, per_page: 100 }), ]) posted = postedFindingIds(reviewComments.map((c) => c.body)) - // Reviews are listed oldest first; only this bot's own latest review counts. - const mine = botLogin - ? reviews.filter((r) => r.user?.login === botLogin && BOT_REVIEW_RE.test(r.body ?? "")) - : [] - lastBotHeadline = mine.at(-1)?.body?.trim() + // Reviews are listed oldest first; only this bot's own reviews count. When + // the bot's login is unknown, fall back to the headline match alone for + // dismissal, and never skip (no own-review headline to compare). + const botReviews = reviews.filter( + (r) => BOT_REVIEW_RE.test(r.body ?? "") && (!botLogin || r.user?.login === botLogin), + ) + lastBotHeadline = botLogin ? botReviews.at(-1)?.body?.trim() : undefined + staleBlocking = botReviews.filter((r) => r.state === "CHANGES_REQUESTED").map((r) => r.id) } catch { /* listing failed: post everything rather than nothing */ } @@ -137,6 +150,28 @@ export async function postGitHubReview( const comments = inlineComments(env, posted, commentable) result.inlineSkippedAsPosted = inlineComments(env, new Set(), commentable).length - comments.length + // Gate lifecycle: when this run no longer blocks, an earlier blocking + // altimate review would keep the PR blocked forever. Dismiss it, pointing at + // the new verdict. (Requires `pull-requests: write`; a failure is non-fatal.) + if (event === "COMMENT" && staleBlocking.length) { + let dismissed = 0 + for (const id of staleBlocking) { + try { + await octo.rest.pulls.dismissReview({ + owner, + repo, + pull_number: prNumber, + review_id: id, + message: `Superseded by a newer altimate review: ${reviewBody}`, + }) + dismissed++ + } catch { + /* keep going; the summary still shows the current verdict */ + } + } + result.dismissedReviews = dismissed + } + // Nothing new inline, not blocking, and this bot's latest review already says // the same thing: the updated summary comment covers it; another identical // timeline entry per push is noise. A blocking verdict always posts, and a diff --git a/packages/opencode/src/altimate/review/runner.ts b/packages/opencode/src/altimate/review/runner.ts index eec3732d81..aa59b398ca 100644 --- a/packages/opencode/src/altimate/review/runner.ts +++ b/packages/opencode/src/altimate/review/runner.ts @@ -102,6 +102,16 @@ export interface DispatcherRunnerOptions { export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRunner { const checkCache = new Map() + // Engine calls that threw, by method → first reason. Each method still + // returns its empty result so one failure never aborts the review, but the + // failures are reported (envelope `engineErrors`, the comment, telemetry) + // instead of reading as "no findings". + const failures = new Map() + function fail(method: string, err: unknown) { + const reason = (err instanceof Error ? err.message : String(err)).replace(/\s+/g, " ").slice(0, 200) + const prev = failures.get(method) + failures.set(method, { reason: prev?.reason ?? reason, count: (prev?.count ?? 0) + 1 }) + } let manifestPromise: Promise | undefined async function loadManifest(): Promise { @@ -252,8 +262,14 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun ].filter((c): c is string => typeof c === "string" && !!c) // ran=true: the core parsed and analyzed the SQL (even if zero issues). // This lets the orchestrator defer structural checks to the AST lint. - out = { issues, piiColumns: [...new Set(piiColumns)], ran: true } - } catch { + out = { + issues, + piiColumns: [...new Set(piiColumns)], + ran: true, + piiAbstained: !!(data.pii as any)?.parse_error, + } + } catch (err) { + fail("check", err) out = { issues: [], piiColumns: [], ran: false } } checkCache.set(cacheKey, out) @@ -310,7 +326,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun const res = await Dispatcher.call("altimate_core.grade", { sql, schema_context: await resolveSchema() }) const data = (res.data ?? {}) as Record return { grade: data.overall_grade ?? data.grade } - } catch { + } catch (err) { + fail("grade", err) return {} } }, @@ -324,7 +341,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun const res = await Dispatcher.call("altimate_core.grain", { sql }) const d = (res.data ?? {}) as Record return { group_by: asArray(d.group_by), dedup_partition: asArray(d.dedup_partition) } - } catch { + } catch (err) { + fail("grain", err) return { group_by: [], dedup_partition: [] } } }, @@ -337,14 +355,16 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun try { const res = await Dispatcher.call("altimate_core.dbt_config_lint", { sql: rawSql }) out.push(...asArray((res.data as any)?.findings)) - } catch { + } catch (err) { + fail("dbtConfigLint", err) /* skip */ } if (oldRawSql) { try { const res = await Dispatcher.call("altimate_core.dbt_config_diff", { base_sql: oldRawSql, head_sql: rawSql }) out.push(...asArray((res.data as any)?.findings)) - } catch { + } catch (err) { + fail("dbtConfigLint", err) /* skip */ } } @@ -358,7 +378,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun try { const res = await Dispatcher.call("altimate_core.structural_diff", { base_sql: baseSql, head_sql: headSql }) return asArray((res.data as any)?.findings) - } catch { + } catch (err) { + fail("structuralDiff", err) return [] } }, @@ -368,7 +389,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun const res = await Dispatcher.call("altimate_core.source_filters", { sql }) const d = (res.data ?? {}) as Record return (d.filters ?? {}) as Record - } catch { + } catch (err) { + fail("sourceFilters", err) return {} } }, @@ -397,7 +419,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun const res = await Dispatcher.call("altimate_core.metadata", { sql }) const d = (res.data ?? {}) as Record return !!(d.has_window_functions || d.has_subqueries || (typeof d.node_count === "number" && d.node_count >= 12)) - } catch { + } catch (err) { + fail("isComplex", err) return false } }, @@ -423,7 +446,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun confidence: typeof c.confidence === "number" ? c.confidence : 0, masking: c.suggested_masking ?? undefined, })) - } catch { + } catch (err) { + fail("classifyPii", err) return [] } }, @@ -450,7 +474,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun rowsChanged: o.rows_changed ?? o.different ?? o.changed, summary: o.summary ?? r.summary, } - } catch { + } catch (err) { + fail("dataDiff", err) return null } }, @@ -468,7 +493,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun source: String(e.source ?? ""), target: String(e.target ?? ""), })) - } catch { + } catch (err) { + fail("columnLineage", err) return [] } }, @@ -484,7 +510,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun message: String(f.message ?? ""), line: f.line, })) - } catch { + } catch (err) { + fail("lexicalScan", err) return [] } }, @@ -529,16 +556,24 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun differences: diffs.map((d) => d?.description ?? String(d)), confidence: EngineCoerce.bandConfidence(data.confidence), } - } catch { + } catch (err) { + fail("equivalence", err) return { decided: false } } }, - async detectPii(sql: string): Promise<{ columns: string[] }> { + async detectPii(sql: string): Promise<{ columns: string[]; abstained?: boolean }> { // Text-based PII comes from altimate_core.check (schema.detect_pii is // warehouse-based and unavailable in CI). Reuses the memoized check. + // When core could not analyse the SQL (check did not run, or its PII + // parser reported a parse error) the empty list means "unknown", not + // "no PII": say so. const result = await runCheck(sql) - return { columns: result.piiColumns ?? [] } + return { columns: result.piiColumns ?? [], abstained: !result.ran || result.piiAbstained === true } + }, + + failures() { + return [...failures].map(([method, f]) => ({ method, reason: f.reason, count: f.count })) }, } } diff --git a/packages/opencode/src/altimate/review/telemetry.ts b/packages/opencode/src/altimate/review/telemetry.ts index 3fbe4af1bb..0e6f4c0ad5 100644 --- a/packages/opencode/src/altimate/review/telemetry.ts +++ b/packages/opencode/src/altimate/review/telemetry.ts @@ -117,6 +117,7 @@ export function emitReviewRun(input: { ai_duration_ms: env.ai?.durationMs, base_source: env.scope?.baseSource, out_of_scope_files: env.scope?.outOfScopeFiles ?? 0, + engine_errors: env.engineErrors?.reduce((n, e) => n + e.count, 0) ?? 0, stale_manifest: env.staleManifest === true, critical: env.summary.critical, warning: env.summary.warning, diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index 5a45e14351..b30d5f5fc4 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -156,6 +156,11 @@ export const VerdictEnvelope = z.object({ staleManifest: z.boolean().optional(), /** Base resolution and review coverage (see ReviewScope). */ scope: ReviewScope.optional(), + /** Engine calls that failed during the review. Their checks did not run, so + * the verdict is never a clean APPROVE when this is present. */ + engineErrors: z + .array(z.object({ method: z.string(), reason: z.string(), count: z.number().int().positive() })) + .optional(), /** The review policy applied: from the base branch, the working tree, or * defaults; its hash; and settings the PR changes but that were not applied. */ policy: z @@ -235,6 +240,7 @@ export interface BuildEnvelopeInput { scope?: ReviewScope ai?: VerdictEnvelope["ai"] policy?: VerdictEnvelope["policy"] + engineErrors?: VerdictEnvelope["engineErrors"] } function summarize(findings: Finding[], degraded: boolean): VerdictEnvelope["summary"] { @@ -246,7 +252,10 @@ function summarize(findings: Finding[], degraded: boolean): VerdictEnvelope["sum /** Assemble the verdict envelope (unsigned). Call signEnvelope to sign it. */ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { const rubric = input.rubric ?? DEFAULT_RUBRIC - const ideal = computeIdealVerdict(input.findings, rubric) + // An engine failure means some checks did not run: "no findings" is then + // unknown, not clean, so the verdict cannot be APPROVE. + const computed = computeIdealVerdict(input.findings, rubric) + const ideal = computed === "APPROVE" && input.engineErrors?.length ? "COMMENT" : computed const verdict = applyMode(ideal, input.mode) const degraded = input.degraded ?? input.findings.some((f) => f.degraded) return VerdictEnvelope.parse({ @@ -266,6 +275,7 @@ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { scope: input.scope, ai: input.ai, policy: input.policy, + engineErrors: input.engineErrors, generatedAt: input.generatedAt, }) } diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index da119a2728..ff2dfc3f03 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -1664,6 +1664,8 @@ export namespace Telemetry { /** Where the review base came from (flag, github_event, default_branch, …). */ base_source?: string out_of_scope_files?: number + /** Engine calls that threw during the review (their checks did not run). */ + engine_errors?: number stale_manifest?: boolean critical?: number warning?: number diff --git a/packages/opencode/src/cli/cmd/review.ts b/packages/opencode/src/cli/cmd/review.ts index cef6942c20..b1677b7fe1 100644 --- a/packages/opencode/src/cli/cmd/review.ts +++ b/packages/opencode/src/cli/cmd/review.ts @@ -194,7 +194,8 @@ export const ReviewCommand = cmd({ `Posted review to ${where}` + (r.inlineFellBack ? " (inline comments fell back to summary-only)" : "") + (r.inlineSkippedAsPosted ? ` (${r.inlineSkippedAsPosted} inline already on the PR)` : "") + - (r.reviewSkipped ? " (summary updated; no new review needed)" : ""), + (r.reviewSkipped ? " (summary updated; no new review needed)" : "") + + (r.dismissedReviews ? ` (dismissed ${r.dismissedReviews} earlier blocking review(s))` : ""), ) } } diff --git a/packages/opencode/test/altimate/review-failures-gate.test.ts b/packages/opencode/test/altimate/review-failures-gate.test.ts new file mode 100644 index 0000000000..07f2c4e252 --- /dev/null +++ b/packages/opencode/test/altimate/review-failures-gate.test.ts @@ -0,0 +1,237 @@ +import { describe, test, expect } from "bun:test" +import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { makeFinding } from "../../src/altimate/review/finding" +import { buildEnvelope, signEnvelope, verifyEnvelope } from "../../src/altimate/review/verdict" +import { renderSummary, findingMarker } from "../../src/altimate/review/format" +import { postGitHubReview, type GitHubClient } from "../../src/altimate/review/post-github" + +/** + * A review must never look clean because something broke: engine failures and + * PII abstentions are reported, one file's crash degrades only that file, and + * a blocking review is cleared when a rerun no longer blocks. + */ + +function runner(over: Partial = {}): ReviewRunner { + return { + 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: [] } + }, + ...over, + } as ReviewRunner +} + +const two = [ + { path: "models/a.sql", status: "added" as const, diff: "+select 1 as id\n" }, + { path: "models/b.sql", status: "added" as const, diff: "+select 2 as id\n" }, +] + +describe("engine failures are never clean", () => { + test("no findings plus an engine failure is COMMENT, not APPROVE, and the failure is shown", async () => { + const env = await runReview({ + changedFiles: two, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["sql_quality"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: runner({ failures: () => [{ method: "check", reason: "native core not loaded", count: 2 }] }), + getContent: async (f) => (f.endsWith("a.sql") ? "select 1 as id" : "select 2 as id"), + }) + expect(env.findings).toHaveLength(0) + expect(env.idealVerdict).toBe("COMMENT") + expect(env.engineErrors).toEqual([{ method: "check", reason: "native core not loaded", count: 2 }]) + expect(renderSummary(env)).toContain("Some engine checks failed and did not run: check ×2 (native core not loaded)") + }) + + test("engine errors are signed", () => { + const env = signEnvelope( + buildEnvelope({ findings: [], tier: "lite", mode: "comment", engineErrors: [{ method: "equivalence", reason: "x", count: 1 }] }), + ) + expect(env.verdict).toBe("COMMENT") + expect(verifyEnvelope(env)).toBe(true) + expect(verifyEnvelope({ ...env, engineErrors: undefined })).toBe(false) + }) + + test("without failures an empty review still approves", () => { + expect(buildEnvelope({ findings: [], tier: "lite", mode: "comment" }).verdict).toBe("APPROVE") + }) +}) + +describe("one file's failure degrades only that file", () => { + test("unreadable content for one model: the other is still reviewed", async () => { + let checked: string[] = [] + const env = await runReview({ + changedFiles: two, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["sql_quality"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: runner({ + async check(sql: string) { + checked.push(sql) + return { issues: [], ran: true } + }, + }), + getContent: async (f) => { + if (f.endsWith("a.sql")) throw new Error("EACCES: permission denied") + return "select 2 as id" + }, + }) + expect(checked).toContain("select 2 as id") + expect(env.scope?.unverified).toEqual([ + { path: "models/a.sql", reason: "review failed for this file: EACCES: permission denied" }, + ]) + }) + + test("a lane that throws on one file keeps the other file's findings", async () => { + const env = await runReview({ + changedFiles: two, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["sql_quality"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: runner({ + async check(sql: string) { + if (sql.includes("1")) throw new Error("engine panic") + return { issues: [{ rule: "select-star", message: "avoid", severity: "warning" }], ran: true } + }, + }), + getContent: async (f) => (f.endsWith("a.sql") ? "select 1 as id" : "select 2 as id"), + }) + expect(env.findings.some((f) => f.file === "models/b.sql")).toBe(true) + expect(env.scope?.unverified?.map((u) => u.path)).toEqual(["models/a.sql"]) + }) +}) + +describe("PII abstention", () => { + test("a PII check that could not analyse the model is reported, not treated as clean", async () => { + const env = await runReview({ + changedFiles: [two[0]], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["sql_quality"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: runner({ + async detectPii() { + return { columns: [], abstained: true } + }, + }), + getContent: async () => "select 1 as id", + }) + expect(env.scope?.unverified).toEqual([{ path: "models/a.sql", reason: "the PII check could not analyse this model" }]) + expect(renderSummary(env)).toContain("the PII check could not analyse this model") + }) +}) + +describe("posting: dedup, dismissal of a stale block, no repeat reviews", () => { + function fakeClient(state: { + reviewComments?: Array<{ body: string }> + reviews?: Array<{ id: number; body: string; state: string }> + }) { + const calls: Record = { createReview: [], dismissReview: [], createComment: [], updateComment: [] } + const client = { + async paginate(fn: any) { + if (fn === client.rest.issues.listComments) return [] + if (fn === client.rest.pulls.listReviewComments) return state.reviewComments ?? [] + if (fn === client.rest.pulls.listReviews) return state.reviews ?? [] + return [] + }, + rest: { + issues: { + listComments: () => {}, + async createComment(a: any) { + calls.createComment.push(a) + return { data: { id: 1 } } + }, + async updateComment(a: any) { + calls.updateComment.push(a) + return { data: { id: 1 } } + }, + }, + pulls: { + listReviewComments: () => {}, + listReviews: () => {}, + async get() { + return { data: { head: { sha: "abc" } } } + }, + async createReview(a: any) { + calls.createReview.push(a) + return { data: { id: 99 } } + }, + async dismissReview(a: any) { + calls.dismissReview.push(a) + return { data: {} } + }, + }, + }, + } + return { client: client as unknown as GitHubClient, calls } + } + const target = { token: "t", owner: "o", repo: "r", prNumber: 7 } + const engineFinding = (line?: number) => + makeFinding({ + severity: "warning", + category: "sql_quality", + title: "m: select-star", + body: "avoid", + file: "models/m.sql", + model: "m", + startLine: line, + evidence: { tool: "altimate_core.check", result: {} }, + ruleKey: "q:select-star", + }) + + test("a clean rerun dismisses the earlier blocking altimate review", async () => { + const env = buildEnvelope({ findings: [], tier: "lite", mode: "gate" }) + const { client, calls } = fakeClient({ + reviews: [ + { id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED" }, + { id: 12, body: "LGTM from a human", state: "CHANGES_REQUESTED" }, + ], + }) + const r = await postGitHubReview(env, target, client) + expect(calls.dismissReview.map((c) => c.review_id)).toEqual([11]) + expect(r.dismissedReviews).toBe(1) + }) + + test("a still-blocking rerun does not dismiss and posts REQUEST_CHANGES", async () => { + const blocking = makeFinding({ + severity: "critical", + category: "lineage_breakage", + title: "m: breaks downstream", + body: "x", + file: "models/m.sql", + evidence: { tool: "impact_analysis", result: {} }, + }) + const env = buildEnvelope({ findings: [blocking], tier: "full", mode: "gate" }) + const { client, calls } = fakeClient({ + reviews: [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED" }], + }) + await postGitHubReview(env, target, client) + expect(calls.dismissReview).toHaveLength(0) + expect(calls.createReview[0].event).toBe("REQUEST_CHANGES") + }) + + test("findings already on the PR are not re-posted, and with nothing new no review is added", async () => { + const f = engineFinding(3) + const env = buildEnvelope({ findings: [f], tier: "lite", mode: "comment" }) + const { client, calls } = fakeClient({ + reviewComments: [{ body: `⚠️ old\n\n${findingMarker(f.id)}` }], + reviews: [{ id: 5, body: "💬 Reviewed with comments — 1 warning (lite tier)", state: "COMMENTED" }], + }) + const r = await postGitHubReview(env, target, client) + expect(r.inlineSkippedAsPosted).toBe(1) + expect(r.reviewSkipped).toBe(true) + expect(calls.createReview).toHaveLength(0) + expect(calls.createComment.length + calls.updateComment.length).toBe(1) + }) +}) From 27dbe72477ea7504d4d2b1f8eb93f03083c2dd89 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 13 Nov 2026 11:10:41 +0530 Subject: [PATCH 15/23] fix(review): a failed run never clears a block; shallow CI checkouts fetch the base; upgrade note for gate users - a stale `CHANGES_REQUESTED` review is dismissed only when the new run completed (no `engineErrors`, no file that failed); an engine crash no longer unblocks a PR by making its findings disappear - in CI, a missing target branch is fetched from `origin` and a shallow history deepened (50/200/1000) until the merge-base exists, so the default `actions/checkout` works without `fetch-depth: 0`; still an error when that fails - docs: what changes for existing `gate` setups (pattern rules no longer block unless listed in `rubric.blockingRules`) and the new checkout behavior Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 10 ++++- packages/opencode/src/altimate/review/git.ts | 38 +++++++++++++++++-- .../src/altimate/review/post-github.ts | 10 ++++- .../altimate/review-failures-gate.test.ts | 23 +++++++++++ .../test/altimate/review-scope-diff.test.ts | 33 ++++++++++++++++ 5 files changed, 108 insertions(+), 6 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 65da66e2b8..615436ef6c 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -108,7 +108,7 @@ Options: | Flag | Description | |------|-------------| -| `--base ` | Base git ref. Defaults to the pull request's target branch in CI (GitHub `pull_request.base.ref` or `GITHUB_BASE_REF`, GitLab `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`), else the remote default branch. Always reduced to the merge-base with the head, so commits the base gained after the PR branched are never reviewed. In CI, a target branch that is not fetched is an error (use `fetch-depth: 0`). | +| `--base ` | Base git ref. Defaults to the pull request's target branch in CI (GitHub `pull_request.base.ref` or `GITHUB_BASE_REF`, GitLab `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`), else the remote default branch. Always reduced to the merge-base with the head, so commits the base gained after the PR branched are never reviewed. In CI, a shallow checkout is handled: the target branch is fetched and the history deepened until the merge-base is found. If that fails (no `origin`, no access), the review stops with an error rather than diffing against another branch. | | `--head ` | Head git ref. Omit to review the working tree. | | `--manifest ` | Path to the compiled `manifest.json`. When omitted, the reviewer walks up from the current directory to find the nearest `dbt_project.yml` and uses its adjacent `target/manifest.json`; the discovered path is logged to stderr. | | `--mode comment\|gate` | `comment` never blocks; `gate` exits non-zero on `REQUEST_CHANGES`. | @@ -203,7 +203,7 @@ jobs: | Input | How to produce it | Unlocks | |---|---|---| -| Full git history of the PR's target branch | `actions/checkout` with `fetch-depth: 0` | Correct base: the diff starts at the merge-base with the PR's target branch. A target branch that is not fetched is an error, never a silent fallback to `main`. | +| The PR's target branch and the merge-base | Fetched automatically from `origin` when the checkout is shallow; `fetch-depth: 0` avoids the extra fetches | Correct base: the diff starts at the merge-base with the PR's target branch. When it can't be fetched, the review stops with an error, never a silent fallback to `main`. | | `target/manifest.json` | `dbt compile` (or `dbt parse` for lint + lineage only) | Blast radius, lineage breakage, tiering. Without it the run is lint-only. | | `target/compiled/…` | `dbt compile` | Engine checks on the head (lint, grade, PII, grain). | | `target-base/compiled/…` | Compile the base ref into `target-base/` (below) | Equivalence proofs and column-breakage for modified models. | @@ -304,6 +304,12 @@ rubric: rules) or `ai`. Only `engine` findings count toward REQUEST_CHANGES. A pattern rule you trust can be allowed to block by naming its id in `rubric.blockingRules`. The advisory AI lane never blocks. +- **Upgrading a `gate` setup.** Before this policy, any critical finding in a + `blockOn` category could block, including pattern rules such as the regex + PII check. Now pattern-rule findings comment but don't block. To keep a + pattern rule blocking, add its id to `rubric.blockingRules`. A blocking + review is dismissed only by a later run that completed: when an engine call + or a file failed, the earlier block stays. ### What the PR comment shows diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index d7026f82c5..055842f958 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -202,6 +202,33 @@ async function mergeBase(a: string, b: string, cwd: string): Promise Promise): Promise { + if (branch.startsWith("-")) return false + try { + await git(["fetch", "--no-tags", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], cwd) + } catch { + return false + } + if (await found()) return true + for (const depth of [50, 200, 1000]) { + try { + if ((await git(["rev-parse", "--is-shallow-repository"], cwd)).trim() !== "true") return false + const headSha = (await git(["rev-parse", "HEAD"], cwd)).trim() + await git(["fetch", "--no-tags", `--deepen=${depth}`, "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`, headSha], cwd) + } catch { + return false + } + if (await found()) return true + } + return false +} + /** The PR's target branch from the CI provider, when the run is for a PR/MR. */ async function ciTargetBranch(env: NodeJS.ProcessEnv): Promise<{ branch: string; source: BaseSource } | undefined> { if (env.GITHUB_EVENT_PATH) { @@ -241,10 +268,15 @@ export async function resolveReviewBase(opts: ResolveBaseOptions): Promise { + for (const ref of [`origin/${target.branch}`, target.branch]) { + const sha = await mergeBase(ref, head, opts.cwd) + if (sha) return { ref, sha, source: target.source } + } + return undefined } + const found = (await find()) ?? ((await fetchTargetHistory(target.branch, opts.cwd, find)) ? await find() : undefined) + if (found) return found throw new Error( `PR target branch '${target.branch}' (${target.source}) is not available locally. ` + `Fetch it (actions/checkout with fetch-depth: 0, or git fetch origin ${target.branch}) or pass --base.`, diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index c432e8f318..a217290e4e 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -72,6 +72,12 @@ export interface PostResult { } /** Headline of a review this bot posted (see verdictHeadline). */ +/** True when no engine call and no file failed, so missing findings mean "fixed", not "not checked". */ +export function runCompleted(env: VerdictEnvelope): boolean { + if (env.engineErrors?.length) return false + return !(env.scope?.unverified ?? []).some((u) => u.reason.startsWith("review failed for this file")) +} + const BOT_REVIEW_RE = /(Approved|Reviewed with comments|Changes requested)\b.*\((trivial|lite|full) tier/ /** The Octokit surface the poster uses; injectable so the posting rules @@ -153,7 +159,9 @@ export async function postGitHubReview( // Gate lifecycle: when this run no longer blocks, an earlier blocking // altimate review would keep the PR blocked forever. Dismiss it, pointing at // the new verdict. (Requires `pull-requests: write`; a failure is non-fatal.) - if (event === "COMMENT" && staleBlocking.length) { + // Only a run that actually completed may clear a block: when an engine call + // or a file failed, the blocking finding may simply not have been produced. + if (event === "COMMENT" && staleBlocking.length && runCompleted(env)) { let dismissed = 0 for (const id of staleBlocking) { try { diff --git a/packages/opencode/test/altimate/review-failures-gate.test.ts b/packages/opencode/test/altimate/review-failures-gate.test.ts index 07f2c4e252..3fcc45fc79 100644 --- a/packages/opencode/test/altimate/review-failures-gate.test.ts +++ b/packages/opencode/test/altimate/review-failures-gate.test.ts @@ -203,6 +203,29 @@ describe("posting: dedup, dismissal of a stale block, no repeat reviews", () => expect(r.dismissedReviews).toBe(1) }) + test("a rerun where the engine or a file failed does not clear the block", async () => { + const blocking = [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED" }] + const crashed = buildEnvelope({ + findings: [], + tier: "full", + mode: "gate", + engineErrors: [{ method: "check", reason: "native core not loaded", count: 3 }], + }) + const a = fakeClient({ reviews: blocking }) + await postGitHubReview(crashed, target, a.client) + expect(a.calls.dismissReview).toHaveLength(0) + + const fileFailed = buildEnvelope({ + findings: [], + tier: "full", + mode: "gate", + scope: { unverified: [{ path: "models/m.sql", reason: "review failed for this file: boom" }] } as any, + }) + const b = fakeClient({ reviews: blocking }) + await postGitHubReview(fileFailed, target, b.client) + expect(b.calls.dismissReview).toHaveLength(0) + }) + test("a still-blocking rerun does not dismiss and posts REQUEST_CHANGES", async () => { const blocking = makeFinding({ severity: "critical", diff --git a/packages/opencode/test/altimate/review-scope-diff.test.ts b/packages/opencode/test/altimate/review-scope-diff.test.ts index f2503321fc..88051f363b 100644 --- a/packages/opencode/test/altimate/review-scope-diff.test.ts +++ b/packages/opencode/test/altimate/review-scope-diff.test.ts @@ -431,3 +431,36 @@ describe("reviewPullRequest end to end: monorepo, PR into a non-default branch", expect(env.findings.some((f) => f.file.includes("drift"))).toBe(false) }, 60_000) }) + +describe("a shallow CI checkout without the target branch", () => { + test("the target branch and enough history are fetched to find the merge-base", async () => { + const exec = (await import("node:util")).promisify((await import("node:child_process")).execFile) + const fsp = (await import("node:fs")).promises + const os = await import("node:os") + const pth = await import("node:path") + const g = (cwd: string, ...a: string[]) => exec("git", a, { cwd }).then((r) => r.stdout.trim()) + const origin = await fsp.realpath(await fsp.mkdtemp(pth.join(os.tmpdir(), "shallow-origin-"))) + await g(origin, "init", "-q", "-b", "main") + await g(origin, "config", "user.email", "t@t") + await g(origin, "config", "user.name", "t") + await g(origin, "config", "commit.gpgsign", "false") + await g(origin, "config", "uploadpack.allowReachableSHA1InWant", "true") + for (let i = 0; i < 5; i++) { + await fsp.writeFile(pth.join(origin, `f${i}.sql`), `select ${i}\n`) + await g(origin, "add", "-A") + await g(origin, "commit", "-qm", `main ${i}`) + } + const branchPoint = await g(origin, "rev-parse", "HEAD") + await g(origin, "checkout", "-q", "-b", "feature") + for (let i = 0; i < 3; i++) { + await fsp.writeFile(pth.join(origin, `pr${i}.sql`), `select ${i}\n`) + await g(origin, "add", "-A") + await g(origin, "commit", "-qm", `pr ${i}`) + } + const clone = await fsp.realpath(await fsp.mkdtemp(pth.join(os.tmpdir(), "shallow-clone-"))) + await exec("git", ["clone", "-q", "--depth", "1", "--branch", "feature", `file://${origin}`, clone]) + const resolved = await resolveReviewBase({ cwd: clone, env: { GITHUB_BASE_REF: "main" } }) + expect(resolved.source).toBe("github_env") + expect(resolved.sha).toBe(branchPoint) + }, 60_000) +}) From c74fe413738c7ef9469616527259e6cdf3e49953 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 10:21:08 +0530 Subject: [PATCH 16/23] fix(review): address review comments: engine `success:false`, per-file isolation, failed-file verdict, base PII abstention, bot-review identity - `runner.ts`: `altimate_core.*` handlers return `{ success: false }` instead of throwing; a `callCore` wrapper rethrows so each method records the failure in `engineErrors` and a failed check no longer reads as clean and PII-free - `orchestrate.ts`: the synchronous `lineageBreakageLane` / `detectModelPatterns` calls run as per-file tasks, and each schema.yml file is guarded, so one throw degrades only that file instead of aborting the review - `orchestrate.ts`: an unanalysable base no longer reports every head PII column as newly exposed; the file is marked unverified instead - `verdict.ts`: a file whose review failed downgrades an otherwise clean verdict to COMMENT (shared `FAILED_FILE_REASON`) - `post-github.ts`: stale blocking reviews must carry a hidden marker or a bot author, so a human review quoting the headline is never dismissed - `format.ts`: group unverified paths without re-spreading the array per item Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 6 +- .../src/altimate/review/orchestrate.ts | 53 ++++++++++---- .../src/altimate/review/post-github.ts | 33 ++++++--- .../opencode/src/altimate/review/runner.ts | 32 +++++--- .../opencode/src/altimate/review/verdict.ts | 12 ++- .../altimate/review-failures-gate.test.ts | 73 +++++++++++++++++-- .../test/altimate/review-runner.test.ts | 19 +++++ 7 files changed, 180 insertions(+), 48 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 6e8653c42e..870d48f8e0 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -222,7 +222,11 @@ export function coverageNotes(env: VerdictEnvelope): string[] { if (undecided) notes.push(`${undecided} finding(s) could not be decided by the engine and are marked _unverified_.`) const unverified = env.scope?.unverified ?? [] const byReason = new Map() - for (const u of unverified) byReason.set(u.reason, [...(byReason.get(u.reason) ?? []), u.path]) + for (const u of unverified) { + const paths = byReason.get(u.reason) + if (paths) paths.push(u.path) + else byReason.set(u.reason, [u.path]) + } for (const [reason, paths] of byReason) { const head = paths.slice(0, 5).map((p) => `\`${p}\``).join(", ") const more = paths.length > 5 ? ` and ${paths.length - 5} more` : "" diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index d91f43be3f..f1f83ecead 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -12,7 +12,14 @@ import { type ChangedFile, type DbtProjectLayout, filterChangedFiles, hasOldSide import { classifyPR, compilePathTokenResolver, TIER_LANES } from "./risk-tier" import { type Rubric, exclusionReason, clampSeverity } from "./rubric" import { type ReviewConfig } from "./config" -import { type ReviewMode, type ReviewScope, type VerdictEnvelope, buildEnvelope, signEnvelope } from "./verdict" +import { + type ReviewMode, + type ReviewScope, + type VerdictEnvelope, + FAILED_FILE_REASON, + buildEnvelope, + signEnvelope, +} from "./verdict" import { detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" import { type SelectItemColumn, normalizeSelectLine } from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" @@ -1129,7 +1136,7 @@ export async function runReview(input: OrchestrateInput): Promise unverified.push({ path: file.path, - reason: `review failed for this file: ${(err instanceof Error ? err.message : String(err)).replace(/\s+/g, " ").slice(0, 160)}`, + reason: `${FAILED_FILE_REASON}: ${(err instanceof Error ? err.message : String(err)).replace(/\s+/g, " ").slice(0, 160)}`, }) await Promise.all( modelFiles.map(async (file) => { @@ -1264,7 +1271,8 @@ export async function runReview(input: OrchestrateInput): Promise lineageBreakageLane(ctx.file, ctx.impact, input.rubric))) tasks.push(columnBreakageLane(ctx, input.runner, getCompiled, dialect)) } if (lanes.has("test_coverage")) tasks.push(missingGrainTestLane(ctx, input.runner)) @@ -1285,11 +1293,12 @@ export async function runReview(input: OrchestrateInput): Promise() + let baseAbstained = false if (hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { try { - basePii = new Set( - (await input.runner.detectPii(currentCtx.engineOldSql, dialect)).columns.map((c) => c.toLowerCase()), - ) + const baseRes = await input.runner.detectPii(currentCtx.engineOldSql, dialect) + baseAbstained = baseRes.abstained === true + basePii = new Set(baseRes.columns.map((c) => c.toLowerCase())) } catch { /* unknown base exposure: report as if new */ } @@ -1303,8 +1312,16 @@ export async function runReview(input: OrchestrateInput): Promise !diffScopedPii.classifiedColumns.has(col.toLowerCase())) : currentCtx.pii - // The fallback reports only columns the base did not already expose. - fallbackPii = fallbackPii.filter((col) => !basePii.has(col.toLowerCase())) + // Only columns this PR newly exposes: a PII column the base already + // surfaced is not this change's concern (the docs promise "newly expose"). + if (fallbackPii.length && baseAbstained) { + // An unanalysable base says nothing about what it exposed; reporting + // every head column as newly exposed would be a false positive. + unverified.push({ path: currentCtx.file.path, reason: "the PII check could not analyse the base model" }) + fallbackPii = [] + } else { + fallbackPii = fallbackPii.filter((col) => !basePii.has(col.toLowerCase())) + } const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql findings.push(...piiLane(currentCtx.file, fallbackPii, baseUnknown)) } @@ -1313,7 +1330,7 @@ export async function runReview(input: OrchestrateInput): Promise detectModelPatterns(ctx.file, ctx.newSql, input.rubric))) tasks.push(lexicalLane(ctx.file, input.runner)) } // dbt config/Jinja lint (materialization / incremental / contract) — gate on its @@ -1381,12 +1398,18 @@ export async function runReview(input: OrchestrateInput): Promise { - const oldRef = file.oldPath ?? file.path - const [oldContent, newContent] = await Promise.all([ - file.status !== "added" ? getContent?.(oldRef, "old") : Promise.resolve(undefined), - file.status !== "deleted" ? getContent?.(file.path, "new") : Promise.resolve(undefined), - ]) - return detectSchemaYmlPatterns(file, input.rubric, { oldContent, newContent }) + try { + const oldRef = file.oldPath ?? file.path + const [oldContent, newContent] = await Promise.all([ + file.status !== "added" ? getContent?.(oldRef, "old") : Promise.resolve(undefined), + file.status !== "deleted" ? getContent?.(file.path, "new") : Promise.resolve(undefined), + ]) + return detectSchemaYmlPatterns(file, input.rubric, { oldContent, newContent }) + } catch (err) { + // One malformed schema file degrades that file only. + failedFile(file, err) + return [] as Finding[] + } }), ) for (const findings of schemaFindingSets) all.push(findings) diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index a217290e4e..7f64500ec8 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -1,6 +1,6 @@ import { Octokit } from "@octokit/rest" import { promises as fs } from "node:fs" -import { type VerdictEnvelope, VCS_EVENT } from "./verdict" +import { type VerdictEnvelope, VCS_EVENT, FAILED_FILE_REASON } from "./verdict" import { commentableLines, inlineComments, @@ -71,14 +71,24 @@ export interface PostResult { dismissedReviews?: number } -/** Headline of a review this bot posted (see verdictHeadline). */ /** True when no engine call and no file failed, so missing findings mean "fixed", not "not checked". */ export function runCompleted(env: VerdictEnvelope): boolean { if (env.engineErrors?.length) return false - return !(env.scope?.unverified ?? []).some((u) => u.reason.startsWith("review failed for this file")) + return !(env.scope?.unverified ?? []).some((u) => u.reason.startsWith(FAILED_FILE_REASON)) } +/** Headline of a review this bot posted (see verdictHeadline). */ const BOT_REVIEW_RE = /(Approved|Reviewed with comments|Changes requested)\b.*\((trivial|lite|full) tier/ +/** Hidden marker in the body of every review this bot posts. */ +const BOT_REVIEW_MARKER = "" + +/** A review this bot posted: the headline, plus the marker or a bot author + * (reviews posted before the marker existed). A human review that quotes the + * headline is never treated as the bot's. */ +function isBotReview(r: { body?: string | null; user?: { type?: string } | null }): boolean { + const body = r.body ?? "" + return BOT_REVIEW_RE.test(body) && (body.includes(BOT_REVIEW_MARKER) || r.user?.type === "Bot") +} /** The Octokit surface the poster uses; injectable so the posting rules * (dedup, dismissal, skip) are testable without the network. */ @@ -118,7 +128,8 @@ export async function postGitHubReview( // this map only translates verdict → GitHub event. APPROVE always maps to a // COMMENT event — the bot must never submit a formal GitHub approval. const event = VCS_EVENT[env.verdict] - const reviewBody = verdictHeadline(env) + const headline = verdictHeadline(env) + const reviewBody = `${headline}\n\n${BOT_REVIEW_MARKER}` // Rerun dedup: a finding already commented inline (same fingerprint, which // ignores line numbers) is not posted again on the next push. @@ -132,12 +143,10 @@ export async function postGitHubReview( ]) posted = postedFindingIds(reviewComments.map((c) => c.body)) // Reviews are listed oldest first; only this bot's own reviews count. When - // the bot's login is unknown, fall back to the headline match alone for - // dismissal, and never skip (no own-review headline to compare). - const botReviews = reviews.filter( - (r) => BOT_REVIEW_RE.test(r.body ?? "") && (!botLogin || r.user?.login === botLogin), - ) - lastBotHeadline = botLogin ? botReviews.at(-1)?.body?.trim() : undefined + // the bot's login is unknown, fall back to the headline/marker match alone + // for dismissal, and never skip (no own-review headline to compare). + const botReviews = reviews.filter((r) => isBotReview(r) && (!botLogin || r.user?.login === botLogin)) + lastBotHeadline = botLogin ? botReviews.at(-1)?.body?.replace(BOT_REVIEW_MARKER, "").trim() : undefined staleBlocking = botReviews.filter((r) => r.state === "CHANGES_REQUESTED").map((r) => r.id) } catch { /* listing failed: post everything rather than nothing */ @@ -170,7 +179,7 @@ export async function postGitHubReview( repo, pull_number: prNumber, review_id: id, - message: `Superseded by a newer altimate review: ${reviewBody}`, + message: `Superseded by a newer altimate review: ${headline}`, }) dismissed++ } catch { @@ -184,7 +193,7 @@ export async function postGitHubReview( // the same thing: the updated summary comment covers it; another identical // timeline entry per push is noise. A blocking verdict always posts, and a // changed headline (e.g. after "Changes requested") posts a new review. - if (!comments.length && event === "COMMENT" && lastBotHeadline === reviewBody) { + if (!comments.length && event === "COMMENT" && lastBotHeadline === headline) { result.reviewSkipped = true return result } diff --git a/packages/opencode/src/altimate/review/runner.ts b/packages/opencode/src/altimate/review/runner.ts index aa59b398ca..39999dd96b 100644 --- a/packages/opencode/src/altimate/review/runner.ts +++ b/packages/opencode/src/altimate/review/runner.ts @@ -112,6 +112,14 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun const prev = failures.get(method) failures.set(method, { reason: prev?.reason ?? reason, count: (prev?.count ?? 0) + 1 }) } + // The altimate_core handlers catch their own exceptions and return + // `{ success: false, error }` instead of throwing. Rethrow so each method's + // catch records the failure; otherwise a failed call reads as a clean result. + const callCore: typeof Dispatcher.call = async (method, params, context) => { + const res: any = await Dispatcher.call(method, params, context) + if (res?.success === false) throw new Error(res.error || `${method} failed`) + return res + } let manifestPromise: Promise | undefined async function loadManifest(): Promise { @@ -207,7 +215,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun : hasTables ? { ...schema, dialect } : { tables: { _altimate_lint_: { columns: [{ name: "_", type: "string" }] } }, version: "1", dialect } - const res = await Dispatcher.call("altimate_core.check", { sql, schema_context: schemaContext, base_sql: baseSql }) + const res = await callCore("altimate_core.check", { sql, schema_context: schemaContext, base_sql: baseSql }) const data = (res.data ?? {}) as Record // `altimate_core.check` is a composite: { validation, lint, safety }. // The AST anti-pattern findings live at data.lint.findings (each a @@ -323,7 +331,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun async grade(sql: string): Promise { try { - const res = await Dispatcher.call("altimate_core.grade", { sql, schema_context: await resolveSchema() }) + const res = await callCore("altimate_core.grade", { sql, schema_context: await resolveSchema() }) const data = (res.data ?? {}) as Record return { grade: data.overall_grade ?? data.grade } } catch (err) { @@ -338,7 +346,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun async grain(sql: string): Promise<{ group_by: string[]; dedup_partition: string[] }> { try { - const res = await Dispatcher.call("altimate_core.grain", { sql }) + const res = await callCore("altimate_core.grain", { sql }) const d = (res.data ?? {}) as Record return { group_by: asArray(d.group_by), dedup_partition: asArray(d.dedup_partition) } } catch (err) { @@ -353,7 +361,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun ): Promise> { const out: any[] = [] try { - const res = await Dispatcher.call("altimate_core.dbt_config_lint", { sql: rawSql }) + const res = await callCore("altimate_core.dbt_config_lint", { sql: rawSql }) out.push(...asArray((res.data as any)?.findings)) } catch (err) { fail("dbtConfigLint", err) @@ -361,7 +369,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun } if (oldRawSql) { try { - const res = await Dispatcher.call("altimate_core.dbt_config_diff", { base_sql: oldRawSql, head_sql: rawSql }) + const res = await callCore("altimate_core.dbt_config_diff", { base_sql: oldRawSql, head_sql: rawSql }) out.push(...asArray((res.data as any)?.findings)) } catch (err) { fail("dbtConfigLint", err) @@ -376,7 +384,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun headSql: string, ): Promise> { try { - const res = await Dispatcher.call("altimate_core.structural_diff", { base_sql: baseSql, head_sql: headSql }) + const res = await callCore("altimate_core.structural_diff", { base_sql: baseSql, head_sql: headSql }) return asArray((res.data as any)?.findings) } catch (err) { fail("structuralDiff", err) @@ -386,7 +394,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun async sourceFilters(sql: string): Promise> { try { - const res = await Dispatcher.call("altimate_core.source_filters", { sql }) + const res = await callCore("altimate_core.source_filters", { sql }) const d = (res.data ?? {}) as Record return (d.filters ?? {}) as Record } catch (err) { @@ -416,7 +424,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun async isComplex(sql: string): Promise { try { - const res = await Dispatcher.call("altimate_core.metadata", { sql }) + const res = await callCore("altimate_core.metadata", { sql }) const d = (res.data ?? {}) as Record return !!(d.has_window_functions || d.has_subqueries || (typeof d.node_count === "number" && d.node_count >= 12)) } catch (err) { @@ -430,7 +438,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun try { // classify_pii classifies a SCHEMA's columns by name/type — feed it the // model's output columns as a one-table schema. - const res = await Dispatcher.call("altimate_core.classify_pii", { + const res = await callCore("altimate_core.classify_pii", { schema_context: { tables: { model: { columns: columns.map((name) => ({ name, type: "string" })) } }, version: "1", @@ -482,7 +490,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun async columnLineage(sql: string, dialect?: string): Promise> { try { - const res = await Dispatcher.call("altimate_core.column_lineage", { + const res = await callCore("altimate_core.column_lineage", { sql, schema_path: "", schema_context: await resolveSchema(), @@ -502,7 +510,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun async lexicalScan(addedLines: string[]) { if (!addedLines.length) return [] try { - const res = await Dispatcher.call("altimate_core.review_lexical_scan", { added_lines: addedLines }) + const res = await callCore("altimate_core.review_lexical_scan", { added_lines: addedLines }) const data = (res.data ?? {}) as Record return asArray(data.findings).map((f) => ({ rule: String(f.rule ?? "lexical"), @@ -519,7 +527,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun async equivalence(oldSql: string, newSql: string, dialect?: string): Promise { try { const schema = await resolveSchema() - const res = await Dispatcher.call("altimate_core.equivalence", { + const res = await callCore("altimate_core.equivalence", { sql1: oldSql, sql2: newSql, dialect, diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index b30d5f5fc4..bdc06288b0 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -249,13 +249,19 @@ function summarize(findings: Finding[], degraded: boolean): VerdictEnvelope["sum return { critical: tally.critical, warning: tally.warning, suggestion: tally.suggestion, degraded } } +/** Prefix of the `scope.unverified` reason for a file whose review threw. */ +export const FAILED_FILE_REASON = "review failed for this file" + /** Assemble the verdict envelope (unsigned). Call signEnvelope to sign it. */ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { const rubric = input.rubric ?? DEFAULT_RUBRIC - // An engine failure means some checks did not run: "no findings" is then - // unknown, not clean, so the verdict cannot be APPROVE. + // An engine failure or a file whose review failed means some checks did not + // run: "no findings" is then unknown, not clean, so the verdict cannot be APPROVE. const computed = computeIdealVerdict(input.findings, rubric) - const ideal = computed === "APPROVE" && input.engineErrors?.length ? "COMMENT" : computed + const incomplete = + !!input.engineErrors?.length || + (input.scope?.unverified ?? []).some((u) => u.reason.startsWith(FAILED_FILE_REASON)) + const ideal = computed === "APPROVE" && incomplete ? "COMMENT" : computed const verdict = applyMode(ideal, input.mode) const degraded = input.degraded ?? input.findings.some((f) => f.degraded) return VerdictEnvelope.parse({ diff --git a/packages/opencode/test/altimate/review-failures-gate.test.ts b/packages/opencode/test/altimate/review-failures-gate.test.ts index 3fcc45fc79..38ee065e37 100644 --- a/packages/opencode/test/altimate/review-failures-gate.test.ts +++ b/packages/opencode/test/altimate/review-failures-gate.test.ts @@ -113,7 +113,51 @@ describe("one file's failure degrades only that file", () => { }) }) +describe("a file whose review failed is never approved", () => { + test("a failed-file entry downgrades an otherwise clean verdict to COMMENT", () => { + const env = buildEnvelope({ + findings: [], + tier: "lite", + mode: "comment", + scope: { unverified: [{ path: "models/a.sql", reason: "review failed for this file: boom" }] } as any, + }) + expect(env.idealVerdict).toBe("COMMENT") + }) + + test("a synchronous detector that throws degrades only its file", async () => { + const env = await runReview({ + changedFiles: [{ path: "models/schema.yml", kind: "schema_yml", status: "modified" as const, diff: "- - unique\n" }] as any, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["sql_quality"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: runner(), + getContent: async () => { + throw new Error("git show failed") + }, + }) + expect(env.scope?.unverified).toEqual([{ path: "models/schema.yml", reason: "review failed for this file: git show failed" }]) + expect(env.idealVerdict).toBe("COMMENT") + }) +}) + describe("PII abstention", () => { + test("an unanalysable base does not report every head PII column as newly exposed", async () => { + const env = await runReview({ + changedFiles: [{ path: "models/a.sql", status: "modified" as const, diff: "-select 1 as id\n+select email from users\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["pii_exposure"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: runner({ + async detectPii(sql: string) { + return sql.includes("email") ? { columns: ["email"] } : { columns: [], abstained: true } + }, + }), + getContent: async (_f, side) => (side === "new" ? "select email from users" : "select 1 as id"), + }) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toHaveLength(0) + expect(env.scope?.unverified).toContainEqual({ path: "models/a.sql", reason: "the PII check could not analyse the base model" }) + }) + test("a PII check that could not analyse the model is reported, not treated as clean", async () => { const env = await runReview({ changedFiles: [two[0]], @@ -135,7 +179,7 @@ describe("PII abstention", () => { describe("posting: dedup, dismissal of a stale block, no repeat reviews", () => { function fakeClient(state: { reviewComments?: Array<{ body: string }> - reviews?: Array<{ id: number; body: string; state: string }> + reviews?: Array<{ id: number; body: string; state: string; user?: { type: string } }> }) { const calls: Record = { createReview: [], dismissReview: [], createComment: [], updateComment: [] } const client = { @@ -177,6 +221,7 @@ describe("posting: dedup, dismissal of a stale block, no repeat reviews", () => return { client: client as unknown as GitHubClient, calls } } const target = { token: "t", owner: "o", repo: "r", prNumber: 7 } + const bot = { type: "Bot" } const engineFinding = (line?: number) => makeFinding({ severity: "warning", @@ -194,7 +239,7 @@ describe("posting: dedup, dismissal of a stale block, no repeat reviews", () => const env = buildEnvelope({ findings: [], tier: "lite", mode: "gate" }) const { client, calls } = fakeClient({ reviews: [ - { id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED" }, + { id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED", user: bot }, { id: 12, body: "LGTM from a human", state: "CHANGES_REQUESTED" }, ], }) @@ -203,8 +248,25 @@ describe("posting: dedup, dismissal of a stale block, no repeat reviews", () => expect(r.dismissedReviews).toBe(1) }) + test("a human review quoting the headline is never dismissed; the marker identifies the bot", async () => { + const env = buildEnvelope({ findings: [], tier: "lite", mode: "gate" }) + const { client, calls } = fakeClient({ + reviews: [ + { id: 21, body: "Changes requested (full tier) until the backfill is fixed", state: "CHANGES_REQUESTED", user: { type: "User" } }, + { + id: 22, + body: "🛑 Changes requested — 1 critical (full tier)\n\n", + state: "CHANGES_REQUESTED", + user: { type: "User" }, + }, + ], + }) + await postGitHubReview(env, target, client) + expect(calls.dismissReview.map((c) => c.review_id)).toEqual([22]) + }) + test("a rerun where the engine or a file failed does not clear the block", async () => { - const blocking = [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED" }] + const blocking = [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED", user: bot }] const crashed = buildEnvelope({ findings: [], tier: "full", @@ -237,11 +299,12 @@ describe("posting: dedup, dismissal of a stale block, no repeat reviews", () => }) const env = buildEnvelope({ findings: [blocking], tier: "full", mode: "gate" }) const { client, calls } = fakeClient({ - reviews: [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED" }], + reviews: [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED", user: bot }], }) await postGitHubReview(env, target, client) expect(calls.dismissReview).toHaveLength(0) expect(calls.createReview[0].event).toBe("REQUEST_CHANGES") + expect(calls.createReview[0].body).toContain("") }) test("findings already on the PR are not re-posted, and with nothing new no review is added", async () => { @@ -249,7 +312,7 @@ describe("posting: dedup, dismissal of a stale block, no repeat reviews", () => const env = buildEnvelope({ findings: [f], tier: "lite", mode: "comment" }) const { client, calls } = fakeClient({ reviewComments: [{ body: `⚠️ old\n\n${findingMarker(f.id)}` }], - reviews: [{ id: 5, body: "💬 Reviewed with comments — 1 warning (lite tier)", state: "COMMENTED" }], + reviews: [{ id: 5, body: "💬 Reviewed with comments — 1 warning (lite tier)", state: "COMMENTED", user: bot }], }) const r = await postGitHubReview(env, target, client) expect(r.inlineSkippedAsPosted).toBe(1) diff --git a/packages/opencode/test/altimate/review-runner.test.ts b/packages/opencode/test/altimate/review-runner.test.ts index 538b2d7631..de07bc6ddc 100644 --- a/packages/opencode/test/altimate/review-runner.test.ts +++ b/packages/opencode/test/altimate/review-runner.test.ts @@ -162,3 +162,22 @@ describe("runner honors engine `decidable` flag (core 0.5.1)", () => { await tmp[Symbol.asyncDispose]?.() }) }) + +describe("engine handlers that report failure instead of throwing", () => { + test("a {success:false} result is an engine failure, not a clean or PII-free check", async () => { + await using tmp = await tmpdir() + dispatcherSpy = spyOn(Dispatcher, "call").mockImplementation((async () => ({ + success: false, + data: {}, + error: "Error: native core not loaded", + })) as any) + const runner = createDispatcherRunner({ manifestPath: path.join(tmp.path, "missing.json") }) + expect((await runner.check("select 1 as id", "duckdb")).ran).toBe(false) + expect((await runner.detectPii("select 1 as id", "duckdb")).abstained).toBe(true) + expect(await runner.grain!("select 1 as id")).toEqual({ group_by: [], dedup_partition: [] }) + const failed = runner.failures!().map((f) => f.method) + expect(failed).toContain("check") + expect(failed).toContain("grain") + expect(runner.failures!()[0].reason).toBe("Error: native core not loaded") + }) +}) From d56624de96b98c182e9f999e4c110bfd50a97098 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 11:13:29 +0530 Subject: [PATCH 17/23] fix(review): address review feedback: PII abstention keeps the block, typed unverified kinds, safer dismissal, deepen `--head` - `scope.unverified` entries carry a typed `kind` (`failed`, `abstained`, `not_compiled`). `reviewIncomplete` (engine errors, failed files, abstained checks) drives both the APPROVE -> COMMENT downgrade and `runCompleted`, so a PII abstention neither approves nor dismisses an earlier block. - Dismissal: only when this run's head (`scope.headSha`, new) is the PR's current head; only reviews carrying this project's marker (`` below the repo root); and only after the replacement review was posted (or skipped). A failed `createReview` keeps the block. - `fetchTargetHistory` deepens the configured head ref, not `HEAD`, and a shallow checkout starts with `--depth=50` instead of the target's whole history. - Runner: `dataDiff` records an in-band `success: false`; the config-diff failure is named `dbtConfigDiff`; stale `/* skip */` comments removed. - One `errorReason` helper (one line, bounded) for runner failures, lane errors and failed files, so a multi-line message cannot break the note. - Docs: abstentions block APPROVE and keep the block; dismissal rules. - Tests: verdict on unreadable content and PII abstention, a block surviving abstention, older-push and other-project runs not dismissing, no dismissal when the replacement review fails, deepening past 50 commits with `--head`, `dataDiff` in-band failure. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 18 ++-- packages/opencode/src/altimate/review/git.ts | 30 +++++- .../src/altimate/review/orchestrate.ts | 25 +++-- .../src/altimate/review/post-github.ts | 73 +++++++++------ packages/opencode/src/altimate/review/run.ts | 3 + .../opencode/src/altimate/review/runner.ts | 13 ++- .../opencode/src/altimate/review/verdict.ts | 35 +++++-- .../altimate/review-failures-gate.test.ts | 91 ++++++++++++++++++- .../test/altimate/review-runner.test.ts | 2 + .../test/altimate/review-scope-diff.test.ts | 31 +++++++ 10 files changed, 259 insertions(+), 62 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 615436ef6c..33e2da24be 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -309,7 +309,8 @@ rubric: PII check. Now pattern-rule findings comment but don't block. To keep a pattern rule blocking, add its id to `rubric.blockingRules`. A blocking review is dismissed only by a later run that completed: when an engine call - or a file failed, the earlier block stays. + or a file failed, or a check (such as PII) could not analyse a model, the + earlier block stays. ### What the PR comment shows @@ -331,12 +332,15 @@ rubric: SQL; when it can't be compiled, PII columns are reported as non-blocking warnings that may predate the PR. A model the PII check could not analyse is listed as not fully verified. -- **Failures are never a clean pass:** if an engine check throws, the comment - names it and the verdict is at most COMMENT, never APPROVE (envelope - `engineErrors`). A failure on one file marks that file unverified and the rest - of the PR is still reviewed. -- **The gate clears itself:** when a rerun no longer blocks, the earlier blocking - altimate review is dismissed (needs `pull-requests: write`). +- **Failures are never a clean pass:** if an engine check fails, a file's + review fails, or a check could not analyse a model, the comment names it and + the verdict is at most COMMENT, never APPROVE (envelope `engineErrors` and + `scope.unverified`). A failure on one file marks that file unverified and the + rest of the PR is still reviewed. +- **The gate clears itself:** when a completed rerun on the PR's current head + no longer blocks, the earlier blocking altimate review for the same dbt + project is dismissed after the new review is posted (needs + `pull-requests: write`). ### Risk-tier path tokens diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index 055842f958..a21152f9d2 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -208,18 +208,29 @@ async function mergeBase(a: string, b: string, cwd: string): Promise Promise): Promise { +async function fetchTargetHistory( + branch: string, + head: string, + cwd: string, + found: () => Promise, +): Promise { if (branch.startsWith("-")) return false + const shallow = async () => (await git(["rev-parse", "--is-shallow-repository"], cwd)).trim() === "true" try { - await git(["fetch", "--no-tags", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], cwd) + // In a shallow checkout, fetch only recent target history; the loop below + // deepens it. A full fetch would pull the target branch's whole history. + const depth = (await shallow()) ? ["--depth=50"] : [] + await git(["fetch", "--no-tags", ...depth, "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], cwd) } catch { return false } if (await found()) return true for (const depth of [50, 200, 1000]) { try { - if ((await git(["rev-parse", "--is-shallow-repository"], cwd)).trim() !== "true") return false - const headSha = (await git(["rev-parse", "HEAD"], cwd)).trim() + if (!(await shallow())) return false + // Deepen the history of the head being reviewed, which may differ from + // the checkout (`--head `). + const headSha = (await git(["rev-parse", "--verify", `${head}^{commit}`], cwd)).trim() await git(["fetch", "--no-tags", `--deepen=${depth}`, "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`, headSha], cwd) } catch { return false @@ -275,7 +286,7 @@ export async function resolveReviewBase(opts: ResolveBaseOptions): Promise { + try { + return (await git(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], cwd)).trim() || undefined + } catch { + return undefined + } +} + /** Compute a short hash of the manifest file for the verdict envelope. */ export async function manifestHash(manifestPath: string, cwd: string): Promise { try { diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index f1f83ecead..ec326668cb 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -18,6 +18,7 @@ import { type VerdictEnvelope, FAILED_FILE_REASON, buildEnvelope, + errorReason, signEnvelope, } from "./verdict" import { detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" @@ -1121,7 +1122,7 @@ export async function runReview(input: OrchestrateInput): Promise f.kind === "model_sql" || f.kind === "python_model") const ctxByPath = new Map() - const unverified: Array<{ path: string; reason: string }> = [] + const unverified: NonNullable = [] let anyManifest = false if (input.runner.manifestAvailable) { anyManifest = await input.runner.manifestAvailable().catch(() => false) @@ -1130,13 +1131,14 @@ export async function runReview(input: OrchestrateInput): Promise = [] const prLevel = (method: string, lane: Promise) => lane.catch((err) => { - laneErrors.push({ method, reason: (err instanceof Error ? err.message : String(err)).slice(0, 200), count: 1 }) + laneErrors.push({ method, reason: errorReason(err, 200), count: 1 }) return [] as Finding[] }) const failedFile = (file: { path: string }, err: unknown) => unverified.push({ path: file.path, - reason: `${FAILED_FILE_REASON}: ${(err instanceof Error ? err.message : String(err)).replace(/\s+/g, " ").slice(0, 160)}`, + reason: `${FAILED_FILE_REASON}: ${errorReason(err, 160)}`, + kind: "failed", }) await Promise.all( modelFiles.map(async (file) => { @@ -1160,13 +1162,18 @@ export async function runReview(input: OrchestrateInput): Promise !basePii.has(col.toLowerCase())) diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index 7f64500ec8..ddd7946ccd 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -1,6 +1,6 @@ import { Octokit } from "@octokit/rest" import { promises as fs } from "node:fs" -import { type VerdictEnvelope, VCS_EVENT, FAILED_FILE_REASON } from "./verdict" +import { type VerdictEnvelope, VCS_EVENT, reviewIncomplete } from "./verdict" import { commentableLines, inlineComments, @@ -71,23 +71,32 @@ export interface PostResult { dismissedReviews?: number } -/** True when no engine call and no file failed, so missing findings mean "fixed", not "not checked". */ +/** True when every check ran (no engine error, no failed file, no abstained + * check), so missing findings mean "fixed", not "not checked". */ export function runCompleted(env: VerdictEnvelope): boolean { - if (env.engineErrors?.length) return false - return !(env.scope?.unverified ?? []).some((u) => u.reason.startsWith(FAILED_FILE_REASON)) + return !reviewIncomplete(env) } /** Headline of a review this bot posted (see verdictHeadline). */ const BOT_REVIEW_RE = /(Approved|Reviewed with comments|Changes requested)\b.*\((trivial|lite|full) tier/ -/** Hidden marker in the body of every review this bot posts. */ -const BOT_REVIEW_MARKER = "" +/** Hidden marker in the body of every review this bot posts; reviews of a + * dbt project below the repository root also name it (`project=`). */ +const BOT_REVIEW_MARKER_RE = // -/** A review this bot posted: the headline, plus the marker or a bot author - * (reviews posted before the marker existed). A human review that quotes the - * headline is never treated as the bot's. */ -function isBotReview(r: { body?: string | null; user?: { type?: string } | null }): boolean { +function botReviewMarker(projectRoot: string | undefined): string { + return projectRoot ? `` : "" +} + +/** A review this bot posted for this dbt project: the headline, plus the + * marker or a bot author (reviews posted before the marker existed). A human + * review that quotes the headline is never treated as the bot's, and in a + * monorepo one project's run never touches another project's review. */ +function isBotReview(r: { body?: string | null; user?: { type?: string } | null }, projectRoot: string | undefined): boolean { const body = r.body ?? "" - return BOT_REVIEW_RE.test(body) && (body.includes(BOT_REVIEW_MARKER) || r.user?.type === "Bot") + if (!BOT_REVIEW_RE.test(body)) return false + const marker = BOT_REVIEW_MARKER_RE.exec(body) + if (!marker && r.user?.type !== "Bot") return false + return (marker?.[1] ?? "") === (projectRoot ?? "") } /** The Octokit surface the poster uses; injectable so the posting rules @@ -129,7 +138,8 @@ export async function postGitHubReview( // COMMENT event — the bot must never submit a formal GitHub approval. const event = VCS_EVENT[env.verdict] const headline = verdictHeadline(env) - const reviewBody = `${headline}\n\n${BOT_REVIEW_MARKER}` + const projectRoot = env.scope?.projectRoot || undefined + const reviewBody = `${headline}\n\n${botReviewMarker(projectRoot)}` // Rerun dedup: a finding already commented inline (same fingerprint, which // ignores line numbers) is not posted again on the next push. @@ -145,8 +155,10 @@ export async function postGitHubReview( // Reviews are listed oldest first; only this bot's own reviews count. When // the bot's login is unknown, fall back to the headline/marker match alone // for dismissal, and never skip (no own-review headline to compare). - const botReviews = reviews.filter((r) => isBotReview(r) && (!botLogin || r.user?.login === botLogin)) - lastBotHeadline = botLogin ? botReviews.at(-1)?.body?.replace(BOT_REVIEW_MARKER, "").trim() : undefined + const botReviews = reviews.filter( + (r) => isBotReview(r, projectRoot) && (!botLogin || r.user?.login === botLogin), + ) + lastBotHeadline = botLogin ? botReviews.at(-1)?.body?.replace(BOT_REVIEW_MARKER_RE, "").trim() : undefined staleBlocking = botReviews.filter((r) => r.state === "CHANGES_REQUESTED").map((r) => r.id) } catch { /* listing failed: post everything rather than nothing */ @@ -165,12 +177,27 @@ export async function postGitHubReview( const comments = inlineComments(env, posted, commentable) result.inlineSkippedAsPosted = inlineComments(env, new Set(), commentable).length - comments.length + // Anchor inline comments to the PR head commit. Without commit_id, GitHub's + // line-positioning is fragile and can 422 even on valid lines. + let commitId: string | undefined + try { + const pr = await octo.rest.pulls.get({ owner, repo, pull_number: prNumber }) + commitId = pr.data.head.sha + } catch { + /* fall back to default head resolution */ + } + // Gate lifecycle: when this run no longer blocks, an earlier blocking // altimate review would keep the PR blocked forever. Dismiss it, pointing at // the new verdict. (Requires `pull-requests: write`; a failure is non-fatal.) // Only a run that actually completed may clear a block: when an engine call - // or a file failed, the blocking finding may simply not have been produced. - if (event === "COMMENT" && staleBlocking.length && runCompleted(env)) { + // or a file failed, or a check abstained, the blocking finding may simply + // not have been produced. A run on an older push (its head is no longer the + // PR's head) never clears the block a newer push's run may have posted. + const headSha = env.scope?.headSha + const onCurrentHead = !headSha || !commitId || headSha === commitId + const dismissStale = async () => { + if (event !== "COMMENT" || !staleBlocking.length || !runCompleted(env) || !onCurrentHead) return let dismissed = 0 for (const id of staleBlocking) { try { @@ -195,19 +222,10 @@ export async function postGitHubReview( // changed headline (e.g. after "Changes requested") posts a new review. if (!comments.length && event === "COMMENT" && lastBotHeadline === headline) { result.reviewSkipped = true + await dismissStale() return result } - // Anchor inline comments to the PR head commit. Without commit_id, GitHub's - // line-positioning is fragile and can 422 even on valid lines. - let commitId: string | undefined - try { - const pr = await octo.rest.pulls.get({ owner, repo, pull_number: prNumber }) - commitId = pr.data.head.sha - } catch { - /* fall back to default head resolution */ - } - try { const r = await octo.rest.pulls.createReview({ owner, @@ -219,6 +237,7 @@ export async function postGitHubReview( comments: comments.length ? comments : undefined, }) result.reviewId = r.data.id + await dismissStale() } catch (e: any) { // Only a line-positioning error (422 Unprocessable) justifies dropping the // inline comments — anchoring outside the diff hunk. Other errors (auth, @@ -263,7 +282,9 @@ export async function postGitHubReview( body: reviewBody, }) result.reviewId = r.data.id + await dismissStale() } catch (e2: any) { + // The replacement review did not land: keep the earlier block. // Summary comment already landed; don't fail CI on a review-post error. result.postError = `${e2?.status ?? ""} ${e2?.message ?? e2}`.trim() } diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index c7813e3d9b..d2fb98d442 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -10,6 +10,7 @@ import { type ResolvedBase, gitRepoRoot, manifestHash, + resolveCommit, showAtRef, } from "./git" import { makeCompiledResolver, dbtProjectName, dbtProjectLayout } from "./compiled" @@ -237,6 +238,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise const resolved: ResolvedBase | undefined = needGit ? await resolveReviewBase({ cwd: opts.cwd, base: opts.base, head: opts.head }) : undefined + const headSha = resolved ? await resolveCommit(opts.head ?? "HEAD", opts.cwd) : undefined // The policy (.altimate/review.yml) comes from the BASE commit, so the PR // under review cannot relax its own rules; what it would change is listed. @@ -436,6 +438,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise scope: { baseRef: resolved?.ref ?? opts.base, baseSha: resolved?.sha, + headSha, baseSource: resolved?.source, projectRoot: projectRootRel, outOfScopeFiles: scoped.outOfScope || undefined, diff --git a/packages/opencode/src/altimate/review/runner.ts b/packages/opencode/src/altimate/review/runner.ts index 39999dd96b..cb4126f435 100644 --- a/packages/opencode/src/altimate/review/runner.ts +++ b/packages/opencode/src/altimate/review/runner.ts @@ -3,6 +3,7 @@ import { EngineCoerce } from "../native/engine-coerce" import { parseManifest } from "../native/dbt/manifest" import type { CheckResult, EquivalenceResult, GradeResult, ImpactResult, ReviewRunner } from "./orchestrate" import { buildReviewSchemaContext, type SchemaContext } from "./schema-context" +import { errorReason } from "./verdict" /** * Production ReviewRunner backed by the native Dispatcher (the Rust core). @@ -108,7 +109,7 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun // instead of reading as "no findings". const failures = new Map() function fail(method: string, err: unknown) { - const reason = (err instanceof Error ? err.message : String(err)).replace(/\s+/g, " ").slice(0, 200) + const reason = errorReason(err) const prev = failures.get(method) failures.set(method, { reason: prev?.reason ?? reason, count: (prev?.count ?? 0) + 1 }) } @@ -365,15 +366,13 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun out.push(...asArray((res.data as any)?.findings)) } catch (err) { fail("dbtConfigLint", err) - /* skip */ } if (oldRawSql) { try { const res = await callCore("altimate_core.dbt_config_diff", { base_sql: oldRawSql, head_sql: rawSql }) out.push(...asArray((res.data as any)?.findings)) } catch (err) { - fail("dbtConfigLint", err) - /* skip */ + fail("dbtConfigDiff", err) } } return out @@ -474,7 +473,11 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun target_warehouse: warehouse || undefined, }) const r = res as any - if (!r || r.success === false) return null + if (r?.success === false) { + fail("dataDiff", r.error ?? "data.diff failed") + return null + } + if (!r) return null const o = (r.outcome ?? {}) as Record return { rowsOnlyInBase: o.rows_only_in_source ?? o.removed ?? o.exclusive_source, diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index bdc06288b0..6b93b14701 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -118,8 +118,14 @@ export const ReviewScope = z.object({ outOfScopeFiles: z.number().int().nonnegative().optional(), /** Non-model renames with unchanged content, name, role and layer (pure moves): not re-reviewed. */ movedUnchangedFiles: z.number().int().nonnegative().optional(), - /** Models the engine lanes could not verify, with the reason. */ - unverified: z.array(z.object({ path: z.string(), reason: z.string() })).optional(), + /** Head commit the review ran on; a run on an older push never clears a block. */ + headSha: z.string().optional(), + /** Models the engine lanes could not verify, with the reason and its kind: + * `failed` (the file's review threw), `abstained` (a check could not analyse + * the SQL), `not_compiled` (no compiled SQL; engine lanes skipped). */ + unverified: z + .array(z.object({ path: z.string(), reason: z.string(), kind: z.enum(["failed", "abstained", "not_compiled"]).optional() })) + .optional(), }) export type ReviewScope = z.infer @@ -249,19 +255,32 @@ function summarize(findings: Finding[], degraded: boolean): VerdictEnvelope["sum return { critical: tally.critical, warning: tally.warning, suggestion: tally.suggestion, degraded } } +/** An error as one bounded line, for envelope reasons and the PR comment. */ +export function errorReason(err: unknown, max = 200): string { + return (err instanceof Error ? err.message : String(err)).replace(/\s+/g, " ").trim().slice(0, max) +} + /** Prefix of the `scope.unverified` reason for a file whose review threw. */ export const FAILED_FILE_REASON = "review failed for this file" +/** True when some check did not run: an engine call failed, a file's review + * threw, or a check abstained on a model. Missing findings then mean "not + * checked", so the run can neither APPROVE nor clear an earlier block. */ +export function reviewIncomplete(input: Pick): boolean { + if (input.engineErrors?.length) return true + return (input.scope?.unverified ?? []).some( + (u) => u.kind === "failed" || u.kind === "abstained" || u.reason.startsWith(FAILED_FILE_REASON), + ) +} + /** Assemble the verdict envelope (unsigned). Call signEnvelope to sign it. */ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { const rubric = input.rubric ?? DEFAULT_RUBRIC - // An engine failure or a file whose review failed means some checks did not - // run: "no findings" is then unknown, not clean, so the verdict cannot be APPROVE. + // An engine failure, a file whose review failed, or a check that abstained + // means some checks did not run: "no findings" is then unknown, not clean, + // so the verdict cannot be APPROVE. const computed = computeIdealVerdict(input.findings, rubric) - const incomplete = - !!input.engineErrors?.length || - (input.scope?.unverified ?? []).some((u) => u.reason.startsWith(FAILED_FILE_REASON)) - const ideal = computed === "APPROVE" && incomplete ? "COMMENT" : computed + const ideal = computed === "APPROVE" && reviewIncomplete(input) ? "COMMENT" : computed const verdict = applyMode(ideal, input.mode) const degraded = input.degraded ?? input.findings.some((f) => f.degraded) return VerdictEnvelope.parse({ diff --git a/packages/opencode/test/altimate/review-failures-gate.test.ts b/packages/opencode/test/altimate/review-failures-gate.test.ts index 38ee065e37..dac4afa702 100644 --- a/packages/opencode/test/altimate/review-failures-gate.test.ts +++ b/packages/opencode/test/altimate/review-failures-gate.test.ts @@ -90,8 +90,11 @@ describe("one file's failure degrades only that file", () => { }) expect(checked).toContain("select 2 as id") expect(env.scope?.unverified).toEqual([ - { path: "models/a.sql", reason: "review failed for this file: EACCES: permission denied" }, + { path: "models/a.sql", reason: "review failed for this file: EACCES: permission denied", kind: "failed" }, ]) + // A file that was never reviewed is not a clean pass. + expect(env.verdict).not.toBe("APPROVE") + expect(env.idealVerdict).toBe("COMMENT") }) test("a lane that throws on one file keeps the other file's findings", async () => { @@ -135,7 +138,7 @@ describe("a file whose review failed is never approved", () => { throw new Error("git show failed") }, }) - expect(env.scope?.unverified).toEqual([{ path: "models/schema.yml", reason: "review failed for this file: git show failed" }]) + expect(env.scope?.unverified).toEqual([{ path: "models/schema.yml", reason: "review failed for this file: git show failed", kind: "failed" }]) expect(env.idealVerdict).toBe("COMMENT") }) }) @@ -155,7 +158,11 @@ describe("PII abstention", () => { getContent: async (_f, side) => (side === "new" ? "select email from users" : "select 1 as id"), }) expect(env.findings.filter((f) => f.category === "pii_exposure")).toHaveLength(0) - expect(env.scope?.unverified).toContainEqual({ path: "models/a.sql", reason: "the PII check could not analyse the base model" }) + expect(env.scope?.unverified).toContainEqual({ + path: "models/a.sql", + reason: "the PII check could not analyse the base model", + kind: "abstained", + }) }) test("a PII check that could not analyse the model is reported, not treated as clean", async () => { @@ -171,8 +178,12 @@ describe("PII abstention", () => { }), getContent: async () => "select 1 as id", }) - expect(env.scope?.unverified).toEqual([{ path: "models/a.sql", reason: "the PII check could not analyse this model" }]) + expect(env.scope?.unverified).toEqual([ + { path: "models/a.sql", reason: "the PII check could not analyse this model", kind: "abstained" }, + ]) expect(renderSummary(env)).toContain("the PII check could not analyse this model") + // An abstention is "not checked", so the run cannot APPROVE. + expect(env.idealVerdict).toBe("COMMENT") }) }) @@ -288,6 +299,78 @@ describe("posting: dedup, dismissal of a stale block, no repeat reviews", () => expect(b.calls.dismissReview).toHaveLength(0) }) + test("a rerun where the PII check abstained does not clear an earlier PII block", async () => { + const blocking = [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED", user: bot }] + const abstained = buildEnvelope({ + findings: [], + tier: "full", + mode: "gate", + scope: { unverified: [{ path: "models/m.sql", reason: "the PII check could not analyse this model", kind: "abstained" }] }, + }) + expect(abstained.idealVerdict).toBe("COMMENT") + const { client, calls } = fakeClient({ reviews: blocking }) + await postGitHubReview(abstained, target, client) + expect(calls.dismissReview).toHaveLength(0) + }) + + test("a run on an older push never clears the block", async () => { + const env = buildEnvelope({ findings: [], tier: "lite", mode: "gate", scope: { headSha: "old" } }) + const { client, calls } = fakeClient({ + reviews: [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED", user: bot }], + }) + await postGitHubReview(env, target, client) + expect(calls.dismissReview).toHaveLength(0) + const current = buildEnvelope({ findings: [], tier: "lite", mode: "gate", scope: { headSha: "abc" } }) + const b = fakeClient({ + reviews: [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED", user: bot }], + }) + await postGitHubReview(current, target, b.client) + expect(b.calls.dismissReview.map((c) => c.review_id)).toEqual([11]) + }) + + test("in a monorepo one project's clean run never dismisses another project's block", async () => { + const env = buildEnvelope({ findings: [engineFinding(3)], tier: "lite", mode: "gate", scope: { projectRoot: "projects/a" } }) + const { client, calls } = fakeClient({ + reviews: [ + { + id: 31, + body: "🛑 Changes requested — 1 critical (full tier)\n\n", + state: "CHANGES_REQUESTED", + user: bot, + }, + { + id: 32, + body: "🛑 Changes requested — 1 critical (full tier)\n\n", + state: "CHANGES_REQUESTED", + user: bot, + }, + ], + }) + await postGitHubReview(env, target, client) + expect(calls.dismissReview.map((c) => c.review_id)).toEqual([32]) + expect(calls.createReview[0].body).toContain("") + }) + + test("the block is dismissed only after the replacement review is posted", async () => { + const env = buildEnvelope({ findings: [engineFinding(3)], tier: "lite", mode: "gate" }) + const { client, calls } = fakeClient({ + reviews: [{ id: 11, body: "🛑 Changes requested — 1 critical (full tier)", state: "CHANGES_REQUESTED", user: bot }], + }) + const order: string[] = [] + ;(client.rest.pulls as any).createReview = async () => { + order.push("create") + throw Object.assign(new Error("Server Error"), { status: 502 }) + } + ;(client.rest.pulls as any).dismissReview = async () => { + order.push("dismiss") + return { data: {} } + } + const r = await postGitHubReview(env, target, client) + expect(r.postError).toContain("502") + expect(order).toEqual(["create", "create"]) + expect(calls.dismissReview).toHaveLength(0) + }) + test("a still-blocking rerun does not dismiss and posts REQUEST_CHANGES", async () => { const blocking = makeFinding({ severity: "critical", diff --git a/packages/opencode/test/altimate/review-runner.test.ts b/packages/opencode/test/altimate/review-runner.test.ts index de07bc6ddc..40f832804b 100644 --- a/packages/opencode/test/altimate/review-runner.test.ts +++ b/packages/opencode/test/altimate/review-runner.test.ts @@ -175,7 +175,9 @@ describe("engine handlers that report failure instead of throwing", () => { expect((await runner.check("select 1 as id", "duckdb")).ran).toBe(false) expect((await runner.detectPii("select 1 as id", "duckdb")).abstained).toBe(true) expect(await runner.grain!("select 1 as id")).toEqual({ group_by: [], dedup_partition: [] }) + expect(await runner.dataDiff!("select 1 as id", "select 2 as id", ["id"])).toBeNull() const failed = runner.failures!().map((f) => f.method) + expect(failed).toContain("dataDiff") expect(failed).toContain("check") expect(failed).toContain("grain") expect(runner.failures!()[0].reason).toBe("Error: native core not loaded") diff --git a/packages/opencode/test/altimate/review-scope-diff.test.ts b/packages/opencode/test/altimate/review-scope-diff.test.ts index 88051f363b..0158213966 100644 --- a/packages/opencode/test/altimate/review-scope-diff.test.ts +++ b/packages/opencode/test/altimate/review-scope-diff.test.ts @@ -463,4 +463,35 @@ describe("a shallow CI checkout without the target branch", () => { expect(resolved.source).toBe("github_env") expect(resolved.sha).toBe(branchPoint) }, 60_000) + test("deepening follows --head (not the checkout) and goes beyond 50 commits", async () => { + const exec = (await import("node:util")).promisify((await import("node:child_process")).execFile) + const fsp = (await import("node:fs")).promises + const os = await import("node:os") + const pth = await import("node:path") + const g = (cwd: string, ...a: string[]) => exec("git", a, { cwd }).then((r) => r.stdout.trim()) + const origin = await fsp.realpath(await fsp.mkdtemp(pth.join(os.tmpdir(), "deepen-origin-"))) + await g(origin, "init", "-q", "-b", "main") + await g(origin, "config", "user.email", "t@t") + await g(origin, "config", "user.name", "t") + await g(origin, "config", "commit.gpgsign", "false") + await g(origin, "config", "uploadpack.allowReachableSHA1InWant", "true") + const commit = async (file: string, msg: string) => { + await fsp.writeFile(pth.join(origin, file), `${msg}\n`) + await g(origin, "add", "-A") + await g(origin, "commit", "-qm", msg) + } + await commit("seed.sql", "seed") + const branchPoint = await g(origin, "rev-parse", "HEAD") + for (let i = 0; i < 60; i++) await commit("main.sql", `main ${i}`) + await g(origin, "checkout", "-q", "-b", "pr", branchPoint) + for (let i = 0; i < 60; i++) await commit("pr.sql", `pr ${i}`) + await g(origin, "checkout", "-q", "-b", "other", "main") + await commit("other.sql", "other") + // The checkout is `other`; the review targets the `pr` head. + const clone = await fsp.realpath(await fsp.mkdtemp(pth.join(os.tmpdir(), "deepen-clone-"))) + await exec("git", ["clone", "-q", "--depth", "1", "--branch", "other", `file://${origin}`, clone]) + await g(clone, "fetch", "-q", "--depth", "1", "origin", "+refs/heads/pr:refs/remotes/origin/pr") + const resolved = await resolveReviewBase({ cwd: clone, head: "origin/pr", env: { GITHUB_BASE_REF: "main" } }) + expect(resolved.sha).toBe(branchPoint) + }, 60_000) }) From fd6608dc890a44c2acda43c1df7df36af7b82c38 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 15:50:27 +0530 Subject: [PATCH 18/23] fix(review): address re-review: not-compiled models, PR-head dismissal check, bot-authored dismissals, dialect parse failures - `reviewIncomplete` treats a model with no compiled head SQL (`kind: "not_compiled"`, new `side: "head"`) as incomplete: its engine and PII checks were skipped, so the run cannot APPROVE or dismiss a block; a base-side gap stays non-blocking; legacy entries without `side` count as head-side - dismissal requires the run to be proven on the PR head: `reviewedPrHead` accepts the head itself or the `refs/pull/N/merge` commit built from it (`scope.headParents`, read with `git cat-file` so shallow checkouts work) and fails closed when either SHA is unknown - `isBotReview` requires a bot author (or the token's own login via `users.getAuthenticated`); the marker only scopes the project. Unmarked bot reviews match any project; the project in the marker is URI-encoded so paths with spaces round-trip - `callCore` maps core `success:false` parse/unsupported-dialect errors to `CoreParseError`, which abstains (unknown result, PII still abstains) instead of adding `engineErrors` - the legacy `FAILED_FILE_REASON` prefix check applies only to envelopes without `kind`; misleading dismissal comment and test name fixed - docs: an otherwise clean verdict becomes COMMENT; parse-only runs never APPROVE a changed Jinja model; the gate's head check and bot-author rule - tests: not-compiled head/base verdicts and orchestration `side`, blocked rerun without compiled head, merge-commit checkout (fake client and a real depth-1 clone), unknown SHA / failed `pulls.get`, copied marker by a human, token-login reviews, legacy and spaced project markers, parse-failure abstention Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 23 +- packages/opencode/src/altimate/review/git.ts | 15 ++ .../src/altimate/review/orchestrate.ts | 8 +- .../src/altimate/review/post-github.ts | 88 ++++++-- packages/opencode/src/altimate/review/run.ts | 6 + .../opencode/src/altimate/review/runner.ts | 21 +- .../opencode/src/altimate/review/verdict.ts | 32 ++- .../altimate/review-failures-gate.test.ts | 208 ++++++++++++++++-- .../test/altimate/review-runner.test.ts | 32 ++- .../test/altimate/review-scope-diff.test.ts | 2 +- 10 files changed, 381 insertions(+), 54 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 33e2da24be..c84ffed295 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -309,8 +309,8 @@ rubric: PII check. Now pattern-rule findings comment but don't block. To keep a pattern rule blocking, add its id to `rubric.blockingRules`. A blocking review is dismissed only by a later run that completed: when an engine call - or a file failed, or a check (such as PII) could not analyse a model, the - earlier block stays. + or a file failed, a check (such as PII) could not analyse a model, or a + changed model had no compiled SQL, the earlier block stays. ### What the PR comment shows @@ -333,14 +333,23 @@ rubric: warnings that may predate the PR. A model the PII check could not analyse is listed as not fully verified. - **Failures are never a clean pass:** if an engine check fails, a file's - review fails, or a check could not analyse a model, the comment names it and - the verdict is at most COMMENT, never APPROVE (envelope `engineErrors` and - `scope.unverified`). A failure on one file marks that file unverified and the - rest of the PR is still reviewed. + review fails, a check could not analyse a model, or a changed model has no + compiled head SQL (its engine and PII checks were skipped), the comment names + it and an otherwise clean verdict becomes COMMENT, never APPROVE (envelope + `engineErrors` and `scope.unverified`); a real blocking finding still + blocks. A project reviewed without `dbt compile` (parse-only) therefore never + gets APPROVE for a changed Jinja model. A failure on one file marks that file + unverified and the rest of the PR is still reviewed. SQL the engine cannot + parse in your dialect is not an engine failure: the affected checks abstain + on that model (a PII abstention still marks it not fully verified). - **The gate clears itself:** when a completed rerun on the PR's current head no longer blocks, the earlier blocking altimate review for the same dbt project is dismissed after the new review is posted (needs - `pull-requests: write`). + `pull-requests: write`). "Current head" means the reviewed commit is the PR + head, or the merge commit a `pull_request` checkout builds from it + (`refs/pull/N/merge`). When either the reviewed commit or the PR head cannot + be determined, the block stays. Only reviews authored by a bot (or by the + token's own user) are dismissed. ### Risk-tier path tokens diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index a21152f9d2..fb0962a7bd 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -345,6 +345,21 @@ export async function resolveCommit(ref: string, cwd: string): Promise { + try { + const raw = await git(["cat-file", "-p", sha], cwd) + const header = raw.split("\n\n")[0] ?? "" + return header + .split("\n") + .filter((l) => l.startsWith("parent ")) + .map((l) => l.slice("parent ".length).trim()) + } catch { + return [] + } +} + /** Compute a short hash of the manifest file for the verdict envelope. */ export async function manifestHash(manifestPath: string, cwd: string): Promise { try { diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index ec326668cb..bed65b4924 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1162,12 +1162,18 @@ export async function runReview(input: OrchestrateInput): Promise