From 7dcb5b413d769eacbae411566636206918c71056 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 12 Nov 2026 16:35:36 +0530 Subject: [PATCH 1/6] 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 2/6] 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 3/6] 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 4/6] 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 5/6] 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 6/6] 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,