diff --git a/dashboard/e2e/prs-overview-data.ts b/dashboard/e2e/prs-overview-data.ts new file mode 100644 index 00000000..f07ec887 --- /dev/null +++ b/dashboard/e2e/prs-overview-data.ts @@ -0,0 +1,626 @@ +// Invented answers for the Pull requests overview: the bookstore's org (acme) +// and its repos, every pull request's author a person (octocat, mara, theo, +// jun), CoderHelm or another bot. Five weeks from the summary research +// (normal, bad, quiet, CoderHelm waiting on people, unstable), plus a +// people-only org, a young install, a backfill in progress and one repo. + +import type { OverviewDot, OverviewRepo, OverviewSummary, PrStage, PrsOverview, SummaryPart } from "../src/lib/api"; + +const H = 3600; +const D = 86_400; +const NOW = Date.now(); +const iso = (secsAgo: number) => new Date(NOW - secsAgo * 1000).toISOString(); + +export type Scenario = "normal" | "bad" | "quiet" | "coderhelm_waiting" | "unstable" | "people_only" | "young" | "backfilling" | "empty"; + +/** A small seeded generator, so every run draws the same dots. */ +function rng(seed: number) { + let s = seed >>> 0; + return () => { + s = (Math.imul(s, 1664525) + 1013904223) >>> 0; + return s / 2 ** 32; + }; +} + +const REPOS = [ + "acme/checkout", + "acme/web", + "acme/inventory-api", + "acme/mobile", + "acme/search", + "acme/catalog", + "acme/payments", + "acme/reviews", + "acme/shipping", + "acme/admin", + "acme/emails", + "acme/infra", + "acme/recommendations", + "acme/docs-site", +]; + +const TITLES = [ + "Round cart totals per currency", + "Show stock per warehouse on the book page", + "Cache the bestseller list for an hour", + "Retry gift card redemption once", + "Add the paperback filter to search", + "Bump the image resizer to 4.2", + "Split the order email into two templates", + "Fix the wishlist count after sign out", + "Store the shipping estimate on the order", + "Paginate the author page", + "Move the returns form to the new layout", + "Log slow catalog queries", +]; + +const STATE_OF: Record = { + draft: [["draft", "Draft"]], + first_review: [ + ["needs_review", "Needs review"], + ["needs_reviewer", "Needs a reviewer"], + ], + in_review: [ + ["changes_requested", "Changes requested"], + ["re_review", "Re-review needed"], + ["needs_code_owner", "Needs a code owner"], + ["open_threads", "Open threads"], + ], + blocked: [ + ["checks_failing", "Checks failing"], + ["conflicts", "Conflicts"], + ["needs_decision", "Needs a decision"], + ], + coderhelm_working: [["coderhelm_working", "CoderHelm working"]], + approved: [ + ["checks_running", "Checks running"], + ["ready_to_merge", "Ready to merge"], + ["ready_auto_merge", "Ready, auto-merge on"], + ], +}; + +const CYCLE = { p50: 19 * H, p85: Math.round(3.1 * D), p95: Math.round(6.2 * D) }; + +interface Shape { + stages: Record; + /** Share of each stage that is past p85. */ + old: Partial>; + coderhelmShare: number; + botShare: number; + /** Where the old ones gather. */ + hot?: string; + /** Share of old ones whose turn-holder is idle; ones blocked by a red main in `hot`. */ + idle?: number; + mainBlocked?: number; +} + +function dots(shape: Shape, seed: number): OverviewDot[] { + const r = rng(seed); + const out: OverviewDot[] = []; + let n = 100; + for (const stage of Object.keys(shape.stages) as PrStage[]) { + const count = shape.stages[stage]; + for (let i = 0; i < count; i++) { + const isOld = r() < (shape.old[stage] ?? 0); + const age = isOld ? CYCLE.p85 + r() * 9 * D : 20 * 60 + r() * r() * CYCLE.p85; + const who = stage === "coderhelm_working" || r() < shape.coderhelmShare ? "coderhelm" : r() < shape.botShare ? "bot" : "person"; + const repo = isOld && shape.hot && r() < 0.65 ? shape.hot : REPOS[Math.floor(r() * 9)]; + const [state, state_label] = STATE_OF[stage][Math.floor(r() * STATE_OF[stage].length)]; + const number = 300 + n++; + out.push({ + key: `${repo}#${number}`, + repo, + number, + title: who === "bot" ? "Bump the image resizer to 4.2" : TITLES[Math.floor(r() * TITLES.length)], + stage, + state, + state_label, + age_secs: Math.round(age), + coderhelm: who === "coderhelm", + author_type: who as "person" | "coderhelm" | "bot", + band: age > CYCLE.p95 ? "p95" : age > CYCLE.p85 ? "p85" : age > CYCLE.p50 ? "p50" : null, + idle: age > CYCLE.p50 && stage !== "draft" && r() < (shape.idle ?? 0.5), + main_blocked: stage === "blocked" && repo === shape.hot && r() < (shape.mainBlocked ?? 0), + }); + } + } + return out; +} + +type Health = "healthy" | "at_risk" | "slipping" | "quiet"; + +interface RepoExtra { + health?: Health; + flags?: string[]; + main_red_secs?: number; + reverts?: number; + security?: { count: number; worst: "critical" | "high" | "medium" | "low" }; + bypasses?: number; + human?: number; + flows?: [number, number]; +} + +function repoRows(ds: OverviewDot[], extra: Record, seed: number, quiet: string[] = ["acme/docs-site"]): OverviewRepo[] { + const r = rng(seed); + const rows: OverviewRepo[] = REPOS.map((repo) => { + const x = extra[repo] ?? {}; + const mine = ds.filter((d) => d.repo === repo); + const stages: Partial> = {}; + for (const d of mine) stages[d.stage as PrStage] = (stages[d.stage as PrStage] ?? 0) + 1; + const past = mine.filter((d) => d.band === "p85" || d.band === "p95").length; + const [arrivals, merges] = x.flows ?? [Math.round(mine.length * 0.6 + r() * 3), Math.round(mine.length * 0.6 + r() * 3)]; + const isQuiet = quiet.includes(repo) || (mine.length === 0 && arrivals === 0 && merges === 0); + const inflow = arrivals > merges; + const health: Health = isQuiet ? "quiet" : x.health ?? (past > 3 && inflow ? "at_risk" : "healthy"); + const short = repo.split("/")[1]; + const fewMerges = merges < 10; + return { + repo, + open: mine.length, + stages, + past_p85: past, + past_p85_delta: past > 0 ? Math.round(r() * 4) - 1 : 0, + first_review: mine.length ? { p50: Math.round((5 + r() * 18) * H), p85: Math.round((1 + r() * 3) * D) } : null, + arrivals: isQuiet ? 0 : arrivals, + merges: isQuiet ? 0 : merges, + spark: Array.from({ length: 8 }, (_, i) => Math.max(0, Math.round(mine.length * (0.6 + 0.05 * i) + r() * 3 - 1))), + oldest_secs: mine.length ? Math.max(...mine.map((d) => d.age_secs)) : null, + reworked: isQuiet ? 0 : x.reverts ?? 0, + stale: mine.filter((d) => d.idle).length, + abandoned: mine.filter((d) => d.idle && d.age_secs > 14 * D).length, + human_reviewed: isQuiet || fewMerges ? null : x.human ?? 0.9 + r() * 0.1, + human_reviewed_delta: isQuiet || fewMerges ? null : Math.round((r() * 6 - 3)) / 100, + ci_first_try: isQuiet || mine.length + merges < 10 ? null : 0.64 + r() * 0.25, + main_red_secs: isQuiet ? 0 : x.main_red_secs ?? 0, + reverts: isQuiet ? 0 : x.reverts ?? 0, + large_share: isQuiet || fewMerges ? null : 0.05 + r() * 0.2, + security_past_sla: x.security ?? null, + bypasses_unreviewed: x.bypasses ?? 0, + flags: x.flags ?? [], + health, + why: isQuiet + ? `No pull request activity in ${short} this week.` + : x.flags?.length + ? x.flags.join("; ") + : `Past-p85 count ${past}, inside its 8-week range; arrivals ${arrivals}, merges ${merges}.`, + inherited: r() < 0.4, + link: { overview: `repo=${repo}` }, + }; + }); + const rank = (h: string) => ({ slipping: 3, at_risk: 2, healthy: 1, quiet: 0 })[h as Health] ?? 0; + return rows.sort((a, b) => rank(b.health) - rank(a.health) || b.past_p85 - a.past_p85 || (b.oldest_secs ?? 0) - (a.oldest_secs ?? 0)); +} + +const n = (v: number, fact: string, link: PrsOverview["needs_decision"]["link"], unit: "count" | "secs" | "share" = "count"): SummaryPart => ({ n: v, unit, fact, link }); +const t = (s: string): SummaryPart => ({ t: s }); +/** "(usual 31 to 40)": the range's ends are facts too. */ +const usual = (lo: number, hi: number, after: string): SummaryPart[] => [t(" (usual "), n(lo, "merges_8w_low", merged("merged:>=2026-01-04")), t(" to "), n(hi, "merges_8w_high", merged("merged:>=2026-01-04")), t(after)]; +const merged = (q: string) => ({ github: `https://github.com/pulls?q=${encodeURIComponent(`is:pr org:acme is:merged ${q}`)}` }); + +const METHOD = + "Facts are computed from CoderHelm's records of every pull request in the installed repos, people's, CoderHelm's and other bots'. Each is ranked by its effect on the org total; a change is mentioned only when it is at least 2 and 10% of the week before, a wait only past 24 hours, and no rate on fewer than 10 events. Each line is a fixed template over one fact; no number is written that isn't in the facts."; + +const RULE = + "Slipping: any obligation breached (a critical security fix past its SLA, an unreviewed bypass, a high-severity finding merged) or main red now. At risk: a headline number outside its 8-week range in the bad direction. Quiet: merges under a quarter of the 8-week median and nothing past usual. Healthy otherwise. The org takes the worst state of any repo holding 10% or more of open PRs, plus any obligation breach anywhere."; + +interface Tiles { + stale: [number, number | null]; + redSecs: number | null; + reverts: number; + reviewed: [number | null, number | null]; +} + +function tiles(x: Tiles): OverviewSummary["tiles"] { + return [ + { fact: "stale", label: "Stale: idle past the stage p85", value: x.stale[0], unit: "count", delta: x.stale[1], link: { list: "view=stale" } }, + { + fact: "failures", + label: "Failures: main red this week", + value: x.redSecs, + unit: "secs", + delta: null, + second: { value: x.reverts, unit: "count", label: x.reverts === 1 ? "revert" : "reverts", link: merged("revert in:title merged:>=2026-01-04") }, + link: { list: "state=checks_failing" }, + }, + { fact: "reviewed", label: "Reviewed: human-approved merges", value: x.reviewed[0], unit: "share", delta: x.reviewed[1], link: merged("review:approved merged:>=2026-01-04") }, + ]; +} + +const CH = { list: "turn=coderhelm" }; +const chMerged = merged("author:app/coderhelm merged:>=2026-01-04"); + +function summary(kind: Scenario): OverviewSummary { + const window = { from: iso(7 * D), to: iso(0) }; + const computed_at = iso(40); + const base = { window, computed_at, method: METHOD, more: null, quiet: null }; + switch (kind) { + case "bad": + return { + ...base, + verdict: { + state: "slipping", + word: "Slipping", + rule: RULE, + parts: [n(2, "security_past_sla", { list: "repo=acme/payments" }), t(" critical security fixes in payments are past their SLA, and inventory-api main has been red on payments_test since Wednesday. Merges fell to "), n(14, "merges", merged("merged:>=2026-01-04")), ...usual(31, 40, ".")], + }, + tiles: tiles({ stale: [17, 6], redSecs: 2 * D + 3 * H, reverts: 1, reviewed: [0.85, -0.1] }), + attention: [ + { rank: 1, fact: "security_past_sla", owner: "payments-team", owner_kind: "team", age_secs: 11 * D, link: { list: "repo=acme/payments" }, parts: [n(2, "security_past_sla", { list: "repo=acme/payments" }), t(" critical security fixes past SLA: payments#311, #318")] }, + { rank: 2, fact: "main_red", owner: "inventory CODEOWNERS", owner_kind: "codeowners", age_secs: 2 * D, link: { list: "repo=acme/inventory-api&state=checks_failing" }, parts: [t("inventory-api main red on payments_test; "), n(9, "blocked_by_main", { list: "repo=acme/inventory-api&state=checks_failing" }), t(" PRs fail behind it")] }, + { rank: 3, fact: "bypass", owner: "infra-owners", owner_kind: "team", age_secs: D, link: { list: "pr=acme/infra#212" }, parts: [t("infra#212 merged through an admin bypass, no review after")] }, + { rank: 4, fact: "no_review", owner: null, owner_note: "no reviewer was requested", age_secs: null, link: merged("repo:acme/web review:none merged:>=2026-01-04"), parts: [n(3, "merged_without_review", merged("repo:acme/web review:none merged:>=2026-01-04")), t(" merges in web with no review event")] }, + { rank: 5, fact: "stale", owner: "checkout CODEOWNERS", owner_kind: "codeowners", age_secs: 4 * D, link: { list: "repo=acme/checkout&past=p85" }, parts: [n(7, "past_p85_repo", { list: "repo=acme/checkout&past=p85" }), t(" checkout PRs past usual with no first review")] }, + ], + changed: { fact: "check_red", parts: [t("payments_test started failing Wednesday on inventory-api main; the drop in merges follows from it.")] }, + stability: { fact: "rework", parts: [n(1, "reverts", merged("revert in:title merged:>=2026-01-04")), t(" revert this week, in web; merged PRs later reverted or hotfixed: "), n(0.031, "proxy", merged("merged:>=2026-01-04"), "share"), t(" over 30 days.")] }, + coderhelm: { fact: "coderhelm_runs", link: CH, parts: [n(4, "coderhelm_blocked", { list: "turn=coderhelm&stage=blocked" }), t(" of its PRs are blocked on the red main; it has not rerun them, since the failure isn't in their code. Opened "), n(6, "coderhelm_opened", CH), t(", merged "), n(2, "coderhelm_merged", chMerged), t(".")] }, + }; + case "quiet": + return { + ...base, + verdict: { state: "quiet", word: "Quiet", rule: RULE, parts: [n(6, "merges", merged("merged:>=2026-01-04")), t(" PRs merged (usual about "), n(30, "merges_8w_median", merged("merged:>=2026-01-04")), t("), with nothing past usual and nothing failing.")] }, + tiles: tiles({ stale: [0, -2], redSecs: 0, reverts: 0, reviewed: [null, null] }), + attention: [], + quiet: { + repos: 14, + open: 9, + parts: [t("Nothing needs you. Checked "), n(14, "repos", { overview: "" }), t(" repos and "), n(9, "open", { list: "" }), t(" open PRs: none stale, main green all week, no reverts, every merge human-reviewed, no security fix past SLA, no bypasses.")], + }, + changed: { fact: "arrivals", parts: [t("Activity was low all week; no repo got worse.")] }, + stability: { fact: "rework", parts: [t("No reverts or hotfix suspects in 14 days; main stayed green in every repo.")] }, + coderhelm: { fact: "coderhelm_author", link: CH, parts: [n(1, "coderhelm_merged", chMerged), t(" PR merged, a dependency bump. No runs gave up or were stopped.")] }, + }; + case "coderhelm_waiting": + return { + ...base, + verdict: { + state: "at_risk", + word: "At risk", + rule: RULE, + parts: [t("Work is done but not landing: "), n(7, "coderhelm_waiting", { list: "turn=person&q=coderhelm" }), t(" CoderHelm PRs are green and passed its review, waiting on a person for a median of "), n(Math.round(3.5 * D), "coderhelm_waiting_p50", { list: "turn=person&q=coderhelm" }, "secs"), t(". "), n(29, "merges", merged("merged:>=2026-01-04")), t(" merged"), ...usual(31, 40, ".")], + }, + tiles: tiles({ stale: [13, 5], redSecs: 0, reverts: 0, reviewed: [0.96, 0.01] }), + attention: [ + { rank: 1, fact: "coderhelm_waiting", owner: "mara", owner_kind: "person", age_secs: 4 * D, link: { list: "pr=acme/inventory-api#390" }, parts: [t("inventory-api#390: review requested 4 days ago, no response")] }, + { rank: 2, fact: "coderhelm_waiting", owner: "mara", owner_kind: "person", age_secs: 4 * D, link: { list: "pr=acme/inventory-api#394" }, parts: [t("inventory-api#394: review requested 4 days ago, no response")] }, + { rank: 3, fact: "re_review", owner: "theo", owner_kind: "person", age_secs: 2 * D, link: { list: "pr=acme/web#441" }, parts: [t("web#441: CoderHelm pushed the requested change; not re-reviewed yet")] }, + { rank: 4, fact: "needs_decision", owner: "octocat", owner_kind: "person", age_secs: 5 * D, link: { list: "pr=acme/checkout#80" }, parts: [t("checkout#80: CoderHelm needs a decision on the migration order")] }, + ], + more: { count: 3, link: { list: "turn=person&q=coderhelm" } }, + changed: { fact: "coderhelm_opened", parts: [t("CoderHelm opened "), n(12, "coderhelm_opened", CH), t(" PRs (from 5); reviews done stayed at "), n(24, "reviews_done", { list: "stage=first_review" }), t(".")] }, + stability: { fact: "rework", parts: [t("No reverts in 14 days; "), n(1, "follow_ups", merged("merged:>=2026-01-04")), t(" hotfix suspect, on a person's PR.")] }, + coderhelm: { fact: "coderhelm_waiting", link: CH, parts: [t("Blocked on people: not starting new work in inventory-api until #390 lands. Opened "), n(12, "coderhelm_opened", CH), t(", merged "), n(5, "coderhelm_merged", chMerged), t("; runs: 10 first-try green, 2 green after fixes.")] }, + }; + case "unstable": + return { + ...base, + verdict: { + state: "at_risk", + word: "At risk", + rule: RULE, + parts: [t("Checks are flaky: "), n(3, "flaky_new", { list: "state=checks_failing" }), t(" new flaky checks, web main red twice, and "), n(2, "reverts", merged("revert in:title merged:>=2026-01-04")), t(" merges reverted. "), n(27, "merges", merged("merged:>=2026-01-04")), t(" merged"), ...usual(31, 40, ".")], + }, + tiles: tiles({ stale: [9, 1], redSecs: Math.round(4.5 * H), reverts: 2, reviewed: [0.93, -0.02] }), + attention: [ + { rank: 1, fact: "flaky", owner: "web-platform", owner_kind: "team", age_secs: 3 * D, link: { list: "repo=acme/web&state=checks_failing" }, parts: [t("e2e/checkout.spec failed then passed on the same commit "), n(12, "flaky_retries", { list: "repo=acme/web&state=checks_failing" }), t(" times in web")] }, + { rank: 2, fact: "main_red", owner: "web CODEOWNERS", owner_kind: "codeowners", age_secs: 2 * D, link: { list: "pr=acme/web#447" }, parts: [t("web main red Tuesday 10:02 to 13:40 and Thursday 16:15 to 17:05; green after web#447")] }, + { rank: 3, fact: "reverts", owner: "theo", owner_kind: "person", age_secs: 2 * D, link: { list: "pr=acme/web#447" }, parts: [t("web#447 reverted web#439 two days after it merged")] }, + ], + changed: { fact: "flaky_new", parts: [t("Red checks began Monday, after acme/infra#212 changed the CI image (suspect: merged 2h before, same runner).")] }, + stability: { fact: "rework", parts: [n(2, "reverts", merged("revert in:title merged:>=2026-01-04")), t(" reverts and "), n(1, "follow_ups", merged("merged:>=2026-01-04")), t(" hotfix suspect in 14 days (8-week range 0 to 1).")] }, + coderhelm: { fact: "coderhelm_runs", link: CH, parts: [n(6, "coderhelm_rerun_only", CH), t(" of its "), n(15, "coderhelm_runs", CH), t(" runs went green only on a rerun: flaky, not fixed, and labeled so. Opened "), n(9, "coderhelm_opened", CH), t(", merged "), n(7, "coderhelm_merged", chMerged), t(".")] }, + }; + case "people_only": + return { + ...base, + verdict: { state: "at_risk", word: "At risk", rule: RULE, parts: [n(11, "past_p85", { list: "past=p85" }), t(" open PRs are past usual (up 4), 7 of them in checkout with no first review. "), n(40, "merges", merged("merged:>=2026-01-04")), t(" merged"), ...usual(31, 40, ".")] }, + tiles: tiles({ stale: [11, 4], redSecs: 0, reverts: 1, reviewed: [0.94, 0] }), + attention: [ + { rank: 1, fact: "stale", owner: "checkout CODEOWNERS", owner_kind: "codeowners", age_secs: 4 * D, link: { list: "repo=acme/checkout&past=p85" }, parts: [n(7, "past_p85_repo", { list: "repo=acme/checkout&past=p85" }), t(" checkout PRs past usual with no first review")] }, + { rank: 2, fact: "oldest", owner: "mara", owner_kind: "person", age_secs: 12 * D, link: { list: "pr=acme/checkout#301" }, parts: [t("checkout#301 waits on a review")] }, + { rank: 3, fact: "dependency", owner: null, owner_note: "a bot's PR with no reviewer", age_secs: 9 * D, link: { list: "pr=acme/web#355" }, parts: [t("web#355, a Dependabot bump, has had no review in 9 days")] }, + ], + changed: null, + stability: { fact: "rework", parts: [n(1, "reverts", merged("revert in:title merged:>=2026-01-04")), t(" revert in 14 days, in web; main stayed green.")] }, + coderhelm: { fact: "coderhelm_author", link: CH, parts: [t("No PRs from CoderHelm in this window: opened "), n(0, "coderhelm_opened", CH), t(", reviewed "), n(0, "coderhelm_reviewed", CH), t(". Every number above is people's and other bots' work.")] }, + }; + case "young": + case "backfilling": + return { + ...base, + verdict: { state: "at_risk", word: "At risk", rule: RULE, parts: [n(9, "past_p85", { list: "past=p85" }), t(" of "), n(41, "open", { list: "" }), t(" open PRs have waited longer than 85% of the merged PRs read so far took. Week-over-week changes need more history.")] }, + tiles: tiles({ stale: [9, null], redSecs: null, reverts: 0, reviewed: [null, null] }), + attention: [{ rank: 1, fact: "oldest", owner: "theo", owner_kind: "person", age_secs: 9 * D, link: { list: "pr=acme/web#318" }, parts: [t("web#318 waits on a review")] }], + changed: null, + stability: { fact: "rework", parts: [n(0, "reverts", merged("revert in:title merged:>=2026-01-04")), t(" reverts seen so far; the usual range needs 8 weeks of history.")] }, + coderhelm: { fact: "coderhelm_author", link: CH, parts: [t("Opened "), n(3, "coderhelm_opened", CH), t(", merged "), n(2, "coderhelm_merged", chMerged), t("; no runs gave up.")] }, + }; + case "empty": + return { + ...base, + verdict: { state: "quiet", word: "Quiet", rule: RULE, parts: [t("No pull requests yet.")] }, + tiles: [], + attention: [], + quiet: { repos: 0, open: 0, parts: [t("Nothing to check yet.")] }, + changed: null, + stability: { fact: "rework", parts: [t("No merges yet.")] }, + coderhelm: { fact: "coderhelm_author", link: CH, parts: [t("No PRs from CoderHelm yet.")] }, + }; + default: + return { + ...base, + verdict: { + state: "healthy", + word: "Healthy", + rule: RULE, + parts: [n(38, "merges", merged("merged:>=2026-01-04")), t(" PRs merged"), ...usual(31, 40, ", median time to merge "), n(9 * H, "cycle_p50", merged("merged:>=2026-01-04"), "secs"), t(" (was "), n(11 * H, "cycle_p50_before", merged("merged:>=2026-01-04"), "secs"), t("); nothing is past a deadline and main stayed green.")], + }, + tiles: tiles({ stale: [4, -2], redSecs: 0, reverts: 0, reviewed: [0.97, 0.01] }), + attention: [ + { rank: 1, fact: "ready_waiting", owner: "theo", owner_kind: "person", age_secs: 26 * H, link: { list: "pr=acme/web#412" }, parts: [t("web#412 is approved and green, waiting on a merge")] }, + { rank: 2, fact: "ready_waiting", owner: "jun", owner_kind: "person", age_secs: 25 * H, link: { list: "pr=acme/inventory-api#388" }, parts: [t("inventory-api#388 is approved and green, waiting on a merge")] }, + { rank: 3, fact: "first_review_wait", owner: null, owner_note: "no reviewer assigned", age_secs: 2 * D, link: { list: "pr=acme/checkout#77" }, parts: [t("checkout#77 has waited 2 days for a first review")] }, + ], + changed: { fact: "new_repo", parts: [t("mobile came online Tuesday: "), n(4, "arrivals_repo", { list: "repo=acme/mobile" }), t(" PRs there, all merged.")] }, + stability: { fact: "rework", parts: [n(0, "reverts", merged("revert in:title merged:>=2026-01-04")), t(" reverts and "), n(1, "follow_ups", merged("merged:>=2026-01-04")), t(" hotfix suspect in 14 days; main stayed green.")] }, + coderhelm: { fact: "coderhelm_runs", link: CH, parts: [t("Opened "), n(11, "coderhelm_opened", CH), t(", merged "), n(9, "coderhelm_merged", chMerged), t("; runs: 9 first-try green, 2 green after fixes, none gave up.")] }, + }; + } +} + +const SHAPES: Record = { + normal: { stages: { draft: 8, first_review: 14, in_review: 12, blocked: 4, coderhelm_working: 3, approved: 9 }, old: { first_review: 0.15, in_review: 0.1, blocked: 0.25 }, coderhelmShare: 0.15, botShare: 0.1, idle: 0.3 }, + bad: { stages: { draft: 7, first_review: 21, in_review: 14, blocked: 13, coderhelm_working: 2, approved: 4 }, old: { first_review: 0.4, in_review: 0.2, blocked: 0.6 }, coderhelmShare: 0.15, botShare: 0.08, hot: "acme/inventory-api", idle: 0.6, mainBlocked: 0.9 }, + quiet: { stages: { draft: 1, first_review: 1, in_review: 1, blocked: 0, coderhelm_working: 0, approved: 1 }, old: {}, coderhelmShare: 0.1, botShare: 0.2, idle: 0 }, + coderhelm_waiting: { stages: { draft: 6, first_review: 16, in_review: 10, blocked: 4, coderhelm_working: 2, approved: 7 }, old: { first_review: 0.35, in_review: 0.2 }, coderhelmShare: 0.35, botShare: 0.05, hot: "acme/inventory-api", idle: 0.6 }, + unstable: { stages: { draft: 5, first_review: 10, in_review: 9, blocked: 17, coderhelm_working: 3, approved: 6 }, old: { blocked: 0.35, first_review: 0.1 }, coderhelmShare: 0.2, botShare: 0.08, hot: "acme/web", idle: 0.3, mainBlocked: 0.5 }, + people_only: { stages: { draft: 8, first_review: 21, in_review: 14, blocked: 7, coderhelm_working: 0, approved: 8 }, old: { first_review: 0.35, in_review: 0.15, blocked: 0.2 }, coderhelmShare: 0, botShare: 0.12, hot: "acme/checkout", idle: 0.5 }, + young: { stages: { draft: 4, first_review: 14, in_review: 9, blocked: 6, coderhelm_working: 2, approved: 6 }, old: { first_review: 0.3, blocked: 0.3 }, coderhelmShare: 0.1, botShare: 0.1 }, + backfilling: { stages: { draft: 4, first_review: 14, in_review: 9, blocked: 6, coderhelm_working: 2, approved: 6 }, old: { first_review: 0.3, blocked: 0.3 }, coderhelmShare: 0.1, botShare: 0.1 }, + empty: { stages: { draft: 0, first_review: 0, in_review: 0, blocked: 0, coderhelm_working: 0, approved: 0 }, old: {}, coderhelmShare: 0, botShare: 0 }, +}; + +const EXTRA: Partial>> = { + bad: { + "acme/payments": { health: "slipping", security: { count: 2, worst: "critical" }, flags: ["2 critical past SLA"] }, + "acme/inventory-api": { health: "slipping", main_red_secs: 2 * D + 3 * H, flows: [31, 19], flags: ["main red 51h", "9 blocked by main"] }, + "acme/infra": { health: "slipping", bypasses: 1, flags: ["1 bypass, no review after"] }, + "acme/web": { health: "at_risk", reverts: 1, human: 0.71, flags: ["3 no-review merges"] }, + "acme/checkout": { health: "at_risk", flows: [12, 6], flags: ["7 past usual"] }, + }, + coderhelm_waiting: { "acme/inventory-api": { health: "at_risk", flows: [14, 4], flags: ["queue gap +10"] } }, + unstable: { + "acme/web": { health: "at_risk", main_red_secs: Math.round(4.5 * H), reverts: 2, flags: ["main red 4h 30m", "new flaky check"] }, + "acme/search": { health: "at_risk", flags: ["CI first try 58%"] }, + }, + people_only: { "acme/checkout": { health: "at_risk", flows: [12, 6], flags: ["7 past usual"] } }, +}; + +const LABELS: Record = { + draft: "Draft", + first_review: "Waiting for first review", + in_review: "In review", + blocked: "Blocked", + coderhelm_working: "CoderHelm working", + approved: "Approved, not merged", +}; + +/** A whole overview answer for a scenario; `repo` scopes it to one repo. */ +export function overview(kind: Scenario = "normal", repo?: string): PrsOverview { + const shape = SHAPES[kind]; + let all = dots(shape, kind.length * 7919 + 17); + const isEmpty = (kind as string) === "empty"; + const young = kind === "young" || kind === "backfilling" || isEmpty; + const chZero = kind === "people_only"; + const repos = isEmpty + ? REPOS.map((r) => ({ ...repoRows([], {}, 1)[0], repo: r, open: 0, stages: {}, past_p85: 0, arrivals: 0, merges: 0, spark: null, oldest_secs: null, health: "quiet", why: "No pull request activity.", link: { overview: `repo=${r}` } })) + : repoRows(all, EXTRA[kind] ?? {}, 99); + if (repo) all = all.filter((d) => d.repo === repo); + const stagesCount = (s: PrStage) => all.filter((d) => d.stage === s).length; + const strip = (Object.keys(LABELS) as PrStage[]).map((stage, i) => ({ + stage, + label: LABELS[stage], + count: stagesCount(stage), + delta: young ? null : [2, 6, -2, kind === "bad" ? 9 : 1, 0, -1][i], + spark: young ? null : Array.from({ length: 8 }, (_, w) => Math.max(0, stagesCount(stage) - 3 + ((w * 7 + i * 3) % 5))), + past_p85: all.filter((d) => d.stage === stage && (d.band === "p85" || d.band === "p95")).length, + link: { list: `stage=${stage}` }, + })); + const open = all.filter((d) => d.stage !== "draft").length; + const decisions = all.filter((d) => d.state === "needs_decision"); + const idle = all.filter((d) => d.idle); + const scoped = repo ? repos.filter((r) => r.repo === repo) : repos; + const bad = kind === "bad"; + const unstable = kind === "unstable"; + const missing: PrsOverview["missing"] = [ + { path: "review.concentration.where", reason: "not_recorded", text: "Not recorded yet: CoderHelm doesn't store which paths or CODEOWNERS entries a review covered." }, + { path: "coderhelm.exceptions.cost_per_merged", reason: "not_recorded", text: "Not recorded yet: run cost isn't joined to pull requests." }, + ]; + if (young) { + for (const s of Object.keys(LABELS)) missing.push({ path: `strip.${s}.delta`, reason: "history", text: "Not enough history yet: the week-over-week change needs a snapshot from 7 days ago." }); + missing.push({ path: "review.flow", reason: "history", text: "Not enough history yet: the weekly flow needs 2 weeks of review logs." }); + missing.push({ path: "review.depth.rubber_stamp", reason: "history", text: "Not enough history yet: the repo's p10 approval time needs 30 approvals." }); + missing.push({ path: "review.rubber_stamp_by_size", reason: "history", text: "Not enough history yet: fewer than 10 qualifying PRs." }); + missing.push({ path: "repo_view.flow", reason: "history", text: "Not enough history yet: the flow by stage needs 2 nightly snapshots." }); + missing.push({ path: "failures.main_red", reason: "history", text: "Not enough history yet: main's checks are read from this week on." }); + missing.push({ path: "failures.flaky", reason: "history", text: "Not enough history yet: a flaky check needs 10 runs." }); + } + const o: PrsOverview = { + scope: { org: "acme", repo: repo ?? null, window: "7d", vs: "8w", repos: 14, repos_read: kind === "backfilling" ? 12 : 14, orgs: ["acme"] }, + synced_at: iso(40), + generated_at: iso(40), + history: { + days: young ? 9 : 400, + weeks: young ? 1 : 57, + young, + merged_90d: isEmpty ? 0 : young ? 47 : 412, + since: iso(young ? 9 * D : 400 * D), + backfill: kind === "backfilling" ? { repos: 40, repos_read: 12, done: false, days: 90 } : { repos: 14, repos_read: 14, done: true, days: 400 }, + }, + thresholds: { + scope: repo ? "repo" : "org", + inherited: !!repo && repo !== "acme/checkout", + min_merged: 30, + min_weeks: 8, + external: young, + cycle: isEmpty ? null : CYCLE, + first_review: isEmpty ? null : { p50: 6 * H, p85: 2 * D }, + bands: [ + { key: "linearb_elite_cycle", label: "LinearB elite cycle time (p75)", secs: 25 * H, source: "LinearB benchmarks" }, + { key: "google_review", label: "Google whole review (median)", secs: 4 * H, source: "Sadowski et al." }, + ], + rule: "p85 of ready-to-merge over 90 days; a repo with fewer than 30 merges uses the org's; before 8 weeks of history the external bands stand beside it, labeled as external.", + }, + open, + drafts: stagesCount("draft"), + strip, + turns: { + person: all.filter((d) => ["first_review", "in_review"].includes(d.stage) || d.state === "needs_decision").length, + coderhelm: all.filter((d) => d.stage === "coderhelm_working").length, + machines: all.filter((d) => d.stage === "approved").length, + nobody: kind === "quiet" || isEmpty ? 0 : 2, + }, + conditions: { + stale: young ? { count: idle.length, delta: null, author: Math.round(idle.length / 3), reviewer: idle.length - Math.round(idle.length / 3) } : { count: idle.length, delta: bad ? 6 : 1, author: Math.round(idle.length / 3), reviewer: idle.length - Math.round(idle.length / 3) }, + abandoned: all.filter((d) => d.idle && d.age_secs > 14 * D).length, + zombie: kind === "quiet" || isEmpty ? 0 : 2, + high_drift: young ? null : bad ? 6 : 3, + blocked_by_main: young ? null : all.filter((d) => d.main_blocked).length, + }, + needs_decision: { count: decisions.length, oldest_secs: decisions.length ? Math.max(...decisions.map((d) => d.age_secs)) : null, link: { list: "view=needs_decision" } }, + aging: { dots: all, total: all.length, shown: all.length }, + repos: scoped, + rollup: { + health: bad ? "slipping" : kind === "quiet" || isEmpty ? "quiet" : kind === "normal" ? "healthy" : "at_risk", + repo: bad ? "acme/payments" : null, + rule: RULE, + }, + review: { + flow: young ? null : Array.from({ length: 8 }, (_, i) => ({ week: iso((7 - i) * 7 * D).slice(0, 10), requests: 18 + i * (bad ? 2 : 1), done: 19 + (i % 3) - (bad && i > 5 ? 4 : 0) })), + gap: young ? null : bad ? 12 : kind === "coderhelm_waiting" ? 9 : -1, + concentration: { top_share: isEmpty ? null : 0.58, reviewers: 23, delta: young ? null : 0.09, where: null }, + depth: { merged_without_review: isEmpty ? null : bad ? 0.09 : 0.03, rubber_stamp: young || isEmpty ? null : 0.06, median_size: isEmpty ? null : 86, median_size_delta: young ? null : 12 }, + coverage: isEmpty ? null : bad ? { merged: 41, human: 35, ai_only: 1, non_owner: 0, bypass: 1, none: 4 } : kind === "quiet" ? { merged: 6, human: 6, ai_only: 0, non_owner: 0, bypass: 0, none: 0 } : { merged: 38, human: 36, ai_only: 1, non_owner: 0, bypass: 0, none: 1 }, + first_review_human: isEmpty ? null : { p50: 6 * H, p85: D }, + first_review_any: isEmpty ? null : { p50: 3 * 60, p85: 40 * 60 }, + rubber_stamp_by_size: young || isEmpty ? null : { small: null, medium: 0.04, large: bad ? 0.09 : 0.05 }, + queue: isEmpty ? null : { under_4h: 6, h4_24: 9, d1_3: 4, over_3d: bad ? 7 : 2 }, + single_reviewer_paths: null, + funnel: chZero || isEmpty ? null : { raised: 52, acknowledged: 44, changed: 34, verified: 31, incorrect: 5 }, + }, + stale: { + stale: idle.length, + past_usual: all.filter((d) => d.band === "p85" || d.band === "p95").length, + on_author: Math.round(idle.length / 3), + on_reviewer: idle.length - Math.round(idle.length / 3), + abandoned: { count: all.filter((d) => d.idle && d.age_secs > 14 * D).length, oldest_secs: 23 * D }, + zombie: kind === "quiet" || isEmpty ? 0 : 2, + drift: young ? null : [ + { key: "acme/checkout#388", overlapping: 31 }, + { key: "acme/web#402", overlapping: 18 }, + { key: "acme/search#211", overlapping: 12 }, + ], + draft_p85_secs: 12 * D, + archive_candidates: kind === "quiet" ? 0 : 5, + }, + failures: { + ci_first_try: isEmpty ? null : { share: unstable ? 0.61 : 0.74, lo: 0.71, hi: 0.8, n: 212 }, + ci_fail_rate: isEmpty ? null : { share: unstable ? 0.27 : 0.18, n: 640 }, + flaky: young ? null : { count: unstable ? 5 : 1, new: unstable ? 3 : 0, top: unstable ? [{ check: "e2e/checkout.spec", repo: "acme/web", retries: 12 }, { check: "integration (search)", repo: "acme/search", retries: 5 }, { check: "lint", repo: "acme/web", retries: 3 }] : [{ check: "e2e/cart.spec", repo: "acme/web", retries: 2 }] }, + main_red: young ? null : bad ? { episodes: 1, secs: 2 * D + 3 * H, repo: "acme/inventory-api", mean_to_green_secs: 65 * 60 } : unstable ? { episodes: 2, secs: Math.round(4.5 * H), repo: "acme/web", mean_to_green_secs: 2 * H } : { episodes: 0, secs: 0, repo: null, mean_to_green_secs: 65 * 60 }, + reverts: isEmpty ? null : { count: unstable ? 2 : bad ? 1 : 0, coderhelm: unstable ? 1 : 0, coderhelm_merged: chZero ? 0 : 11, people: unstable ? 1 : bad ? 1 : 0, people_merged: 30 }, + proxy: isEmpty ? null : unstable ? 0.052 : 0.024, + suspects: unstable ? [{ kind: "incident", target: "acme/infra#212", by: "CI image update", reason: "merged 2h before the first red run, same runner" }] : bad ? [{ kind: "hotfix", target: "acme/web#430", by: "acme/web#436", reason: "web#436 changed the same lines 3 days later, titled as a fix" }] : [], + queue_p95_secs: 4 * 60, + }, + security: { + sla_days: { critical: 7, high: 30, medium: 90, low: 180 }, + open: isEmpty ? null : bad ? { critical: 2, high: 3, medium: 9, low: 4 } : { critical: 0, high: 1, medium: 6, low: 3 }, + past_sla: bad ? [{ key: "acme/payments#311", severity: "critical", age_secs: 11 * D }, { key: "acme/payments#318", severity: "critical", age_secs: 9 * D }] : [], + bypasses: isEmpty ? null : { count: bad ? 1 : 0, reviewed_after: 0 }, + exempt_by_coderhelm: chZero ? 0 : 0, + no_human_approval: isEmpty ? null : bad ? { total: 6, person: 4, coderhelm: 0, bot: 2 } : { total: 1, person: 0, coderhelm: 0, bot: 1 }, + sensitive_without_owner: bad ? 1 : 0, + dependency: [ + { group: "Dependabot", merge_rate: 0.86, superseded: 0.06 }, + { group: "Renovate", merge_rate: null, superseded: null }, + { group: "CoderHelm", merge_rate: chZero ? null : 0.92, superseded: chZero ? null : 0.04 }, + ], + }, + events: isEmpty + ? [] + : bad + ? [ + { at: iso(2 * D), repo: "acme/infra", kind: "bypass", text: "Bypass merge infra#212 (admin), no review after", link: { list: "pr=acme/infra#212" }, severity: 3 }, + { at: iso(3 * D), repo: "acme/inventory-api", kind: "main_red", text: "Main red on payments_test, still red after 51h", link: { list: "repo=acme/inventory-api&state=checks_failing" }, severity: 3 }, + { at: iso(3 * D + 2 * H), repo: "acme/payments", kind: "sla", text: "Critical security fix payments#311 passed its 7-day SLA", link: { list: "pr=acme/payments#311" }, severity: 3 }, + { at: iso(4 * D), repo: "acme/web", kind: "revert", text: "Revert merged: web#430, 1 day after merge (a person's PR)", link: { list: "pr=acme/web#430" }, severity: 2 }, + { at: iso(5 * D), repo: "acme/web", kind: "codeowners", text: "CODEOWNERS removed (web#428)", link: { list: "pr=acme/web#428" }, severity: 2 }, + { at: iso(6 * D), repo: "acme/shipping", kind: "agent_stopped", text: "CoderHelm gave up on shipping#80: needs a test key only a repo admin can add", link: { list: "pr=acme/shipping#80" }, severity: 2 }, + ] + : unstable + ? [ + { at: iso(2 * D), repo: "acme/web", kind: "main_red", text: "Main red 50m on e2e/checkout.spec; green after web#447", link: { list: "pr=acme/web#447" }, severity: 3 }, + { at: iso(2 * D + 4 * H), repo: "acme/web", kind: "revert", text: "Revert merged: web#439, 2 days after merge (CoderHelm's PR)", link: { list: "pr=acme/web#439" }, severity: 2 }, + { at: iso(4 * D), repo: "acme/web", kind: "main_red", text: "Main red 3h 38m on e2e/checkout.spec", link: { list: "repo=acme/web" }, severity: 3 }, + { at: iso(5 * D), repo: "acme/web", kind: "flaky", text: "New flaky check e2e/checkout.spec: 12 passes on retry", link: { list: "repo=acme/web&state=checks_failing" }, severity: 1 }, + { at: iso(6 * D), repo: "acme/infra", kind: "suspect", text: "Suspect: infra#212 changed the CI image 2h before the first red run", link: { list: "pr=acme/infra#212" }, severity: 1 }, + ] + : kind === "normal" + ? [{ at: iso(5 * D), repo: "acme/mobile", kind: "online", text: "mobile came online: first PR activity", link: { overview: "repo=acme/mobile" }, severity: 0 }] + : [], + coderhelm: { + author: chZero + ? { opened: 0, merged: 0, closed_unmerged: 0, open: 0, merge_rate: null, p50_merge_secs: null, waiting_on_people: null, rule: "Merged / (merged + closed unmerged) for PRs resolved in the window; open PRs excluded." } + : { opened: 14, merged: 11, closed_unmerged: 1, open: 2, merge_rate: 0.92, p50_merge_secs: 7 * H, waiting_on_people: 0.71, rule: "Merged / (merged + closed unmerged) for PRs resolved in the window; open PRs excluded." }, + fixer: chZero ? { fixed: 0, merged: 0, closed_unmerged: 0, open: 0 } : { fixed: 6, merged: 5, closed_unmerged: 0, open: 1 }, + reviewer: chZero ? { reviewed: 0, findings: null, verified_rate: null, p50_first_look_secs: null } : { reviewed: 38, findings: { p0: 3, p1: 9, p2: 21 }, verified_rate: 0.64, p50_first_look_secs: 360 }, + runs: chZero ? { first_try: 0, after_fixes: 0, rerun_only: 0, gave_up: 0, blocked: 0, stopped: 0, reasons: [] } : unstable ? { first_try: 6, after_fixes: 3, rerun_only: 6, gave_up: 0, blocked: 0, stopped: 0, reasons: [{ reason: "flaky check", count: 6 }] } : bad ? { first_try: 2, after_fixes: 1, rerun_only: 0, gave_up: 1, blocked: 4, stopped: 0, reasons: [{ reason: "red main", count: 4 }, { reason: "needs a secret", count: 1 }] } : { first_try: 9, after_fixes: 2, rerun_only: 0, gave_up: 0, blocked: 0, stopped: 0, reasons: [] }, + exceptions: { + needs_decision: chZero ? 0 : decisions.filter((d) => d.coderhelm).length, + oldest_secs: decisions.length ? Math.max(...decisions.map((d) => d.age_secs)) : null, + reworked: chZero ? { coderhelm: 0, people: 1, coderhelm_merged: 0, people_merged: 40 } : { coderhelm: unstable ? 1 : 0, people: 1, coderhelm_merged: 11, people_merged: 31 }, + merges: chZero ? null : { on_approval: 9, own_authority: 2, exempt: 0 }, + cost_per_merged: null, + }, + }, + facts: [ + { id: "open", kind: "count", scope: "acme", value: open, prev: open - 3, delta: 3, unusual: false, weight: 0.12, link: { list: "" } }, + { id: "past_p85", kind: "count", scope: "acme", value: all.filter((d) => d.band === "p85" || d.band === "p95").length, prev: 7, delta: 4, unusual: true, weight: 0.31, link: { list: "past=p85" } }, + { id: "merges", kind: "count", scope: "acme", value: 38, prev: 31, delta: 7, unusual: false, weight: 0.22, link: merged("merged:>=2026-01-04") }, + { id: "reverts", kind: "count", scope: "acme", value: 0, prev: 1, delta: -1, unusual: false, weight: 0.05, link: merged("revert in:title") }, + ], + summary: (() => { + // The Stale tile is the same fact as the Stale panel's top line. + const sm = summary(kind); + const tile = sm.tiles.find((x) => x.fact === "stale"); + if (tile) { + tile.value = idle.length; + tile.delta = young ? null : bad ? 6 : 1; + } + return sm; + })(), + missing, + sources: [{ name: "records", read: "ok", detail: "" }], + }; + if (repo) { + const days = young ? 1 : 84; + o.repo_view = { + flow: young + ? null + : Array.from({ length: days }, (_, i) => ({ + day: iso((days - i) * D).slice(0, 10), + stages: { draft: 1 + (i % 3 === 0 ? 1 : 0), first_review: 3 + Math.round(4 * Math.sin(i / 9) ** 2) + Math.floor(i / 20), in_review: 3 + (i % 5 === 0 ? 1 : 0), blocked: 1 + Math.floor(i / 30), coderhelm_working: i % 4 === 0 ? 1 : 0, approved: 2 }, + })), + merged: Array.from({ length: 34 }, (_, i) => { + const r = rng(i + 5); + const ch = i % 4 === 0; + return { key: `${repo}#${200 + i}`, number: 200 + i, title: TITLES[i % TITLES.length], cycle_secs: Math.round((1 + r() * r() * 120) * H), merged_at: iso((90 - i * 2.5) * D), coderhelm: ch }; + }), + }; + } + return o; +} + +/** Every login the fixtures use for people: none may appear outside a pull request's row or an item's owner. */ +export const PEOPLE = ["octocat", "mara", "theo", "jun"]; diff --git a/dashboard/e2e/prs-overview-mock.ts b/dashboard/e2e/prs-overview-mock.ts new file mode 100644 index 00000000..80146951 --- /dev/null +++ b/dashboard/e2e/prs-overview-mock.ts @@ -0,0 +1,42 @@ +import type { Page, Route } from "@playwright/test"; +import type { PrsOverview } from "../src/lib/api"; +import { overview, type Scenario } from "./prs-overview-data"; +import { detail, page as prsPage } from "./prs-data"; + +export interface OverviewBackend { + calls: string[]; + /** The answer to /api/prs/overview for its query; a number is an error status. Tests swap it mid-way. */ + answer: (url: URL) => PrsOverview | number; +} + +/** Answers every API call the overview and the list make, from the invented data. */ +export async function mockOverview(page: Page, scenario: Scenario | ((url: URL) => PrsOverview | number) = "normal"): Promise { + const db: OverviewBackend = { + calls: [], + answer: typeof scenario === "function" ? scenario : (url) => overview(scenario, url.searchParams.get("repo") ?? undefined), + }; + const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const url = new URL(route.request().url()); + const p = url.pathname; + db.calls.push(`${route.request().method()} ${p}${url.search}`); + if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "octocat", email: "octocat@example.com", avatar_url: "", role: "member" }); + if (p === "/api/usage") return json(route, { month: "2026-01", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/security/overview") return json(route, { enabled: false, dry_run: true, counts: { open: 0, p0: 0, p1: 0 } }); + if (p === "/api/setup") return json(route, { repos: [], new_recommendations: [], auto_setup_new_repos: false }); + if (p === "/api/support/badge") return json(route, { waiting: 0, queue_open: null }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "acme", status: "active", current: true }] }); + if (p === "/api/repos") return json(route, { repos: [{ name: "acme/web", enabled: true }, { name: "acme/checkout", enabled: true }] }); + if (p === "/api/prs/overview") { + const a = db.answer(url); + if (typeof a === "number") return json(route, { error: "nope" }, a); + return json(route, a); + } + if (p === "/api/prs") return json(route, prsPage()); + if (p === "/api/prs/detail") return json(route, detail()); + return json(route, { error: "Not mocked" }, 404); + }); + return db; +} diff --git a/dashboard/e2e/prs-overview.spec.ts b/dashboard/e2e/prs-overview.spec.ts new file mode 100644 index 00000000..7403a7f6 --- /dev/null +++ b/dashboard/e2e/prs-overview.spec.ts @@ -0,0 +1,237 @@ +import { expect, test, type Page } from "@playwright/test"; +import { overview, PEOPLE } from "./prs-overview-data"; +import { mockOverview } from "./prs-overview-mock"; + +// The Pull requests overview (/prs/overview): the summary written from +// facts, the stage strip and its drill-down into the list, the aging chart, +// the repo table and one repo's page, the five panels, CoderHelm's slice, +// the "not enough history yet" and backfill states, the empty, error, +// loading and older-backend states, no person's name outside an item's +// owner, and the phone layout. Every API call is answered by the mock. + +async function open(page: Page, scenario: Parameters[1] = "normal", url = "/prs/overview?org=acme") { + const db = await mockOverview(page, scenario); + await page.goto(url); + await expect(page.getByTestId("overview-summary")).toBeVisible(); + return db; +} + +test("the Pull requests menu lands on the Overview tab, and List is beside it", async ({ page }) => { + await mockOverview(page, "normal"); + await page.goto("/prs/overview"); + const tabs = page.getByTestId("section-tabs"); + await expect(tabs.getByRole("link", { name: "Overview" })).toHaveAttribute("aria-current", "page"); + await expect(tabs.getByRole("link", { name: "List" })).toHaveAttribute("href", /^\/prs\/?$/); +}); + +test("the summary: a verdict, three fixed tiles, ranked items with owners, and the stability and CoderHelm lines", async ({ page }) => { + await open(page, "bad"); + const s = page.getByTestId("overview-summary"); + await expect(s).toHaveAttribute("data-verdict", "slipping"); + await expect(page.getByTestId("summary-verdict-word")).toHaveText(/Slipping/); + // The sentence starts with the reason, not the chip's word again. + await expect(page.getByTestId("summary-verdict")).not.toContainText("Slipping."); + const tiles = page.getByTestId("summary-tile"); + await expect(tiles).toHaveCount(3); + await expect(tiles.nth(0)).toHaveAttribute("data-tile", "stale"); + await expect(tiles.nth(1)).toHaveAttribute("data-tile", "failures"); + await expect(tiles.nth(2)).toHaveAttribute("data-tile", "reviewed"); + const items = page.getByTestId("summary-item"); + expect(await items.count()).toBeLessThanOrEqual(5); + await expect(items.first()).toContainText("past SLA"); + // A line with no owner says why. + await expect(page.getByTestId("summary-owner").filter({ hasText: "no reviewer was requested" })).toBeVisible(); + await expect(page.getByTestId("summary-stability")).toBeVisible(); + await expect(page.getByTestId("summary-coderhelm")).toContainText("blocked on the red main"); + await expect(page.getByTestId("summary-window")).toContainText(/computed (Mon|Tue|Wed|Thu|Fri|Sat|Sun) [A-Z][a-z]{2} \d+, \d\d:\d\d/); + await page.getByTestId("summary-source-toggle").click(); + await expect(page.getByTestId("summary-rule")).toContainText("Slipping: any obligation breached"); +}); + +test("every number in the summary links to what produced it", async ({ page }) => { + await open(page, "normal"); + const nums = page.getByTestId("summary-number"); + expect(await nums.count()).toBeGreaterThan(4); + for (const n of await nums.all()) { + await expect(n).toHaveAttribute("data-fact", /.+/); + await expect(n).toHaveAttribute("href", /.+/); + } + // The text between them carries no bare count: digits sit inside a fact's link, a PR reference or a time. + const verdict = (await page.getByTestId("summary-verdict").innerText()).replace(/\s+/g, " "); + const linked = (await page.getByTestId("summary-verdict").getByTestId("summary-number").allInnerTexts()).join(" "); + for (const d of verdict.match(/\d+(\.\d+)?[hd%]?/g) ?? []) expect(`${linked} 11h`).toContain(d); +}); + +test("the five example weeks each read as their own verdict", async ({ page }) => { + for (const [kind, state, words] of [ + ["normal", "healthy", "38"], + ["bad", "slipping", "critical security fixes"], + ["quiet", "quiet", "6"], + ["coderhelm_waiting", "at_risk", "Work is done but not landing"], + ["unstable", "at_risk", "flaky"], + ] as const) { + await page.unrouteAll({ behavior: "ignoreErrors" }); + await open(page, kind); + await expect(page.getByTestId("overview-summary")).toHaveAttribute("data-verdict", state); + await expect(page.getByTestId("summary-verdict")).toContainText(words); + } + await expect(page.getByTestId("summary-coderhelm")).toContainText("rerun"); +}); + +test("a quiet week says what was checked", async ({ page }) => { + await open(page, "quiet"); + await expect(page.getByTestId("summary-quiet")).toContainText("Checked 14 repos and 9 open PRs"); + await expect(page.getByTestId("summary-item")).toHaveCount(0); +}); + +test("a strip cell opens the list filtered to its stage, and the list shows the filter", async ({ page }) => { + const db = await open(page, "normal"); + await page.locator('[data-testid="strip-cell"][data-stage="first_review"]').first().click(); + await expect(page).toHaveURL(/\/prs\/?\?org=acme&stage=first_review/, { timeout: 60_000 }); + await expect(page.getByTestId("prs-filter-chip")).toContainText("Stage: Waiting for first review"); + await expect.poll(() => db.calls.some((c) => c.startsWith("GET /api/prs?") && c.includes("stage=first_review"))).toBe(true); + await page.getByTestId("prs-filter-chip").click(); + await expect(page).not.toHaveURL(/stage=/); +}); + +test("past-usual counts open the list filtered to past p85", async ({ page }) => { + await open(page, "bad"); + await page.getByTestId("panel-stale").getByTestId("stale-past-usual").click(); + await expect(page).toHaveURL(/past=p85/, { timeout: 60_000 }); + await expect(page.getByTestId("prs-filter-chip")).toContainText("Open past the p85"); +}); + +test("the aging chart: one mark per PR, a shape per author, the percentile lines, and a click opens the PR", async ({ page }) => { + await open(page, "bad"); + const o = overview("bad"); + const dots = page.getByTestId("aging-dot"); + await expect(dots).toHaveCount(o.aging.dots.length); + await expect(page.locator('[data-testid="aging-dot"][data-shape="hexagon"]').first()).toBeAttached(); + await expect(page.locator('[data-testid="aging-dot"][data-shape="circle"]').first()).toBeAttached(); + await expect(page.locator('[data-testid="aging-dot"][data-idle="true"]').first()).toBeAttached(); + await expect(page.locator('[data-testid="aging-dot"][data-main-blocked="true"]').first()).toBeAttached(); + for (const l of ["p50", "p85", "p95"]) await expect(page.getByTestId(`aging-line-${l}`)).toBeAttached(); + // Every mark is named in words, never only by colour. + await expect(dots.first()).toHaveAttribute("aria-label", /open .*(person's|CoderHelm's|bot's) pull request/); + await page.getByTestId("aging-select-past").click(); + await expect(page.getByTestId("aging-bubble")).not.toBeEmpty(); + const key = o.aging.dots[0].key; + await page.locator(`[data-testid="aging-dot"][href*="${encodeURIComponent(key)}"]`).first().click(); + await expect(page).toHaveURL(new RegExp(`/prs/?\\?.*pr=${encodeURIComponent(key).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`), { timeout: 60_000 }); +}); + +test("the repo table: health words with their rule, new columns, and a row opens that repo's overview", async ({ page }) => { + const db = await open(page, "bad"); + const rows = page.getByTestId("repo-row"); + await expect(rows.first()).toHaveAttribute("data-health", "slipping"); + await expect(page.getByTestId("rollup-rule")).toContainText("The org takes the worst state"); + await expect(page.getByTestId("repo-flags").first()).not.toBeEmpty(); + await page.getByTestId("repo-link").first().click(); + await expect(page).toHaveURL(/\/prs\/overview\/?\?org=acme&repo=acme%2F/, { timeout: 60_000 }); + await expect(page.getByTestId("overview-repo-views")).toBeVisible(); + await expect.poll(() => db.calls.some((c) => c.includes("/api/prs/overview?") && c.includes("repo=acme"))).toBe(true); +}); + +test("the five panels render, and the Stale tile equals the Stale panel's headline", async ({ page }) => { + for (const kind of ["normal", "bad"] as const) { + await page.unrouteAll({ behavior: "ignoreErrors" }); + await open(page, kind); + for (const p of ["stale", "failures", "review", "security", "events"]) await expect(page.getByTestId(`panel-${p}`)).toBeVisible(); + const tile = (await page.locator('[data-testid="summary-tile"][data-tile="stale"] [data-fact="stale"]').innerText()).trim(); + const panel = (await page.getByTestId("stale-headline").innerText()).trim(); + expect(panel.startsWith(tile)).toBe(true); + expect(tile).toBe(String(overview(kind).stale.stale)); + } + await expect(page.getByTestId("coverage-bar")).toBeVisible(); + await expect(page.getByTestId("review-funnel")).toContainText("verified fixed"); + await expect(page.getByTestId("security-past-sla")).toHaveText("2"); + await expect(page.getByTestId("failure-suspects")).toContainText("suspect"); + await expect(page.getByTestId("event-rows").locator("li")).toHaveCount(6); +}); + +test("CoderHelm's panel reports outcomes and runs in one end state each, with no line counts", async ({ page }) => { + await open(page, "unstable"); + const ch = page.getByTestId("overview-coderhelm"); + await expect(ch).toContainText("green only on a rerun (flaky, not fixed) 6"); + await expect(ch).not.toContainText(/lines? (of code|written)/i); +}); + +test("an org with no CoderHelm pull requests still gets the whole overview", async ({ page }) => { + await open(page, "people_only"); + await expect(page.getByTestId("aging-dot").first()).toBeAttached(); + await expect(page.getByTestId("repo-row").first()).toBeVisible(); + await expect(page.getByTestId("panel-review")).toBeVisible(); + await expect(page.locator('[data-testid="aging-dot"][data-shape="hexagon"]')).toHaveCount(0); + await expect(page.getByTestId("summary-coderhelm")).toContainText("No PRs from CoderHelm in this window"); +}); + +test("not enough history yet: young data says so instead of a zero", async ({ page }) => { + await open(page, "young"); + await expect(page.getByTestId("history-note")).toContainText("1 week"); + await expect(page.getByTestId("not-yet").first()).toBeVisible(); + await expect(page.getByTestId("aging-external")).toBeVisible(); + await expect(page.getByTestId("aging-band").first()).toBeAttached(); +}); + +test("a backfill in progress shows how far it has read", async ({ page }) => { + await open(page, "backfilling"); + await expect(page.getByTestId("history-backfill")).toContainText("12 of 40 repos read"); +}); + +test("no person's name appears outside an item's owner", async ({ page }) => { + for (const kind of ["bad", "coderhelm_waiting", "people_only"] as const) { + await page.unrouteAll({ behavior: "ignoreErrors" }); + await open(page, kind); + await expect(page.getByTestId("panel-events")).toBeVisible(); + const text = await page.getByTestId("prs-overview").evaluate((root) => { + const clone = root.cloneNode(true) as HTMLElement; + clone.querySelectorAll('[data-testid="summary-owner"]').forEach((n) => n.remove()); + return clone.innerText + " " + Array.from(clone.querySelectorAll("[aria-label],[title]")).map((n) => `${n.getAttribute("aria-label") ?? ""} ${n.getAttribute("title") ?? ""}`).join(" "); + }); + for (const p of PEOPLE) expect(text.toLowerCase(), `${p} in ${kind}`).not.toMatch(new RegExp(`(^|[^a-z0-9-])@?${p}([^a-z0-9-]|$)`)); + } +}); + +test("an older backend's 404 explains and points at the list", async ({ page }) => { + await mockOverview(page, () => 404); + await page.goto("/prs/overview"); + await expect(page.getByTestId("overview-not-served")).toBeVisible(); + await expect(page.getByTestId("overview-not-served").getByRole("link", { name: "list" })).toHaveAttribute("href", /^\/prs\/?$/); +}); + +test("a failed read shows the error with a retry that reads again", async ({ page }) => { + let fail = true; + await mockOverview(page, (url) => (fail ? 500 : overview("normal", url.searchParams.get("repo") ?? undefined))); + await page.goto("/prs/overview"); + await expect(page.getByTestId("list-error")).toBeVisible({ timeout: 45_000 }); + fail = false; + await page.getByTestId("list-error").getByRole("button").first().click(); + await expect(page.getByTestId("overview-summary")).toBeVisible(); +}); + +test("while it reads, the page shows its outline, and with nothing yet it says so", async ({ page }) => { + let release!: () => void; + const gate = new Promise((r) => (release = r)); + await mockOverview(page, "empty"); + await page.route("**/api/prs/overview**", async (route) => { + await gate; + await route.fallback(); + }); + await page.goto("/prs/overview"); + await expect(page.getByTestId("overview-loading")).toBeVisible(); + release(); + await expect(page.getByTestId("overview-empty")).toBeVisible(); +}); + +for (const width of [320, 375]) { + test(`the phone layout at ${width}: priority order and no sideways scroll`, async ({ page }) => { + await page.setViewportSize({ width, height: 800 }); + await open(page, "bad"); + await expect(page.getByTestId("overview-phone")).toBeVisible(); + await expect(page.getByTestId("overview-past-usual")).toBeVisible(); + await page.getByTestId("phone-stale").click(); + await expect(page.getByTestId("overview-phone").getByTestId("panel-stale")).toBeVisible(); + const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(wide).toBeLessThanOrEqual(0); + }); +} diff --git a/dashboard/e2e/wide-data/index.ts b/dashboard/e2e/wide-data/index.ts index 859c216d..a40e72e9 100644 --- a/dashboard/e2e/wide-data/index.ts +++ b/dashboard/e2e/wide-data/index.ts @@ -14,6 +14,7 @@ import { infraData } from "./infra"; import { setupData } from "./setup"; import { skillRunsData } from "./skill-runs"; import { prsData } from "./prs"; +import { prsOverviewData } from "./prs-overview"; import { inboxData } from "./inbox"; // An invented backend whose records are full of long, unbroken strings @@ -53,7 +54,7 @@ const base: Handler = ({ method, path }) => { }; // Knowledge answers /api/knowledge before the chat's file does. -const HANDLERS: Handler[] = [base, runsData, reviewData, settingsData, logsData, learningData, knowledgeData, brainData, agentsData, pluginsData, securityData, infraData, setupData, skillRunsData, inboxData, prsData]; +const HANDLERS: Handler[] = [base, runsData, reviewData, settingsData, logsData, learningData, knowledgeData, brainData, agentsData, pluginsData, securityData, infraData, setupData, skillRunsData, inboxData, prsData, prsOverviewData]; /** Mocks the whole API. Returns the list of GETs no handler answered. */ export async function mockWideApi(page: Page): Promise<{ unanswered: string[] }> { diff --git a/dashboard/e2e/wide-data/prs-overview.ts b/dashboard/e2e/wide-data/prs-overview.ts new file mode 100644 index 00000000..0a34d2d6 --- /dev/null +++ b/dashboard/e2e/wide-data/prs-overview.ts @@ -0,0 +1,31 @@ +import type { Handler } from "./index"; +import { ORG, REPO, SENTENCE, TITLE, TOKEN } from "./long"; +import { overview } from "../prs-overview-data"; + +// The Pull requests overview: the bad week, with every repo, title, owner, +// event and sentence stretched to the longest text the page will get. + +const LOGIN = "dana-developer-with-a-long-login"; + +function wide(): unknown { + let s = JSON.stringify(overview("bad")); + // Each invented repo becomes a long one, still one per name. + s = s.replace(/acme\/([a-z-]+)/g, (_m, name: string) => `${REPO}-${name}`); + s = s.replace(/"org":"acme"/g, `"org":"${ORG}"`).replace(/"acme"/g, `"${ORG}"`); + for (const t of ["Round cart totals per currency", "Show stock per warehouse on the book page", "Cache the bestseller list for an hour"]) s = s.split(t).join(`${TITLE} ${TOKEN}`); + const o = JSON.parse(s); + for (const a of o.summary.attention) { + a.parts.push({ t: ` ${SENTENCE} ${TOKEN}` }); + if (a.owner) a.owner = `${LOGIN}-${TOKEN}`; + } + for (const e of o.events) e.text = `${e.text}: ${SENTENCE} ${TOKEN}`; + o.summary.changed.parts.push({ t: ` ${SENTENCE} ${TOKEN}` }); + o.failures.flaky = { count: 1, new: 1, top: [{ check: TOKEN, repo: REPO, retries: 12 }] }; + return o; +} + +export const prsOverviewData: Handler = ({ method, path }) => { + if (method !== "GET") return undefined; + if (path === "/api/prs/overview") return wide(); + return undefined; +}; diff --git a/dashboard/src/app/prs/overview/charts.tsx b/dashboard/src/app/prs/overview/charts.tsx new file mode 100644 index 00000000..91a38645 --- /dev/null +++ b/dashboard/src/app/prs/overview/charts.tsx @@ -0,0 +1,451 @@ +"use client"; + +// The overview's charts, drawn as plain SVG on the dashboard's tokens: a +// word-sized sparkline, the stage mix bar, the aging chart (one mark per open +// pull request against the org's own percentile lines), the review queue's +// requests against reviews done, and one repo's flow by stage and merged cycle +// times. Recharts is in the app already, but none of these need it: each is a +// handful of marks whose shape and words matter more than an axis library. +// Every mark carries its meaning in words or shape; colour only repeats it. + +import Link from "next/link"; +import { useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from "react"; +import type { OverviewDot, OverviewPercentiles, PrStage, PrsOverview } from "@/lib/api"; +import { focusRing } from "@/components/ui"; +import { dur, durLong, STAGE_FILL, STAGES, stageLook, type Scope, prHref } from "./model"; + +/** A word-sized line of up to 8 weekly values; nothing when there are fewer than 2. */ +export function Sparkline({ values, label, className = "" }: { values: number[] | null | undefined; label: string; className?: string }) { + if (!values || values.length < 2) return null; + const w = 56; + const h = 16; + const max = Math.max(1, ...values); + const step = w / (values.length - 1); + const pts = values.map((v, i) => `${(i * step).toFixed(1)},${(h - 1 - (v / max) * (h - 2)).toFixed(1)}`).join(" "); + const last = values[values.length - 1]; + return ( + + + + + ); +} + +/** A stacked bar of a repo's open pull requests by stage, each segment named. */ +export function MixBar({ stages, open }: { stages: Partial>; open: number }) { + if (open <= 0) return none open; + const parts = STAGES.map((s) => ({ s, n: stages[s.stage] ?? 0 })).filter((p) => p.n > 0); + const words = parts.map((p) => `${p.n} ${p.s.short.toLowerCase()}`).join(", "); + return ( + + {parts.map((p) => ( + + ))} + + ); +} + +/** The legend for the mix bar's fills, with each stage's words. */ +export function MixLegend() { + return ( +
    + {STAGES.map((s) => ( +
  • +
  • + ))} +
+ ); +} + +const HOUR = 3600; +const DAY = 86_400; + +/** Log-scaled age axis ticks, in hours and days. */ +const TICKS = [HOUR, 6 * HOUR, DAY, 3 * DAY, 7 * DAY, 14 * DAY, 30 * DAY, 90 * DAY]; + +function hexPath(cx: number, cy: number, r: number): string { + const pts = Array.from({ length: 6 }, (_, i) => { + const a = (Math.PI / 3) * i - Math.PI / 2; + return `${(cx + r * Math.cos(a)).toFixed(2)},${(cy + r * Math.sin(a)).toFixed(2)}`; + }); + return `M${pts.join("L")}Z`; +} + +/** A stable spread inside a column for a key, so dots don't move on every read. */ +function jitter(key: string): number { + let h = 2166136261; + for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 16777619); + return ((h >>> 0) % 1000) / 1000; +} + +/** Which percentile a dot's age is past: its fill steps up one lightness per line. */ +const BAND_CLASS: Record = { + none: "fill-zinc-500 stroke-zinc-300", + p50: "fill-amber-200/70 stroke-amber-100", + p85: "fill-amber-400 stroke-amber-200", + p95: "fill-orange-500 stroke-orange-200", +}; + +export interface Brushed { + dots: OverviewDot[]; + sentence: string; +} + +/** + * What a selection of dots has more of than the page as a whole (repo, + * stage, author type, size is not on the dot): the BubbleUp sentence. + */ +export function bubbleUp(selected: OverviewDot[], all: OverviewDot[]): string { + if (selected.length === 0) return ""; + const n = selected.length; + const top = (f: (d: OverviewDot) => K) => { + const counts = new Map(); + for (const d of selected) counts.set(f(d), (counts.get(f(d)) ?? 0) + 1); + const allCounts = new Map(); + for (const d of all) allCounts.set(f(d), (allCounts.get(f(d)) ?? 0) + 1); + let best: { k: K; c: number; lift: number } | null = null; + for (const [k, c] of counts) { + const lift = c / n - (allCounts.get(k) ?? 0) / Math.max(1, all.length); + if (!best || lift > best.lift || (lift === best.lift && c > best.c)) best = { k, c, lift }; + } + return best; + }; + const repo = top((d) => d.repo); + const stage = top((d) => d.stage); + const author = top((d) => (d.coderhelm ? "CoderHelm's" : d.author_type === "bot" ? "bots'" : "people's")); + const bits: string[] = []; + if (repo && repo.c > 1 && repo.lift > 0.05) bits.push(`${repo.c} of these ${n} are in ${repo.k}`); + if (stage && stage.c > 1 && stage.lift > 0.05) bits.push(`${stage.c} are ${stageLook(stage.k).label.toLowerCase()}`); + if (author && author.c > 1 && author.lift > 0.05) bits.push(`${author.c} are ${author.k}`); + if (bits.length === 0) return `These ${n} look like the rest: no repo, stage or author type stands out.`; + const s = bits.join(", "); + return `${s.charAt(0).toUpperCase()}${s.slice(1)}.`; +} + +/** + * Vacanti's aging chart: the six stages as columns, each open pull request a + * mark at its age since ready for review (log scale), a hexagon for + * CoderHelm's and a circle for people's, with the scope's p50, p85 and p95 + * cycle-time lines. Each mark is a link to the pull request's detail. Drag + * across the chart (or press "Past p85") to select a cluster and read what + * it has more of. + */ +export function AgingChart({ + overview, + scope, + onBrush, +}: { + overview: PrsOverview; + scope: Scope; + onBrush: (b: Brushed | null) => void; +}) { + const dots = overview.aging.dots; + const lines = overview.thresholds.cycle; + const bands = overview.thresholds.external ? overview.thresholds.bands : []; + const W = 640; + const H = 300; + const pad = { l: 34, r: 62, t: 10, b: 26 }; + const maxAge = Math.max(14 * DAY, ...dots.map((d) => d.age_secs), lines?.p95 ?? 0); + const minAge = HOUR / 2; + const y = (secs: number) => { + const v = Math.log(Math.max(minAge, secs)) - Math.log(minAge); + const top = Math.log(maxAge * 1.15) - Math.log(minAge); + return pad.t + (H - pad.t - pad.b) * (1 - v / top); + }; + const colW = (W - pad.l - pad.r) / STAGES.length; + const x = (stage: string, key: string) => { + const i = Math.max(0, STAGES.findIndex((s) => s.stage === stage)); + return pad.l + colW * i + colW * (0.18 + 0.64 * jitter(key)); + }; + const placed = useMemo(() => dots.map((d) => ({ d, cx: x(d.stage, d.key), cy: y(d.age_secs) })), [dots]); // eslint-disable-line react-hooks/exhaustive-deps + + const svgRef = useRef(null); + const [drag, setDrag] = useState<{ x0: number; y0: number; x1: number; y1: number } | null>(null); + const [picked, setPicked] = useState | null>(null); + + const toLocal = (e: ReactPointerEvent) => { + const r = svgRef.current!.getBoundingClientRect(); + return { px: ((e.clientX - r.left) / r.width) * W, py: ((e.clientY - r.top) / r.height) * H }; + }; + const select = (keys: Set | null) => { + setPicked(keys); + if (!keys || keys.size === 0) { + onBrush(null); + return; + } + const sel = dots.filter((d) => keys.has(d.key)); + onBrush({ dots: sel, sentence: bubbleUp(sel, dots) }); + }; + + const tickLabels = TICKS.filter((t) => t <= maxAge * 1.15); + const lineDefs = lines + ? ([ + ["p50", lines.p50], + ["p85", lines.p85], + ["p95", lines.p95 ?? null], + ] as const) + : []; + + return ( +
+ { + if ((e.target as Element).closest("a")) return; + const { px, py } = toLocal(e); + setDrag({ x0: px, y0: py, x1: px, y1: py }); + (e.currentTarget as Element).setPointerCapture?.(e.pointerId); + }} + onPointerMove={(e) => { + if (!drag) return; + const { px, py } = toLocal(e); + setDrag({ ...drag, x1: px, y1: py }); + }} + onPointerUp={() => { + if (!drag) return; + const [xa, xb] = [Math.min(drag.x0, drag.x1), Math.max(drag.x0, drag.x1)]; + const [ya, yb] = [Math.min(drag.y0, drag.y1), Math.max(drag.y0, drag.y1)]; + setDrag(null); + if (xb - xa < 4 && yb - ya < 4) { + select(null); + return; + } + select(new Set(placed.filter((p) => p.cx >= xa && p.cx <= xb && p.cy >= ya && p.cy <= yb).map((p) => p.d.key))); + }} + > + {/* Columns */} + {STAGES.map((s, i) => ( + + {i > 0 && } + + {s.short} + + + ))} + {/* Age ticks */} + {tickLabels.map((t) => ( + + + + {dur(t)} + + + ))} + {/* External context bands, faint and labeled as external */} + {bands.map((b) => ( + + + {`${b.label}, ${durLong(b.secs)} (external: ${b.source})`} + + ))} + {/* The scope's own percentile lines */} + {lineDefs.map(([name, v]) => + v == null ? null : ( + + + + {`${name} ${dur(v)}`} + + + ), + )} + {/* One mark per open pull request */} + {placed.map(({ d, cx, cy }) => { + const look = stageLook(d.stage); + const label = `${d.repo}#${d.number} ${d.title}. ${d.state_label || look.label}, open ${durLong(d.age_secs)}${d.band ? `, past the ${d.band}` : ""}${d.idle ? ", idle" : ""}${d.main_blocked ? ", blocked by a red main" : ""}. ${d.coderhelm ? "CoderHelm's" : d.author_type === "bot" ? "A bot's" : "A person's"} pull request.`; + // Idle past the stage p85: hollow, keeping its band's outline. + const cls = `${BAND_CLASS[d.band ?? "none"]} ${d.idle ? "!fill-zinc-950" : ""} ${picked && !picked.has(d.key) ? "opacity-30" : ""}`; + return ( + + {label} + {d.main_blocked && } + {d.coderhelm ? ( + + ) : d.author_type === "bot" ? ( + + ) : ( + + )} + + ); + })} + {drag && ( + + )} + +
+ + + A person's + + + + CoderHelm's + + + + Other bots' + + + + Past p85 + + + + Past p95 + + + + Idle + + + + Blocked by red main + + {bands.length > 0 && ( + + + )} + +
+
+ ); +} + +/** Review requests against reviews done per week, the gap between them shaded. */ +export function QueueFlow({ weeks }: { weeks: { week: string; requests: number; done: number }[] }) { + const W = 260; + const H = 70; + const max = Math.max(1, ...weeks.flatMap((w) => [w.requests, w.done])); + const step = weeks.length > 1 ? W / (weeks.length - 1) : W; + const yv = (v: number) => H - 4 - (v / max) * (H - 10); + const pts = (k: "requests" | "done") => weeks.map((w, i) => `${(i * step).toFixed(1)},${yv(w[k]).toFixed(1)}`); + const area = `M${pts("requests").join("L")}L${pts("done").reverse().join("L")}Z`; + return ( + `${w.requests} asked, ${w.done} done`).join("; ")}`} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className="block h-16 w-full" data-testid="queue-flow"> + + + + + ); +} + +/** One repo's open pull requests by stage per day, stacked. */ +export function StageFlow({ days }: { days: { day: string; stages: Partial> }[] }) { + const W = 520; + const H = 140; + const totals = days.map((d) => STAGES.reduce((a, s) => a + (d.stages[s.stage] ?? 0), 0)); + const max = Math.max(1, ...totals); + const step = days.length > 1 ? W / (days.length - 1) : W; + const layers: string[] = []; + const base = days.map(() => 0); + for (const s of STAGES) { + const lower = base.slice(); + days.forEach((d, i) => (base[i] += d.stages[s.stage] ?? 0)); + const up = days.map((_, i) => `${(i * step).toFixed(1)},${(H - (base[i] / max) * H).toFixed(1)}`); + const down = days.map((_, i) => `${(i * step).toFixed(1)},${(H - (lower[i] / max) * H).toFixed(1)}`).reverse(); + layers.push(`M${up.join("L")}L${down.join("L")}Z`); + } + const fills = ["fill-zinc-600", "fill-amber-400", "fill-orange-400", "fill-red-400", "fill-sky-400", "fill-emerald-400"]; + return ( + + {layers.map((d, i) => ( + + ))} + + ); +} + +/** Merged pull requests' cycle times, with the same percentile lines. */ +export function CycleScatter({ merged, lines }: { merged: { key: string; merged_at: string; cycle_secs: number; coderhelm: boolean; title: string }[]; lines: OverviewPercentiles | null }) { + const W = 520; + const H = 160; + const times = merged.map((m) => new Date(m.merged_at).getTime()); + const t0 = Math.min(...times); + const t1 = Math.max(...times, t0 + 1); + const maxC = Math.max(DAY, ...merged.map((m) => m.cycle_secs), lines?.p95 ?? 0) * 1.1; + const yv = (s: number) => H - 6 - (Math.log(Math.max(600, s)) - Math.log(600)) / (Math.log(maxC) - Math.log(600)) * (H - 12); + const xv = (t: number) => 4 + ((t - t0) / (t1 - t0)) * (W - 70); + return ( + + {lines && + (["p50", "p85", "p95"] as const).map((k) => { + const v = lines[k]; + if (v == null) return null; + return ( + + + {`${k} ${dur(v)}`} + + ); + })} + {merged.map((m, i) => + m.coderhelm ? ( + + {`${m.key} ${m.title}: ${durLong(m.cycle_secs)}, CoderHelm's`} + + ) : ( + + {`${m.key} ${m.title}: ${durLong(m.cycle_secs)}, a person's`} + + ), + )} + + ); +} diff --git a/dashboard/src/app/prs/overview/model.ts b/dashboard/src/app/prs/overview/model.ts new file mode 100644 index 00000000..c4fe9458 --- /dev/null +++ b/dashboard/src/app/prs/overview/model.ts @@ -0,0 +1,185 @@ +// The Pull requests overview's words and pure helpers: one look per stage and +// per repo health (a label, a tone and a shape, never colour alone), the +// compact durations, where each number links, and what the backend said it +// can't give yet. The server computes every number; nothing here derives one. + +import type { OverviewLink, OverviewMissing, PrStage, PrsOverview, RepoHealth } from "@/lib/api"; +import type { Shape, Tone } from "@/components/list/status"; + +export interface Look { + label: string; + short: string; + tone: Tone; + shape: Shape; +} + +/** The six stages, in the strip's order. */ +export const STAGES: (Look & { stage: PrStage })[] = [ + { stage: "draft", label: "Draft", short: "Draft", tone: "muted", shape: "ring" }, + { stage: "first_review", label: "Waiting for first review", short: "First review", tone: "waiting", shape: "diamond" }, + { stage: "in_review", label: "In review", short: "In review", tone: "attention", shape: "return" }, + { stage: "blocked", label: "Blocked", short: "Blocked", tone: "danger", shape: "triangle" }, + { stage: "coderhelm_working", label: "CoderHelm working", short: "CoderHelm", tone: "live", shape: "hexagon" }, + { stage: "approved", label: "Approved, not merged", short: "Approved", tone: "success", shape: "check" }, +]; + +export function stageLook(stage: string): Look { + return STAGES.find((s) => s.stage === stage) ?? { label: stage, short: stage, tone: "neutral", shape: "square" }; +} + +/** + * One fill per stage for the mix bar. Each segment also carries its stage in + * words (its title and the legend's shapes), so no reader needs the colour. + */ +export const STAGE_FILL: Record = { + draft: "bg-zinc-600", + first_review: "bg-amber-400", + in_review: "bg-orange-400", + blocked: "bg-red-400", + coderhelm_working: "bg-sky-400", + approved: "bg-emerald-400", +}; + +/** The ordered health scale, with "quiet" its own grey state. */ +export const HEALTH: Record = { + healthy: { label: "Healthy", short: "Healthy", tone: "success", shape: "check", rank: 1 }, + at_risk: { label: "At risk", short: "At risk", tone: "waiting", shape: "diamond", rank: 2 }, + slipping: { label: "Slipping", short: "Slipping", tone: "danger", shape: "triangle", rank: 3 }, + quiet: { label: "Quiet", short: "Quiet", tone: "muted", shape: "ring", rank: 0 }, +}; + +export function healthLook(h: string): Look & { rank: number } { + return HEALTH[h as RepoHealth] ?? { label: h, short: h, tone: "neutral", shape: "square", rank: 0 }; +} + +/** "45s", "6m", "19h", "3.1d", "14d": one compact duration. */ +export function dur(secs: number | null | undefined): string { + if (secs == null || !Number.isFinite(secs)) return ""; + const s = Math.max(0, secs); + if (s < 60) return `${Math.round(s)}s`; + if (s < 3600) return `${Math.round(s / 60)}m`; + if (s < 86_400) return `${Math.round(s / 3600)}h`; + const d = s / 86_400; + return d < 10 ? `${(Math.round(d * 10) / 10).toString()}d` : `${Math.round(d)}d`; +} + +/** "3.1 days", "19 hours": the long form for screen readers and titles. */ +export function durLong(secs: number | null | undefined): string { + if (secs == null || !Number.isFinite(secs)) return ""; + const s = Math.max(0, secs); + const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; + if (s < 3600) return plural(Math.max(1, Math.round(s / 60)), "minute"); + if (s < 86_400) return plural(Math.round(s / 3600), "hour"); + const d = Math.round((s / 86_400) * 10) / 10; + return `${d} day${d === 1 ? "" : "s"}`; +} + +/** "58%". */ +export function pct(share: number | null | undefined): string { + if (share == null || !Number.isFinite(share)) return ""; + return `${Math.round(share * 100)}%`; +} + +/** "+6", "-2", "0": a week-over-week change in neutral words. */ +export function signed(n: number | null | undefined): string { + if (n == null) return ""; + return n > 0 ? `+${n}` : n < 0 ? `−${Math.abs(n)}` : "0"; +} + +export interface Scope { + org: string; + repo: string; +} + +/** The query string of a scope: org, then repo. */ +function scopeQuery(scope: Scope): URLSearchParams { + const q = new URLSearchParams(); + if (scope.org) q.set("org", scope.org); + if (scope.repo) q.set("repo", scope.repo); + return q; +} + +/** Where a link goes: the list with its filter in the scope, the overview, or GitHub. */ +export function hrefOf(link: OverviewLink | null | undefined, scope: Scope): string | null { + if (!link) return null; + if (link.github) return link.github; + if (link.overview !== undefined) { + const q = new URLSearchParams(link.overview); + const out = scopeQuery({ org: scope.org || (q.get("repo") ?? "").split("/")[0], repo: "" }); + for (const [k, v] of q) out.set(k, v); + const s = out.toString(); + return `/prs/overview${s ? `?${s}` : ""}`; + } + if (link.list !== undefined) { + const q = scopeQuery(scope); + for (const [k, v] of new URLSearchParams(link.list)) q.set(k, v); + const s = q.toString(); + return `/prs${s ? `?${s}` : ""}`; + } + return null; +} + +/** The list with one pull request's detail open. */ +export function prHref(key: string, scope: Scope): string { + const q = scopeQuery(scope); + q.set("pr", key); + return `/prs?${q.toString()}`; +} + +export function isExternal(href: string): boolean { + return /^https?:\/\//.test(href); +} + +/** What the backend said it can't give for this path (or anything under it). */ +export function missingFor(o: PrsOverview | null, path: string): OverviewMissing | undefined { + return (o?.missing ?? []).find((m) => m.path === path || m.path.startsWith(`${path}.`)); +} + +/** "Not enough history yet" or "Not recorded yet": the short words for a gap. */ +export function gapWords(m: OverviewMissing | undefined): string { + return m?.reason === "not_recorded" ? "Not recorded yet" : "Not enough history yet"; +} + +/** The window in words: "Last 7 days vs the 8 weeks before". */ +export function windowWords(win: string): string { + const days = Number.parseInt(win, 10) || 7; + return `Last ${days} days vs the 8 weeks before`; +} + +export const WINDOWS = [ + { value: "7d", label: "Last 7 days" }, + { value: "14d", label: "Last 14 days" }, + { value: "28d", label: "Last 28 days" }, +]; + +/** "Sun Jan 11, 09:12": the one readable date and time, with its weekday. */ +export function when(iso: string | null | undefined): string { + if (!iso) return ""; + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return ""; + const day = d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" }).replace(/,/g, ""); + const time = d.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }); + return `${day}, ${time}`; +} + +/** "Sun Jan 4": a day with its weekday. */ +export function dayWords(iso: string | null | undefined): string { + if (!iso) return ""; + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return ""; + return d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" }).replace(/,/g, ""); +} + +/** "3h 10m", "2d 3h": a span of time, two units at most. */ +export function span(secs: number | null | undefined): string { + if (secs == null) return ""; + if (secs < 3600) return `${Math.round(secs / 60)}m`; + if (secs < 86_400) { + const h = Math.floor(secs / 3600); + const m = Math.round((secs % 3600) / 60); + return m ? `${h}h ${m}m` : `${h}h`; + } + const d = Math.floor(secs / 86_400); + const h = Math.round((secs % 86_400) / 3600); + return h ? `${d}d ${h}h` : `${d}d`; +} diff --git a/dashboard/src/app/prs/overview/page.tsx b/dashboard/src/app/prs/overview/page.tsx new file mode 100644 index 00000000..d5cf4be8 --- /dev/null +++ b/dashboard/src/app/prs/overview/page.tsx @@ -0,0 +1,997 @@ +"use client"; + +import Link from "next/link"; +import { Suspense, useCallback, useEffect, useRef, useState, type ReactNode } from "react"; +import { api, ApiError, type OverviewLink, type OverviewMissing, type PrsOverview, type SummaryPart, type SummaryTile } from "@/lib/api"; +import { RoleGuard } from "@/components/role-guard"; +import { cardClass, Page, PageHeader } from "@/components/page"; +import { ListError, ShapeIcon, useListParams } from "@/components/list"; +import { TONES } from "@/components/list/status"; +import { Select } from "@/components/select"; +import { Skeleton } from "@/components/skeleton"; +import { EmptyState } from "@/components/empty-state"; +import { ChevronRightIcon } from "@/components/icons"; +import { focusRing, linkButton } from "@/components/ui"; +import { AnyLink, Card, NotYet } from "./parts"; +import { EventsPanel, FailuresPanel, phoneSentences, ReviewPanel, SecurityPanel, StalePanel } from "./panels"; +import { AgingChart, CycleScatter, MixBar, MixLegend, QueueFlow, Sparkline, StageFlow, type Brushed } from "./charts"; +import { + dur, + durLong, + gapWords, + healthLook, + hrefOf, + isExternal, + missingFor, + pct, + prHref, + type Scope, + signed, + stageLook, + STAGES, + WINDOWS, + when, + dayWords, + span, +} from "./model"; + +export default function OverviewGuarded() { + return ( + + }> + + + + ); +} + +/** How often the overview is read again while the tab is visible. */ +const POLL_MS = 60_000; + +function Overview() { + const [params, setParams] = useListParams({ org: "", repo: "", window: "7d" }); + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [notServed, setNotServed] = useState(false); + const gen = useRef(0); + const scope: Scope = { org: params.org || data?.scope.org || "", repo: params.repo }; + + const load = useCallback( + (quiet = false) => { + const g = ++gen.current; + if (!quiet) setLoading(true); + return api + .prsOverview({ org: params.org, repo: params.repo, window: params.window }) + .then((d) => { + if (g !== gen.current) return; + setData(d); + setError(null); + setNotServed(false); + }) + .catch((e) => { + if (g !== gen.current) return; + if (e instanceof ApiError && (e.status === 404 || e.status === 405)) setNotServed(true); + else if (!quiet) setError(e instanceof Error ? e.message : String(e)); + }) + .finally(() => { + if (g === gen.current) setLoading(false); + }); + }, + [params.org, params.repo, params.window], + ); + + useEffect(() => { + load(); + }, [load]); + + useEffect(() => { + if (notServed) return; + const id = window.setInterval(() => { + if (document.visibilityState === "visible") load(true); + }, POLL_MS); + return () => window.clearInterval(id); + }, [load, notServed]); + + const header = ( + + ); + + if (notServed) { + return ( + + {header} +
+ + This install's CoderHelm doesn't summarize pull requests yet. Until it updates, the{" "} + + list + {" "} + shows every open pull request and whose turn it is. + +
+
+ ); + } + + return ( + + {header} + setParams(p)} /> + {error && !data ? ( +
+ load()} details={error} /> +
+ ) : loading && !data ? ( + + ) : data && data.open === 0 && data.history.merged_90d === 0 && data.repos.every((r) => r.health === "quiet") ? ( +
+ + CoderHelm hasn't seen a pull request in {scope.repo || scope.org || "your repos"} yet. As soon as one opens, it shows here with how long it has waited and on whom. + +
+ ) : data ? ( + + ) : null} +
+ ); +} + +/** Org, repo and window, carried in the address; and when it was read. */ +function Controls({ + data, + params, + onPick, +}: { + data: PrsOverview | null; + params: { org: string; repo: string; window: string }; + onPick: (p: Partial<{ org: string; repo: string; window: string }>) => void; +}) { + const orgs = data?.scope.orgs ?? (data?.scope.org ? [data.scope.org] : []); + const org = params.org || data?.scope.org || ""; + const repos = (data?.repos ?? []).map((r) => r.repo); + const sources = (data?.sources ?? []).filter((s) => s.read !== "ok"); + return ( +
+ {orgs.length > 1 && ( + onPick({ repo: v === "__all" ? "" : v, org })} + options={[ + { value: "__all", label: `Repos: all ${data?.scope.repos ?? ""}`.trim() }, + ...(params.repo && !repos.includes(params.repo) ? [params.repo] : repos).map((r) => ({ value: r, label: r })), + ]} + /> + setKind(v === "__all" ? "" : v)} + options={[{ value: "__all", label: "All kinds" }, ...kinds.map((k) => ({ value: k, label: KIND_WORDS[k] ?? k }))]} + /> + ) : undefined + } + > + {o.events == null ? ( + + ) : shown.length === 0 ? ( +

Nothing notable: no red main past its usual length, no reverts, bypasses, SLA breaches, new flaky checks or stopped runs.

+ ) : ( +
    + {shown.map((e, i) => ( +
  1. + {when(e.at)} + {e.repo.split("/")[1]} + + + = 3 ? "triangle" : e.severity === 2 ? "diamond" : "ring"} tone={e.severity >= 3 ? "danger" : e.severity === 2 ? "waiting" : "neutral"} live={false} /> + {KIND_WORDS[e.kind] ?? e.kind} + {" "} + + {e.text} + + +
  2. + ))} +
+ )} + + ); +} + +/** One sentence per panel for the phone, each opening its panel. */ +export function phoneSentences(o: PrsOverview): Record<"stale" | "failures" | "review" | "security" | "events", ReactNode> { + const st = o.stale; + const f = o.failures; + const r = o.review; + const s = o.security; + return { + stale: st.stale != null ? `Stale: ${st.stale} idle${st.abandoned ? `, ${st.abandoned.count} abandoned?` : ""}${st.zombie ? `, ${st.zombie} zombie` : ""}` : "Stale: not enough history yet", + failures: f.main_red || f.flaky ? `Failures: ${f.main_red && f.main_red.secs > 0 ? `main red ${span(f.main_red.secs)}` : "main green"}${f.flaky?.new ? `, ${f.flaky.new} new flaky` : ""}${f.reverts?.count ? `, ${f.reverts.count} revert${f.reverts.count === 1 ? "" : "s"}` : ""}` : "Failures: not enough history yet", + review: r.coverage ? `Review: ${r.coverage.human} of ${r.coverage.merged} human-approved, AI only ${r.coverage.ai_only}, none ${r.coverage.none}` : "Review: not enough history yet", + security: s.past_sla ? `Security: ${s.past_sla.length} past SLA${s.bypasses ? `, ${s.bypasses.count} bypass${s.bypasses.count === 1 ? "" : "es"}` : ""}` : "Security: not recorded yet", + events: `Events: ${(o.events ?? []).length} this week`, + }; +} diff --git a/dashboard/src/app/prs/overview/parts.tsx b/dashboard/src/app/prs/overview/parts.tsx new file mode 100644 index 00000000..aa326d21 --- /dev/null +++ b/dashboard/src/app/prs/overview/parts.tsx @@ -0,0 +1,63 @@ +"use client"; + +// Small pieces the overview's sections share: a titled card, a link that +// goes wherever an overview link points, the "not enough history yet" words, +// and one labeled number. + +import Link from "next/link"; +import type { ReactNode } from "react"; +import type { OverviewLink, OverviewMissing } from "@/lib/api"; +import { cardClass } from "@/components/page"; +import { focusRing } from "@/components/ui"; +import { gapWords, hrefOf, isExternal, type Scope } from "./model"; + +export function AnyLink({ link, scope, children, className = "", testId }: { link: OverviewLink | null | undefined; scope: Scope; children: ReactNode; className?: string; testId?: string }) { + const href = hrefOf(link, scope); + if (!href) return {children}; + if (isExternal(href)) + return ( + + {children} + + ); + return ( + + {children} + + ); +} + +/** "Not enough history yet", with the reason the backend gave. */ +export function NotYet({ m, className = "" }: { m: OverviewMissing | undefined; className?: string }) { + return ( + + {gapWords(m)} + + ); +} + +export function Card({ title, aside, children, testId, id }: { title: ReactNode; aside?: ReactNode; children: ReactNode; testId?: string; id: string }) { + return ( +
+
+

+ {title} +

+ {aside &&
{aside}
} +
+ {children} +
+ ); +} + +export function Metric({ label, value, note, m }: { label: string; value: string | null; note?: string; m?: OverviewMissing }) { + return ( +
+
{label}
+
+ {value ?? } + {note && {note}} +
+
+ ); +} diff --git a/dashboard/src/app/prs/page.tsx b/dashboard/src/app/prs/page.tsx index 7f636981..e68a8844 100644 --- a/dashboard/src/app/prs/page.tsx +++ b/dashboard/src/app/prs/page.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { api, ApiError, type PrBackfill, type PrRow, type PrsPage, type PrsQuery, type PrTurn } from "@/lib/api"; +import { api, ApiError, type PrBackfill, type PrRow, type PrsPage, type PrsQuery, type PrStage, type PrTurn } from "@/lib/api"; import { RoleGuard } from "@/components/role-guard"; import { Page, PageHeader } from "@/components/page"; import { @@ -89,7 +89,7 @@ function typing(e: KeyboardEvent): boolean { const rowId = (key: string) => `pr-row-${key.replace(/[^A-Za-z0-9_-]/g, "-")}`; function PrsPage() { - const [params, setParams] = useListParams({ org: "", repo: "", turn: "", state: "", person: "", q: "", view: "", pr: "" }); + const [params, setParams] = useListParams({ org: "", repo: "", turn: "", state: "", person: "", q: "", view: "", stage: "", past: "", pr: "" }); const phone = usePhone(); const split = useSplit(); const [page, setPage] = useState(null); @@ -117,9 +117,11 @@ function PrsPage() { person: params.person, q: params.q, view: isView(params.view) ? params.view : "", + stage: isStage(params.stage) ? params.stage : "", + past: params.past === "p85" || params.past === "p95" ? params.past : "", limit: PAGE_SIZE, }), - [params.org, params.repo, params.turn, params.state, params.person, params.q, params.view], + [params.org, params.repo, params.turn, params.state, params.person, params.q, params.view, params.stage, params.past], ); const gen = useRef(0); @@ -196,7 +198,12 @@ function PrsPage() { .finally(() => setLoadingMore(false)); }; - const rows = useMemo(() => [...(page?.prs ?? []), ...more], [page, more]); + // The overview's filters. A backend that doesn't filter by stage yet still + // gets the rows narrowed here, from the stage each row carries. + const rows = useMemo(() => { + const all = [...(page?.prs ?? []), ...more]; + return isStage(params.stage) ? all.filter((r) => !r.stage || r.stage === params.stage) : all; + }, [page, more, params.stage]); const groups = useMemo(() => groupByTurn(rows), [rows]); const viewer = page?.viewer ?? null; const counts = page?.counts ?? {}; @@ -265,8 +272,8 @@ function PrsPage() { return () => document.removeEventListener("keydown", onKey); }, [order, focusKey, focusRow, openPr, closePr, params.pr, split]); - const filtered = !!(params.turn || params.state || params.person || params.q || params.view); - const clear = () => setParams({ turn: "", state: "", person: "", q: "", view: "" }); + const filtered = !!(params.turn || params.state || params.person || params.q || params.view || params.stage || params.past); + const clear = () => setParams({ turn: "", state: "", person: "", q: "", view: "", stage: "", past: "" }); const scopeLabel = params.repo || params.org || "every repo"; const detailOpen = !!open; const overlay = detailOpen && !split; @@ -308,6 +315,8 @@ function PrsPage() { setParams({ turn: params.turn === t ? "" : t, view: "" })} /> + setParams({ [k]: "" })} /> + setParams({ q }, { replace: true }), placeholder: "Search titles, repos, numbers, people", label: "Search pull requests" }} @@ -445,6 +454,49 @@ function History({ backfill }: { backfill: PrBackfill[] }) { ); } +const STAGE_WORDS: Record = { + draft: "Draft", + first_review: "Waiting for first review", + in_review: "In review", + blocked: "Blocked", + coderhelm_working: "CoderHelm working", + approved: "Approved, not merged", +}; + +function isStage(v: string): v is PrStage { + return v in STAGE_WORDS; +} + +/** The filters the overview opens the list with, each one clearable. */ +function OverviewFilters({ stage, past, onClear }: { stage: string; past: string; onClear: (k: "stage" | "past") => void }) { + const chips: { k: "stage" | "past"; text: string }[] = []; + if (isStage(stage)) chips.push({ k: "stage", text: `Stage: ${STAGE_WORDS[stage]}` }); + if (past === "p85" || past === "p95") chips.push({ k: "past", text: `Open past the ${past}` }); + if (chips.length === 0) return null; + return ( +
+ + From the overview + + {chips.map((c) => ( + + ))} +
+ ); +} + /** The scope as a trail that is also the address: All orgs, then the org, then the repo. Each step is a switcher. */ function Scope({ org, diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index 35ee89cf..e8d4f113 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -1494,6 +1494,18 @@ export const api = { /** One pull request: the path to merge, the wait ledger and the timeline. */ getPr: (repo: string, number: number) => request(`/api/prs/detail?repo=${encodeURIComponent(repo)}&number=${number}`), + /** + * The state of the org's pull requests in one answer: the written summary, + * the stage strip, the aging dots, the repos and review load, and + * CoderHelm's part. Computed facts only; a 404 means this backend doesn't + * serve it yet. + */ + prsOverview: (q: { org?: string; repo?: string; window?: string } = {}) => { + const params = new URLSearchParams(); + for (const [k, v] of Object.entries(q)) if (v) params.set(k, v); + const s = params.toString(); + return request(`/api/prs/overview${s ? `?${s}` : ""}`); + }, /** A repo's open pull requests, most recently updated first (read from GitHub through the app). */ listOpenPrs: (repo: string) => request<{ prs?: OpenPr[] }>(`/api/reviewer/open-prs?repo=${encodeURIComponent(repo)}`).then((r) => r.prs ?? []), @@ -2303,6 +2315,10 @@ export interface PrsQuery { person?: string; q?: string; view?: PrView | ""; + /** One of the overview's six stages. */ + stage?: PrStage | ""; + /** Open past the scope's cycle-time percentile: `p85` or `p95`. */ + past?: "p85" | "p95" | ""; limit?: number; cursor?: string; } @@ -2366,6 +2382,10 @@ export interface PrRow { updated_at?: string; state: PrState | string; state_label?: string; + /** The overview's stage; null once merged or closed. */ + stage?: PrStage | string | null; + /** Left draft, else created: every age starts here. */ + ready_at?: string | null; turn: PrTurn | string; next: PrNext; /** stale, stacked, agent_authored, large */ @@ -2420,6 +2440,281 @@ export interface PrsPage { backfill?: PrBackfill[]; } +/** The six stages of an open pull request, in the strip's order. */ +export type PrStage = "draft" | "first_review" | "in_review" | "blocked" | "coderhelm_working" | "approved"; + +/** Where a number goes: the list with a filter, the overview with a scope, or GitHub for closed work. */ +export interface OverviewLink { + list?: string; + overview?: string; + github?: string; +} + +/** A metric the backend can't give yet, and why. Nothing is estimated in its place. */ +export interface OverviewMissing { + path: string; + /** `history`: the store is younger than the comparison; `not_recorded`: not stored yet. */ + reason: "history" | "not_recorded" | string; + text: string; +} + +export interface OverviewPercentiles { + p50: number; + p85: number; + p95?: number; +} + +export interface OverviewStripCell { + stage: PrStage | string; + label: string; + count: number; + delta: number | null; + spark: number[] | null; + past_p85: number | null; + link: OverviewLink; +} + +export interface OverviewDot { + key: string; + repo: string; + number: number; + title: string; + stage: PrStage | string; + state: string; + state_label: string; + age_secs: number; + coderhelm: boolean; + /** Who wrote it: a person, CoderHelm, or another bot (Dependabot and the like). */ + author_type?: "person" | "coderhelm" | "bot"; + band: "p50" | "p85" | "p95" | null; + /** The turn-holder has taken no human action for longer than the stage's p85 (drawn hollow). */ + idle?: boolean; + /** Its required checks fail on the same check that fails on main (drawn with a ring). */ + main_blocked?: boolean; +} + +/** The ordered scale, with Quiet its own grey state. */ +export type RepoHealth = "healthy" | "at_risk" | "slipping" | "quiet"; + +export interface OverviewRepo { + repo: string; + open: number; + stages: Partial>; + past_p85: number; + past_p85_delta: number | null; + first_review: OverviewPercentiles | null; + arrivals: number; + merges: number; + spark: number[] | null; + oldest_secs: number | null; + reworked: number | null; + /** Idle past the stage p85, and abandoned candidates. */ + stale?: number | null; + abandoned?: number | null; + /** Human-approved share of merges, 7 days; null under 10 merges. */ + human_reviewed?: number | null; + human_reviewed_delta?: number | null; + /** First required-check rollup green on the first head, no rerun; null under 10 PRs. */ + ci_first_try?: number | null; + /** Hours (in seconds) the default branch's required checks sat red this week; null when not recorded. */ + main_red_secs?: number | null; + reverts?: number | null; + large_share?: number | null; + security_past_sla?: { count: number; worst: "critical" | "high" | "medium" | "low" } | null; + bypasses_unreviewed?: number | null; + /** Short words for what drove the health word: "2 crit past SLA", "main red 3h". */ + flags?: string[]; + health: RepoHealth | string; + why: string; + inherited: boolean; + link: OverviewLink; +} + +/** One part of a summary line: words, or a number that comes from a fact and links to what produced it. */ +export type SummaryPart = { t: string } | { n: number; unit?: "count" | "secs" | "share"; fact: string; link: OverviewLink }; + +export interface SummaryLine { + /** The fact the line is written from. */ + fact: string; + parts: SummaryPart[]; +} + +/** One "Needs attention" item: a specific pull request or a group of them, with its owner (an item's owner, never a count per person) and age. */ +export interface SummaryItem extends SummaryLine { + rank: number; + /** Who owns the item: a team or CODEOWNERS entry, or a GitHub login only as the owner of that one item. */ + owner: string | null; + owner_kind?: "person" | "team" | "codeowners" | null; + /** Why there is no owner: "no reviewer assigned", "several repos". */ + owner_note?: string | null; + age_secs: number | null; + link: OverviewLink; +} + +export interface SummaryTile { + /** The three fixed tiles: stale, failures, reviewed. */ + fact: "stale" | "failures" | "reviewed" | string; + label: string; + value: number | null; + unit: "count" | "secs" | "share"; + delta: number | null; + /** What the delta is against, in words: "was 95%", "+4". */ + delta_words?: string | null; + /** A second number in the same tile (Failures: reverts beside main red time). */ + second?: { value: number; unit: "count" | "secs" | "share"; label: string; link: OverviewLink } | null; + link: OverviewLink; +} + +/** + * The summary block: a verdict, up to three numbers each with its change, up + * to five ranked items that need attention, what changed, and the stability + * and CoderHelm lines (always there, failures included). Every number in it + * comes from `facts`; a quiet week says what was checked. + */ +export interface OverviewSummary { + window: { from: string; to: string }; + computed_at: string; + verdict: { state: "healthy" | "at_risk" | "slipping" | "quiet"; word: string; parts: SummaryPart[]; rule: string }; + tiles: SummaryTile[]; + attention: SummaryItem[]; + /** More items past the five shown, in the list. */ + more: { count: number; link: OverviewLink } | null; + quiet: { repos: number; open: number; parts: SummaryPart[] } | null; + changed: SummaryLine | null; + stability: SummaryLine; + coderhelm: SummaryLine & { link: OverviewLink }; + /** How the block was made, for "view source". */ + method: string; +} + +export interface OverviewFact { + id: string; + kind: string; + scope: string; + value: number; + prev?: number | null; + delta?: number | null; + unusual?: boolean; + weight: number; + link: OverviewLink; +} + +export interface PrsOverview { + scope: { org: string | null; repo: string | null; window: string; vs: string; repos: number; repos_read: number; orgs?: string[] }; + synced_at?: string | null; + generated_at?: string | null; + history: { + days: number; + weeks: number; + young: boolean; + merged_90d: number; + since?: string | null; + /** Merged and closed PRs read back from GitHub at install, every author's, under the shared budget. */ + backfill?: { repos: number; repos_read: number; done: boolean; days: number; held?: boolean } | null; + }; + thresholds: { + scope: "org" | "repo" | string; + inherited: boolean; + min_merged: number; + min_weeks: number; + external: boolean; + cycle: OverviewPercentiles | null; + first_review: OverviewPercentiles | null; + bands: { key: string; label: string; secs: number; source: string }[]; + rule: string; + }; + open: number; + drafts: number; + strip: OverviewStripCell[]; + turns: { person: number; coderhelm: number; machines: number; nobody: number }; + /** The staleness states over the same open PRs. Null when not computable yet (see `missing`). */ + conditions: { + stale: { count: number; delta: number | null; author: number; reviewer: number } | null; + abandoned: number | null; + zombie: number | null; + high_drift: number | null; + blocked_by_main: number | null; + }; + needs_decision: { count: number; oldest_secs: number | null; link: OverviewLink }; + aging: { dots: OverviewDot[]; total: number; shown: number }; + repos: OverviewRepo[]; + rollup: { health: RepoHealth | string; repo: string | null; rule: string }; + review: { + flow: { week: string; requests: number; done: number }[] | null; + gap: number | null; + concentration: { top_share: number | null; reviewers: number; delta: number | null; where: { repo: string; share: number }[] | null }; + depth: { merged_without_review: number | null; rubber_stamp: number | null; median_size: number | null; median_size_delta: number | null }; + /** Merged PRs in exactly one coverage state, 7 days. */ + coverage: { merged: number; human: number; ai_only: number; non_owner: number; bypass: number; none: number } | null; + first_review_human: OverviewPercentiles | null; + first_review_any: OverviewPercentiles | null; + /** Share per size bucket; null under 10 qualifying PRs. */ + rubber_stamp_by_size: { small: number | null; medium: number | null; large: number | null } | null; + queue: { under_4h: number; h4_24: number; d1_3: number; over_3d: number } | null; + single_reviewer_paths: { repo: string; path: string }[] | null; + funnel: { raised: number; acknowledged: number; changed: number; verified: number; incorrect: number } | null; + }; + stale: { + /** The headline: open, not draft or blocked, the turn-holder idle past the stage p85. Equals the Stale tile. */ + stale: number | null; + /** A second measure, labeled apart: age since ready past the cycle-time p85, moving or not. */ + past_usual: number | null; + on_author: number | null; + on_reviewer: number | null; + abandoned: { count: number; oldest_secs: number | null } | null; + zombie: number | null; + drift: { key: string; overlapping: number }[] | null; + draft_p85_secs: number | null; + archive_candidates: number | null; + }; + failures: { + ci_first_try: { share: number | null; lo: number | null; hi: number | null; n: number } | null; + ci_fail_rate: { share: number | null; n: number } | null; + flaky: { count: number; new: number; top: { check: string; repo: string; retries: number }[] } | null; + main_red: { episodes: number; secs: number; repo: string | null; mean_to_green_secs: number | null } | null; + reverts: { count: number; coderhelm: number; coderhelm_merged: number; people: number; people_merged: number } | null; + /** Merged PRs later reverted or hotfixed, 30 days; null under 10 merges. */ + proxy: number | null; + suspects: { kind: "hotfix" | "incident"; target: string; by: string; reason: string }[] | null; + queue_p95_secs: number | null; + }; + security: { + sla_days: { critical: number; high: number; medium: number; low: number }; + open: { critical: number; high: number; medium: number; low: number } | null; + past_sla: { key: string; severity: string; age_secs: number }[] | null; + bypasses: { count: number; reviewed_after: number } | null; + exempt_by_coderhelm: number | null; + no_human_approval: { total: number; person: number; coderhelm: number; bot: number } | null; + sensitive_without_owner: number | null; + dependency: { group: string; merge_rate: number | null; superseded: number | null }[] | null; + }; + /** Notable events this week, each kind behind its floor; at most 8 here. */ + events: { at: string; repo: string; kind: string; text: string; link: OverviewLink; severity: number }[] | null; + coderhelm: { + author: { opened: number; merged: number; closed_unmerged: number; open: number; merge_rate: number | null; p50_merge_secs: number | null; waiting_on_people: number | null; rule: string }; + fixer: { fixed: number; merged: number; closed_unmerged: number; open: number }; + reviewer: { reviewed: number; findings: { p0: number; p1: number; p2: number } | null; verified_rate: number | null; p50_first_look_secs: number | null }; + /** Every run ends in exactly one state. */ + runs: { first_try: number; after_fixes: number; rerun_only: number; gave_up: number; blocked: number; stopped: number; reasons: { reason: string; count: number }[] } | null; + exceptions: { + needs_decision: number; + oldest_secs: number | null; + reworked: { coderhelm: number; people: number; coderhelm_merged: number; people_merged: number } | null; + merges: { on_approval: number; own_authority: number; exempt?: number | null } | null; + cost_per_merged: number | null; + }; + }; + /** One repo's scope adds two time views: open PRs by stage per day (12 weeks), and merged PRs' cycle times. */ + repo_view?: { + flow: { day: string; stages: Partial> }[] | null; + merged: { key: string; number: number; title: string; cycle_secs: number; merged_at: string; coderhelm: boolean }[] | null; + } | null; + facts: OverviewFact[]; + summary: OverviewSummary; + missing: OverviewMissing[]; + sources?: PrSource[]; +} + export interface PrChecklistLine { key: string; mark: "done" | "waiting" | "blocked" | "none" | string; diff --git a/dashboard/src/lib/nav.ts b/dashboard/src/lib/nav.ts index d7901fc4..f28e6ba4 100644 --- a/dashboard/src/lib/nav.ts +++ b/dashboard/src/lib/nav.ts @@ -57,7 +57,17 @@ export const NAV_SECTIONS: NavSection[] = [ // Every open pull request in the installed repos, people's and CoderHelm's, // grouped by whose turn it is. Reading it is everyone's ("view"). Its key is // the phone bar's "prs" place. - { key: "prs", label: "Pull requests", icon: "prs", pages: [{ href: "/prs", label: "Pull requests", need: "view" }] }, + // The Overview (the org's state in one screen) comes first, so the menu + // lands there; the List is every pull request by whose turn it is. + { + key: "prs", + label: "Pull requests", + icon: "prs", + pages: [ + { href: "/prs/overview", label: "Overview", need: "view" }, + { href: "/prs", label: "List", need: "view" }, + ], + }, { key: "plans", label: "Plans", diff --git a/dashboard/src/lib/routes.ts b/dashboard/src/lib/routes.ts index c638b924..f14eaa98 100644 --- a/dashboard/src/lib/routes.ts +++ b/dashboard/src/lib/routes.ts @@ -32,6 +32,7 @@ export const ROUTES: Record = { "/inbox/answer": { label: "Answer", parent: "/inbox", detail: true, tab: "Answer CoderHelm", description: "Answer a question CoderHelm asked, on one screen, and let its run carry on." }, "/inbox/pr": { label: "Pull request", parent: "/inbox", detail: true, tab: "Approve or merge", description: "One pull request to approve or merge: what it does, its checks and CoderHelm's review first, then the diff." }, "/prs": { label: "Pull requests", description: "Every open pull request in your repos, people's and CoderHelm's: whose turn it is, what each one needs next and from whom, and its path to merge." }, + "/prs/overview": { label: "Overview", parent: "/prs", tab: "Pull requests overview", description: "Where your org's pull requests wait, for whom, and whether that is usual: a summary, open work by age, each repo's health, review and CoderHelm's part." }, "/runs/detail": { label: "Run", parent: "/", detail: true, description: "One run, step by step: from the ticket to the plan, the code, the tests and the pull request." }, "/setup": { label: "Setup", description: "Recommended settings for every repo: what CoderHelm found in each one, what it recommends and why, and the runs that applied them." }, diff --git a/docs/content/docs/getting-started/meta.json b/docs/content/docs/getting-started/meta.json index 341f80f0..20c52bdb 100644 --- a/docs/content/docs/getting-started/meta.json +++ b/docs/content/docs/getting-started/meta.json @@ -1,5 +1,5 @@ { "title": "Getting started", "defaultOpen": true, - "pages": ["index", "github", "atlassian", "setup", "first-run", "pull-requests", "reviewer", "stale-pull-requests", "review-fixes", "security-fixes", "infrastructure-vulnerabilities", "plans"] + "pages": ["index", "github", "atlassian", "setup", "first-run", "pull-requests", "pull-requests-overview", "reviewer", "stale-pull-requests", "review-fixes", "security-fixes", "infrastructure-vulnerabilities", "plans"] } diff --git a/docs/content/docs/getting-started/pull-requests-overview.mdx b/docs/content/docs/getting-started/pull-requests-overview.mdx new file mode 100644 index 00000000..ceec008e --- /dev/null +++ b/docs/content/docs/getting-started/pull-requests-overview.mdx @@ -0,0 +1,171 @@ +--- +title: Pull requests overview +description: One page for the state of your org's pull requests. It shows where open work waits, for whom, and whether that is usual for your org, with what stalled, what broke, whether review happened and what's past a deadline. +--- + +Open **Pull requests**. The **Overview** tab is the default and the **List** tab holds every pull request by whose turn it is. Pick an org, one repo or all of them, and a window (the last 7, 14 or 28 days). Each window is compared with the 8 weeks before it. + +The overview counts **every** pull request in your installed repos, whether a person, CoderHelm, Dependabot or another bot wrote it. CoderHelm's pull requests are one slice of the same numbers and appear in their own panel. + +![The overview for the acme org: the summary, the stage strip and the repo table](/images/pull-requests-overview/org-desktop.png) + +## How the numbers are made + +- **Thresholds come from your own history.** "Usual" means a percentile of your merged pull requests, never a number from another company. A repo uses its own percentiles once it has **30 merged pull requests in 90 days**. Until then it uses the org's, and the page says so. +- **Eight weeks before ranges.** A count is unusual when it falls outside the lowest and highest of its previous 8 weekly values. Until there are 8 weeks of history, the aging chart also shows two outside benchmarks as faint bands, labeled as external. +- **No rate on fewer than 10 events.** A share such as "human-reviewed" or "merge rate" is left blank when fewer than 10 pull requests stand behind it. +- **Nothing is estimated.** When CoderHelm doesn't hold the data a number needs, the page says **Not enough history yet** (it is collecting it) or **Not recorded yet** (it doesn't collect it yet). It never shows a zero it can't back. +- **No person is ranked.** No count, ranking or duration is ever shown per person. A name appears only as the owner of one item that needs attention, or in a pull request's own row in the list. + +When CoderHelm is first installed it reads your merged and closed pull requests back from GitHub, under the same hourly budget as everything else it does. Until that finishes, the page shows how far it has got, for example "12 of 40 repos read". + +## The summary + +![A slipping week for acme: the verdict, three tiles and what needs attention](/images/pull-requests-overview/org-summary-bad.png) + +The summary is written from computed facts with fixed sentences. Every number in it links to the pull requests it counts. **View source** lists the facts and the verdict rule. + +- **The verdict** is one of four words. + - **Slipping:** an obligation is breached, such as a critical security fix past its deadline or a bypass merge nobody reviewed afterwards. + - **At risk:** a headline number is outside its 8-week range in the bad direction. + - **Quiet:** merges are under a quarter of the 8-week median and nothing is past usual. + - **Healthy:** none of the above. + + The org takes the worst state of any repo holding 10% or more of the open pull requests, plus any obligation breach in any repo, so one tiny repo can't turn the org red but a single critical fix still counts. +- **Three tiles** stay the same every week, so you can compare them: + - **Stale** counts idle pull requests and matches the Stale panel's top line. + - **Failures** shows the time main was red and the reverts this week. + - **Reviewed** is the share of merges a person approved. +- **Needs attention** has at most five lines, ranked by severity and then age, each with an owner and an age. When a line has no owner it says why, for example "no reviewer assigned". +- **What changed** names the largest move since last week. A change is mentioned only when it is at least 2 and at least 10% of the week before, and a wait only past a day. +- **Stability** and **CoderHelm** lines always appear. CoderHelm's line starts with what it broke or is blocked on. + +A quiet week says what was checked: + +![A quiet week: nothing needs you, and the summary lists what it checked](/images/pull-requests-overview/org-summary-quiet.png) + +## Open now + +The strip splits open pull requests into six stages: **Draft**, **First review**, **In review**, **Blocked**, **CoderHelm working** and **Approved**, not merged. Each cell shows the count, the change since last week, an 8-week line and how many are past p85. Click a cell to open the list filtered to that stage. + +Under it, **Whose turn** splits the same pull requests by who moves next: people, CoderHelm, CI or the merge queue, or nobody. The **Condition** row overlays the staleness states below. + +The **aging chart** puts one mark per open pull request at its age since it was ready for review, on a log scale, with your p50, p85 and p95 cycle-time lines. The marks: + +- A circle is a person's pull request, a hexagon is CoderHelm's and a square is another bot's. +- A hollow mark is idle. +- A ring means it is blocked by a red main. + +Drag across a cluster, or press **Select past p85**, and the chart says what the selection has more of than the rest. Click a mark to open that pull request. + +## Every metric + +All durations start when a pull request is **ready for review**, which is when it leaves draft, or when it is created if it never was a draft. "Human" leaves out the author, CoderHelm and every other bot. Weekends count. + +| Metric | Definition | Threshold | +| --- | --- | --- | +| Open | Open pull requests that aren't drafts; drafts counted apart | Outside the 8-week range | +| Cycle time | Merged minus ready, over the last 90 days; shown as p50, p85, p95 | The source of every "past usual" line | +| Past usual | Open pull requests whose age is past the scope's p85 cycle time | A rising count against the 8-week range | +| Time to first review, people | First review by a person minus ready; p50 and p85 over 8 weeks | Your p85 | +| Time to first review, any reviewer | The same, counting CoderHelm and other bots | Shown beside the people's line, never instead of it | +| Arrivals and merges | Pull requests reaching ready, and merged, in the window | Arrivals above merges two weeks running | +| Merge rate | Merged / (merged + closed unmerged) for pull requests resolved in the window; open ones left out | Shown on 10 or more | +| Human-reviewed share | Merges a person other than the author approved / all merges | Below the 8-week range, on 10 or more merges | +| CI first try | The first required-check result on a pull request was green, with no rerun | Below the 8-week range, on 10 or more | +| Flaky check | A check that failed and then passed on the same commit, twice or more in 30 days | 10 or more runs | +| Reverts | Merged pull requests reverted within 14 days | Every one is listed | +| Merged PRs later reverted or hotfixed | (Reverted + hotfix suspects) / merged, 30 days, by author type | Labeled a proxy, not a DORA figure | +| Large PR share | Merges over 400 changed lines / merges | Above the 8-week range | +| Review concentration | Share of human reviews done by the busiest 20% of reviewers, 30 days | No names, ever | +| Review queue gap | Review requests made minus human reviews done, this week | Positive two weeks running | + +Hotfix and incident links are always labeled **suspect** with their reason, because tracing a fix back to the change that caused it is often wrong. + +## Stale states + +![The Stale panel for acme](/images/pull-requests-overview/org-panel-stale.png) + +Only people's actions reset a pull request's clock. Bot pushes, label changes and CI updates don't, so a pull request only bots touch can't look fresh. The author's clock (commits, replies) and the reviewers' clock (reviews, comments) are kept apart, and whose turn it is decides which one counts. + +| State | Meaning | +| --- | --- | +| **Stale** | Open, not a draft or blocked, and whoever holds the turn has done nothing for longer than the p85 time in that stage, with a floor of one day. This is the Stale tile. | +| **Stuck** | Can't merge without action: conflicts, a failing required check, a missing review, waiting on another pull request. This is the Blocked stage. | +| **Abandoned candidate** | No author action for longer than the p95 cycle time and at least 14 days, with a reviewer's change request unanswered. | +| **Zombie** | Open past the p95 cycle time, where only bots and CI have touched it lately. | +| **High drift** | Commits on main since it branched that touch its files, at or above the p85 at merge. | + +**Open past usual** is a second, different measure shown in the panel: it counts old pull requests whether or not anyone is acting on them. + +CoderHelm never closes an idle pull request. Archive candidates (idle 30 days or more) are counted so a team can decide what to do with them. + +## Failures and incidents + +![The Failures and incidents panel](/images/pull-requests-overview/org-panel-failures.png) + +Flaky checks are kept apart from real breaks, reruns never count as fixes, and CI queue time is shown on its own as capacity, never as a failure. CoderHelm's runs each end in exactly one state: green on the first try, green after fixes, green only on a rerun (flaky, not fixed), gave up, blocked, or stopped by a person, with the reason. + +## Review health + +![The Review health panel](/images/pull-requests-overview/org-panel-review.png) + +Each merge lands in exactly one of five **coverage states**: + +1. **Human-approved:** a person other than the author approved it. +2. **AI-reviewed only:** only CoderHelm or another bot approved it. AI review never counts as human review. +3. **Non-owner approval:** a person approved it but CODEOWNERS required an owner. +4. **Bypass or exemption:** it merged past a rule that still held it. +5. **No review:** nobody reviewed it. + +Quick approvals with no comment are measured by pull request size, because a silent approval on a 3-line change is fine and on a 600-line change it isn't. Load belongs to repos and paths, never to people. CoderHelm's own findings are a funnel: raised, acknowledged, changed and verified fixed on a later commit, with the ones dismissed as incorrect beside it. + +## Security and policy + +![The Security and policy panel](/images/pull-requests-overview/org-panel-security.png) + +Security fixes are measured against your org's deadlines. The defaults are **7 days for critical, 30 for high, 90 for medium and 180 for low**, and a vulnerability on the known-exploited list counts as critical. The panel shows: + +- open fixes by severity, and the oldest past its deadline; +- bypass merges, and whether anyone reviewed them afterwards; +- merges with no independent human approval, split by who wrote them; +- CoderHelm's own exempt merges and its merges without a person's approval. + +CoderHelm reports these about itself, because nothing else would. + +## This week's events + +![This week's events](/images/pull-requests-overview/org-panel-events.png) + +Only notable events appear, each behind its own floor, at most eight at a time and filterable by kind: + +- main red for longer than usual; +- reverts; +- bypass merges; +- security deadlines passed; +- new flaky checks; +- CoderHelm giving up or being stopped; +- rule and CODEOWNERS changes; +- repos coming online or going quiet. + +## One repo + +Click a repo to see the same overview for that repo alone. It adds the open pull requests by stage over 12 weeks, and the cycle time of every merged pull request against the same percentile lines. + +![The overview for one repo, acme/checkout](/images/pull-requests-overview/org-repo.png) + +## On a phone + +![The overview on a phone](/images/pull-requests-overview/org-phone.png) + +The summary comes first, then the stages as a grid, the pull requests past usual, one line per panel that opens it, and the repos. + +## Digest, nudges and alerts + +Everything that reaches people is **off until a team turns it on**, and nothing is sent yet. Turning these on comes in a later release, and this page will say where. When they arrive, this is how they behave: + +- **Weekly digest:** sent by Slack or email on Monday morning, to subscribers only. It carries the summary, the three largest changes since last week, the pull requests past p95 by repo, obligation breaches and CoderHelm's line. +- **Nudges:** turned on per team, and sent privately to whoever holds the turn. A pull request is nudged when it crosses its stage's p85, again two and four working days later, then never again. One with activity in the last working day is skipped. +- **Alerts for leaders:** a breached obligation, main red for longer than usual, a repo whose review queue is growing while its old pull requests are outside their range, or data that stopped updating for more than an hour. + +CoderHelm never closes an idle pull request on its own. diff --git a/docs/public/images/pull-requests-overview/org-desktop.png b/docs/public/images/pull-requests-overview/org-desktop.png new file mode 100644 index 00000000..8ec27f93 Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-desktop.png differ diff --git a/docs/public/images/pull-requests-overview/org-panel-events.png b/docs/public/images/pull-requests-overview/org-panel-events.png new file mode 100644 index 00000000..03e162fe Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-panel-events.png differ diff --git a/docs/public/images/pull-requests-overview/org-panel-failures.png b/docs/public/images/pull-requests-overview/org-panel-failures.png new file mode 100644 index 00000000..29fccf53 Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-panel-failures.png differ diff --git a/docs/public/images/pull-requests-overview/org-panel-review.png b/docs/public/images/pull-requests-overview/org-panel-review.png new file mode 100644 index 00000000..1fd905ad Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-panel-review.png differ diff --git a/docs/public/images/pull-requests-overview/org-panel-security.png b/docs/public/images/pull-requests-overview/org-panel-security.png new file mode 100644 index 00000000..4d604f02 Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-panel-security.png differ diff --git a/docs/public/images/pull-requests-overview/org-panel-stale.png b/docs/public/images/pull-requests-overview/org-panel-stale.png new file mode 100644 index 00000000..d5d96418 Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-panel-stale.png differ diff --git a/docs/public/images/pull-requests-overview/org-phone.png b/docs/public/images/pull-requests-overview/org-phone.png new file mode 100644 index 00000000..9d38d517 Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-phone.png differ diff --git a/docs/public/images/pull-requests-overview/org-repo.png b/docs/public/images/pull-requests-overview/org-repo.png new file mode 100644 index 00000000..cf7a5420 Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-repo.png differ diff --git a/docs/public/images/pull-requests-overview/org-summary-bad.png b/docs/public/images/pull-requests-overview/org-summary-bad.png new file mode 100644 index 00000000..1d320826 Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-summary-bad.png differ diff --git a/docs/public/images/pull-requests-overview/org-summary-quiet.png b/docs/public/images/pull-requests-overview/org-summary-quiet.png new file mode 100644 index 00000000..3394de88 Binary files /dev/null and b/docs/public/images/pull-requests-overview/org-summary-quiet.png differ diff --git a/docs/published-pages.json b/docs/published-pages.json index 89d814c9..fdb2ee1f 100644 --- a/docs/published-pages.json +++ b/docs/published-pages.json @@ -74,6 +74,7 @@ "/getting-started/infrastructure-vulnerabilities/", "/getting-started/jira/", "/getting-started/plans/", + "/getting-started/pull-requests-overview/", "/getting-started/pull-requests/", "/getting-started/review-fixes/", "/getting-started/reviewer/",