Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
f0289e8
feat(review): let the AI lane see whole PRs and the dbt parents of wh…
RaghwendraSingh Nov 16, 2026
cb23583
fix(review): honour `macro-paths` that point outside the dbt project …
RaghwendraSingh Nov 16, 2026
e4b92d1
feat(review): give every finding a stable `rule` id
RaghwendraSingh Nov 16, 2026
93196da
feat(review): per-rule posting tiers (inline, summary, off)
RaghwendraSingh Nov 16, 2026
0f14959
feat(review): mark findings on lines the PR did not add as pre-existing
RaghwendraSingh Nov 16, 2026
77deeeb
feat(review): cap inline comments and lay the summary out by where fi…
RaghwendraSingh Nov 16, 2026
8367db7
feat(review): list every changed file the review did not look at, wit…
RaghwendraSingh Nov 16, 2026
e37c6b2
fix(review): keep the folder-config hint for moved files in the ledger
RaghwendraSingh Nov 16, 2026
b41fe37
feat(review): cap rendered bodies, quote the matched line, post sugge…
RaghwendraSingh Nov 16, 2026
633640c
feat(review): record tokens, cost and calls for the AI review lane
RaghwendraSingh Nov 16, 2026
1d2fae8
feat(review): anchor rule findings to the diff line they matched
RaghwendraSingh Nov 16, 2026
da0be4a
fix(review): keep `self-join` and `join-case-folded-one-side` at summ…
RaghwendraSingh Nov 16, 2026
e49a9d4
feat(review): record undecidable equivalence in the coverage ledger
RaghwendraSingh Nov 16, 2026
f5f06ec
fix(review): apply held-out per-rule judging to two rule tiers
RaghwendraSingh Nov 16, 2026
c1960e4
fix(review): anchor `incremental-filter-created-only` to its filter line
RaghwendraSingh Nov 16, 2026
4fb7c00
fix(review): fold spacing and keyword case in `case-duplicate-when`
RaghwendraSingh Nov 16, 2026
bcba532
fix(review): see `IGNORE NULLS ORDER BY` in calls, and accept DuckDB'…
RaghwendraSingh Nov 16, 2026
41d1cc2
fix(review): recognise more temporary-code phrasing in `temporary-cod…
RaghwendraSingh Nov 16, 2026
a872691
fix(review): gate `microbatch-granularity-mismatch` on the adapter
RaghwendraSingh Nov 16, 2026
b73a356
fix(review): read output columns through `select * from <cte>`
RaghwendraSingh Nov 16, 2026
cef31b5
fix(review): anchor core check issues on Jinja models by compiled lin…
RaghwendraSingh Nov 16, 2026
47c9971
fix(review): anchor removed-column findings where the column was removed
RaghwendraSingh Nov 16, 2026
ae3d4e4
fix(review): anchor `macro-param-shifted` on the changed signature line
RaghwendraSingh Nov 16, 2026
d940017
fix(review): anchor `non-deterministic-dedup` on the line that orders…
RaghwendraSingh Nov 16, 2026
6c86e46
fix(review): raise `removed-final-layer-columns` to warning
RaghwendraSingh Nov 17, 2026
575b57b
fix(review): keep rules whose tier depends on the judging sample at s…
RaghwendraSingh Nov 17, 2026
4733424
fix(review): address review comments: UNION output names, package par…
RaghwendraSingh Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/opencode/src/altimate/review/adapter-capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ export interface AdapterCapability {
* leaves no table during the build. Undefined = not established.
*/
contractTableReplaceAtomic?: boolean
/**
* A microbatch model's `batch_size` must equal its `partition_by`
* granularity, or the run fails. Undefined = the adapter has no such rule.
*/
microbatchBatchSizeMatchesPartition?: boolean
/** Documentation backing the entries above. */
sources: string[]
}
Expand Down Expand Up @@ -61,7 +66,12 @@ export const ADAPTER_CAPABILITIES: Record<string, AdapterCapability> = {
},
bigquery: {
integerDivisionTruncates: false,
sources: ["https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#arithmetic_operators"],
microbatchBatchSizeMatchesPartition: true,
sources: [
"https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#arithmetic_operators",
"https://docs.getdbt.com/docs/build/incremental-microbatch",
"https://github.com/dbt-labs/dbt-adapters/blob/main/dbt-bigquery/src/dbt/include/bigquery/macros/materializations/incremental_strategy/microbatch.sql",
],
},
databricks: {
integerDivisionTruncates: false,
Expand Down
262 changes: 229 additions & 33 deletions packages/opencode/src/altimate/review/ai-review.ts

Large diffs are not rendered by default.

23 changes: 22 additions & 1 deletion packages/opencode/src/altimate/review/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { promises as fs } from "node:fs"
import YAML from "yaml"
import { createHash } from "node:crypto"
import { Rubric, DEFAULT_RUBRIC } from "./rubric"
import { ReviewMode } from "./verdict"
import { ReviewMode, DEFAULT_POSTING_POLICY } from "./verdict"
import { Severity } from "./finding"

/**
Expand Down Expand Up @@ -77,6 +77,27 @@ export const ReviewConfig = z.object({
.default({ enabled: false, warehouse: "" }),
/** Rubric overrides, deep-merged onto DEFAULT_RUBRIC. */
rubric: Rubric.partial().default({}),
/**
* Per-rule posting policy, keyed by finding `rule` id (`tool:rule`) or a
* `tool:*` glob: `inline` posts on the diff, `summary` keeps it to the
* summary comment, `off` drops it. Overrides the shipped defaults in
* rule-tiers.ts. Read from the base branch, so a PR cannot relax it.
* Engine rules that decide the verdict can be turned off only by exact id.
*/
rules: z.record(z.string(), z.enum(["inline", "summary", "off"])).default({}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Rule keys are not validated, so a typo in rules: is accepted and silently has no effect. Constrain keys to the tool:rule or tool:* shape so a malformed key fails at config load.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/review/config.ts, line 87:

<comment>Rule keys are not validated, so a typo in `rules:` is accepted and silently has no effect. Constrain keys to the `tool:rule` or `tool:*` shape so a malformed key fails at config load.</comment>

<file context>
@@ -77,6 +77,27 @@ export const ReviewConfig = z.object({
+   * rule-tiers.ts. Read from the base branch, so a PR cannot relax it.
+   * Engine rules that decide the verdict can be turned off only by exact id.
+   */
+  rules: z.record(z.string(), z.enum(["inline", "summary", "off"])).default({}),
+  /**
+   * How findings reach the PR: `inlineBudget` caps new inline comments per run
</file context>
Suggested change
rules: z.record(z.string(), z.enum(["inline", "summary", "off"])).default({}),
rules: z.record(z.string().regex(/^[\w.-]+:(\*|[\w-]+)$/), z.enum(["inline", "summary", "off"])).default({}),

/**
* How findings reach the PR: `inlineBudget` caps new inline comments per run
* (the rest stay in the summary), `inlineSeverityFloor` keeps lower
* severities out of inline comments, and `silentWhenClean` posts nothing on
* a run with no findings and nothing to report about coverage.
*/
posting: z
.object({
inlineBudget: z.number().int().min(0).default(DEFAULT_POSTING_POLICY.inlineBudget),
inlineSeverityFloor: Severity.default(DEFAULT_POSTING_POLICY.inlineSeverityFloor),
silentWhenClean: z.boolean().default(DEFAULT_POSTING_POLICY.silentWhenClean),
})
.default(() => ({ ...DEFAULT_POSTING_POLICY })),
/** Extra path suffixes to exclude from review. */
exclude: z.array(z.string()).default([]),
/**
Expand Down
51 changes: 35 additions & 16 deletions packages/opencode/src/altimate/review/dbt-patterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ const detectClock: Detector = (c) => {
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "clock_in_transform", lines: hits.slice(0, 3) } },
evidence: { tool: "dbt-patterns", result: { rule: "clock_in_transform", line: hits[0], lines: hits.slice(0, 3) } },
ruleKey: "idempotency:clock",
})
}
Expand Down Expand Up @@ -240,7 +240,7 @@ const detectFanout: Detector = (c) => {
confidence: "high",
evidence: {
tool: "dbt-patterns",
result: { rule: "fanout_join", joins: newJoins.map((j) => j.trim()).slice(0, 2) },
result: { rule: "fanout_join", line: newJoins[0], joins: newJoins.map((j) => j.trim()).slice(0, 2) },
},
ruleKey: "fanout:join-before-agg",
})
Expand Down Expand Up @@ -292,13 +292,14 @@ function addedLineNumbers(diff: string | undefined): Set<number> | undefined {
* change when one of the PR's added lines falls inside its line span (by text
* only when the diff carries no hunk headers).
*/
function dedupWindows(c: Ctx): Array<{ spec: string; text: string }> {
function dedupWindows(c: Ctx): Array<{ spec: string; text: string; line: string }> {
// Comments blanked with newlines kept, so offsets map to head line numbers.
const sql = c.newSql.replace(/\/\*[\s\S]*?\*\/|--[^\n]*|\{#[\s\S]*?#\}/g, (m) => m.replace(/[^\n]/g, " "))
const lineAt = (offset: number) => sql.slice(0, offset).split("\n").length
const headLines = c.newSql.split("\n")
const addedLines = addedLineNumbers(c.file.diff)
const added = c.added.map((l) => stripComments(l).trim()).filter((l) => l.length >= 3)
const out: Array<{ spec: string; text: string }> = []
const added = c.added.map((raw) => ({ raw, l: stripComments(raw).trim() })).filter(({ l }) => l.length >= 3)
const out: Array<{ spec: string; text: string; line: string }> = []
for (const m of sql.matchAll(/row_number\s*\(\s*\)\s*over\s*\(/gi)) {
const open = m.index! + m[0].length - 1
let depth = 0
Expand All @@ -312,11 +313,22 @@ function dedupWindows(c: Ctx): Array<{ spec: string; text: string }> {
}
if (close < 0) continue
const text = sql.slice(m.index!, close + 1)
const touched = addedLines
? [...addedLines].some((n) => n >= lineAt(m.index!) && n <= lineAt(close))
: added.some((l) => text.includes(l) || l.includes(text.replace(/\s+/g, " ")))
if (!touched) continue
out.push({ spec: sql.slice(open + 1, close).replace(/\s+/g, " ").trim(), text: text.replace(/\s+/g, " ") })
let line: string | undefined
if (addedLines) {
// The added line that opens the window, else the first added line inside it.
const first = lineAt(m.index!)
const last = lineAt(close)
const touched = [...addedLines].filter((n) => n >= first && n <= last).sort((a, b) => a - b)
if (!touched.length) continue
line = headLines[(touched.includes(first) ? first : touched[0]) - 1] ?? ""
} else {
const inside = added.filter(({ l }) => text.includes(l) || l.includes(text.replace(/\s+/g, " ")))
if (!inside.length) continue
const end = sql.indexOf("\n", m.index!)
const opener = sql.slice(sql.lastIndexOf("\n", m.index!) + 1, end < 0 ? undefined : end).trim()
line = (added.find(({ l }) => l === opener) ?? inside[0]).raw
}
out.push({ spec: sql.slice(open + 1, close).replace(/\s+/g, " ").trim(), text: text.replace(/\s+/g, " "), line })
}
return out
}
Expand All @@ -339,7 +351,7 @@ const detectDedupTie: Detector = (c) => {
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "dedup_no_tiebreaker", line: hit.text } },
evidence: { tool: "dbt-patterns", result: { rule: "dedup_no_tiebreaker", line: hit.line, window: hit.text } },
ruleKey: "dedup:no-tiebreaker",
})
}
Expand Down Expand Up @@ -369,7 +381,7 @@ const detectDedupLoadTimestamp: Detector = (c) => {
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "dedup_load_timestamp_only", line: w.text } },
evidence: { tool: "dbt-patterns", result: { rule: "dedup_load_timestamp_only", line: w.line, window: w.text } },
ruleKey: "dedup:load-timestamp-only",
})
}
Expand Down Expand Up @@ -437,6 +449,7 @@ const detectCountDistinct: Detector = (c) => {
const addedDistinct = c.added.some(hasCountDistinct)
const removedPlain = c.removed.some(hasPlainCount)
if (!((removedDistinct && addedPlain) || (addedDistinct && removedPlain))) return null
const line = c.added.find(removedDistinct && addedPlain ? hasPlainCount : hasCountDistinct)
return makeFinding({
severity: "warning",
category: "sql_correctness",
Expand All @@ -447,7 +460,7 @@ const detectCountDistinct: Detector = (c) => {
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "count_distinct_change" } },
evidence: { tool: "dbt-patterns", result: { rule: "count_distinct_change", line } },
ruleKey: "sql_correctness:count-distinct",
})
}
Expand Down Expand Up @@ -716,13 +729,15 @@ const detectCaseNoElse: Detector = (c) => {
(m) => !/\belse\b/i.test(m[0]) && !NULL_CONSUMING_CALL.test(joined.slice(0, m.index)),
)
if (!bare) return null
const head = bare[0].split("\n")[0].trim()
return pattern(
c,
"sql_correctness",
"suggestion",
"case-no-else",
"CASE without ELSE returns NULL for unmatched rows",
"A `CASE` expression with no `ELSE` silently yields NULL for any unmatched row, which can skew downstream metrics. Add an explicit `ELSE`.",
c.added.find((l) => stripComments(l).includes(head)),
)
}

Expand Down Expand Up @@ -758,7 +773,8 @@ const detectNaturalJoin: Detector = (c) => {

// 38. Self-join: same ref()/source() appears 2+ times.
const detectSelfJoin: Detector = (c) => {
if (!addedHit(c, /\bjoin\b/i)) return null
const hit = addedHit(c, /\bjoin\b/i)
if (!hit) return null
// A self-join reads one relation twice in the same FROM … JOIN chain. The same ref in two
// CTEs, or in two UNION branches, is two separate reads, not a self-join.
const sql = stripComments(c.newSql).replace(/\{\{\s*(ref|source)\s*\(([^)]*)\)\s*\}\}/gi, (_, kind, args) =>
Expand All @@ -772,6 +788,7 @@ const detectSelfJoin: Detector = (c) => {
"self-join",
"self-join detected — verify it can't fan out",
"The same relation is joined to itself. Self-joins are easy to get wrong (missing grain predicate → fan-out). Confirm the join keys keep it one-to-one.",
hit,
)
}

Expand All @@ -796,7 +813,7 @@ const detectWindowNoPartition: Detector = (c) => {
const head = sql.slice(lineStart, open + 1).trim()
return changed.some((l) => l.includes(head)) && !/partition\s+by/i.test(sql.slice(open, end))
})
const hit = unpartitioned ? changed[0] : undefined
const hit = unpartitioned ? c.added.find((l) => stripComments(l).trim() === changed[0]) : undefined

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SUGGESTION]: Anchors to the first OVER ( line, not the unpartitioned one

changed[0] is the first added line that contains any over (, while unpartitioned may be true for a later clause. When a diff adds a partitioned window before an unpartitioned one, the finding anchors to the correctly partitioned line with a window function has no PARTITION BY message, and once dbt-patterns:window-no-partition is promoted to inline the comment is posted there. Have the matchAll predicate record the offending head (use find rather than some) and anchor that line.

if (!hit) return null
return pattern(
c,
Expand Down Expand Up @@ -897,13 +914,15 @@ const detectOffsetNoOrder: Detector = (c) => {
const detectMultiCountDistinct: Detector = (c) => {
const count = (stripComments(c.added.join("\n")).match(/count\s*\(\s*distinct/gi) || []).length
if (count < 2) return null
const hit = addedHit(c, /count\s*\(\s*distinct/i)
return pattern(
c,
"warehouse_cost",
"suggestion",
"multi-count-distinct",
`${count} COUNT(DISTINCT …) in one query is expensive`,
"Multiple `COUNT(DISTINCT …)` each need their own sort/hash; on large tables this is a major cost. Consider APPROX_COUNT_DISTINCT or pre-aggregation where exactness isn't required.",
hit,
)
}

Expand Down Expand Up @@ -992,7 +1011,7 @@ export function detectMacroPatterns(
file: file.path,
model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "macro-var-no-default", var: name } },
evidence: { tool: "dbt-patterns", result: { rule: "macro-var-no-default", var: name, line } },
ruleKey: `materialization:macro-var-no-default`,
}),
)
Expand Down
Loading
Loading