Skip to content
23 changes: 23 additions & 0 deletions docs/docs/usage/dbt-pr-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,9 @@ mode: comment # comment | gate
severityThreshold: suggestion
manifestPath: target/manifest.json
dialect: snowflake
# portability: true # cross-engine advice. Unset: off once the engine is known
# (configured or detected). An explicit value applies even when
# the engine is unknown. Set true for multi-adapter packages.
reviewers: [] # empty = risk-tier defaults; or pin lanes
dataDiff: # OFF by default — see "Data-diff in CI" below
enabled: false
Expand All @@ -283,6 +286,26 @@ rubric:
skipNonProdModels: true
```

### What the PR comment shows

- **One summary comment**, updated in place on every push, capped at about
5,000 characters. Critical findings come first; anything that does not fit is
counted, and the full list is always in the verdict envelope
(`altimate review --json`). Local CLI output is never truncated.
- **Repeated findings are grouped:** the same rule with the same message on
three or more models is one bullet listing the models. Local CLI output lists
every finding with its location.
Comment on lines +296 to +297

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The grouping condition is normalized, not literal: format.ts blanks model/column names before comparing titles and bodies, so messages that differ only by those names are grouped. Document the normalized-message behavior to match the posted summary.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/docs/usage/dbt-pr-review.md, line 296:

<comment>The grouping condition is normalized, not literal: `format.ts` blanks model/column names before comparing titles and bodies, so messages that differ only by those names are grouped. Document the normalized-message behavior to match the posted summary.</comment>

<file context>
@@ -291,13 +292,15 @@ rubric:
-- **Repeated rules are grouped:** the same rule on three or more models is one
-  bullet listing the models.
+- **Repeated findings are grouped:** the same rule with the same message on
+  three or more models is one bullet listing the models. Local CLI output lists
+  every finding with its location.
 - **Inline comments only on lines of the PR's diff.** Findings computed on
</file context>
Suggested change
three or more models is one bullet listing the models. Local CLI output lists
every finding with its location.
three or more models are grouped when their normalized rule/message matches; model and column names are ignored. Local CLI output lists every finding with its location.

- **Inline comments only on lines of the PR's diff.** Findings computed on
compiled SQL, or on unchanged lines, stay in the summary.
- **No re-posting on reruns:** each inline comment carries the finding's
fingerprint, so a push does not repeat findings already on the PR, and a
non-blocking rerun with nothing new and the same headline as the bot's last
review only updates the summary.
- **PII:** flagged only for PII columns the change newly exposes, not for
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
columns the base already surfaced. That comparison needs the base version's
SQL; when it can't be compiled, PII columns are reported as non-blocking
warnings that may predate the PR.

### Risk-tier path tokens

Named categories under `riskTierPathTokens` promote any diff touching a matching
Expand Down
8 changes: 8 additions & 0 deletions packages/opencode/src/altimate/review/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ export const ReviewConfig = z.object({
dialect: z.string().default(""),
/** Enable the advisory LLM reviewer lane (needs a configured model). */
ai: z.boolean().default(true),
/**
* Report cross-engine portability advice ("isn't portable across
* warehouses"). Off by default once the engine is known (from the manifest's
* adapter or `dialect`), because a project that runs on one engine gains
* nothing from it. Turn on for packages that support several adapters.
* Functions missing on the project's own engine are always reported.
*/
portability: z.boolean().optional(),
/**
* 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
Expand Down
51 changes: 28 additions & 23 deletions packages/opencode/src/altimate/review/dbt-patterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Log } from "@/altimate/util/log"
import { type Finding, type Severity, type ReviewCategory, makeFinding } from "./finding"
import { type ChangedFile, fileKind } from "./diff-filter"
import { type Rubric, clampSeverity, exclusionReason } from "./rubric"
import { evaluateCatalog } from "./rule-catalog"
import { evaluateCatalog, selectItemColumns } from "./rule-catalog"

/** Local copy to avoid a cycle with orchestrate.ts. */
function modelNameFromPath(p: string): string {
Expand Down Expand Up @@ -109,7 +109,7 @@ interface Ctx {
inMartOrReporting: boolean
}

type Detector = (c: Ctx) => Finding | null
type Detector = (c: Ctx) => Finding | Finding[] | null

// A line that is dbt Jinja / config rather than SQL — e.g. the microbatch
// `begin=(modules.datetime.datetime.now() - ...)` config kwarg, which is NOT a
Expand Down Expand Up @@ -304,7 +304,7 @@ const PII_RE =
/\b(email|ssn|social_security|phone_number|first_name|last_name|full_name|street_address|date_of_birth|dob|passport|credit_card)\b/i
const detectPiiIntoMart: Detector = (c) => {
if (!c.inMartOrReporting) return null
const hit = c.added.find((l) => {
const hits = c.added.filter((l) => {
const s = stripComments(l)
return (
PII_RE.test(s) &&
Expand All @@ -313,24 +313,29 @@ const detectPiiIntoMart: Detector = (c) => {
)
)
})
if (!hit) return null
// Highly-sensitive identifiers (SSN/financial/passport/DOB) into a broadly-read
// marts layer are critical; softer PII (email/phone/name) is a warning.
const sev: Severity = /\b(ssn|social_security|credit_card|passport|date_of_birth|dob)\b/i.test(hit)
? "critical"
: "warning"
return makeFinding({
severity: sev,
category: "pii_exposure",
title: `${c.model}: PII column added to a marts/reporting model`,
body:
"A PII-named column was added to a model in `marts/`/`reporting/`, widening PII exposure into a broadly-read " +
"layer. Confirm the column is needed here, that masking/access policy applies, and that the downstream grant is appropriate.",
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line: hit.trim() } },
ruleKey: "pii_exposure:into-mart",
// One finding per PII column token on each added line (`ssn, passport` is two):
// each carries its column, `AS` alias and line in `result` so the orchestrator
// can suppress a base-exposed column without hiding a new one beside it. They
// share a fingerprint, so dedupe keeps the most severe survivor.
return hits.flatMap((hit) => selectItemColumns(hit, PII_RE)).map(({ column, alias, line }) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: selectItemColumns scans through FROM, so email from ssn produces PII columns email and ssn even though ssn is the source relation. The spurious sensitive token can survive suppression and create a critical block; stop token extraction at the top-level FROM.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/review/dbt-patterns.ts, line 320:

<comment>`selectItemColumns` scans through `FROM`, so `email from ssn` produces PII columns `email` and `ssn` even though `ssn` is the source relation. The spurious sensitive token can survive suppression and create a critical block; stop token extraction at the top-level `FROM`.</comment>

<file context>
@@ -313,14 +313,14 @@ const detectPiiIntoMart: Detector = (c) => {
+  // each carries its column, `AS` alias and line in `result` so the orchestrator
+  // can suppress a base-exposed column without hiding a new one beside it. They
+  // share a fingerprint, so dedupe keeps the most severe survivor.
+  return hits.flatMap((hit) => selectItemColumns(hit, PII_RE)).map(({ column, alias, line }) => {
     // Highly-sensitive identifiers (SSN/financial/passport/DOB) into a broadly-read
     // marts layer are critical; softer PII (email/phone/name) is a warning.
</file context>

// Highly-sensitive identifiers (SSN/financial/passport/DOB) into a broadly-read
// marts layer are critical; softer PII (email/phone/name) is a warning.
const sev: Severity = /^(ssn|social_security|credit_card|passport|date_of_birth|dob)$/i.test(column)
? "critical"
: "warning"
return makeFinding({
severity: sev,
category: "pii_exposure",
title: `${c.model}: PII column added to a marts/reporting model`,
body:
"A PII-named column was added to a model in `marts/`/`reporting/`, widening PII exposure into a broadly-read " +
"layer. Confirm the column is needed here, that masking/access policy applies, and that the downstream grant is appropriate.",
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line, column, alias } },
ruleKey: "pii_exposure:into-mart",
})
})
}

Expand Down Expand Up @@ -780,8 +785,8 @@ export function detectModelPatterns(file: ChangedFile, newSql: string | undefine
}
const out: Finding[] = []
for (const d of MODEL_DETECTORS) {
const f = d(ctx)
if (f) out.push({ ...f, severity: clampSeverity(f.category, f.severity, f.confidence) })
for (const f of [d(ctx) ?? []].flat())
out.push({ ...f, severity: clampSeverity(f.category, f.severity, f.confidence) })
}
// Declarative rule catalog (data-driven checks) complements the programmatic detectors.
out.push(...evaluateCatalog(file, newSql, added, removed, rubric))
Expand Down
205 changes: 179 additions & 26 deletions packages/opencode/src/altimate/review/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,20 @@ export function verdictHeadline(env: VerdictEnvelope): string {
return `${VERDICT_LABEL[env.verdict]} — ${counts} (${tierLabel})`
}

/** Default size budget for the posted PR comment (characters). */
export const SUMMARY_BUDGET_CHARS = 5_000
/** The same rule on this many models or more collapses into one bullet. */
export const GROUP_MIN_MODELS = 3

export interface RenderOptions {
/** Character budget for the comment; findings beyond it are counted, not listed.
* `Infinity` renders everything (local CLI output). */
maxChars?: number
}

/** Full PR/MR summary comment body (markdown), prefixed with the dedup marker. */
export function renderSummary(env: VerdictEnvelope): string {
export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): string {
const maxChars = opts.maxChars ?? SUMMARY_BUDGET_CHARS
const lines: string[] = [REVIEW_MARKER, "", `## ${verdictHeadline(env)}`, ""]

if (env.summary.degraded) {
Expand Down Expand Up @@ -80,33 +92,15 @@ export function renderSummary(env: VerdictEnvelope): string {
lines.push(`> 🧭 **Tier: ${env.tier}** — ${shown}${overflow}`, "")
}

if (!env.findings.length) {
lines.push("No issues found in the changed dbt models. 🎉", "")
} else {
const grouped = groupBySeverity(env.findings)
for (const sev of ["critical", "warning", "suggestion"] as const) {
const items = grouped[sev]
if (!items.length) continue
lines.push(`### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${items.length})`, "")
for (const f of items) {
const loc = f.file + (f.startLine ? `:${f.startLine}` : "")
lines.push(
`- **${f.title}** \n ${oneLine(f.body)} \n <sub>\`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}</sub>`,
)
}
lines.push("")
}
}

const tail: string[] = []
if (env.override) {
lines.push(
tail.push(
`> 🔓 **Break-glass override** by @${env.override.by}: ${env.override.reason}`,
`> (would have been \`${env.override.priorVerdict}\`)`,
"",
)
}

lines.push(
tail.push(
"---",
`<sub>altimate dbt-pr-review · verdict \`${env.verdict}\`` +
(env.signature ? ` · signed \`${env.signature.slice(0, 18)}…\`` : "") +
Expand All @@ -115,7 +109,105 @@ export function renderSummary(env: VerdictEnvelope): string {
(env.ai?.state === "ok" && env.ai.model ? ` · AI \`${env.ai.model}\`` : "") +
"</sub>",
)
return lines.join("\n")

if (!env.findings.length) {
lines.push("No issues found in the changed dbt models. 🎉", "")
return [...lines, ...tail].join("\n")
}

// Findings fill the budget left after the fixed parts, most severe first.
// What does not fit is counted, never silently dropped: the envelope keeps
// every finding. The reserve keeps room for the "… N more finding(s)" line.
const overflowReserve = 220
let used = [...lines, ...tail].join("\n").length + overflowReserve
let hidden = 0
const grouped = groupBySeverity(env.findings)
for (const sev of ["critical", "warning", "suggestion"] as const) {
const items = grouped[sev]
if (!items.length) continue
const heading = [`### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${items.length})`, ""]
// Uncapped (local) output lists every finding with its own location.
const bullets = bulletsFor(items, maxChars !== Infinity)
let headed = false
for (const b of bullets) {
const cost = b.text.length + 1 + (headed ? 0 : heading.join("\n").length + 2)
if (used + cost > maxChars) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: A critical bullet that exceeds the budget is skipped while later, smaller bullets still render

When a bullet does not fit, the loop does hidden += b.count; continue without changing used, so every later bullet is still considered and a short warning/suggestion can fit after a critical was dropped. A single long critical body is realistic: columnBreakageLane joins every removed column and its downstream models into detail (orchestrate.ts:582-592), easily exceeding the whole 5K budget. The posted comment can then show suggestions while omitting a critical, contradicting the "Critical findings come first" promise in docs/docs/usage/dbt-pr-review.md:291 (and the hidden notice does not say a critical was hidden).

Stop rendering once a bullet of a given severity overflows (e.g. break, and skip lower severities when a higher-severity finding was hidden), so the visible set stays ordered by severity.

hidden += b.count
continue
}
if (!headed) {
lines.push(...heading)
headed = true
}
lines.push(b.text)
used += cost
}
if (headed) lines.push("")
}
if (hidden) {
lines.push(
`> … ${hidden} more finding(s) not shown to keep this comment short — the full list is in the verdict envelope ` +

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The --output artifact this points at does not exist for the bundled action

github/review/action.yml builds its args from --mode/--manifest/--severity/--cwd/--base/--head/--post only — it never passes --json or --output, so an action user who hits the 5K budget has no --output artifact to open, and renderSummary is the only rendering they see. The uncapped list does reach the step log (the CLI writes renderSummary(env, { maxChars: Infinity }) to stdout), and the envelope is written only for an explicit CLI --output. Point readers at the job log or at altimate review --json --output <file> instead of an artifact the action never creates.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: low priority, tracked. The note should point to the job log or altimate review --json --output <file>.

"(`altimate review --json`, or the action's `--output` artifact).",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The bundled action does not pass --output, so this artifact is never created; point readers to the job log or explicit altimate review --json --output <file> usage.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/review/format.ts, line 149:

<comment>The bundled action does not pass `--output`, so this artifact is never created; point readers to the job log or explicit `altimate review --json --output <file>` usage.</comment>

<file context>
@@ -115,7 +109,90 @@ export function renderSummary(env: VerdictEnvelope): string {
+  if (hidden) {
+    lines.push(
+      `> … ${hidden} more finding(s) not shown to keep this comment short — the full list is in the verdict envelope ` +
+        "(`altimate review --json`, or the action's `--output` artifact).",
+      "",
+    )
</file context>
Suggested change
"(`altimate review --json`, or the action's `--output` artifact).",
"(`altimate review --json`, or the job log; use `--output <file>` when running the CLI directly).",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: low priority, tracked (same as the kilo thread).

"",
)
}
return [...lines, ...tail].join("\n")
}

/** Backticked names blanked, so the same rule on different models/columns
* normalizes to the same text. */
function blankNames(s: string): string {
return s.replace(/`[^`]*`/g, "`…`")
}

/** A finding's title without its leading `model: `, with backticked names
* blanked: the title half of the grouping key. */
function groupKeyTitle(f: Finding): string {
return blankNames(f.model && f.title.startsWith(`${f.model}: `) ? f.title.slice(f.model.length + 2) : f.title)
}

/** 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. */
function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; count: number }> {
const groups = new Map<string, Finding[]>()
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This delimiter-concatenated grouping key is ambiguous when a title or body contains |, so distinct findings can collapse into one bullet. Build the grouped key from a structured tuple instead of concatenating unescaped text.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/review/format.ts, line 177:

<comment>This delimiter-concatenated grouping key is ambiguous when a title or body contains `|`, so distinct findings can collapse into one bullet. Build the grouped key from a structured tuple instead of concatenating unescaped text.</comment>

<file context>
@@ -153,19 +154,27 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s
-    const key = `${f.category}|${ruleTitle(f)}`
+    // 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 g = groups.get(key)
     if (g) g.push(f)
</file context>
Suggested change
const key = group ? `${f.category}|${groupKeyTitle(f)}|${blankNames(oneLine(f.body))}` : f.id
const key = group ? JSON.stringify([f.category, groupKeyTitle(f), blankNames(oneLine(f.body))]) : f.id

const g = groups.get(key)
if (g) g.push(f)
else groups.set(key, [f])
}
const out: Array<{ text: string; count: number }> = []
for (const g of groups.values()) {
// Group by distinct models: several findings of one rule on the SAME model
// (e.g. two different columns) are distinct issues and stay separate bullets.
const names = [...new Set(g.map((f) => f.model ?? f.file))]
if (group && names.length >= GROUP_MIN_MODELS) {
const shown = names.slice(0, 8).map((n) => `\`${n}\``).join(", ")
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 = g.every((f) => f.body === g[0].body) ? oneLine(g[0].body) : blankNames(oneLine(g[0].body))
const unverified = g.some((f) => f.degraded) ? " · _unverified_" : ""
out.push({
text:
`- **${groupKeyTitle(g[0])}** — ${g.length} findings across ${names.length} model(s): ${shown}${more} \n` +
` ${body} \n <sub>${g[0].category}${unverified}</sub>`,
count: g.length,
})
continue
}
for (const f of g) {
const loc = f.file + (f.startLine ? `:${f.startLine}` : "")
out.push({
text: `- **${f.title}** \n ${oneLine(f.body)} \n <sub>\`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}</sub>`,
count: 1,
})
}
}
return out
}

/**
Expand All @@ -142,6 +234,11 @@ export function coverageNotes(env: VerdictEnvelope): string[] {
}
if (env.scope?.outOfScopeFiles)
notes.push(`${env.scope.outOfScopeFiles} changed file(s) outside the dbt project were not reviewed.`)
if (env.scope?.movedUnchangedFiles)
notes.push(
`${env.scope.movedUnchangedFiles} file(s) moved without edits; their SQL was not re-reviewed. ` +
"Folder-level config in `dbt_project.yml` (`+schema`, `+materialized`, `+tags`) can still change where and how a moved model builds.",
Comment on lines +239 to +240

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This note incorrectly claims every unchanged move has SQL that was not re-reviewed. movedUnchangedFiles also counts unchanged renames of YAML and other files, so the summary is misleading for those moves; describe unchanged content generically or restrict the counter to model files.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/review/format.ts, line 221:

<comment>This note incorrectly claims every unchanged move has SQL that was not re-reviewed. `movedUnchangedFiles` also counts unchanged renames of YAML and other files, so the summary is misleading for those moves; describe unchanged content generically or restrict the counter to model files.</comment>

<file context>
@@ -216,6 +216,11 @@ export function coverageNotes(env: VerdictEnvelope): string[] {
     notes.push(`${env.scope.outOfScopeFiles} changed file(s) outside the dbt project were not reviewed.`)
+  if (env.scope?.movedUnchangedFiles)
+    notes.push(
+      `${env.scope.movedUnchangedFiles} file(s) moved without edits; their SQL was not re-reviewed. ` +
+        "Folder-level config in `dbt_project.yml` (`+schema`, `+materialized`, `+tags`) can still change where and how a moved model builds.",
+    )
</file context>
Suggested change
`${env.scope.movedUnchangedFiles} file(s) moved without edits; their SQL was not re-reviewed. ` +
"Folder-level config in `dbt_project.yml` (`+schema`, `+materialized`, `+tags`) can still change where and how a moved model builds.",
`${env.scope.movedUnchangedFiles} file(s) moved without edits; their unchanged contents were not re-reviewed. ` +
"For moved models, folder-level config in `dbt_project.yml` (`+schema`, `+materialized`, `+tags`) can still change where and how they build.",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: wording nit.

)
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 ? `: ${env.ai.reason}` : ""}.`)
Expand All @@ -157,14 +254,70 @@ export interface InlineComment {
body: string
}

export function inlineComments(env: VerdictEnvelope): InlineComment[] {
/** Hidden per-finding marker on inline comments, keyed by the finding's stable
* fingerprint (rule, file, model, column — not the line), so a rerun can tell
* which findings are already on the PR. */
export function findingMarker(id: string): string {
return `<!-- altimate-finding:${id} -->`
}

/** Finding ids already posted, read from existing inline comment bodies. */
export function postedFindingIds(bodies: Array<string | null | undefined>): Set<string> {
const out = new Set<string>()
for (const b of bodies) for (const m of (b ?? "").matchAll(/<!-- altimate-finding:([\w-]+) -->/g)) out.add(m[1])
return out
}

/** Line numbers on the head side of a unified diff that GitHub accepts for an
* inline comment: added lines and context lines inside a hunk. */
export function commentableLines(diff: string | undefined): Set<number> {
const out = new Set<number>()
if (!diff) return out
let right = 0
let inHunk = false
const rows = diff.split("\n")
if (rows[rows.length - 1] === "") rows.pop() // the diff's trailing newline, not a line
for (const line of rows) {
const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line)
if (h) {
right = Number(h[1])
inHunk = true
continue
}
// File headers (`--- a/…`, `+++ b/…`) only occur outside a hunk.
if (!inHunk || line.startsWith("\\")) continue
// A blank context line may have lost its leading space in transit.
if (line.startsWith("+") || line.startsWith(" ") || line === "") out.add(right++)
else if (!line.startsWith("-")) inHunk = false
}
return out
}

/**
* Inline comments for findings with a line. With `commentable` (head-side
* commentable lines per file, see `commentableLines`), only lines inside the
* PR's diff hunks are kept: GitHub rejects the whole batch over one line
* outside the diff. A file with no entry has unknown hunks (GitHub omits the
* patch for large diffs): its lines are attempted, and the 422 fallback covers a
* miss. The finding keeps its line in the envelope and summary.
*/
export function inlineComments(
env: VerdictEnvelope,
alreadyPosted: Set<string> = new Set(),
commentable?: Map<string, Set<number>>,
): InlineComment[] {
return env.findings
.filter((f) => typeof f.startLine === "number")
.filter(
(f) =>
typeof f.startLine === "number" &&
!alreadyPosted.has(f.id) &&
(!commentable?.has(f.file) || commentable.get(f.file)!.has(f.startLine)),
)
.map((f) => ({
path: f.file,
line: f.startLine!,
side: "RIGHT" as const,
body: `${SEVERITY_EMOJI[f.severity]} **${f.title}**\n\n${f.body}`,
body: `${SEVERITY_EMOJI[f.severity]} **${f.title}**\n\n${f.body}\n\n${findingMarker(f.id)}`,
}))
}

Expand Down
Loading
Loading