8000 feat(reviews): download review findings as SARIF by redoh · Pull Request #10 · inkspect-code-review/inkspect-ui · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ as appropriate. The package's `0.1.0` version is not a claim of a tagged release

### 2026-11-20

#### Added

- Download recorded review findings as SARIF 2.1.0 from the dashboard.

#### Fixed

- Fetch the realtime channel when the initial dashboard overview omits it so later review events refresh the page.
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ Use the main `inkspect` repository to assemble compatible self-hosted releases.

Source code is licensed under [MIT](LICENSE). Third-party dependencies retain their own licenses.

## Download review findings

Open a completed review in **Dashboard → Reviews → Overview** and select **Download SARIF**.
The browser creates a SARIF 2.1.0 file for the recorded revision, including reviews
with zero findings. The file records incomplete coverage and excluded file counts.
Paths are relative to the repository root. Repeated findings are matched using the
path, normalized title and occurrence in source order. Renaming the file or rewording
the title can change the fingerprint. The download stays local to your browser.

## Ignored pull request authors

Use **Settings → Workspace → Automatic reviews → GitHub check failure threshold** to select the lowest severity that fails a new PR check. The default is P0 (critical).
Expand Down
6 changes: 5 additions & 1 deletion src/components/review-report.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { ReportResponse, ReviewReport, ReviewScore } from "@inkspect/core/l
import { allFindingFixPrompts, findingFixPrompt } from "@inkspect/core/lib/review-prompts";
import styles from "./reviews.module.css";
import { FindingStatusControl } from "./finding-status-control";
import { downloadReviewSarif } from "./review-sarif";

function CopyPromptButton({ value, label = "Copy", ariaLabel, className, successMessage = "Fix prompt copied to clipboard.", onFailure, onSuccess }: { value: string; label?: string; ariaLabel: string; className?: string; successMessage?: string; onFailure: () => void; onSuccess?: () => void }) {
const [status, setStatus] = useState<"idle" | "copying" | "copied" | "failed">("idle");
Expand Down Expand Up @@ -148,7 +149,10 @@ export function ReviewReportView({ value, details, fix, organizationId }: { valu
</Tabs.List>
<Tabs.Content className={styles.tabPanel} value="overview" forceMount hidden={tab !== "overview"}>
<section className={styles.overview} aria-labelledby="review-decision">
<div className={styles.decision} data-decision={r.decision}><span aria-hidden="true" /><h2 id="review-decision">{decisions[r.decision]}</h2></div>
<div className={styles.sectionHeading}>
<div className={styles.decision} data-decision={r.decision}><span aria-hidden="true" /><h2 id="review-decision">{decisions[r.decision]}</h2></div>
<button type="button" => downloadReviewSarif(r)}>Download SARIF</button>
</div>
<p className={styles.reviewSummary}>{r.summary}</p>
{r.change_alignment && <div className={styles.alignment}><h3>PR intent <span>{alignmentLabels[r.change_alignment.level] || r.change_alignment.level.replaceAll("_", " ")}</span></h3><p>{r.change_alignment.rationale}</p></div>}
</section>
Expand Down
68 changes: 68 additions & 0 deletions src/components/review-sarif.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { ReviewReport } from "@inkspect/core/lib/review-types";

const ruleId = "inkspect/code-review";
const levels: Record<string, string> = {
p0: "error", critical: "error", p1: "error", high: "error",
p2: "warning", medium: "warning", p3: "note", low: "note",
};

// Reports contain locations and finding text, but do not retain the source file.
// Use the normalized title at the path as the anchor. Number repeated anchors in
// source order so a change in severity, commit or absolute line doesn't renumber them.
function anchorHash(path: string, title: string) {
const anchor = JSON.stringify([path, title.trim().replace(/\s+/g, " ").toLowerCase()]);
let hash = 0xcbf29ce484222325n;
for (const byte of new TextEncoder().encode(anchor)) {
hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100000001b3n);
}
return hash.toString(16).padStart(16, "0");
}

export function reviewSarif({ run, findings }: ReviewReport) {
const occurrences = new Map<string, number>();
const ordered = [...findings].sort((a, b) => a.location.start_line - b.location.start_line || a.location.end_line - b.location.end_line);
const results = ordered.map(finding => {
const { path, start_line, end_line } = finding.location;
const hash = anchorHash(path, finding.title);
const occurrence = (occurrences.get(hash) ?? 0) + 1;
occurrences.set(hash, occurrence);
return {
ruleId,
level: levels[finding.severity.toLowerCase()] ?? "warning",
message: { text: [finding.title, finding.reason].filter(Boolean).join("\n\n") },
locations: [{ physicalLocation: {
artifactLocation: { uri: path.split("/").map(encodeURIComponent).join("/"), uriBaseId: "%SRCROOT%" },
region: { startLine: start_line, endLine: end_line },
} }],
partialFingerprints: { primaryLocationLineHash: `${hash}:${occurrence}` },
properties: { severity: finding.severity, advisory: finding.advisory === true },
};
});
const complete = run.status === "completed" && run.coverage_complete;
return {
$schema: "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json",
version: "2.1.0",
runs: [{
tool: { driver: { name: "Inkspect", rules: [{ id: ruleId, shortDescription: { text: "Code review finding" } }] } },
originalUriBaseIds: { "%SRCROOT%": { description: { text: "Root of the reviewed repository." } } },
invocations: [{ executionSuccessful: complete, ...(!complete && { toolExecutionNotifications: [
{ level: "warning", message: { text: "Inkspect could not review the full requested scope." } },
] }) }],
properties: { revision: run.target.revision_id, baseRevision: run.base.revision_id, coverageComplete: run.coverage_complete, excludedFiles: run.exclusions?.excluded_files ?? 0 },
results,
}],
};
}

export function downloadReviewSarif(report: ReviewReport) {
const data = JSON.stringify(reviewSarif(report), null, 2);
const url = URL.createObjectURL(new Blob([data], { type: "application/sarif+json" }));
try {
const link = document.createElement("a");
link.href = url;
link.download = `inkspect-${report.run.target.revision_id.replace(/[^a-z0-9_-]/gi, "_").slice(0, 48)}.sarif`;
link.click();
} finally {
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
}
65 changes: 65 additions & 0 deletions tests/app/fixtures/review-report-render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ReviewCostView } from "@inkspect/ui/components/review-cost";
import { ReviewDiagram, ReviewReportView } from "@inkspect/ui/components/review-report";
import type { ReportResponse } from "@inkspect/core/lib/review-types";
import { allFindingFixPrompts, findingFixPrompt } from "@inkspect/core/lib/review-prompts";
import { reviewSarif, downloadReviewSarif } from "../../../src/components/review-sarif";

function fixture(): ReportResponse {
const revision = { repository_id: "1", revision_id: "a".repeat(40) };
Expand All @@ -24,6 +25,70 @@ function fixture(): ReportResponse {
};
}

test("SARIF download contains the recorded locations and coverage and keeps alert IDs across revisions", () => {
const { report } = fixture();
const finding = report.findings[0];
finding.location.path = "src/çağrı #1%?.ts";
report.findings.push({ ...finding, id: "F2", severity: "P3", location: { ...finding.location, start_line: 1, end_line: 1 } });
const sarif = reviewSarif(report);
const run = sarif.runs[0];
assert.equal(sarif.version, "2.1.0");
assert.equal(run.results.length, 2);
assert.equal(run.invocations[0].executionSuccessful, false);
assert.equal(run.properties.excludedFiles, 2);
assert.equal(run.properties.revision, report.run.target.revision_id);
assert.deepEqual(run.results.map(r => r.level), ["note", "error"]);
const result = run.results[1];
assert.equal(result.ruleId, run.tool.driver.rules[0].id);
assert.deepEqual(result.locations[0].physicalLocation, {
artifactLocation: { uri: "src/%C3%A7a%C4%9Fr%C4%B1%20%231%25%3F.ts", uriBaseId: "%SRCROOT%" },
region: { startLine: 12, endLine: 14 },
});
assert.match(result.message.text, /Include the boundary/);
assert.notDeepEqual(result.partialFingerprints, run.results[0].partialFingerprints);
const previous = run.results.map(r => r.partialFingerprints);
finding.id = "different-run-id";
finding.title = " Include the Boundary ";
finding.severity = "medium";
finding.location.start_line += 5;
finding.location.end_line += 5;
report.findings.reverse();
report.run.target = { ...report.run.target, revision_id: "b".repeat(40) };
const next = reviewSarif(report).runs[0];
assert.deepEqual(next.results.map(r => r.partialFingerprints), previous);
assert.equal(next.results[1].level, "warning");
assert.doesNotMatch(JSON.stringify(next), /bedrock|Test perfect squares|private-provider/);
});

test("the overview downloads an empty, completed SARIF report as a local file", async () => {
const value = fixture();
value.report.findings = [];
value.report.run.coverage_complete = true;
const html = renderToStaticMarkup(<ReviewReportView value={value} />);
assert.match(html, /<button type="button">Download SARIF<\/button>/);
const link = { href: "", download: "", click() { clicked = true; } };
let clicked = false;
const previous = Object.getOwnPropertyDescriptor(globalThis, "document");
Object.defineProperty(globalThis, "document", { configurable: true, value: {
createElement(tag: string) { assert.equal(tag, "a"); return link; },
} });
try {
downloadReviewSarif(value.report);
assert.ok(clicked);
assert.match(link.href, /^blob:/);
assert.equal(link.download, `inkspect-${value.report.run.target.revision_id}.sarif`);
const response = await fetch(link.href);
assert.equal(response.headers.get("content-type"), "application/sarif+json");
const [run] = (await response.json()).runs;
assert.equal(run.invocations[0].executionSuccessful, true);
assert.deepEqual(run.results, []);
} finally {
if (previous) Object.defineProperty(globalThis, "document", previous);
else Reflect.deleteProperty(globalThis, "document");
URL.revokeObjectURL(link.href);
}
});

test("structured reports work without Markdown and preserve important review information", () => {
const html = renderToStaticMarkup(<ReviewReportView value={fixture()} />);
for (const text of ["Changes requested", "Boundary error", "Code quality", "Security", "Partially aligned", "Prime factors", "src/math.ts:12–14", "Suggested fix", "Run perfect-square tests", "Tests could not run", "2 changed files were excluded", "coverage is incomplete", "could not be checked", "recorded snapshot", "Math flow", "evidence-E1"]) assert.ok(html.toLowerCase().includes(text.toLowerCase()), text);
Expand Down
Loading
0