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
58 changes: 58 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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. |

Expand Down
1 change: 1 addition & 0 deletions docs/MIGRATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion scripts/preview-learnings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@

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")));
Comment thread
mk7luke marked this conversation as resolved.
Resolved

const server = app.listen(0);
const port = (server.address() as { port: number }).port;
Expand Down
2 changes: 1 addition & 1 deletion scripts/preview-spa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@
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());
});

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
a file system access
, but is not rate-limited.

const port = Number.parseInt(process.env.PORT ?? "8092", 10);
app.listen(port, () => console.log(`\n SPA preview (open/admin): http://localhost:${port}/ (db: ${tmpDb})\n`));
Expand Down
2 changes: 1 addition & 1 deletion scripts/preview-webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,10 @@
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());
});

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
a file system access
, but is not rate-limited.

const port = Number.parseInt(process.env.PORT ?? "8092", 10);
app.listen(port, () => {
Expand Down
2 changes: 1 addition & 1 deletion scripts/screenshot-actionbar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,10 @@
);
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());
});

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
a file system access
, but is not rate-limited.

const server = app.listen(0);
const port = (server.address() as { port: number }).port;
Expand Down
2 changes: 1 addition & 1 deletion scripts/serve-seeded.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@
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());
});

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
a file system access
, but is not rate-limited.
app.listen(port, () => console.log(`seeded SPA on http://127.0.0.1:${port}`));
}

Expand Down
132 changes: 132 additions & 0 deletions src/ai/review-cache.ts
Original file line number Diff line number Diff line change
@@ -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<string>();
for (const { text, digest } of opts.patches) {
if (!text || seen.has(text)) continue;
seen.add(text);
user = user.split(text).join(`<patch:${digest}>`);
}
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(),
});
}
17 changes: 17 additions & 0 deletions src/api/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
bulkTriageFindings,
getFindingCoords,
getFindingIdsByFingerprint,
reviewCacheStats,
type FindingCoords,
} from "../storage/dao.js";
import {
Expand Down Expand Up @@ -72,6 +73,7 @@ import {
getRecentIssues,
getRecentPRsWithReviews,
getRepoOverview,
getReviewScorecard,
getRiskDistribution,
getRoleOverrides,
getSparkline,
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading