import path from "node:path" import YAML from "yaml" import { type Finding, type ReviewCategory, type Severity, ReviewCategory as ReviewCategoryEnum, makeFinding, dedupe, findingOrigin, mergeRepeats, repeatGroupId, SEVERITY_ORDER, } from "./finding" import { type ChangedFile, type DbtProjectLayout, type DiffLine, type DiffRow, type NotReviewed, partitionChangedFiles, relativeToRoot, hasOldSide, isExcludedPath, walkDiffLines, walkDiffRows, } from "./diff-filter" export { type DiffLine, walkDiffLines } from "./diff-filter" import { classifyPR, compilePathTokenResolver, TIER_LANES } from "./risk-tier" import { type Rubric, exclusionReason, clampSeverity } from "./rubric" import { type ReviewConfig } from "./config" import { type ReviewMode, type ReviewScope, type VerdictEnvelope, FAILED_FILE_REASON, buildEnvelope, errorReason, isOutsideProjectReason, signEnvelope, computeIdealVerdict, verdictEligible, } from "./verdict" import { detectMacroPatterns, detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" import { type FinalOutputs, type RawReach, type RelationPrefixes, type SelectItem, type SelectItemColumn, finalOutputs, rawReach, refCovered, ROOT_SCOPE, SILENT_JINJA_TAG, normalizeSelectLine, selectItems, } from "./rule-catalog" import { listMirrorsModel, type ConsumerColumnList } from "./consumer-lists" import { detectUnitTestFixtures } from "./unit-tests" import { finalSelectNames } from "./select-list" import { detectTestAdequacy, detectThresholdLoosening } from "./test-adequacy" import { incrementalFindings, snapshotFindings, snapshotYmlFindings } from "./incremental-semantics" import { dbtProjectFindings, dispatchKwargFindings, dispatchVariants, docRefFindings, jinjaFindings, joinTargets, missingRefFindings, modelConfigFindings, isPackageProject, packageLockFindings, packagesFindings, quickstartModelFindings, testWindowFindings, testsOnNullColumns, yamlParseFindings, } from "./project-rules" import { type AiContextFile, type AiLaneStatus, type AiReviewFile, type AiReviewInput, type AiReviewResult, aiInputBudget, safeReason, selectAiFiles, selectAiFilesByQuota } from "./ai-review" import { type MacroCard, type ModelCard, attachContextCards } from "./ai-context-card" import { ruleTier } from "./rule-tiers" import { type AiSwitches, switchOn } from "./ai-switches" import { isAiOtherFile } from "./ai-other-files" import { AI_PYTHON_KIND, isAiPythonFile } from "./ai-python-files" import { type Convention, conventionTexts } from "./conventions" import { dropRulesOff } from "./rules-off" import { type RulePolicyDrops, type RulePostPolicy, type RuleVerdictValue, dropByRulePolicy, rulePolicyApplies, rulePolicyDrop, } from "./rule-post-policy" import { type AiVerifyEvidence, numberedSlice } from "./ai-verify" import { holdsCredentials, isCredentialPath } from "./credentials" import type { ColumnReach } from "../native/dbt/column-reach" const AI_SUPPORTING_KINDS = new Set(["macro", "test", "snapshot", "schema_yml", "source_yml", "seed", "project_config"]) /** * The deterministic review recipe. * * The LLM (when present) is a coordinator that turns engine output into prose — * but the findings and the verdict are produced HERE, mechanically, from * deterministic engine calls behind the `ReviewRunner` interface. That is the * defensible core: a generic reviewer guesses; this proves. * * `ReviewRunner` is intentionally high-level so the orchestrator is pure and * unit-testable. Production backs it with the native Dispatcher (see * tools/dbt-pr-review.ts); tests pass a fake. */ /** * Maps a regex-layer check code → a matcher for the equivalent core AST rule. * A regex twin is dropped ONLY when core lint ACTUALLY emitted the matching * finding for that file — not merely because core ran. This is the safe form: * if core's AST rule misses a specific instance (e.g. `= null` it doesn't flag), * the regex finding survives instead of falling through the crack. */ const CORE_AST_COVERED: Record = { "select-star": /select.?star|l001/, "cross-join": /cartesian|cross.?join/, "comma-join": /cartesian|cross.?join/, "constant-join": /cartesian|cross.?join|join.?without.?cond|l052/, "not-in-nullable": /not.?in|nullable/, "window-no-partition": /window.*partition/, "equals-null": /null.?comparison/, "leading-wildcard": /leading.?wildcard|like.?wildcard/, "division-no-guard": /division|divide/, "left-to-inner": /outer.?join|left.?to.?inner|l043/, "null-concat": /null.?propagat|null.?concat|l044/, "greatest-least-null": /greatest|least|l045/, "distinct-with-window": /distinct.?with.?window|l046/, "cast-float-to-int": /cast.?division|cast.?float|l048/, "now-in-filter": /clock.?in.?filter|l049/, "join-on-cast": /cast.?in.?join|join-on-cast|l050/, "full-outer-join": /full.?outer|l051/, "join-no-on": /join.?without.?cond|l052/, "in-with-null": /null.?in.?in.?list|l053/, "sum-of-ratio": /sum.?of.?ratio|l054/, "timezone-naive-now": /clock.?in.?filter|l049/, } /** * Extract function names a finding references in call form `NAME(` or backticked * `NAME`, lowercased — used to reconcile the regex portability catalog against * core's AST L033 (NonPortableFunction). Advice functions (coalesce, etc.) are * harmless: core never flags ANSI functions, so they can't cause suppression. */ function fnTokensOf(text: string): string[] { const out: string[] = [] for (const m of text.matchAll(/`([A-Za-z_][A-Za-z0-9_.]*)`|\b([A-Za-z_][A-Za-z0-9_.]+)\s*\(/g)) { out.push((m[1] ?? m[2]).toLowerCase()) } return out } /** Impact-analysis result, normalized. */ export interface ImpactResult { hasManifest: boolean /** SAFE | LOW | MEDIUM | HIGH | BREAKING (from the DAG walk). */ severity: "SAFE" | "LOW" | "MEDIUM" | "HIGH" | "BREAKING" | "UNKNOWN" directCount: number transitiveCount: number testCount: number } /** Equivalence result, normalized with a first-class undecidable state. */ export interface EquivalenceResult { /** False when the engine could not decide (no schema / undecidable). */ decided: boolean equivalent?: boolean differences?: string[] confidence?: "high" | "medium" | "low" } export interface GradeResult { grade?: string // A–F issues?: Array<{ rule: string; message: string; line?: number; severity?: string }> } export interface CheckResult { issues?: Array<{ rule: string; message: string; line?: number; severity?: string; category?: string }> piiColumns?: string[] /** Core's PII pass could not parse the SQL: `piiColumns` is unknown, not empty. */ piiAbstained?: boolean /** * True when the native core lint actually ran (parsed the SQL via the AST), * even if it found zero issues. Distinguishes "clean SQL" from "core * unavailable / degraded". When true, the orchestrator defers structural SQL * checks to the AST lint and suppresses the fragile regex twins. */ ran?: boolean } /** High-level engine surface the orchestrator depends on. */ export interface ReviewRunner { /** True when the configured dbt manifest loaded, independent of model lookup. */ manifestAvailable?(): Promise impact(model: string): Promise grade(sql: string, dialect: string): Promise check(sql: string, dialect: string, baseSql?: string): Promise equivalence(oldSql: string, newSql: string, dialect?: string): Promise /** `abstained`: the PII pass could not analyse the SQL, so `columns` is unknown. */ detectPii(sql: string, dialect: string): Promise<{ columns: string[]; abstained?: boolean }> /** Engine calls that threw during this review (method, first reason, count). */ failures?(): Array<{ method: string; reason: string; count: number }> /** * Lexical scan (reserved-word aliases + dialect operators) — the curated lists * and detection live in the compiled core; this passes raw added diff lines. * Optional so the orchestrator stays unit-testable with a fake runner. */ lexicalScan?(addedLines: string[]): Promise> /** Direct downstream models (name + file path) of a model, from the manifest DAG. */ downstreamModels?(model: string): Promise> /** Downstream models and exposures that read one column of a model (manifest + compiled SQL). */ columnReach?(model: string, column: string, dialect?: string): Promise /** * Direct dbt parents of the nodes defined in these files (project-relative * paths): models, seeds and snapshots by file, sources with their declared * columns, and the project's own macros. A changed yml maps to the models its * tests cover. Paths of parents are project-relative too. */ graphParents?(paths: string[]): Promise> /** * Consumers of a model that dbt refs don't show: exposures that depend on it, * and whether it has an enforced contract (with the declared columns). * Undefined when the model is not in the manifest. */ modelConsumers?( model: string, ): Promise< { exposures: Array<{ name: string; type?: string }>; contractEnforced: boolean; contractColumns: string[] } | undefined > /** A model's or snapshot's merged dbt `config` from the manifest (project + yml + inline). */ modelConfig?(name: string): Promise | undefined> /** Manifest facts about a model, snapshot or seed for the AI lane's context card: the * node defined in `path` in this project, else by name (this project first). Never throws. */ modelCard?(name: string, opts?: { path?: string }): Promise /** Models, snapshots and seeds of this project whose yml (`patch_path`) is `path`. Never throws. */ patchedModels?(path: string): Promise /** A macro's callers and adapter variants: a macro defined in `path` in this project * (the one named `name` first), else by name (this project first). Never throws. */ macroCard?(name: string, opts?: { path?: string; changedModels?: string[] }): Promise /** Column sets the model's `unique` / `unique_combination_of_columns` tests declare unique. */ declaredUniqueKeys?(model: string): Promise /** Column-lineage edges for a query: source `"table"."col"` → target output column. */ columnLineage?(sql: string, dialect: string): Promise> /** Classify a set of column names as PII (Email/SSN/…) with confidence + masking. */ classifyPii?( columns: string[], ): Promise> /** Structural complexity (window/subquery/large plan) from core `metadata` — a tiering signal. */ isComplex?(sql: string): Promise /** Extract a model's grain key (final GROUP BY + dedup PARTITION BY) from its SQL. */ grain?(sql: string): Promise<{ group_by: string[]; dedup_partition: string[] }> /** Declared primary/unique key of a model, from contract or unique test (manifest). */ declaredPrimaryKey?(model: string): Promise /** Per-upstream WHERE-filter columns of a model's SQL (cross-model consistency). */ sourceFilters?(sql: string): Promise> /** dbt config/Jinja lint over RAW model SQL (parses `{{ config() }}` in core). */ dbtConfigLint?( rawSql: string, oldRawSql?: string, ): Promise> /** AST base-vs-head structural diff — the `*_change` rules (parses both versions in core). */ structuralDiff?( baseSql: string, headSql: string, ): Promise> /** * Run a base-vs-head DATA diff (core DataParity over a warehouse connection): * actual row/value deltas. Returns null when no warehouse/driver is available * (the lane then skips — data-diff is a CI capability, not always present). */ dataDiff?( baseSql: string, headSql: string, keyColumns: string[], /** Warehouse connection name to diff against; omit for the default. */ warehouse?: string, ): Promise<{ rowsOnlyInBase?: number; rowsOnlyInHead?: number; rowsChanged?: number; summary?: string } | null> } export interface OrchestrateInput { changedFiles: ChangedFile[] config: ReviewConfig rubric: Rubric mode: ReviewMode runner: ReviewRunner /** Resolve RAW model contents (Jinja) from the working tree / git refs. */ getContent?: (file: string, side: "old" | "new") => Promise /** Resolve dbt-COMPILED SQL (rendered) for the engine lanes; undefined when * no compiled artifact exists. The dbt-patterns lane always uses raw. */ getCompiled?: (file: string, side: "old" | "new") => Promise generatedAt?: string manifestHash?: string coreVersion?: string modelVersion?: string /** altimate-code CLI release recorded in engine.cliVersion for audit reconstruction. */ cliVersion?: string /** * Optional LLM reviewer lane. Injected (not imported) so the orchestrator * stays pure/unit-testable: production wires `runAiReview` (harness LLM); * tests pass a fake or omit it (the lane is then skipped). Receives the * deterministic findings as grounding and returns ADVISORY findings only. */ aiReview?: (input: AiReviewInput) => Promise /** Why the AI lane is off when `aiReview` is not injected (shown in the comment). */ aiDisabledReason?: string /** Explicit `provider/model` for the AI lane. */ aiModel?: string /** Send the changed files' unchanged dbt parents to the AI lane as context. */ aiGraphContext?: boolean /** Attach a dbt manifest context card to each AI file (the `contextCard` switch; needs a manifest). */ aiContextCard?: boolean /** Give the AI lane what the dbt-grounded verifier reads (the `verify` switch). */ aiVerify?: boolean /** The review's resolved AI switches (ai-switches.ts); without them each switch reads its env variable. */ aiSwitches?: Partial /** Changed files outside the dbt project, for the AI lane only (`pythonFiles` switch). */ aiOutsideFiles?: ChangedFile[] /** The review's repository root (`--cwd`'s git root); env-named files must be outside it. */ reviewDir?: string /** Team conventions from the base branch (`conventions` switch), for the AI finder. */ conventions?: Convention[] /** Rule ids not posted when the AI lane runs (rules-off.ts); undefined keeps every type. */ rulesOff?: Set /** The rule-post policy over verified rule findings (rule-post-policy.ts); undefined turns it off. */ rulePolicy?: RulePostPolicy /** Fixed-string search over the dbt project at head, for the verifier. */ grepProject?: AiVerifyEvidence["grepProject"] /** Every file the PR changes (repo-relative), including files outside the dbt project; the verifier may read them. */ prFiles?: string[] /** Every rename the PR makes, new path → old path, including files outside the dbt project. */ prRenames?: Map /** PR metadata passed to the AI reviewer for intent checking. */ prTitle?: string prBody?: string /** G1 — attach the classifier's reason list to the envelope. */ explainTier?: boolean /** G2 — override the classifier's tier decision. Envelope carries tierForced:true. */ forceTier?: "trivial" | "lite" | "full" /** Manifest was stale relative to change-affecting files (see run.ts::detectStaleManifest). */ staleManifest?: boolean /** The dbt project's directories from dbt_project.yml (custom model-paths). */ layout?: DbtProjectLayout /** Names `ref()` can resolve to at head (repo resources + installed packages); undefined = unknown. */ resourceNames?: () => Promise | undefined> /** `{% docs %}` names installed packages define; undefined when that can't be known. */ packageDocNames?: () => Promise | undefined> /** What the review covered: base resolution and files left out of scope. */ scope?: Omit & { notReviewed?: NotReviewed[] } /** Drop the regex catalog's cross-engine portability findings (single known engine). */ suppressPortability?: boolean /** Other adapters the project supports (from its adapter-specific macros); portability advice is kept when any of them lacks the construct. */ portabilityTargets?: string[] /** The dialect came from config or the manifest, not the default guess. */ dialectKnown?: boolean /** Opt-in explicit column lists outside dbt (see consumer-lists.ts). */ consumerLists?: ConsumerColumnList[] /** Which review policy was applied (see config.ts loadReviewPolicy). */ policy?: VerdictEnvelope["policy"] } /** A catalog finding tagged as cross-engine portability advice. */ export function isCatalogPortability(f: Finding): boolean { 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 only * when the rule names the engines that support the construct and `dialect`, * and every one of the project's other supported adapters (`targets`), is * among them. Otherwise (an engine not listed, or support never established) * it may be an error on one of the project's engines and is kept. */ export function isSuppressiblePortability(f: Finding, dialect: string, targets: string[] = []): boolean { if (!isCatalogPortability(f)) return false const worksOn = (f.evidence?.result as { worksOn?: string[] })?.worksOn return !!worksOn && [dialect.toLowerCase(), ...targets].every((d) => worksOn.includes(d)) } /** Head-side line numbers of a unified diff: `commentable` holds the lines * GitHub accepts for an inline comment (added and context lines inside a * hunk); `added` holds only the `+` lines the PR introduced. */ export function scanDiffLines(diff: string | undefined): { commentable: Set; added: Set } { const commentable = new Set() const added = new Set() for (const { line, kind } of walkDiffLines(diff)) { commentable.add(line) if (kind === "+") added.add(line) } return { commentable, added } } /** Head-side line numbers each changed file's diff adds. A newly added file * counts every line of its diff as added. */ export function addedLinesByFile(files: ChangedFile[]): Map> { return new Map( files.map((f) => { const { commentable, added } = scanDiffLines(f.diff) return [f.path, f.status === "added" ? commentable : added] }), ) } /** * Keep a finding's `suggestion` only when GitHub can apply it as written: every * line of the range was added by the PR, the head file has those lines, and * the replacement changes them. Otherwise the replacement moves into the body * as a plain "Suggested fix" block. */ export async function validateSuggestions( findings: Finding[], getContent: OrchestrateInput["getContent"], added: Map>, ): Promise { const heads = new Map>() const head = (file: string) => { if (!heads.has(file)) heads.set(file, getContent?.(file, "new").catch(() => undefined) ?? Promise.resolve(undefined)) return heads.get(file)! } return Promise.all( findings.map(async (f) => { const s = f.suggestion if (!s) return f const lines = added.get(f.file) const range = Array.from({ length: s.endLine - s.startLine + 1 }, (_, i) => s.startLine + i) const inDiff = s.startLine <= s.endLine && !!lines && range.every((n) => lines.has(n)) const text = inDiff ? await head(f.file) : undefined const rows = text?.split("\n") const current = rows && rows.length >= s.endLine ? rows.slice(s.startLine - 1, s.endLine).join("\n") : undefined if (current !== undefined && current !== s.replacement) return f const { suggestion: _drop, ...rest } = f return { ...rest, body: `${f.body}\n\nSuggested fix:\n\`\`\`sql\n${s.replacement}\n\`\`\`` } as Finding }), ) } /** Shortest evidence text matched as a substring of an added line. */ const EVIDENCE_SUBSTRING_MIN = 12 /** * Give a line-less finding the diff line its rule matched. The rule records * the matched source text in `evidence.result.line`; this finds it in the * file's diff: the first added line with the same trimmed text, else the first * context line with it (which `markPreExisting` then marks pre-existing), else the * first added line containing it when it is long enough to be specific. A * finding whose text isn't in the diff keeps no line and stays in the summary. */ export function anchorByEvidence(findings: Finding[], files: ChangedFile[]): Finding[] { const diffs = new Map(files.map((f) => [f.path, f.diff])) const walked = new Map() return findings.map((f) => { if (typeof f.startLine === "number") return f const raw = (f.evidence?.result as { line?: unknown } | undefined)?.line const want = typeof raw === "string" ? raw.trim() : "" if (!want || !diffs.has(f.file)) return f if (!walked.has(f.file)) walked.set(f.file, [...walkDiffLines(diffs.get(f.file))]) const rows = walked.get(f.file)! const hit = rows.find((r) => r.kind === "+" && r.text.trim() === want) ?? rows.find((r) => r.kind === " " && r.text.trim() === want) ?? (want.length >= EVIDENCE_SUBSTRING_MIN ? rows.find((r) => r.kind === "+" && r.text.includes(want)) : undefined) return hit ? { ...f, startLine: hit.line, endLine: hit.line } : f }) } const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") /** The head line nearest a removed row: the `+` row at the same position in * its change block, else the nearest `+` row in its hunk, else (a pure * deletion) the context row after it, else the one before it. */ function headSiteOfRemoved(rows: DiffRow[], i: number): number | undefined { const hunk = rows[i].hunk let lo = i let hi = i while (lo > 0 && rows[lo - 1].hunk === hunk && rows[lo - 1].kind !== " ") lo-- while (hi < rows.length - 1 && rows[hi + 1].hunk === hunk && rows[hi + 1].kind !== " ") hi++ const block = rows.slice(lo, hi + 1) const plus = block.filter((r) => r.kind === "+") if (plus.length) { const k = block.filter((r) => r.kind === "-").indexOf(rows[i]) return plus[Math.min(k, plus.length - 1)].line } const inHunk = rows.map((r, j) => ({ r, j })).filter(({ r }) => r.hunk === hunk) const nearest = (kind: DiffRow["kind"]) => inHunk.filter(({ r }) => r.kind === kind).sort((a, b) => Math.abs(a.j - i) - Math.abs(b.j - i))[0]?.r const added = nearest("+") if (added) return added.line return ( inHunk.find(({ r, j }) => j > i && r.kind === " ")?.r.line ?? inHunk.filter(({ r, j }) => j < i && r.kind === " ").at(-1)?.r.line ) } /** * Anchor for a finding about removed output columns: the head-side site of * the base line that defined the first removed column the diff shows. The * defining line is the last removed line whose select item ends in the column * (`x.col`, `expr as col`), else the first removed line naming it. The site is * a `deletionSite`: the finding is about the PR's removal, not pre-existing * code. No removed line names a column → no anchor (the finding stays in the * summary). */ export function removedColumnAnchor( diff: string | undefined, columns: string[], ): Pick { const rows = [...walkDiffRows(diff)] const removed = rows.map((r, i) => ({ r, i, code: r.text.replace(/--.*$/, "").trim() })).filter((x) => x.r.kind === "-") for (const col of columns) { const id = `["\`\\[]?${escapeRe(col)}["\`\\]]?` const defines = new RegExp(`^,?\\s*(?:.*\\s+as\\s+|(?:[\\w"\`\\[\\]]+\\.)*)${id}\\s*,?$`, "i") const names = new RegExp(`(^|[^\\w])${escapeRe(col)}([^\\w]|$)`, "i") const def = removed.filter((x) => defines.test(x.code)).at(-1) ?? removed.find((x) => names.test(x.code)) const line = def && headSiteOfRemoved(rows, def.i) if (line !== undefined) return { startLine: line, endLine: line, deletionSite: true } } return {} } /** * Mark a finding anchored on a diff context line (one the PR did not add) as * `preExisting`, unless the line is a `deletionSite` standing in for code the * PR removed. Lines are never removed here: the envelope keeps every * finding's line, and posting filters inline comments to the lines GitHub * accepts. Every line of a newly added file counts as added. */ export function markPreExisting(findings: Finding[], files: ChangedFile[]): Finding[] { const lines = new Map(files.map((f) => [f.path, { ...scanDiffLines(f.diff), isNew: f.status === "added" }])) return findings.map((f) => { if (typeof f.startLine !== "number") return f const file = lines.get(f.file) if (!file || file.isNew || !file.commentable.has(f.startLine) || file.added.has(f.startLine) || f.deletionSite) return f return { ...f, preExisting: true } }) } /** True when SQL text contains Jinja (`{{ }}`, `{% %}` or `{# #}`). */ export function hasJinja(sql: string | undefined): boolean { return !!sql && /\{\{|\{%|\{#/.test(sql) } /** Derive the dbt model name from a model file path. */ export function modelNameFromPath(p: string): string { return path.basename(p).replace(/\.(sql|py)$/i, "") } const VALID_CATEGORIES = new Set(ReviewCategoryEnum.options) /** * Map a raw engine-issue category to a ReviewCategory WITHOUT discarding it. * Preserving the engine's category is what keeps the rubric's blockers (e.g. * contract_violation) effective — coercing everything to sql_quality would * silently neuter them. */ function mapCheckCategory(raw?: unknown): ReviewCategory { if (typeof raw !== "string" || !raw) return "sql_quality" const norm = raw.toLowerCase() if (VALID_CATEGORIES.has(norm)) return norm as ReviewCategory if (/contract/.test(norm)) return "contract_violation" if (/idempoten/.test(norm)) return "idempotency" if (/\btest\b|coverage/.test(norm)) return "test_coverage" if (/pii|sensitive/.test(norm)) return "pii_exposure" if (/cost|perf|scan|spill|prune/.test(norm)) return "warehouse_cost" if (/freshness|stale/.test(norm)) return "freshness" return "sql_quality" } function lineageBreakageLane(file: ChangedFile & { kind: string }, impact: ImpactResult, rubric: Rubric): Finding[] { const model = modelNameFromPath(file.path) const total = impact.directCount + impact.transitiveCount const degraded = !impact.hasManifest // dbt resolves `ref()` by MODEL NAME, not file path — so a rename that keeps // the same model name (a pure directory move) does NOT break lineage. Only a // rename that changes the model name is a break, alongside a deletion. const modelNameChanged = file.status === "renamed" && !!file.oldPath && modelNameFromPath(file.oldPath) !== model const isBreakingRemoval = file.status === "deleted" || modelNameChanged // Deleted/renamed model with downstream consumers is the canonical break. if (isBreakingRemoval && total >= rubric.thresholds.lineageWarnConsumers) { const sev = clampSeverity( "lineage_breakage", total >= rubric.thresholds.lineageCriticalConsumers ? "critical" : "warning", degraded ? "unknown" : "high", ) return [ makeFinding({ severity: sev, category: "lineage_breakage", title: `Model ${model} ${file.status} — ${total} downstream consumer${total !== 1 ? "s" : ""}`, body: `\`${model}\` is ${file.status} but ${total} downstream model${total !== 1 ? "s" : ""}` + ` (+${impact.testCount} test${impact.testCount !== 1 ? "s" : ""}) still depend on it.` + (degraded ? "\n\n_No manifest available — verify the blast radius locally._" : ""), file: file.path, model, confidence: degraded ? "unknown" : "high", degraded, evidence: { tool: "impact_analysis", result: impact }, ruleKey: `lineage_breakage:${file.status}`, rule: "impact-analysis:downstream-consumers", }), ] } // A modified model's blast radius is not a defect: it feeds risk tiering // (tier reasons name the downstream count), and concrete breakage on a // modified model comes from the column-removal lanes. return [] } async function semanticChangeLane( file: ChangedFile & { kind: string }, runner: ReviewRunner, oldSql: string | undefined, newSql: string | undefined, dialect: string, impact: ImpactResult, rubric: Rubric, unverified: Array<{ path: string; reason: string }>, ): Promise { if (!hasOldSide(file)) return [] if (!oldSql || !newSql || oldSql.trim() === newSql.trim()) return [] const model = modelNameFromPath(file.path) const eq = await runner.equivalence(oldSql, newSql, dialect) // Provably equivalent: stay silent — never nitpick what's proven safe. The core // engine models set-vs-multiset semantics (UNION vs UNION ALL, SELECT DISTINCT), // so equivalent:true is trustworthy for row multiplicity. if (eq.decided && eq.equivalent) return [] if (!eq.decided) { // Undecidable / no schema: the engine not knowing is not evidence of a change // (1 of 426 such findings matched a real defect on replay), so it goes to the // coverage ledger instead of the findings. unverified.push({ path: file.path, reason: "equivalence could not be proven (no schema or unsupported SQL); verify with a data-diff", }) return [] } // Decided NOT equivalent. THE FUSION: a proven behavior change to a model with // downstream consumers is a genuine break → critical (clamped by confidence, so // only high/medium can block). No downstream → warning. This is what makes // `semantic_change` ∈ blockOn meaningful: "provably not equivalent + N // downstream → BLOCK". const total = impact.directCount + impact.transitiveCount const baseSev: Severity = total >= rubric.thresholds.lineageCriticalConsumers ? "critical" : "warning" const diffs = (eq.differences ?? []).slice(0, 8) return [ makeFinding({ severity: clampSeverity("semantic_change", baseSev, eq.confidence ?? "medium"), category: "semantic_change", title: total > 0 ? `${model}: rewrite is NOT row-equivalent — ${total} downstream consumer${total !== 1 ? "s" : ""} affected` : `${model}: rewrite is NOT row-equivalent`, body: `\`${model}\` is described as a refactor but produces different results:\n` + (diffs.length ? diffs.map((d) => `- ${d}`).join("\n") : "- output differs") + `\n\nConfidence: ${eq.confidence ?? "medium"}.`, file: file.path, model, confidence: eq.confidence ?? "medium", evidence: { tool: "altimate_core.equivalence", result: { equivalent: false, differences: diffs } }, ruleKey: "semantic_change:not-equivalent", rule: "altimate-core.equivalence:not-equivalent", }), ] } /** * A check issue as evidence. On compiled SQL its line number doesn't exist in * the PR's file, so the compiled line's text goes in `line` (the number moves * to `compiledLine`) for `anchorByEvidence` to find among the added lines; * only text that is specific and unique in the compiled SQL. */ function checkEvidence(issue: { line?: number }, sql: string, linesMatchFile: boolean): object { if (linesMatchFile || typeof issue.line !== "number") return issue const rows = sql.split("\n") const text = rows[issue.line - 1]?.trim() ?? "" if (text.length < EVIDENCE_SUBSTRING_MIN || rows.filter((r) => r.trim() === text).length !== 1) return issue return { ...issue, line: text, compiledLine: issue.line } } /** * Fallback line for a non-deterministic-dedup issue on compiled SQL whose * compiled text is not in the raw diff (the window came from a macro, or a * Jinja-built line): the added line that opens a `row_number()` over the * named time column, else the added line ordering by it (`order by col`, * a macro's `order_by='col'`). No added line names the column → no line. */ function anchorDedupIssue(f: Finding, file: ChangedFile): Finding { if (typeof anchorByEvidence([f], [file])[0].startLine === "number") return f const cols = (/\[([^\]]+)\]/.exec(f.body)?.[1] ?? "").split(",").map((c) => c.trim()).filter(Boolean) const names = (t: string) => cols.some((c) => new RegExp(`(^|[^\\w])${escapeRe(c)}([^\\w]|$)`, "i").test(t)) const added = [...walkDiffLines(file.diff)].filter((r) => r.kind === "+") const hit = added.find((r) => /\brow_number\s*\(/i.test(r.text) && names(r.text)) ?? added.find((r) => /\border(\s+by|_by)\b/i.test(r.text) && names(r.text)) return hit ? { ...f, startLine: hit.line, endLine: hit.line } : f } async function qualityLane( file: ChangedFile & { kind: string }, runner: ReviewRunner, 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) const isStaging = /(^|\/)stg_|(^|\/)staging\//.test(file.path) || model.startsWith("stg_") const findings: Finding[] = [] // Diff-scoping (surface only findings the PR INTRODUCED, not pre-existing // issues in the changed file) is done IN CORE: we pass the base compiled SQL // and core returns only the findings new relative to it. The structural / // parsing comparison lives in the AST engine, not this plumbing layer. const check = await runner.check(sql, dialect, oldSql) for (const issue of check.issues ?? []) { // dbt-context tuning of the generic core lint ("what NOT to flag"): // dbt models are SELECT definitions, not standalone queries — a missing // LIMIT is correct, not a smell; and `select *` from a source is the // idiomatic staging pattern. Suppress those in the dbt context. const rule = String(issue.rule ?? "").toLowerCase() if (rule === "select-without-limit") continue if (isStaging && (rule === "select-star" || rule === "select_star")) continue // OLTP/index-oriented rules that don't apply to columnar analytics warehouses // (and false-fire on idiomatic dbt SQL like a correlated NOT EXISTS): if (rule === "correlated-subquery" || rule === "correlated_subquery") continue if (rule === "function-on-filter-column" || rule === "function-on-join-column") continue // Injection rules target queries assembled from user input; a model's UNION or // comment is ordinary SQL. if (INJECTION_RULE.test(rule)) continue // The engine's planner and parser cover less than the warehouses do: a type it can't // coerce, a function it doesn't know, or syntax it can't parse is a gap in the engine, // not an error in the model. Unresolved columns and tables are kept. const msg = String(issue.message ?? "") if (rule === "validate" && ENGINE_LIMIT_MESSAGE.test(msg)) continue // A syntax error on compiled SQL or on Jinja-templated raw SQL is a gap in the engine's parser or // the template, not the model. On plain raw SQL (no compile ran) it may be a real regression, so it // is kept as a suggestion with unknown confidence, which the verdict does not count. const syntax = rule === "validate" && /^syntax error/i.test(msg) if (syntax && (!linesMatchFile || /\{\{|\{%/.test(sql))) continue const cat = mapCheckCategory(issue.category) const isError = issue.severity === "error" // Error-severity contract/PII issues are blockable; others are warning/suggestion. let sev: Severity = isError ? "warning" : "suggestion" if (isError && (cat === "contract_violation" || cat === "pii_exposure")) sev = "critical" sev = syntax ? "suggestion" : clampSeverity(cat, sev, "high") const f = makeFinding({ severity: sev, category: cat, title: `${model}: ${issue.rule}`, body: issue.message, file: file.path, model, startLine: linesMatchFile ? issue.line : undefined, endLine: linesMatchFile ? issue.line : undefined, ...(syntax ? { confidence: "unknown" as const } : {}), evidence: { tool: "altimate_core.check", result: checkEvidence(issue, sql, linesMatchFile) }, // Include the message so distinct instances of the same rule (e.g. two // different non-portable functions) don't collapse under one fingerprint. ruleKey: `quality:${issue.rule}:${(issue.message ?? "").slice(0, 60)}`, }) findings.push(!linesMatchFile && rule === "non_deterministic_dedup" ? anchorDedupIssue(f, file) : f) } return findings } /** * Lexical lane — reserved-word aliases + dialect operators, detected by the * compiled core's `review_lexical_scan` over the raw ADDED diff lines (these * are pre-parse lexical checks; the curated lists live in the binary). Advisory. */ const INJECTION_RULE = /injection|^unbalanced_quote$/ const ENGINE_LIMIT_MESSAGE = /^(error during planning|execution error|this feature is not implemented)/i async function lexicalLane(file: ChangedFile & { kind: string }, runner: ReviewRunner): Promise { if (!runner.lexicalScan || file.status === "deleted") return [] const added = splitDiff(file.diff).added if (!added.length) return [] const model = modelNameFromPath(file.path) const raw = await runner.lexicalScan(added) return raw.map((f) => makeFinding({ severity: "suggestion", category: "sql_quality", title: `${model}: ${f.message.slice(0, 70)}`, body: f.message, file: file.path, model, confidence: "medium", evidence: { tool: "altimate_core.lexical", result: { rule: f.rule } }, ruleKey: `lexical:${f.rule}`, }), ) } /** Parse a column-lineage source `"db"."schema"."table"."col"` → { table, col }. */ function parseLineageSource(src: string): { table: string; col: string } { const parts = src.replace(/"/g, "").split(".").filter(Boolean) return { col: (parts.at(-1) ?? "").toLowerCase(), table: (parts.at(-2) ?? "").toLowerCase() } } /** * COLUMN-LEVEL breakage — the real lineage differentiator a linter can't do. * When a PR removes/renames an OUTPUT column of a model, trace (via the engine's * column lineage) which downstream models actually SELECT that column and flag * the concrete break: "removing `X` breaks `A`, `B`". Needs base+head compiled * SQL, the manifest DAG, and downstream compiled SQL. */ async function columnBreakageLane( ctx: ModelContext, runner: ReviewRunner, getCompiled: ((file: string, side: "old" | "new") => Promise) | undefined, dialect: string, ): Promise { if (!runner.columnLineage || !runner.downstreamModels || !getCompiled) return [] const { file, engineOldSql, engineNewSql } = ctx if (!engineOldSql || !engineNewSql || !hasOldSide(file)) return [] const model = modelNameFromPath(file.path) // 1. Output columns removed by this change (column-lineage targets, old − new). const oldCols = new Set((await runner.columnLineage(engineOldSql, dialect)).map((e) => e.target.toLowerCase()).filter(Boolean)) if (!oldCols.size) return [] const newCols = new Set((await runner.columnLineage(engineNewSql, dialect)).map((e) => e.target.toLowerCase()).filter(Boolean)) const removed = [...oldCols].filter((c) => !newCols.has(c)) if (!removed.length) return [] const removedSet = new Set(removed) // 2. Which downstream models actually consume a removed column of THIS model? const downstream = await runner.downstreamModels(model) const brokenBy = new Map>() // removedCol -> downstream models for (const d of downstream) { const dSql = await getCompiled(d.path, "new") if (!dSql) continue for (const edge of await runner.columnLineage(dSql, dialect)) { const { table, col } = parseLineageSource(edge.source) if (table === model.toLowerCase() && removedSet.has(col)) { if (!brokenBy.has(col)) brokenBy.set(col, new Set()) brokenBy.get(col)!.add(d.name) } } } if (!brokenBy.size) return [] const detail = [...brokenBy.entries()] .map(([col, models]) => `\`${col}\` → ${[...models].map((m) => `\`${m}\``).join(", ")}`) .join("; ") return [ makeFinding({ severity: "critical", category: "lineage_breakage", title: `${model}: removed column(s) break downstream models`, body: `This change removes/renames output column(s) that downstream models still SELECT: ${detail}. ` + `Those models will fail (or silently drop the column) on the next run. Update the consumers or keep the column.`, file: file.path, model, confidence: "high", evidence: { tool: "altimate_core.column_lineage", result: { removed, brokenBy: Object.fromEntries([...brokenBy].map(([k, v]) => [k, [...v]])) } }, ruleKey: `lineage_breakage:column-removed`, rule: "altimate-core.column-lineage:removed-columns", }), ] } /** * A query's output columns (lowercased); empty when unknown or `*`. Column * lineage gives columns that read a source column; the final SELECT's own * aliases add literal and function-only columns lineage can't see. */ async function outputColumns(runner: ReviewRunner, sql: string, dialect: string): Promise> { if (!runner.columnLineage) return new Set() const cols = (await runner.columnLineage(sql, dialect)).map((e) => e.target.toLowerCase()).filter(Boolean) // A star in the output means the list is incomplete: report nothing rather than guess. if (cols.some((c) => c === "*" || c.endsWith(".*"))) return new Set() // Lineage returned nothing (failed, or could not analyse this side): the // set is unknown. Filling it from the select list alone would make every // unaliased expression look removed when only one side's lineage failed. if (!cols.length) return new Set() // `*` in the final SELECT: keep lineage's own answer (it expands stars it can resolve), // plus the CTE's own list when the star reads a CTE of this query. const named = finalSelectNames(sql) return new Set([...cols, ...(named ?? [])]) } /** Output columns added and removed by the change (both empty when either side is unknown). */ async function columnDelta( ctx: ModelContext, runner: ReviewRunner, dialect: string, ): Promise<{ added: string[]; removed: string[]; current: Set }> { const none = { added: [], removed: [], current: new Set() } const { file, engineNewSql, engineOldSql, newSql, oldSql } = ctx if (file.status === "deleted") return none const withOld = hasOldSide(file) const delta = (current: Set, before?: Set) => !current.size || (withOld && !before?.size) ? none : { added: [...current].filter((c) => !before?.has(c)), removed: before ? [...before].filter((c) => !current.has(c)) : [], current, } // Compiled SQL on both sides: column lineage plus the final SELECT's names. if (engineNewSql && (!withOld || engineOldSql)) { const current = await outputColumns(runner, engineNewSql, dialect) const before = withOld ? await outputColumns(runner, engineOldSql!, dialect) : undefined return delta(current, before) } // Compiled SQL missing on either side (`dbt parse`-only CI, or a base that did // not compile): the raw model's own SELECT list, when it names every column. // Columns produced inside a macro stay unknown. if (!newSql) return none const current = rawSelectList(newSql) const before = withOld && oldSql ? rawSelectList(oldSql) : undefined return delta(current, before) } /** Output names of a raw (Jinja) model's final SELECT; empty when a Jinja * expression or tag is in the list, or when any item has no name of its own * (e.g. `amount::numeric(18,2)`): this list is the whole answer, not a supplement. */ function rawSelectList(sql: string): Set { const plain = sql .replace(/\{#[\s\S]*?#\}/g, " ") // A tag in the list (`{% if %}` / `{% for %}`) makes its columns conditional: // it becomes its own `__jinja__` item, which marks the list unknown. .replace(/\{%[\s\S]*?%\}/g, " , __jinja__ , ") .replace(/\{\{[\s\S]*?\}\}/g, " __jinja__ ") const names = finalSelectNames(plain, { complete: true }) // A Jinja expression inside an item (e.g. `{{ col }} as x`) leaves its alias // intact; only a Jinja item standing alone is unknown. if (!names || names.includes("__jinja__")) return new Set() return new Set(names) } const FINAL_LAYER = /(^|\/)(marts?|reporting|dimensional|presentation|extracts|exports)\//i // Intermediate/staging models nested under a final-layer folder are not read directly. const NOT_FINAL = /(^|\/)(intermediate|staging|base)\/|(^|\/)(int|stg|base)_[^/]*$/i const ticks = (xs: string[]) => xs.map((x) => `\`${x}\``).join(", ") /** Column names (lowercased) the given schema yml texts declare for `model`: * the `models:` entry with that name (all its versions), or a versioned * model's file name (`orders_v2` → `orders`, version 2). Unparsable files * declare nothing. */ export function ymlModelColumns(texts: string[], model: string): Set { const out = new Set() const target = model.toLowerCase() const names = (cols: unknown) => { if (Array.isArray(cols)) for (const c of cols) if (c && typeof c === "object" && "name" in c) out.add(String((c as any).name).toLowerCase()) } for (const text of texts) { let doc: any try { doc = YAML.parse(text) } catch { continue } for (const m of Array.isArray(doc?.models) ? doc.models : []) { const name = String(m?.name ?? "").toLowerCase() if (!name) continue const versions: any[] = Array.isArray(m.versions) ? m.versions : [] if (name === target) { names(m.columns) for (const v of versions) names(v?.columns) continue } const v = versions.find((v) => `${name}_v${String(v?.v ?? "").toLowerCase()}` === target) if (v) { names(m.columns) names(v.columns) } } } return out } /** * Consumers dbt refs don't show. A column removed or renamed on a model that * feeds exposures (dashboards, apps, ML) or has an enforced contract breaks * readers outside the DAG; the finding names them. And a new column missing * from an enforced contract fails `dbt build` — reported only when the project * opts in (`checkContractColumns`); `dbt build` already enforces it. */ async function consumerContractLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, opts: { checkContractColumns: boolean; changedYmlText: () => Promise }, ): Promise { if (!runner.modelConsumers || !runner.columnLineage) return [] const model = modelNameFromPath(ctx.file.path) const consumers = await runner.modelConsumers(model) if (!consumers) return [] const declared = consumers.exposures.length > 0 || consumers.contractEnforced // A final-layer model is read outside dbt (BI, exports) even when nothing is declared. const finalLayer = FINAL_LAYER.test(ctx.file.path) && !NOT_FINAL.test(ctx.file.path) if (!declared && !(finalLayer && hasOldSide(ctx.file))) return [] const { added, removed } = await columnDelta(ctx, runner, dialect) const out: Finding[] = [] if (removed.length && !declared) { out.push( makeFinding({ severity: "warning", category: "lineage_breakage", title: `${model}: removed column(s) on a final-layer model`, body: `This change removes ${ticks(removed)} from \`${model}\`, a final-layer model that dashboards and exports usually read directly; ` + `those readers aren't in the DAG. Keep the old column alongside the new one for a deprecation period, or declare the consumers as exposures.`, file: ctx.file.path, model, confidence: "medium", evidence: { tool: "dbt.manifest", result: { removed, finalLayer: true } }, ruleKey: "lineage_breakage:final-layer-column-removed", rule: "dbt.manifest:removed-final-layer-columns", ...removedColumnAnchor(ctx.file.diff, removed), }), ) } if (removed.length && declared) { const who: string[] = [] if (consumers.exposures.length) who.push(`exposure(s) ${consumers.exposures.map((e) => `\`${e.name}\`${e.type ? ` (${e.type})` : ""}`).join(", ")}`) if (consumers.contractEnforced) who.push("an enforced contract, so readers outside dbt rely on its columns") out.push( makeFinding({ severity: "warning", category: "lineage_breakage", title: `${model}: removed column(s) on a model with declared consumers`, body: `This change removes ${ticks(removed)}. \`${model}\` has ${who.join(" and ")}. ` + `Keep the column for a deprecation period, or publish a new model version and migrate the consumers.`, file: ctx.file.path, model, confidence: "high", evidence: { tool: "dbt.manifest", result: { removed, exposures: consumers.exposures.map((e) => e.name), contractEnforced: consumers.contractEnforced }, }, ruleKey: "lineage_breakage:consumer-column-removed", rule: "dbt.manifest:removed-columns-declared-consumers", ...removedColumnAnchor(ctx.file.diff, removed), }), ) } if (consumers.contractEnforced && opts.checkContractColumns && consumers.contractColumns.length && added.length) { const declared = new Set(consumers.contractColumns) // A column the PR declares for THIS model in a changed yml is declared even // when the manifest predates the PR; another model's columns never count. const inChangedYml = ymlModelColumns(await opts.changedYmlText(), model) const missing = added.filter((c) => !declared.has(c) && !inChangedYml.has(c)) if (missing.length) out.push( makeFinding({ severity: "warning", category: "contract_violation", title: `${model}: new column(s) missing from the enforced contract`, body: `${ticks(missing)} ${missing.length === 1 ? "is" : "are"} selected but not declared in \`${model}\`'s contract, ` + `so \`dbt build\` fails the contract check. Declare ${missing.length === 1 ? "it" : "them"} (with \`data_type\`) in the model's yml.`, file: ctx.file.path, model, confidence: "high", evidence: { tool: "contract-check", result: { missing } }, ruleKey: "contract_violation:contract-missing-column", rule: "contract-check:missing-columns", }), ) } return out } /** * Opt-in consumer column lists (`consumerColumnLists` in review.yml): when the * PR changes a model's columns, every configured list that mirrors the model * must gain the new columns and drop the removed ones. */ async function consumerListLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, lists: ConsumerColumnList[], ): Promise { if (!lists.length) return [] const model = modelNameFromPath(ctx.file.path) const mirrors = lists.filter((l) => listMirrorsModel(l, model)) if (!mirrors.length || !hasOldSide(ctx.file)) return [] const { added, removed } = await columnDelta(ctx, runner, dialect) if (!added.length && !removed.length) return [] const out: Finding[] = [] for (const list of mirrors) { const have = new Set(list.columns) const missing = added.filter((c) => !have.has(c)) const stale = removed.filter((c) => have.has(c)) if (!missing.length && !stale.length) continue const parts: string[] = [] if (missing.length) parts.push(`lacks the new column(s) ${ticks(missing)}`) if (stale.length) parts.push(`still lists the removed column(s) ${ticks(stale)}`) out.push( makeFinding({ severity: "warning", category: "lineage_breakage", title: `${model}: column list in ${list.path} is out of step`, body: `\`${list.path}\` declares an explicit column list for \`${model}\` that ${parts.join(" and ")}. ` + `Readers of that list will drop or fail on these columns; update it in this PR.`, file: ctx.file.path, model, confidence: "high", evidence: { tool: "consumer-column-list", result: { list: list.path, missing, stale } }, ruleKey: `lineage_breakage:consumer-list:${list.path}`, rule: "consumer-column-list:stale", }), ) } return out } /** Incremental / table-replace semantics (incremental-semantics.ts). */ async function incrementalSemanticsLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, dialectKnown: boolean, prText: string, sliceVars: string[], ): Promise { const { file, newSql, oldSql } = ctx if (!newSql || file.status === "deleted") return [] const model = modelNameFromPath(file.path) const consumers = await runner.modelConsumers?.(model) return incrementalFindings({ file, model, newSql, oldSql: hasOldSide(file) ? oldSql : undefined, manifestConfig: await runner.modelConfig?.(model), added: splitDiff(file.diff).added, dialect, dialectKnown, prText, hasExposures: !!consumers?.exposures.length, sliceVars, columnDelta: () => columnDelta(ctx, runner, dialect), }) } /** * DATA-DIFF — the showcase: actually run base vs head against the warehouse * (core DataParity) and report row/value deltas a linter can never see. Needs a * configured warehouse connection (CI); skips gracefully when absent. Key * columns are inferred from the model's `*_id`/`id` output columns. */ async function dataDiffLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, cfg: { enabled: boolean; warehouse: string }, ): Promise { // Opt-in: data-diff costs warehouse compute and needs credentials, so it only // runs when explicitly enabled in `.altimate/review.yml`. if (!cfg.enabled) return [] if (!runner.dataDiff || !runner.columnLineage) return [] const { file, engineOldSql, engineNewSql } = ctx if (!engineOldSql || !engineNewSql || !hasOldSide(file)) return [] const model = modelNameFromPath(file.path) const cols = (await runner.columnLineage(engineNewSql, dialect)).map((e) => e.target.toLowerCase()) const keys = [...new Set(cols.filter((c) => c === "id" || /_id$/.test(c)))].slice(0, 1) if (!keys.length) return [] // no inferable key → can't data-diff const diff = await runner.dataDiff(engineOldSql, engineNewSql, keys, cfg.warehouse || undefined) if (!diff) return [] // no warehouse/driver → skip const base = diff.rowsOnlyInBase ?? 0 const head = diff.rowsOnlyInHead ?? 0 const changed = diff.rowsChanged ?? 0 if (base + head + changed === 0) return [] return [ makeFinding({ severity: "warning", category: "semantic_change", title: `${model}: data-diff shows output rows change vs base`, body: `Run against the warehouse, this change produces a different result than the base on key \`${keys[0]}\`: ` + `${base} only-in-base, ${head} only-in-head, ${changed} changed` + (diff.summary ? ` — ${diff.summary}` : "") + `. Confirm the data impact is intended.`, file: file.path, model, confidence: "high", evidence: { tool: "data.diff", result: diff }, ruleKey: "semantic_change:data-diff", rule: "data.diff:row-delta", }), ] } /** Count leading `_`-separated segments two model names share (a merge-stem signal). */ function leadingSegMatch(a: string, b: string): number { const A = a.split("_") const B = b.split("_") let n = 0 while (n < A.length && n < B.length && A[n] === B[n]) n++ return n } /** Strip a trailing semicolon so a model's compiled SQL can be wrapped as a subquery. */ function asSubquery(sql: string, alias: string): string { return `select * from (\n${sql.trim().replace(/;\s*$/, "")}\n) as ${alias}` } /** * TOPOLOGY-AWARE equivalence — covers the merge refactor that model-level * equivalence misses. When a PR DELETES N models {X,Y,Z} and ADDS one model W * that supersedes them (e.g. `int_column_access_{base,direct,modified}` → * `int_column_access_daily`), W has no 1:1 base, so `semanticChangeLane` skips * it entirely. Here we compose the BASE compiled SQL of the replaced set as * `UNION ALL` and ask the engine whether W reproduces it. * * FP-safe BY CONSTRUCTION: the `UNION ALL` composition is INFERRED (the replaced * models might have been combined differently downstream), so this lane is * ADVISORY ONLY — it is hard-capped at `warning` and can never block. It surfaces * "this merge isn't proven equivalent — verify" rather than asserting a break, * and stays SILENT when the engine PROVES the merge equivalent. */ async function topologyEquivalenceLane( modelFiles: (ChangedFile & { kind: string })[], runner: ReviewRunner, getCompiled: ((file: string, side: "old" | "new") => Promise) | undefined, dialect: string, ): Promise { if (!getCompiled) return [] const deleted = modelFiles.filter((f) => f.status === "deleted") const added = modelFiles.filter((f) => f.status === "added") if (deleted.length < 2 || !added.length) return [] const out: Finding[] = [] for (const w of added) { const wName = modelNameFromPath(w.path) // Pair: replaced set = deleted models sharing the MAXIMAL leading-segment // stem with W, requiring ≥2 shared segments and ≥2 such models (a real merge, // not a coincidental name overlap). let maxSeg = 0 for (const d of deleted) maxSeg = Math.max(maxSeg, leadingSegMatch(wName, modelNameFromPath(d.path))) if (maxSeg < 2) continue const replaced = deleted.filter((d) => leadingSegMatch(wName, modelNameFromPath(d.path)) === maxSeg) if (replaced.length < 2) continue // Compose the BASE side: UNION ALL of the replaced models' base compiled SQL. const parts: string[] = [] let ok = true for (let i = 0; i < replaced.length; i++) { const sql = await getCompiled(replaced[i].path, "old") if (!sql || !sql.trim()) { ok = false break } parts.push(asSubquery(sql, `_repl_${i}`)) } if (!ok || parts.length < 2) continue const headSql = await getCompiled(w.path, "new") if (!headSql || !headSql.trim()) continue const baseComposition = parts.join("\nunion all\n") const eq = await runner.equivalence(baseComposition, headSql.trim().replace(/;\s*$/, ""), dialect) // Proven equivalent → the merge is safe; stay silent (never nitpick what's proven). if (eq.decided && eq.equivalent) continue const replacedNames = replaced.map((d) => `\`${modelNameFromPath(d.path)}\``).join(", ") const diffs = (eq.differences ?? []).slice(0, 6) const detail = eq.decided ? `the merged model is **NOT row-equivalent** to \`UNION ALL\` of the replaced models` + (diffs.length ? `:\n${diffs.map((d) => `- ${d}`).join("\n")}` : ".") : `equivalence could not be decided (no schema / unsupported SQL).` out.push( makeFinding({ // Hard-capped at warning: the composition is inferred, so this never blocks. severity: clampSeverity("semantic_change", "warning", eq.confidence ?? "low"), category: "semantic_change", title: `${wName}: merges ${replaced.length} models — not proven equivalent`, body: `\`${wName}\` replaces ${replacedNames}. This is a TOPOLOGY refactor (the new model has ` + `no 1:1 base), so model-level equivalence can't check it directly. Composing the replaced ` + `models as \`UNION ALL\`, ${detail}\n\n` + `_The \`UNION ALL\` composition is inferred — if the replaced models were combined differently ` + `(e.g. \`UNION\` / a join) by their consumer, a difference here may be expected. Confirm the ` + `data impact with a data-diff._`, file: w.path, model: wName, confidence: eq.decided ? eq.confidence ?? "low" : "unknown", degraded: !eq.decided, evidence: { tool: "altimate_core.equivalence", result: { topology: "merge", replaced: replaced.map((d) => modelNameFromPath(d.path)), decided: eq.decided, equivalent: eq.equivalent ?? null, }, }, ruleKey: `semantic_change:topology-merge:${wName}`, rule: "altimate-core.equivalence:not-equivalent", }), ) } return out } /** * GRAIN MISMATCH — the model's SQL dedups/groups by a key that conflicts with its * DECLARED uniqueness (primary key / `unique` test). Catches `6c42eab`-class bugs: * deduping on `role_name` while the grain is declared `role_id` keeps the wrong * rows / the uniqueness test silently won't hold. Sound: needs a declared key AND a * clear grain key in the SQL; fires only when the SQL grain has a column the * declared key lacks (so the declared key isn't actually unique). */ async function grainMismatchLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.grain || !runner.declaredPrimaryKey) return [] const { file, engineNewSql } = ctx if (!engineNewSql || file.status === "deleted") return [] const model = modelNameFromPath(file.path) const pk = await runner.declaredPrimaryKey(model) if (!pk || !pk.length) return [] // no declared grain → nothing to check against const grain = await runner.grain(engineNewSql) const actual = grain.group_by.length ? grain.group_by : grain.dedup_partition if (!actual.length) return [] // no clear grain in the SQL → stay silent const pkLower = new Set(pk.map((c) => c.toLowerCase())) const extra = actual.filter((c) => !pkLower.has(c.toLowerCase())) if (!extra.length) return [] // grain ⊆ declared key → the key is still unique const how = grain.group_by.length ? "grouped by" : "deduped (PARTITION BY) on" return [ makeFinding({ severity: clampSeverity("sql_correctness", "warning", "medium"), category: "sql_correctness", title: `${model}: grain key conflicts with declared uniqueness`, body: `\`${model}\` is ${how} [${actual.join(", ")}], but it declares uniqueness on ` + `[${pk.join(", ")}] (contract / unique test). Column(s) [${extra.join(", ")}] are in the ` + `grain but not the declared key, so the model can emit multiple rows per declared key — ` + `the uniqueness test will fail or the dedup keeps the wrong row. Align the GROUP BY / ` + `PARTITION BY with the declared key (e.g. dedup on the id, not the name).`, file: file.path, model, confidence: "medium", evidence: { tool: "altimate_core.grain", result: { grain: actual, declared: pk, extra } }, ruleKey: "sql_correctness:grain-mismatch", rule: "altimate-core.grain:conflicts-declared-uniqueness", }), ] } /** * MISSING GRAIN TEST — a NEW grain-bearing model (intermediate / mart / fact / dim) * with no declared uniqueness (`unique` / `unique_combination_of_columns` / contract * PK). Most of the dedup/grain/fan-out bugs in practice trace back to a model whose * grain was never asserted, so a silent dup never trips a test. Advisory (suggestion) * and scoped to grain-bearing models so staging passthroughs aren't nagged. */ async function missingGrainTestLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.declaredPrimaryKey) return [] const { file } = ctx if (file.status !== "added") return [] const model = modelNameFromPath(file.path) const grainBearing = /(^|\/)(marts|intermediate|reporting)\//.test(file.path) || /^(int_|mrt_|fct_|fact_|dim_|agg_|rpt_)/.test(model) if (!grainBearing) return [] const pk = await runner.declaredPrimaryKey(model) if (pk && pk.length) return [] // grain is asserted — good return [ makeFinding({ severity: clampSeverity("test_coverage", "suggestion", "medium"), category: "test_coverage", title: `${model}: new model has no uniqueness/grain test`, body: `\`${model}\` is a new grain-bearing model but declares no \`unique\` / ` + `\`unique_combination_of_columns\` test (and no contract primary key). Without a grain ` + `assertion, a fan-out or wrong-dedup bug silently doubles rows and no test catches it. ` + `Add a uniqueness test on the model's grain so the contract is enforced in CI.`, file: file.path, model, confidence: "medium", evidence: { tool: "dbt.manifest", result: { hasGrainTest: false } }, ruleKey: "test_coverage:missing-grain-test", rule: "dbt.manifest:new-model-no-grain-test", }), ] } /** Var names defined under `vars:` in dbt_project.yml (top level and project-scoped). */ export function definedVars(projectYml?: string): Set { const out = new Set() if (!projectYml) return out let doc: any try { doc = YAML.parse(projectYml) } catch { return out } const vars = doc?.vars if (!vars || typeof vars !== "object") return out for (const [k, v] of Object.entries(vars)) { out.add(k) if (v && typeof v === "object" && !Array.isArray(v)) for (const k2 of Object.keys(v)) out.add(k2) } return out } /** * `{% set cfg = {"materialized": "incremental", ...} %}` + `config(**cfg)` is a * common way to share config; inline a flat literal dict's entries as kwargs so * the config lint sees them. */ export function inlineConfigSplats(sql: string): string { const dicts = new Map() for (const m of sql.matchAll(/\{%-?\s*set\s+(\w+)\s*=\s*\{/g)) { // The dict body up to its matching brace; nested dicts (a BigQuery partition_by) stay as written. const open = m.index! + m[0].length - 1 let depth = 0 let end = -1 for (let i = open; i < sql.length; i++) { if (sql[i] === "{") depth++ else if (sql[i] === "}" && --depth === 0) { end = i break } } if (end < 0 || !/^\s*-?%\}/.test(sql.slice(end + 1))) continue const body = sql.slice(open + 1, end) // Only top-level `"key":` becomes `key=`. let out = "" let d = 0 for (let i = 0; i < body.length; i++) { const c = body[i] if ("{[(".includes(c)) d++ else if ("}])".includes(c)) d-- const key = d === 0 ? /^["'](\w+)["']\s*:/.exec(body.slice(i)) : null if (key) { out += key[1] + "=" i += key[0].length - 1 } else out += c } dicts.set(m[1], out.replace(/,\s*$/, "")) } if (!dicts.size) return sql return sql.replace(/\bconfig\s*\(([\s\S]*?)\)\s*\}\}/g, (whole) => whole.replace(/\*\*(\w+)/g, (splat, name) => dicts.get(name) ?? splat), ) } const MATERIALIZED = /\bmaterialized\s*=\s*['"](\w+)['"]/i const MICROBATCH = /\bincremental_strategy\s*=\s*['"]microbatch['"]/i /** * An unguarded incremental model is this PR's problem only when the PR creates it: a model * whose SQL a macro generates carries its guard in the macro, and a model that was already * incremental without a guard (same materialization, no `is_incremental()`) predates the PR. */ function introducesUnguardedIncremental(newSql: string, oldSql: string | undefined): boolean { const outsideJinja = newSql.replace(/\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}|\{#[\s\S]*?#\}/g, " ") if (!/\bselect\b/i.test(outsideJinja)) return false if (oldSql === undefined) return true const sameMaterialization = MATERIALIZED.exec(oldSql)?.[1]?.toLowerCase() === MATERIALIZED.exec(newSql)?.[1]?.toLowerCase() return !(sameMaterialization && !/\bis_incremental\s*\(/.test(oldSql)) } /** * A `unique_key` change moves the merge grain, except under microbatch (which replaces by * `event_time` batch and ignores `unique_key`) and when the only added key columns are the * model's partition columns (a coarser column derived from the row, added for pruning). */ function changesMergeGrain(message: string, newSql: string, oldSql: string | undefined): boolean { if (MICROBATCH.test(newSql) || (oldSql && MICROBATCH.test(oldSql))) return false const m = /\[([^\]]*)\]\s*→\s*\[([^\]]*)\]/.exec(message) if (!m) return true const cols = (s: string) => s.split(",").map((c) => c.trim().toLowerCase()).filter(Boolean) const before = cols(m[1]) const after = cols(m[2]) const added = after.filter((c) => !before.includes(c)) if (!before.length || !before.every((c) => after.includes(c)) || !added.length) return true const partition = /\bpartition_by\s*=\s*(\[[^\]]*\]|\{[^}]*\}|['"][^'"]*['"])/i.exec(newSql)?.[1]?.toLowerCase() ?? "" return !added.every((c) => new RegExp(`['"]${c.replace(/\W/g, "")}['"]`).test(partition)) } /** * The changed files' unchanged dbt parents, read at head, for the AI lane's * cross-file checks: an upstream model's columns, a seed's rows, a macro's * signature. Manifest paths are project-relative; changed paths may carry a * prefix (review run from the repo root), which is reapplied to the parents. */ async function aiGraphContext( paths: string[], runner: ReviewRunner, getContent: OrchestrateInput["getContent"], ): Promise { if (!runner.graphParents || !getContent || !paths.length) return undefined try { const parents = await runner.graphParents(paths) const out: AiContextFile[] = [] for (const p of parents) { if (p.kind === "source") { if (!p.columns?.length) continue out.push({ path: p.path, kind: p.kind, name: p.name, forPaths: p.forPaths, content: `columns: ${p.columns.join(", ")}` }) continue } const content = await getContent(p.path, "new").catch(() => undefined) if (content) out.push({ path: p.path, kind: p.kind, name: p.name, forPaths: p.forPaths, content }) } return out } catch { // Context is an enrichment: without it the lane reviews the changed files alone. return undefined } } /** * dbt CONFIG lint — runs the core dbt-config parser (minijinja) over the RAW model * (the `{{ config() }}` block + body) and emits the config/Jinja findings: incremental * guard / unique_key, microbatch lookback, enforced-contract on_table_exists, * var-without-default, and materialization change (vs base). This replaces the regex * dbt-patterns config detectors — the parsing now lives in core. */ async function dbtConfigLane(ctx: ModelContext, runner: ReviewRunner, projectVars: Set = new Set()): Promise { if (!runner.dbtConfigLint) return [] const { file, newSql, oldSql } = ctx if (!newSql || file.status === "deleted") return [] const model = modelNameFromPath(file.path) const raw = await runner.dbtConfigLint(inlineConfigSplats(newSql), hasOldSide(file) && oldSql ? inlineConfigSplats(oldSql) : undefined) const out: Finding[] = [] for (const f of raw) { // A var defined in dbt_project.yml, or given a default elsewhere in the model, compiles fine. if (f.rule === "var_no_default") { const name = /var\(\s*['"]([^'"]+)['"]/.exec(f.message)?.[1] const esc = name?.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") if (name && (projectVars.has(name) || new RegExp(`var\\(\\s*['"]${esc}['"]\\s*,`).test(newSql))) continue } if (f.rule === "incremental_no_guard" && !introducesUnguardedIncremental(newSql, hasOldSide(file) ? oldSql : undefined)) continue if (f.rule === "unique_key_change" && !changesMergeGrain(f.message, newSql, hasOldSide(file) ? oldSql : undefined)) continue const cat: ReviewCategory = /var_no_default|microbatch|incremental|materialization/.test(f.rule) ? "materialization" : /contract/.test(f.rule) ? "contract_violation" : "sql_correctness" const isError = f.severity === "error" let sev: Severity = isError ? "warning" : "suggestion" if (isError && cat === "contract_violation") sev = "critical" sev = clampSeverity(cat, sev, "high") out.push( makeFinding({ severity: sev, category: cat, title: `${model}: ${f.rule.replace(/_/g, " ")}`, body: f.message + (f.suggestion ? `\n\n${f.suggestion}` : ""), file: file.path, model, confidence: "high", evidence: { tool: "altimate_core.dbt_config", result: { code: f.code, rule: f.rule } }, ruleKey: `${cat}:dbt-config:${f.code}`, }), ) } return out } /** * A new LEFT JOIN onto a model whose declared uniqueness tests don't cover the * join key: the joined model has stated its grain and the join ignores it (an * SCD2 dimension joined without `is_current`, a natural key instead of the * declared one), so a repeated key multiplies the left rows. Inner joins are * skipped, since they are often one-to-many on purpose, as are models with no * declared key, where nothing says what one row means. */ async function joinKeyUniquenessLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.declaredUniqueKeys || !runner.modelConfig || !ctx.newSql || ctx.file.status === "deleted") return [] const added = (ctx.file.diff ?? "").split("\n").filter((l) => l.startsWith("+") && !l.startsWith("+++")).map((l) => l.slice(1)) const out: Finding[] = [] const model = modelNameFromPath(ctx.file.path) for (const t of joinTargets(ctx.newSql, added)) { // Unknown to the manifest (a package model, a typo): nothing to compare against. if (!t.left || !(await runner.modelConfig(t.model))) continue const declared = (await runner.declaredUniqueKeys(t.model)).filter((k) => k.length) if (!declared.length || declared.some((k) => k.every((c) => t.keys.includes(c.toLowerCase())))) continue out.push( makeFinding({ severity: "suggestion", category: "fanout", title: `${model}: LEFT JOIN key on \`${t.model}\` isn't its declared unique key`, body: `\`${t.join}\` matches \`${t.model}\` on [${t.keys.join(", ")}], but its uniqueness tests cover ` + `${declared.map((k) => `[${k.join(", ")}]`).join(", ")}, which the join doesn't fully constrain.` + ` If a key repeats there, this join multiplies rows. Add a \`unique\` / \`unique_combination_of_columns\` test on the join key, or join on the declared key.`, file: ctx.file.path, model, confidence: "medium", evidence: { tool: "dbt.manifest", result: { joined: t.model, keys: t.keys, declared } }, ruleKey: `fanout:join-key-untested:${t.model}`, rule: "dbt.manifest:left-join-key-not-unique", }), ) } return out } const TIME_PARTITION_COLUMN = /(^|_)(date|day|week|month|quarter|year|period|hour|ts|time|timestamp)(_|$)|_at$/i /** * An incremental merge key that differs from every uniqueness test on the model: * one of the two is wrong. A test key missing a `unique_key` column fails once a * row per extra value lands; a `unique_key` missing a test column merges rows the * test treats as distinct. * * `uniquenessTestsChanged`: the PR changed a schema yml, where the uniqueness tests are declared. */ async function uniqueKeyMismatchLane(ctx: ModelContext, runner: ReviewRunner, uniquenessTestsChanged: boolean): Promise { if (!runner.modelConfig || !runner.declaredUniqueKeys || ctx.file.status === "deleted") return [] // Only when this PR touched one side of the comparison: the model's incremental config, or the yml tests. // A long-standing mismatch is not re-reported on every edit to the model. const configTouched = splitDiff(ctx.file.diff).added.some((l) => /\b(unique_key|materialized|incremental_strategy)\b/i.test(l)) if (!configTouched && !uniquenessTestsChanged && ctx.file.status !== "added") return [] const model = modelNameFromPath(ctx.file.path) const cfg = await runner.modelConfig(model) if (cfg?.materialized !== "incremental" || !cfg.unique_key) return [] const uk = (Array.isArray(cfg.unique_key) ? cfg.unique_key : String(cfg.unique_key).split(",")) .map((c) => String(c).trim().toLowerCase()) .filter(Boolean) const declared = await runner.declaredUniqueKeys(model) if (!uk.length || !declared.length) return [] const same = (k: string[]) => k.length === uk.length && k.every((c) => uk.includes(c.toLowerCase())) if (declared.some(same)) return [] // A merge key that is a declared key plus date/partition columns (`block_month`, // `effective_date`) is the common pruning pattern; those columns don't change which rows match. const timeOnlyExtra = (k: string[]) => { const lk = k.map((c) => c.toLowerCase()) return lk.every((c) => uk.includes(c)) && uk.filter((c) => !lk.includes(c)).every((c) => TIME_PARTITION_COLUMN.test(c)) } if (declared.some(timeOnlyExtra)) return [] // A wider merge key only duplicates rows if an extra column changes for an existing row; // a narrower or different key can collapse distinct rows into one. const wider = declared.some((k) => k.every((c) => uk.includes(c.toLowerCase()))) const tests = declared.map((k) => `[${k.join(", ")}]`).join(", ") return [ makeFinding({ severity: wider ? "suggestion" : "warning", category: "materialization", title: `${model}: incremental unique_key differs from the declared uniqueness test`, body: `\`${model}\` merges on \`unique_key\` [${uk.join(", ")}], but its uniqueness test${declared.length > 1 ? "s declare" : " declares"} ${tests}. ` + `If the merge key is right the test fails as soon as two rows share the test key; if the test is right the merge collapses or duplicates rows. Make them the same column set.`, file: ctx.file.path, model, confidence: "high", evidence: { tool: "dbt.manifest", result: { unique_key: uk, declared } }, ruleKey: "materialization:unique-key-test-mismatch", rule: "dbt.manifest:unique-key-differs-from-test", }), ] } /** * STRUCTURAL base-vs-head diff — the `*_change` SQL rules (DISTINCT/UNION flip, * GROUP BY grain shift, surrogate-key change, COALESCE removed, predicate * removed, type narrowing). These moved off diff-LINE regex onto a core AST * comparison (`structural_diff`): it parses BOTH versions, so it no longer * mistakes a moved line for a change or an ON-clause `and` for a WHERE. Cheap * and schema-free, so it runs at every tier the regex twins used to. */ const STRUCTURAL_CATEGORY: Record = { distinct_added: "semantic_change", distinct_removed: "semantic_change", union_all_to_union: "warehouse_cost", union_to_union_all: "sql_correctness", group_by_change: "semantic_change", surrogate_key_change: "dedup", coalesce_removed: "semantic_change", removed_predicate: "semantic_change", type_narrowing: "contract_violation", join_key_regression: "join_risk", } // PII classification thresholds for the diff-scoped lane. Names/addresses are // common, lower-sensitivity PII that the broad name-pattern detector over-flags, // so the precise lane requires higher confidence before surfacing them. Kept a // named constant (not a magic number) and deliberately narrow: broadening the // low-risk set to variants would suppress MORE real columns, hurting recall. const PII_LOW_RISK_CLASS = /^(name|address)$/i const PII_LOW_RISK_MIN_CONFIDENCE = 0.9 const PII_DEFAULT_MIN_CONFIDENCE = 0.7 async function structuralChangeLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.structuralDiff) return [] // Use the ENGINE (compiled) SQL — structural_diff parses with a real SQL parser, // so raw Jinja (`{{ ref() }}`) would fail to parse and the lane would silently // return nothing. engineOldSql/engineNewSql fall back to raw only when it holds no Jinja. const { file, engineNewSql, engineOldSql } = ctx if (!hasOldSide(file) || !engineNewSql || !engineOldSql || engineNewSql.trim() === engineOldSql.trim()) return [] const model = modelNameFromPath(file.path) const raw = await runner.structuralDiff(engineOldSql, engineNewSql) const out: Finding[] = [] for (const f of raw) { const cat: ReviewCategory = STRUCTURAL_CATEGORY[f.rule] ?? "semantic_change" // Only `join_risk` (SC010 join-key regression) is allowed to block: a changed // join key silently corrupts row sets. Other structural rules core marks // `error` stay advisory (warning) so this lane never over-blocks on a rule // it wasn't designed to gate. const sev = clampSeverity(cat, cat === "join_risk" && f.severity === "error" ? "critical" : "warning", "high") out.push( makeFinding({ severity: sev, category: cat, title: `${model}: ${f.rule.replace(/_/g, " ")}`, body: f.message + (f.suggestion ? `\n\n${f.suggestion}` : ""), file: file.path, model, confidence: "high", evidence: { tool: "altimate_core.structural_diff", result: { code: f.code, rule: f.rule } }, ruleKey: `${cat}:structural:${f.code}`, }), ) } return out } /** * CROSS-MODEL SIBLING CONSISTENCY — when two+ changed models read the SAME * upstream but filter it differently, one is likely missing a guard the others * apply (ingestion `d1fe5cf`: one of three sibling loaders lacked a NULL filter → * 23.7k leaked rows). Per-upstream filter columns come from the core AST * (`source_filters`); this PR-level lane compares them. Advisory (siblings may * legitimately differ), so it surfaces the divergence to confirm, never blocks. */ async function siblingConsistencyLane(ctxs: ModelContext[], runner: ReviewRunner): Promise { if (!runner.sourceFilters) return [] const perModel: Array<{ model: string; file: string; filters: Map> }> = [] for (const ctx of ctxs) { if (!ctx.engineNewSql || ctx.file.status === "deleted") continue const sf = await runner.sourceFilters(ctx.engineNewSql) const filters = new Map>() for (const [u, cols] of Object.entries(sf)) filters.set(u, new Set(cols.map((c) => c.toLowerCase()))) if (filters.size) perModel.push({ model: modelNameFromPath(ctx.file.path), file: ctx.file.path, filters }) } if (perModel.length < 2) return [] // upstream → sibling models that read it (within this PR). const byUpstream = new Map() for (const pm of perModel) { for (const u of pm.filters.keys()) { if (!byUpstream.has(u)) byUpstream.set(u, []) byUpstream.get(u)!.push(pm) } } const out: Finding[] = [] const seen = new Set() for (const [u, models] of byUpstream) { if (models.length < 2) continue const union = new Set() for (const m of models) for (const c of m.filters.get(u) ?? []) union.add(c) for (const m of models) { const mine = m.filters.get(u) ?? new Set() const missing = [...union].filter((c) => !mine.has(c)) if (!missing.length) continue const key = `${m.file}|${u}` if (seen.has(key)) continue seen.add(key) const others = models.filter((x) => x.file !== m.file).map((x) => `\`${x.model}\``) out.push( makeFinding({ severity: clampSeverity("sql_correctness", "warning", "medium"), category: "sql_correctness", title: `${m.model}: filters \`${u}\` differently from sibling model(s)`, body: `\`${m.model}\` reads \`${u}\` but does not filter it on [${missing.join(", ")}], while sibling ` + `model(s) ${others.join(", ")} (also reading \`${u}\` in this PR) do. A missing row filter silently ` + `leaks rows. Confirm the difference is intentional, or apply the same predicate.`, file: m.file, model: m.model, confidence: "medium", evidence: { tool: "altimate_core.source_filters", result: { upstream: u, missing } }, ruleKey: `sql_correctness:sibling-filter:${u}`, rule: "altimate-core.source-filters:sibling-mismatch", }), ) } } return out } /** * PII exposure via core's `classify_pii` — flags columns the change INTRODUCES * that classify as PII (Email/SSN/…), with the masking suggestion. Diff-scoped: * only NEW PII (a column whose name appears in the added diff), so it never nags * about pre-existing PII columns the PR didn't touch. */ async function piiClassifyLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, ): Promise<{ findings: Finding[]; classifiedColumns: Set; completed: boolean }> { const empty = { findings: [], classifiedColumns: new Set(), completed: false } if (!runner.classifyPii) return empty const { file, engineNewSql } = ctx if (!engineNewSql || file.status === "deleted") return empty const model = modelNameFromPath(file.path) if (!runner.columnLineage) return empty // Output columns the change INTRODUCED = head targets − base targets (precise; // a pre-existing column merely mentioned in the diff is NOT counted). let newCols: string[] try { const headCols = [...new Set((await runner.columnLineage(engineNewSql, dialect)).map((e) => e.target).filter(Boolean))] // Zero head targets means lineage could NOT resolve this model's output // columns — the classifier considered nothing, so this is uncertainty, not a // confident "no new PII". Returning `completed: false` keeps the deterministic // regex fallback alive (vs. the `!newCols.length` case below, where lineage // DID resolve columns but none are newly introduced — that is genuinely done). if (!headCols.length) return empty const baseCols = ctx.engineOldSql ? new Set((await runner.columnLineage(ctx.engineOldSql, dialect)).map((e) => e.target.toLowerCase())) : undefined newCols = baseCols ? headCols.filter((c) => !baseCols.has(c.toLowerCase())) : headCols } catch { return empty } if (!newCols.length) return { findings: [], classifiedColumns: new Set(), completed: true } let pii try { pii = await runner.classifyPii(newCols) } catch { return empty } // Columns core's classifier actually CONSIDERED (returned a verdict for), even // if below threshold. The broad fallback and the regex twins dedup against THIS // set — not all introduced columns — so a column core simply MISSED (never // classified) stays eligible for the broad name-pattern detector instead of // being silently dropped. const classifiedColumns = new Set(pii.map((p) => String(p.column ?? "").toLowerCase()).filter(Boolean)) const out: Finding[] = [] // "Exposure" severity only escalates for published/broadly-read layers // (marts/reporting). This is intentionally narrower than where grain tests // 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) const minConfidence = lowRiskClass ? PII_LOW_RISK_MIN_CONFIDENCE : PII_DEFAULT_MIN_CONFIDENCE if (p.confidence < minConfidence || !p.column) continue const col = p.column.toLowerCase() const highConfidence = p.confidence >= 0.9 const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass && !baseUnknown ? "critical" : "warning" out.push( makeFinding({ severity: clampSeverity("pii_exposure", severity, highConfidence ? "high" : "medium"), category: "pii_exposure", title: `${model}: exposes ${p.classification} column \`${p.column}\``, body: `This change surfaces a **${p.classification}**-classified column \`${p.column}\` ` + `(confidence ${(p.confidence * 100).toFixed(0)}%). Confirm masking / access policy before merging to a non-restricted schema` + (p.masking ? `; suggested masking: \`${p.masking}\`.` : "."), file: file.path, model, // 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}`, rule: "altimate-core.classify-pii:exposes", }), ) } return { findings: out, classifiedColumns, completed: true } } /** `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: 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.` + (baseUnknown ? " The base version could not be compiled, so these columns may already be exposed before this PR." : ""), file: file.path, model, // `unknown`: undecided exposure never counts toward the warning pattern. confidence: baseUnknown ? "unknown" : "high", evidence: { tool: "schema.detect_pii", result: { columns } }, ruleKey: "pii:exposure", rule: "schema.detect-pii:exposes", }), ] } /** * Run the full review and return a signed verdict envelope. */ interface ModelContext { file: ChangedFile & { kind: string } impact: ImpactResult pii: string[] /** RAW Jinja SQL (for the dbt-patterns lane + the diff). */ newSql?: string oldSql?: string /** dbt-COMPILED SQL (preferred) for the engine lanes; falls back to raw. */ engineNewSql?: string engineOldSql?: string /** Structurally complex change (window/subquery/large plan) — a tiering signal. */ complex?: boolean } /** * The raw (uncompiled) base cannot expose any of the source columns `names`: * none appears in it as a word outside comments, no select item reads a `*`, its * only Jinja expressions are `ref`, `source`, `config` or `this`, and its only * Jinja statements are control flow (`if`/`for`/`set` and their ends), which * emit no text of their own. A macro (`dbt_utils.star(…)`), a variable, a * `{{ col }}` loop, an `{% include %}` or a `{% call %}` block could emit any * column, so any other tag proves nothing. String literals still count as * evidence: a JSON path (`payload:ssn`, `'$.ssn'`) can expose the column. * A `*` is any `*` token not preceded by a word (`*`, `c.*`, `*except(email)`, * `as struct *`, `object_construct(*)`); `count(*)` reads no column. Spaced * multiplication (`a * b`) also matches, which only leaves the base undecided. */ const RAW_BASE_PLAIN_EXPR = /^\{\{-?\s*(?:(?:ref|source|config)\s*\([^{}]*\)|this)\s*-?\}\}$/ const RAW_BASE_STAR = /(?:^|[\s.(])\*(?=\s|$|[a-z(),])/i /** What `rawBaseLacks` reads from a raw base, parsed once per file: its code * without comments, or `undefined` when the base is undecided for every column. */ function rawBaseCode(oldSql: string | undefined): string | undefined { if (!oldSql) return undefined if (!(oldSql.match(/\{\{[\s\S]*?\}\}/g) ?? []).every((e) => RAW_BASE_PLAIN_EXPR.test(e))) return undefined if (!(oldSql.match(/\{%[\s\S]*?%\}/g) ?? []).every((t) => SILENT_JINJA_TAG.test(t))) return undefined if (selectItems(oldSql).some((i) => RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) return undefined // Comments out, literals and quoted identifiers kept (one pass, so `--` inside // `'…'` or `"…"` is not a comment). return oldSql.replace(/\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"/g, (m) => m.startsWith("'") || m.startsWith('"') ? m : " ", ) } function rawBaseLacks(code: string | undefined, names: string[]): boolean { if (code === undefined || !names.length) return false return names.every((n) => !new RegExp(`(? { const { reviewable, dropped } = partitionChangedFiles( input.changedFiles, input.rubric.exclusions.excludeGlobs, input.layout, ) // Files some lane received (the coverage ledger lists the rest). const touched = new Set() const touch = (files: Array<{ path: string }>) => { for (const f of files) touched.add(f.path) } const dialect = input.config.dialect const getContent = input.getContent const getCompiled = input.getCompiled // Pre-compute every engine result ONCE per model file: blast radius (for // tiering + lineage), PII columns (hard-floor → must precede tiering), and // both SQL sides. This avoids duplicate engine calls and lets tiering see PII. const modelFiles = reviewable.filter((f) => f.kind === "model_sql" || f.kind === "python_model") // Every model gets at least the PII check; one that fails is recorded as unverified. touch(modelFiles) const ctxByPath = new Map() const unverified: NonNullable = [] let anyManifest = false let manifestMissing = false if (input.runner.manifestAvailable) { anyManifest = await input.runner.manifestAvailable().catch(() => false) manifestMissing = !anyManifest } // PR-level lanes (across files) that threw: reported with the engine errors. const laneErrors: Array<{ method: string; reason: string; count: number }> = [] const prLevel = (method: string, lane: Promise) => lane.catch((err) => { laneErrors.push({ method, reason: errorReason(err, 200), count: 1 }) return [] as Finding[] }) const failedFile = (file: { path: string }, err: unknown) => unverified.push({ path: file.path, reason: `${FAILED_FILE_REASON}: ${errorReason(err, 160)}`, kind: "failed", }) await Promise.all( modelFiles.map(async (file) => { try { const model = modelNameFromPath(file.path) // For renames the previous content lives at oldPath, not the new path. const oldRef = file.oldPath ?? file.path const withOld = hasOldSide(file) const [newSql, oldSql, compiledNew, compiledOld] = await Promise.all([ file.status !== "deleted" ? getContent?.(file.path, "new") : Promise.resolve(undefined), withOld ? getContent?.(oldRef, "old") : Promise.resolve(undefined), file.status !== "deleted" ? getCompiled?.(file.path, "new") : Promise.resolve(undefined), withOld ? getCompiled?.(oldRef, "old") : Promise.resolve(undefined), ]) // Engine lanes need dbt-compiled SQL. Raw SQL is used only when it holds // no Jinja: the AST engine reads `{{ config() }}` as an injection attempt // and a mixed raw-vs-compiled pair can never be proven equivalent, so a // Jinja model without compiled output is marked unverified instead of // producing warnings about its template syntax. The dbt-patterns lane // always uses raw (it needs the Jinja). const engineNewSql = compiledNew ?? (file.kind === "model_sql" && hasJinja(newSql) ? undefined : newSql) const engineOldSql = compiledOld ?? (file.kind === "model_sql" && hasJinja(oldSql) ? undefined : oldSql) if (file.status !== "deleted" && newSql && !engineNewSql) unverified.push({ path: file.path, reason: "no compiled SQL for the head (run dbt compile)", kind: "not_compiled", side: "head", }) else if (withOld && oldSql && !engineOldSql) unverified.push({ path: file.path, reason: "no compiled SQL for the base (compile the base into target-base)", kind: "not_compiled", side: "base", }) const impact = await input.runner.impact(model) if (impact.hasManifest) anyManifest = true const piiRes = engineNewSql ? await input.runner.detectPii(engineNewSql, dialect) : { columns: [] } if (piiRes.abstained) unverified.push({ path: file.path, reason: "the PII check could not analyse this model", kind: "abstained" }) const pii = piiRes.columns const complex = engineNewSql && input.runner.isComplex ? await input.runner.isComplex(engineNewSql) : false ctxByPath.set(file.path, { file, impact, pii, newSql, oldSql, engineNewSql, engineOldSql, complex }) } catch (err) { // One file's failure (unreadable content, an engine crash) degrades that // file only; it must not abort the whole review. failedFile(file, err) } }), ) // A run is degraded when model files exist but none resolved against a manifest. // 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 // categories are configured, which keeps `highRiskPathTokenCategory` // undefined per file and no promotion fires. // // `compilePathTokenResolver` throws on an unknown `preset:` (typo // guard, cubic + harness-bot P2). Catch that here so a single config // typo in `.altimate/review.yml` doesn't crash every review run in the // project's CI — surface the error to stderr AND propagate a // `configError` reason into the envelope so the reader can see what // broke. The review continues with no path-token promotion (the // conservative safe fallback), so users notice their opt-in is dead // rather than getting silent auto-approve on billing/PCI/etc. paths // (cubic-review P2 on PR #1028 risk-tier.ts:134). let pathTokenCategoryOf: ((p: string) => string | undefined) | undefined let pathTokenConfigError: string | undefined try { pathTokenCategoryOf = compilePathTokenResolver(input.config.riskTierPathTokens) } catch (e: any) { pathTokenConfigError = `riskTierPathTokens config invalid: ${e?.message ?? String(e)}` process.stderr.write(`⚠️ ${pathTokenConfigError}\n Review continuing without path-token promotion.\n`) pathTokenCategoryOf = undefined } const tierResult = classifyPR(reviewable, { blastRadiusOf: (p) => { const c = ctxByPath.get(p) return c ? c.impact.directCount + c.impact.transitiveCount : 0 }, touchesPiiOf: (f) => (ctxByPath.get(f.path)?.pii.length ?? 0) > 0, isComplexOf: (f) => ctxByPath.get(f.path)?.complex ?? false, pathTokenCategoryOf, }) // Surface config errors in the tier-reasons stream so a reader of the // envelope (or PR comment) sees WHY their opt-in didn't fire. if (pathTokenConfigError) tierResult.reasons.unshift(pathTokenConfigError) const classifiedTier = tierResult.tier // G2 — --force-tier overrides the classifier. Envelope records both the // forced tier and the original classification whenever the flag is passed // (regardless of whether the forced value happens to match the classifier), // so audits can see the bypass every time the flag was used. The reasons // list gets a leading "forced" marker so downstream doesn't confuse the // forced tier for a natural one. Codex-R18-review fix — the earlier // `!== classifiedTier` gate silently hid the bypass when the forced tier // matched the classifier's result. const tier = input.forceTier ?? classifiedTier const tierForced = input.forceTier !== undefined const tierReasons = tierForced ? [ `forced via --force-tier=${input.forceTier} (classifier said ${classifiedTier})`, ...tierResult.reasons, ] : tierResult.reasons const lanes = new Set(input.config.reviewers.length ? input.config.reviewers : TIER_LANES[tier]) const prText = [input.prTitle, input.prBody].filter(Boolean).join("\n") // New content of the PR's changed schema files, read once and only if a lane asks. let ymlText: Promise | undefined const changedYmlText = () => (ymlText ??= Promise.all( reviewable .filter((f) => f.kind === "schema_yml" && f.status !== "deleted") .map((f) => (getContent?.(f.path, "new") ?? Promise.resolve(undefined)).then((t) => t ?? "").catch(() => "")), )) const all: Finding[][] = [] // Files where the diff-scoped PII classifier completed (looked at the change), // those where it actually emitted a finding, and — per file — the lowercased // columns it classified and those it flagged. These drive column-aware dedup // of the coarse regex PII twins in the merge step below. const diffScopedPiiCompletedFiles = new Set() const diffScopedPiiFindingFiles = new Set() const classifiedPiiColumnsByFile = new Map>() const flaggedPiiColumnsByFile = 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>() // The head's dbt_project.yml, read once: inherited test thresholds and defined vars. const projectYmlPath = `${input.layout?.root ? `${input.layout.root.replace(/\/$/, "")}/` : ""}dbt_project.yml` const projectYml = await getContent?.(projectYmlPath, "new").catch(() => undefined) const projectVars = definedVars(projectYml) const ymlChanged = reviewable.some((f) => f.kind === "schema_yml") // Per file, the final output of the base and head models, parsed from the SQL // the engine reads (compiled, or raw only when it holds no Jinja): a raw Jinja // base would credit it with every `{% if %}` branch, including ones the target // never renders. No engine SQL → nothing is known exposed. const outputsByFile = new Map() const outputs = (file: string, side: "old" | "new") => { const key = `${side}\u0000${file}` let parsed = outputsByFile.get(key) if (!parsed) { const ctx = ctxByPath.get(file) parsed = finalOutputs((side === "old" ? ctx?.engineOldSql : ctx?.engineNewSql) ?? "") outputsByFile.set(key, parsed) } return parsed } // The schema prefixes the base reads tables under: a base compiled into // another environment (prod `target-base`, a `+schema` change) reads the same // tables under different prefixes, which `refCovered` then ignores. const envOf = (file: string): RelationPrefixes => ({ base: outputs(file, "old").prefixes }) // `source.column` refs the base exposed raw under a name its PII detection // reported: named in its final select, or passed through its plain `*` // (`select * from customers` exposes `customers.ssn` when `ssn` is base PII). const baseRawPiiByFile = new Map>() const baseRawPii = (file: string) => { const cached = baseRawPiiByFile.get(file) if (cached) return cached const basePii = basePiiColumnsByFile.get(file) const refs = new Set() if (!basePii) return refs const base = outputs(file, "old") for (const name of basePii) { for (const ref of base.raw.get(name) ?? []) refs.add(ref) if (!base.names.has(name) && base.passthrough) for (const ref of base.starRaw(name)) refs.add(ref) } baseRawPiiByFile.set(file, refs) return refs } // A regex twin's SOURCE column (`ssn`, with its output alias when it has one) is // already exposed only when the head reads it raw from sources that a base PII // output also exposed raw: same table and column (`c.ssn` → `cust.ssn` on // `customers` is not new; `s.ssn` from `spouses` is). An alias alone is not // proof (`c.email as contact` → `c.ssn as contact` newly exposes `ssn`), and // neither is a base output that only masks the column (`sha2(c.ssn) as ssn_hash`) // or a CTE's own alias that never reaches the final select. A column the head's // final output doesn't expose raw under that name is reported. // The output name comes from the head's final-select item that spans the line // and reads the column raw, so an alias on the next line counts; else the // twin's own alias, else the column. const isBaseExposed = (file: string, column: string, alias?: string, line?: string) => { const spanning = line ? headItemsOnLine(file, line).filter((i) => i.scope === ROOT_SCOPE && i.rawColumn === column) : [] const names = spanning.length ? [...new Set(spanning.map((i) => i.name!))] : [alias ?? column] const head = outputs(file, "new").raw const exposed = baseRawPii(file) return names.every((name) => { const refs = [...(head.get(name) ?? [])].filter((r) => r.endsWith(`.${column}`)) return refs.length > 0 && refs.every((r) => refCovered(r, exposed, envOf(file))) }) } // A head PII output name the base already exposed. When the head selects a // column raw under it, the base must expose that same source column raw (base // `md5(home_address) as home_address` → head `home_address` is new). A head // output that is not a raw column is base-exposed when every source column its // value is computed from is one a base PII output exposed raw, or when the base // computes the name the same way (same item text with its literals, same // CTEs/subqueries read, over source columns the base's name also read): // `md5(x) as x` → `lower(x) as x` unmasks, and base raw `email` → // `lower(ssn) as email` reads `ssn`. A name the head's final select doesn't // resolve counts as base-exposed only when the head passes it through a plain // `*` and every source column that `*` resolves it to was exposed raw by a // base PII output (named, or through the base's own `*`). const isBaseExposedOutput = (file: string, name: string, basePii: Set) => { const head = outputs(file, "new") const rawColumns = head.raw.get(name) if (rawColumns?.size) { const exposed = baseRawPii(file) return [...rawColumns].every((ref) => refCovered(ref, exposed, envOf(file))) } if (!basePii.has(name)) return false const base = outputs(file, "old") if (head.names.has(name)) { const exposed = baseRawPii(file) const reads = head.reads.get(name) if (reads && [...reads].every((ref) => refCovered(ref, exposed, envOf(file)))) return true // The same computation counts only over the same source columns: the // signature holds the item text and derived-query bodies, not the tables // (`lower(email)` from `customers` → from `spouses` is new). Refs no // source explains are left to the signature. const baseReads = base.reads.get(name) ?? new Set() const sameReads = [...(reads ?? [])] .filter((ref) => !ref.startsWith("?")) .every((ref) => refCovered(ref, baseReads, envOf(file))) const baseSigs = base.signatures.get(name) return sameReads && !!baseSigs && [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) } // Unresolved only through a plain `*`: a shape the parser does not model (a // parenthesised top-level union, `* except (…)`) is reported. A `*` the // parser resolves is base-exposed only when every source column it passes // the name through was one a base PII output exposed raw. if (!head.passthrough) return false const starRefs = head.starRaw(name) const exposed = baseRawPii(file) return starRefs.size > 0 && [...starRefs].every((ref) => refCovered(ref, exposed, envOf(file))) } for (const ctx of ctxByPath.values()) { const tasks: 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, 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)) tasks.push( semanticChangeLane( ctx.file, input.runner, ctx.engineOldSql, ctx.engineNewSql, dialect, ctx.impact, input.rubric, unverified, ), ) } if (lanes.has("lineage_breakage")) { // Synchronous detectors run as tasks so a throw is isolated to this file. tasks.push(Promise.resolve().then(() => lineageBreakageLane(ctx.file, ctx.impact, input.rubric))) tasks.push(columnBreakageLane(ctx, input.runner, getCompiled, dialect)) } if (lanes.has("lineage_breakage") || lanes.has("contract_violation")) { tasks.push( consumerContractLane(ctx, input.runner, dialect, { checkContractColumns: input.config.checkContractColumns, changedYmlText }), ) tasks.push(consumerListLane(ctx, input.runner, dialect, input.consumerLists ?? [])) } if (lanes.has("test_coverage")) tasks.push(missingGrainTestLane(ctx, input.runner)) // PII classification always runs (cheap name-pattern check, diff-scoped to // newly-introduced columns) — exposing PII is a hard-floor concern that // shouldn't depend on the cost tier enabling the pii_exposure lane. If core // lineage/classification fails, keep the broad deterministic fallback. // Run it as a concurrent task (not an inline await) so the heavy native // lineage/classify calls overlap the other engine lanes for this file. const currentCtx = ctx tasks.push( (async () => { const diffScopedPii = await piiClassifyLane(currentCtx, input.runner, dialect) if (diffScopedPii.completed) { diffScopedPiiCompletedFiles.add(currentCtx.file.path) classifiedPiiColumnsByFile.set(currentCtx.file.path, diffScopedPii.classifiedColumns) } if (diffScopedPii.findings.length) diffScopedPiiFindingFiles.add(currentCtx.file.path) flaggedPiiColumnsByFile.set( currentCtx.file.path, new Set(diffScopedPii.findings.map((f) => String((f.evidence?.result as any)?.column ?? "").toLowerCase())), ) const findings = [...diffScopedPii.findings] let basePii = new Set() let baseAbstained = false if (hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { try { const baseRes = await input.runner.detectPii(currentCtx.engineOldSql, dialect) baseAbstained = baseRes.abstained === true basePii = new Set(baseRes.columns.map((c) => c.toLowerCase())) } catch { /* unknown base exposure: report as if new */ } 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) — // dedup against the columns core actually CONSIDERED, never all // introduced columns, so a missed column still surfaces here. let fallbackPii = diffScopedPii.completed ? currentCtx.pii.filter((col) => !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 && baseAbstained) { // An unanalysable base says nothing about what it exposed; reporting // every head column as newly exposed would be a false positive. unverified.push({ path: currentCtx.file.path, reason: "the PII check could not analyse the base model", kind: "abstained", }) fallbackPii = [] } else { fallbackPii = fallbackPii.filter( (col) => !isBaseExposedOutput(currentCtx.file.path, col.toLowerCase(), basePii), ) } const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql findings.push(...piiLane(currentCtx.file, fallbackPii, baseUnknown)) } return findings })(), ) // Deterministic dbt anti-pattern detectors run on RAW SQL + diff (need Jinja). if (lanes.has("dbt_patterns")) { tasks.push( Promise.resolve().then(() => detectModelPatterns(ctx.file, ctx.newSql, input.rubric, { dialect, dialectKnown: !!input.dialectKnown }), ), ) tasks.push(lexicalLane(ctx.file, input.runner)) } if (lanes.has("dbt_patterns") || lanes.has("materialization")) { tasks.push(incrementalSemanticsLane(ctx, input.runner, dialect, !!input.dialectKnown, prText, input.config.incrementalSliceVars)) } // dbt config/Jinja lint (materialization / incremental / contract) — gate on its // own concerns, not just dbt_patterns, so it isn't silently dropped on a tier that // enables those concerns without dbt_patterns. if (lanes.has("dbt_patterns") || lanes.has("materialization") || lanes.has("contract_violation")) { tasks.push(dbtConfigLane(ctx, input.runner, projectVars)) tasks.push(uniqueKeyMismatchLane(ctx, input.runner, ymlChanged)) tasks.push(joinKeyUniquenessLane(ctx, input.runner)) tasks.push( (input.runner.modelConfig?.(modelNameFromPath(ctx.file.path)) ?? Promise.resolve(undefined)) .catch(() => undefined) .then((mc) => [ ...jinjaFindings(ctx.file, ctx.oldSql, ctx.newSql), ...modelConfigFindings(ctx.file, ctx.newSql && inlineConfigSplats(ctx.newSql), dialect, mc, !!input.dialectKnown), ]), ) } // Base-vs-head structural diff is a `semantic_change` concern (DISTINCT/UNION/grain/ // surrogate-key/predicate changes) — gate on semantic_change, keeping dbt_patterns // so the trivial tier (which has no semantic_change lane) still gets it. if (lanes.has("semantic_change") || lanes.has("dbt_patterns")) { tasks.push(structuralChangeLane(ctx, input.runner)) } // A lane that throws drops only its own findings for this file, recorded // as unverified — never the whole review. let laneFailed = false const settled = await Promise.all( tasks.map((t) => t.catch((err) => { if (!laneFailed) failedFile(ctx.file, err) laneFailed = true return [] as Finding[] }), ), ) all.push(...settled) } // PR-level: cross-model sibling filter-consistency (divergent filters on a // shared upstream across the changed models). if (lanes.has("semantic_change")) { all.push(await prLevel("sibling_consistency", siblingConsistencyLane([...ctxByPath.values()], input.runner))) } // PR-level: topology-aware equivalence for merge refactors (N models deleted + // 1 added that supersedes them). Per-model equivalence can't see these because // the new model has no 1:1 base. Advisory only (capped at warning). if (lanes.has("semantic_change")) { all.push(await prLevel("topology_equivalence", topologyEquivalenceLane(modelFiles, input.runner, getCompiled, dialect))) } // Snapshot definitions: a changed `check_cols`/strategy or query on an existing snapshot. if (lanes.has("dbt_patterns") || lanes.has("materialization")) { const snapshots = reviewable.filter((f) => f.kind === "snapshot" && f.status !== "deleted" && f.status !== "added") touch(snapshots) const sets = await Promise.all( snapshots.map(async (file) => { try { const [oldSql, newSql] = await Promise.all([getContent?.(file.oldPath ?? file.path, "old"), getContent?.(file.path, "new")]) if (!newSql) return [] const model = modelNameFromPath(file.path) const manifestConfig = await input.runner.modelConfig?.(model) return snapshotFindings({ file, model, newSql, oldSql, prText, manifestConfig }) } catch (err) { failedFile(file, err) return [] } }), ) for (const findings of sets) all.push(findings) } // An `adapter.dispatch` call that now passes a keyword some `__` variant in the repo doesn't take. const dispatchVariantFindings = async (file: ChangedFile, newSql: string): Promise => { if (!/\badapter\.dispatch\b/.test(newSql)) return [] const texts = new Map([[file.path, newSql]]) for (const name of new Set([...newSql.matchAll(/\badapter\.dispatch\s*\(\s*['"](?:\w+\.)?(\w+)['"]/g)].map((m) => m[1]))) { const hits = (await input.grepProject?.(`__${name}(`).catch(() => [])) ?? [] for (const path of new Set(hits.map((h) => h.path))) if (!texts.has(path)) texts.set(path, (await getContent?.(path, "new").catch(() => undefined)) ?? "") } return dispatchKwargFindings(file, newSql, (name) => [...texts.values()].flatMap((t) => dispatchVariants(t, name))) } // Macros: the catalog rules that hold in a SQL template, and vars with no default. if (lanes.has("dbt_patterns")) { const macros = reviewable.filter((f) => f.kind === "macro" && f.status !== "deleted") touch(macros) const sets = await Promise.all( macros.map(async (file) => { try { const [newSql, oldSql] = await Promise.all([ getContent?.(file.path, "new"), file.status === "added" ? Promise.resolve(undefined) : getContent?.(file.oldPath ?? file.path, "old")?.catch(() => undefined), ]) if (!newSql) return [] return [ ...detectMacroPatterns(file, newSql, input.rubric, projectVars, { dialect, dialectKnown: !!input.dialectKnown }), ...jinjaFindings(file, oldSql, newSql), ...(await dispatchVariantFindings(file, newSql)), ] } catch (err) { failedFile(file, err) return [] } }), ) for (const findings of sets) all.push(findings) } // ref() to a name no model, seed or snapshot carries: dbt fails to parse the project. if (lanes.has("dbt_patterns") && input.resourceNames) { const models = [...ctxByPath.values()].filter((c) => c.file.status !== "deleted" && /\bref\s*\(/.test(c.file.diff ?? "")) const names = models.length ? await input.resourceNames().catch(() => undefined) : undefined if (names) for (const c of models) all.push(missingRefFindings(c.file, names)) } // Singular tests and snapshots: Jinja structure. packages.yml / dbt_project.yml: pins and config. if (lanes.has("dbt_patterns")) { const others = reviewable.filter( (f) => f.status !== "deleted" && ((f.kind === "test" || f.kind === "snapshot") || f.kind === "project_config"), ) touch(others) const sets = await Promise.all( others.map(async (file) => { try { const [newContent, oldContent] = await Promise.all([ getContent?.(file.path, "new"), file.status === "added" ? Promise.resolve(undefined) : getContent?.(file.oldPath ?? file.path, "old")?.catch(() => undefined), ]) if (file.kind === "project_config") return [...packagesFindings(file, newContent), ...dbtProjectFindings(file, oldContent, newContent)] return [...jinjaFindings(file, oldContent, newContent), ...(file.kind === "test" ? testWindowFindings(file) : [])] } catch (err) { failedFile(file, err) return [] } }), ) for (const findings of sets) all.push(findings) } // Files checked whatever their dbt role (a `.quickstart/quickstart.yml` is "other"): YAML that // no longer parses, and new models missing from the quickstart `public_models`. const otherChecked = new Set() const checkedOther = (file: ChangedFile) => { otherChecked.add(file.path) touch([file]) } if (lanes.has("dbt_patterns")) { const read = (p: string, side: "old" | "new") => getContent?.(p, side)?.catch(() => undefined) ?? Promise.resolve(undefined) const ymls = reviewable.filter((f) => f.status !== "deleted" && /\.ya?ml$/i.test(f.path)) const sets = await Promise.all( ymls.map(async (file) => { const [newContent, oldContent] = await Promise.all([ read(file.path, "new"), file.status === "added" ? Promise.resolve(undefined) : read(file.oldPath ?? file.path, "old"), ]) if (file.kind === "other") checkedOther(file) return yamlParseFindings(file, oldContent, newContent) }), ) for (const findings of sets) all.push(findings) for (const file of reviewable.filter((f) => f.status === "added" && /(^|\/)package-lock\.yml$/.test(f.path))) { const dir = file.path.slice(0, file.path.length - "package-lock.yml".length) const [projectYml, testsYml, nested] = await Promise.all([ read(`${dir}dbt_project.yml`, "new"), read(`${dir}integration_tests/dbt_project.yml`, "new"), // `integration_tests//dbt_project.yml` (grepProject globs from the project root; // a git pathspec `*` crosses directories). (dir === (input.layout?.root ? input.layout.root + "/" : "") && input.grepProject?.("name", "integration_tests/*dbt_project.yml").then((h) => h ?? []).catch(() => [])) || Promise.resolve([]), ]) if (projectYml === undefined && testsYml === undefined) continue checkedOther(file) all.push(packageLockFindings(file, isPackageProject(projectYml, !!testsYml || nested.length > 0))) } const newModels = reviewable.filter((f) => f.kind === "model_sql" && f.status === "added") if (newModels.length) { const QUICKSTART = /(^|\/)\.quickstart\/quickstart\.ya?ml$/ const changed = reviewable.find((f) => QUICKSTART.test(f.path) && f.status !== "deleted") const qsPath = changed?.path ?? `${input.layout?.root ? input.layout.root + "/" : ""}.quickstart/quickstart.yml` const content = await read(qsPath, "new") if (content) { if (changed) checkedOther(changed) all.push(quickstartModelFindings(changed ?? newModels[0], qsPath, content, newModels.map((f) => modelNameFromPath(f.path)))) } } } // schema.yml-level detectors (test removal) — run on changed YAML files // regardless of tier, since deleting a guardrail test is always worth flagging. // Pass old + new content when available so the detector diffs structural YAML // (per-(entity, column, test) tuples) instead of walking the unified diff // (which loses context when the model header is outside the -U3 window and // silently drops sibling-column edge cases). Falls back to diff-only line // detection when a content resolver isn't wired (e.g. unit-test callers). // // `oldContent` is fetched for anything that has an old side — MODIFIED, // RENAMED, and DELETED. A schema.yml being renamed (e.g. moved to a new // subdir) that also drops a `unique`/`not_null` guardrail must still surface // as a finding; the earlier `status === "modified"` gate silently skipped // renames. A whole schema.yml being DELETED removes every test declared in // it — an even bigger removal — so the detector runs against `oldContent` // vs an empty new document (cubic-review P2). // // `newContent` fetch is skipped for deleted files (nothing at HEAD to read; // git-show would fail). // // Fetches run in parallel across schema files (a schema-heavy PR could touch // dozens of yml files; serial `git show` per file adds up). // A `{% docs name %}` block in any of the project's .md files at head (cached per name). const docLookups = new Map>() // Docs blocks of installed packages (cached); undefined when they can't be known. let pkgDocs: Promise | undefined> | undefined const packageDocs = () => (pkgDocs ??= input.packageDocNames?.().catch(() => undefined) ?? Promise.resolve(undefined)) const docExists = (name: string) => { if (!docLookups.has(name)) { const block = new RegExp(`\\{%-?\\s*docs\\s+${name}\\s*-?%\\}`) docLookups.set( name, (input.grepProject?.(`docs ${name}`, "*.md") ?? Promise.resolve([])) // An unavailable search (undefined) is no evidence the block is missing. .then(async (hits) => hits === undefined || hits.some((h) => block.test(h.text)) || !!(await packageDocs())?.has(name)) // A failed search is no evidence the block is missing. .catch(() => true), ) } return docLookups.get(name)! } // The project defines docs blocks of its own (any `{% docs x %}` in its .md files), and its // installed packages' blocks are known: a package may define the name otherwise. let docsAny: Promise | undefined const projectHasDocs = () => (docsAny ??= (input.grepProject?.("docs", "*.md") ?? Promise.resolve([])) .then(async (hits) => !!hits?.some((h) => /\{%-?\s*docs\s+\w+\s*-?%\}/.test(h.text)) && (await packageDocs()) !== undefined) // A failed or unavailable search is no evidence: stay silent. .catch(() => false)) const schemaFiles = reviewable.filter((f) => f.kind === "schema_yml") touch(schemaFiles) const sqlByModel = new Map([...ctxByPath.values()].filter((c) => c.newSql).map((c) => [modelNameFromPath(c.file.path).toLowerCase(), c.newSql!])) if (schemaFiles.length) { const schemaFindingSets = await Promise.all( schemaFiles.map(async (file) => { try { const oldRef = file.oldPath ?? file.path const [oldContent, newContent] = await Promise.all([ file.status !== "added" ? getContent?.(oldRef, "old") : Promise.resolve(undefined), file.status !== "deleted" ? getContent?.(file.path, "new") : Promise.resolve(undefined), ]) return [ ...detectSchemaYmlPatterns(file, input.rubric, { oldContent, newContent }), ...testsOnNullColumns(file, newContent, sqlByModel), ...detectUnitTestFixtures(file, oldContent, newContent), ...snapshotYmlFindings(file, oldContent, newContent), ...detectTestAdequacy({ file, oldContent, newContent, projectYml, layout: input.layout }), ...(lanes.has("dbt_patterns") && input.grepProject ? await docRefFindings(file, oldContent, newContent, docExists, projectHasDocs) : []), ] } catch (err) { // One malformed schema file degrades that file only. failedFile(file, err) return [] as Finding[] } }), ) for (const findings of schemaFindingSets) all.push(findings) } // A dbt_project.yml change that loosens test thresholds for a whole path. for (const file of reviewable.filter((f) => f.kind === "project_config" && /(^|\/)dbt_project\.ya?ml$/.test(f.path))) { if (file.status !== "modified") continue touch([file]) const [oldContent, newContent] = await Promise.all([getContent?.(file.path, "old"), getContent?.(file.path, "new")]) all.push(detectThresholdLoosening(file, oldContent, newContent)) } // Architectural dedup: the regex `dbt-patterns`/`rule-catalog` layer is a // diff-aware, Jinja-aware, offline fallback. For the STRUCTURAL SQL checks // that the native core lint covers via the parsed AST, the AST version is the // source of truth — it can't be tripped by string literals, aliases, or // leading commas the way regex can. So when core lint actually ran for a // file, drop the regex twins of those AST-covered checks. The dbt-specific / // diff-specific detectors (incremental, materialization, ref conventions, // schema.yml test removal, portability) are NOT covered by core and stay. const coreRanFiles = new Set() if (lanes.has("sql_quality") || lanes.has("warehouse_cost")) { await Promise.all( [...ctxByPath.values()].map(async (ctx) => { if (!ctx.engineNewSql || ctx.file.status === "deleted") return // Cache hit: qualityLane already ran this exact check. const cr = await input.runner .check(ctx.engineNewSql, dialect, ctx.engineOldSql) .catch(() => ({ ran: false }) as CheckResult) if (cr.ran) coreRanFiles.add(ctx.file.path) }), ) } // Per file, the function names core's AST L033 (NonPortableFunction) flagged. // The regex portability catalog defers to core for these (single source); // regex still covers functions core didn't flag (dialect-suppressed / not in // core's set) plus reserved words / types / operators that L033 doesn't do. const flat = all.flat() const schemaPiiFiles = new Set( flat.filter((f) => f.category === "pii_exposure" && f.evidence?.tool === "schema.detect_pii").map((f) => f.file), ) // Per file, the concatenated rule names core's AST lint actually emitted — // so we suppress a regex twin only when core genuinely covered that concern. const coreRulesByFile = new Map() for (const f of flat) { if (f.evidence?.tool !== "altimate_core.check") continue const rule = String((f.evidence?.result as any)?.rule ?? "") .toLowerCase() .replace(/_/g, "-") coreRulesByFile.set(f.file, `${coreRulesByFile.get(f.file) ?? ""} ${rule}`) } const corePortabilityFns = new Map>() for (const f of flat) { if (f.evidence?.tool === "altimate_core.check" && (f.evidence?.result as any)?.rule === "non_portable_function") { const m = /([A-Za-z_][A-Za-z0-9_.]*)\s*\(\)/.exec(`${f.title} ${f.body}`) if (m) { const set = corePortabilityFns.get(f.file) ?? new Set() set.add(m[1].toLowerCase()) corePortabilityFns.set(f.file, set) } } } // An added line is a pure reindent (or comment/comma-only edit) only when it // matches a removed line AND every select item it belongs to in the head is the // same item, in the same query scope (CTE, nested query or final select), in the // base. Matching a removed line elsewhere is not enough: `email,` moved from a // CTE into the final select, or `ssn` left behind when `sha2(\n ssn\n) as x` // is unwrapped, exposes something new. const reindentByFile = new Map; head: SelectItem[]; headLines: string[]; base: Set }>() const itemKey = (i: SelectItem) => `${i.scope}#${i.branch}\u0000${i.text.toLowerCase()}` const reindentInfo = (file: string) => { const ctx = ctxByPath.get(file) if (!ctx?.newSql) return undefined let r = reindentByFile.get(file) if (!r) { r = { removed: new Set(splitDiff(ctx.file.diff).removed.map(normalizeSelectLine).filter(Boolean)), // One parse of the head serves the reindent check and the reach analysis. head: headReach(file)!.items, headLines: ctx.newSql.split("\n").map(normalizeSelectLine), base: new Set(ctx.oldSql ? selectItems(ctx.oldSql).map(itemKey) : []), } reindentByFile.set(file, r) } return r } // The 1-based head lines equal to `line` (normalised). const headLineNumbers = (file: string, line: string) => { const r = reindentInfo(file) const normalized = normalizeSelectLine(line) if (!r || !normalized) return [] return r.headLines.flatMap((l, i) => (l === normalized ? [i + 1] : [])) } // Head select items spanning any head line equal to `line` (normalised). const headItemsOnLine = (file: string, line: string) => { const lineNos = headLineNumbers(file, line) return (reindentInfo(file)?.head ?? []).filter((i) => lineNos.some((n) => i.startLine <= n && n <= i.endLine)) } const isReindented = (file: string, line: string) => { const r = reindentInfo(file) if (!r || !ctxByPath.get(file)?.oldSql || !r.removed.has(normalizeSelectLine(line))) return false const items = headItemsOnLine(file, line) return items.length > 0 && items.every((i) => r.base.has(itemKey(i))) } // Without a compiled base every other PII lane is undecided (an unknown- // confidence warning). A regex twin whose source columns the raw base cannot // expose (`rawBaseLacks`) is proven new, so those undecided findings must not // stand in for it: it survives their dedup and keeps its severity below. // The proof is withheld only on evidence, from the head's raw SQL, that the // column does not reach the model's output unmasked. Both must hold: // - on the twin's line: it lies inside select items and each reads the column // only inside masking calls or a window clause (`sha2(\n ssn\n) as // tax_ref`; not `coalesce(\n ssn,\n '')`, which keeps the value), is a `*` // that excludes it, or sits in a CTE or FROM subquery that no reading query // passes on unmasked (`rawReach`: hashed or dropped on the way, or read only // by an `in`/`exists` condition); or it is in no select item but in a // clause that selects nothing (`order by\n ssn`); // - in the rest of the head: nothing may expose the column (`mayExpose`). The // twin fires only on a line that opens with the column, so the same column // selected elsewhere (`select ssn from …` on one line, a `*` over its // table) still reaches the output when the twin's own line is dropped. // Anything `rawReach` cannot follow counts as reaching, so the twin blocks. const headReachByFile = new Map() const headReach = (file: string) => { if (!headReachByFile.has(file)) { const sql = ctxByPath.get(file)?.newSql headReachByFile.set(file, sql ? rawReach(sql) : undefined) } return headReachByFile.get(file) } const rawBaseCodeByFile = new Map() const baseCode = (file: string) => { if (!rawBaseCodeByFile.has(file)) rawBaseCodeByFile.set(file, rawBaseCode(ctxByPath.get(file)?.oldSql)) return rawBaseCodeByFile.get(file) } // Asked for each twin in the dedup and again for its severity: kept per finding // (per-token twins share a fingerprint, so the finding itself is the key). const provenByFinding = new WeakMap() const provenNewTwin = (f: Finding) => { let proven = provenByFinding.get(f) if (proven === undefined) provenByFinding.set(f, (proven = proveNewTwin(f))) return proven } const proveNewTwin = (f: Finding) => { const ctx = ctxByPath.get(f.file) if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql) return false const result = (f.evidence?.result ?? {}) as { column?: string; line?: string; items?: SelectItemColumn[] } const hits = result.items?.length ? result.items : result.column ? [{ column: result.column, line: result.line ?? "" }] : [] if (!hits.length || !rawBaseLacks(baseCode(f.file), hits.map((h) => h.column))) return false const reach = headReach(f.file) const mayReachOutput = (hit: { column: string; line: string }) => { const column = hit.column.toLowerCase() const lineNos = headLineNumbers(f.file, hit.line) if (!reach || !lineNos.length || reach.mayExpose(column)) return true // Any head line with this text counts: the diff does not say which one it is. return lineNos.some((n) => { // The analysis's own items: it knows them by identity. const items = reach.items.filter((i) => i.startLine <= n && n <= i.endLine) return items.length ? items.some((i) => reach.passes(i, column)) : !reach.inClause(n) }) } return hits.every(mayReachOutput) } const merged = flat.filter((f) => { const tool = f.evidence?.tool const fallbackRule = String((f.evidence?.result as any)?.rule ?? "").replace(/_/g, "-") // Dedup the coarse regex PII twins against the precise deterministic PII // detectors — but only when a better detector genuinely COVERS the same // column. Suppressing whenever the classifier merely "ran" hid real PII // (a high-risk column core's classifier missed but the regex would catch, // especially on tiers without the broad `pii_exposure` lane). if ( (tool === "dbt-patterns" || tool === "rule-catalog") && f.category === "pii_exposure" && (fallbackRule === "pii-into-mart" || fallbackRule === "select-pii-columns") ) { const proven = provenNewTwin(f) // The broad `schema.detect_pii` lane already flagged this file → redundant. if (schemaPiiFiles.has(f.file) && !proven) return false const result = (f.evidence?.result ?? {}) as { line?: string column?: string alias?: string items?: SelectItemColumn[] } if (fallbackRule === "pii-into-mart") { // `pii_into_mart` is one finding per column token, carrying the column, // its alias and the line. A reindented base line exposes nothing new. if (result.line && isReindented(f.file, result.line)) return false if (!result.column) return !diffScopedPiiCompletedFiles.has(f.file) // Suppress when core's classifier actually CONSIDERED that column (flagged // or deliberately muted). A column core never classified falls through. // A proven-new twin is dropped only when core muted the column, not when // core flagged it as an undecided warning. const classified = classifiedPiiColumnsByFile.get(f.file) const flagged = flaggedPiiColumnsByFile.get(f.file) const considered = (c?: string) => !!c && !!classified?.has(c) && !(proven && flagged?.has(c)) if (considered(result.column) || considered(result.alias)) return false // A column the base already exposed is not newly exposed by this PR. return !isBaseExposed(f.file, result.column, result.alias, result.line) } // `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.column, i.alias, i.line))) 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) && !proven) return false return true } if (!coreRanFiles.has(f.file)) return true if (tool !== "dbt-patterns" && tool !== "rule-catalog") return true // Structural twins: the check code survives on evidence.result.rule (ruleKey // is stripped by the zod schema). Suppress ONLY if core actually emitted the // equivalent rule for this file (else the issue would fall through). const code = fallbackRule const coreMatcher = CORE_AST_COVERED[code] if (coreMatcher && coreMatcher.test(coreRulesByFile.get(f.file) ?? "")) return false // Portability twins: drop a regex finding ONLY IF it is itself a portability // finding AND core L033 flagged the same function. This spares other // concerns about the same function (e.g. GETDATE() idempotency), which are // distinct findings that must survive. const coreFns = corePortabilityFns.get(f.file) // Portability phrasings used across the catalog ("non-portable", // "dialect-specific", "aren't/isn't standard", "not standard SQL"). Excludes // idempotency/other concerns, which never use this language. const isPortability = /portab|dialect[ -]specific|non-?standard|n't standard|not standard|standard sql/i.test( f.body, ) if (coreFns?.size && isPortability && fnTokensOf(`${f.title} ${f.body}`).some((t) => coreFns.has(t))) return false return true }) // Without a compiled base (raw Jinja on the old side) the regex PII twins can't // tell a new column from one the base already exposed: report them like the // other PII lanes, as a warning of unknown confidence that never blocks. // Unless the raw base proves the column new (`rawBaseLacks`): then the twin // keeps its severity and is marked, so it counts toward the verdict as the // one pattern finding that blocks without being named in `blockingRules`. for (const [i, f] of merged.entries()) { const rule = (f.evidence?.result as { rule?: string } | undefined)?.rule if (f.category !== "pii_exposure" || (rule !== "pii_into_mart" && rule !== "select-pii-columns")) continue const ctx = ctxByPath.get(f.file) if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql) continue if (provenNewTwin(f)) { if (f.evidence) merged[i] = { ...f, evidence: { ...f.evidence, result: { ...(f.evidence.result as object), provenNew: true } } } continue } merged[i] = { ...f, severity: f.severity === "critical" ? "warning" : f.severity, confidence: "unknown" } } // The findings a reader sees before the severity threshold: deduped, rubric // exclusions and off-engine portability advice dropped, repeats merged, most // severe first. The AI lane is grounded in this list (its prompt keeps the // top 40), so dropped or repeated findings don't crowd out real ones. const scopedFiles = [...input.changedFiles, ...(input.aiOutsideFiles ?? [])] const cleanFindings = (list: Finding[], merge = true): Finding[] => { let out = dedupe(list) .filter((f) => !exclusionReason(f, input.rubric)) .map((f) => { // The matched source text some lanes record, quoted as evidence. const line = (f.evidence?.result as { line?: unknown } | undefined)?.line return typeof line === "string" && line.trim() && !f.evidenceLine ? { ...f, evidenceLine: line.trim().slice(0, 200) } : f }) // Per-rule posting policy: `off` rules are dropped (and so never ground the // AI lane); the rest are marked for inline or summary-only posting. out = out .map((f) => ({ f, tier: ruleTier(f.rule, input.config.rules) })) .filter(({ tier }) => tier !== "off") .map(({ f, tier }) => ({ ...f, tier: tier === "inline" ? ("inline" as const) : ("summary" as const) })) // 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) out = out.filter((f) => !isSuppressiblePortability(f, dialect, input.portabilityTargets)) // Outside-project files the AI lane reads are classified like in-project ones. out = markPreExisting(anchorByEvidence(out, scopedFiles), scopedFiles) if (merge) out = mergeRepeats(out) return out.sort((a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || a.file.localeCompare(b.file)) } // AI reviewer lane — runs AFTER the deterministic lanes so it can be GROUNDED // in (and told not to duplicate) the engine findings. Advisory only: its // findings are clamped to ≤ warning upstream, so they enrich the review but // never change what blocks. Skipped when no aiReview fn is injected (tests / // headless-without-model) — the review degrades to deterministic-only. let aiStatus: AiLaneStatus | undefined // Files the AI lane sent, and those it reviewed (sent in a call that answered); outside-project ones apart. let aiSentPaths: string[] = [] const aiReviewed = new Set() let aiReviewedOutside: string[] = [] // The rule verifier's verdict per posted rule finding (`verifyRules`), and whether it ran. const ruleVerdicts = new Map() let ruleVerifierRan = false // The rule verifier was asked to run (it may still have skipped or failed). let ruleVerifyAttempted = false // The deterministic findings validated before the AI lane ran (the first `count` of `merged`), reused after it. let preAiValidated: { count: number; list: Finding[] } | undefined if (!lanes.has("ai_review")) { aiStatus = { state: "skipped", reason: `not part of the ${tier} tier` } } else if (!input.aiReview) { aiStatus = { state: "skipped", reason: input.aiDisabledReason ?? "disabled" } } else { // Changed files that may hold credentials: named like a credential file now or before a // rename, over every file the PR changes. Neither side of them reaches the AI lane or the verifier. const prRenames = input.prRenames ?? new Map() const credentialLike = new Set( [ ...input.changedFiles.map((f) => [f.path, f.oldPath ?? prRenames.get(f.path)] as const), ...(input.prFiles ?? []).map((p) => [p, prRenames.get(p)] as const), ] .filter(([p, old]) => isCredentialPath(p) || (!!old && isCredentialPath(old))) .map(([p]) => p), ) const mayHoldCredentials = (p: string) => credentialLike.has(p) || isCredentialPath(p) // A file whose diff carries key material is not sent; one whose full text does is sent as its diff only. const screened = (f: AiReviewFile): AiReviewFile[] => mayHoldCredentials(f.path) || (f.diff && holdsCredentials(f.diff)) ? [] : [f.sql && holdsCredentials(f.sql) ? { ...f, sql: undefined } : f] const aiFiles: AiReviewFile[] = [...ctxByPath.values()].flatMap((ctx) => screened({ path: ctx.file.path, status: ctx.file.status, model: modelNameFromPath(ctx.file.path), kind: ctx.file.kind, diff: ctx.file.diff, sql: ctx.engineNewSql ?? ctx.newSql, }), ) // Macros, data tests, snapshots, yml and seeds carry defects no model diff shows. // Seeds go as a diff only: the full CSV is data, not logic. const supporting = reviewable.filter( (f) => AI_SUPPORTING_KINDS.has(f.kind) && f.status !== "deleted" && !mayHoldCredentials(f.path), ) // `otherFiles`: other/analysis files inside the project root (.sql/.yml/.yaml), after the supporting files. if (switchOn("otherFiles", input.aiSwitches)) { const root = input.layout?.root supporting.push( ...reviewable.filter( (f) => isAiOtherFile(f) && !mayHoldCredentials(f.path) && (root === undefined || relativeToRoot(f.path, root) !== undefined), ), ) } const contents = await Promise.all( supporting.map((f) => f.kind === "seed" ? undefined : getContent?.(f.path, "new")?.catch(() => undefined), ), ) supporting.forEach((f, i) => aiFiles.push( ...screened({ path: f.path, status: f.status, model: modelNameFromPath(f.path), kind: f.kind, diff: f.diff, sql: contents[i] }), ), ) // `pythonFiles`: changed .py files the lane does not send yet, inside the project root or // outside it (AI lane only), after every other file, with their head content. if (switchOn("pythonFiles", input.aiSwitches)) { const queued = new Set(aiFiles.map((f) => f.path)) const python = [...reviewable, ...(input.aiOutsideFiles ?? [])].filter( (f) => isAiPythonFile(f) && !mayHoldCredentials(f.path) && !isExcludedPath(f.path, input.rubric.exclusions.excludeGlobs) && !queued.has(f.path) && !!queued.add(f.path), ) const pyContents = await Promise.all(python.map((f) => getContent?.(f.path, "new")?.catch(() => undefined))) python.forEach((f, i) => aiFiles.push( ...screened({ path: f.path, status: f.status, model: modelNameFromPath(f.path), kind: AI_PYTHON_KIND, diff: f.diff, sql: pyContents[i] }), ), ) } // Only the files the AI lane will send are reached (its file cap, or the // per-kind quotas in coverage mode); the rest stay in the ledger. const aiBudget = aiInputBudget(process.env, input.aiSwitches) const aiSent = aiBudget.coverage ? selectAiFilesByQuota(aiFiles, aiBudget.coverage.quotas, aiBudget.coverage).sent : selectAiFiles(aiFiles, aiBudget.maxFiles) touch(aiSent) aiSentPaths = aiSent.map((f) => f.path) if (input.aiContextCard && anyManifest) await attachContextCards(aiFiles, input.runner) const context = input.aiGraphContext ? await aiGraphContext(aiFiles.map((f) => f.path), input.runner, getContent) : undefined // Files the PR changes that the AI may list and the verifier may read; never the user's exclusions or credentials. const prFiles = (input.prFiles ?? input.changedFiles.map((f) => f.path)).filter( (p) => !isExcludedPath(p, input.rubric.exclusions.excludeGlobs) && !mayHoldCredentials(p), ) // A renamed file's old side is read from its old path, as the content resolver does: the // in-scope rename as scoped, otherwise the PR's rename. Symlink targets are refused by safeReadInside. const inScopePaths = new Set(input.changedFiles.map((f) => f.path)) const oldPathOf = new Map([...prRenames].filter(([p]) => !inScopePaths.has(p))) for (const f of input.changedFiles) if (f.oldPath) oldPathOf.set(f.path, f.oldPath) const pathActuallyRead = (p: string, side: "old" | "new") => (side === "old" ? (oldPathOf.get(p) ?? p) : p) const refused = (p: string, side: "old" | "new") => mayHoldCredentials(p) || isCredentialPath(pathActuallyRead(p, side)) const REFUSED = "not available: may hold credentials" // Grep hits are dropped for any file that may hold credentials, by name or by its whole content. const grepProject: AiVerifyEvidence["grepProject"] = input.grepProject && (async (pattern, glob) => { const found = await input.grepProject!(pattern, glob) if (!found) return undefined const paths = [...new Set(found.map((h) => h.path))] const texts = await Promise.all( paths.map((p) => (mayHoldCredentials(p) ? undefined : getContent?.(p, "new").catch(() => undefined))), ) const clean = new Set(paths.filter((_, i) => texts[i] !== undefined && !holdsCredentials(texts[i]!))) return found.filter((h) => clean.has(h.path)) }) // The verifier reads engine SQL first (the same SQL the engine lanes saw), then compiled output. const evidence: AiVerifyEvidence | undefined = input.aiVerify ? { dialect, files: aiFiles, projectRoot: input.layout?.root, runner: input.runner, addedLines: addedLinesByFile( [...input.changedFiles, ...(input.aiOutsideFiles ?? [])].filter((f) => !mayHoldCredentials(f.path)), ), prTitle: input.prTitle, prBody: input.prBody, grepProject, prFiles, ...(input.conventions?.length ? { conventions: conventionTexts(input.conventions) } : {}), readFile: async (p, side, start, end) => { if (refused(p, side)) return REFUSED const text = await getContent?.(p, side) return text && holdsCredentials(text) ? REFUSED : numberedSlice(text, start, end) }, compiledSql: async (p, side) => { if (refused(p, side)) return undefined const ctx = ctxByPath.get(p) const engine = side === "new" ? ctx?.engineNewSql : ctx?.engineOldSql const sql = engine ?? (await getCompiled?.(pathActuallyRead(p, side), side)) return sql && holdsCredentials(sql) ? undefined : sql }, } : undefined // The rule findings as the envelope would post them (rule types off already dropped), for the rule verifier. if (evidence && switchOn("verifyRules", input.aiSwitches)) preAiValidated = { count: merged.length, list: await validateSuggestions(merged, getContent, addedLinesByFile([...input.changedFiles, ...(input.aiOutsideFiles ?? [])])), } // Rule types off on files the AI lane sends are dropped where the lane answers, so they are // verified only when their file's call failed (then they are posted); on any other file they // are posted, so they are verified like the rest. const sentSet = new Set(aiSentPaths) const ruleCandidates = preAiValidated ? (() => { const posted = cleanFindings(preAiValidated.list).filter( (f) => SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && findingOrigin(f) !== "ai" && f.severity !== "critical" && !mayHoldCredentials(f.file), ) const offKept = new Set(dropRulesOff(posted.filter((f) => sentSet.has(f.file)), input.rulesOff).kept) const offOnSent = (f: Finding) => sentSet.has(f.file) && !offKept.has(f) return { after: posted.filter((f) => !offOnSent(f)), ifUnreviewed: posted.filter(offOnSent) } })() : undefined const verifyRulesAfter = ruleCandidates?.after try { const res = await input.aiReview({ files: aiFiles, context, grounding: cleanFindings(merged), prTitle: input.prTitle, prBody: input.prBody, model: input.aiModel, prFiles, ...(evidence ? { evidence } : {}), ...(input.aiSwitches ? { switches: input.aiSwitches } : {}), ...(otherChecked.size ? { checkedPaths: [...otherChecked] } : {}), ...(input.reviewDir ? { reviewDir: input.reviewDir } : {}), ...(input.conventions?.length ? { conventions: input.conventions } : {}), ...(verifyRulesAfter?.length ? { verifyRulesAfter } : {}), ...(ruleCandidates?.ifUnreviewed.length ? { verifyRulesIfUnreviewed: ruleCandidates.ifUnreviewed } : {}), ...(input.rulePolicy ? { noisyRules: input.rulePolicy.noisyRules } : {}), }) const aiFindings = Array.isArray(res) ? res : res.findings if (Array.isArray(res)) aiStatus = { state: "ok" } else aiStatus = res.status if (aiStatus.verifyRules === "drop_refuted") { ruleVerifyAttempted = true // A batch forced to answer on its budget is the rule run's usual mode (the default budget // split over batches of 8 rarely leaves a tool round), and the rule-post policy was tuned on // those answers: they count. A verdict from a batch that timed out counts as no verdict. // Either way these steps filter posting only, so no verdict can unblock a gate. const batches = aiStatus.verifier?.batches ?? [] for (const v of aiStatus.verifier?.ruleVerdicts ?? []) ruleVerdicts.set(v.id, batches[v.batch]?.state === "timeout" ? null : v.verdict) ruleVerifierRan = rulePolicyApplies(aiStatus.ruleVerifier) } // A sent file counts as reviewed only when the lane answered for its call. if (aiStatus.state === "ok") { const failed = new Set(aiStatus.failedFiles ?? []) for (const p of aiSentPaths) if (!failed.has(p)) aiReviewed.add(p) } const outsidePaths = new Set((input.aiOutsideFiles ?? []).map((f) => f.path)) aiReviewedOutside = [...aiReviewed].filter((p) => outsidePaths.has(p)) // Defense in depth: the AI never blocks, regardless of what it returns. for (const f of aiFindings) merged.push(f.severity === "critical" ? { ...f, severity: "warning" } : f) } catch (err) { // A failed AI lane must never fail the review — but it must say so. aiStatus = { state: "error", reason: safeReason(err) } } } // Flatten, drop excluded, dedupe, threshold-filter. Findings validated before the AI lane are not validated again. const addedForSuggestions = addedLinesByFile([...input.changedFiles, ...(input.aiOutsideFiles ?? [])]) const validated = preAiValidated ? [...preAiValidated.list, ...(await validateSuggestions(merged.slice(preAiValidated.count), getContent, addedForSuggestions))] : await validateSuggestions(merged, getContent, addedForSuggestions) const minSev = SEVERITY_ORDER[input.config.severityThreshold] let findings = cleanFindings(validated).filter((f) => SEVERITY_ORDER[f.severity] >= minSev) // The verdict counts every instance; merging repeats is presentation only. let verdictFindings = cleanFindings(validated, false).filter((f) => SEVERITY_ORDER[f.severity] >= minSev) // Rule noise, only when the AI lane ran and answered (fail-open otherwise, like the // verifier): rule types off, then rule findings the verifier refuted, then the rule-post // policy. These steps filter posting only: the verdict counts every rule finding, so neither a // model verdict nor author text the verifier reads (the PR description) can unblock a gate. An // unmerged instance takes the verdict of its merged group. AI findings and critical rule findings are never // dropped by these steps. A merged repeat group with an AI member is left alone too, so a // rule finding it was merged with cannot take the AI finding down with it. const aiLaneRan = lanes.has("ai_review") && !!input.aiReview && aiStatus?.state === "ok" const mixedGroups = new Set(verdictFindings.filter((f) => findingOrigin(f) === "ai").map(repeatGroupId)) // A merged finding of such a group (by id), or an unmerged instance of one (by its group id). const inMixed = (f: Finding) => mixedGroups.has(f.id) || mixedGroups.has(repeatGroupId(f)) const ruleStep = (list: Finding[], step: (rules: Finding[]) => Finding[]) => { const kept = new Set(step(list.filter((f) => !inMixed(f)))) return list.filter((f) => inMixed(f) || kept.has(f)) } const rulesOff = aiLaneRan ? input.rulesOff : undefined // Rule types off stand on the AI lane having reviewed the same file: a finding on a file the // lane did not review (not sent, or its call failed) is posted. const offStep = (list: Finding[]) => { const r = dropRulesOff(list.filter((f) => aiReviewed.has(f.file)), rulesOff) const kept = new Set(r.kept) return { kept: list.filter((f) => !aiReviewed.has(f.file) || kept.has(f)), dropped: r.dropped } } findings = ruleStep(findings, (list) => offStep(list).kept) const verdictOf = (f: Finding) => ruleVerdicts.get(f.id) ?? ruleVerdicts.get(repeatGroupId(f)) const refuted = (f: Finding) => findingOrigin(f) !== "ai" && !inMixed(f) && f.severity !== "critical" && verdictOf(f) === "refuted" if (aiLaneRan && ruleVerdicts.size) { findings = findings.filter((f) => !refuted(f)) } let rulePolicy: { applied: boolean; dropped: RulePolicyDrops } | undefined if (aiLaneRan && input.rulePolicy && ruleVerifyAttempted) { if (ruleVerifierRan) { const byId = (list: Finding[]) => new Map(list.map((f) => [f.id, verdictOf(f) ?? null] as const)) findings = ruleStep(findings, (list) => dropByRulePolicy(list, byId(list), input.rulePolicy).kept) // The counts are taken over the instances below. rulePolicy = { applied: true, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } } } else rulePolicy = { applied: false, dropped: { unverifiable_high_sev: 0, noisy_type_not_confirmed: 0 } } } // The verdict counts the rule findings these steps did not post. When they change it — toward // REQUEST_CHANGES (a confident engine warning toward the ≥3-warning pattern), or away from APPROVE // with nothing else to show — they are listed with why they were withheld, so every verdict is // explainable from the comment. The per-step counts (`rulesOff`, `rulesRefuted`, `rulePolicy`) are // taken here over the instances, the unit the verdict, the summary and this list use; a merged // comment of three instances counts three. type Withheld = NonNullable[number] const withheldAll: Array<{ f: Finding; reason: Withheld["reason"] }> = [] let offDropped: Record = {} { let rest = verdictFindings const offKept = new Set( ruleStep(rest, (list) => { const r = offStep(list) offDropped = r.dropped return r.kept }), ) for (const f of rest) if (!offKept.has(f)) withheldAll.push({ f, reason: "rule_type_off" }) rest = rest.filter((f) => offKept.has(f)) if (aiLaneRan && ruleVerdicts.size) { for (const f of rest) if (refuted(f)) withheldAll.push({ f, reason: "refuted" }) rest = rest.filter((f) => !refuted(f)) } if (rulePolicy?.applied && input.rulePolicy) for (const f of rest) { const why = inMixed(f) ? undefined : rulePolicyDrop(f, verdictOf(f) ?? null, input.rulePolicy) if (why) { withheldAll.push({ f, reason: why }) rulePolicy.dropped[why]++ } } } const rulesRefuted = aiLaneRan && ruleVerifyAttempted ? withheldAll.filter((w) => w.reason === "refuted").length : undefined const withheldIds = new Set(withheldAll.map((w) => w.f)) const idealAll = computeIdealVerdict(verdictFindings, input.rubric) const idealPosted = computeIdealVerdict(verdictFindings.filter((f) => !withheldIds.has(f)), input.rubric) const blocking = (f: Finding) => f.severity === "warning" && f.confidence !== "unknown" && verdictEligible(f, input.rubric) const listed = idealAll === "REQUEST_CHANGES" && idealPosted !== "REQUEST_CHANGES" ? withheldAll.filter((w) => blocking(w.f)) : idealAll !== "APPROVE" && idealPosted === "APPROVE" ? withheldAll : [] const withheld: Withheld[] = listed.map(({ f, reason }) => ({ id: f.id, title: f.title, file: f.file, ...(f.startLine ? { startLine: f.startLine } : {}), severity: f.severity, reason, })) // Lint-only means no changed model resolved against a manifest. A single // undecidable finding does not make the whole run lint-only; those findings // carry their own `degraded` flag and are counted separately in the summary. const degraded = runDegraded const engineErrors = [...(input.runner.failures?.() ?? []), ...laneErrors] // Coverage ledger: every changed file the review did not look at, and why. // First reason per path wins; `unverified` entries are always kept. const sortedUnverified = unverified.sort((a, b) => a.path.localeCompare(b.path)) // An outside-project file the AI lane reviewed is not "outside the dbt project, not reviewed". const aiReviewedSet = new Set(aiReviewedOutside) const inputNotReviewed = (input.scope?.notReviewed ?? []).filter((n) => !aiReviewedSet.has(n.path)) // `outOfScopeFiles` drops only the reviewed files it counted (listed as outside the project). const reviewedCountedOutside = new Set( (input.scope?.notReviewed ?? []) .filter((n) => aiReviewedSet.has(n.path) && isOutsideProjectReason(n.reason)) .map((n) => n.path), ).size const ledger: NotReviewed[] = [ ...inputNotReviewed, ...dropped, ...reviewable // Other/analysis files the AI lane reviewed (`otherFiles`, `pythonFiles`) are covered; a // file in a call that failed, or a lane that errored or timed out, is not. .filter((f) => ((f.kind === "other" && !otherChecked.has(f.path)) || f.kind === "analysis") && !aiReviewed.has(f.path)) .map((f) => ({ path: f.path, reason: "not a dbt model/macro/test/yml/seed file" })), ...reviewable .filter((f) => !touched.has(f.path)) .map((f) => ({ path: f.path, reason: `no checks run for ${f.kind} files at the ${tier} tier` })), ...(manifestMissing && !anyManifest ? modelFiles.map((f) => ({ path: f.path, reason: "no dbt manifest: lineage, config and graph checks skipped" })) : []), ] const seen = new Set() const notReviewed = ledger.filter((e) => !seen.has(e.path) && !!seen.add(e.path)) notReviewed.push(...sortedUnverified) const envelope = buildEnvelope({ engineErrors: engineErrors.length ? engineErrors : undefined, ai: aiStatus, ...(rulesOff ? { rulesOff: offDropped } : {}), ...(rulesRefuted !== undefined ? { rulesRefuted } : {}), ...(rulePolicy ? { rulePolicy } : {}), ...(withheld.length ? { withheld } : {}), policy: input.policy, findings, verdictFindings, tier, mode: input.mode, rubric: input.rubric, engine: { core: input.coreVersion, model: input.modelVersion, cliVersion: input.cliVersion }, manifestHash: input.manifestHash, staleManifest: input.staleManifest, generatedAt: input.generatedAt, degraded, scope: input.scope || notReviewed.length ? { ...input.scope, ...(reviewedCountedOutside && input.scope?.outOfScopeFiles !== undefined ? { outOfScopeFiles: Math.max(0, input.scope.outOfScopeFiles - reviewedCountedOutside) || undefined } : {}), ...(aiReviewedOutside.length ? { aiReviewedOutside } : {}), unverified: sortedUnverified.length ? sortedUnverified : undefined, notReviewed, } : undefined, // Include tierReasons whenever `--explain-tier` / `--force-tier` is set, // when a riskTierPathTokens config error was caught above, OR when the // classifier lands on `full` tier — a naturally-full run is a customer- // visible policy call ("why did my YAML-only diff get REQUEST_CHANGES?") // and the reason list is what makes the verdict debuggable without the // customer having to re-run with --explain-tier. `trivial`/`lite` runs // stay silent to avoid noise on approvals. tierReasons: input.explainTier || tierForced || pathTokenConfigError || tier === "full" ? tierReasons : undefined, tierForced: tierForced ? true : undefined, tierClassified: tierForced ? classifiedTier : undefined, }) return signEnvelope(envelope) }