import path from "node:path" import { realpath, readFile, stat } from "node:fs/promises" import { createHash } from "node:crypto" import { collectChangedFiles, gitRepoRoot, listFilesAt, listWorkingTreeFiles, resolveHeadRef, resolveReviewBase, showAtRef, } from "./git" import { reviewPullRequest, type ReviewPullRequestOptions } from "./run" import { applyMode, buildEnvelope, isOutsideProjectReason, reviewIncomplete, signEnvelope, VerdictEnvelope, type ReviewMode, type RiskTier, type Verdict, } from "./verdict" import { reportFailure } from "./failure" import { projectLabel } from "./format" import { parseDbtProjectLayout } from "./compiled" import { aiLaneTimeoutMs } from "./ai-review" import { relativeToRoot, resolvedLayoutDirs, type ChangedFile } from "./diff-filter" /** * Multi-project review (`altimate review --all-projects`): a PR in a mono-repo * can change several dbt projects. Each touched project is reviewed on its own * (its manifest and layout, with the project directory as `cwd`) and the * results are merged into one signed verdict envelope, so the PR gets one * comment. * * Projects are discovered at the BASE commit (the merge-base), so a PR cannot * choose which project reviews its own files: a `dbt_project.yml` it adds, * removes, moves or re-lays-out never takes a file away from the project that * owns it on the base branch, and such a project file is listed as not fully * verified. A project that does not exist at the base and holds files no base * project contains is reviewed as its own project and marked as added. * * Policy precedence: the nearest `.altimate/review` file at or above the * directory reviewed, up to the repository root (each read from the base * branch, as in a single-project review). A sibling directory's policy never * applies, whichever directory the command runs from. */ const PROJECT_FILE = /(^|\/)dbt_project\.ya?ml$/ const IGNORED_DIR = /(^|\/)(dbt_packages|target|node_modules|\.venv|venv|site-packages)\// const VERDICT_RANK: Record = { APPROVE: 0, COMMENT: 1, REQUEST_CHANGES: 2 } const TIER_RANK: Record = { trivial: 0, lite: 1, full: 2 } type AiStatus = NonNullable type VerifierStatus = NonNullable type ProjectEntry = NonNullable["projects"]>[number] const AI_STATE_RANK: Record = { skipped: 0, ok: 1, timeout: 2, error: 3 } const VERIFIER_STATE_RANK: Record = { skipped: 0, ok: 1, budget: 2, timeout: 3, error: 4 } /** Most discarded findings kept on the merged verifier record (as on one project's). */ const VERIFIER_DROPPED_MAX = 20 /** Most `at` locations kept per withheld rule (as on one project's). */ const WITHHELD_AT_MAX = 5 /** Reason for a file outside every reviewed project (the projects are listed in `scope.projects`). */ const OUTSIDE_ALL = "outside the dbt projects reviewed" /** Overall time for every project's review: 30 minutes (two AI lane deadlines). */ export const ALL_PROJECTS_BUDGET_MS = 1_800_000 /** The run's overall budget: `ALTIMATE_REVIEW_ALL_PROJECTS_BUDGET_MS`, else 30 minutes. */ export function allProjectsBudgetMs(env: Record = process.env): number { const n = Number(env.ALTIMATE_REVIEW_ALL_PROJECTS_BUDGET_MS) return env.ALTIMATE_REVIEW_ALL_PROJECTS_BUDGET_MS && Number.isFinite(n) && n > 0 ? n : ALL_PROJECTS_BUDGET_MS } /** Fixed reasons for dbt project files the PR changes (see `projectFileNotes`). */ export const PROJECT_FILE_REASON = { added: "dbt project file added by this PR inside an existing project; its files are reviewed with that project, as on the base branch", removed: "dbt project file removed or moved by this PR; the project's other changed files are still assigned to it, as on the base branch, but checked without its base layout", layout: "this PR changes the project's resource paths (`model-paths` and the like); files are assigned to projects as on the base branch, but checked with the new layout", } as const /** Fixed reason for the files of a project whose directory the PR removes. */ export const PROJECT_GONE_REASON = "the dbt project's directory is removed by this PR; its changed files were not reviewed" /** Fixed reason for the files of a project the time budget left unreviewed: the deterministic * reviews alone used the whole budget. */ export const BUDGET_REASON = "not reviewed: the `--all-projects` time budget ran out before this project's review started" /** Fixed reason for a project reviewed with its AI lane off because AI work used the budget. */ export const BUDGET_AI_REASON = "skipped: the `--all-projects` time budget left no time for this project's AI lane; the deterministic review ran in full" /** Least AI lane time worth starting under `--all-projects`: a quarter of the lane deadline (or of the * budget, when smaller), at most one minute. */ export function minAiLaneMs(laneMs: number = aiLaneTimeoutMs()): number { return Math.min(60_000, laneMs / 4) } /** Fixed reason for the files of a project whose review threw. */ export const PROJECT_FAILED_REASON = "The review of this dbt project hit an internal error. See the job log for details." /** Where each dbt project's file is, by project root ("" = repo root). */ export function projectFiles(files: string[]): Map { const out = new Map() for (const f of [...files].sort()) { if (!PROJECT_FILE.test(f) || IGNORED_DIR.test(f)) continue const dir = path.posix.dirname(f) const root = dir === "." ? "" : dir if (!out.has(root)) out.set(root, f) } return out } /** Repo-relative roots ("" = repo root) of every dbt project at `ref` (default: the working * tree), sorted; undefined when git cannot list the files. */ export async function discoverDbtProjects(gitRoot: string, ref?: string): Promise { const files = ref ? await listFilesAt(gitRoot, ref) : await listWorkingTreeFiles(gitRoot) return files && [...projectFiles(files).keys()].sort() } /** The deepest project root containing the repo-relative path `p`, or undefined. */ export function owningProject(p: string, roots: Iterable): string | undefined { let best: string | undefined for (const r of roots) { if (r !== "" && !p.startsWith(r + "/")) continue if (best === undefined || r.length > best.length) best = r } return best } /** Where projects are, for assigning changed files: the base commit's projects (with the * directories their base `dbt_project.yml` declares) and the projects only the head has. */ export interface ProjectMap { base: string[] /** Repo-relative resource directories of each base project (`model-paths` etc. at base). */ baseDirs?: Map /** Projects at the head that do not exist at base. */ added?: string[] } /** The projects a path belongs to: the deepest base project containing it; else every base * project whose base resource paths contain it; else the deepest project the PR adds. */ export function projectsFor(p: string, map: ProjectMap): string[] { const own = owningProject(p, map.base) if (own !== undefined) return [own] const viaDirs = map.base.filter((r) => (map.baseDirs?.get(r) ?? []).some((d) => relativeToRoot(p, d) !== undefined)) if (viaDirs.length) return viaDirs const added = owningProject(p, map.added ?? []) return added === undefined ? [] : [added] } /** Assign each changed file to its projects (see `projectsFor`). A rename whose old and new * paths belong to different projects goes to both: a deletion from one, an addition to the other. */ export function assignToProjects( files: ChangedFile[], map: ProjectMap, ): { byProject: Map; unassigned: ChangedFile[] } { const byProject = new Map() const unassigned: ChangedFile[] = [] for (const f of files) { const roots = new Set([...projectsFor(f.path, map), ...(f.oldPath ? projectsFor(f.oldPath, map) : [])]) if (!roots.size) unassigned.push(f) for (const r of roots) byProject.set(r, [...(byProject.get(r) ?? []), f]) } return { byProject, unassigned } } async function canonical(p: string): Promise { try { return await realpath(p) } catch { return path.resolve(p) } } /** `abs` relative to the repo root in POSIX form, or undefined when outside it. */ function repoRel(gitRootReal: string, abs: string): string | undefined { const rel = path.relative(gitRootReal, abs).replace(/\\/g, "/") if (rel === ".." || rel.startsWith("../") || path.isAbsolute(rel)) return undefined return rel } /** The ancestors of `dir` up to the repo root, nearest first ([] for the root or a path outside it). */ function ancestorsUpToRoot(gitRootReal: string, dir: string): string[] { let rel = repoRel(gitRootReal, dir) const out: string[] = [] while (rel) { rel = path.posix.dirname(rel) === "." ? "" : path.posix.dirname(rel) out.push(path.join(gitRootReal, rel)) } return out } /** A project root for the job log: control characters replaced, so a name cannot forge a log line. */ const logName = (root: string) => (root || ".").replace(/[\u0000-\u001f\u007f]/g, "?") /** One unverified/not-reviewed entry the multi-project review adds (fixed reason). */ type Note = { path: string; reason: string; kind: "abstained" | "failed" } /** * Notes for the dbt project files a PR changes: one it adds inside an existing project, * one it removes or moves away, one whose resource paths it changes. None of them moves a * file to another project (assignment follows the base commit); they are listed as not * fully verified. An added one does not hold back approval (the files are reviewed with the * base project, whose layout is unchanged). A removed one or a layout change holds back * approval when the project has other changed files: those were classified by a layout the * base branch does not have, so a file may have been missed as a model. */ async function projectFileNotes( files: ChangedFile[], map: ProjectMap, baseProjectFiles: Set, byProject: Map, readBase: (rel: string) => Promise, readHead: (rel: string) => Promise, ): Promise { const notes: Note[] = [] const rootOf = (p: string) => (path.posix.dirname(p) === "." ? "" : path.posix.dirname(p)) const othersChanged = (root: string) => (byProject.get(root) ?? []).some((f) => !PROJECT_FILE.test(f.path)) const note = (p: string, reason: string, holdsBack = false) => notes.push({ path: p, reason, kind: holdsBack && othersChanged(rootOf(p)) ? "failed" : "abstained" }) for (const f of files) { for (const p of new Set([f.path, ...(f.oldPath ? [f.oldPath] : [])])) { if (!PROJECT_FILE.test(p) || IGNORED_DIR.test(p)) continue const gone = f.status === "deleted" || (p === f.oldPath && p !== f.path) if (baseProjectFiles.has(p)) { if (gone) note(p, PROJECT_FILE_REASON.removed, true) else { const [before, after] = await Promise.all([readBase(p), readHead(p)]) const layout = (text: string | undefined) => JSON.stringify(text === undefined ? null : (parseDbtProjectLayout(text, rootOf(p))?.dirs ?? null)) if (layout(before) !== layout(after)) note(p, PROJECT_FILE_REASON.layout, true) } } else if (!gone && owningProject(p, map.base) !== undefined) { // New at this path inside a base project: it creates no project of its own here. note(p, PROJECT_FILE_REASON.added) } } } return notes } /** `env` with `notes` listed (unverified and not reviewed) and `projects` recorded, re-signed. */ function withNotes(env: VerdictEnvelope, notes: Note[], projects?: ProjectEntry[]): VerdictEnvelope { const scope = env.scope ?? { notReviewed: [] } const seen = new Set((scope.unverified ?? []).map((u) => `${u.path}\0${u.reason}`)) const fresh = notes.filter((n) => !seen.has(`${n.path}\0${n.reason}`) && !!seen.add(`${n.path}\0${n.reason}`)) const unverified = [...(scope.unverified ?? []), ...fresh] // A note that holds back approval turns an approval into a comment; nothing else changes. const held = fresh.some((n) => n.kind === "failed") return signEnvelope( VerdictEnvelope.parse({ ...env, verdict: held && env.verdict === "APPROVE" ? "COMMENT" : env.verdict, idealVerdict: held && env.idealVerdict === "APPROVE" ? "COMMENT" : env.idealVerdict, scope: { ...scope, unverified: unverified.length ? unverified : undefined, notReviewed: [...(scope.notReviewed ?? []), ...fresh.map((n) => ({ path: n.path, reason: n.reason }))], projects: projects ?? scope.projects, }, signature: undefined, }), ) } /** Test seams for `reviewAllProjects`. */ export interface ReviewAllProjectsDeps { /** Reviews one project (default `reviewPullRequest`). */ reviewProject?: (opts: ReviewPullRequestOptions) => Promise /** Overall budget in milliseconds (default `allProjectsBudgetMs()`). */ budgetMs?: number } export async function reviewAllProjects( opts: ReviewPullRequestOptions, deps: ReviewAllProjectsDeps = {}, ): Promise { const review = deps.reviewProject ?? reviewPullRequest const budgetMs = deps.budgetMs ?? allProjectsBudgetMs() const gitRoot = (await gitRepoRoot(opts.cwd)) ?? opts.cwd const gitRootReal = await canonical(gitRoot) const cwdReal = await canonical(opts.cwd) // Every project is reviewed at one head commit, resolved once. const head = opts.head ? await resolveHeadRef(opts.head, opts.cwd) : undefined const resolved = await resolveReviewBase({ cwd: opts.cwd, base: opts.base, head }) const shared: ReviewPullRequestOptions = { ...opts, head } // Reviewed from the invocation directory: its own policy, else the nearest one above it. const inPlace: ReviewPullRequestOptions = { ...shared, policyFallbackDirs: ancestorsUpToRoot(gitRootReal, cwdReal) } const collected = opts.changedFiles ?? (await collectChangedFiles({ base: resolved.sha, head, cwd: opts.cwd })) // Projects at the base commit (and the head, for projects the PR adds). A failure to list // them is reported and keeps the run from approving; it never falls back silently. let discoveryError: unknown const onError = (err: unknown) => void (discoveryError ??= err) const [baseList, headList] = await Promise.all([ listFilesAt(gitRoot, resolved.sha, onError), head ? listFilesAt(gitRoot, head, onError) : listWorkingTreeFiles(gitRoot, onError), ]) if (!baseList || !headList) { const failure = reportFailure("internal_error", { check: "project discovery" }, discoveryError) const env = await review(inPlace) return signEnvelope( VerdictEnvelope.parse({ ...env, verdict: env.verdict === "APPROVE" ? "COMMENT" : env.verdict, idealVerdict: env.idealVerdict === "APPROVE" ? "COMMENT" : env.idealVerdict, internalFailure: true, engineErrors: [ ...(env.engineErrors ?? []), { method: "project discovery", reason: failure.message, count: 1, category: "internal_error" }, ], signature: undefined, }), ) } const baseFiles = projectFiles(baseList) const headFiles = projectFiles(headList) const baseRoots = [...baseFiles.keys()].sort() const readBase = (rel: string) => showAtRef(gitRoot, resolved.sha, rel) const readHead = (rel: string) => head ? showAtRef(gitRoot, head, rel) : readFile(path.join(gitRootReal, rel), "utf8").catch(() => undefined) // Each base project's resource directories, from its base dbt_project.yml. const baseDirs = new Map() for (const [root, file] of baseFiles) { const text = await readBase(file) const layout = text === undefined ? undefined : parseDbtProjectLayout(text, root) if (layout) baseDirs.set(root, resolvedLayoutDirs(layout).map((d) => d.dir)) } const map: ProjectMap = { base: baseRoots, baseDirs, added: [...headFiles.keys()].filter((r) => !baseFiles.has(r)).sort() } const { byProject, unassigned } = assignToProjects(collected, map) const touched = [...byProject.keys()].sort() const addedRoots = new Set(map.added) const notes = await projectFileNotes(collected, map, new Set(baseFiles.values()), byProject, readBase, readHead) if (touched.length === 0) return withNotes(await review(inPlace), notes, []) // An explicit --manifest belongs to the project that contains it. One outside every project // (CI's `$RUNNER_TEMP/manifest.json`) belongs to the project the command runs in, if any. const allRoots = [...baseRoots, ...touched.filter((r) => addedRoots.has(r))] const cwdRel = repoRel(gitRootReal, cwdReal) const cwdOwner = cwdRel === undefined ? undefined : owningProject(cwdRel + "/", allRoots) const manifestAbs = opts.manifestPath ? await canonical(path.isAbsolute(opts.manifestPath) ? opts.manifestPath : path.join(opts.cwd, opts.manifestPath)) : undefined const manifestRel = manifestAbs ? repoRel(gitRootReal, manifestAbs) : undefined const manifestOwner = (manifestRel !== undefined ? owningProject(manifestRel, allRoots) : undefined) ?? cwdOwner const manifestFor = (root: string) => (manifestAbs && root === manifestOwner ? manifestAbs : undefined) if (manifestAbs && (manifestOwner === undefined || !touched.includes(manifestOwner))) { const where = manifestOwner === undefined ? "is outside every dbt project" : "belongs to a project this PR does not change" process.stderr.write( `⚠️ --manifest ${where}, so no reviewed project uses it; each project auto-discovers its own. ` + "Place the manifest inside the project it describes (e.g. its target/), or run from that project's directory.\n", ) } const optsFor = (root: string): ReviewPullRequestOptions => { const rootAbs = path.join(gitRootReal, root) // Invoked from inside the project: the single-project review from there. const here = cwdOwner === root return { ...shared, cwd: here ? opts.cwd : rootAbs, manifestPath: manifestFor(root), policyFallbackDirs: ancestorsUpToRoot(gitRootReal, here ? cwdReal : rootAbs), } } // Projects run one after another within one budget. The budget bounds AI work: each AI // lane gets at most what is left, and once too little is left the remaining projects are // reviewed with the AI lane off. AI time never skips a project's deterministic review: a // project is listed as not reviewed only when the deterministic reviews run with the AI // lane off have, by themselves, used the whole budget. const prFiles = collected.map((f) => f.path) const runs: ProjectRun[] = [] const startedAt = Date.now() let deterministicMs = 0 // Python files outside every project go to one project's AI lane only (`pythonFiles`, off by // default): each is offered to project after project until a lane reviews it. const pendingOutside = new Set(unassigned.map((f) => f.path)) for (const root of touched) { const own = byProject.get(root)! const received = [...own, ...unassigned] const run = { root, paths: own.map((f) => f.path), received: received.map((f) => f.path), added: addedRoots.has(root) || undefined } const remaining = budgetMs - (Date.now() - startedAt) if (deterministicMs >= budgetMs) { runs.push({ ...run, ...placeholder(root, own, "budget", opts.mode) }) continue } const aiOff = !opts.noAi && remaining < minAiLaneMs(Math.min(aiLaneTimeoutMs(), budgetMs)) if (!(await stat(path.join(gitRootReal, root)).then((s) => s.isDirectory(), () => false))) { // The PR removes the project's directory: there is nothing left to run its review in. const env = signEnvelope( buildEnvelope({ findings: [], tier: "trivial", mode: opts.mode ?? "comment", scope: { projectRoot: root, notReviewed: [] } }), ) // A file moved out of the removed directory is listed by its old path, the one in this project. const inRoot = (p: string | undefined) => !!p && (root === "" || p.startsWith(root + "/")) const gonePaths = own.map((f) => (inRoot(f.oldPath) ? f.oldPath! : f.path)) runs.push({ ...run, removed: true, env: withNotes(env, gonePaths.map((p) => ({ path: p, reason: PROJECT_GONE_REASON, kind: "abstained" }))), }) continue } process.stderr.write(`ℹ️ reviewing dbt project ${logName(root)} (${own.length} changed file(s))\n`) const projectStart = Date.now() try { const env = await review({ ...optsFor(root), changedFiles: received, prFiles, aiOutsidePaths: [...pendingOutside], ...(aiOff ? { noAi: true, noAiReason: BUDGET_AI_REASON } : remaining < aiLaneTimeoutMs() ? { aiLaneTimeoutMs: remaining } : {}), }) if (aiOff || opts.noAi) deterministicMs += Date.now() - projectStart for (const p of outsideTaken(env)) pendingOutside.delete(p) runs.push({ ...run, env }) } catch (err) { reportFailure("internal_error", { check: "project review", path: root || "." }, err) runs.push({ ...run, ...placeholder(root, own, "failed", opts.mode) }) } } if (runs.length === 1 && !runs[0].status) return withNotes(runs[0].env, notes, [projectEntry(runs[0])]) return withNotes(mergeProjectEnvelopes(runs), notes) } /** The envelope for a project that was not reviewed (`budget`) or whose review threw * (`failed`): its files are listed as failed, so the run cannot approve; a throw also sets * `internalFailure`. */ function placeholder( root: string, own: ChangedFile[], status: "budget" | "failed", mode: ReviewMode | undefined, ): { env: VerdictEnvelope; status: "budget" | "failed" } { const reason = status === "budget" ? BUDGET_REASON : PROJECT_FAILED_REASON const unverified = own.map((f) => ({ path: f.path, reason, kind: "failed" as const, ...(status === "failed" ? { category: "internal_error" as const } : {}), })) const env = signEnvelope( buildEnvelope({ findings: [], tier: "trivial", mode: mode ?? "comment", internalFailure: status === "failed", scope: { projectRoot: root, unverified, notReviewed: unverified.map((u) => ({ path: u.path, reason: u.reason })) }, }), ) return { env, status } } /** * The outside-project files a project's AI lane took: only those it reviewed * (`scope.aiReviewedOutside`: sent in a call that answered). A file in a failed call, over * the quota, in a dry run, or in a lane that errored, timed out or had no model stays * pending for the next project. */ export function outsideTaken(env: Pick): string[] { return env.scope?.aiReviewedOutside ?? [] } /** One project's review: its repo-relative root, the changed files assigned to it, and its envelope. */ export interface ProjectRun { root: string paths: string[] env: VerdictEnvelope /** Every path the project's review was given (its own and the files outside every project). */ received?: string[] /** Not reviewed (`budget`) or its review threw (`failed`). */ status?: "budget" | "failed" /** The project does not exist at the base commit. */ added?: true /** The PR removes the project's directory; nothing was reviewed in it. */ removed?: true } function projectEntry(r: ProjectRun): ProjectEntry { return { root: r.root, files: r.paths.length, verdict: r.env.verdict, mode: r.env.mode, manifestHash: r.env.manifestHash, policyHash: r.env.policy?.hash, status: r.status, added: r.added, removed: r.removed, lintOnly: r.env.summary.degraded && !r.status ? true : undefined, } } /** Merge per-project envelopes into one signed envelope (see reviewAllProjects). */ export function mergeProjectEnvelopes(runs: ProjectRun[]): VerdictEnvelope { const envs = runs.map((r) => r.env) // Run-level facts come from a project that was reviewed, when there is one. const lead = runs.find((r) => !r.status)?.env ?? envs[0] // A file two projects review (a shared macro directory) yields one finding id: listed once, counted once. const seenIds = new Set() const duplicates: VerdictEnvelope["findings"] = [] const findings = envs .flatMap((e) => e.findings) .filter((f) => (seenIds.has(f.id) ? (duplicates.push(f), false) : !!seenIds.add(f.id))) // Each project's mode is its policy's, with `--mode` applied only where it tightens it // (reviewPullRequest); the merge never re-applies the flag. const mode = envs.some((e) => e.mode === "gate") ? "gate" : "comment" const worst = (vs: Verdict[]) => vs.reduce((a, b) => (VERDICT_RANK[b] > VERDICT_RANK[a] ? b : a)) const maxTier = (ts: RiskTier[]) => ts.reduce((a, b) => (TIER_RANK[b] > TIER_RANK[a] ? b : a)) const tierReasons = [...new Set(envs.flatMap((e) => e.tierReasons ?? []))] const forced = envs.filter((e) => e.tierForced) // A path is "outside" only when every project review given it found it outside. const inScopeSomewhere = new Set() for (const r of runs) { // A file the project's AI lane reviewed outside the project (`pythonFiles`) is outside it too. const outside = new Set([ ...(r.env.scope?.notReviewed ?? []).filter((n) => isOutsideProjectReason(n.reason)).map((n) => n.path), ...(r.env.scope?.aiReviewedOutside ?? []), ]) for (const p of r.received ?? r.paths) if (!outside.has(p)) inScopeSomewhere.add(p) } // Outside-project files one project's AI lane reviewed: not listed as not reviewed, but // still counted in `outOfScopeFiles` (no deterministic check covered them). const aiOnlyOutside = [...new Set(envs.flatMap((e) => e.scope?.aiReviewedOutside ?? []))].filter((p) => !inScopeSomewhere.has(p)) const aiOnly = new Set(aiOnlyOutside) const notReviewed: Array<{ path: string; reason: string }> = [] const seenEntry = new Set() for (const e of envs) { for (const n of e.scope?.notReviewed ?? []) { const outside = isOutsideProjectReason(n.reason) if (outside && (inScopeSomewhere.has(n.path) || aiOnly.has(n.path))) continue const key = outside ? `outside\0${n.path}` : `${n.path}\0${n.reason}` if (seenEntry.has(key)) continue seenEntry.add(key) notReviewed.push(outside ? { path: n.path, reason: OUTSIDE_ALL } : n) } } const outsideCount = notReviewed.filter((n) => isOutsideProjectReason(n.reason)).length + aiOnlyOutside.length const movedCount = envs.reduce((s, e) => s + (e.scope?.movedUnchangedFiles ?? 0), 0) const unverified = envs.flatMap((e) => e.scope?.unverified ?? []) const disabledModels = [...new Set(envs.flatMap((e) => e.scope?.disabledModels ?? []))] const engineErrors = new Map[number]>() for (const err of envs.flatMap((e) => e.engineErrors ?? [])) { const key = `${err.method}\0${err.reason}\0${err.category ?? ""}` const prev = engineErrors.get(key) engineErrors.set(key, prev ? { ...prev, count: prev.count + err.count } : { ...err }) } // Per rule and reason, as on one project's; every project's full list is kept. const withheld = new Map[number]>() for (const w of envs.flatMap((e) => e.withheld ?? [])) { // Off by default in one project and by its policy in another: two entries, two wordings. const key = `${w.rule}\0${w.reason ?? ""}\0${w.byDefault ? "default" : ""}` const prev = withheld.get(key) if (!prev) { withheld.set(key, { ...w }) continue } const at = [...(prev.at ?? []), ...(w.at ?? [])].slice(0, WITHHELD_AT_MAX) const list = prev.findings || w.findings ? [...(prev.findings ?? []), ...(w.findings ?? [])] : undefined withheld.set(key, { rule: w.rule, ...(w.reason ? { reason: w.reason } : {}), count: prev.count + w.count, verdict: prev.verdict + w.verdict, at: at.length ? at : undefined, ...(w.byDefault ? { byDefault: true as const } : {}), ...(list ? { findings: list } : {}), }) } // The headline counts every project's own tally (each repeat of a rule included), less the // findings listed once for two projects. const summary = { critical: 0, warning: 0, suggestion: 0, degraded: envs.some((e) => e.summary.degraded) } for (const e of envs) for (const sev of ["critical", "warning", "suggestion"] as const) summary[sev] += e.summary[sev] for (const f of duplicates) if (!f.preExisting) summary[f.severity] = Math.max(0, summary[f.severity] - 1) const internalFailure = envs.some((e) => e.internalFailure) // Each project's verdict already has its own mode applied: a project whose mode ended up // `comment` never blocks. A project that did not complete never lets the merge approve. const incomplete = internalFailure || envs.some((e) => reviewIncomplete(e)) const atLeastComment = (v: Verdict): Verdict => (v === "APPROVE" && incomplete ? "COMMENT" : v) const idealVerdict = atLeastComment(worst(envs.map((e) => e.idealVerdict))) const verdict = atLeastComment(applyMode(worst(envs.map((e) => e.verdict)), mode)) // Per-project values are recorded in `scope.projects`; the top level carries one only when every project agrees. const same = (vals: T[]): T | undefined => vals.every((v) => JSON.stringify(v) === JSON.stringify(vals[0])) ? vals[0] : undefined const merged: VerdictEnvelope = { version: lead.version, verdict, idealVerdict, mode, tier: maxTier(envs.map((e) => e.tier)), tierReasons: tierReasons.length ? tierReasons : undefined, tierForced: forced.length ? true : undefined, tierClassified: forced.length ? maxTier(forced.map((e) => e.tierClassified!)) : undefined, findings, summary, engine: lead.engine, manifestHash: same(envs.map((e) => e.manifestHash)), staleManifest: envs.some((e) => e.staleManifest) ? true : undefined, engineErrors: engineErrors.size ? [...engineErrors.values()] : undefined, internalFailure: internalFailure ? true : undefined, withheld: withheld.size ? [...withheld.values()] : undefined, // Hidden findings decide the merged verdict only when every project at the worst verdict // owes it to its own hidden findings; a project there that does not keeps it without them. withheldDecides: withheld.size ? withheldDecidesMerged(envs) : undefined, policy: mergePolicy(envs), scope: { baseRef: lead.scope?.baseRef, baseSha: lead.scope?.baseSha, baseSource: lead.scope?.baseSource, outOfScopeFiles: outsideCount || undefined, aiReviewedOutside: aiOnlyOutside.length ? aiOnlyOutside : undefined, movedUnchangedFiles: movedCount || undefined, disabledModels: disabledModels.length ? disabledModels : undefined, unverified: unverified.length ? unverified : undefined, notReviewed, projects: runs.map(projectEntry), }, ai: mergeAi(runs), generatedAt: lead.generatedAt, } return signEnvelope(VerdictEnvelope.parse(merged)) } /** Least-trusted source first: a policy the PR controls outranks the defaults, which outrank the base branch's. */ const POLICY_SOURCE_RANK = { base: 0, default: 1, working_tree: 2 } as const /** One project's policy when all agree; otherwise the least-trusted source, a hash of every * project's hash, every setting the PR changes, and the posting policy only if shared. * A project that was not reviewed has no policy and is left out. */ function mergePolicy(envs: VerdictEnvelope[]): VerdictEnvelope["policy"] { const all = envs.map((e) => e.policy).filter((p): p is NonNullable => !!p) if (!all.length) return undefined if (all.every((p) => JSON.stringify(p) === JSON.stringify(all[0]))) return all[0] const changed = [...new Set(all.flatMap((p) => p.changedInPr ?? []))] const postings = all.map((p) => JSON.stringify(p.posting)) return { source: all.map((p) => p.source).reduce((a, b) => (POLICY_SOURCE_RANK[b] > POLICY_SOURCE_RANK[a] ? b : a)), hash: createHash("sha256").update(all.map((p) => p.hash).join("\n")).digest("hex").slice(0, 16), changedInPr: changed.length ? changed : undefined, posting: postings.every((x) => x === postings[0]) ? all[0].posting : undefined, } } /** A per-project reason on the merged record: the project as a code span, then the * project's own reason, which is fixed text (`failure.ts`, lane constants). */ const projectReason = (root: string, reason: string) => `${projectLabel(root)}: ${reason}` function withheldDecidesMerged(envs: VerdictEnvelope[]): boolean { const top = envs.map((e) => e.idealVerdict).reduce((a, b) => (VERDICT_RANK[b] > VERDICT_RANK[a] ? b : a)) const decides = (e: VerdictEnvelope) => e.withheldDecides === true return envs.filter((e) => e.idealVerdict === top).every(decides) } function mergeAi(runs: ProjectRun[]): VerdictEnvelope["ai"] { const lanes = runs.filter((r) => r.env.ai) if (!lanes.length) return undefined const ais = lanes.map((r) => r.env.ai!) const first = ais[0] const ok = ais.find((a) => a.state === "ok") // The worst state wins (a sibling's error or timeout is not hidden by another project's ok), // with that project's reason; `skipped` (nothing to send) ranks below `ok`. const worstLane = lanes.reduce((a, b) => (AI_STATE_RANK[b.env.ai!.state] > AI_STATE_RANK[a.env.ai!.state] ? b : a)) const state = worstLane.env.ai!.state const base = ok ?? first // An `ok` lane with a reason is a partial failure: the first such project's reason. const reasonLane = state === "ok" ? lanes.find((r) => r.env.ai!.state === "ok" && r.env.ai!.reason) : worstLane const laneReason = reasonLane?.env.ai!.reason // Projects whose AI lane the time budget turned off are named, whichever lane's reason leads. const budgetOff = lanes.filter((r) => r.env.ai!.state === "skipped" && r.env.ai!.reason === BUDGET_AI_REASON) const budgetNote = lanes.length > 1 && budgetOff.length && budgetOff.length < lanes.length ? `the \`--all-projects\` time budget left no time for the AI lane of ${budgetOff.map((r) => projectLabel(r.root)).join(", ")}; their deterministic review ran in full` : undefined const reason = laneReason && lanes.length > 1 ? projectReason(reasonLane!.root, laneReason) : laneReason const input = ais.some((a) => a.input) ? ais.flatMap((a) => a.input ?? []) : undefined const unsent = ais.flatMap((a) => a.unsent ?? []) const notSent = ais.flatMap((a) => a.notSent ?? []).sort() const foreignDropped = ais.reduce((n, a) => n + (a.foreignDropped ?? 0), 0) const notSentReasons = ais.flatMap((a) => a.notSentReasons ?? []).sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)) const truncated = ais.flatMap((a) => a.truncated ?? []).sort() const unreviewed = ais.flatMap((a) => a.unreviewed ?? []) // 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, c.skipped ?? ""]) return !seenConv.has(key) && !!seenConv.add(key) }) return { ...base, state, reason: [reason, budgetNote].filter(Boolean).join("; ") || undefined, model: base.model ?? first.model, calls: sumOf(ais.map((a) => a.calls)), failedCalls: sumOf(ais.map((a) => a.failedCalls)), tokens: sumTokens(ais.map((a) => a.tokens)), cost: sumOf(ais.map((a) => a.cost)), durationMs: sumOf(ais.map((a) => a.durationMs)), input, unsent: unsent.length ? unsent : undefined, notSent: notSent.length ? notSent : undefined, foreignDropped: foreignDropped || undefined, notSentReasons: notSentReasons.length ? notSentReasons : undefined, truncated: truncated.length ? truncated : undefined, cardsFailed: sumOf(ais.map((a) => a.cardsFailed)), unreviewed: unreviewed.length ? unreviewed : undefined, conventions: conventions.length ? conventions : undefined, verifier: mergeVerifier(lanes.map((r) => ({ root: r.root, v: r.env.ai!.verifier }))), notPosted: mergeNotPosted(ais.map((a) => a.notPosted)), ruleVerifier: mergeRuleVerifier(ais.map((a) => a.ruleVerifier)), projects: lanes.map((r) => ({ root: r.root, state: r.env.ai!.state, reason: r.env.ai!.reason, calls: r.env.ai!.calls })), } } function sumOf(vals: Array): number | undefined { const nums = vals.filter((v): v is number => v !== undefined) return nums.length ? nums.reduce((a, b) => a + b, 0) : undefined } function sumTokens(vals: Array): AiStatus["tokens"] { const present = vals.filter((t) => t !== undefined) return present.length ? present.reduce((a, b) => ({ input: a.input + b.input, inputTotal: a.inputTotal + b.inputTotal, output: a.output + b.output, reasoning: a.reasoning + b.reasoning, cacheRead: a.cacheRead + b.cacheRead, })) : undefined } /** Every project's verifier: the worst state (with its project's reason), summed usage and counters, all decisions. */ function mergeVerifier(runs: Array<{ root: string; v: AiStatus["verifier"] }>): AiStatus["verifier"] { const present = runs.filter((r): r is { root: string; v: VerifierStatus } => r.v !== undefined) if (!present.length) return undefined if (present.length === 1) return present[0].v const vs = present.map((r) => r.v) const worstRun = present.reduce((a, b) => (VERIFIER_STATE_RANK[b.v.state] > VERIFIER_STATE_RANK[a.v.state] ? b : a)) const dropped = vs.flatMap((v) => v.dropped ?? []) const decisions = vs.flatMap((v) => v.decisions ?? []) return { state: worstRun.v.state, reason: worstRun.v.reason ? projectReason(worstRun.root, worstRun.v.reason) : undefined, durationMs: sumOf(vs.map((v) => v.durationMs)), tokens: sumTokens(vs.map((v) => v.tokens)), cost: sumOf(vs.map((v) => v.cost)), turns: sumOf(vs.map((v) => v.turns)), toolCalls: sumOf(vs.map((v) => v.toolCalls)), toolErrors: sumOf(vs.map((v) => v.toolErrors)), reviewed: sumOf(vs.map((v) => v.reviewed)), kept: sumOf(vs.map((v) => v.kept)), discarded: sumOf(vs.map((v) => v.discarded)), summary: sumOf(vs.map((v) => v.summary)), unreviewed: sumOf(vs.map((v) => v.unreviewed)), dropped: dropped.length ? dropped.slice(0, VERIFIER_DROPPED_MAX) : undefined, decisions: decisions.length ? decisions : undefined, } } /** Every project's not-posted list: one source and list when all agree, else the union; any error kept. */ function mergeNotPosted(lists: Array): AiStatus["notPosted"] { const present = lists.filter((l): l is NonNullable => l !== undefined) if (!present.length) return undefined const error = present.find((l) => l.error)?.error return { source: present.some((l) => l.source === "file") ? "file" : "default", rules: [...new Set(present.flatMap((l) => l.rules))].sort(), ...(error ? { error } : {}), } } type RuleVerifier = NonNullable const RULE_VERIFIER_STATE_RANK: Record = { skipped: 0, ok: 1, budget: 2, timeout: 3, error: 4 } /** Every project's rule verifier: the worst state (its fixed reason), summed counts and usage, every * verdict with its batch index offset by the batches of earlier projects. */ function mergeRuleVerifier(runs: Array): AiStatus["ruleVerifier"] { const rs = runs.filter((r): r is RuleVerifier => r !== undefined) if (rs.length <= 1) return rs[0] const worstRun = rs.reduce((a, b) => (RULE_VERIFIER_STATE_RANK[b.state] > RULE_VERIFIER_STATE_RANK[a.state] ? b : a)) let offset = 0 const verdicts: NonNullable = [] const batches: NonNullable = [] for (const r of rs) { for (const v of r.verdicts ?? []) verdicts.push(v.batch === undefined ? v : { ...v, batch: v.batch + offset }) batches.push(...(r.batches ?? [])) offset += r.batches?.length ?? 0 } const sum = (k: "turns" | "toolCalls" | "candidates" | "sent" | "reviewed" | "withheld") => rs.reduce((n, r) => n + r[k], 0) const toolErrors = sumOf(rs.map((r) => r.toolErrors)) return { state: worstRun.state, ...(worstRun.reason ? { reason: worstRun.reason } : {}), ...(rs.find((r) => r.model)?.model ? { model: rs.find((r) => r.model)!.model } : {}), durationMs: sumOf(rs.map((r) => r.durationMs)), tokens: sumTokens(rs.map((r) => r.tokens)), cost: sumOf(rs.map((r) => r.cost)), turns: sum("turns"), toolCalls: sum("toolCalls"), ...(toolErrors ? { toolErrors } : {}), candidates: sum("candidates"), sent: sum("sent"), reviewed: sum("reviewed"), withheld: sum("withheld"), ...(verdicts.length ? { verdicts } : {}), ...(batches.length ? { batches } : {}), } }