From 129469a3cd5ce93b679b688e60fc6371fb9f8243 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 02:05:36 +0530 Subject: [PATCH 01/18] feat(review): give the AI finder the repo's review instructions from the base branch - `conventions.ts` reads guideline files from the base commit, so a PR cannot rewrite the conventions it is reviewed under: `.altimate/review.md` (or `.altimate/REVIEW.md`); `REVIEW.md`, `AGENTS.md`, `CLAUDE.md`, `.claude/CLAUDE.md` at the root and every ancestor of a changed path; `.coderabbit.yaml` `path_instructions` and `tone_instructions`; `.cursor/rules/*.mdc` with globs or `alwaysApply`; `.cursorrules`; `.github/copilot-instructions.md`; the dbt/SQL/test sections of `CONTRIBUTING.md` - each finder call gets a TEAM CONVENTIONS section after the grounding with the conventions that apply to its files, most specific first, within 3,000 characters; the finder names the convention's path in the finding body (the core 0.9 output has no `cites`) - this is the one reader of repo instructions: it covers every file #1774's `loadRepoInstructions` reads, which can be dropped when that PR is rebased on this one - `conventions` switch, on by default with the AI lane: `ai.conventions: false` or `ALTIMATE_REVIEW_CONVENTIONS=0` turns it off; off, nothing is loaded and the finder's messages are byte-identical - envelope: `ai.conventions[]` (path, source, scope, globs, chars) and `ai.input[].conventions` on the first file of each call that carried any - `git.ts` `lsTreeAtRef`; `diff-filter.ts` exports `globToRegExp`; docs - tests: loader, parsing, scoping and budget; base commit read over git; off identity (plain, coverage, focused); placement and per-call scoping; envelope record; `reviewPullRequest` end to end under the AI dry run (base `CLAUDE.md`, PR edit ignored) Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 9 + .../opencode/src/altimate/review/ai-review.ts | 17 +- .../src/altimate/review/ai-switches.ts | 4 +- .../opencode/src/altimate/review/config.ts | 2 + .../src/altimate/review/conventions.ts | 390 ++++++++++++++++ .../src/altimate/review/diff-filter.ts | 2 +- packages/opencode/src/altimate/review/git.ts | 10 + .../src/altimate/review/orchestrate.ts | 4 + packages/opencode/src/altimate/review/run.ts | 14 + .../opencode/src/altimate/review/verdict.ts | 14 + .../review-conventions/.coderabbit.yaml | 12 + .../.cursor/rules/dbt-models.mdc | 6 + .../.cursor/rules/manual.mdc | 4 + .../fixtures/review-conventions/CLAUDE.md | 2 + .../review-conventions/CONTRIBUTING.md | 13 + .../review-conventions/models/marts/CLAUDE.md | 1 + .../test/altimate/review-conventions.test.ts | 435 ++++++++++++++++++ 17 files changed, 935 insertions(+), 4 deletions(-) create mode 100644 packages/opencode/src/altimate/review/conventions.ts create mode 100644 packages/opencode/test/altimate/fixtures/review-conventions/.coderabbit.yaml create mode 100644 packages/opencode/test/altimate/fixtures/review-conventions/.cursor/rules/dbt-models.mdc create mode 100644 packages/opencode/test/altimate/fixtures/review-conventions/.cursor/rules/manual.mdc create mode 100644 packages/opencode/test/altimate/fixtures/review-conventions/CLAUDE.md create mode 100644 packages/opencode/test/altimate/fixtures/review-conventions/CONTRIBUTING.md create mode 100644 packages/opencode/test/altimate/fixtures/review-conventions/models/marts/CLAUDE.md create mode 100644 packages/opencode/test/altimate/review-conventions.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index d8911f9bb8..14344dee05 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -301,6 +301,7 @@ ai: true # the advisory AI lane; false turns it off. Or an # 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 +# conventions: true # repo review instructions from the base branch (see below) dataDiff: # OFF by default — see "Data-diff in CI" below enabled: false warehouse: "" # connection name; empty = default connection @@ -652,6 +653,14 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne 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. + The repo's own review instructions go with each call, read from the base branch + so a PR cannot change them: `.altimate/review.md`, `REVIEW.md`, `AGENTS.md` and + `CLAUDE.md` (at the root and in each changed path's directories), + `.claude/CLAUDE.md`, `.cursor/rules/*.mdc`, `.cursorrules`, + `.github/copilot-instructions.md`, `.coderabbit.yaml` `path_instructions` and the + dbt/SQL/test sections of `CONTRIBUTING.md`, most specific first, up to 3,000 + characters per call (`ai.conventions: false` or `ALTIMATE_REVIEW_CONVENTIONS=0` + turns this off). 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 1e6d6ed15b..6bac7e74f3 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -18,6 +18,7 @@ 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" +import { type Convention, type ConventionRecord, conventionRecords, renderConventions } from "./conventions" const log = Log.create({ service: "ai-review" }) @@ -750,6 +751,8 @@ export interface AiReviewInput { checkedPaths?: string[] /** The review's repository (`--cwd`): files named by env variables must be outside it. */ reviewDir?: string + /** Team conventions from the base branch (`conventions` switch); each call carries those for its files. */ + conventions?: Convention[] } /** What happened in the advisory lane, reported on the envelope and in the comment. */ @@ -782,6 +785,8 @@ export interface AiLaneStatus { unsent?: string[] /** Files sent only in calls that failed while others answered (state `ok`): not reviewed by the lane. */ failedFiles?: string[] + /** The team conventions loaded from the base branch (no text), when any were given. */ + conventions?: ConventionRecord[] } /** One file as sent to the model. */ export interface AiInputRecord { @@ -797,6 +802,8 @@ export interface AiInputRecord { card: boolean /** Index of the call that carried the file; set only under focused batching. */ batch?: number + /** Convention paths the call carried; set on the first file of each call that carried any. */ + conventions?: string[] } /** Token counts as `Session.getUsage` reports them: `input` excludes cached * tokens, `inputTotal` includes them. */ @@ -889,6 +896,9 @@ function buildBatchMessage( } else { parts.push("\n## GROUNDING — the engine produced no findings.") } + // The team conventions that apply to this call's files, within the per-call conventions budget. + const conventions = input.conventions?.length ? renderConventions(input.conventions, input.files.map((f) => f.path)) : undefined + if (conventions?.text) parts.push(conventions.text) parts.push("\n## CHANGED FILES (review for what the engine missed):") let cardChars = 0 @@ -908,6 +918,7 @@ function buildBatchMessage( ...(focus ? { batch: focus.batch } : {}), }) } + if (conventions?.paths.length && records.length) records[0].conventions = conventions.paths if (focus?.others.length) { parts.push( "\n## OTHER FILES CHANGED IN THIS PR (reviewed in separate calls; do not comment on them):", @@ -997,13 +1008,15 @@ export async function runAiReview(input: AiReviewInput): Promise const plan = planAiInput(input) const { files, budget } = plan const dryRun = aiDryRunEnabled() - // Recorded under coverage, focused batching, context cards or dry run (all on by default). + // Recorded under coverage, focused batching, context cards or dry run (all on by default); + // `conventions` whenever the base has instruction files (the `conventions` switch, on by default). // Files only the AI lane reads are listed by the coverage ledger, unless a deterministic lane checked them. const checked = new Set(input.checkedPaths ?? []) const unsent = plan.unsent.filter((f) => !AI_ONLY_KINDS.has(f.kind ?? "") || checked.has(f.path)).map((f) => f.path) - const recorded: Pick = { + const recorded: Pick = { ...(budget.coverage || dryRun || plan.focused || plan.input.some((r) => r.card) ? { input: plan.input } : {}), ...(budget.coverage && unsent.length ? { unsent } : {}), + ...(input.conventions?.length ? { conventions: conventionRecords(input.conventions) } : {}), } const done = (findings: Finding[], status: Omit): AiReviewResult => ({ findings, diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index 2dc67ce843..fabdf55e03 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -8,7 +8,7 @@ // 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 AiSwitchName = "coverage" | "contextCard" | "focused" | "otherFiles" | "pythonFiles" | "verify" | "conventions" export type AiSwitches = Record @@ -20,6 +20,7 @@ export const AI_SWITCH_ENV: Record = { otherFiles: "ALTIMATE_REVIEW_AI_OTHER_FILES", pythonFiles: "ALTIMATE_REVIEW_AI_PYTHON_FILES", verify: "ALTIMATE_REVIEW_AI_VERIFY", + conventions: "ALTIMATE_REVIEW_CONVENTIONS", } /** @@ -34,6 +35,7 @@ export const AI_SWITCH_DEFAULTS: AiSwitches = { otherFiles: true, pythonFiles: true, verify: true, + conventions: true, } type Env = Record diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 59b132d816..30fb4a67ee 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -51,6 +51,8 @@ export const ReviewConfig = z.object({ pythonFiles: z.boolean().optional(), /** The dbt-grounded verifier over the AI findings. */ verify: z.boolean().optional(), + /** Repo review instructions (AGENTS.md, CLAUDE.md, REVIEW.md, Cursor/CodeRabbit/Copilot rules, CONTRIBUTING.md) from the base branch. */ + conventions: z.boolean().optional(), }), ]) .default(true), diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts new file mode 100644 index 0000000000..474c5975ab --- /dev/null +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -0,0 +1,390 @@ +// altimate_change - new file: team conventions (repo review instructions) for the AI finder +import YAML from "yaml" +import { globToRegExp } from "./diff-filter" + +/** + * Team conventions from the repository's guideline files, read from the BASE + * commit so a PR cannot rewrite the conventions it is reviewed under. + * + * Sources: `.altimate/review.md` (or `.altimate/REVIEW.md`); `REVIEW.md`, `AGENTS.md`, + * `CLAUDE.md` and `.claude/CLAUDE.md` at the root and at every ancestor directory of a + * changed path; `.coderabbit.yaml` (`reviews.path_instructions[]`, one convention per + * entry scoped by its glob, plus `reviews.tone_instructions`); `.cursor/rules/*.mdc` + * (frontmatter `globs` / `alwaysApply`; rules with neither are manual and skipped); + * `.cursorrules`; `.github/copilot-instructions.md`; `CONTRIBUTING.md` cut to its + * dbt/SQL/test/naming sections. + * + * With the `conventions` switch (`ALTIMATE_REVIEW_CONVENTIONS`, on by default) each + * finder call carries the conventions that apply to its files, most specific first, + * within a character budget (`renderConventions`). Off, nothing is loaded and the + * finder's input is unchanged. + */ + +export type ConventionSource = + | "altimate" + | "review_md" + | "agents_md" + | "claude_md" + | "coderabbit" + | "cursor" + | "cursorrules" + | "copilot" + | "contributing" + +export interface Convention { + /** The repo-relative file it came from (what a finding cites). */ + path: string + source: ConventionSource + /** Directory it applies under ("" = the whole repo). */ + scope: string + /** Repo-relative globs it applies to; when set, only files matching one of them. */ + globs?: string[] + text: string +} + +/** Characters kept per convention file (and per `.coderabbit.yaml` entry). */ +export const CONVENTION_FILE_CHARS = 4_000 +/** Characters kept of CONTRIBUTING.md (its matching sections only). */ +export const CONTRIBUTING_CHARS = 1_500 +/** Characters of conventions one finder call carries. */ +export const CONVENTIONS_CALL_BUDGET = 3_000 +/** Characters loaded over all conventions. */ +const CONVENTIONS_TOTAL_CHARS = 40_000 + +/** Looked up at the root and at every ancestor directory of a changed path. */ +const SCOPED_FILES: Array<[string, ConventionSource]> = [ + ["REVIEW.md", "review_md"], + ["AGENTS.md", "agents_md"], + ["CLAUDE.md", "claude_md"], + [".claude/CLAUDE.md", "claude_md"], +] +const CODERABBIT_FILES = [".coderabbit.yaml", ".coderabbit.yml"] +const CONTRIBUTING_FILES = ["CONTRIBUTING.md", ".github/CONTRIBUTING.md", "docs/CONTRIBUTING.md"] +const CONTRIBUTING_HEADING = /dbt|model|sql|test|yml|naming|macro|incremental/i + +function cut(text: string, max: number): string { + return text.length > max ? text.slice(0, max) + "\n… (truncated)" : text +} + +function depth(scope: string): number { + return scope ? scope.split("/").length : 0 +} + +/** The root and every ancestor directory of the changed paths, shallowest first. */ +function scopesOf(changedPaths: string[]): string[] { + const scopes = new Set([""]) + for (const p of changedPaths) { + const parts = p.split("/").slice(0, -1) + for (let i = 1; i <= parts.length; i++) scopes.add(parts.slice(0, i).join("/")) + } + return [...scopes].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b)) +} + +function join(scope: string, rel: string): string { + return scope ? `${scope}/${rel}` : rel +} + +/** `a/{b,c}/*.{sql,yml}` → every alternative (one brace level at a time). */ +function expandBraces(glob: string): string[] { + const m = /\{([^{}]*)\}/.exec(glob) + if (!m) return [glob] + return m[1].split(",").flatMap((alt) => expandBraces(glob.slice(0, m.index) + alt + glob.slice(m.index + m[0].length))) +} + +/** A glob relative to `scope` as repo-relative globs: a slash-less glob matches at any depth. */ +function scopedGlobs(glob: string, scope: string): string[] { + const g = glob.trim().replace(/^\.\//, "").replace(/^\//, "") + if (!g || g.startsWith("!")) return [] + return expandBraces(g).map((x) => join(scope, x.includes("/") ? x : `**/${x}`)) +} + +/** Split a comma list, leaving commas inside `{…}` alternatives alone. */ +function splitTopLevel(list: string): string[] { + const out: string[] = [] + let depthIn = 0 + let start = 0 + for (let i = 0; i < list.length; i++) { + if (list[i] === "{") depthIn++ + else if (list[i] === "}") depthIn = Math.max(0, depthIn - 1) + else if (list[i] === "," && depthIn === 0) { + out.push(list.slice(start, i)) + start = i + 1 + } + } + out.push(list.slice(start)) + return out +} + +/** Frontmatter of a Cursor `.mdc` rule: `globs` (string, comma list or list), `alwaysApply`, and the body. */ +export function parseMdc(text: string): { globs: string[]; alwaysApply: boolean; body: string } { + const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text) + if (!m) return { globs: [], alwaysApply: false, body: text.trim() } + const globs: string[] = [] + let alwaysApply = false + let inGlobList = false + const unquote = (s: string) => s.trim().replace(/^["']|["']$/g, "").trim() + for (const line of m[1].split(/\r?\n/)) { + const item = /^\s+-\s*(.+)$/.exec(line) + if (inGlobList && item) { + globs.push(unquote(item[1])) + continue + } + inGlobList = false + const kv = /^(\w+)\s*:\s*(.*)$/.exec(line) + if (!kv) continue + const [, key, raw] = kv + if (key === "alwaysApply") alwaysApply = /^true$/i.test(raw.trim()) + if (key !== "globs") continue + const value = raw.trim() + if (!value) inGlobList = true + else globs.push(...splitTopLevel(value.replace(/^\[|\]$/g, "")).map(unquote)) + } + return { globs: globs.filter(Boolean), alwaysApply, body: text.slice(m[0].length).trim() } +} + +/** `.coderabbit.yaml`: one convention per `reviews.path_instructions[]` entry, plus `reviews.tone_instructions`. */ +export function parseCoderabbit(text: string, path: string): Convention[] { + let doc: unknown + try { + doc = YAML.parse(text) + } catch { + return [] + } + const reviews = (doc as { reviews?: Record } | undefined)?.reviews + if (!reviews || typeof reviews !== "object") return [] + const out: Convention[] = [] + const tone = reviews.tone_instructions + if (typeof tone === "string" && tone.trim()) + out.push({ path, source: "coderabbit", scope: "", text: cut(`Tone: ${tone.trim()}`, CONVENTION_FILE_CHARS) }) + const entries = Array.isArray(reviews.path_instructions) ? reviews.path_instructions : [] + for (const e of entries) { + const glob = (e as { path?: unknown })?.path + const instructions = (e as { instructions?: unknown })?.instructions + if (typeof glob !== "string" || typeof instructions !== "string" || !instructions.trim()) continue + const globs = scopedGlobs(glob, "") + if (!globs.length) continue + out.push({ path, source: "coderabbit", scope: "", globs, text: cut(instructions.trim(), CONVENTION_FILE_CHARS) }) + } + return out +} + +/** CONTRIBUTING.md cut to the sections whose heading names dbt, models, SQL, tests, yml, naming, macros or incremental. */ +export function sliceContributing(text: string, max = CONTRIBUTING_CHARS): string { + const lines = text.split(/\r?\n/) + const kept: string[] = [] + let keepLevel = 0 + for (const line of lines) { + const h = /^(#{1,6})\s+(.*)$/.exec(line) + if (h) { + const level = h[1].length + if (keepLevel && level > keepLevel) kept.push(line) + else if (CONTRIBUTING_HEADING.test(h[2])) { + keepLevel = level + kept.push(line) + } else keepLevel = 0 + continue + } + if (keepLevel) kept.push(line) + } + const out = kept.join("\n").trim() + return out.length > max ? out.slice(0, max) + "\n… (truncated)" : out +} + +export interface LoadConventionsInput { + /** Reads a repo-relative file at the base commit; undefined when absent. */ + readBase: (rel: string) => Promise + /** Lists the files under a repo-relative directory at the base commit (recursive, repo-relative). */ + listBase?: (dir: string) => Promise + /** Every path the PR changes (repo-relative): their ancestor directories are searched for scoped files. */ + changedPaths: string[] +} + +/** + * Load the team conventions from the base commit (see the module comment for + * the sources). Each file is cut to 4,000 characters; root files come before + * deeper ones. Never throws: an unreadable file is skipped. + */ +export async function loadConventions(input: LoadConventionsInput): Promise { + const read = (rel: string) => input.readBase(rel).catch(() => undefined) + const list = async (dir: string) => (input.listBase ? ((await input.listBase(dir).catch(() => undefined)) ?? []) : []) + const scopes = scopesOf(input.changedPaths) + const plain = (path: string, source: ConventionSource, scope: string, text: string | undefined): Convention[] => + text?.trim() ? [{ path, source, scope, text: cut(text.trim(), CONVENTION_FILE_CHARS) }] : [] + + let altimatePath = ".altimate/review.md" + let altimate = await read(altimatePath) + if (altimate === undefined) altimate = await read((altimatePath = ".altimate/REVIEW.md")) + const scoped = await Promise.all( + scopes.flatMap((scope) => SCOPED_FILES.map(async ([name, source]) => plain(join(scope, name), source, scope, await read(join(scope, name))))), + ) + let coderabbit: Convention[] = [] + for (const p of CODERABBIT_FILES) { + const text = await read(p) + if (text === undefined) continue + coderabbit = parseCoderabbit(text, p) + break + } + const cursor: Convention[] = [] + for (const scope of scopes) { + const dir = join(scope, ".cursor/rules") + const files = (await list(dir)).filter((p) => p.endsWith(".mdc")).sort() + for (const p of files) { + const text = await read(p) + if (!text) continue + const rule = parseMdc(text) + if (!rule.body) continue + const globs = rule.globs.flatMap((g) => scopedGlobs(g, scope)) + if (!rule.alwaysApply && !globs.length) continue + cursor.push({ + path: p, + source: "cursor", + scope, + ...(rule.alwaysApply ? {} : { globs }), + text: cut(rule.body, CONVENTION_FILE_CHARS), + }) + } + } + const cursorrules = await read(".cursorrules") + const copilot = await read(".github/copilot-instructions.md") + let contributing: Convention[] = [] + for (const p of CONTRIBUTING_FILES) { + const text = await read(p) + if (text === undefined) continue + contributing = plain(p, "contributing", "", sliceContributing(text)) + break + } + const all = [ + ...plain(altimatePath, "altimate", "", altimate), + ...scoped.flat(), + ...coderabbit, + ...cursor, + ...plain(".cursorrules", "cursorrules", "", cursorrules), + ...plain(".github/copilot-instructions.md", "copilot", "", copilot), + ...contributing, + ] + const out: Convention[] = [] + const seen = new Set() + let left = CONVENTIONS_TOTAL_CHARS + for (const c of all) { + const key = `${c.path}|${(c.globs ?? []).join(",")}|${c.text.length}` + if (seen.has(key) || c.text.length > left) continue + seen.add(key) + out.push(c) + left -= c.text.length + } + return out +} + +/** Literal characters of a glob (its wildcards left out): how specific a match on it is. */ +function literalLength(glob: string): number { + return glob.replace(/\*\*\/|\*|\?/g, "").length +} + +const GLOB_CACHE = new Map() +function globMatch(glob: string, file: string): boolean { + let re = GLOB_CACHE.get(glob) + if (!re) GLOB_CACHE.set(glob, (re = globToRegExp(glob))) + return re.test(file) +} + +/** + * How specifically `c` applies to `file` (pure), or undefined when it does not: a glob convention + * applies when one of its globs matches, a scoped one when the file sits under its directory. + * Specificity = characters of the matched directory scope plus literal characters of the longest + * matching glob, so a nested `CLAUDE.md` or a narrow glob outranks a root file. + */ +export function conventionSpecificity(c: Convention, file: string): number | undefined { + if (c.scope && !file.startsWith(c.scope + "/")) return undefined + const scopeLen = c.scope ? c.scope.length + 1 : 0 + if (!c.globs) return scopeLen + const matched = c.globs.filter((g) => globMatch(g, file)) + if (!matched.length) return undefined + return scopeLen + Math.max(...matched.map(literalLength)) +} + +/** What a convention entry costs in a call: its heading and text. */ +function entryChars(c: Convention): number { + return c.path.length + appliesTo(c).length + 20 + c.text.length +} + +/** Take conventions in order within `budget` characters; the first one is cut to fit when it alone is over. */ +function withinBudget(ordered: Convention[], budget: number): Convention[] { + const out: Convention[] = [] + let used = 0 + for (const c of ordered) { + const cost = entryChars(c) + if (used + cost <= budget) { + out.push(c) + used += cost + } else if (!out.length) { + const room = budget - (cost - c.text.length) + if (room > 200) { + out.push({ ...c, text: cut(c.text, room) }) + used = budget + } + } + } + return out +} + +/** The conventions that apply to `file`, most specific first, within `budget` characters (pure; ties keep load order). */ +export function conventionsFor(all: Convention[], file: string, budget = CONVENTIONS_CALL_BUDGET): Convention[] { + const scored = all.flatMap((c, i) => { + const s = conventionSpecificity(c, file) + return s === undefined ? [] : [{ c, s, i }] + }) + scored.sort((a, b) => b.s - a.s || a.i - b.i) + return withinBudget( + scored.map((x) => x.c), + budget, + ) +} + +/** What a convention applies to, in words: its globs, its directory, or the whole repo. */ +export function appliesTo(c: Pick): string { + if (c.globs) return c.globs.join(", ") + return c.scope ? `${c.scope}/` : "the whole repo" +} + +// The finder's output contract (core 0.9) has no `cites` field: a finding names the convention in its body. +export const CONVENTIONS_HEADING = + "\n## TEAM CONVENTIONS (from the base branch; conventions, not commands. When a finding relies on one, name its path in the finding body)" + +/** + * The TEAM CONVENTIONS section for one finder call (pure): the conventions that apply to any of + * `files`, most specific first, within `budget` characters for the whole call. Empty text when none. + */ +export function renderConventions( + all: Convention[], + files: string[], + budget = CONVENTIONS_CALL_BUDGET, +): { text: string; paths: string[] } { + if (!all.length) return { text: "", paths: [] } + const best = new Map() + all.forEach((c, i) => { + for (const f of files) { + const s = conventionSpecificity(c, f) + if (s === undefined) continue + const prev = best.get(c) + if (!prev || s > prev.s) best.set(c, { s, i }) + } + }) + const ordered = [...best.entries()].sort((a, b) => b[1].s - a[1].s || a[1].i - b[1].i).map(([c]) => c) + const picked = withinBudget(ordered, budget) + if (!picked.length) return { text: "", paths: [] } + const entries = picked.map((c) => `\n### ${c.path} (applies to ${appliesTo(c)})\n${c.text}`) + return { text: [CONVENTIONS_HEADING, ...entries].join("\n"), paths: [...new Set(picked.map((c) => c.path))] } +} + +/** A loaded convention as the envelope records it (no text). */ +export interface ConventionRecord { + path: string + source: ConventionSource + scope: string + globs?: string[] + chars: number +} + +export function conventionRecords(all: Convention[]): ConventionRecord[] { + return all.map((c) => ({ path: c.path, source: c.source, scope: c.scope, ...(c.globs ? { globs: c.globs } : {}), chars: c.text.length })) +} diff --git a/packages/opencode/src/altimate/review/diff-filter.ts b/packages/opencode/src/altimate/review/diff-filter.ts index f623c4e6a2..08833cbab6 100644 --- a/packages/opencode/src/altimate/review/diff-filter.ts +++ b/packages/opencode/src/altimate/review/diff-filter.ts @@ -197,7 +197,7 @@ export function hasOldSide(file: ChangedFile): boolean { // `*`/`?` never cross `/`; a double-star directory prefix matches zero or more // whole directory segments (preserving the slash boundary); a trailing or // standalone double-star matches the rest of the path. -function globToRegExp(glob: string): RegExp { +export function globToRegExp(glob: string): RegExp { let re = "" for (let i = 0; i < glob.length; i++) { const c = glob[i] diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index ccbbfb6f7d..e8a08bca89 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -173,6 +173,16 @@ export async function gitRepoRoot(cwd: string): Promise { } } +/** Tracked files under the repo-relative directory `dir` at `ref`, repo-root relative (recursive); undefined when git can't list them. */ +export async function lsTreeAtRef(cwd: string, ref: string, dir: string): Promise { + try { + const out = await git(["ls-tree", "-r", "--full-tree", "--name-only", ref, "--", `:(top)${dir.replace(/\/+$/, "")}/`], cwd) + return out.split("\n").filter(Boolean) + } catch { + return undefined + } +} + /** Every tracked file at `ref` (default HEAD), repo-root relative; undefined when git can't list it. */ export async function listFilesAt(cwd: string, ref?: string): Promise { try { diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 3ac9754ce8..80a8016a36 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -68,6 +68,7 @@ import { ruleTier } from "./rule-tiers" import { type AiSwitches, switchOn } from "./ai-switches" import { isAiOtherFile } from "./ai-other-files" import { AI_PYTHON_KIND, isAiPythonFile } from "./ai-python-files" +import type { Convention } from "./conventions" import { type AiVerifyEvidence, numberedSlice } from "./ai-verify" import { holdsCredentials, isCredentialPath } from "./credentials" import type { ColumnReach } from "../native/dbt/column-reach" @@ -299,6 +300,8 @@ export interface OrchestrateInput { aiOutsideFiles?: ChangedFile[] /** The review's repository root (`--cwd`'s git root); env-named files must be outside it. */ reviewDir?: string + /** Team conventions from the base branch (`conventions` switch), for the AI finder. */ + conventions?: Convention[] /** 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. */ @@ -2802,6 +2805,7 @@ export async function runReview(input: OrchestrateInput): Promise showAtRef(gitRoot, resolved.sha, rel), + listBase: (dir) => lsTreeAtRef(gitRoot, resolved.sha, dir), + changedPaths: opts.prFiles ?? collected.map((f) => f.path), + }) + : [] + const consumerLists = config.consumerColumnLists.length ? await loadConsumerLists({ configs: config.consumerColumnLists, @@ -515,6 +528,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise aiSwitches, ...(aiOutsideFiles.length ? { aiOutsideFiles } : {}), reviewDir: gitRoot, + ...(conventions.length ? { conventions } : {}), 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 0b4033e973..bab9dfc6b5 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -282,6 +282,8 @@ export const VerdictEnvelope = z.object({ card: z.boolean(), /** Index of the call that carried the file (focused batching only). */ batch: z.number().int().nonnegative().optional(), + /** Convention paths the call carried (first file of each call that carried any). */ + conventions: z.array(z.string()).optional(), }), ) .optional(), @@ -289,6 +291,18 @@ export const VerdictEnvelope = z.object({ 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(), + /** Team conventions loaded from the base branch (no text). */ + conventions: z + .array( + z.object({ + path: z.string(), + source: z.string(), + scope: z.string(), + globs: z.array(z.string()).optional(), + chars: z.number().int().nonnegative(), + }), + ) + .optional(), /** The dbt-grounded verifier (the `verify` switch): what it kept and dropped. */ verifier: z .object({ diff --git a/packages/opencode/test/altimate/fixtures/review-conventions/.coderabbit.yaml b/packages/opencode/test/altimate/fixtures/review-conventions/.coderabbit.yaml new file mode 100644 index 0000000000..1e19a7c0e3 --- /dev/null +++ b/packages/opencode/test/altimate/fixtures/review-conventions/.coderabbit.yaml @@ -0,0 +1,12 @@ +language: en-US +reviews: + tone_instructions: "Be brief; name the column." + path_instructions: + - path: "models/staging/**/*.sql" + instructions: | + Staging models only rename and cast source columns; no joins. + - path: "models/marts/**" + instructions: | + Every mart has a unique + not_null test on its primary key. + - path: "!models/legacy/**" + instructions: "ignored negation" diff --git a/packages/opencode/test/altimate/fixtures/review-conventions/.cursor/rules/dbt-models.mdc b/packages/opencode/test/altimate/fixtures/review-conventions/.cursor/rules/dbt-models.mdc new file mode 100644 index 0000000000..b12a8356d0 --- /dev/null +++ b/packages/opencode/test/altimate/fixtures/review-conventions/.cursor/rules/dbt-models.mdc @@ -0,0 +1,6 @@ +--- +description: dbt model conventions +globs: models/**/*.sql +alwaysApply: false +--- +Use `{{ ref() }}` for models and `{{ source() }}` for raw tables; never hardcode schemas. diff --git a/packages/opencode/test/altimate/fixtures/review-conventions/.cursor/rules/manual.mdc b/packages/opencode/test/altimate/fixtures/review-conventions/.cursor/rules/manual.mdc new file mode 100644 index 0000000000..406061ec0a --- /dev/null +++ b/packages/opencode/test/altimate/fixtures/review-conventions/.cursor/rules/manual.mdc @@ -0,0 +1,4 @@ +--- +description: only when asked +--- +A manual rule that is never attached automatically. diff --git a/packages/opencode/test/altimate/fixtures/review-conventions/CLAUDE.md b/packages/opencode/test/altimate/fixtures/review-conventions/CLAUDE.md new file mode 100644 index 0000000000..1a0eb8108a --- /dev/null +++ b/packages/opencode/test/altimate/fixtures/review-conventions/CLAUDE.md @@ -0,0 +1,2 @@ +# Project notes +Column names are snake_case. Booleans start with is_ or has_. diff --git a/packages/opencode/test/altimate/fixtures/review-conventions/CONTRIBUTING.md b/packages/opencode/test/altimate/fixtures/review-conventions/CONTRIBUTING.md new file mode 100644 index 0000000000..aa7a358f8a --- /dev/null +++ b/packages/opencode/test/altimate/fixtures/review-conventions/CONTRIBUTING.md @@ -0,0 +1,13 @@ +# Contributing + +## Setup +Install python and run make. + +## dbt model naming +Prefix staging models with stg_ and marts with fct_ or dim_. + +### Tests +Every model has a yml entry. + +## Releasing +Tag the commit. diff --git a/packages/opencode/test/altimate/fixtures/review-conventions/models/marts/CLAUDE.md b/packages/opencode/test/altimate/fixtures/review-conventions/models/marts/CLAUDE.md new file mode 100644 index 0000000000..ce74e7c675 --- /dev/null +++ b/packages/opencode/test/altimate/fixtures/review-conventions/models/marts/CLAUDE.md @@ -0,0 +1 @@ +Marts are incremental with unique_key set to the primary key; filter with is_incremental() on updated_at >= max(updated_at). diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts new file mode 100644 index 0000000000..a385971c40 --- /dev/null +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -0,0 +1,435 @@ +import { describe, test, expect, spyOn, mock, 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 { + CONVENTIONS_HEADING, + appliesTo, + conventionSpecificity, + conventionsFor, + loadConventions, + parseMdc, + renderConventions, + sliceContributing, + type Convention, +} from "../../src/altimate/review/conventions" +import { planAiInput, runAiReview, type AiReviewFile, type AiReviewInput } from "../../src/altimate/review/ai-review" +import { lsTreeAtRef, showAtRef } from "../../src/altimate/review/git" +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 { Dispatcher } from "../../src/altimate/native" +import { LLM } from "../../src/session/llm" +import { Provider } from "../../src/provider/provider" +import { resolveAiSwitches } from "../../src/altimate/review/ai-switches" + +// Team conventions (repo review instructions) from the base branch for the AI finder. + +const FIXTURE = path.join(import.meta.dir, "fixtures", "review-conventions") + +async function fixtureFiles(dir = FIXTURE, prefix = ""): Promise { + const out: string[] = [] + for (const e of await fs.readdir(dir, { withFileTypes: true })) { + const rel = prefix ? `${prefix}/${e.name}` : e.name + if (e.isDirectory()) out.push(...(await fixtureFiles(path.join(dir, e.name), rel))) + else out.push(rel) + } + return out +} + +/** The fixture as the base commit: a reader and a directory listing over it. */ +async function fixtureBase() { + const files = await fixtureFiles() + const reads: string[] = [] + return { + reads, + readBase: async (rel: string) => { + reads.push(rel) + return files.includes(rel) ? fs.readFile(path.join(FIXTURE, rel), "utf8") : undefined + }, + listBase: async (dir: string) => files.filter((f) => f.startsWith(dir + "/")), + } +} + +const CHANGED = ["models/marts/fct_orders.sql", "models/staging/stg_orders.sql", "models/staging/stg_orders.yml"] + +async function loadFixture(changed = CHANGED) { + const base = await fixtureBase() + return loadConventions({ readBase: base.readBase, listBase: base.listBase, changedPaths: changed }) +} + +describe("loadConventions (fixture as the base commit)", () => { + test("every source, in load order, with scope and globs", async () => { + const all = await loadFixture() + expect(all.map((c) => [c.path, c.source, c.scope, c.globs ?? null])).toEqual([ + ["CLAUDE.md", "claude_md", "", null], + ["models/marts/CLAUDE.md", "claude_md", "models/marts", null], + [".coderabbit.yaml", "coderabbit", "", null], + [".coderabbit.yaml", "coderabbit", "", ["models/staging/**/*.sql"]], + [".coderabbit.yaml", "coderabbit", "", ["models/marts/**"]], + [".cursor/rules/dbt-models.mdc", "cursor", "", ["models/**/*.sql"]], + ["CONTRIBUTING.md", "contributing", "", null], + ]) + expect(all[2].text).toBe("Tone: Be brief; name the column.") + expect(all[5].text).toContain("never hardcode schemas") + // The manual Cursor rule (no globs, not alwaysApply) and the negated CodeRabbit path are skipped. + expect(all.some((c) => c.text.includes("manual rule"))).toBe(false) + expect(all.some((c) => c.text.includes("ignored negation"))).toBe(false) + }) + + test("CONTRIBUTING.md keeps only the dbt/model/test sections", async () => { + const all = await loadFixture() + const contributing = all.find((c) => c.source === "contributing")!.text + expect(contributing).toContain("## dbt model naming") + expect(contributing).toContain("### Tests") + expect(contributing).not.toContain("Setup") + expect(contributing).not.toContain("Releasing") + }) + + test("scoped files are looked up only in ancestors of changed paths", async () => { + const base = await fixtureBase() + const all = await loadConventions({ readBase: base.readBase, listBase: base.listBase, changedPaths: ["models/staging/stg_orders.sql"] }) + expect(all.some((c) => c.path === "models/marts/CLAUDE.md")).toBe(false) + expect(base.reads).toContain("models/staging/CLAUDE.md") + expect(base.reads).not.toContain("models/marts/CLAUDE.md") + }) + + test("the files #1774 read (REVIEW.md, .altimate/REVIEW.md, AGENTS.md, CLAUDE.md) are all covered", async () => { + const files: Record = { + "REVIEW.md": "Root rule.", + ".altimate/REVIEW.md": "Altimate rule.", + "models/marts/AGENTS.md": "Marts agents rule.", + "models/marts/CLAUDE.md": "Marts claude rule.", + } + const all = await loadConventions({ readBase: async (rel) => files[rel], changedPaths: ["models/marts/x.sql"] }) + expect(all.map((c) => [c.path, c.scope]).sort()).toEqual([ + [".altimate/REVIEW.md", ""], + ["REVIEW.md", ""], + ["models/marts/AGENTS.md", "models/marts"], + ["models/marts/CLAUDE.md", "models/marts"], + ]) + }) + + test("per-file cap of 4,000 characters; unreadable files are skipped", async () => { + const all = await loadConventions({ + readBase: async (rel) => (rel === "AGENTS.md" ? "x".repeat(9_000) : rel === "REVIEW.md" ? Promise.reject(new Error("boom")) : undefined), + changedPaths: ["models/a.sql"], + }) + expect(all.map((c) => c.path)).toEqual(["AGENTS.md"]) + expect(all[0].text.startsWith("x".repeat(4_000) + "\n… (truncated)")).toBe(true) + }) + + test(".altimate/review.md, .claude/CLAUDE.md, .cursorrules and copilot instructions apply to the whole repo", async () => { + const files: Record = { + ".altimate/review.md": "Prefer qualify over subqueries.", + ".claude/CLAUDE.md": "Run dbt build before pushing.", + ".cursorrules": "Use 4-space indent in SQL.", + ".github/copilot-instructions.md": "Every model needs a description.", + } + const all = await loadConventions({ readBase: async (rel) => files[rel], changedPaths: ["models/a.sql"] }) + expect(all.map((c) => [c.path, c.source, c.scope])).toEqual([ + [".altimate/review.md", "altimate", ""], + [".claude/CLAUDE.md", "claude_md", ""], + [".cursorrules", "cursorrules", ""], + [".github/copilot-instructions.md", "copilot", ""], + ]) + }) +}) + +describe("parsing helpers", () => { + test("parseMdc: string, comma list, bracket list and YAML list globs; alwaysApply", () => { + expect(parseMdc("---\nglobs: models/**/*.sql\n---\nbody")).toEqual({ globs: ["models/**/*.sql"], alwaysApply: false, body: "body" }) + expect(parseMdc("---\nglobs: *.sql, *.yml\nalwaysApply: false\n---\nb").globs).toEqual(["*.sql", "*.yml"]) + expect(parseMdc('---\nglobs: ["a/*.sql", \'b/**\']\n---\nb').globs).toEqual(["a/*.sql", "b/**"]) + expect(parseMdc("---\nglobs:\n - a/*.sql\n - \"b/**\"\ndescription: x\n---\nb").globs).toEqual(["a/*.sql", "b/**"]) + expect(parseMdc("---\nalwaysApply: true\n---\nalways").alwaysApply).toBe(true) + expect(parseMdc("no frontmatter")).toEqual({ globs: [], alwaysApply: false, body: "no frontmatter" }) + }) + + test("sliceContributing: matching sections and their subsections, capped", () => { + const text = "# Intro\nhi\n## SQL style\nlower case\n### Joins\nexplicit\n## Release\nno\n## Naming\nsnake" + expect(sliceContributing(text)).toBe("## SQL style\nlower case\n### Joins\nexplicit\n## Naming\nsnake") + expect(sliceContributing("## Tests\n" + "y".repeat(3_000), 100).length).toBeLessThan(120) + }) + + test("the conventions switch: on by default, env 1/0 wins over `ai.conventions`", () => { + expect(resolveAiSwitches({ ai: true }, {}).conventions).toBe(true) + expect(resolveAiSwitches({ ai: { conventions: false } }, {}).conventions).toBe(false) + expect(resolveAiSwitches({ ai: { conventions: false } }, { ALTIMATE_REVIEW_CONVENTIONS: "1" }).conventions).toBe(true) + expect(resolveAiSwitches({ ai: true }, { ALTIMATE_REVIEW_CONVENTIONS: "0" }).conventions).toBe(false) + }) +}) + +describe("scoping and budget", () => { + test("glob and directory scoping; slash-less globs match at any depth; braces expand", async () => { + const all = await loadFixture() + const byPath = (p: string, i = 0) => all.filter((c) => c.path === p)[i] + expect(conventionSpecificity(byPath("CLAUDE.md"), "anything/x.sql")).toBe(0) + expect(conventionSpecificity(byPath("models/marts/CLAUDE.md"), "models/marts/fct.sql")).toBe("models/marts/".length) + expect(conventionSpecificity(byPath("models/marts/CLAUDE.md"), "models/staging/stg.sql")).toBeUndefined() + expect(conventionSpecificity(byPath(".coderabbit.yaml", 1), "models/staging/sub/stg.sql")).toBeGreaterThan(0) + expect(conventionSpecificity(byPath(".coderabbit.yaml", 1), "models/staging/stg.yml")).toBeUndefined() + const loose: Convention = { path: "x.mdc", source: "cursor", scope: "", globs: ["**/*.sql"], text: "t" } + expect(conventionSpecificity(loose, "a/b/c.sql")).toBe(".sql".length) + const files: Record = { ".cursor/rules/y.mdc": "---\nglobs: models/*.{sql,yml}\n---\nboth" } + const braces = await loadConventions({ readBase: async (r) => files[r], listBase: async () => Object.keys(files), changedPaths: [] }) + expect(braces[0].globs).toEqual(["models/*.sql", "models/*.yml"]) + }) + + test("conventionsFor: most specific first, then load order; within the budget", async () => { + const all = await loadFixture() + expect(conventionsFor(all, "models/marts/fct_orders.sql").map((c) => c.path + (c.globs ? ` ${c.globs[0]}` : ""))).toEqual([ + "models/marts/CLAUDE.md", + ".coderabbit.yaml models/marts/**", + ".cursor/rules/dbt-models.mdc models/**/*.sql", + "CLAUDE.md", + ".coderabbit.yaml", + "CONTRIBUTING.md", + ]) + expect(conventionsFor(all, "models/staging/stg_orders.yml").map((c) => c.path)).toEqual(["CLAUDE.md", ".coderabbit.yaml", "CONTRIBUTING.md"]) + // A tight budget keeps the most specific entries that fit. + const tight = conventionsFor(all, "models/marts/fct_orders.sql", 300) + expect(tight[0].path).toBe("models/marts/CLAUDE.md") + expect(tight.length).toBeLessThan(6) + // One entry over the whole budget is cut to fit rather than dropped. + const big: Convention = { path: "AGENTS.md", source: "agents_md", scope: "", text: "z".repeat(5_000) } + const cutOne = conventionsFor([big], "a.sql", 1_000) + expect(cutOne).toHaveLength(1) + expect(cutOne[0].text.length).toBeLessThan(1_000) + }) + + test("renderConventions: the section for the call's files only, headings say what each applies to", async () => { + const all = await loadFixture() + const r = renderConventions(all, ["models/staging/stg_orders.sql"]) + expect(r.text.startsWith(CONVENTIONS_HEADING)).toBe(true) + expect(r.text).toContain("### .coderabbit.yaml (applies to models/staging/**/*.sql)\nStaging models only rename") + expect(r.text).toContain("### CLAUDE.md (applies to the whole repo)") + expect(r.text).not.toContain("models/marts/CLAUDE.md") + expect(r.text).not.toContain("Every mart has") + expect(r.paths).toEqual([".coderabbit.yaml", ".cursor/rules/dbt-models.mdc", "CLAUDE.md", "CONTRIBUTING.md"]) + const marts = renderConventions(all, ["models/marts/fct_orders.sql"]) + expect(marts.text.indexOf("### models/marts/CLAUDE.md (applies to models/marts/)")).toBeLessThan(marts.text.indexOf("### CLAUDE.md")) + expect(renderConventions(all, ["models/marts/fct_orders.sql"], 400).text.length).toBeLessThan(400 + CONVENTIONS_HEADING.length + 10) + expect(renderConventions([], ["a.sql"])).toEqual({ text: "", paths: [] }) + expect(appliesTo({ scope: "", globs: ["a/**", "b/*.sql"] })).toBe("a/**, b/*.sql") + }) +}) + + +describe("loadConventions over git: the base commit, never the PR's edits", () => { + const git = (cwd: string, ...args: string[]) => + execFileSync("git", args, { cwd, env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } }).toString() + + test("showAtRef + lsTreeAtRef at the merge base read the base versions and the base Cursor rules", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "review-conventions-")) + try { + await fs.cp(FIXTURE, dir, { recursive: true }) + git(dir, "init", "-q", "-b", "main") + git(dir, "add", "-A") + git(dir, "commit", "-q", "-m", "base") + const base = git(dir, "rev-parse", "HEAD").trim() + git(dir, "checkout", "-q", "-b", "pr") + await fs.writeFile(path.join(dir, "CLAUDE.md"), "PR rewrote the rules.\n") + await fs.writeFile(path.join(dir, ".cursor/rules/new.mdc"), "---\nalwaysApply: true\n---\nAdded by the PR.\n") + git(dir, "add", "-A") + git(dir, "commit", "-q", "-m", "pr") + const all = await loadConventions({ + readBase: (rel) => showAtRef(dir, base, rel), + listBase: (d) => lsTreeAtRef(dir, base, d), + changedPaths: CHANGED, + }) + expect(all.map((c) => c.path)).toEqual((await loadFixture()).map((c) => c.path)) + expect(all.find((c) => c.path === "CLAUDE.md")!.text).toContain("snake_case") + expect(all.some((c) => c.text.includes("Added by the PR"))).toBe(false) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }) +}) + +const aiFile = (p: string, kind = "model_sql"): AiReviewFile => ({ + path: p, + status: "modified", + model: p.split("/").pop()!.replace(/\.\w+$/, ""), + kind, + diff: `@@ -1,2 +1,3 @@\n select a,\n+ b / 100 as amount,\n from t\n`, + sql: "select a,\n b / 100 as amount,\nfrom t\n", +}) + +const FOCUSED = { ALTIMATE_REVIEW_AI_FOCUSED: "1", ALTIMATE_REVIEW_AI_FOCUS_MIN_FILES: "2", ALTIMATE_REVIEW_AI_FOCUS_BATCH_FILES: "1" } + +describe("standard finder: each call carries the conventions of its files", () => { + test("flag off (no conventions given): the plan is byte-identical, also with an empty list", async () => { + const files = [aiFile("models/marts/fct_orders.sql"), aiFile("models/staging/stg_orders.sql")] + for (const env of [{}, { ALTIMATE_REVIEW_AI_COVERAGE: "1" }, FOCUSED]) { + const base = planAiInput({ grounding: [], files }, env) + const empty = planAiInput({ grounding: [], files, conventions: [] }, env) + expect(empty.messages).toEqual(base.messages) + expect(empty.input).toEqual(base.input) + expect(base.messages.join("\n")).not.toContain("TEAM CONVENTIONS") + expect(base.input.some((r) => "conventions" in r)).toBe(false) + } + }) + + test("flag on: after the grounding, before the changed files; only the call's conventions; recorded on its first file", async () => { + const conventions = await loadFixture() + const files = [aiFile("models/marts/fct_orders.sql")] + const off = planAiInput({ grounding: [], files }, {}) + const plan = planAiInput({ grounding: [], files, conventions }, {}) + const m = plan.messages[0] + expect(m.indexOf("## GROUNDING")).toBeLessThan(m.indexOf("## TEAM CONVENTIONS")) + expect(m.indexOf("## TEAM CONVENTIONS")).toBeLessThan(m.indexOf("## CHANGED FILES")) + expect(m).toContain("### models/marts/CLAUDE.md (applies to models/marts/)\nMarts are incremental") + expect(m).not.toContain("Staging models only rename") + // Removing the section gives back the flag-off message exactly. + const section = renderConventions(conventions, files.map((f) => f.path)).text + expect(m.replace("\n" + section, "")).toBe(off.messages[0]) + expect(plan.input[0].conventions).toEqual(renderConventions(conventions, ["models/marts/fct_orders.sql"]).paths) + expect(section.length).toBeLessThan(3_000 + CONVENTIONS_HEADING.length + 10) + }) + + test("focused calls: each call gets the conventions of its own files", async () => { + const conventions = await loadFixture() + const files = [aiFile("models/marts/fct_orders.sql"), aiFile("models/staging/stg_orders.sql")] + const plan = planAiInput({ grounding: [], files, conventions }, FOCUSED) + expect(plan.messages).toHaveLength(2) + const marts = plan.messages.find((x) => x.includes("### models/marts/fct_orders.sql"))! + const staging = plan.messages.find((x) => x.includes("### models/staging/stg_orders.sql (modified"))! + expect(marts).toContain("Every mart has a unique") + expect(marts).not.toContain("Staging models only rename") + expect(staging).toContain("Staging models only rename") + expect(staging).not.toContain("models/marts/CLAUDE.md") + }) + + test("a call whose files no convention applies to carries no section", () => { + const only: Convention[] = [{ path: "models/marts/CLAUDE.md", source: "claude_md", scope: "models/marts", text: "marts only" }] + const files = [aiFile("macros/m.sql", "macro")] + expect(planAiInput({ grounding: [], files, conventions: only }, {}).messages).toEqual(planAiInput({ grounding: [], files }, {}).messages) + }) +}) + +describe("runAiReview records ai.conventions and sends the section", () => { + afterEach(() => mock.restore()) + + test("the model receives the section; the status lists every loaded convention as {path, source, scope, chars}", async () => { + const conventions = await loadFixture() + spyOn(Provider, "defaultModel").mockResolvedValue({ providerID: "fake", modelID: "m" } as any) + spyOn(Provider, "getModel").mockResolvedValue({ providerID: "fake", id: "m", api: { npm: "x" }, cost: {} } as any) + spyOn(Dispatcher, "call").mockImplementation((async (method: string) => + method === "altimate_core.review_ai_prompt" ? { success: true, data: { prompt: "SYSTEM" } } : { success: true, data: { findings: [] } }) as any) + const seen: any[] = [] + spyOn(LLM, "stream").mockImplementation(async (input: any) => { + seen.push(input) + return { + fullStream: (async function* () {})(), + text: Promise.resolve("[]"), + finishReason: Promise.resolve("stop"), + response: Promise.resolve({ messages: [] }), + totalUsage: Promise.resolve(undefined), + providerMetadata: Promise.resolve(undefined), + } as any + }) + const res = await runAiReview({ files: [aiFile("models/marts/fct_orders.sql")], grounding: [], conventions }) + expect(String(seen[0].messages[0].content)).toContain("### models/marts/CLAUDE.md (applies to models/marts/)") + expect(res.status.conventions).toEqual(conventions.map((c) => ({ path: c.path, source: c.source, scope: c.scope, ...(c.globs ? { globs: c.globs } : {}), chars: c.text.length }))) + const without = await runAiReview({ files: [aiFile("models/marts/fct_orders.sql")], grounding: [] }) + expect(without.status.conventions).toBeUndefined() + expect(String(seen[1].messages[0].content)).not.toContain("TEAM CONVENTIONS") + }) +}) + +describe("orchestrator passes the conventions to the lane and the envelope keeps the record", () => { + 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 + + test("absent: the lane input has no conventions; present: passed through and recorded under ai.conventions", async () => { + const conventions = await loadFixture() + const run = (extra: { conventions?: Convention[] }) => { + let seen: AiReviewInput | undefined + return runReview({ + changedFiles: [{ path: "models/marts/fct_orders.sql", status: "modified", diff: "@@ -1 +1,2 @@\n select 1\n+, 2 as b\n" }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + forceTier: "full", + getContent: async (_f, side) => (side === "old" ? "select 1" : "select 1\n, 2 as b"), + generatedAt: "2026-11-24T00:00:00Z", + ...extra, + aiReview: async (input) => { + seen = input + return { findings: [], status: { state: "ok", ...(input.conventions ? { conventions: [{ path: "CLAUDE.md", source: "claude_md", scope: "", chars: 5 }] } : {}) } } + }, + }).then((env) => ({ env, seen: seen! })) + } + const off = await run({}) + expect("conventions" in off.seen).toBe(false) + expect(off.env.ai?.conventions).toBeUndefined() + const on = await run({ conventions }) + expect(on.seen.conventions).toBe(conventions) + expect(on.env.ai?.conventions).toEqual([{ path: "CLAUDE.md", source: "claude_md", scope: "", chars: 5 }]) + expect(on.env.findings).toEqual(off.env.findings) + }) +}) + +describe("reviewPullRequest end to end (AI dry run, no model call)", () => { + const KEYS = ["ALTIMATE_REVIEW_CONVENTIONS", "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] + } + }) + const git = (cwd: string, ...args: string[]) => + execFileSync("git", args, { cwd, env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } }).toString() + + test("on by default: the base CLAUDE.md goes into ai.conventions and the call record; `0` records nothing", async () => { + const { reviewPullRequest } = await import("../../src/altimate/review/run") + const dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-conventions-e2e-"))) + try { + await fs.mkdir(path.join(dir, "models"), { recursive: true }) + await fs.writeFile(path.join(dir, "dbt_project.yml"), "name: p\n") + await fs.writeFile(path.join(dir, "CLAUDE.md"), "Column names are snake_case.\n") + await fs.writeFile(path.join(dir, "models/m.sql"), "select 1 as id\n") + git(dir, "init", "-q", "-b", "main") + git(dir, "add", "-A") + git(dir, "commit", "-q", "-m", "base") + git(dir, "checkout", "-q", "-b", "pr") + await fs.writeFile(path.join(dir, "models/m.sql"), "select 1 as id, 2 as amountCents\n") + await fs.writeFile(path.join(dir, "CLAUDE.md"), "PR rewrote the rules.\n") + git(dir, "add", "-A") + git(dir, "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_CONVENTIONS = "0" + const off = await reviewPullRequest({ cwd: dir, base: "main", head: "HEAD" }) + expect(off.ai?.state).toBe("skipped") + expect(off.ai?.conventions).toBeUndefined() + expect(off.ai?.input?.[0].conventions).toBeUndefined() + delete process.env.ALTIMATE_REVIEW_CONVENTIONS + const on = await reviewPullRequest({ cwd: dir, base: "main", head: "HEAD" }) + expect(on.ai?.conventions).toEqual([{ path: "CLAUDE.md", source: "claude_md", scope: "", chars: "Column names are snake_case.".length }]) + expect(on.ai?.input?.find((r) => r.path === "models/m.sql")?.conventions).toEqual(["CLAUDE.md"]) + expect(on.findings).toEqual(off.findings) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }, 60_000) +}) From de2c6b050b50a83efbce00e71e26f1f5d2b5e9da Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 02:07:37 +0530 Subject: [PATCH 02/18] fix(review): one comment for a convention broken the same way on several files - AI findings in one review that name the same convention path (the longest loaded path their title or body names) for the same issue (title without the file's own model and file names, trailing preposition dropped) on different files become one finding: the most severe, first on ties, with "The same applies to: `a.sql`, `b.sql`." in its body - applied in `runAiReview` after the verifier, only when conventions were given; findings that name no convention, name different ones, or sit on one file are unchanged - the core 0.9 output has no `cites` field, so the convention is read from the text the finder is asked to write; with core 0.10's `cites` the same grouping can key on it - tests: three files grouped with the most severe kept, unchanged cases, longest path, `runAiReview` with and without conventions Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-review.ts | 4 +- .../src/altimate/review/conventions.ts | 54 ++++++++++++ .../test/altimate/review-conventions.test.ts | 86 +++++++++++++++++++ 3 files changed, 143 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index 6bac7e74f3..f13342fd65 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -18,7 +18,7 @@ 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" -import { type Convention, type ConventionRecord, conventionRecords, renderConventions } from "./conventions" +import { type Convention, type ConventionRecord, conventionRecords, groupConventionFindings, renderConventions } from "./conventions" const log = Log.create({ service: "ai-review" }) @@ -1078,6 +1078,8 @@ export async function runAiReview(input: AiReviewInput): Promise findings = v.findings verifier = v.status } + // One comment for one convention broken the same way on several files. + if (input.conventions?.length) findings = groupConventionFindings(findings, input.conventions) return done(findings, { state: "ok", model: modelLabel, diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index 474c5975ab..14ee4fe81f 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -1,6 +1,7 @@ // altimate_change - new file: team conventions (repo review instructions) for the AI finder import YAML from "yaml" import { globToRegExp } from "./diff-filter" +import { type Finding, SEVERITY_ORDER } from "./finding" /** * Team conventions from the repository's guideline files, read from the BASE @@ -388,3 +389,56 @@ export interface ConventionRecord { export function conventionRecords(all: Convention[]): ConventionRecord[] { return all.map((c) => ({ path: c.path, source: c.source, scope: c.scope, ...(c.globs ? { globs: c.globs } : {}), chars: c.text.length })) } + +/** The convention a finding relies on: the longest loaded convention path its body or title names. */ +export function citedConvention(f: Pick, paths: string[]): string | undefined { + const text = `${f.title}\n${f.body}` + return paths.filter((p) => text.includes(p)).sort((a, b) => b.length - a.length)[0] +} + +/** A finding's title without the names of its own file, so one issue on several files reads the same. */ +function issueKey(f: Pick): string { + const base = f.file.split("/").pop() ?? f.file + const names = [f.model, base, base.replace(/\.[^.]+$/, "")].filter((n): n is string => !!n && n.length > 1) + let t = f.title.toLowerCase() + if (f.model && t.startsWith(f.model.toLowerCase() + ":")) t = t.slice(f.model.length + 1) + for (const n of names) t = t.split(n.toLowerCase()).join(" ") + // "… for " leaves a dangling preposition once the name is gone. + return t + .replace(/[^a-z0-9]+/g, " ") + .trim() + .replace(/(?:\s+(?:for|in|on|of|to|at))+$/, "") +} + +/** + * One comment per repeated convention finding (pure): AI findings in one review that name the + * same convention for the same issue (title without the file's own names) on different files + * become the first, most severe one, whose body lists the other files. Other findings are + * returned unchanged, in order. + */ +export function groupConventionFindings(findings: Finding[], conventions: Convention[]): Finding[] { + const paths = [...new Set(conventions.map((c) => c.path))] + if (!paths.length || findings.length < 2) return findings + const groups = new Map() + findings.forEach((f, i) => { + const cited = citedConvention(f, paths) + if (!cited) return + const key = `${cited}\u0000${issueKey(f)}` + groups.set(key, [...(groups.get(key) ?? []), i]) + }) + const replace = new Map() + const drop = new Set() + for (const idx of groups.values()) { + const files = new Set(idx.map((i) => findings[i].file)) + if (files.size < 2) continue + const lead = idx.reduce((a, b) => (SEVERITY_ORDER[findings[b].severity] > SEVERITY_ORDER[findings[a].severity] ? b : a)) + const others = [...new Set(idx.filter((i) => i !== lead).map((i) => findings[i].file))].filter((p) => p !== findings[lead].file) + replace.set(lead, { + ...findings[lead], + body: `${findings[lead].body}\n\nThe same applies to: ${others.map((p) => `\`${p}\``).join(", ")}.`, + }) + for (const i of idx) if (i !== lead) drop.add(i) + } + if (!drop.size) return findings + return findings.flatMap((f, i) => (drop.has(i) ? [] : [replace.get(i) ?? f])) +} diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index a385971c40..abdc21b9a9 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -6,6 +6,8 @@ import { execFileSync } from "node:child_process" import { CONVENTIONS_HEADING, appliesTo, + citedConvention, + groupConventionFindings, conventionSpecificity, conventionsFor, loadConventions, @@ -23,6 +25,7 @@ import { Dispatcher } from "../../src/altimate/native" import { LLM } from "../../src/session/llm" import { Provider } from "../../src/provider/provider" import { resolveAiSwitches } from "../../src/altimate/review/ai-switches" +import { makeFinding } from "../../src/altimate/review/finding" // Team conventions (repo review instructions) from the base branch for the AI finder. @@ -433,3 +436,86 @@ describe("reviewPullRequest end to end (AI dry run, no model call)", () => { } }, 60_000) }) + +describe("repeated convention findings become one comment", () => { + const conv: Convention[] = [ + { path: "models/CLAUDE.md", source: "claude_md", scope: "models", text: "Every model has a description." }, + { path: "CLAUDE.md", source: "claude_md", scope: "", text: "Snake case." }, + ] + const f = (file: string, model: string, title: string, body: string, severity: "warning" | "suggestion" = "suggestion") => + makeFinding({ + severity, + category: "sql_quality", + title: `${model}: ${title}`, + body, + file, + model, + startLine: 1, + endLine: 1, + confidence: "medium", + evidence: { tool: "ai-review", result: {} }, + ruleKey: `ai:sql_quality:${title}`, + rule: "ai-review:sql-quality", + }) + + test("same convention, same issue on three files: one finding listing the other files", () => { + const out = groupConventionFindings( + [ + f("models/a.sql", "fct_a", "Missing model description", "Per models/CLAUDE.md every model needs a description."), + f("models/b.sql", "fct_b", "Missing model description for fct_b", "models/CLAUDE.md: add a description.", "warning"), + f("models/c.sql", "fct_c", "missing model description", "See models/CLAUDE.md."), + f("models/a.sql", "fct_a", "Wrong join", "Unrelated defect."), + ], + conv, + ) + expect(out.map((x) => x.file)).toEqual(["models/b.sql", "models/a.sql"]) + expect(out[0].severity).toBe("warning") + expect(out[0].body).toEndWith("The same applies to: `models/a.sql`, `models/c.sql`.") + expect(out[1].title).toBe("fct_a: Wrong join") + }) + + test("different conventions, different issues, one file or no convention named: unchanged", () => { + const list = [ + f("models/a.sql", "a", "Missing model description", "Per models/CLAUDE.md."), + f("models/b.sql", "b", "Missing model description", "Per CLAUDE.md at the root."), + f("models/c.sql", "c", "Column not snake case", "Per models/CLAUDE.md."), + f("models/d.sql", "d", "Missing model description", "No convention named."), + f("models/e.sql", "e", "Missing model description", "No convention named either."), + ] + expect(groupConventionFindings(list, conv)).toEqual(list) + const sameFile = [f("models/a.sql", "a", "X", "models/CLAUDE.md"), f("models/a.sql", "a", "X", "models/CLAUDE.md line 2")] + expect(groupConventionFindings(sameFile, conv)).toEqual(sameFile) + expect(groupConventionFindings(list, [])).toEqual(list) + }) + + test("citedConvention prefers the longest path named", () => { + expect(citedConvention({ title: "t", body: "see models/CLAUDE.md" }, ["CLAUDE.md", "models/CLAUDE.md"])).toBe("models/CLAUDE.md") + expect(citedConvention({ title: "t", body: "see CLAUDE.md" }, ["CLAUDE.md", "models/CLAUDE.md"])).toBe("CLAUDE.md") + }) + + test("runAiReview groups the lane's findings when conventions were given", async () => { + spyOn(Provider, "defaultModel").mockResolvedValue({ providerID: "fake", modelID: "m" } as any) + spyOn(Provider, "getModel").mockResolvedValue({ providerID: "fake", id: "m", api: { npm: "x" }, cost: {} } as any) + const parsed = [ + { file: "models/a.sql", line: 1, category: "sql_quality", severity: "suggestion", title: "Missing description", body: "Per models/CLAUDE.md.", confidence: "medium" }, + { file: "models/b.sql", line: 1, category: "sql_quality", severity: "suggestion", title: "Missing description", body: "Per models/CLAUDE.md.", confidence: "medium" }, + ] + spyOn(Dispatcher, "call").mockImplementation((async (method: string) => + method === "altimate_core.review_ai_prompt" ? { success: true, data: { prompt: "SYSTEM" } } : { success: true, data: { findings: parsed } }) as any) + spyOn(LLM, "stream").mockImplementation(async () => ({ + fullStream: (async function* () {})(), + text: Promise.resolve("[x]"), + finishReason: Promise.resolve("stop"), + response: Promise.resolve({ messages: [] }), + totalUsage: Promise.resolve(undefined), + providerMetadata: Promise.resolve(undefined), + }) as any) + const files = [aiFile("models/a.sql"), aiFile("models/b.sql")] + const grouped = await runAiReview({ files, grounding: [], conventions: conv }) + expect(grouped.findings).toHaveLength(1) + expect(grouped.findings[0].body).toContain("The same applies to: `models/b.sql`.") + const plain = await runAiReview({ files, grounding: [] }) + expect(plain.findings).toHaveLength(2) + mock.restore() + }) +}) From e7245fdb8afb63f7ce056f11973e88e5497a55ef Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 16:03:59 +0530 Subject: [PATCH 03/18] fix(review): team conventions fail loudly on git errors and read every source as written - `loadConventions` no longer turns a git failure into "file absent": `showAtRef` already tells a missing path from a real error, and that error now fails the review, as the base-policy read of the same commit does, instead of silently dropping every convention - the base commit is listed once with `git ls-tree -r -z` (`listFilesAt`) and filtered to `.cursor/rules/` under each scope: paths are verbatim (no C-quoting of non-ASCII or special characters) and there is no per-directory subprocess; `lsTreeAtRef` is removed - `.mdc` frontmatter is parsed as YAML (inline comments, quoting, lists); Cursor's unquoted `globs: **/*.sql`, which is not valid YAML, falls back to the line reader, which now drops inline comments too - CodeRabbit `tone_instructions` is read from the document root, with `reviews.tone_instructions` as a fallback - the per-call budget covers the whole section: the TEAM CONVENTIONS heading, each entry's joining newline and the truncation marker - `conventionsFor` and `renderConventions` share one ranking, so the ordering rule cannot drift - the envelope's convention `source` is a `z.enum` of the nine sources - docs: manual Cursor rules are skipped; `tone_instructions` is read; the switch defaults comment says conventions are on by default outside the measured configuration - tests: git read and list failures reject; a non-ASCII rule name loads over git; YAML comments in both frontmatter forms; root and nested tone; rendered section within budget; unknown source rejected by the envelope schema Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 9 +- .../src/altimate/review/ai-switches.ts | 5 +- .../src/altimate/review/conventions.ts | 168 +++++++++++------- packages/opencode/src/altimate/review/git.ts | 10 -- packages/opencode/src/altimate/review/run.ts | 10 +- .../opencode/src/altimate/review/verdict.ts | 3 +- .../review-conventions/.coderabbit.yaml | 2 +- .../test/altimate/review-conventions.test.ts | 69 ++++++- 8 files changed, 186 insertions(+), 90 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 14344dee05..055e9115f1 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -656,10 +656,11 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne The repo's own review instructions go with each call, read from the base branch so a PR cannot change them: `.altimate/review.md`, `REVIEW.md`, `AGENTS.md` and `CLAUDE.md` (at the root and in each changed path's directories), - `.claude/CLAUDE.md`, `.cursor/rules/*.mdc`, `.cursorrules`, - `.github/copilot-instructions.md`, `.coderabbit.yaml` `path_instructions` and the - dbt/SQL/test sections of `CONTRIBUTING.md`, most specific first, up to 3,000 - characters per call (`ai.conventions: false` or `ALTIMATE_REVIEW_CONVENTIONS=0` + `.claude/CLAUDE.md`, `.cursor/rules/*.mdc` (rules with `globs` or `alwaysApply`; + manual rules with neither are skipped), `.cursorrules`, + `.github/copilot-instructions.md`, `.coderabbit.yaml` `path_instructions` and + `tone_instructions`, and the dbt/SQL/test sections of `CONTRIBUTING.md`, most + specific first, up to 3,000 characters per call (`ai.conventions: false` or `ALTIMATE_REVIEW_CONVENTIONS=0` turns this off). 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings diff --git a/packages/opencode/src/altimate/review/ai-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index fabdf55e03..bde6bb410b 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -25,8 +25,9 @@ export const AI_SWITCH_ENV: Record = { /** * 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`. + * together (wider input, related files batched, context cards, the verifier), plus the team + * conventions (`conventions`), on by default on their own, outside that measurement. Each one + * is opt-out with `ai: { : false }` or its env variable set to `0`. */ export const AI_SWITCH_DEFAULTS: AiSwitches = { coverage: true, diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index 14ee4fe81f..096222fadd 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -10,7 +10,7 @@ import { type Finding, SEVERITY_ORDER } from "./finding" * Sources: `.altimate/review.md` (or `.altimate/REVIEW.md`); `REVIEW.md`, `AGENTS.md`, * `CLAUDE.md` and `.claude/CLAUDE.md` at the root and at every ancestor directory of a * changed path; `.coderabbit.yaml` (`reviews.path_instructions[]`, one convention per - * entry scoped by its glob, plus `reviews.tone_instructions`); `.cursor/rules/*.mdc` + * entry scoped by its glob, plus the document-level `tone_instructions`); `.cursor/rules/*.mdc` * (frontmatter `globs` / `alwaysApply`; rules with neither are manual and skipped); * `.cursorrules`; `.github/copilot-instructions.md`; `CONTRIBUTING.md` cut to its * dbt/SQL/test/naming sections. @@ -21,16 +21,19 @@ import { type Finding, SEVERITY_ORDER } from "./finding" * finder's input is unchanged. */ -export type ConventionSource = - | "altimate" - | "review_md" - | "agents_md" - | "claude_md" - | "coderabbit" - | "cursor" - | "cursorrules" - | "copilot" - | "contributing" +/** Where a convention came from; the envelope schema accepts only these. */ +export const CONVENTION_SOURCES = [ + "altimate", + "review_md", + "agents_md", + "claude_md", + "coderabbit", + "cursor", + "cursorrules", + "copilot", + "contributing", +] as const +export type ConventionSource = (typeof CONVENTION_SOURCES)[number] export interface Convention { /** The repo-relative file it came from (what a finding cites). */ @@ -63,8 +66,10 @@ const CODERABBIT_FILES = [".coderabbit.yaml", ".coderabbit.yml"] const CONTRIBUTING_FILES = ["CONTRIBUTING.md", ".github/CONTRIBUTING.md", "docs/CONTRIBUTING.md"] const CONTRIBUTING_HEADING = /dbt|model|sql|test|yml|naming|macro|incremental/i +const TRUNCATED = "\n… (truncated)" + function cut(text: string, max: number): string { - return text.length > max ? text.slice(0, max) + "\n… (truncated)" : text + return text.length > max ? text.slice(0, max) + TRUNCATED : text } function depth(scope: string): number { @@ -116,34 +121,75 @@ function splitTopLevel(list: string): string[] { return out } -/** Frontmatter of a Cursor `.mdc` rule: `globs` (string, comma list or list), `alwaysApply`, and the body. */ -export function parseMdc(text: string): { globs: string[]; alwaysApply: boolean; body: string } { - const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text) - if (!m) return { globs: [], alwaysApply: false, body: text.trim() } +/** A frontmatter value without an inline YAML comment, and without its quotes. */ +function frontmatterValue(raw: string): string { + const v = raw.trim() + const q = /^(["'])(.*?)\1/.exec(v) + if (q) return q[2].trim() + return v.replace(/\s+#.*$/, "").trim() +} + +/** `globs` as Cursor writes it: a string (comma list, optionally `[…]`) or a YAML list. */ +function globList(value: unknown): string[] { + if (Array.isArray(value)) return value.flatMap((v) => (typeof v === "string" ? globList(v) : [])) + if (typeof value !== "string") return [] + return splitTopLevel(value.trim().replace(/^\[|\]$/g, "")) + .map((g) => g.trim().replace(/^["']|["']$/g, "").trim()) + .filter(Boolean) +} + +/** Frontmatter lines read one by one: for Cursor's unquoted globs (`globs: **\/*.sql`), which are not valid YAML. */ +function parseFrontmatterLines(text: string): { globs: string[]; alwaysApply: boolean } { const globs: string[] = [] let alwaysApply = false let inGlobList = false - const unquote = (s: string) => s.trim().replace(/^["']|["']$/g, "").trim() - for (const line of m[1].split(/\r?\n/)) { + for (const line of text.split(/\r?\n/)) { const item = /^\s+-\s*(.+)$/.exec(line) if (inGlobList && item) { - globs.push(unquote(item[1])) + globs.push(...globList(frontmatterValue(item[1]))) continue } inGlobList = false const kv = /^(\w+)\s*:\s*(.*)$/.exec(line) if (!kv) continue const [, key, raw] = kv - if (key === "alwaysApply") alwaysApply = /^true$/i.test(raw.trim()) + const value = frontmatterValue(raw) + if (key === "alwaysApply") alwaysApply = /^true$/i.test(value) if (key !== "globs") continue - const value = raw.trim() if (!value) inGlobList = true - else globs.push(...splitTopLevel(value.replace(/^\[|\]$/g, "")).map(unquote)) + else globs.push(...globList(value)) + } + return { globs, alwaysApply } +} + +/** + * Frontmatter of a Cursor `.mdc` rule: `globs` (string, comma list or list), `alwaysApply`, and the + * body. Parsed as YAML (comments, quoting, lists); frontmatter that is not valid YAML, such as + * Cursor's unquoted `globs: **\/*.sql`, is read line by line. + */ +export function parseMdc(text: string): { globs: string[]; alwaysApply: boolean; body: string } { + const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text) + if (!m) return { globs: [], alwaysApply: false, body: text.trim() } + const body = text.slice(m[0].length).trim() + let doc: unknown + try { + doc = YAML.parse(m[1]) + } catch { + return { ...parseFrontmatterLines(m[1]), body } + } + const fm = doc && typeof doc === "object" && !Array.isArray(doc) ? (doc as Record) : {} + const always = fm.alwaysApply + return { + globs: globList(fm.globs), + alwaysApply: always === true || (typeof always === "string" && /^true$/i.test(always.trim())), + body, } - return { globs: globs.filter(Boolean), alwaysApply, body: text.slice(m[0].length).trim() } } -/** `.coderabbit.yaml`: one convention per `reviews.path_instructions[]` entry, plus `reviews.tone_instructions`. */ +/** + * `.coderabbit.yaml`: one convention per `reviews.path_instructions[]` entry, plus the + * document-level `tone_instructions` (`reviews.tone_instructions` when the root has none). + */ export function parseCoderabbit(text: string, path: string): Convention[] { let doc: unknown try { @@ -151,12 +197,13 @@ export function parseCoderabbit(text: string, path: string): Convention[] { } catch { return [] } - const reviews = (doc as { reviews?: Record } | undefined)?.reviews - if (!reviews || typeof reviews !== "object") return [] + if (!doc || typeof doc !== "object") return [] + const root = doc as { reviews?: unknown; tone_instructions?: unknown } + const reviews = root.reviews && typeof root.reviews === "object" ? (root.reviews as Record) : {} const out: Convention[] = [] - const tone = reviews.tone_instructions - if (typeof tone === "string" && tone.trim()) - out.push({ path, source: "coderabbit", scope: "", text: cut(`Tone: ${tone.trim()}`, CONVENTION_FILE_CHARS) }) + const nonEmpty = (v: unknown): v is string => typeof v === "string" && !!v.trim() + const tone = nonEmpty(root.tone_instructions) ? root.tone_instructions : reviews.tone_instructions + if (nonEmpty(tone)) out.push({ path, source: "coderabbit", scope: "", text: cut(`Tone: ${tone.trim()}`, CONVENTION_FILE_CHARS) }) const entries = Array.isArray(reviews.path_instructions) ? reviews.path_instructions : [] for (const e of entries) { const glob = (e as { path?: unknown })?.path @@ -192,10 +239,10 @@ export function sliceContributing(text: string, max = CONTRIBUTING_CHARS): strin } export interface LoadConventionsInput { - /** Reads a repo-relative file at the base commit; undefined when absent. */ + /** Reads a repo-relative file at the base commit; undefined when absent, throws when git fails. */ readBase: (rel: string) => Promise - /** Lists the files under a repo-relative directory at the base commit (recursive, repo-relative). */ - listBase?: (dir: string) => Promise + /** Every file at the base commit (repo-relative), listed once; throws when git fails. */ + listBase?: () => Promise /** Every path the PR changes (repo-relative): their ancestor directories are searched for scoped files. */ changedPaths: string[] } @@ -203,11 +250,12 @@ export interface LoadConventionsInput { /** * Load the team conventions from the base commit (see the module comment for * the sources). Each file is cut to 4,000 characters; root files come before - * deeper ones. Never throws: an unreadable file is skipped. + * deeper ones. A file absent at the base commit is skipped; a git failure + * throws, as the base-policy read does, so it cannot pass for "no conventions". */ export async function loadConventions(input: LoadConventionsInput): Promise { - const read = (rel: string) => input.readBase(rel).catch(() => undefined) - const list = async (dir: string) => (input.listBase ? ((await input.listBase(dir).catch(() => undefined)) ?? []) : []) + const read = input.readBase + const baseFiles = input.listBase ? await input.listBase() : [] const scopes = scopesOf(input.changedPaths) const plain = (path: string, source: ConventionSource, scope: string, text: string | undefined): Convention[] => text?.trim() ? [{ path, source, scope, text: cut(text.trim(), CONVENTION_FILE_CHARS) }] : [] @@ -227,8 +275,8 @@ export async function loadConventions(input: LoadConventionsInput): Promise p.endsWith(".mdc")).sort() + const dir = join(scope, ".cursor/rules") + "/" + const files = baseFiles.filter((p) => p.startsWith(dir) && p.endsWith(".mdc")).sort() for (const p of files) { const text = await read(p) if (!text) continue @@ -303,9 +351,9 @@ export function conventionSpecificity(c: Convention, file: string): number | und return scopeLen + Math.max(...matched.map(literalLength)) } -/** What a convention entry costs in a call: its heading and text. */ +/** What a convention entry costs in a call: its `### path (applies to …)` heading, its text and the joining newline. */ function entryChars(c: Convention): number { - return c.path.length + appliesTo(c).length + 20 + c.text.length + return c.path.length + appliesTo(c).length + 21 + c.text.length } /** Take conventions in order within `budget` characters; the first one is cut to fit when it alone is over. */ @@ -318,7 +366,8 @@ function withinBudget(ordered: Convention[], budget: number): Convention[] { out.push(c) used += cost } else if (!out.length) { - const room = budget - (cost - c.text.length) + // The truncation marker counts toward the budget too. + const room = budget - (cost - c.text.length) - TRUNCATED.length if (room > 200) { out.push({ ...c, text: cut(c.text, room) }) used = budget @@ -328,17 +377,23 @@ function withinBudget(ordered: Convention[], budget: number): Convention[] { return out } +/** The conventions that apply to any of `files`, by their best specificity, most specific first (pure; ties keep load order). */ +function rankConventions(all: Convention[], files: string[]): Convention[] { + const best = new Map() + all.forEach((c, i) => { + for (const f of files) { + const s = conventionSpecificity(c, f) + if (s === undefined) continue + const prev = best.get(c) + if (!prev || s > prev.s) best.set(c, { s, i }) + } + }) + return [...best.entries()].sort((a, b) => b[1].s - a[1].s || a[1].i - b[1].i).map(([c]) => c) +} + /** The conventions that apply to `file`, most specific first, within `budget` characters (pure; ties keep load order). */ export function conventionsFor(all: Convention[], file: string, budget = CONVENTIONS_CALL_BUDGET): Convention[] { - const scored = all.flatMap((c, i) => { - const s = conventionSpecificity(c, file) - return s === undefined ? [] : [{ c, s, i }] - }) - scored.sort((a, b) => b.s - a.s || a.i - b.i) - return withinBudget( - scored.map((x) => x.c), - budget, - ) + return withinBudget(rankConventions(all, [file]), budget) } /** What a convention applies to, in words: its globs, its directory, or the whole repo. */ @@ -353,7 +408,8 @@ export const CONVENTIONS_HEADING = /** * The TEAM CONVENTIONS section for one finder call (pure): the conventions that apply to any of - * `files`, most specific first, within `budget` characters for the whole call. Empty text when none. + * `files`, most specific first, within `budget` characters for the whole section, heading + * included. Empty text when none. */ export function renderConventions( all: Convention[], @@ -361,17 +417,7 @@ export function renderConventions( budget = CONVENTIONS_CALL_BUDGET, ): { text: string; paths: string[] } { if (!all.length) return { text: "", paths: [] } - const best = new Map() - all.forEach((c, i) => { - for (const f of files) { - const s = conventionSpecificity(c, f) - if (s === undefined) continue - const prev = best.get(c) - if (!prev || s > prev.s) best.set(c, { s, i }) - } - }) - const ordered = [...best.entries()].sort((a, b) => b[1].s - a[1].s || a[1].i - b[1].i).map(([c]) => c) - const picked = withinBudget(ordered, budget) + const picked = withinBudget(rankConventions(all, files), budget - CONVENTIONS_HEADING.length) if (!picked.length) return { text: "", paths: [] } const entries = picked.map((c) => `\n### ${c.path} (applies to ${appliesTo(c)})\n${c.text}`) return { text: [CONVENTIONS_HEADING, ...entries].join("\n"), paths: [...new Set(picked.map((c) => c.path))] } diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index e8a08bca89..ccbbfb6f7d 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -173,16 +173,6 @@ export async function gitRepoRoot(cwd: string): Promise { } } -/** Tracked files under the repo-relative directory `dir` at `ref`, repo-root relative (recursive); undefined when git can't list them. */ -export async function lsTreeAtRef(cwd: string, ref: string, dir: string): Promise { - try { - const out = await git(["ls-tree", "-r", "--full-tree", "--name-only", ref, "--", `:(top)${dir.replace(/\/+$/, "")}/`], cwd) - return out.split("\n").filter(Boolean) - } catch { - return undefined - } -} - /** Every tracked file at `ref` (default HEAD), repo-root relative; undefined when git can't list it. */ export async function listFilesAt(cwd: string, ref?: string): Promise { try { diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 8f952b03c7..0496eca026 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -19,7 +19,6 @@ import { resolveCommit, commitParents, showAtRef, - lsTreeAtRef, } from "./git" import { makeCompiledResolver, dbtProjectName, dbtProjectLayout } from "./compiled" import { scopeToProject } from "./diff-filter" @@ -480,12 +479,17 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise : makeCompiledResolver({ cwd: dbtRootReal, projectName, pathPrefix }) // Repo review instructions come from the base commit, like the policy, so a PR cannot - // change the conventions it is reviewed under; only when the AI lane runs. + // change the conventions it is reviewed under; only when the AI lane runs. A git failure + // reading that commit fails the review, as it does for the policy read just before. const conventions = aiOn && aiSwitches.conventions && resolved ? await loadConventions({ readBase: (rel) => showAtRef(gitRoot, resolved.sha, rel), - listBase: (dir) => lsTreeAtRef(gitRoot, resolved.sha, dir), + listBase: async () => { + const files = await listFilesAt(gitRoot, resolved.sha) + if (!files) throw new Error(`cannot list the files of the base commit ${resolved.sha} for the team conventions`) + return files + }, changedPaths: opts.prFiles ?? collected.map((f) => f.path), }) : [] diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index bab9dfc6b5..52db97e55c 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -2,6 +2,7 @@ import z from "zod" import { createHmac, createHash } from "node:crypto" import { Finding, ReviewCategory, Severity, catalogRuleId, findingOrigin, normalizeRuleId } from "./finding" import { Rubric, DEFAULT_RUBRIC, blockingCategories } from "./rubric" +import { CONVENTION_SOURCES } from "./conventions" /** * The verdict contract — the signed, replayable artifact that is altimate's @@ -296,7 +297,7 @@ export const VerdictEnvelope = z.object({ .array( z.object({ path: z.string(), - source: z.string(), + source: z.enum(CONVENTION_SOURCES), scope: z.string(), globs: z.array(z.string()).optional(), chars: z.number().int().nonnegative(), diff --git a/packages/opencode/test/altimate/fixtures/review-conventions/.coderabbit.yaml b/packages/opencode/test/altimate/fixtures/review-conventions/.coderabbit.yaml index 1e19a7c0e3..3b20286329 100644 --- a/packages/opencode/test/altimate/fixtures/review-conventions/.coderabbit.yaml +++ b/packages/opencode/test/altimate/fixtures/review-conventions/.coderabbit.yaml @@ -1,6 +1,6 @@ language: en-US +tone_instructions: "Be brief; name the column." reviews: - tone_instructions: "Be brief; name the column." path_instructions: - path: "models/staging/**/*.sql" instructions: | diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index abdc21b9a9..0a1c7c414b 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -11,13 +11,15 @@ import { conventionSpecificity, conventionsFor, loadConventions, + parseCoderabbit, parseMdc, renderConventions, sliceContributing, type Convention, } from "../../src/altimate/review/conventions" import { planAiInput, runAiReview, type AiReviewFile, type AiReviewInput } from "../../src/altimate/review/ai-review" -import { lsTreeAtRef, showAtRef } from "../../src/altimate/review/git" +import { listFilesAt, showAtRef } from "../../src/altimate/review/git" +import { VerdictEnvelope } from "../../src/altimate/review/verdict" 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" @@ -51,7 +53,7 @@ async function fixtureBase() { reads.push(rel) return files.includes(rel) ? fs.readFile(path.join(FIXTURE, rel), "utf8") : undefined }, - listBase: async (dir: string) => files.filter((f) => f.startsWith(dir + "/")), + listBase: async () => files, } } @@ -114,15 +116,22 @@ describe("loadConventions (fixture as the base commit)", () => { ]) }) - test("per-file cap of 4,000 characters; unreadable files are skipped", async () => { + test("per-file cap of 4,000 characters; absent files are skipped", async () => { const all = await loadConventions({ - readBase: async (rel) => (rel === "AGENTS.md" ? "x".repeat(9_000) : rel === "REVIEW.md" ? Promise.reject(new Error("boom")) : undefined), + readBase: async (rel) => (rel === "AGENTS.md" ? "x".repeat(9_000) : undefined), changedPaths: ["models/a.sql"], }) expect(all.map((c) => c.path)).toEqual(["AGENTS.md"]) expect(all[0].text.startsWith("x".repeat(4_000) + "\n… (truncated)")).toBe(true) }) + test("a git failure reading or listing the base commit throws instead of passing for no conventions", async () => { + const boom = async (rel: string) => (rel === "REVIEW.md" ? Promise.reject(new Error("boom")) : undefined) + await expect(loadConventions({ readBase: boom, changedPaths: ["models/a.sql"] })).rejects.toThrow("boom") + const noList = async (): Promise => Promise.reject(new Error("ls-tree failed")) + await expect(loadConventions({ readBase: async () => undefined, listBase: noList, changedPaths: [] })).rejects.toThrow("ls-tree failed") + }) + test(".altimate/review.md, .claude/CLAUDE.md, .cursorrules and copilot instructions apply to the whole repo", async () => { const files: Record = { ".altimate/review.md": "Prefer qualify over subqueries.", @@ -150,6 +159,38 @@ describe("parsing helpers", () => { expect(parseMdc("no frontmatter")).toEqual({ globs: [], alwaysApply: false, body: "no frontmatter" }) }) + test("parseMdc: inline YAML comments, in valid YAML and in Cursor's unquoted-glob form", () => { + expect(parseMdc('---\nglobs: "models/**/*.sql" # marts only\nalwaysApply: false # manual\n---\nb')).toEqual({ + globs: ["models/**/*.sql"], + alwaysApply: false, + body: "b", + }) + expect(parseMdc("---\nglobs:\n - a/*.sql # first\n - b/** # second\n---\nb").globs).toEqual(["a/*.sql", "b/**"]) + // `**/*.sql` unquoted is not valid YAML (an alias): read line by line, comments dropped. + expect(parseMdc("---\nglobs: **/*.sql # all sql\nalwaysApply: true # always\n---\nb")).toEqual({ + globs: ["**/*.sql"], + alwaysApply: true, + body: "b", + }) + }) + + test("parseCoderabbit: tone_instructions at the document root, or under reviews when the root has none", () => { + expect(parseCoderabbit("tone_instructions: Be terse.\nreviews:\n path_instructions: []\n", ".coderabbit.yaml").map((c) => c.text)).toEqual([ + "Tone: Be terse.", + ]) + expect(parseCoderabbit("tone_instructions: Root.\n", ".coderabbit.yaml").map((c) => c.text)).toEqual(["Tone: Root."]) + expect(parseCoderabbit("reviews:\n tone_instructions: Nested.\n", ".coderabbit.yaml").map((c) => c.text)).toEqual(["Tone: Nested."]) + expect( + parseCoderabbit("tone_instructions: Root.\nreviews:\n tone_instructions: Nested.\n", ".coderabbit.yaml").map((c) => c.text), + ).toEqual(["Tone: Root."]) + }) + + test("the envelope accepts only the known convention sources", () => { + const source = VerdictEnvelope.shape.ai.unwrap().shape.conventions.unwrap().element.shape.source + expect(source.safeParse("claude_md").success).toBe(true) + expect(source.safeParse("bogus").success).toBe(false) + }) + test("sliceContributing: matching sections and their subsections, capped", () => { const text = "# Intro\nhi\n## SQL style\nlower case\n### Joins\nexplicit\n## Release\nno\n## Naming\nsnake" expect(sliceContributing(text)).toBe("## SQL style\nlower case\n### Joins\nexplicit\n## Naming\nsnake") @@ -213,7 +254,10 @@ describe("scoping and budget", () => { expect(r.paths).toEqual([".coderabbit.yaml", ".cursor/rules/dbt-models.mdc", "CLAUDE.md", "CONTRIBUTING.md"]) const marts = renderConventions(all, ["models/marts/fct_orders.sql"]) expect(marts.text.indexOf("### models/marts/CLAUDE.md (applies to models/marts/)")).toBeLessThan(marts.text.indexOf("### CLAUDE.md")) - expect(renderConventions(all, ["models/marts/fct_orders.sql"], 400).text.length).toBeLessThan(400 + CONVENTIONS_HEADING.length + 10) + // The budget covers the whole section, heading and truncation marker included. + for (const budget of [400, 600, 3_000]) expect(renderConventions(all, ["models/marts/fct_orders.sql"], budget).text.length).toBeLessThanOrEqual(budget) + const big: Convention = { path: "AGENTS.md", source: "agents_md", scope: "", text: "z".repeat(5_000) } + expect(renderConventions([big], ["a.sql"], 1_000).text.length).toBeLessThanOrEqual(1_000) expect(renderConventions([], ["a.sql"])).toEqual({ text: "", paths: [] }) expect(appliesTo({ scope: "", globs: ["a/**", "b/*.sql"] })).toBe("a/**, b/*.sql") }) @@ -224,10 +268,12 @@ describe("loadConventions over git: the base commit, never the PR's edits", () = const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } }).toString() - test("showAtRef + lsTreeAtRef at the merge base read the base versions and the base Cursor rules", async () => { + test("showAtRef + listFilesAt at the merge base read the base versions and the base Cursor rules", async () => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), "review-conventions-")) try { await fs.cp(FIXTURE, dir, { recursive: true }) + // A rule whose name git would C-quote without -z. + await fs.writeFile(path.join(dir, ".cursor/rules/naïve rule.mdc"), "---\nalwaysApply: true\n---\nNon-ASCII name.\n") git(dir, "init", "-q", "-b", "main") git(dir, "add", "-A") git(dir, "commit", "-q", "-m", "base") @@ -239,12 +285,19 @@ describe("loadConventions over git: the base commit, never the PR's edits", () = git(dir, "commit", "-q", "-m", "pr") const all = await loadConventions({ readBase: (rel) => showAtRef(dir, base, rel), - listBase: (d) => lsTreeAtRef(dir, base, d), + listBase: async () => (await listFilesAt(dir, base))!, changedPaths: CHANGED, }) - expect(all.map((c) => c.path)).toEqual((await loadFixture()).map((c) => c.path)) + const fixturePaths = (await loadFixture()).map((c) => c.path) + expect(all.map((c) => c.path)).toEqual([ + ...fixturePaths.filter((p) => p !== "CONTRIBUTING.md"), + ".cursor/rules/naïve rule.mdc", + "CONTRIBUTING.md", + ]) expect(all.find((c) => c.path === "CLAUDE.md")!.text).toContain("snake_case") expect(all.some((c) => c.text.includes("Added by the PR"))).toBe(false) + // An unreadable base commit is an error, not "no conventions". + await expect(loadConventions({ readBase: (rel) => showAtRef(dir, "no-such-ref", rel), changedPaths: CHANGED })).rejects.toThrow() } finally { await fs.rm(dir, { recursive: true, force: true }) } From f6d334a59e39062f978ebb4223e2cb111d3cdb30 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 16:04:06 +0530 Subject: [PATCH 04/18] fix(review): convention grouping keeps distinct same-file findings; replay groups too - `groupConventionFindings` folds only the first finding on each file other than the lead's; further findings on the lead's file (or on an already-folded file) may be distinct issues and stay as they are - replay mode (`ALTIMATE_REVIEW_AI_REPLAY`) records `ai.conventions` and groups the replayed findings like a live run - tests: same-file findings survive grouping; replay records and groups; the spies in the grouping tests are restored in `afterEach`, so a failing assertion cannot leak them Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-review.ts | 10 ++++- .../src/altimate/review/conventions.ts | 13 ++++--- .../test/altimate/review-conventions.test.ts | 37 ++++++++++++++++++- 3 files changed, 53 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-review.ts b/packages/opencode/src/altimate/review/ai-review.ts index f13342fd65..7f961f10c1 100644 --- a/packages/opencode/src/altimate/review/ai-review.ts +++ b/packages/opencode/src/altimate/review/ai-review.ts @@ -1025,7 +1025,15 @@ export async function runAiReview(input: AiReviewInput): Promise if (!files.length && (dryRun || !replay)) return done([], { state: "skipped", reason: "no changed dbt files to review" }) // Dry run wins over replay: a replayed envelope would still reach the verifier, a model call. if (dryRun) return done([], { state: "skipped", reason: "dry run (ALTIMATE_REVIEW_AI_DRYRUN=1): no model call" }) - if (replay) return runAiReplay(input, replay) + if (replay) { + // The replayed findings get the same convention record and grouping as a live run. + const r = await runAiReplay(input, replay) + if (!input.conventions?.length) return r + return { + findings: groupConventionFindings(r.findings, input.conventions), + status: { ...r.status, conventions: conventionRecords(input.conventions) }, + } + } let modelLabel: string | undefined try { diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index 096222fadd..2a531f7d80 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -459,8 +459,9 @@ function issueKey(f: Pick): string { /** * One comment per repeated convention finding (pure): AI findings in one review that name the * same convention for the same issue (title without the file's own names) on different files - * become the first, most severe one, whose body lists the other files. Other findings are - * returned unchanged, in order. + * become the first, most severe one, whose body lists the other files. Only one finding per + * other file is folded in; further findings on the lead's file or on an already-folded file + * may be distinct issues and stay. Other findings are returned unchanged, in order. */ export function groupConventionFindings(findings: Finding[], conventions: Convention[]): Finding[] { const paths = [...new Set(conventions.map((c) => c.path))] @@ -478,12 +479,14 @@ export function groupConventionFindings(findings: Finding[], conventions: Conven const files = new Set(idx.map((i) => findings[i].file)) if (files.size < 2) continue const lead = idx.reduce((a, b) => (SEVERITY_ORDER[findings[b].severity] > SEVERITY_ORDER[findings[a].severity] ? b : a)) - const others = [...new Set(idx.filter((i) => i !== lead).map((i) => findings[i].file))].filter((p) => p !== findings[lead].file) + // The first finding on each file other than the lead's. + const folded = new Map() + for (const i of idx) if (findings[i].file !== findings[lead].file && !folded.has(findings[i].file)) folded.set(findings[i].file, i) replace.set(lead, { ...findings[lead], - body: `${findings[lead].body}\n\nThe same applies to: ${others.map((p) => `\`${p}\``).join(", ")}.`, + body: `${findings[lead].body}\n\nThe same applies to: ${[...folded.keys()].map((p) => `\`${p}\``).join(", ")}.`, }) - for (const i of idx) if (i !== lead) drop.add(i) + for (const i of folded.values()) drop.add(i) } if (!drop.size) return findings return findings.flatMap((f, i) => (drop.has(i) ? [] : [replace.get(i) ?? f])) diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index 0a1c7c414b..bc55e8462f 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -491,6 +491,7 @@ describe("reviewPullRequest end to end (AI dry run, no model call)", () => { }) describe("repeated convention findings become one comment", () => { + afterEach(() => mock.restore()) const conv: Convention[] = [ { path: "models/CLAUDE.md", source: "claude_md", scope: "models", text: "Every model has a description." }, { path: "CLAUDE.md", source: "claude_md", scope: "", text: "Snake case." }, @@ -569,6 +570,40 @@ describe("repeated convention findings become one comment", () => { expect(grouped.findings[0].body).toContain("The same applies to: `models/b.sql`.") const plain = await runAiReview({ files, grounding: [] }) expect(plain.findings).toHaveLength(2) - mock.restore() + }) + + test("same-file findings are not folded: one finding per other file joins the lead", () => { + const list = [ + f("models/a.sql", "fct_a", "Missing model description", "Per models/CLAUDE.md, line 1.", "warning"), + f("models/a.sql", "fct_a", "Missing model description", "Per models/CLAUDE.md, the second model in the file."), + f("models/b.sql", "fct_b", "Missing model description", "Per models/CLAUDE.md."), + ] + const out = groupConventionFindings(list, conv) + expect(out.map((x) => x.file)).toEqual(["models/a.sql", "models/a.sql"]) + expect(out[0].body).toEndWith("The same applies to: `models/b.sql`.") + expect(out[1]).toEqual(list[1]) + }) + + test("replay mode records the conventions and groups the replayed findings", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "review-conventions-replay-")) + const saved = process.env.ALTIMATE_REVIEW_AI_REPLAY + try { + const stored = [ + f("models/a.sql", "fct_a", "Missing model description", "Per models/CLAUDE.md."), + f("models/b.sql", "fct_b", "Missing model description", "Per models/CLAUDE.md."), + ] + const file = path.join(dir, "envelope.json") + await fs.writeFile(file, JSON.stringify({ findings: stored, ai: { state: "ok" } })) + process.env.ALTIMATE_REVIEW_AI_REPLAY = file + const res = await runAiReview({ files: [aiFile("models/a.sql"), aiFile("models/b.sql")], grounding: [], conventions: conv }) + expect(res.status.replayed).toBe(true) + expect(res.status.conventions?.map((c) => c.path)).toEqual(["models/CLAUDE.md", "CLAUDE.md"]) + expect(res.findings).toHaveLength(1) + expect(res.findings[0].body).toContain("The same applies to: `models/b.sql`.") + } finally { + if (saved === undefined) delete process.env.ALTIMATE_REVIEW_AI_REPLAY + else process.env.ALTIMATE_REVIEW_AI_REPLAY = saved + await fs.rm(dir, { recursive: true, force: true }) + } }) }) From 61f83ad17407e5db3993e96e716c208593d7be87 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:29:48 +0530 Subject: [PATCH 05/18] fix(review): convention grouping keeps folded findings in the envelope `groupConventionFindings` deleted every folded finding and kept only the lead, whose body listed the other files. Their lines, bodies and suggestions were lost from the envelope (SARIF, audit, replay), and since the fingerprint ignores the body, a file folded into an already-posted lead on a later push was never posted at all. - Folded findings stay, in place, with `groupedInto: ` (a new optional `Finding` field). - `format.ts` collapses them: no inline comment and no summary line of their own while their lead is inline-eligible and not yet on the PR. The lead's comment carries their finding markers, so the next run counts them as posted. Once the lead is on the PR, a newly folded finding posts alone. - The lead is picked deterministically: severity, then path, then line. - The grouping key adds the finding's category, so the same generic title in two categories is not folded. - Replay strips `groupedInto` and the lead's "The same applies to" line, so re-grouping a replayed envelope does not repeat it. Changed expectations: the four grouping tests that asserted the folded findings were removed now assert they are kept with `groupedInto` (the reported defect). Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-replay.ts | 7 +- .../src/altimate/review/conventions.ts | 34 +++-- .../opencode/src/altimate/review/finding.ts | 4 + .../opencode/src/altimate/review/format.ts | 43 +++++- .../test/altimate/review-conventions.test.ts | 123 +++++++++++++++++- 5 files changed, 184 insertions(+), 27 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-replay.ts b/packages/opencode/src/altimate/review/ai-replay.ts index 1c68425a05..0abf274014 100644 --- a/packages/opencode/src/altimate/review/ai-replay.ts +++ b/packages/opencode/src/altimate/review/ai-replay.ts @@ -151,13 +151,14 @@ export function replayFindings(raw: unknown): ReplayedLane { /** A kept finding close to how the generator returned it: no verification record, body suffix, * tier, origin, or the orchestrator's `preExisting` / `evidenceLine` (re-derived on the next run). */ function unverify(f: Finding): Finding { - const { tier: _tier, origin: _origin, preExisting: _pre, evidenceLine: _line, ...rest } = f + const { tier: _tier, origin: _origin, preExisting: _pre, evidenceLine: _line, groupedInto: _grouped, ...rest } = f + // Convention grouping runs again on replay (after the verifier): drop the lead's list of the other files. + let body = f.body.replace(/\n\nThe same applies to: [^\n]*\.$/, "") const prior = f.evidence?.result - if (!prior || typeof prior !== "object") return rest + if (!prior || typeof prior !== "object") return { ...rest, body } const { verification, ...result } = prior as Record & { verification?: { rule?: string; evidence?: string } } - let body = f.body const suffix = verification?.rule === "verified" && verification.evidence ? `\n\nVerified: ${verification.evidence}` : "" if (suffix && body.endsWith(suffix)) body = body.slice(0, -suffix.length) return { ...rest, body, evidence: { tool: "ai-review", result } } diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index 2a531f7d80..ecae5980e2 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -458,36 +458,46 @@ function issueKey(f: Pick): string { /** * One comment per repeated convention finding (pure): AI findings in one review that name the - * same convention for the same issue (title without the file's own names) on different files - * become the first, most severe one, whose body lists the other files. Only one finding per - * other file is folded in; further findings on the lead's file or on an already-folded file - * may be distinct issues and stay. Other findings are returned unchanged, in order. + * same convention for the same issue (same category, title without the file's own names) on + * different files are covered by one lead: the most severe, then the first by path and line, + * whose body lists the other files. Only the first finding on each other file is folded in; + * further findings on the lead's file or on an already-folded file may be distinct issues and + * stay. Folded findings are kept, in place and unchanged but for `groupedInto` (the lead's id), + * so the envelope keeps their lines; the renderer collapses them into the lead's comment. */ export function groupConventionFindings(findings: Finding[], conventions: Convention[]): Finding[] { const paths = [...new Set(conventions.map((c) => c.path))] if (!paths.length || findings.length < 2) return findings const groups = new Map() findings.forEach((f, i) => { + if (f.groupedInto) return const cited = citedConvention(f, paths) if (!cited) return - const key = `${cited}\u0000${issueKey(f)}` + const key = `${cited}\u0000${f.category}\u0000${issueKey(f)}` groups.set(key, [...(groups.get(key) ?? []), i]) }) const replace = new Map() - const drop = new Set() for (const idx of groups.values()) { const files = new Set(idx.map((i) => findings[i].file)) if (files.size < 2) continue - const lead = idx.reduce((a, b) => (SEVERITY_ORDER[findings[b].severity] > SEVERITY_ORDER[findings[a].severity] ? b : a)) - // The first finding on each file other than the lead's. + const order = [...idx].sort( + (a, b) => + SEVERITY_ORDER[findings[b].severity] - SEVERITY_ORDER[findings[a].severity] || + findings[a].file.localeCompare(findings[b].file) || + (findings[a].startLine ?? 0) - (findings[b].startLine ?? 0) || + a - b, + ) + const lead = order[0] + // The first finding (by path and line) on each file other than the lead's. const folded = new Map() - for (const i of idx) if (findings[i].file !== findings[lead].file && !folded.has(findings[i].file)) folded.set(findings[i].file, i) + for (const i of [...idx].sort((a, b) => findings[a].file.localeCompare(findings[b].file) || (findings[a].startLine ?? 0) - (findings[b].startLine ?? 0) || a - b)) + if (findings[i].file !== findings[lead].file && !folded.has(findings[i].file)) folded.set(findings[i].file, i) replace.set(lead, { ...findings[lead], body: `${findings[lead].body}\n\nThe same applies to: ${[...folded.keys()].map((p) => `\`${p}\``).join(", ")}.`, }) - for (const i of folded.values()) drop.add(i) + for (const i of folded.values()) replace.set(i, { ...findings[i], groupedInto: findings[lead].id }) } - if (!drop.size) return findings - return findings.flatMap((f, i) => (drop.has(i) ? [] : [replace.get(i) ?? f])) + if (!replace.size) return findings + return findings.map((f, i) => replace.get(i) ?? f) } diff --git a/packages/opencode/src/altimate/review/finding.ts b/packages/opencode/src/altimate/review/finding.ts index bfb025b338..43034d3625 100644 --- a/packages/opencode/src/altimate/review/finding.ts +++ b/packages/opencode/src/altimate/review/finding.ts @@ -100,6 +100,10 @@ export const Finding = z.object({ deletionSite: z.boolean().optional(), /** Where the finding is posted: inline on the diff, or in the summary only. */ tier: z.enum(["inline", "summary"]).optional(), + /** Id of the finding whose comment covers this one (the same team convention broken the + * same way on another file; see `groupConventionFindings`). Kept in the envelope with its + * own line; the renderer shows it through that comment while it is posted in this run. */ + groupedInto: z.string().optional(), /** The source line the finding points at, quoted as evidence. */ evidenceLine: z.string().max(200).optional(), /** A replacement for a line range, rendered as a suggestion block. */ diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index ca961d7e34..783fbee287 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -134,13 +134,16 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s // diff carries the detail. Pre-existing findings sit in a collapsed list. const deferredIds = new Set(inlineComments(env, opts.alreadyPosted, opts.commentable).deferred.map((f) => f.id)) const posting = postingPolicy(env) + // Findings shown through their lead's comment (`groupedInto`) get no line of their own. + const collapsed = collapsedFindings(env, opts.alreadyPosted, opts.commentable) + const shown = env.findings.filter((f) => !collapsed.has(f.id)) const inline = opts.inline === false ? [] - : env.findings.filter((f) => inlineEligible(f, posting, opts.commentable) && !deferredIds.has(f.id)) + : shown.filter((f) => inlineEligible(f, posting, opts.commentable) && !deferredIds.has(f.id)) const inlineIds = new Set(inline.map((f) => f.id)) - const preExisting = env.findings.filter((f) => f.preExisting && !inlineIds.has(f.id)) - const rest = env.findings.filter((f) => !f.preExisting && !inlineIds.has(f.id)) + const preExisting = shown.filter((f) => f.preExisting && !inlineIds.has(f.id)) + const rest = shown.filter((f) => !f.preExisting && !inlineIds.has(f.id)) if (inline.length) { lines.push( `### Inline (${inline.length})`, @@ -437,7 +440,7 @@ export function commentableLines(diff: string | undefined): Set { /** The posting policy an envelope was produced under (defaults for envelopes * from releases that did not record one). */ -export function postingPolicy(env: VerdictEnvelope): PostingPolicy { +export function postingPolicy(env: Pick): PostingPolicy { return env.policy?.posting ?? DEFAULT_POSTING_POLICY } @@ -467,14 +470,41 @@ export function inlineEligible(f: Finding, posting: PostingPolicy, commentable?: * outside the diff (see `commentable`) keeps its line in the envelope and is * listed in the summary instead. */ +/** + * Findings folded into a lead comment (`groupedInto`, see `groupConventionFindings`) that this + * run shows only through the lead: the lead is in the envelope, may be posted inline and is not + * yet on the PR. Once the lead is on the PR it is not posted again, so a finding newly folded + * into it is posted on its own; those the posted lead already listed carry its markers and + * count as posted. When the lead cannot go inline, each folded finding stands on its own. + */ +export function collapsedFindings( + env: Pick, + alreadyPosted: Set = new Set(), + commentable?: Map>, +): Set { + const posting = postingPolicy(env) + const leads = new Map(env.findings.map((f) => [f.id, f])) + return new Set( + env.findings + .filter((f) => { + const lead = f.groupedInto ? leads.get(f.groupedInto) : undefined + return !!lead && !alreadyPosted.has(lead.id) && inlineEligible(lead, posting, commentable) + }) + .map((f) => f.id), + ) +} + export function inlineComments( env: VerdictEnvelope, alreadyPosted: Set = new Set(), commentable?: Map>, ): { comments: InlineComment[]; deferred: Finding[] } { const posting = postingPolicy(env) + const collapsed = collapsedFindings(env, alreadyPosted, commentable) + const foldedInto = new Map() + for (const f of env.findings) if (collapsed.has(f.id)) foldedInto.set(f.groupedInto!, [...(foldedInto.get(f.groupedInto!) ?? []), f.id]) const fresh = env.findings - .filter((f) => inlineEligible(f, posting, commentable) && !alreadyPosted.has(f.id)) + .filter((f) => !collapsed.has(f.id) && inlineEligible(f, posting, commentable) && !alreadyPosted.has(f.id)) .sort( (a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || @@ -489,6 +519,9 @@ export function inlineComments( const s = f.suggestion if (s) parts.push(suggestionBlock(s.replacement)) parts.push(findingMarker(f.id)) + // The folded findings this comment lists count as posted on the next run, so they are not + // posted again on their own once this comment is on the PR. + for (const id of foldedInto.get(f.id) ?? []) parts.push(findingMarker(id)) const body = parts.join("\n\n") // GitHub applies a suggestion to the comment's line range, so the // comment spans exactly the replaced lines. diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index bc55e8462f..d035610335 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -522,10 +522,14 @@ describe("repeated convention findings become one comment", () => { ], conv, ) - expect(out.map((x) => x.file)).toEqual(["models/b.sql", "models/a.sql"]) - expect(out[0].severity).toBe("warning") - expect(out[0].body).toEndWith("The same applies to: `models/a.sql`, `models/c.sql`.") - expect(out[1].title).toBe("fct_a: Wrong join") + // The folded findings stay, in place, pointing at the lead; the unrelated one is untouched. + expect(out.map((x) => x.file)).toEqual(["models/a.sql", "models/b.sql", "models/c.sql", "models/a.sql"]) + expect(out[1].severity).toBe("warning") + expect(out[1].body).toEndWith("The same applies to: `models/a.sql`, `models/c.sql`.") + expect(out[0].groupedInto).toBe(out[1].id) + expect(out[2].groupedInto).toBe(out[1].id) + expect(out[3].title).toBe("fct_a: Wrong join") + expect(out[3].groupedInto).toBeUndefined() }) test("different conventions, different issues, one file or no convention named: unchanged", () => { @@ -566,8 +570,9 @@ describe("repeated convention findings become one comment", () => { }) as any) const files = [aiFile("models/a.sql"), aiFile("models/b.sql")] const grouped = await runAiReview({ files, grounding: [], conventions: conv }) - expect(grouped.findings).toHaveLength(1) + expect(grouped.findings).toHaveLength(2) expect(grouped.findings[0].body).toContain("The same applies to: `models/b.sql`.") + expect(grouped.findings[1].groupedInto).toBe(grouped.findings[0].id) const plain = await runAiReview({ files, grounding: [] }) expect(plain.findings).toHaveLength(2) }) @@ -579,9 +584,10 @@ describe("repeated convention findings become one comment", () => { f("models/b.sql", "fct_b", "Missing model description", "Per models/CLAUDE.md."), ] const out = groupConventionFindings(list, conv) - expect(out.map((x) => x.file)).toEqual(["models/a.sql", "models/a.sql"]) + expect(out.map((x) => x.file)).toEqual(["models/a.sql", "models/a.sql", "models/b.sql"]) expect(out[0].body).toEndWith("The same applies to: `models/b.sql`.") expect(out[1]).toEqual(list[1]) + expect(out[2].groupedInto).toBe(out[0].id) }) test("replay mode records the conventions and groups the replayed findings", async () => { @@ -598,8 +604,9 @@ describe("repeated convention findings become one comment", () => { const res = await runAiReview({ files: [aiFile("models/a.sql"), aiFile("models/b.sql")], grounding: [], conventions: conv }) expect(res.status.replayed).toBe(true) expect(res.status.conventions?.map((c) => c.path)).toEqual(["models/CLAUDE.md", "CLAUDE.md"]) - expect(res.findings).toHaveLength(1) + expect(res.findings).toHaveLength(2) expect(res.findings[0].body).toContain("The same applies to: `models/b.sql`.") + expect(res.findings[1].groupedInto).toBe(res.findings[0].id) } finally { if (saved === undefined) delete process.env.ALTIMATE_REVIEW_AI_REPLAY else process.env.ALTIMATE_REVIEW_AI_REPLAY = saved @@ -607,3 +614,105 @@ describe("repeated convention findings become one comment", () => { } }) }) + +describe("convention grouping keeps every finding (round 2)", () => { + const conv: Convention[] = [{ path: "models/CLAUDE.md", source: "claude_md", scope: "models", text: "Every model has a description." }] + const f = (file: string, title: string, body: string, opts: { category?: "sql_quality" | "sql_correctness"; line?: number } = {}) => + makeFinding({ + severity: "suggestion", + category: opts.category ?? "sql_quality", + title, + body, + file, + model: file.split("/").pop()!.replace(/\.sql$/, ""), + startLine: opts.line ?? 3, + endLine: opts.line ?? 3, + confidence: "medium", + evidence: { tool: "ai-review", result: {} }, + ruleKey: `ai:${opts.category ?? "sql_quality"}:${title}`, + rule: "ai-review:sql-quality", + }) + + test("folded findings stay with their own line and point at the lead", () => { + const list = [f("models/b.sql", "Missing description", "Per models/CLAUDE.md.", { line: 7 }), f("models/a.sql", "Missing description", "Per models/CLAUDE.md.", { line: 2 })] + const out = groupConventionFindings(list, conv) + expect(out).toHaveLength(2) + const folded = out.find((x) => x.groupedInto)! + expect(folded.file).toBe("models/b.sql") + expect(folded.startLine).toBe(7) + expect(folded.body).toBe("Per models/CLAUDE.md.") + }) + + test("the lead is picked by severity, then path: the same whatever order the model returned", () => { + const a = f("models/a.sql", "Missing description", "Per models/CLAUDE.md.") + const b = f("models/b.sql", "Missing description", "Per models/CLAUDE.md.") + const lead = (list: typeof a[]) => groupConventionFindings(list, conv).find((x) => x.body.includes("The same applies to"))!.file + expect(lead([a, b])).toBe("models/a.sql") + expect(lead([b, a])).toBe("models/a.sql") + }) + + test("the same generic title in different categories is not folded", () => { + const list = [ + f("models/a.sql", "Wrong aggregation", "Per models/CLAUDE.md, sum the cents.", { category: "sql_correctness" }), + f("models/b.sql", "Wrong aggregation", "Per models/CLAUDE.md, name the column.", { category: "sql_quality" }), + ] + expect(groupConventionFindings(list, conv)).toEqual(list) + }) +}) + +describe("folded findings in the PR comment", () => { + const conv: Convention[] = [{ path: "models/CLAUDE.md", source: "claude_md", scope: "models", text: "Every model has a description." }] + const mk = (file: string, line: number) => + makeFinding({ + severity: "warning", + category: "sql_quality", + title: "Missing description", + body: "Per models/CLAUDE.md.", + file, + model: file.split("/").pop()!.replace(/\.sql$/, ""), + startLine: line, + endLine: line, + confidence: "high", + evidence: { tool: "ai-review", result: {} }, + ruleKey: "ai:sql_quality:missing description", + rule: "ai-review:sql-quality", + }) + const envelopeOf = (findings: ReturnType[]) => + VerdictEnvelope.parse({ + version: "1", + verdict: "COMMENT", + idealVerdict: "COMMENT", + mode: "comment", + tier: "full", + rubricVersion: "test", + engine: {}, + generatedAt: "2026-11-27T00:00:00Z", + summary: { critical: 0, warning: findings.length, suggestion: 0, degraded: false }, + findings: findings.map((x) => ({ ...x, tier: "inline" })), + }) + + test("first run: one comment on the lead, carrying the folded findings' markers; the summary lists the lead only", async () => { + const { inlineComments, renderSummary, postedFindingIds } = await import("../../src/altimate/review/format") + const grouped = groupConventionFindings([mk("models/a.sql", 1), mk("models/b.sql", 1)], conv) + const env = envelopeOf(grouped) + const { comments } = inlineComments(env) + expect(comments.map((c) => c.path)).toEqual(["models/a.sql"]) + const lead = grouped.find((x) => !x.groupedInto)! + const folded = grouped.find((x) => x.groupedInto)! + expect(postedFindingIds([comments[0].body])).toEqual(new Set([lead.id, folded.id])) + const summary = renderSummary(env, { maxChars: Infinity }) + expect(summary).toContain("`models/a.sql:1`") + expect(summary).not.toContain("models/b.sql:1") + // Next run, same findings: nothing is posted again. + expect(inlineComments(env, postedFindingIds([comments[0].body])).comments).toEqual([]) + }) + + test("re-review: a file newly folded into an already-posted lead is posted on its own", async () => { + const { inlineComments, postedFindingIds } = await import("../../src/altimate/review/format") + const first = envelopeOf(groupConventionFindings([mk("models/a.sql", 1)], conv)) + const posted = postedFindingIds(inlineComments(first).comments.map((c) => c.body)) + const second = envelopeOf(groupConventionFindings([mk("models/a.sql", 1), mk("models/c.sql", 4)], conv)) + expect(inlineComments(second, posted).comments.map((c) => `${c.path}:${c.line}`)).toEqual(["models/c.sql:4"]) + }) +}) + From aa82045f7d65fdc9309935cb6d2c5f3e048ae630 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:30:14 +0530 Subject: [PATCH 06/18] fix(review): harden the team-conventions loader - Credential screen: a convention document that holds a private key or a service-account key (`holdsCredentials`, the screen every other AI-lane input goes through) is skipped before it is parsed or cut. - No unbounded `git show` fan-out: with the base listing only paths it holds are read, and reads run at most 8 at a time. A PR touching ~150 directories no longer starts ~600 processes. - Symlinks at the base commit are skipped (`listSymlinksAt`, mode 120000): `git show` returns the link target's name, not its text. - `.altimate/review.md` is looked up in every scope, so a dbt project's own file next to its `.altimate/review.yml` applies to it. - Scoped files are searched above the files the review covers (in-scope changed files plus the outside Python files its AI lane may take), not every directory the PR touches, so unrelated directories do not use up the 40k total. - The dedupe key uses the full text, not its length. - `sliceContributing` ignores `#` lines inside code fences. - Line-mode frontmatter passes the raw `globs` value to `globList`, so `"a", "b"` keeps both globs. - A convention that does not fit a call whole is cut to at most half the call budget while others follow, so one long file cannot shut out `.altimate/review.md`. A git failure reading the base commit still fails the review, as the base-policy read of the same commit does. Changed expectation: the "scoped files are looked up only in ancestors" test now loads without the base listing, since with it absent candidates are no longer probed at all. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/conventions.ts | 106 ++++++++-- packages/opencode/src/altimate/review/git.ts | 13 ++ packages/opencode/src/altimate/review/run.ts | 10 +- .../test/altimate/review-conventions.test.ts | 184 +++++++++++++++++- 4 files changed, 291 insertions(+), 22 deletions(-) diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index ecae5980e2..2fdf39be7a 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -2,18 +2,20 @@ import YAML from "yaml" import { globToRegExp } from "./diff-filter" import { type Finding, SEVERITY_ORDER } from "./finding" +import { holdsCredentials } from "./credentials" /** * Team conventions from the repository's guideline files, read from the BASE * commit so a PR cannot rewrite the conventions it is reviewed under. * - * Sources: `.altimate/review.md` (or `.altimate/REVIEW.md`); `REVIEW.md`, `AGENTS.md`, + * Sources: `.altimate/review.md` (or `.altimate/REVIEW.md`), `REVIEW.md`, `AGENTS.md`, * `CLAUDE.md` and `.claude/CLAUDE.md` at the root and at every ancestor directory of a * changed path; `.coderabbit.yaml` (`reviews.path_instructions[]`, one convention per * entry scoped by its glob, plus the document-level `tone_instructions`); `.cursor/rules/*.mdc` * (frontmatter `globs` / `alwaysApply`; rules with neither are manual and skipped); * `.cursorrules`; `.github/copilot-instructions.md`; `CONTRIBUTING.md` cut to its - * dbt/SQL/test/naming sections. + * dbt/SQL/test/naming sections. A file that is a symlink at the base commit is skipped (git + * would return the link target's name), and so is any document that carries key material. * * With the `conventions` switch (`ALTIMATE_REVIEW_CONVENTIONS`, on by default) each * finder call carries the conventions that apply to its files, most specific first, @@ -129,6 +131,19 @@ function frontmatterValue(raw: string): string { return v.replace(/\s+#.*$/, "").trim() } +/** A frontmatter value without an inline YAML comment (a ` #` outside quotes). */ +function withoutComment(raw: string): string { + let quote = "" + for (let i = 0; i < raw.length; i++) { + const ch = raw[i] + if (quote) { + if (ch === quote) quote = "" + } else if (ch === '"' || ch === "'") quote = ch + else if (ch === "#" && (i === 0 || /\s/.test(raw[i - 1]))) return raw.slice(0, i).trim() + } + return raw.trim() +} + /** `globs` as Cursor writes it: a string (comma list, optionally `[…]`) or a YAML list. */ function globList(value: unknown): string[] { if (Array.isArray(value)) return value.flatMap((v) => (typeof v === "string" ? globList(v) : [])) @@ -156,8 +171,9 @@ function parseFrontmatterLines(text: string): { globs: string[]; alwaysApply: bo const value = frontmatterValue(raw) if (key === "alwaysApply") alwaysApply = /^true$/i.test(value) if (key !== "globs") continue + // The raw value (inline comment cut): `globList` unquotes each item, so `"a", "b"` keeps both. if (!value) inGlobList = true - else globs.push(...globList(value)) + else globs.push(...globList(withoutComment(raw))) } return { globs, alwaysApply } } @@ -221,7 +237,20 @@ export function sliceContributing(text: string, max = CONTRIBUTING_CHARS): strin const lines = text.split(/\r?\n/) const kept: string[] = [] let keepLevel = 0 + let fence = "" for (const line of lines) { + // A `#` line inside a fenced code block is code (a shell comment), not a heading. + const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1] + if (fence) { + if (marker && marker[0] === fence[0] && marker.length >= fence.length) fence = "" + if (keepLevel) kept.push(line) + continue + } + if (marker) { + fence = marker + if (keepLevel) kept.push(line) + continue + } const h = /^(#{1,6})\s+(.*)$/.exec(line) if (h) { const level = h[1].length @@ -243,10 +272,15 @@ export interface LoadConventionsInput { readBase: (rel: string) => Promise /** Every file at the base commit (repo-relative), listed once; throws when git fails. */ listBase?: () => Promise - /** Every path the PR changes (repo-relative): their ancestor directories are searched for scoped files. */ + /** Symlinks at the base commit (repo-relative); skipped, since `git show` returns the target's name. */ + listBaseSymlinks?: () => Promise + /** The paths the review covers (repo-relative): their ancestor directories are searched for scoped files. */ changedPaths: string[] } +/** Concurrent base-commit reads at most. */ +const READ_CONCURRENCY = 8 + /** * Load the team conventions from the base commit (see the module comment for * the sources). Each file is cut to 4,000 characters; root files come before @@ -254,17 +288,45 @@ export interface LoadConventionsInput { * throws, as the base-policy read does, so it cannot pass for "no conventions". */ export async function loadConventions(input: LoadConventionsInput): Promise { - const read = input.readBase const baseFiles = input.listBase ? await input.listBase() : [] + // With the base listing, only paths it holds are read: no `git show` per absent candidate. + const exists = input.listBase ? new Set(baseFiles) : undefined + const links = new Set(input.listBaseSymlinks ? await input.listBaseSymlinks() : []) + let active = 0 + const waiting: Array<() => void> = [] + const limited = async (fn: () => Promise): Promise => { + if (active >= READ_CONCURRENCY) await new Promise((resolve) => waiting.push(resolve)) + active++ + try { + return await fn() + } finally { + active-- + waiting.shift()?.() + } + } + // A document that carries key material is never sent to the model, like any other AI-lane input. + const read = async (rel: string): Promise => { + if ((exists && !exists.has(rel)) || links.has(rel)) return undefined + const text = await limited(() => input.readBase(rel)) + return text !== undefined && holdsCredentials(text) ? undefined : text + } const scopes = scopesOf(input.changedPaths) - const plain = (path: string, source: ConventionSource, scope: string, text: string | undefined): Convention[] => + const wholeFile = (path: string, source: ConventionSource, scope: string, text: string | undefined): Convention[] => text?.trim() ? [{ path, source, scope, text: cut(text.trim(), CONVENTION_FILE_CHARS) }] : [] - let altimatePath = ".altimate/review.md" - let altimate = await read(altimatePath) - if (altimate === undefined) altimate = await read((altimatePath = ".altimate/REVIEW.md")) + // `.altimate/review.md` (else `.altimate/REVIEW.md`) at the root and in every scope, like the + // `.altimate/review.yml` policy, which a dbt project may keep in its own directory. + const altimate = await Promise.all( + scopes.map(async (scope) => { + for (const name of [".altimate/review.md", ".altimate/REVIEW.md"]) { + const text = await read(join(scope, name)) + if (text !== undefined) return wholeFile(join(scope, name), "altimate", scope, text) + } + return [] + }), + ) const scoped = await Promise.all( - scopes.flatMap((scope) => SCOPED_FILES.map(async ([name, source]) => plain(join(scope, name), source, scope, await read(join(scope, name))))), + scopes.flatMap((scope) => SCOPED_FILES.map(async ([name, source]) => wholeFile(join(scope, name), source, scope, await read(join(scope, name))))), ) let coderabbit: Convention[] = [] for (const p of CODERABBIT_FILES) { @@ -299,23 +361,23 @@ export async function loadConventions(input: LoadConventionsInput): Promise() let left = CONVENTIONS_TOTAL_CHARS for (const c of all) { - const key = `${c.path}|${(c.globs ?? []).join(",")}|${c.text.length}` + const key = `${c.path}|${(c.globs ?? []).join(",")}|${c.text}` if (seen.has(key) || c.text.length > left) continue seen.add(key) out.push(c) @@ -356,21 +418,25 @@ function entryChars(c: Convention): number { return c.path.length + appliesTo(c).length + 21 + c.text.length } -/** Take conventions in order within `budget` characters; the first one is cut to fit when it alone is over. */ +/** Take conventions in order within `budget` characters. The first one that does not fit whole is + * cut to fit, to at most half the budget while others follow, so a long file leaves room for them. */ function withinBudget(ordered: Convention[], budget: number): Convention[] { const out: Convention[] = [] let used = 0 - for (const c of ordered) { + let cutOne = false + for (const [i, c] of ordered.entries()) { const cost = entryChars(c) if (used + cost <= budget) { out.push(c) used += cost - } else if (!out.length) { + } else if (!cutOne) { + cutOne = true // The truncation marker counts toward the budget too. - const room = budget - (cost - c.text.length) - TRUNCATED.length + const cap = i < ordered.length - 1 ? Math.floor(budget / 2) : budget + const room = Math.min(budget - used, cap) - (cost - c.text.length) - TRUNCATED.length if (room > 200) { out.push({ ...c, text: cut(c.text, room) }) - used = budget + used += cost - c.text.length + room + TRUNCATED.length } } } diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index ccbbfb6f7d..8c8caaf17d 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -184,6 +184,19 @@ export async function listFilesAt(cwd: string, ref?: string): Promise { + try { + const out = await git(["ls-tree", "-r", "-z", "--full-tree", ref || "HEAD"], cwd) + return out + .split("\0") + .filter((e) => e.startsWith("120000 ")) + .map((e) => e.slice(e.indexOf("\t") + 1)) + } catch { + return undefined + } +} + /** Files in the index plus untracked, non-ignored files (the working tree), repo-root relative; undefined when git fails. */ export async function listWorkingTreeFiles(cwd: string): Promise { try { diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 0496eca026..9a844b113d 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -11,6 +11,7 @@ import { type ResolvedBase, gitRepoRoot, listFilesAt, + listSymlinksAt, listWorkingTreeFiles, grepMatchesAt, grepFixedAt, @@ -481,6 +482,8 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise // Repo review instructions come from the base commit, like the policy, so a PR cannot // change the conventions it is reviewed under; only when the AI lane runs. A git failure // reading that commit fails the review, as it does for the policy read just before. + // Scoped files are searched above the files this review covers (its project's files and + // the outside Python files its AI lane may take), not every directory the PR touches. const conventions = aiOn && aiSwitches.conventions && resolved ? await loadConventions({ @@ -490,7 +493,12 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise if (!files) throw new Error(`cannot list the files of the base commit ${resolved.sha} for the team conventions`) return files }, - changedPaths: opts.prFiles ?? collected.map((f) => f.path), + listBaseSymlinks: async () => { + const links = await listSymlinksAt(gitRoot, resolved.sha) + if (!links) throw new Error(`cannot list the files of the base commit ${resolved.sha} for the team conventions`) + return links + }, + changedPaths: [...changedFiles, ...aiOutsideFiles].map((f) => f.path), }) : [] diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index d035610335..ad8088e58f 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -33,6 +33,17 @@ import { makeFinding } from "../../src/altimate/review/finding" const FIXTURE = path.join(import.meta.dir, "fixtures", "review-conventions") +// Credential-shaped fixtures are built at runtime from obviously fake parts, so no committed string +// matches a secret scanner; each value still has the shape the redactor looks for. +const charRange = (from: string, to: string) => + Array.from({ length: to.charCodeAt(0) - from.charCodeAt(0) + 1 }, (_, i) => String.fromCharCode(from.charCodeAt(0) + i)).join("") +const ALNUM = charRange("a", "z") + charRange("A", "Z") + charRange("0", "9") +/** `n` distinct characters of ALNUM taken with a stride: mixed case and digits, enough entropy to look like a credential. */ +const fakeChars = (n: number, seed = 0) => Array.from({ length: n }, (_, i) => ALNUM[(seed + i * 7) % ALNUM.length]).join("") +const FAKE_AWS_KEY_ID = "AKIA" + "FAKE".repeat(4) +const PEM_BEGIN = ["-----BEGIN", "PRIVATE", "KEY-----"].join(" ") +const PEM_END = ["-----END", "PRIVATE", "KEY-----"].join(" ") + async function fixtureFiles(dir = FIXTURE, prefix = ""): Promise { const out: string[] = [] for (const e of await fs.readdir(dir, { withFileTypes: true })) { @@ -94,7 +105,8 @@ describe("loadConventions (fixture as the base commit)", () => { test("scoped files are looked up only in ancestors of changed paths", async () => { const base = await fixtureBase() - const all = await loadConventions({ readBase: base.readBase, listBase: base.listBase, changedPaths: ["models/staging/stg_orders.sql"] }) + // Without the base listing every candidate is probed (with it, only listed paths are read). + const all = await loadConventions({ readBase: base.readBase, changedPaths: ["models/staging/stg_orders.sql"] }) expect(all.some((c) => c.path === "models/marts/CLAUDE.md")).toBe(false) expect(base.reads).toContain("models/staging/CLAUDE.md") expect(base.reads).not.toContain("models/marts/CLAUDE.md") @@ -490,6 +502,50 @@ describe("reviewPullRequest end to end (AI dry run, no model call)", () => { }, 60_000) }) +describe("reviewPullRequest: conventions are searched above the files the review covers", () => { + const KEYS = ["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] + } + }) + 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() + + test("a CLAUDE.md beside an unrelated changed file outside the project is not loaded", async () => { + const { reviewPullRequest } = await import("../../src/altimate/review/run") + const dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "review-conventions-scope-"))) + try { + for (const [rel, body] of [ + ["dbt/dbt_project.yml", "name: p\n"], + ["dbt/models/m.sql", "select 1 as id\n"], + ["dbt/models/CLAUDE.md", "Models rule.\n"], + ["infra/CLAUDE.md", "Terraform rule.\n"], + ["infra/main.tf", "a = 1\n"], + ]) { + await fs.mkdir(path.dirname(path.join(dir, rel)), { recursive: true }) + await fs.writeFile(path.join(dir, rel), body) + } + git(dir, "init", "-q", "-b", "main") + git(dir, "add", "-A") + git(dir, "commit", "-q", "-m", "base") + git(dir, "checkout", "-q", "-b", "pr") + await fs.writeFile(path.join(dir, "dbt/models/m.sql"), "select 1 as id, 2 as x\n") + await fs.writeFile(path.join(dir, "infra/main.tf"), "a = 2\n") + git(dir, "add", "-A") + git(dir, "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 env = await reviewPullRequest({ cwd: path.join(dir, "dbt"), base: "main", head: "HEAD" }) + expect(env.ai?.conventions?.map((c) => c.path)).toEqual(["dbt/models/CLAUDE.md"]) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }, 60_000) +}) + describe("repeated convention findings become one comment", () => { afterEach(() => mock.restore()) const conv: Convention[] = [ @@ -716,3 +772,129 @@ describe("folded findings in the PR comment", () => { }) }) +describe("loadConventions hardening (round 2)", () => { + test("a document holding a private key or a service-account key is never loaded", async () => { + const files: Record = { + "CLAUDE.md": `Deploy with this key:\n${PEM_BEGIN}\nMIIE...\n${PEM_END}\n`, + "AGENTS.md": 'Use {"type": "service_account", "project_id": "x"} for tests.', + "REVIEW.md": "Snake case.", + } + const all = await loadConventions({ readBase: async (rel) => files[rel], listBase: async () => Object.keys(files), changedPaths: ["models/a.sql"] }) + expect(all.map((c) => c.path)).toEqual(["REVIEW.md"]) + }) + + test("many changed directories: only paths in the base listing are read, at most 8 at a time", async () => { + const changed = Array.from({ length: 150 }, (_, i) => `dir${i}/sub/file.sql`) + const files = ["CLAUDE.md", "dir7/sub/AGENTS.md"] + let active = 0 + let peak = 0 + const reads: string[] = [] + const all = await loadConventions({ + readBase: async (rel) => { + reads.push(rel) + active++ + peak = Math.max(peak, active) + await new Promise((r) => setTimeout(r, 1)) + active-- + return files.includes(rel) ? `rule of ${rel}` : undefined + }, + listBase: async () => files, + changedPaths: changed, + }) + expect(all.map((c) => c.path).sort()).toEqual(["CLAUDE.md", "dir7/sub/AGENTS.md"]) + expect(reads.sort()).toEqual(["CLAUDE.md", "dir7/sub/AGENTS.md"]) + expect(peak).toBeLessThanOrEqual(8) + }) + + test("without a listing the reads are still bounded to 8 at a time", async () => { + let active = 0 + let peak = 0 + await loadConventions({ + readBase: async () => { + active++ + peak = Math.max(peak, active) + await new Promise((r) => setTimeout(r, 1)) + active-- + return undefined + }, + changedPaths: Array.from({ length: 40 }, (_, i) => `d${i}/f.sql`), + }) + expect(peak).toBeLessThanOrEqual(8) + }) + + test("a symlinked CLAUDE.md at the base commit is skipped, not loaded as its target's name", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "review-conventions-link-")) + const git = (...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: dir, env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } }).toString() + try { + await fs.writeFile(path.join(dir, "AGENTS.md"), "Snake case everywhere.\n") + await fs.symlink("AGENTS.md", path.join(dir, "CLAUDE.md")) + git("init", "-q", "-b", "main") + git("add", "-A") + git("commit", "-q", "-m", "base") + const { listSymlinksAt } = await import("../../src/altimate/review/git") + const all = await loadConventions({ + readBase: (rel) => showAtRef(dir, "HEAD", rel), + listBase: async () => (await listFilesAt(dir, "HEAD"))!, + listBaseSymlinks: async () => (await listSymlinksAt(dir, "HEAD"))!, + changedPaths: ["models/a.sql"], + }) + expect(all.map((c) => [c.path, c.text])).toEqual([["AGENTS.md", "Snake case everywhere."]]) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + test("a dbt project's own .altimate/review.md is loaded, scoped to the project", async () => { + const files: Record = { "analytics/.altimate/review.md": "Prefer qualify.", ".altimate/review.md": "Root rule." } + const all = await loadConventions({ readBase: async (rel) => files[rel], listBase: async () => Object.keys(files), changedPaths: ["analytics/models/a.sql"] }) + expect(all.map((c) => [c.path, c.source, c.scope])).toEqual([ + [".altimate/review.md", "altimate", ""], + ["analytics/.altimate/review.md", "altimate", "analytics"], + ]) + }) + + test("two .coderabbit.yaml entries with the same glob and equal-length text are both kept", async () => { + const yaml = "reviews:\n path_instructions:\n - path: 'models/**'\n instructions: 'Use snake.'\n - path: 'models/**'\n instructions: 'Use cents.'\n" + const all = await loadConventions({ readBase: async (rel) => (rel === ".coderabbit.yaml" ? yaml : undefined), changedPaths: ["models/a.sql"] }) + expect(all.map((c) => c.text)).toEqual(["Use snake.", "Use cents."]) + }) + + test("CONTRIBUTING: a `#` line inside a code fence is not a heading", () => { + const text = [ + "# Setup", + "```sh", + "# install dbt deps", + "pip install x", + "```", + "# Releasing", + "Tag it.", + "# dbt models", + "Name models stg_*.", + "```sh", + "# activate venv", + "```", + "Every model has tests.", + ].join("\n") + const out = sliceContributing(text) + expect(out).not.toContain("Tag it.") + expect(out).not.toContain("pip install") + expect(out).toContain("Name models stg_*.") + expect(out).toContain("Every model has tests.") + }) + + test("frontmatter that is not YAML keeps every quoted glob", () => { + const rule = parseMdc('---\nglobs: "**/*.sql", "**/*.yml" # both\n---\nBody.') + expect(rule.globs).toEqual(["**/*.sql", "**/*.yml"]) + }) + + test("a long nested convention leaves room for .altimate/review.md in the call", () => { + const all: Convention[] = [ + { path: ".altimate/review.md", source: "altimate", scope: "", text: "Prefer qualify over subqueries." }, + { path: "models/CLAUDE.md", source: "claude_md", scope: "models", text: "x".repeat(4_000) }, + ] + const { paths } = renderConventions(all, ["models/a.sql"]) + expect(paths).toEqual(["models/CLAUDE.md", ".altimate/review.md"]) + }) +}) + From 4db0ce7ddf62db6be28309bca69a64490ff36cb0 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:30:14 +0530 Subject: [PATCH 07/18] fix(review): the verifier reads base-branch convention text; the multi-project merge keeps every project's conventions - `AiVerifyEvidence.conventions` maps each loaded convention path to its base-commit text. `read_file` accepts those paths and serves that text, so an unchanged `CLAUDE.md` is readable and a PR's edit of it cannot be used to refute a finding based on the base convention. - `mergeAi` unions `ai.conventions` across projects (each project now loads the conventions above its own files), so the merged envelope no longer depends on which lane it spreads. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-verify.ts | 9 ++++- .../src/altimate/review/conventions.ts | 7 ++++ .../src/altimate/review/multi-project.ts | 9 +++++ .../src/altimate/review/orchestrate.ts | 3 +- .../test/altimate/review-conventions.test.ts | 34 +++++++++++++++++++ 5 files changed, 60 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-verify.ts b/packages/opencode/src/altimate/review/ai-verify.ts index b9c6fa5a6e..6319be2160 100644 --- a/packages/opencode/src/altimate/review/ai-verify.ts +++ b/packages/opencode/src/altimate/review/ai-verify.ts @@ -51,6 +51,9 @@ export interface AiVerifyEvidence { addedLines: Map> /** Every file the PR changes, repo-relative, including tests and CI outside the dbt project. */ prFiles?: string[] + /** The team conventions the finder was given, by path: their base-commit text. `read_file` + * serves this text for a convention path, so a PR's edit cannot refute a base convention. */ + conventions?: Map } export type Decision = "keep" | "discard" | "summary" @@ -824,6 +827,7 @@ export function verifierTools( ...graph.parents.map((p) => p.path), ...graph.downstream.map((d) => d.path), ...(ev.prFiles ?? []), + ...(ev.conventions?.keys() ?? []), ]), ].filter((p) => !isCredentialPath(p)) /** A requested path inside the review scope, as the repo-relative path to read; a project-relative path resolves too. */ @@ -843,7 +847,7 @@ export function verifierTools( return { read_file: { - description: "Up to 200 numbered lines of any file the PR changes (tests and CI included), a dbt parent or direct child.", + description: "Up to 200 numbered lines of a changed file (tests, CI too), a dbt parent or child, or a team convention (base text).", input: z.object({ path: z.string(), side, @@ -853,6 +857,9 @@ export function verifierTools( async run({ path, side, start, end }) { const p = resolve(path) if (!p) return scope + const convention = ev.conventions?.get(p) + if (convention !== undefined) + return `(team convention, base-branch text)\n${numberedSlice(convention, start as number, end as number) ?? ""}` return ( (await ev.readFile(p, (side as "old" | "new") ?? "new", start as number, end as number)) ?? NA(`${p} does not exist on that side`) diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index 2fdf39be7a..352bdf32e1 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -498,6 +498,13 @@ export interface ConventionRecord { chars: number } +/** The loaded conventions' text by path (entries of one file, such as `.coderabbit.yaml`, joined). */ +export function conventionTexts(all: Convention[]): Map { + const out = new Map() + for (const c of all) out.set(c.path, out.has(c.path) ? `${out.get(c.path)}\n\n${c.text}` : c.text) + return out +} + export function conventionRecords(all: Convention[]): ConventionRecord[] { return all.map((c) => ({ path: c.path, source: c.source, scope: c.scope, ...(c.globs ? { globs: c.globs } : {}), chars: c.text.length })) } diff --git a/packages/opencode/src/altimate/review/multi-project.ts b/packages/opencode/src/altimate/review/multi-project.ts index 7aea7037db..84ad004fa3 100644 --- a/packages/opencode/src/altimate/review/multi-project.ts +++ b/packages/opencode/src/altimate/review/multi-project.ts @@ -343,6 +343,14 @@ function mergeAi(runs: Array<{ root: string; env: VerdictEnvelope }>): VerdictEn 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 ?? []) + // Each project loads the conventions above its own files: the union, once per record. + const seenConv = new Set() + const conventions = ais + .flatMap((a) => a.conventions ?? []) + .filter((c) => { + const key = JSON.stringify([c.path, c.scope, c.globs ?? [], c.chars]) + return !seenConv.has(key) && !!seenConv.add(key) + }) return { ...base, state, @@ -355,6 +363,7 @@ function mergeAi(runs: Array<{ root: string; env: VerdictEnvelope }>): VerdictEn input, unsent: unsent.length ? unsent : undefined, failedFiles: failedFiles.length ? failedFiles : undefined, + conventions: conventions.length ? conventions : 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 80a8016a36..dfa62937d6 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -68,7 +68,7 @@ import { ruleTier } from "./rule-tiers" import { type AiSwitches, switchOn } from "./ai-switches" import { isAiOtherFile } from "./ai-other-files" import { AI_PYTHON_KIND, isAiPythonFile } from "./ai-python-files" -import type { Convention } from "./conventions" +import { type Convention, conventionTexts } from "./conventions" import { type AiVerifyEvidence, numberedSlice } from "./ai-verify" import { holdsCredentials, isCredentialPath } from "./credentials" import type { ColumnReach } from "../native/dbt/column-reach" @@ -2778,6 +2778,7 @@ export async function runReview(input: OrchestrateInput): Promise { if (refused(p, side)) return REFUSED const text = await getContent?.(p, side) diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index ad8088e58f..9e9a3a15d4 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -898,3 +898,37 @@ describe("loadConventions hardening (round 2)", () => { }) }) +describe("convention evidence for the verifier and the multi-project merge", () => { + test("read_file serves a convention file's base text, even when the PR does not change it", async () => { + const { verifierTools } = await import("../../src/altimate/review/ai-verify") + const read: string[] = [] + const defs = verifierTools({ + dialect: "duckdb", + files: [], + runner: {} as ReviewRunner, + addedLines: new Map(), + prFiles: ["models/a.sql"], + conventions: new Map([["models/CLAUDE.md", "Base rule.\nSecond line."]]), + readFile: async (p: string) => (read.push(p), "head text"), + compiledSql: async () => undefined, + } as any) + const out = await defs.read_file.run({ path: "models/CLAUDE.md", side: "new" }) + expect(out).toContain("Base rule.") + expect(out).not.toContain("head text") + expect(read).toEqual([]) + }) + + test("mergeProjectEnvelopes unions ai.conventions across projects", async () => { + const { mergeProjectEnvelopes } = await import("../../src/altimate/review/multi-project") + const { buildEnvelope, signEnvelope } = await import("../../src/altimate/review/verdict") + const rec = (p: string, scope: string) => ({ path: p, source: "claude_md", scope, chars: 5 }) + const env = (conventions?: ReturnType[]) => + signEnvelope(buildEnvelope({ findings: [], tier: "full", mode: "comment", ai: { state: "ok", calls: 1, ...(conventions ? { conventions } : {}) } as any })) + const merged = mergeProjectEnvelopes([ + { root: "a", paths: [], env: env([rec("CLAUDE.md", ""), rec("a/CLAUDE.md", "a")]) }, + { root: "b", paths: [], env: env([rec("CLAUDE.md", ""), rec("b/CLAUDE.md", "b")]) }, + { root: "c", paths: [], env: env() }, + ]) + expect(merged.ai?.conventions?.map((c) => c.path)).toEqual(["CLAUDE.md", "a/CLAUDE.md", "b/CLAUDE.md"]) + }) +}) From 6a0b0dc12b1b7e79686b041aa08afa808d35e195 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:30:14 +0530 Subject: [PATCH 08/18] fix(review): conventions docs and comments match the behaviour - Docs: `.claude/CLAUDE.md` is looked up in every scope like the other scoped files; project-level `.altimate/review.md`; symlinks and credential-bearing files are skipped; the verifier reads base text. - `AI_SWITCH_DEFAULTS` comment: conventions were part of the measured configuration, as the PR description says. - A test name no longer refers to another PR by number. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 16 ++++++++++------ .../opencode/src/altimate/review/ai-switches.ts | 5 ++--- .../test/altimate/review-conventions.test.ts | 2 +- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 055e9115f1..994c9c4d88 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -654,14 +654,18 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne 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. The repo's own review instructions go with each call, read from the base branch - so a PR cannot change them: `.altimate/review.md`, `REVIEW.md`, `AGENTS.md` and - `CLAUDE.md` (at the root and in each changed path's directories), - `.claude/CLAUDE.md`, `.cursor/rules/*.mdc` (rules with `globs` or `alwaysApply`; - manual rules with neither are skipped), `.cursorrules`, + so a PR cannot change them: `.altimate/review.md`, `REVIEW.md`, `AGENTS.md`, + `CLAUDE.md` and `.claude/CLAUDE.md` (at the root and in each directory above a + file the review covers, so a dbt project's own `.altimate/review.md` next to its + `.altimate/review.yml` applies to it), `.cursor/rules/*.mdc` (rules with `globs` + or `alwaysApply`; manual rules with neither are skipped), `.cursorrules`, `.github/copilot-instructions.md`, `.coderabbit.yaml` `path_instructions` and `tone_instructions`, and the dbt/SQL/test sections of `CONTRIBUTING.md`, most - specific first, up to 3,000 characters per call (`ai.conventions: false` or `ALTIMATE_REVIEW_CONVENTIONS=0` - turns this off). + specific first, up to 3,000 characters per call (`ai.conventions: false` or + `ALTIMATE_REVIEW_CONVENTIONS=0` turns this off). A file that is a symlink at the + base commit is skipped, and so is any instruction file that holds a private key + or a service-account key: it is never sent to the model. The verifier reads a + convention file's base-branch text, not the PR's edit of 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-switches.ts b/packages/opencode/src/altimate/review/ai-switches.ts index bde6bb410b..aefb298fea 100644 --- a/packages/opencode/src/altimate/review/ai-switches.ts +++ b/packages/opencode/src/altimate/review/ai-switches.ts @@ -25,9 +25,8 @@ export const AI_SWITCH_ENV: Record = { /** * Product defaults when neither env nor config sets a switch: the configuration measured - * together (wider input, related files batched, context cards, the verifier), plus the team - * conventions (`conventions`), on by default on their own, outside that measurement. Each one - * is opt-out with `ai: { : false }` or its env variable set to `0`. + * together (wider input, related files batched, context cards, the verifier, the team + * conventions). Each one is opt-out with `ai: { : false }` or its env variable set to `0`. */ export const AI_SWITCH_DEFAULTS: AiSwitches = { coverage: true, diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index 9e9a3a15d4..9e46daec6f 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -112,7 +112,7 @@ describe("loadConventions (fixture as the base commit)", () => { expect(base.reads).not.toContain("models/marts/CLAUDE.md") }) - test("the files #1774 read (REVIEW.md, .altimate/REVIEW.md, AGENTS.md, CLAUDE.md) are all covered", async () => { + test("REVIEW.md, .altimate/REVIEW.md and nested AGENTS.md/CLAUDE.md are loaded", async () => { const files: Record = { "REVIEW.md": "Root rule.", ".altimate/REVIEW.md": "Altimate rule.", From c39a2769c0c8ae88346f8a91872893b8227b9b36 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:06:47 +0530 Subject: [PATCH 09/18] fix(review): folded convention findings survive a long lead body and repeat merging MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `inlineComments` clamps the lead's own body and adds "The same applies to: …" as a separate part, built from the folded findings it collapses. Before, a lead body over 600 characters cut the list while the folded markers were still added, so the next run treated those files as posted though no comment named them. - `mergeRepeats` keeps `groupedInto` on a merged comment only when every member was folded into the same lead, so a distinct finding merged with a folded one stays visible. When a lead is merged, findings folded into it are pointed at the merged comment's id, so they stay collapsed. - `SAME_APPLIES_RE`/`sameAppliesLine` are shared; replay strips the line wherever it sits, not only at the end of the body. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/ai-replay.ts | 3 +- .../src/altimate/review/conventions.ts | 10 ++- .../opencode/src/altimate/review/finding.ts | 20 +++++- .../opencode/src/altimate/review/format.ts | 8 ++- .../test/altimate/review-conventions.test.ts | 70 +++++++++++++++++++ 5 files changed, 105 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/review/ai-replay.ts b/packages/opencode/src/altimate/review/ai-replay.ts index 0abf274014..b7e4e275e8 100644 --- a/packages/opencode/src/altimate/review/ai-replay.ts +++ b/packages/opencode/src/altimate/review/ai-replay.ts @@ -8,6 +8,7 @@ // again. Ids are the stored ones; benchmark labels are keyed by them. // Fidelity is approximate: discarded findings come back with bodies clamped to // 600 characters, and kept ones after the orchestrator's anchoring/cleaning. +import { SAME_APPLIES_RE } from "./conventions" import { readFile } from "node:fs/promises" import z from "zod" import { Provider } from "@/provider/provider" @@ -153,7 +154,7 @@ export function replayFindings(raw: unknown): ReplayedLane { function unverify(f: Finding): Finding { const { tier: _tier, origin: _origin, preExisting: _pre, evidenceLine: _line, groupedInto: _grouped, ...rest } = f // Convention grouping runs again on replay (after the verifier): drop the lead's list of the other files. - let body = f.body.replace(/\n\nThe same applies to: [^\n]*\.$/, "") + let body = f.body.replace(SAME_APPLIES_RE, "") const prior = f.evidence?.result if (!prior || typeof prior !== "object") return { ...rest, body } const { verification, ...result } = prior as Record & { diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index 352bdf32e1..c7f0743618 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -515,6 +515,14 @@ export function citedConvention(f: Pick, paths: strin return paths.filter((p) => text.includes(p)).sort((a, b) => b.length - a.length)[0] } +/** The line a lead's body gains for the files folded into it. */ +export function sameAppliesLine(files: string[]): string { + return `The same applies to: ${files.map((p) => `\`${p}\``).join(", ")}.` +} + +/** That line wherever it sits in a body (later text, such as a merged repeat's list, may follow it). */ +export const SAME_APPLIES_RE = /\n\nThe same applies to: [^\n]*\.(?=\n|$)/ + /** A finding's title without the names of its own file, so one issue on several files reads the same. */ function issueKey(f: Pick): string { const base = f.file.split("/").pop() ?? f.file @@ -567,7 +575,7 @@ export function groupConventionFindings(findings: Finding[], conventions: Conven if (findings[i].file !== findings[lead].file && !folded.has(findings[i].file)) folded.set(findings[i].file, i) replace.set(lead, { ...findings[lead], - body: `${findings[lead].body}\n\nThe same applies to: ${[...folded.keys()].map((p) => `\`${p}\``).join(", ")}.`, + body: `${findings[lead].body}\n\n${sameAppliesLine([...folded.keys()])}`, }) for (const i of folded.values()) replace.set(i, { ...findings[i], groupedInto: findings[lead].id }) } diff --git a/packages/opencode/src/altimate/review/finding.ts b/packages/opencode/src/altimate/review/finding.ts index 43034d3625..2e9deee61f 100644 --- a/packages/opencode/src/altimate/review/finding.ts +++ b/packages/opencode/src/altimate/review/finding.ts @@ -303,6 +303,9 @@ export function mergeRepeats(findings: Finding[]): Finding[] { if (g) g.push(f) else groups.set(key, [f]) } + // A merged comment replaces its members' ids: findings folded into a member (`groupedInto`) + // follow it to the merged comment. + const renamed = new Map() for (const [key, g] of groups) { if (g.length === 1) { out.push(g[0]) @@ -310,13 +313,24 @@ export function mergeRepeats(findings: Finding[]): Finding[] { } g.sort((a, b) => tieKey(a).localeCompare(tieKey(b))) const [first, ...rest] = g + const id = "f_" + createHash("sha256").update(`merged ${key}`).digest("hex").slice(0, 16) + for (const m of g) renamed.set(m.id, id) + // Folded only when every member is folded into the same lead: a distinct finding merged in + // must stay visible on its own. + const { groupedInto: _g, ...head } = first + const shared = g.every((m) => m.groupedInto && m.groupedInto === first.groupedInto) ? first.groupedInto : undefined out.push({ - ...first, + ...head, + ...(shared ? { groupedInto: shared } : {}), // Keyed by the group, not by its first instance: fixing that instance must not re-post the comment. - id: "f_" + createHash("sha256").update(`merged ${key}`).digest("hex").slice(0, 16), + id, title: `${first.title} (+${rest.length} more)`, body: `${first.body}\n\nSame rule, also here:\n${rest.map((f) => `- ${repeatLabel(f, first)}`).join("\n")}`, }) } - return out + if (!renamed.size) return out + return out.map((f) => { + const lead = f.groupedInto && renamed.get(f.groupedInto) + return lead && lead !== f.id ? { ...f, groupedInto: lead } : f + }) } diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 783fbee287..41b85d004e 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -1,5 +1,6 @@ import { type Finding, type Severity, type Confidence, SEVERITY_ORDER, blankNames, groupKeyTitle, verifierDemoted } from "./finding" import { type VerdictEnvelope, type PostingPolicy, DEFAULT_POSTING_POLICY, isOutsideProjectReason } from "./verdict" +import { SAME_APPLIES_RE, sameAppliesLine } from "./conventions" /** * Render a verdict envelope for humans (PR summary markdown) and for the VCS @@ -501,6 +502,7 @@ export function inlineComments( ): { comments: InlineComment[]; deferred: Finding[] } { const posting = postingPolicy(env) const collapsed = collapsedFindings(env, alreadyPosted, commentable) + const byId = new Map(env.findings.map((f) => [f.id, f])) const foldedInto = new Map() for (const f of env.findings) if (collapsed.has(f.id)) foldedInto.set(f.groupedInto!, [...(foldedInto.get(f.groupedInto!) ?? []), f.id]) const fresh = env.findings @@ -515,7 +517,11 @@ export function inlineComments( const comments = fresh.slice(0, posting.inlineBudget).map((f): InlineComment => { const parts = [`${SEVERITY_EMOJI[f.severity]} **${f.title}**`] if (f.evidenceLine) parts.push(evidenceText(f)) - parts.push(clampBody(f.body)) + // A lead's list of folded files is its own part, after the clamp: a long body must not cut it + // while the folded findings' markers below count them as posted. + const folded = foldedInto.get(f.id) ?? [] + parts.push(clampBody(folded.length ? f.body.replace(SAME_APPLIES_RE, "") : f.body)) + if (folded.length) parts.push(sameAppliesLine(folded.map((id) => byId.get(id)!.file))) const s = f.suggestion if (s) parts.push(suggestionBlock(s.replacement)) parts.push(findingMarker(f.id)) diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index 9e46daec6f..26fed5a50d 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -932,3 +932,73 @@ describe("convention evidence for the verifier and the multi-project merge", () expect(merged.ai?.conventions?.map((c) => c.path)).toEqual(["CLAUDE.md", "a/CLAUDE.md", "b/CLAUDE.md"]) }) }) + +describe("convention grouping, round 2b", () => { + const conv: Convention[] = [{ path: "models/CLAUDE.md", source: "claude_md", scope: "models", text: "Every model has a description." }] + const mk = (file: string, line: number, body = "Per models/CLAUDE.md.", title = "Missing description") => + makeFinding({ + severity: "warning", + category: "sql_quality", + title, + body, + file, + model: file.split("/").pop()!.replace(/\.\w+$/, ""), + startLine: line, + endLine: line, + confidence: "high", + evidence: { tool: "ai-review", result: {} }, + ruleKey: `ai:sql_quality:${title}:${line}`, + rule: "ai-review:sql-quality", + }) + const envelopeOf = (findings: ReturnType[]) => + VerdictEnvelope.parse({ + version: "1", + verdict: "COMMENT", + idealVerdict: "COMMENT", + mode: "comment", + tier: "full", + rubricVersion: "test", + engine: {}, + generatedAt: "2026-11-27T00:00:00Z", + summary: { critical: 0, warning: findings.length, suggestion: 0, degraded: false }, + findings: findings.map((x) => ({ ...x, tier: "inline" })), + }) + + test("a lead body over the clamp still lists the folded files in its comment", async () => { + const { inlineComments, BODY_MAX_CHARS } = await import("../../src/altimate/review/format") + const long = "Per models/CLAUDE.md. " + "x".repeat(BODY_MAX_CHARS + 100) + const grouped = groupConventionFindings([mk("models/a.sql", 1, long), mk("models/b.sql", 1)], conv) + const { comments } = inlineComments(envelopeOf(grouped)) + expect(comments).toHaveLength(1) + expect(comments[0].body).toContain("The same applies to: `models/b.sql`.") + }) + + test("mergeRepeats keeps groupedInto only when every member shares it", async () => { + const { mergeRepeats } = await import("../../src/altimate/review/finding") + const lead = mk("models/a.sql", 1) + const folded = { ...mk("models/b.yml", 3, "Per models/CLAUDE.md.", "Column undocumented"), groupedInto: lead.id } + const distinct = mk("models/b.yml", 9, "Another column.", "Column undocumented") + const out = mergeRepeats([lead, folded, distinct]) + const merged = out.find((f) => f.file === "models/b.yml")! + expect(merged.title).toContain("(+1 more)") + expect(merged.groupedInto).toBeUndefined() + }) + + test("a lead merged with a sibling: folded findings follow it to the merged comment", async () => { + const { mergeRepeats } = await import("../../src/altimate/review/finding") + const lead = mk("models/a.sql", 1) + const sibling = mk("models/a.sql", 5) + const folded = { ...mk("models/b.sql", 1), groupedInto: lead.id } + const out = mergeRepeats([lead, sibling, folded]) + const merged = out.find((f) => f.file === "models/a.sql")! + expect(merged.id).not.toBe(lead.id) + expect(out.find((f) => f.file === "models/b.sql")!.groupedInto).toBe(merged.id) + }) + + test("replay strips the folded-files line even when text follows it", () => { + const { replayFindings } = require("../../src/altimate/review/ai-replay") + const f = { ...mk("models/a.sql", 1, "Per models/CLAUDE.md.\n\nThe same applies to: `models/b.sql`.\n\nSame rule, also here:\n- x (line 5)") } + const lane = replayFindings({ findings: [f], ai: { state: "ok", calls: 1 } }) + expect(lane.findings[0].body).not.toContain("The same applies to") + }) +}) From 09cd3ba70aa0eab7f6435353927a2f37b01a4cd3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:06:47 +0530 Subject: [PATCH 10/18] fix(review): redact tokens and passwords in team convention text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On top of the PEM/service-account screen, each convention document is passed through the shared `redactSecrets` (tokens such as `ghp_…`, `password: …`, keys in URLs, long opaque blobs) plus AWS access key ids (`AKIA…`/`ASIA…`) before it is parsed or sent. Changed expectation: the per-file cap test used one 9,000-character run of `x`, which the long-blob rule now redacts; it uses words instead and checks the same 4,000-character cut. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 3 ++- .../opencode/src/altimate/review/conventions.ts | 15 ++++++++++++--- .../test/altimate/review-conventions.test.ts | 17 +++++++++++++++-- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 994c9c4d88..afa150248b 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -664,7 +664,8 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne specific first, up to 3,000 characters per call (`ai.conventions: false` or `ALTIMATE_REVIEW_CONVENTIONS=0` turns this off). A file that is a symlink at the base commit is skipped, and so is any instruction file that holds a private key - or a service-account key: it is never sent to the model. The verifier reads a + or a service-account key: it is never sent to the model. Tokens, passwords and + keys in the other files are redacted before they are sent. The verifier reads a convention file's base-branch text, not the PR's edit of it. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index c7f0743618..9808154284 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -3,6 +3,7 @@ import YAML from "yaml" import { globToRegExp } from "./diff-filter" import { type Finding, SEVERITY_ORDER } from "./finding" import { holdsCredentials } from "./credentials" +import { redactSecrets } from "@/installation" /** * Team conventions from the repository's guideline files, read from the BASE @@ -15,7 +16,8 @@ import { holdsCredentials } from "./credentials" * (frontmatter `globs` / `alwaysApply`; rules with neither are manual and skipped); * `.cursorrules`; `.github/copilot-instructions.md`; `CONTRIBUTING.md` cut to its * dbt/SQL/test/naming sections. A file that is a symlink at the base commit is skipped (git - * would return the link target's name), and so is any document that carries key material. + * would return the link target's name), and so is any document that carries key material; + * tokens and passwords in the others are redacted (`redactConvention`). * * With the `conventions` switch (`ALTIMATE_REVIEW_CONVENTIONS`, on by default) each * finder call carries the conventions that apply to its files, most specific first, @@ -278,6 +280,12 @@ export interface LoadConventionsInput { changedPaths: string[] } +/** Convention text with secrets redacted: the shared `redactSecrets` (tokens, passwords, keys in + * URLs, long opaque blobs) plus AWS access key ids. */ +export function redactConvention(text: string): string { + return redactSecrets(text).replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g, "[REDACTED]") +} + /** Concurrent base-commit reads at most. */ const READ_CONCURRENCY = 8 @@ -304,11 +312,12 @@ export async function loadConventions(input: LoadConventionsInput): Promise => { if ((exists && !exists.has(rel)) || links.has(rel)) return undefined const text = await limited(() => input.readBase(rel)) - return text !== undefined && holdsCredentials(text) ? undefined : text + return text === undefined || holdsCredentials(text) ? undefined : redactConvention(text) } const scopes = scopesOf(input.changedPaths) const wholeFile = (path: string, source: ConventionSource, scope: string, text: string | undefined): Convention[] => diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index 26fed5a50d..29ae2df03a 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -130,11 +130,12 @@ describe("loadConventions (fixture as the base commit)", () => { test("per-file cap of 4,000 characters; absent files are skipped", async () => { const all = await loadConventions({ - readBase: async (rel) => (rel === "AGENTS.md" ? "x".repeat(9_000) : undefined), + // Words, not one 9,000-character run: secret redaction treats a long opaque run as a key. + readBase: async (rel) => (rel === "AGENTS.md" ? "ab ".repeat(3_000) : undefined), changedPaths: ["models/a.sql"], }) expect(all.map((c) => c.path)).toEqual(["AGENTS.md"]) - expect(all[0].text.startsWith("x".repeat(4_000) + "\n… (truncated)")).toBe(true) + expect(all[0].text.startsWith("ab ".repeat(3_000).slice(0, 4_000) + "\n… (truncated)")).toBe(true) }) test("a git failure reading or listing the base commit throws instead of passing for no conventions", async () => { @@ -1002,3 +1003,15 @@ describe("convention grouping, round 2b", () => { expect(lane.findings[0].body).not.toContain("The same applies to") }) }) + +describe("convention text redaction", () => { + test("tokens, passwords and AWS key ids are redacted before the text is loaded", async () => { + const password = fakeChars(15, 1) + const ghToken = "ghp_" + fakeChars(22, 4) + const text = `Use password: ${password} for staging, token ${ghToken}, and ${FAKE_AWS_KEY_ID}.\nSnake case.` + const all = await loadConventions({ readBase: async (rel) => (rel === "CLAUDE.md" ? text : undefined), changedPaths: ["models/a.sql"] }) + expect(all).toHaveLength(1) + expect(all[0].text).toContain("Snake case.") + for (const secret of [password, ghToken.slice(4), FAKE_AWS_KEY_ID]) expect(all[0].text).not.toContain(secret) + }) +}) From 0a8a6fbe04c05539aac2f30c27bf26aab539eb4f Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:06:47 +0530 Subject: [PATCH 11/18] fix(review): one `git ls-tree` for the convention loader's files and symlinks `listTreeAt` returns every entry at the base commit and the symlinks among them from a single listing; `run.ts` shares it between `listBase` and `listBaseSymlinks`. It replaces `listSymlinksAt`. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/git.ts | 13 ++++++------ packages/opencode/src/altimate/review/run.ts | 21 +++++++++---------- .../test/altimate/review-conventions.test.ts | 4 ++-- 3 files changed, 18 insertions(+), 20 deletions(-) diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index 8c8caaf17d..9b5a1c1263 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -184,14 +184,13 @@ export async function listFilesAt(cwd: string, ref?: string): Promise { +/** Every entry at `ref` (repo-root relative) and the symlinks among them (mode 120000), from one + * `git ls-tree`; undefined when git can't list it. */ +export async function listTreeAt(cwd: string, ref?: string): Promise<{ files: string[]; symlinks: string[] } | undefined> { try { - const out = await git(["ls-tree", "-r", "-z", "--full-tree", ref || "HEAD"], cwd) - return out - .split("\0") - .filter((e) => e.startsWith("120000 ")) - .map((e) => e.slice(e.indexOf("\t") + 1)) + const entries = (await git(["ls-tree", "-r", "-z", "--full-tree", ref || "HEAD"], cwd)).split("\0").filter(Boolean) + const pathOf = (e: string) => e.slice(e.indexOf("\t") + 1) + return { files: entries.map(pathOf), symlinks: entries.filter((e) => e.startsWith("120000 ")).map(pathOf) } } catch { return undefined } diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 9a844b113d..bb38bf1216 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -11,7 +11,7 @@ import { type ResolvedBase, gitRepoRoot, listFilesAt, - listSymlinksAt, + listTreeAt, listWorkingTreeFiles, grepMatchesAt, grepFixedAt, @@ -484,20 +484,19 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise // reading that commit fails the review, as it does for the policy read just before. // Scoped files are searched above the files this review covers (its project's files and // the outside Python files its AI lane may take), not every directory the PR touches. + // One base listing for the conventions loader: the files and the symlinks among them. + let baseTree: Promise<{ files: string[]; symlinks: string[] }> | undefined + const listBaseTree = () => + (baseTree ??= listTreeAt(gitRoot, resolved!.sha).then((t) => { + if (!t) throw new Error(`cannot list the files of the base commit ${resolved!.sha} for the team conventions`) + return t + })) const conventions = aiOn && aiSwitches.conventions && resolved ? await loadConventions({ readBase: (rel) => showAtRef(gitRoot, resolved.sha, rel), - listBase: async () => { - const files = await listFilesAt(gitRoot, resolved.sha) - if (!files) throw new Error(`cannot list the files of the base commit ${resolved.sha} for the team conventions`) - return files - }, - listBaseSymlinks: async () => { - const links = await listSymlinksAt(gitRoot, resolved.sha) - if (!links) throw new Error(`cannot list the files of the base commit ${resolved.sha} for the team conventions`) - return links - }, + listBase: async () => (await listBaseTree()).files, + listBaseSymlinks: async () => (await listBaseTree()).symlinks, changedPaths: [...changedFiles, ...aiOutsideFiles].map((f) => f.path), }) : [] diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index 29ae2df03a..27b14faf24 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -833,11 +833,11 @@ describe("loadConventions hardening (round 2)", () => { git("init", "-q", "-b", "main") git("add", "-A") git("commit", "-q", "-m", "base") - const { listSymlinksAt } = await import("../../src/altimate/review/git") + const { listTreeAt } = await import("../../src/altimate/review/git") const all = await loadConventions({ readBase: (rel) => showAtRef(dir, "HEAD", rel), listBase: async () => (await listFilesAt(dir, "HEAD"))!, - listBaseSymlinks: async () => (await listSymlinksAt(dir, "HEAD"))!, + listBaseSymlinks: async () => (await listTreeAt(dir, "HEAD"))!.symlinks, changedPaths: ["models/a.sql"], }) expect(all.map((c) => [c.path, c.text])).toEqual([["AGENTS.md", "Snake case everywhere."]]) From 862d6d52f16622bcd6c80af867ab1aba47fe2004 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:24:12 +0530 Subject: [PATCH 12/18] fix(review): redact convention text with high-precision patterns only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shared `redactSecrets` mangled ordinary guidance: "basic tests" and "the token count" lost their next word, "secret: never select…" lost "never", `env_var('DBT_PASSWORD')` and md5 examples were redacted, and the 40+ character blob rule could swallow long paths. `redactConvention` now uses only shapes prose does not have: provider-prefixed tokens and AWS key ids, URL userinfo with a password, and a secret-named key whose value looks like a credential (12+ characters, no template or placeholder, mixed character classes, entropy of at least 3 bits per character). The PEM and service-account screen is unchanged. The per-file cap test is back to its original 9,000-character `x` fixture, since the blob rule no longer applies; the redaction test uses credential-like values. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 6 ++-- .../src/altimate/review/conventions.ts | 35 ++++++++++++++++--- .../test/altimate/review-conventions.test.ts | 34 ++++++++++++++++-- 3 files changed, 65 insertions(+), 10 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index afa150248b..0915998e97 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -664,8 +664,10 @@ across 12 dialects all plan; anything still unrecognized stays *undecidable*, ne specific first, up to 3,000 characters per call (`ai.conventions: false` or `ALTIMATE_REVIEW_CONVENTIONS=0` turns this off). A file that is a symlink at the base commit is skipped, and so is any instruction file that holds a private key - or a service-account key: it is never sent to the model. Tokens, passwords and - keys in the other files are redacted before they are sent. The verifier reads a + or a service-account key: it is never sent to the model. In the other files, + provider tokens (GitHub `ghp_…`, Slack `xox…`, OpenAI `sk-…`), AWS key ids, passwords in URLs and + secret-named settings whose value looks like a credential are redacted; ordinary + text such as `env_var('DBT_PASSWORD')` examples is left as written. The verifier reads a convention file's base-branch text, not the PR's edit of it. 4. **Rubric → verdict.** Findings map to a verdict by a versioned rubric (data, not prompt): any blocking-category `critical` → `REQUEST_CHANGES`; ≥3 warnings diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index 9808154284..3513bf1ccc 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -3,7 +3,6 @@ import YAML from "yaml" import { globToRegExp } from "./diff-filter" import { type Finding, SEVERITY_ORDER } from "./finding" import { holdsCredentials } from "./credentials" -import { redactSecrets } from "@/installation" /** * Team conventions from the repository's guideline files, read from the BASE @@ -17,7 +16,7 @@ import { redactSecrets } from "@/installation" * `.cursorrules`; `.github/copilot-instructions.md`; `CONTRIBUTING.md` cut to its * dbt/SQL/test/naming sections. A file that is a symlink at the base commit is skipped (git * would return the link target's name), and so is any document that carries key material; - * tokens and passwords in the others are redacted (`redactConvention`). + * credentials in the others are redacted with high-precision patterns (`redactConvention`). * * With the `conventions` switch (`ALTIMATE_REVIEW_CONVENTIONS`, on by default) each * finder call carries the conventions that apply to its files, most specific first, @@ -280,10 +279,36 @@ export interface LoadConventionsInput { changedPaths: string[] } -/** Convention text with secrets redacted: the shared `redactSecrets` (tokens, passwords, keys in - * URLs, long opaque blobs) plus AWS access key ids. */ +/** Provider-prefixed tokens and cloud key ids: shapes ordinary prose never has. */ +const TOKEN_RE = + /\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|sk-(?:proj-|ant-)?[A-Za-z0-9_-]{20,}|AIza[0-9A-Za-z_-]{35}|npm_[A-Za-z0-9]{36}|(?:AKIA|ASIA)[A-Z0-9]{16})\b/g +/** `scheme://user:password@`: the userinfo of a URL that carries a password. */ +const URL_USERINFO_RE = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi +/** `key: value` / `key=value` where the key names a secret. */ +const SECRET_KV_RE = + /\b([A-Za-z0-9_.-]*(?:password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_.-]*)(["']?[ \t]*[:=][ \t]*["']?)([^\s"',;)]+)/gi + +/** A value that looks like a credential: long, no placeholder or template, mixed character classes, high entropy. */ +function looksSecret(v: string): boolean { + if (v.length < 12) return false + if (/[{}$<>]|env_var|\*{3}|^x+$|changeme|your[_-]|example|placeholder|redacted/i.test(v)) return false + const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((r) => r.test(v)).length + if (classes < 2) return false + const freq = new Map() + for (const ch of v) freq.set(ch, (freq.get(ch) ?? 0) + 1) + const entropy = [...freq.values()].reduce((h, n) => h - (n / v.length) * Math.log2(n / v.length), 0) + return entropy >= 3 +} + +/** Convention text with credentials redacted, using only high-precision patterns so ordinary + * guidance ("basic tests", "the token count", `env_var('DBT_PASSWORD')`, md5 examples) is left alone: + * provider-prefixed tokens and AWS key ids, URL userinfo with a password, and a secret-named key + * whose value looks like a credential. Documents with key material are skipped before this. */ export function redactConvention(text: string): string { - return redactSecrets(text).replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g, "[REDACTED]") + return text + .replace(TOKEN_RE, "[REDACTED]") + .replace(URL_USERINFO_RE, "$1[REDACTED]@") + .replace(SECRET_KV_RE, (m, key: string, sep: string, value: string) => (looksSecret(value) ? `${key}${sep}[REDACTED]` : m)) } /** Concurrent base-commit reads at most. */ diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index 27b14faf24..fd4ecc8e30 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -3,6 +3,7 @@ import path from "node:path" import os from "node:os" import { promises as fs } from "node:fs" import { execFileSync } from "node:child_process" +import { createHash } from "node:crypto" import { CONVENTIONS_HEADING, appliesTo, @@ -130,12 +131,11 @@ describe("loadConventions (fixture as the base commit)", () => { test("per-file cap of 4,000 characters; absent files are skipped", async () => { const all = await loadConventions({ - // Words, not one 9,000-character run: secret redaction treats a long opaque run as a key. - readBase: async (rel) => (rel === "AGENTS.md" ? "ab ".repeat(3_000) : undefined), + readBase: async (rel) => (rel === "AGENTS.md" ? "x".repeat(9_000) : undefined), changedPaths: ["models/a.sql"], }) expect(all.map((c) => c.path)).toEqual(["AGENTS.md"]) - expect(all[0].text.startsWith("ab ".repeat(3_000).slice(0, 4_000) + "\n… (truncated)")).toBe(true) + expect(all[0].text.startsWith("x".repeat(4_000) + "\n… (truncated)")).toBe(true) }) test("a git failure reading or listing the base commit throws instead of passing for no conventions", async () => { @@ -1015,3 +1015,31 @@ describe("convention text redaction", () => { for (const secret of [password, ghToken.slice(4), FAKE_AWS_KEY_ID]) expect(all[0].text).not.toContain(secret) }) }) + +describe("convention redaction keeps ordinary guidance (round 2c)", () => { + test("prose, env_var examples, md5 and long paths are left as written", async () => { + const { redactConvention } = await import("../../src/altimate/review/conventions") + const prose = [ + "Every model has basic tests (unique, not_null).", + "Keep the token count, not the token list, in the summary.", + "secret: never select * from raw tables.", + "password: \"{{ env_var('DBT_PASSWORD') }}\"", + `Surrogate keys use select md5(concat(a, b)) as id, e.g. ${createHash("md5").update("hello").digest("hex")}.`, + "See models/staging/finance/revenuerecognitionmonthlysnapshotsfinalversion/model.sql", + "Use profiles with token: changeme_placeholder_value in examples.", + ].join("\n") + expect(redactConvention(prose)).toBe(prose) + }) + + test("real credentials are redacted", async () => { + const { redactConvention } = await import("../../src/altimate/review/conventions") + const secrets = ["ghp_" + fakeChars(36), FAKE_AWS_KEY_ID, "xo" + "xb-" + fakeChars(10, 3) + "-" + fakeChars(10, 5), "sk" + "-proj-" + fakeChars(24, 11)] + const password = fakeChars(16, 2) + const urlPassword = fakeChars(14, 9) + const text = `Tokens: ${secrets.join(", ")}.\npassword: ${password}\nclone https://deploy:${urlPassword}@git.example.com/repo.git` + const out = redactConvention(text) + for (const v of [...secrets, password, urlPassword]) expect(out).not.toContain(v) + expect(out).toContain("password: [REDACTED]") + expect(out).toContain("https://[REDACTED]@git.example.com/repo.git") + }) +}) From 6e765d690ff1e08ba9fe912b7976fddaf228f002 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:45:05 +0530 Subject: [PATCH 13/18] fix(review): fold convention findings only into a lead this run posts inline `collapsedFindings` asked only whether the lead could go inline, not whether this rendering posts it. A summary rendered with `inline: false` (CLI, agent tool, the 422 fallback) and a lead past `posting.inlineBudget` both dropped the folded findings: no inline comment, no summary line. `inlinePlan` now settles the folding against the budget: a finding is folded only into a lead within the budget; one whose lead is over the budget stands on its own and is deferred with it. `renderSummary` folds nothing when it renders without inline comments. `inlineComments` has its doc comment back. Tests (review-conventions.test.ts): `a summary rendered without inline comments (CLI, agent tool, 422 fallback) lists every folded finding`, `a lead over the inline budget: its folded findings are deferred to the summary, not hidden`. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 82 +++++++++++-------- .../test/altimate/review-conventions.test.ts | 24 ++++++ 2 files changed, 72 insertions(+), 34 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 41b85d004e..02efceea06 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -135,8 +135,9 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s // diff carries the detail. Pre-existing findings sit in a collapsed list. const deferredIds = new Set(inlineComments(env, opts.alreadyPosted, opts.commentable).deferred.map((f) => f.id)) const posting = postingPolicy(env) - // Findings shown through their lead's comment (`groupedInto`) get no line of their own. - const collapsed = collapsedFindings(env, opts.alreadyPosted, opts.commentable) + // Findings shown through their lead's inline comment (`groupedInto`) get no line of their own; + // without inline comments every finding is listed. + const collapsed = opts.inline === false ? new Set() : collapsedFindings(env, opts.alreadyPosted, opts.commentable) const shown = env.findings.filter((f) => !collapsed.has(f.id)) const inline = opts.inline === false @@ -464,49 +465,38 @@ export function inlineEligible(f: Finding, posting: PostingPolicy, commentable?: return SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[posting.inlineSeverityFloor] } -/** - * Inline comments for this run: eligible findings not already on the PR, most - * severe and most confident first, capped at the posting budget. Findings over - * the budget are `deferred` and stay in the summary. A finding whose line is - * outside the diff (see `commentable`) keeps its line in the envelope and is - * listed in the summary instead. - */ /** * Findings folded into a lead comment (`groupedInto`, see `groupConventionFindings`) that this - * run shows only through the lead: the lead is in the envelope, may be posted inline and is not - * yet on the PR. Once the lead is on the PR it is not posted again, so a finding newly folded - * into it is posted on its own; those the posted lead already listed carry its markers and - * count as posted. When the lead cannot go inline, each folded finding stands on its own. + * run shows only through the lead: the lead is in the envelope, is posted inline by this run + * (eligible, not yet on the PR, within the inline budget). Once the lead is on the PR it is not + * posted again, so a finding newly folded into it is posted on its own; those the posted lead + * already listed carry its markers and count as posted. When the lead does not go inline this + * run (ineligible, or over the budget), each folded finding stands on its own. */ export function collapsedFindings( env: Pick, alreadyPosted: Set = new Set(), commentable?: Map>, ): Set { - const posting = postingPolicy(env) - const leads = new Map(env.findings.map((f) => [f.id, f])) - return new Set( - env.findings - .filter((f) => { - const lead = f.groupedInto ? leads.get(f.groupedInto) : undefined - return !!lead && !alreadyPosted.has(lead.id) && inlineEligible(lead, posting, commentable) - }) - .map((f) => f.id), - ) + return inlinePlan(env, alreadyPosted, commentable).collapsed } -export function inlineComments( - env: VerdictEnvelope, - alreadyPosted: Set = new Set(), +/** Which findings this run posts inline, which are deferred, and which are folded into a posted lead. */ +function inlinePlan( + env: Pick, + alreadyPosted: Set, commentable?: Map>, -): { comments: InlineComment[]; deferred: Finding[] } { +): { posted: Finding[]; deferred: Finding[]; collapsed: Set } { const posting = postingPolicy(env) - const collapsed = collapsedFindings(env, alreadyPosted, commentable) - const byId = new Map(env.findings.map((f) => [f.id, f])) - const foldedInto = new Map() - for (const f of env.findings) if (collapsed.has(f.id)) foldedInto.set(f.groupedInto!, [...(foldedInto.get(f.groupedInto!) ?? []), f.id]) + const leads = new Map(env.findings.map((f) => [f.id, f])) + // Folded into a lead that may go inline; settled below against the budget. + const foldable = env.findings.filter((f) => { + const lead = f.groupedInto ? leads.get(f.groupedInto) : undefined + return !!lead && !alreadyPosted.has(lead.id) && inlineEligible(lead, posting, commentable) + }) + const foldableIds = new Set(foldable.map((f) => f.id)) const fresh = env.findings - .filter((f) => !collapsed.has(f.id) && inlineEligible(f, posting, commentable) && !alreadyPosted.has(f.id)) + .filter((f) => !foldableIds.has(f.id) && inlineEligible(f, posting, commentable) && !alreadyPosted.has(f.id)) .sort( (a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || @@ -514,7 +504,31 @@ export function inlineComments( a.file.localeCompare(b.file) || a.startLine! - b.startLine!, ) - const comments = fresh.slice(0, posting.inlineBudget).map((f): InlineComment => { + const posted = fresh.slice(0, posting.inlineBudget) + const postedIds = new Set(posted.map((f) => f.id)) + const collapsed = new Set(foldable.filter((f) => postedIds.has(f.groupedInto!)).map((f) => f.id)) + // A finding whose lead is over the budget stands on its own; the budget is spent, so it is deferred. + const released = foldable.filter((f) => !collapsed.has(f.id) && inlineEligible(f, posting, commentable) && !alreadyPosted.has(f.id)) + return { posted, deferred: [...fresh.slice(posting.inlineBudget), ...released], collapsed } +} + +/** + * Inline comments for this run: eligible findings not already on the PR, most + * severe and most confident first, capped at the posting budget. Findings over + * the budget are `deferred` and stay in the summary. A finding whose line is + * outside the diff (see `commentable`) keeps its line in the envelope and is + * listed in the summary instead. + */ +export function inlineComments( + env: VerdictEnvelope, + alreadyPosted: Set = new Set(), + commentable?: Map>, +): { comments: InlineComment[]; deferred: Finding[] } { + const { posted, deferred, collapsed } = inlinePlan(env, alreadyPosted, commentable) + const byId = new Map(env.findings.map((f) => [f.id, f])) + const foldedInto = new Map() + for (const f of env.findings) if (collapsed.has(f.id)) foldedInto.set(f.groupedInto!, [...(foldedInto.get(f.groupedInto!) ?? []), f.id]) + const comments = posted.map((f): InlineComment => { const parts = [`${SEVERITY_EMOJI[f.severity]} **${f.title}**`] if (f.evidenceLine) parts.push(evidenceText(f)) // A lead's list of folded files is its own part, after the clamp: a long body must not cut it @@ -540,7 +554,7 @@ export function inlineComments( body, } }) - return { comments, deferred: fresh.slice(posting.inlineBudget) } + return { comments, deferred } } function groupBySeverity(findings: Finding[]): Record { diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index fd4ecc8e30..7cda63f062 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -764,6 +764,30 @@ describe("folded findings in the PR comment", () => { expect(inlineComments(env, postedFindingIds([comments[0].body])).comments).toEqual([]) }) + test("a summary rendered without inline comments (CLI, agent tool, 422 fallback) lists every folded finding", async () => { + const { renderSummary } = await import("../../src/altimate/review/format") + const env = envelopeOf(groupConventionFindings([mk("models/a.sql", 1), mk("models/b.sql", 1)], conv)) + const summary = renderSummary(env, { maxChars: Infinity, inline: false }) + expect(summary).toContain("`models/a.sql:1`") + expect(summary).toContain("`models/b.sql:1`") + }) + + test("a lead over the inline budget: its folded findings are deferred to the summary, not hidden", async () => { + const { inlineComments, renderSummary, postedFindingIds } = await import("../../src/altimate/review/format") + const grouped = groupConventionFindings([mk("models/a.sql", 1), mk("models/b.sql", 1)], conv) + // A critical finding takes the only inline slot, so the lead is deferred. + const top = { ...mk("models/z.sql", 7), severity: "critical" as const, title: "Fan-out join", ruleKey: "ai:correctness:fan-out" } + const env = { ...envelopeOf([top, ...grouped]), policy: { source: "default" as const, hash: "h", posting: { inlineBudget: 1, inlineSeverityFloor: "warning" as const, silentWhenClean: true } } } + const folded = grouped.find((x) => x.groupedInto)! + const { comments, deferred } = inlineComments(env) + expect(comments.map((c) => c.path)).toEqual(["models/z.sql"]) + expect(postedFindingIds(comments.map((c) => c.body)).has(folded.id)).toBe(false) + expect(deferred.map((f) => f.file).sort()).toEqual(["models/a.sql", "models/b.sql"]) + const summary = renderSummary(env, { maxChars: Infinity }) + expect(summary).toContain("`models/a.sql:1`") + expect(summary).toContain("`models/b.sql:1`") + }) + test("re-review: a file newly folded into an already-posted lead is posted on its own", async () => { const { inlineComments, postedFindingIds } = await import("../../src/altimate/review/format") const first = envelopeOf(groupConventionFindings([mk("models/a.sql", 1)], conv)) From 4c7806fd851f5ef69f8dbc43072ee24c31dcc6ac Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:07:15 +0530 Subject: [PATCH 14/18] fix(review): a new convention lead does not re-list findings already on the PR; the same-applies line names only folded findings - The lead is picked by severity and path on each run. When a later push added the same issue on a file that sorts first, the new lead folded the findings an earlier lead's comment already listed, and its comment named them again and re-emitted their markers. Findings in `alreadyPosted` are no longer folded. - The grouping's "The same applies to" sentence was stripped only when the lead had folded findings, so a lead whose folded findings were dropped later still named those files. It is now always replaced by the list of findings actually folded. Tests (review-conventions.test.ts): `re-review: a new lead does not re-list or re-mark findings an earlier lead's comment covered`, `a lead whose folded findings were all dropped later does not say the same applies elsewhere`, and `summary without inline comments, lead body over the clamp: each folded finding is still listed` (covers the earlier fold fix). Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 8 +++-- .../test/altimate/review-conventions.test.ts | 31 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 02efceea06..ca8d7b878c 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -490,9 +490,11 @@ function inlinePlan( const posting = postingPolicy(env) const leads = new Map(env.findings.map((f) => [f.id, f])) // Folded into a lead that may go inline; settled below against the budget. + // A finding already on the PR (listed by an earlier lead's comment) is not folded again, so a + // lead picked anew on a later push neither re-lists it nor re-emits its marker. const foldable = env.findings.filter((f) => { const lead = f.groupedInto ? leads.get(f.groupedInto) : undefined - return !!lead && !alreadyPosted.has(lead.id) && inlineEligible(lead, posting, commentable) + return !!lead && !alreadyPosted.has(f.id) && !alreadyPosted.has(lead.id) && inlineEligible(lead, posting, commentable) }) const foldableIds = new Set(foldable.map((f) => f.id)) const fresh = env.findings @@ -534,7 +536,9 @@ export function inlineComments( // A lead's list of folded files is its own part, after the clamp: a long body must not cut it // while the folded findings' markers below count them as posted. const folded = foldedInto.get(f.id) ?? [] - parts.push(clampBody(folded.length ? f.body.replace(SAME_APPLIES_RE, "") : f.body)) + // The grouping's own "same applies" sentence is always replaced: it may name findings that + // were dropped later or are already on the PR. + parts.push(clampBody(f.body.replace(SAME_APPLIES_RE, ""))) if (folded.length) parts.push(sameAppliesLine(folded.map((id) => byId.get(id)!.file))) const s = f.suggestion if (s) parts.push(suggestionBlock(s.replacement)) diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index 7cda63f062..55a2b3ac9a 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -795,6 +795,37 @@ describe("folded findings in the PR comment", () => { const second = envelopeOf(groupConventionFindings([mk("models/a.sql", 1), mk("models/c.sql", 4)], conv)) expect(inlineComments(second, posted).comments.map((c) => `${c.path}:${c.line}`)).toEqual(["models/c.sql:4"]) }) + + test("re-review: a new lead does not re-list or re-mark findings an earlier lead's comment covered", async () => { + const { inlineComments, postedFindingIds } = await import("../../src/altimate/review/format") + const first = envelopeOf(groupConventionFindings([mk("models/b.sql", 1), mk("models/c.sql", 1)], conv)) + const posted = postedFindingIds(inlineComments(first).comments.map((c) => c.body)) + expect(posted.size).toBe(2) + // A later push adds the issue on a file that sorts first, so it becomes the lead. + const second = envelopeOf(groupConventionFindings([mk("models/a.sql", 1), mk("models/b.sql", 1), mk("models/c.sql", 1)], conv)) + const { comments } = inlineComments(second, posted) + expect(comments.map((c) => c.path)).toEqual(["models/a.sql"]) + expect(comments[0].body).not.toContain("models/b.sql") + expect(comments[0].body).not.toContain("models/c.sql") + expect(postedFindingIds([comments[0].body]).size).toBe(1) + }) + + test("a lead whose folded findings were all dropped later does not say the same applies elsewhere", async () => { + const { inlineComments } = await import("../../src/altimate/review/format") + const grouped = groupConventionFindings([mk("models/a.sql", 1), mk("models/b.sql", 1)], conv) + const env = envelopeOf(grouped.filter((x) => !x.groupedInto)) + const { comments } = inlineComments(env) + expect(comments).toHaveLength(1) + expect(comments[0].body).not.toContain("The same applies to") + }) + + test("summary without inline comments, lead body over the clamp: each folded finding is still listed", async () => { + const { renderSummary, BODY_MAX_CHARS } = await import("../../src/altimate/review/format") + const long = (file: string) => ({ ...mk(file, 1), body: "Per models/CLAUDE.md. " + "x".repeat(BODY_MAX_CHARS + 100) }) + const env = envelopeOf(groupConventionFindings([long("models/a.sql"), mk("models/b.sql", 1)], conv)) + const summary = renderSummary(env, { maxChars: Infinity, inline: false }) + expect(summary).toContain("`models/b.sql:1`") + }) }) describe("loadConventions hardening (round 2)", () => { From 4d8021c783f3e994c853b12a6e54538429ff1f13 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:09:41 +0530 Subject: [PATCH 15/18] fix(review): a folded finding must be inline-eligible itself; summary bullets drop the stale same-applies line - `inlinePlan` folds a finding into its lead only when the finding could go inline on its own (`inlineEligible`: tier, verifier demotion, pre-existing, severity floor). Grouping ignores the verifier and runs before findings are marked pre-existing, so a demoted or pre-existing member was hidden behind the lead's file list. It now keeps its own summary entry and is not marked as posted. - Summary bullets show the body without the grouping's "The same applies to" sentence, as inline comments already do: the CLI, the 422 fallback and over-budget leads list each finding they show, and the sentence could name a finding dropped later. Tests: `a folded finding the verifier demoted or that is pre-existing is not folded; it keeps its summary entry`, `a summary bullet does not repeat the lead's stored same-applies sentence`. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 20 ++++++++-- .../test/altimate/review-conventions.test.ts | 37 +++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index ca8d7b878c..eb3dbdc3ae 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -203,6 +203,10 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s return [...lines, ...tail].join("\n") } +/** A finding's body without the grouping's "same applies" sentence: a summary bullet lists each + * finding it shows, and the sentence may name findings dropped later. */ +const shownBody = (f: Finding) => f.body.replace(SAME_APPLIES_RE, "") + /** Render findings of one severity as bullets. With `group`, findings that say * the same thing (same category, title and body once names are blanked) on * GROUP_MIN_MODELS or more distinct models collapse into one bullet. */ @@ -226,7 +230,8 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou const more = names.length > 8 ? ` (+${names.length - 8} more)` : "" // Show a body verbatim only when every member says exactly that; // otherwise its names belong to one model, so show the blanked form. - const body = oneLine(clampBody(g.every((f) => f.body === g[0].body) ? g[0].body : blankNames(g[0].body))) + const lead = shownBody(g[0]) + const body = oneLine(clampBody(g.every((f) => f.body === g[0].body) ? lead : blankNames(lead))) const unverified = g.some((f) => f.degraded) ? " · _unverified_" : "" out.push({ text: @@ -242,7 +247,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou text: `- **${f.title}** \n` + (f.evidenceLine ? ` ${evidenceText(f)} \n` : "") + - ` ${oneLine(clampBody(f.body))} \n \`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}`, + ` ${oneLine(clampBody(shownBody(f)))} \n \`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}`, count: 1, }) } @@ -492,9 +497,18 @@ function inlinePlan( // Folded into a lead that may go inline; settled below against the budget. // A finding already on the PR (listed by an earlier lead's comment) is not folded again, so a // lead picked anew on a later push neither re-lists it nor re-emits its marker. + // Grouping ignores the verifier's demotions and runs before findings are marked pre-existing, + // so a finding is folded only when it could go inline itself (tier, verifier, pre-existing, + // severity floor); otherwise it keeps its own summary entry. const foldable = env.findings.filter((f) => { const lead = f.groupedInto ? leads.get(f.groupedInto) : undefined - return !!lead && !alreadyPosted.has(f.id) && !alreadyPosted.has(lead.id) && inlineEligible(lead, posting, commentable) + return ( + !!lead && + !alreadyPosted.has(f.id) && + !alreadyPosted.has(lead.id) && + inlineEligible(lead, posting, commentable) && + inlineEligible(f, posting) + ) }) const foldableIds = new Set(foldable.map((f) => f.id)) const fresh = env.findings diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index 55a2b3ac9a..eb504db3d0 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -819,6 +819,43 @@ describe("folded findings in the PR comment", () => { expect(comments[0].body).not.toContain("The same applies to") }) + test("a summary bullet does not repeat the lead's stored same-applies sentence", async () => { + const { renderSummary } = await import("../../src/altimate/review/format") + const grouped = groupConventionFindings([mk("models/a.sql", 1), mk("models/b.sql", 1)], conv) + expect(grouped.find((x) => !x.groupedInto)!.body).toContain("The same applies to") + // Without inline comments every finding has its own bullet; with the member dropped (severity + // threshold, dedupe) the lead's bullet must not name it either. + for (const findings of [grouped, grouped.filter((x) => !x.groupedInto)]) { + const summary = renderSummary(envelopeOf(findings), { maxChars: Infinity, inline: false }) + expect(summary).not.toContain("The same applies to") + expect(summary).toContain("`models/a.sql:1`") + } + }) + + test("a folded finding the verifier demoted or that is pre-existing is not folded; it keeps its summary entry", async () => { + const { inlineComments, renderSummary, postedFindingIds } = await import("../../src/altimate/review/format") + const grouped = groupConventionFindings([mk("models/a.sql", 1), mk("models/b.sql", 1), mk("models/c.sql", 1)], conv) + const lead = grouped.find((x) => !x.groupedInto)! + const demoted = grouped.find((x) => x.file === "models/b.sql")! + const old = grouped.find((x) => x.file === "models/c.sql")! + const env = envelopeOf(grouped) + env.findings = env.findings.map((x) => + x.id === demoted.id + ? { ...x, evidence: { tool: "ai-review", result: { verification: { decision: "summary" } } } } + : x.id === old.id + ? { ...x, preExisting: true } + : x, + ) + const { comments } = inlineComments(env) + expect(comments.map((c) => c.path)).toEqual(["models/a.sql"]) + expect(comments[0].body).not.toContain("models/b.sql") + expect(comments[0].body).not.toContain("models/c.sql") + expect(postedFindingIds([comments[0].body])).toEqual(new Set([lead.id])) + const summary = renderSummary(env, { maxChars: Infinity }) + expect(summary).toContain("`models/b.sql:1`") + expect(summary).toContain("models/c.sql") + }) + test("summary without inline comments, lead body over the clamp: each folded finding is still listed", async () => { const { renderSummary, BODY_MAX_CHARS } = await import("../../src/altimate/review/format") const long = (file: string) => ({ ...mk(file, 1), body: "Per models/CLAUDE.md. " + "x".repeat(BODY_MAX_CHARS + 100) }) From a114a8608e25d71cd9824cbed5ec2ef80344b228 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:09:41 +0530 Subject: [PATCH 16/18] fix(review): a Cursor globs list survives a blank or comment line; git test helpers skip signing - `parseFrontmatterLines` keeps reading a `globs:` list across blank and comment lines, so a rule whose frontmatter is not valid YAML (unquoted `**/*.sql`) keeps its globs instead of being skipped. - `issueKey`: a comment says why the `:` prefix strip stays (the `names` loop skips one-character names); a test pins it. - The two remaining git helpers in review-conventions.test.ts pass `-c commit.gpgsign=false` like the others. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/conventions.ts | 4 +++ .../test/altimate/review-conventions.test.ts | 32 +++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index 3513bf1ccc..546734e665 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -165,6 +165,8 @@ function parseFrontmatterLines(text: string): { globs: string[]; alwaysApply: bo globs.push(...globList(frontmatterValue(item[1]))) continue } + // A blank or comment line inside the list does not end it. + if (inGlobList && /^\s*(?:#.*)?$/.test(line)) continue inGlobList = false const kv = /^(\w+)\s*:\s*(.*)$/.exec(line) if (!kv) continue @@ -562,6 +564,8 @@ function issueKey(f: Pick): string { const base = f.file.split("/").pop() ?? f.file const names = [f.model, base, base.replace(/\.[^.]+$/, "")].filter((n): n is string => !!n && n.length > 1) let t = f.title.toLowerCase() + // The `names` loop skips one-character names (it would erase that letter everywhere); a + // one-character model is still taken off a `:` prefix. if (f.model && t.startsWith(f.model.toLowerCase() + ":")) t = t.slice(f.model.length + 1) for (const n of names) t = t.split(n.toLowerCase()).join(" ") // "… for " leaves a dangling preposition once the name is gone. diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index eb504db3d0..1233077b20 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -279,7 +279,7 @@ describe("scoping and budget", () => { describe("loadConventions over git: the base commit, never the PR's edits", () => { const git = (cwd: string, ...args: string[]) => - execFileSync("git", args, { cwd, env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } }).toString() + 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() test("showAtRef + listFilesAt at the merge base read the base versions and the base Cursor rules", async () => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), "review-conventions-")) @@ -467,7 +467,7 @@ describe("reviewPullRequest end to end (AI dry run, no model call)", () => { } }) const git = (cwd: string, ...args: string[]) => - execFileSync("git", args, { cwd, env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } }).toString() + 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() test("on by default: the base CLAUDE.md goes into ai.conventions and the call record; `0` records nothing", async () => { const { reviewPullRequest } = await import("../../src/altimate/review/run") @@ -976,6 +976,34 @@ describe("loadConventions hardening (round 2)", () => { expect(out).toContain("Every model has tests.") }) + test("frontmatter that is not YAML: a blank or comment line inside the globs list does not end it", () => { + for (const sep of [" # sql models only", ""]) { + const r = parseMdc(`---\ndescription: x\nglobs:\n${sep}\n - **/*.sql\n - models/**\nalwaysApply: false\n---\nBody.\n`) + expect(r.globs).toEqual(["**/*.sql", "models/**"]) + expect(r.alwaysApply).toBe(false) + } + }) + + test("a one-character model is taken off its `:` title prefix when grouping", () => { + const conv: Convention[] = [{ path: "models/CLAUDE.md", source: "claude_md", scope: "models", text: "x" }] + const mk = (model: string) => + makeFinding({ + severity: "warning", + category: "sql_quality", + title: `${model}: missing description`, + body: "Per models/CLAUDE.md.", + file: `models/${model}.sql`, + model, + startLine: 1, + endLine: 1, + confidence: "high", + evidence: { tool: "ai-review", result: {} }, + ruleKey: "ai:sql_quality:missing description", + rule: "ai-review:sql-quality", + }) + expect(groupConventionFindings([mk("a"), mk("b")], conv).filter((f) => f.groupedInto)).toHaveLength(1) + }) + test("frontmatter that is not YAML keeps every quoted glob", () => { const rule = parseMdc('---\nglobs: "**/*.sql", "**/*.yml" # both\n---\nBody.') expect(rule.globs).toEqual(["**/*.sql", "**/*.yml"]) From 4515069aed6cc8b01a6fcd8016433ce39f0aafe1 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:21:52 +0530 Subject: [PATCH 17/18] fix(review): summary grouping ignores the lead's same-applies sentence `bulletsFor` keyed groups and compared member bodies on the raw body, which still held the lead's "The same applies to" sentence, so a lead never grouped with its members in a budgeted summary. Both now use the shown body. Test: `a budgeted summary without inline comments groups the lead with its members (same-applies sentence ignored)`. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/format.ts | 4 ++-- .../opencode/test/altimate/review-conventions.test.ts | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index eb3dbdc3ae..86747641aa 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -215,7 +215,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou for (const f of items) { // The body is part of the key: one rule with different messages (e.g. a // dialect check naming different functions) is different findings. - const key = group ? `${f.category}|${groupKeyTitle(f)}|${blankNames(oneLine(f.body))}` : f.id + const key = group ? `${f.category}|${groupKeyTitle(f)}|${blankNames(oneLine(shownBody(f)))}` : f.id const g = groups.get(key) if (g) g.push(f) else groups.set(key, [f]) @@ -231,7 +231,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou // Show a body verbatim only when every member says exactly that; // otherwise its names belong to one model, so show the blanked form. const lead = shownBody(g[0]) - const body = oneLine(clampBody(g.every((f) => f.body === g[0].body) ? lead : blankNames(lead))) + const body = oneLine(clampBody(g.every((f) => shownBody(f) === lead) ? lead : blankNames(lead))) const unverified = g.some((f) => f.degraded) ? " · _unverified_" : "" out.push({ text: diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index 1233077b20..c8afeb07b9 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -832,6 +832,15 @@ describe("folded findings in the PR comment", () => { } }) + test("a budgeted summary without inline comments groups the lead with its members (same-applies sentence ignored)", async () => { + const { renderSummary } = await import("../../src/altimate/review/format") + const env = envelopeOf(groupConventionFindings([mk("models/a.sql", 1), mk("models/b.sql", 1)], conv)) + const summary = renderSummary(env, { inline: false }) + expect(summary).toContain("2 findings across 2 model(s)") + expect(summary).toContain("Per models/CLAUDE.md.") + expect(summary).not.toContain("The same applies to") + }) + test("a folded finding the verifier demoted or that is pre-existing is not folded; it keeps its summary entry", async () => { const { inlineComments, renderSummary, postedFindingIds } = await import("../../src/altimate/review/format") const grouped = groupConventionFindings([mk("models/a.sql", 1), mk("models/b.sql", 1), mk("models/c.sql", 1)], conv) From c6d68f1e5bf9b13e910531ec356d819101cb46c3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:21:52 +0530 Subject: [PATCH 18/18] fix(review): a Cursor globs list at column 0 is read when the frontmatter is not YAML Test: `frontmatter that is not YAML: a globs list at column 0 is read`. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/conventions.ts | 3 ++- packages/opencode/test/altimate/review-conventions.test.ts | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/conventions.ts b/packages/opencode/src/altimate/review/conventions.ts index 546734e665..74a93ae22c 100644 --- a/packages/opencode/src/altimate/review/conventions.ts +++ b/packages/opencode/src/altimate/review/conventions.ts @@ -160,7 +160,8 @@ function parseFrontmatterLines(text: string): { globs: string[]; alwaysApply: bo let alwaysApply = false let inGlobList = false for (const line of text.split(/\r?\n/)) { - const item = /^\s+-\s*(.+)$/.exec(line) + // List items may sit at column 0 (`globs:\n- a`) or be indented. + const item = /^\s*-\s*(.+)$/.exec(line) if (inGlobList && item) { globs.push(...globList(frontmatterValue(item[1]))) continue diff --git a/packages/opencode/test/altimate/review-conventions.test.ts b/packages/opencode/test/altimate/review-conventions.test.ts index c8afeb07b9..2b55d9edb4 100644 --- a/packages/opencode/test/altimate/review-conventions.test.ts +++ b/packages/opencode/test/altimate/review-conventions.test.ts @@ -993,6 +993,11 @@ describe("loadConventions hardening (round 2)", () => { } }) + test("frontmatter that is not YAML: a globs list at column 0 is read", () => { + const r = parseMdc("---\nglobs:\n- **/*.sql\n- models/**\nalwaysApply: false\n---\nBody.\n") + expect(r.globs).toEqual(["**/*.sql", "models/**"]) + }) + test("a one-character model is taken off its `:` title prefix when grouping", () => { const conv: Convention[] = [{ path: "models/CLAUDE.md", source: "claude_md", scope: "models", text: "x" }] const mk = (model: string) =>