From 93db8701de2075c7e28ac73bb0d262f8c4025ad6 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 01:52:32 +0530 Subject: [PATCH 01/34] feat(review): resolve the AI lane's switches once, from env, `ai:` config and defaults - `ai` in `.altimate/review.yml` takes `true`/`false` or an object: `enabled` plus optional `coverage`, `contextCard`, `focused`, `otherFiles`, `pythonFiles`, `verify`; every key is optional so the default policy hash is unchanged - `ai-switches.ts`: `resolveAiSwitches` gives each switch from its env variable (`1` on, `0` off), then the config object, then the product default (all off in this commit) - `run.ts` resolves the switches once and passes them to the orchestrator and the AI lane; `aiInputBudget`, the verifier check and the replay verifier read them, and fall back to the env variable alone when called without them - tests: precedence, env-only fallback, budget, config forms and policy hash Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-replay.ts | 5 +- .../opencode/src/altimate/review/ai-review.ts | 18 ++++-- .../src/altimate/review/ai-switches.ts | 54 ++++++++++++++++++ .../opencode/src/altimate/review/config.ts | 34 +++++++++++- .../src/altimate/review/orchestrate.ts | 6 +- packages/opencode/src/altimate/review/run.ts | 15 +++-- .../test/altimate/review-ai-switches.test.ts | 55 +++++++++++++++++++ 7 files changed, 170 insertions(+), 17 deletions(-) create mode 100644 packages/opencode/src/altimate/review/ai-switches.ts create mode 100644 packages/opencode/test/altimate/review-ai-switches.test.ts diff --git a/packages/opencode/src/altimate/review/ai-replay.ts b/packages/opencode/src/altimate/review/ai-replay.ts index e9711969b9..63b689d01c 100644 --- a/packages/opencode/src/altimate/review/ai-replay.ts +++ b/packages/opencode/src/altimate/review/ai-replay.ts @@ -14,7 +14,8 @@ import { Provider } from "@/provider/provider" import { Log } from "@/altimate/util/log" import { Finding, ReviewCategory, makeFinding, ruleId } from "./finding" import type { AiLaneStatus, AiReviewInput, AiReviewResult } from "./ai-review" -import { aiVerifyEnabled, runAiVerify, type VerifierStatus } from "./ai-verify" +import { runAiVerify, type VerifierStatus } from "./ai-verify" +import { switchOn } from "./ai-switches" import { modelNameFromPath } from "./orchestrate" const log = Log.create({ service: "ai-replay" }) @@ -189,7 +190,7 @@ export async function runAiReplay(input: AiReviewInput, path: string): Promise> try { const chosen = input.model ? Provider.parseModel(input.model) : await Provider.defaultModel() diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index b9d19e1922..f1f37ba274 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -9,10 +9,11 @@ import { redactSecrets } from "@/installation" import { Dispatcher } from "../native" import { type Finding, type ReviewCategory, type Severity, makeFinding, ruleId } from "./finding" import { readStreamText } from "../llm/stream-text" -import { type AiVerifyEvidence, type VerifierStatus, aiVerifyEnabled, runAiVerify } from "./ai-verify" +import { type AiVerifyEvidence, type VerifierStatus, runAiVerify } from "./ai-verify" import { aiReplayPath, runAiReplay } from "./ai-replay" import { walkDiffLines } from "./diff-filter" import { CARD_BATCH_MAX_CHARS } from "./ai-context-card" +import { type AiSwitches, switchOn } from "./ai-switches" const log = Log.create({ service: "ai-review" }) @@ -63,7 +64,10 @@ export interface AiFocusBudget { batchFiles: number maxBatches: number } -export function aiInputBudget(env: Record = process.env): AiInputBudget { +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 @@ -77,7 +81,7 @@ export function aiInputBudget(env: Record = process. const n = Number(v) return v && Number.isInteger(n) && n >= 0 ? n : d } - const coverageOn = env.ALTIMATE_REVIEW_AI_COVERAGE === "1" + 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), @@ -95,7 +99,7 @@ export function aiInputBudget(env: Record = process. } : undefined, focused: - env.ALTIMATE_REVIEW_AI_FOCUSED === "1" + 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), @@ -685,6 +689,8 @@ export interface AiReviewInput { evidence?: AiVerifyEvidence /** 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 } /** What happened in the advisory lane, reported on the envelope and in the comment. */ @@ -875,7 +881,7 @@ export interface AiInputPlan { * `env` argument; `runAiReview` sends exactly these messages. */ export function planAiInput(input: AiReviewInput, env: Record = process.env): AiInputPlan { - const budget = aiInputBudget(env) + const budget = aiInputBudget(env, input.switches) let files: AiReviewFile[] let unsent: AiReviewFile[] if (budget.coverage) ({ sent: files, unsent } = selectAiFilesByQuota(input.files, budget.coverage.quotas)) @@ -962,7 +968,7 @@ export async function runAiReview(input: AiReviewInput): Promise const reason = failed.length ? `${failed.length} of ${results.length} calls failed: ${failed[0].reason}` : undefined // Opt-in: try to refute each finding with dbt evidence. Never throws. let verifier: VerifierStatus | undefined - if (input.evidence && aiVerifyEnabled()) { + if (input.evidence && switchOn("verify", input.switches)) { const v = await runAiVerify({ findings, grounding: input.grounding, evidence: input.evidence, model }) findings = v.findings verifier = v.status diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts new file mode 100644 index 0000000000..385fc8979d --- /dev/null +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -0,0 +1,54 @@ +// altimate_change - new file: what the AI review lane does, resolved once per review +// +// Each switch is set by, in order: its env variable (`1` on, `0` off), the +// `ai:` object in `.altimate/review.yml` (read from the base branch), then the +// product default. `reviewPullRequest` resolves the switches and passes them +// down; code called without them (direct callers, unit tests) reads only the +// env variable, as before, so an unset variable means off there. +import type { ReviewConfig } from "./config" + +export type AiSwitchName = "coverage" | "contextCard" | "focused" | "otherFiles" | "pythonFiles" | "verify" + +export type AiSwitches = Record + +/** The env variable that overrides each switch. */ +export const AI_SWITCH_ENV: Record = { + coverage: "ALTIMATE_REVIEW_AI_COVERAGE", + contextCard: "ALTIMATE_REVIEW_AI_CONTEXT_CARD", + focused: "ALTIMATE_REVIEW_AI_FOCUSED", + otherFiles: "ALTIMATE_REVIEW_AI_OTHER_FILES", + pythonFiles: "ALTIMATE_REVIEW_AI_PYTHON_FILES", + verify: "ALTIMATE_REVIEW_AI_VERIFY", +} + +/** Product defaults when neither env nor config sets a switch. */ +export const AI_SWITCH_DEFAULTS: AiSwitches = { + coverage: false, + contextCard: false, + focused: false, + otherFiles: false, + pythonFiles: false, + verify: false, +} + +type Env = Record + +/** The env override for a switch: true for `1`, false for `0`, undefined otherwise. */ +export function envSwitch(name: AiSwitchName, env: Env = process.env): boolean | undefined { + const v = env[AI_SWITCH_ENV[name]] + return v === "1" ? true : v === "0" ? false : undefined +} + +/** Every switch for one review: env, then the `ai:` config object, then the default. */ +export function resolveAiSwitches(cfg: Pick, env: Env = process.env): AiSwitches { + const configured = typeof cfg.ai === "object" ? cfg.ai : {} + const out = { ...AI_SWITCH_DEFAULTS } + for (const name of Object.keys(AI_SWITCH_ENV) as AiSwitchName[]) + out[name] = envSwitch(name, env) ?? configured[name] ?? AI_SWITCH_DEFAULTS[name] + return out +} + +/** A switch from resolved switches when given, else from its env variable alone (unset = off). */ +export function switchOn(name: AiSwitchName, switches: Partial | undefined, env: Env = process.env): boolean { + return switches?.[name] ?? envSwitch(name, env) ?? false +} diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 8c0de13c19..43d19d6335 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -25,8 +25,33 @@ export const ReviewConfig = z.object({ /** SQL dialect for static analysis. Empty = auto-detect from the dbt * manifest's `adapter_type` (set explicitly here to override). */ dialect: z.string().default(""), - /** Enable the advisory LLM reviewer lane (needs a configured model). */ - ai: z.boolean().default(true), + /** + * The advisory LLM reviewer lane (needs a configured model): `true`/`false`, + * or an object with `enabled` and per-switch settings for what the lane does + * (see ai-switches.ts). An env variable set to `1` or `0` overrides a switch. + * Read from the base branch, so a PR cannot change them for itself. Every key + * is optional so the default policy hash does not change. + */ + ai: z + .union([ + z.boolean(), + z.object({ + enabled: z.boolean().optional(), + /** Per-kind file quotas and hunk-centred excerpts instead of a 20-file cap. */ + coverage: z.boolean().optional(), + /** dbt manifest context card with each changed model. */ + contextCard: z.boolean().optional(), + /** Related changed files reviewed together in a few calls on larger PRs. */ + focused: z.boolean().optional(), + /** Changed `other`/`analysis` files inside the project (.sql/.yml/.yaml/.py). */ + otherFiles: z.boolean().optional(), + /** Changed Python files, inside or outside the dbt project. */ + pythonFiles: z.boolean().optional(), + /** The dbt-grounded verifier over the AI findings. */ + verify: z.boolean().optional(), + }), + ]) + .default(true), /** * Report cross-engine portability advice ("isn't portable across * warehouses"). Off by default once the engine is known (from the manifest's @@ -133,6 +158,11 @@ export type ReviewConfig = z.infer export const DEFAULT_REVIEW_CONFIG: ReviewConfig = ReviewConfig.parse({}) +/** Whether the AI lane is enabled (`ai: false` or `ai: { enabled: false }` turns it off). */ +export function aiLaneEnabled(cfg: Pick): boolean { + return typeof cfg.ai === "boolean" ? cfg.ai : cfg.ai.enabled !== false +} + /** Deep-merge a partial rubric override onto the default rubric. */ export function resolveRubric(cfg: ReviewConfig): Rubric { return Rubric.parse({ diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 06198e8bc7..f6cbd6fa83 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -63,6 +63,7 @@ import { import { type AiContextFile, type AiLaneStatus, type AiReviewFile, type AiReviewInput, type AiReviewResult, aiInputBudget, safeReason, selectAiFiles, selectAiFilesByQuota } from "./ai-review" import { type MacroCard, type ModelCard, attachContextCards } from "./ai-context-card" import { ruleTier } from "./rule-tiers" +import type { AiSwitches } from "./ai-switches" import { type AiVerifyEvidence, numberedSlice } from "./ai-verify" import { holdsCredentials, isCredentialPath } from "./credentials" import type { ColumnReach } from "../native/dbt/column-reach" @@ -288,6 +289,8 @@ export interface OrchestrateInput { aiContextCard?: boolean /** Give the AI lane what the dbt-grounded verifier reads (`ALTIMATE_REVIEW_AI_VERIFY=1`). */ aiVerify?: boolean + /** The review's resolved AI switches (ai-switches.ts); without them each switch reads its env variable. */ + aiSwitches?: Partial /** Fixed-string search over the dbt project at head, for the verifier. */ grepProject?: AiVerifyEvidence["grepProject"] /** Every file the PR changes (repo-relative), including files outside the dbt project; the verifier may read them. */ @@ -2680,7 +2683,7 @@ export async function runReview(input: OrchestrateInput): Promise f.path), input.runner, getContent) : undefined @@ -2745,6 +2748,7 @@ export async function runReview(input: OrchestrateInput): Promise { // The project's dbt directories (repo-relative), or one glob inside the project. const dirs = layout diff --git a/packages/opencode/test/altimate/review-ai-switches.test.ts b/packages/opencode/test/altimate/review-ai-switches.test.ts new file mode 100644 index 0000000000..b4616727ee --- /dev/null +++ b/packages/opencode/test/altimate/review-ai-switches.test.ts @@ -0,0 +1,55 @@ +import { describe, test, expect } from "bun:test" +import { AI_SWITCH_DEFAULTS, AI_SWITCH_ENV, envSwitch, resolveAiSwitches, switchOn } from "../../src/altimate/review/ai-switches" +import { DEFAULT_REVIEW_CONFIG, aiLaneEnabled, parseReviewConfig, policyHash } from "../../src/altimate/review/config" +import { aiInputBudget } from "../../src/altimate/review/ai-review" + +describe("AI switches", () => { + test("env 1/0 override, anything else defers", () => { + expect(envSwitch("coverage", { ALTIMATE_REVIEW_AI_COVERAGE: "1" })).toBe(true) + expect(envSwitch("coverage", { ALTIMATE_REVIEW_AI_COVERAGE: "0" })).toBe(false) + expect(envSwitch("coverage", { ALTIMATE_REVIEW_AI_COVERAGE: "yes" })).toBeUndefined() + expect(envSwitch("coverage", {})).toBeUndefined() + }) + + test("env wins over config, config over the default", () => { + const cfg = { ai: { coverage: true, focused: false } } + expect(resolveAiSwitches(cfg, {}).coverage).toBe(true) + expect(resolveAiSwitches(cfg, { ALTIMATE_REVIEW_AI_COVERAGE: "0" }).coverage).toBe(false) + expect(resolveAiSwitches(cfg, { ALTIMATE_REVIEW_AI_FOCUSED: "1" }).focused).toBe(true) + expect(resolveAiSwitches({ ai: true }, {})).toEqual(AI_SWITCH_DEFAULTS) + }) + + test("without resolved switches only the env variable counts", () => { + expect(switchOn("verify", undefined, {})).toBe(false) + expect(switchOn("verify", undefined, { ALTIMATE_REVIEW_AI_VERIFY: "1" })).toBe(true) + expect(switchOn("verify", { verify: false }, { ALTIMATE_REVIEW_AI_VERIFY: "1" })).toBe(false) + }) + + test("every switch has an env variable", () => { + expect(Object.keys(AI_SWITCH_ENV).sort()).toEqual(Object.keys(AI_SWITCH_DEFAULTS).sort()) + }) + + test("the input budget follows the switches", () => { + expect(aiInputBudget({}, { coverage: true }).coverage).toBeDefined() + expect(aiInputBudget({}, { coverage: false }).coverage).toBeUndefined() + expect(aiInputBudget({ ALTIMATE_REVIEW_AI_FOCUSED: "1" }).focused).toBeDefined() + expect(aiInputBudget({}, { focused: true }).focused).toBeDefined() + }) +}) + +describe("`ai:` in .altimate/review.yml", () => { + test("boolean and object forms", () => { + expect(aiLaneEnabled(parseReviewConfig("ai: false"))).toBe(false) + expect(aiLaneEnabled(parseReviewConfig("ai: true"))).toBe(true) + expect(aiLaneEnabled(parseReviewConfig("ai:\n enabled: false"))).toBe(false) + const cfg = parseReviewConfig("ai:\n coverage: false\n verify: true") + expect(aiLaneEnabled(cfg)).toBe(true) + expect(resolveAiSwitches(cfg, {}).verify).toBe(true) + expect(resolveAiSwitches(cfg, {}).coverage).toBe(false) + }) + + test("the default policy hash is unchanged by the object form", () => { + expect(DEFAULT_REVIEW_CONFIG.ai).toBe(true) + expect(policyHash(parseReviewConfig("mode: comment"))).toBe(policyHash(DEFAULT_REVIEW_CONFIG)) + }) +}) From 01f81bc949783d45b8b7f367d40b73e2959a23f4 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 01:53:40 +0530 Subject: [PATCH 02/34] feat(review): send other changed project files to the AI lane (`otherFiles` switch) - with `ai.otherFiles` / `ALTIMATE_REVIEW_AI_OTHER_FILES=1`, changed `other` and `analysis` files inside the dbt project root (`.sql`, `.yml`, `.yaml`, `.py`, not deleted, not credential-like) go to the AI lane after the supporting files, with their head content - under coverage they take their own quota, `ALTIMATE_REVIEW_AI_QUOTA_OTHER` (default 8), selected apart and appended after the existing buckets; existing quotas, spare and order are unchanged - sections get a label and a fence by extension; the `ai.input` row carries the kind - a file the lane sent is no longer listed as "not a dbt model/macro/test/yml/seed file" - off (the default in this commit), the lane's input and the ledger are unchanged - tests: off unchanged, on adds allowed files, quota, deleted, disallowed and out-of-root files left out, ledger, resolved switches over env, a finding on an added file Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-other-files.ts | 22 ++ .../opencode/src/altimate/review/ai-review.ts | 40 ++- .../src/altimate/review/orchestrate.ts | 25 +- .../altimate/review-ai-other-files.test.ts | 233 ++++++++++++++++++ 4 files changed, 313 insertions(+), 7 deletions(-) create mode 100644 packages/opencode/src/altimate/review/ai-other-files.ts create mode 100644 packages/opencode/test/altimate/review-ai-other-files.test.ts diff --git a/packages/opencode/src/altimate/review/ai-other-files.ts b/packages/opencode/src/altimate/review/ai-other-files.ts new file mode 100644 index 0000000000..498e960321 --- /dev/null +++ b/packages/opencode/src/altimate/review/ai-other-files.ts @@ -0,0 +1,22 @@ +// altimate_change - new file: other changed project files for the AI lane +// +// With the `otherFiles` switch (`ALTIMATE_REVIEW_AI_OTHER_FILES`), changed files of kind +// `other` or `analysis` inside the dbt project root also go to the AI lane, under their own +// coverage quota (`ALTIMATE_REVIEW_AI_QUOTA_OTHER`), after the existing kinds. No rule lane +// reads them. Off, the lane's input is unchanged. + +/** Kinds the switch adds. */ +export const AI_OTHER_KINDS: ReadonlySet = new Set(["other", "analysis"]) +/** Extensions the switch accepts. */ +export const AI_OTHER_EXTENSIONS = [".sql", ".yml", ".yaml", ".py"] +/** Default coverage quota for the added files. */ +export const AI_OTHER_FILES_QUOTA = 8 + +/** A changed file the switch adds: other/analysis kind, not deleted, allowed extension. */ +export function isAiOtherFile(f: { path: string; status: string; kind?: string }): boolean { + return ( + AI_OTHER_KINDS.has(f.kind ?? "") && + f.status !== "deleted" && + AI_OTHER_EXTENSIONS.some((ext) => f.path.toLowerCase().endsWith(ext)) + ) +} diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index f1f37ba274..9ff97a528a 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -14,6 +14,7 @@ import { aiReplayPath, runAiReplay } from "./ai-replay" import { walkDiffLines } from "./diff-filter" import { CARD_BATCH_MAX_CHARS } from "./ai-context-card" import { type AiSwitches, switchOn } from "./ai-switches" +import { AI_OTHER_FILES_QUOTA, AI_OTHER_KINDS } from "./ai-other-files" const log = Log.create({ service: "ai-review" }) @@ -52,8 +53,10 @@ export interface AiInputBudget { /** Characters of file sections per call; Infinity keeps a single call (the default without coverage). */ batchChars: number /** `ALTIMATE_REVIEW_AI_COVERAGE=1`: per-kind file quotas (replacing `maxFiles`) and - * hunk-centred excerpts instead of head truncation. Undefined keeps today's input. */ - coverage?: AiCoverageRender & { quotas: Record } + * 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. */ + coverage?: AiCoverageRender & { quotas: Record; otherQuota?: number } /** `ALTIMATE_REVIEW_AI_FOCUSED=1`: on PRs with at least `minFiles` selected files, review * related files together in calls of about `batchFiles` files, at most `maxBatches` calls * unless `batchChars` needs more. */ @@ -96,6 +99,9 @@ export function aiInputBudget( 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) } + : {}), } : undefined, focused: @@ -175,9 +181,21 @@ const KIND_LABEL: Record = { 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", } const FENCE: Record = { schema_yml: "yaml", source_yml: "yaml", project_config: "yaml", seed: "csv", python_model: "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(".py") ? "python" : 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 @@ -231,10 +249,14 @@ export function changedLineCount(diff: string | undefined): number { export function selectAiFilesByQuota( files: AiReviewFile[], quotas: Record = COVERAGE_QUOTAS, + extra: { otherQuota?: 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 ?? "") const byBucket = new Map(BUCKET_ORDER.map((b) => [b, []])) eligible + .filter((f) => !isOther(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)) @@ -248,10 +270,20 @@ export function selectAiFilesByQuota( 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)) 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. */ @@ -486,7 +518,7 @@ function renderFile(f: AiReviewFile, maxChars: number, coverageArg: CoverageArg, ? truncate(f.sql, fileChars) : excerptFile(f.sql, f.diff, maxChars).text if (f.sql.length > fileChars) stats = { ...stats, truncated: true } - parts.push(`${isModel ? "Current SQL" : "Current file"}:\n\`\`\`${FENCE[f.kind ?? ""] ?? "sql"}\n` + body + "\n```") + parts.push(`${isModel ? "Current SQL" : "Current file"}:\n\`\`\`${fenceOf(f)}\n` + body + "\n```") } return { text: parts.join("\n"), ...stats } } @@ -884,7 +916,7 @@ export function planAiInput(input: AiReviewInput, env: Record AI_SUPPORTING_KINDS.has(f.kind) && f.status !== "deleted" && !mayHoldCredentials(f.path), ) + // `otherFiles`: other/analysis files inside the project root (.sql/.yml/.yaml/.py), after the supporting files. + if (switchOn("otherFiles", input.aiSwitches)) { + const root = input.layout?.root + supporting.push( + ...reviewable.filter( + (f) => + isAiOtherFile(f) && + !mayHoldCredentials(f.path) && + (root === undefined || relativeToRoot(f.path, root) !== undefined), + ), + ) + } const contents = await Promise.all( supporting.map((f) => f.kind === "seed" @@ -2684,7 +2698,11 @@ export async function runReview(input: OrchestrateInput): Promise f.path), input.runner, getContent) : undefined // Files the PR changes that the AI may list and the verifier may read; never the user's exclusions or credentials. @@ -2781,7 +2799,8 @@ export async function runReview(input: OrchestrateInput): Promise (f.kind === "other" && !otherChecked.has(f.path)) || f.kind === "analysis") + // Other/analysis files the AI lane sent (`otherFiles`) were reviewed. + .filter((f) => ((f.kind === "other" && !otherChecked.has(f.path)) || f.kind === "analysis") && !touched.has(f.path)) .map((f) => ({ path: f.path, reason: "not a dbt model/macro/test/yml/seed file" })), ...reviewable .filter((f) => !touched.has(f.path)) diff --git a/packages/opencode/test/altimate/review-ai-other-files.test.ts b/packages/opencode/test/altimate/review-ai-other-files.test.ts new file mode 100644 index 0000000000..01e2c86f06 --- /dev/null +++ b/packages/opencode/test/altimate/review-ai-other-files.test.ts @@ -0,0 +1,233 @@ +import { describe, test, expect, afterEach } from "bun:test" +import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { DEFAULT_DBT_DIRS, type ChangedFile } from "../../src/altimate/review/diff-filter" +import { makeFinding, ruleId } from "../../src/altimate/review/finding" +import { + aiInputBudget, + planAiInput, + selectAiFilesByQuota, + type AiReviewFile, + type AiReviewInput, +} from "../../src/altimate/review/ai-review" + +// The `otherFiles` switch (ALTIMATE_REVIEW_AI_OTHER_FILES) sends changed other/analysis files to the AI lane. + +const runner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, +} as ReviewRunner + +const mod = (path: string, status: ChangedFile["status"] = "modified"): ChangedFile => ({ + path, + status, + diff: `@@ -1,1 +1,2 @@\n ${path}\n+changed_${path}\n`, +}) + +const CHANGED: ChangedFile[] = [ + mod("models/marts/m.sql"), + mod("macros/to_cents.sql"), + mod("analyses/revenue_check.sql"), + mod("scripts/load_raw.py"), + mod("integration_tests/ci.yml"), + mod("config/extra.yaml"), + mod("data/lookup.csv"), // other, extension not allowed + mod("scripts/gone.py", "deleted"), +] + +const OFF_ENV = ["ALTIMATE_REVIEW_AI_OTHER_FILES", "ALTIMATE_REVIEW_AI_QUOTA_OTHER"] +afterEach(() => { + for (const k of OFF_ENV) delete process.env[k] +}) + +async function lane(changed: ChangedFile[], opts: { flag?: boolean; layoutRoot?: string; finding?: string } = {}) { + if (opts.flag) process.env.ALTIMATE_REVIEW_AI_OTHER_FILES = "1" + else delete process.env.ALTIMATE_REVIEW_AI_OTHER_FILES + let seen: AiReviewInput | undefined + const env = await runReview({ + changedFiles: changed, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + ...(opts.layoutRoot !== undefined ? { layout: { root: opts.layoutRoot, dirs: DEFAULT_DBT_DIRS } } : {}), + getContent: async (f, side) => (side === "old" ? undefined : `-- head of ${f}\nchanged_${f}\n`), + generatedAt: "2026-11-24T00:00:00Z", + aiReview: async (input) => { + seen = input + const target = opts.finding ? input.files.find((f) => f.path === opts.finding) : undefined + const findings = target + ? [ + makeFinding({ + severity: "warning", + category: "sql_correctness", + title: `${target.model}: wrong filter`, + body: "The filter drops every row.", + file: target.path, + model: target.model, + startLine: 2, + endLine: 2, + confidence: "high", + evidence: { tool: "ai-review", result: {} }, + ruleKey: "ai:sql_correctness:wrong filter", + rule: ruleId("ai-review", "sql_correctness"), + }), + ] + : [] + return { findings, status: { state: "ok" } } + }, + }) + return { input: seen!, env } +} + +describe("ALTIMATE_REVIEW_AI_OTHER_FILES: orchestrator file list", () => { + test("unset: other and analysis files never reach the lane", async () => { + const { input } = await lane(CHANGED) + expect(input.files.map((f) => f.path)).toEqual(["models/marts/m.sql", "macros/to_cents.sql"]) + }) + + test("set: other/analysis files with allowed extensions are added after the rest, with head content", async () => { + const off = await lane(CHANGED) + const on = await lane(CHANGED, { flag: true }) + const paths = on.input.files.map((f) => f.path) + expect(paths.slice(0, off.input.files.length)).toEqual(off.input.files.map((f) => f.path)) + expect(paths.slice(off.input.files.length)).toEqual([ + "analyses/revenue_check.sql", + "scripts/load_raw.py", + "integration_tests/ci.yml", + "config/extra.yaml", + ]) + const byPath = new Map(on.input.files.map((f) => [f.path, f])) + expect(byPath.get("analyses/revenue_check.sql")).toMatchObject({ kind: "analysis", sql: "-- head of analyses/revenue_check.sql\nchanged_analyses/revenue_check.sql\n" }) + expect(byPath.get("scripts/load_raw.py")?.kind).toBe("other") + expect(paths).not.toContain("data/lookup.csv") + expect(paths).not.toContain("scripts/gone.py") + }) + + test("set: files outside the dbt project root stay excluded", async () => { + const changed = [mod("dbt/models/m.sql"), mod("dbt/analyses/a.sql"), mod("dbt/scripts/x.py"), mod("airflow/dags/load.py"), mod("infra/k8s.yaml")] + const { input } = await lane(changed, { flag: true, layoutRoot: "dbt" }) + expect(input.files.map((f) => f.path)).toEqual(["dbt/models/m.sql", "dbt/analyses/a.sql", "dbt/scripts/x.py"]) + }) + + test("set: an added file the lane sent is not listed as not reviewed; unset it is", async () => { + const off = await lane(CHANGED) + const on = await lane(CHANGED, { flag: true }) + const listed = (e: typeof on.env) => (e.scope?.notReviewed ?? []).map((n) => n.path) + expect(listed(off.env)).toContain("analyses/revenue_check.sql") + expect(listed(on.env)).not.toContain("analyses/revenue_check.sql") + expect(listed(on.env)).toContain("data/lookup.csv") + }) + + test("resolved switches win over the env variable", async () => { + process.env.ALTIMATE_REVIEW_AI_OTHER_FILES = "1" + let seen: AiReviewInput | undefined + await runReview({ + changedFiles: CHANGED, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiSwitches: { otherFiles: false }, + getContent: async (f, side) => (side === "old" ? undefined : `x`), + generatedAt: "2026-11-24T00:00:00Z", + aiReview: async (input) => { + seen = input + return { findings: [], status: { state: "ok" } } + }, + }) + expect(seen!.files.map((f) => f.path)).toEqual(["models/marts/m.sql", "macros/to_cents.sql"]) + }) + + test("set: a finding the model returns on an added file reaches the envelope", async () => { + const { env } = await lane(CHANGED, { flag: true, finding: "scripts/load_raw.py" }) + const f = env.findings.find((x) => x.file === "scripts/load_raw.py") + expect(f).toBeDefined() + expect(f!.rule).toBe(ruleId("ai-review", "sql_correctness")) + expect(f!.startLine).toBe(2) + }) +}) + +describe("ALTIMATE_REVIEW_AI_OTHER_FILES: planner", () => { + const file = (path: string, kind: string, lines = 1, status = "modified"): AiReviewFile => ({ + path, + status, + kind, + model: path, + diff: `@@ -1,1 +1,${lines} @@\n` + Array.from({ length: lines }, (_, i) => `+${path}_${i}`).join("\n"), + sql: `head of ${path}\n`, + }) + const COVERAGE = { ALTIMATE_REVIEW_AI_COVERAGE: "1" } + const base = [file("models/m.sql", "model_sql", 3), file("macros/x.sql", "macro", 2), file("models/_s.yml", "schema_yml")] + + test("flag off: the plan is byte-identical with or without the flag's quota variable", () => { + const a = planAiInput({ grounding: [], files: base }, COVERAGE) + const b = planAiInput({ grounding: [], files: base }, { ...COVERAGE, ALTIMATE_REVIEW_AI_QUOTA_OTHER: "3" }) + expect(b.messages).toEqual(a.messages) + expect(b.input).toEqual(a.input) + expect(aiInputBudget(COVERAGE).coverage).not.toHaveProperty("otherQuota") + }) + + test("flag on, no other files: the plan equals the flag-off plan", () => { + const off = planAiInput({ grounding: [], files: base }, COVERAGE) + const on = planAiInput({ grounding: [], files: base }, { ...COVERAGE, ALTIMATE_REVIEW_AI_OTHER_FILES: "1" }) + expect(on.messages).toEqual(off.messages) + expect(on.input).toEqual(off.input) + }) + + test("flag on: other/analysis files follow the existing files, under their own quota", () => { + const others = [ + file("scripts/a.py", "other", 1), + file("analyses/b.sql", "analysis", 5), + file("ci/c.yml", "other", 3), + ] + const env = { ...COVERAGE, ALTIMATE_REVIEW_AI_OTHER_FILES: "1", ALTIMATE_REVIEW_AI_QUOTA_OTHER: "2" } + const off = planAiInput({ grounding: [], files: base }, COVERAGE) + const on = planAiInput({ grounding: [], files: [...base, ...others] }, env) + // Existing files: same order, same sections. + expect(on.input.slice(0, off.input.length)).toEqual(off.input) + expect(on.messages[0].startsWith(off.messages[0].replace(/\nReturn ONLY the JSON array per the output contract\.$/, ""))).toBe(true) + // Added: the two most-changed others, with their kind on the input row; the third is unsent. + expect(on.input.slice(off.input.length).map((r) => [r.path, r.kind])).toEqual([ + ["analyses/b.sql", "analysis"], + ["ci/c.yml", "other"], + ]) + expect(on.unsent.map((f) => f.path)).toEqual(["scripts/a.py"]) + expect(on.messages[0]).toContain("### ci/c.yml (modified, other project file)") + expect(on.messages[0]).toContain("Current file:\n```yaml\nhead of ci/c.yml") + }) + + test("default quota is 8 and does not lend spare to the existing buckets", () => { + const models = Array.from({ length: 14 }, (_, i) => file(`models/m${i}.sql`, "model_sql")) + const others = Array.from({ length: 10 }, (_, i) => file(`scripts/s${i}.py`, "other")) + const quotas = aiInputBudget({ ...COVERAGE, ALTIMATE_REVIEW_AI_OTHER_FILES: "1" }).coverage! + expect(quotas.otherQuota).toBe(8) + const off = selectAiFilesByQuota(models, quotas.quotas) + const on = selectAiFilesByQuota([...models, ...others], quotas.quotas, quotas) + expect(on.sent.slice(0, off.sent.length)).toEqual(off.sent) + expect(on.sent.slice(off.sent.length).map((f) => f.path)).toEqual(others.slice(0, 8).map((f) => f.path)) + expect(on.sent.length).toBe(off.sent.length + 8) + }) + + test("deleted other files are never sent", () => { + const env = { ...COVERAGE, ALTIMATE_REVIEW_AI_OTHER_FILES: "1" } + const plan = planAiInput({ grounding: [], files: [...base, file("scripts/gone.py", "other", 1, "deleted")] }, env) + expect(plan.input.map((r) => r.path)).not.toContain("scripts/gone.py") + }) +}) From 373bd3e5316ef235f7c3013852533782961eb433 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 01:56:46 +0530 Subject: [PATCH 03/34] feat(review): send changed Python files to the AI lane (`pythonFiles` switch) - with `ai.pythonFiles` / `ALTIMATE_REVIEW_AI_PYTHON_FILES=1`, every changed `.py` file (not deleted, not a build or vendored path, not excluded, not credential-like) that the lane does not already send goes to it after every other file, as kind `python_file`, inside or outside the dbt project root - files outside the project root reach the orchestrator as `aiOutsideFiles`, read by the AI lane only; under coverage they take their own quota, `ALTIMATE_REVIEW_AI_QUOTA_PYTHON` (default 6); existing quotas, spare and order are unchanged - an outside file the lane sent and reviewed (the lane answered) is not listed as "outside the dbt project" in `scope.notReviewed`; it is recorded in `scope.aiReviewedOutside` and `outOfScopeFiles` drops by one; if the lane failed it stays listed - the stderr "were not reviewed" count leaves out the outside files the AI lane takes; a second line counts them - `--all-projects`: outside files go to the first touched project's AI lane only (`aiOutsidePython`), and the merge treats a path any project's AI lane reviewed as reviewed - off (the default in this commit), the lane's input and the scope are unchanged - tests: off unchanged, inside and outside files, quota, no double add with other files, scope after an ok and a failed lane, stderr lines, multi-project merge and a two-project dry run with the file in one project's input Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-python-files.ts | 19 + .../opencode/src/altimate/review/ai-review.ts | 27 +- .../src/altimate/review/multi-project.ts | 14 +- .../src/altimate/review/orchestrate.ts | 53 ++- packages/opencode/src/altimate/review/run.ts | 32 +- .../opencode/src/altimate/review/verdict.ts | 2 + .../altimate/review-ai-python-files.test.ts | 350 ++++++++++++++++++ 7 files changed, 475 insertions(+), 22 deletions(-) create mode 100644 packages/opencode/src/altimate/review/ai-python-files.ts create mode 100644 packages/opencode/test/altimate/review-ai-python-files.test.ts diff --git a/packages/opencode/src/altimate/review/ai-python-files.ts b/packages/opencode/src/altimate/review/ai-python-files.ts new file mode 100644 index 0000000000..7a14ba0f6f --- /dev/null +++ b/packages/opencode/src/altimate/review/ai-python-files.ts @@ -0,0 +1,19 @@ +// altimate_change - new file: changed Python files for the AI lane +// +// With the `pythonFiles` switch (`ALTIMATE_REVIEW_AI_PYTHON_FILES`), every changed, +// non-deleted `.py` file in the repository (inside or outside the dbt project root) that the +// lane does not already send goes to the AI lane, under its own coverage quota +// (`ALTIMATE_REVIEW_AI_QUOTA_PYTHON`), after the existing kinds. Files outside the project +// root reach the orchestrator only for the AI lane (`OrchestrateInput.aiOutsideFiles`); no +// rule lane reads them. Off, the lane's input is unchanged. +import { shouldReview } from "./diff-filter" + +/** Kind the added files carry in the AI lane. */ +export const AI_PYTHON_KIND = "python_file" +/** Default coverage quota for the added files. */ +export const AI_PYTHON_FILES_QUOTA = 6 + +/** A changed file the switch adds: `.py`, not deleted, not a build or vendored path. */ +export function isAiPythonFile(f: { path: string; status: string }): boolean { + return f.status !== "deleted" && f.path.toLowerCase().endsWith(".py") && shouldReview(f.path) +} diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 9ff97a528a..3d98890854 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -15,6 +15,7 @@ import { walkDiffLines } from "./diff-filter" import { CARD_BATCH_MAX_CHARS } from "./ai-context-card" import { type AiSwitches, 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" const log = Log.create({ service: "ai-review" }) @@ -55,8 +56,9 @@ export interface AiInputBudget { /** `ALTIMATE_REVIEW_AI_COVERAGE=1`: per-kind file quotas (replacing `maxFiles`) and * hunk-centred excerpts instead of head truncation. Undefined keeps today's input. * `otherQuota` (`otherFiles` switch): quota for other/analysis files, kept outside - * `quotas` so the existing buckets and their spare are unchanged. */ - coverage?: AiCoverageRender & { quotas: Record; otherQuota?: number } + * `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 } /** `ALTIMATE_REVIEW_AI_FOCUSED=1`: on PRs with at least `minFiles` selected files, review * related files together in calls of about `batchFiles` files, at most `maxBatches` calls * unless `batchChars` needs more. */ @@ -102,6 +104,9 @@ export function aiInputBudget( ...(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: @@ -184,8 +189,17 @@ const KIND_LABEL: Record = { // 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", } -const FENCE: Record = { schema_yml: "yaml", source_yml: "yaml", project_config: "yaml", seed: "csv", python_model: "python" } /** Code fence for a file's current content; `other`/`analysis` files by extension. */ function fenceOf(f: AiReviewFile): string { @@ -249,14 +263,16 @@ export function changedLineCount(diff: string | undefined): number { export function selectAiFilesByQuota( files: AiReviewFile[], quotas: Record = COVERAGE_QUOTAS, - extra: { otherQuota?: number } = {}, + 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)) + .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)) @@ -271,6 +287,7 @@ export function selectAiFilesByQuota( } 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)) } } diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 0cfa04f74e..d48ab19113 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -154,7 +154,14 @@ export async function reviewAllProjects(opts: ReviewPullRequestOptions): Promise for (const root of touched) { const own = byProject.get(root)! process.stderr.write(`ℹ️ reviewing dbt project ${root || "."} (${own.length} changed file(s))\n`) - const env = await reviewPullRequest({ ...optsFor(root), changedFiles: [...own, ...unassigned], prFiles, prRenames }) + // Python files outside every project go to one project's AI lane only (`pythonFiles`). + const env = await reviewPullRequest({ + ...optsFor(root), + changedFiles: [...own, ...unassigned], + prFiles, + prRenames, + aiOutsidePython: root === touched[0], + }) runs.push({ root, paths: own.map((f) => f.path), env }) } return mergeProjectEnvelopes(runs, roots) @@ -194,7 +201,9 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri const tierReasons = [...new Set(envs.flatMap((e) => e.tierReasons ?? []))] // A path some project reviewed is not "outside the dbt project" for the PR. - const reviewed = new Set(runs.flatMap((r) => r.paths)) + // So is a path outside every project that one project's AI lane reviewed. + const aiReviewedOutside = [...new Set(envs.flatMap((e) => e.scope?.aiReviewedOutside ?? []))] + const reviewed = new Set([...runs.flatMap((r) => r.paths), ...aiReviewedOutside]) const notReviewed: Array<{ path: string; reason: string }> = [] const seenEntry = new Set() for (const e of envs) { @@ -251,6 +260,7 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri headParents: first.scope?.headParents, coveredProjects: coveredProjects ?? runs.map((r) => r.root), outOfScopeFiles: outsideCount || undefined, + aiReviewedOutside: aiReviewedOutside.length ? aiReviewedOutside : undefined, movedUnchangedFiles: movedCount || undefined, unverified: unverified.length ? unverified : undefined, notReviewed, diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index e1ecce99e7..4e30a945c5 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -66,6 +66,7 @@ import { type MacroCard, type ModelCard, attachContextCards } from "./ai-context import { ruleTier } from "./rule-tiers" import { type AiSwitches, switchOn } from "./ai-switches" import { isAiOtherFile } from "./ai-other-files" +import { AI_PYTHON_KIND, isAiPythonFile } from "./ai-python-files" import { type AiVerifyEvidence, numberedSlice } from "./ai-verify" import { holdsCredentials, isCredentialPath } from "./credentials" import type { ColumnReach } from "../native/dbt/column-reach" @@ -293,6 +294,8 @@ export interface OrchestrateInput { aiVerify?: boolean /** The review's resolved AI switches (ai-switches.ts); without them each switch reads its env variable. */ aiSwitches?: Partial + /** Changed files outside the dbt project, for the AI lane only (`pythonFiles` switch). */ + aiOutsideFiles?: ChangedFile[] /** Fixed-string search over the dbt project at head, for the verifier. */ grepProject?: AiVerifyEvidence["grepProject"] /** Every file the PR changes (repo-relative), including files outside the dbt project; the verifier may read them. */ @@ -2634,6 +2637,9 @@ export async function runReview(input: OrchestrateInput): Promise f.path)) + const python = [...reviewable, ...(input.aiOutsideFiles ?? [])].filter( + (f) => + isAiPythonFile(f) && + !mayHoldCredentials(f.path) && + !isExcludedPath(f.path, input.rubric.exclusions.excludeGlobs) && + !queued.has(f.path) && + !!queued.add(f.path), + ) + const pyContents = await Promise.all(python.map((f) => getContent?.(f.path, "new")?.catch(() => undefined))) + python.forEach((f, i) => + aiFiles.push( + ...screened({ path: f.path, status: f.status, model: modelNameFromPath(f.path), kind: AI_PYTHON_KIND, diff: f.diff, sql: pyContents[i] }), + ), + ) + } // Only the files the AI lane will send are reached (its file cap, or the // per-kind quotas in coverage mode); the rest stay in the ledger. const aiBudget = aiInputBudget(process.env, input.aiSwitches) - touch( - aiBudget.coverage - ? selectAiFilesByQuota(aiFiles, aiBudget.coverage.quotas, aiBudget.coverage).sent - : selectAiFiles(aiFiles, aiBudget.maxFiles), - ) + const aiSent = aiBudget.coverage + ? selectAiFilesByQuota(aiFiles, aiBudget.coverage.quotas, aiBudget.coverage).sent + : selectAiFiles(aiFiles, aiBudget.maxFiles) + touch(aiSent) + const outsidePaths = new Set((input.aiOutsideFiles ?? []).map((f) => f.path)) + aiOutsideSent = aiSent.filter((f) => outsidePaths.has(f.path)).map((f) => f.path) if (input.aiContextCard && anyManifest) await attachContextCards(aiFiles, input.runner) const context = input.aiGraphContext ? await aiGraphContext(aiFiles.map((f) => f.path), input.runner, getContent) : undefined // Files the PR changes that the AI may list and the verifier may read; never the user's exclusions or credentials. @@ -2771,6 +2797,8 @@ export async function runReview(input: OrchestrateInput): Promise a.path.localeCompare(b.path)) + // An outside-project file the AI lane reviewed is not "outside the dbt project, not reviewed". + const aiReviewedSet = new Set(aiReviewedOutside) + const inputNotReviewed = (input.scope?.notReviewed ?? []).filter((n) => !aiReviewedSet.has(n.path)) const ledger: NotReviewed[] = [ - ...(input.scope?.notReviewed ?? []), + ...inputNotReviewed, ...dropped, ...reviewable // Other/analysis files the AI lane sent (`otherFiles`) were reviewed. @@ -2828,7 +2859,15 @@ export async function runReview(input: OrchestrateInput): Promise + /** Send changed Python files outside the dbt project to this review's AI lane (`pythonFiles` + * switch). Default true; `--all-projects` sets it for one project only. */ + aiOutsidePython?: boolean } /** dbt adapter_type → core SQL dialect. Mostly identity; a few aliases. */ @@ -364,9 +368,26 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise const collected = opts.changedFiles ?? (await collectChangedFiles({ base, head: opts.head, cwd: opts.cwd })) const scoped = scopeToProject(collected, projectRootRel, layout) const changedFiles = scoped.inScope - if (scoped.outOfScope > 0) { + let aiDisabledReason: string | undefined + if (opts.noAi) aiDisabledReason = "disabled by --no-ai" + else if (!aiLaneEnabled(config)) aiDisabledReason = "disabled by `ai: false` in .altimate/review.yml" + const aiOn = !aiDisabledReason + const aiSwitches = resolveAiSwitches(config) + // `pythonFiles`: .py files outside the dbt project skip every lane but the AI lane. + const outside = new Set(scoped.outOfScopePaths) + const aiOutsideFiles = + aiOn && aiSwitches.pythonFiles && opts.aiOutsidePython !== false + ? collected.filter((f) => outside.has(f.path) && isAiPythonFile(f)) + : [] + const notReviewedOutside = scoped.outOfScope - aiOutsideFiles.length + if (notReviewedOutside > 0) { + process.stderr.write( + `ℹ️ ${notReviewedOutside} changed file(s) outside the dbt project (${projectRootRel || "."}) were not reviewed.\n`, + ) + } + if (aiOutsideFiles.length > 0) { process.stderr.write( - `ℹ️ ${scoped.outOfScope} changed file(s) outside the dbt project (${projectRootRel || "."}) were not reviewed.\n`, + `ℹ️ ${aiOutsideFiles.length} changed Python file(s) outside the dbt project (${projectRootRel || "."}) go to the AI review only.\n`, ) } // Map renamed files → their old path so getContent resolves the "old" side @@ -447,12 +468,6 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise ? undefined : makeCompiledResolver({ cwd: dbtRootReal, projectName, pathPrefix }) - let aiDisabledReason: string | undefined - if (opts.noAi) aiDisabledReason = "disabled by --no-ai" - else if (!aiLaneEnabled(config)) aiDisabledReason = "disabled by `ai: false` in .altimate/review.yml" - const aiOn = !aiDisabledReason - const aiSwitches = resolveAiSwitches(config) - const consumerLists = config.consumerColumnLists.length ? await loadConsumerLists({ configs: config.consumerColumnLists, @@ -489,6 +504,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise aiContextCard: aiSwitches.contextCard, aiVerify: aiSwitches.verify, aiSwitches, + ...(aiOutsideFiles.length ? { aiOutsideFiles } : {}), grepProject: (pattern, glob) => { // The project's dbt directories (repo-relative), or one glob inside the project. const dirs = layout diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index 6e5c54f5df..e562612aeb 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -134,6 +134,8 @@ export const ReviewScope = z.object({ projectRoot: z.string().optional(), /** Changed files outside the dbt project: counted, not reviewed. */ outOfScopeFiles: z.number().int().nonnegative().optional(), + /** Changed files outside the dbt project that only the AI lane reviewed (Python files). */ + aiReviewedOutside: z.array(z.string()).optional(), /** Non-model renames with unchanged content, name, role and layer (pure moves): not re-reviewed. */ movedUnchangedFiles: z.number().int().nonnegative().optional(), /** Head commit the review ran on; a run on an older push never clears a block. */ diff --git a/packages/opencode/test/altimate/review-ai-python-files.test.ts b/packages/opencode/test/altimate/review-ai-python-files.test.ts new file mode 100644 index 0000000000..f40a2c6000 --- /dev/null +++ b/packages/opencode/test/altimate/review-ai-python-files.test.ts @@ -0,0 +1,350 @@ +import { describe, test, expect, afterEach } from "bun:test" +import path from "node:path" +import os from "node:os" +import { promises as fs } from "node:fs" +import { execFileSync } from "node:child_process" +import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { DEFAULT_DBT_DIRS, type ChangedFile } from "../../src/altimate/review/diff-filter" +import { aiInputBudget, planAiInput, selectAiFilesByQuota, type AiReviewFile, type AiReviewInput } from "../../src/altimate/review/ai-review" +import { AI_PYTHON_KIND, isAiPythonFile } from "../../src/altimate/review/ai-python-files" +import { mergeProjectEnvelopes, reviewAllProjects } from "../../src/altimate/review/multi-project" + +// The `pythonFiles` switch (ALTIMATE_REVIEW_AI_PYTHON_FILES) sends changed .py files, inside or outside the dbt project, to the AI lane. + +const runner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, +} as ReviewRunner + +const mod = (p: string, status: ChangedFile["status"] = "modified"): ChangedFile => ({ + path: p, + status, + diff: `@@ -1,1 +1,2 @@\n ${p}\n+changed_${p}\n`, +}) + +const KEYS = [ + "ALTIMATE_REVIEW_AI_PYTHON_FILES", + "ALTIMATE_REVIEW_AI_QUOTA_PYTHON", + "ALTIMATE_REVIEW_AI_OTHER_FILES", + "ALTIMATE_REVIEW_AI_COVERAGE", + "ALTIMATE_REVIEW_AI_DRYRUN", + "GITHUB_EVENT_PATH", + "GITHUB_BASE_REF", + "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", +] +const saved = Object.fromEntries(KEYS.map((k) => [k, process.env[k]])) +afterEach(() => { + for (const k of KEYS) { + if (saved[k] === undefined) delete process.env[k] + else process.env[k] = saved[k] + } +}) + +async function lane(changed: ChangedFile[], opts: { flags?: Record; layoutRoot?: string; outside?: ChangedFile[] } = {}) { + for (const k of ["ALTIMATE_REVIEW_AI_PYTHON_FILES", "ALTIMATE_REVIEW_AI_OTHER_FILES"]) delete process.env[k] + Object.assign(process.env, opts.flags ?? {}) + let seen: AiReviewInput | undefined + await runReview({ + changedFiles: changed, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + ...(opts.layoutRoot !== undefined ? { layout: { root: opts.layoutRoot, dirs: DEFAULT_DBT_DIRS } } : {}), + ...(opts.outside ? { aiOutsideFiles: opts.outside } : {}), + getContent: async (f, side) => (side === "old" ? undefined : `# head of ${f}\n`), + generatedAt: "2026-11-24T00:00:00Z", + aiReview: async (input) => { + seen = input + return { findings: [], status: { state: "ok" } } + }, + }) + return seen! +} + +const PY = { ALTIMATE_REVIEW_AI_PYTHON_FILES: "1" } +const OTHER = { ALTIMATE_REVIEW_AI_OTHER_FILES: "1" } +const IN_ROOT: ChangedFile[] = [ + mod("dbt/models/m.sql"), + mod("dbt/models/py_model.py"), + mod("dbt/scripts/helper.py"), + mod("dbt/analyses/check.py"), + mod("dbt/scripts/gone.py", "deleted"), + mod("dbt/target/run/compiled.py"), +] +const OUTSIDE: ChangedFile[] = [mod("airflow/dags/load.py"), mod("tools/.venv/lib/x.py")] + +describe("isAiPythonFile", () => { + test(".py, not deleted, not a build or vendored path", () => { + expect(isAiPythonFile({ path: "a/b.py", status: "added" })).toBe(true) + expect(isAiPythonFile({ path: "a/B.PY", status: "modified" })).toBe(true) + expect(isAiPythonFile({ path: "a/b.py", status: "deleted" })).toBe(false) + expect(isAiPythonFile({ path: "a/b.sql", status: "modified" })).toBe(false) + expect(isAiPythonFile({ path: "x/.venv/b.py", status: "modified" })).toBe(false) + expect(isAiPythonFile({ path: "target/b.py", status: "modified" })).toBe(false) + }) +}) + +describe("ALTIMATE_REVIEW_AI_PYTHON_FILES: orchestrator file list", () => { + test("unset: the lane input is unchanged, outside files given or not", async () => { + const plain = await lane(IN_ROOT, { layoutRoot: "dbt" }) + const withOutside = await lane(IN_ROOT, { layoutRoot: "dbt", outside: OUTSIDE }) + expect(withOutside.files).toEqual(plain.files) + expect(plain.files.map((f) => f.path)).toEqual(["dbt/models/m.sql", "dbt/models/py_model.py"]) + }) + + test("set: .py files inside and outside the root follow every other file, as python_file, with head content", async () => { + const off = await lane(IN_ROOT, { layoutRoot: "dbt" }) + const on = await lane(IN_ROOT, { layoutRoot: "dbt", outside: OUTSIDE, flags: PY }) + expect(on.files.slice(0, off.files.length)).toEqual(off.files) + expect(on.files.slice(off.files.length).map((f) => [f.path, f.kind, f.sql])).toEqual([ + ["dbt/scripts/helper.py", AI_PYTHON_KIND, "# head of dbt/scripts/helper.py\n"], + ["dbt/analyses/check.py", AI_PYTHON_KIND, "# head of dbt/analyses/check.py\n"], + ["airflow/dags/load.py", AI_PYTHON_KIND, "# head of airflow/dags/load.py\n"], + ]) + // The Python model is not sent twice; deleted and build-output files never are. + expect(on.files.filter((f) => f.path === "dbt/models/py_model.py")).toHaveLength(1) + }) + + test("with ALTIMATE_REVIEW_AI_OTHER_FILES: files it adds are not added again", async () => { + const other = await lane(IN_ROOT, { layoutRoot: "dbt", flags: OTHER }) + const both = await lane(IN_ROOT, { layoutRoot: "dbt", outside: OUTSIDE, flags: { ...OTHER, ...PY } }) + expect(both.files.slice(0, other.files.length)).toEqual(other.files) + expect(other.files.map((f) => f.path)).toContain("dbt/scripts/helper.py") + expect(both.files.slice(other.files.length).map((f) => f.path)).toEqual(["airflow/dags/load.py"]) + const paths = both.files.map((f) => f.path) + expect(new Set(paths).size).toBe(paths.length) + }) +}) + +describe("ALTIMATE_REVIEW_AI_PYTHON_FILES: planner", () => { + const file = (p: string, kind: string, lines = 1, status = "modified"): AiReviewFile => ({ + path: p, + status, + kind, + model: p, + diff: `@@ -1,1 +1,${lines} @@\n` + Array.from({ length: lines }, (_, i) => `+${p}_${i}`).join("\n"), + sql: `head of ${p}\n`, + }) + const COVERAGE = { ALTIMATE_REVIEW_AI_COVERAGE: "1" } + const base = [file("models/m.sql", "model_sql", 3), file("macros/x.sql", "macro", 2), file("models/_s.yml", "schema_yml")] + + test("flag off: byte-identical plan with or without the quota variable; no pythonQuota", () => { + for (const env of [{}, COVERAGE]) { + const a = planAiInput({ grounding: [], files: base }, env) + const b = planAiInput({ grounding: [], files: base }, { ...env, ALTIMATE_REVIEW_AI_QUOTA_PYTHON: "2" }) + expect(b.messages).toEqual(a.messages) + expect(b.input).toEqual(a.input) + } + expect(aiInputBudget(COVERAGE).coverage).not.toHaveProperty("pythonQuota") + expect(aiInputBudget({ ...COVERAGE, ...PY }).coverage?.pythonQuota).toBe(6) + }) + + test("flag on, no Python files: the plan equals the flag-off plan", () => { + for (const env of [{}, COVERAGE]) { + const off = planAiInput({ grounding: [], files: base }, env) + const on = planAiInput({ grounding: [], files: base }, { ...env, ...PY }) + expect(on.messages).toEqual(off.messages) + expect(on.input).toEqual(off.input) + } + }) + + test("flag on: Python files follow the other files under their own quota, most-changed first, with a python fence", () => { + const others = [file("scripts/o.sql", "other", 1)] + const py = [file("a.py", AI_PYTHON_KIND, 1), file("b.py", AI_PYTHON_KIND, 5), file("c.py", AI_PYTHON_KIND, 3)] + const env = { ...COVERAGE, ...OTHER, ...PY, ALTIMATE_REVIEW_AI_QUOTA_PYTHON: "2" } + const off = planAiInput({ grounding: [], files: [...base, ...others] }, { ...COVERAGE, ...OTHER }) + const on = planAiInput({ grounding: [], files: [...base, ...py, ...others] }, env) + expect(on.input.slice(0, off.input.length)).toEqual(off.input) + expect(on.input.slice(off.input.length).map((r) => [r.path, r.kind])).toEqual([ + ["b.py", AI_PYTHON_KIND], + ["c.py", AI_PYTHON_KIND], + ]) + expect(on.unsent.map((f) => f.path)).toEqual(["a.py"]) + expect(on.messages[0]).toContain("### b.py (modified, Python file)") + expect(on.messages[0]).toContain("Current file:\n```python\nhead of b.py") + }) + + test("the quota lends no spare to the existing buckets, and theirs none to it", () => { + const models = Array.from({ length: 14 }, (_, i) => file(`models/m${i}.sql`, "model_sql")) + const py = Array.from({ length: 9 }, (_, i) => file(`scripts/s${i}.py`, AI_PYTHON_KIND)) + const q = aiInputBudget({ ...COVERAGE, ...PY }).coverage! + const off = selectAiFilesByQuota(models, q.quotas) + const on = selectAiFilesByQuota([...models, ...py], q.quotas, { pythonQuota: q.pythonQuota }) + expect(on.sent.slice(0, off.sent.length)).toEqual(off.sent) + expect(on.sent.slice(off.sent.length).map((f) => f.path)).toEqual(py.slice(0, 6).map((f) => f.path)) + }) +}) + +describe("reviewPullRequest end to end: .py files outside the dbt project reach the lane only under the flag", () => { + const git = (cwd: string, ...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { + cwd, + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }).toString() + const write = async (root: string, rel: string, body: string) => { + await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) + await fs.writeFile(path.join(root, rel), body) + } + + test("AI dry run: ai.input lists the outside .py file as python_file; unset it is out of scope only", async () => { + const { reviewPullRequest } = await import("../../src/altimate/review/run") + const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-py-e2e-"))) + try { + await write(root, "dbt/dbt_project.yml", "name: p\n") + await write(root, "dbt/models/m.sql", "select 1 as id\n") + await write(root, "airflow/dags/load.py", "print(1)\n") + await write(root, "airflow/old.py", "print(0)\n") + git(root, "init", "-q", "-b", "main") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "base") + git(root, "checkout", "-q", "-b", "pr") + await write(root, "dbt/models/m.sql", "select 1 as id, 2 as x\n") + await write(root, "airflow/dags/load.py", "print(2)\n") + await write(root, "README.md", "docs\n") + await fs.rm(path.join(root, "airflow/old.py")) + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "pr") + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]) delete process.env[k] + process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" + const lines: string[] = [] + const write0 = process.stderr.write.bind(process.stderr) + ;(process.stderr as any).write = (chunk: any, ...rest: any[]) => { + lines.push(String(chunk)) + return write0(chunk, ...rest) + } + const outsideLines = () => lines.filter((l) => l.includes("outside the dbt project")) + const off = await reviewPullRequest({ cwd: path.join(root, "dbt"), base: "main", head: "HEAD" }) + expect(outsideLines()).toEqual(["ℹ️ 3 changed file(s) outside the dbt project (dbt) were not reviewed.\n"]) + lines.length = 0 + expect(off.ai?.input?.map((r) => r.path)).toEqual(["dbt/models/m.sql"]) + expect(off.scope?.outOfScopeFiles).toBe(3) + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" + const on = await reviewPullRequest({ cwd: path.join(root, "dbt"), base: "main", head: "HEAD" }) + expect(on.ai?.input?.map((r) => [r.path, r.kind])).toEqual([ + ["dbt/models/m.sql", "model_sql"], + ["airflow/dags/load.py", AI_PYTHON_KIND], + ]) + expect(on.findings).toEqual(off.findings) + // The stderr count leaves out the file the AI lane takes. + expect(outsideLines()).toEqual([ + "ℹ️ 2 changed file(s) outside the dbt project (dbt) were not reviewed.\n", + "ℹ️ 1 changed Python file(s) outside the dbt project (dbt) go to the AI review only.\n", + ]) + ;(process.stderr as any).write = write0 + // The dry run made no model call, so the file is still listed as not reviewed. + expect(on.scope?.notReviewed.map((n) => n.path)).toContain("airflow/dags/load.py") + expect(on.scope?.aiReviewedOutside).toBeUndefined() + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) +}) + +describe("outside-project Python files the AI lane reviewed are not listed as not reviewed", () => { + const outsideScope = (paths: string[]) => ({ + projectRoot: "dbt", + outOfScopeFiles: paths.length, + notReviewed: paths.map((p) => ({ path: p, reason: "outside the dbt project (dbt)" })), + }) + async function run(state: "ok" | "error") { + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" + return runReview({ + changedFiles: [mod("dbt/models/m.sql")], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + layout: { root: "dbt", dirs: DEFAULT_DBT_DIRS }, + aiOutsideFiles: [mod("airflow/load.py")], + scope: outsideScope(["airflow/load.py", "README.md"]), + getContent: async (f, side) => (side === "old" ? undefined : `x`), + generatedAt: "2026-11-25T00:00:00Z", + aiReview: async () => ({ findings: [], status: state === "ok" ? { state: "ok" } : { state: "error", reason: "boom" } }), + }) + } + + test("lane answered: dropped from notReviewed, recorded as aiReviewedOutside, count lowered", async () => { + const env = await run("ok") + expect(env.scope?.notReviewed.map((n) => n.path)).toEqual(["README.md"]) + expect(env.scope?.aiReviewedOutside).toEqual(["airflow/load.py"]) + expect(env.scope?.outOfScopeFiles).toBe(1) + }) + + test("lane failed: still listed as outside the project, not reviewed", async () => { + const env = await run("error") + expect(env.scope?.notReviewed.map((n) => n.path)).toEqual(["airflow/load.py", "README.md"]) + expect(env.scope?.aiReviewedOutside).toBeUndefined() + expect(env.scope?.outOfScopeFiles).toBe(2) + }) + + test("multi-project merge: a path one project's AI lane reviewed is not listed by the others", async () => { + const a = await run("ok") + const b = await run("error") + const merged = mergeProjectEnvelopes([ + { root: "dbt", paths: ["dbt/models/m.sql"], env: a }, + { root: "other", paths: [], env: b }, + ]) + expect(merged.scope?.notReviewed.map((n) => n.path)).toEqual(["README.md"]) + expect(merged.scope?.aiReviewedOutside).toEqual(["airflow/load.py"]) + expect(merged.scope?.outOfScopeFiles).toBe(1) + }) +}) + +describe("--all-projects: an outside-project Python file goes to one project's AI lane", () => { + const git = (cwd: string, ...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { + cwd, + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }).toString() + const write = async (root: string, rel: string, body: string) => { + await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) + await fs.writeFile(path.join(root, rel), body) + } + + test("AI dry run over two projects: the outside .py file is in one project's input", async () => { + const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-py-mp-"))) + try { + await write(root, "a/dbt_project.yml", "name: a\n") + await write(root, "a/models/m.sql", "select 1 as id\n") + await write(root, "b/dbt_project.yml", "name: b\n") + await write(root, "b/models/n.sql", "select 1 as id\n") + await write(root, "airflow/load.py", "print(1)\n") + git(root, "init", "-q", "-b", "main") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "base") + git(root, "checkout", "-q", "-b", "pr") + await write(root, "a/models/m.sql", "select 1 as id, 2 as x\n") + await write(root, "b/models/n.sql", "select 1 as id, 3 as y\n") + await write(root, "airflow/load.py", "print(2)\n") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "pr") + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]) delete process.env[k] + process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" + const env = await reviewAllProjects({ cwd: root, base: "main", head: "HEAD" }) + const py = (env.ai?.input ?? []).filter((r) => r.path === "airflow/load.py") + expect(py.length).toBe(1) + expect(env.ai?.input?.map((r) => r.path).sort()).toEqual(["a/models/m.sql", "airflow/load.py", "b/models/n.sql"]) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) +}) From 35c93a35c336f7d791eae3ba5a8c66bd1979c3df Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 01:57:11 +0530 Subject: [PATCH 04/34] feat(review): `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE` replaces the finder's system prompt - the finder prompt still comes from the compiled core; when the variable names a file, its text replaces the core prompt for every finder call (the test-gap addition still applies) - an unreadable or empty file is an error reported as the lane's state, never a silent fallback to the core prompt - env only: a `.altimate/review.yml` key would point at a file the PR can edit - tests: core prompt when unset, file text when set without asking core, empty and missing files are errors Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-review.ts | 22 ++++++++++-- .../altimate/review-ai-system-prompt.test.ts | 34 +++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 packages/opencode/test/altimate/review-ai-system-prompt.test.ts diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 3d98890854..339ce514c8 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -7,6 +7,7 @@ import { MessageID, SessionID } from "@/session/schema" import { Log } from "@/altimate/util/log" import { redactSecrets } from "@/installation" import { Dispatcher } from "../native" +import { readFile } from "node:fs/promises" import { type Finding, type ReviewCategory, type Severity, makeFinding, ruleId } from "./finding" import { readStreamText } from "../llm/stream-text" import { type AiVerifyEvidence, type VerifierStatus, runAiVerify } from "./ai-verify" @@ -911,6 +912,22 @@ function buildBatchMessage( 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. + */ +export async function finderSystemPrompt(env: Record = process.env): Promise { + const file = env.ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE + if (file) { + const text = await readFile(file, "utf8") + if (!text.trim()) throw new Error(`ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE is empty: ${file}`) + 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 @@ -977,9 +994,8 @@ export async function runAiReview(input: AiReviewInput): Promise let modelLabel: string | undefined try { - // Prompt comes from the compiled core, not this file. - const promptRes = await Dispatcher.call("altimate_core.review_ai_prompt", {}) - const corePrompt = ((promptRes.data ?? {}) as Record).prompt as string | undefined + // Prompt comes from the compiled core, not this file (or ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE). + const corePrompt = await finderSystemPrompt() if (!corePrompt) return done([], { state: "error", reason: "the core reviewer prompt is unavailable" }) const testGap = aiTestGapEnabled() const system = testGap ? corePrompt + TEST_GAP_INSTRUCTION : corePrompt diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts new file mode 100644 index 0000000000..15d5269653 --- /dev/null +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -0,0 +1,34 @@ +import { describe, test, expect, spyOn, afterEach } from "bun:test" +import path from "node:path" +import { promises as fs } from "node:fs" +import { finderSystemPrompt } from "../../src/altimate/review/ai-review" +import { Dispatcher } from "../../src/altimate/native" +import { tmpdir } from "../fixture/fixture" + +describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { + let spy: ReturnType | undefined + afterEach(() => spy?.mockRestore()) + + test("unset: the core prompt", async () => { + spy = spyOn(Dispatcher, "call").mockResolvedValue({ success: true, data: { prompt: "CORE" } } as any) + expect(await finderSystemPrompt({})).toBe("CORE") + expect(spy).toHaveBeenCalledWith("altimate_core.review_ai_prompt", {}) + }) + + test("set: the file's text replaces the core prompt, core not asked", async () => { + await using tmp = await tmpdir() + const file = path.join(tmp.path, "p.txt") + await fs.writeFile(file, "FILE PROMPT") + spy = spyOn(Dispatcher, "call").mockResolvedValue({ success: true, data: { prompt: "CORE" } } as any) + expect(await finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file })).toBe("FILE PROMPT") + expect(spy).not.toHaveBeenCalled() + }) + + test("an empty or missing file is an error, not a fallback", async () => { + await using tmp = await tmpdir() + const file = path.join(tmp.path, "empty.txt") + await fs.writeFile(file, " \n") + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file })).rejects.toThrow("is empty") + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: path.join(tmp.path, "none.txt") })).rejects.toThrow() + }) +}) From 84608a44a1d84bd450c81f08f762e4443490e0c7 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 01:59:40 +0530 Subject: [PATCH 05/34] fix(review): AI findings the verifier left unreviewed on budget go to the summary - when a verifier batch answers early on its token or tool-output budget (`budget` state), the findings it gave no verdict for were kept inline, unverified; under the open fail mode they now go to the summary (`verification.decision: summary`, rule `unreviewed_stopped`), counted under `summary` - a batch that finished normally keeps an omitted finding as before; timeouts and errors are unchanged; the closed fail mode still discards - `retriage` replays the new rule from recorded decisions - tests: budget demotion and inline eligibility, normal batch unchanged, closed fail mode Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-verify.ts | 31 ++++++++++++--- .../test/altimate/review-ai-verify.test.ts | 38 +++++++++++++++++++ 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-verify.ts b/packages/opencode/src/altimate/review/ai-verify.ts index 164fc6d8dd..84a6d53222 100644 --- a/packages/opencode/src/altimate/review/ai-verify.ts +++ b/packages/opencode/src/altimate/review/ai-verify.ts @@ -465,10 +465,15 @@ export function triage( ts: TsFeatures, m: ModelFeatures | undefined, knobs: TriageKnobs, + stopped = false, ): { decision: Decision; rule: string } { + // A finding left without a verdict because its batch stopped on the token or tool-output + // budget was never checked: under the open fail mode it goes to the summary, not inline. if (!m) return knobs.failMode === "open" - ? { decision: "keep", rule: "unreviewed" } + ? stopped + ? { decision: "summary", rule: "unreviewed_stopped" } + : { decision: "keep", rule: "unreviewed" } : { decision: "discard", rule: "unreviewed" } if (ts.restatesGrounding) return { decision: "discard", rule: "duplicate_of_engine" } if (m.verdict === "refuted") { @@ -564,7 +569,7 @@ export function retriage( m = { ...rest, evidence: hasEvidence ? "(recorded)" : "" } if (knobs.claimsOtherFileAsCrossFile && d.ts.claimsOtherFile) m.claimType = "cross_file" } else counts.unreviewed++ - const { decision, rule } = triage(d, d.ts, m, knobs) + const { decision, rule } = triage(d, d.ts, m, knobs, d.rule === "unreviewed_stopped") if (decision === "discard") counts.discarded++ else if (decision === "summary") counts.summary++ else counts.kept++ @@ -601,6 +606,8 @@ export function applyTriage( ts: TsFeatures[], model: Array, knobs: TriageKnobs, + /** Per finding: its batch answered early on the budget (`budget` state). */ + stopped: boolean[] = [], ): { findings: Finding[] dropped: DroppedFinding[] @@ -615,7 +622,7 @@ export function applyTriage( const m = model[i] if (m) counts.reviewed++ else counts.unreviewed++ - const { decision, rule } = triage(f, ts[i], m, knobs) + const { decision, rule } = triage(f, ts[i], m, knobs, stopped[i] === true) decisions.push(compactDecision(f, ts[i], m, decision, rule)) if (decision === "discard") { counts.discarded++ @@ -637,7 +644,17 @@ export function applyTriage( if (decision === "summary") counts.summary++ else counts.kept++ if (!m) { - out.push(f) + // An unreviewed finding demoted to the summary carries only the decision and its rule. + if (decision !== "summary") out.push(f) + else { + const prior = + f.evidence?.result && typeof f.evidence.result === "object" ? (f.evidence.result as Record) : {} + out.push({ + ...f, + evidence: { tool: f.evidence?.tool ?? "ai-review", result: { ...prior, verification: { decision, rule } } }, + tier: "summary" as const, + }) + } return } const verification: Verification = { @@ -1240,7 +1257,11 @@ export async function runAiVerify( const model: Array = input.findings.map(() => undefined) batches.forEach((b, k) => b.idx.forEach((i, j) => (model[i] = outcomes[k].verdicts.get(b.ids[j])))) - const triaged = applyTriage(input.findings, ts, model, triageKnobs(env)) + const stopped: boolean[] = input.findings.map(() => false) + batches.forEach((b, k) => { + if (outcomes[k].state === "budget") for (const i of b.idx) stopped[i] = true + }) + const triaged = applyTriage(input.findings, ts, model, triageKnobs(env), stopped) for (const d of triaged.dropped) log.info("ai verify dropped", { id: d.id, file: d.file, rule: d.rule, verdict: d.verdict }) diff --git a/packages/opencode/test/altimate/review-ai-verify.test.ts b/packages/opencode/test/altimate/review-ai-verify.test.ts index 8637401631..92210beeca 100644 --- a/packages/opencode/test/altimate/review-ai-verify.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify.test.ts @@ -1632,3 +1632,41 @@ describe("decisions[]: offline re-triage from one run's envelope", () => { }) }) }) + +describe("runAiVerify: findings left unreviewed when a batch stops", () => { + const two = () => [aiFinding({ title: "fct: first claim" }), aiFinding({ title: "fct: second claim", startLine: 11, endLine: 11 })] + const big = { tokens: { input: 30_000, inputTotal: 30_000, output: 10, reasoning: 0, cacheRead: 0 }, cost: 0 } + + test("budget: the finding without a verdict goes to the summary, not inline", async () => { + const { llm } = scripted((req) => + req.toolChoice === "none" ? { text: JSON.stringify([verdict("c1")]) } : toolStep([["pr_description", {}]], big), + ) + const { findings, status } = await verify(two(), llm) + expect(status.state).toBe("budget") + expect(status.reviewed).toBe(1) + expect(status.unreviewed).toBe(1) + expect(status.summary).toBe(1) + const second = findings.find((f) => f.title === "fct: second claim")! + expect(second.tier).toBe("summary") + expect(inlineEligible({ ...second, tier: "inline" }, DEFAULT_POSTING_POLICY)).toBe(false) + expect(status.decisions?.find((d) => d.id === second.id)?.rule).toBe("unreviewed_stopped") + }) + + test("a batch that finished normally keeps an omitted finding as before (open fail mode)", async () => { + const { llm } = scripted(() => ({ text: JSON.stringify([verdict("c1")]) })) + const { findings, status } = await verify(two(), llm) + expect(status.state).toBe("ok") + expect(status.unreviewed).toBe(1) + expect(status.summary).toBe(0) + const second = findings.find((f) => f.title === "fct: second claim")! + expect(inlineEligible({ ...second, tier: "inline" }, DEFAULT_POSTING_POLICY)).toBe(true) + }) + + test("the closed fail mode still discards it", async () => { + const { llm } = scripted((req) => + req.toolChoice === "none" ? { text: JSON.stringify([verdict("c1")]) } : toolStep([["pr_description", {}]], big), + ) + const { findings } = await verify(two(), llm, {}, { env: { ALTIMATE_REVIEW_AI_VERIFY_FAIL: "closed" } }) + expect(findings.map((f) => f.title)).toEqual(["fct: first claim"]) + }) +}) From e3c5b2d20f24ba516b96230f576cb8eac603cd8e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 02:02:22 +0530 Subject: [PATCH 06/34] feat(review): the measured AI lane configuration on by default - coverage quotas and hunk excerpts, manifest context cards, focused batches, other project files, Python files and the AI verifier are now on whenever the AI lane runs; measured together, this configuration found more real defects per PR with fewer wrong comments than the opt-in pieces alone - each one is opt-out with `ai: { : false }` in `.altimate/review.yml` (read from the base branch) or its env variable set to `0`; `1` still turns one on - with the AI lane off (`--no-ai`, `ai: false`, no model) nothing changes - docs: the `ai:` object and what the lane now reads - tests: defaults and opt-outs, flags-off identity (planner and orchestrator input and envelope equal the env-only path), `--no-ai` envelope identical with every switch on or off Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 26 +++- .../src/altimate/review/ai-switches.ts | 18 ++- .../test/altimate/review-ai-defaults.test.ts | 140 ++++++++++++++++++ .../altimate/review-ai-python-files.test.ts | 1 + 4 files changed, 174 insertions(+), 11 deletions(-) create mode 100644 packages/opencode/test/altimate/review-ai-defaults.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index ed9a8094d3..4d57a3be9d 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -290,6 +290,16 @@ dialect: snowflake # several adapters (`postgres__x`, `snowflake__x`) still gets advice # on constructs one of those adapters lacks. Set true to see all of it. reviewers: [] # empty = risk-tier defaults; or pin lanes +ai: true # the advisory AI lane; false turns it off. Or an object, all keys + # optional and on by default (see "AI reviewer lane" below): +# ai: +# enabled: true +# coverage: true # per-kind file quotas and hunk excerpts instead of a 20-file cap +# contextCard: true # dbt manifest context with each changed model +# focused: true # related files reviewed together in a few calls on larger PRs +# otherFiles: true # other/analysis files inside the project (.sql/.yml/.yaml/.py) +# pythonFiles: true # changed Python files, inside or outside the project +# verify: true # the dbt-grounded verifier over the AI comments dataDiff: # OFF by default — see "Data-diff in CI" below enabled: false warehouse: "" # connection name; empty = default connection @@ -611,10 +621,18 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne runs **after** the deterministic lanes, grounded in their findings, and adds advisory contextual comments (intent, naming, business logic, test coverage). It sees every changed dbt file, not only models: macros, singular data tests, - snapshots, schema/source yml, seeds (diff only) and project config, each - labeled with its role, with models first under the 20-file cap. - Findings are clamped to ≤ warning and never block. Skipped (clean degrade) if - no model is available. + snapshots, schema/source yml, seeds (diff only) and project config, plus other + changed project files (analyses, CI and config yml, scripts) and changed Python + files anywhere in the repository, each labeled with its role, under per-kind + quotas (models 12, macros 8, tests 4, yml 6, other 8, Python 6). Related files + are reviewed together, each model with its manifest context, and a dbt-grounded + verifier then checks every AI comment against the code: refuted ones are dropped + and ones it cannot check go to the summary. Findings are clamped to ≤ warning + and never block. Skipped (clean degrade) if no model is available. Each part can + be turned off under `ai:` in `.altimate/review.yml` or with its env variable set + to `0` (`ALTIMATE_REVIEW_AI_COVERAGE`, `_CONTEXT_CARD`, `_FOCUSED`, + `_OTHER_FILES`, `_PYTHON_FILES`, `_VERIFY`); `1` turns one on. + `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE=` replaces the finder's system prompt. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index 385fc8979d..a2387e2d5a 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -21,14 +21,18 @@ export const AI_SWITCH_ENV: Record = { verify: "ALTIMATE_REVIEW_AI_VERIFY", } -/** Product defaults when neither env nor config sets a switch. */ +/** + * Product defaults when neither env nor config sets a switch: the configuration measured + * together (wider input, related files batched, context cards, the verifier). Each one is + * opt-out with `ai: { : false }` or its env variable set to `0`. + */ export const AI_SWITCH_DEFAULTS: AiSwitches = { - coverage: false, - contextCard: false, - focused: false, - otherFiles: false, - pythonFiles: false, - verify: false, + coverage: true, + contextCard: true, + focused: true, + otherFiles: true, + pythonFiles: true, + verify: true, } type Env = Record diff --git a/packages/opencode/test/altimate/review-ai-defaults.test.ts b/packages/opencode/test/altimate/review-ai-defaults.test.ts new file mode 100644 index 0000000000..eb007d40cd --- /dev/null +++ b/packages/opencode/test/altimate/review-ai-defaults.test.ts @@ -0,0 +1,140 @@ +import { describe, test, expect, afterEach } from "bun:test" +import path from "node:path" +import os from "node:os" +import { promises as fs } from "node:fs" +import { execFileSync } from "node:child_process" +import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { DEFAULT_DBT_DIRS, type ChangedFile } from "../../src/altimate/review/diff-filter" +import { planAiInput, type AiReviewFile, type AiReviewInput } from "../../src/altimate/review/ai-review" +import { AI_SWITCH_DEFAULTS, AI_SWITCH_ENV, resolveAiSwitches, type AiSwitches } from "../../src/altimate/review/ai-switches" + +const ALL_OFF = Object.fromEntries(Object.keys(AI_SWITCH_DEFAULTS).map((k) => [k, false])) as AiSwitches +const ENV_KEYS = [...Object.values(AI_SWITCH_ENV), "ALTIMATE_REVIEW_AI_DRYRUN", "GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"] +const saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])) +afterEach(() => { + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k] + else process.env[k] = saved[k] + } +}) + +const runner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, +} as ReviewRunner + +const mod = (p: string): ChangedFile => ({ path: p, status: "modified", diff: `@@ -1,1 +1,2 @@\n ${p}\n+changed_${p}\n` }) + +describe("product defaults", () => { + test("every switch is on by default and each can be turned off by config or env", () => { + expect(resolveAiSwitches({ ai: true }, {})).toEqual(AI_SWITCH_DEFAULTS) + expect(Object.values(AI_SWITCH_DEFAULTS).every(Boolean)).toBe(true) + expect(resolveAiSwitches({ ai: { ...ALL_OFF } }, {})).toEqual(ALL_OFF) + const envOff = Object.fromEntries(Object.values(AI_SWITCH_ENV).map((k) => [k, "0"])) + expect(resolveAiSwitches({ ai: true }, envOff)).toEqual(ALL_OFF) + }) +}) + +describe("flags-off identity: every switch off is today's lane", () => { + const files: AiReviewFile[] = [ + { path: "models/a.sql", status: "modified", model: "a", kind: "model_sql", diff: "@@ -1 +1,2 @@\n x\n+y\n", sql: "select 1" }, + { path: "macros/m.sql", status: "modified", model: "m", kind: "macro", diff: "@@ -1 +1,2 @@\n x\n+y\n", sql: "{% macro m() %}{% endmacro %}" }, + { path: "analyses/q.sql", status: "modified", model: "q", kind: "analysis", diff: "@@ -1 +1,2 @@\n x\n+y\n", sql: "select 2" }, + ] + + test("planner: resolved switches all off equal the env-only plan with nothing set", () => { + const legacy = planAiInput({ grounding: [], files }, {}) + const off = planAiInput({ grounding: [], files, switches: ALL_OFF }, {}) + expect(off.messages).toEqual(legacy.messages) + expect(off.input).toEqual(legacy.input) + expect(off.budget).toEqual(legacy.budget) + }) + + test("orchestrator: the AI lane input with switches all off equals the input without switches", async () => { + const changed = [mod("models/marts/m.sql"), mod("macros/to_cents.sql"), mod("analyses/a.sql"), mod("scripts/x.py")] + const run = async (aiSwitches?: AiSwitches) => { + let seen: AiReviewInput | undefined + const env = await runReview({ + changedFiles: changed, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + layout: { root: "", dirs: DEFAULT_DBT_DIRS }, + aiOutsideFiles: [mod("airflow/load.py")], + ...(aiSwitches ? { aiSwitches } : {}), + getContent: async (f, side) => (side === "old" ? undefined : `head ${f}`), + generatedAt: "2026-11-25T00:00:00Z", + aiReview: async (input) => { + seen = input + return { findings: [], status: { state: "ok" } } + }, + }) + const { switches: _s, ...rest } = seen! + return { input: rest, env } + } + const legacy = await run() + const off = await run(ALL_OFF) + expect(off.input).toEqual(legacy.input) + expect({ ...off.env, signature: undefined }).toEqual({ ...legacy.env, signature: undefined }) + }) +}) + +describe("AI lane off: the switches change nothing", () => { + const git = (cwd: string, ...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { + cwd, + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }).toString() + const write = async (root: string, rel: string, body: string) => { + await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) + await fs.writeFile(path.join(root, rel), body) + } + + test("--no-ai: identical envelope with every switch on or off", async () => { + const { reviewPullRequest } = await import("../../src/altimate/review/run") + const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-ai-off-"))) + try { + await write(root, "dbt/dbt_project.yml", "name: p\n") + await write(root, "dbt/models/m.sql", "select 1 as id\n") + await write(root, "dbt/analyses/a.sql", "select 1\n") + await write(root, "airflow/load.py", "print(1)\n") + git(root, "init", "-q", "-b", "main") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "base") + git(root, "checkout", "-q", "-b", "pr") + await write(root, "dbt/models/m.sql", "select 1 as id, 2 as x\n") + await write(root, "dbt/analyses/a.sql", "select 2\n") + await write(root, "airflow/load.py", "print(2)\n") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "pr") + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]) delete process.env[k] + const strip = (e: any) => ({ ...e, generatedAt: undefined, signature: undefined }) + for (const k of Object.values(AI_SWITCH_ENV)) process.env[k] = "1" + const on = await reviewPullRequest({ cwd: path.join(root, "dbt"), base: "main", head: "HEAD", noAi: true }) + for (const k of Object.values(AI_SWITCH_ENV)) process.env[k] = "0" + const off = await reviewPullRequest({ cwd: path.join(root, "dbt"), base: "main", head: "HEAD", noAi: true }) + expect(strip(on)).toEqual(strip(off)) + expect(on.scope?.notReviewed.map((n) => n.path)).toContain("airflow/load.py") + expect(on.ai?.state).toBe("skipped") + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) +}) diff --git a/packages/opencode/test/altimate/review-ai-python-files.test.ts b/packages/opencode/test/altimate/review-ai-python-files.test.ts index f40a2c6000..8778e9f692 100644 --- a/packages/opencode/test/altimate/review-ai-python-files.test.ts +++ b/packages/opencode/test/altimate/review-ai-python-files.test.ts @@ -230,6 +230,7 @@ describe("reviewPullRequest end to end: .py files outside the dbt project reach return write0(chunk, ...rest) } const outsideLines = () => lines.filter((l) => l.includes("outside the dbt project")) + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "0" const off = await reviewPullRequest({ cwd: path.join(root, "dbt"), base: "main", head: "HEAD" }) expect(outsideLines()).toEqual(["ℹ️ 3 changed file(s) outside the dbt project (dbt) were not reviewed.\n"]) lines.length = 0 From e7f27d7b21a0132783de64a17d9fea6279e3cdb0 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 11:31:58 +0530 Subject: [PATCH 07/34] fix(review): AI findings left unreviewed by a verifier timeout also go to the summary - a verifier batch that times out leaves its findings without a verdict, like one that answers early on the budget; under the open fail mode they now go to the summary (`verification.decision: summary`, rule `unreviewed_stopped`) instead of inline - the same applies when the deadline hits before any batch ran (graph gathering): every finding goes to the summary, counted under `summary` - errors are unchanged (open keeps, closed discards); the closed fail mode still discards - tests: batch timeout and timeout before any batch demote to the summary, closed fail mode discards on a timeout Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-verify.ts | 50 ++++++++++--------- .../test/altimate/review-ai-verify.test.ts | 40 +++++++++++++-- 2 files changed, 64 insertions(+), 26 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-verify.ts b/packages/opencode/src/altimate/review/ai-verify.ts index 84a6d53222..eb3471a131 100644 --- a/packages/opencode/src/altimate/review/ai-verify.ts +++ b/packages/opencode/src/altimate/review/ai-verify.ts @@ -5,8 +5,8 @@ // grep). The verifier sees only the candidate comments and their diff hunks, // never the reviewer's prompt or context, and a deterministic triage table — // not the model — decides what is kept. Opt-in (`ALTIMATE_REVIEW_AI_VERIFY=1`) -// and fail-open: any error, timeout or exhausted budget leaves the findings it -// did not review unchanged. +// and fail-open: an error leaves the findings it did not review unchanged; a +// timeout or exhausted budget moves them to the summary. import { asSchema, tool, type ModelMessage, type Tool } from "ai" import z from "zod" import type { Provider } from "@/provider/provider" @@ -458,7 +458,8 @@ const LOCAL_CLAIMS = new Set(["code_fact", "conventi /** * Decide one finding (pure; first matching row wins). Without a model verdict * (id omitted, unparsable answer, timeout, budget, error) the fail mode alone - * decides: open keeps the finding unchanged, closed discards it. + * decides: open keeps the finding unchanged, or moves it to the summary when + * the verifier stopped (timeout or budget); closed discards it. */ export function triage( f: Pick, @@ -467,8 +468,8 @@ export function triage( knobs: TriageKnobs, stopped = false, ): { decision: Decision; rule: string } { - // A finding left without a verdict because its batch stopped on the token or tool-output - // budget was never checked: under the open fail mode it goes to the summary, not inline. + // A finding left without a verdict because the verifier stopped (timeout, or the token or + // tool-output budget) was never checked: under the open fail mode it goes to the summary. if (!m) return knobs.failMode === "open" ? stopped @@ -594,19 +595,30 @@ export interface Verification { features: TsFeatures } +/** An unreviewed finding demoted to the summary; it carries only the decision and its rule. */ +function toSummary(f: Finding, rule: string): Finding { + const prior = + f.evidence?.result && typeof f.evidence.result === "object" ? (f.evidence.result as Record) : {} + return { + ...f, + evidence: { tool: f.evidence?.tool ?? "ai-review", result: { ...prior, verification: { decision: "summary", rule } } }, + tier: "summary" as const, + } +} + /** * Apply triage to every finding. Kept and summary findings that the model * reviewed carry `evidence.result.verification` (the evidence tool stays * `ai-review`); verified ones get the evidence appended to the body. Severity * is never raised. Unreviewed findings kept by the open fail mode are - * returned unchanged. + * returned unchanged, or demoted to the summary when the verifier stopped. */ export function applyTriage( findings: Finding[], ts: TsFeatures[], model: Array, knobs: TriageKnobs, - /** Per finding: its batch answered early on the budget (`budget` state). */ + /** Per finding: its batch stopped before a verdict (`timeout` or `budget` state). */ stopped: boolean[] = [], ): { findings: Finding[] @@ -644,17 +656,7 @@ export function applyTriage( if (decision === "summary") counts.summary++ else counts.kept++ if (!m) { - // An unreviewed finding demoted to the summary carries only the decision and its rule. - if (decision !== "summary") out.push(f) - else { - const prior = - f.evidence?.result && typeof f.evidence.result === "object" ? (f.evidence.result as Record) : {} - out.push({ - ...f, - evidence: { tool: f.evidence?.tool ?? "ai-review", result: { ...prior, verification: { decision, rule } } }, - tier: "summary" as const, - }) - } + out.push(decision === "summary" ? toSummary(f, rule) : f) return } const verification: Verification = { @@ -1259,7 +1261,7 @@ export async function runAiVerify( batches.forEach((b, k) => b.idx.forEach((i, j) => (model[i] = outcomes[k].verdicts.get(b.ids[j])))) const stopped: boolean[] = input.findings.map(() => false) batches.forEach((b, k) => { - if (outcomes[k].state === "budget") for (const i of b.idx) stopped[i] = true + if (outcomes[k].state === "budget" || outcomes[k].state === "timeout") for (const i of b.idx) stopped[i] = true }) const triaged = applyTriage(input.findings, ts, model, triageKnobs(env), stopped) for (const d of triaged.dropped) @@ -1296,16 +1298,18 @@ export async function runAiVerify( } } catch (err) { log.error("ai verify failed", { error: err }) - // No finding got a verdict: the fail mode decides, as for an unreviewed finding. + // No finding got a verdict: the fail mode decides, as for an unreviewed finding; on a + // timeout the open fail mode moves them to the summary. const closed = triageKnobs(deps.env ?? process.env).failMode === "closed" + const timedOut = controller.signal.aborted const n = input.findings.length return { - findings: closed ? [] : input.findings, + findings: closed ? [] : timedOut ? input.findings.map((f) => toSummary(f, "unreviewed_stopped")) : input.findings, status: status({ - ...(controller.signal.aborted + ...(timedOut ? { state: "timeout" as const, reason: "no answer before the verifier timeout" } : { state: "error" as const, reason: safeReason(err) }), - ...(closed ? { kept: 0, discarded: n } : {}), + ...(closed ? { kept: 0, discarded: n } : timedOut ? { kept: 0, summary: n } : {}), }), } } finally { diff --git a/packages/opencode/test/altimate/review-ai-verify.test.ts b/packages/opencode/test/altimate/review-ai-verify.test.ts index 92210beeca..2d3f6fcc49 100644 --- a/packages/opencode/test/altimate/review-ai-verify.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify.test.ts @@ -982,12 +982,13 @@ describe("runAiVerify: the bounded tool loop", () => { expect(status.reason).not.toContain("abcdefghijklmnop") }) - test("a timeout aborts the call and leaves the findings unchanged", async () => { + test("a timeout aborts the call and moves the unreviewed findings to the summary", async () => { const f = aiFinding() const llm: VerifierLlm = (req) => new Promise((_, reject) => req.abort.addEventListener("abort", () => reject(new Error("aborted")))) const { findings, status } = await verify([f], llm, {}, { timeoutMs: 20 }) - expect(findings).toEqual([f]) + expect(findings.map((x) => x.id)).toEqual([f.id]) + expect(findings[0].tier).toBe("summary") expect(status.state).toBe("timeout") }) @@ -996,7 +997,7 @@ describe("runAiVerify: the bounded tool loop", () => { const { llm } = scripted(() => toolStep([["read_file", { path: "models/fct.sql" }]])) // The read never settles; the deadline must still end the run. const { findings, status } = await verify([f], llm, { readFile: () => new Promise(() => {}) }, { timeoutMs: 20 }) - expect(findings).toEqual([f]) + expect(findings.map((x) => x.id)).toEqual([f.id]) expect(status.state).toBe("timeout") }) @@ -1669,4 +1670,37 @@ describe("runAiVerify: findings left unreviewed when a batch stops", () => { const { findings } = await verify(two(), llm, {}, { env: { ALTIMATE_REVIEW_AI_VERIFY_FAIL: "closed" } }) expect(findings.map((f) => f.title)).toEqual(["fct: first claim"]) }) + + test("timeout: the findings without a verdict go to the summary, not inline", async () => { + const llm: VerifierLlm = (req) => + new Promise((_, reject) => req.abort.addEventListener("abort", () => reject(new Error("aborted")))) + const { findings, status } = await verify(two(), llm, {}, { timeoutMs: 20 }) + expect(status.state).toBe("timeout") + expect(status.unreviewed).toBe(2) + expect(status.summary).toBe(2) + expect(status.kept).toBe(0) + for (const f of findings) { + expect(f.tier).toBe("summary") + expect(inlineEligible({ ...f, tier: "inline" }, DEFAULT_POSTING_POLICY)).toBe(false) + expect(status.decisions?.find((d) => d.id === f.id)?.rule).toBe("unreviewed_stopped") + } + }) + + test("timeout before any batch ran: the findings still go to the summary", async () => { + const { llm, calls } = scripted(() => ({ text: JSON.stringify([verdict("c1")]) })) + const hang = { graphParents: () => new Promise(() => {}) } as any + const { findings, status } = await verify(two(), llm, { runner: hang }, { timeoutMs: 20 }) + expect(calls).toHaveLength(0) + expect(status.state).toBe("timeout") + expect(status.summary).toBe(2) + expect(status.kept).toBe(0) + expect(findings.map((f) => f.tier)).toEqual(["summary", "summary"]) + }) + + test("the closed fail mode still discards them on a timeout", async () => { + const llm: VerifierLlm = (req) => + new Promise((_, reject) => req.abort.addEventListener("abort", () => reject(new Error("aborted")))) + const { findings } = await verify(two(), llm, {}, { timeoutMs: 20, env: { ALTIMATE_REVIEW_AI_VERIFY_FAIL: "closed" } }) + expect(findings).toEqual([]) + }) }) From 3148c95ac43a4546f1e08203b80381d16802feb6 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 15:57:44 +0530 Subject: [PATCH 08/34] fix(review): AI-only files count as reviewed only when their call answered; Python files go through `pythonFiles` only - `.py` is no longer an `otherFiles` extension: in-project Python files reach the AI lane only through `pythonFiles`, under the Python quota, so `pythonFiles: false` stops them all - `runAiReview` reports `ai.failedFiles` (files only in calls that failed while others answered); the coverage ledger keeps other/analysis/Python files listed as not reviewed when the lane errored, timed out or failed for their call, instead of when it was sent - `ai.unsent` no longer lists other/analysis/Python files over their quota: nothing but the AI lane reads them, so they stay in the "Not reviewed" ledger instead of being described as checked by the deterministic lanes - the verifier and suggestion validation see the added lines of outside-project files, so their findings are no longer triaged as `unchanged_code` - `--all-projects`: outside-project Python files are offered to the next project while a project's AI lane does not run or take them (off in its policy, a tier without the lane) - run.ts: the disabled reason covers both `ai: false` and `ai: { enabled: false }`; the outside-Python stderr line says the files are offered to the lane when it runs - tests: in-project .py not sent by `otherFiles` alone; lane error/timeout/partial failure keep files in the ledger (in and outside the project); outside-file added lines reach the verifier; the next project takes the files when the first's policy turns the lane off; Python files over quota are not in `ai.unsent`; stderr restored in `finally`; the spare test uses more models than the quotas can take Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-other-files.ts | 6 +- .../opencode/src/altimate/review/ai-review.ts | 30 ++++- .../src/altimate/review/multi-project.ts | 11 +- .../src/altimate/review/orchestrate.ts | 32 ++++-- packages/opencode/src/altimate/review/run.ts | 8 +- .../opencode/src/altimate/review/verdict.ts | 2 + .../altimate/review-ai-other-files.test.ts | 41 ++++++- .../altimate/review-ai-python-files.test.ts | 107 ++++++++++++++++-- 8 files changed, 199 insertions(+), 38 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-other-files.ts b/packages/opencode/src/altimate/review/ai-other-files.ts index 498e960321..1ec47ad62e 100644 --- a/packages/opencode/src/altimate/review/ai-other-files.ts +++ b/packages/opencode/src/altimate/review/ai-other-files.ts @@ -3,12 +3,14 @@ // With the `otherFiles` switch (`ALTIMATE_REVIEW_AI_OTHER_FILES`), changed files of kind // `other` or `analysis` inside the dbt project root also go to the AI lane, under their own // coverage quota (`ALTIMATE_REVIEW_AI_QUOTA_OTHER`), after the existing kinds. No rule lane -// reads them. Off, the lane's input is unchanged. +// reads them. Off, the lane's input is unchanged. `.py` files are not among them: Python +// files reach the lane only through the `pythonFiles` switch (ai-python-files.ts), under +// the Python quota, so turning that switch off stops every Python file. /** Kinds the switch adds. */ export const AI_OTHER_KINDS: ReadonlySet = new Set(["other", "analysis"]) /** Extensions the switch accepts. */ -export const AI_OTHER_EXTENSIONS = [".sql", ".yml", ".yaml", ".py"] +export const AI_OTHER_EXTENSIONS = [".sql", ".yml", ".yaml"] /** Default coverage quota for the added files. */ export const AI_OTHER_FILES_QUOTA = 8 diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 339ce514c8..2f80b2bf80 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -20,6 +20,9 @@ import { AI_PYTHON_FILES_QUOTA, AI_PYTHON_KIND } from "./ai-python-files" const log = Log.create({ service: "ai-review" }) +/** Kinds only the AI lane reads (the `otherFiles` and `pythonFiles` switches). */ +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 @@ -767,8 +770,11 @@ export interface AiLaneStatus { 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 (they still went through the deterministic lanes). */ + /** Sendable files left out by the coverage quotas (they still went through the deterministic lanes). + * Files only the AI lane reads (other/analysis, Python) are not listed: the coverage ledger has them. */ unsent?: string[] + /** Files sent only in calls that failed while others answered (state `ok`): not reviewed by the lane. */ + failedFiles?: string[] } /** One file as sent to the model. */ export interface AiInputRecord { @@ -979,9 +985,11 @@ export async function runAiReview(input: AiReviewInput): Promise const { files, budget } = plan const dryRun = aiDryRunEnabled() // Recorded only when an opt-in switch changed or inspects the input, so the default envelope is unchanged. + // Files only the AI lane reads are not "checked by the deterministic lanes"; the ledger lists them. + const unsent = plan.unsent.filter((f) => !AI_ONLY_KINDS.has(f.kind ?? "")).map((f) => f.path) const recorded: Pick = { ...(budget.coverage || dryRun || plan.focused || plan.input.some((r) => r.card) ? { input: plan.input } : {}), - ...(budget.coverage && plan.unsent.length ? { unsent: plan.unsent.map((f) => f.path) } : {}), + ...(budget.coverage && unsent.length ? { unsent } : {}), } const done = (findings: Finding[], status: Omit): AiReviewResult => ({ findings, @@ -994,7 +1002,7 @@ export async function runAiReview(input: AiReviewInput): Promise let modelLabel: string | undefined try { - // Prompt comes from the compiled core, not this file (or ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE). + // The file named by ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE when set, else the compiled core's prompt. const corePrompt = await finderSystemPrompt() if (!corePrompt) return done([], { state: "error", reason: "the core reviewer prompt is unavailable" }) const testGap = aiTestGapEnabled() @@ -1031,14 +1039,26 @@ export async function runAiReview(input: AiReviewInput): Promise if (failed.length === results.length) return done([], { state: failed[0].state, reason: failed[0].reason, model: modelLabel, ...spent }) const reason = failed.length ? `${failed.length} of ${results.length} calls failed: ${failed[0].reason}` : undefined - // Opt-in: try to refute each finding with dbt evidence. Never throws. + // Files no answered call carried: the coverage ledger keeps them as not reviewed. + const answered = new Set(batches.flatMap((b, k) => (results[k].state === "ok" ? b.map((f) => f.path) : []))) + const failedFiles = [...new Set(batches.flatMap((b, k) => (results[k].state === "ok" ? [] : b.map((f) => f.path))))].filter( + (p) => !answered.has(p), + ) + // 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.grounding, evidence: input.evidence, model }) findings = v.findings verifier = v.status } - return done(findings, { state: "ok", model: modelLabel, ...(reason ? { reason } : {}), ...spent, ...(verifier ? { verifier } : {}) }) + return done(findings, { + state: "ok", + model: modelLabel, + ...(reason ? { reason } : {}), + ...(failedFiles.length ? { failedFiles } : {}), + ...spent, + ...(verifier ? { verifier } : {}), + }) } catch (err) { log.error("ai review failed", { error: err }) return done([], { state: "error", reason: safeReason(err), model: modelLabel }) diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index d48ab19113..05238876df 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -151,17 +151,22 @@ export async function reviewAllProjects(opts: ReviewPullRequestOptions): Promise const prFiles = collected.map((f) => f.path) const prRenames = collected.flatMap((f) => (f.status === "renamed" && f.oldPath ? [[f.path, f.oldPath] as [string, string]] : [])) const runs: ProjectRun[] = [] + // Python files outside every project go to one project's AI lane only (`pythonFiles`): the + // first project whose lane runs and takes them. While a project's lane does not (off in its + // policy, a tier without the lane), they are offered to the next project. + const unassignedPaths = new Set(unassigned.map((f) => f.path)) + let outsidePythonPending = true for (const root of touched) { const own = byProject.get(root)! process.stderr.write(`ℹ️ reviewing dbt project ${root || "."} (${own.length} changed file(s))\n`) - // Python files outside every project go to one project's AI lane only (`pythonFiles`). const env = await reviewPullRequest({ ...optsFor(root), changedFiles: [...own, ...unassigned], prFiles, prRenames, - aiOutsidePython: root === touched[0], + aiOutsidePython: outsidePythonPending, }) + if (env.ai?.state === "ok" || (env.ai?.input ?? []).some((r) => unassignedPaths.has(r.path))) outsidePythonPending = false runs.push({ root, paths: own.map((f) => f.path), env }) } return mergeProjectEnvelopes(runs, roots) @@ -313,6 +318,7 @@ function mergeAi(runs: Array<{ root: string; env: VerdictEnvelope }>): VerdictEn const base = ok ?? first const input = ais.some((a) => a.input) ? ais.flatMap((a) => a.input ?? []) : undefined const unsent = ais.flatMap((a) => a.unsent ?? []) + const failedFiles = ais.flatMap((a) => a.failedFiles ?? []) return { ...base, state, @@ -324,6 +330,7 @@ function mergeAi(runs: Array<{ root: string; env: VerdictEnvelope }>): VerdictEn durationMs: sumOf(ais.map((a) => a.durationMs)), input, unsent: unsent.length ? unsent : undefined, + failedFiles: failedFiles.length ? failedFiles : undefined, verifier: mergeVerifier(lanes.map((r) => ({ root: r.root, v: r.env.ai!.verifier }))), projects: lanes.map((r) => ({ root: r.root, state: r.env.ai!.state, reason: r.env.ai!.reason, calls: r.env.ai!.calls })), } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 4e30a945c5..dda43a5a4e 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2637,8 +2637,9 @@ export async function runReview(input: OrchestrateInput): Promise() let aiReviewedOutside: string[] = [] if (!lanes.has("ai_review")) { aiStatus = { state: "skipped", reason: `not part of the ${tier} tier` } @@ -2727,8 +2728,7 @@ export async function runReview(input: OrchestrateInput): Promise f.path)) - aiOutsideSent = aiSent.filter((f) => outsidePaths.has(f.path)).map((f) => f.path) + aiSentPaths = aiSent.map((f) => f.path) if (input.aiContextCard && anyManifest) await attachContextCards(aiFiles, input.runner) const context = input.aiGraphContext ? await aiGraphContext(aiFiles.map((f) => f.path), input.runner, getContent) : undefined // Files the PR changes that the AI may list and the verifier may read; never the user's exclusions or credentials. @@ -2763,7 +2763,9 @@ export async function runReview(input: OrchestrateInput): Promise !mayHoldCredentials(f.path))), + addedLines: addedLinesByFile( + [...input.changedFiles, ...(input.aiOutsideFiles ?? [])].filter((f) => !mayHoldCredentials(f.path)), + ), prTitle: input.prTitle, prBody: input.prBody, grepProject, @@ -2797,8 +2799,13 @@ export async function runReview(input: OrchestrateInput): Promise f.path)) + aiReviewedOutside = [...aiReviewed].filter((p) => outsidePaths.has(p)) // Defense in depth: the AI never blocks, regardless of what it returns. for (const f of aiFindings) merged.push(f.severity === "critical" ? { ...f, severity: "warning" } : f) } catch (err) { @@ -2808,7 +2815,11 @@ export async function runReview(input: OrchestrateInput): Promise SEVERITY_ORDER[f.severity] >= minSev) // The verdict counts every instance; merging repeats is presentation only. @@ -2830,8 +2841,9 @@ export async function runReview(input: OrchestrateInput): Promise ((f.kind === "other" && !otherChecked.has(f.path)) || f.kind === "analysis") && !touched.has(f.path)) + // Other/analysis files the AI lane reviewed (`otherFiles`, `pythonFiles`) are covered; a + // file in a call that failed, or a lane that errored or timed out, is not. + .filter((f) => ((f.kind === "other" && !otherChecked.has(f.path)) || f.kind === "analysis") && !aiReviewed.has(f.path)) .map((f) => ({ path: f.path, reason: "not a dbt model/macro/test/yml/seed file" })), ...reviewable .filter((f) => !touched.has(f.path)) diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 01acfac082..f8f5e3cf71 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -81,7 +81,7 @@ export interface ReviewPullRequestOptions { /** Every rename the PR makes (new → old path), when `changedFiles` is a subset of it. */ prRenames?: Array<[string, string]> /** Send changed Python files outside the dbt project to this review's AI lane (`pythonFiles` - * switch). Default true; `--all-projects` sets it for one project only. */ + * switch). Default true; `--all-projects` sets it until one project's AI lane runs. */ aiOutsidePython?: boolean } @@ -370,7 +370,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise const changedFiles = scoped.inScope let aiDisabledReason: string | undefined if (opts.noAi) aiDisabledReason = "disabled by --no-ai" - else if (!aiLaneEnabled(config)) aiDisabledReason = "disabled by `ai: false` in .altimate/review.yml" + else if (!aiLaneEnabled(config)) aiDisabledReason = "disabled in .altimate/review.yml" const aiOn = !aiDisabledReason const aiSwitches = resolveAiSwitches(config) // `pythonFiles`: .py files outside the dbt project skip every lane but the AI lane. @@ -385,9 +385,11 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise `ℹ️ ${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 || "."}) go to the AI review only.\n`, + `ℹ️ ${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 diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index e562612aeb..f2272e78d3 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -287,6 +287,8 @@ export const VerdictEnvelope = z.object({ .optional(), /** Sendable files the opt-in coverage quotas kept from the model (the deterministic lanes still checked them). */ unsent: z.array(z.string()).optional(), + /** Files sent only in calls that failed while other calls answered: not reviewed by the AI lane. */ + failedFiles: z.array(z.string()).optional(), /** The opt-in dbt-grounded verifier (`ALTIMATE_REVIEW_AI_VERIFY=1`): what it kept and dropped. */ verifier: z .object({ diff --git a/packages/opencode/test/altimate/review-ai-other-files.test.ts b/packages/opencode/test/altimate/review-ai-other-files.test.ts index 01e2c86f06..9ea6bea7eb 100644 --- a/packages/opencode/test/altimate/review-ai-other-files.test.ts +++ b/packages/opencode/test/altimate/review-ai-other-files.test.ts @@ -10,6 +10,7 @@ import { selectAiFilesByQuota, type AiReviewFile, type AiReviewInput, + type AiLaneStatus, } from "../../src/altimate/review/ai-review" // The `otherFiles` switch (ALTIMATE_REVIEW_AI_OTHER_FILES) sends changed other/analysis files to the AI lane. @@ -108,13 +109,13 @@ describe("ALTIMATE_REVIEW_AI_OTHER_FILES: orchestrator file list", () => { expect(paths.slice(0, off.input.files.length)).toEqual(off.input.files.map((f) => f.path)) expect(paths.slice(off.input.files.length)).toEqual([ "analyses/revenue_check.sql", - "scripts/load_raw.py", "integration_tests/ci.yml", "config/extra.yaml", ]) const byPath = new Map(on.input.files.map((f) => [f.path, f])) expect(byPath.get("analyses/revenue_check.sql")).toMatchObject({ kind: "analysis", sql: "-- head of analyses/revenue_check.sql\nchanged_analyses/revenue_check.sql\n" }) - expect(byPath.get("scripts/load_raw.py")?.kind).toBe("other") + // Python files reach the lane only through the `pythonFiles` switch. + expect(paths).not.toContain("scripts/load_raw.py") expect(paths).not.toContain("data/lookup.csv") expect(paths).not.toContain("scripts/gone.py") }) @@ -122,7 +123,7 @@ describe("ALTIMATE_REVIEW_AI_OTHER_FILES: orchestrator file list", () => { test("set: files outside the dbt project root stay excluded", async () => { const changed = [mod("dbt/models/m.sql"), mod("dbt/analyses/a.sql"), mod("dbt/scripts/x.py"), mod("airflow/dags/load.py"), mod("infra/k8s.yaml")] const { input } = await lane(changed, { flag: true, layoutRoot: "dbt" }) - expect(input.files.map((f) => f.path)).toEqual(["dbt/models/m.sql", "dbt/analyses/a.sql", "dbt/scripts/x.py"]) + expect(input.files.map((f) => f.path)).toEqual(["dbt/models/m.sql", "dbt/analyses/a.sql"]) }) test("set: an added file the lane sent is not listed as not reviewed; unset it is", async () => { @@ -134,6 +135,32 @@ describe("ALTIMATE_REVIEW_AI_OTHER_FILES: orchestrator file list", () => { expect(listed(on.env)).toContain("data/lookup.csv") }) + test("set: an added file stays listed as not reviewed when the lane fails or its call failed", async () => { + const run = async (status: AiLaneStatus) => { + process.env.ALTIMATE_REVIEW_AI_OTHER_FILES = "1" + return runReview({ + changedFiles: CHANGED, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + getContent: async (f, side) => (side === "old" ? undefined : `x`), + generatedAt: "2026-11-24T00:00:00Z", + aiReview: async () => ({ findings: [], status }), + }) + } + const listed = (e: Awaited>) => (e.scope?.notReviewed ?? []).map((n) => n.path) + for (const status of [ + { state: "error", reason: "boom" }, + { state: "timeout", reason: "slow" }, + ] as AiLaneStatus[]) + expect(listed(await run(status))).toContain("analyses/revenue_check.sql") + const partial = await run({ state: "ok", reason: "1 of 2 calls failed: boom", failedFiles: ["analyses/revenue_check.sql"] }) + expect(listed(partial)).toContain("analyses/revenue_check.sql") + expect(listed(partial)).not.toContain("integration_tests/ci.yml") + }) + test("resolved switches win over the env variable", async () => { process.env.ALTIMATE_REVIEW_AI_OTHER_FILES = "1" let seen: AiReviewInput | undefined @@ -156,8 +183,8 @@ describe("ALTIMATE_REVIEW_AI_OTHER_FILES: orchestrator file list", () => { }) test("set: a finding the model returns on an added file reaches the envelope", async () => { - const { env } = await lane(CHANGED, { flag: true, finding: "scripts/load_raw.py" }) - const f = env.findings.find((x) => x.file === "scripts/load_raw.py") + const { env } = await lane(CHANGED, { flag: true, finding: "integration_tests/ci.yml" }) + const f = env.findings.find((x) => x.file === "integration_tests/ci.yml") expect(f).toBeDefined() expect(f!.rule).toBe(ruleId("ai-review", "sql_correctness")) expect(f!.startLine).toBe(2) @@ -214,7 +241,9 @@ describe("ALTIMATE_REVIEW_AI_OTHER_FILES: planner", () => { }) test("default quota is 8 and does not lend spare to the existing buckets", () => { - const models = Array.from({ length: 14 }, (_, i) => file(`models/m${i}.sql`, "model_sql")) + // More models than the four quotas plus their spare can take, so a spare that wrongly + // counted the other quota would send more models. + const models = Array.from({ length: 40 }, (_, i) => file(`models/m${i}.sql`, "model_sql")) const others = Array.from({ length: 10 }, (_, i) => file(`scripts/s${i}.py`, "other")) const quotas = aiInputBudget({ ...COVERAGE, ALTIMATE_REVIEW_AI_OTHER_FILES: "1" }).coverage! expect(quotas.otherQuota).toBe(8) diff --git a/packages/opencode/test/altimate/review-ai-python-files.test.ts b/packages/opencode/test/altimate/review-ai-python-files.test.ts index 8778e9f692..34867ce706 100644 --- a/packages/opencode/test/altimate/review-ai-python-files.test.ts +++ b/packages/opencode/test/altimate/review-ai-python-files.test.ts @@ -122,15 +122,42 @@ describe("ALTIMATE_REVIEW_AI_PYTHON_FILES: orchestrator file list", () => { expect(on.files.filter((f) => f.path === "dbt/models/py_model.py")).toHaveLength(1) }) - test("with ALTIMATE_REVIEW_AI_OTHER_FILES: files it adds are not added again", async () => { + test("ALTIMATE_REVIEW_AI_OTHER_FILES alone sends no .py file; Python files go through this switch only", async () => { const other = await lane(IN_ROOT, { layoutRoot: "dbt", flags: OTHER }) const both = await lane(IN_ROOT, { layoutRoot: "dbt", outside: OUTSIDE, flags: { ...OTHER, ...PY } }) + expect(other.files.filter((f) => f.path.endsWith(".py")).map((f) => f.path)).toEqual(["dbt/models/py_model.py"]) expect(both.files.slice(0, other.files.length)).toEqual(other.files) - expect(other.files.map((f) => f.path)).toContain("dbt/scripts/helper.py") - expect(both.files.slice(other.files.length).map((f) => f.path)).toEqual(["airflow/dags/load.py"]) + expect(both.files.slice(other.files.length).map((f) => [f.path, f.kind])).toEqual([ + ["dbt/scripts/helper.py", AI_PYTHON_KIND], + ["dbt/analyses/check.py", AI_PYTHON_KIND], + ["airflow/dags/load.py", AI_PYTHON_KIND], + ]) const paths = both.files.map((f) => f.path) expect(new Set(paths).size).toBe(paths.length) }) + + test("the verifier sees the added lines of outside-project files", async () => { + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" + let seen: AiReviewInput | undefined + await runReview({ + changedFiles: [mod("dbt/models/m.sql")], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + layout: { root: "dbt", dirs: DEFAULT_DBT_DIRS }, + aiOutsideFiles: [mod("airflow/load.py")], + aiVerify: true, + getContent: async (f, side) => (side === "old" ? undefined : `x`), + generatedAt: "2026-11-25T00:00:00Z", + aiReview: async (input) => { + seen = input + return { findings: [], status: { state: "ok" } } + }, + }) + expect([...(seen!.evidence!.addedLines.get("airflow/load.py") ?? [])]).toEqual([2]) + }) }) describe("ALTIMATE_REVIEW_AI_PYTHON_FILES: planner", () => { @@ -206,6 +233,8 @@ describe("reviewPullRequest end to end: .py files outside the dbt project reach test("AI dry run: ai.input lists the outside .py file as python_file; unset it is out of scope only", async () => { const { reviewPullRequest } = await import("../../src/altimate/review/run") const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-py-e2e-"))) + const lines: string[] = [] + const write0 = process.stderr.write.bind(process.stderr) try { await write(root, "dbt/dbt_project.yml", "name: p\n") await write(root, "dbt/models/m.sql", "select 1 as id\n") @@ -223,8 +252,6 @@ describe("reviewPullRequest end to end: .py files outside the dbt project reach git(root, "commit", "-q", "-m", "pr") for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]) delete process.env[k] process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" - const lines: string[] = [] - const write0 = process.stderr.write.bind(process.stderr) ;(process.stderr as any).write = (chunk: any, ...rest: any[]) => { lines.push(String(chunk)) return write0(chunk, ...rest) @@ -243,16 +270,16 @@ describe("reviewPullRequest end to end: .py files outside the dbt project reach ["airflow/dags/load.py", AI_PYTHON_KIND], ]) expect(on.findings).toEqual(off.findings) - // The stderr count leaves out the file the AI lane takes. + // The stderr count leaves out the file offered to the AI lane. expect(outsideLines()).toEqual([ "ℹ️ 2 changed file(s) outside the dbt project (dbt) were not reviewed.\n", - "ℹ️ 1 changed Python file(s) outside the dbt project (dbt) go to the AI review only.\n", + "ℹ️ 1 changed Python file(s) outside the dbt project (dbt) are offered to the AI review only, when that lane runs; the result lists any it did not review.\n", ]) - ;(process.stderr as any).write = write0 // The dry run made no model call, so the file is still listed as not reviewed. expect(on.scope?.notReviewed.map((n) => n.path)).toContain("airflow/dags/load.py") expect(on.scope?.aiReviewedOutside).toBeUndefined() } finally { + ;(process.stderr as any).write = write0 await fs.rm(root, { recursive: true, force: true }) } }, 60_000) @@ -264,7 +291,7 @@ describe("outside-project Python files the AI lane reviewed are not listed as no outOfScopeFiles: paths.length, notReviewed: paths.map((p) => ({ path: p, reason: "outside the dbt project (dbt)" })), }) - async function run(state: "ok" | "error") { + async function run(state: "ok" | "error" | "partial") { process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" return runReview({ changedFiles: [mod("dbt/models/m.sql")], @@ -278,7 +305,15 @@ describe("outside-project Python files the AI lane reviewed are not listed as no scope: outsideScope(["airflow/load.py", "README.md"]), getContent: async (f, side) => (side === "old" ? undefined : `x`), generatedAt: "2026-11-25T00:00:00Z", - aiReview: async () => ({ findings: [], status: state === "ok" ? { state: "ok" } : { state: "error", reason: "boom" } }), + aiReview: async () => ({ + findings: [], + status: + state === "ok" + ? { state: "ok" } + : state === "partial" + ? { state: "ok", reason: "1 of 2 calls failed: boom", failedFiles: ["airflow/load.py"] } + : { state: "error", reason: "boom" }, + }), }) } @@ -296,6 +331,12 @@ describe("outside-project Python files the AI lane reviewed are not listed as no expect(env.scope?.outOfScopeFiles).toBe(2) }) + test("its call failed while others answered: still listed as outside the project, not reviewed", async () => { + const env = await run("partial") + expect(env.scope?.notReviewed.map((n) => n.path)).toEqual(["airflow/load.py", "README.md"]) + expect(env.scope?.aiReviewedOutside).toBeUndefined() + }) + test("multi-project merge: a path one project's AI lane reviewed is not listed by the others", async () => { const a = await run("ok") const b = await run("error") @@ -348,4 +389,50 @@ describe("--all-projects: an outside-project Python file goes to one project's A await fs.rm(root, { recursive: true, force: true }) } }, 60_000) + + test("the first project's AI lane is off in its policy: the next project's lane takes the file", async () => { + const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-py-mp-off-"))) + try { + await write(root, "a/dbt_project.yml", "name: a\n") + await write(root, "a/.altimate/review.yml", "ai: false\n") + await write(root, "a/models/m.sql", "select 1 as id\n") + await write(root, "b/dbt_project.yml", "name: b\n") + await write(root, "b/models/n.sql", "select 1 as id\n") + await write(root, "airflow/load.py", "print(1)\n") + git(root, "init", "-q", "-b", "main") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "base") + git(root, "checkout", "-q", "-b", "pr") + await write(root, "a/models/m.sql", "select 1 as id, 2 as x\n") + await write(root, "b/models/n.sql", "select 1 as id, 3 as y\n") + await write(root, "airflow/load.py", "print(2)\n") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "pr") + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]) delete process.env[k] + process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" + const env = await reviewAllProjects({ cwd: root, base: "main", head: "HEAD" }) + expect(env.ai?.input?.map((r) => r.path).sort()).toEqual(["airflow/load.py", "b/models/n.sql"]) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) +}) + +describe("ai.unsent lists only files the deterministic lanes checked", () => { + test("Python files over their quota are not in ai.unsent (the coverage ledger has them)", async () => { + const { runAiReview } = await import("../../src/altimate/review/ai-review") + process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" + const py = Array.from({ length: 8 }, (_, i): AiReviewFile => ({ + path: `scripts/s${i}.py`, + status: "modified", + kind: AI_PYTHON_KIND, + model: `s${i}`, + diff: "@@ -1,1 +1,2 @@\n x\n+y\n", + sql: "print(1)\n", + })) + const res = await runAiReview({ grounding: [], files: py, switches: { coverage: true, pythonFiles: true } }) + expect(res.status.input?.length).toBe(6) + expect(res.status.unsent).toBeUndefined() + }) }) From d9114be28edc39f99c10adb6d98054a6a21958aa Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 15:57:44 +0530 Subject: [PATCH 09/34] fix(review): record the verifier's stopped and failed findings for re-triage under either fail mode - `triage` records `unreviewed_stopped` for a finding left without a verdict by a timeout or budget under the closed fail mode too (still discarded), so `retriage` with open knobs moves it to the summary instead of keeping it - the failure path of `runAiVerify` (timeout before or outside a batch, unexpected error) now records a `VerifierDecision` per finding; features not yet computed are computed without the graph's model names - remove the unused `aiVerifyEnabled` (the `verify` switch replaced it); the module comments of the verifier and context cards describe them as on by default, opt-out - tests: closed-mode stopped rule and its re-triage, decisions on a timeout before any batch ran, `switchOn("verify")` env-only semantics Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-context-card.ts | 3 +- .../opencode/src/altimate/review/ai-verify.ts | 47 +++++++++++++------ .../test/altimate/review-ai-verify.test.ts | 24 +++++++--- 3 files changed, 51 insertions(+), 23 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-context-card.ts b/packages/opencode/src/altimate/review/ai-context-card.ts index 283684f5b3..093b01bbf4 100644 --- a/packages/opencode/src/altimate/review/ai-context-card.ts +++ b/packages/opencode/src/altimate/review/ai-context-card.ts @@ -1,6 +1,7 @@ // altimate_change - new file: dbt manifest context card for the AI lane // -// Opt-in (`ALTIMATE_REVIEW_AI_CONTEXT_CARD=1`, needs a manifest): each file +// On by default in `reviewPullRequest` (the `contextCard` switch; opt out with +// `ai: { contextCard: false }` or `ALTIMATE_REVIEW_AI_CONTEXT_CARD=0`; needs a manifest): each file // sent to the AI reviewer carries a short block of manifest facts the diff does // not show — materialization and keys, parents and children, declared columns // and their tests, sibling models; for a macro, its callers and adapter variants. diff --git a/packages/opencode/src/altimate/review/ai-verify.ts b/packages/opencode/src/altimate/review/ai-verify.ts index eb3471a131..b9c6fa5a6e 100644 --- a/packages/opencode/src/altimate/review/ai-verify.ts +++ b/packages/opencode/src/altimate/review/ai-verify.ts @@ -4,7 +4,8 @@ // with dbt evidence (compiled SQL, the manifest DAG, column lineage, project // grep). The verifier sees only the candidate comments and their diff hunks, // never the reviewer's prompt or context, and a deterministic triage table — -// not the model — decides what is kept. Opt-in (`ALTIMATE_REVIEW_AI_VERIFY=1`) +// not the model — decides what is kept. On by default in `reviewPullRequest` (the `verify` +// switch; opt out with `ai: { verify: false }` or `ALTIMATE_REVIEW_AI_VERIFY=0`) // and fail-open: an error leaves the findings it did not review unchanged; a // timeout or exhausted budget moves them to the summary. import { asSchema, tool, type ModelMessage, type Tool } from "ai" @@ -95,11 +96,6 @@ export interface VerifierStatus { decisions?: VerifierDecision[] } -/** Whether the verifier runs (opt-in). */ -export function aiVerifyEnabled(env: Record = process.env): boolean { - return env.ALTIMATE_REVIEW_AI_VERIFY === "1" -} - export interface RunAiVerifyInput { /** The AI lane's findings: the candidates to verify. */ findings: Finding[] @@ -470,12 +466,12 @@ export function triage( ): { decision: Decision; rule: string } { // A finding left without a verdict because the verifier stopped (timeout, or the token or // tool-output budget) was never checked: under the open fail mode it goes to the summary. - if (!m) - return knobs.failMode === "open" - ? stopped - ? { decision: "summary", rule: "unreviewed_stopped" } - : { decision: "keep", rule: "unreviewed" } - : { decision: "discard", rule: "unreviewed" } + // The rule records the stop under either fail mode, so `retriage` can switch modes. + if (!m) { + const rule = stopped ? "unreviewed_stopped" : "unreviewed" + if (knobs.failMode === "closed") return { decision: "discard", rule } + return stopped ? { decision: "summary", rule } : { decision: "keep", rule } + } if (ts.restatesGrounding) return { decision: "discard", rule: "duplicate_of_engine" } if (m.verdict === "refuted") { if (m.evidence.trim()) return { decision: "discard", rule: "refuted" } @@ -1207,11 +1203,13 @@ export async function runAiVerify( return { findings: input.findings, status: status({ state: "skipped", reason: "no AI findings to verify" }) } let timer: ReturnType | undefined const controller = new AbortController() + const ev = input.evidence + const fileByPath = new Map(ev.files.map((f) => [f.path, f])) + // Deterministic features, once computed; the failure path records decisions with them. + let ts: TsFeatures[] | undefined try { const env = deps.env ?? process.env - const ev = input.evidence const llm = deps.llm ?? harnessVerifierLlm(input.model) - const fileByPath = new Map(ev.files.map((f) => [f.path, f])) const batches = batchFindings(input.findings).map((idx) => { const ids = idx.map((_, j) => `c${j + 1}`) const message = buildVerifyMessage( @@ -1230,7 +1228,7 @@ export async function runAiVerify( timer = setTimeout(() => controller.abort(), deps.timeoutMs ?? aiTimeoutMs(promptChars)) const graph = await untilAborted(gatherGraph(ev), controller.signal) const names = { parents: graph.parents.map((p) => p.name), downstream: graph.downstream.map((d) => d.name) } - const ts = input.findings.map((f) => + ts = input.findings.map((f) => extractFeatures(f, fileByPath.get(f.file), input.grounding, names, ev.addedLines.get(f.file) ?? new Set()), ) const defs = verifierTools(ev, graph) @@ -1303,6 +1301,24 @@ export async function runAiVerify( const closed = triageKnobs(deps.env ?? process.env).failMode === "closed" const timedOut = controller.signal.aborted const n = input.findings.length + // Recorded like any unreviewed finding, so the outcome can be re-triaged offline. Features + // not computed before the failure are computed now, without the dbt graph's model names. + // runAiVerify never throws, so a failure here only leaves the decisions out. + let decisions: VerifierDecision[] | undefined + try { + const features = + ts ?? + input.findings.map((f) => + extractFeatures(f, fileByPath.get(f.file), input.grounding, { parents: [], downstream: [] }, ev.addedLines.get(f.file) ?? new Set()), + ) + const knobs = triageKnobs(deps.env ?? process.env) + decisions = input.findings.map((f, i) => { + const { decision, rule } = triage(f, features[i], undefined, knobs, timedOut) + return compactDecision(f, features[i], undefined, decision, rule) + }) + } catch (e) { + log.error("ai verify decisions failed", { error: e }) + } return { findings: closed ? [] : timedOut ? input.findings.map((f) => toSummary(f, "unreviewed_stopped")) : input.findings, status: status({ @@ -1310,6 +1326,7 @@ export async function runAiVerify( ? { state: "timeout" as const, reason: "no answer before the verifier timeout" } : { state: "error" as const, reason: safeReason(err) }), ...(closed ? { kept: 0, discarded: n } : timedOut ? { kept: 0, summary: n } : {}), + ...(decisions ? { decisions } : {}), }), } } finally { diff --git a/packages/opencode/test/altimate/review-ai-verify.test.ts b/packages/opencode/test/altimate/review-ai-verify.test.ts index 2d3f6fcc49..5fcffecbc2 100644 --- a/packages/opencode/test/altimate/review-ai-verify.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify.test.ts @@ -4,7 +4,6 @@ import { MockLanguageModelV3 } from "ai/test" import z from "zod" import { readStreamStep } from "../../src/altimate/llm/stream-text" import { - aiVerifyEnabled, ANSWER_NOW, ANSWER_DIRECT, applyTriage, @@ -38,6 +37,7 @@ import { inlineEligible } from "../../src/altimate/review/format" import { DEFAULT_POSTING_POLICY } from "../../src/altimate/review/verdict" import type { AiReviewFile } from "../../src/altimate/review/ai-review" import { runAiReview } from "../../src/altimate/review/ai-review" +import { switchOn } from "../../src/altimate/review/ai-switches" import { createDispatcherRunner } from "../../src/altimate/review/runner" import { LLM } from "../../src/session/llm" import { mkdirSync, symlinkSync, writeFileSync } from "fs" @@ -63,11 +63,11 @@ const FAKE_PW = ["SECRET", "123"].join("") describe("wiring", () => { afterEach(() => mock.restore()) - test("opt-in only: ALTIMATE_REVIEW_AI_VERIFY must be exactly 1", () => { - expect(aiVerifyEnabled({})).toBe(false) - expect(aiVerifyEnabled({ ALTIMATE_REVIEW_AI_VERIFY: "0" })).toBe(false) - expect(aiVerifyEnabled({ ALTIMATE_REVIEW_AI_VERIFY: "true" })).toBe(false) - expect(aiVerifyEnabled({ ALTIMATE_REVIEW_AI_VERIFY: "1" })).toBe(true) + test("without resolved switches only ALTIMATE_REVIEW_AI_VERIFY=1 turns the verifier on", () => { + expect(switchOn("verify", undefined, {})).toBe(false) + expect(switchOn("verify", undefined, { ALTIMATE_REVIEW_AI_VERIFY: "0" })).toBe(false) + expect(switchOn("verify", undefined, { ALTIMATE_REVIEW_AI_VERIFY: "true" })).toBe(false) + expect(switchOn("verify", undefined, { ALTIMATE_REVIEW_AI_VERIFY: "1" })).toBe(true) }) test("readStreamStep keeps the SDK's tool calls and response messages for tools without execute", async () => { @@ -476,6 +476,7 @@ describe("triage (first match wins)", () => { ) expect(triage(f, TS, undefined, K)).toEqual({ decision: "keep", rule: "unreviewed" }) expect(triage(f, TS, undefined, { ...K, failMode: "closed" })).toEqual({ decision: "discard", rule: "unreviewed" }) + expect(triage(f, TS, undefined, { ...K, failMode: "closed" }, true)).toEqual({ decision: "discard", rule: "unreviewed_stopped" }) // Without a verdict even a grounding duplicate is left alone: fail-open means unchanged. expect(triage(f, { ...TS, restatesGrounding: true }, undefined, K).decision).toBe("keep") }) @@ -1667,8 +1668,12 @@ describe("runAiVerify: findings left unreviewed when a batch stops", () => { const { llm } = scripted((req) => req.toolChoice === "none" ? { text: JSON.stringify([verdict("c1")]) } : toolStep([["pr_description", {}]], big), ) - const { findings } = await verify(two(), llm, {}, { env: { ALTIMATE_REVIEW_AI_VERIFY_FAIL: "closed" } }) + const { findings, status } = await verify(two(), llm, {}, { env: { ALTIMATE_REVIEW_AI_VERIFY_FAIL: "closed" } }) expect(findings.map((f) => f.title)).toEqual(["fct: first claim"]) + // The stop is recorded under the closed mode too, so re-triage with open knobs demotes it. + const second = status.decisions!.find((d) => d.rule.startsWith("unreviewed"))! + expect(second).toMatchObject({ decision: "discard", rule: "unreviewed_stopped" }) + expect(retriage([second], DEFAULT_TRIAGE_KNOBS).decisions[0]).toMatchObject({ decision: "summary", rule: "unreviewed_stopped" }) }) test("timeout: the findings without a verdict go to the summary, not inline", async () => { @@ -1695,6 +1700,11 @@ describe("runAiVerify: findings left unreviewed when a batch stops", () => { expect(status.summary).toBe(2) expect(status.kept).toBe(0) expect(findings.map((f) => f.tier)).toEqual(["summary", "summary"]) + // Each demoted finding is recorded, so the run can be re-triaged offline. + expect(status.decisions?.map((d) => [d.id, d.decision, d.rule])).toEqual( + findings.map((f) => [f.id, "summary", "unreviewed_stopped"]), + ) + expect(retriage(status.decisions!, { ...DEFAULT_TRIAGE_KNOBS, failMode: "closed" }).counts.discarded).toBe(2) }) test("the closed fail mode still discards them on a timeout", async () => { From d767de119612ffdfde890b0d08d60adf808b934d Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 15:57:44 +0530 Subject: [PATCH 10/34] fix(review): unknown keys under `ai:` fail the config load - the `ai:` object is a `z.strictObject`, so a typo such as `ai: { enable: false }` fails the load and names the key instead of leaving the lane running - the config comment says env overrides are the operator's CI setting, not repository policy - docs: verifier routing as `triage()` does it (refuted dropped; unverifiable cross-file, speculative and unreached go to the summary; plausible local ones stay inline), manifest context where available, `otherFiles` extensions, unknown `ai:` keys - tests: unknown key rejected; the object form's policy hash; the flags-off baseline clears ambient `ALTIMATE_REVIEW_AI_*` variables Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 14 +++++++++----- packages/opencode/src/altimate/review/config.ts | 12 +++++++----- .../test/altimate/review-ai-defaults.test.ts | 2 ++ .../test/altimate/review-ai-switches.test.ts | 9 +++++++++ 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 4d57a3be9d..636cd9ffbb 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -291,13 +291,14 @@ dialect: snowflake # on constructs one of those adapters lacks. Set true to see all of it. reviewers: [] # empty = risk-tier defaults; or pin lanes ai: true # the advisory AI lane; false turns it off. Or an object, all keys - # optional and on by default (see "AI reviewer lane" below): + # optional and on by default; an unknown key fails the load + # (see "AI reviewer lane" below): # ai: # enabled: true # coverage: true # per-kind file quotas and hunk excerpts instead of a 20-file cap # contextCard: true # dbt manifest context with each changed model # focused: true # related files reviewed together in a few calls on larger PRs -# otherFiles: true # other/analysis files inside the project (.sql/.yml/.yaml/.py) +# otherFiles: true # other/analysis files inside the project (.sql/.yml/.yaml) # pythonFiles: true # changed Python files, inside or outside the project # verify: true # the dbt-grounded verifier over the AI comments dataDiff: # OFF by default — see "Data-diff in CI" below @@ -625,9 +626,12 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne changed project files (analyses, CI and config yml, scripts) and changed Python files anywhere in the repository, each labeled with its role, under per-kind quotas (models 12, macros 8, tests 4, yml 6, other 8, Python 6). Related files - are reviewed together, each model with its manifest context, and a dbt-grounded - verifier then checks every AI comment against the code: refuted ones are dropped - and ones it cannot check go to the summary. Findings are clamped to ≤ warning + are reviewed together, with manifest context where a manifest has facts for the + file, and a dbt-grounded verifier then checks every AI comment against the code: + refuted ones are dropped; unverifiable cross-file and speculative ones go to the + summary, as do ones the verifier did not reach before its budget or timeout; + unverifiable local comments with a valid evidence line stay inline (the rest are + dropped). Findings are clamped to ≤ warning and never block. Skipped (clean degrade) if no model is available. Each part can be turned off under `ai:` in `.altimate/review.yml` or with its env variable set to `0` (`ALTIMATE_REVIEW_AI_COVERAGE`, `_CONTEXT_CARD`, `_FOCUSED`, diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 43d19d6335..59b132d816 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -28,14 +28,16 @@ export const ReviewConfig = z.object({ /** * The advisory LLM reviewer lane (needs a configured model): `true`/`false`, * or an object with `enabled` and per-switch settings for what the lane does - * (see ai-switches.ts). An env variable set to `1` or `0` overrides a switch. - * Read from the base branch, so a PR cannot change them for itself. Every key - * is optional so the default policy hash does not change. + * (see ai-switches.ts). Read from the base branch, so a PR cannot change them + * for itself through this file. An env variable set to `1` or `0` overrides a + * switch: that is the operator's setting in the CI workflow, not repository + * policy. Every key is optional so the default policy hash does not change; + * an unknown key fails the load, so a typo cannot leave a switch on. */ ai: z .union([ z.boolean(), - z.object({ + z.strictObject({ enabled: z.boolean().optional(), /** Per-kind file quotas and hunk-centred excerpts instead of a 20-file cap. */ coverage: z.boolean().optional(), @@ -43,7 +45,7 @@ export const ReviewConfig = z.object({ contextCard: z.boolean().optional(), /** Related changed files reviewed together in a few calls on larger PRs. */ focused: z.boolean().optional(), - /** Changed `other`/`analysis` files inside the project (.sql/.yml/.yaml/.py). */ + /** Changed `other`/`analysis` files inside the project (.sql/.yml/.yaml; Python files go through `pythonFiles`). */ otherFiles: z.boolean().optional(), /** Changed Python files, inside or outside the dbt project. */ pythonFiles: z.boolean().optional(), diff --git a/packages/opencode/test/altimate/review-ai-defaults.test.ts b/packages/opencode/test/altimate/review-ai-defaults.test.ts index eb007d40cd..83d0b2bfe8 100644 --- a/packages/opencode/test/altimate/review-ai-defaults.test.ts +++ b/packages/opencode/test/altimate/review-ai-defaults.test.ts @@ -89,6 +89,8 @@ describe("flags-off identity: every switch off is today's lane", () => { const { switches: _s, ...rest } = seen! return { input: rest, env } } + // The env-only baseline reads the switch variables: clear them so ambient values cannot leak in. + for (const k of Object.values(AI_SWITCH_ENV)) delete process.env[k] const legacy = await run() const off = await run(ALL_OFF) expect(off.input).toEqual(legacy.input) diff --git a/packages/opencode/test/altimate/review-ai-switches.test.ts b/packages/opencode/test/altimate/review-ai-switches.test.ts index b4616727ee..828f6a19f3 100644 --- a/packages/opencode/test/altimate/review-ai-switches.test.ts +++ b/packages/opencode/test/altimate/review-ai-switches.test.ts @@ -51,5 +51,14 @@ describe("`ai:` in .altimate/review.yml", () => { test("the default policy hash is unchanged by the object form", () => { expect(DEFAULT_REVIEW_CONFIG.ai).toBe(true) expect(policyHash(parseReviewConfig("mode: comment"))).toBe(policyHash(DEFAULT_REVIEW_CONFIG)) + // The object form hashes as written: an empty object or a set switch is a different policy. + const empty = parseReviewConfig("ai: {}") + expect(aiLaneEnabled(empty)).toBe(true) + expect(resolveAiSwitches(empty, {})).toEqual(AI_SWITCH_DEFAULTS) + expect(policyHash(parseReviewConfig("ai:\n verify: false"))).not.toBe(policyHash(DEFAULT_REVIEW_CONFIG)) + }) + + test("an unknown key under `ai:` fails the load and names the key", () => { + expect(() => parseReviewConfig("ai:\n enable: false")).toThrow(/unrecognized_keys[\s\S]*"enable"/) }) }) From 3db21a51286303bf04e7fb9ee4e88c8aab8165b8 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:16:15 +0530 Subject: [PATCH 11/34] fix(review): hand outside-project Python files on per file under `--all-projects`; classify their findings pre-existing - `reviewAllProjects` keeps the set of outside-project Python files no lane has taken yet and passes it as `aiOutsidePaths`. A file leaves the set only when it is in a project's `ai.input` or `scope.aiReviewedOutside`, so a project whose lane answers without taking it (`ai: { pythonFiles: false }`, quota, exclusions) no longer clears the handoff for later projects. - `run.ts`: `aiOutsidePython?: boolean` becomes `aiOutsidePaths?: string[]`. - `cleanFindings` runs `anchorByEvidence`/`markPreExisting` over the in-scope files plus `aiOutsideFiles`, so a finding on an unchanged context line of an outside-project file is marked pre-existing like an in-project one. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/multi-project.ts | 14 +-- .../src/altimate/review/orchestrate.ts | 4 +- packages/opencode/src/altimate/review/run.ts | 12 ++- .../altimate/review-ai-python-files.test.ts | 99 +++++++++++++++++++ 4 files changed, 116 insertions(+), 13 deletions(-) diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 05238876df..15f01bf53b 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -151,11 +151,11 @@ export async function reviewAllProjects(opts: ReviewPullRequestOptions): Promise const prFiles = collected.map((f) => f.path) const prRenames = collected.flatMap((f) => (f.status === "renamed" && f.oldPath ? [[f.path, f.oldPath] as [string, string]] : [])) const runs: ProjectRun[] = [] - // Python files outside every project go to one project's AI lane only (`pythonFiles`): the - // first project whose lane runs and takes them. While a project's lane does not (off in its - // policy, a tier without the lane), they are offered to the next project. - const unassignedPaths = new Set(unassigned.map((f) => f.path)) - let outsidePythonPending = true + // Python files outside every project go to one project's AI lane only (`pythonFiles`): each + // file is offered to project after project until a lane takes it (it is in the lane's input, + // or the lane reviewed it). A project that does not take it (lane off in its policy, + // `pythonFiles: false`, a tier without the lane, its quota) passes it on. + const pendingOutside = new Set(unassigned.map((f) => f.path)) for (const root of touched) { const own = byProject.get(root)! process.stderr.write(`ℹ️ reviewing dbt project ${root || "."} (${own.length} changed file(s))\n`) @@ -164,9 +164,9 @@ export async function reviewAllProjects(opts: ReviewPullRequestOptions): Promise changedFiles: [...own, ...unassigned], prFiles, prRenames, - aiOutsidePython: outsidePythonPending, + aiOutsidePaths: [...pendingOutside], }) - if (env.ai?.state === "ok" || (env.ai?.input ?? []).some((r) => unassignedPaths.has(r.path))) outsidePythonPending = false + for (const p of [...(env.ai?.input ?? []).map((r) => r.path), ...(env.scope?.aiReviewedOutside ?? [])]) pendingOutside.delete(p) runs.push({ root, paths: own.map((f) => f.path), env }) } return mergeProjectEnvelopes(runs, roots) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index dda43a5a4e..bed424cc39 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2606,6 +2606,7 @@ export async function runReview(input: OrchestrateInput): Promise { let out = dedupe(list) .filter((f) => !exclusionReason(f, input.rubric)) @@ -2626,7 +2627,8 @@ export async function runReview(input: OrchestrateInput): Promise !isSuppressiblePortability(f, dialect, input.portabilityTargets)) - out = markPreExisting(anchorByEvidence(out, input.changedFiles), input.changedFiles) + // Outside-project files the AI lane reads are classified like in-project ones. + out = markPreExisting(anchorByEvidence(out, scopedFiles), scopedFiles) if (merge) out = mergeRepeats(out) return out.sort((a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || a.file.localeCompare(b.file)) } diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index f8f5e3cf71..d22f3f99a0 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -80,9 +80,10 @@ export interface ReviewPullRequestOptions { prFiles?: string[] /** Every rename the PR makes (new → old path), when `changedFiles` is a subset of it. */ prRenames?: Array<[string, string]> - /** Send changed Python files outside the dbt project to this review's AI lane (`pythonFiles` - * switch). Default true; `--all-projects` sets it until one project's AI lane runs. */ - aiOutsidePython?: boolean + /** 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. */ @@ -375,9 +376,10 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise const aiSwitches = resolveAiSwitches(config) // `pythonFiles`: .py files outside the dbt project skip every lane but the AI lane. const outside = new Set(scoped.outOfScopePaths) + const offered = opts.aiOutsidePaths && new Set(opts.aiOutsidePaths) const aiOutsideFiles = - aiOn && aiSwitches.pythonFiles && opts.aiOutsidePython !== false - ? collected.filter((f) => outside.has(f.path) && isAiPythonFile(f)) + aiOn && aiSwitches.pythonFiles + ? collected.filter((f) => outside.has(f.path) && isAiPythonFile(f) && (!offered || offered.has(f.path))) : [] const notReviewedOutside = scoped.outOfScope - aiOutsideFiles.length if (notReviewedOutside > 0) { diff --git a/packages/opencode/test/altimate/review-ai-python-files.test.ts b/packages/opencode/test/altimate/review-ai-python-files.test.ts index 34867ce706..a7ea5426f5 100644 --- a/packages/opencode/test/altimate/review-ai-python-files.test.ts +++ b/packages/opencode/test/altimate/review-ai-python-files.test.ts @@ -10,6 +10,7 @@ import { DEFAULT_DBT_DIRS, type ChangedFile } from "../../src/altimate/review/di import { aiInputBudget, planAiInput, selectAiFilesByQuota, type AiReviewFile, type AiReviewInput } from "../../src/altimate/review/ai-review" import { AI_PYTHON_KIND, isAiPythonFile } from "../../src/altimate/review/ai-python-files" import { mergeProjectEnvelopes, reviewAllProjects } from "../../src/altimate/review/multi-project" +import { makeFinding, ruleId } from "../../src/altimate/review/finding" // The `pythonFiles` switch (ALTIMATE_REVIEW_AI_PYTHON_FILES) sends changed .py files, inside or outside the dbt project, to the AI lane. @@ -436,3 +437,101 @@ describe("ai.unsent lists only files the deterministic lanes checked", () => { expect(res.status.unsent).toBeUndefined() }) }) + +describe("--all-projects: the outside-project handoff follows what a project actually took", () => { + const git = (cwd: string, ...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { + cwd, + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }).toString() + const write = async (root: string, rel: string, body: string) => { + await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) + await fs.writeFile(path.join(root, rel), body) + } + const ENV = ["ALTIMATE_REVIEW_AI_REPLAY", "ALTIMATE_REVIEW_AI_VERIFY"] + const savedEnv = Object.fromEntries(ENV.map((k) => [k, process.env[k]])) + afterEach(() => { + for (const k of ENV) { + if (savedEnv[k] === undefined) delete process.env[k] + else process.env[k] = savedEnv[k] + } + }) + + test("the first project's lane answers with `pythonFiles: false`: the next project's lane reviews the file", async () => { + const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-py-mp-took-"))) + try { + await write(root, "a/dbt_project.yml", "name: a\n") + await write(root, "a/.altimate/review.yml", "ai:\n pythonFiles: false\n") + await write(root, "a/models/m.sql", "select 1 as id\n") + await write(root, "b/dbt_project.yml", "name: b\n") + await write(root, "b/models/n.sql", "select 1 as id\n") + await write(root, "airflow/load.py", "print(1)\n") + git(root, "init", "-q", "-b", "main") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "base") + git(root, "checkout", "-q", "-b", "pr") + await write(root, "a/models/m.sql", "select 1 as id, 2 as x\n") + await write(root, "b/models/n.sql", "select 1 as id, 3 as y\n") + await write(root, "airflow/load.py", "print(2)\n") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "pr") + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "ALTIMATE_REVIEW_AI_PYTHON_FILES"]) + delete process.env[k] + // A replayed lane answers (`state: ok`) without a model call; the verifier is off. + const replay = path.join(root, "..", path.basename(root) + "-replay.json") + await fs.writeFile(replay, JSON.stringify({ findings: [], ai: { state: "ok", calls: 1 } })) + process.env.ALTIMATE_REVIEW_AI_REPLAY = replay + process.env.ALTIMATE_REVIEW_AI_VERIFY = "0" + try { + const env = await reviewAllProjects({ cwd: root, base: "main", head: "HEAD" }) + expect(env.scope?.aiReviewedOutside).toEqual(["airflow/load.py"]) + expect((env.scope?.notReviewed ?? []).map((n) => n.path)).not.toContain("airflow/load.py") + } finally { + await fs.rm(replay, { force: true }) + } + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) +}) + +describe("outside-project Python findings are classified pre-existing like in-project ones", () => { + test("a finding on a context line of an outside .py file is marked pre-existing", async () => { + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" + const outside: ChangedFile = { path: "airflow/load.py", status: "modified", diff: "@@ -1,2 +1,3 @@\n a = 1\n b = 2\n+c = 3\n" } + const env = await runReview({ + changedFiles: [mod("dbt/models/m.sql")], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + layout: { root: "dbt", dirs: DEFAULT_DBT_DIRS }, + aiOutsideFiles: [outside], + getContent: async (f, side) => (side === "old" ? undefined : "a = 1\nb = 2\nc = 3\n"), + generatedAt: "2026-11-27T00:00:00Z", + aiReview: async () => ({ + findings: [ + makeFinding({ + severity: "warning", + category: "sql_correctness", + title: "load: unused name", + body: "b is never read.", + file: "airflow/load.py", + model: "load", + startLine: 2, + endLine: 2, + confidence: "high", + evidence: { tool: "ai-review", result: {} }, + ruleKey: "ai:sql_correctness:unused name", + rule: ruleId("ai-review", "sql_correctness"), + }), + ], + status: { state: "ok" }, + }), + }) + const f = env.findings.find((x) => x.file === "airflow/load.py") + expect(f).toBeDefined() + expect(f!.preExisting).toBe(true) + }) +}) From fcb133bfcd2dfe0ec493cd3f763f4f10b3806572 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:16:33 +0530 Subject: [PATCH 12/34] fix(review): refuse a system-prompt file inside the git work tree `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE` must be an absolute path, and its realpath (symlinks followed) must not be inside the git work tree of the current directory, which in CI is the PR checkout. A relative path such as `.github/review-prompt.md` would otherwise let any PR rewrite the finder's system prompt. The error messages no longer echo the path. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-review.ts | 27 +++++++++++++++---- .../altimate/review-ai-system-prompt.test.ts | 22 +++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 2f80b2bf80..79e47d8f8c 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -7,7 +7,9 @@ import { MessageID, SessionID } from "@/session/schema" import { Log } from "@/altimate/util/log" import { redactSecrets } from "@/installation" import { Dispatcher } from "../native" -import { readFile } from "node:fs/promises" +import { readFile, realpath } from "node:fs/promises" +import path from "node:path" +import { gitRepoRoot } from "./git" import { type Finding, type ReviewCategory, type Severity, makeFinding, ruleId } from "./finding" import { readStreamText } from "../llm/stream-text" import { type AiVerifyEvidence, type VerifierStatus, runAiVerify } from "./ai-verify" @@ -921,19 +923,34 @@ function buildBatchMessage( /** * 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. + * an error, never a silent fallback to the core prompt. The path must be absolute and must not + * resolve (symlinks followed) inside the git work tree of `cwd`: in CI that is the PR checkout, + * so a file there would let the PR rewrite the prompt. */ -export async function finderSystemPrompt(env: Record = process.env): Promise { +export async function finderSystemPrompt( + env: Record = process.env, + cwd: string = process.cwd(), +): Promise { const file = env.ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE if (file) { - const text = await readFile(file, "utf8") - if (!text.trim()) throw new Error(`ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE is empty: ${file}`) + if (!path.isAbsolute(file)) throw new Error("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE must be an absolute path outside the repository") + const real = await realpath(file) + const tree = await gitRepoRoot(cwd) + if (tree && isInside(real, await realpath(tree))) + throw new Error("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE is inside the git work tree; place it outside the checkout") + 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 } +function isInside(p: string, dir: string): boolean { + const rel = path.relative(dir, p) + return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel)) +} + /** What the lane would send: files, the unsent rest, one message per call, and a record per file. */ export interface AiInputPlan { budget: AiInputBudget diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts index 15d5269653..213094ae95 100644 --- a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -31,4 +31,26 @@ describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file })).rejects.toThrow("is empty") await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: path.join(tmp.path, "none.txt") })).rejects.toThrow() }) + + test("a relative path is refused: it would resolve inside the PR checkout", async () => { + spy = spyOn(Dispatcher, "call").mockResolvedValue({ success: true, data: { prompt: "CORE" } } as any) + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: "review-prompt.md" })).rejects.toThrow("absolute path") + expect(spy).not.toHaveBeenCalled() + }) + + test("a file inside the git work tree, or a symlink to one, is refused", async () => { + await using repo = await tmpdir({ git: true }) + await using outside = await tmpdir() + const inside = path.join(repo.path, ".github", "review-prompt.md") + await fs.mkdir(path.dirname(inside), { recursive: true }) + await fs.writeFile(inside, "PR PROMPT") + const link = path.join(outside.path, "link.md") + await fs.symlink(inside, link) + for (const file of [inside, link]) + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, repo.path)).rejects.toThrow("inside the git work tree") + // The same text outside the work tree is read. + const ok = path.join(outside.path, "p.md") + await fs.writeFile(ok, "RUNNER PROMPT") + expect(await finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: ok }, repo.path)).toBe("RUNNER PROMPT") + }) }) From 9d5ab27f5ab6636804e0fd104a964beded69748c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:16:33 +0530 Subject: [PATCH 13/34] fix(review): AI switch env values accept common boolean spellings; others warn Before the switches were resolved together, any value other than `1` meant off, so a workflow with `ALTIMATE_REVIEW_AI_VERIFY=false` would now get the default (on). `envSwitch` now reads `1`/`true`/`on`/`yes` as on and `0`/`false`/`off`/`no` as off (trimmed, case-insensitive). Any other non-empty value is ignored with a stderr warning from `resolveAiSwitches` naming the variable, and the config or default applies. The wiring test that expected `true` to leave the verifier off now expects it on (that is the requested change) and checks an unrecognized value instead. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/ai-switches.ts | 23 ++++++++++++++----- .../test/altimate/review-ai-switches.test.ts | 21 ++++++++++++++++- .../test/altimate/review-ai-verify.test.ts | 5 ++-- 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index a2387e2d5a..568991ccbf 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -1,6 +1,7 @@ // altimate_change - new file: what the AI review lane does, resolved once per review // -// Each switch is set by, in order: its env variable (`1` on, `0` off), the +// Each switch is set by, in order: its env variable (`1`/`true`/`on`/`yes` on, +// `0`/`false`/`off`/`no` off; any other value is ignored with a warning), the // `ai:` object in `.altimate/review.yml` (read from the base branch), then the // product default. `reviewPullRequest` resolves the switches and passes them // down; code called without them (direct callers, unit tests) reads only the @@ -37,18 +38,28 @@ export const AI_SWITCH_DEFAULTS: AiSwitches = { type Env = Record -/** The env override for a switch: true for `1`, false for `0`, undefined otherwise. */ +const ENV_TRUE = new Set(["1", "true", "on", "yes"]) +const ENV_FALSE = new Set(["0", "false", "off", "no"]) + +/** The env override for a switch: true for `1`/`true`/`on`/`yes`, false for `0`/`false`/`off`/`no` + * (case-insensitive), undefined otherwise. */ export function envSwitch(name: AiSwitchName, env: Env = process.env): boolean | undefined { - const v = env[AI_SWITCH_ENV[name]] - return v === "1" ? true : v === "0" ? false : undefined + const v = env[AI_SWITCH_ENV[name]]?.trim().toLowerCase() + if (v === undefined) return undefined + return ENV_TRUE.has(v) ? true : ENV_FALSE.has(v) ? false : undefined } /** Every switch for one review: env, then the `ai:` config object, then the default. */ export function resolveAiSwitches(cfg: Pick, env: Env = process.env): AiSwitches { const configured = typeof cfg.ai === "object" ? cfg.ai : {} const out = { ...AI_SWITCH_DEFAULTS } - for (const name of Object.keys(AI_SWITCH_ENV) as AiSwitchName[]) - out[name] = envSwitch(name, env) ?? configured[name] ?? AI_SWITCH_DEFAULTS[name] + for (const name of Object.keys(AI_SWITCH_ENV) as AiSwitchName[]) { + const fromEnv = envSwitch(name, env) + const raw = env[AI_SWITCH_ENV[name]] + if (fromEnv === undefined && raw?.trim()) + process.stderr.write(`⚠️ ignoring ${AI_SWITCH_ENV[name]}=${raw}: use 1/0 (or true/false, on/off, yes/no)\n`) + out[name] = fromEnv ?? configured[name] ?? AI_SWITCH_DEFAULTS[name] + } return out } diff --git a/packages/opencode/test/altimate/review-ai-switches.test.ts b/packages/opencode/test/altimate/review-ai-switches.test.ts index 828f6a19f3..a737f7c9c6 100644 --- a/packages/opencode/test/altimate/review-ai-switches.test.ts +++ b/packages/opencode/test/altimate/review-ai-switches.test.ts @@ -7,10 +7,29 @@ describe("AI switches", () => { test("env 1/0 override, anything else defers", () => { expect(envSwitch("coverage", { ALTIMATE_REVIEW_AI_COVERAGE: "1" })).toBe(true) expect(envSwitch("coverage", { ALTIMATE_REVIEW_AI_COVERAGE: "0" })).toBe(false) - expect(envSwitch("coverage", { ALTIMATE_REVIEW_AI_COVERAGE: "yes" })).toBeUndefined() + expect(envSwitch("coverage", { ALTIMATE_REVIEW_AI_COVERAGE: "maybe" })).toBeUndefined() + expect(envSwitch("coverage", { ALTIMATE_REVIEW_AI_COVERAGE: "" })).toBeUndefined() expect(envSwitch("coverage", {})).toBeUndefined() }) + test("common boolean spellings are accepted, so `=false` still turns a switch off", () => { + for (const v of ["true", "TRUE", "on", "yes", " 1 "]) expect(envSwitch("verify", { ALTIMATE_REVIEW_AI_VERIFY: v })).toBe(true) + for (const v of ["false", "False", "off", "no", "0"]) expect(envSwitch("verify", { ALTIMATE_REVIEW_AI_VERIFY: v })).toBe(false) + expect(resolveAiSwitches({ ai: true }, { ALTIMATE_REVIEW_AI_VERIFY: "false" }).verify).toBe(false) + }) + + test("a value that is not a boolean is ignored with a warning naming the variable", () => { + const write0 = process.stderr.write + let err = "" + ;(process.stderr as any).write = (s: string) => ((err += s), true) + try { + expect(resolveAiSwitches({ ai: true }, { ALTIMATE_REVIEW_AI_VERIFY: "disabled" }).verify).toBe(true) + } finally { + ;(process.stderr as any).write = write0 + } + expect(err).toContain("ALTIMATE_REVIEW_AI_VERIFY=disabled") + }) + test("env wins over config, config over the default", () => { const cfg = { ai: { coverage: true, focused: false } } expect(resolveAiSwitches(cfg, {}).coverage).toBe(true) diff --git a/packages/opencode/test/altimate/review-ai-verify.test.ts b/packages/opencode/test/altimate/review-ai-verify.test.ts index 5fcffecbc2..c6b4606fd8 100644 --- a/packages/opencode/test/altimate/review-ai-verify.test.ts +++ b/packages/opencode/test/altimate/review-ai-verify.test.ts @@ -63,11 +63,12 @@ const FAKE_PW = ["SECRET", "123"].join("") describe("wiring", () => { afterEach(() => mock.restore()) - test("without resolved switches only ALTIMATE_REVIEW_AI_VERIFY=1 turns the verifier on", () => { + test("without resolved switches only an on value of ALTIMATE_REVIEW_AI_VERIFY turns the verifier on", () => { expect(switchOn("verify", undefined, {})).toBe(false) expect(switchOn("verify", undefined, { ALTIMATE_REVIEW_AI_VERIFY: "0" })).toBe(false) - expect(switchOn("verify", undefined, { ALTIMATE_REVIEW_AI_VERIFY: "true" })).toBe(false) + expect(switchOn("verify", undefined, { ALTIMATE_REVIEW_AI_VERIFY: "maybe" })).toBe(false) expect(switchOn("verify", undefined, { ALTIMATE_REVIEW_AI_VERIFY: "1" })).toBe(true) + expect(switchOn("verify", undefined, { ALTIMATE_REVIEW_AI_VERIFY: "true" })).toBe(true) }) test("readStreamStep keeps the SDK's tool calls and response messages for tools without execute", async () => { From 229b4cad3a3d5ddb2731b355ed7ad879458350e9 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:16:46 +0530 Subject: [PATCH 14/34] fix(review): list over-quota `other` files a rule lane checked in `ai.unsent` `runAiReview` dropped every other/analysis/Python file from `ai.unsent` because the coverage ledger lists files only the AI lane reads. But the `dbt_patterns` lane parses changed `other` YAML files (`otherChecked`), and the ledger skips those, so one the other quota kept from the model was reported nowhere. The orchestrator now passes `otherChecked` as `checkedPaths`, and such files stay in `ai.unsent`. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-review.ts | 13 +++++-- .../src/altimate/review/orchestrate.ts | 1 + .../altimate/review-ai-other-files.test.ts | 37 +++++++++++++++++++ 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 79e47d8f8c..6e00712ba3 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -746,6 +746,9 @@ export interface AiReviewInput { 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[] } /** What happened in the advisory lane, reported on the envelope and in the comment. */ @@ -773,7 +776,8 @@ export interface AiLaneStatus { /** What each file sent carried; recorded under coverage, context cards or dry run. */ input?: AiInputRecord[] /** Sendable files left out by the coverage quotas (they still went through the deterministic lanes). - * Files only the AI lane reads (other/analysis, Python) are not listed: the coverage ledger has them. */ + * 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 sent only in calls that failed while others answered (state `ok`): not reviewed by the lane. */ failedFiles?: string[] @@ -1001,9 +1005,10 @@ export async function runAiReview(input: AiReviewInput): Promise const plan = planAiInput(input) const { files, budget } = plan const dryRun = aiDryRunEnabled() - // Recorded only when an opt-in switch changed or inspects the input, so the default envelope is unchanged. - // Files only the AI lane reads are not "checked by the deterministic lanes"; the ledger lists them. - const unsent = plan.unsent.filter((f) => !AI_ONLY_KINDS.has(f.kind ?? "")).map((f) => f.path) + // Recorded under coverage, focused batching, context cards or dry run (all 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 } : {}), diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index bed424cc39..32cebd2fcc 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2797,6 +2797,7 @@ export async function runReview(input: OrchestrateInput): Promise { }) }) +describe("other files over their quota are reported somewhere", () => { + test("a YAML file a rule lane checked but the quota kept from the model is in ai.unsent; an unchecked one in the ledger", async () => { + const { runAiReview } = await import("../../src/altimate/review/ai-review") + const saved = process.env.ALTIMATE_REVIEW_AI_DRYRUN + process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" + try { + const ymls = Array.from({ length: 10 }, (_, i) => mod(`integration_tests/c${i}.yml`)) + const analyses = Array.from({ length: 10 }, (_, i) => mod(`analyses/a${i}.sql`)) + const env = await runReview({ + changedFiles: [mod("models/marts/m.sql"), ...ymls, ...analyses], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + aiSwitches: { coverage: true, otherFiles: true }, + getContent: async (f, side) => (side === "old" ? "a: 1\n" : "a: 2\n"), + generatedAt: "2026-11-27T00:00:00Z", + aiReview: runAiReview, + }) + const sent = new Set((env.ai?.input ?? []).map((r) => r.path)) + const unsent = new Set(env.ai?.unsent ?? []) + const ledger = new Set((env.scope?.notReviewed ?? []).map((n) => n.path)) + for (const f of [...ymls, ...analyses]) { + if (sent.has(f.path)) continue + // Every changed file the model did not see is reported exactly once. + expect([unsent.has(f.path), ledger.has(f.path)].filter(Boolean).length).toBe(1) + } + expect(ymls.some((f) => unsent.has(f.path))).toBe(true) + expect(analyses.some((f) => ledger.has(f.path))).toBe(true) + } finally { + if (saved === undefined) delete process.env.ALTIMATE_REVIEW_AI_DRYRUN + else process.env.ALTIMATE_REVIEW_AI_DRYRUN = saved + } + }) +}) + describe("ALTIMATE_REVIEW_AI_OTHER_FILES: planner", () => { const file = (path: string, kind: string, lines = 1, status = "modified"): AiReviewFile => ({ path, From efe08b06db617a8309cc735905f87a21e966ef3c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:16:46 +0530 Subject: [PATCH 15/34] fix(review): carry `ai.failedFiles` through an AI replay `replayFindings` copied only state, reason, model, tokens, cost and calls, so a partly failed envelope replayed with `ALTIMATE_REVIEW_AI_REPLAY` came back without `failedFiles` and the ledger counted the files its failed calls carried as reviewed. The replay schema and status now keep the field. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/ai-replay.ts | 4 +++- packages/opencode/test/altimate/review-ai-replay.test.ts | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/ai-replay.ts b/packages/opencode/src/altimate/review/ai-replay.ts index 63b689d01c..1c68425a05 100644 --- a/packages/opencode/src/altimate/review/ai-replay.ts +++ b/packages/opencode/src/altimate/review/ai-replay.ts @@ -44,6 +44,7 @@ const ReplayEnvelope = z.object({ tokens: Tokens.optional(), cost: z.number().optional(), calls: z.number().optional(), + failedFiles: z.array(z.string()).optional(), verifier: z .object({ discarded: z.number().optional(), @@ -71,7 +72,7 @@ const ReplayEnvelope = z.object({ export interface ReplayedLane { findings: Finding[] - /** The stored generator status: state, reason, model, tokens, cost, calls. */ + /** The stored generator status: state, reason, model, tokens, cost, calls, failed files. */ status: Omit /** Problems found while rebuilding (findings that could not be recovered). */ warnings: string[] @@ -95,6 +96,7 @@ export function replayFindings(raw: unknown): ReplayedLane { ...(ai.tokens ? { tokens: ai.tokens } : {}), ...(ai.cost !== undefined ? { cost: ai.cost } : {}), ...(ai.calls !== undefined ? { calls: ai.calls } : {}), + ...(ai.failedFiles?.length ? { failedFiles: ai.failedFiles } : {}), replayed: true, } const warnings: string[] = [] diff --git a/packages/opencode/test/altimate/review-ai-replay.test.ts b/packages/opencode/test/altimate/review-ai-replay.test.ts index 72be34a8d8..0a511091fe 100644 --- a/packages/opencode/test/altimate/review-ai-replay.test.ts +++ b/packages/opencode/test/altimate/review-ai-replay.test.ts @@ -133,6 +133,11 @@ describe("replayFindings (envelope → the generator's findings)", () => { expect(lane.status).toEqual({ state: "ok", calls: 1, replayed: true }) }) + test("a partly failed lane keeps its failed files, so the ledger still lists them", () => { + const lane = replayFindings({ findings: [], ai: { state: "ok", calls: 2, reason: "1 of 2 calls failed: boom", failedFiles: ["models/b.sql"] } }) + expect(lane.status.failedFiles).toEqual(["models/b.sql"]) + }) + test("an envelope without an AI lane cannot be replayed", () => { expect(() => replayFindings({ findings: [] })).toThrow("no AI lane status") }) From 2c627299c531ec5f45892d8e2d97fd9ccea775f4 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:16:47 +0530 Subject: [PATCH 16/34] fix(review): state the default-on AI parts and their cost; drop stale opt-in comments - Docs: every AI part is on by default and adds model calls; how to opt out (`ai: { verify: false }`, env `0`, `ai: false`); accepted env spellings; quotas apply with `coverage` (one 20-file cap without it); the system-prompt file must be absolute and outside the checkout. - Comments that still described coverage, focused batches, context cards and the verifier as opt-in `=1` features now name their switches. - `fenceOf`: drop the unreachable `.py` branch (Python files take their fence from `FENCE`); the `otherFiles` comment no longer lists `.py`. - Telemetry: `ai_reviewed_outside_files`, since `out_of_scope_files` now leaves out outside-project files the AI lane reviewed. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 21 +++++++++++++------ .../opencode/src/altimate/review/ai-review.ts | 18 ++++++++-------- .../src/altimate/review/orchestrate.ts | 6 +++--- .../opencode/src/altimate/review/telemetry.ts | 1 + .../opencode/src/altimate/review/verdict.ts | 6 +++--- .../opencode/src/altimate/telemetry/index.ts | 3 +++ 6 files changed, 34 insertions(+), 21 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 636cd9ffbb..df86fd540d 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -625,18 +625,27 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne snapshots, schema/source yml, seeds (diff only) and project config, plus other changed project files (analyses, CI and config yml, scripts) and changed Python files anywhere in the repository, each labeled with its role, under per-kind - quotas (models 12, macros 8, tests 4, yml 6, other 8, Python 6). Related files + quotas (models 12, macros 8, tests 4, yml 6, other 8, Python 6; with `coverage` + off, one 20-file cap applies instead). Related files are reviewed together, with manifest context where a manifest has facts for the file, and a dbt-grounded verifier then checks every AI comment against the code: refuted ones are dropped; unverifiable cross-file and speculative ones go to the summary, as do ones the verifier did not reach before its budget or timeout; unverifiable local comments with a valid evidence line stay inline (the rest are dropped). Findings are clamped to ≤ warning - and never block. Skipped (clean degrade) if no model is available. Each part can - be turned off under `ai:` in `.altimate/review.yml` or with its env variable set - to `0` (`ALTIMATE_REVIEW_AI_COVERAGE`, `_CONTEXT_CARD`, `_FOCUSED`, - `_OTHER_FILES`, `_PYTHON_FILES`, `_VERIFY`); `1` turns one on. - `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE=` replaces the finder's system prompt. + and never block. Skipped (clean degrade) if no model is available. Every part is + on by default, so with a model configured the default review makes more model + calls than the finder alone (the verifier, and more files per PR): more tokens and + wall time per review. Each part can be turned off under `ai:` in + `.altimate/review.yml` (for example `ai: { verify: false }`) or with its env + variable set to `0` (`ALTIMATE_REVIEW_AI_COVERAGE`, `_CONTEXT_CARD`, `_FOCUSED`, + `_OTHER_FILES`, `_PYTHON_FILES`, `_VERIFY`); `1` turns one on. `true`/`false`, + `on`/`off` and `yes`/`no` are accepted too; any other value is ignored with a + warning. `ai: false` turns the whole lane off. + `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE=` replaces the finder's system + prompt. The path must be absolute and outside the repository checkout (for + example under `$RUNNER_TEMP`); a file inside the git work tree, or a symlink to + one, is refused, since a PR could change it. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 6e00712ba3..4c6e3fc381 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -32,7 +32,7 @@ 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 `ALTIMATE_REVIEW_AI_COVERAGE=1`. */ +/** 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 @@ -43,7 +43,7 @@ const COVERAGE_FULL_DIFF_FILE_CHARS = 2_000 /** Default per-call size under coverage (~30k tokens): 30 quota files at up to ~22k chars each would * otherwise make one ~660k-char call that overruns common context windows. */ const COVERAGE_BATCH_CHARS = 120_000 -/** Focused batching defaults under `ALTIMATE_REVIEW_AI_FOCUSED=1`. */ +/** 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 @@ -59,13 +59,13 @@ export interface AiInputBudget { maxFileChars: number /** Characters of file sections per call; Infinity keeps a single call (the default without coverage). */ batchChars: number - /** `ALTIMATE_REVIEW_AI_COVERAGE=1`: per-kind file quotas (replacing `maxFiles`) and + /** 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 } - /** `ALTIMATE_REVIEW_AI_FOCUSED=1`: on PRs with at least `minFiles` selected files, review + /** 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 @@ -177,7 +177,7 @@ export interface AiReviewFile { diff?: string /** Current content: dbt-compiled (preferred) or raw SQL for a model, the file itself otherwise. */ sql?: string - /** Rendered dbt manifest context card (`ALTIMATE_REVIEW_AI_CONTEXT_CARD=1`). */ + /** Rendered dbt manifest context card (the `contextCard` switch). */ card?: string } @@ -213,7 +213,7 @@ function fenceOf(f: AiReviewFile): string { if (known) return known if (!AI_OTHER_KINDS.has(f.kind ?? "")) return "sql" const p = f.path.toLowerCase() - return p.endsWith(".py") ? "python" : p.endsWith(".yml") || p.endsWith(".yaml") ? "yaml" : "sql" + return p.endsWith(".yml") || p.endsWith(".yaml") ? "yaml" : "sql" } function kindRank(kind: string | undefined): number { @@ -740,7 +740,7 @@ export interface AiReviewInput { 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 `ALTIMATE_REVIEW_AI_VERIFY=1`. */ + /** What the verifier may read; it runs only when this is set and the `verify` switch is on. */ evidence?: AiVerifyEvidence /** Every file the PR changes (repo-relative), including files outside the dbt project. */ prFiles?: string[] @@ -766,7 +766,7 @@ export interface AiLaneStatus { cost?: number /** Model calls made (one per batch). */ calls?: number - /** The dbt-grounded verifier's outcome, when it ran (opt-in). */ + /** 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. */ @@ -964,7 +964,7 @@ export interface AiInputPlan { batches: AiReviewFile[][] messages: string[] input: AiInputRecord[] - /** Focused batching applied (`ALTIMATE_REVIEW_AI_FOCUSED=1` and enough files). */ + /** Focused batching applied (the `focused` switch and enough files). */ focused: boolean } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 32cebd2fcc..8e8c2e4392 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -288,9 +288,9 @@ export interface OrchestrateInput { aiModel?: string /** Send the changed files' unchanged dbt parents to the AI lane as context. */ aiGraphContext?: boolean - /** Attach a dbt manifest context card to each AI file (`ALTIMATE_REVIEW_AI_CONTEXT_CARD=1`; needs a manifest). */ + /** Attach a dbt manifest context card to each AI file (the `contextCard` switch; needs a manifest). */ aiContextCard?: boolean - /** Give the AI lane what the dbt-grounded verifier reads (`ALTIMATE_REVIEW_AI_VERIFY=1`). */ + /** Give the AI lane what the dbt-grounded verifier reads (the `verify` switch). */ aiVerify?: boolean /** The review's resolved AI switches (ai-switches.ts); without them each switch reads its env variable. */ aiSwitches?: Partial @@ -2680,7 +2680,7 @@ export async function runReview(input: OrchestrateInput): Promise AI_SUPPORTING_KINDS.has(f.kind) && f.status !== "deleted" && !mayHoldCredentials(f.path), ) - // `otherFiles`: other/analysis files inside the project root (.sql/.yml/.yaml/.py), after the supporting files. + // `otherFiles`: other/analysis files inside the project root (.sql/.yml/.yaml), after the supporting files. if (switchOn("otherFiles", input.aiSwitches)) { const root = input.layout?.root supporting.push( diff --git a/packages/opencode/src/altimate/review/telemetry.ts b/packages/opencode/src/altimate/review/telemetry.ts index c07058ad19..3d9da966f4 100644 --- a/packages/opencode/src/altimate/review/telemetry.ts +++ b/packages/opencode/src/altimate/review/telemetry.ts @@ -130,6 +130,7 @@ export function emitReviewRun(input: { ai_verify_discarded: env.ai?.verifier?.discarded, base_source: env.scope?.baseSource, out_of_scope_files: env.scope?.outOfScopeFiles ?? 0, + ai_reviewed_outside_files: env.scope?.aiReviewedOutside?.length ?? 0, engine_errors: env.engineErrors?.reduce((n, e) => n + e.count, 0) ?? 0, stale_manifest: env.staleManifest === true, critical: env.summary.critical, diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index f2272e78d3..e268bca07b 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -269,7 +269,7 @@ export const VerdictEnvelope = z.object({ replayed: z.boolean().optional(), /** The replayed envelope did not list every generator finding. */ replayIncomplete: z.boolean().optional(), - /** What each file sent to the model carried (opt-in coverage, context cards or dry run). */ + /** What each file sent to the model carried (coverage, focused batching, context cards or dry run). */ input: z .array( z.object({ @@ -285,11 +285,11 @@ export const VerdictEnvelope = z.object({ }), ) .optional(), - /** Sendable files the opt-in coverage quotas kept from the model (the deterministic lanes still checked them). */ + /** Sendable files the coverage quotas kept from the model (the deterministic lanes still checked them). */ unsent: z.array(z.string()).optional(), /** Files sent only in calls that failed while other calls answered: not reviewed by the AI lane. */ failedFiles: z.array(z.string()).optional(), - /** The opt-in dbt-grounded verifier (`ALTIMATE_REVIEW_AI_VERIFY=1`): what it kept and dropped. */ + /** The dbt-grounded verifier (the `verify` switch): what it kept and dropped. */ verifier: z .object({ state: z.enum(["ok", "skipped", "timeout", "error", "budget"]), diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index ea2cac069d..5b673f3e7c 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -1681,7 +1681,10 @@ export namespace Telemetry { ai_verify_discarded?: number /** Where the review base came from (flag, github_event, default_branch, …). */ base_source?: string + /** Changed files outside the dbt project that no lane reviewed (outside-project Python files the AI lane reviewed are not counted; see `ai_reviewed_outside_files`). */ out_of_scope_files?: number + /** Changed files outside the dbt project the AI lane reviewed (`pythonFiles`). */ + ai_reviewed_outside_files?: number /** Engine calls that threw during the review (their checks did not run). */ engine_errors?: number stale_manifest?: boolean From 051d0ecd2093828be840c06b95fa3dcbe35c5d30 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:01:47 +0530 Subject: [PATCH 17/34] fix(review): check the system-prompt file against the reviewed repository and fail closed The check used `gitRepoRoot(process.cwd())`: a review run with `--cwd` from outside the repository, or where git refuses the directory (`safe.directory`), skipped it, and `/..p.md` passed the prefix test. `trustedFilePath` (new `trusted-file.ts`, shared with the rules-off list in the next PR) requires an absolute path, resolves its realpath and refuses it when it is inside the review's repository (`reviewDir`, the `--cwd` git root passed through `OrchestrateInput` and `AiReviewInput`) or the process's work tree. Work trees are found by walking up to a `.git` entry, with no git call. When neither resolves, the file is refused. The prefix test is `rel === ".." || rel.startsWith(".." + sep)`, and the checked realpath is the one read. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 5 +- .../opencode/src/altimate/review/ai-review.ts | 26 ++++------- .../src/altimate/review/orchestrate.ts | 3 ++ packages/opencode/src/altimate/review/run.ts | 1 + .../src/altimate/review/trusted-file.ts | 43 +++++++++++++++++ .../altimate/review-ai-system-prompt.test.ts | 46 +++++++++++++++++++ 6 files changed, 105 insertions(+), 19 deletions(-) create mode 100644 packages/opencode/src/altimate/review/trusted-file.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index df86fd540d..098bfa3206 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -644,8 +644,9 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne warning. `ai: false` turns the whole lane off. `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE=` replaces the finder's system prompt. The path must be absolute and outside the repository checkout (for - example under `$RUNNER_TEMP`); a file inside the git work tree, or a symlink to - one, is refused, since a PR could change it. + example under `$RUNNER_TEMP`); a file inside the reviewed repository or the + current directory's git work tree, or a symlink to one, is refused, since a PR + could change it, and so is any file when neither resolves to a work tree. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 4c6e3fc381..6c591224c8 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -7,9 +7,8 @@ import { MessageID, SessionID } from "@/session/schema" import { Log } from "@/altimate/util/log" import { redactSecrets } from "@/installation" import { Dispatcher } from "../native" -import { readFile, realpath } from "node:fs/promises" -import path from "node:path" -import { gitRepoRoot } from "./git" +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 { type AiVerifyEvidence, type VerifierStatus, runAiVerify } from "./ai-verify" @@ -749,6 +748,8 @@ export interface AiReviewInput { /** 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 } /** What happened in the advisory lane, reported on the envelope and in the comment. */ @@ -928,20 +929,16 @@ function buildBatchMessage( * 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 not - * resolve (symlinks followed) inside the git work tree of `cwd`: in CI that is the PR checkout, - * so a file there would let the PR rewrite the prompt. + * resolve (symlinks followed) inside the review's repository or the process's work tree (in CI + * the PR checkout), so a PR cannot rewrite the prompt (`trustedFilePath`). */ export async function finderSystemPrompt( env: Record = process.env, - cwd: string = process.cwd(), + reviewDir?: string, ): Promise { const file = env.ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE if (file) { - if (!path.isAbsolute(file)) throw new Error("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE must be an absolute path outside the repository") - const real = await realpath(file) - const tree = await gitRepoRoot(cwd) - if (tree && isInside(real, await realpath(tree))) - throw new Error("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE is inside the git work tree; place it outside the checkout") + 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 @@ -950,11 +947,6 @@ export async function finderSystemPrompt( return ((promptRes.data ?? {}) as Record).prompt as string | undefined } -function isInside(p: string, dir: string): boolean { - const rel = path.relative(dir, p) - return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel)) -} - /** What the lane would send: files, the unsent rest, one message per call, and a record per file. */ export interface AiInputPlan { budget: AiInputBudget @@ -1025,7 +1017,7 @@ export async function runAiReview(input: AiReviewInput): Promise let modelLabel: string | undefined try { // The file named by ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE when set, else the compiled core's prompt. - const corePrompt = await finderSystemPrompt() + const corePrompt = await finderSystemPrompt(process.env, input.reviewDir) if (!corePrompt) return done([], { state: "error", reason: "the core reviewer prompt is unavailable" }) const testGap = aiTestGapEnabled() const system = testGap ? corePrompt + TEST_GAP_INSTRUCTION : corePrompt diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 8e8c2e4392..56776f5d18 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -296,6 +296,8 @@ export interface OrchestrateInput { aiSwitches?: Partial /** Changed files outside the dbt project, for the AI lane only (`pythonFiles` switch). */ aiOutsideFiles?: ChangedFile[] + /** The review's repository root (`--cwd`'s git root); env-named files must be outside it. */ + reviewDir?: string /** Fixed-string search over the dbt project at head, for the verifier. */ grepProject?: AiVerifyEvidence["grepProject"] /** Every file the PR changes (repo-relative), including files outside the dbt project; the verifier may read them. */ @@ -2798,6 +2800,7 @@ export async function runReview(input: OrchestrateInput): Promise { // The project's dbt directories (repo-relative), or one glob inside the project. const dirs = layout diff --git a/packages/opencode/src/altimate/review/trusted-file.ts b/packages/opencode/src/altimate/review/trusted-file.ts new file mode 100644 index 0000000000..5b34979d4b --- /dev/null +++ b/packages/opencode/src/altimate/review/trusted-file.ts @@ -0,0 +1,43 @@ +// altimate_change - new file: operator-supplied files that must not come from the PR checkout +import { existsSync, realpathSync } from "node:fs" +import path from "node:path" + +/** The git work tree containing `dir`: the nearest ancestor (realpath) with a `.git` entry. No git + * call, so `safe.directory` or a missing git cannot hide it. Undefined outside a work tree. */ +export function workTreeOf(dir: string): string | undefined { + let d: string + try { + d = realpathSync(dir) + } catch { + return undefined + } + for (;;) { + if (existsSync(path.join(d, ".git"))) return d + const up = path.dirname(d) + if (up === d) return undefined + d = up + } +} + +/** True when `p` is `dir` or below it (both absolute, resolved). */ +export function isInsideDir(p: string, dir: string): boolean { + const rel = path.relative(dir, p) + return rel === "" || (rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel)) +} + +/** + * The realpath of a file named by the env variable `name`, checked to be outside every work tree + * the review touches: the review's repository (`reviewDirs`) and the process's current directory + * (the PR checkout in CI). The path must be absolute; symlinks are followed before the check, and + * callers read the returned realpath. Fails closed: when none of those directories resolves to a + * work tree, the file is refused, since it cannot be shown to be outside the checkout. + */ +export function trustedFilePath(name: string, file: string, reviewDirs: Array = []): string { + if (!path.isAbsolute(file)) throw new Error(`${name} must be an absolute path outside the repository`) + const real = realpathSync(file) + const trees = [...new Set([...reviewDirs, process.cwd()].flatMap((d) => (d ? [workTreeOf(d)] : [])).filter((t): t is string => !!t))] + if (!trees.length) throw new Error(`${name}: cannot tell whether the file is outside the repository checkout (no git work tree found); refusing it`) + if (trees.some((t) => isInsideDir(real, t))) + throw new Error(`${name} is inside the git work tree; place it outside the checkout`) + return real +} diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts index 213094ae95..4688f2aae7 100644 --- a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -53,4 +53,50 @@ describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { await fs.writeFile(ok, "RUNNER PROMPT") expect(await finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: ok }, repo.path)).toBe("RUNNER PROMPT") }) + + test("a file whose name starts with `..` inside the review's repository is refused", async () => { + await using repo = await tmpdir({ git: true }) + const file = path.join(repo.path, "..p.md") + await fs.writeFile(file, "PR PROMPT") + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, repo.path)).rejects.toThrow("inside the git work tree") + }) + + test("fails closed when neither the review's directory nor the process's resolves to a work tree", async () => { + await using repo = await tmpdir({ git: true }) + await using elsewhere = await tmpdir() + const file = path.join(repo.path, "p.md") + await fs.writeFile(file, "PR PROMPT") + const cwd = process.cwd() + process.chdir(elsewhere.path) + try { + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file })).rejects.toThrow("refusing it") + // The review's repository is checked even when the process runs elsewhere. + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, repo.path)).rejects.toThrow("inside the git work tree") + } finally { + process.chdir(cwd) + } + }) + + test("runReview hands the lane the review's repository", async () => { + const { runReview } = await import("../../src/altimate/review/orchestrate") + const { DEFAULT_REVIEW_CONFIG } = await import("../../src/altimate/review/config") + const { DEFAULT_RUBRIC } = await import("../../src/altimate/review/rubric") + let seen: any + await runReview({ + changedFiles: [{ path: "models/m.sql", status: "modified", diff: "@@ -1 +1 @@\n-select 1\n+select 2\n" }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: { async impact() { return { hasManifest: false } }, async grade() { return { grade: "B" } }, async check() { return { issues: [], ran: true } }, async equivalence() { return { decided: true, equivalent: true } }, async detectPii() { return { columns: [] } } } as any, + forceTier: "full", + reviewDir: "/repo/root", + getContent: async () => "select 2", + generatedAt: "2026-11-27T00:00:00Z", + aiReview: async (input: any) => { + seen = input + return { findings: [], status: { state: "ok" } } + }, + } as any) + expect(seen.reviewDir).toBe("/repo/root") + }) }) From f8220e794ba55538c1581bbe51a8b5e2b3055ddb Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:01:47 +0530 Subject: [PATCH 18/34] fix(review): a lane that did not answer leaves outside Python files pending; warn once per value - `outsideTaken`: a project takes outside-project Python files when it reviewed them (`scope.aiReviewedOutside`), or when they are in its input and its lane answered or it is a dry run. A lane that errored, timed out or had no model recorded its input without reviewing it, so the files are offered to the next project. - The "ignoring =" warning is written once per value per process, not once per project under `--all-projects`. - `envBool` exports the boolean env parsing for other switches to reuse. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-switches.ts | 14 ++++++++++++-- .../opencode/src/altimate/review/multi-project.ts | 14 +++++++++++++- .../test/altimate/review-ai-python-files.test.ts | 11 +++++++++++ .../test/altimate/review-ai-switches.test.ts | 15 +++++++++++++++ 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index 568991ccbf..6695a9bde3 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -44,11 +44,19 @@ const ENV_FALSE = new Set(["0", "false", "off", "no"]) /** The env override for a switch: true for `1`/`true`/`on`/`yes`, false for `0`/`false`/`off`/`no` * (case-insensitive), undefined otherwise. */ export function envSwitch(name: AiSwitchName, env: Env = process.env): boolean | undefined { - const v = env[AI_SWITCH_ENV[name]]?.trim().toLowerCase() + return envBool(env[AI_SWITCH_ENV[name]]) +} + +/** An env value as a boolean: `1`/`true`/`on`/`yes` true, `0`/`false`/`off`/`no` false (trimmed, + * any case), undefined for anything else or unset. */ +export function envBool(raw: string | undefined): boolean | undefined { + const v = raw?.trim().toLowerCase() if (v === undefined) return undefined return ENV_TRUE.has(v) ? true : ENV_FALSE.has(v) ? false : undefined } +const WARNED = new Set() + /** Every switch for one review: env, then the `ai:` config object, then the default. */ export function resolveAiSwitches(cfg: Pick, env: Env = process.env): AiSwitches { const configured = typeof cfg.ai === "object" ? cfg.ai : {} @@ -56,7 +64,9 @@ export function resolveAiSwitches(cfg: Pick, env: Env = proc for (const name of Object.keys(AI_SWITCH_ENV) as AiSwitchName[]) { const fromEnv = envSwitch(name, env) const raw = env[AI_SWITCH_ENV[name]] - if (fromEnv === undefined && raw?.trim()) + // Once per value per process: `--all-projects` resolves the switches for every project. + const warning = `${AI_SWITCH_ENV[name]}=${raw}` + if (fromEnv === undefined && raw?.trim() && !WARNED.has(warning) && !!WARNED.add(warning)) process.stderr.write(`⚠️ ignoring ${AI_SWITCH_ENV[name]}=${raw}: use 1/0 (or true/false, on/off, yes/no)\n`) out[name] = fromEnv ?? configured[name] ?? AI_SWITCH_DEFAULTS[name] } diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 15f01bf53b..b189307928 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -5,6 +5,7 @@ import { collectChangedFiles, gitRepoRoot, listFilesAt, listWorkingTreeFiles, re import { reviewPullRequest, type ReviewPullRequestOptions } from "./run" import { applyMode, signEnvelope, summarize, VerdictEnvelope, type RiskTier, type Verdict } from "./verdict" import type { ChangedFile } from "./diff-filter" +import { aiDryRunEnabled } from "./ai-review" /** * Multi-project review (`altimate review --all-projects`): a PR in a mono-repo @@ -166,12 +167,23 @@ export async function reviewAllProjects(opts: ReviewPullRequestOptions): Promise prRenames, aiOutsidePaths: [...pendingOutside], }) - for (const p of [...(env.ai?.input ?? []).map((r) => r.path), ...(env.scope?.aiReviewedOutside ?? [])]) pendingOutside.delete(p) + for (const p of outsideTaken(env, aiDryRunEnabled())) pendingOutside.delete(p) runs.push({ root, paths: own.map((f) => f.path), env }) } return mergeProjectEnvelopes(runs, roots) } +/** + * The outside-project files a project's AI lane took: those it reviewed (`scope.aiReviewedOutside`) + * and, when the lane answered or in a dry run (which plans without a call), those in its input. + * A lane that errored, timed out or had no model recorded its input without reviewing it, so + * those files stay pending for the next project. + */ +export function outsideTaken(env: Pick, dryRun: boolean): string[] { + const input = env.ai?.state === "ok" || dryRun ? (env.ai?.input ?? []).map((r) => r.path) : [] + return [...input, ...(env.scope?.aiReviewedOutside ?? [])] +} + /** `env` re-signed with `scope.coveredProjects`, so the poster may reconcile earlier reviews of those projects. */ function withCoveredProjects(env: VerdictEnvelope, roots: string[]): VerdictEnvelope { if (!roots.length) return env diff --git a/packages/opencode/test/altimate/review-ai-python-files.test.ts b/packages/opencode/test/altimate/review-ai-python-files.test.ts index a7ea5426f5..a3210b7db1 100644 --- a/packages/opencode/test/altimate/review-ai-python-files.test.ts +++ b/packages/opencode/test/altimate/review-ai-python-files.test.ts @@ -535,3 +535,14 @@ describe("outside-project Python findings are classified pre-existing like in-pr expect(f!.preExisting).toBe(true) }) }) + +describe("--all-projects: a lane that did not answer does not take the outside files", () => { + test("error, timeout or no model: its input stays pending; ok, dry run or reviewed: taken", async () => { + const { outsideTaken } = await import("../../src/altimate/review/multi-project") + const rec = { path: "airflow/load.py", kind: AI_PYTHON_KIND, chars: 1, truncated: false, hunksSent: 1, hunksTotal: 1, card: false } + for (const state of ["error", "timeout", "skipped"] as const) expect(outsideTaken({ ai: { state, input: [rec] } } as any, false)).toEqual([]) + expect(outsideTaken({ ai: { state: "ok", input: [rec] } } as any, false)).toEqual(["airflow/load.py"]) + expect(outsideTaken({ ai: { state: "skipped", input: [rec] } } as any, true)).toEqual(["airflow/load.py"]) + expect(outsideTaken({ ai: { state: "error" }, scope: { aiReviewedOutside: ["airflow/x.py"] } } as any, false)).toEqual(["airflow/x.py"]) + }) +}) diff --git a/packages/opencode/test/altimate/review-ai-switches.test.ts b/packages/opencode/test/altimate/review-ai-switches.test.ts index a737f7c9c6..af5faf0101 100644 --- a/packages/opencode/test/altimate/review-ai-switches.test.ts +++ b/packages/opencode/test/altimate/review-ai-switches.test.ts @@ -81,3 +81,18 @@ describe("`ai:` in .altimate/review.yml", () => { expect(() => parseReviewConfig("ai:\n enable: false")).toThrow(/unrecognized_keys[\s\S]*"enable"/) }) }) + +describe("ignored env values (round 2)", () => { + test("the warning for one value is written once per process, not once per project", () => { + const write0 = process.stderr.write + let err = "" + ;(process.stderr as any).write = (s: string) => ((err += s), true) + try { + resolveAiSwitches({ ai: true }, { ALTIMATE_REVIEW_AI_FOCUSED: "sometimes" }) + resolveAiSwitches({ ai: true }, { ALTIMATE_REVIEW_AI_FOCUSED: "sometimes" }) + } finally { + ;(process.stderr as any).write = write0 + } + expect(err.split("ALTIMATE_REVIEW_AI_FOCUSED=sometimes").length - 1).toBe(1) + }) +}) From 4ceacf021c5ad8d80e9abbc3229e878997d007b4 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:22:45 +0530 Subject: [PATCH 19/34] fix(review): the system-prompt file tests pass a temp repository as the review directory The tests that read a prompt file relied on the test process running inside a git checkout (the fail-closed check needs a work tree). They now pass a temporary git repository as `reviewDir`, so they pass wherever they run. Co-Authored-By: Claude Opus 5.5 --- .../test/altimate/review-ai-system-prompt.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts index 4688f2aae7..26a35dc797 100644 --- a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -17,19 +17,22 @@ describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { test("set: the file's text replaces the core prompt, core not asked", async () => { await using tmp = await tmpdir() + // The review's repository: a temp git repo, so the test does not depend on running inside a checkout. + await using repo = await tmpdir({ git: true }) const file = path.join(tmp.path, "p.txt") await fs.writeFile(file, "FILE PROMPT") spy = spyOn(Dispatcher, "call").mockResolvedValue({ success: true, data: { prompt: "CORE" } } as any) - expect(await finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file })).toBe("FILE PROMPT") + expect(await finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, repo.path)).toBe("FILE PROMPT") expect(spy).not.toHaveBeenCalled() }) test("an empty or missing file is an error, not a fallback", async () => { await using tmp = await tmpdir() + await using repo = await tmpdir({ git: true }) const file = path.join(tmp.path, "empty.txt") await fs.writeFile(file, " \n") - await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file })).rejects.toThrow("is empty") - await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: path.join(tmp.path, "none.txt") })).rejects.toThrow() + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, repo.path)).rejects.toThrow("is empty") + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: path.join(tmp.path, "none.txt") }, repo.path)).rejects.toThrow() }) test("a relative path is refused: it would resolve inside the PR checkout", async () => { From 7aaafff68a2924c14b9f5c9fb8d996cadfc66698 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:42:13 +0530 Subject: [PATCH 20/34] fix(review): trusted files check every enclosing work tree and the named path, not only the realpath `trustedFilePath` had three gaps: - It stopped at the nearest `.git`, so with the review directory and the process both inside a nested checkout, a file elsewhere in the enclosing PR checkout was accepted. `workTreesOf` now returns every enclosing work tree. - It compared only the realpath, so a path inside the checkout that the PR turns into a symlink (or a linked directory) to an outside file was accepted. The realpath of every directory on the named path is now checked too. - A missing file threw a raw ENOENT that did not name the variable. The error now names it and keeps the errno `code`. Tests (review-ai-system-prompt.test.ts): `a path inside the work tree is refused even when it is a symlink to a file outside`, `a nested checkout does not hide the enclosing work tree`, `a missing file is an error naming the variable`. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 5 ++- .../opencode/src/altimate/review/ai-review.ts | 6 +-- .../src/altimate/review/trusted-file.ts | 43 +++++++++++++------ .../altimate/review-ai-system-prompt.test.ts | 38 ++++++++++++++++ 4 files changed, 75 insertions(+), 17 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 098bfa3206..d88f3f384c 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -645,8 +645,9 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE=` replaces the finder's system prompt. The path must be absolute and outside the repository checkout (for example under `$RUNNER_TEMP`); a file inside the reviewed repository or the - current directory's git work tree, or a symlink to one, is refused, since a PR - could change it, and so is any file when neither resolves to a work tree. + current directory's git work tree (or any work tree around them), a symlink to + one, or a path through a symlink inside one is refused, since a PR could change + it, and so is any file when neither resolves to a work tree. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 6c591224c8..1e6d6ed15b 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -928,9 +928,9 @@ function buildBatchMessage( /** * 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 not - * resolve (symlinks followed) inside the review's repository or the process's work tree (in CI - * the PR checkout), so a PR cannot rewrite the prompt (`trustedFilePath`). + * 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, diff --git a/packages/opencode/src/altimate/review/trusted-file.ts b/packages/opencode/src/altimate/review/trusted-file.ts index 5b34979d4b..7627fb499e 100644 --- a/packages/opencode/src/altimate/review/trusted-file.ts +++ b/packages/opencode/src/altimate/review/trusted-file.ts @@ -2,19 +2,21 @@ import { existsSync, realpathSync } from "node:fs" import path from "node:path" -/** The git work tree containing `dir`: the nearest ancestor (realpath) with a `.git` entry. No git - * call, so `safe.directory` or a missing git cannot hide it. Undefined outside a work tree. */ -export function workTreeOf(dir: string): string | undefined { +/** Every git work tree containing `dir`: each ancestor (realpath) with a `.git` entry, nearest + * first, so a nested checkout does not hide the one around it. No git call, so `safe.directory` + * or a missing git cannot hide one. Empty outside any work tree. */ +export function workTreesOf(dir: string): string[] { let d: string try { d = realpathSync(dir) } catch { - return undefined + return [] } + const out: string[] = [] for (;;) { - if (existsSync(path.join(d, ".git"))) return d + if (existsSync(path.join(d, ".git"))) out.push(d) const up = path.dirname(d) - if (up === d) return undefined + if (up === d) return out d = up } } @@ -27,17 +29,34 @@ export function isInsideDir(p: string, dir: string): boolean { /** * The realpath of a file named by the env variable `name`, checked to be outside every work tree - * the review touches: the review's repository (`reviewDirs`) and the process's current directory - * (the PR checkout in CI). The path must be absolute; symlinks are followed before the check, and - * callers read the returned realpath. Fails closed: when none of those directories resolves to a + * the review touches: those enclosing the review's repository (`reviewDirs`) and the process's + * current directory (the PR checkout in CI). The path must be absolute. Both the realpath and the + * named path are checked: a symlink inside a work tree is refused whichever way it points (each + * directory on the named path is resolved, so a linked directory counts where the link is). + * Callers read the returned realpath. Fails closed: when none of those directories resolves to a * work tree, the file is refused, since it cannot be shown to be outside the checkout. */ export function trustedFilePath(name: string, file: string, reviewDirs: Array = []): string { if (!path.isAbsolute(file)) throw new Error(`${name} must be an absolute path outside the repository`) - const real = realpathSync(file) - const trees = [...new Set([...reviewDirs, process.cwd()].flatMap((d) => (d ? [workTreeOf(d)] : [])).filter((t): t is string => !!t))] + let real: string + try { + real = realpathSync(file) + } catch (e) { + // Keeps the errno `code`, so callers can still tell a missing file apart. + const code = (e as NodeJS.ErrnoException)?.code + throw Object.assign(new Error(`${name}: the file does not exist or cannot be resolved (${code ?? "error"})`), { code }) + } + const trees = [...new Set([...reviewDirs, process.cwd()].flatMap((d) => (d ? workTreesOf(d) : [])))] if (!trees.length) throw new Error(`${name}: cannot tell whether the file is outside the repository checkout (no git work tree found); refusing it`) - if (trees.some((t) => isInsideDir(real, t))) + // The realpath, plus the realpath of every directory on the named path. + const spots = [real] + for (let d = path.dirname(path.resolve(file)); ; d = path.dirname(d)) { + try { + spots.push(realpathSync(d)) + } catch {} + if (path.dirname(d) === d) break + } + if (trees.some((t) => spots.some((p) => isInsideDir(p, t)))) throw new Error(`${name} is inside the git work tree; place it outside the checkout`) return real } diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts index 26a35dc797..35ef985601 100644 --- a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -80,6 +80,44 @@ describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { } }) + test("a path inside the work tree is refused even when it is a symlink to a file outside", async () => { + await using repo = await tmpdir({ git: true }) + await using outside = await tmpdir() + const target = path.join(outside.path, "p.md") + await fs.writeFile(target, "RUNNER FILE") + // The PR commits the configured path as a link to a file outside the checkout. + const fileLink = path.join(repo.path, "review-prompt.md") + await fs.symlink(target, fileLink) + // ...or links a directory on the configured path to a directory outside. + const dirLink = path.join(repo.path, "prompts") + await fs.symlink(outside.path, dirLink) + for (const file of [fileLink, path.join(dirLink, "p.md")]) + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, repo.path)).rejects.toThrow("inside the git work tree") + }) + + test("a nested checkout does not hide the enclosing work tree", async () => { + await using repo = await tmpdir({ git: true }) + const nested = path.join(repo.path, "vendor", "dbt") + await fs.mkdir(path.join(nested, ".git"), { recursive: true }) + const file = path.join(repo.path, "review-prompt.md") + await fs.writeFile(file, "PR PROMPT") + const cwd = process.cwd() + process.chdir(nested) + try { + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, nested)).rejects.toThrow("inside the git work tree") + } finally { + process.chdir(cwd) + } + }) + + test("a missing file is an error naming the variable", async () => { + await using tmp = await tmpdir() + await using repo = await tmpdir({ git: true }) + await expect( + finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: path.join(tmp.path, "none.txt") }, repo.path), + ).rejects.toThrow("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE") + }) + test("runReview hands the lane the review's repository", async () => { const { runReview } = await import("../../src/altimate/review/orchestrate") const { DEFAULT_REVIEW_CONFIG } = await import("../../src/altimate/review/config") From 161aecd810dc1548b377d84fc256c4519192b967 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:42:22 +0530 Subject: [PATCH 21/34] test(review): the outside-project handoff test clears an exported `ALTIMATE_REVIEW_AI_DRYRUN` Dry run returns before replay, so with `ALTIMATE_REVIEW_AI_DRYRUN=1` in the environment the lane was skipped and the test failed. The key is now cleared with the other ambient variables; the file's `KEYS` restore it afterwards. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/test/altimate/review-ai-python-files.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/opencode/test/altimate/review-ai-python-files.test.ts b/packages/opencode/test/altimate/review-ai-python-files.test.ts index a3210b7db1..1ef96c3bca 100644 --- a/packages/opencode/test/altimate/review-ai-python-files.test.ts +++ b/packages/opencode/test/altimate/review-ai-python-files.test.ts @@ -475,7 +475,8 @@ describe("--all-projects: the outside-project handoff follows what a project act await write(root, "airflow/load.py", "print(2)\n") git(root, "add", "-A") git(root, "commit", "-q", "-m", "pr") - for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "ALTIMATE_REVIEW_AI_PYTHON_FILES"]) + // Dry run returns before replay, so an exported ALTIMATE_REVIEW_AI_DRYRUN would skip the lane. + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "ALTIMATE_REVIEW_AI_PYTHON_FILES", "ALTIMATE_REVIEW_AI_DRYRUN"]) delete process.env[k] // A replayed lane answers (`state: ok`) without a model call; the verifier is off. const replay = path.join(root, "..", path.basename(root) + "-replay.json") From 0f0657c0f72a1098faffbd8bf1b7e8dbcecbee41 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:42:22 +0530 Subject: [PATCH 22/34] fix(review): make the once-per-value switch warning explicit; document that an empty value is unset `!!WARNED.add(warning)` was always true; the set is now updated in the branch body. No behaviour change. The docs now say an empty switch value counts as unset, which is what `envBool` does. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 4 ++-- packages/opencode/src/altimate/review/ai-switches.ts | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index d88f3f384c..f499402da2 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -640,8 +640,8 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne `.altimate/review.yml` (for example `ai: { verify: false }`) or with its env variable set to `0` (`ALTIMATE_REVIEW_AI_COVERAGE`, `_CONTEXT_CARD`, `_FOCUSED`, `_OTHER_FILES`, `_PYTHON_FILES`, `_VERIFY`); `1` turns one on. `true`/`false`, - `on`/`off` and `yes`/`no` are accepted too; any other value is ignored with a - warning. `ai: false` turns the whole lane off. + `on`/`off` and `yes`/`no` are accepted too; an empty value counts as unset, and + any other value is ignored with a warning. `ai: false` turns the whole lane off. `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE=` replaces the finder's system prompt. The path must be absolute and outside the repository checkout (for example under `$RUNNER_TEMP`); a file inside the reviewed repository or the diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index 6695a9bde3..f12b7f1429 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -66,8 +66,10 @@ export function resolveAiSwitches(cfg: Pick, env: Env = proc const raw = env[AI_SWITCH_ENV[name]] // Once per value per process: `--all-projects` resolves the switches for every project. const warning = `${AI_SWITCH_ENV[name]}=${raw}` - if (fromEnv === undefined && raw?.trim() && !WARNED.has(warning) && !!WARNED.add(warning)) + if (fromEnv === undefined && raw?.trim() && !WARNED.has(warning)) { + WARNED.add(warning) process.stderr.write(`⚠️ ignoring ${AI_SWITCH_ENV[name]}=${raw}: use 1/0 (or true/false, on/off, yes/no)\n`) + } out[name] = fromEnv ?? configured[name] ?? AI_SWITCH_DEFAULTS[name] } return out From 6cc6ea71975cd26ff5aa1b59320d23b00801c3ed Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:05:38 +0530 Subject: [PATCH 23/34] fix(review): `--all-projects` passes on an outside Python file that only a failed call carried `outsideTaken` claimed every path in a lane's `ai.input` once the lane state was `ok`, but a partly failed lane is `ok` with the failed calls' files in `ai.failedFiles`. An outside Python file sent only in a failed call was removed from the pending set and never offered to the next project. Those files now stay pending (outside dry runs, which make no call). Test (review-ai-python-files.test.ts): `a partly failed lane: a file only a failed call carried stays pending`. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/multi-project.ts | 7 +++++-- .../opencode/test/altimate/review-ai-python-files.test.ts | 7 +++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index b189307928..7f7f096424 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -175,12 +175,15 @@ export async function reviewAllProjects(opts: ReviewPullRequestOptions): Promise /** * The outside-project files a project's AI lane took: those it reviewed (`scope.aiReviewedOutside`) - * and, when the lane answered or in a dry run (which plans without a call), those in its input. + * and, when the lane answered or in a dry run (which plans without a call), those in its input + * that no failed call carried (`ai.failedFiles`). * A lane that errored, timed out or had no model recorded its input without reviewing it, so * those files stay pending for the next project. */ export function outsideTaken(env: Pick, dryRun: boolean): string[] { - const input = env.ai?.state === "ok" || dryRun ? (env.ai?.input ?? []).map((r) => r.path) : [] + // A lane that answered in part did not review the files only its failed calls carried. + const failed = new Set(dryRun ? [] : (env.ai?.failedFiles ?? [])) + const input = env.ai?.state === "ok" || dryRun ? (env.ai?.input ?? []).map((r) => r.path).filter((p) => !failed.has(p)) : [] return [...input, ...(env.scope?.aiReviewedOutside ?? [])] } diff --git a/packages/opencode/test/altimate/review-ai-python-files.test.ts b/packages/opencode/test/altimate/review-ai-python-files.test.ts index 1ef96c3bca..217df802aa 100644 --- a/packages/opencode/test/altimate/review-ai-python-files.test.ts +++ b/packages/opencode/test/altimate/review-ai-python-files.test.ts @@ -546,4 +546,11 @@ describe("--all-projects: a lane that did not answer does not take the outside f expect(outsideTaken({ ai: { state: "skipped", input: [rec] } } as any, true)).toEqual(["airflow/load.py"]) expect(outsideTaken({ ai: { state: "error" }, scope: { aiReviewedOutside: ["airflow/x.py"] } } as any, false)).toEqual(["airflow/x.py"]) }) + + test("a partly failed lane: a file only a failed call carried stays pending", async () => { + const { outsideTaken } = await import("../../src/altimate/review/multi-project") + const rec = (p: string) => ({ path: p, kind: AI_PYTHON_KIND, chars: 1, truncated: false, hunksSent: 1, hunksTotal: 1, card: false }) + const env = { ai: { state: "ok", input: [rec("airflow/a.py"), rec("airflow/b.py")], failedFiles: ["airflow/b.py"] } } + expect(outsideTaken(env as any, false)).toEqual(["airflow/a.py"]) + }) }) From 0d01d4576bee8a64c7c805a234088217d381eb0c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:05:38 +0530 Subject: [PATCH 24/34] fix(review): a Python file renamed out of the dbt project is offered to the AI lane at its new path `scopeToProject` keeps a rename that leaves the project as a deletion at the old path, so the surviving file was neither in scope nor in `outOfScopePaths`, and edits made with the move got no AI review. `scopeToProject` now reports the head paths of such renames (`movedOutPaths`), and `reviewPullRequest` offers them to the AI lane with the other outside Python files. Under `--all-projects` the file is assigned to the project it left, so that project offers it, whatever other projects took. Test (review-ai-python-files.test.ts): `a Python file renamed out of the dbt project is offered to the AI lane at its new path (AI dry run)`. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/diff-filter.ts | 5 +++ packages/opencode/src/altimate/review/run.ts | 11 +++-- .../altimate/review-ai-python-files.test.ts | 40 +++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/review/diff-filter.ts b/packages/opencode/src/altimate/review/diff-filter.ts index 4323a98104..5b6a0a736d 100644 --- a/packages/opencode/src/altimate/review/diff-filter.ts +++ b/packages/opencode/src/altimate/review/diff-filter.ts @@ -297,6 +297,8 @@ export interface ScopeResult { outOfScopePaths: string[] /** Paths behind `movedUnchanged`. */ movedUnchangedPaths: string[] + /** Head paths of renames out of the project (scoped in as a deletion at the old path). */ + movedOutPaths: string[] } const isModel = (p: string, layout?: DbtProjectLayout) => { @@ -330,6 +332,7 @@ export function scopeToProject( ): ScopeResult { const outOfScopePaths: string[] = [] const movedUnchangedPaths: string[] = [] + const movedOutPaths: string[] = [] const inScope: ChangedFile[] = [] const basename = (p: string) => norm(p).split("/").pop() const layoutDirs = layout ? resolvedLayoutDirs(layout).map((d) => d.dir) : [] @@ -346,6 +349,7 @@ export function scopeToProject( if (f.oldPath && inside !== oldInside) { const { oldPath, similarity: _similarity, ...rest } = f inScope.push(inside ? { ...rest, status: "added" } : { ...rest, path: oldPath, status: "deleted" }) + if (!inside) movedOutPaths.push(f.path) continue } if ( @@ -368,6 +372,7 @@ export function scopeToProject( movedUnchanged: movedUnchangedPaths.length, outOfScopePaths, movedUnchangedPaths, + movedOutPaths, } } diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 1b40a96c21..64ff0777ac 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -374,14 +374,19 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise else if (!aiLaneEnabled(config)) aiDisabledReason = "disabled in .altimate/review.yml" const aiOn = !aiDisabledReason const aiSwitches = resolveAiSwitches(config) - // `pythonFiles`: .py files outside the dbt project skip every lane but the AI lane. + // `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) => outside.has(f.path) && isAiPythonFile(f) && (!offered || offered.has(f.path))) + ? collected.filter( + (f) => isAiPythonFile(f) && ((outside.has(f.path) && (!offered || offered.has(f.path))) || movedOut.has(f.path)), + ) : [] - const notReviewedOutside = scoped.outOfScope - aiOutsideFiles.length + 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`, diff --git a/packages/opencode/test/altimate/review-ai-python-files.test.ts b/packages/opencode/test/altimate/review-ai-python-files.test.ts index 217df802aa..11149df1ec 100644 --- a/packages/opencode/test/altimate/review-ai-python-files.test.ts +++ b/packages/opencode/test/altimate/review-ai-python-files.test.ts @@ -286,6 +286,46 @@ describe("reviewPullRequest end to end: .py files outside the dbt project reach }, 60_000) }) +describe("a Python file renamed out of the dbt project", () => { + const git = (cwd: string, ...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { + cwd, + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }).toString() + const write = async (root: string, rel: string, body: string) => { + await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) + await fs.writeFile(path.join(root, rel), body) + } + + test("is offered to the AI lane at its new path (AI dry run)", async () => { + const { reviewPullRequest } = await import("../../src/altimate/review/run") + const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-py-moved-"))) + try { + const body = Array.from({ length: 20 }, (_, i) => `print(${i})`).join("\n") + "\n" + await write(root, "dbt/dbt_project.yml", "name: p\n") + await write(root, "dbt/models/m.sql", "select 1 as id\n") + await write(root, "dbt/scripts/load.py", body) + git(root, "init", "-q", "-b", "main") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "base") + git(root, "checkout", "-q", "-b", "pr") + await write(root, "dbt/models/m.sql", "select 1 as id, 2 as x\n") + await fs.rm(path.join(root, "dbt/scripts/load.py")) + // Moved and edited: git still sees a rename. + await write(root, "airflow/load.py", body.replace("print(3)", "print(33)")) + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "pr") + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]) delete process.env[k] + process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" + const env = await reviewPullRequest({ cwd: path.join(root, "dbt"), base: "main", head: "HEAD" }) + expect(env.ai?.input?.map((r) => [r.path, r.kind])).toContainEqual(["airflow/load.py", AI_PYTHON_KIND]) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) +}) + describe("outside-project Python files the AI lane reviewed are not listed as not reviewed", () => { const outsideScope = (paths: string[]) => ({ projectRoot: "dbt", From c40cf424abfad034b116c82d5ead859e2ea3e09c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:05:38 +0530 Subject: [PATCH 25/34] fix(review): no ignored-value warning for AI switches when the lane is off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `run.ts` resolved the switches even with `--no-ai` or `ai: false`, so a bad value such as `ALTIMATE_REVIEW_AI_VERIFY=maybe` printed an "ignoring …" warning for a lane that would not run. `resolveAiSwitches` takes `{ warn: false }`, which `run.ts` passes when the lane is off; the resolved values are unchanged. Test (review-ai-switches.test.ts): `no warning when the AI lane is off (`--no-ai`, `ai: false`)`. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-switches.ts | 9 +++++++-- packages/opencode/src/altimate/review/run.ts | 2 +- .../test/altimate/review-ai-switches.test.ts | 13 +++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index f12b7f1429..2dc67ce843 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -58,7 +58,11 @@ export function envBool(raw: string | undefined): boolean | undefined { const WARNED = new Set() /** Every switch for one review: env, then the `ai:` config object, then the default. */ -export function resolveAiSwitches(cfg: Pick, env: Env = process.env): AiSwitches { +export function resolveAiSwitches( + cfg: Pick, + env: Env = process.env, + opts: { warn?: boolean } = {}, +): AiSwitches { const configured = typeof cfg.ai === "object" ? cfg.ai : {} const out = { ...AI_SWITCH_DEFAULTS } for (const name of Object.keys(AI_SWITCH_ENV) as AiSwitchName[]) { @@ -66,7 +70,8 @@ export function resolveAiSwitches(cfg: Pick, env: Env = proc const raw = env[AI_SWITCH_ENV[name]] // Once per value per process: `--all-projects` resolves the switches for every project. const warning = `${AI_SWITCH_ENV[name]}=${raw}` - if (fromEnv === undefined && raw?.trim() && !WARNED.has(warning)) { + // No warning for a lane that will not run (`warn: false`). + if (opts.warn !== false && fromEnv === undefined && raw?.trim() && !WARNED.has(warning)) { WARNED.add(warning) process.stderr.write(`⚠️ ignoring ${AI_SWITCH_ENV[name]}=${raw}: use 1/0 (or true/false, on/off, yes/no)\n`) } diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 64ff0777ac..cf78399658 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -373,7 +373,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise 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) + const aiSwitches = resolveAiSwitches(config, process.env, { warn: aiOn }) // `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. diff --git a/packages/opencode/test/altimate/review-ai-switches.test.ts b/packages/opencode/test/altimate/review-ai-switches.test.ts index af5faf0101..763b76e207 100644 --- a/packages/opencode/test/altimate/review-ai-switches.test.ts +++ b/packages/opencode/test/altimate/review-ai-switches.test.ts @@ -95,4 +95,17 @@ describe("ignored env values (round 2)", () => { } expect(err.split("ALTIMATE_REVIEW_AI_FOCUSED=sometimes").length - 1).toBe(1) }) + + test("no warning when the AI lane is off (`--no-ai`, `ai: false`)", () => { + const write0 = process.stderr.write + let err = "" + ;(process.stderr as any).write = (s: string) => ((err += s), true) + try { + const off = resolveAiSwitches({ ai: false }, { ALTIMATE_REVIEW_AI_VERIFY: "lane-off-value" }, { warn: false }) + expect(off.verify).toBe(true) + } finally { + ;(process.stderr as any).write = write0 + } + expect(err).toBe("") + }) }) From e9589ed86273ce96068ac4d66b23c5dfb13df797 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:21:42 +0530 Subject: [PATCH 26/34] fix(review): a refused trusted file names the work tree it was found inside `trustedFilePath` now refuses with "is inside the git work tree ", so a work tree the operator did not expect is visible; the file path itself is still not echoed. The docs note that a home directory that is itself a git repository (dotfiles kept in git) is such a work tree, so files anywhere under it are refused. Test (review-ai-system-prompt.test.ts): `a nested checkout does not hide the enclosing work tree` now checks that the error names the enclosing tree. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 4 +++- packages/opencode/src/altimate/review/trusted-file.ts | 6 ++++-- .../opencode/test/altimate/review-ai-system-prompt.test.ts | 6 +++++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index f499402da2..3efcab3dd5 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -647,7 +647,9 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne example under `$RUNNER_TEMP`); a file inside the reviewed repository or the current directory's git work tree (or any work tree around them), a symlink to one, or a path through a symlink inside one is refused, since a PR could change - it, and so is any file when neither resolves to a work tree. + it, and so is any file when neither resolves to a work tree. The error names the + work tree it found; note that a home directory that is itself a git repository + (dotfiles kept in git) is such a work tree, so files anywhere under it are refused. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → diff --git a/packages/opencode/src/altimate/review/trusted-file.ts b/packages/opencode/src/altimate/review/trusted-file.ts index 7627fb499e..2b727b3dd0 100644 --- a/packages/opencode/src/altimate/review/trusted-file.ts +++ b/packages/opencode/src/altimate/review/trusted-file.ts @@ -56,7 +56,9 @@ export function trustedFilePath(name: string, file: string, reviewDirs: Array spots.some((p) => isInsideDir(p, t)))) - throw new Error(`${name} is inside the git work tree; place it outside the checkout`) + // Names the work tree (not the file), so a tree the operator did not expect (a home directory + // kept in git) is visible. + const tree = trees.find((t) => spots.some((p) => isInsideDir(p, t))) + if (tree) throw new Error(`${name} is inside the git work tree ${tree}; place it outside the checkout`) return real } diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts index 35ef985601..64d0476646 100644 --- a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -104,7 +104,11 @@ describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { const cwd = process.cwd() process.chdir(nested) try { - await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, nested)).rejects.toThrow("inside the git work tree") + // The error names the enclosing work tree the file was found in. + const outer = await fs.realpath(repo.path) + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, nested)).rejects.toThrow( + `inside the git work tree ${outer};`, + ) } finally { process.chdir(cwd) } From 76c8f14915d60374d690329d4af84a6dfd09d4d7 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:06:01 +0530 Subject: [PATCH 27/34] fix(review): a file renamed out of the dbt project counts as outside it, so coverage counts agree - `scopeToProject` adds the head path of a rename out of the project to `outOfScopePaths` as well as `movedOutPaths`. The ledger lists it as outside the project until the AI lane reviews it, so a moved-out `.py` the lane skips, fails on, or leaves out by quota is no longer missing from every ledger. - `runReview` lowers `outOfScopeFiles` only by reviewed files that the scope listed as outside the project. A reviewed rename next to an unreviewed `README.md` keeps the count at 1, so the note and `out_of_scope_files` telemetry match the stderr notice. - `--all-projects`: a path assigned to a project but listed by it as outside (a rename out of it) counts as reviewed only when a lane reviewed it. - `outsideTaken` doc: files carried only by failed calls. - Tests: single-project dry run, replayed lane and `pythonFiles` off for a moved-out `.py`; `--all-projects` dry run and replayed lane; a reviewed file the count did not include; `movedOutPaths` pinned in the cross-project rename test. The `git`/`write` helpers in review-ai-python-files.test.ts are hoisted. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/diff-filter.ts | 11 +- .../src/altimate/review/multi-project.ts | 14 +- .../src/altimate/review/orchestrate.ts | 10 +- .../altimate/review-ai-python-files.test.ts | 194 +++++++++++++----- .../test/altimate/review-scope-diff.test.ts | 5 +- 5 files changed, 171 insertions(+), 63 deletions(-) diff --git a/packages/opencode/src/altimate/review/diff-filter.ts b/packages/opencode/src/altimate/review/diff-filter.ts index 5b6a0a736d..f623c4e6a2 100644 --- a/packages/opencode/src/altimate/review/diff-filter.ts +++ b/packages/opencode/src/altimate/review/diff-filter.ts @@ -297,7 +297,8 @@ export interface ScopeResult { outOfScopePaths: string[] /** Paths behind `movedUnchanged`. */ movedUnchangedPaths: string[] - /** Head paths of renames out of the project (scoped in as a deletion at the old path). */ + /** Head paths of renames out of the project: scoped in as a deletion at the old path, and the + * head path is also in `outOfScopePaths` (outside the project, not reviewed by its lanes). */ movedOutPaths: string[] } @@ -323,7 +324,8 @@ const isModel = (p: string, layout?: DbtProjectLayout) => { * findings. A move across roles or layers stays in scope. * - A rename across the project boundary is a deletion from one project and an * addition to the other: only the side inside `root` is kept, rewritten as - * `deleted` (old path) or `added` (new path). + * `deleted` (old path) or `added` (new path). The head path of a rename out + * of the project is outside it, so it is also counted out of scope. */ export function scopeToProject( files: ChangedFile[], @@ -349,7 +351,10 @@ export function scopeToProject( if (f.oldPath && inside !== oldInside) { const { oldPath, similarity: _similarity, ...rest } = f inScope.push(inside ? { ...rest, status: "added" } : { ...rest, path: oldPath, status: "deleted" }) - if (!inside) movedOutPaths.push(f.path) + if (!inside) { + movedOutPaths.push(f.path) + outOfScopePaths.push(f.path) + } continue } if ( diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 7f7f096424..9042d3c25a 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -176,7 +176,7 @@ export async function reviewAllProjects(opts: ReviewPullRequestOptions): Promise /** * The outside-project files a project's AI lane took: those it reviewed (`scope.aiReviewedOutside`) * and, when the lane answered or in a dry run (which plans without a call), those in its input - * that no failed call carried (`ai.failedFiles`). + * except the ones carried only by failed calls (`ai.failedFiles`). * A lane that errored, timed out or had no model recorded its input without reviewing it, so * those files stay pending for the next project. */ @@ -222,8 +222,18 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri // A path some project reviewed is not "outside the dbt project" for the PR. // So is a path outside every project that one project's AI lane reviewed. + // A file renamed out of a project is assigned to it but reviewed only as a deletion at its old + // path; that project lists the new path as outside, so the path counts only when a lane reviewed it. const aiReviewedOutside = [...new Set(envs.flatMap((e) => e.scope?.aiReviewedOutside ?? []))] - const reviewed = new Set([...runs.flatMap((r) => r.paths), ...aiReviewedOutside]) + const listedOutside = (e: VerdictEnvelope) => + new Set((e.scope?.notReviewed ?? []).filter((n) => OUTSIDE_PROJECT_RE.test(n.reason)).map((n) => n.path)) + const reviewed = new Set([ + ...runs.flatMap((r) => { + const outside = listedOutside(r.env) + return r.paths.filter((p) => !outside.has(p)) + }), + ...aiReviewedOutside, + ]) const notReviewed: Array<{ path: string; reason: string }> = [] const seenEntry = new Set() for (const e of envs) { diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 56776f5d18..00c6b57b9b 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -2843,6 +2843,12 @@ export async function runReview(input: OrchestrateInput): Promise !aiReviewedSet.has(n.path)) + // `outOfScopeFiles` drops only the reviewed files it counted (listed as outside the project). + const reviewedCountedOutside = new Set( + (input.scope?.notReviewed ?? []) + .filter((n) => aiReviewedSet.has(n.path) && /^outside the dbt project/.test(n.reason)) + .map((n) => n.path), + ).size const ledger: NotReviewed[] = [ ...inputNotReviewed, ...dropped, @@ -2879,8 +2885,8 @@ export async function runReview(input: OrchestrateInput): Promise + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { + cwd, + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }).toString() +const write = async (root: string, rel: string, body: string) => { + await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) + await fs.writeFile(path.join(root, rel), body) +} + const mod = (p: string, status: ChangedFile["status"] = "modified"): ChangedFile => ({ path: p, status, @@ -221,15 +232,6 @@ describe("ALTIMATE_REVIEW_AI_PYTHON_FILES: planner", () => { }) describe("reviewPullRequest end to end: .py files outside the dbt project reach the lane only under the flag", () => { - const git = (cwd: string, ...args: string[]) => - execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { - cwd, - env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, - }).toString() - const write = async (root: string, rel: string, body: string) => { - await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) - await fs.writeFile(path.join(root, rel), body) - } test("AI dry run: ai.input lists the outside .py file as python_file; unset it is out of scope only", async () => { const { reviewPullRequest } = await import("../../src/altimate/review/run") @@ -287,40 +289,134 @@ describe("reviewPullRequest end to end: .py files outside the dbt project reach }) describe("a Python file renamed out of the dbt project", () => { - const git = (cwd: string, ...args: string[]) => - execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { - cwd, - env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, - }).toString() - const write = async (root: string, rel: string, body: string) => { - await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) - await fs.writeFile(path.join(root, rel), body) + const ENV = ["ALTIMATE_REVIEW_AI_REPLAY", "ALTIMATE_REVIEW_AI_VERIFY"] + const savedEnv = Object.fromEntries(ENV.map((k) => [k, process.env[k]])) + afterEach(() => { + for (const k of ENV) { + if (savedEnv[k] === undefined) delete process.env[k] + else process.env[k] = savedEnv[k] + } + }) + const body = Array.from({ length: 20 }, (_, i) => `print(${i})`).join("\n") + "\n" + /** `scripts/load.py` moved (and edited) to `airflow/load.py`, plus the given edits. */ + async function movedRepo(name: string, prefix: string, files: Record, edits: Record) { + const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), name))) + for (const [rel, text] of Object.entries(files)) await write(root, rel, text) + await write(root, `${prefix}scripts/load.py`, body) + git(root, "init", "-q", "-b", "main") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "base") + git(root, "checkout", "-q", "-b", "pr") + for (const [rel, text] of Object.entries(edits)) await write(root, rel, text) + await fs.rm(path.join(root, `${prefix}scripts/load.py`)) + // Moved and edited: git still sees a rename. + await write(root, "airflow/load.py", body.replace("print(3)", "print(33)")) + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "pr") + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "ALTIMATE_REVIEW_AI_DRYRUN"]) + delete process.env[k] + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" + return root + } + /** A replayed lane answers (`state: ok`) without a model call; the verifier is off. */ + async function replayOk(root: string) { + const replay = path.join(root, "..", path.basename(root) + "-replay.json") + await fs.writeFile(replay, JSON.stringify({ findings: [], ai: { state: "ok", calls: 1 } })) + process.env.ALTIMATE_REVIEW_AI_REPLAY = replay + process.env.ALTIMATE_REVIEW_AI_VERIFY = "0" + return replay } + const outsideListed = (env: { scope?: { notReviewed: Array<{ path: string; reason: string }> } }) => + (env.scope?.notReviewed ?? []).filter((n) => n.reason.startsWith("outside the dbt project")).map((n) => n.path) + const single = (name: string) => + movedRepo(name, "dbt/", { "dbt/dbt_project.yml": "name: p\n", "dbt/models/m.sql": "select 1 as id\n", "README.md": "docs\n" }, { + "dbt/models/m.sql": "select 1 as id, 2 as x\n", + "README.md": "more docs\n", + }) - test("is offered to the AI lane at its new path (AI dry run)", async () => { + test("is offered to the AI lane at its new path (AI dry run), and stays listed as not reviewed", async () => { const { reviewPullRequest } = await import("../../src/altimate/review/run") - const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-py-moved-"))) + const root = await single("review-py-moved-") try { - const body = Array.from({ length: 20 }, (_, i) => `print(${i})`).join("\n") + "\n" - await write(root, "dbt/dbt_project.yml", "name: p\n") - await write(root, "dbt/models/m.sql", "select 1 as id\n") - await write(root, "dbt/scripts/load.py", body) - git(root, "init", "-q", "-b", "main") - git(root, "add", "-A") - git(root, "commit", "-q", "-m", "base") - git(root, "checkout", "-q", "-b", "pr") - await write(root, "dbt/models/m.sql", "select 1 as id, 2 as x\n") - await fs.rm(path.join(root, "dbt/scripts/load.py")) - // Moved and edited: git still sees a rename. - await write(root, "airflow/load.py", body.replace("print(3)", "print(33)")) - git(root, "add", "-A") - git(root, "commit", "-q", "-m", "pr") - for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]) delete process.env[k] process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" - process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" const env = await reviewPullRequest({ cwd: path.join(root, "dbt"), base: "main", head: "HEAD" }) expect(env.ai?.input?.map((r) => [r.path, r.kind])).toContainEqual(["airflow/load.py", AI_PYTHON_KIND]) + // The dry run made no model call. + expect(outsideListed(env)).toEqual(["README.md", "airflow/load.py"]) + expect(env.scope?.outOfScopeFiles).toBe(2) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) + + test("reviewed by the lane next to an unreviewed outside file: the outside count stays 1", async () => { + const { reviewPullRequest } = await import("../../src/altimate/review/run") + const root = await single("review-py-moved-ok-") + const replay = await replayOk(root) + try { + const env = await reviewPullRequest({ cwd: path.join(root, "dbt"), base: "main", head: "HEAD" }) + expect(env.scope?.aiReviewedOutside).toEqual(["airflow/load.py"]) + expect(outsideListed(env)).toEqual(["README.md"]) + expect(env.scope?.outOfScopeFiles).toBe(1) } finally { + await fs.rm(replay, { force: true }) + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) + + test("the lane does not take it (`pythonFiles` off): listed as outside the project, not reviewed", async () => { + const { reviewPullRequest } = await import("../../src/altimate/review/run") + const root = await single("review-py-moved-off-") + const replay = await replayOk(root) + try { + process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "0" + const env = await reviewPullRequest({ cwd: path.join(root, "dbt"), base: "main", head: "HEAD" }) + expect(env.scope?.aiReviewedOutside).toBeUndefined() + expect(env.scope?.notReviewed.find((n) => n.path === "airflow/load.py")?.reason).toBe("outside the dbt project (dbt)") + expect(env.scope?.outOfScopeFiles).toBe(2) + } finally { + await fs.rm(replay, { force: true }) + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) + + const twoProjects = (name: string) => + movedRepo( + name, + "a/", + { + "a/dbt_project.yml": "name: a\n", + "a/models/m.sql": "select 1 as id\n", + "b/dbt_project.yml": "name: b\n", + "b/models/n.sql": "select 1 as id\n", + }, + { "a/models/m.sql": "select 1 as id, 2 as x\n", "b/models/n.sql": "select 1 as id, 3 as y\n" }, + ) + + test("--all-projects (AI dry run): routed to the project it left, offered once, listed as not reviewed", async () => { + const root = await twoProjects("review-py-mp-moved-") + try { + process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" + const env = await reviewAllProjects({ cwd: root, base: "main", head: "HEAD" }) + expect(env.ai?.input?.map((r) => r.path).sort()).toEqual(["a/models/m.sql", "airflow/load.py", "b/models/n.sql"]) + expect(env.scope?.projects?.find((p) => p.root === "a")?.files).toBe(2) + expect(env.scope?.notReviewed.map((n) => n.path)).toContain("airflow/load.py") + expect(env.scope?.outOfScopeFiles).toBe(1) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) + + test("--all-projects: reviewed by the lane of the project it left, not listed", async () => { + const root = await twoProjects("review-py-mp-moved-ok-") + const replay = await replayOk(root) + try { + const env = await reviewAllProjects({ cwd: root, base: "main", head: "HEAD" }) + expect(env.scope?.aiReviewedOutside).toEqual(["airflow/load.py"]) + expect(env.scope?.notReviewed.map((n) => n.path)).not.toContain("airflow/load.py") + expect(env.scope?.outOfScopeFiles).toBeUndefined() + } finally { + await fs.rm(replay, { force: true }) await fs.rm(root, { recursive: true, force: true }) } }, 60_000) @@ -332,7 +428,7 @@ describe("outside-project Python files the AI lane reviewed are not listed as no outOfScopeFiles: paths.length, notReviewed: paths.map((p) => ({ path: p, reason: "outside the dbt project (dbt)" })), }) - async function run(state: "ok" | "error" | "partial") { + async function run(state: "ok" | "error" | "partial", listed = ["airflow/load.py", "README.md"]) { process.env.ALTIMATE_REVIEW_AI_PYTHON_FILES = "1" return runReview({ changedFiles: [mod("dbt/models/m.sql")], @@ -343,7 +439,7 @@ describe("outside-project Python files the AI lane reviewed are not listed as no forceTier: "full", layout: { root: "dbt", dirs: DEFAULT_DBT_DIRS }, aiOutsideFiles: [mod("airflow/load.py")], - scope: outsideScope(["airflow/load.py", "README.md"]), + scope: outsideScope(listed), getContent: async (f, side) => (side === "old" ? undefined : `x`), generatedAt: "2026-11-25T00:00:00Z", aiReview: async () => ({ @@ -365,6 +461,12 @@ describe("outside-project Python files the AI lane reviewed are not listed as no expect(env.scope?.outOfScopeFiles).toBe(1) }) + test("a reviewed file the outside count did not include does not lower it", async () => { + const env = await run("ok", ["README.md"]) + expect(env.scope?.aiReviewedOutside).toEqual(["airflow/load.py"]) + expect(env.scope?.outOfScopeFiles).toBe(1) + }) + test("lane failed: still listed as outside the project, not reviewed", async () => { const env = await run("error") expect(env.scope?.notReviewed.map((n) => n.path)).toEqual(["airflow/load.py", "README.md"]) @@ -392,15 +494,6 @@ describe("outside-project Python files the AI lane reviewed are not listed as no }) describe("--all-projects: an outside-project Python file goes to one project's AI lane", () => { - const git = (cwd: string, ...args: string[]) => - execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { - cwd, - env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, - }).toString() - const write = async (root: string, rel: string, body: string) => { - await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) - await fs.writeFile(path.join(root, rel), body) - } test("AI dry run over two projects: the outside .py file is in one project's input", async () => { const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-py-mp-"))) @@ -479,15 +572,6 @@ describe("ai.unsent lists only files the deterministic lanes checked", () => { }) describe("--all-projects: the outside-project handoff follows what a project actually took", () => { - const git = (cwd: string, ...args: string[]) => - execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { - cwd, - env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, - }).toString() - const write = async (root: string, rel: string, body: string) => { - await fs.mkdir(path.dirname(path.join(root, rel)), { recursive: true }) - await fs.writeFile(path.join(root, rel), body) - } const ENV = ["ALTIMATE_REVIEW_AI_REPLAY", "ALTIMATE_REVIEW_AI_VERIFY"] const savedEnv = Object.fromEntries(ENV.map((k) => [k, process.env[k]])) afterEach(() => { diff --git a/packages/opencode/test/altimate/review-scope-diff.test.ts b/packages/opencode/test/altimate/review-scope-diff.test.ts index ba0c832856..fa527cab13 100644 --- a/packages/opencode/test/altimate/review-scope-diff.test.ts +++ b/packages/opencode/test/altimate/review-scope-diff.test.ts @@ -306,7 +306,10 @@ describe("scopeToProject: the dbt project being reviewed, nothing else", () => { { path: "projects/a/models/out.sql", status: "deleted" }, { path: "projects/a/models/in.sql", status: "added" }, ]) - expect(r.outOfScope).toBe(0) + // The moved-out file's new path is outside this project and not reviewed here. + expect(r.movedOutPaths).toEqual(["projects/b/models/out.sql"]) + expect(r.outOfScopePaths).toEqual(["projects/b/models/out.sql"]) + expect(r.outOfScope).toBe(1) }) }) From 0df0c649f961c2ea06ddb32bd7aa1792899cad1c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:06:02 +0530 Subject: [PATCH 28/34] fix(review): a trusted file is refused when its symlink chain passes through the work tree `trustedFilePath` checked the realpath and the realpath of each directory on the named path. An outside alias that resolves through a link inside the work tree and back out kept all of those outside, so a PR could still choose which outside file was loaded. `resolutionChain` now follows the path one component at a time, through every link target, and each visited path is checked. A chain that cannot be followed (a loop, a missing component) is refused. Tests: `an outside alias that resolves through a link in the work tree and back out is refused` (absolute and relative links), `a symlink loop is refused`. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/trusted-file.ts | 62 +++++++++++++++---- .../altimate/review-ai-system-prompt.test.ts | 31 ++++++++++ 2 files changed, 81 insertions(+), 12 deletions(-) diff --git a/packages/opencode/src/altimate/review/trusted-file.ts b/packages/opencode/src/altimate/review/trusted-file.ts index 2b727b3dd0..c1412b3ffb 100644 --- a/packages/opencode/src/altimate/review/trusted-file.ts +++ b/packages/opencode/src/altimate/review/trusted-file.ts @@ -1,5 +1,5 @@ // altimate_change - new file: operator-supplied files that must not come from the PR checkout -import { existsSync, realpathSync } from "node:fs" +import { existsSync, lstatSync, readlinkSync, realpathSync } from "node:fs" import path from "node:path" /** Every git work tree containing `dir`: each ancestor (realpath) with a `.git` entry, nearest @@ -30,11 +30,12 @@ export function isInsideDir(p: string, dir: string): boolean { /** * The realpath of a file named by the env variable `name`, checked to be outside every work tree * the review touches: those enclosing the review's repository (`reviewDirs`) and the process's - * current directory (the PR checkout in CI). The path must be absolute. Both the realpath and the - * named path are checked: a symlink inside a work tree is refused whichever way it points (each - * directory on the named path is resolved, so a linked directory counts where the link is). + * current directory (the PR checkout in CI). The path must be absolute. Every path the resolution + * passes through is checked, not only the realpath: a symlink inside a work tree is refused + * whichever way it points, also when an outside link leads to it (see `resolutionChain`). * Callers read the returned realpath. Fails closed: when none of those directories resolves to a - * work tree, the file is refused, since it cannot be shown to be outside the checkout. + * work tree, or the resolution cannot be followed, the file is refused, since it cannot be shown + * to be outside the checkout. */ export function trustedFilePath(name: string, file: string, reviewDirs: Array = []): string { if (!path.isAbsolute(file)) throw new Error(`${name} must be an absolute path outside the repository`) @@ -48,13 +49,12 @@ export function trustedFilePath(name: string, file: string, reviewDirs: Array (d ? workTreesOf(d) : [])))] if (!trees.length) throw new Error(`${name}: cannot tell whether the file is outside the repository checkout (no git work tree found); refusing it`) - // The realpath, plus the realpath of every directory on the named path. - const spots = [real] - for (let d = path.dirname(path.resolve(file)); ; d = path.dirname(d)) { - try { - spots.push(realpathSync(d)) - } catch {} - if (path.dirname(d) === d) break + let spots: string[] + try { + spots = [real, ...resolutionChain(file)] + } catch (e) { + const code = (e as NodeJS.ErrnoException)?.code + throw new Error(`${name}: cannot follow the file's symlinks (${code ?? "error"}); refusing it`) } // Names the work tree (not the file), so a tree the operator did not expect (a home directory // kept in git) is visible. @@ -62,3 +62,41 @@ export function trustedFilePath(name: string, file: string, reviewDirs: Array MAX_SYMLINK_HOPS) throw Object.assign(new Error("too many symlinks"), { code: "ELOOP" }) + const target = readlinkSync(next) + if (path.isAbsolute(target)) cur = path.parse(target).root + pending.unshift(...target.slice(path.isAbsolute(target) ? path.parse(target).root.length : 0).split(path.sep).filter(Boolean)) + } + visited.push(cur) + return visited +} diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts index 64d0476646..0d4d968497 100644 --- a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -95,6 +95,37 @@ describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, repo.path)).rejects.toThrow("inside the git work tree") }) + test("an outside alias that resolves through a link in the work tree and back out is refused", async () => { + await using repo = await tmpdir({ git: true }) + await using outside = await tmpdir() + const targetDir = path.join(outside.path, "target") + await fs.mkdir(targetDir) + await fs.writeFile(path.join(targetDir, "p.md"), "RUNNER FILE") + // The PR controls `repo/hop`, which points back outside; the configured alias points at it. + await fs.symlink(targetDir, path.join(repo.path, "hop")) + const alias = path.join(outside.path, "alias") + await fs.symlink(path.join(repo.path, "hop"), alias) + // A relative link through the work tree is followed the same way. + const relAlias = path.join(outside.path, "rel-alias") + await fs.symlink(path.relative(outside.path, path.join(repo.path, "hop")), relAlias) + for (const file of [path.join(alias, "p.md"), path.join(relAlias, "p.md")]) + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, repo.path)).rejects.toThrow("inside the git work tree") + // The same file named directly is read. + expect(await finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: path.join(targetDir, "p.md") }, repo.path)).toBe("RUNNER FILE") + }) + + test("a symlink loop is refused", async () => { + await using repo = await tmpdir({ git: true }) + await using outside = await tmpdir() + const a = path.join(outside.path, "a") + const b = path.join(outside.path, "b") + await fs.symlink(b, a) + await fs.symlink(a, b) + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: a }, repo.path)).rejects.toThrow( + "ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", + ) + }) + test("a nested checkout does not hide the enclosing work tree", async () => { await using repo = await tmpdir({ git: true }) const nested = path.join(repo.path, "vendor", "dbt") From a4284af98534daa3fbe3fd5f047a0314f51ac619 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:06:02 +0530 Subject: [PATCH 29/34] test(review): `--no-ai` suppresses the ignored-value warning end to end; docs match - review-ai-switches.test.ts: the unit test is renamed to what it checks (`warn: false`), and a `reviewPullRequest` test shows `--no-ai` writes no warning while the same value with the lane on does. - Docs: the ignored-value warning is printed once per value and only when the AI lane runs; the trusted-file paragraph covers a symlink chain through the work tree. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 12 +++-- .../test/altimate/review-ai-switches.test.ts | 46 ++++++++++++++++++- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 3efcab3dd5..a220de29af 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -641,15 +641,17 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne variable set to `0` (`ALTIMATE_REVIEW_AI_COVERAGE`, `_CONTEXT_CARD`, `_FOCUSED`, `_OTHER_FILES`, `_PYTHON_FILES`, `_VERIFY`); `1` turns one on. `true`/`false`, `on`/`off` and `yes`/`no` are accepted too; an empty value counts as unset, and - any other value is ignored with a warning. `ai: false` turns the whole lane off. + any other value is ignored (with a warning, printed once per value and only when + the AI lane runs). `ai: false` turns the whole lane off. `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE=` replaces the finder's system prompt. The path must be absolute and outside the repository checkout (for example under `$RUNNER_TEMP`); a file inside the reviewed repository or the current directory's git work tree (or any work tree around them), a symlink to - one, or a path through a symlink inside one is refused, since a PR could change - it, and so is any file when neither resolves to a work tree. The error names the - work tree it found; note that a home directory that is itself a git repository - (dotfiles kept in git) is such a work tree, so files anywhere under it are refused. + one, or a path whose resolution passes through a symlink inside one (also from + an outside alias) is refused, since a PR could change it, and so is any file + when neither resolves to a work tree. The error names the work tree it found; + note that a home directory that is itself a git repository (dotfiles kept in + git) is such a work tree, so files anywhere under it are refused. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings → risk pattern → `REQUEST_CHANGES`; only suggestions → `COMMENT`; nothing → diff --git a/packages/opencode/test/altimate/review-ai-switches.test.ts b/packages/opencode/test/altimate/review-ai-switches.test.ts index 763b76e207..03b19d1b27 100644 --- a/packages/opencode/test/altimate/review-ai-switches.test.ts +++ b/packages/opencode/test/altimate/review-ai-switches.test.ts @@ -1,4 +1,8 @@ import { describe, test, expect } from "bun:test" +import path from "node:path" +import os from "node:os" +import { promises as fs } from "node:fs" +import { execFileSync } from "node:child_process" import { AI_SWITCH_DEFAULTS, AI_SWITCH_ENV, envSwitch, resolveAiSwitches, switchOn } from "../../src/altimate/review/ai-switches" import { DEFAULT_REVIEW_CONFIG, aiLaneEnabled, parseReviewConfig, policyHash } from "../../src/altimate/review/config" import { aiInputBudget } from "../../src/altimate/review/ai-review" @@ -96,7 +100,7 @@ describe("ignored env values (round 2)", () => { expect(err.split("ALTIMATE_REVIEW_AI_FOCUSED=sometimes").length - 1).toBe(1) }) - test("no warning when the AI lane is off (`--no-ai`, `ai: false`)", () => { + test("no warning when the caller passes `warn: false`", () => { const write0 = process.stderr.write let err = "" ;(process.stderr as any).write = (s: string) => ((err += s), true) @@ -108,4 +112,44 @@ describe("ignored env values (round 2)", () => { } expect(err).toBe("") }) + + test("reviewPullRequest: `--no-ai` writes no warning; the same value with the lane on does", async () => { + const { reviewPullRequest } = await import("../../src/altimate/review/run") + const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-switch-warn-"))) + const git = (...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { + cwd: root, + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }) + const KEYS = ["ALTIMATE_REVIEW_AI_VERIFY", "ALTIMATE_REVIEW_AI_DRYRUN", "GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"] + const saved = Object.fromEntries(KEYS.map((k) => [k, process.env[k]])) + const write0 = process.stderr.write + let err = "" + try { + await fs.mkdir(path.join(root, "models"), { recursive: true }) + await fs.writeFile(path.join(root, "dbt_project.yml"), "name: p\n") + await fs.writeFile(path.join(root, "models", "m.sql"), "select 1 as id\n") + git("init", "-q", "-b", "main") + git("add", "-A") + git("commit", "-q", "-m", "base") + await fs.writeFile(path.join(root, "models", "m.sql"), "select 1 as id, 2 as x\n") + git("commit", "-q", "-am", "pr") + for (const k of KEYS) delete process.env[k] + process.env.ALTIMATE_REVIEW_AI_VERIFY = "lane-off-e2e" + // The dry run plans the lane without a model call. + process.env.ALTIMATE_REVIEW_AI_DRYRUN = "1" + ;(process.stderr as any).write = (s: string) => ((err += s), true) + await reviewPullRequest({ cwd: root, base: "HEAD~1", head: "HEAD", noAi: true }) + expect(err).not.toContain("ALTIMATE_REVIEW_AI_VERIFY=lane-off-e2e") + await reviewPullRequest({ cwd: root, base: "HEAD~1", head: "HEAD" }) + expect(err).toContain("ignoring ALTIMATE_REVIEW_AI_VERIFY=lane-off-e2e") + } finally { + ;(process.stderr as any).write = write0 + for (const k of KEYS) { + if (saved[k] === undefined) delete process.env[k] + else process.env[k] = saved[k] + } + await fs.rm(root, { recursive: true, force: true }) + } + }, 60_000) }) From f2171af2638478ed61dcdf03e8d2e9c7a3388fca Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:20:46 +0530 Subject: [PATCH 30/34] fix(review): the trusted-file symlink walk is canonical, so a case-variant path cannot slip past the work tree MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a case-insensitive file system `resolutionChain` recorded paths in the typed case while work-tree roots are realpaths, so `/…/REPO/link/f` or an outside alias whose target spells the work tree in another case was accepted. The walk now resolves each directory to its realpath before taking the next component, and `trustedFilePath` refuses a file when the walk does not end at its realpath. Test: `a work tree spelled in another case (case-insensitive file systems) is still found` (in-tree link named through the other spelling, and an outside alias whose target uses it; skipped on case-sensitive file systems). Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/trusted-file.ts | 10 ++++++++-- .../altimate/review-ai-system-prompt.test.ts | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/trusted-file.ts b/packages/opencode/src/altimate/review/trusted-file.ts index c1412b3ffb..23eb1d527b 100644 --- a/packages/opencode/src/altimate/review/trusted-file.ts +++ b/packages/opencode/src/altimate/review/trusted-file.ts @@ -56,6 +56,8 @@ export function trustedFilePath(name: string, file: string, reviewDirs: Array spots.some((p) => isInsideDir(p, t))) @@ -68,7 +70,8 @@ const MAX_SYMLINK_HOPS = 40 /** * Every path visited while resolving the absolute path `file` one component at a time: each - * component's location, and through every symlink, each component of its target. A link inside a + * component's location under the canonical (realpath) parent, the canonical path of each + * directory, and through every symlink, each component of its target. A link inside a * work tree is on this list even when an outside alias leads to it and its target leads back out. * Throws when a component is missing or the links loop. */ @@ -86,10 +89,13 @@ export function resolutionChain(file: string): string[] { cur = path.dirname(cur) continue } + // `cur` is canonical (realpath), so a component typed in another case on a case-insensitive + // file system still lands under the work tree's canonical root. const next = path.join(cur, part) visited.push(next) if (!lstatSync(next).isSymbolicLink()) { - cur = next + cur = realpathSync(next) + visited.push(cur) continue } if (++hops > MAX_SYMLINK_HOPS) throw Object.assign(new Error("too many symlinks"), { code: "ELOOP" }) diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts index 0d4d968497..d4862572fe 100644 --- a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -114,6 +114,26 @@ describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { expect(await finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: path.join(targetDir, "p.md") }, repo.path)).toBe("RUNNER FILE") }) + test("a work tree spelled in another case (case-insensitive file systems) is still found", async () => { + await using repo = await tmpdir({ git: true }) + await using outside = await tmpdir() + const variant = path.join(path.dirname(repo.path), path.basename(repo.path).toUpperCase()) + // Only a case-insensitive file system (macOS, Windows) resolves the other spelling. + const insensitive = variant !== repo.path && (await fs.stat(variant).then(() => true, () => false)) + if (!insensitive) return + const targetDir = path.join(outside.path, "d2") + await fs.mkdir(targetDir) + await fs.writeFile(path.join(targetDir, "f"), "RUNNER FILE") + await fs.symlink(targetDir, path.join(repo.path, "link")) + // The in-tree link named through the other spelling of the work tree... + const direct = path.join(variant, "link", "f") + // ...and an outside alias whose target is written in the other spelling. + const alias = path.join(outside.path, "aliasCase") + await fs.symlink(path.join(variant, "link"), alias) + for (const file of [direct, path.join(alias, "f")]) + await expect(finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: file }, repo.path)).rejects.toThrow("inside the git work tree") + }) + test("a symlink loop is refused", async () => { await using repo = await tmpdir({ git: true }) await using outside = await tmpdir() From 86f22a2485f24d48f9adcd8cc2a68f4b67945ce2 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 20:11:18 +0530 Subject: [PATCH 31/34] refactor(review): one `isOutsideProjectReason` predicate for the outside-project reason The "outside the dbt project" reason prefix was matched by the same regex in `orchestrate.ts`, `format.ts` and three times in `multi-project.ts`. All now call `isOutsideProjectReason` in `verdict.ts` (beside `FAILED_FILE_REASON`, which every caller already imports, so no import cycle through `run.ts`). It accepts exactly what the regex accepted. Test: `isOutsideProjectReason accepts exactly what the regex matches it replaced accepted` (run.ts reasons, the merge's `outside the dbt projects reviewed`, and reasons that must not match). Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 4 ++-- .../src/altimate/review/multi-project.ts | 9 ++++---- .../src/altimate/review/orchestrate.ts | 3 ++- .../opencode/src/altimate/review/verdict.ts | 6 +++++ .../test/altimate/review-all-projects.test.ts | 23 ++++++++++++++++++- 5 files changed, 36 insertions(+), 9 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index a9df891891..ca961d7e34 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -1,5 +1,5 @@ import { type Finding, type Severity, type Confidence, SEVERITY_ORDER, blankNames, groupKeyTitle, verifierDemoted } from "./finding" -import { type VerdictEnvelope, type PostingPolicy, DEFAULT_POSTING_POLICY } from "./verdict" +import { type VerdictEnvelope, type PostingPolicy, DEFAULT_POSTING_POLICY, isOutsideProjectReason } from "./verdict" /** * Render a verdict envelope for humans (PR summary markdown) and for the VCS @@ -279,7 +279,7 @@ export function coverageNotes(env: VerdictEnvelope): string[] { const ledger = notReviewedLedger(env) const listed = new Set(ledger.map((e) => e.path)) const scopePaths = env.scope?.notReviewed ?? [] - if (env.scope?.outOfScopeFiles && !scopePaths.some((e) => /^outside the dbt project/.test(e.reason) && listed.has(e.path))) + if (env.scope?.outOfScopeFiles && !scopePaths.some((e) => isOutsideProjectReason(e.reason) && listed.has(e.path))) notes.push(`${env.scope.outOfScopeFiles} changed file(s) outside the dbt project were not reviewed.`) if (env.scope?.movedUnchangedFiles && !scopePaths.some((e) => /^moved without edits/.test(e.reason) && listed.has(e.path))) notes.push( diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 9042d3c25a..7aea7037db 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -3,7 +3,7 @@ import { realpath } from "node:fs/promises" import { createHash } from "node:crypto" import { collectChangedFiles, gitRepoRoot, listFilesAt, listWorkingTreeFiles, resolveReviewBase } from "./git" import { reviewPullRequest, type ReviewPullRequestOptions } from "./run" -import { applyMode, signEnvelope, summarize, VerdictEnvelope, type RiskTier, type Verdict } from "./verdict" +import { applyMode, isOutsideProjectReason, signEnvelope, summarize, VerdictEnvelope, type RiskTier, type Verdict } from "./verdict" import type { ChangedFile } from "./diff-filter" import { aiDryRunEnabled } from "./ai-review" @@ -29,7 +29,6 @@ const AI_STATE_RANK: Record = { skipped: 0, ok: 1, ti const VERIFIER_STATE_RANK: Record = { skipped: 0, ok: 1, budget: 2, timeout: 3, error: 4 } /** Most discarded findings kept on the merged verifier record (as on one project's). */ const VERIFIER_DROPPED_MAX = 20 -const OUTSIDE_PROJECT_RE = /^outside the dbt project/ /** Reason for a file outside every reviewed project (the projects are listed in `scope.projects`). */ const OUTSIDE_ALL = "outside the dbt projects reviewed" @@ -226,7 +225,7 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri // path; that project lists the new path as outside, so the path counts only when a lane reviewed it. const aiReviewedOutside = [...new Set(envs.flatMap((e) => e.scope?.aiReviewedOutside ?? []))] const listedOutside = (e: VerdictEnvelope) => - new Set((e.scope?.notReviewed ?? []).filter((n) => OUTSIDE_PROJECT_RE.test(n.reason)).map((n) => n.path)) + new Set((e.scope?.notReviewed ?? []).filter((n) => isOutsideProjectReason(n.reason)).map((n) => n.path)) const reviewed = new Set([ ...runs.flatMap((r) => { const outside = listedOutside(r.env) @@ -238,7 +237,7 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri const seenEntry = new Set() for (const e of envs) { for (const n of e.scope?.notReviewed ?? []) { - const outside = OUTSIDE_PROJECT_RE.test(n.reason) + const outside = isOutsideProjectReason(n.reason) if (outside && reviewed.has(n.path)) continue const key = outside ? `outside\0${n.path}` : `${n.path}\0${n.reason}` if (seenEntry.has(key)) continue @@ -246,7 +245,7 @@ export function mergeProjectEnvelopes(runs: ProjectRun[], coveredProjects?: stri notReviewed.push(outside ? { path: n.path, reason: OUTSIDE_ALL } : n) } } - const outsideCount = notReviewed.filter((n) => OUTSIDE_PROJECT_RE.test(n.reason)).length + const outsideCount = notReviewed.filter((n) => isOutsideProjectReason(n.reason)).length const movedCount = envs.reduce((s, e) => s + (e.scope?.movedUnchangedFiles ?? 0), 0) const unverified = envs.flatMap((e) => e.scope?.unverified ?? []) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 00c6b57b9b..3ac9754ce8 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -35,6 +35,7 @@ import { FAILED_FILE_REASON, buildEnvelope, errorReason, + isOutsideProjectReason, signEnvelope, } from "./verdict" import { detectMacroPatterns, detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" @@ -2846,7 +2847,7 @@ export async function runReview(input: OrchestrateInput): Promise aiReviewedSet.has(n.path) && /^outside the dbt project/.test(n.reason)) + .filter((n) => aiReviewedSet.has(n.path) && isOutsideProjectReason(n.reason)) .map((n) => n.path), ).size const ledger: NotReviewed[] = [ diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index e268bca07b..0b4033e973 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -439,6 +439,12 @@ export function errorReason(err: unknown, max = 200): string { /** Prefix of the `scope.unverified` reason for a file whose review threw. */ export const FAILED_FILE_REASON = "review failed for this file" +/** Whether a `scope.notReviewed` reason marks a file outside the dbt project: one project's + * `outside the dbt project ()` (run.ts) or the merge's `outside the dbt projects reviewed`. */ +export function isOutsideProjectReason(reason: string): boolean { + return /^outside the dbt project/.test(reason) +} + /** True when some check did not run: an engine call failed, a file's review * threw, a check abstained on a model, or a model had no compiled head SQL (its * engine and PII checks were skipped). Missing findings then mean "not diff --git a/packages/opencode/test/altimate/review-all-projects.test.ts b/packages/opencode/test/altimate/review-all-projects.test.ts index 24f74d4a07..206e16784b 100644 --- a/packages/opencode/test/altimate/review-all-projects.test.ts +++ b/packages/opencode/test/altimate/review-all-projects.test.ts @@ -13,7 +13,7 @@ import { owningProject, reviewAllProjects, } from "../../src/altimate/review/multi-project" -import { buildEnvelope, signEnvelope, verifyEnvelope, type VerdictEnvelope } from "../../src/altimate/review/verdict" +import { buildEnvelope, isOutsideProjectReason, signEnvelope, verifyEnvelope, type VerdictEnvelope } from "../../src/altimate/review/verdict" import { makeFinding } from "../../src/altimate/review/finding" import { renderSummary } from "../../src/altimate/review/format" import { postGitHubReview, type GitHubClient } from "../../src/altimate/review/post-github" @@ -548,3 +548,24 @@ describe("mergeProjectEnvelopes", () => { expect(unassigned.map((f) => f.path)).toEqual(["other/x.yml"]) }) }) + +describe("isOutsideProjectReason", () => { + test("accepts exactly what the `/^outside the dbt project/` matches it replaced accepted", () => { + // The regex each call site (orchestrate.ts, format.ts, multi-project.ts) used before the predicate. + const before = (reason: string) => /^outside the dbt project/.test(reason) + const reasons = [ + "outside the dbt project (.)", // run.ts, project at the repository root + "outside the dbt project (projects/a)", // run.ts, nested project + "outside the dbt projects reviewed", // the merge's OUTSIDE_ALL + "outside the dbt project", + "Outside the dbt project (.)", + " outside the dbt project (.)", + "not a dbt model/macro/test/yml/seed file", + "no dbt manifest: lineage, config and graph checks skipped", + "no checks run for other files at the lite tier", + "", + ] + expect(reasons.map(isOutsideProjectReason)).toEqual(reasons.map(before)) + expect(reasons.filter(isOutsideProjectReason)).toEqual(reasons.slice(0, 4)) + }) +}) From f0f439eeeed5a9b63377d2cd2da2f30990c6880e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 20:11:18 +0530 Subject: [PATCH 32/34] test(review): the case-variant work-tree test is skipped visibly on a case-sensitive file system The test returned early, and so passed, where the upper-case spelling of the work tree does not exist. It is now `test.skipIf` on a probe of the temp directory's file system (a probe directory looked up under its upper-case name), and asserts that the other spelling resolves when it runs. Co-Authored-By: Claude Opus 5.5 --- .../altimate/review-ai-system-prompt.test.ts | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts index d4862572fe..52c10a856c 100644 --- a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -1,10 +1,21 @@ import { describe, test, expect, spyOn, afterEach } from "bun:test" import path from "node:path" -import { promises as fs } from "node:fs" +import os from "node:os" +import { promises as fs, existsSync, mkdtempSync, rmSync } from "node:fs" import { finderSystemPrompt } from "../../src/altimate/review/ai-review" import { Dispatcher } from "../../src/altimate/native" import { tmpdir } from "../fixture/fixture" +// Whether the temp directory's file system ignores case: a probe directory is found under its upper-case name. +const caseSensitiveTmp = (() => { + const probe = mkdtempSync(path.join(os.tmpdir(), "case-probe-")) + try { + return !existsSync(path.join(path.dirname(probe), path.basename(probe).toUpperCase())) + } finally { + rmSync(probe, { recursive: true, force: true }) + } +})() + describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { let spy: ReturnType | undefined afterEach(() => spy?.mockRestore()) @@ -114,13 +125,13 @@ describe("ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE", () => { expect(await finderSystemPrompt({ ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE: path.join(targetDir, "p.md") }, repo.path)).toBe("RUNNER FILE") }) - test("a work tree spelled in another case (case-insensitive file systems) is still found", async () => { + // Only a case-insensitive file system (macOS, Windows) resolves the other spelling; elsewhere the test is skipped. + test.skipIf(caseSensitiveTmp)("a work tree spelled in another case (case-insensitive file systems) is still found", async () => { await using repo = await tmpdir({ git: true }) await using outside = await tmpdir() const variant = path.join(path.dirname(repo.path), path.basename(repo.path).toUpperCase()) - // Only a case-insensitive file system (macOS, Windows) resolves the other spelling. - const insensitive = variant !== repo.path && (await fs.stat(variant).then(() => true, () => false)) - if (!insensitive) return + expect(variant).not.toBe(repo.path) + expect(await fs.stat(variant).then(() => true, () => false)).toBe(true) const targetDir = path.join(outside.path, "d2") await fs.mkdir(targetDir) await fs.writeFile(path.join(targetDir, "f"), "RUNNER FILE") From c8181d755305177468dbc1c52c1f712674dcc6b5 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 20:11:18 +0530 Subject: [PATCH 33/34] docs(review): the ignored-value warning is printed when the AI lane is enabled `resolveAiSwitches` gets `warn: aiOn`, which is set before a model is resolved, so a run without a model still warns. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index a220de29af..d8911f9bb8 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -642,7 +642,7 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne `_OTHER_FILES`, `_PYTHON_FILES`, `_VERIFY`); `1` turns one on. `true`/`false`, `on`/`off` and `yes`/`no` are accepted too; an empty value counts as unset, and any other value is ignored (with a warning, printed once per value and only when - the AI lane runs). `ai: false` turns the whole lane off. + the AI lane is enabled). `ai: false` turns the whole lane off. `ALTIMATE_REVIEW_AI_SYSTEM_PROMPT_FILE=` replaces the finder's system prompt. The path must be absolute and outside the repository checkout (for example under `$RUNNER_TEMP`); a file inside the reviewed repository or the From d25b7459055421a91e3936ace766a1d0261af90c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Sun, 29 Nov 2026 00:19:06 +0530 Subject: [PATCH 34/34] test(review): the `caseSensitiveTmp` comment says what the value means The comment described the opposite condition: the value is `true` when the temp directory's file system is case-sensitive, which is what `skipIf` needs. Co-Authored-By: Claude --- packages/opencode/test/altimate/review-ai-system-prompt.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts index 52c10a856c..20386d5b50 100644 --- a/packages/opencode/test/altimate/review-ai-system-prompt.test.ts +++ b/packages/opencode/test/altimate/review-ai-system-prompt.test.ts @@ -6,7 +6,7 @@ import { finderSystemPrompt } from "../../src/altimate/review/ai-review" import { Dispatcher } from "../../src/altimate/native" import { tmpdir } from "../fixture/fixture" -// Whether the temp directory's file system ignores case: a probe directory is found under its upper-case name. +// Whether the temp directory's file system is case-sensitive: a probe directory is not found under its upper-case name. const caseSensitiveTmp = (() => { const probe = mkdtempSync(path.join(os.tmpdir(), "case-probe-")) try {