import path from "node:path" import { readFile, realpath, stat, access, readdir } from "node:fs/promises" import YAML from "yaml" import { Installation } from "../../installation" import { aiLaneEnabled, headPolicyChanges, loadReviewPolicy, policyHash, resolveRubric } from "./config" import { SEVERITY_ORDER, type Severity } from "./finding" import { collectChangedFiles, makeContentResolver, resolveReviewBase, type ResolvedBase, gitRepoRoot, listFilesAt, listTreeAt, listWorkingTreeFiles, grepMatchesAt, grepFixedAt, projectGrepSpecs, manifestHash, resolveCommit, commitParents, showAtRef, } from "./git" import { makeCompiledResolver, dbtProjectName, dbtProjectLayout } from "./compiled" import { scopeToProject } from "./diff-filter" import { buildCatalogSchemaContext } from "./schema-context" import { createDispatcherRunner } from "./runner" import { runReview } from "./orchestrate" import { ADAPTERS } from "./dbt-patterns" import { runAiReview } from "./ai-review" import { resolveAiSwitches } from "./ai-switches" import { isAiPythonFile } from "./ai-python-files" import { loadConventions } from "./conventions" import { resolveRulesOff } from "./rules-off" import { configuredRulePolicy } from "./rule-post-policy" import { loadConsumerLists } from "./consumer-lists" import type { ReviewMode, VerdictEnvelope } from "./verdict" import type { ChangedFile } from "./diff-filter" /** * End-to-end review entry point: load `.altimate/review.yml`, collect the diff, * run the deterministic recipe against the Rust core, and return a signed * verdict envelope. Used by both the `dbt_pr_review` tool and the * `altimate review` CLI command so they can never diverge. */ export interface ReviewPullRequestOptions { cwd: string /** Base ref; defaults to the PR target branch from CI (else the remote default branch), reduced to the merge-base. */ base?: string /** Head ref; omit to diff against the working tree. */ head?: string /** Override the manifest path from config. */ manifestPath?: string /** Directories whose `.altimate/review` policy applies, in order, when `cwd` has none * (`--all-projects`: the ancestors of `cwd` up to the repository root, nearest first). */ policyFallbackDirs?: string[] /** Override the review mode from config. */ mode?: ReviewMode /** Override the minimum severity to surface. */ severityThreshold?: Severity /** Pre-collected changed files (skips git; used by CI providers). */ changedFiles?: ChangedFile[] /** Resolver for file contents (used when changedFiles is pre-supplied). */ getContent?: (file: string, side: "old" | "new") => Promise /** Model identifier recorded in the envelope. */ modelVersion?: string coreVersion?: string /** altimate-code CLI release recorded in engine.cliVersion for audit reconstruction. */ cliVersion?: string /** Disable the LLM reviewer lane (default: enabled; self-degrades if no model). */ noAi?: boolean /** PR metadata for the AI reviewer's intent check. */ prTitle?: string prBody?: string /** Explicit `provider/model` for the advisory AI lane. */ aiModel?: string /** G1 — surface the tier classifier's reasons on the verdict envelope. */ explainTier?: boolean /** G2 — [EXPERIMENTAL] bypass the tier classifier with the supplied tier. * Envelope carries `tierForced: true` when used. Debug / bench only. */ forceTier?: "trivial" | "lite" | "full" /** Every file the PR changes, when `changedFiles` is a subset of it (multi-project review). */ prFiles?: string[] /** Every rename the PR makes (new → old path), when `changedFiles` is a subset of it. */ prRenames?: Array<[string, string]> /** The changed Python files outside the dbt project this review's AI lane may take * (`pythonFiles` switch). Default all of them; `--all-projects` passes those no earlier * project's lane took. */ aiOutsidePaths?: string[] } /** dbt adapter_type → core SQL dialect. Mostly identity; a few aliases. */ const ADAPTER_DIALECT: Record = { bigquery: "bigquery", snowflake: "snowflake", redshift: "redshift", postgres: "postgres", databricks: "databricks", spark: "databricks", duckdb: "duckdb", trino: "trino", athena: "athena", mysql: "mysql", oracle: "oracle", sqlserver: "tsql", synapse: "tsql", fabric: "fabric", } /** Read the dbt manifest's `metadata.adapter_type` and map it to a dialect. */ async function detectDialect(manifestAbs: string): Promise { try { const raw = await readFile(manifestAbs, "utf8") const adapter = String(JSON.parse(raw)?.metadata?.adapter_type ?? "").toLowerCase() return ADAPTER_DIALECT[adapter] ?? (adapter || undefined) } catch { return undefined } } /** * G3 (Round 18) — walk upward from `cwd` looking for the nearest * `dbt_project.yml`; if found, return the adjacent `target/manifest.json` * (when it exists). Anchored on `dbt_project.yml` so we never pick up a * `target/` from an unrelated tool (e.g. an Airflow project) that happens * to live above us on the filesystem. * * We DO NOT re-run `dbt compile` here — that could touch a real warehouse or * consume credentials. The customer is still responsible for compiling; we * just find the existing artifact when they didn't pass `--manifest`. * * Returns undefined when no dbt project is found upward, or when the found * project has no compiled manifest. */ async function autoDiscoverManifest(cwd: string): Promise<{ path: string; projectRoot: string } | undefined> { // Walk up looking for dbt_project.yml so the manifest we auto-discover is // demonstrably tied to a dbt project (never `target/manifest.json` from an // unrelated cwd, e.g. Airflow's `target/`). `path.dirname(root) === root` // on every platform, so once we reach the filesystem root the next step // is a fixed point — exit at that point (NIT #6 tidy from consensus review). for (let dir = path.resolve(cwd); ; dir = path.dirname(dir)) { for (const fn of ["dbt_project.yml", "dbt_project.yaml"]) { try { await access(path.join(dir, fn)) const candidate = path.join(dir, "target", "manifest.json") try { await access(candidate) return { path: candidate, projectRoot: dir } } catch { // dbt project found at this dir but no compiled artifact. Do // NOT walk further — a grandparent's `target/manifest.json` // belongs to that grandparent's project, not to this one, and // reviewing against it would compile the wrong DAG. Deliberate: // "found a project, it just hasn't been compiled" — silent // fallback to a sibling project would surprise the caller // (altimate-harness-bot review, PR #1027 run.ts:114). return undefined } } catch { /* keep walking */ } } if (path.dirname(dir) === dir) return undefined } } /** Whether a repo-relative path is one whose modification could invalidate * the compiled manifest — dbt source (SQL, YAML, Python models, seed CSV, * docs markdown blocks) or top-level dbt config. `README.md` at repo root, * `.github/`, `package.json`, etc. are excluded so their mtimes don't * trigger a stale warning. Exported for tests — see review-run-stale.test.ts. * Referenced by `detectStaleManifest`. */ export function isManifestAffecting(rel: string): boolean { // Code / schema / seed CSV live under any dbt source directory. if (/(^|\/)(models|seeds|snapshots|macros|tests|analyses)\/.*\.(sql|py|yml|yaml|csv)$/i.test(rel)) return true // dbt docs blocks (`.md`) are only manifest-affecting under `models/` and // `analyses/` — where `{% docs %}` blocks are canonically parsed. A // `macros/README.md` / `tests/README.md` / `seeds/README.md` is package // documentation, not manifest input (altimate-harness-bot review, // PR #1027 run.ts:133). if (/(^|\/)(models|analyses)\/.*\.md$/i.test(rel)) return true // Top-level dbt project config files. if (/(^|\/)(dbt_project|packages|profiles|dependencies)\.ya?ml$/i.test(rel)) return true return false } /** Detect a stale manifest and warn to stderr. Returns `true` when a * change-affecting file was modified after the manifest — signalling the * verdict may have been computed against out-of-date metadata. Non-fatal; * the review proceeds against the (possibly stale) manifest and the * caller mirrors the flag onto the signed envelope so a downstream * auditor can distinguish stale-manifest verdicts from clean ones * (stderr alone is easy for CI to swallow). * * A deleted or renamed manifest-affecting file is treated as unconditionally * stale: the file's mtime cannot be checked (the path is gone) but the * manifest still references it, so the metadata is by definition out of date * (cubic-review PR #1041 — the prior path-only signature silently reported * clean for deletions and could false-certify verdicts against ghost models). */ async function detectStaleManifest(manifestAbs: string, changed: ChangedFile[], fsRoot: string): Promise { try { const manifestMtime = (await stat(manifestAbs)).mtimeMs for (const f of changed) { // For renamed files, the OLD path is what the manifest still knows about; // check both sides so both a rename-away and a rename-to a // manifest-affecting shape trigger the signal. const paths: string[] = [f.path] if (f.status === "renamed" && f.oldPath) paths.push(f.oldPath) if (!paths.some(isManifestAffecting)) continue // Deleted / renamed files no longer exist at their old path on disk, so // stat would fail. The manifest still references them though, so the // metadata is stale by definition — fire immediately. if (f.status === "deleted" || f.status === "renamed") { process.stderr.write( `⚠️ manifest ${manifestAbs} appears stale — ${f.status} \`${f.path}\` is a manifest-affecting path. ` + `Re-run \`dbt compile\` (or \`dbt build\`) to refresh before reviewing.\n`, ) return true } // `changed` paths are repo-root relative (from `git diff --name-status`), // so root at the git top-level rather than the caller's cwd. When the // CLI is invoked from a subdir the naive path.join(cwd, rel) points at // a non-existent path and the stale check silently no-ops. const abs = path.isAbsolute(f.path) ? f.path : path.join(fsRoot, f.path) try { const changedMtime = (await stat(abs)).mtimeMs if (changedMtime > manifestMtime) { process.stderr.write( `⚠️ manifest ${manifestAbs} appears stale — ${f.path} was modified after the manifest was written. ` + `Re-run \`dbt compile\` (or \`dbt build\`) to refresh before reviewing.\n`, ) return true } } catch { /* file not on disk for an added/modified entry — skip (rare race) */ } } } catch { /* manifest unreadable → detectDialect will have already returned undefined */ } return false } export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise { // Resolve the repo top-level once; used to root working-tree FS reads, the // stale-manifest existence check, and the compiled-SQL resolver's path // mapping. Falls back to opts.cwd when we couldn't resolve it (non-git or // bare-repo contexts) — safe for the repo-root-invoked case but not helpful // in the subdir-invocation case that this addresses. const gitRoot = (await gitRepoRoot(opts.cwd)) ?? opts.cwd // Only resolve a base ref if we actually need git (to collect changed files // or to read old/new content). A caller that supplies BOTH `changedFiles` and // `getContent` (e.g. a non-git CI integration) must not be forced through a // git lookup that can fail when there's no usable history. // // The base is always the MERGE-BASE of the PR's target branch and the head: // the diff, and every "old" file version, come from the commit the PR // branched from, so commits the target gained since never leak in as changes. const needGit = !opts.changedFiles || !opts.getContent const resolved: ResolvedBase | undefined = needGit ? await resolveReviewBase({ cwd: opts.cwd, base: opts.base, head: opts.head }) : undefined const headSha = resolved ? await resolveCommit(opts.head ?? "HEAD", opts.cwd) : undefined // A `pull_request` checkout is the synthetic merge commit; record its parents // so the poster can tell it reviewed the PR head (one of them). const parents = headSha ? await commitParents(headSha, opts.cwd) : [] const headParents = parents.length > 1 ? parents : undefined // The policy (.altimate/review.yml) comes from the BASE commit, so the PR // under review cannot relax its own rules; what it would change is listed. // The first of cwd and `policyFallbackDirs` that has a policy file wins. const policyAt = async (dir: string) => { const dirRel = await repoRelative(gitRoot, dir, true) return loadReviewPolicy({ cwd: dir, readBase: resolved && dirRel !== undefined ? (rel) => showAtRef(opts.cwd, resolved.sha, path.posix.join(dirRel, rel)) : undefined, }) } const policyHere = await policyAt(opts.cwd) let policy = policyHere for (const dir of opts.policyFallbackDirs ?? []) { if (policy.source !== "default") break policy = await policyAt(dir) } if (policy !== policyHere) { // A policy file the PR adds in cwd replaces the inherited one once merged: list // what it changes relative to the policy applied (relative to the defaults when // no directory has one on the base branch). const addedHere = policy.source === "base" ? await headPolicyChanges(opts.cwd, policy.config) : policyHere.changedInPr policy.changedInPr = [...new Set([...policy.changedInPr, ...addedHere])] } const config = policy.config if (policy.changedInPr.length) { process.stderr.write( `ℹ️ this PR changes .altimate/review (${policy.changedInPr.join(", ")}); the base branch's policy was applied.\n`, ) } if (opts.forceTier && config.allowForceTier === false) { throw new Error("--force-tier is disabled by `allowForceTier: false` in the base branch's .altimate/review.yml") } if (opts.manifestPath) config.manifestPath = opts.manifestPath // `--mode` / `--severity` come from the PR-editable workflow. Against a base // policy they may only tighten it: they cannot turn `gate` into `comment` // or hide severities the base policy surfaces. const fromBase = policy.source === "base" if (opts.mode) { if (fromBase && config.mode === "gate" && opts.mode !== "gate") { process.stderr.write(`ℹ️ --mode ${opts.mode} ignored: the base branch's policy sets \`mode: gate\`.\n`) } else config.mode = opts.mode } if (opts.severityThreshold) { if (fromBase && SEVERITY_ORDER[opts.severityThreshold] > SEVERITY_ORDER[config.severityThreshold]) { process.stderr.write( `ℹ️ --severity ${opts.severityThreshold} ignored: the base branch's policy surfaces ${config.severityThreshold} and above.\n`, ) } else config.severityThreshold = opts.severityThreshold } // The signed hash describes the policy actually applied, after the flags. policy.hash = policyHash(config) const rubric = resolveRubric(config) // Resolve the manifest against the PROJECT being reviewed (cwd), not the // binary's process.cwd() — otherwise a relative path silently misses when the // CLI is invoked from elsewhere, degrading every review to lint-only. let manifestAbs = path.isAbsolute(config.manifestPath) ? config.manifestPath : path.join(opts.cwd, config.manifestPath) // The "effective dbt project root" for downstream lookups (dbtProjectName, // compiled-SQL resolver, scope). The nearest dbt_project.yml at or above cwd // (inside the repo); G3 auto-discovery below may refine it. const project = await findDbtProject(opts.cwd, gitRoot, manifestAbs) let dbtRoot = project ?? opts.cwd // G3 (Round 18) — auto-discovery when the caller didn't pass `--manifest` and // the config-relative resolve above doesn't point at an existing file. Walk // upward for the dbt project root and use its `target/manifest.json`. Explicit // `--manifest` always wins (see run.ts opts.manifestPath override at the top). if (!opts.manifestPath) { let manifestExists = false try { await access(manifestAbs) manifestExists = true } catch { /* fall through to auto-discovery */ } if (!manifestExists) { const discovered = await autoDiscoverManifest(opts.cwd) if (discovered) { manifestAbs = discovered.path dbtRoot = discovered.projectRoot process.stderr.write( `ℹ️ auto-discovered dbt manifest at ${discovered.path} ` + `(dbt project root: ${discovered.projectRoot}). Pass --manifest to override.\n`, ) } } } // The dbt project's location inside the repo ("" = repo root). Undefined // when no dbt_project.yml was found or it lies outside the repo: then // nothing is scoped out and conventional directory names classify files. const projectRootRel = await repoRelative(gitRoot, dbtRoot, project !== undefined || dbtRoot !== opts.cwd) const layout = projectRootRel !== undefined ? await dbtProjectLayout(dbtRoot, projectRootRel) : undefined if (resolved && resolved.source !== "flag") { process.stderr.write(`ℹ️ review base: ${resolved.ref} (${resolved.source}), merge-base ${resolved.sha.slice(0, 12)}\n`) } const base = resolved?.sha ?? opts.base ?? "" const collected = opts.changedFiles ?? (await collectChangedFiles({ base, head: opts.head, cwd: opts.cwd })) const scoped = scopeToProject(collected, projectRootRel, layout) const changedFiles = scoped.inScope let aiDisabledReason: string | undefined if (opts.noAi) aiDisabledReason = "disabled by --no-ai" else if (!aiLaneEnabled(config)) aiDisabledReason = "disabled in .altimate/review.yml" const aiOn = !aiDisabledReason const aiSwitches = resolveAiSwitches(config, process.env, { warn: aiOn }) // Rule types off once the AI lane runs; a bad list file named by the env variable fails here. const rulesOff = aiOn ? resolveRulesOff(config, aiSwitches, process.env, gitRoot) : undefined // `pythonFiles`: .py files outside the dbt project skip every lane but the AI lane. A file // renamed out of this project belongs to it (`--all-projects` assigns it here), so it is offered // at its new path whatever other projects took. const outside = new Set(scoped.outOfScopePaths) const movedOut = new Set(scoped.movedOutPaths) const offered = opts.aiOutsidePaths && new Set(opts.aiOutsidePaths) const aiOutsideFiles = aiOn && aiSwitches.pythonFiles ? collected.filter( (f) => isAiPythonFile(f) && ((outside.has(f.path) && (!offered || offered.has(f.path))) || movedOut.has(f.path)), ) : [] const notReviewedOutside = scoped.outOfScope - aiOutsideFiles.filter((f) => outside.has(f.path)).length if (notReviewedOutside > 0) { process.stderr.write( `ℹ️ ${notReviewedOutside} changed file(s) outside the dbt project (${projectRootRel || "."}) were not reviewed.\n`, ) } // An upper bound: the lane's tier, Python quota, exclusions and credential screen decide // what it sends, and the result's coverage ledger lists any it did not review. if (aiOutsideFiles.length > 0) { process.stderr.write( `ℹ️ ${aiOutsideFiles.length} changed Python file(s) outside the dbt project (${projectRootRel || "."}) are offered to the AI review only, when that lane runs; the result lists any it did not review.\n`, ) } // Map renamed files → their old path so getContent resolves the "old" side // 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 or, // when `changedFiles` is a subset, as the whole PR renamed them. const prRenames = new Map([ ...(opts.prRenames ?? []), ...collected.filter((f) => f.status === "renamed" && f.oldPath).map((f) => [f.path, f.oldPath as string] as const), ]) 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 }) // Freshness check: detect (and warn — non-fatal) when the manifest predates // change-affecting files. Runs for both the pinned-head CI shape AND the // working-tree local shape — the local scenario "dbt compile once, edit for // an hour, then altimate review" is where staleness actually bites in // practice, so gating this behind `--head` (the prior behavior) silently // under-warned the most common developer workflow. mtime granularity on // the working tree can be noisy during a live edit session, but the check // is limited to files that would materially change the manifest // (`isManifestAffecting`), so noise is bounded. Return value is stamped // into the signed envelope so downstream auditors see it too. const staleManifest = await detectStaleManifest(manifestAbs, changedFiles, gitRoot) // Resolve the SQL dialect: explicit config wins; otherwise auto-detect from // the dbt manifest's `adapter_type` (so a BigQuery/Redshift project isn't // analyzed as the snowflake default — wrong-dialect portability suppression). const detectedDialect = config.dialect ? undefined : await detectDialect(manifestAbs) // Known = set in config, or an adapter the review maps to a dialect. An // unmapped adapter (a community adapter) is treated as unknown, so generic // advice isn't suppressed on a guess. const dialectKnown = !!config.dialect || (!!detectedDialect && Object.values(ADAPTER_DIALECT).includes(detectedDialect)) if (!config.dialect) config.dialect = detectedDialect ?? "snowflake" // Prefer dbt's catalog.json (real warehouse columns from `dbt docs generate`) // for the schema context — complete columns are what make column-lineage // breakage and proven equivalence actually fire (the manifest only has // documented columns). Falls back to manifest-derived schema when absent. const catalogAbs = path.join(path.dirname(manifestAbs), "catalog.json") const catalogSchema = await buildCatalogSchemaContext(catalogAbs) const runner = createDispatcherRunner({ manifestPath: manifestAbs, schemaContext: catalogSchema }) const mhash = await manifestHash(manifestAbs, opts.cwd) // Prefer dbt's COMPILED SQL (target/compiled) for the engine lanes — the clean // approach (Datafold/Recce/Fusion all render-then-analyze rather than parse Jinja). // Use `dbtRoot` (the discovered project root when G3 auto-discovery fired, // else opts.cwd) so a subdir invocation still finds `target/compiled/…` // next to the discovered manifest instead of falling back to raw Jinja. const projectName = await dbtProjectName(dbtRoot) // Repo-relative file paths need the git-root → dbt-root prefix stripped // so `packages/dbt/models/foo.sql` resolves to `models/foo.sql` inside the // dbt project. `path.relative` returns "" when dbtRoot === gitRoot (the // repo-root-invoked case) — makeCompiledResolver's `pathPrefix` treats // that as a no-op. // // Canonicalise both roots via `fs.realpath` before computing the relative // path. `gitRoot` from `git rev-parse --show-toplevel` is already // symlink-resolved; `dbtRoot` is not, so on macOS (`/var` → `/private/var`) // or any other symlinked-parent layout the `path.relative` result was a // meaningless climb path (`../../var/...`) that never matched incoming // repo-relative paths, and compiled SQL was silently missed // (cubic-review P2 + kilo suggestion). Falls back gracefully when the // realpath call fails (e.g. path deleted mid-run). let gitRootReal = gitRoot let dbtRootReal = dbtRoot try { gitRootReal = await realpath(gitRoot) dbtRootReal = await realpath(dbtRoot) } catch { /* keep original values on realpath failure */ } const pathPrefix = path.relative(gitRootReal, dbtRootReal) const getCompiled = opts.getContent ? undefined : makeCompiledResolver({ cwd: dbtRootReal, projectName, pathPrefix }) // Repo review instructions come from the base commit, like the policy, so a PR cannot // change the conventions it is reviewed under; only when the AI lane runs. A git failure // reading that commit fails the review, as it does for the policy read just before. // Scoped files are searched above the files this review covers (its project's files and // the outside Python files its AI lane may take), not every directory the PR touches. // One base listing for the conventions loader: the files and the symlinks among them. let baseTree: Promise<{ files: string[]; symlinks: string[] }> | undefined const listBaseTree = () => (baseTree ??= listTreeAt(gitRoot, resolved!.sha).then((t) => { if (!t) throw new Error(`cannot list the files of the base commit ${resolved!.sha} for the team conventions`) return t })) const conventions = aiOn && aiSwitches.conventions && resolved ? await loadConventions({ readBase: (rel) => showAtRef(gitRoot, resolved.sha, rel), listBase: async () => (await listBaseTree()).files, listBaseSymlinks: async () => (await listBaseTree()).symlinks, changedPaths: [...changedFiles, ...aiOutsideFiles].map((f) => f.path), }) : [] const consumerLists = config.consumerColumnLists.length ? await loadConsumerLists({ configs: config.consumerColumnLists, gitRoot, head: opts.head, read: (p) => getContent(p, "new"), }) : [] return runReview({ resourceNames: () => projectResourceNames(opts.cwd, opts.head, projectRootRel, dbtRoot), packageDocNames: () => packageDocNames(opts.cwd, opts.head, projectRootRel, dbtRoot), changedFiles, config, rubric, mode: config.mode, runner, getContent, getCompiled, generatedAt: new Date().toISOString(), manifestHash: mhash, modelVersion: opts.modelVersion, coreVersion: opts.coreVersion, // Default cliVersion so agent-invoked callers (dbt_pr_review tool) that // don't thread the version get the audit-trail field populated too. // Only the CLI command explicitly forwards Installation.VERSION today, // so a missing default silently regresses envelope provenance for tool- // path verdicts (cubic-review PR #1041). cliVersion: opts.cliVersion ?? Installation.VERSION, aiReview: aiOn ? runAiReview : undefined, aiDisabledReason, aiModel: opts.aiModel, aiGraphContext: process.env.ALTIMATE_REVIEW_AI_GRAPH === "1", aiContextCard: aiSwitches.contextCard, aiVerify: aiSwitches.verify, aiSwitches, ...(aiOutsideFiles.length ? { aiOutsideFiles } : {}), reviewDir: gitRoot, ...(conventions.length ? { conventions } : {}), ...(rulesOff ? { rulesOff } : {}), ...(aiOn && aiSwitches.rulePolicy ? { rulePolicy: configuredRulePolicy(config) } : {}), grepProject: (pattern, glob) => { // The project's dbt directories (repo-relative), or one glob inside the project. const dirs = layout ? [...layout.dirs.model, ...layout.dirs.macro, ...layout.dirs.seed, ...layout.dirs.snapshot, ...layout.dirs.test] : ["models", "macros", "seeds", "snapshots", "tests"] const specs = projectGrepSpecs(projectRootRel, dirs, glob) return specs ? grepFixedAt(gitRoot, opts.head, pattern, specs) : Promise.resolve(undefined) }, prFiles: opts.prFiles ?? collected.map((f) => f.path), prRenames, prTitle: opts.prTitle, prBody: opts.prBody, explainTier: opts.explainTier, forceTier: opts.forceTier, staleManifest, layout, suppressPortability: shouldSuppressPortability(config.portability, dialectKnown), portabilityTargets: await projectAdapters(opts.cwd, opts.head, projectRootRel), dialectKnown, consumerLists, policy: { source: policy.source, hash: policy.hash, changedInPr: policy.changedInPr.length ? policy.changedInPr : undefined, posting: config.posting, }, scope: { baseRef: resolved?.ref ?? opts.base, baseSha: resolved?.sha, headSha, headParents, baseSource: resolved?.source, projectRoot: projectRootRel, outOfScopeFiles: scoped.outOfScope || undefined, movedUnchangedFiles: scoped.movedUnchanged || undefined, notReviewed: [ ...scoped.outOfScopePaths.map((path) => ({ path, reason: `outside the dbt project (${projectRootRel || "."})` })), ...scoped.movedUnchangedPaths.map((path) => ({ path, reason: "moved without edits; not re-reviewed" })), ], }, }) } /** Drop cross-engine portability advice? An explicit `portability` setting * wins (even when the engine is unknown); unset, drop it once the engine is * known (configured or detected from the manifest). */ export function shouldSuppressPortability(portability: boolean | undefined, dialectKnown: boolean): boolean { return portability === undefined ? dialectKnown : !portability } /** * The pull/merge request's title and description from the CI environment, so * the AI lane can check the change against its stated intent. GitHub: the * `pull_request` object in GITHUB_EVENT_PATH. GitLab: CI_MERGE_REQUEST_TITLE / * CI_MERGE_REQUEST_DESCRIPTION. Empty outside a PR/MR run. */ export async function prContextFromEnv(env: NodeJS.ProcessEnv = process.env): Promise<{ prTitle?: string; prBody?: string }> { if (env.GITHUB_EVENT_PATH) { try { const pr = JSON.parse(await readFile(env.GITHUB_EVENT_PATH, "utf8"))?.pull_request if (pr) { return { prTitle: typeof pr.title === "string" && pr.title ? pr.title : undefined, prBody: typeof pr.body === "string" && pr.body ? pr.body : undefined, } } } catch { /* unreadable event file: try GitLab */ } } return { prTitle: env.CI_MERGE_REQUEST_TITLE || undefined, prBody: env.CI_MERGE_REQUEST_DESCRIPTION || undefined, } } /** * The dbt project being reviewed: the nearest directory at or above `cwd` * (not above the repo root) holding dbt_project.yml; else the project that * owns the configured manifest (`/target/manifest.json`). */ async function findDbtProject(cwd: string, gitRoot: string, manifestAbs: string): Promise { const hasProjectFile = async (dir: string) => { for (const fn of ["dbt_project.yml", "dbt_project.yaml"]) { try { await access(path.join(dir, fn)) return true } catch { /* try next */ } } return false } let stop = path.resolve(gitRoot) try { stop = await realpath(stop) } catch { /* keep unresolved */ } let dir = path.resolve(cwd) try { dir = await realpath(dir) } catch { /* keep unresolved */ } for (;;) { if (await hasProjectFile(dir)) return dir if (dir === stop || path.dirname(dir) === dir) break dir = path.dirname(dir) } const owner = path.dirname(path.dirname(manifestAbs)) return (await hasProjectFile(owner)) ? owner : undefined } /** `dir` relative to the repo root in POSIX form, or undefined when unknown * or outside the repo. */ async function repoRelative(gitRoot: string, dir: string, known: boolean): Promise { if (!known) return undefined let a = gitRoot let b = dir try { a = await realpath(gitRoot) b = await realpath(dir) } catch { /* compare unresolved */ } const rel = path.relative(a, b).replace(/\\/g, "/") if (rel.startsWith("..") || path.isAbsolute(rel)) return undefined return rel } const RESOURCE_FILE = /\.(sql|py|csv)$/i const resourceName = (f: string) => path.basename(f).replace(RESOURCE_FILE, "").toLowerCase() /** * Adapters the project's own macros carry variants for (`postgres__x`, * `snowflake__x`, ...). A project with variants for several adapters is meant * to run on all of them, so portability advice is judged against each one, * not just the adapter this checkout is configured for. */ export async function projectAdapters( cwd: string, head: string | undefined, projectRootRel: string | undefined, ): Promise { if (projectRootRel === undefined) return [] const prefix = projectRootRel ? projectRootRel + "/" : "" const lines = await grepMatchesAt(cwd, head, `macro[[:space:]]+(${ADAPTERS.join("|")})__`, `${prefix}*.sql`) const seen = new Set() for (const line of lines ?? []) { if (line.includes("/dbt_packages/")) continue const m = /macro\s+(\w+?)__$/.exec(line) if (m) seen.add(m[1] === "presto" ? "trino" : m[1]) } 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 * models of installed packages (`dbt_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 projectResourceNames( 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 // Working-tree review: models added but not yet committed are refable too. if (head === undefined) files.push(...((await listWorkingTreeFiles(cwd)) ?? [])) const prefix = projectRootRel ? projectRootRel + "/" : "" const names = new Set() for (const f of files) if (f.startsWith(prefix) && RESOURCE_FILE.test(f)) names.add(resourceName(f)) // Working-tree review reads the files on disk, from the repository root. const repoRoot = head ? undefined : await gitRepoRoot(cwd) // dbt 1.9+ snapshots can be YAML-only (`snapshots: - name: x relation: ...`), with no .sql file. for (const line of (await grepMatchesAt(cwd, head, "^snapshots:", `${prefix}*.yml`)) ?? []) { const rel = line.slice(line.indexOf(":") + 1, line.lastIndexOf(":snapshots:")) if (rel.includes("/dbt_packages/")) continue let doc: { snapshots?: { name?: unknown }[] } | null = null try { const text = head ? await showAtRef(cwd, head, rel) : await readFile(path.join(repoRoot ?? cwd, rel), "utf8") doc = YAML.parse(text ?? "") } catch { continue } for (const snap of Array.isArray(doc?.snapshots) ? doc.snapshots : []) if (typeof snap?.name === "string") names.add(snap.name.toLowerCase()) } if (files.includes(prefix + "packages.yml") || files.includes(prefix + "dependencies.yml")) { const pkgDir = path.join(dbtRoot, "dbt_packages") 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) { if (e.isDirectory() && depth < 12 && e.name !== ".git") await walk(path.join(dir, e.name), depth + 1) else if (e.isFile() && RESOURCE_FILE.test(e.name)) names.add(resourceName(e.name)) } return true } if (!(await walk(pkgDir, 0))) return undefined } return names }