diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 2e8419cbe5..b9d19e1922 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -34,6 +34,10 @@ const COVERAGE_FULL_DIFF_FILE_CHARS = 2_000 /** Default per-call size under coverage (~30k tokens): 30 quota files at up to ~22k chars each would * otherwise make one ~660k-char call that overruns common context windows. */ const COVERAGE_BATCH_CHARS = 120_000 +/** Focused batching defaults under `ALTIMATE_REVIEW_AI_FOCUSED=1`. */ +const FOCUS_DEFAULTS: AiFocusBudget = { minFiles: 7, batchFiles: 5, maxBatches: 4 } +/** Paths listed per call under "OTHER FILES CHANGED IN THIS PR". */ +const FOCUS_OTHER_FILES = 40 /** * How much of the PR the lane sends. Defaults keep one bounded call; the @@ -49,12 +53,25 @@ export interface AiInputBudget { /** `ALTIMATE_REVIEW_AI_COVERAGE=1`: per-kind file quotas (replacing `maxFiles`) and * hunk-centred excerpts instead of head truncation. Undefined keeps today's input. */ coverage?: AiCoverageRender & { quotas: Record } + /** `ALTIMATE_REVIEW_AI_FOCUSED=1`: on PRs with at least `minFiles` selected files, review + * related files together in calls of about `batchFiles` files, at most `maxBatches` calls + * unless `batchChars` needs more. */ + focused?: AiFocusBudget +} +export interface AiFocusBudget { + minFiles: number + batchFiles: number + maxBatches: number } export function aiInputBudget(env: Record = process.env): AiInputBudget { const num = (v: string | undefined, d: number) => { const n = Number(v) return v && Number.isFinite(n) && n > 0 ? n : d } + const int = (v: string | undefined, d: number) => { + const n = Number(v) + return v && Number.isInteger(n) && n > 0 ? n : d + } // A quota of 0 disables that bucket. const quota = (v: string | undefined, d: number) => { const n = Number(v) @@ -77,6 +94,14 @@ export function aiInputBudget(env: Record = process. }, } : undefined, + focused: + env.ALTIMATE_REVIEW_AI_FOCUSED === "1" + ? { + minFiles: int(env.ALTIMATE_REVIEW_AI_FOCUS_MIN_FILES, FOCUS_DEFAULTS.minFiles), + batchFiles: int(env.ALTIMATE_REVIEW_AI_FOCUS_BATCH_FILES, FOCUS_DEFAULTS.batchFiles), + maxBatches: int(env.ALTIMATE_REVIEW_AI_FOCUS_MAX_BATCHES, FOCUS_DEFAULTS.maxBatches), + } + : undefined, } } @@ -86,6 +111,40 @@ export function aiDryRunEnabled(env: Record = proces return env.ALTIMATE_REVIEW_AI_DRYRUN === "1" } +/** Opt-in test-gap instruction (`ALTIMATE_REVIEW_AI_TEST_GAP=1`), appended to the core system prompt. */ +export function aiTestGapEnabled(env: Record = process.env): boolean { + return env.ALTIMATE_REVIEW_AI_TEST_GAP === "1" +} + +export const TEST_GAP_INSTRUCTION = ` + +## Tests for changed macros, materializations and tests +For each changed macro, materialization or generic test whose runtime behaviour changes (control flow, the SQL statements it issues, defaults, or the relations it creates, renames or drops), check whether this PR also adds or changes a test that runs the new behaviour: a dbt unit test, a singular or generic test, an integration_tests model, or a test file in the PR's file list. When none does, report ONE test_coverage comment on the changed definition that names the behaviour left untested and the case a test should cover. Do not report this for comments, renames, formatting, or a change that only moves code.` + +/** Most PR paths listed for the test-gap instruction. */ +const TEST_GAP_FILES_MAX = 40 + +/** Files a batch message already names: the batch, plus the other reviewed files a focused message lists. */ +export function listedFiles(plan: Pick, batch: AiReviewFile[]): AiReviewFile[] { + if (!plan.focused) return batch + return [...batch, ...plan.files.filter((f) => !batch.includes(f)).slice(0, FOCUS_OTHER_FILES)] +} + +/** The PR's other changed paths, appended to a batch message for the test-gap instruction. */ +export function testGapFileList(message: string, batch: AiReviewFile[], prFiles: string[] = []): string { + const inBatch = new Set(batch.map((f) => f.path)) + const others = prFiles.filter((p) => !inBatch.has(p)) + if (!others.length) return message + const shown = others.slice(0, TEST_GAP_FILES_MAX) + return [ + message, + "", + "## OTHER FILES THIS PR CHANGES (paths only, not shown; use them to judge test coverage)", + ...shown.map((p) => `- ${p}`), + ...(others.length > shown.length ? [`- … and ${others.length - shown.length} more`] : []), + ].join("\n") +} + export interface AiReviewFile { path: string status: string @@ -451,6 +510,156 @@ export function batchAiFiles(files: AiReviewFile[], budget: AiInputBudget): AiRe return batches } +const MACRO_DEF = /\{%-?\s*macro\s+(\w+)\s*\(/g +const DISPATCH_CALL = /adapter\.dispatch\(\s*['"](\w+)['"]/g +const REF_CALL = /\bref\(([^)]*)\)/g +const STRING_ARG = /['"]([^'"]+)['"]/g +const YML_NAME = /^[+ ]?\s*-\s*name:\s*['"]?([\w.-]+)['"]?\s*$/gm + +function dirOf(p: string): string { + const i = p.lastIndexOf("/") + return i < 0 ? "" : p.slice(0, i) +} + +/** Macro names a macro file defines: from its content, or from the diff's added lines without it. */ +function definedMacros(f: AiReviewFile): string[] { + if (f.kind !== "macro") return [] + const text = + f.sql ?? + (f.diff ?? "") + .split("\n") + .filter((l) => l.startsWith("+") && !l.startsWith("+++")) + .map((l) => l.slice(1)) + .join("\n") + return [...text.matchAll(MACRO_DEF)].map((m) => m[1]) +} + +/** + * Related changed files, for focused batches: connected components over macro + * dispatch families (`default__x`, `snowflake__x`, `adapter.dispatch('x'`), `ref()` + * edges, yml `- name:` declarations, then a same-directory fallback for files with + * no edge. Components follow the input order of their first member; members keep + * input order. + */ +export function groupAiFiles(files: AiReviewFile[]): AiReviewFile[][] { + const parent = files.map((_, i) => i) + const linked = files.map(() => false) + const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i]))) + const join = (a: number, b: number) => { + if (a === b) return + linked[a] = linked[b] = true + const [ra, rb] = [find(a), find(b)] + if (ra !== rb) parent[Math.max(ra, rb)] = Math.min(ra, rb) + } + const byModel = new Map() + files.forEach((f, i) => byModel.set(f.model, [...(byModel.get(f.model) ?? []), i])) + const family = new Map() + const joinFamily = (base: string, i: number) => { + const first = family.get(base) + if (first === undefined) family.set(base, i) + else join(first, i) + } + files.forEach((f, i) => { + const text = `${f.sql ?? ""}\n${f.diff ?? ""}` + for (const name of definedMacros(f)) joinFamily(name.replace(/^[A-Za-z0-9]+__(?=\w)/, ""), i) + for (const m of text.matchAll(DISPATCH_CALL)) joinFamily(m[1], i) + for (const m of text.matchAll(REF_CALL)) { + const name = [...m[1].matchAll(STRING_ARG)].at(-1)?.[1] + for (const j of (name && byModel.get(name)) || []) join(i, j) + } + if (f.kind === "schema_yml" || f.kind === "source_yml") + for (const m of text.matchAll(YML_NAME)) for (const j of byModel.get(m[1]) ?? []) join(i, j) + }) + const byDir = new Map() + files.forEach((f, i) => { + if (linked[i]) return + const first = byDir.get(dirOf(f.path)) + if (first === undefined) byDir.set(dirOf(f.path), i) + else join(first, i) + }) + const groups = new Map() + files.forEach((f, i) => { + const root = find(i) + groups.set(root, [...(groups.get(root) ?? []), f]) + }) + // Roots are each component's lowest index, so sorting by root orders components by first member. + return [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, g]) => g) +} + +/** + * Pack related-file groups into calls: groups over `batchFiles` files or + * `batchChars` characters split into consecutive chunks, chunks fill calls of up + * to `batchFiles` files and `batchChars` characters without being split; over + * `maxBatches` calls, the chunks are balanced by prompt size into at most + * `maxBatches` calls instead. `batchChars` keeps each call inside the model's + * context window, so it wins over `maxBatches`: a balanced call over it is split + * again, and the plan then has more than `maxBatches` calls. + */ +export function packFocusedBatches(groups: AiReviewFile[][], budget: AiInputBudget): AiReviewFile[][] { + const { batchFiles, maxBatches } = budget.focused ?? FOCUS_DEFAULTS + const chars = new Map() + const size = (c: AiReviewFile[]) => + c.reduce((n, f) => { + if (!chars.has(f)) chars.set(f, fileSection(f, budget.maxFileChars, budget.coverage).length) + return n + chars.get(f)! + }, 0) + const chunks = groups.flatMap((g) => { + const out: AiReviewFile[][] = [] + for (let i = 0; i < g.length; i += batchFiles) out.push(...batchAiFiles(g.slice(i, i + batchFiles), budget)) + return out + }) + const batches: AiReviewFile[][] = [] + for (const c of chunks) { + const cur = batches.at(-1) + if (cur && cur.length + c.length <= batchFiles && size(cur) + size(c) <= budget.batchChars) cur.push(...c) + else batches.push([...c]) + } + if (batches.length <= maxBatches) return batches + const bins = Array.from({ length: maxBatches }, () => ({ chars: 0, chunks: [] as number[] })) + chunks + .map((c, i) => ({ i, chars: size(c) })) + .sort((a, b) => b.chars - a.chars || a.i - b.i) + .forEach(({ i, chars }) => { + const bin = bins.reduce((best, b) => (b.chars < best.chars ? b : best)) + bin.chars += chars + bin.chunks.push(i) + }) + return bins + .filter((b) => b.chunks.length) + .flatMap((b) => (b.chars <= budget.batchChars ? [b.chunks] : splitByChars(b.chunks.sort((x, y) => x - y), (i) => size(chunks[i]), budget.batchChars))) + .map((ids) => ids.sort((x, y) => x - y).flatMap((i) => chunks[i])) +} + +/** Consecutive runs of `ids` whose summed size fits `max` (an oversized id goes alone). */ +function splitByChars(ids: number[], sizeOf: (i: number) => number, max: number): number[][] { + const out: number[][] = [] + let cur: number[] = [] + let total = 0 + for (const i of ids) { + const n = sizeOf(i) + if (cur.length && total + n > max) { + out.push(cur) + cur = [] + total = 0 + } + cur.push(i) + total += n + } + if (cur.length) out.push(cur) + return out +} + +/** Findings from several calls without repeats: same file, line and title (case and punctuation aside). */ +export function dedupAiFindings(findings: Finding[]): Finding[] { + const seen = new Set() + return findings.filter((f) => { + const key = [f.file ?? "", f.startLine ?? 0, f.title.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()].join("\u0000") + if (seen.has(key)) return false + seen.add(key) + return true + }) +} + /** An unchanged file the changed ones depend on (dbt DAG parent), sent as read-only context. */ export interface AiContextFile { path: string @@ -474,6 +683,8 @@ export interface AiReviewInput { model?: string /** What the verifier may read; it runs only when this is set and `ALTIMATE_REVIEW_AI_VERIFY=1`. */ evidence?: AiVerifyEvidence + /** Every file the PR changes (repo-relative), including files outside the dbt project. */ + prFiles?: string[] } /** What happened in the advisory lane, reported on the envelope and in the comment. */ @@ -515,6 +726,8 @@ export interface AiInputRecord { hunksTotal: number /** A manifest context card went with the file. */ card: boolean + /** Index of the call that carried the file; set only under focused batching. */ + batch?: number } /** Token counts as `Session.getUsage` reports them: `input` excludes cached * tokens, `inputTotal` includes them. */ @@ -585,16 +798,24 @@ export function buildUserMessage(input: AiReviewInput, maxFileChars = MAX_DIFF_C /** The user message for one call and a record of each file it carries. A context * card is added only while the call's cards total at most 6,000 characters; a card * that would pass that is skipped and later, smaller ones may still fit. */ -function buildBatchMessage(input: AiReviewInput, maxFileChars: number, coverage: CoverageArg): { message: string; records: AiInputRecord[] } { +function buildBatchMessage( + input: AiReviewInput, + maxFileChars: number, + coverage: CoverageArg, + focus?: { batch: number; others: AiReviewFile[] }, +): { message: string; records: AiInputRecord[] } { const records: AiInputRecord[] = [] const parts: string[] = [] if (input.prTitle) parts.push(`PR title: ${truncate(input.prTitle, 200)}`) if (input.prBody) parts.push(`PR description:\n${truncate(input.prBody, 1500)}`) - if (input.grounding.length) { + // A focused call carries only the grounding for its own files (and file-less findings). + const inCall = new Set(input.files.map((f) => f.path)) + const grounding = focus ? input.grounding.filter((g) => !g.file || inCall.has(g.file)) : input.grounding + if (grounding.length) { parts.push( "\n## GROUNDING — deterministic engine findings (DO NOT repeat these):", - ...input.grounding.slice(0, 40).map((f) => `- [${f.severity}] ${f.category} · ${f.file}: ${f.title}`), + ...grounding.slice(0, 40).map((f) => `- [${f.severity}] ${f.category} · ${f.file}: ${f.title}`), ) } else { parts.push("\n## GROUNDING — the engine produced no findings.") @@ -615,8 +836,15 @@ function buildBatchMessage(input: AiReviewInput, maxFileChars: number, coverage: hunksSent: r.hunksSent, hunksTotal: r.hunksTotal, card: withCard, + ...(focus ? { batch: focus.batch } : {}), }) } + if (focus?.others.length) { + parts.push( + "\n## OTHER FILES CHANGED IN THIS PR (reviewed in separate calls; do not comment on them):", + ...focus.others.slice(0, FOCUS_OTHER_FILES).map((f) => `- ${f.path} (${f.kind ?? "model_sql"})`), + ) + } const context = relatedContext(input) if (context.length) { parts.push( @@ -637,6 +865,8 @@ export interface AiInputPlan { batches: AiReviewFile[][] messages: string[] input: AiInputRecord[] + /** Focused batching applied (`ALTIMATE_REVIEW_AI_FOCUSED=1` and enough files). */ + focused: boolean } /** @@ -654,9 +884,13 @@ export function planAiInput(input: AiReviewInput, env: Record sendable(f) && !chosen.has(f)) } - const batches = files.length ? batchAiFiles(files, budget) : [] - const built = batches.map((b) => buildBatchMessage({ ...input, files: b }, budget.maxFileChars, budget.coverage)) - return { budget, files, unsent, batches, messages: built.map((b) => b.message), input: built.flatMap((b) => b.records) } + const focused = !!budget.focused && files.length >= budget.focused.minFiles + const batches = focused ? packFocusedBatches(groupAiFiles(files), budget) : files.length ? batchAiFiles(files, budget) : [] + const built = batches.map((b, i) => { + const focus = focused ? { batch: i, others: files.filter((f) => !b.includes(f)) } : undefined + return buildBatchMessage({ ...input, files: b }, budget.maxFileChars, budget.coverage, focus) + }) + return { budget, files, unsent, batches, messages: built.map((b) => b.message), input: built.flatMap((b) => b.records), focused } } /** @@ -674,7 +908,7 @@ export async function runAiReview(input: AiReviewInput): Promise const dryRun = aiDryRunEnabled() // Recorded only when an opt-in switch changed or inspects the input, so the default envelope is unchanged. const recorded: Pick = { - ...(budget.coverage || dryRun || plan.input.some((r) => r.card) ? { input: plan.input } : {}), + ...(budget.coverage || dryRun || plan.focused || plan.input.some((r) => r.card) ? { input: plan.input } : {}), ...(budget.coverage && plan.unsent.length ? { unsent: plan.unsent.map((f) => f.path) } : {}), } const done = (findings: Finding[], status: Omit): AiReviewResult => ({ @@ -690,8 +924,10 @@ export async function runAiReview(input: AiReviewInput): Promise try { // Prompt comes from the compiled core, not this file. const promptRes = await Dispatcher.call("altimate_core.review_ai_prompt", {}) - const system = ((promptRes.data ?? {}) as Record).prompt as string | undefined - if (!system) return done([], { state: "error", reason: "the core reviewer prompt is unavailable" }) + const corePrompt = ((promptRes.data ?? {}) as Record).prompt as string | undefined + if (!corePrompt) return done([], { state: "error", reason: "the core reviewer prompt is unavailable" }) + const testGap = aiTestGapEnabled() + const system = testGap ? corePrompt + TEST_GAP_INSTRUCTION : corePrompt let model: Awaited> try { @@ -713,9 +949,10 @@ export async function runAiReview(input: AiReviewInput): Promise const results: BatchResult[] = [] for (let i = 0; i < batches.length; i += BATCH_CONCURRENCY) { const slice = batches.slice(i, i + BATCH_CONCURRENCY) - results.push(...(await Promise.all(slice.map((b, j) => reviewBatch(plan.messages[i + j], b, system, model))))) + results.push(...(await Promise.all(slice.map((b, j) => reviewBatch(testGap ? testGapFileList(plan.messages[i + j], listedFiles(plan, b), input.prFiles) : plan.messages[i + j], b, system, model))))) } let findings = results.flatMap((r) => r.findings) + if (plan.focused) findings = dedupAiFindings(findings) const failed = results.filter((r) => r.state !== "ok") log.info("ai review complete", { findings: findings.length, batches: batches.length, failed: failed.length }) // The lane is ok when any call answered; a partial failure is reported, not hidden. diff --git a/packages/opencode/src/altimate/review/ai-verify.ts b/packages/opencode/src/altimate/review/ai-verify.ts index 20a8be9b4c..164fc6d8dd 100644 --- a/packages/opencode/src/altimate/review/ai-verify.ts +++ b/packages/opencode/src/altimate/review/ai-verify.ts @@ -19,9 +19,16 @@ import type { Finding } from "./finding" import { type AiReviewFile, type AiTokens, type BatchUsage, addUsage, aiTimeoutMs, streamUsage } from "./ai-review" import { type ReviewRunner, scanDiffLines, walkDiffLines } from "./orchestrate" import { readStreamStep, type StepToolCall } from "../llm/stream-text" +import { isCredentialPath } from "./credentials" const log = Log.create({ service: "ai-verify" }) +// The verifier refuses a file that may hold credentials: by name (its path or, for a rename, its +// old path; a working-tree symlink's target) on both sides of `read_file` and `compiled_sql` and in +// `grep_project` hits; by content (private keys, service-account keys) in `read_file`, `compiled_sql` +// and every file `grep_project` would show. The AI lane never gets such a file, nor one whose diff holds a key. +export { holdsCredentials, isCredentialPath } from "./credentials" + /** What the verifier may read: the PR's files, the engine, and the dbt project. */ export interface AiVerifyEvidence { dialect?: string @@ -41,6 +48,8 @@ export interface AiVerifyEvidence { prBody?: string /** Head-side line numbers each changed file adds (see `addedLinesByFile`). */ addedLines: Map> + /** Every file the PR changes, repo-relative, including tests and CI outside the dbt project. */ + prFiles?: string[] } export type Decision = "keep" | "discard" | "summary" @@ -382,12 +391,27 @@ export function hunkAround(diff: string | undefined, line?: number): string { : text || "(the line is outside the diff)" } +/** Most PR file paths listed in a verifier message. */ +const PR_FILES_MAX = 40 + /** The user message for one batch: the PR title and each candidate with its hunk. Not the whole file, not the grounding. */ export function buildVerifyMessage( prTitle: string | undefined, candidates: Array<{ id: string; finding: Finding; diff?: string }>, + prFiles: string[] = [], ): string { - const parts = [`PR: ${(prTitle ?? "(untitled)").slice(0, 200)}`, "", "Candidates:"] + const parts = [`PR: ${(prTitle ?? "(untitled)").slice(0, 200)}`] + // A test-coverage claim is checked against the PR's own test files, which may sit outside the dbt project. + if (prFiles.length && candidates.some((c) => c.finding.category === "test_coverage")) { + const shown = prFiles.slice(0, PR_FILES_MAX) + parts.push( + "", + "Files this PR changes (read_file can open any of them):", + ...shown.map((p) => `- ${p}`), + ...(prFiles.length > shown.length ? [`- … and ${prFiles.length - shown.length} more`] : []), + ) + } + parts.push("", "Candidates:") for (const { id, finding: f, diff } of candidates) { parts.push( "", @@ -784,8 +808,9 @@ export function verifierTools( ...ev.addedLines.keys(), ...graph.parents.map((p) => p.path), ...graph.downstream.map((d) => d.path), + ...(ev.prFiles ?? []), ]), - ] + ].filter((p) => !isCredentialPath(p)) /** A requested path inside the review scope, as the repo-relative path to read; a project-relative path resolves too. */ const resolve = (p: unknown): string | undefined => { const want = String(p ?? "").replace(/^\.?\/+/, "") @@ -799,11 +824,11 @@ export function verifierTools( graph.parents.find((p) => p.name === name && (p.kind === "model" || p.kind === "snapshot"))?.path ?? graph.downstream.find((d) => d.name === name)?.path const side = z.enum(["old", "new"]).optional().describe("old=base, new=head (default)") - const scope = NA("outside review scope (changed files, their dbt parents and direct downstream models only)") + const scope = NA("outside review scope (files the PR changes, their dbt parents and direct downstream models only)") return { read_file: { - description: "Up to 200 numbered lines of a changed file, its dbt parents or direct children.", + description: "Up to 200 numbered lines of any file the PR changes (tests and CI included), a dbt parent or direct child.", input: z.object({ path: z.string(), side, @@ -920,8 +945,9 @@ export function verifierTools( async run({ pattern, glob }) { if (!ev.grepProject) return NA("project search unavailable") if (String(pattern).length < 2) return NA("pattern needs at least 2 characters") - const hits = await ev.grepProject(String(pattern), glob as string | undefined) - if (!hits) return NA("the search failed (git error, timeout, or a glob outside the project); this is not evidence of absence") + const found = await ev.grepProject(String(pattern), glob as string | undefined) + if (!found) return NA("the search failed (git error, timeout, or a glob outside the project); this is not evidence of absence") + const hits = found.filter((h) => !isCredentialPath(h.path)) return hits.length ? hits.map((h) => `${h.path}:${h.line}: ${h.text}`).join("\n") : "no matches" }, }, @@ -1176,6 +1202,7 @@ export async function runAiVerify( finding: input.findings[i], diff: fileByPath.get(input.findings[i].file)?.diff, })), + ev.prFiles, ) return { idx, ids, message } }) diff --git a/packages/opencode/src/altimate/review/credentials.ts b/packages/opencode/src/altimate/review/credentials.ts new file mode 100644 index 0000000000..b437f8d5d2 --- /dev/null +++ b/packages/opencode/src/altimate/review/credentials.ts @@ -0,0 +1,44 @@ +// Connection profiles, env files, package-registry, git, cloud, Docker and Kubernetes credential +// stores, service-account and OAuth client keys, key material and Terraform variables. Matched on the file name. +const CREDENTIAL_FILE = new RegExp( + "(^|/)(" + + [ + // profiles.yml, dbt_profiles.yml, profiles-ci.yml, profiles.yml.example; not a model's + // schema file such as customer_profiles.yml + "(dbt[_-]?)?profiles([._-][^/]*)?\\.ya?ml(\\.[^/]*)?", + "\\.env[^/]*", // .env, .env.local, .env-prod, .envrc + "[^/]+\\.env", // prod.env + "\\.netrc", + "\\.pgpass", + "\\.npmrc", + "\\.pypirc", + "\\.git-credentials", + "id_(rsa|dsa|ecdsa|ed25519)", + "keyfile[^/]*\\.json", + "[^/]*service[^/]*account[^/]*\\.json", + "credentials[^/]*\\.json", + "\\.aws/credentials", + "\\.docker/config\\.json", + "kubeconfig", + "secrets?\\.(ya?ml|json)", + "client_secret[^/]*\\.json", + "[^/]+\\.(pem|key|p12|pfx|p8|tfvars|tfvars\\.json)", + ].join("|") + + ")$", + "i", +) + +/** + * A path whose name says it may hold credentials. A changed file named so, now or before a + * rename, is not sent to the AI lane, and the verifier neither reads it (either side) nor shows its grep hits. + */ +export function isCredentialPath(path: string): boolean { + return CREDENTIAL_FILE.test(path) +} + +const CREDENTIAL_CONTENT = /-----BEGIN (?:[A-Z0-9 ]* )?PRIVATE KEY(?: BLOCK)?-----|"type"\s*:\s*"service_account"/ + +/** Text that carries a private key (PEM, OpenSSH or PGP armor) or a cloud service-account key, whatever the file is called. */ +export function holdsCredentials(text: string): boolean { + return CREDENTIAL_CONTENT.test(text) +} diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index 619de7fc25..026836049d 100644 --- a/packages/opencode/src/altimate/review/dbt-patterns.ts +++ b/packages/opencode/src/altimate/review/dbt-patterns.ts @@ -991,7 +991,9 @@ export function redundantJoinPredicates(sql: string): string[] { } else if (rel) i += rel[0].length const tail = /^\s+(?:as\s+)?(\w+)\s+on\b/i.exec(s.slice(i)) ?? /^\s+on\b/i.exec(s.slice(i)) if (!tail) { - joins.push({ preds: [], start: m.index!, end: i, inner, outer }) + // A join with no ON (`cross join params as p`): step over its alias so the chain continues. + const bare = /^\s+(?:as\s+)?(?!(?:natural|inner|left|right|full|cross|outer|join|lateral|on|using|where|group|order|qualify|having|union|limit|window|select|from)\b)\w+\b/i.exec(s.slice(i)) + joins.push({ preds: [], start: m.index!, end: i + (bare?.[0].length ?? 0), inner, outer }) continue } const fallback = rel?.[1].split(".").pop()?.toLowerCase() diff --git a/packages/opencode/src/altimate/review/diff-filter.ts b/packages/opencode/src/altimate/review/diff-filter.ts index ee5673caa5..4323a98104 100644 --- a/packages/opencode/src/altimate/review/diff-filter.ts +++ b/packages/opencode/src/altimate/review/diff-filter.ts @@ -254,6 +254,14 @@ export function partitionChangedFiles( return { reviewable, dropped } } +/** True when a path is build output / vendored or matches one of the user's exclude globs: + * files the review must not read, even outside the reviewable set. */ +export function isExcludedPath(path: string, extraExcludeGlobs: string[] = []): boolean { + const p = norm(path) + if (SKIP_DIR_PATTERNS.some((re) => re.test(p)) || SKIP_FILE_PATTERNS.some((re) => re.test(p))) return true + return extraExcludeGlobs.some((g) => globToRegExp(g).test(p)) +} + /** Filter changed files down to the reviewable set, with their dbt kind. */ export function filterChangedFiles( files: ChangedFile[], diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index 01b5d292b3..d1b43c63d5 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -3,6 +3,7 @@ import { promisify } from "node:util" import { promises as fs } from "node:fs" import path from "node:path" import type { ChangedFile } from "./diff-filter" +import { isCredentialPath } from "./credentials" /** * Git helpers for the review pipeline. Produces the ChangedFile[] for a PR @@ -95,7 +96,8 @@ export async function collectChangedFiles(opts: CollectOptions): Promise ../profiles.yml`) + // must not reach a credential file the requested name doesn't show. + if (isCredentialPath(path.relative(rootReal, targetReal).split(sep).join("/"))) return undefined return await fs.readFile(targetReal, "utf8") } catch { return undefined @@ -220,7 +225,9 @@ export async function grepFixedAt( // No pathspec would search the whole repository. if (!pathspecs.length) return undefined const maxHits = opts.maxHits ?? 50 - const args = ["grep", "-n", "-I", "-F", "--full-name", "-m", String(maxHits), "-e", pattern, ...(ref ? [ref] : []), "--"] + // -z: NUL after the path and line number, and paths unquoted (git otherwise + // C-quotes non-ASCII names, `"models/caf\303\251/x.yml"`), so callers see canonical paths. + const args = ["grep", "-z", "-n", "-I", "-F", "--full-name", "-m", String(maxHits), "-e", pattern, ...(ref ? [ref] : []), "--"] args.push(...pathspecs.map((p) => `:(top)${p}`)) let out: string let failed = false @@ -235,7 +242,7 @@ export async function grepFixedAt( const hits: Array<{ path: string; line: number; text: string }> = [] for (const row of out.split("\n")) { const rest = ref && row.startsWith(ref + ":") ? row.slice(ref.length + 1) : row - const m = /^(.+?):(\d+):(.*)$/.exec(rest) + const m = /^([^\0]+)\0(\d+)\0(.*)$/.exec(rest) if (!m) continue hits.push({ path: m[1], line: Number(m[2]), text: m[3].slice(0, 300) }) if (hits.length >= maxHits) break diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index d3cedad9fc..06198e8bc7 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -18,6 +18,7 @@ import { type NotReviewed, partitionChangedFiles, hasOldSide, + isExcludedPath, walkDiffLines, walkDiffRows, } from "./diff-filter" @@ -63,11 +64,10 @@ import { type AiContextFile, type AiLaneStatus, type AiReviewFile, type AiReview import { type MacroCard, type ModelCard, attachContextCards } from "./ai-context-card" import { ruleTier } from "./rule-tiers" 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"]) -// Connection profiles hold warehouse credentials: never send their diff or content to the AI lane. -const AI_CREDENTIAL_FILE = /(^|\/)profiles\.ya?ml$/i /** * The deterministic review recipe. @@ -290,6 +290,10 @@ export interface OrchestrateInput { aiVerify?: boolean /** 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 @@ -303,6 +307,8 @@ export interface OrchestrateInput { 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). */ @@ -2379,6 +2385,9 @@ export async function runReview(input: OrchestrateInput): Promise>() + // 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*-?%\\}`) @@ -2386,13 +2395,21 @@ export async function runReview(input: OrchestrateInput): Promise hits === undefined || hits.some((h) => block.test(h.text))) + .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!])) @@ -2411,7 +2428,7 @@ export async function runReview(input: OrchestrateInput): Promise ({ - 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, - })) + // 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" && !AI_CREDENTIAL_FILE.test(f.path), + (f) => AI_SUPPORTING_KINDS.has(f.kind) && f.status !== "deleted" && !mayHoldCredentials(f.path), ) const contents = await Promise.all( - supporting.map((f) => (f.kind === "seed" ? undefined : getContent?.(f.path, "new")?.catch(() => undefined))), + supporting.map((f) => + f.kind === "seed" + ? undefined + : getContent?.(f.path, "new")?.catch(() => undefined), + ), ) supporting.forEach((f, i) => - aiFiles.push({ path: f.path, status: f.status, model: modelNameFromPath(f.path), kind: f.kind, diff: f.diff, sql: contents[i] }), + aiFiles.push( + ...screened({ path: f.path, status: f.status, model: modelNameFromPath(f.path), kind: f.kind, diff: f.diff, sql: contents[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. @@ -2642,6 +2684,31 @@ export async function runReview(input: OrchestrateInput): Promise 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 ? { @@ -2649,15 +2716,22 @@ export async function runReview(input: OrchestrateInput): Promise !mayHoldCredentials(f.path))), prTitle: input.prTitle, prBody: input.prBody, - grepProject: input.grepProject, - readFile: async (p, side, start, end) => numberedSlice(await getContent?.(p, side), start, end), + grepProject, + prFiles, + 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 - return engine ?? (await getCompiled?.(ctx?.file.oldPath && side === "old" ? ctx.file.oldPath : p, side)) + const sql = engine ?? (await getCompiled?.(pathActuallyRead(p, side), side)) + return sql && holdsCredentials(sql) ? undefined : sql }, } : undefined @@ -2669,6 +2743,7 @@ export async function runReview(input: OrchestrateInput): Promise r.kind === "+") + const errLine = err.line + const at = + errLine === undefined + ? added[0] + : (added.find((r) => r.line === errLine) ?? + [...added].reverse().find((r) => r.line < errLine) ?? + rows.find((r) => r.kind === " " && r.line === errLine)) + const text = at?.text ?? (errLine ? newContent.split("\n")[errLine - 1] : undefined) const f = finding( file, "yaml-parse-error", @@ -414,7 +426,7 @@ export function yamlParseFindings(file: ChangedFile, oldContent: string | undefi : `${err.message}${err.line ? ` (line ${err.line})` : ""}. The file parsed before this change; tools that read it now fail.`, text, ) - return [err.line ? { ...f, startLine: err.line, endLine: err.line } : f] + return [at ? { ...f, startLine: at.line, endLine: at.line } : f] } /** New models named like the public models a `.quickstart/quickstart.yml` lists, but missing from @@ -489,14 +501,17 @@ export function packageLockFindings(file: ChangedFile, isPackage: boolean): Find const DOC_REF = /\bdoc\s*\(\s*['"](\w+)['"]\s*\)/g -/** `doc('x')` names this change adds to a yml file that no docs block in the project defines: - * dbt fails to parse the project. Only when another `doc()` in the file resolves in the project, - * so docs kept in an installed package aren't mistaken for missing ones. */ +/** `doc('x')` names this change adds to a yml file that no docs block in the project or its + * installed packages defines: dbt fails to parse the project. Only when another `doc()` in the + * file resolves, or, when the file has no other `doc()`, the project keeps its own docs blocks + * (`projectHasDocs` also requires the packages' blocks to be known); so docs kept in an + * uninstalled package aren't mistaken for missing ones. */ export async function docRefFindings( file: ChangedFile, oldContent: string | undefined, newContent: string | undefined, docExists: (name: string) => Promise, + projectHasDocs?: () => Promise, ): Promise { if (!newContent || file.status === "deleted") return [] const before = new Set([...(oldContent ?? "").matchAll(DOC_REF)].map((m) => m[1])) @@ -509,6 +524,7 @@ export async function docRefFindings( const others = [...new Set([...newContent.matchAll(DOC_REF)].map((m) => m[1]))].filter((n) => !missing.includes(n)).slice(0, 5) let resolves = false for (const n of others) if ((resolves = await docExists(n))) break + if (!others.length && projectHasDocs) resolves = await projectHasDocs() if (!resolves) return [] return missing.map((name) => finding( @@ -517,7 +533,7 @@ export async function docRefFindings( "warning", "sql_correctness", `\`doc('${name}')\` has no docs block`, - `No \`{% docs ${name} %}\` block exists in the project's \`.md\` files, while the other \`doc()\` references in this file resolve there. dbt fails to parse the project on a \`doc()\` it can't resolve. Add the docs block, or fix the name.`, + `No \`{% docs ${name} %}\` block exists in the project's \`.md\` files or its installed packages, while ${others.length ? "the other \`doc()\` references in this file resolve" : "the project defines its own docs blocks"}. dbt fails to parse the project on a \`doc()\` it can't resolve. Add the docs block, or fix the name.`, lines.get(name), ), ) diff --git a/packages/opencode/src/altimate/review/rubric.ts b/packages/opencode/src/altimate/review/rubric.ts index 158b9ee728..b86cb8b073 100644 --- a/packages/opencode/src/altimate/review/rubric.ts +++ b/packages/opencode/src/altimate/review/rubric.ts @@ -70,6 +70,9 @@ export function blockingCategories(rubric: Rubric): Set { return new Set(rubric.blockOn) } +/** Findings that break `dbt parse` for the whole project, so a dev/sandbox/scratch folder doesn't excuse them. */ +const PROJECT_BREAKING_RULES = new Set(["dbt-project-rules:yaml-parse-error", "dbt-project-rules:doc-block-missing"]) + /** * Apply the rubric's exclusion predicates. Returns the reason a finding should * be dropped, or null to keep it. Centralizing this here (vs prompt text) is @@ -80,7 +83,7 @@ export function exclusionReason(finding: Finding, rubric: Rubric): string | null const isStaging = /(^|\/)stg_|(^|\/)staging\//.test(finding.file) || finding.model?.startsWith("stg_") const isDev = /(^|\/)(dev|sandbox|scratch)\//.test(finding.file) - if (ex.skipNonProdModels && isDev) return "non-prod model (dev/sandbox/scratch)" + if (ex.skipNonProdModels && isDev && !PROJECT_BREAKING_RULES.has(finding.rule ?? "")) return "non-prod model (dev/sandbox/scratch)" if ( ex.allowSelectStarInStaging && diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 0012f700bc..ff7bd0527e 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -876,9 +876,10 @@ const CORRECTNESS: Rule[] = [ { // A literal holding SQL (it has whitespace) that ends, or starts, with a word character right at the `~`, // inside an open `{{`/`{%` on the line (a bare `col ~ 'a b'` is a Postgres regex match, not Jinja). + // Single- or double-quoted; an escape (`\n`) at the seam is not a word. added: // The whitespace check is a lookahead so the literal is scanned once (no split backtracking on long lines). - /\{[{%](?:(?![}%]\}).)*?(?:'(?=[^'\n]*\s)[^'\n]*[A-Za-z0-9]'\s*~\s*[A-Za-z_][\w.]*|[\w)]\s*~\s*'[A-Za-z0-9](?=[^'\n]*\s)[^'\n]*')/, + /\{[{%](?:(?![}%]\}).)*?(?:'(?=[^'\n]*\s)[^'\n]*(? f.status === "renamed" && f.oldPath).map((f) => [f.path, f.oldPath as string]), + // from where the file lived at `base`: in-scope files as scoped (a rename into + // the project is scoped as added), files outside the project as collected. + const prRenames = new Map( + collected.filter((f) => f.status === "renamed" && f.oldPath).map((f) => [f.path, f.oldPath as string]), ) + const inScopePaths = new Set(changedFiles.map((f) => f.path)) + const renames = new Map([...prRenames].filter(([p]) => !inScopePaths.has(p))) + for (const f of changedFiles) if (f.status === "renamed" && f.oldPath) renames.set(f.path, f.oldPath) const getContent = opts.getContent ?? makeContentResolver({ base, head: opts.head, cwd: opts.cwd, renames, gitRoot }) @@ -434,6 +438,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise return runReview({ resourceNames: () => projectResourceNames(opts.cwd, opts.head, projectRootRel, dbtRoot), + packageDocNames: () => packageDocNames(opts.cwd, opts.head, projectRootRel, dbtRoot), changedFiles, config, rubric, @@ -465,6 +470,8 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise const specs = projectGrepSpecs(projectRootRel, dirs, glob) return specs ? grepFixedAt(gitRoot, opts.head, pattern, specs) : Promise.resolve(undefined) }, + prFiles: collected.map((f) => f.path), + prRenames, prTitle: opts.prTitle, prBody: opts.prBody, explainTier: opts.explainTier, @@ -612,6 +619,41 @@ export async function projectAdapters( return [...seen].sort() } +/** + * `{% docs name %}` blocks defined in the `.md` files of installed packages (`dbt_packages/`). Empty when the + * project declares no packages; undefined when that can't be known (no project root, git can't + * list the tree, or packages are declared but not installed). + */ +export async function packageDocNames( + cwd: string, + head: string | undefined, + projectRootRel: string | undefined, + dbtRoot: string, +): Promise | undefined> { + if (projectRootRel === undefined) return undefined + const files = await listFilesAt(cwd, head) + if (!files) return undefined + const prefix = projectRootRel ? projectRootRel + "/" : "" + const names = new Set() + if (!files.includes(prefix + "packages.yml") && !files.includes(prefix + "dependencies.yml")) return names + const walk = async (dir: string, depth: number): Promise => { + let entries + try { + entries = await readdir(dir, { withFileTypes: true }) + } catch { + return false + } + for (const e of entries) { + const p = path.join(dir, e.name) + if (e.isDirectory() && depth < 12 && e.name !== ".git") await walk(p, depth + 1) + else if (e.isFile() && e.name.endsWith(".md")) + for (const m of (await readFile(p, "utf8").catch(() => "")).matchAll(/\{%-?\s*docs\s+(\w+)\s*-?%\}/g)) names.add(m[1]) + } + return true + } + return (await walk(path.join(dbtRoot, "dbt_packages"), 0)) ? names : undefined +} + /** * Names `ref()` can resolve to: model/seed/snapshot files in the repo at head, snapshots * defined in YAML, and diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index c52f6e6393..3f8f66074d 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -248,6 +248,8 @@ export const VerdictEnvelope = z.object({ hunksSent: z.number().int().nonnegative(), hunksTotal: z.number().int().nonnegative(), card: z.boolean(), + /** Index of the call that carried the file (focused batching only). */ + batch: z.number().int().nonnegative().optional(), }), ) .optional(), diff --git a/packages/opencode/test/altimate/fixtures/review-ai-prompt-coverage.txt b/packages/opencode/test/altimate/fixtures/review-ai-prompt-coverage.txt new file mode 100644 index 0000000000..3b32e09fc1 --- /dev/null +++ b/packages/opencode/test/altimate/fixtures/review-ai-prompt-coverage.txt @@ -0,0 +1,568 @@ +PR title: Rework revenue marts +PR description: +Moves cents conversion into a macro. + +Also adds tests. + +## GROUNDING — deterministic engine findings (DO NOT repeat these): +- [warning] warehouse_cost · models/marts/fct_big.sql: SELECT * in a mart + +## CHANGED FILES (review for what the engine missed): + +### models/marts/fct_big.sql (modified) +Diff: +```diff +@@ -10,22 +10,24 @@ + select 0 as ctx_before ++ , coalesce(col_0_0, 'unknown_value_0') as renamed_column_0_0 ++ , coalesce(col_0_1, 'unknown_value_1') as renamed_column_0_1 ++ , coalesce(col_0_2, 'unknown_value_2') as renamed_column_0_2 ++ , coalesce(col_0_3, 'unknown_value_3') as renamed_column_0_3 ++ , coalesce(col_0_4, 'unknown_value_4') as renamed_column_0_4 ++ , coalesce(col_0_5, 'unknown_value_5') as renamed_column_0_5 ++ , coalesce(col_0_6, 'unknown_value_6') as renamed_column_0_6 ++ , coalesce(col_0_7, 'unknown_value_7') as renamed_column_0_7 ++ , coalesce(col_0_8, 'unknown_value_8') as renamed_column_0_8 ++ , coalesce(col_0_9, 'unknown_value_9') as renamed_column_0_9 ++ , coalesce(col_0_10, 'unknown_value_10') as renamed_column_0_10 ++ , coalesce(col_0_11, 'unknown_value_11') as renamed_column_0_11 ++ , coalesce(col_0_12, 'unknown_value_12') as renamed_column_0_12 ++ , coalesce(col_0_13, 'unknown_value_13') as renamed_column_0_13 ++ , coalesce(col_0_14, 'unknown_value_14') as renamed_column_0_14 ++ , coalesce(col_0_15, 'unknown_value_15') as renamed_column_0_15 ++ , coalesce(col_0_16, 'unknown_value_16') as renamed_column_0_16 ++ , coalesce(col_0_17, 'unknown_value_17') as renamed_column_0_17 ++ , coalesce(col_0_18, 'unknown_value_18') as renamed_column_0_18 ++ , coalesce(col_0_19, 'unknown_value_19') as renamed_column_0_19 +- , old_col_0 + from {{ ref('stg_0') }} +@@ -110,22 +110,24 @@ + select 1 as ctx_before ++ , coalesce(col_1_0, 'unknown_value_0') as renamed_column_1_0 ++ , coalesce(col_1_1, 'unknown_value_1') as renamed_column_1_1 ++ , coalesce(col_1_2, 'unknown_value_2') as renamed_column_1_2 ++ , coalesce(col_1_3, 'unknown_value_3') as renamed_column_1_3 ++ , coalesce(col_1_4, 'unknown_value_4') as renamed_column_1_4 ++ , coalesce(col_1_5, 'unknown_value_5') as renamed_column_1_5 ++ , coalesce(col_1_6, 'unknown_value_6') as renamed_column_1_6 ++ , coalesce(col_1_7, 'unknown_value_7') as renamed_column_1_7 ++ , coalesce(col_1_8, 'unknown_value_8') as renamed_column_1_8 ++ , coalesce(col_1_9, 'unknown_value_9') as renamed_column_1_9 ++ , coalesce(col_1_10, 'unknown_value_10') as renamed_column_1_10 ++ , coalesce(col_1_11, 'unknown_value_11') as renamed_column_1_11 ++ , coalesce(col_1_12, 'unknown_value_12') as renamed_column_1_12 ++ , coalesce(col_1_13, 'unknown_value_13') as renamed_column_1_13 ++ , coalesce(col_1_14, 'unknown_value_14') as renamed_column_1_14 ++ , coalesce(col_1_15, 'unknown_value_15') as renamed_column_1_15 ++ , coalesce(col_1_16, 'unknown_value_16') as renamed_column_1_16 ++ , coalesce(col_1_17, 'unknown_value_17') as renamed_column_1_17 ++ , coalesce(col_1_18, 'unknown_value_18') as renamed_column_1_18 ++ , coalesce(col_1_19, 'unknown_value_19') as renamed_column_1_19 +- , old_col_1 + from {{ ref('stg_1') }} +@@ -210,22 +210,24 @@ + select 2 as ctx_before ++ , coalesce(col_2_0, 'unknown_value_0') as renamed_column_2_0 ++ , coalesce(col_2_1, 'unknown_value_1') as renamed_column_2_1 ++ , coalesce(col_2_2, 'unknown_value_2') as renamed_column_2_2 ++ , coalesce(col_2_3, 'unknown_value_3') as renamed_column_2_3 ++ , coalesce(col_2_4, 'unknown_value_4') as renamed_column_2_4 ++ , coalesce(col_2_5, 'unknown_value_5') as renamed_column_2_5 ++ , coalesce(col_2_6, 'unknown_value_6') as renamed_column_2_6 ++ , coalesce(col_2_7, 'unknown_value_7') as renamed_column_2_7 ++ , coalesce(col_2_8, 'unknown_value_8') as renamed_column_2_8 ++ , coalesce(col_2_9, 'unknown_value_9') as renamed_column_2_9 ++ , coalesce(col_2_10, 'unknown_value_10') as renamed_column_2_10 ++ , coalesce(col_2_11, 'unknown_value_11') as renamed_column_2_11 ++ , coalesce(col_2_12, 'unknown_value_12') as renamed_column_2_12 ++ , coalesce(col_2_13, 'unknown_value_13') as renamed_column_2_13 ++ , coalesce(col_2_14, 'unknown_value_14') as renamed_column_2_14 ++ , coalesce(col_2_15, 'unknown_value_15') as renamed_column_2_15 ++ , coalesce(col_2_16, 'unknown_value_16') as renamed_column_2_16 ++ , coalesce(col_2_17, 'unknown_value_17') as renamed_column_2_17 ++ , coalesce(col_2_18, 'unknown_value_18') as renamed_column_2_18 ++ , coalesce(col_2_19, 'unknown_value_19') as renamed_column_2_19 +- , old_col_2 + from {{ ref('stg_2') }} +@@ -310,22 +310,24 @@ + select 3 as ctx_before ++ , coalesce(col_3_0, 'unknown_value_0') as renamed_column_3_0 ++ , coalesce(col_3_1, 'unknown_value_1') as renamed_column_3_1 ++ , coalesce(col_3_2, 'unknown_value_2') as renamed_column_3_2 ++ , coalesce(col_3_3, 'unknown_value_3') as renamed_column_3_3 ++ , coalesce(col_3_4, 'unknown_value_4') as renamed_column_3_4 ++ , coalesce(col_3_5, 'unknown_value_5') as renamed_column_3_5 ++ , coalesce(col_3_6, 'unknown_value_6') as renamed_column_3_6 ++ , coalesce(col_3_7, 'unknown_value_7') as renamed_column_3_7 ++ , coalesce(col_3_8, 'unknown_value_8') as renamed_column_3_8 ++ , coalesce(col_3_9, 'unknown_value_9') as renamed_column_3_9 ++ , coalesce(col_3_10, 'unknown_value_10') as renamed_column_3_10 ++ , coalesce(col_3_11, 'unknown_value_11') as renamed_column_3_11 ++ , coalesce(col_3_12, 'unknown_value_12') as renamed_column_3_12 ++ , coalesce(col_3_13, 'unknown_value_13') as renamed_column_3_13 ++ , coalesce(col_3_14, 'unknown_value_14') as renamed_column_3_14 ++ , coalesce(col_3_15, 'unknown_value_15') as renamed_column_3_15 ++ , coalesce(col_3_16, 'unknown_value_16') as renamed_column_3_16 ++ , coalesce(col_3_17, 'unknown_value_17') as renamed_column_3_17 ++ , coalesce(col_3_18, 'unknown_value_18') as renamed_column_3_18 ++ , coalesce(col_3_19, 'unknown_value_19') as renamed_column_3_19 +- , old_col_3 + from {{ ref('stg_3') }} +@@ -410,22 +410,24 @@ + select 4 as ctx_before ++ , coalesce(col_4_0, 'unknown_value_0') as renamed_column_4_0 ++ , coalesce(col_4_1, 'unknown_value_1') as renamed_column_4_1 ++ , coalesce(col_4_2, 'unknown_value_2') as renamed_column_4_2 ++ , coalesce(col_4_3, 'unknown_value_3') as renamed_column_4_3 ++ , coalesce(col_4_4, 'unknown_value_4') as renamed_column_4_4 ++ , coalesce(col_4_5, 'unknown_value_5') as renamed_column_4_5 ++ , coalesce(col_4_6, 'unknown_value_6') as renamed_column_4_6 ++ , coalesce(col_4_7, 'unknown_value_7') as renamed_column_4_7 ++ , coalesce(col_4_8, 'unknown_value_8') as renamed_column_4_8 ++ , coalesce(col_4_9, 'unknown_value_9') as renamed_column_4_9 ++ , coalesce(col_4_10, 'unknown_value_10') as renamed_column_4_10 ++ , coalesce(col_4_11, 'unknown_value_11') as renamed_column_4_11 ++ , coalesce(col_4_12, 'unknown_value_12') as renamed_column_4_12 ++ , coalesce(col_4_13, 'unknown_value_13') as renamed_column_4_13 ++ , coalesce(col_4_14, 'unknown_value_14') as renamed_column_4_14 ++ , coalesce(col_4_15, 'unknown_value_15') as renamed_column_4_15 ++ , coalesce(col_4_16, 'unknown_value_16') as renamed_column_4_16 ++ , coalesce(col_4_17, 'unknown_value_17') as renamed_column_4_17 ++ , coalesce(col_4_18, 'unknown_value_18') as renamed_column_4_18 ++ , coalesce(col_4_19, 'unknown_value_19') as renamed_column_4_19 +- , old_col_4 + from {{ ref('stg_4') }} +``` +Current SQL: +```sql + , cast(field_0 as varchar) as field_0_text -- line 1 + , cast(field_1 as varchar) as field_1_text -- line 2 + , cast(field_2 as varchar) as field_2_text -- line 3 + , cast(field_3 as varchar) as field_3_text -- line 4 + , cast(field_4 as varchar) as field_4_text -- line 5 + , cast(field_5 as varchar) as field_5_text -- line 6 + , cast(field_6 as varchar) as field_6_text -- line 7 + , cast(field_7 as varchar) as field_7_text -- line 8 + , cast(field_8 as varchar) as field_8_text -- line 9 + , cast(field_9 as varchar) as field_9_text -- line 10 + , cast(field_10 as varchar) as field_10_text -- line 11 + , cast(field_11 as varchar) as field_11_text -- line 12 + , cast(field_12 as varchar) as field_12_text -- line 13 + , cast(field_13 as varchar) as field_13_text -- line 14 + , cast(field_14 as varchar) as field_14_text -- line 15 + , cast(field_15 as varchar) as field_15_text -- line 16 + , cast(field_16 as varchar) as field_16_text -- line 17 + , cast(field_17 as varchar) as field_17_text -- line 18 + , cast(field_18 as varchar) as field_18_text -- line 19 + , cast(field_19 as varchar) as field_19_text -- line 20 + , cast(field_20 as varchar) as field_20_text -- line 21 + , cast(field_21 as varchar) as field_21_text -- line 22 + , cast(field_22 as varchar) as field_22_text -- line 23 + , cast(field_23 as varchar) as field_23_text -- line 24 + , cast(field_24 as varchar) as field_24_text -- line 25 + , cast(field_25 as varchar) as field_25_text -- line 26 + , cast(field_26 as varchar) as field_26_text -- line 27 + , cast(field_27 as varchar) as field_27_text -- line 28 + , cast(field_28 as varchar) as field_28_text -- line 29 + , cast(field_29 as varchar) as field_29_text -- line 30 + , cast(field_30 as varchar) as field_30_text -- line 31 + , cast(field_31 as varchar) as field_31_text -- line 32 + , cast(field_32 as varchar) as field_32_text -- line 33 + , cast(field_33 as varchar) as field_33_text -- line 34 + , cast(field_34 as varchar) as field_34_text -- line 35 +… (truncated) +``` + +### models/staging/stg_0.sql (modified) +Diff: +```diff +@@ -1,2 +1,2 @@ + select +- a_0 ++ b_0 + +``` +Current SQL: +```sql +select b_0 from {{ source('raw', 't0') }} +``` + +### snapshots/snap.sql (modified, snapshot) +Diff: +```diff ++ unique_key='id', + +``` +Current file: +```sql +{% snapshot snap %}select 1{% endsnapshot %} +``` + +### models/py/pm.py (added, Python model) +Diff: +```diff ++def model(dbt, session): + +``` +Current file: +```python +def model(dbt, session): + return dbt.ref('fct') + +``` + +### macros/to_cents.sql (modified, macro (Jinja; changes every model that calls it)) +Diff: +```diff +-round({{ c }}) ++round({{ c }} * 100) + +``` +Current file: +```sql +{% macro to_cents(c) %}round({{ c }} * 100){% endmacro %} +``` + +### tests/assert_positive.sql (added, singular data test) +Diff: +```diff ++select * from {{ ref('fct') }} where id < 0 + +``` +Current file: +```sql +select * from {{ ref('fct') }} where id < 0 +``` + +### models/marts/_marts.yml (modified, schema yml (tests, contracts, descriptions)) +Diff: +```diff ++ - name: id ++ tests: [unique] + +``` +Current file: +```yaml +models: + - name: fct + +``` + +### seeds/codes.csv (modified, seed CSV) +Diff: +```diff ++US,United States + +``` + +### dbt_project.yml (modified, project config) +Diff: +```diff ++ +materialized: table + +``` +Current file: +```yaml +name: shop + +``` + +## RELATED FILES — unchanged dbt parents of the changed files (context only; comment on the changed files, not these): + +### models/staging/stg_orders.sql (model `stg_orders`, used by models/marts/fct_big.sql) +```sql +select id, amount from raw.orders +``` + +Return ONLY the JSON array per the output contract. +=====BATCH===== +PR title: Rework revenue marts +PR description: +Moves cents conversion into a macro. + +Also adds tests. + +## GROUNDING — deterministic engine findings (DO NOT repeat these): +- [warning] warehouse_cost · models/marts/fct_big.sql: SELECT * in a mart + +## CHANGED FILES (review for what the engine missed): + +### models/marts/fct_big.sql (modified) +Diff: +```diff +@@ -10,22 +10,24 @@ + select 0 as ctx_before ++ , coalesce(col_0_0, 'unknown_value_0') as renamed_column_0_0 ++ , coalesce(col_0_1, 'unknown_value_1') as renamed_column_0_1 ++ , coalesce(col_0_2, 'unknown_value_2') as renamed_column_0_2 ++ , coalesce(col_0_3, 'unknown_value_3') as renamed_column_0_3 ++ , coalesce(col_0_4, 'unknown_value_4') as renamed_column_0_4 ++ , coalesce(col_0_5, 'unknown_value_5') as renamed_column_0_5 ++ , coalesce(col_0_6, 'unknown_value_6') as renamed_column_0_6 ++ , coalesce(col_0_7, 'unknown_value_7') as renamed_column_0_7 ++ , coalesce(col_0_8, 'unknown_value_8') as renamed_column_0_8 ++ , coalesce(col_0_9, 'unknown_value_9') as renamed_column_0_9 ++ , coalesce(col_0_10, 'unknown_value_10') as renamed_column_0_10 ++ , coalesce(col_0_11, 'unknown_value_11') as renamed_column_0_11 ++ , coalesce(col_0_12, 'unknown_value_12') as renamed_column_0_12 ++ , coalesce(col_0_13, 'unknown_value_13') as renamed_column_0_13 ++ , coalesce(col_0_14, 'unknown_value_14') as renamed_column_0_14 ++ , coalesce(col_0_15, 'unknown_value_15') as renamed_column_0_15 ++ , coalesce(col_0_16, 'unknown_value_16') as renamed_column_0_16 ++ , coalesce(col_0_17, 'unknown_value_17') as renamed_column_0_17 ++ , coalesce(col_0_18, 'unknown_value_18') as renamed_column_0_18 ++ , coalesce(col_0_19, 'unknown_value_19') as renamed_column_0_19 +- , old_col_0 + from {{ ref('stg_0') }} +@@ -110,22 +110,24 @@ + select 1 as ctx_before ++ , coalesce(col_1_0, 'unknown_value_0') as renamed_column_1_0 ++ , coalesce(col_1_1, 'unknown_value_1') as renamed_column_1_1 ++ , coalesce(col_1_2, 'unknown_value_2') as renamed_column_1_2 ++ , coalesce(col_1_3, 'unknown_value_3') as renamed_column_1_3 ++ , coalesce(col_1_4, 'unknown_value_4') as renamed_column_1_4 ++ , coalesce(col_1_5, 'unknown_value_5') as renamed_column_1_5 ++ , coalesce(col_1_6, 'unknown_value_6') as renamed_column_1_6 ++ , coalesce(col_1_7, 'unknown_value_7') as renamed_column_1_7 ++ , coalesce(col_1_8, 'unknown_value_8') as renamed_column_1_8 ++ , coalesce(col_1_9, 'unknown_value_9') as renamed_column_1_9 ++ , coalesce(col_1_10, 'unknown_value_10') as renamed_column_1_10 ++ , coalesce(col_1_11, 'unknown_value_11') as renamed_column_1_11 ++ , coalesce(col_1_12, 'unknown_value_12') as renamed_column_1_12 ++ , coalesce(col_1_13, 'unknown_value_13') as renamed_column_1_13 ++ , coalesce(col_1_14, 'unknown_value_14') as renamed_column_1_14 ++ , coalesce(col_1_15, 'unknown_value_15') as renamed_column_1_15 ++ , coalesce(col_1_16, 'unknown_value_16') as renamed_column_1_16 ++ , coalesce(col_1_17, 'unknown_value_17') as renamed_column_1_17 ++ , coalesce(col_1_18, 'unknown_value_18') as renamed_column_1_18 ++ , coalesce(col_1_19, 'unknown_value_19') as renamed_column_1_19 +- , old_col_1 + from {{ ref('stg_1') }} +@@ -210,22 +210,24 @@ + select 2 as ctx_before ++ , coalesce(col_2_0, 'unknown_value_0') as renamed_column_2_0 ++ , coalesce(col_2_1, 'unknown_value_1') as renamed_column_2_1 ++ , coalesce(col_2_2, 'unknown_value_2') as renamed_column_2_2 ++ , coalesce(col_2_3, 'unknown_value_3') as renamed_column_2_3 ++ , coalesce(col_2_4, 'unknown_value_4') as renamed_column_2_4 ++ , coalesce(col_2_5, 'unknown_value_5') as renamed_column_2_5 ++ , coalesce(col_2_6, 'unknown_value_6') as renamed_column_2_6 ++ , coalesce(col_2_7, 'unknown_value_7') as renamed_column_2_7 ++ , coalesce(col_2_8, 'unknown_value_8') as renamed_column_2_8 ++ , coalesce(col_2_9, 'unknown_value_9') as renamed_column_2_9 ++ , coalesce(col_2_10, 'unknown_value_10') as renamed_column_2_10 ++ , coalesce(col_2_11, 'unknown_value_11') as renamed_column_2_11 ++ , coalesce(col_2_12, 'unknown_value_12') as renamed_column_2_12 ++ , coalesce(col_2_13, 'unknown_value_13') as renamed_column_2_13 ++ , coalesce(col_2_14, 'unknown_value_14') as renamed_column_2_14 ++ , coalesce(col_2_15, 'unknown_value_15') as renamed_column_2_15 ++ , coalesce(col_2_16, 'unknown_value_16') as renamed_column_2_16 ++ , coalesce(col_2_17, 'unknown_value_17') as renamed_column_2_17 ++ , coalesce(col_2_18, 'unknown_value_18') as renamed_column_2_18 ++ , coalesce(col_2_19, 'unknown_value_19') as renamed_column_2_19 +- , old_col_2 + from {{ ref('stg_2') }} +@@ -310,22 +310,24 @@ + select 3 as ctx_before ++ , coalesce(col_3_0, 'unknown_value_0') as renamed_column_3_0 ++ , coalesce(col_3_1, 'unknown_value_1') as renamed_column_3_1 ++ , coalesce(col_3_2, 'unknown_value_2') as renamed_column_3_2 ++ , coalesce(col_3_3, 'unknown_value_3') as renamed_column_3_3 ++ , coalesce(col_3_4, 'unknown_value_4') as renamed_column_3_4 ++ , coalesce(col_3_5, 'unknown_value_5') as renamed_column_3_5 ++ , coalesce(col_3_6, 'unknown_value_6') as renamed_column_3_6 ++ , coalesce(col_3_7, 'unknown_value_7') as renamed_column_3_7 ++ , coalesce(col_3_8, 'unknown_value_8') as renamed_column_3_8 ++ , coalesce(col_3_9, 'unknown_value_9') as renamed_column_3_9 ++ , coalesce(col_3_10, 'unknown_value_10') as renamed_column_3_10 ++ , coalesce(col_3_11, 'unknown_value_11') as renamed_column_3_11 ++ , coalesce(col_3_12, 'unknown_value_12') as renamed_column_3_12 ++ , coalesce(col_3_13, 'unknown_value_13') as renamed_column_3_13 ++ , coalesce(col_3_14, 'unknown_value_14') as renamed_column_3_14 ++ , coalesce(col_3_15, 'unknown_value_15') as renamed_column_3_15 ++ , coalesce(col_3_16, 'unknown_value_16') as renamed_column_3_16 ++ , coalesce(col_3_17, 'unknown_value_17') as renamed_column_3_17 ++ , coalesce(col_3_18, 'unknown_value_18') as renamed_column_3_18 ++ , coalesce(col_3_19, 'unknown_value_19') as renamed_column_3_19 +- , old_col_3 + from {{ ref('stg_3') }} +@@ -410,22 +410,24 @@ + select 4 as ctx_before ++ , coalesce(col_4_0, 'unknown_value_0') as renamed_column_4_0 ++ , coalesce(col_4_1, 'unknown_value_1') as renamed_column_4_1 ++ , coalesce(col_4_2, 'unknown_value_2') as renamed_column_4_2 ++ , coalesce(col_4_3, 'unknown_value_3') as renamed_column_4_3 ++ , coalesce(col_4_4, 'unknown_value_4') as renamed_column_4_4 ++ , coalesce(col_4_5, 'unknown_value_5') as renamed_column_4_5 ++ , coalesce(col_4_6, 'unknown_value_6') as renamed_column_4_6 ++ , coalesce(col_4_7, 'unknown_value_7') as renamed_column_4_7 ++ , coalesce(col_4_8, 'unknown_value_8') as renamed_column_4_8 ++ , coalesce(col_4_9, 'unknown_value_9') as renamed_column_4_9 ++ , coalesce(col_4_10, 'unknown_value_10') as renamed_column_4_10 ++ , coalesce(col_4_11, 'unknown_value_11') as renamed_column_4_11 ++ , coalesce(col_4_12, 'unknown_value_12') as renamed_column_4_12 ++ , coalesce(col_4_13, 'unknown_value_13') as renamed_column_4_13 ++ , coalesce(col_4_14, 'unknown_value_14') as renamed_column_4_14 ++ , coalesce(col_4_15, 'unknown_value_15') as renamed_column_4_15 ++ , coalesce(col_4_16, 'unknown_value_16') as renamed_column_4_16 ++ , coalesce(col_4_17, 'unknown_value_17') as renamed_column_4_17 ++ , coalesce(col_4_18, 'unknown_value_18') as renamed_column_4_18 ++ , coalesce(col_4_19, 'unknown_value_19') as renamed_column_4_19 +- , old_col_4 + from {{ ref('stg_4') }} +``` +Current SQL: +```sql + , cast(field_0 as varchar) as field_0_text -- line 1 + , cast(field_1 as varchar) as field_1_text -- line 2 + , cast(field_2 as varchar) as field_2_text -- line 3 + , cast(field_3 as varchar) as field_3_text -- line 4 + , cast(field_4 as varchar) as field_4_text -- line 5 + , cast(field_5 as varchar) as field_5_text -- line 6 + , cast(field_6 as varchar) as field_6_text -- line 7 + , cast(field_7 as varchar) as field_7_text -- line 8 + , cast(field_8 as varchar) as field_8_text -- line 9 + , cast(field_9 as varchar) as field_9_text -- line 10 + , cast(field_10 as varchar) as field_10_text -- line 11 + , cast(field_11 as varchar) as field_11_text -- line 12 + , cast(field_12 as varchar) as field_12_text -- line 13 + , cast(field_13 as varchar) as field_13_text -- line 14 + , cast(field_14 as varchar) as field_14_text -- line 15 + , cast(field_15 as varchar) as field_15_text -- line 16 + , cast(field_16 as varchar) as field_16_text -- line 17 + , cast(field_17 as varchar) as field_17_text -- line 18 + , cast(field_18 as varchar) as field_18_text -- line 19 + , cast(field_19 as varchar) as field_19_text -- line 20 + , cast(field_20 as varchar) as field_20_text -- line 21 + , cast(field_21 as varchar) as field_21_text -- line 22 + , cast(field_22 as varchar) as field_22_text -- line 23 + , cast(field_23 as varchar) as field_23_text -- line 24 + , cast(field_24 as varchar) as field_24_text -- line 25 + , cast(field_25 as varchar) as field_25_text -- line 26 + , cast(field_26 as varchar) as field_26_text -- line 27 + , cast(field_27 as varchar) as field_27_text -- line 28 + , cast(field_28 as varchar) as field_28_text -- line 29 + , cast(field_29 as varchar) as field_29_text -- line 30 + , cast(field_30 as varchar) as field_30_text -- line 31 + , cast(field_31 as varchar) as field_31_text -- line 32 + , cast(field_32 as varchar) as field_32_text -- line 33 + , cast(field_33 as varchar) as field_33_text -- line 34 + , cast(field_34 as varchar) as field_34_text -- line 35 +… (truncated) +``` + +## RELATED FILES — unchanged dbt parents of the changed files (context only; comment on the changed files, not these): + +### models/staging/stg_orders.sql (model `stg_orders`, used by models/marts/fct_big.sql) +```sql +select id, amount from raw.orders +``` + +Return ONLY the JSON array per the output contract. +=====BATCH===== +PR title: Rework revenue marts +PR description: +Moves cents conversion into a macro. + +Also adds tests. + +## GROUNDING — deterministic engine findings (DO NOT repeat these): +- [warning] warehouse_cost · models/marts/fct_big.sql: SELECT * in a mart + +## CHANGED FILES (review for what the engine missed): + +### models/staging/stg_0.sql (modified) +Diff: +```diff +@@ -1,2 +1,2 @@ + select +- a_0 ++ b_0 + +``` +Current SQL: +```sql +select b_0 from {{ source('raw', 't0') }} +``` + +### snapshots/snap.sql (modified, snapshot) +Diff: +```diff ++ unique_key='id', + +``` +Current file: +```sql +{% snapshot snap %}select 1{% endsnapshot %} +``` + +### models/py/pm.py (added, Python model) +Diff: +```diff ++def model(dbt, session): + +``` +Current file: +```python +def model(dbt, session): + return dbt.ref('fct') + +``` + +### macros/to_cents.sql (modified, macro (Jinja; changes every model that calls it)) +Diff: +```diff +-round({{ c }}) ++round({{ c }} * 100) + +``` +Current file: +```sql +{% macro to_cents(c) %}round({{ c }} * 100){% endmacro %} +``` + +### tests/assert_positive.sql (added, singular data test) +Diff: +```diff ++select * from {{ ref('fct') }} where id < 0 + +``` +Current file: +```sql +select * from {{ ref('fct') }} where id < 0 +``` + +### models/marts/_marts.yml (modified, schema yml (tests, contracts, descriptions)) +Diff: +```diff ++ - name: id ++ tests: [unique] + +``` +Current file: +```yaml +models: + - name: fct + +``` + +### seeds/codes.csv (modified, seed CSV) +Diff: +```diff ++US,United States + +``` + +### dbt_project.yml (modified, project config) +Diff: +```diff ++ +materialized: table + +``` +Current file: +```yaml +name: shop + +``` + +Return ONLY the JSON array per the output contract. \ No newline at end of file diff --git a/packages/opencode/test/altimate/review-ai-inputs.test.ts b/packages/opencode/test/altimate/review-ai-inputs.test.ts index 28ba434ae7..db3d26993c 100644 --- a/packages/opencode/test/altimate/review-ai-inputs.test.ts +++ b/packages/opencode/test/altimate/review-ai-inputs.test.ts @@ -7,7 +7,10 @@ import { aiInputBudget, batchAiFiles, buildUserMessage, + dedupAiFindings, excerptDiff, + groupAiFiles, + packFocusedBatches, excerptFile, laneUsage, planAiInput, @@ -208,6 +211,27 @@ describe("files sent to the advisory AI lane", () => { const input = await aiInputFor([mod("models/marts/m.sql"), { path: "macros/old.sql", status: "deleted", diff: "-x\n" }]) expect(input?.files.some((f) => f.path === "macros/old.sql")).toBe(false) }) + + test("PR files the user excluded, or build output, are neither listed nor readable by the verifier", async () => { + let seen: AiReviewInput | undefined + await runReview({ + changedFiles: [mod("models/marts/m.sql")], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: { ...DEFAULT_RUBRIC, exclusions: { ...DEFAULT_RUBRIC.exclusions, excludeGlobs: ["secrets/**"] } }, + mode: "comment", + runner, + aiVerify: true, + getContent: async (f, side) => (side === "old" ? undefined : FILES[f]), + generatedAt: "2026-11-14T00:00:00Z", + prFiles: ["models/marts/m.sql", "secrets/key.sql", "target/run/m.sql", "tests/unit/test_m.py"], + aiReview: async (input) => { + seen = input + return { findings: [], status: { state: "ok" } } + }, + }) + expect(seen?.prFiles).toEqual(["models/marts/m.sql", "tests/unit/test_m.py"]) + expect(seen?.evidence?.prFiles).toEqual(["models/marts/m.sql", "tests/unit/test_m.py"]) + }) }) describe("selection and prompt layout", () => { @@ -446,8 +470,9 @@ describe("verifier evidence (opt-in)", () => { evidence: { tool: "ai-review", result: { confidence: "medium" } }, rule: "ai-review:sql-correctness", } - const run = (aiVerify: boolean | undefined, seen: { input?: AiReviewInput }) => + const run = (aiVerify: boolean | undefined, seen: { input?: AiReviewInput }, prFiles?: string[]) => runReview({ + ...(prFiles ? { prFiles } : {}), changedFiles: [mod("models/marts/m.sql", "@@ -1 +1 @@\n-select 1 as id\n+select 2 as id\n")], config: { ...DEFAULT_REVIEW_CONFIG }, rubric: DEFAULT_RUBRIC, @@ -487,6 +512,13 @@ describe("verifier evidence (opt-in)", () => { expect(ev.files.map((f) => f.path)).toEqual(["models/marts/m.sql"]) expect(ev.dialect).toBe(DEFAULT_REVIEW_CONFIG.dialect) }) + + test("the PR file list given to the lane and the verifier drops credential files", async () => { + const seen: { input?: AiReviewInput } = {} + await run(true, seen, ["models/marts/m.sql", "config/profiles.yml", ".env", "tests/test_m.py"]) + expect(seen.input!.evidence!.prFiles).toEqual(["models/marts/m.sql", "tests/test_m.py"]) + expect(seen.input!.prFiles).toEqual(["models/marts/m.sql", "tests/test_m.py"]) + }) }) describe("input coverage (opt-in ALTIMATE_REVIEW_AI_COVERAGE=1)", () => { @@ -967,3 +999,194 @@ describe("review feedback: input planning and card resolution", () => { expect(files[1].card).toContain("seed `countries`") }) }) + +describe("focused batches for large PRs (opt-in ALTIMATE_REVIEW_AI_FOCUSED=1)", () => { + const FOCUSED = { ALTIMATE_REVIEW_AI_FOCUSED: "1" } + const file = (path: string, kind = "model_sql", sql = "select 1", model?: string): AiReviewFile => ({ + path, + status: "modified", + kind, + model: model ?? path.split("/").pop()!.replace(/\.\w+$/, ""), + diff: "+x\n", + sql, + }) + const paths = (groups: AiReviewFile[][]) => groups.map((g) => g.map((f) => f.path)) + const tenFiles = () => { + const base = defaultPromptInput() + return { ...base, files: base.files.slice(0, 10) } + } + + test("FOCUSED unset: batches and messages are today's, with and without coverage", () => { + const input = tenFiles() + for (const env of [{}, { ALTIMATE_REVIEW_AI_BATCH_CHARS: "3000" }, { ALTIMATE_REVIEW_AI_COVERAGE: "1" }]) { + const plan = planAiInput(input, env) + expect(plan.focused).toBe(false) + expect(plan.batches).toEqual(batchAiFiles(plan.files, plan.budget)) + expect(plan.messages).toEqual( + plan.batches.map((b) => buildUserMessage({ ...input, files: b }, plan.budget.maxFileChars, plan.budget.coverage)), + ) + expect(plan.input.some((r) => "batch" in r)).toBe(false) + } + // Coverage-only messages pinned before focused batching existed. + const envs = [{ ALTIMATE_REVIEW_AI_COVERAGE: "1" }, { ALTIMATE_REVIEW_AI_COVERAGE: "1", ALTIMATE_REVIEW_AI_BATCH_CHARS: "3000" }] + const snapshot = readFileSync(path.join(import.meta.dir, "fixtures/review-ai-prompt-coverage.txt"), "utf8") + expect(envs.flatMap((env) => planAiInput(input, env).messages).join("\n=====BATCH=====\n")).toBe(snapshot) + expect(planAiInput(input, { ...envs[0], ...FOCUSED }).focused).toBe(true) + }) + + test("a macro, its adapter variants and a file dispatching to it form one group", () => { + const groups = groupAiFiles([ + file("macros/a/default__hash.sql", "macro", "{% macro default__hash(c) %}md5({{ c }}){% endmacro %}"), + file("models/x/m1.sql"), + file("macros/b/snowflake__hash.sql", "macro", "{%- macro snowflake__hash(c) -%}sha2({{ c }}){%- endmacro -%}"), + file("macros/c/hash.sql", "macro", "{% macro hash(c) %}{{ return(adapter.dispatch('hash', 'pkg')(c)) }}{% endmacro %}"), + file("models/y/m2.sql"), + ]) + expect(paths(groups)).toEqual([ + ["macros/a/default__hash.sql", "macros/b/snowflake__hash.sql", "macros/c/hash.sql"], + ["models/x/m1.sql"], + ["models/y/m2.sql"], + ]) + // Without content, macro names come from the diff's added lines. + const fromDiff = groupAiFiles([ + { path: "macros/p/postgres__k.sql", status: "added", kind: "macro", model: "postgres__k", diff: "+{% macro postgres__k() %}1{% endmacro %}\n" }, + { path: "macros/q/default__k.sql", status: "added", kind: "macro", model: "default__k", diff: "+{% macro default__k() %}1{% endmacro %}\n" }, + ]) + expect(fromDiff).toHaveLength(1) + }) + + test("ref edges: a singular test joins the model it tests (package arg: the last string)", () => { + const groups = groupAiFiles([ + file("models/marts/orders.sql"), + file("models/staging/stg_x.sql"), + file("tests/assert_orders.sql", "test", "select * from {{ ref(\"orders\") }} where amount < 0"), + file("models/other/uses_pkg.sql", "model_sql", "select * from {{ ref('pkg', 'stg_x') }}"), + ]) + expect(paths(groups)).toEqual([ + ["models/marts/orders.sql", "tests/assert_orders.sql"], + ["models/staging/stg_x.sql", "models/other/uses_pkg.sql"], + ]) + }) + + test("a schema yml joins the models it declares", () => { + const groups = groupAiFiles([ + file("models/marts/orders.sql"), + file("models/staging/stg.sql"), + file("models/schema/_core.yml", "schema_yml", "version: 2\nmodels:\n - name: orders\n columns:\n - name: id\n"), + ]) + expect(paths(groups)).toEqual([["models/marts/orders.sql", "models/schema/_core.yml"], ["models/staging/stg.sql"]]) + }) + + test("files with no edge group by directory", () => { + const groups = groupAiFiles([ + file("models/a/x.sql"), + file("models/b/y.sql"), + file("models/a/z.sql"), + file("models/c/p.sql"), + file("models/c/q.sql", "model_sql", "select * from {{ ref('p') }}"), + file("models/c/r.sql"), + ]) + // p and q are linked by ref, so r (edge-less) stays alone despite sharing their directory. + expect(paths(groups)).toEqual([["models/a/x.sql", "models/a/z.sql"], ["models/b/y.sql"], ["models/c/p.sql", "models/c/q.sql"], ["models/c/r.sql"]]) + }) + + test("a 12-file group splits into chunks of 5/5/2 and no chunk is split across calls", () => { + const big = Array.from({ length: 12 }, (_, i) => file(`models/big/m${i}.sql`)) + const small = [file("models/s/a.sql"), file("models/s/b.sql"), file("models/s/c.sql"), file("models/s/d.sql")] + const budget = aiInputBudget(FOCUSED) + const batches = packFocusedBatches([big, small], budget) + expect(batches.map((b) => b.length)).toEqual([5, 5, 2, 4]) + expect(paths(batches)[2]).toEqual(["models/big/m10.sql", "models/big/m11.sql"]) + expect(batches.every((b) => b.length <= 5)).toBe(true) + // The 2-file chunk and a 3-file group share a call; a 4-file group does not fit after them. + const packed = packFocusedBatches([big.slice(10), small.slice(0, 3), small], budget) + expect(packed.map((b) => b.length)).toEqual([5, 4]) + }) + + test("30 unrelated files with defaults: exactly 4 calls, balanced by prompt size", () => { + const files = Array.from({ length: 30 }, (_, i) => file(`models/d${i}/m${i}.sql`, "model_sql", "x".repeat(100 + i * 37))) + const plan = planAiInput({ grounding: [], files }, { ...FOCUSED, ALTIMATE_REVIEW_AI_MAX_FILES: "30" }) + expect(plan.focused).toBe(true) + expect(plan.batches).toHaveLength(4) + expect(plan.batches.flat()).toHaveLength(30) + const chars = plan.batches.map((b) => b.reduce((n, f) => n + plan.input.find((r) => r.path === f.path)!.chars, 0)) + expect(Math.max(...chars) - Math.min(...chars)).toBeLessThan(Math.max(...chars) * 0.1) + // Within a call, files keep input order. + for (const b of plan.batches) expect(b).toEqual(files.filter((f) => b.includes(f))) + }) + + test("focused packing honours batchChars, splitting past maxBatches when it must", () => { + // 30 files of ~6k chars each under coverage, 4 balanced calls of ~45k: none may exceed a 30k batch budget. + const files = Array.from({ length: 30 }, (_, i) => file(`models/d${i}/m${i}.sql`, "model_sql", "x".repeat(16_000))) + const env = { ...FOCUSED, ALTIMATE_REVIEW_AI_COVERAGE: "1", ALTIMATE_REVIEW_AI_QUOTA_MODEL: "30", ALTIMATE_REVIEW_AI_BATCH_CHARS: "30000" } + const plan = planAiInput({ grounding: [], files }, env) + expect(plan.focused).toBe(true) + expect(plan.batches.flat()).toHaveLength(30) + const chars = plan.batches.map((b) => b.reduce((n, f) => n + plan.input.find((r) => r.path === f.path)!.chars, 0)) + expect(Math.max(...chars)).toBeLessThanOrEqual(plan.budget.batchChars) + expect(plan.batches.length).toBeGreaterThan(4) + // A related group that fits the file count but not batchChars is split too. + const small = Array.from({ length: 8 }, (_, i) => file(`models/s/m${i}.sql`, "model_sql", "y".repeat(2_500))) + const budget = { ...aiInputBudget(FOCUSED), batchChars: 3_000 } + const packed = packFocusedBatches(groupAiFiles(small), budget) + expect(packed.flat()).toHaveLength(8) + for (const b of packed) expect(b.length === 1 || b.reduce((n, f) => n + f.sql!.length, 0) <= 3_000).toBe(true) + }) + + test("focus settings must be positive integers", () => { + const b = aiInputBudget({ ...FOCUSED, ALTIMATE_REVIEW_AI_FOCUS_BATCH_FILES: "2.5", ALTIMATE_REVIEW_AI_FOCUS_MAX_BATCHES: "0", ALTIMATE_REVIEW_AI_FOCUS_MIN_FILES: "x" }) + expect(b.focused).toEqual({ minFiles: 7, batchFiles: 5, maxBatches: 4 }) + }) + + test("fewer than 7 selected files: today's batching", () => { + const files = Array.from({ length: 6 }, (_, i) => file(`models/d${i}/m${i}.sql`)) + const plan = planAiInput({ grounding: [], files }, FOCUSED) + expect(plan.focused).toBe(false) + expect(plan.batches).toEqual([files]) + expect(plan.messages[0]).not.toContain("OTHER FILES CHANGED") + expect(planAiInput({ grounding: [], files }, { ...FOCUSED, ALTIMATE_REVIEW_AI_FOCUS_MIN_FILES: "6" }).focused).toBe(true) + }) + + test("each call carries its own files' grounding and lists the other changed files", () => { + const files = Array.from({ length: 8 }, (_, i) => file(`models/d${i}/m${i}.sql`)) + const g = (p: string | undefined, title: string) => + makeFinding({ severity: "warning", category: "warehouse_cost", title, body: "b", file: p ?? "" }) + const grounding = [g("models/d0/m0.sql", "first-file finding"), g("models/d7/m7.sql", "last-file finding"), g(undefined, "project finding")] + const plan = planAiInput({ grounding, files }, FOCUSED) + expect(plan.batches.map((b) => b.length)).toEqual([5, 3]) + const [m0, m1] = plan.messages + expect(m0).toContain("first-file finding") + expect(m0).not.toContain("last-file finding") + expect(m1).toContain("last-file finding") + expect(m1).not.toContain("first-file finding") + expect(m0).toContain("project finding") + expect(m1).toContain("project finding") + const others = m0.split("## OTHER FILES CHANGED IN THIS PR (reviewed in separate calls; do not comment on them):")[1] + expect(others).toContain("- models/d5/m5.sql (model_sql)") + expect(others).toContain("- models/d7/m7.sql (model_sql)") + expect(others).not.toContain("models/d0/m0.sql") + expect(m0.indexOf("### models/d4/m4.sql")).toBeLessThan(m0.indexOf("## OTHER FILES CHANGED")) + }) + + test("duplicate findings across calls collapse to the first", () => { + const f = (title: string, startLine?: number, p = "models/a.sql") => + makeFinding({ severity: "suggestion", category: "sql_correctness", title, body: title, file: p, startLine }) + const out = dedupAiFindings([f("a: Fan-out JOIN!", 3), f("A: fan-out join", 3), f("a: fan-out join", 4), f("a: fan-out join", 3, "models/b.sql"), f("x"), f("X.")]) + expect(out.map((x) => [x.title, x.startLine, x.file])).toEqual([ + ["a: Fan-out JOIN!", 3, "models/a.sql"], + ["a: fan-out join", 4, "models/a.sql"], + ["a: fan-out join", 3, "models/b.sql"], + ["x", undefined, "models/a.sql"], + ]) + }) + + test("ai.input records the call index only under focused batching", () => { + const files = Array.from({ length: 8 }, (_, i) => file(`models/d${i}/m${i}.sql`)) + expect(planAiInput({ grounding: [], files }, FOCUSED).input.map((r) => r.batch)).toEqual([0, 0, 0, 0, 0, 1, 1, 1]) + expect(planAiInput({ grounding: [], files }, { ALTIMATE_REVIEW_AI_COVERAGE: "1" }).input.every((r) => r.batch === undefined)).toBe(true) + expect(aiInputBudget(FOCUSED).focused).toEqual({ minFiles: 7, batchFiles: 5, maxBatches: 4 }) + expect( + aiInputBudget({ ...FOCUSED, ALTIMATE_REVIEW_AI_FOCUS_BATCH_FILES: "3", ALTIMATE_REVIEW_AI_FOCUS_MAX_BATCHES: "6", ALTIMATE_REVIEW_AI_FOCUS_MIN_FILES: "10" }).focused, + ).toEqual({ minFiles: 10, batchFiles: 3, maxBatches: 6 }) + }) +}) diff --git a/packages/opencode/test/altimate/review-ai-test-gap.test.ts b/packages/opencode/test/altimate/review-ai-test-gap.test.ts new file mode 100644 index 0000000000..9e68dfcf7f --- /dev/null +++ b/packages/opencode/test/altimate/review-ai-test-gap.test.ts @@ -0,0 +1,68 @@ +import { describe, test, expect, spyOn, mock, afterEach } from "bun:test" +import { listedFiles, testGapFileList, TEST_GAP_INSTRUCTION, runAiReview, type AiReviewFile } from "../../src/altimate/review/ai-review" +import { LLM } from "../../src/session/llm" +import { Provider } from "../../src/provider/provider" + +const FAKE_MODEL = { providerID: "fake", id: "m", api: { npm: "x" }, cost: {} } as unknown as Provider.Model +const file = (path: string, line = 11): AiReviewFile => ({ + path, + status: "modified", + model: path.split("/").pop()!.replace(/\.sql$/, ""), + diff: `@@ -${line - 1},2 +${line - 1},3 @@\n select a,\n+ b / 100 as amount,\n from t\n`, +}) + +describe("test-gap instruction (ALTIMATE_REVIEW_AI_TEST_GAP=1)", () => { + afterEach(() => mock.restore()) + + test("testGapFileList lists the PR's other files, not the batch's own", () => { + const msg = testGapFileList("BODY", [file("models/fct.sql")], ["models/fct.sql", "tests/unit/test_x.py", ".github/workflows/ci.yml"]) + expect(msg).toBe( + "BODY\n\n## OTHER FILES THIS PR CHANGES (paths only, not shown; use them to judge test coverage)\n- tests/unit/test_x.py\n- .github/workflows/ci.yml", + ) + expect(testGapFileList("BODY", [file("models/fct.sql")], ["models/fct.sql"])).toBe("BODY") + }) + + test("under focused batching the test-gap list skips files the focused list already names", () => { + const files = Array.from({ length: 8 }, (_, i) => file(`models/d${i}/m${i}.sql`)) + const batch = files.slice(0, 5) + const listed = listedFiles({ files, focused: true }, batch) + expect(listed).toEqual(files) + const msg = testGapFileList("BODY", listed, [...files.map((f) => f.path), "tests/unit/test_x.py"]) + expect(msg).toBe("BODY\n\n## OTHER FILES THIS PR CHANGES (paths only, not shown; use them to judge test coverage)\n- tests/unit/test_x.py") + expect(listedFiles({ files, focused: false }, batch)).toBe(batch) + }) + + test("on: the system prompt gains the instruction and the message the file list; off: neither", async () => { + const seen: any[] = [] + spyOn(Provider, "defaultModel").mockResolvedValue({ providerID: "fake", modelID: "m" } as any) + spyOn(Provider, "getModel").mockResolvedValue(FAKE_MODEL as any) + spyOn(LLM, "stream").mockImplementation(async (input: any) => { + seen.push(input) + return { + fullStream: (async function* () {})(), + text: Promise.resolve("[]"), + finishReason: Promise.resolve("stop"), + response: Promise.resolve({ messages: [] }), + totalUsage: Promise.resolve({ inputTokens: 1, outputTokens: 1, totalTokens: 2 }), + providerMetadata: Promise.resolve(undefined), + } as any + }) + const input = { files: [file("models/fct.sql")], grounding: [], prFiles: ["models/fct.sql", "tests/unit/test_x.py"] } + const prev = process.env.ALTIMATE_REVIEW_AI_TEST_GAP + try { + delete process.env.ALTIMATE_REVIEW_AI_TEST_GAP + await runAiReview(input) + process.env.ALTIMATE_REVIEW_AI_TEST_GAP = "1" + await runAiReview(input) + } finally { + if (prev === undefined) delete process.env.ALTIMATE_REVIEW_AI_TEST_GAP + else process.env.ALTIMATE_REVIEW_AI_TEST_GAP = prev + } + const [off, on] = seen + expect(off.system[0]).not.toContain(TEST_GAP_INSTRUCTION) + expect(on.system[0].endsWith(TEST_GAP_INSTRUCTION)).toBe(true) + expect(on.system[0].slice(0, -TEST_GAP_INSTRUCTION.length)).toBe(off.system[0]) + expect(String(off.messages[0].content)).not.toContain("OTHER FILES THIS PR CHANGES") + expect(String(on.messages[0].content)).toContain("- tests/unit/test_x.py") + }) +}) diff --git a/packages/opencode/test/altimate/review-ai-verify.test.ts b/packages/opencode/test/altimate/review-ai-verify.test.ts index 2b1c8bdebb..8637401631 100644 --- a/packages/opencode/test/altimate/review-ai-verify.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify.test.ts @@ -13,6 +13,8 @@ import { runAiVerify, toolsChars, verifierTools, + isCredentialPath, + holdsCredentials, type AiVerifyEvidence, type VerifierLlm, type VerifierStep, @@ -38,9 +40,9 @@ import type { AiReviewFile } from "../../src/altimate/review/ai-review" import { runAiReview } from "../../src/altimate/review/ai-review" import { createDispatcherRunner } from "../../src/altimate/review/runner" import { LLM } from "../../src/session/llm" -import { mkdirSync, writeFileSync } from "fs" +import { mkdirSync, symlinkSync, writeFileSync } from "fs" import { execFileSync } from "child_process" -import { grepFixedAt, projectGrepSpecs } from "../../src/altimate/review/git" +import { grepFixedAt, makeContentResolver, projectGrepSpecs } from "../../src/altimate/review/git" import path from "path" import { tmpdir } from "../fixture/fixture" import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" @@ -48,6 +50,10 @@ import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" import { Provider } from "../../src/provider/provider" +// Fake credential markers are assembled at runtime so secret scanners do not flag the fixtures. +const pkHeader = (kind?: string) => ["-----BEGIN", kind, "PRIVATE", "KEY-----"].filter(Boolean).join(" ") +const FAKE_PW = ["SECRET", "123"].join("") + /** * The dbt-grounded verifier: an opt-in second model call that tries to refute * each AI finding with dbt evidence. Every model here is scripted; no test @@ -868,7 +874,7 @@ describe("runAiVerify: the bounded tool loop", () => { await verify([aiFinding()], llm) const [secret, traversal, parent, bySuffix, downstreamOld] = toolResults(calls[1]) expect(secret).toBe( - "not available: outside review scope (changed files, their dbt parents and direct downstream models only)", + "not available: outside review scope (files the PR changes, their dbt parents and direct downstream models only)", ) expect(traversal).toStartWith("not available: outside review scope") expect(parent).toBe("1: select id as order_id, amount_cents from raw.orders") @@ -1051,6 +1057,52 @@ describe("runAiVerify: the bounded tool loop", () => { expect(toolsChars(tools as any)).toBeLessThan(3_000) }) + test("read_file opens any file the PR changes, outside the dbt project too", async () => { + const read: string[] = [] + const defs = verifierTools( + evidence({ + prFiles: ["models/fct.sql", "packages/transform/tests/unit/test_override.py"], + readFile: async (p) => (read.push(p), "1: def test_x(): ..."), + }), + ) + expect(await defs.read_file.run({ path: "packages/transform/tests/unit/test_override.py" })).toBe("1: def test_x(): ...") + expect(await defs.read_file.run({ path: "other/secret.py" })).toStartWith("not available: outside review scope") + expect(read).toEqual(["packages/transform/tests/unit/test_override.py"]) + }) + + test("credential files the PR changes stay unreadable, whatever lists them, and never show in grep hits", async () => { + const read: string[] = [] + const secrets = ["config/profiles.yml", "dbt/.env", "infra/prod.tfvars", "certs/client.pem", "profiles.yaml"] + const defs = verifierTools( + evidence({ + prFiles: ["models/fct.sql", ...secrets], + addedLines: new Map([["config/profiles.yml", new Set([1])]]), + readFile: async (p) => (read.push(p), "1: password: hunter2"), + grepProject: async () => [ + { path: "config/profiles.yml", line: 3, text: "password: hunter2" }, + { path: "models/fct.sql", line: 1, text: "select password_hash" }, + ], + }), + { parents: [{ name: "profiles", kind: "model", path: "profiles.yaml" }], downstream: [] } as any, + ) + for (const p of [...secrets, "profiles.yml"]) expect(await defs.read_file.run({ path: p })).toStartWith("not available: outside review scope") + expect(read).toEqual([]) + expect(await defs.grep_project.run({ pattern: "password" })).toBe("models/fct.sql:1: select password_hash") + expect(isCredentialPath("models/profiles_summary.sql")).toBe(false) + expect(isCredentialPath("models/env.yml")).toBe(false) + }) + + test("a test-coverage candidate lists the PR's files; other candidates don't", () => { + const files = ["models/fct.sql", "tests/unit/test_override.py"] + const gap = buildVerifyMessage("Fix", [{ id: "c1", finding: aiFinding({ category: "test_coverage" }), diff: DIFF }], files) + expect(gap).toContain("Files this PR changes (read_file can open any of them):\n- models/fct.sql\n- tests/unit/test_override.py") + const other = buildVerifyMessage("Fix", [{ id: "c1", finding: aiFinding(), diff: DIFF }], files) + expect(other).not.toContain("Files this PR changes") + expect(buildVerifyMessage("Fix", [{ id: "c1", finding: aiFinding(), diff: DIFF }])).toBe( + buildVerifyMessage("Fix", [{ id: "c1", finding: aiFinding(), diff: DIFF }], []), + ) + }) + test("verifierTools: equivalence needs a base side; grain needs the engine; grep needs 2 chars", async () => { const defs = verifierTools(evidence()) expect(await defs.grep_project.run({ pattern: "a" })).toBe("not available: pattern needs at least 2 characters") @@ -1091,6 +1143,330 @@ describe("runAiVerify: the bounded tool loop", () => { }) }) +describe("credential files: refused by name, by the path actually read, and by content", () => { + test.each([ + "profiles.yml", + "config/Profiles.YAML", + ".env", + "dbt/.env.local", + ".envrc", + ".env-prod", + "deploy/prod.env", + ".netrc", + ".pgpass", + ".npmrc", + ".pypirc", + ".git-credentials", + "home/.ssh/id_ed25519", // ggignore: a path name, not a secret + "keyfile.json", + "secrets/keyfile-bq.json", + "gcp/my-service-account.json", + "gcp/service_account_key.json", + "credentials.json", + "aws/credentials-prod.json", + "certs/client.pem", + "tls/server.key", + "apple/AuthKey.p8", + "store.p12", + "infra/prod.tfvars", + "infra/terraform.tfvars.json", + "home/.aws/credentials", + ".docker/config.json", + "kubeconfig", + "deploy/secrets.yml", + "config/secret.json", + "gcp/client_secret_1234.apps.json", + "ci/dbt_profiles.yml", + "profiles-ci.yml", + "profiles.yml.example", + "config/profiles.prod.yaml", + ])("%s is a credential path", (p) => expect(isCredentialPath(p)).toBe(true)) + + test.each([ + "models/profiles_summary.sql", + "models/env.yml", + "models/environment.sql", + "models/accounts.json", + "macros/keys.sql", + "docs/credentials.md", + "seeds/service_accounts.csv", + "models/schema.yml", + "dbt_project.yml", + "models/secrets_summary.sql", + "models/marts/customer_profiles.yml", + "models/secrets/stg_vault.yml", + "docs/aws/credentials.md", + "k8s/config.json", + ])("%s is not a credential path", (p) => expect(isCredentialPath(p)).toBe(false)) + + test("content holding a private key or a service-account key is credentials, whatever the name", () => { + expect(holdsCredentials("x\n" + pkHeader("RSA") + "\nMII...")).toBe(true) + expect(holdsCredentials(pkHeader())).toBe(true) + expect(holdsCredentials("x\n" + pkHeader("PGP").replace("KEY-----", "KEY BLOCK-----") + "\nfake-key-body")).toBe(true) + expect(holdsCredentials('{ "type": "service_account", "project_id": "p" }')).toBe(true) + expect(holdsCredentials("select private_key_id from keys -- BEGIN")).toBe(false) + expect(holdsCredentials("-----BEGIN PUBLIC KEY-----")).toBe(false) + }) + + const git = (cwd: string, ...args: string[]) => + execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...args], { cwd, stdio: "ignore" }) + const runner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } as ReviewRunner + type Changed = Parameters[0]["changedFiles"] + /** What runReview hands the AI lane over the real git content resolver. */ + const aiInputFor = async ( + root: string, + changedFiles: Changed, + head?: string, + more: { prFiles?: string[]; prRenames?: Map; grep?: boolean } = {}, + ) => { + const renames = new Map([ + ...(more.prRenames ?? []), + ...changedFiles.flatMap((f) => (f.oldPath ? [[f.path, f.oldPath] as [string, string]] : [])), + ]) + let got: Parameters[0]["aiReview"]>>[0] | undefined + await runReview({ + changedFiles, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiVerify: true, + getContent: makeContentResolver({ base: "HEAD~1", head, cwd: root, renames, gitRoot: root }), + prFiles: more.prFiles ?? changedFiles.map((f) => f.path), + prRenames: more.prRenames, + grepProject: more.grep ? (pattern, glob) => grepFixedAt(root, head, pattern, [glob ?? "models"]) : undefined, + generatedAt: "2026-11-23T00:00:00Z", + aiReview: async (input) => ((got = input), { findings: [], status: { state: "ok" } }), + }) + return got! + } + /** The verifier evidence runReview builds over the real git content resolver. */ + const evidenceFor = async (root: string, changedFiles: Changed, head?: string) => + (await aiInputFor(root, changedFiles, head)).evidence! + + test("the old side of a renamed credential file is refused (read_file, compiled_sql, equivalence)", async () => { + await using tmp = await tmpdir() + const root = tmp.path + git(root, "init", "-q") + writeFileSync(path.join(root, "profiles.yml"), `prod:\n password: ${FAKE_PW}\n`) + writeFileSync(path.join(root, ".env"), "select 'SECRET456' as id\n") + mkdirSync(path.join(root, "models")) + writeFileSync(path.join(root, "models", "a.sql"), "select 1 as id\n") + git(root, "add", ".") + git(root, "commit", "-qm", "base") + git(root, "mv", "profiles.yml", "profiles.yml.example") + writeFileSync(path.join(root, "profiles.yml.example"), "prod:\n password: \"{{ env_var('PW') }}\"\n") + git(root, "mv", ".env", "models/env_model.sql") + git(root, "commit", "-qam", "head") + const ev = await evidenceFor( + root, + [ + { path: "profiles.yml.example", oldPath: "profiles.yml", status: "renamed", diff: `@@ -2 +2 @@\n- password: ${FAKE_PW}\n+ password: x\n` }, + { path: "models/env_model.sql", oldPath: ".env", status: "renamed", diff: "" }, + ], + "HEAD", + ) + const tools = verifierTools(ev) + // Both sides are refused: the verifier lists it nowhere, and evidence.readFile refuses it. + for (const side of ["old", "new"] as const) { + expect(await tools.read_file.run({ path: "profiles.yml.example", side })).toStartWith("not available") + expect(await ev.readFile("profiles.yml.example", side)).toBe("not available: may hold credentials") + } + // A model renamed from a credential file: neither the engine's old SQL nor compiled output is shown. + expect(await ev.compiledSql("models/env_model.sql", "old")).toBeUndefined() + expect(await tools.compiled_sql.run({ path: "models/env_model.sql", side: "old" })).not.toContain("SECRET456") + expect(await tools.equivalence.run({ path: "models/env_model.sql" })).toStartWith("not available") + expect(await tools.read_file.run({ path: "models/env_model.sql", side: "old" })).toStartWith("not available") + expect(await ev.readFile("models/env_model.sql", "old")).toBe("not available: may hold credentials") + expect(ev.files.map((f) => f.path)).not.toContain("models/env_model.sql") + }) + + test("working-tree mode never follows a symlink to a credential file; other symlinks still read", async () => { + await using tmp = await tmpdir() + const root = tmp.path + git(root, "init", "-q") + writeFileSync(path.join(root, "profiles.yml"), `prod:\n password: ${FAKE_PW}\n`) + mkdirSync(path.join(root, "docs")) + writeFileSync(path.join(root, "docs", "readme.md"), "hello\n") + git(root, "add", ".") + git(root, "commit", "-qm", "base") + symlinkSync("../profiles.yml", path.join(root, "docs", "link.md")) + symlinkSync("readme.md", path.join(root, "docs", "alias.md")) + const resolver = makeContentResolver({ base: "HEAD", cwd: root, gitRoot: root }) + expect(await resolver("docs/link.md", "new")).toBeUndefined() + expect(await resolver("docs/alias.md", "new")).toBe("hello\n") + const ev = await evidenceFor(root, [ + { path: "docs/link.md", status: "added", diff: "@@ -0,0 +1 @@\n+../profiles.yml\n" }, + { path: "docs/alias.md", status: "added", diff: "@@ -0,0 +1 @@\n+readme.md\n" }, + ]) + const tools = verifierTools(ev) + expect(await tools.read_file.run({ path: "docs/link.md" })).not.toContain(FAKE_PW) + expect(await tools.read_file.run({ path: "docs/alias.md" })).toStartWith("1: hello") + }) + + test("read_file refuses a file whose content is a private key, whatever it is called", async () => { + await using tmp = await tmpdir() + const root = tmp.path + git(root, "init", "-q") + writeFileSync(path.join(root, "notes.md"), "x\n") + git(root, "add", ".") + git(root, "commit", "-qm", "base") + writeFileSync(path.join(root, "notes.md"), pkHeader("OPENSSH") + "\nfake-key-body\n") + const ev = await evidenceFor(root, [{ path: "notes.md", status: "modified", diff: "@@ -1 +1,2 @@\n-x\n+k\n" }]) + expect(await verifierTools(ev).read_file.run({ path: "notes.md" })).toBe("not available: may hold credentials") + }) + + test("an unedited rename of a credential file is refused on the new side (git ref and working tree)", async () => { + await using tmp = await tmpdir() + const root = tmp.path + git(root, "init", "-q") + writeFileSync(path.join(root, "warehouse.yml"), `prod:\n password: ${FAKE_PW}\n`) + mkdirSync(path.join(root, "models")) + writeFileSync(path.join(root, "models", "a.sql"), "select 1 as id\n") + git(root, "add", ".") + git(root, "commit", "-qm", "base") + git(root, "mv", "warehouse.yml", ".env") + git(root, "commit", "-qm", "head") + git(root, "mv", ".env", "conn.txt") // working tree: the same file renamed again, uncommitted + const changed: Changed = [{ path: "conn.txt", oldPath: ".env", status: "renamed", diff: "" }] + for (const head of ["HEAD", undefined]) { + const files: Changed = head ? [{ path: ".env", oldPath: "warehouse.yml", status: "renamed", diff: "" }] : changed + const p = files[0].path + const tools = verifierTools((await aiInputFor(root, files, head)).evidence!) + for (const side of ["new", "old"] as const) { + const got = await tools.read_file.run({ path: p, side }) + expect(got).not.toContain(FAKE_PW) + } + } + // Renamed from a credential name to an innocuous one, unedited: still refused on the new side. + const ev = (await aiInputFor(root, changed)).evidence! + expect(await ev.readFile("conn.txt", "new")).toBe("not available: may hold credentials") + expect(ev.prFiles).toEqual([]) + }) + + test("a model renamed from a credential file, moved into the project, sends no diff to the AI lane", async () => { + await using tmp = await tmpdir() + const root = tmp.path + git(root, "init", "-q") + writeFileSync(path.join(root, ".env"), `DB_PASSWORD=${FAKE_PW}\nselect 1 as id\n`) + mkdirSync(path.join(root, "models")) + writeFileSync(path.join(root, "models", "a.sql"), "select 1 as id\n") + git(root, "add", ".") + git(root, "commit", "-qm", "base") + git(root, "mv", ".env", "models/x.sql") + writeFileSync(path.join(root, "models", "x.sql"), "select 1 as id\n") + git(root, "commit", "-qam", "head") + const diff = `@@ -1,2 +1 @@\n-DB_PASSWORD=${FAKE_PW}\n select 1 as id\n` + // Scoped into the project, the rename arrives as "added"; only the PR's rename map knows its old path. + const input = await aiInputFor(root, [{ path: "models/x.sql", status: "added", diff }], "HEAD", { + prRenames: new Map([["models/x.sql", ".env"]]), + }) + expect(JSON.stringify(input.files)).not.toContain(FAKE_PW) + expect(input.files.map((f) => f.path)).not.toContain("models/x.sql") + expect(await input.evidence!.readFile("models/x.sql", "old")).toBe("not available: may hold credentials") + expect(await input.evidence!.compiledSql("models/x.sql", "new")).toBeUndefined() + }) + + test("a rename outside the dbt project: its old side reads the old path; a credential one is refused", async () => { + await using tmp = await tmpdir() + const root = tmp.path + git(root, "init", "-q") + mkdirSync(path.join(root, "ci")) + writeFileSync(path.join(root, "ci", "old.sh"), "echo old\n") + writeFileSync(path.join(root, "ci", "profiles.yml"), `password: ${FAKE_PW}\n`) + mkdirSync(path.join(root, "models")) + writeFileSync(path.join(root, "models", "a.sql"), "select 1 as id\n") + git(root, "add", ".") + git(root, "commit", "-qm", "base") + git(root, "mv", "ci/old.sh", "ci/run.sh") + git(root, "mv", "ci/profiles.yml", "ci/settings.txt") + writeFileSync(path.join(root, "models", "a.sql"), "select 2 as id\n") + git(root, "commit", "-qam", "head") + const ev = ( + await aiInputFor(root, [{ path: "models/a.sql", status: "modified", diff: "@@ -1 +1 @@\n-select 1 as id\n+select 2 as id\n" }], "HEAD", { + prFiles: ["models/a.sql", "ci/run.sh", "ci/settings.txt"], + prRenames: new Map([ + ["ci/run.sh", "ci/old.sh"], + ["ci/settings.txt", "ci/profiles.yml"], + ]), + }) + ).evidence! + const tools = verifierTools(ev) + expect(await tools.read_file.run({ path: "ci/run.sh", side: "old" })).toStartWith("1: echo old") + expect(ev.prFiles).toEqual(["models/a.sql", "ci/run.sh"]) + expect(await ev.readFile("ci/settings.txt", "new")).toBe("not available: may hold credentials") + }) + + test("key material is screened by content: grep hits, diffs and PGP armor", async () => { + await using tmp = await tmpdir() + const root = tmp.path + git(root, "init", "-q") + mkdirSync(path.join(root, "models")) + mkdirSync(path.join(root, "macros")) + writeFileSync(path.join(root, "models", "a.sql"), "select 1 as id\n") + writeFileSync(path.join(root, "macros", "m.sql"), "{% macro m() %}1{% endmacro %}\n") + git(root, "add", ".") + git(root, "commit", "-qm", "base") + const pgp = pkHeader("PGP").replace("KEY-----", "KEY BLOCK-----") + writeFileSync(path.join(root, "models", "k.md"), `${pgp}\nfake-key-body\n`) + writeFileSync(path.join(root, "models", "a.sql"), "select 1 as id -- fake-key-body mentioned\n") + writeFileSync(path.join(root, "macros", "m.sql"), `{% macro m() %}1{% endmacro %}\n-- ${pkHeader("RSA")}\n`) + git(root, "add", ".") + git(root, "commit", "-qm", "head") + const input = await aiInputFor( + root, + [ + { path: "models/k.md", status: "added", diff: `@@ -0,0 +1,2 @@\n+${pgp}\n+fake-key-body\n` }, + { path: "models/a.sql", status: "modified", diff: "@@ -1 +1 @@\n-select 1 as id\n+select 1 as id -- fake-key-body mentioned\n" }, + { path: "macros/m.sql", status: "modified", diff: `@@ -1 +1,2 @@\n {% macro m() %}1{% endmacro %}\n+-- ${pkHeader("RSA")}\n` }, + ], + "HEAD", + { grep: true }, + ) + const tools = verifierTools(input.evidence!) + expect(await tools.read_file.run({ path: "models/k.md" })).toBe("not available: may hold credentials") + // The whole file holds a key, so none of its lines are shown; other files' hits still are. + expect(await tools.grep_project.run({ pattern: "fake-key-body" })).toBe("models/a.sql:1: select 1 as id -- fake-key-body mentioned") + // A file whose diff carries a key header is not sent to the AI lane. + expect(input.files.map((f) => f.path)).not.toContain("macros/m.sql") + expect(JSON.stringify(input.files)).not.toContain("PRIVATE") + }) + + test("grepFixedAt returns canonical non-ASCII paths, so the credential filter still matches", async () => { + await using tmp = await tmpdir() + const root = tmp.path + git(root, "init", "-q") + mkdirSync(path.join(root, "models", "café"), { recursive: true }) + writeFileSync(path.join(root, "models", "café", "profiles.yml"), `password: ${FAKE_PW}\n`) + writeFileSync(path.join(root, "models", "café", "a.sql"), "select password_hash\n") + git(root, "add", ".") + git(root, "commit", "-qm", "init") + for (const ref of ["HEAD", undefined]) { + const hits = await grepFixedAt(root, ref, "password", ["models"]) + expect(hits?.map((h) => h.path).sort()).toEqual(["models/café/a.sql", "models/café/profiles.yml"]) + const tools = verifierTools({ ...evidence(), grepProject: async () => hits }) + expect(await tools.grep_project.run({ pattern: "password" })).toBe("models/café/a.sql:1: select password_hash") + } + }) +}) + describe("runAiReview with the verifier on (harness path, scripted LLM.stream)", () => { afterEach(() => mock.restore()) diff --git a/packages/opencode/test/altimate/review-dbt-patterns.test.ts b/packages/opencode/test/altimate/review-dbt-patterns.test.ts index 2f152e74ba..db3cfb2e2b 100644 --- a/packages/opencode/test/altimate/review-dbt-patterns.test.ts +++ b/packages/opencode/test/altimate/review-dbt-patterns.test.ts @@ -1646,6 +1646,30 @@ describe("join predicate repeated from an earlier join", () => { const same = body.replace("'app'", "'web'") expect(redundant(same, ["inner join b on b.id = p.id and p.platform = 'web'"])).toHaveLength(1) }) + test("a cross join with an alias in the chain keeps the chain", () => { + const body = [ + "select * from claims as c", + "inner join months as m on c.month_id = m.month_id", + "cross join params as p", + "left join assigned as a", + " on a.person_id = c.person_id", + " and m.month_id = c.month_id", + ].join("\n") + expect(redundant(body, [" and m.month_id = c.month_id"])).toHaveLength(1) + const bare = body.replace("cross join params as p", "cross join params") + expect(redundant(bare, [" and m.month_id = c.month_id"])).toHaveLength(1) + }) + test("twin: after a cross join, a predicate on the new relation is silent", () => { + const body = [ + "select * from claims as c", + "inner join months as m on c.month_id = m.month_id", + "cross join params as p", + "left join assigned as a", + " on a.person_id = c.person_id", + " and a.month_id = c.month_id", + ].join("\n") + expect(redundant(body, [" and a.month_id = c.month_id"])).toHaveLength(0) + }) test("the same predicate in a separate query (another CTE) is not the same join chain", () => { const body = [ "with x as (select * from e join a on e.region = a.target_region),", diff --git a/packages/opencode/test/altimate/review-project-rules.test.ts b/packages/opencode/test/altimate/review-project-rules.test.ts index 9813ac6aca..fb86948c36 100644 --- a/packages/opencode/test/altimate/review-project-rules.test.ts +++ b/packages/opencode/test/altimate/review-project-rules.test.ts @@ -16,6 +16,7 @@ import { testWindowFindings, testsOnNullColumns, yamlParseFindings, + yamlError, } from "../../src/altimate/review/project-rules" import { CATALOG, ruleMatches, leftJoinNullifiedByWhere, evaluateCatalog } from "../../src/altimate/review/rule-catalog" import { inlineConfigSplats, isSuppressiblePortability, runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" @@ -578,6 +579,33 @@ describe("YAML that stops parsing", () => { test("a file that already failed at base is not this change", () => { expect(yamlParseFindings(f(bad), bad, bad)).toHaveLength(0) }) + test("an unterminated quote fails past the edit: anchors on the added line", () => { + const b = "models:\n - name: orders\n columns:\n - name: total\n description: Total in USD.\n - name: ordered_at\n" + const h = b.replace("description: Total in USD.", 'description: "Total in USD.') + const file: ChangedFile = { path: "models/orders.yml", status: "modified", diff: '@@ -5 +5 @@\n- description: Total in USD.\n+ description: "Total in USD.\n' } + const fs = yamlParseFindings(file, b, h) + expect(fs).toHaveLength(1) + expect(fs[0].startLine).toBe(5) + expect((fs[0].evidence!.result as { line?: string }).line).toBe(' description: "Total in USD.') + }) + test("a deletion-only break anchors on the error line the hunk shows", () => { + const b = "models:\n - name: a\n columns:\n - name: id\n" + const h = "models:\n - name: a\n - name: id\n" + const file: ChangedFile = { path: "models/a.yml", status: "modified", diff: "@@ -1,4 +1,3 @@\n models:\n - name: a\n- columns:\n - name: id\n" } + const fs = yamlParseFindings(file, b, h) + expect(fs).toHaveLength(1) + // The parser's error line is a context line of the hunk (no line is added). + expect(yamlError(h)!.line).toBeGreaterThan(0) + expect(fs[0].startLine).toBe(yamlError(h)!.line!) + }) + test("an error before every added line and outside the hunks stays on the file, not an unrelated added line", () => { + const b = "models:\n - name: a\n columns:\n - name: id\n" + const h = "models:\n - name: a\n - name: id\n" + const file: ChangedFile = { path: "models/a.yml", status: "modified", diff: "@@ -9,0 +9,1 @@\n+# trailing\n" } + const fs = yamlParseFindings(file, b, h) + expect(fs).toHaveLength(1) + expect(fs[0].startLine ?? null).toBeNull() + }) test("runs on a quickstart file the review otherwise doesn't classify, and lists it as reviewed", async () => { const env = await prReview([{ path: ".quickstart/quickstart.yml", head: bad, base }]) expect(ruleIds(env.findings)).toContain("dbt-project-rules:yaml-parse-error") @@ -642,6 +670,23 @@ describe("doc() reference with no docs block", () => { test("no other doc() in the file resolves locally (docs may come from a package): silent", async () => { expect(await docRefFindings(yml("audience_id"), base, head("audience_id"), async () => false)).toHaveLength(0) }) + describe("a file whose only doc() is the new one", () => { + const solo = 'models:\n - name: orders\n description: "{{ doc(\'orders_grain\') }}"\n' + const added: ChangedFile = { path: "models/orders.yml", status: "added", diff: `@@ -0,0 +1,3 @@\n+${solo.trimEnd().split("\n").join("\n+")}\n` } + test("fires when the project keeps its own docs blocks", async () => { + const fs = await docRefFindings(added, undefined, solo, async () => false, async () => true) + expect(fs.map((x) => x.rule)).toEqual(["dbt-project-rules:doc-block-missing"]) + }) + test("silent when the project has no docs blocks (they may come from a package)", async () => { + expect(await docRefFindings(added, undefined, solo, async () => false, async () => false)).toHaveLength(0) + expect(await docRefFindings(added, undefined, solo, async () => false)).toHaveLength(0) + }) + test("other doc() names that don't resolve still keep it silent", async () => { + const two = solo + ' - name: items\n description: "{{ doc(\'items_grain\') }}"\n' + const both: ChangedFile = { path: "models/orders.yml", status: "modified", diff: `@@ -3,0 +4,2 @@\n+ - name: items\n+ description: "{{ doc('items_grain') }}"\n` } + expect(await docRefFindings(both, solo, two, async () => false, async () => true)).toHaveLength(0) + }) + }) test("end to end: the project's .md files are searched for the block", async () => { const searched: string[] = [] const env = await prReview([{ path: "models/staging/stg_ads.yml", head: head("audience_id"), base, diff: yml("audience_id").diff }], { @@ -653,6 +698,26 @@ describe("doc() reference with no docs block", () => { expect(ruleIds(env.findings)).toContain("dbt-project-rules:doc-block-missing") expect(searched).toContain("docs audience_id *.md") }) + describe("end to end: docs blocks of installed packages", () => { + const solo = 'models:\n - name: orders\n description: "{{ doc(\'orders_grain\') }}"\n' + const files = [{ path: "models/orders.yml", status: "added" as const, head: solo }] + // The project keeps docs blocks of its own, but not `orders_grain`. + const grepProject = async (pattern: string) => (pattern === "docs" ? [{ path: "models/docs.md", line: 1, text: "{% docs other %}" }] : []) + test("a name an installed package defines is silent", async () => { + const env = await prReview(files, { grepProject, packageDocNames: async () => new Set(["orders_grain"]) }) + expect(ruleIds(env.findings)).not.toContain("dbt-project-rules:doc-block-missing") + }) + test("packages that can't be known (declared, not installed) keep the no-other-doc() path silent", async () => { + expect(ruleIds((await prReview(files, { grepProject, packageDocNames: async () => undefined })).findings)).not.toContain("dbt-project-rules:doc-block-missing") + expect(ruleIds((await prReview(files, { grepProject })).findings)).not.toContain("dbt-project-rules:doc-block-missing") + }) + test("no package defines it: fires, and the body says why it is trusted", async () => { + const env = await prReview(files, { grepProject, packageDocNames: async () => new Set() }) + const f = env.findings.find((x) => x.rule === "dbt-project-rules:doc-block-missing") + expect(f?.body).toContain("the project defines its own docs blocks") + expect(f?.body).not.toContain("other `doc()` references") + }) + }) }) describe("package-lock.yml added to a dbt package", () => { @@ -734,6 +799,12 @@ describe("SQL text concatenated in Jinja without a space", () => { expect(seam("{{ dbt.datediff('changed_at', 'coalesce(lead(changed_at) over (partition by ticket_id' ~ pkg.cols() ~ ' order by changed_at), now()', 'second') }}")).toBe(true) expect(seam("{{ 'select id from' ~ relation }}")).toBe(true) }) + test("double-quoted strings", () => { + expect(seam('{% set q = "select " ~ cols ~ "from " ~ rel %}')).toBe(true) + expect(seam('{% set q = "select " ~ cols ~ " from " ~ rel %}')).toBe(false) + expect(seam('{{ elementary.debug_log("column_snapshot_query - \\n" ~ column_snapshot_query) }}')).toBe(false) + expect(seam("{{ log('query: \\n' ~ q) }}")).toBe(false) + }) test("twin: the space is inside the string", () => { expect(seam("{{ dbt.datediff('changed_at', 'coalesce(lead(changed_at) over (partition by ticket_id ' ~ pkg.cols() ~ ' order by changed_at), now()', 'second') }}")).toBe(false) }) diff --git a/packages/opencode/test/altimate/review-run-stale.test.ts b/packages/opencode/test/altimate/review-run-stale.test.ts index 7623da65f3..d656e41781 100644 --- a/packages/opencode/test/altimate/review-run-stale.test.ts +++ b/packages/opencode/test/altimate/review-run-stale.test.ts @@ -159,3 +159,38 @@ describe("projectResourceNames", () => { expect(await projectAdapters(dir, "HEAD", "p")).toEqual([]) }) }) + +describe("packageDocNames", () => { + const repo = (files: Record) => { + const dir = mkdtempSync(join(tmpdir(), "pkg-docs-")) + for (const [rel, body] of Object.entries(files)) { + mkdirSync(join(dir, rel, ".."), { recursive: true }) + writeFileSync(join(dir, rel), body) + } + const git = (...x: string[]) => execFileSync("git", x, { cwd: dir, stdio: "ignore" }) + git("init", "-q") + git("add", "-A") + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + return dir + } + + test("collects docs blocks from .md files anywhere under installed dbt_packages/", async () => { + const { packageDocNames } = await import("../../src/altimate/review/run") + const dir = repo({ "p/packages.yml": "packages: []\n", "p/models/a.sql": "select 1" }) + // dbt_packages/ is installed (ignored in real repos), so it lives on disk only. + mkdirSync(join(dir, "p/dbt_packages/utils/docs/deep"), { recursive: true }) + writeFileSync(join(dir, "p/dbt_packages/utils/docs/a.md"), "{% docs order_id %}x{% enddocs %}\n{%- docs amount -%}y{% enddocs %}") + writeFileSync(join(dir, "p/dbt_packages/utils/docs/deep/b.md"), "{% docs grain %}z{% enddocs %}") + writeFileSync(join(dir, "p/dbt_packages/utils/docs/not_md.sql"), "{% docs ignored %}{% enddocs %}") + expect([...(await packageDocNames(dir, "HEAD", "p", join(dir, "p")))!].sort()).toEqual(["amount", "grain", "order_id"]) + }) + + test("no packages declared is an empty set; declared but not installed is undefined", async () => { + const { packageDocNames } = await import("../../src/altimate/review/run") + const none = repo({ "p/models/a.sql": "select 1" }) + expect(await packageDocNames(none, "HEAD", "p", join(none, "p"))).toEqual(new Set()) + const missing = repo({ "p/dependencies.yml": "projects: []\n" }) + expect(await packageDocNames(missing, "HEAD", "p", join(missing, "p"))).toBeUndefined() + expect(await packageDocNames(missing, "HEAD", undefined, join(missing, "p"))).toBeUndefined() + }) +}) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index fffd2f8a2a..514b2dcc02 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -120,6 +120,13 @@ describe("rubric", () => { expect(exclusionReason(f, DEFAULT_RUBRIC)).toContain("non-prod") }) + test("exclusion: a finding that breaks dbt parse is kept in a scratch folder", () => { + for (const rule of ["dbt-project-rules:yaml-parse-error", "dbt-project-rules:doc-block-missing"]) { + const f = makeFinding({ severity: "warning", category: "sql_correctness", title: "parse", body: "x", file: "models/base/scratch/base.yml", ruleKey: "parse", rule }) + expect(exclusionReason(f, DEFAULT_RUBRIC)).toBeNull() + } + }) + test("exclusion: SELECT * allowed in staging", () => { const f = makeFinding({ severity: "suggestion",