Repository navigation
fix(review): verdict trust: only the engine blocks, policy from the base branch, allowForceTier #1722
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(review): verdict trust: only the engine blocks, policy from the base branch, allowForceTier #1722
Changes from all commits
0e95696
b33c042
32ed5e7
df4f6d6
699c779
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -288,16 +288,38 @@ exclude: | |
| riskTierPathTokens: # OFF by default — see "Risk-tier path tokens" below | ||
| finops: [preset:finops] # promote any FinOps-named path to `full` tier | ||
| pii: [ssn, email, phone] # or supply your own case-insensitive tokens | ||
| allowForceTier: true # set false in gate CI: --force-tier is then rejected | ||
| rubric: | ||
| blockOn: [lineage_breakage, contract_violation, pii_exposure, semantic_change] | ||
| warningPatternThreshold: 3 | ||
| blockingRules: [] # catalog rule ids allowed to block (default: engine only) | ||
| thresholds: | ||
| warehouseCostMinRows: 1000000 | ||
| exclusions: | ||
| allowSelectStarInStaging: true | ||
| skipNonProdModels: true | ||
| ``` | ||
|
|
||
| ### Which policy applies, and what can block | ||
|
|
||
| - **The base branch's `.altimate/review.yml` applies.** The file is read from the | ||
| commit the PR branched from, so a PR cannot relax the rules it is reviewed | ||
|
Comment on lines
+305
to
+306
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. State the base-policy guarantee's Git boundary. If an API caller supplies both Limit this guarantee to reviews that resolve a Git base. Document the working-tree fallback for pre-supplied files/content. This clarification does not require implementing the deferred policy-reader API.
|
||
| under (switch to `comment` mode, drop a `blockOn` category, exclude its own | ||
| paths). If the PR edits the file, the comment lists the changed settings; they | ||
| take effect after merge. The applied policy's hash is signed into the envelope | ||
| (`policy`). The action's `mode` and `severity_threshold` inputs (`--mode`, | ||
| `--severity`) can only tighten a base policy: they cannot turn `mode: gate` | ||
| into `comment` or raise its severity threshold. Other workflow steps are still | ||
| PR-editable, so protect `.github/` with CODEOWNERS or branch rules. | ||
| - **Only the deterministic engine blocks.** Findings carry an `origin`: | ||
| `engine` (AST, lineage, manifest, equivalence, data-diff), `catalog` (pattern | ||
| rules) or `ai`. Only `engine` findings count toward REQUEST_CHANGES. A pattern | ||
| rule you trust can be allowed to block by naming its id in | ||
| `rubric.blockingRules`. One pattern finding blocks without being named: a | ||
| highly sensitive PII column proven new when the base or the head cannot be | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. State the PII category requirement. If
|
||
| compiled, so the engine has nothing to compare (see the **PII** bullet under | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: The bullet this now points at still scopes the exception to a missing base compile The new sentence says the PII twin blocks "when the base or the head cannot be compiled", but the target it points at - the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P3: Update the referenced PII bullet to cover an uncompiled head as well as an uncompiled base; it currently describes only the base case, contradicting this exception. Prompt for AI agents |
||
| "What the PR comment shows"). The advisory AI lane never blocks. | ||
|
|
||
| ### What the PR comment shows | ||
|
|
||
| - **One summary comment**, updated in place on every push, capped at about | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,6 +2,7 @@ import z from "zod" | |
| import path from "node:path" | ||
| import { promises as fs } from "node:fs" | ||
| import YAML from "yaml" | ||
| import { createHash } from "node:crypto" | ||
| import { Rubric, DEFAULT_RUBRIC } from "./rubric" | ||
| import { ReviewMode } from "./verdict" | ||
| import { Severity } from "./finding" | ||
|
|
@@ -34,6 +35,9 @@ export const ReviewConfig = z.object({ | |
| * Functions missing on the project's own engine are always reported. | ||
| */ | ||
| portability: z.boolean().optional(), | ||
| /** Allow `--force-tier` (a debug bypass of the risk classifier). Set false | ||
| * in gate CI so a run cannot skip checks by forcing a lower tier. */ | ||
| allowForceTier: z.boolean().default(true), | ||
| /** | ||
| * Data-diff: actually run base-vs-head against the warehouse (core DataParity) | ||
| * and report row/value deltas. OPT-IN — it costs warehouse compute and needs a | ||
|
|
@@ -114,6 +118,106 @@ export function parseReviewConfig(text: string): ReviewConfig { | |
| return ReviewConfig.parse(data) | ||
| } | ||
|
|
||
| /** Where the applied policy came from. */ | ||
| export type PolicySource = "base" | "working_tree" | "default" | ||
|
|
||
| export interface ReviewPolicy { | ||
| config: ReviewConfig | ||
| source: PolicySource | ||
| /** Short hash of the applied config (canonical JSON), signed into the envelope. */ | ||
| hash: string | ||
| /** Settings the PR changes relative to the applied base policy (not applied). */ | ||
| changedInPr: string[] | ||
| } | ||
|
|
||
| function canonical(value: unknown): string { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not changing: nit. They serve different modules; consolidation can happen in a cleanup pass. |
||
| if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null" | ||
| if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]" | ||
| const obj = value as Record<string, unknown> | ||
| return ( | ||
| "{" + | ||
| Object.keys(obj) | ||
| .filter((k) => obj[k] !== undefined) | ||
| .sort() | ||
| .map((k) => JSON.stringify(k) + ":" + canonical(obj[k])) | ||
| .join(",") + | ||
| "}" | ||
| ) | ||
| } | ||
|
|
||
| /** Short, stable hash of a resolved config. */ | ||
| export function policyHash(config: ReviewConfig): string { | ||
| return createHash("sha256").update(canonical(config)).digest("hex").slice(0, 16) | ||
| } | ||
|
|
||
| /** Settings that differ between two configs: top-level keys, and `rubric.*` one level down. */ | ||
| export function policyChanges(base: ReviewConfig, head: ReviewConfig): string[] { | ||
| const out: string[] = [] | ||
| const keys = new Set([...Object.keys(base), ...Object.keys(head)]) as Set<keyof ReviewConfig> | ||
| for (const k of [...keys].sort()) { | ||
| if (canonical(base[k]) === canonical(head[k])) continue | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: Comparing parsed partial configs reports settings spelled out at their default values as changes Representation, not effective policy, drives this comparison. A base file with
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Follow-up: low priority, tracked. Compare |
||
| if (k === "rubric") { | ||
| const b = (base.rubric ?? {}) as Record<string, unknown> | ||
| const h = (head.rubric ?? {}) as Record<string, unknown> | ||
| for (const rk of [...new Set([...Object.keys(b), ...Object.keys(h)])].sort()) | ||
| if (canonical(b[rk]) !== canonical(h[rk])) out.push(`rubric.${rk}`) | ||
| } else out.push(k) | ||
| } | ||
| return out | ||
| } | ||
|
|
||
| async function readFirst(read: (rel: string) => Promise<string | undefined>): Promise<string | undefined> { | ||
| for (const rel of CANDIDATE_FILES) { | ||
| const text = await read(rel) | ||
| if (text !== undefined) return text | ||
| } | ||
| return undefined | ||
| } | ||
|
|
||
| /** | ||
| * Load the review policy the PR is judged by. | ||
| * | ||
| * With `readBase` (a reader over the merge-base commit), the policy is the | ||
| * BASE branch's `.altimate/review.yml`: a pull request must not be able to | ||
| * relax the rules it is reviewed under (switch `mode` to comment, drop a | ||
| * `blockOn` category, exclude its own paths, disable lanes). The PR's own | ||
| * version is parsed only to list what it would change, which the comment | ||
| * shows; it takes effect once merged. Without `readBase` (no git), the working | ||
| * tree's file applies. | ||
| */ | ||
| export async function loadReviewPolicy(opts: { | ||
| cwd: string | ||
| readBase?: (rel: string) => Promise<string | undefined> | ||
| }): Promise<ReviewPolicy> { | ||
| if (!opts.readBase) { | ||
| const config = await loadReviewConfig(opts.cwd) | ||
| const present = await readFirst((rel) => fs.readFile(path.join(opts.cwd, rel), "utf8").catch(() => undefined)) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: The no-git branch reads the same candidate file twice
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not changing: nit, one extra small file read on a non-default path. |
||
| return { config, source: present === undefined ? "default" : "working_tree", hash: policyHash(config), changedInPr: [] } | ||
| } | ||
| const baseText = await readFirst(opts.readBase) | ||
| let config: ReviewConfig | ||
| try { | ||
| config = baseText === undefined ? structuredClone(DEFAULT_REVIEW_CONFIG) : parseReviewConfig(baseText) | ||
| } catch (e: any) { | ||
| throw new Error( | ||
| `Failed to load the base branch's .altimate/review config: ${e?.message ?? e}. ` + | ||
| "The policy is read from the base branch so a PR cannot relax it; fix the file on the base branch " + | ||
| "(a PR that repairs it is reviewed under the broken base file, so merge it with an admin bypass).", | ||
| ) | ||
| } | ||
| const headText = await readFirst((rel) => fs.readFile(path.join(opts.cwd, rel), "utf8").catch(() => undefined)) | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||
| let changedInPr: string[] = [] | ||
| if (headText !== baseText) { | ||
| try { | ||
| const head = headText === undefined ? structuredClone(DEFAULT_REVIEW_CONFIG) : parseReviewConfig(headText) | ||
| changedInPr = policyChanges(config, head) | ||
| } catch { | ||
| changedInPr = ["(the PR's .altimate/review file does not parse)"] | ||
| } | ||
| } | ||
| return { config, source: baseText === undefined ? "default" : "base", hash: policyHash(config), changedInPr } | ||
| } | ||
|
|
||
| /** | ||
| * Load `.altimate/review.{yml,yaml,json}` from a project directory. Returns the | ||
| * defaults when no config file is present. Throws on a malformed/invalid file | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -84,9 +84,43 @@ export const Finding = z.object({ | |
| /** True when produced without a manifest/warehouse (lint-only degraded run). */ | ||
| degraded: z.boolean().default(false), | ||
| evidence: Evidence.optional(), | ||
| /** Which layer produced it: the deterministic engine, the regex/pattern | ||
| * catalog, or the advisory AI lane. Only `engine` findings decide the | ||
| * verdict unless the rubric opts a named catalog rule in. Stamped by | ||
| * buildEnvelope from `evidence.tool`. */ | ||
| origin: z.enum(["engine", "catalog", "ai"]).optional(), | ||
| }) | ||
| export type Finding = z.infer<typeof Finding> | ||
|
|
||
| export type FindingOrigin = NonNullable<Finding["origin"]> | ||
|
|
||
| /** Evidence tools backed by the deterministic engine (AST, manifest, lineage, | ||
| * warehouse) rather than text patterns. */ | ||
| const ENGINE_TOOLS = new Set(["impact_analysis", "dbt.manifest", "data.diff", "schema.detect_pii"]) | ||
|
|
||
| /** The layer a finding came from, always derived from `evidence.tool`: a | ||
| * supplied `origin` is ignored, so an externally built finding cannot claim | ||
| * to be engine-backed. Unknown or missing evidence counts as `catalog`, so a | ||
| * new detector can never block until it is classified. */ | ||
| export function findingOrigin(f: Pick<Finding, "evidence" | "origin">): FindingOrigin { | ||
| const tool = f.evidence?.tool ?? "" | ||
| if (tool === "ai-review") return "ai" | ||
| if (tool.startsWith("altimate_core.") || ENGINE_TOOLS.has(tool)) return "engine" | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: The namespace prefix is too broad for the trust boundary: an unrecognized Prompt for AI agents
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Follow-up: low priority, tracked. Switch to an explicit allowlist of engine tools. |
||
| return "catalog" | ||
| } | ||
|
|
||
| /** A rule id in one spelling: catalog sources use `hardcoded-credential` and | ||
| * `pii_into_mart` alike, so ids compare lowercased with `_` as `-`. */ | ||
| export function normalizeRuleId(id: string): string { | ||
| return id.trim().toLowerCase().replace(/_/g, "-") | ||
| } | ||
|
|
||
| /** The catalog rule id behind a finding (`evidence.result.rule`), if any. */ | ||
| export function catalogRuleId(f: Pick<Finding, "evidence">): string | undefined { | ||
| const rule = (f.evidence?.result as { rule?: unknown } | undefined)?.rule | ||
| return typeof rule === "string" ? rule : undefined | ||
| } | ||
|
|
||
| /** Fields that define finding identity for fingerprinting / dedup. */ | ||
| export interface FingerprintInput { | ||
| category: ReviewCategory | string | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -359,6 +359,12 @@ export function coverageNotes(env: VerdictEnvelope, maxChars = Infinity): string | |||||
| `${env.scope.movedUnchangedFiles} file(s) moved without edits (no content changes to review). ` + | ||||||
| "Folder-level config in `dbt_project.yml` (`+schema`, `+materialized`, `+tags`) can still change where and how a moved model builds.", | ||||||
| ) | ||||||
| if (env.policy?.changedInPr?.length) { | ||||||
| notes.push( | ||||||
| `This PR changes the review policy (\`.altimate/review.yml\`: ${env.policy.changedInPr.join(", ")}). ` + | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: This note misidentifies the policy file when the repository uses the supported Prompt for AI agents
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Follow-up: low priority, tracked. Say "review policy" generically. |
||||||
| "The base branch's policy was applied; the change takes effect after merge.", | ||||||
| ) | ||||||
| } | ||||||
| if (env.ai && env.ai.state !== "ok") { | ||||||
| const what = { skipped: "skipped", timeout: "timed out", error: "failed" }[env.ai.state] | ||||||
| notes.push(`Advisory AI review ${what}${env.ai.reason ? `: ${reasonOf(env.ai.reason)}` : ""}.`) | ||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -281,6 +281,21 @@ export async function resolveReviewBase(opts: ResolveBaseOptions): Promise<Resol | |
| return { ref: parent, sha, source: "parent" } | ||
| } | ||
|
|
||
| /** File content at a commit (`git show <ref>:<path>`), or undefined when the | ||
| * path does not exist there. `rel` is repository-relative, POSIX. */ | ||
| export async function showAtRef(cwd: string, ref: string, rel: string): Promise<string | undefined> { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. WARNING: A failed
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 956f4ef (see the cubic thread on |
||
| try { | ||
| return await git(["show", `${ref}:${rel}`], cwd) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [MINOR] return await git(["show", `${ref}:${rel}`], cwd)A failure other than a missing path (missing object in a partial clone, permissions) silently yields default policy ( Fix: return undefined only for git's "does not exist in" / "exists on disk, but not in" errors; rethrow otherwise. (Claude)
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks. Fixed in |
||
| } catch (err) { | ||
| // Only "the path is not in that commit" means absent. Any other failure | ||
| // (bad ref, corrupt object, git missing) must surface: callers such as the | ||
| // base-policy loader would otherwise fall back to the permissive default. | ||
| const msg = err instanceof Error ? err.message : String(err) | ||
| if (/does not exist in|exists on disk, but not in/i.test(msg)) return undefined | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. WARNING:
The second alternative is also dead code here: Prefer an exit-code existence check over parsing stderr, e.g. |
||
| throw err | ||
| } | ||
| } | ||
|
|
||
| /** Compute a short hash of the manifest file for the verdict envelope. */ | ||
| export async function manifestHash(manifestPath: string, cwd: string): Promise<string | undefined> { | ||
| try { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -223,6 +223,8 @@ export interface OrchestrateInput { | |
| scope?: Omit<ReviewScope, "unverified"> | ||
| /** Drop the regex catalog's cross-engine portability findings (single known engine). */ | ||
| suppressPortability?: boolean | ||
| /** Which review policy was applied (see config.ts loadReviewPolicy). */ | ||
| policy?: VerdictEnvelope["policy"] | ||
| } | ||
|
|
||
| /** A catalog finding tagged as cross-engine portability advice. */ | ||
|
|
@@ -1662,7 +1664,9 @@ export async function runReview(input: OrchestrateInput): Promise<VerdictEnvelop | |
| } | ||
| const proveNewTwin = (f: Finding) => { | ||
| const ctx = ctxByPath.get(f.file) | ||
| if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql) return false | ||
| // With both sides analysable the engine's own PII lanes decide. They need the head too: | ||
| // a readable base beside a head that is still raw Jinja leaves only this proof. | ||
| if (!ctx || !hasOldSide(ctx.file) || (ctx.engineOldSql && ctx.engineNewSql)) return false | ||
| const result = (f.evidence?.result ?? {}) as { column?: string; line?: string; items?: SelectItemColumn[] } | ||
| const hits = result.items?.length ? result.items : result.column ? [{ column: result.column, line: result.line ?? "" }] : [] | ||
| if (!hits.length || !rawBaseLacks(baseCode(f.file), hits.map((h) => h.column))) return false | ||
|
|
@@ -1755,12 +1759,19 @@ export async function runReview(input: OrchestrateInput): Promise<VerdictEnvelop | |
| // tell a new column from one the base already exposed: report them like the | ||
| // other PII lanes, as a warning of unknown confidence that never blocks. | ||
| // Unless the raw base proves the column new (`rawBaseLacks`): then the twin | ||
| // keeps its severity. | ||
| // keeps its severity and is marked, so it counts toward the verdict as the | ||
| // one pattern finding that blocks without being named in `blockingRules`. | ||
| for (const [i, f] of merged.entries()) { | ||
| const rule = (f.evidence?.result as { rule?: string } | undefined)?.rule | ||
| if (f.category !== "pii_exposure" || (rule !== "pii_into_mart" && rule !== "select-pii-columns")) continue | ||
| const ctx = ctxByPath.get(f.file) | ||
| if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql || provenNewTwin(f)) continue | ||
| if (!ctx || !hasOldSide(ctx.file)) continue | ||
| if (provenNewTwin(f)) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [WARNING]: The proven-new PII mark is skipped exactly when the base is readable but the head is not compiled The
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed and fixed in 699c779. With a plain-SQL base and a head that is still raw Jinja, the engine's PII lanes had nothing to analyse and the proof was skipped because the base was readable, so a newly added |
||
| if (f.evidence) merged[i] = { ...f, evidence: { ...f.evidence, result: { ...(f.evidence.result as object), provenNew: true } } } | ||
| continue | ||
| } | ||
| // A readable base: the twin keeps its severity, as advice. | ||
| if (ctx.engineOldSql) continue | ||
| merged[i] = { ...f, severity: f.severity === "critical" ? "warning" : f.severity, confidence: "unknown" } | ||
| } | ||
|
|
||
|
|
@@ -1818,6 +1829,7 @@ export async function runReview(input: OrchestrateInput): Promise<VerdictEnvelop | |
| const degraded = runDegraded | ||
| const envelope = buildEnvelope({ | ||
| ai: aiStatus, | ||
| policy: input.policy, | ||
| findings, | ||
| tier, | ||
| mode: input.mode, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
SUGGESTION: The docs state a stronger trust boundary than the shipped path enforces
The policy file is base-scoped, but
github/review/action.ymlalways passes--mode/--severityfrom the workflow (args=(--mode "$IN_MODE" ...)), and onpull_requestevents that workflow comes from the PR. A PR can therefore still switch the gate to comment mode by editing.github/workflows/*.yml— the PR description notes this as out of scope, but this bullet reads as if no PR-side edit can relax the gate. Adding that caveat (and pointing at CODEOWNERS / branch protection on.github/) would keep the doc accurate.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 956f4ef. Workflow flags can no longer relax a base policy, and the docs state the remaining caveat (protect
.github/).