Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(changes): lead change records with what they did to code health (#4141)
Raghav Chamadiya47288d8b7eb9
diff --git a/docs/layers/CHANGES.md b/docs/layers/CHANGES.mdindex 37ef6a608..d13d9af0a 100644--- a/docs/layers/CHANGES.md+++ b/docs/layers/CHANGES.md@@ -79,7 +79,7 @@ with `REPOWISE_SEAM_CHANGE_METADATA`. See| Surface | Use ||---|---|| CLI | `repowise changes list [--category C] [--shape merge\|squash\|commit] [--grep TEXT]`, `repowise changes show REF [--format table\|json\|in-toto]` |-| REST | `GET /api/repos/{id}/changes` (filters `category`, `shape`, `q`, `needs_attention`, `author`, `area`, `since`, `until`, `delta`, `touches_hotspot`; `evidence=true` adds each row's kept checklist status counts), `GET /api/repos/{id}/changes/summary`, `GET /api/repos/{id}/changes/{change_id}` |+| REST | `GET /api/repos/{id}/changes` (filters `category`, `shape`, `q`, `needs_attention`, `author`, `area`, `since`, `until`, `delta`, `touches_hotspot`; `evidence=true` adds each row's kept checklist status counts, leaving out the health row since health leads from the commit rollup), `GET /api/repos/{id}/changes/summary`, `GET /api/repos/{id}/changes/{change_id}` || Web | Commits page, "By change" view: each change with its checklist's attention and unknown counts and a "Needs attention" filter; a detail page per change |Every row leads with `health`: its commits' stored health deltas summed (introduced, worsened, resolved, files worsened) and a `kind` of `improved`, `worsened`, `mixed` or `neutral`; `null` means no commit was scanned. The `delta` filter's `improved` and `worsened` each include `mixed`. `/changes/summary` counts a period's changes by kind, improvements first, and the detail adds the worse findings (file, lines, symbol, biomarker) behind the counts. `GET /api/repos/{id}/commits` carries the same `health_delta` per commit and takes the same filters, and `GET /api/repos/{id}/wins?since=&author=` lists findings resolved, files whose score rose and refactorings that landed.diff --git a/packages/core/src/repowise/core/changes/collect.py b/packages/core/src/repowise/core/changes/collect.pyindex 7cfd356ce..e5b758a86 100644--- a/packages/core/src/repowise/core/changes/collect.py+++ b/packages/core/src/repowise/core/changes/collect.py@@ -29,6 +29,7 @@ import structlogfrom repowise.core.changes.evidence import (EVIDENCE_SCHEMA_VERSION,+ SUMMARY_SKIPPED_KINDS,ChangeEvidence,EvidenceInputs,EvidenceItem,@@ -381,12 +382,18 @@ def cached_evidence(row: Any) -> ChangeEvidence | None:def evidence_summary(row: Any) -> dict[str, Any] | None:- """Status counts of the kept checklist, or ``None`` when none is kept."""+ """Status counts of the kept checklist, or ``None`` when none is kept.++ Kinds in ``SUMMARY_SKIPPED_KINDS`` are not counted, so the list's attention+ mark and the needs-attention filter agree on one set of rows.+ """evidence = cached_evidence(row)if evidence is None:return Nonecounts = {"generated_at": evidence.generated_at, "ok": 0, "attention": 0, "unknown": 0}for item in evidence.items:+ if item.kind in SUMMARY_SKIPPED_KINDS:+ continue# A status this reader does not know is not a pass.counts[item.status if item.status in ("ok", "attention") else "unknown"] += 1return countsdiff --git a/packages/core/src/repowise/core/changes/evidence.py b/packages/core/src/repowise/core/changes/evidence.pyindex b6aa6d763..5b0ebb6fa 100644--- a/packages/core/src/repowise/core/changes/evidence.py+++ b/packages/core/src/repowise/core/changes/evidence.py@@ -65,6 +65,11 @@ KINDS: tuple[str, ...] = ("outcomes",)+#: Kinds a checklist's status counts leave out. Health leads a change row from+#: its commits' stored deltas, so counting the checklist's own health row would+#: flag the same fact twice, from a second source.+SUMMARY_SKIPPED_KINDS: frozenset[str] = frozenset({"health_delta"})+@dataclass(frozen=True, slots=True)class EvidenceItem:diff --git a/packages/ui/__tests__/commits/findings-by-file.test.tsx b/packages/ui/__tests__/commits/findings-by-file.test.tsxnew file mode 100644index 000000000..86082b651--- /dev/null+++ b/packages/ui/__tests__/commits/findings-by-file.test.tsx@@ -0,0 +1,73 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import type { CommitHealthFinding } from "@repowise-dev/types/git";+import { groupFindingsByFile } from "../../src/commits/health-delta";+import { FindingsByFile } from "../../src/commits/findings-by-file";++const f = (path: string, symbol: string, line: number, over: Partial<CommitHealthFinding> = {}): CommitHealthFinding => ({+ change_kind: "introduced",+ dimension: "defect",+ biomarker_type: "complex_method",+ severity: "medium",+ path,+ symbol,+ line_start: line,+ attribution_basis: "added_lines",+ reason: `${symbol} is complex`,+ ...over,+});++describe("groupFindingsByFile", () => {+ it("keeps files in the order of their worst finding", () => {+ const groups = groupFindingsByFile([f("b.py", "x", 1), f("a.py", "y", 2), f("b.py", "z", 3)]);+ expect(groups.map((g) => [g.path, g.findings.length])).toEqual([+ ["b.py", 2],+ ["a.py", 1],+ ]);+ });+});++describe("FindingsByFile", () => {+ const findings = [+ f("src/one/mod.py", "run", 10),+ f("src/two/mod.py", "walk", 20, { attribution_basis: "touched_file" }),+ f("src/c.py", "c", 3),+ f("src/d.py", "d", 4),+ f("src/e.py", "e", 5),+ ];++ it("names each file by its shortest distinct path and each finding by symbol and line", () => {+ render(<FindingsByFile findings={findings} fileAction={(g) => <button>prompt {g.path}</button>} />);+ expect(screen.getByTitle("src/one/mod.py").textContent).toBe("one/mod.py");+ expect(screen.getByText("run · L10")).toBeTruthy();+ expect(screen.getByText(/file touched, not a line it wrote/)).toBeTruthy();+ expect(screen.getByText("prompt src/one/mod.py")).toBeTruthy();+ });++ it("folds files past the first three behind one disclosure", () => {+ render(<FindingsByFile findings={findings} />);+ expect(screen.getByText("Show 2 more files").closest("details")).toBeTruthy();+ expect(screen.getByTitle("src/e.py").closest("details")).toBeTruthy();+ expect(screen.getByTitle("src/c.py").closest("details")).toBeNull();+ });+});++describe("FindingsByFile attribution notes", () => {+ it("says where a moved finding came from rather than calling it a touched file", () => {+ render(+ <FindingsByFile+ findings={[+ f("pkg/new.py", "run", 4, {+ change_kind: "worsened",+ attribution_basis: "moved",+ moved_from: { path: "pkg/old.py", symbol: "run" },+ }),+ f("pkg/b.py", "walk", 9, { attribution_basis: "changed_call_edge" }),+ ]}+ />,+ );+ expect(screen.getByText(/moved here from run in pkg\/old\.py/)).toBeTruthy();+ expect(screen.getByText(/reached through a call it edited/)).toBeTruthy();+ expect(screen.queryByText(/file touched, not a line it wrote/)).toBeNull();+ });+});diff --git a/packages/ui/__tests__/commits/health-delta.test.tsx b/packages/ui/__tests__/commits/health-delta.test.tsxnew file mode 100644index 000000000..a5e5d5aa3--- /dev/null+++ b/packages/ui/__tests__/commits/health-delta.test.tsx@@ -0,0 +1,65 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { healthDeltaKind } from "../../src/commits/health-delta";+import { HealthDeltaMark } from "../../src/commits/health-delta-mark";++const d = (introduced: number, worsened: number, resolved: number, improved?: number | null) => ({+ introduced,+ worsened,+ resolved,+ improved,+});++describe("healthDeltaKind", () => {+ it("reads the counts", () => {+ expect(healthDeltaKind(d(0, 0, 0))).toBe("neutral");+ expect(healthDeltaKind(d(0, 0, 2))).toBe("improved");+ expect(healthDeltaKind(d(0, 0, 0, 1))).toBe("improved");+ expect(healthDeltaKind(d(1, 0, 0))).toBe("worsened");+ expect(healthDeltaKind(d(0, 1, 3))).toBe("mixed");+ });++ it("prefers the server's own kind", () => {+ expect(healthDeltaKind({ ...d(0, 0, 0), kind: "mixed" })).toBe("mixed");+ });+});++describe("HealthDeltaMark", () => {+ it("says a change was not compared rather than reading it as clean", () => {+ render(<HealthDeltaMark delta={null} />);+ expect(screen.getByText("Not yet analysed")).toBeTruthy();+ });++ it("colours only a real improvement green and a regression red", () => {+ const { container, rerender } = render(<HealthDeltaMark delta={d(0, 0, 3)} />);+ expect(screen.getByText("+3")).toBeTruthy();+ expect(container.innerHTML).toContain("--color-success");++ rerender(<HealthDeltaMark delta={d(2, 0, 0)} />);+ expect(screen.getByText("\u22122")).toBeTruthy();+ expect(container.innerHTML).toContain("--color-error");++ rerender(<HealthDeltaMark delta={d(1, 0, 3)} />);+ expect(screen.getByText("Mixed")).toBeTruthy();+ expect(container.innerHTML).not.toMatch(/--color-(success|error)/);+ });++ it("renders a neutral result quietly, with no dot or figure", () => {+ const { container } = render(<HealthDeltaMark delta={d(0, 0, 0)} labels={{ neutral: "Unchanged" }} />);+ expect(screen.getByText("Unchanged")).toBeTruthy();+ expect(container.querySelector(".rounded-full")).toBeNull();+ });++ it("names a partial comparison", () => {+ render(<HealthDeltaMark delta={{ ...d(1, 0, 0), status: "partial" }} />);+ expect(screen.getByText("Part of this change was not compared")).toBeTruthy();+ });++ it("shows a stale delta's direction without colour or counts", () => {+ const { container } = render(<HealthDeltaMark delta={{ ...d(2, 0, 0), stale: true }} />);+ expect(screen.getByText("Worse")).toBeTruthy();+ expect(screen.queryByText("−2")).toBeNull();+ expect(container.innerHTML).not.toContain("--color-error");+ expect(screen.getByText(/older analyzer/)).toBeTruthy();+ });+});diff --git a/packages/ui/__tests__/health/change-prompt.test.ts b/packages/ui/__tests__/health/change-prompt.test.tsnew file mode 100644index 000000000..b5c186e31--- /dev/null+++ b/packages/ui/__tests__/health/change-prompt.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import { buildChangeAiPrompt, changePromptFixes, type ChangePromptInput } from "../../src/health/ai-prompt-builder";++const base: ChangePromptInput = {+ label: "#7",+ title: "feat: x",+ head_sha: "a".repeat(40),+ commits: ["a".repeat(40), "b".repeat(40)],+ files: ["src/a.py"],+ findings: [],+ resolved: 0,+ complete: true,+ attention: [],+};++describe("buildChangeAiPrompt", () => {+ it("asks to fix what the change made worse, with file and line", () => {+ const text = buildChangeAiPrompt({+ change: {+ ...base,+ resolved: 2,+ findings: [+ {+ change_kind: "worsened",+ severity: "high",+ severity_before: "medium",+ path: "src/a.py",+ symbol: "run",+ line_start: 10,+ line_end: 40,+ reason: "run grew",+ sha: "c".repeat(40),+ },+ ],+ },+ });+ expect(text).toContain("## What this change made worse");+ expect(text).toContain("`src/a.py:10-40` in `run` (commit `cccccccccccc`)");+ expect(text).toContain("was medium");+ expect(text).toContain("resolved 2 existing findings");+ expect(text).toContain("git show aaaaaaaaaaaa; git show bbbbbbbbbbbb");+ });++ it("falls back to reviewing what the checklist flagged", () => {+ const text = buildChangeAiPrompt({+ change: { ...base, attention: ["Decisions crossed: 2 accepted"], complete: false },+ flavor: "claude-code-mcp",+ });+ expect(text).not.toContain("made worse");+ expect(text).toContain("- Decisions crossed: 2 accepted");+ expect(text).toContain("could not be compared");+ expect(text).toContain("get_risk");+ });++ it("says how many worse findings the capped list leaves out", () => {+ const finding = { change_kind: "introduced", severity: "high", path: "src/a.py", reason: "too long" };+ const text = buildChangeAiPrompt({ change: { ...base, findings: [finding], omitted: 12 } });+ expect(text).toContain("12 more findings this change made worse are not listed below");+ expect(buildChangeAiPrompt({ change: { ...base, findings: [finding] } })).not.toContain("not listed below");+ });++ it("still asks to fix when every worse finding is past the listed ones", () => {+ const change = { ...base, findings: [], omitted: 3 };+ expect(changePromptFixes(change)).toBe(true);+ const text = buildChangeAiPrompt({ change });+ expect(text).toContain("3 more findings this change made worse are not listed below");+ expect(text).toContain("Fix the findings above in place");+ expect(changePromptFixes(base)).toBe(false);+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex ed08691f8..3c822277e 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -30,6 +30,7 @@"./git": "./src/git/index.ts","./git/*": "./src/git/*.tsx","./commits": "./src/commits/index.ts",+ "./commits/health-delta": "./src/commits/health-delta.ts","./commits/*": "./src/commits/*.tsx","./dead-code": "./src/dead-code/index.ts","./dead-code/*": "./src/dead-code/*.tsx",diff --git a/packages/ui/src/commits/commit-files-table.tsx b/packages/ui/src/commits/commit-files-table.tsxindex 79a7dabf2..038f8c894 100644--- a/packages/ui/src/commits/commit-files-table.tsx+++ b/packages/ui/src/commits/commit-files-table.tsx@@ -1,55 +1,66 @@+"use client";+import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";import { formatLOC } from "../lib/format";import type { CommitFile } from "@repowise-dev/types/git";export interface CommitFilesTableProps {files: CommitFile[];+ /** What touched the files, as the caption names it. */+ noun?: string;className?: string;}-const COLUMNS: ResponsiveColumn<CommitFile>[] = [- {- key: "path",- header: "File",- cellClassName: "font-mono text-[11px] [overflow-wrap:anywhere]",- render: (f) => f.path,- },- {- key: "lines",- header: "Lines",- align: "right",- headerClassName: "w-28",- render: (f) => (- <span className="tabular-nums">- <span className="text-[var(--color-success)]">+{formatLOC(f.lines_added)}</span>{" "}- <span className="text-[var(--color-error)]">-{formatLOC(f.lines_deleted)}</span>- </span>- ),- },- {- key: "prior_fixes",- header: "Prior fixes",- align: "right",- headerClassName: "w-24",- // A dash is "the repo no longer tracks this", not zero.- render: (f) => <span className="tabular-nums">{f.prior_fixes ?? "—"}</span>,- },-];+const PATH: ResponsiveColumn<CommitFile> = {+ key: "path",+ header: "File",+ cellClassName: "font-mono text-[11px] [overflow-wrap:anywhere]",+ render: (f) => f.path,+};++const LINES: ResponsiveColumn<CommitFile> = {+ key: "lines",+ header: "Lines",+ align: "right",+ headerClassName: "w-28",+ render: (f) => (+ <span className="tabular-nums">+ <span className="text-[var(--color-success)]">+{formatLOC(f.lines_added)}</span>{" "}+ <span className="text-[var(--color-error)]">-{formatLOC(f.lines_deleted)}</span>+ </span>+ ),+};++const PRIOR_FIXES: ResponsiveColumn<CommitFile> = {+ key: "prior_fixes",+ header: "Prior fixes",+ align: "right",+ headerClassName: "w-24",+ // A dash is "the repo no longer tracks this", not zero.+ render: (f) => <span className="tabular-nums">{f.prior_fixes ?? "—"}</span>,+};/*** The files a commit touched, and the fix record each carries. Leads the sheet- * because, unlike the percentile, it does not grow with the diff.+ * because, unlike the percentile, it does not grow with the diff. A caller+ * with no fix record at all (the field absent on every row) gets no column,+ * rather than a column of dashes that would read as "untracked".*/-export function CommitFilesTable({ files, className }: CommitFilesTableProps) {+export function CommitFilesTable({ files, noun = "commit", className }: CommitFilesTableProps) {if (files.length === 0) return null;+ const withFixes = files.some((f) => f.prior_fixes !== undefined);return (<ResponsiveTableclassName={className}- columns={COLUMNS}+ columns={withFixes ? [PATH, LINES, PRIOR_FIXES] : [PATH, LINES]}rows={files}rowKey={(f) => f.path}- caption="Files this commit touched, and how much bug-fix history each carries"+ caption={+ withFixes+ ? `Files this ${noun} touched, and how much bug-fix history each carries`+ : `Files this ${noun} touched`+ }stacked="sm"bare/>diff --git a/packages/ui/src/commits/commit-health-table.tsx b/packages/ui/src/commits/commit-health-table.tsxindex 28925e85e..34c19a6a4 100644--- a/packages/ui/src/commits/commit-health-table.tsx+++ b/packages/ui/src/commits/commit-health-table.tsx@@ -1,31 +1,36 @@+"use client";+import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";import { SeverityMark } from "../health/severity-mark";import type { Severity } from "../health/tokens";import type { CommitHealthFinding } from "@repowise-dev/types/git";+import { attributionKind, movedFromLabel } from "./health-delta";export interface CommitHealthTableProps {findings: CommitHealthFinding[];+ /** What the findings belong to, as the copy names it: a commit, or a+ * merged change made of several. */+ noun?: string;className?: string;}-/** Bases where the change wrote the code the finding sits on. The rest only- * touched the file, which is a weaker claim and is labelled as one. */-const DIRECT = new Set(["added_lines", "changed_symbol", "new_file"]);--const INDIRECT_NOTE: Record<string, string> = {- changed_call_edge: "reached through a call this commit edited",- unknown: "not explained by this commit's diff",-};-/** How the commit relates to the finding, when it did not write the line itself. */-function basisNote(f: CommitHealthFinding): string | null {- if (f.attribution_basis === "moved" || f.moved_from) {- const src = f.moved_from;- if (!src) return "moved here from another file";- return src.symbol ? `moved here from ${src.symbol} in ${src.path}` : `moved here from ${src.path}`;+/** How the change relates to the finding, when it did not write the line itself. */+function basisNote(f: CommitHealthFinding, noun: string): string | null {+ switch (attributionKind(f)) {+ case "direct":+ return null;+ case "moved": {+ const from = movedFromLabel(f);+ return from ? `moved here from ${from}` : "moved here from another file";+ }+ case "call_edge":+ return `reached through a call this ${noun} edited`;+ case "unexplained":+ return `not explained by this ${noun}'s diff`;+ default:+ return `in a file this ${noun} touched, not on a line it wrote`;}- if (DIRECT.has(f.attribution_basis)) return null;- return INDIRECT_NOTE[f.attribution_basis] ?? "in a file this commit touched, not on a line it wrote";}function where(f: CommitHealthFinding): string {@@ -33,62 +38,64 @@ function where(f: CommitHealthFinding): string {return f.symbol ? `${f.symbol} — ${f.path}${at}` : `${f.path}${at}`;}-const COLUMNS: ResponsiveColumn<CommitHealthFinding>[] = [- {- key: "severity",- header: "Severity",- headerClassName: "w-24",- render: (f) => (- <span className="inline-flex flex-col gap-0.5">- <SeverityMark severity={f.severity as Severity} />- {f.change_kind === "worsened" && f.severity_before && (- <span className="text-[10px] text-[var(--color-text-tertiary)]">- was {f.severity_before}- </span>- )}- </span>- ),- },- {- key: "reason",- header: "What changed",- cellClassName: "[overflow-wrap:anywhere]",- render: (f) => {- const note = basisNote(f);- return (- <span>- {f.reason}- {note && <span className="text-[var(--color-text-tertiary)]"> ({note})</span>}+function columns(noun: string): ResponsiveColumn<CommitHealthFinding>[] {+ return [+ {+ key: "severity",+ header: "Severity",+ headerClassName: "w-24",+ render: (f) => (+ <span className="inline-flex flex-col gap-0.5">+ <SeverityMark severity={f.severity as Severity} />+ {f.change_kind === "worsened" && f.severity_before && (+ <span className="text-[10px] text-[var(--color-text-tertiary)]">+ was {f.severity_before}+ </span>+ )}</span>- );+ ),},- },- {- key: "where",- header: "Where",- cellClassName: "font-mono text-[11px] [overflow-wrap:anywhere]",- headerClassName: "w-64",- render: where,- },-];+ {+ key: "reason",+ header: "What changed",+ cellClassName: "[overflow-wrap:anywhere]",+ render: (f) => {+ const note = basisNote(f, noun);+ return (+ <span>+ {f.reason}+ {note && <span className="text-[var(--color-text-tertiary)]"> ({note})</span>}+ </span>+ );+ },+ },+ {+ key: "where",+ header: "Where",+ cellClassName: "font-mono text-[11px] [overflow-wrap:anywhere]",+ headerClassName: "w-64",+ render: where,+ },+ ];+}/**- * What a commit introduced or worsened, worst first.+ * What a commit (or a merged change) introduced or worsened, worst first.** Only these two kinds are listed. A resolved finding is real good news but has* no location worth pointing at any more, so it is counted in the section* heading instead of given a row here.*/-export function CommitHealthTable({ findings, className }: CommitHealthTableProps) {+export function CommitHealthTable({ findings, noun = "commit", className }: CommitHealthTableProps) {if (findings.length === 0) return null;return (<ResponsiveTableclassName={className}- columns={COLUMNS}+ columns={columns(noun)}rows={findings}- rowKey={(f) => `${f.path}:${f.line_start ?? 0}:${f.biomarker_type}`}- caption="Code-health findings this commit introduced or made worse"+ rowKey={(f) => `${f.path}:${f.line_start ?? 0}:${f.biomarker_type}:${f.symbol ?? ""}`}+ caption={`Code-health findings this ${noun} introduced or made worse`}stacked="sm"bare/>diff --git a/packages/ui/src/commits/findings-by-file.tsx b/packages/ui/src/commits/findings-by-file.tsxnew file mode 100644index 000000000..76138bfdc--- /dev/null+++ b/packages/ui/src/commits/findings-by-file.tsx@@ -0,0 +1,148 @@+import type { ReactNode } from "react";+import { SeverityMark } from "../health/severity-mark";+import type { Severity } from "../health/tokens";+import { disambiguateBasenames } from "../lib/format";+import type { CommitHealthFinding } from "@repowise-dev/types/git";+import { attributionKind, groupFindingsByFile, movedFromLabel } from "./health-delta";++export interface FileFindings<F> {+ path: string;+ findings: F[];+}++export interface FindingsByFileLabels {+ count: (n: number) => string;+ more: (files: number) => string;+ was: (severity: string) => string;+ /** Said of a finding in a file the change touched but on a line it did not write. */+ indirect: string;+ /** Said of a finding whose code the change carried here from *from* (`symbol in path`). */+ moved: (from: string | null) => string;+ /** Said of a finding reached through a call the change edited. */+ callEdge: string;+ /** Said of a finding nothing in the change's diff explains. */+ unexplained: string;+}++const DEFAULT_LABELS: FindingsByFileLabels = {+ count: (n) => `${n} finding${n === 1 ? "" : "s"}`,+ more: (n) => `Show ${n} more file${n === 1 ? "" : "s"}`,+ was: (s) => `was ${s}`,+ indirect: "file touched, not a line it wrote",+ moved: (from) => (from ? `moved here from ${from}` : "moved here from another file"),+ callEdge: "reached through a call it edited",+ unexplained: "not explained by its diff",+};++function basisNote(f: CommitHealthFinding, l: FindingsByFileLabels): string | null {+ switch (attributionKind(f)) {+ case "direct":+ return null;+ case "moved":+ return l.moved(movedFromLabel(f));+ case "call_edge":+ return l.callEdge;+ case "unexplained":+ return l.unexplained;+ default:+ return l.indirect;+ }+}++export interface FindingsByFileProps<F extends CommitHealthFinding> {+ /** Worst first; files keep the order of their worst finding. */+ findings: F[];+ /** The quiet per-file action, e.g. a prompt for this file's findings. */+ fileAction?: (group: FileFindings<F>) => ReactNode;+ /** Files shown before the rest fold behind "Show N more files". */+ visibleFiles?: number;+ labels?: Partial<FindingsByFileLabels>;+}++function FindingRow({ f, l }: { f: CommitHealthFinding; l: FindingsByFileLabels }) {+ const where = [f.symbol, f.line_start ? `L${f.line_start}` : null].filter(Boolean).join(" · ");+ const note = basisNote(f, l);+ return (+ <li className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5 py-1.5">+ <SeverityMark severity={f.severity as Severity} className="w-16" />+ <span className="min-w-[12rem] flex-1 text-xs text-[var(--color-text-primary)] [overflow-wrap:anywhere]">+ {f.reason}+ {f.change_kind === "worsened" && f.severity_before && (+ <span className="text-[var(--color-text-tertiary)]"> ({l.was(f.severity_before)})</span>+ )}+ {note && <span className="text-[var(--color-text-tertiary)]"> · {note}</span>}+ </span>+ {where && (+ <span className="font-mono text-[11px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">+ {where}+ </span>+ )}+ </li>+ );+}++function FileGroup<F extends CommitHealthFinding>({+ group,+ label,+ action,+ l,+}: {+ group: FileFindings<F>;+ label: string;+ action: ReactNode;+ l: FindingsByFileLabels;+}) {+ return (+ // `group/row` so a per-row prompt action reveals on hover and focus within.+ <section className="group/row py-3">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="min-w-0 font-mono text-xs text-[var(--color-text-primary)] [overflow-wrap:anywhere]" title={group.path}>+ {label}+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)]">{l.count(group.findings.length)}</span>+ {action && <span className="ml-auto">{action}</span>}+ </div>+ <ul className="mt-1">+ {group.findings.map((f) => (+ <FindingRow key={`${f.line_start ?? 0}:${f.biomarker_type}:${f.symbol ?? ""}`} f={f} l={l} />+ ))}+ </ul>+ </section>+ );+}++/**+ * Code-health findings grouped by file: a header per file (shortest label+ * that tells the files apart, full path on hover) and one line per finding+ * with its reason and `symbol · line`. The first few files are open; the rest+ * fold behind one native disclosure, so this stays a server component.+ */+export function FindingsByFile<F extends CommitHealthFinding>({+ findings,+ fileAction,+ visibleFiles = 3,+ labels,+}: FindingsByFileProps<F>) {+ if (findings.length === 0) return null;+ const l = { ...DEFAULT_LABELS, ...labels };+ const groups = groupFindingsByFile(findings);+ const names = disambiguateBasenames(groups.map((g) => g.path));+ const render = (g: FileFindings<F>) => (+ <FileGroup key={g.path} group={g} label={names.get(g.path) ?? g.path} action={fileAction?.(g)} l={l} />+ );+ const shown = groups.slice(0, visibleFiles);+ const rest = groups.slice(visibleFiles);+ return (+ <div className="divide-y divide-[var(--color-border-default)]">+ {shown.map(render)}+ {rest.length > 0 && (+ <details className="group/more py-3">+ <summary className="cursor-pointer text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]">+ {l.more(rest.length)}+ </summary>+ <div className="mt-1 divide-y divide-[var(--color-border-default)]">{rest.map(render)}</div>+ </details>+ )}+ </div>+ );+}diff --git a/packages/ui/src/commits/health-delta-mark.tsx b/packages/ui/src/commits/health-delta-mark.tsxnew file mode 100644index 000000000..371f8f8da--- /dev/null+++ b/packages/ui/src/commits/health-delta-mark.tsx@@ -0,0 +1,109 @@+import { cn } from "../lib/cn";+import {+ betterCount,+ healthDeltaKind,+ worseCount,+ type HealthDeltaCounts,+ type HealthDeltaKind,+} from "./health-delta";++export type HealthDeltaLabels = Record<HealthDeltaKind | "notCompared" | "partial" | "stale", string>;++const DEFAULT_LABELS: HealthDeltaLabels = {+ improved: "Better",+ worsened: "Worse",+ mixed: "Mixed",+ neutral: "No change",+ notCompared: "Not yet analysed",+ partial: "Part of this change was not compared",+ stale: "From an older analyzer: the direction holds, the counts do not compare",+};++/** Green only for a real improvement, red only for a regression; a mixed or+ * neutral result stays plain so colour keeps meaning one thing. */+const DOT: Record<HealthDeltaKind, string> = {+ improved: "bg-[var(--color-success)]",+ worsened: "bg-[var(--color-error)]",+ mixed: "bg-[var(--color-border-hover)]",+ neutral: "",+};++const TEXT: Record<HealthDeltaKind, string> = {+ improved: "text-[var(--color-success)]",+ worsened: "text-[var(--color-error)]",+ mixed: "text-[var(--color-text-primary)]",+ neutral: "text-[var(--color-text-tertiary)]",+};++/** "+3", "−2" or "+3 −1": the signed finding counts behind the word. */+export function signedFigures(better: number, worse: number): string {+ return [better > 0 ? `+${better}` : "", worse > 0 ? `−${worse}` : ""].filter(Boolean).join(" ");+}++export interface HealthDeltaMarkProps {+ /** Null when the commit or change was never compared, which is not the+ * same claim as "changed nothing". */+ delta: HealthDeltaCounts | null | undefined;+ /** Words for each state; packages/ui has no i18n, so hosts pass their own. */+ labels?: Partial<HealthDeltaLabels>;+ /** Off where the counts already lead beside the mark, e.g. a lede figure. */+ figures?: boolean;+ className?: string;+}++/**+ * What a change did to code health, as a dot, a word and the signed finding+ * counts behind it ("Better +3", "Worse -2", "Mixed +3 -1"). A neutral result+ * renders quietly: it is the default state, not something to mark. A stale+ * delta (older analyzer) shows its word and a hollow dot only.+ */+/** The caveat a delta carries, stale before partial; null when it reads as is. */+function caveat(delta: HealthDeltaCounts, l: HealthDeltaLabels): string | null {+ if (delta.stale) return l.stale;+ return delta.status === "partial" ? l.partial : null;+}++/** The dot: hollow when stale, the kind's colour otherwise, none when neutral. */+function MarkDot({ kind, stale }: { kind: HealthDeltaKind; stale: boolean }) {+ if (kind === "neutral") return null;+ return (+ <span+ aria-hidden+ className={cn("h-1.5 w-1.5 shrink-0 rounded-full", stale ? "border border-current" : DOT[kind])}+ />+ );+}++export function HealthDeltaMark({ delta, labels, figures = true, className }: HealthDeltaMarkProps) {+ const l = { ...DEFAULT_LABELS, ...labels };+ if (!delta) {+ return (+ <span className={cn("text-xs text-[var(--color-text-tertiary)]", className)}>+ {l.notCompared}+ </span>+ );+ }+ const kind = healthDeltaKind(delta);+ // A stale delta keeps its direction but drops its colour and figures.+ const stale = !!delta.stale;+ const note = caveat(delta, l);+ const counts = figures && !stale ? signedFigures(betterCount(delta), worseCount(delta)) : "";+ return (+ <span+ className={cn(+ "inline-flex items-center gap-1.5 whitespace-nowrap text-xs",+ stale ? "text-[var(--color-text-tertiary)]" : TEXT[kind],+ className,+ )}+ title={note ?? undefined}+ >+ <MarkDot kind={kind} stale={stale} />+ <span className={kind === "neutral" ? undefined : "font-medium"}>+ {l[kind]}+ {delta.status === "partial" && <span aria-hidden>*</span>}+ </span>+ {counts && <span className="font-mono tabular-nums">{counts}</span>}+ {note && <span className="sr-only">{note}</span>}+ </span>+ );+}diff --git a/packages/ui/src/commits/health-delta.ts b/packages/ui/src/commits/health-delta.tsnew file mode 100644index 000000000..c08665c9b--- /dev/null+++ b/packages/ui/src/commits/health-delta.ts@@ -0,0 +1,79 @@+/**+ * What a commit or a change did to code health, read from its finding counts.+ * Pure, so the list cell, the detail lede and the prompt all agree.+ */++export type HealthDeltaKind = "improved" | "worsened" | "mixed" | "neutral";++/** The counts every health delta carries. `improved` is null until stored+ * deltas carry the analyzer's improved bucket. A server rollup may also send+ * its own `kind`, which wins over the one read from the counts. */+export interface HealthDeltaCounts {+ introduced: number;+ worsened: number;+ resolved: number;+ improved?: number | null | undefined;+ kind?: HealthDeltaKind | undefined;+ /** `partial` when part of the change was not compared. */+ status?: string | undefined;+ /** Written by an older analyzer: the direction holds, the counts do not compare. */+ stale?: boolean | undefined;+}++/** Findings the change made better: resolved, plus improved when known. */+export function betterCount(d: HealthDeltaCounts): number {+ return d.resolved + (d.improved ?? 0);+}++/** Findings the change made worse: new ones plus ones it made more severe. */+export function worseCount(d: HealthDeltaCounts): number {+ return d.introduced + d.worsened;+}++export function healthDeltaKind(d: HealthDeltaCounts): HealthDeltaKind {+ if (d.kind) return d.kind;+ const better = betterCount(d) > 0;+ const worse = worseCount(d) > 0;+ if (better && worse) return "mixed";+ if (better) return "improved";+ return worse ? "worsened" : "neutral";+}++/** Attribution bases where the change wrote the code a finding sits on. The+ * rest only touched the file, a weaker claim that is labelled as one. */+export const DIRECT_ATTRIBUTION: ReadonlySet<string> = new Set(["added_lines", "changed_symbol", "new_file"]);++/** How a change relates to a finding: it wrote the line (`direct`), carried+ * the code from another file (`moved`), edited a call that reaches it+ * (`call_edge`), nothing in its diff explains it (`unexplained`), or it only+ * touched the file (`touched`). */+export type AttributionKind = "direct" | "moved" | "call_edge" | "unexplained" | "touched";++export function attributionKind(f: {+ attribution_basis: string;+ moved_from?: { path: string } | null;+}): AttributionKind {+ if (f.attribution_basis === "moved" || f.moved_from) return "moved";+ if (DIRECT_ATTRIBUTION.has(f.attribution_basis)) return "direct";+ if (f.attribution_basis === "changed_call_edge") return "call_edge";+ if (f.attribution_basis === "unknown") return "unexplained";+ return "touched";+}++/** Where a moved finding's code came from (`symbol in path`), or null when not stored. */+export function movedFromLabel(f: { moved_from?: { path: string; symbol?: string | null } | null }): string | null {+ const src = f.moved_from;+ if (!src) return null;+ return src.symbol ? `${src.symbol} in ${src.path}` : src.path;+}++/** Findings grouped by file, files in order of their first (worst) finding. */+export function groupFindingsByFile<F extends { path: string }>(findings: F[]): { path: string; findings: F[] }[] {+ const groups = new Map<string, F[]>();+ for (const f of findings) {+ const group = groups.get(f.path);+ if (group) group.push(f);+ else groups.set(f.path, [f]);+ }+ return [...groups].map(([path, items]) => ({ path, findings: items }));+}diff --git a/packages/ui/src/commits/index.ts b/packages/ui/src/commits/index.tsindex 1606f4721..65811269a 100644--- a/packages/ui/src/commits/index.ts+++ b/packages/ui/src/commits/index.ts@@ -11,3 +11,7 @@ export * from "./agent-trend-strip";export * from "./commit-risk-histogram";export * from "./commit-risk-scatter";export * from "./commit-distribution";+export * from "./commit-files-table";+export * from "./health-delta";+export * from "./health-delta-mark";+export * from "./findings-by-file";diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex 37026e76c..337a10e28 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -64,6 +64,13 @@ export {type BuildCommitPromptOptions,type CommitPromptInput,} from "./ai-prompts/commit-prompt";+export {+ buildChangeAiPrompt,+ changePromptFixes,+ type BuildChangePromptOptions,+ type ChangePromptFinding,+ type ChangePromptInput,+} from "./ai-prompts/change-prompt";export {buildPerformanceOpportunityPrompt,buildRefactoringOpportunityPrompt,diff --git a/packages/ui/src/health/ai-prompts/change-prompt.ts b/packages/ui/src/health/ai-prompts/change-prompt.tsnew file mode 100644index 000000000..00226fb41--- /dev/null+++ b/packages/ui/src/health/ai-prompts/change-prompt.ts@@ -0,0 +1,158 @@+import {+ bulletList,+ closingSections,+ joinSections,+ pluralS,+ preamble,+ repoSuffix,+ type AiPromptFlavor,+} from "./shared";++// ─────────────────────────────────────────────────────────────────────+// Merged change prompt (one PR / MR / change record)+// ─────────────────────────────────────────────────────────────────────++/** One finding the change introduced or made worse. */+export interface ChangePromptFinding {+ change_kind: string;+ severity: string;+ severity_before?: string | null | undefined;+ path: string;+ symbol?: string | null | undefined;+ line_start?: number | null | undefined;+ line_end?: number | null | undefined;+ reason: string;+ /** The commit of the change that charged it, when the rollup knows. */+ sha?: string | null | undefined;+}++export interface ChangePromptInput {+ /** Short name: the forge ref (a PR number) or a trimmed id. */+ label: string;+ title: string;+ head_sha: string;+ commits: string[];+ files: string[];+ /** Findings the change introduced or worsened, worst first. */+ findings: ChangePromptFinding[];+ /** Worse findings past the listed ones (the server sends the worst first, capped). */+ omitted?: number | undefined;+ /** Findings it resolved; counted, they have no location left. */+ resolved: number;+ /** False when part of the change was not compared. */+ complete: boolean;+ /** Evidence rows that need a look, already worded ("Decisions crossed: 4 accepted"). */+ attention: string[];+}++export interface BuildChangePromptOptions {+ change: ChangePromptInput;+ flavor?: AiPromptFlavor;+ repoName?: string;+}++/**+ * Whether the change made anything worse: listed findings, or worse ones past+ * the capped list. The prompt fixes when so, else reviews the flagged rows.+ */+export function changePromptFixes(c: ChangePromptInput): boolean {+ return c.findings.length > 0 || (c.omitted ?? 0) > 0;+}++/** Above this many files the list is cut; the agent can read the rest from git. */+const FILE_CAP = 25;++function at(f: ChangePromptFinding): string {+ if (!f.line_start) return f.path;+ const end = f.line_end && f.line_end !== f.line_start ? `-${f.line_end}` : "";+ return `${f.path}:${f.line_start}${end}`;+}++function findingLine(f: ChangePromptFinding): string {+ const was = f.change_kind === "worsened" && f.severity_before ? `, was ${f.severity_before}` : "";+ const sym = f.symbol ? ` in \`${f.symbol}\`` : "";+ const by = f.sha ? ` (commit \`${f.sha.slice(0, 12)}\`)` : "";+ return `**${f.change_kind}** (${f.severity}${was}) \`${at(f)}\`${sym}${by}: ${f.reason}`;+}++/** How to read the whole change: its commits, or the head when there is one. */+function diffCommand(c: ChangePromptInput): string {+ if (c.commits.length <= 1) return `git show ${c.head_sha.slice(0, 12)}`;+ return c.commits.map((s) => `git show ${s.slice(0, 12)}`).join("; ");+}++function changeFacts(c: ChangePromptInput): string {+ const shown = c.files.slice(0, FILE_CAP).map((f) => `\`${f}\``);+ const more = c.files.length > FILE_CAP ? ` and ${c.files.length - FILE_CAP} more` : "";+ return bulletList([+ `Change: ${c.label} — ${c.title}`,+ `Commits: ${c.commits.length} (head \`${c.head_sha.slice(0, 12)}\`)`,+ `Files (${c.files.length}): ${shown.join(", ")}${more}`,+ c.resolved > 0 ? `It also resolved ${c.resolved} existing finding${pluralS(c.resolved)}; keep those fixes.` : null,+ c.complete ? null : "Part of this change could not be compared, so the list below may be incomplete.",+ c.omitted+ ? `${c.omitted} more finding${pluralS(c.omitted)} this change made worse ${c.omitted === 1 ? "is" : "are"} not listed below (the list keeps the worst first); after these, check the files above for the rest.`+ : null,+ ]);+}++/**+ * The prompt for one merged change. With findings it asks the agent to fix+ * what the change made worse; without, it asks for a focused review of what+ * the evidence checklist flagged.+ */+export function buildChangeAiPrompt({+ change: c,+ flavor = "generic",+ repoName,+}: BuildChangePromptOptions): string {+ const fixing = changePromptFixes(c);+ const lead = preamble(flavor, {+ source: fixing+ ? "Repowise compared code health before and after this merged change and charged the findings below to it."+ : "Repowise built an evidence checklist for this merged change; the rows below are what it flagged.",+ open: "the files and lines named below",+ mcpTail:+ "Call `get_context([...])` on the files named below and `get_risk(changed_files=[...])` for blast radius and test gaps before reading by hand.",+ });++ const work =+ c.findings.length > 0+ ? ["## What this change made worse", "", bulletList(c.findings.map(findingLine)), ""]+ : [];+ const flagged = c.attention.length > 0 ? ["## Flagged for a look", "", bulletList(c.attention), ""] : [];++ const constraints = fixing+ ? [+ "Fix the findings above in place. Do not revert the change or undo the behaviour it was merged for.",+ "Keep each fix small and local to the named symbol; no unrelated refactors.",+ "If a finding is a false positive or the cost is justified, say so and leave it.",+ "Run the tests that cover the touched files before and after.",+ ]+ : [+ "Review only; do not edit unless a flagged row is a real defect.",+ "Ground every point in the diff and name files and lines.",+ ];+ const expected = fixing+ ? [+ "1. For each finding: fixed (with the diff), or why it should stay.",+ "2. The tests you ran and their result.",+ ]+ : [+ "1. For each flagged row: whether it matters for this change and why.",+ "2. Anything a reviewer should still check, tied to files.",+ ];++ return joinSections([+ lead,+ "",+ `## Merged change${repoSuffix(repoName)}`,+ "",+ changeFacts(c),+ "",+ ...work,+ ...flagged,+ ...closingSections(constraints, expected),+ `Read the change with \`${diffCommand(c)}\` first.`,+ ]);+}diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 9a3ed39bf..9e276ecca 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -297,12 +297,10 @@"emptyTitle": "No changes indexed yet","emptyHint": "Changes are read from git history on the next index or update.","emptyAction": "Go to overview",- "change": "Change","merged": "Merged","category": "Category","files": "Files","lines": "Lines",- "title_col": "Title","provenance": "Provenance","showing": "Showing {shown} of {total}","newer": "Newer",@@ -310,15 +308,8 @@"allCategories": "All categories","detailCommits": "Commits","detailFiles": "Files",- "detailMetadata": "Forge metadata",- "source": "Source",- "linkedIssues": "Linked issues",- "approvals": "Approvals","unknown": "Unknown","coverage": "coverage {pct}%",- "back": "All changes",- "shape": "Shape",- "head": "Head","detailEvidence": "Evidence checklist","evidenceLoading": "Building the evidence checklist. The first view of a change takes a few seconds.","evidenceUnavailable": "The evidence checklist could not be built for this change.",@@ -332,18 +323,12 @@"outcomesWindowOpen": "window still open","outcomesNone": "No later commit in this history reverts this change or names it as a cause.","outcomesNote": "Links come only from later commits that name this change. The file rate says where fixes landed, not what caused them.",- "statusOk": "ok","statusAttention": "attention","statusUnknown": "unknown","byChangeTitle": "Merged changes",- "byChangeDescription": "One row per merged change. Open a change for its evidence checklist: owners, reaching tests, contracts, decisions crossed and health delta. The Evidence column counts what that checklist flagged.",+ "byChangeDescription": "One row per merged change, newest first. Open one for what it did to code health, the checks that need a look, and its files.","commits": "Commits",- "evidence": "Evidence",- "evidenceNotBuilt": "Not built",- "evidenceNotBuiltHint": "The checklist is built the first time the change is opened.",- "evidenceClear": "Nothing flagged","evidenceAttention": "{count, plural, one {# needs attention} other {# need attention}}",- "evidenceUnknown": "{count} unknown","needsAttention": "Needs attention","attentionScope": "Only changes with a built checklist are listed.","attentionEmpty": "No built checklist flags anything for attention.",@@ -400,7 +385,52 @@"risk_score": "Larger than {percentile}% of recent commits","outcomes": "{reverts, plural, one {# revert} other {# reverts}}, {references, plural, one {# cause reference} other {# cause references}}","outcomes_rate": "{reverts, plural, one {# revert} other {# reverts}}, {references, plural, one {# cause reference} other {# cause references}}; {fixed} of {files, plural, one {# file} other {# files}} fixed within {days} days"- }+ },+ "healthCol": "Code health",+ "checklistCol": "Checklist",+ "healthLabels": {+ "improved": "Better",+ "worsened": "Worse",+ "mixed": "Mixed",+ "neutral": "No change",+ "notCompared": "Not yet analysed",+ "partial": "Part of this change was not compared",+ "stale": "From an older analyzer: the direction holds, the counts do not compare"+ },+ "verdictLabel": "What this change did to code health",+ "verdictNeutral": "Compared clean: nothing introduced, worsened or resolved.",+ "verdictImproved": "Resolved {better, plural, one {# finding} other {# findings}} and made nothing worse. Nice work.",+ "verdictPartial": "{unscanned, plural, =0 {Part of this change could not be compared, so these counts are a floor.} one {# of its commits has not been scanned yet, so these counts are a floor.} other {# of its commits have not been scanned yet, so these counts are a floor.}}",+ "verdictUnknown": "None of this change's commits has been analysed by the current analyzer yet; recent commits are analysed as updates run.",+ "gotWorse": "Got worse",+ "gotWorseDescription": "Findings this change introduced or made more severe, worst first.",+ "gotWorseShown": "Showing the {shown} most severe of {total}.",+ "promptAction": "Copy prompt for your agent",+ "promptTitle": "Prompt for this change",+ "promptDescription": "Hands your agent what this change made worse, with files and lines, or what its checklist flagged when nothing got worse.",+ "checksPassed": "{count, plural, one {# check passed} other {# checks passed}}",+ "checksAllPassed": "{count, plural, one {The # check passed.} other {All # checks passed.}}",+ "metaCommits": "{count, plural, one {# commit} other {# commits}}",+ "metaFiles": "{count, plural, one {# file} other {# files}}",+ "metaMerged": "merged {date}",+ "metaApprovals": "{count, plural, one {# approval} other {# approvals}}",+ "metaIssues": "issues {issues}",+ "metaProvenance": "AI provenance {label}",+ "change": "Change",+ "promptActionFix": "Copy prompt to fix what this change made worse",+ "ledeUnitWorse": "{worse, plural, one {finding introduced or worsened} other {findings introduced or worsened}} · {better} resolved",+ "ledeUnitBetter": "{better, plural, one {finding resolved} other {findings resolved}} · nothing made worse",+ "ledeUnitNeutral": "findings changed",+ "verdictWorseReading": "Each one is listed below by file, worst first, with the symbol and line. The prompt hands them to your agent.",+ "fileFindings": "{count, plural, one {# finding} other {# findings}}",+ "moreFiles": "{count, plural, one {Show # more file} other {Show # more files}}",+ "findingWas": "was {severity}",+ "findingIndirect": "file touched, not a line it wrote",+ "findingMovedFrom": "moved here from {from}",+ "findingMoved": "moved here from another file",+ "findingCallEdge": "reached through a call it edited",+ "findingUnexplained": "not explained by its diff",+ "promptActionFile": "Copy prompt for {file}"},"architecture": {"tabs": {diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 683f3a771..225ba2e80 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -297,12 +297,10 @@"emptyTitle": "尚未索引任何变更","emptyHint": "变更会在下一次索引或更新时从 git 历史读取。","emptyAction": "前往概览",- "change": "变更","merged": "合并时间","category": "类别","files": "文件","lines": "行数",- "title_col": "标题","provenance": "来源","showing": "显示 {shown} / {total}","newer": "较新",@@ -310,15 +308,8 @@"allCategories": "全部类别","detailCommits": "提交","detailFiles": "文件",- "detailMetadata": "代码托管平台元数据",- "source": "来源",- "linkedIssues": "关联的问题",- "approvals": "批准数","unknown": "未知","coverage": "覆盖率 {pct}%",- "back": "全部变更",- "shape": "形式",- "head": "头部提交","detailEvidence": "证据清单","evidenceLoading": "正在生成证据清单。首次查看一个变更需要几秒钟。","evidenceUnavailable": "无法为此变更生成证据清单。",@@ -332,18 +323,12 @@"outcomesWindowOpen": "窗口尚未结束","outcomesNone": "在此历史中,没有后续提交回滚此变更或将其称为原因。","outcomesNote": "链接只来自明确提到此变更的后续提交。文件比率说明修复落在哪里,而不是由什么引起。",- "statusOk": "正常","statusAttention": "需关注","statusUnknown": "未知","byChangeTitle": "已合并的变更",- "byChangeDescription": "每个已合并的变更一行。打开一个变更即可查看其证据清单:负责人、可达测试、契约、涉及的决策和健康度变化。“证据”列统计该清单标记的项目。",+ "byChangeDescription": "每个已合并的变更一行,最新的在前。打开一个变更,可查看它对代码健康度的影响、需要关注的检查项及其文件。","commits": "提交",- "evidence": "证据",- "evidenceNotBuilt": "尚未生成",- "evidenceNotBuiltHint": "首次打开该变更时会生成证据清单。",- "evidenceClear": "无标记项","evidenceAttention": "{count} 项需关注",- "evidenceUnknown": "{count} 项未知","needsAttention": "需关注","attentionScope": "仅列出已生成证据清单的变更。","attentionEmpty": "已生成的证据清单中没有需关注的项目。",@@ -400,7 +385,52 @@"risk_score": "大于 {percentile}% 的近期提交","outcomes": "{reverts} 次回滚,{references} 次被引为原因","outcomes_rate": "{reverts} 次回滚,{references} 次被引为原因;{files} 个文件中有 {fixed} 个在 {days} 天内被修复"- }+ },+ "healthCol": "代码健康度",+ "checklistCol": "清单",+ "healthLabels": {+ "improved": "变好",+ "worsened": "变差",+ "mixed": "有好有坏",+ "neutral": "无变化",+ "notCompared": "尚未分析",+ "partial": "该变更有部分内容未比较",+ "stale": "来自旧版分析器:方向可信,数量不可比较"+ },+ "verdictLabel": "该变更对代码健康度的影响",+ "verdictNeutral": "比较结果干净:没有新增、恶化或解决任何问题。",+ "verdictImproved": "{better, plural, other {解决了 # 个问题}},且没有让任何地方变差。干得漂亮。",+ "verdictPartial": "{unscanned, plural, =0 {该变更有部分内容无法比较,因此这些数字是下限。} other {该变更有 # 个提交尚未扫描,因此这些数字是下限。}}",+ "verdictUnknown": "该变更的提交尚未经当前分析器分析;最近的提交会在每次更新时依次分析。",+ "gotWorse": "变差的部分",+ "gotWorseDescription": "该变更新增或加重的问题,按严重程度从高到低排列。",+ "gotWorseShown": "显示 {total} 个中最严重的 {shown} 个。",+ "promptAction": "复制给你的智能体的提示词",+ "promptTitle": "该变更的提示词",+ "promptDescription": "把该变更让代码变差的地方(含文件和行号)交给你的智能体;若没有变差,则交给它清单标记的项目。",+ "checksPassed": "{count, plural, other {# 项检查通过}}",+ "checksAllPassed": "{count, plural, other {全部 # 项检查均通过。}}",+ "metaCommits": "{count, plural, other {# 个提交}}",+ "metaFiles": "{count, plural, other {# 个文件}}",+ "metaMerged": "合并于 {date}",+ "metaApprovals": "{count, plural, other {# 个批准}}",+ "metaIssues": "关联议题 {issues}",+ "metaProvenance": "AI 来源 {label}",+ "change": "变更",+ "promptActionFix": "复制提示词,修复该变更让代码变差的地方",+ "ledeUnitWorse": "个问题新增或恶化 · 已解决 {better} 个",+ "ledeUnitBetter": "个问题已解决 · 没有让任何地方变差",+ "ledeUnitNeutral": "个问题发生变化",+ "verdictWorseReading": "下面按文件列出每个问题,最严重的在前,并给出符号和行号。提示词会把它们交给你的智能体。",+ "fileFindings": "{count, plural, other {# 个问题}}",+ "moreFiles": "{count, plural, other {再显示 # 个文件}}",+ "findingWas": "原为 {severity}",+ "findingIndirect": "仅改动了该文件,并非它写下的行",+ "findingMovedFrom": "从 {from} 移到此处",+ "findingMoved": "从另一个文件移到此处",+ "findingCallEdge": "经由它修改的调用到达",+ "findingUnexplained": "它的差异无法解释",+ "promptActionFile": "复制 {file} 的提示词"},"architecture": {"tabs": {diff --git a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsxindex 817f6512d..a713bf2ac 100644--- a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx+++ b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx@@ -6,16 +6,24 @@ import { GitPullRequest } from "lucide-react";import { getTranslations } from "next-intl/server";import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { OverviewSection } from "@repowise-dev/ui/overview";+import { CommitFilesTable } from "@repowise-dev/ui/commits/commit-files-table";import { formatDate } from "@repowise-dev/ui/lib/format";-import { Badge } from "@repowise-dev/ui/ui/badge";-import type { EvidenceItem } from "@repowise-dev/types/changes";-import { changeLabel, commitsViewHref, evidenceValueText, evidenceWord } from "@/lib/changes";+import { changePromptFixes } from "@repowise-dev/ui/health/ai-prompt-builder";+import type { ChangeRecord } from "@repowise-dev/types/changes";+import { categoryLabel, changeLabel, changePromptInput, splitEvidence } from "@/lib/changes";import { getChange } from "@/lib/api/changes";+import { ChangeHealthLede, ChangeGotWorse } from "@/components/changes/change-health";+import { ChangeChecks } from "@/components/changes/change-checks";+import { ChangeOutcomes } from "@/components/changes/change-outcomes";+import { ChangePromptAction } from "@/components/changes/change-prompt-action";interface Props {params: Promise<{ id: string; changeId: string }>;}+/** Above this many files, the list starts collapsed (as on the commit sheet). */+const LONG_FILE_LIST = 10;+export async function generateMetadata({ params }: Props): Promise<Metadata> {const { id, changeId } = await params;try {@@ -26,82 +34,46 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {}}-const STATUS_VARIANT = { ok: "fresh", attention: "stale", unknown: "outline" } as const;-const STATUS_KEY = { ok: "statusOk", attention: "statusAttention", unknown: "statusUnknown" } as const;--type Row = Record<string, unknown>;--/** What later history says about the change, in the later commits' own words. */-async function Outcomes({ item, repoId }: { item: EvidenceItem; repoId: string }) {+/** The change's facts in one mono line; forge facts only when known. */+async function MetaLine({ change }: { change: ChangeRecord }) {const t = await getTranslations("views.changes");- if (item.status === "unknown") {- return <p className="text-xs text-[var(--color-text-tertiary)]">{evidenceValueText(t, item)}</p>;- }- const rows = item.details as Row[];- const links = rows.filter((r) => r.kind === "revert" || r.kind === "fix_reference");- const rate = rows.find((r) => r.kind === "file_fix_rate");- const later = (r: Row) => {- const sha = String(r.sha ?? "").slice(0, 12);- const id = typeof r.change_id === "string" ? r.change_id : null;- if (!id) return <span className="font-mono">{sha}</span>;- return (- <Link href={`/repos/${repoId}/changes/${encodeURIComponent(id)}`} className="hover:underline">- {id} <span className="font-mono">{sha}</span>- </Link>- );- };+ const meta = change.metadata;+ const prov = change.provenance;+ const pct = prov?.coverage == null ? null : Math.round(prov.coverage * 100);+ const parts = [+ changeLabel(change),+ categoryLabel(t, change.category),+ change.merged_at ? t("metaMerged", { date: formatDate(change.merged_at) }) : null,+ change.head_sha.slice(0, 12),+ `+${change.lines_added} −${change.lines_deleted}`,+ t("metaCommits", { count: change.commit_count }),+ t("metaFiles", { count: change.files_changed }),+ prov+ ? `${t("metaProvenance", { label: prov.label.replace("_", " ") })}${pct == null ? "" : ` (${t("coverage", { pct })})`}`+ : null,+ meta.approvals != null ? t("metaApprovals", { count: meta.approvals }) : null,+ meta.linked_issues?.length ? t("metaIssues", { issues: meta.linked_issues.join(", ") }) : null,+ ].filter((p): p is string => p !== null);return (- <>- <ul className="space-y-2 text-xs">- {links.length === 0 && (- <li className="text-[var(--color-text-secondary)]">{t("outcomesNone")}</li>- )}- {links.map((r) => (- <li key={`${String(r.kind)}-${String(r.sha)}`} className="space-y-0.5">- <div className="text-[var(--color-text-primary)]">- {r.kind === "revert" ? t("outcomesRevertedBy") : t("outcomesCause")} {later(r)}- {r.kind === "revert" && r.in_force === false && (- <span className="text-[var(--color-text-tertiary)]">- {" "}- ({t("outcomesNoLongerInForce")})- </span>- )}- </div>- <blockquote className="border-l-2 border-[var(--color-border-default)] pl-2 text-[var(--color-text-secondary)]">- {String(r.evidence ?? "")}- </blockquote>- </li>- ))}- {rate && (- <li className="text-[var(--color-text-primary)]">- {t("outcomesFileRate", {- fixed: Number(rate.files_fixed),- total: Number(rate.files),- days: Number(rate.days),- })}- {rate.window_complete === false && (- <span className="text-[var(--color-text-tertiary)]">- {" "}- ({t("outcomesWindowOpen")})- </span>- )}- </li>- )}- </ul>- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">{t("outcomesNote")}</p>- </>+ <p className="font-mono text-xs text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">+ {parts.join(" · ")}+ </p>);}-/** The evidence checklist and the outcomes, streamed in: the first read of a change builds them. */-async function EvidenceSections({ repoId, changeId }: { repoId: string; changeId: string }) {+/**+ * The evidence checklist and outcomes, streamed: the first read of a change+ * builds them. When the change made nothing worse, a review of the rows+ * needing a look is the page's one action.+ */+async function ChangeEvidence({ repoId, change }: { repoId: string; change: ChangeRecord }) {const t = await getTranslations("views.changes");- let evidence;+ let evidence = null;let building = false;try {- const change = await getChange(repoId, changeId, { evidence: true });- evidence = change.evidence;- building = change.evidence_building ?? false;+ const full = await getChange(repoId, change.id, { evidence: true });+ evidence = full.evidence ?? null;+ building = full.evidence_building ?? false;} catch {evidence = null;}@@ -114,42 +86,26 @@ async function EvidenceSections({ repoId, changeId }: { repoId: string; changeId</OverviewSection>);}- const outcomes = evidence.items.find((i) => i.kind === "outcomes");+ const view = splitEvidence(evidence.items);+ const input = changePromptInput(t, change, view.exceptions);+ const review =+ !changePromptFixes(input) && view.exceptions.length > 0 ? (+ <ChangePromptAction change={input} />+ ) : undefined;return (<>- <OverviewSection title={t("detailEvidence")}>- <ul className="divide-y divide-[var(--color-border-default)] text-xs">- {evidence.items- .filter((item) => item !== outcomes)- .map((item) => (- <li key={item.kind} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2">- <span className="w-full shrink-0 font-medium text-[var(--color-text-primary)] sm:w-48">- {evidenceWord(t, `evidenceKinds.${item.kind}`, item.label)}- </span>- <Badge variant={STATUS_VARIANT[item.status]}>{t(STATUS_KEY[item.status])}</Badge>- <span className="text-[var(--color-text-tertiary)]">- {evidenceWord(t, `evidenceBasis.${item.basis}`, item.basis)}- </span>- <span className="min-w-[10rem] flex-1 break-words text-[var(--color-text-secondary)]">- {evidenceValueText(t, item)}- </span>- </li>- ))}- </ul>- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">- {t("evidenceGenerated", { date: formatDate(evidence.generated_at) })}- </p>- </OverviewSection>- {outcomes && (- <OverviewSection title={t("detailOutcomes")}>- <Outcomes item={outcomes} repoId={repoId} />- </OverviewSection>- )}+ <ChangeChecks+ exceptions={view.exceptions}+ passed={view.passed}+ generatedAt={evidence.generated_at}+ action={review}+ />+ {view.outcomes && <ChangeOutcomes item={view.outcomes} repoId={repoId} />}</>);}-/** One Change Record: what landed, from which commits, with what provenance. */+/** One Change Record: what it did to code health, then its evidence, files and commits. */export default async function ChangeDetailPage({ params }: Props) {const { id, changeId } = await params;const t = await getTranslations("views.changes");@@ -160,91 +116,58 @@ export default async function ChangeDetailPage({ params }: Props) {} catch {notFound();}-- const meta = change.metadata;- const prov = change.provenance;- const facts: [string, string][] = [- [t("shape"), change.shape],- [t("category"), change.category],- [t("merged"), change.merged_at ? formatDate(change.merged_at) : t("unknown")],- [t("head"), change.head_sha.slice(0, 12)],- [t("lines"), `+${change.lines_added} -${change.lines_deleted}`],- ];- if (prov) {- const pct = prov.coverage == null ? null : Math.round(prov.coverage * 100);- facts.push([- t("provenance"),- `${prov.label.replace("_", " ")}${pct == null ? "" : ` (${t("coverage", { pct })})`}`,- ]);- }+ const prompt = changePromptInput(t, change);return (- <PageShell- icon={<GitPullRequest />}- title={`${changeLabel(change)} ${change.title}`}- actions={- <Link href={commitsViewHref(id, "changes")} className="text-xs hover:underline">- {t("back")}- </Link>- }- >- <dl className="mb-6 grid grid-cols-2 gap-x-6 gap-y-2 text-sm sm:grid-cols-3">- {facts.map(([k, v]) => (- <div key={k}>- <dt className="text-xs text-[var(--color-text-tertiary)]">{k}</dt>- <dd className="font-mono text-xs text-[var(--color-text-primary)]">{v}</dd>- </div>- ))}- </dl>+ <PageShell icon={<GitPullRequest />} title={change.title}>+ <div className="-mt-2">+ <MetaLine change={change} />+ </div>++ {/* Health leads from the change's own rollup, so it paints with the page. */}+ <ChangeHealthLede+ health={change.health}+ action={changePromptFixes(prompt) ? <ChangePromptAction change={prompt} /> : undefined}+ />+ <ChangeGotWorse health={change.health} prompt={prompt} /><Suspense- fallback={- <OverviewSection title={t("detailEvidence")}>- <p className="text-xs text-[var(--color-text-tertiary)]">{t("evidenceLoading")}</p>- </OverviewSection>- }+ fallback={<p className="text-xs text-[var(--color-text-tertiary)]">{t("evidenceLoading")}</p>}>- <EvidenceSections repoId={id} changeId={decodeURIComponent(changeId)} />+ <ChangeEvidence repoId={id} change={change} /></Suspense>- <OverviewSection title={`${t("detailFiles")} (${change.files_changed})`}>- <ul className="space-y-1 font-mono text-xs">- {change.files.map((f) => (- <li key={f.path} className="flex justify-between gap-4">- <span className="truncate">{f.path}</span>- <span className="shrink-0 tabular-nums">- <span className="text-[var(--color-success)]">+{f.added}</span>{" "}- <span className="text-[var(--color-error)]">-{f.deleted}</span>- </span>- </li>- ))}- </ul>+ <OverviewSection+ title={t("detailFiles")}+ hint={t("metaFiles", { count: change.files_changed })}+ collapsible+ defaultOpen={change.files.length <= LONG_FILE_LIST}+ >+ <CommitFilesTable+ noun="change"+ files={change.files.map((f) => ({ path: f.path, lines_added: f.added, lines_deleted: f.deleted }))}+ /></OverviewSection>- <OverviewSection title={`${t("detailCommits")} (${change.commits.length})`}>+ <OverviewSection+ title={t("detailCommits")}+ hint={t("metaCommits", { count: change.commits.length })}+ collapsible+ defaultOpen={false}+ ><ul className="space-y-1 font-mono text-xs">{change.commits.map((sha) => (- <li key={sha}>{sha}</li>+ <li key={sha}>+ <Link+ href={`/repos/${id}/commits?commit=${sha}`}+ className="rounded-sm text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {sha}+ </Link>+ </li>))}</ul></OverviewSection>-- <OverviewSection title={t("detailMetadata")}>- <dl className="grid grid-cols-2 gap-x-6 gap-y-2 text-xs sm:grid-cols-3">- <div>- <dt className="text-[var(--color-text-tertiary)]">{t("source")}</dt>- <dd>{meta.source ?? t("unknown")}</dd>- </div>- <div>- <dt className="text-[var(--color-text-tertiary)]">{t("linkedIssues")}</dt>- <dd>{meta.linked_issues?.join(", ") ?? t("unknown")}</dd>- </div>- <div>- <dt className="text-[var(--color-text-tertiary)]">{t("approvals")}</dt>- <dd>{meta.approvals ?? t("unknown")}</dd>- </div>- </dl>- </OverviewSection></PageShell>);}diff --git a/packages/web/src/components/changes/change-checks.tsx b/packages/web/src/components/changes/change-checks.tsxnew file mode 100644index 000000000..f3468c0b9--- /dev/null+++ b/packages/web/src/components/changes/change-checks.tsx@@ -0,0 +1,91 @@+import type { ReactNode } from "react";+import { getTranslations } from "next-intl/server";+import { OverviewSection } from "@repowise-dev/ui/overview";+import { formatDate } from "@repowise-dev/ui/lib/format";+import type { EvidenceItem } from "@repowise-dev/types/changes";+import { evidenceValueText, evidenceWord, type ChangesTranslator } from "@/lib/changes";++/** Attention is amber; unknown is a hollow neutral mark. A passed check has no mark. */+const DOT = {+ attention: "bg-[var(--color-warning)]",+ unknown: "border border-[var(--color-text-tertiary)]",+} as const;++const WORD = { attention: "statusAttention", unknown: "statusUnknown" } as const;++function CheckRow({ item, t }: { item: EvidenceItem; t: ChangesTranslator }) {+ const flagged = item.status === "ok" ? null : item.status;+ return (+ <li className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2">+ <span className="w-full shrink-0 text-[var(--color-text-primary)] sm:w-48">+ {evidenceWord(t, `evidenceKinds.${item.kind}`, item.label)}+ </span>+ {flagged && (+ <span className="inline-flex items-center gap-1.5 whitespace-nowrap font-medium text-[var(--color-text-primary)]">+ <span aria-hidden className={`h-1.5 w-1.5 shrink-0 rounded-full ${DOT[flagged]}`} />+ {t(WORD[flagged])}+ </span>+ )}+ <span className="min-w-[10rem] flex-1 break-words text-[var(--color-text-secondary)]">+ {evidenceValueText(t, item)}+ </span>+ {/* An unresolved basis repeats what the unknown mark already says. */}+ {item.basis !== "unresolved" && (+ <span className="text-[var(--color-text-tertiary)]">+ {evidenceWord(t, `evidenceBasis.${item.basis}`, item.basis)}+ </span>+ )}+ </li>+ );+}++const LIST = "divide-y divide-[var(--color-border-default)] text-xs";++/**+ * The evidence checklist, exceptions only: rows needing attention or not known+ * are listed with a dot and a word; the checks that passed fold into one+ * "N checks passed" line that opens on demand.+ */+export async function ChangeChecks({+ exceptions,+ passed,+ generatedAt,+ action,+}: {+ exceptions: EvidenceItem[];+ passed: EvidenceItem[];+ generatedAt: string;+ /** The page's primary action when it hands over a review of these rows. */+ action?: ReactNode;+}) {+ const t = await getTranslations("views.changes");+ const summary = exceptions.length+ ? t("checksPassed", { count: passed.length })+ : t("checksAllPassed", { count: passed.length });+ return (+ <OverviewSection title={t("detailEvidence")} action={action}>+ {exceptions.length > 0 && (+ <ul className={LIST}>+ {exceptions.map((item) => (+ <CheckRow key={item.kind} item={item} t={t} />+ ))}+ </ul>+ )}+ {passed.length > 0 && (+ <details className="group text-xs">+ <summary className="cursor-pointer text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]">+ {summary}+ </summary>+ <ul className={`${LIST} mt-1`}>+ {passed.map((item) => (+ <CheckRow key={item.kind} item={item} t={t} />+ ))}+ </ul>+ </details>+ )}+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {t("evidenceGenerated", { date: formatDate(generatedAt) })}+ </p>+ </OverviewSection>+ );+}diff --git a/packages/web/src/components/changes/change-health.tsx b/packages/web/src/components/changes/change-health.tsxnew file mode 100644index 000000000..ea8a453eb--- /dev/null+++ b/packages/web/src/components/changes/change-health.tsx@@ -0,0 +1,97 @@+import type { ReactNode } from "react";+import { getTranslations } from "next-intl/server";+import { PageLede } from "@repowise-dev/ui/shared/page-lede";+import { OverviewSection } from "@repowise-dev/ui/overview";+import { FindingsByFile } from "@repowise-dev/ui/commits/findings-by-file";+import { HealthDeltaMark } from "@repowise-dev/ui/commits/health-delta-mark";+import { betterCount, healthDeltaKind, worseCount } from "@repowise-dev/ui/commits/health-delta";+import type { ChangePromptInput } from "@repowise-dev/ui/health/ai-prompt-builder";+import type { ChangeHealthResponse } from "@repowise-dev/types/history";+import { filePromptInput, healthDeltaLabels } from "@/lib/changes";+import { ChangePromptAction } from "./change-prompt-action";++type Health = ChangeHealthResponse | null | undefined;++/**+ * The change page's lede, figure first: how many findings the change made+ * worse (or, when it only helped, how many it resolved), the dot-and-word+ * mark beside it, one reading, and the primary action when there is work to+ * hand over. A change none of whose commits was analysed says so.+ */+export async function ChangeHealthLede({ health, action }: { health: Health; action?: ReactNode }) {+ const t = await getTranslations("views.changes");+ const labels = healthDeltaLabels(t);+ if (!health) {+ return (+ <PageLede+ label={t("verdictLabel")}+ value="—"+ badge={<HealthDeltaMark delta={null} labels={labels} />}+ action={action}+ >+ <p>{t("verdictUnknown")}</p>+ </PageLede>+ );+ }+ const kind = healthDeltaKind(health);+ const better = betterCount(health);+ const worse = worseCount(health);+ const lead =+ kind === "improved"+ ? { value: better, unit: t("ledeUnitBetter", { better }), reading: t("verdictImproved", { better }) }+ : kind === "neutral"+ ? { value: 0, unit: t("ledeUnitNeutral"), reading: t("verdictNeutral") }+ : { value: worse, unit: t("ledeUnitWorse", { worse, better }), reading: t("verdictWorseReading") };+ return (+ <PageLede+ label={t("verdictLabel")}+ value={String(lead.value)}+ unit={lead.unit}+ badge={<HealthDeltaMark delta={health} labels={labels} figures={false} />}+ action={action}+ >+ <p>{lead.reading}</p>+ {health.status === "partial" && (+ <p>{t("verdictPartial", { unscanned: health.unscanned_commits })}</p>+ )}+ </PageLede>+ );+}++/**+ * "Got worse": the findings the change's commits introduced or made more+ * severe, grouped by file, each file with a quiet prompt for its findings.+ * What got better is the lede's count; a resolved finding has no location.+ */+export async function ChangeGotWorse({ health, prompt }: { health: Health; prompt: ChangePromptInput }) {+ const findings = health?.findings ?? [];+ if (!health || findings.length === 0) return null;+ const t = await getTranslations("views.changes");+ const worse = worseCount(health);+ return (+ <OverviewSection+ title={t("gotWorse")}+ description={+ findings.length < worse+ ? `${t("gotWorseDescription")} ${t("gotWorseShown", { shown: findings.length, total: worse })}`+ : t("gotWorseDescription")+ }+ >+ <FindingsByFile+ findings={findings}+ labels={{+ count: (n) => t("fileFindings", { count: n }),+ more: (n) => t("moreFiles", { count: n }),+ was: (severity) => t("findingWas", { severity }),+ indirect: t("findingIndirect"),+ moved: (from) => (from ? t("findingMovedFrom", { from }) : t("findingMoved")),+ callEdge: t("findingCallEdge"),+ unexplained: t("findingUnexplained"),+ }}+ fileAction={(group) => (+ <ChangePromptAction quiet subject={group.path} change={filePromptInput(prompt, group.path)} />+ )}+ />+ </OverviewSection>+ );+}diff --git a/packages/web/src/components/changes/change-outcomes.tsx b/packages/web/src/components/changes/change-outcomes.tsxnew file mode 100644index 000000000..6ba16c325--- /dev/null+++ b/packages/web/src/components/changes/change-outcomes.tsx@@ -0,0 +1,82 @@+import Link from "next/link";+import { getTranslations } from "next-intl/server";+import { OverviewSection } from "@repowise-dev/ui/overview";+import type { EvidenceItem } from "@repowise-dev/types/changes";+import { evidenceValueText } from "@/lib/changes";++type Row = Record<string, unknown>;++const LINK = "text-[var(--color-accent-primary)] hover:underline";++/** The later commit or change a link row names, as a link to it. */+function LaterRef({ r, repoId }: { r: Row; repoId: string }) {+ const sha = String(r.sha ?? "");+ const id = typeof r.change_id === "string" ? r.change_id : null;+ if (!id) {+ return (+ <Link href={`/repos/${repoId}/commits?commit=${encodeURIComponent(sha)}`} className={`font-mono ${LINK}`}>+ {sha.slice(0, 12)}+ </Link>+ );+ }+ return (+ <Link href={`/repos/${repoId}/changes/${encodeURIComponent(id)}`} className={LINK}>+ {id} <span className="font-mono">{sha.slice(0, 12)}</span>+ </Link>+ );+}++/** A revert or a later fix naming this change as its cause, in its own words. */+async function LinkRow({ r, repoId }: { r: Row; repoId: string }) {+ const t = await getTranslations("views.changes");+ return (+ <li className="space-y-0.5">+ <div className="text-[var(--color-text-primary)]">+ {r.kind === "revert" ? t("outcomesRevertedBy") : t("outcomesCause")} <LaterRef r={r} repoId={repoId} />+ {r.kind === "revert" && r.in_force === false && (+ <span className="text-[var(--color-text-tertiary)]"> ({t("outcomesNoLongerInForce")})</span>+ )}+ </div>+ <blockquote className="border-l-2 border-[var(--color-border-default)] pl-2">{String(r.evidence ?? "")}</blockquote>+ </li>+ );+}++/** Where fixes later landed among the change's files. */+async function FileRateRow({ rate }: { rate: Row }) {+ const t = await getTranslations("views.changes");+ return (+ <li>+ {t("outcomesFileRate", { fixed: Number(rate.files_fixed), total: Number(rate.files), days: Number(rate.days) })}+ {rate.window_complete === false && (+ <span className="text-[var(--color-text-tertiary)]"> ({t("outcomesWindowOpen")})</span>+ )}+ </li>+ );+}++/** What later history says about the change, in the later commits' own words. */+export async function ChangeOutcomes({ item, repoId }: { item: EvidenceItem; repoId: string }) {+ const t = await getTranslations("views.changes");+ if (item.status === "unknown") {+ return (+ <OverviewSection title={t("detailOutcomes")}>+ <p className="text-xs text-[var(--color-text-tertiary)]">{evidenceValueText(t, item)}</p>+ </OverviewSection>+ );+ }+ const rows = item.details as Row[];+ const links = rows.filter((r) => r.kind === "revert" || r.kind === "fix_reference");+ const rate = rows.find((r) => r.kind === "file_fix_rate");+ return (+ <OverviewSection title={t("detailOutcomes")} description={t("outcomesNote")}>+ <ul className="space-y-2 text-xs text-[var(--color-text-secondary)]">+ {links.length === 0 && <li>{t("outcomesNone")}</li>}+ {links.map((r) => (+ <LinkRow key={`${String(r.kind)}-${String(r.sha)}`} r={r} repoId={repoId} />+ ))}+ {rate && <FileRateRow rate={rate} />}+ </ul>+ </OverviewSection>+ );+}diff --git a/packages/web/src/components/changes/change-prompt-action.tsx b/packages/web/src/components/changes/change-prompt-action.tsxnew file mode 100644index 000000000..187655540--- /dev/null+++ b/packages/web/src/components/changes/change-prompt-action.tsx@@ -0,0 +1,63 @@+"use client";++import { useState } from "react";+import { useTranslations } from "next-intl";+import {+ AiPromptButton,+ AiPromptModal,+ buildChangeAiPrompt,+ changePromptFixes,+ type ChangePromptInput,+} from "@repowise-dev/ui/health";++/**+ * Reveal rule for a per-row prompt: hidden at rest, shown on row hover, focus+ * within the row, and where there is no hover. Rows carry `group/row`.+ */+// Follow-up: replace the quiet branch with L-nav's RowPromptAction (ghost+// variant) and the modal with L-perf's useAiPromptAction once both merge.+const ROW_REVEAL =+ "opacity-0 focus-visible:opacity-100 group-hover/row:opacity-100 group-focus-within/row:opacity-100 [@media(hover:none)]:opacity-100";++/**+ * A change prompt: the shared button and dialog in their own client boundary,+ * so the page around them stays server-rendered. The filled button is the+ * page's one primary action; `quiet` is the per-file row action.+ */+export function ChangePromptAction({+ change,+ quiet = false,+ subject,+}: {+ change: ChangePromptInput;+ quiet?: boolean;+ /** What a quiet row action is about (its file), for its accessible name. */+ subject?: string;+}) {+ // Fixing what got worse when the change made anything worse; else a review+ // of what its checklist flagged. The builder picks the same way.+ const fixing = changePromptFixes(change);+ const [open, setOpen] = useState(false);+ const t = useTranslations("views.changes");+ const label = quiet+ ? t("promptActionFile", { file: subject ?? "" })+ : t(fixing ? "promptActionFix" : "promptAction");+ return (+ <>+ <AiPromptButton+ label={label}+ variant={quiet ? "icon" : "default"}+ className={quiet ? ROW_REVEAL : undefined}+ onClick={() => setOpen(true)}+ />+ <AiPromptModal+ open={open}+ onOpenChange={setOpen}+ getPrompt={(flavor) => buildChangeAiPrompt({ change, flavor })}+ filePath={quiet ? subject : change.label}+ title={t("promptTitle")}+ description={t("promptDescription")}+ />+ </>+ );+}diff --git a/packages/web/src/components/changes/changes-table.tsx b/packages/web/src/components/changes/changes-table.tsxindex b42a155da..1b5173d62 100644--- a/packages/web/src/components/changes/changes-table.tsx+++ b/packages/web/src/components/changes/changes-table.tsx@@ -3,146 +3,114 @@import Link from "next/link";import { useTranslations } from "next-intl";import { ResponsiveTable, type ResponsiveColumn } from "@repowise-dev/ui/shared/responsive-table";-import { formatDate } from "@repowise-dev/ui/lib/format";+import { HealthDeltaMark } from "@repowise-dev/ui/commits/health-delta-mark";+import { formatLOC, formatRelativeTime } from "@repowise-dev/ui/lib/format";import type { ChangeEvidenceSummary, ChangeListItem } from "@/lib/api/changes";-import { categoryLabel, changeLabel } from "@/lib/changes";+import { changeLabel, healthDeltaLabels } from "@/lib/changes";/**- * The kept checklist in one cell: attention first, then unknown, quiet when- * every item checked out. A checklist with no items reads as unknown, never- * as clean. The list never builds a checklist; the change page does.+ * The kept checklist, marked only when it flags something: a dot and a word+ * for attention, nothing at rest. Unknowns are left to the change page, where+ * they are named. A checklist with no items reads as unknown, never as clean.*/-function EvidenceCell({ summary }: { summary: ChangeEvidenceSummary | null | undefined }) {+function ChecklistCell({ summary }: { summary: ChangeEvidenceSummary | null | undefined }) {const t = useTranslations("views.changes");- if (!summary) {- return (- <span className="text-xs text-[var(--color-text-tertiary)]" title={t("evidenceNotBuiltHint")}>- {t("evidenceNotBuilt")}- </span>- );- }+ if (!summary) return null;if (summary.ok + summary.attention + summary.unknown === 0) {return <span className="text-xs text-[var(--color-text-tertiary)]">{t("unknown")}</span>;}- if (summary.attention === 0 && summary.unknown === 0) {- return <span className="text-xs text-[var(--color-text-tertiary)]">{t("evidenceClear")}</span>;- }+ if (summary.attention === 0) return null;return (- <span className="inline-flex flex-wrap items-center gap-x-2 text-xs">- {summary.attention > 0 && (- <span className="inline-flex items-center gap-1.5 text-[var(--color-text-primary)]">- <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-warning)]" />- {t("evidenceAttention", { count: summary.attention })}- </span>- )}- {summary.unknown > 0 && (- <span className="text-[var(--color-text-tertiary)]">- {t("evidenceUnknown", { count: summary.unknown })}- </span>- )}+ <span className="inline-flex items-center gap-1.5 whitespace-nowrap text-xs text-[var(--color-text-primary)]">+ <span aria-hidden className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-warning)]" />+ {t("evidenceAttention", { count: summary.attention })}</span>);}-/** Merged changes, one row each, linking to the change's page and checklist. */-export function ChangesTable({- repoId,- rows,- showProvenance,-}: {- repoId: string;- rows: ChangeListItem[];- showProvenance: boolean;-}) {+/**+ * Merged changes, one row each, in the commit queue's shape: the title is the+ * link and wraps, the id is a quiet mono prefix, and only exceptions carry+ * colour.+ */+export function ChangesTable({ repoId, rows }: { repoId: string; rows: ChangeListItem[] }) {const t = useTranslations("views.changes");+ // A server from before the health rollup sends no field at all; null is+ // "not scanned" and still gets the column.+ const hasHealth = rows.some((c) => c.health !== undefined);+ const healthLabels = healthDeltaLabels(t);+const columns: ResponsiveColumn<ChangeListItem>[] = [{- key: "id",+ key: "title",header: t("change"),- cellClassName: "whitespace-nowrap",+ cellClassName: "min-w-[240px] max-w-[560px]",render: (c) => (- <Link- href={`/repos/${repoId}/changes/${encodeURIComponent(c.id)}`}- title={c.id}- className="inline-block max-w-[12rem] truncate whitespace-nowrap align-bottom font-mono text-xs text-[var(--color-accent-primary)] hover:underline"- >- {changeLabel(c)}- </Link>+ <div className="flex items-baseline gap-2">+ <span className="shrink-0 font-mono text-xs text-[var(--color-text-tertiary)]" title={c.id}>+ {changeLabel(c)}+ </span>+ <Link+ href={`/repos/${repoId}/changes/${encodeURIComponent(c.id)}`}+ className="min-w-0 rounded-sm text-xs text-[var(--color-text-primary)] [text-wrap:pretty] hover:text-[var(--color-accent-primary)] hover:underline focus-visible:text-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {c.title}+ </Link>+ </div>),},+ ...(hasHealth+ ? [+ {+ key: "health",+ header: t("healthCol"),+ headerClassName: "w-32",+ render: (c: ChangeListItem) => <HealthDeltaMark delta={c.health} labels={healthLabels} />,+ },+ ]+ : []),{- key: "title",- header: t("title_col"),- cellClassName: "min-w-[220px] max-w-[440px] truncate",- render: (c) => <span title={c.title}>{c.title}</span>,- },- {- key: "evidence",- header: t("evidence"),- render: (c) => <EvidenceCell summary={c.evidence_summary} />,+ key: "checklist",+ header: t("checklistCol"),+ headerClassName: "w-36",+ render: (c) => <ChecklistCell summary={c.evidence_summary} />,},{key: "merged_at",header: t("merged"),+ headerClassName: "w-24",priority: 2,render: (c) => (- <span className="text-xs text-[var(--color-text-secondary)]">- {c.merged_at ? formatDate(c.merged_at) : ""}+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]" title={c.merged_at ?? undefined}>+ {c.merged_at ? formatRelativeTime(c.merged_at) : ""}</span>),},- {- key: "category",- header: t("category"),- priority: 2,- render: (c) => <span className="text-xs">{categoryLabel(t, c.category)}</span>,- },- {- key: "commits",- header: t("commits"),- align: "right",- priority: 3,- render: (c) => <span className="font-mono text-xs tabular-nums">{c.commit_count}</span>,- },{key: "files",header: t("files"),align: "right",+ headerClassName: "w-16",priority: 3,- render: (c) => <span className="font-mono text-xs tabular-nums">{c.files_changed}</span>,+ render: (c) => <span className="text-xs tabular-nums text-[var(--color-text-secondary)]">{c.files_changed}</span>,},{key: "lines",header: t("lines"),align: "right",+ headerClassName: "w-28",priority: 3,render: (c) => (- <span className="font-mono text-xs tabular-nums">- <span className="text-[var(--color-success)]">+{c.lines_added}</span>{" "}- <span className="text-[var(--color-error)]">-{c.lines_deleted}</span>+ <span className="whitespace-nowrap text-xs tabular-nums">+ <span className="text-[var(--color-success)]">+{formatLOC(c.lines_added)}</span>{" "}+ <span className="text-[var(--color-error)]">-{formatLOC(c.lines_deleted)}</span></span>),},];- if (showProvenance) {- columns.push({- key: "provenance",- header: t("provenance"),- priority: 3,- render: (c) => {- const prov = c.provenance;- if (!prov) return null;- const pct = prov.coverage == null ? null : Math.round(prov.coverage * 100);- return (- <span className="text-xs">- {prov.label.replace("_", " ")}- {pct != null && (- <span className="text-[var(--color-text-tertiary)]"> · {t("coverage", { pct })}</span>- )}- </span>- );- },- });- }- return <ResponsiveTable columns={columns} rows={rows} rowKey={(c) => c.id} stacked="sm" />;+ return (+ <div className="overflow-hidden rounded-lg border border-[var(--color-border-default)]">+ <ResponsiveTable columns={columns} rows={rows} rowKey={(c) => c.id} stacked="sm" bare />+ </div>+ );}diff --git a/packages/web/src/components/commits/by-change-view.test.tsx b/packages/web/src/components/commits/by-change-view.test.tsxindex 3547d6e64..de8d553dc 100644--- a/packages/web/src/components/commits/by-change-view.test.tsx+++ b/packages/web/src/components/commits/by-change-view.test.tsx@@ -79,12 +79,37 @@ describe("ByChangeView", () => {evidence: true,needs_attention: undefined,});+ // Only the exception is marked: a clean or unbuilt checklist renders nothing,+ // and unknowns are left to the change page.expect(screen.getAllByText("2 need attention").length).toBeGreaterThan(0);- expect(screen.getAllByText("1 unknown").length).toBeGreaterThan(0);- expect(screen.getAllByText("Nothing flagged").length).toBeGreaterThan(0);- expect(screen.getAllByText("Not built").length).toBeGreaterThan(0);- expect(screen.getAllByRole("link", { name: "#1" })[0]!.getAttribute("href")).toBe("/repos/r1/changes/pr-1");+ expect(screen.queryByText(/unknown/i)).toBeNull();+ expect(screen.queryByText("Nothing flagged")).toBeNull();+ expect(screen.queryByText("Not built")).toBeNull();+ // The title is the link; the id is a quiet prefix, not a link.+ expect(screen.getAllByRole("link", { name: "change pr-1" })[0]!.getAttribute("href")).toBe(+ "/repos/r1/changes/pr-1",+ );+ expect(screen.queryByRole("link", { name: "#1" })).toBeNull();expect(screen.queryByText(/Only changes with a built checklist/)).toBeNull();+ // No row carries a health rollup yet, so the column is not drawn.+ expect(screen.queryByText("Code health")).toBeNull();+ });++ it("leads each row with its health rollup once the server sends one", async () => {+ listChanges.mockResolvedValue(+ page([+ row("pr-1", { health: { kind: "improved", status: "available", introduced: 0, worsened: 0, resolved: 3 } } as never),+ row("pr-2", { health: { kind: "worsened", status: "available", introduced: 1, worsened: 1, resolved: 0 } } as never),+ row("pr-3", { health: null } as never),+ ]),+ );+ await show();+ expect(screen.getAllByText("Code health").length).toBeGreaterThan(0);+ expect(screen.getAllByText("Better").length).toBeGreaterThan(0);+ expect(screen.getAllByText("+3").length).toBeGreaterThan(0);+ expect(screen.getAllByText("Worse").length).toBeGreaterThan(0);+ expect(screen.getAllByText("−2").length).toBeGreaterThan(0);+ expect(screen.getAllByText("Not yet analysed").length).toBeGreaterThan(0);});it("filters to changes needing attention and says what the filter covers", async () => {@@ -143,7 +168,8 @@ describe("ByChangeView", () => {listChanges.mockResolvedValue({ ...page([]), checklists_built: { built: 1, changes: 505 } });await show({ attention: "1" });expect(screen.getByText(/Checklists built for 1 of 505 changes\./)).toBeTruthy();- expect(screen.getByText(/repowise changes show REF/)).toBeTruthy();+ // How one gets built sits behind the scope line's info tip.+ expect(screen.getByRole("button", { name: "More info" })).toBeTruthy();});it("names every category chip in both locales", () => {diff --git a/packages/web/src/components/commits/by-change-view.tsx b/packages/web/src/components/commits/by-change-view.tsxindex a560c3bca..1bdaa3e67 100644--- a/packages/web/src/components/commits/by-change-view.tsx+++ b/packages/web/src/components/commits/by-change-view.tsx@@ -2,6 +2,7 @@ import Link from "next/link";import { getTranslations } from "next-intl/server";import { ApiError } from "@repowise-dev/ui/shared/api-error";import { EmptyState } from "@repowise-dev/ui/shared/empty-state";+import { InfoTip } from "@repowise-dev/ui/shared/info-tip";import { OverviewSection } from "@repowise-dev/ui/overview";import { ChangesTable } from "@/components/changes/changes-table";import { listChanges } from "@/lib/api/changes";@@ -142,17 +143,20 @@ export async function ByChangeView({ repoId, params }: { repoId: string; params:allCategories: t("allCategories"),}}/>- <p className="mb-3 text-xs text-[var(--color-text-tertiary)]">- {attention && `${t("attentionScope")} `}- {built && `${t("checklistsBuilt", { built: built.built, changes: built.changes })} `}- {t("checklistsBuildHint")}+ {/* One scope line; how a checklist gets built is behind the tip. */}+ <p className="mb-3 flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">+ <span>+ {attention && `${t("attentionScope")} `}+ {built && t("checklistsBuilt", { built: built.built, changes: built.changes })}+ </span>+ <InfoTip content={t("checklistsBuildHint")} /></p>{page.items.length === 0 ? (<p className="py-6 text-sm text-[var(--color-text-secondary)]">{t(attention ? "attentionEmpty" : "filterEmpty")}</p>) : (- <ChangesTable repoId={repoId} rows={page.items} showProvenance={page.attribution} />+ <ChangesTable repoId={repoId} rows={page.items} />)}<Pagershowing={t("showing", { shown: page.items.length, total: page.total })}diff --git a/packages/web/src/lib/changes-evidence.test.ts b/packages/web/src/lib/changes-evidence.test.tsnew file mode 100644index 000000000..4d5a5869a--- /dev/null+++ b/packages/web/src/lib/changes-evidence.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from "vitest";+import { createTranslator } from "next-intl";+import type { ChangeRecord, EvidenceItem } from "@repowise-dev/types/changes";+import { type ChangesTranslator, changePromptInput, filePromptInput, healthDeltaLabels, splitEvidence } from "./changes";+import en from "../../messages/en.json";+import zhCN from "../../messages/zh-CN.json";++function ev(kind: string, status: EvidenceItem["status"], over: Partial<EvidenceItem> = {}): EvidenceItem {+ return { kind, label: kind, status, basis: "inferred", value: null, details: [], source: "s", ...over };+}++describe("splitEvidence", () => {+ it("lists a revert with the exceptions so the list's attention mark has a row", () => {+ const view = splitEvidence([ev("outcomes", "attention"), ev("owners", "ok")]);+ expect(view.exceptions.map((i) => i.kind)).toEqual(["outcomes"]);+ expect(view.outcomes?.kind).toBe("outcomes");+ });++ it("leaves health, outcomes and provenance to their own places and lists exceptions first", () => {+ const view = splitEvidence([+ ev("owners", "ok"),+ ev("components_touched", "unknown"),+ ev("decisions_crossed", "attention"),+ ev("health_delta", "attention"),+ ev("provenance", "unknown"),+ ev("outcomes", "ok"),+ ]);+ expect(view.outcomes?.kind).toBe("outcomes");+ expect(view.exceptions.map((i) => i.kind)).toEqual(["decisions_crossed", "components_touched"]);+ expect(view.passed.map((i) => i.kind)).toEqual(["owners"]);+ });+});++const finding = {+ change_kind: "introduced",+ dimension: "defect",+ biomarker_type: "complex_method",+ severity: "medium",+ path: "src/a.py",+ symbol: "run",+ line_start: 10,+ line_end: 40,+ attribution_basis: "added_lines",+ reason: "run has cyclomatic complexity 9",+ sha: "c".repeat(40),+};++const change = (health: ChangeRecord["health"]) =>+ ({+ id: "pr-7",+ forge_ref: "#7",+ title: "feat: x",+ head_sha: "a".repeat(40),+ commits: ["a".repeat(40)],+ files: [{ path: "src/a.py", added: 3, deleted: 1 }],+ health,+ }) as ChangeRecord;++describe.each([+ ["en", en],+ ["zh-CN", zhCN],+])("changePromptInput in %s", (locale, messages) => {+ const t = createTranslator({ locale, messages, namespace: "views.changes" }) as unknown as ChangesTranslator;++ it("carries the rollup's worse findings and resolved count", () => {+ const input = changePromptInput(+ t,+ change({+ status: "partial",+ kind: "mixed",+ scanned_commits: 1,+ unscanned_commits: 1,+ introduced: 1,+ worsened: 0,+ resolved: 2,+ files_worsened: 1,+ findings: [finding],+ }),+ );+ expect(input).toMatchObject({ label: "#7", files: ["src/a.py"], resolved: 2, complete: false, omitted: 0 });+ expect(input.findings[0]).toMatchObject({ path: "src/a.py", sha: finding.sha });+ expect(input.attention).toEqual([]);+ const one = filePromptInput({ ...input, findings: [...input.findings, { ...finding, path: "src/b.py" }] }, "src/a.py");+ expect(one.files).toEqual(["src/a.py"]);+ expect(one.findings.map((f) => f.path)).toEqual(["src/a.py"]);+ expect(one.resolved).toBe(0);+ });++ it("counts the worse findings past the server's capped list", () => {+ const capped = changePromptInput(+ t,+ change({+ status: "available",+ kind: "worsened",+ scanned_commits: 1,+ unscanned_commits: 0,+ introduced: 60,+ worsened: 2,+ resolved: 0,+ files_worsened: 1,+ findings: [finding],+ }),+ );+ expect(capped.omitted).toBe(61);+ expect(filePromptInput(capped, "src/a.py").omitted).toBe(0);+ });++ it("names every health mark state from the catalog", () => {+ for (const word of Object.values(healthDeltaLabels(t))) expect(word).not.toMatch(/healthLabels/);+ });++ it("words the flagged rows when the change was never scanned", () => {+ const input = changePromptInput(t, change(null), [+ ev("decisions_crossed", "attention", { line: { key: "decisions_crossed", params: { accepted: 2, candidate: 0 } } }),+ ev("owners", "unknown"),+ ]);+ expect(input.findings).toEqual([]);+ expect(input.complete).toBe(true);+ expect(input.attention).toHaveLength(2);+ for (const line of input.attention) expect(line).not.toMatch(/[{}]|evidenceKinds|status(Attention|Unknown)/);+ });+});diff --git a/packages/web/src/lib/changes.ts b/packages/web/src/lib/changes.tsindex 101830f2f..0dbabc0bc 100644--- a/packages/web/src/lib/changes.ts+++ b/packages/web/src/lib/changes.ts@@ -3,7 +3,9 @@* alike. Kept out of the client table module: a server component cannot call* a function exported from a "use client" file.*/-import type { ChangeListItem, EvidenceItem } from "@repowise-dev/types/changes";+import type { ChangeListItem, ChangeRecord, EvidenceItem } from "@repowise-dev/types/changes";+import type { ChangePromptInput } from "@repowise-dev/ui/health/ai-prompt-builder";+import type { HealthDeltaLabels } from "@repowise-dev/ui/commits/health-delta-mark";/** The change's short name: the forge ref when it has one, else a trimmed id. */export function changeLabel(c: Pick<ChangeListItem, "forge_ref" | "id">): string {@@ -71,3 +73,82 @@ export function evidenceValueText(t: ChangesTranslator, item: EvidenceItem): strexport function evidenceWord(t: ChangesTranslator, key: string, fallback: string): string {return t.has(key) ? t(key) : fallback;}++/**+ * A checklist in the order the change page reads it. Health leads the page and+ * outcomes have their own section; provenance sits in the metadata line, so a+ * repository without attribution does not carry an "unknown" on every change.+ * What is left splits into exceptions (attention first, then unknown) and the+ * checks that passed.+ */+export interface EvidenceView {+ outcomes: EvidenceItem | undefined;+ exceptions: EvidenceItem[];+ passed: EvidenceItem[];+}++/**+ * Health leads from the change's own rollup and provenance sits in the+ * metadata line, so neither is listed (the server's attention count skips+ * health too, and provenance is never attention). Outcomes keep their own+ * section, but one needing attention (a revert) is also listed with the+ * exceptions, so the list's attention mark always has a row here.+ */+const NOT_LISTED = new Set(["health_delta", "provenance"]);++export function splitEvidence(items: EvidenceItem[]): EvidenceView {+ const rest = items.filter((i) => !NOT_LISTED.has(i.kind));+ return {+ outcomes: items.find((i) => i.kind === "outcomes"),+ exceptions: [+ ...rest.filter((i) => i.status === "attention"),+ ...rest.filter((i) => i.status === "unknown" && i.kind !== "outcomes"),+ ],+ passed: rest.filter((i) => i.status === "ok" && i.kind !== "outcomes"),+ };+}++/**+ * What the agent prompt needs from a change: the findings it made worse+ * (from its health rollup), or with none, the checklist rows needing a look.+ */+export function changePromptInput(+ t: ChangesTranslator,+ change: ChangeRecord,+ exceptions: EvidenceItem[] = [],+): ChangePromptInput {+ const health = change.health;+ return {+ label: changeLabel(change),+ title: change.title,+ head_sha: change.head_sha,+ commits: change.commits,+ files: change.files.map((f) => f.path),+ findings: health?.findings ?? [],+ omitted: health ? Math.max(0, health.introduced + health.worsened - (health.findings?.length ?? 0)) : 0,+ resolved: health?.resolved ?? 0,+ complete: health?.status !== "partial",+ attention: exceptions.map(+ (i) => `${evidenceWord(t, `evidenceKinds.${i.kind}`, i.label)}: ${evidenceValueText(t, i) || t(`status${i.status === "attention" ? "Attention" : "Unknown"}`)}`,+ ),+ };+}++/** The same prompt narrowed to one file: its findings, and only that file. */+export function filePromptInput(input: ChangePromptInput, path: string): ChangePromptInput {+ // Resolved and omitted counts are change-wide; a per-file prompt does not claim them.+ return { ...input, files: [path], findings: input.findings.filter((f) => f.path === path), resolved: 0, omitted: 0, attention: [] };+}++/** The health mark's words, from the catalog; one place for the list and the lede. */+export function healthDeltaLabels(t: (key: string) => string): HealthDeltaLabels {+ return {+ improved: t("healthLabels.improved"),+ worsened: t("healthLabels.worsened"),+ mixed: t("healthLabels.mixed"),+ neutral: t("healthLabels.neutral"),+ notCompared: t("healthLabels.notCompared"),+ partial: t("healthLabels.partial"),+ stale: t("healthLabels.stale"),+ };+}diff --git a/tests/unit/core/test_change_evidence.py b/tests/unit/core/test_change_evidence.pyindex 104214db7..8322875b8 100644--- a/tests/unit/core/test_change_evidence.py+++ b/tests/unit/core/test_change_evidence.py@@ -224,6 +224,17 @@ def test_a_kept_checklist_reads_reaching_tests_under_the_current_rule():row = SimpleNamespace(evidence_json=dump_evidence(kept))assert evidence_summary(row)["attention"] == 0+ # Health leads the row from its own rollup; its checklist row is not counted.+ health = {**item, "kind": "health_delta", "label": "Health delta", "details": []}+ kept = {**kept, "items": [health]}+ row = SimpleNamespace(evidence_json=dump_evidence(kept))+ assert evidence_summary(row) | {"generated_at": None} == {+ "generated_at": None,+ "ok": 0,+ "attention": 0,+ "unknown": 0,+ }+def test_every_item_reads_as_a_plain_line():"""Each kind words its value; no raw key, boolean or dict reaches a reader."""