diff --git a/CHANGELOG.md b/CHANGELOG.md index 375d54cf..a2304046 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **A πŸ‘Ž reaction now retires a finding.** React πŸ‘Ž to one of DiffSentry's + inline comments and the next review stops raising it β€” across every PR that + finding class fires on, not just this one; πŸ‘ confirms it. Replying to a + finding already taught a learning, but it costs a sentence and a model call, + and the cheapest signal a maintainer can give was being thrown away. The + reactions are read once per review pass, because GitHub sends Apps no + `reaction` webhook and a pass is exactly when the answer is needed. A thread + carrying both reactions is left untouched, as is a fingerprint two threads + disagree about: taking a side there would retire a whole finding class on a + coin flip. Outcomes are written as ordinary triage state, so the command + center shows them beside dashboard dismissals β€” but a πŸ‘Ž suppresses regardless + of `DIFFSENTRY_SUPPRESS_DISMISSED`, which gates a housekeeping preference, + while a reaction is feedback about that finding. + +- **The same diff is no longer reviewed twice at full price.** Cross-review + dedup has always stopped a repeat finding being *posted* twice; it never + stopped it being *paid* for twice, because the model call happens long before + dedup sees a fingerprint. Results are now cached for 14 days, so reviewing a + tree that has already been reviewed β€” a retried pass after a provider blip, a + duplicate trigger, `@bot review` or `@bot full review` run twice over the same + commit β€” costs one call between them rather than two. + + Worth being precise about what this does *not* buy, because the obvious claim + is wrong: an **incremental** pass after a force-push generally still misses. + Its changed-file set is recomputed against the commit the rebase destroyed, so + the prompt differs even when the tree is byte-identical. A full review of that + same tree hits. The hit rate on a busy repository has not been measured. + + The key is the model id plus the entire prompt with each + patch replaced by its whitespace-normalized hash: a rebase that only moves + `@@` line numbers still hits, while a change to the code, the repo config, the + learnings, the profile or the review instructions themselves misses β€” including + a future prompt edit nothing had to remember to account for. A parse failure + is never cached (a provider having a bad day is not a property of the diff), + nor is a failover answer, so a cached row always means the primary model. + On by default; `DIFFSENTRY_REVIEW_CACHE=0` turns it off. New schema migration + 9; the table is discardable at any time. + +- **A Scorecard screen at `/scorecard`.** Pattern analytics answers "which rules + fire?". This answers the question a noisy reviewer actually loses trust over β€” + *were they right?* Per repo / source / severity it shows what was raised, + confirmed, dismissed, snoozed and still unjudged, plus what the review cache + has saved. The confirmed-rate is withheld below five judgements, and the + unjudged count sits beside every rate: on most repositories nearly everything + is unjudged, and a scorecard that hid that would be worse than none. + +- **An MCP server, so the findings reach the agent that has to fix them.** + `node dist/mcp/server.js` speaks the existing platform API over MCP (stdio), + giving Claude Code, Cursor or any MCP client four tools β€” `list_repos`, + `get_pr_findings`, `search_findings`, `request_review` β€” in place of copying a + `curl` response into a prompt. It is a client of the HTTP API rather than a + second way into the database: no DB handle, nothing minted, and exactly the + reach its bearer token's scopes allow, so authorization stays in one place. + Point it at an instance with `DIFFSENTRY_URL` and a token from the dashboard's + API tokens screen. The protocol is implemented directly β€” it is JSON-RPC over + newline-delimited stdio and four tools, and a dependency would be larger than + the thing it implements. + - Every finishing touch can now be delivered as a **stacked PR** instead of a commit. `✨ Finishing Touches` nests both choices under each of the four touches β€” `Create stacked PR` / `Commit on current branch` for docstrings and diff --git a/README.md b/README.md index a22eba3b..60e7af28 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ Everything below documents DiffSentry in full. Jump to a section: - [What it does](#what-it-does) - [Public demo / sandbox mode](#public-demo--sandbox-mode) +- [MCP server β€” DiffSentry inside your coding agent](#mcp-server--diffsentry-inside-your-coding-agent) - [Setup](#setup) - [Per-repo configuration](#per-repo-configuration) - [End-to-end test harness](#end-to-end-test-harness) @@ -268,6 +269,14 @@ cost surprises). filters and a recurring-fingerprint group view. - **Pattern analytics** at `/dashboard/patterns` β€” per-(repo, rule) 30-day + all-time hit counts to spot noisy rules. +- **Scorecard** at `/scorecard` in the command-center SPA β€” pattern analytics + answers "which rules fire?"; this answers the question a noisy reviewer + actually loses trust over: *were they right?* Per repo / source / severity it + shows what was raised, confirmed, dismissed, snoozed and still unjudged, plus + what the review cache has saved. A confirmed-rate is withheld below five + judgements β€” a percentage off three samples reads as authority and isn't one β€” + and the unjudged column is shown beside every rate so the size of the gap is + never hidden. - **Operator settings** at `/dashboard/settings` β€” runtime + storage health + a live warn/error log tail captured via an in-process pino ring buffer. - **Guided first-run diagnostics** at `/settings/diagnostics` in the @@ -284,6 +293,23 @@ cost surprises). installed repo so the dashboard isn't empty on first run. ### Quality of life +- **πŸ‘Ž retires a finding** β€” react πŸ‘Ž to one of DiffSentry's inline comments and + the next review stops raising it, across every PR it fires on; πŸ‘ confirms it. + Replying already teaches a learning, but it costs a sentence and a model call; + a reaction costs two clicks. A thread carrying both reactions is left alone β€” + two maintainers disagreeing is not a mandate. Outcomes land in the triage data + behind the [Scorecard](#web-dashboard-read-only-optional). +- **Review result cache** β€” reviewing a branch that hasn't changed costs one + model call, not two: a retried pass, a duplicate trigger, and `@bot review` / + `@bot full review` run twice over the same tree all hit it. Keyed on the model + plus the whole prompt with each patch whitespace-normalized, so a rebase that + only moves `@@` line numbers doesn't break the key, while any real change β€” to + the code, the config, the learnings or the review instructions themselves β€” + misses. **An incremental pass after a force-push usually still misses**: it + recomputes its changed-file set against a commit the rebase destroyed, so the + prompt differs even though the tree doesn't. A full review of the same tree + hits. On by default, 14-day retention; `DIFFSENTRY_REVIEW_CACHE=0` turns it + off. - **Confidence-tagged findings** β€” AI marks each finding `high` / `medium` / `low`; uncertain ones render with a `πŸ€”` blockquote so reviewers can triage. - **Whitespace-insensitive fingerprints** β€” comments survive re-indenting and @@ -315,6 +341,45 @@ read-only demo** of the real UI backed by bundled sample data. **Disabling it.** Security-conscious operators can turn the demo off entirely with **`DISABLE_DEMO=1`**, after which `/demo` returns `404`. +## MCP server β€” DiffSentry inside your coding agent + +The platform API could always hand a coding agent the findings on a PR; getting +them there meant a human copying a `curl` response into a prompt. `dist/mcp/server.js` +speaks that same API over **MCP**, so Claude Code, Cursor or any MCP client can +ask for them directly β€” read the findings, fix them, ask for a re-review. + +**Four tools:** `list_repos`, `get_pr_findings`, `search_findings`, +`request_review`. + +**Configure it** with the instance URL and an API token minted under **API +tokens** in the dashboard. A `read` token can do the first three; `request_review` +needs the `review` scope. + +```json +{ + "mcpServers": { + "diffsentry": { + "command": "node", + "args": ["/path/to/DiffSentry/dist/mcp/server.js"], + "env": { + "DIFFSENTRY_URL": "https://diffsentry.example.com", + "DIFFSENTRY_TOKEN": "dsk_..." + } + } + } +} +``` + +It is a **client of the HTTP API, not a second way into the database**: it holds +no DB handle, mints nothing, and can do exactly what its token's scopes allow β€” +so the authorization story stays in one place. Run it per developer with their +own token rather than as a shared service. + +Two notes if you are packaging it yourself: the process speaks JSON-RPC on +**stdout**, so it must be started with `node` directly and never through +`npm run` (which prints its own banner there and corrupts the stream); and it +needs `npm run build` first, like every other `dist/` entrypoint. + ## Setup > **In a hurry?** [docs/QUICK_START.md](docs/QUICK_START.md) is a ~10-minute path @@ -795,6 +860,7 @@ GitHub webhook | `DASHBOARD_INSTANCE_NAME` | No | `DiffSentry` | Default instance name (sidebar wordmark + tab title). An admin can override it live in Settings β†’ Branding. | | `DASHBOARD_ACCENT_COLOR` | No | `#5a8dff` | Default brand accent (hex `#rgb`/`#rrggbb`) the whole UI derives its accent from. Overridable live by an admin. | | `DIFFSENTRY_SUPPRESS_DISMISSED` | No | | Set to `1` so new reviews drop findings whose fingerprint was dismissed or is currently snoozed via triage. Off by default β€” triage never changes review output unless enabled. | +| `DIFFSENTRY_REVIEW_CACHE` | No | on | Set to `0` to disable the review result cache (see [Quality of life](#quality-of-life)). A πŸ‘Ž reaction suppresses its finding regardless of `DIFFSENTRY_SUPPRESS_DISMISSED` β€” it is feedback on that finding, not a triage preference. | | `DASHBOARD_CONFIG_PR_BRANCH_PREFIX` | No | `diffsentry/config` | Branch-name prefix used when an admin edits `.diffsentry.yaml` from the dashboard and chooses "open a PR". | | `IMPACT_MINUTES_PER_FINDING` | No | `15` | Reviewer-minutes-saved-per-finding heuristic for the Impact report's time-saved estimate. The only estimated figure on that page; all other numbers are counted from the raw tables. | diff --git a/docs/MIGRATIONS.md b/docs/MIGRATIONS.md index 4e483a1f..7e27d96d 100644 --- a/docs/MIGRATIONS.md +++ b/docs/MIGRATIONS.md @@ -45,6 +45,7 @@ baseline is not re-run), and applies migration 2 onward. No data is touched. | 6 | `walkthrough_state` | Server-side walkthrough state persistence (`walkthrough_state`). | | 7 | `impact_shares` | Shareable impact-report links (`impact_shares`). | | 8 | `drop_saved_views` | Drops the never-used `saved_views` table (created by v2, written to by nothing). | +| 9 | `ai_review_cache` | Review result cache keyed by model + normalized prompt (`ai_review_cache`). Discardable β€” see [`src/ai/review-cache.ts`](../src/ai/review-cache.ts). | ## Adding a migration diff --git a/scripts/preview-learnings.ts b/scripts/preview-learnings.ts index a5176227..aa4755fd 100644 --- a/scripts/preview-learnings.ts +++ b/scripts/preview-learnings.ts @@ -55,7 +55,7 @@ async function main() { const webDist = path.join(process.cwd(), "web", "dist"); app.use(express.static(webDist)); - app.get("*", (_req, res) => res.sendFile(path.join(webDist, "index.html"))); + app.get("/{*splat}", (_req, res) => res.sendFile(path.join(webDist, "index.html"))); const server = app.listen(0); const port = (server.address() as { port: number }).port; diff --git a/scripts/preview-spa.ts b/scripts/preview-spa.ts index 8b0efabe..5f17dedd 100644 --- a/scripts/preview-spa.ts +++ b/scripts/preview-spa.ts @@ -54,7 +54,7 @@ async function main() { const app = express(); app.use("/api/v1", createApiRouter({ learningsDir: path.join(os.tmpdir(), "ds-preview-spa-learnings") })); app.use(express.static(webDist)); - app.get("*", (req, res, next) => { + app.get("/{*splat}", (req, res, next) => { if (req.path.startsWith("/api")) return next(); res.sendFile(path.join(webDist, "index.html"), (err) => err && next()); }); diff --git a/scripts/preview-webhooks.ts b/scripts/preview-webhooks.ts index a4dedddd..5ca001ad 100644 --- a/scripts/preview-webhooks.ts +++ b/scripts/preview-webhooks.ts @@ -80,7 +80,7 @@ async function main() { const app = express(); app.use("/api/v1", createApiRouter({ learningsDir, replayWebhook })); app.use(express.static(webDist)); - app.get("*", (req, res, next) => { + app.get("/{*splat}", (req, res, next) => { if (req.path.startsWith("/api")) return next(); res.sendFile(path.join(webDist, "index.html"), (err) => err && next()); }); diff --git a/scripts/screenshot-actionbar.ts b/scripts/screenshot-actionbar.ts index 62d1fedf..042221f5 100644 --- a/scripts/screenshot-actionbar.ts +++ b/scripts/screenshot-actionbar.ts @@ -83,7 +83,7 @@ async function main() { ); const webDist = path.join(__dirname, "..", "web", "dist"); app.use(express.static(webDist)); - app.get("*", (req, res, next) => { + app.get("/{*splat}", (req, res, next) => { if (req.path.startsWith("/api")) return next(); res.sendFile(path.join(webDist, "index.html"), (err) => err && next()); }); diff --git a/scripts/serve-seeded.ts b/scripts/serve-seeded.ts index 7cd53307..90910b35 100644 --- a/scripts/serve-seeded.ts +++ b/scripts/serve-seeded.ts @@ -41,7 +41,7 @@ async function main() { app.use("/api/v1", createApiRouter({ learningsDir, reviewer: fakeReviewer() })); const webDist = path.join(__dirname, "..", "web", "dist"); app.use(express.static(webDist)); - app.get("*", (req, res, next) => { + app.get("/{*splat}", (req, res, next) => { if (req.path.startsWith("/api")) return next(); res.sendFile(path.join(webDist, "index.html"), (err) => err && next()); }); diff --git a/src/ai/review-cache.ts b/src/ai/review-cache.ts new file mode 100644 index 00000000..f81991e7 --- /dev/null +++ b/src/ai/review-cache.ts @@ -0,0 +1,132 @@ +import { createHash } from "node:crypto"; +import type { Config, PRContext, ReviewResult } from "../types.js"; +import { readReviewCache, writeReviewCache } from "../storage/dao.js"; +import { logger } from "../logger.js"; + +/** + * Review result cache. + * + * The same diff gets reviewed more than once more often than it looks: a rebase + * onto a moved base, a force-push that restores a tree already reviewed, a + * revert-and-reapply, a `@bot full review` on an unchanged branch, a retry after + * a transient provider failure. Cross-review dedup already stops those from + * *posting* twice β€” it has never stopped them from *billing* twice, because the + * model call happens before dedup ever sees a fingerprint. This closes that gap. + * + * Correctness rests entirely on the key, so the key is the whole design: see + * {@link reviewCacheKey}. Everything else here is retention and a kill switch. + */ + +/** How long a cached review stays usable. */ +const TTL_DAYS = 14; + +/** `DIFFSENTRY_REVIEW_CACHE=0` turns it off; anything else (including unset) leaves it on. */ +export function reviewCacheEnabled(): boolean { + return process.env.DIFFSENTRY_REVIEW_CACHE !== "0"; +} + +function cutoffIso(now = new Date()): string { + return new Date(now.getTime() - TTL_DAYS * 86_400_000).toISOString(); +} + +/** + * `provider:model` for the PRIMARY provider β€” the identity the key is stamped + * with. A failover answer is never cached (see the write path), so a row always + * means "this is what the primary said". + */ +export function primaryModelId(config: Config): string { + const model = + config.aiProvider === "anthropic" + ? config.anthropicModel + : config.aiProvider === "openai" + ? config.openaiModel + : config.localAiModel; + return `${config.aiProvider}:${model}`; +} + +/** + * The exact prompt the model would receive, with each file's patch swapped for a + * whitespace-normalized hash of itself. + * + * Hashing the prompt verbatim would be one line shorter and is the obvious move, + * but it would never hit: a rebase rewrites every `@@` hunk header without + * changing a line of code, and a rebase is the most common reason the same diff + * is reviewed twice. The caller supplies each patch already paired with its + * `patchHash` digest β€” the same normalizer cross-review dedup fingerprints with, + * which strips hunk headers and collapses whitespace while preserving each + * line's +/- direction and folding in the filename, so two different edits can't + * share a hash. (The caller computes it so this module never has to import the + * reviewer, which imports the AI layer.) + * + * Everything else in the prompt stays verbatim and therefore participates in the + * key: the system prompt (so a profile change, or a future edit to the review + * instructions this module never hears about, invalidates every row), the repo + * config, the learnings, the title, the description, and the related-context + * block. The model id is prepended because the same prompt answers differently + * on a different model. + * + * Patches are substituted by literal string replacement, so passing both the raw + * patch and the budget-truncated patch a large PR actually sends is harmless β€” + * whichever one the builder put in the prompt is the one that matches. + */ +export function reviewCacheKey(opts: { + model: string; + system: string; + user: string; + patches: Array<{ text: string; digest: string }>; +}): string { + let user = opts.user; + const seen = new Set(); + for (const { text, digest } of opts.patches) { + if (!text || seen.has(text)) continue; + seen.add(text); + user = user.split(text).join(``); + } + return createHash("sha256").update(`${opts.model}\u0000${opts.system}\u0000${user}`).digest("hex"); +} + +/** + * A previously cached result for this key, or null. + * + * `servedBy` is deliberately not restored: it records which provider answered + * *this* pass, and a replay was answered by nobody. `parseFailed` results are + * never written, so a hit is always a real review. + */ +export function readCachedReview(cacheKey: string): ReviewResult | null { + if (!reviewCacheEnabled()) return null; + const row = readReviewCache(cacheKey, cutoffIso()); + if (!row) return null; + try { + const parsed = JSON.parse(row.resultJson) as ReviewResult; + if (!parsed || !Array.isArray(parsed.comments)) return null; + delete parsed.servedBy; + return parsed; + } catch (err) { + logger.debug({ err }, "Discarding unreadable review-cache row"); + return null; + } +} + +/** + * Store a result. A parse failure is never cached: it is the provider having a + * bad day, not a property of the diff, and freezing one for a fortnight would + * turn a transient blip into a silently unreviewed branch. + */ +export function writeCachedReview(opts: { + cacheKey: string; + model: string; + context: PRContext; + result: ReviewResult; +}): void { + if (!reviewCacheEnabled()) return; + if (opts.result.parseFailed) return; + writeReviewCache({ + cacheKey: opts.cacheKey, + owner: opts.context.owner, + repo: opts.context.repo, + number: opts.context.pullNumber, + model: opts.model, + resultJson: JSON.stringify(opts.result), + maxAgeIso: cutoffIso(), + }); +} diff --git a/src/api/router.ts b/src/api/router.ts index eebe7c35..9af6f0e9 100644 --- a/src/api/router.ts +++ b/src/api/router.ts @@ -20,6 +20,7 @@ import { bulkTriageFindings, getFindingCoords, getFindingIdsByFingerprint, + reviewCacheStats, type FindingCoords, } from "../storage/dao.js"; import { @@ -72,6 +73,7 @@ import { getRecentIssues, getRecentPRsWithReviews, getRepoOverview, + getReviewScorecard, getRiskDistribution, getRoleOverrides, getSparkline, @@ -812,6 +814,21 @@ export function createApiRouter(deps: ApiDeps): express.Router { return Math.min(Math.max(days, 1), 365); }; + // Finding outcomes: what humans did about what we raised, per repo / source / + // severity. Reported raw (accepted / dismissed / snoozed / untriaged) rather + // than as a precision score β€” see getReviewScorecard. `cache` reports what the + // review cache has saved, which belongs on the same screen: both answer "is + // this reviewer worth what it costs?". + router.get("/analytics/scorecard", (req, res) => { + try { + const days = parseDays(req, 90); + sendData(res, { days, rows: getReviewScorecard(days), cache: reviewCacheStats() }); + } catch (err) { + logger.error({ err }, "api /analytics/scorecard failed"); + sendError(res, 500, "internal", "Failed to load the review scorecard."); + } + }); + // Per-author leaderboard + daily sparkline series. router.get("/analytics/authors", (req, res) => { try { diff --git a/src/dashboard/queries.ts b/src/dashboard/queries.ts index 5246ecff..cc42c074 100644 --- a/src/dashboard/queries.ts +++ b/src/dashboard/queries.ts @@ -785,6 +785,80 @@ export function getPatternRules(limit = 100): PatternRuleRow[] { .all(thirty, limit) as PatternRuleRow[]; } +// ─── Review quality scorecard ────────────────────────────────────── + +/** + * One (repo, source, severity) bucket of findings with what humans did about + * them. Pattern analytics answers "which rules fire?"; this answers the + * question a noisy reviewer actually loses trust over β€” "were they right?" + */ +export interface ScorecardRow { + owner: string; + repo: string; + /** 'ai' | 'safety' | 'builtin' | 'custom' | 'eslint' | 'tsc' | 'semgrep'. */ + source: string; + severity: string; + total: number; + /** Explicitly confirmed by a human (accepted = 1), reaction πŸ‘ included. */ + accepted: number; + /** Explicitly dismissed (accepted = 0), reaction πŸ‘Ž included. */ + dismissed: number; + /** Currently snoozed β€” a human deferred rather than judged. */ + snoozed: number; + /** Nobody has judged these either way. */ + untriaged: number; +} + +/** + * Finding outcomes per repo / source / severity over the last `days`. + * + * `accepted` and `dismissed` are the only two judgements in the data, so they + * are the only two reported; precision is deliberately left to the caller to + * compute, because `accepted / (accepted + dismissed)` off a handful of triaged + * findings is a number that reads as authority and isn't one. `untriaged` is + * returned beside them so a reader can see how much of the picture is missing β€” + * on most repos it is nearly all of it, and a scorecard that hid that would be + * worse than none. + * + * Snoozed is counted by the live clock, so a lapsed snooze falls back into + * `untriaged` on its own rather than needing a sweep. + */ +export function getReviewScorecard(days = 90, limit = 500): ScorecardRow[] { + const db = openDatabase(); + if (!db) return []; + const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString(); + const now = new Date().toISOString(); + try { + return db + .prepare( + `SELECT rv.owner, + rv.repo, + COALESCE(fi.source, 'ai') AS source, + COALESCE(fi.severity, 'minor') AS severity, + COUNT(*) AS total, + SUM(CASE WHEN fi.accepted = 1 THEN 1 ELSE 0 END) AS accepted, + SUM(CASE WHEN fi.accepted = 0 THEN 1 ELSE 0 END) AS dismissed, + SUM(CASE WHEN fi.accepted IS NULL + AND fi.snoozed_until IS NOT NULL + AND fi.snoozed_until > ? THEN 1 ELSE 0 END) AS snoozed, + SUM(CASE WHEN fi.accepted IS NULL + AND (fi.snoozed_until IS NULL + OR fi.snoozed_until <= ?) THEN 1 ELSE 0 END) AS untriaged + FROM findings fi + JOIN reviews rv ON rv.id = fi.review_id + WHERE rv.created_at >= ? + GROUP BY rv.owner, rv.repo, source, severity + ORDER BY total DESC + LIMIT ?`, + ) + .all(now, now, since, limit) as ScorecardRow[]; + } catch (err) { + // The triage columns arrive in migration 2; a v1 database has none of them. + logger.debug({ err }, "queries.getReviewScorecard failed"); + return []; + } +} + // ─── Custom rules + their hit-counts ─────────────────────────────── /** A custom_rules row augmented with its lifetime / recent pattern-hit counts. */ diff --git a/src/feedback.ts b/src/feedback.ts new file mode 100644 index 00000000..25270cf9 --- /dev/null +++ b/src/feedback.ts @@ -0,0 +1,147 @@ +import { logger } from "./logger.js"; +import { bulkTriageFindings, getFindingIdsByFingerprint, recordEvent } from "./storage/dao.js"; + +/** + * Reaction feedback: the cheapest signal a maintainer can give a reviewer. + * + * Replying to a finding already teaches a learning (see `synthesizeLearning`), + * but it costs a sentence and a round trip through the model. A πŸ‘Ž costs two + * clicks, and until now DiffSentry threw it away. This module reads the + * reactions on its own inline findings and turns them into the triage state the + * command center and `getSuppressedFingerprints` already understand, so the + * feedback loop closes without anyone typing. + * + * GitHub has no `reaction` webhook event for Apps, so there is nothing to + * subscribe to β€” the reactions are polled once per review pass, which is also + * exactly when the answer is needed. + */ + +/** Reactions on one of our review threads, as read from the head comment. */ +export interface ThreadFeedback { + /** Dedup fingerprint stamped in the comment body. */ + fingerprint: string; + path: string | null; + /** Logins that reacted πŸ‘Ž. Our own bot is filtered out before this. */ + down: string[]; + /** Logins that reacted πŸ‘. */ + up: string[]; +} + +export interface ReactionFeedbackResult { + /** Fingerprints a human thumbed down β€” this pass must not re-raise them. */ + dismissed: Set; + /** Fingerprints a human thumbed up. */ + affirmed: Set; + /** Finding rows whose triage state actually changed. */ + rowsChanged: number; +} + +const EMPTY: ReactionFeedbackResult = { dismissed: new Set(), affirmed: new Set(), rowsChanged: 0 }; + +/** + * A bot's own login is spelled two ways depending on which GitHub API answered: + * REST says `diffsentry[bot]`, GraphQL's `Bot.login` says `diffsentry`. Reaction + * data comes back over GraphQL, so matching only the REST spelling would let our + * own reactions (anything that ever reacts as the App) read as human feedback. + */ +function isSelf(login: string, botName: string): boolean { + const l = login.toLowerCase(); + const name = botName.toLowerCase(); + return l === name || l === `${name}[bot]`; +} + +/** + * Turn thread reactions into finding triage. + * + * A thread carrying both πŸ‘ and πŸ‘Ž is left untouched: two maintainers disagree, + * and silently taking one side would retire a finding class on a coin flip. + * Everything else is unambiguous β€” πŸ‘Ž dismisses the fingerprint (accepted = 0, + * which is what `getSuppressedFingerprints` reads), πŸ‘ accepts it. + * + * Writes are per-fingerprint, not per-finding, so a πŸ‘Ž retires the whole class + * across every PR it has ever fired on. That is the point: a false positive is + * a property of the rule, not of the pull request that happened to trip it. + */ +export function applyReactionFeedback(opts: { + owner: string; + repo: string; + number: number; + botName: string; + threads: ThreadFeedback[]; +}): ReactionFeedbackResult { + if (opts.threads.length === 0) return EMPTY; + + const dismissed = new Set(); + const affirmed = new Set(); + // Logins per fingerprint, so the triage row records who actually reacted + // rather than an anonymous "reaction". + const byFingerprint = new Map(); + // Disagreement latches for the whole pass. A fingerprint usually has more + // than two threads β€” the same finding fires on every file that trips it β€” so + // forgetting a conflict after handling it lets a third, agreeing thread + // resurrect a verdict two maintainers had already contradicted. + const conflicted = new Set(); + + const retire = (fingerprint: string): void => { + conflicted.add(fingerprint); + byFingerprint.delete(fingerprint); + dismissed.delete(fingerprint); + affirmed.delete(fingerprint); + }; + + for (const t of opts.threads) { + if (!t.fingerprint || conflicted.has(t.fingerprint)) continue; + const down = t.down.filter((l) => !isSelf(l, opts.botName)); + const up = t.up.filter((l) => !isSelf(l, opts.botName)); + // Both reactions on one thread is the same disagreement as two threads + // pulling opposite ways, and binds the fingerprint just as hard. + if (down.length > 0 && up.length > 0) { + logger.debug({ fp: t.fingerprint, path: t.path }, "Reaction feedback split πŸ‘/πŸ‘Ž; leaving triage untouched"); + retire(t.fingerprint); + continue; + } + if (down.length === 0 && up.length === 0) continue; + + const accepted = up.length > 0; + const prior = byFingerprint.get(t.fingerprint); + if (prior && prior.accepted !== accepted) { + retire(t.fingerprint); + continue; + } + (accepted ? affirmed : dismissed).add(t.fingerprint); + byFingerprint.set(t.fingerprint, { + accepted, + who: [...new Set([...(prior?.who ?? []), ...(accepted ? up : down)])], + }); + } + + let rowsChanged = 0; + for (const [fingerprint, { accepted, who }] of byFingerprint) { + const ids = getFindingIdsByFingerprint(fingerprint); + if (ids.length === 0) continue; + const changed = bulkTriageFindings({ + ids, + accepted, + triagedBy: who[0] ?? null, + triageNote: `${accepted ? "πŸ‘" : "πŸ‘Ž"} on ${opts.owner}/${opts.repo}#${opts.number} by ${who.join(", ")}`, + }); + rowsChanged += changed; + if (changed > 0) { + recordEvent({ + owner: opts.owner, + repo: opts.repo, + number: opts.number, + kind: "feedback.reaction", + payload: { fingerprint, accepted, by: who, findings: changed }, + }); + } + } + + if (dismissed.size > 0 || affirmed.size > 0) { + logger.info( + { dismissed: dismissed.size, affirmed: affirmed.size, rowsChanged, owner: opts.owner, repo: opts.repo, pr: opts.number }, + "Applied reaction feedback to finding triage", + ); + } + return { dismissed, affirmed, rowsChanged }; +} diff --git a/src/github.ts b/src/github.ts index 9ff09b2c..a10ad9af 100644 --- a/src/github.ts +++ b/src/github.ts @@ -4,6 +4,7 @@ import { Config, FileChange, PRContext, ReviewComment, ReviewResult, IssueContex import { logger } from "./logger.js"; import { isFileLevelFinding, REVIEW_BODY_MARKER } from "./review-body.js"; import { injectSummaryIntoPRBody } from "./walkthrough.js"; +import type { ThreadFeedback } from "./feedback.js"; import { parseThreadSeverity, parseThreadFingerprint, @@ -442,6 +443,17 @@ export function countBlockingThreads(threads: any[], botLogin: string): number { return n; } +/** + * The slice of GitHub's GraphQL reaction shape `collectFindingFeedback` reads. + * Declared rather than cast: it doubles as the written record of that query's + * contract, which is the one part of the method nothing else can check. + * `reactors` is a union (User | Bot | …) and only `login` is taken from it. + */ +interface ReactionGroup { + content?: string; + reactors?: { nodes?: Array<{ login?: string }> }; +} + export class GitHubClient { private config: Config; @@ -1777,6 +1789,89 @@ export class GitHubClient { return all; } + /** + * Reactions on the head comment of each of our unresolved review threads. + * + * Deliberately its own query rather than extra fields on + * `fetchAllReviewThreads`: a wrong field name there would fail the fetch that + * thread resolution and the sticky verdict both depend on, and reaction + * feedback is a nice-to-have that must never cost us those. Failure here + * returns [] and the review proceeds exactly as it did before. + * + * `reactors` (not the deprecated `users`) is the current connection, and it + * is a union β€” a Bot and a User both have a `login`, so both are read and + * `src/feedback.ts` filters our own out. Resolved threads are skipped: a πŸ‘Ž + * on a finding someone already closed is history, not an instruction. + */ + async collectFindingFeedback( + installationId: number, + owner: string, + repo: string, + pullNumber: number, + signal?: AbortSignal, + ): Promise { + const log = logger.child({ owner, repo, pr: pullNumber }); + const botLogin = `${this.config.botName}[bot]`.toLowerCase(); + const query = ` + query($owner: String!, $repo: String!, $pr: Int!, $cursor: String) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $pr) { + reviewThreads(first: 100, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { + isResolved + path + comments(first: 1) { + nodes { + body + author { login __typename } + reactionGroups { + content + reactors(first: 20) { nodes { __typename ... on User { login } ... on Bot { login } } } + } + } + } + } + } + } + } + } + `; + try { + const octokit = await this.getInstallationOctokit(installationId, signal); + const out: ThreadFeedback[] = []; + let cursor: string | null = null; + while (true) { + const result: any = await octokit.graphql(query, { owner, repo, pr: pullNumber, cursor }); + const block = result.repository.pullRequest.reviewThreads; + for (const thread of block.nodes ?? []) { + if (thread.isResolved) continue; + if (!isOurBotThread(thread, botLogin)) continue; + const head = thread.comments?.nodes?.[0]; + const fingerprint = parseThreadFingerprint(head?.body ?? ""); + if (!fingerprint) continue; + const groups: ReactionGroup[] = head?.reactionGroups ?? []; + const logins = (content: string): string[] => + groups + .filter((g) => g.content === content) + .flatMap((g) => g.reactors?.nodes ?? []) + .map((n) => (typeof n.login === "string" ? n.login : "")) + .filter(Boolean); + const down = logins("THUMBS_DOWN"); + const up = logins("THUMBS_UP"); + if (down.length === 0 && up.length === 0) continue; + out.push({ fingerprint, path: thread.path ?? null, down, up }); + } + if (!block.pageInfo?.hasNextPage) break; + cursor = block.pageInfo.endCursor; + } + return out; + } catch (err) { + log.warn({ err }, "Failed to read reaction feedback; continuing without it"); + return []; + } + } + /** * Resolve all unresolved review threads on a PR (used by the "resolve" command). */ diff --git a/src/mcp/server.ts b/src/mcp/server.ts new file mode 100644 index 00000000..e5045e3e --- /dev/null +++ b/src/mcp/server.ts @@ -0,0 +1,371 @@ +#!/usr/bin/env node +/** + * DiffSentry MCP server β€” the findings, in the agent that has to fix them. + * + * The platform API has always been able to hand a coding agent the findings on + * a PR; getting them there meant a human copying a curl response into a prompt. + * This is that same API spoken over MCP (stdio), so Claude Code, Cursor or any + * MCP client can ask for them directly. + * + * It is a CLIENT of the HTTP API, not a second way into the database: it holds + * no DB handle, mints nothing, and can do exactly what its bearer token's scopes + * allow. A `read` token cannot trigger a review, because the server it talks to + * says no β€” the authorization story stays in one place. + * + * Protocol is implemented directly rather than through an SDK. It is JSON-RPC + * 2.0 over newline-delimited stdio and four tools; a dependency would be larger + * than the thing it implements, and this repo keeps its runtime dependency list + * short on purpose. + * + * Run it with: + * DIFFSENTRY_URL=https://your-instance DIFFSENTRY_TOKEN=dsk_... node dist/mcp/server.js + */ + +/** + * Per-request deadline on the outbound HTTP call. + * + * `main` answers requests in arrival order, so an unbounded fetch does not just + * hang its own tool call β€” it blocks every MCP request queued behind it, for as + * long as the socket stays open. Generous rather than tight: `search_findings` + * against a large database is legitimately slow, and a timeout that fires on + * healthy work is worse than none. + */ +const REQUEST_TIMEOUT_MS = 30_000; + +/** Versions of the MCP spec this server is known to speak. */ +const SUPPORTED_PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"]; +const DEFAULT_PROTOCOL = SUPPORTED_PROTOCOLS[0]; + +/** + * stdout is the protocol channel and nothing else may touch it β€” a single stray + * log line makes the server unparseable to its client. This is also why the + * module never imports the app's pino logger, which writes to stdout. + */ +function log(message: string, extra?: unknown): void { + const suffix = extra === undefined ? "" : ` ${JSON.stringify(extra)}`; + process.stderr.write(`[diffsentry-mcp] ${message}${suffix}\n`); +} + +interface ToolDef { + name: string; + description: string; + inputSchema: { type: "object"; properties: Record; required?: string[] }; + /** Returns the text the client sees. Throwing produces a tool error, not a transport error. */ + run: (args: Record, api: ApiClient) => Promise; +} + +// ─── HTTP client ──────────────────────────────────────────────────── + +export class ApiClient { + constructor( + private readonly baseUrl: string, + private readonly token: string, + ) {} + + /** + * `path` is relative to the `/api/v1` mount. The API's error envelope carries + * a human-readable message, so it is surfaced verbatim β€” a 403 saying the + * token lacks the `review` scope is exactly what the agent needs to read. + */ + async request(method: "GET" | "POST", path: string, body?: unknown): Promise { + const url = `${this.baseUrl}/api/v1${path}`; + let res: Response; + try { + res = await fetch(url, { + method, + headers: { + Authorization: `Bearer ${this.token}`, + Accept: "application/json", + ...(body === undefined ? {} : { "Content-Type": "application/json" }), + }, + body: body === undefined ? undefined : JSON.stringify(body), + // `AbortSignal.timeout` over a hand-rolled controller: there is no timer + // left to clear, so no path through this function can leak one. + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + } catch (err) { + // The agent reads this string and decides whether to retry, so name the + // cause rather than surfacing a bare "The operation was aborted". + if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) { + throw new Error( + `${method} ${path} timed out after ${REQUEST_TIMEOUT_MS / 1000}s β€” is DIFFSENTRY_URL reachable from here?`, + { cause: err }, + ); + } + throw new Error( + `${method} ${path} could not reach ${this.baseUrl}: ${err instanceof Error ? err.message : String(err)}`, + { cause: err }, + ); + } + const text = await res.text(); + let parsed: unknown = text; + try { + parsed = text.length > 0 ? JSON.parse(text) : null; + } catch { + // Left as text β€” an HTML error page from a proxy in front of the instance + // is more useful to show than a parse failure about it. + } + if (!res.ok) { + const envelope = parsed as { error?: { message?: string; code?: string } } | null; + const detail = envelope?.error?.message ?? (typeof parsed === "string" ? parsed.slice(0, 400) : ""); + throw new Error(`${method} ${path} failed (HTTP ${res.status})${detail ? `: ${detail}` : ""}`); + } + // Every API response is wrapped in `{ data: ... }`; unwrap so a tool result + // is the payload itself rather than a layer the model has to dig through. + const envelope = parsed as { data?: unknown } | null; + return envelope && typeof envelope === "object" && "data" in envelope ? envelope.data : parsed; + } +} + +// ─── Argument coercion ────────────────────────────────────────────── +// +// An MCP client's arguments are whatever the model produced, so nothing here +// trusts a type. A number arriving as "42" is the common case and is accepted; +// anything genuinely unusable raises a tool error naming the field. + +function str(args: Record, key: string, required: true): string; +function str(args: Record, key: string, required?: false): string | undefined; +function str(args: Record, key: string, required = false): string | undefined { + const v = args[key]; + if (typeof v === "string" && v.trim().length > 0) return v.trim(); + if (typeof v === "number") return String(v); + if (required) throw new Error(`Missing required argument '${key}'.`); + return undefined; +} + +function int(args: Record, key: string, required = false): number | undefined { + const v = args[key]; + const n = typeof v === "number" ? v : typeof v === "string" ? Number.parseInt(v, 10) : NaN; + if (Number.isFinite(n)) return n; + if (required) throw new Error(`Argument '${key}' must be a number.`); + return undefined; +} + +/** `owner/repo` or separate fields β€” models reliably produce both shapes. */ +function repoCoords(args: Record): { owner: string; repo: string } { + const combined = str(args, "repo"); + if (combined?.includes("/")) { + const [owner, repo] = combined.split("/", 2); + if (owner && repo) return { owner, repo }; + } + const owner = str(args, "owner"); + if (owner && combined) return { owner, repo: combined }; + throw new Error("Provide the repository as 'owner/repo', or as separate 'owner' and 'repo' arguments."); +} + +const q = encodeURIComponent; + +// ─── Tools ────────────────────────────────────────────────────────── + +export const TOOLS: ToolDef[] = [ + { + name: "list_repos", + description: + "List the repositories DiffSentry has reviewed, with review counts and when each was last reviewed. " + + "Start here when you do not already know the exact 'owner/repo'.", + inputSchema: { type: "object", properties: {} }, + run: async (_args, api) => api.request("GET", "/repos"), + }, + { + name: "get_pr_findings", + description: + "Every DiffSentry finding on one pull request, with the latest review's summary, risk score and verdict. " + + "This is the tool to call before fixing review comments: each finding carries its file, line, severity and body.", + inputSchema: { + type: "object", + properties: { + repo: { type: "string", description: "'owner/repo' (or just the repo name alongside 'owner')." }, + owner: { type: "string", description: "Repository owner, when 'repo' is not 'owner/repo'." }, + number: { type: "number", description: "Pull request number." }, + }, + required: ["repo", "number"], + }, + run: async (args, api) => { + const { owner, repo } = repoCoords(args); + const number = int(args, "number", true)!; + return api.request("GET", `/repos/${q(owner)}/${q(repo)}/prs/${number}`); + }, + }, + { + name: "search_findings", + description: + "Search findings across repositories β€” by severity, source, repo, age, or free text on the title and path. " + + "Use it to find whether an issue has been raised before, or to sweep up every open finding of a severity.", + inputSchema: { + type: "object", + properties: { + severity: { type: "string", enum: ["critical", "major", "minor", "nit"] }, + source: { type: "string", description: "e.g. 'ai', 'safety', 'builtin', 'custom'." }, + repo: { type: "string", description: "Restrict to one 'owner/repo'." }, + query: { type: "string", description: "Free-text match on the finding title or path." }, + age_days: { type: "number", description: "Only findings newer than this many days." }, + limit: { type: "number", description: "Max results (default 50)." }, + }, + }, + run: async (args, api) => { + const params = new URLSearchParams(); + const severity = str(args, "severity"); + if (severity) params.set("severity", severity); + const source = str(args, "source"); + if (source) params.set("source", source); + const repo = str(args, "repo"); + if (repo) params.set("repo", repo); + const query = str(args, "query"); + if (query) params.set("q", query); + const age = int(args, "age_days"); + if (age !== undefined) params.set("age", String(age)); + params.set("limit", String(Math.min(Math.max(int(args, "limit") ?? 50, 1), 200))); + return api.request("GET", `/findings?${params.toString()}`); + }, + }, + { + name: "request_review", + description: + "Ask DiffSentry to review a pull request β€” 'incremental' (default) reviews what changed since the last pass, " + + "'full' re-reviews every file. Returns as soon as the review is queued, so call get_pr_findings afterwards to " + + "read the result. Requires a token with the 'review' scope.", + inputSchema: { + type: "object", + properties: { + repo: { type: "string", description: "'owner/repo' (or just the repo name alongside 'owner')." }, + owner: { type: "string", description: "Repository owner, when 'repo' is not 'owner/repo'." }, + number: { type: "number", description: "Pull request number." }, + mode: { type: "string", enum: ["incremental", "full"], description: "Defaults to 'incremental'." }, + }, + required: ["repo", "number"], + }, + run: async (args, api) => { + const { owner, repo } = repoCoords(args); + const number = int(args, "number", true)!; + const mode = str(args, "mode") === "full" ? "full" : "incremental"; + return api.request("POST", `/repos/${q(owner)}/${q(repo)}/prs/${number}/review`, { mode }); + }, + }, +]; + +// ─── JSON-RPC plumbing ────────────────────────────────────────────── + +type Json = Record; + +function send(msg: Json): void { + process.stdout.write(`${JSON.stringify(msg)}\n`); +} + +function reply(id: unknown, result: unknown): void { + send({ jsonrpc: "2.0", id, result }); +} + +function replyError(id: unknown, code: number, message: string): void { + send({ jsonrpc: "2.0", id, error: { code, message } }); +} + +/** + * A failed tool is reported as a SUCCESSFUL JSON-RPC response carrying + * `isError: true`, which is what the spec asks for: the model should see β€” and + * be able to act on β€” "that repo does not exist" or "this token cannot trigger + * reviews", not have the transport fail underneath it. + */ +async function handleToolCall(id: unknown, params: Json, api: ApiClient): Promise { + const name = typeof params.name === "string" ? params.name : ""; + const tool = TOOLS.find((t) => t.name === name); + if (!tool) { + reply(id, { content: [{ type: "text", text: `Unknown tool '${name}'.` }], isError: true }); + return; + } + const args = (params.arguments ?? {}) as Record; + try { + const result = await tool.run(args, api); + reply(id, { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + log(`tool ${name} failed`, { message }); + reply(id, { content: [{ type: "text", text: message }], isError: true }); + } +} + +export async function dispatch(msg: Json, api: ApiClient): Promise { + const { id, method, params } = msg as { id?: unknown; method?: string; params?: Json }; + // A notification has no id and takes no response β€” `notifications/initialized` + // is the one every client sends. + const isNotification = id === undefined || id === null; + + switch (method) { + case "initialize": { + const asked = (params?.protocolVersion as string | undefined) ?? ""; + const protocolVersion = SUPPORTED_PROTOCOLS.includes(asked) ? asked : DEFAULT_PROTOCOL; + reply(id, { + protocolVersion, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: "diffsentry", version: "1.0.0" }, + }); + return; + } + case "tools/list": + reply(id, { + tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })), + }); + return; + case "tools/call": + await handleToolCall(id, params ?? {}, api); + return; + case "ping": + reply(id, {}); + return; + default: + if (isNotification) return; + replyError(id, -32601, `Method not found: ${method ?? "(none)"}`); + } +} + +// ─── Entry point ──────────────────────────────────────────────────── + +export function createApiClient(env: NodeJS.ProcessEnv = process.env): ApiClient { + const baseUrl = (env.DIFFSENTRY_URL ?? "").trim().replace(/\/+$/, ""); + const token = (env.DIFFSENTRY_TOKEN ?? "").trim(); + if (!baseUrl) throw new Error("DIFFSENTRY_URL is required (e.g. https://diffsentry.example.com)."); + if (!token) throw new Error("DIFFSENTRY_TOKEN is required β€” mint one under API tokens in the dashboard."); + return new ApiClient(baseUrl, token); +} + +export async function main(): Promise { + const api = createApiClient(); + log(`ready β€” ${TOOLS.length} tools`); + + // Messages are newline-delimited, but a chunk boundary can fall anywhere, so + // buffer and only act on complete lines. + let buffer = ""; + process.stdin.setEncoding("utf8"); + for await (const chunk of process.stdin) { + buffer += chunk; + let newline = buffer.indexOf("\n"); + while (newline !== -1) { + const line = buffer.slice(0, newline).trim(); + buffer = buffer.slice(newline + 1); + newline = buffer.indexOf("\n"); + if (line.length === 0) continue; + let msg: Json; + try { + msg = JSON.parse(line) as Json; + } catch { + // No id to answer with, so there is nobody to tell. Logged and skipped. + log("ignoring unparseable line"); + continue; + } + // Awaited in order: a client may pipeline requests, and answering them in + // arrival order keeps the transcript readable. Tool calls are network + // round trips to one instance, so there is nothing to win by racing them. + await dispatch(msg, api).catch((err) => log("dispatch failed", { message: String(err) })); + } + } +} + +// Only run as the entrypoint (`node dist/mcp/server.js` / `tsx +// src/mcp/server.ts`), matching src/cli/backfill.ts. Imported for its exports β€” +// which is how the tests reach the tool table β€” the module starts nothing and +// never touches stdin. +if (require.main === module) { + main().catch((err) => { + log("fatal", { message: err instanceof Error ? err.message : String(err) }); + process.exit(1); + }); +} diff --git a/src/reviewer.ts b/src/reviewer.ts index 2fd60cc2..a920ca82 100644 --- a/src/reviewer.ts +++ b/src/reviewer.ts @@ -10,7 +10,7 @@ import { WALKTHROUGH_MARKER, formatWalkthrough, formatWalkthroughInner, wrapWalk import { parseCommand, formatHelpMessage, formatConfigMessage, formatUnknownCommandMessage } from "./commands.js"; import type { SlashOptions } from "./slash-commands.js"; import { parseIssueCommand, formatIssueHelpMessage } from "./issue-commands.js"; -import { buildIssueSummaryInstruction, buildIssuePlanInstruction } from "./ai/prompt.js"; +import { buildIssueSummaryInstruction, buildIssuePlanInstruction, buildReviewPrompt } from "./ai/prompt.js"; import { synthesizeReviewSummary, buildReviewComment, @@ -40,6 +40,7 @@ import { renderAutoReleaseNotes, } from "./auto-release-notes.js"; import { recordRepo, recordPR, recordReview, recordFindings, recordPatternHits, recordIssue, recordIssueAction, getSuppressedFingerprints, listCustomRulesForRepo, deleteReviewJob, getWalkthroughState, saveWalkthroughState } from "./storage/dao.js"; +import { applyReactionFeedback } from "./feedback.js"; import { runSafetyScanners } from "./safety-scanner.js"; import { runPatternChecks } from "./pattern-checks.js"; import { runStaticAnalysis, resolveCheckoutDir, dedupeStaticFindings } from "./static-analysis.js"; @@ -53,6 +54,7 @@ import { isPauseAll, resolveProfileOverride, resolveMaxFilesOverride } from "./s import { reviewQueue, type ReviewHandle } from "./realtime/queue.js"; import { buildGraphContext } from "./graph-context.js"; import { applyDiffBudget, resolveDiffBudget } from "./ai/diff-budget.js"; +import { primaryModelId, readCachedReview, reviewCacheKey, writeCachedReview } from "./ai/review-cache.js"; /** Map a PR chat command to the cost-attribution kind for its AI calls. */ function costKindForCommand(type: string): string { @@ -1688,13 +1690,49 @@ export class Reviewer { ? { ...context, files: allReviewableFiles, diffBudget: wholePRBudget } : context; + // Review result cache. Cross-review dedup already stops the same finding + // being POSTED twice; it has never stopped it being PAID for twice, + // because the model call happens long before dedup sees a fingerprint. A + // rebase, a force-push back to a tree we already reviewed, a + // revert-and-reapply, a retried pass and an unchanged `full review` all + // land on the same key here. The walkthrough is deliberately not cached: + // it is one call against the whole PR, not per-finding work, and it is + // what a reader looks at first. + const cacheModel = primaryModelId(this.config); + const cachePrompt = buildReviewPrompt(context, repoConfig, knowledgeLearnings); + const cacheKey = reviewCacheKey({ + model: cacheModel, + system: cachePrompt.system, + user: cachePrompt.user, + // Both the raw patch and the budget-truncated one a large PR actually + // sends; substitution is by literal match, so passing both is harmless. + patches: [ + ...context.files.map((f) => ({ text: f.patch ?? "", digest: patchHash(f.filename, f.patch ?? "") })), + ...(context.diffBudget?.files ?? []).map((b) => ({ text: b.patch, digest: patchHash(b.filename, b.patch) })), + ], + }); + const cachedReview = readCachedReview(cacheKey); + if (cachedReview) { + log.info( + { key: cacheKey.slice(0, 12), comments: cachedReview.comments.length }, + "Review served from cache β€” skipping the model call", + ); + } + const [reviewResult, walkthroughResult] = await Promise.all([ - this.ai.review(context, repoConfig, knowledgeLearnings), + cachedReview ?? this.ai.review(context, repoConfig, knowledgeLearnings), walkthroughEnabled || summaryEnabled ? this.ai.generateWalkthrough(walkthroughContext, repoConfig) : Promise.resolve(null), ]); + // Written before anything downstream mutates the result: the cache must + // hold what the model said, not what this pass went on to filter. + // A failover answer is skipped so a row always means the primary model. + if (!cachedReview && reviewResult.servedBy !== "backup") { + writeCachedReview({ cacheKey, model: cacheModel, context, result: reviewResult }); + } + // Stash per-file fan-in / impact-radius counts on the review result so // downstream passes (e.g. severity calibration) can weight findings in // high-blast-radius files without re-querying the graph. Best-effort: @@ -2358,26 +2396,45 @@ export class Reviewer { if (dropped > 0) log.info({ dropped }, "Suppressed re-worded PR-level repeats"); } + // Reaction feedback. A πŸ‘Ž on one of our inline findings is a maintainer + // telling us about THAT finding, so it suppresses unconditionally β€” unlike + // the command-center triage read below, which is a housekeeping state an + // operator opts into. Both land in the same set because the filter is the + // same; only the authority differs. Best-effort: a failed read returns an + // empty set and the pass behaves exactly as it did before reactions were + // read at all. + const suppressed = new Set(); + try { + const threads = await this.github.collectFindingFeedback(installationId, owner, repo, pullNumber, signal); + const feedback = applyReactionFeedback({ + owner, repo, number: pullNumber, botName: this.config.botName, threads, + }); + for (const fp of feedback.dismissed) suppressed.add(fp); + } catch (err) { + log.warn({ err }, "Reaction feedback pass failed; continuing"); + } + // Opt-in: suppress findings whose fingerprint a human has dismissed (or // currently snoozed) in the command center. Off by default β€” gated on // DIFFSENTRY_SUPPRESS_DISMISSED so triage data never silently changes // review output unless an operator explicitly turns it on. The read // no-ops gracefully (empty set) when persistence is disabled. if (process.env.DIFFSENTRY_SUPPRESS_DISMISSED === "1") { - const suppressed = getSuppressedFingerprints(); - if (suppressed.size > 0) { - const before = reviewResult.comments.length; - reviewResult.comments = reviewResult.comments.filter((c) => { - const fp = c.fingerprint; - if (fp && suppressed.has(fp)) { - log.debug({ fp, path: c.path, line: c.line }, "Suppressing dismissed/snoozed finding (triage feedback)"); - return false; - } - return true; - }); - const dropped = before - reviewResult.comments.length; - if (dropped > 0) log.info({ dropped }, "Suppressed findings via triage feedback"); - } + for (const fp of getSuppressedFingerprints()) suppressed.add(fp); + } + + if (suppressed.size > 0) { + const before = reviewResult.comments.length; + reviewResult.comments = reviewResult.comments.filter((c) => { + const fp = c.fingerprint; + if (fp && suppressed.has(fp)) { + log.debug({ fp, path: c.path, line: c.line }, "Suppressing dismissed/snoozed finding (triage feedback)"); + return false; + } + return true; + }); + const dropped = before - reviewResult.comments.length; + if (dropped > 0) log.info({ dropped }, "Suppressed findings via triage/reaction feedback"); } // Quiet profile: hold everything but critical/major out of the inline diff --git a/src/storage/dao.ts b/src/storage/dao.ts index d5a18197..23620181 100644 --- a/src/storage/dao.ts +++ b/src/storage/dao.ts @@ -2216,3 +2216,102 @@ export function releaseWebhookDelivery(claim: WebhookDeliveryClaim): boolean { } } + +// ─── AI review cache (migration 9) ────────────────────────────── +// +// Pure cost optimisation: every read may miss and every write may be dropped +// without changing what DiffSentry posts. The key is computed in +// src/ai/review-cache.ts, which owns the policy; this layer only stores bytes. + +export interface CachedReviewRow { + resultJson: string; + createdAt: string; + hits: number; +} + +/** + * Look up a cached review by key, ignoring rows older than `maxAgeIso`. + * Bumps the hit counter on a hit β€” the operator view uses it to show what the + * cache has actually saved, and a hit is never on the latency-critical path + * (it replaces a model call that takes seconds). + */ +export function readReviewCache(cacheKey: string, maxAgeIso: string): CachedReviewRow | null { + const db = openDatabase(); + if (!db || !cacheKey) return null; + try { + const row = db + .prepare( + `SELECT result_json AS resultJson, created_at AS createdAt, hits + FROM ai_review_cache WHERE cache_key = ? AND created_at >= ?`, + ) + .get(cacheKey, maxAgeIso) as CachedReviewRow | undefined; + if (!row) return null; + db.prepare(`UPDATE ai_review_cache SET hits = hits + 1, last_hit_at = ? WHERE cache_key = ?`).run( + new Date().toISOString(), + cacheKey, + ); + return row; + } catch (err) { + logger.debug({ err }, "dao.readReviewCache failed"); + return null; + } +} + +/** + * Store a review result. `INSERT OR REPLACE` rather than `OR IGNORE`: a repeat + * write means the row expired and was re-earned, and the fresh `created_at` is + * what keeps it alive. Pruning is folded in here so retention needs no + * scheduler β€” the table only grows on a write, so a write is the only moment it + * can need trimming. + */ +export function writeReviewCache(opts: { + cacheKey: string; + owner: string; + repo: string; + number: number; + model: string; + resultJson: string; + maxAgeIso: string; +}): boolean { + const db = openDatabase(); + if (!db || !opts.cacheKey) return false; + try { + db.prepare( + `INSERT OR REPLACE INTO ai_review_cache + (cache_key, owner, repo, number, model, result_json, created_at, hits, last_hit_at) + VALUES (?, ?, ?, ?, ?, ?, ?, 0, NULL)`, + ).run( + opts.cacheKey, + opts.owner, + opts.repo, + opts.number, + opts.model, + opts.resultJson, + new Date().toISOString(), + ); + db.prepare(`DELETE FROM ai_review_cache WHERE created_at < ?`).run(opts.maxAgeIso); + return true; + } catch (err) { + logger.debug({ err }, "dao.writeReviewCache failed"); + return false; + } +} + +/** Rows, hits and age span of the cache β€” the operator-facing summary. */ +export function reviewCacheStats(): { rows: number; hits: number; oldest: string | null } { + const db = openDatabase(); + if (!db) return { rows: 0, hits: 0, oldest: null }; + try { + const row = db + .prepare( + // `rows` is a SQLite keyword (window frames) β€” alias around it. + `SELECT COUNT(*) AS row_count, COALESCE(SUM(hits), 0) AS hit_count, MIN(created_at) AS oldest + FROM ai_review_cache`, + ) + .get() as { row_count: number; hit_count: number; oldest: string | null }; + return { rows: row.row_count ?? 0, hits: row.hit_count ?? 0, oldest: row.oldest ?? null }; + } catch (err) { + logger.debug({ err }, "dao.reviewCacheStats failed"); + return { rows: 0, hits: 0, oldest: null }; + } +} diff --git a/src/storage/db.ts b/src/storage/db.ts index 0f668703..f4fc10de 100644 --- a/src/storage/db.ts +++ b/src/storage/db.ts @@ -417,6 +417,38 @@ CREATE TABLE IF NOT EXISTS impact_shares ( CREATE INDEX IF NOT EXISTS idx_impact_shares_hash ON impact_shares(share_hash); `; +/** + * Migration 9 β€” review result cache. One row per (model, prompt) pair whose + * patches have been whitespace-normalized, so the same code reviewed twice + * costs one model call. A rebase, a force-push that restores an earlier tree, + * a revert-and-reapply and a `@bot full review` re-run all land on the same key. + * + * `cache_key` is the primary key and already a SHA-256 of everything that can + * change the answer (see src/ai/review-cache.ts) β€” nothing about the PR needs + * to participate in the lookup. The owner/repo/number/model columns are + * recorded for the operator view only: they say which PR first paid for a row, + * never which PRs may read it. + * + * Nothing here is authoritative. The table can be emptied at any time and the + * only consequence is paying for the next review again. + * + * Strictly additive (one new table) β€” same rules as every other migration. + */ +const SCHEMA_V9 = ` +CREATE TABLE IF NOT EXISTS ai_review_cache ( + cache_key TEXT PRIMARY KEY, + owner TEXT, + repo TEXT, + number INTEGER, + model TEXT, + result_json TEXT NOT NULL, + created_at TEXT NOT NULL, + hits INTEGER NOT NULL DEFAULT 0, + last_hit_at TEXT +); +CREATE INDEX IF NOT EXISTS idx_ai_review_cache_created ON ai_review_cache(created_at); +`; + export interface Migration { version: number; name: string; @@ -511,6 +543,7 @@ DROP INDEX IF EXISTS idx_saved_views_owner; DROP TABLE IF EXISTS saved_views; `, }, + { version: 9, name: "ai_review_cache", sql: SCHEMA_V9 }, ]; /** Highest version this binary knows how to migrate to. */ diff --git a/tests/unit/mcp-server.test.ts b/tests/unit/mcp-server.test.ts new file mode 100644 index 00000000..cda5d6b1 --- /dev/null +++ b/tests/unit/mcp-server.test.ts @@ -0,0 +1,170 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { TOOLS, dispatch, createApiClient, type ApiClient } from "../../src/mcp/server.js"; + +// Captures what the server writes to stdout β€” which is the protocol channel and +// must carry nothing else. +const sent: Array> = []; + +beforeEach(() => { + sent.length = 0; + vi.spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => { + for (const line of String(chunk).split("\n")) { + if (line.trim()) sent.push(JSON.parse(line)); + } + return true; + }); + vi.spyOn(process.stderr, "write").mockImplementation(() => true); +}); + +const requests: Array<{ method: string; path: string; body?: unknown }> = []; +function fakeApi(result: unknown | (() => never)): ApiClient { + return { + request: async (method: string, path: string, body?: unknown) => { + requests.push({ method, path, body }); + return typeof result === "function" ? (result as () => never)() : result; + }, + } as unknown as ApiClient; +} + +const api = fakeApi({ ok: true }); + +describe("mcp server protocol", () => { + it("answers initialize with the client's protocol version when it knows it", async () => { + await dispatch({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2024-11-05" } }, api); + expect(sent[0].result).toMatchObject({ + protocolVersion: "2024-11-05", + capabilities: { tools: { listChanged: false } }, + }); + }); + + it("falls back to its own protocol version for an unknown one", async () => { + await dispatch({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "1999-01-01" } }, api); + expect((sent[0].result as { protocolVersion: string }).protocolVersion).toBe("2025-06-18"); + }); + + it("lists every tool with a schema", async () => { + await dispatch({ jsonrpc: "2.0", id: 2, method: "tools/list" }, api); + const tools = (sent[0].result as { tools: Array<{ name: string; inputSchema: unknown; description: string }> }).tools; + expect(tools.map((t) => t.name).sort()).toEqual(["get_pr_findings", "list_repos", "request_review", "search_findings"]); + for (const t of tools) { + expect(t.description.length).toBeGreaterThan(20); + expect(t.inputSchema).toMatchObject({ type: "object" }); + } + }); + + // A notification carries no id, so answering it would desynchronise the client. + it("stays silent on notifications/initialized", async () => { + await dispatch({ jsonrpc: "2.0", method: "notifications/initialized" }, api); + expect(sent).toHaveLength(0); + }); + + it("rejects an unknown method with a JSON-RPC error", async () => { + await dispatch({ jsonrpc: "2.0", id: 3, method: "resources/list" }, api); + expect(sent[0].error).toMatchObject({ code: -32601 }); + }); + + // A failed tool must come back as a successful RPC carrying isError, so the + // model can read the reason instead of the transport dying under it. + it("reports a tool failure as an isError result, not a transport error", async () => { + const failing = fakeApi(() => { + throw new Error("GET /repos failed (HTTP 403): token lacks the 'review' scope"); + }); + await dispatch( + { jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "list_repos", arguments: {} } }, + failing, + ); + expect(sent[0].error).toBeUndefined(); + const result = sent[0].result as { isError?: boolean; content: Array<{ text: string }> }; + expect(result.isError).toBe(true); + expect(result.content[0].text).toContain("403"); + }); + + it("reports an unknown tool as an isError result", async () => { + await dispatch({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "rm_rf", arguments: {} } }, api); + expect((sent[0].result as { isError: boolean }).isError).toBe(true); + }); +}); + +describe("mcp tool arguments", () => { + const tool = (name: string) => TOOLS.find((t) => t.name === name)!; + + beforeEach(() => { + requests.length = 0; + }); + + it("accepts the repo as owner/repo", async () => { + await tool("get_pr_findings").run({ repo: "acme/app", number: 12 }, fakeApi({})); + expect(requests[0].path).toBe("/repos/acme/app/prs/12"); + }); + + it("accepts owner and repo as separate fields", async () => { + await tool("get_pr_findings").run({ owner: "acme", repo: "app", number: "12" }, fakeApi({})); + expect(requests[0].path).toBe("/repos/acme/app/prs/12"); + }); + + it("names the offending field when the repo is unusable", async () => { + await expect(tool("get_pr_findings").run({ number: 12 }, fakeApi({}))).rejects.toThrow(/owner\/repo/); + }); + + it("percent-encodes path segments", async () => { + await tool("get_pr_findings").run({ owner: "a b", repo: "c/d", number: 1 }, fakeApi({})); + expect(requests[0].path).toBe("/repos/c/d/prs/1"); + }); + + it("clamps the findings limit", async () => { + await tool("search_findings").run({ limit: 9999 }, fakeApi({})); + expect(requests[0].path).toContain("limit=200"); + }); + + it("defaults request_review to incremental and only allows the two modes", async () => { + await tool("request_review").run({ repo: "acme/app", number: 3, mode: "nonsense" }, fakeApi({})); + expect(requests[0]).toMatchObject({ method: "POST", body: { mode: "incremental" } }); + await tool("request_review").run({ repo: "acme/app", number: 3, mode: "full" }, fakeApi({})); + expect(requests[1].body).toMatchObject({ mode: "full" }); + }); +}); + +// `main` answers requests in arrival order, so an unbounded fetch blocks every +// MCP request queued behind it, not just its own. +describe("mcp request deadline", () => { + const realFetch = globalThis.fetch; + afterEach(() => { + globalThis.fetch = realFetch; + }); + + it("passes an abort signal to every outbound request", async () => { + let seen: RequestInit | undefined; + globalThis.fetch = (async (_url: string, init: RequestInit) => { + seen = init; + return new Response('{"data":{}}', { status: 200, headers: { "Content-Type": "application/json" } }); + }) as unknown as typeof fetch; + const client = createApiClient({ DIFFSENTRY_URL: "https://x", DIFFSENTRY_TOKEN: "dsk_x" }); + await client.request("GET", "/repos"); + expect(seen?.signal).toBeInstanceOf(AbortSignal); + }); + + it("turns a timed-out request into a readable tool error", async () => { + globalThis.fetch = (async () => { + const err = new Error("The operation was aborted due to timeout"); + err.name = "TimeoutError"; + throw err; + }) as unknown as typeof fetch; + const client = createApiClient({ DIFFSENTRY_URL: "https://x", DIFFSENTRY_TOKEN: "dsk_x" }); + await dispatch( + { jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "list_repos", arguments: {} } }, + client, + ); + const result = sent[0].result as { isError: boolean; content: Array<{ text: string }> }; + expect(result.isError).toBe(true); + expect(result.content[0].text).toMatch(/timed out after 30s/); + expect(result.content[0].text).toContain("DIFFSENTRY_URL"); + }); +}); + +describe("mcp configuration", () => { + it("requires a URL and a token, and says which is missing", () => { + expect(() => createApiClient({ DIFFSENTRY_TOKEN: "dsk_x" })).toThrow(/DIFFSENTRY_URL/); + expect(() => createApiClient({ DIFFSENTRY_URL: "https://x" })).toThrow(/DIFFSENTRY_TOKEN/); + expect(() => createApiClient({ DIFFSENTRY_URL: "https://x", DIFFSENTRY_TOKEN: "dsk_x" })).not.toThrow(); + }); +}); diff --git a/tests/unit/reaction-feedback.test.ts b/tests/unit/reaction-feedback.test.ts new file mode 100644 index 00000000..77b07027 --- /dev/null +++ b/tests/unit/reaction-feedback.test.ts @@ -0,0 +1,140 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const bulkTriageFindings = vi.fn().mockReturnValue(1); +const recordEvent = vi.fn(); + +vi.mock("../../src/storage/dao.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + getFindingIdsByFingerprint: (fp: string) => (fp === "deadbeef" || fp === "cafe1234" ? [1, 2] : []), + bulkTriageFindings: (...args: unknown[]) => bulkTriageFindings(...args), + recordEvent: (...args: unknown[]) => recordEvent(...args), + }; +}); + +const { applyReactionFeedback } = await import("../../src/feedback.js"); + +const base = { owner: "acme", repo: "app", number: 7, botName: "diffsentry" }; + +beforeEach(() => { + bulkTriageFindings.mockClear(); + recordEvent.mockClear(); +}); + +describe("reaction feedback", () => { + it("dismisses the fingerprint a maintainer thumbed down", () => { + const out = applyReactionFeedback({ + ...base, + threads: [{ fingerprint: "deadbeef", path: "src/a.ts", down: ["luke"], up: [] }], + }); + expect([...out.dismissed]).toEqual(["deadbeef"]); + expect(out.affirmed.size).toBe(0); + expect(bulkTriageFindings).toHaveBeenCalledTimes(1); + expect(bulkTriageFindings.mock.calls[0][0]).toMatchObject({ ids: [1, 2], accepted: false, triagedBy: "luke" }); + expect(recordEvent).toHaveBeenCalledTimes(1); + }); + + it("accepts the fingerprint a maintainer thumbed up", () => { + const out = applyReactionFeedback({ + ...base, + threads: [{ fingerprint: "deadbeef", path: "src/a.ts", down: [], up: ["luke"] }], + }); + expect([...out.affirmed]).toEqual(["deadbeef"]); + expect(out.dismissed.size).toBe(0); + expect(bulkTriageFindings.mock.calls[0][0]).toMatchObject({ accepted: true }); + }); + + // Two maintainers disagreeing is not a mandate. Picking a side here would + // retire a whole finding class on a coin flip. + it("leaves a thread carrying both reactions untouched", () => { + const out = applyReactionFeedback({ + ...base, + threads: [{ fingerprint: "deadbeef", path: "src/a.ts", down: ["luke"], up: ["sam"] }], + }); + expect(out.dismissed.size).toBe(0); + expect(out.affirmed.size).toBe(0); + expect(bulkTriageFindings).not.toHaveBeenCalled(); + }); + + // Same disagreement, spread across two threads on the same finding class. + it("cancels a fingerprint that two threads disagree about", () => { + const out = applyReactionFeedback({ + ...base, + threads: [ + { fingerprint: "deadbeef", path: "src/a.ts", down: ["luke"], up: [] }, + { fingerprint: "deadbeef", path: "src/b.ts", down: [], up: ["sam"] }, + ], + }); + expect(out.dismissed.size).toBe(0); + expect(out.affirmed.size).toBe(0); + expect(bulkTriageFindings).not.toHaveBeenCalled(); + }); + + // The repair for a real review finding: a fingerprint usually has more than + // two threads, and forgetting a conflict after handling it let a third, + // agreeing thread resurrect a verdict two maintainers had contradicted. + it("keeps a fingerprint conflicted once a third thread agrees with the first", () => { + const out = applyReactionFeedback({ + ...base, + threads: [ + { fingerprint: "deadbeef", path: "src/a.ts", down: ["luke"], up: [] }, + { fingerprint: "deadbeef", path: "src/b.ts", down: [], up: ["sam"] }, + { fingerprint: "deadbeef", path: "src/c.ts", down: ["luke"], up: [] }, + ], + }); + expect(out.dismissed.size).toBe(0); + expect(out.affirmed.size).toBe(0); + expect(bulkTriageFindings).not.toHaveBeenCalled(); + }); + + // A split thread binds the fingerprint just as hard as two opposed threads. + it("lets a split thread conflict the fingerprint for later clean threads", () => { + const out = applyReactionFeedback({ + ...base, + threads: [ + { fingerprint: "deadbeef", path: "src/a.ts", down: ["luke"], up: ["sam"] }, + { fingerprint: "deadbeef", path: "src/b.ts", down: ["luke"], up: [] }, + ], + }); + expect(out.dismissed.size).toBe(0); + expect(bulkTriageFindings).not.toHaveBeenCalled(); + }); + + // Conflict is per fingerprint, not global β€” an unrelated finding still applies. + it("does not let one conflicted fingerprint block another", () => { + const out = applyReactionFeedback({ + ...base, + threads: [ + { fingerprint: "deadbeef", path: "src/a.ts", down: ["luke"], up: ["sam"] }, + { fingerprint: "cafe1234", path: "src/b.ts", down: ["luke"], up: [] }, + ], + }); + expect([...out.dismissed]).toEqual(["cafe1234"]); + expect(bulkTriageFindings).toHaveBeenCalledTimes(1); + }); + + // GraphQL spells our own login `diffsentry`, REST spells it `diffsentry[bot]`. + // Either way it is us, and our own reaction is not feedback. + it("ignores our own reactions in both login spellings", () => { + const out = applyReactionFeedback({ + ...base, + threads: [ + { fingerprint: "deadbeef", path: "src/a.ts", down: ["diffsentry"], up: [] }, + { fingerprint: "cafe1234", path: "src/b.ts", down: ["DiffSentry[bot]"], up: [] }, + ], + }); + expect(out.dismissed.size).toBe(0); + expect(bulkTriageFindings).not.toHaveBeenCalled(); + }); + + it("records no event when no finding row matched the fingerprint", () => { + const out = applyReactionFeedback({ + ...base, + threads: [{ fingerprint: "0000ffff", path: "src/a.ts", down: ["luke"], up: [] }], + }); + expect([...out.dismissed]).toEqual(["0000ffff"]); + expect(bulkTriageFindings).not.toHaveBeenCalled(); + expect(recordEvent).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/review-cache.test.ts b/tests/unit/review-cache.test.ts new file mode 100644 index 00000000..2bde73a5 --- /dev/null +++ b/tests/unit/review-cache.test.ts @@ -0,0 +1,69 @@ +import { describe, it, expect } from "vitest"; +import { createHash } from "node:crypto"; +import { reviewCacheKey, primaryModelId } from "../../src/ai/review-cache.js"; +import { normalizePatchForHash } from "../../src/reviewer.js"; +import type { Config } from "../../src/types.js"; + +function digest(filename: string, patch: string): string { + return createHash("sha256").update(normalizePatchForHash(filename, patch)).digest("hex").slice(0, 16); +} + +const PATCH_AT_LINE_10 = `@@ -10,3 +10,4 @@ function f() { + const a = 1; ++ const b = 2; + return a;`; + +// Byte-for-byte the same change, rebased onto a base where the function moved. +const PATCH_AT_LINE_84 = `@@ -84,3 +84,4 @@ function f() { + const a = 1; ++ const b = 2; + return a;`; + +function keyFor(patch: string, opts: { system?: string; title?: string } = {}): string { + const system = opts.system ?? "SYSTEM PROMPT"; + const user = `Title: ${opts.title ?? "Add b"}\n\n### src/f.ts\n\`\`\`diff\n${patch}\n\`\`\`\n`; + return reviewCacheKey({ + model: "anthropic:claude-x", + system, + user, + patches: [{ text: patch, digest: digest("src/f.ts", patch) }], + }); +} + +describe("review cache key", () => { + // The whole point: a rebase rewrites every hunk header without changing a + // line of code, and that is the most common reason a diff is reviewed twice. + it("survives a rebase that only moves line numbers", () => { + expect(keyFor(PATCH_AT_LINE_10)).toBe(keyFor(PATCH_AT_LINE_84)); + }); + + it("changes when the code changes", () => { + const edited = PATCH_AT_LINE_10.replace("const b = 2;", "const b = 3;"); + expect(keyFor(edited)).not.toBe(keyFor(PATCH_AT_LINE_10)); + }); + + // The system prompt carries the profile and the review instructions, so a + // future edit to either must invalidate every row without this module + // knowing it happened. + it("changes when the system prompt changes", () => { + expect(keyFor(PATCH_AT_LINE_10, { system: "SYSTEM PROMPT v2" })).not.toBe(keyFor(PATCH_AT_LINE_10)); + }); + + // Anything else the user prompt carries β€” title, description, learnings, + // related context β€” is hashed verbatim. + it("changes when the rest of the prompt changes", () => { + expect(keyFor(PATCH_AT_LINE_10, { title: "Add c" })).not.toBe(keyFor(PATCH_AT_LINE_10)); + }); + + it("changes when the model changes", () => { + const args = { system: "s", user: "u", patches: [] }; + expect(reviewCacheKey({ ...args, model: "a:1" })).not.toBe(reviewCacheKey({ ...args, model: "a:2" })); + }); + + it("names the primary provider's model", () => { + const base = { anthropicModel: "claude-x", openaiModel: "gpt-x", localAiModel: "llama-x" } as Config; + expect(primaryModelId({ ...base, aiProvider: "anthropic" })).toBe("anthropic:claude-x"); + expect(primaryModelId({ ...base, aiProvider: "openai" })).toBe("openai:gpt-x"); + expect(primaryModelId({ ...base, aiProvider: "openai-compatible" })).toBe("openai-compatible:llama-x"); + }); +}); diff --git a/web/src/api/hooks.ts b/web/src/api/hooks.ts index af3ff1ad..c9c1fb80 100644 --- a/web/src/api/hooks.ts +++ b/web/src/api/hooks.ts @@ -30,6 +30,7 @@ import type { MeResponse, NotificationsResponse, PatternsResponse, + ScorecardResponse, PRDetailResponse, PRDiffResponse, RecurringResponse, @@ -274,6 +275,14 @@ export function usePatterns() { }); } +export function useScorecard(days: number) { + return useQuery({ + queryKey: ["analytics", "scorecard", days], + queryFn: () => apiGet("/analytics/scorecard", { days }), + placeholderData: (prev) => prev, + }); +} + export function useAuthorAnalytics(days: number) { return useQuery({ queryKey: ["analytics", "authors", days], diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 2735b098..77725bcf 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -359,6 +359,33 @@ export interface PRDiffResponse { findings: PRFindingRow[]; } +// ─── Review quality scorecard ─────────────────────────────────────── + +export interface ScorecardRow { + owner: string; + repo: string; + source: string; + severity: string; + total: number; + accepted: number; + dismissed: number; + snoozed: number; + untriaged: number; +} + +/** Rows, hits and age of the review result cache. */ +export interface ReviewCacheStats { + rows: number; + hits: number; + oldest: string | null; +} + +export interface ScorecardResponse { + days: number; + rows: ScorecardRow[]; + cache: ReviewCacheStats; +} + export interface PatternsResponse { rules: PatternRuleRow[]; } diff --git a/web/src/components/Shell.tsx b/web/src/components/Shell.tsx index 0b2ce14f..6edb868c 100644 --- a/web/src/components/Shell.tsx +++ b/web/src/components/Shell.tsx @@ -24,6 +24,7 @@ import { OpsIcon, OverviewIcon, PatternsIcon, + ShieldIcon, QueueIcon, RecurringIcon, RulesIcon, @@ -59,6 +60,7 @@ const NAV: NavItem[] = [ { to: "/findings", label: "Findings", Icon: FindingsIcon, end: true }, { to: "/findings/recurring", label: "Recurring", Icon: RecurringIcon, end: false }, { to: "/patterns", label: "Patterns", Icon: PatternsIcon, end: false }, + { to: "/scorecard", label: "Scorecard", Icon: ShieldIcon, end: false }, { to: "/cost", label: "Cost", Icon: CostIcon, end: false }, { to: "/rules", label: "Custom rules", Icon: RulesIcon, end: false, cap: "manageConfig" }, { to: "/leaderboard", label: "Leaderboard", Icon: LeaderboardIcon, end: false }, diff --git a/web/src/demo/fixtures.ts b/web/src/demo/fixtures.ts index e444d8d2..5fd0c34c 100644 --- a/web/src/demo/fixtures.ts +++ b/web/src/demo/fixtures.ts @@ -563,6 +563,8 @@ function match(p: string): unknown { return demoCost(); case "/analytics/authors": return { days: 30, authors: [], series: [] }; + case "/analytics/scorecard": + return demoScorecard(); case "/analytics/trends": return { days: 30, activity: OVERVIEW_ACTIVITY, riskDistribution: [], hotPaths: REPO_DETAIL.hotPaths, hotPathSeries: [] }; // Admin-only endpoints the viewer UI never links to β€” empty but valid. @@ -590,6 +592,21 @@ function match(p: string): unknown { return {}; } +// Enough judged findings for the rate column to render β€” an all-zero scorecard +// would show the page working while teaching the reader nothing. +function demoScorecard() { + return { + days: 90, + rows: [ + { owner: OWNER, repo: HERO_REPO, source: "ai", severity: "major", total: 48, accepted: 31, dismissed: 6, snoozed: 2, untriaged: 9 }, + { owner: OWNER, repo: HERO_REPO, source: "ai", severity: "minor", total: 73, accepted: 18, dismissed: 21, snoozed: 0, untriaged: 34 }, + { owner: OWNER, repo: HERO_REPO, source: "safety", severity: "critical", total: 7, accepted: 7, dismissed: 0, snoozed: 0, untriaged: 0 }, + { owner: OWNER, repo: HERO_REPO, source: "builtin", severity: "minor", total: 26, accepted: 4, dismissed: 14, snoozed: 1, untriaged: 7 }, + ], + cache: { rows: 34, hits: 11, oldest: iso(days(12)) }, + }; +} + function demoCost() { return { range: "30d", diff --git a/web/src/pages/Scorecard.tsx b/web/src/pages/Scorecard.tsx new file mode 100644 index 00000000..60ffb83c --- /dev/null +++ b/web/src/pages/Scorecard.tsx @@ -0,0 +1,116 @@ +import { Link } from "react-router"; +import { useScorecard } from "../api/hooks"; +import type { ScorecardRow } from "../api/types"; +import { Breadcrumbs } from "../components/Shell"; +import { Card, Metric, PageHeader } from "../components/primitives"; +import { EmptyState, QueryBoundary } from "../components/states"; +import { relativeTime } from "../lib/format"; + +const DAYS = 90; + +/** + * A rate off three samples reads as authority and isn't one, so it isn't shown + * until there are enough judgements to mean something. + */ +const MIN_JUDGED_FOR_RATE = 5; + +function confirmedRate(r: ScorecardRow): string { + const judged = r.accepted + r.dismissed; + if (judged < MIN_JUDGED_FOR_RATE) return "β€”"; + return `${Math.round((r.accepted / judged) * 100)}%`; +} + +export function ScorecardPage() { + const query = useScorecard(DAYS); + return ( + <> + + + + {(data) => { + const rows = data.rows; + const sum = (pick: (r: ScorecardRow) => number) => rows.reduce((n, r) => n + pick(r), 0); + const total = sum((r) => r.total); + const accepted = sum((r) => r.accepted); + const dismissed = sum((r) => r.dismissed); + const judged = accepted + dismissed; + return ( + <> +
+ + + = MIN_JUDGED_FOR_RATE ? `${Math.round((accepted / judged) * 100)}%` : "β€”"} + /> + +
+ + + {rows.length === 0 ? ( + + ) : ( + + + + + + + + + + + + + + + + {rows.map((r, i) => ( + + + + + + + + + + + + ))} + +
RepoSourceSeverityRaisedConfirmedDismissedSnoozedUnjudgedConfirmed rate
+ + {r.owner}/{r.repo} + + {r.source}{r.severity}{r.total} 0 ? "strong" : "zero"}`} data-label="Confirmed">{r.accepted} 0 ? "strong" : "zero"}`} data-label="Dismissed">{r.dismissed} 0 ? "" : "zero"}`} data-label="Snoozed">{r.snoozed}{r.untriaged}{confirmedRate(r)}
+ )} +
+ + +
+ + + +
+
+ + ); + }} +
+ + ); +} diff --git a/web/src/router.tsx b/web/src/router.tsx index b3f72359..e32abca3 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -15,6 +15,7 @@ import { FeedPage } from "./pages/Feed"; import { TriageModePage } from "./pages/TriageMode"; import { RecurringPage } from "./pages/Recurring"; import { PatternsPage } from "./pages/Patterns"; +import { ScorecardPage } from "./pages/Scorecard"; import { CostPage } from "./pages/Cost"; import { RulesPage } from "./pages/Rules"; import { LeaderboardPage } from "./pages/Leaderboard"; @@ -88,6 +89,7 @@ export const router = createBrowserRouter( { path: "/findings/triage", element: }, { path: "/findings/recurring", element: }, { path: "/patterns", element: }, + { path: "/scorecard", element: }, { path: "/cost", element: }, { path: "/rules", element: }, { path: "/leaderboard", element: },