// altimate_change - LLM reviewer lane (transport only; prompt + parse live in core) import { Provider } from "@/provider/provider" import { LLM } from "@/session/llm" import { Agent } from "@/agent/agent" import { MessageV2 } from "@/session/message-v2" import { MessageID, SessionID } from "@/session/schema" import { Log } from "@/altimate/util/log" import { logDetail, reportFailure } from "./failure" import { Dispatcher } from "../native" import { readFile } from "node:fs/promises" import { trustedFilePath } from "./trusted-file" import { type Finding, type ReviewCategory, type Severity, makeFinding, ruleId } from "./finding" import { readStreamText } from "../llm/stream-text" import { stripUrlUserinfo } from "./format" import { redactSecrets } from "@/installation" import { type AiVerifyEvidence, type VerifierStatus, type VerifyDeps, runAiVerify } from "./ai-verify" import { aiReplayPath, runAiReplay } from "./ai-replay" import { walkDiffLines } from "./diff-filter" import type { RuleVerifierStatus } from "./ai-verify-rules" import { CARD_BATCH_CHARS_PER_FILE, CARD_BATCH_MAX_CHARS } from "./ai-context-card" import { type AiSwitches, envFlag, switchOn } from "./ai-switches" import { AI_OTHER_FILES_QUOTA, AI_OTHER_KINDS } from "./ai-other-files" import { AI_PYTHON_FILES_QUOTA, AI_PYTHON_KIND } from "./ai-python-files" import { type Convention, type ConventionRecord, conventionRecords, groupConventionFindings, renderConventions } from "./conventions" const log = Log.create({ service: "ai-review" }) /** Kinds only the AI lane reads (the `otherFiles` and `pythonFiles` switches). */ export const AI_ONLY_KINDS: ReadonlySet = new Set([...AI_OTHER_KINDS, AI_PYTHON_KIND]) const AI_TIMEOUT_BASE_MS = 60_000 const AI_TIMEOUT_MAX_MS = 300_000 const MAX_DIFF_CHARS = 6_000 // per file, keep the prompt bounded const MAX_FILES = 20 const CONTEXT_FILE_CHARS = 8_000 const CONTEXT_TOTAL_CHARS = 40_000 const BATCH_CONCURRENCY = 2 /** Per-kind file quotas under the `coverage` switch (on by default). */ const COVERAGE_QUOTAS = { model: 12, macro: 8, test: 4, yml: 6 } /** Head-side lines of context kept around each changed line in a file excerpt. */ const EXCERPT_CONTEXT_LINES = 20 /** Characters of a file's diff section under coverage (hunks beyond it are listed as omitted). */ const COVERAGE_DIFF_CHARS = 16_000 /** Current-file head kept under coverage when the diff section already carries every hunk of a long diff. */ 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 /** Characters of a seed's header sent at most. */ const SEED_ROW_CHARS = 300 /** Focused batching defaults under the `focused` switch (on by default). */ 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 * `ALTIMATE_REVIEW_AI_*` variables widen it for experiments: more files, longer * files, and a per-call size above which files are split across several calls * instead of being cut. */ export interface AiInputBudget { maxFiles: number maxFileChars: number /** Characters of file sections per call; Infinity keeps a single call (the default without coverage). */ batchChars: number /** The `coverage` switch: per-kind file quotas (replacing `maxFiles`) and * hunk-centred excerpts instead of head truncation. Undefined keeps today's input. * `otherQuota` (`otherFiles` switch): quota for other/analysis files, kept outside * `quotas` so the existing buckets and their spare are unchanged. `pythonQuota` * (`pythonFiles` switch): the same for the added Python files. */ coverage?: AiCoverageRender & { quotas: Record; otherQuota?: number; pythonQuota?: number } /** The `focused` switch: 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, switches?: Partial, ): 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) return v && Number.isInteger(n) && n >= 0 ? n : d } const coverageOn = switchOn("coverage", switches, env) return { maxFiles: num(env.ALTIMATE_REVIEW_AI_MAX_FILES, MAX_FILES), maxFileChars: num(env.ALTIMATE_REVIEW_AI_MAX_FILE_CHARS, MAX_DIFF_CHARS), batchChars: num(env.ALTIMATE_REVIEW_AI_BATCH_CHARS, coverageOn ? COVERAGE_BATCH_CHARS : Infinity), coverage: coverageOn ? { diffChars: num(env.ALTIMATE_REVIEW_AI_COVERAGE_DIFF_CHARS, COVERAGE_DIFF_CHARS), quotas: { model: quota(env.ALTIMATE_REVIEW_AI_QUOTA_MODEL, COVERAGE_QUOTAS.model), macro: quota(env.ALTIMATE_REVIEW_AI_QUOTA_MACRO, COVERAGE_QUOTAS.macro), test: quota(env.ALTIMATE_REVIEW_AI_QUOTA_TEST, COVERAGE_QUOTAS.test), yml: quota(env.ALTIMATE_REVIEW_AI_QUOTA_YML, COVERAGE_QUOTAS.yml), }, ...(switchOn("otherFiles", switches, env) ? { otherQuota: quota(env.ALTIMATE_REVIEW_AI_QUOTA_OTHER, AI_OTHER_FILES_QUOTA) } : {}), ...(switchOn("pythonFiles", switches, env) ? { pythonQuota: quota(env.ALTIMATE_REVIEW_AI_QUOTA_PYTHON, AI_PYTHON_FILES_QUOTA) } : {}), } : undefined, focused: switchOn("focused", switches, env) ? { 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, } } /** `ALTIMATE_REVIEW_AI_DRYRUN=1`: plan the lane's input and record it on the * status without calling a model (state `skipped`), for free coverage counts. An * unrecognised value fails safe: a dry run, so no paid call is made. */ export function aiDryRunEnabled(env: Record = process.env): boolean { return envFlag("ALTIMATE_REVIEW_AI_DRYRUN", { fallback: false, unrecognised: true }, env) } /** 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 envFlag("ALTIMATE_REVIEW_AI_TEST_GAP", { fallback: false }, env) } 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 /** Characters of one path listed in a prompt. */ const PROMPT_PATH_CHARS = 300 /** A repository path as one prompt line: control and line-separator characters become a space, * so a file name cannot start a line of its own (a heading, an instruction) in the message. */ export function promptPath(p: string): string { const flat = p.replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g, " ") return flat.length > PROMPT_PATH_CHARS ? flat.slice(0, PROMPT_PATH_CHARS) + "…" : flat } /** Paths as list lines (`- path`), at most `max`, then a count of the rest. */ export function promptPathList(paths: string[], max: number): string[] { const shown = paths.slice(0, max) return [...shown.map((p) => `- ${promptPath(p)}`), ...(paths.length > shown.length ? [`- … and ${paths.length - shown.length} more`] : [])] } /** The PR's changed paths a batch message does not already name, appended for the test-gap * instruction (paths only). Credential-named paths are left out here too. */ export function testGapFileList(message: string, named: AiReviewFile[], prFiles: string[] = []): string { const listed = new Set(named.map((f) => f.path)) const others = [...new Set(prFiles)].filter((p) => !listed.has(p) && !mayHoldCredentials(p)) if (!others.length) return message return [ message, "", "## OTHER FILES THIS PR CHANGES (paths only, not shown; use them to judge test coverage)", ...promptPathList(others, TEST_GAP_FILES_MAX), ].join("\n") } export interface AiReviewFile { path: string status: string /** Model name for a model; the file's base name for any other dbt file. */ model: string /** dbt role of the file (`model_sql`, `macro`, `schema_yml`, `test`, …); omitted means a model. */ kind?: string /** Unified diff (added/removed lines) for this file. */ diff?: string /** Current content: dbt-compiled (preferred) or raw SQL for a model, the file itself otherwise. */ sql?: string /** Rendered dbt manifest context card (the `contextCard` switch). */ card?: string } /** Order under the file cap: models first, then the files whose defects reach the most models. */ const KIND_ORDER = ["model_sql", "python_model", "macro", "test", "snapshot", "schema_yml", "source_yml", "seed", "project_config"] const KIND_LABEL: Record = { macro: "macro (Jinja; changes every model that calls it)", test: "singular data test", snapshot: "snapshot", schema_yml: "schema yml (tests, contracts, descriptions)", source_yml: "sources yml", seed: "seed CSV", project_config: "project config", python_model: "Python model", // Sent only with the `otherFiles` switch. analysis: "dbt analysis (compiled, not materialized)", other: "other project file", // Sent only with the `pythonFiles` switch. [AI_PYTHON_KIND]: "Python file", } const FENCE: Record = { schema_yml: "yaml", source_yml: "yaml", project_config: "yaml", seed: "csv", python_model: "python", [AI_PYTHON_KIND]: "python", } /** Code fence for a file's current content; `other`/`analysis` files by extension. */ function fenceOf(f: AiReviewFile): string { const known = FENCE[f.kind ?? ""] if (known) return known if (!AI_OTHER_KINDS.has(f.kind ?? "")) return "sql" const p = f.path.toLowerCase() return p.endsWith(".yml") || p.endsWith(".yaml") ? "yaml" : "sql" } function kindRank(kind: string | undefined): number { const i = KIND_ORDER.indexOf(kind ?? "model_sql") return i < 0 ? KIND_ORDER.length : i } function sendable(f: AiReviewFile): boolean { return f.status !== "deleted" && !!(f.diff || f.sql) } /** Files the lane sends, in priority order, capped at `maxFiles`. */ export function selectAiFiles(files: AiReviewFile[], maxFiles = MAX_FILES): AiReviewFile[] { return files .filter(sendable) .map((f, i) => ({ f, i })) .sort((a, b) => kindRank(a.f.kind) - kindRank(b.f.kind) || a.i - b.i) .map(({ f }) => f) .slice(0, maxFiles) } /** Quota buckets for `ALTIMATE_REVIEW_AI_COVERAGE`. */ export type AiFileBucket = keyof typeof COVERAGE_QUOTAS const BUCKET_OF: Record = { model_sql: "model", python_model: "model", snapshot: "model", macro: "macro", test: "test", schema_yml: "yml", source_yml: "yml", project_config: "yml", seed: "yml", } /** Buckets in the order their kinds first appear in KIND_ORDER (model, macro, test, yml). */ const BUCKET_ORDER = [...new Set(KIND_ORDER.map((k) => BUCKET_OF[k]))] /** * Added and removed lines of a unified diff that change more than whitespace * (file headers before the first hunk excluded): blank lines, and a removed * line that comes back added with only its whitespace changed, do not count, * so a reformatted file does not outrank a one-line logic change. */ export function changedLineCount(diff: string | undefined): number { if (!diff) return 0 const lines = diff.split("\n") const first = lines.findIndex((l) => l.startsWith("@@")) const squash = (l: string) => l.slice(1).replace(/\s+/g, "") // Hunk by hunk: lines re-wrapped or re-indented without other edits count for nothing. const hunks: string[][] = [[]] for (const l of lines.slice(Math.max(first, 0))) { if (l.startsWith("@@")) hunks.push([]) else if (l.startsWith("+") || l.startsWith("-")) hunks[hunks.length - 1].push(l) } let n = 0 for (const hunk of hunks) { const plus = hunk.filter((l) => l[0] === "+").map(squash) const minus = hunk.filter((l) => l[0] === "-").map(squash) if (plus.join("") === minus.join("")) continue const count = (xs: string[]) => xs.reduce((m, x) => (x ? m.set(x, (m.get(x) ?? 0) + 1) : m), new Map()) const added = count(plus) const removed = count(minus) for (const [key, a] of added) n += Math.max(0, a - (removed.get(key) ?? 0)) for (const [key, r] of removed) n += Math.max(0, r - (added.get(key) ?? 0)) } return n } /** * Files the lane sends under per-kind quotas, so models cannot crowd out the * macros, tests and yml whose defects no model diff shows. Each bucket keeps its * most-changed files (ties by input order); quota a bucket leaves unused goes to * the other buckets in KIND_ORDER order, up to the sum of the quotas. `unsent` * lists the sendable files left out, in input order. */ export function selectAiFilesByQuota( files: AiReviewFile[], quotas: Record = COVERAGE_QUOTAS, extra: { otherQuota?: number; pythonQuota?: number } = {}, ): { sent: AiReviewFile[]; unsent: AiReviewFile[] } { const eligible = files.filter(sendable) // With an `otherQuota`, other/analysis files are selected apart and appended after the rest. const isOther = (f: AiReviewFile) => extra.otherQuota !== undefined && AI_OTHER_KINDS.has(f.kind ?? "") // With a `pythonQuota`, the added Python files likewise, after the other files. const isPython = (f: AiReviewFile) => extra.pythonQuota !== undefined && f.kind === AI_PYTHON_KIND const byBucket = new Map(BUCKET_ORDER.map((b) => [b, []])) eligible .filter((f) => !isOther(f) && !isPython(f)) .map((f, i) => ({ f, i, n: changedLineCount(f.diff) })) .sort((a, b) => b.n - a.n || a.i - b.i) .forEach(({ f }) => byBucket.get(BUCKET_OF[f.kind ?? "model_sql"] ?? "model")!.push(f)) const take = new Map(BUCKET_ORDER.map((b) => [b, Math.min(quotas[b], byBucket.get(b)!.length)])) let spare = BUCKET_ORDER.reduce((n, b) => n + quotas[b], 0) - [...take.values()].reduce((n, t) => n + t, 0) // Unused quota flows to other kinds, but never into a bucket disabled with quota 0. for (const b of BUCKET_ORDER) { if (quotas[b] <= 0) continue const extra = Math.min(spare, byBucket.get(b)!.length - take.get(b)!) take.set(b, take.get(b)! + extra) spare -= extra } const sent = BUCKET_ORDER.flatMap((b) => byBucket.get(b)!.slice(0, take.get(b)!)) sent.push(...mostChanged(eligible.filter(isOther), extra.otherQuota ?? 0)) sent.push(...mostChanged(eligible.filter(isPython), extra.pythonQuota ?? 0)) const chosen = new Set(sent) return { sent, unsent: eligible.filter((f) => !chosen.has(f)) } } /** Up to `n` of `files`, most changed first (ties by input order). */ function mostChanged(files: AiReviewFile[], n: number): AiReviewFile[] { return files .map((f, i) => ({ f, i, n: changedLineCount(f.diff) })) .sort((a, b) => b.n - a.n || a.i - b.i) .slice(0, n) .map(({ f }) => f) } interface DiffHunk { text: string /** Head-side line range from the `@@` header; absent for a diff without headers. */ start?: number end?: number } /** A unified diff split into the text before its first hunk and its hunks. */ function splitHunks(diff: string): { preamble: string; hunks: DiffHunk[] } { const lines = diff.replace(/\n$/, "").split("\n") const first = lines.findIndex((l) => l.startsWith("@@")) if (first < 0) return { preamble: "", hunks: lines.length && diff ? [{ text: lines.join("\n") }] : [] } const hunks: DiffHunk[] = [] let cur: string[] = [] const flush = () => { if (!cur.length) return const m = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(cur[0]) const start = m ? Number(m[1]) : undefined const count = m ? (m[2] === undefined ? 1 : Number(m[2])) : 0 hunks.push({ text: cur.join("\n"), start, end: start === undefined ? undefined : start + Math.max(count, 1) - 1 }) cur = [] } for (const l of lines.slice(first)) { if (l.startsWith("@@")) flush() cur.push(l) } flush() return { preamble: lines.slice(0, first).join("\n"), hunks } } function lineRange(a: number, b: number): string { return a === b ? `line ${a}` : `lines ${a}–${b}` } /** What a file section carries of the file's diff and content. */ interface SectionStats { truncated: boolean hunksSent: number hunksTotal: number /** Seed data rows left out. */ rowsOmitted?: number } /** * A seed's diff as sent: the CSV header (line 1, when the diff shows it) and a * count of the rows added and removed. No data row is sent, added or removed: * seed rows can be personal data or keys. */ export function seedDiffExcerpt(diff: string): { text: string } & Omit & { rowsOmitted: number } { const lines = diff.replace(/\n$/, "").split("\n") const first = lines.findIndex((l) => l.startsWith("@@")) const body = first < 0 ? lines : lines.slice(first) const preamble = first < 0 ? [] : lines.slice(0, first) const hunkCount = body.filter((l) => l.startsWith("@@")).length const isRow = (l: string) => l.startsWith("+") || l.startsWith("-") || l.startsWith(" ") type Row = { text: string; header: boolean; changed: boolean; hunk: number } const rows: Row[] = [] const hunkHeaders: string[] = [] let oldLn = 0 let newLn = 0 for (const l of body) { const m = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(l) if (l.startsWith("@@")) { oldLn = m ? Number(m[1]) : 0 newLn = m ? Number(m[2]) : 0 hunkHeaders.push(l) continue } if (!isRow(l)) continue const kind = l[0] // Line 1 of the CSV, on either side, is the header; without hunk headers no line is known to be it. const header = first >= 0 && ((kind !== "-" && newLn === 1) || (kind !== "+" && oldLn === 1)) rows.push({ text: l, header, changed: kind !== " ", hunk: hunkHeaders.length - 1 }) if (kind !== "-") newLn++ if (kind !== "+") oldLn++ } const data = rows.filter((r) => !r.header) if (!data.length) return { text: diff, hunksSent: hunkCount, hunksTotal: hunkCount, rowsOmitted: 0 } const kept = new Set(rows.filter((r) => r.header)) const clip = (t: string) => (t.length > SEED_ROW_CHARS ? t.slice(0, SEED_ROW_CHARS) + "…" : t) const out = [...preamble] let lastHunk = -2 for (const r of rows) { if (!kept.has(r)) continue if (r.hunk !== lastHunk && r.hunk >= 0) out.push(hunkHeaders[r.hunk]) lastHunk = r.hunk out.push(clip(r.text)) } const added = data.filter((r) => r.changed && r.text.startsWith("+")).length const removed = data.filter((r) => r.changed && r.text.startsWith("-")).length const omittedChanged = data.filter((r) => r.changed && !kept.has(r)).length const omittedUnchanged = data.filter((r) => !r.changed).length out.push( `… (seed data rows omitted: ${omittedChanged} changed and ${omittedUnchanged} unchanged row(s) not sent; ` + `${added} row(s) added and ${removed} removed in this diff)`, ) const whole = new Set(rows.filter((r) => !kept.has(r)).map((r) => r.hunk)) return { text: out.join("\n"), hunksSent: Math.max(0, hunkCount - whole.size), hunksTotal: hunkCount, rowsOmitted: omittedChanged + omittedUnchanged, } } /** * Whole hunks, in order, up to `maxChars`; a hunk is never cut unless it is the * first and alone exceeds the budget (its head is kept, marked). Omitted hunks * are listed by their head-side line ranges. */ export function excerptDiff(diff: string, maxChars: number): { text: string } & SectionStats { const { preamble, hunks } = splitHunks(diff) const out = preamble ? [preamble] : [] let used = preamble.length let sent = 0 let cut = false for (const h of hunks) { if (used + h.text.length + 1 <= maxChars) { out.push(h.text) used += h.text.length + 1 sent++ continue } if (sent === 0) { const head = h.text.slice(0, Math.max(0, maxChars - used)) const nl = head.lastIndexOf("\n") out.push((nl > 0 ? head.slice(0, nl) : head) + "\n… (hunk truncated)") sent = 1 cut = true } break } const omitted = hunks.slice(sent) if (omitted.length) { const ranges = omitted.map((h) => (h.start === undefined ? "?" : lineRange(h.start, h.end!).replace(/^lines? /, ""))) out.push(`… (${omitted.length} more hunk${omitted.length === 1 ? "" : "s"} omitted, at lines ${ranges.join(", ")})`) } return { text: out.join("\n"), truncated: cut || omitted.length > 0, hunksSent: sent, hunksTotal: hunks.length } } const COMPILED_UNLOCATED_MARKER = "\n… (compiled file: changed lines not located, head shown; windows would be approximate)" const JINJA = /\{\{|\{%/ /** * Where the diff's added lines sit in `lines` when the content is not the raw * file (e.g. dbt-compiled SQL, whose line numbers drift once Jinja expands). * Returns undefined when the raw line numbers already match (or nothing can be * checked), the found line numbers when at least half of the eligible added * lines (8+ non-space chars, no Jinja) are found by text, and "unlocated" otherwise. * With no eligible added line (Jinja-only or very short changes), the context * lines decide: raw line numbers are trusted only when those match. */ function locateAddedLines(lines: string[], rows: Array<{ line: number; text: string; kind: string }>): number[] | "unlocated" | undefined { const isEligible = (r: { text: string }) => !JINJA.test(r.text) && r.text.replace(/\s/g, "").length >= 8 const matchesRaw = (r: { line: number; text: string }) => lines[r.line - 1]?.trim() === r.text.trim() const eligible = rows.filter((r) => r.kind === "+" && isEligible(r)) if (!eligible.length) { const context = rows.filter((r) => r.kind !== "+" && isEligible(r)) return context.length && !context.every(matchesRaw) ? "unlocated" : undefined } if (eligible.every(matchesRaw)) return undefined const found: number[] = [] const used = new Set() let from = 0 for (const r of eligible) { const want = r.text.trim() let at = -1 for (let i = from; i < lines.length; i++) if (!used.has(i) && lines[i].trim() === want) { at = i break } if (at < 0) continue used.add(at) found.push(at + 1) from = at + 1 } return found.length * 2 >= eligible.length ? found : "unlocated" } /** * The parts of a file around its changed lines (±20 head-side lines each, * merged), up to `maxChars`, then as much of the file head as still fits. * Gaps are marked with their real line numbers. Without changed lines the file * head is kept, as before. When the content is not the raw file (compiled SQL), * windows are anchored on the added lines' text instead of raw line numbers. */ export function excerptFile(content: string, diff: string | undefined, maxChars: number): { text: string; truncated: boolean } { if (content.length <= maxChars) return { text: content, truncated: false } const lines = content.split("\n") const n = lines.length const rows = [...walkDiffLines(diff)] const located = locateAddedLines(lines, rows) if (located === "unlocated") return { text: truncate(content, maxChars) + COMPILED_UNLOCATED_MARKER, truncated: true } const added = located ?? rows.filter((r) => r.kind === "+").map((r) => r.line) const anchors = (added.length ? added : rows.map((r) => r.line)).filter((l) => l >= 1 && l <= n).sort((a, b) => a - b) if (!anchors.length) return { text: truncate(content, maxChars), truncated: true } const windows: Array<[number, number]> = [] for (const a of anchors) { const s = Math.max(1, a - EXCERPT_CONTEXT_LINES) const e = Math.min(n, a + EXCERPT_CONTEXT_LINES) const last = windows[windows.length - 1] if (last && s <= last[1] + 1) last[1] = Math.max(last[1], e) else windows.push([s, e]) } const MARKER = 40 // room reserved per omission marker const size = (s: number, e: number) => lines.slice(s - 1, e).reduce((t, l) => t + l.length + 1, 0) const kept: Array<[number, number]> = [] let used = 0 for (const [s, e] of windows) { const sz = size(s, e) + MARKER if (used + sz <= maxChars) { kept.push([s, e]) used += sz continue } if (!kept.length) { // The first window alone is over budget: keep as many of its lines as fit. let end = s - 1 while (end < e && used + size(s, end + 1) + MARKER <= maxChars) end++ if (end >= s) { kept.push([s, end]) used += size(s, end) + MARKER } } break } if (!kept.length) return { text: truncate(content, maxChars), truncated: true } // Fill what is left with the file head, before the first window. let head = 0 while (head + 1 < kept[0][0] && used + size(1, head + 1) + MARKER <= maxChars) head++ if (head) { if (head + 1 >= kept[0][0]) kept[0][0] = 1 else kept.unshift([1, head]) } const out: string[] = [] let next = 1 for (const [s, e] of kept) { if (s > next) out.push(`… (${lineRange(next, s - 1)} omitted)`) out.push(lines.slice(s - 1, e).join("\n")) next = e + 1 } if (next <= n) out.push(`… (${lineRange(next, n)} omitted)`) return { text: out.join("\n"), truncated: true } } /** Hunks of `diff` whose text lies wholly within its first `maxChars` characters. */ function headHunkStats(diff: string | undefined, maxChars: number): Omit { if (!diff) return { hunksSent: 0, hunksTotal: 0 } const { preamble, hunks } = splitHunks(diff) let end = preamble ? preamble.length + 1 : 0 let sent = 0 for (const h of hunks) { end += h.text.length if (end > maxChars) break sent++ end += 1 } return { hunksSent: sent, hunksTotal: hunks.length } } /** How coverage mode renders a file: the diff section's own character budget. */ export interface AiCoverageRender { diffChars: number } /** `true` means coverage with the default diff budget; `false` keeps today's rendering. */ type CoverageArg = boolean | AiCoverageRender | undefined function coverageRender(c: CoverageArg): AiCoverageRender | undefined { if (!c) return undefined return c === true ? { diffChars: COVERAGE_DIFF_CHARS } : c } /** One changed file as it appears in the prompt, with what it carries. */ function renderFile(f: AiReviewFile, maxChars: number, coverageArg: CoverageArg, withCard: boolean): { text: string } & SectionStats { const coverage = coverageRender(coverageArg) const label = f.kind && KIND_LABEL[f.kind] const isModel = !f.kind || f.kind === "model_sql" || f.kind === "python_model" // Supporting files are masked here too, whoever built the input (the orchestrator already does). const text = (t: string) => (isModel ? t : maskForAi(t)!) const parts = [`\n### ${f.path} (${f.status}${label ? `, ${label}` : ""})`] if (withCard && f.card) parts.push(`dbt context (from manifest):\n${maskForAi(f.card)}`) // What the provider gets is the masked text, so sizes and cuts are measured on it. const diff = f.diff ? text(f.diff) : undefined let stats: SectionStats = { ...headHunkStats(diff, maxChars), truncated: (diff?.length ?? 0) > maxChars } // Under coverage a long diff sent whole makes the file windows redundant: keep a short head instead. let fileChars = maxChars if (diff && f.kind === "seed") { // Seeds: the header and a few changed rows, within the default per-file budget in every mode. const { text: excerpt, ...ex } = seedDiffExcerpt(diff) stats = { ...ex, truncated: ex.rowsOmitted > 0 || excerpt.length > maxChars } parts.push("Diff:\n```diff\n" + truncate(excerpt, maxChars) + "\n```") } else if (diff) { if (coverage && diff.length > maxChars) { const { text: excerpt, ...ex } = excerptDiff(diff, coverage.diffChars) stats = ex if (ex.hunksSent === ex.hunksTotal && !ex.truncated) fileChars = Math.min(COVERAGE_FULL_DIFF_FILE_CHARS, maxChars) parts.push("Diff:\n```diff\n" + excerpt + "\n```") } else parts.push("Diff:\n```diff\n" + truncate(diff, maxChars) + "\n```") } // A seed's content is data: only its diff excerpt goes. if (f.sql && f.kind !== "seed") { const sql = text(f.sql) const body = !coverage ? truncate(sql, maxChars) : fileChars < maxChars ? truncate(sql, fileChars) : excerptFile(sql, f.diff, maxChars).text if (sql.length > fileChars) stats = { ...stats, truncated: true } parts.push(`${isModel ? "Current SQL" : "Current file"}:\n\`\`\`${fenceOf(f)}\n` + body + "\n```") } return { text: parts.join("\n"), ...stats } } function fileSection(f: AiReviewFile, maxChars: number, coverage: CoverageArg = false): string { return renderFile(f, maxChars, coverage, true).text } /** Split files, in order, into groups whose sections fit `batchChars` (an oversized file goes alone). */ export function batchAiFiles(files: AiReviewFile[], budget: AiInputBudget): AiReviewFile[][] { const batches: AiReviewFile[][] = [] let cur: AiReviewFile[] = [] let size = 0 for (const f of files) { const n = fileSection(f, budget.maxFileChars, budget.coverage).length if (cur.length && size + n > budget.batchChars) { batches.push(cur) cur = [] size = 0 } cur.push(f) size += n } if (cur.length) batches.push(cur) 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 } /** An unchanged file the changed ones depend on (dbt DAG parent), sent as read-only context. */ export interface AiContextFile { path: string /** dbt resource type: `model`, `seed`, `snapshot`, `source`, `macro`. */ kind: string name: string /** Changed files that depend on it. */ forPaths: string[] content: string } export interface AiReviewInput { files: AiReviewFile[] /** Unchanged parents of the changed files, for cross-file checks (columns, seeds, macro signatures). */ context?: AiContextFile[] /** Deterministic engine findings — grounding the AI must NOT duplicate. */ grounding: Finding[] prTitle?: string prBody?: string /** Explicit `provider/model`; omit to use the configured default model. */ model?: string /** What the verifier may read; it runs only when this is set and the `verify` switch is on. */ evidence?: AiVerifyEvidence /** The engine findings the reader will see (after the severity threshold and * the posting policy, without pre-existing ones): what the verifier treats * as already reported. Defaults to `grounding`. */ shownGrounding?: Finding[] /** Every file the PR changes (repo-relative), including files outside the dbt project. */ prFiles?: string[] /** The review's resolved AI switches; without them each switch reads only its env variable. */ switches?: Partial /** Files of an AI-only kind (other/analysis) a deterministic lane also checked: listed in * `unsent` when the quotas keep them from the model, since the coverage ledger does not list them. */ checkedPaths?: string[] /** The review's repository (`--cwd`): files named by env variables must be outside it. */ reviewDir?: string /** Team conventions from the base branch (`conventions` switch); each call carries those for its files. */ conventions?: Convention[] } /** What happened in the advisory lane, reported on the envelope and in the comment. */ export type AiLaneState = "ok" | "skipped" | "timeout" | "error" export interface AiLaneStatus { state: AiLaneState /** Why the lane was skipped or failed (never contains credentials). */ reason?: string /** `provider/model` the lane ran with. */ model?: string durationMs?: number /** Tokens spent across all calls that reported usage. */ tokens?: AiTokens /** Estimated cost in USD from the model's price table (0 when unpriced). */ cost?: number /** Model calls made (one per batch). */ calls?: number /** The dbt-grounded verifier's outcome, when it ran (the `verify` switch). */ verifier?: VerifierStatus /** The generator's findings came from an earlier envelope (`ALTIMATE_REVIEW_AI_REPLAY`); * tokens, cost and calls are that run's, so only `verifier` was spent now. */ replayed?: boolean /** The replayed envelope did not list every generator finding. */ replayIncomplete?: boolean /** What each file sent carried; recorded under coverage, context cards or dry run. */ input?: AiInputRecord[] /** Sendable files left out by the coverage quotas (not reviewed by the AI; the deterministic lanes are unaffected). * Files only the AI lane reads (other/analysis, Python) are not listed, unless a deterministic * lane checked them (`checkedPaths`): the coverage ledger has the rest. */ unsent?: string[] /** Files never sent to the provider (symlink, credential name on the new or old path, key material). */ notSent?: string[] /** The same files, each with the fixed reason. */ notSentReasons?: Array<{ path: string; reason: "symlink" | "credential_name" | "key_material" }> /** Reviewed files the model saw cut to fit (later hunks or file text left out). */ truncated?: string[] /** Files whose dbt context card could not be built (sent without one). */ cardsFailed?: number /** Calls that failed (threw, timed out, or answered without a usable finding); set when any did. */ failedCalls?: number /** A call's answer held more findings than the core parser keeps per call; the rest were dropped. */ capped?: boolean /** Findings of usable answers that named a file outside their call: dropped (the answer stays usable). */ foreignDropped?: number /** Files in the failed calls (all of them when every call failed): not reviewed by the AI. */ unreviewed?: string[] /** The team convention files from the base commit (no text): loaded and skipped. */ conventions?: ConventionRecord[] /** The not-posted rule list applied on files the lane reviewed (rules-off.ts). */ notPosted?: { source: "default" | "file"; rules: string[]; error?: string } /** The rule verifier's outcome (ai-verify-rules.ts), set by the orchestrator. */ ruleVerifier?: RuleVerifierStatus } /** One file as sent to the model. */ export interface AiInputRecord { path: string kind: string /** Characters of the file's prompt section. */ chars: number /** Some of the diff or file content was left out. */ truncated: boolean hunksSent: number hunksTotal: number /** A manifest context card went with the file. */ card: boolean /** The file had a card, left out for the per-call card budget. */ cardOmitted?: boolean /** Seed data rows not sent (only the header and a few changed rows are). */ rowsOmitted?: number /** Index of the call that carried the file; set only under focused batching. */ batch?: number /** The call that carried the file failed: the AI did not review it. */ failed?: boolean /** Convention paths the call carried; set on the first file of each call that carried any. */ conventions?: string[] } /** Token counts as `Session.getUsage` reports them: `input` excludes cached * tokens, `inputTotal` includes them. */ export interface AiTokens { input: number inputTotal: number output: number reasoning: number cacheRead: number } export interface AiReviewResult { findings: Finding[] status: AiLaneStatus /** Files in the calls that answered: the ones the AI actually reviewed. */ reviewedPaths?: string[] } /** Why the lane skipped when no model is configured. */ export const NO_DEFAULT_MODEL = "no AI provider or model is configured; configure one, or pass --no-ai to turn the AI review off" /** Timeout scaled to the prompt: 60 s plus 1 s per 2,000 characters, capped at 5 minutes. */ export function aiTimeoutMs(promptChars: number): number { return Math.min(AI_TIMEOUT_MAX_MS, AI_TIMEOUT_BASE_MS + Math.ceil(promptChars / 2_000) * 1_000) } /** A supporting file's text (packages.yml, dbt_project.yml, yml, macros) as sent * to the AI provider: URL userinfo removed and credential-shaped values masked. */ export function maskForAi(text: string | undefined): string | undefined { if (text === undefined) return undefined return redactSecrets(stripUrlUserinfo(text)) .replace(PASSPHRASE_VALUE, (whole, key: string, sep: string, q: string, value: string) => value.startsWith("[REDACTED") ? whole : `${key}${sep}${q}[REDACTED]`, ) .replace(ODBC_PWD, "$1$2[REDACTED]") } /** A value after a `*passphrase` key (`private_key_passphrase: …`). */ const PASSPHRASE_VALUE = /\b([A-Za-z0-9_.-]*passphrase)(["']?\s*[:=]\s*)(["']?)([^\s"',}\]]+)/gi /** An ODBC connection-string password (`PWD=…;`, braced or bare). */ const ODBC_PWD = /\b(PWD)(\s*=\s*)(\{[^}]*\}|[^;\s"']+)/gi /** An AWS access key id (opt-in files: it has no lower case, so the opaque-word rule misses it). */ const AWS_KEY_ID = /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g /** A diff with its removed lines dropped: the header, hunk headers, context and * added lines only. Used for opt-in file kinds, whose old side is never sent. */ export function newSideDiff(diff: string | undefined): string | undefined { if (diff === undefined) return undefined let inHunk = false return diff .split("\n") .filter((l) => { if (l.startsWith("@@")) inHunk = true // Before the first hunk only the file header (`--- a/…`) can start with `-`. return inHunk ? !l.startsWith("-") : !l.startsWith("-") || l.startsWith("--- ") }) .join("\n") } /** A value after a key whose name says it holds a secret (`API_KEY = …`, `key: …`, `db_password: …`). */ const KEYED_SECRET = /\b([A-Za-z0-9_.-]*(?:key|secret|token|passw(?:or)?d|pwd|credential)s?)(["']?\s*[:=]\s*)(["']?)([^\s"',}\]]+)/gi /** A long opaque word: 20+ token characters (base64 padding at the end). */ const OPAQUE_WORD = /[A-Za-z0-9+/_-]{20,}={0,2}/g /** * The text of an opt-in file (`otherFiles`, `pythonFiles`) as sent: `maskForAi`, then every * value after a secret-named key and every credential-shaped word (20+ characters with a * digit and mixed case, or `+`, `/`, `=`) masked too. These files (scripts, DAGs, config * yml, analyses) commonly hard-code tokens with no `password:` key, so the stricter mask * applies; a long mixed-case identifier with a digit is masked as well. */ export function maskOptInFile(text: string | undefined): string | undefined { if (text === undefined) return undefined return maskForAi(text)! .replace(KEYED_SECRET, (whole, key: string, sep: string, q: string, value: string) => value.startsWith("[REDACTED") ? whole : `${key}${sep}${q}[REDACTED]`, ) .replace(OPAQUE_WORD, (w) => (/\d/.test(w) && ((/[a-z]/.test(w) && /[A-Z]/.test(w)) || /[+/=]/.test(w)) ? "[REDACTED]" : w)) .replace(AWS_KEY_ID, "[REDACTED]") } /** File names that can hold credentials, in any directory: connection profiles (any yml * name holding `profiles`), env files, keys, netrc-style files, and a file or directory named * `secret(s)` / `credential(s)`, alone or joined to other words by `.`, `_` or `-` * (`secret.yml`, `dbt_credentials.yml`, `secrets/conn.sql`). Matched case-insensitively. */ const CREDENTIAL_FILE = /(^|\/)([^/]*profiles[^/]*\.ya?ml|\.env[^/]*|[^/]*\.pem|[^/]*\.key|id_rsa[^/]*|\.netrc|\.pgpass)$|(^|\/)([^/]*[._-])?(secrets?|credentials?)([._-][^/]*)?(\/|$)/i /** Whether a file's name says it can hold credentials; its content never goes to the AI provider. */ export function mayHoldCredentials(path: string): boolean { return CREDENTIAL_FILE.test(path.replace(/\\/g, "/")) } /** Whether a file's content holds a private key (PEM, PGP block, PuTTY key file) or a * service-account key (JSON, escaped JSON, single-quoted or YAML). */ export function holdsCredentials(text: string | undefined): boolean { if (!text) return false return ( /-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----/.test(text) || /^PuTTY-User-Key-File-\d+:/m.test(text) || (SA_TYPE.test(text) && SA_PRIVATE_KEY.test(text)) ) } /** `type: service_account` in JSON (plain, escaped or single-quoted) or YAML. */ const SA_TYPE = /["'\\]*\btype["'\\]*\s*:\s*["'\\]*service_account\b/ /** A `private_key` field in the same shapes. */ const SA_PRIVATE_KEY = /["'\\]*\bprivate_key["'\\]*\s*:/ /** Settle with `work`, or reject as soon as `signal` aborts. The work itself * is not cancelled: a provider that ignores the abort signal cannot hang the caller. */ export function untilAborted(work: Promise | (() => Promise), signal: AbortSignal): Promise { if (signal.aborted) return Promise.reject(signal.reason ?? new Error("aborted")) const p = typeof work === "function" ? work() : work return new Promise((resolve, reject) => { const onAbort = () => reject(signal.reason ?? new Error("aborted")) signal.addEventListener("abort", onAbort, { once: true }) p.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)) }) } /** Every balanced `[...]` in `text` that parses as a JSON array, in order; * brackets inside JSON strings are skipped. `` blocks and code fences are removed first. */ export function jsonArrays(text: string): unknown[][] { const cleaned = text.replace(/[\s\S]*?<\/think>/gi, "").replace(/```[a-z]*\n?/gi, "") const out: unknown[][] = [] for (let start = cleaned.indexOf("["); start >= 0; start = cleaned.indexOf("[", start + 1)) { let depth = 0 let inString = false for (let i = start; i < cleaned.length; i++) { const c = cleaned[i] if (inString) { if (c === "\\") i++ else if (c === '"') inString = false continue } if (c === '"') inString = true else if (c === "[") depth++ else if (c === "]" && --depth === 0) { try { const v = JSON.parse(cleaned.slice(start, i + 1)) if (Array.isArray(v)) { out.push(v) // Arrays nested in this one are part of it. start = i } } catch { // not JSON: try the next "[" } break } } } return out } /** Upper bound for the whole AI lane (finder and verifier), in milliseconds. */ export const AI_LANE_TIMEOUT_MS = 900_000 /** The lane deadline: `ALTIMATE_REVIEW_AI_LANE_TIMEOUT_MS`, else 15 minutes. */ export function aiLaneTimeoutMs(env: Record = process.env): number { const n = Number(env.ALTIMATE_REVIEW_AI_LANE_TIMEOUT_MS) return env.ALTIMATE_REVIEW_AI_LANE_TIMEOUT_MS && Number.isFinite(n) && n > 0 ? n : AI_LANE_TIMEOUT_MS } /** Why work the lane deadline cut off was not reviewed (fixed text). */ export const LANE_DEADLINE_REASON = "the AI review ran out of time; the remaining files were not reviewed" /** Test seams for `runAiReview`: timeouts and the verifier's dependencies. */ export interface AiReviewDeps { /** Overrides the lane deadline. */ laneTimeoutMs?: number /** Overrides each finder call's timeout. */ callTimeoutMs?: number verify?: VerifyDeps } /** * IP boundary: the reviewer's system prompt (its remit + "what NOT to flag" * guardrails + output contract) and the response parse/clamp logic live in the * compiled core (`altimate_core.review_ai_*`), not in this public file. This * module only does TRANSPORT — assemble the user message, run the LLM through * the harness, and hand the raw response back to core to parse and clamp. */ function truncate(s: string | undefined, n: number): string { if (!s) return "" return s.length > n ? s.slice(0, n) + "\n… (truncated)" : s } /** Context sections for the parents of the files in this call, within the context budget. */ function relatedContext(input: AiReviewInput): string[] { const paths = new Set(input.files.map((f) => f.path)) const out: string[] = [] let used = 0 for (const c of input.context ?? []) { if (paths.has(c.path) || !c.forPaths.some((p) => paths.has(p))) continue // Anything but a model's SQL is masked like the changed supporting files. const content = c.kind === "model" ? c.content : maskForAi(c.content)! const section = `\n### ${c.path} (${c.kind} \`${c.name}\`, used by ${c.forPaths.filter((p) => paths.has(p)).join(", ")})\n\`\`\`${c.kind === "source" || c.path.endsWith(".yml") ? "yaml" : c.path.endsWith(".csv") ? "csv" : "sql"}\n${truncate(content, CONTEXT_FILE_CHARS)}\n\`\`\`` if (used + section.length > CONTEXT_TOTAL_CHARS) break out.push(section) used += section.length } return out } /** Assemble the user message (mechanical formatting — not IP). */ export function buildUserMessage(input: AiReviewInput, maxFileChars = MAX_DIFF_CHARS, coverage: CoverageArg = false): string { return buildBatchMessage(input, maxFileChars, coverage).message } /** 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 stay within the per-call card budget * (6,000 characters, or 400 per file in the call if more); a card that would pass it * is skipped (recorded as `cardOmitted`) and later, smaller ones may still fit. */ 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)}`) // 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):", ...grounding.slice(0, 40).map((f) => `- [${f.severity}] ${f.category} · ${f.file}: ${f.title}`), ) } else { parts.push("\n## GROUNDING — the engine produced no findings.") } // The team conventions that apply to this call's files, within the per-call conventions budget. // Masked like every other supporting text sent to the provider. const conventions = input.conventions?.length ? renderConventions(input.conventions, input.files.map((f) => f.path)) : undefined if (conventions?.text) parts.push(maskForAi(conventions.text)!) parts.push("\n## CHANGED FILES (review for what the engine missed):") let cardChars = 0 const cardBudget = Math.max(CARD_BATCH_MAX_CHARS, CARD_BATCH_CHARS_PER_FILE * input.files.length) for (const f of input.files) { const withCard = !!f.card && cardChars + f.card.length <= cardBudget if (withCard) cardChars += f.card!.length const r = renderFile(f, maxFileChars, coverage, withCard) parts.push(r.text) records.push({ path: f.path, kind: f.kind ?? "model_sql", chars: r.text.length, truncated: r.truncated, hunksSent: r.hunksSent, hunksTotal: r.hunksTotal, card: withCard, ...(f.card && !withCard ? { cardOmitted: true } : {}), ...(r.rowsOmitted ? { rowsOmitted: r.rowsOmitted } : {}), ...(focus ? { batch: focus.batch } : {}), }) } if (conventions?.paths.length && records.length) records[0].conventions = conventions.paths 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) => `- ${promptPath(f.path)} (${f.kind ?? "model_sql"})`), ...(focus.others.length > FOCUS_OTHER_FILES ? [`- … and ${focus.others.length - FOCUS_OTHER_FILES} more`] : []), ) } const context = relatedContext(input) if (context.length) { parts.push( "\n## RELATED FILES — unchanged dbt parents of the changed files (context only; comment on the changed files, not these):", ...context, ) } parts.push("\nReturn ONLY the JSON array per the output contract.") return { message: parts.join("\n"), records } } /** * The finder's system prompt: the compiled core's, or the text of the file named by * `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE`, which replaces it. An unreadable or empty file is * an error, never a silent fallback to the core prompt. The path must be absolute and must * neither resolve (symlinks followed) nor be named inside the review's repository or the * process's work tree (in CI the PR checkout), so a PR cannot choose the prompt (`trustedFilePath`). */ export async function finderSystemPrompt( env: Record = process.env, reviewDir?: string, ): Promise { const file = env.ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE if (file) { const real = trustedFilePath("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", file, [reviewDir]) const text = await readFile(real, "utf8") if (!text.trim()) throw new Error("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE is empty") return text } const promptRes = await Dispatcher.call("altimate_core.review_ai_prompt", {}) return ((promptRes.data ?? {}) as Record).prompt as string | undefined } /** What the lane would send: files, the unsent rest, one message per call, and a record per file. */ export interface AiInputPlan { budget: AiInputBudget files: AiReviewFile[] /** Sendable files left out (by the quotas under coverage, by `maxFiles` otherwise). */ unsent: AiReviewFile[] batches: AiReviewFile[][] messages: string[] input: AiInputRecord[] /** Focused batching applied (the `focused` switch and enough files). */ focused: boolean } /** * Plan the lane's input without calling a model: selection, batching, the exact * user messages and what each file carries. Pure: the budget comes from the * `env` argument; `runAiReview` sends exactly these messages. */ export function planAiInput(input: AiReviewInput, env: Record = process.env): AiInputPlan { const budget = aiInputBudget(env, input.switches) let files: AiReviewFile[] let unsent: AiReviewFile[] if (budget.coverage) ({ sent: files, unsent } = selectAiFilesByQuota(input.files, budget.coverage.quotas, budget.coverage)) else { files = selectAiFiles(input.files, budget.maxFiles) const chosen = new Set(files) unsent = input.files.filter((f) => sendable(f) && !chosen.has(f)) } const focused = !!budget.focused && files.length >= budget.focused.minFiles const batches = focused ? packFocusedBatches(groupAiFiles(files), budget) : files.length ? batchAiFiles(files, budget) : [] const testGap = aiTestGapEnabled(env) const built = batches.map((b, i) => { const others = files.filter((f) => !b.includes(f)) const focus = focused ? { batch: i, others } : undefined const out = buildBatchMessage({ ...input, files: b }, budget.maxFileChars, budget.coverage, focus) // Paths the message already names: the call's files and, focused, the other files it lists. const named = focused ? [...b, ...others.slice(0, FOCUS_OTHER_FILES)] : b return testGap ? { ...out, message: testGapFileList(out.message, named, input.prFiles) } : out }) return { budget, files, unsent, batches, messages: built.map((b) => b.message), input: built.flatMap((b) => b.records), focused } } /** * Run the LLM reviewer lane. Returns advisory findings (severity ≤ warning, * clamped by core) and a status saying whether the lane ran, was skipped, timed * out or failed. Never throws — a review must not crash because the AI layer is * unavailable — but never fails silently either: the status reaches the * envelope and the PR comment. */ export async function runAiReview(input: AiReviewInput, deps: AiReviewDeps = {}): Promise { // One deadline for the whole lane: a provider that never answers cannot hold the review. const lane = new AbortController() const laneTimer = setTimeout(() => lane.abort(), deps.laneTimeoutMs ?? aiLaneTimeoutMs()) try { return await runAiLane(input, deps, lane.signal) } finally { clearTimeout(laneTimer) } } async function runAiLane(input: AiReviewInput, deps: AiReviewDeps, laneSignal: AbortSignal): Promise { const verifyDeps: VerifyDeps = { ...deps.verify, abort: laneSignal } const replay = aiReplayPath() const startedAt = Date.now() let plan: AiInputPlan try { plan = planAiInput(input) } catch (err) { return { findings: [], status: { state: "error", reason: reportFailure("ai_error", { check: "input" }, err).message, durationMs: Date.now() - startedAt }, } } const { files, budget } = plan const dryRun = aiDryRunEnabled() // Recorded under coverage, focused batching, context cards or dry run (all on by default); // `conventions` whenever the base has instruction files (the `conventions` switch, on by default). // Files only the AI lane reads are listed by the coverage ledger, unless a deterministic lane checked them. const checked = new Set(input.checkedPaths ?? []) const unsent = plan.unsent.filter((f) => !AI_ONLY_KINDS.has(f.kind ?? "") || checked.has(f.path)).map((f) => f.path) const recorded: Pick = { ...(budget.coverage || dryRun || plan.focused || plan.input.some((r) => r.card) ? { input: plan.input } : {}), ...(budget.coverage && unsent.length ? { unsent } : {}), ...(input.conventions?.length ? { conventions: conventionRecords(input.conventions) } : {}), } const done = (findings: Finding[], status: Omit): AiReviewResult => ({ findings, status: { ...status, ...recorded, durationMs: Date.now() - startedAt }, }) if (!files.length && (dryRun || !replay)) return done([], { state: "skipped", reason: plan.unsent.length ? "every changed dbt file is over the AI file quotas" : "no changed dbt files to review", }) // Dry run wins over replay: a replayed envelope would still reach the verifier, a model call. if (dryRun) return done([], { state: "skipped", reason: "dry run (ALTIMATE_REVIEW_AI_DRYRUN=1): no model call" }) if (replay) { // The replayed findings get the same convention record and grouping as a live run. const r = await runAiReplay(input, replay, verifyDeps) if (!input.conventions?.length) return r return { ...r, findings: groupConventionFindings(r.findings, input.conventions), status: { ...r.status, conventions: conventionRecords(input.conventions) } } } let modelLabel: string | undefined try { // The file named by ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE when set, else the compiled core's prompt. // A refused or unreadable file is reported by fixed text; its path and error go to the job log. let corePrompt: string | undefined try { corePrompt = await finderSystemPrompt(process.env, input.reviewDir) } catch (err) { const check = process.env.ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE ? "system_prompt" : "request" return done([], { state: "error", reason: reportFailure("ai_error", { check }, err).message }) } if (!corePrompt) return done([], { state: "error", reason: "the core reviewer prompt is unavailable" }) const system = aiTestGapEnabled() ? corePrompt + TEST_GAP_INSTRUCTION : corePrompt let model: Awaited> let chosen: ReturnType try { chosen = input.model ? Provider.parseModel(input.model) : await Provider.defaultModel() } catch (err) { // Nothing configured is a skip, and saying how to fix it is more use than // a log line. Any other failure to pick the model is an error. // Without a model nothing was sent: the input record is left out, so the envelope is // the same whichever input switches are on. if (!input.model && err instanceof Error && /^no (providers|models) found$/.test(err.message)) return { findings: [], status: { state: "skipped", reason: NO_DEFAULT_MODEL, durationMs: Date.now() - startedAt } } return done([], { state: "error", reason: reportFailure("ai_error", { check: "model" }, err).message, model: input.model }) } try { model = await Provider.getModel(chosen.providerID, chosen.modelID) } catch (err) { // A model that is configured (explicitly or as the default) but cannot be // resolved is an error, not the same as `--no-ai`. return done([], { state: "error", reason: reportFailure("ai_error", { check: "model" }, err).message, model: input.model ?? `${chosen.providerID}/${chosen.modelID}`, }) } modelLabel = `${model.providerID}/${model.id}` // One call per batch; a PR that fits the budget is a single call, as before. const batches = plan.batches const results: BatchResult[] = [] for (let i = 0; i < batches.length; i += BATCH_CONCURRENCY) { const slice = batches.slice(i, i + BATCH_CONCURRENCY) // Past the lane deadline no new call starts; those files stay not reviewed. if (laneSignal.aborted) { results.push(...slice.map((): BatchResult => ({ findings: [], state: "timeout", reason: LANE_DEADLINE_REASON }))) continue } results.push( ...(await Promise.all(slice.map((b, j) => reviewBatch(plan.messages[i + j], b, system, model, laneSignal, deps.callTimeoutMs)))), ) } let findings = results.flatMap((r) => r.findings) // A call failed when it threw, timed out, or answered with no findings list // (empty, prose, refusal, malformed): its files were not reviewed. const failed = results.filter((r) => r.state !== "ok") const unreviewed = batches.flatMap((b, i) => (results[i].state === "ok" ? [] : b.map((f) => f.path))) log.info("ai review complete", { findings: findings.length, batches: batches.length, failed: failed.length }) if (unreviewed.length && recorded.input) { const lost = new Set(unreviewed) recorded.input = recorded.input.map((r) => (lost.has(r.path) ? { ...r, failed: true } : r)) } // The lane is ok when any call answered; a partial failure is reported with its files, not hidden. const spent = laneUsage(results) const failedCalls = failed.length ? { failedCalls: failed.length } : {} if (failed.length === results.length) return done([], { state: failed[0].state, reason: failed[0].reason, model: modelLabel, ...spent, ...failedCalls, ...(unreviewed.length ? { unreviewed } : {}) }) const reason = failed.length ? `${failed.length} of ${results.length} calls failed: ${failed[0].reason}` : undefined const reviewedPaths = batches.flatMap((b, i) => (results[i].state === "ok" ? b.map((f) => f.path) : [])) // Files the model saw cut (later hunks or file text left out): reviewed, but not whole. const cut = new Set(plan.input.filter((r) => r.truncated).map((r) => r.path)) const truncated = reviewedPaths.filter((p) => cut.has(p)).sort() const cappedCalls = results.filter((r) => r.state === "ok" && r.capped).length const foreignDropped = results.reduce((n, r) => n + (r.state === "ok" ? (r.foreign ?? 0) : 0), 0) // Try to refute each finding with dbt evidence (the `verify` switch). Never throws. let verifier: VerifierStatus | undefined if (input.evidence && switchOn("verify", input.switches)) { const v = await runAiVerify( { findings, grounding: input.shownGrounding ?? input.grounding, evidence: input.evidence, model }, verifyDeps, ) findings = v.findings verifier = v.status } // One comment for one convention broken the same way on several files. if (input.conventions?.length) findings = groupConventionFindings(findings, input.conventions) return { ...done(findings, { state: "ok", model: modelLabel, ...(reason ? { reason } : {}), ...spent, ...failedCalls, ...(cappedCalls ? { capped: true } : {}), ...(foreignDropped ? { foreignDropped } : {}), ...(unreviewed.length ? { unreviewed } : {}), ...(truncated.length ? { truncated } : {}), ...(verifier ? { verifier } : {}), }), reviewedPaths, } } catch (err) { return done([], { state: "error", reason: reportFailure("ai_error", { check: "request" }, err).message, model: modelLabel }) } } interface BatchResult { findings: Finding[] state: AiLaneState reason?: string usage?: BatchUsage /** Core kept its maximum number of findings and the answer held more. */ capped?: boolean /** Items of a usable answer that named a file outside the call: dropped. */ foreign?: number } /** Items of the answer's findings array that name a file outside `valid` (the core parser drops them). */ function foreignItems(text: string, valid: ReadonlyMap): number { const arrays = jsonArrays(text).filter((a) => a.length && a.every((v) => !!v && typeof v === "object" && !Array.isArray(v))) const items = arrays.sort((a, b) => b.length - a.length)[0] ?? [] return items.filter((v: any) => !valid.has(String(v?.file ?? ""))).length } /** Most findings the core parser keeps from one call's answer. */ export const CORE_FINDINGS_PER_CALL = 8 /** Whether an answer is exactly an empty JSON array (after `` blocks and code fences). */ export function isEmptyAnswer(text: string): boolean { return /^\[\s*\]$/.test(text.replace(/[\s\S]*?<\/think>/gi, "").replace(/```[a-z]*\n?/gi, "").trim()) } /** Items in the answer's longest JSON array of objects (0 when it has none). */ function answerItems(text: string): number { return Math.max(0, ...jsonArrays(text).filter((a) => a.every((v) => !!v && typeof v === "object" && !Array.isArray(v))).map((a) => a.length)) } export interface BatchUsage { tokens: AiTokens cost: number } export function addUsage(a: BatchUsage, b: BatchUsage): BatchUsage { return { tokens: { input: a.tokens.input + b.tokens.input, inputTotal: a.tokens.inputTotal + b.tokens.inputTotal, output: a.tokens.output + b.tokens.output, reasoning: a.tokens.reasoning + b.tokens.reasoning, cacheRead: a.tokens.cacheRead + b.tokens.cacheRead, }, cost: a.cost + b.cost, } } /** Lane-status accounting fields for a set of batch results: calls made, and * tokens and cost summed over the calls that reported usage. */ export function laneUsage(results: Array<{ usage?: BatchUsage }>): Pick { const reported = results.flatMap((r) => (r.usage ? [r.usage] : [])) if (!reported.length) return { calls: results.length } const total = reported.reduce(addUsage) return { tokens: total.tokens, cost: total.cost, calls: results.length } } /** * Tokens and cost of one drained stream, with the session's accounting rules. * Returns undefined when the provider reported nothing usable: accounting * never fails the lane. */ export async function streamUsage( stream: { totalUsage: PromiseLike; providerMetadata: PromiseLike }, model: Pick, ): Promise { try { const usage = await stream.totalUsage const metadata = await stream.providerMetadata if (!usage) return undefined // Loaded lazily, as in learn/usage.ts, to keep the session module out of // this module's import graph. const { Session } = await import("@/session") const u = Session.getUsage({ model: model as Provider.Model, usage: usage as any, metadata: (metadata ?? undefined) as any }) return { tokens: { input: u.tokens.input, inputTotal: u.tokens.inputTotal, output: u.tokens.output, reasoning: u.tokens.reasoning, cacheRead: u.tokens.cache.read, }, cost: u.cost, } } catch (err) { // The provider's error can quote its request and response: masked, job log only. log.warn("ai review usage unavailable", { error: logDetail(err) }) return undefined } } /** One model call over a group of files: send, wait (bounded), parse and clamp in core. */ async function reviewBatch( message: string, files: AiReviewFile[], system: string, model: Awaited>, laneSignal?: AbortSignal, callTimeoutMs?: number, ): Promise { const controller = new AbortController() const timeoutMs = callTimeoutMs ?? aiTimeoutMs(message.length) const timeout = setTimeout(() => controller.abort(), timeoutMs) const onLaneAbort = () => controller.abort() laneSignal?.addEventListener("abort", onLaneAbort, { once: true }) if (laneSignal?.aborted) controller.abort() const timedOut = (): BatchResult => laneSignal?.aborted ? { findings: [], state: "timeout", reason: LANE_DEADLINE_REASON } : { findings: [], state: "timeout", reason: `no answer within ${Math.round(timeoutMs / 1000)} s` } let usage: BatchUsage | undefined try { const agent: Agent.Info = { name: "dbt-ai-reviewer", mode: "primary", hidden: true, options: {}, permission: [], prompt: system, temperature: 0, } const user: MessageV2.User = { id: MessageID.ascending(), sessionID: SessionID.descending(), role: "user", time: { created: Date.now() }, agent: agent.name, model: { providerID: model.providerID, modelID: model.id }, } // Every wait races the abort signal: a provider that ignores it cannot hang the lane. const stream = await untilAborted( () => LLM.stream({ agent, user, system: [system], small: false, tools: {}, model, abort: controller.signal, sessionID: user.sessionID, retries: 1, messages: [{ role: "user", content: message }], }), controller.signal, ) const text = await untilAborted(readStreamText(stream), controller.signal) if (controller.signal.aborted) return timedOut() usage = await untilAborted(streamUsage(stream, model), controller.signal).catch(() => undefined) if (!text) return { findings: [], state: "error", reason: "the model returned no text", usage } // Parse + clamp in core (the prompt-injection-resistant, advisory-only // contract). Returns already-validated, severity-clamped, file-checked items. const parseRes = await Dispatcher.call("altimate_core.review_ai_parse", { text, valid_files: files.map((f) => f.path), }) // The core parser reports failure in-band (`success: false`) rather than // throwing; that is an error, never an "ok" run with no findings. const parsedRaw = ((parseRes.data ?? {}) as Record).findings if (parseRes.success === false || !Array.isArray(parsedRaw)) return { findings: [], state: "error", reason: reportFailure("ai_error", { check: "answer" }, parseRes.error ?? "no findings list").message, usage, } const parsed = parsedRaw as any[] const byFile = new Map(files.map((f) => [f.path, f])) const out: Finding[] = [] for (const item of parsed) { // Per-item guard: a single malformed finding (e.g. an out-of-enum severity that // makes makeFinding's schema throw) must NOT discard the whole batch. try { const file = byFile.get(String(item?.file ?? "")) if (!file || !item?.title || !item?.body) continue // Defense-in-depth clamp in the transport layer too: the advisory lane is // never allowed to emit `critical` (or any non-enum value), independent of // what core returns. Only `warning` survives as `warning`; everything else // degrades to `suggestion`. const severity: Severity = item.severity === "warning" ? "warning" : "suggestion" out.push( makeFinding({ severity, category: item.category as ReviewCategory, title: `${file.model}: ${item.title}`, body: String(item.body), file: file.path, model: file.model, startLine: typeof item.line === "number" ? item.line : undefined, endLine: typeof item.line === "number" ? item.line : undefined, confidence: item.confidence === "high" ? "high" : item.confidence === "low" ? "low" : "medium", evidence: { tool: "ai-review", result: { confidence: item.confidence } }, // The line keeps two findings with one title on one file apart; the batch split never enters it. ruleKey: `ai:${item.category}:${String(item.title).slice(0, 60)}:${typeof item.line === "number" ? item.line : ""}`, rule: ruleId("ai-review", String(item.category)), }), ) } catch (err) { log.warn("skipping malformed ai finding", { error: logDetail(err) }) } } // A call is ok only when the answer is exactly an empty JSON array, or at least one of its // findings maps to a file in this call. Anything else (prose, a refusal, another shape, // only files outside the call, every item dropped) is an error for this call: its files // stay not reviewed, never "ok, no findings". if (!out.length && !isEmptyAnswer(text)) return { findings: [], state: "error", reason: reportFailure("ai_error", { check: "answer" }, "the answer holds no usable finding").message, usage, } // Core keeps at most `CORE_FINDINGS_PER_CALL` findings per call; an answer with more items was cut. const capped = parsed.length >= CORE_FINDINGS_PER_CALL && answerItems(text) > parsed.length const foreign = foreignItems(text, byFile) return { findings: out, state: "ok", usage, ...(capped ? { capped: true } : {}), ...(foreign ? { foreign } : {}) } } catch (err) { if (controller.signal.aborted) return timedOut() return { findings: [], state: "error", reason: reportFailure("ai_error", { check: "request" }, err).message, usage } } finally { clearTimeout(timeout) laneSignal?.removeEventListener("abort", onLaneAbort) } }