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(decisions): say what the page actually knows (#1352)
Raghav Chamadiyab138e2726595
diff --git a/packages/ui/__tests__/decisions/checkout-facts.test.tsx b/packages/ui/__tests__/decisions/checkout-facts.test.tsxnew file mode 100644index 000000000..f1047188a--- /dev/null+++ b/packages/ui/__tests__/decisions/checkout-facts.test.tsx@@ -0,0 +1,183 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import { CheckoutFacts } from "../../src/decisions/checkout-facts.js";+import type { EpisodeSummary } from "@repowise-dev/types/episodes";++function makeFact(overrides: Partial<EpisodeSummary> = {}): EpisodeSummary {+ return {+ id: "e1",+ tier: "structural",+ kind: "formatter_drift",+ subject: "ruff format",+ evidence: "ruff format --check .: 419 files would be reformatted",+ nodes: [],+ node_count: 0,+ birth_commit: "acd24602cf51",+ birth_at: "2026-08-05T13:08:35Z",+ last_seen_at: "2026-08-05T13:08:35Z",+ still_true: null,+ ...overrides,+ };+}++describe("CheckoutFacts", () => {+ it("renders the evidence line, which is the fact", () => {+ render(<CheckoutFacts facts={[makeFact()]} available />);+ expect(+ screen.getByText(+ "ruff format --check .: 419 files would be reformatted",+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByText("This tree is not formatter-clean"),+ ).toBeInTheDocument();+ });++ it("groups repeats of one kind under a single heading", () => {+ // Three console scripts are shadowed by one editable install. Three+ // identical headings would be the badge-on-every-row failure.+ render(+ <CheckoutFacts+ available+ facts={[+ makeFact({ id: "a", kind: "editable_shadow", evidence: "a.exe" }),+ makeFact({ id: "b", kind: "editable_shadow", evidence: "b.exe" }),+ makeFact({ id: "c", kind: "editable_shadow", evidence: "c.exe" }),+ ]}+ />,+ );+ expect(+ screen.getAllByText("An editable install shadows an installed command"),+ ).toHaveLength(1);+ expect(screen.getByText("a.exe")).toBeInTheDocument();+ expect(screen.getByText("c.exe")).toBeInTheDocument();+ });++ it("shows a kind it has no heading for rather than dropping it", () => {+ // `kind` is an unconstrained string on both sides of the wire and+ // producers add to it. Falling back is the difference between a new+ // detector appearing unlabelled and not appearing.+ render(+ <CheckoutFacts+ available+ facts={[makeFact({ kind: "vendored_lockfile", evidence: "two lockfiles" })]}+ />,+ );+ expect(screen.getByText("vendored_lockfile")).toBeInTheDocument();+ expect(screen.getByText("two lockfiles")).toBeInTheDocument();+ });++ it("says a trimmed scope is trimmed", () => {+ render(+ <CheckoutFacts+ available+ facts={[+ makeFact({+ kind: "nested_repos",+ nodes: ["backend", "frontend"],+ node_count: 8,+ }),+ ]}+ />,+ );+ expect(screen.getByText(/and 6 more/)).toBeInTheDocument();+ });++ it("renders nothing for an absent verdict, which means unchecked", () => {+ // `still_true: null` is unchecked, never stale. Printing "unverified" on+ // the one fact that cannot vouch for itself for free would read as doubt+ // about the fact rather than about the check.+ // Grepping for words the component cannot emit under any mutation is not+ // a test. Count the rendered paragraphs instead: dropping the+ // `fact.still_true &&` guard adds an empty one.+ const withVerdict = render(+ <CheckoutFacts+ facts={[makeFact({ id: "v", still_true: "re-observed" })]}+ available+ />,+ );+ const withCount = withVerdict.container.querySelectorAll("p").length;+ withVerdict.unmount();++ const { container } = render(+ <CheckoutFacts facts={[makeFact({ still_true: null })]} available />,+ );+ expect(container.querySelectorAll("p").length).toBe(withCount - 1);+ expect(container.textContent).not.toMatch(/unchecked|unverified|stale/i);+ });++ it("states a verdict the whole group shares once, not once per row", () => {+ const verdict = "re-observed by a later index (recorded 2026-08-05)";+ render(+ <CheckoutFacts+ available+ facts={[+ makeFact({ id: "a", kind: "editable_shadow", evidence: "a.exe", still_true: verdict }),+ makeFact({ id: "b", kind: "editable_shadow", evidence: "b.exe", still_true: verdict }),+ makeFact({ id: "c", kind: "editable_shadow", evidence: "c.exe", still_true: verdict }),+ ]}+ />,+ );+ expect(screen.getAllByText(verdict)).toHaveLength(1);+ });++ it("keeps verdicts per row when the group disagrees", () => {+ // Hoisting there would attribute one row's verdict to the other.+ render(+ <CheckoutFacts+ available+ facts={[+ makeFact({ id: "a", kind: "editable_shadow", evidence: "a.exe", still_true: "re-observed" }),+ makeFact({ id: "b", kind: "editable_shadow", evidence: "b.exe", still_true: null }),+ ]}+ />,+ );+ // Asserting the count alone stays green when `rows.every(...)` is forced+ // true, because a hoisted verdict also appears exactly once. The claim is+ // *where* it sits: inside a's row, not at group level where it would be+ // read as covering b too.+ const verdict = screen.getByText("re-observed");+ const owningRow = verdict.closest("li");+ expect(owningRow?.textContent).toContain("a.exe");+ expect(owningRow?.textContent).not.toContain("b.exe");+ });++ it("passes a free verdict through when the store has one", () => {+ render(+ <CheckoutFacts+ available+ facts={[+ makeFact({+ still_true: "re-observed by a later index (recorded 2026-08-05)",+ }),+ ]}+ />,+ );+ expect(+ screen.getByText("re-observed by a later index (recorded 2026-08-05)"),+ ).toBeInTheDocument();+ });++ it("tells an unreadable store apart from a clean tree", () => {+ const cold = render(<CheckoutFacts facts={[]} available={false} />);+ expect(cold.container.textContent).toMatch(/Facts land here once an index/);+ // Must not promise a future index will fill it: the router returns this+ // same flag when a read fails on a store that is already full.+ expect(cold.container.textContent).not.toMatch(/The next index/);+ cold.unmount();++ const clean = render(<CheckoutFacts facts={[]} available />);+ expect(clean.container.textContent).toMatch(/Nothing unusual/);+ });++ it("never says something is missing in either empty state", () => {+ // Copy rule: empty states say what will fill them.+ for (const available of [true, false]) {+ const { container, unmount } = render(+ <CheckoutFacts facts={[]} available={available} />,+ );+ expect(container.textContent).not.toMatch(/no data|not found|missing/i);+ unmount();+ }+ });+});diff --git a/packages/ui/__tests__/decisions/decision-detail.test.tsx b/packages/ui/__tests__/decisions/decision-detail.test.tsxindex adfbb4593..cd619257f 100644--- a/packages/ui/__tests__/decisions/decision-detail.test.tsx+++ b/packages/ui/__tests__/decisions/decision-detail.test.tsx@@ -133,18 +133,65 @@ describe("DecisionDetail", () => {expect(screen.queryByText(/Invalid Date/i)).not.toBeInTheDocument();});- it("reports staleness as a percentage, like the decisions table does", () => {- // It used to render "Staleness: 0.42" here and "42%" in the table — the- // same number in two units on two surfaces.+ it("reports what moved as a count, not as a proportion", () => {+ // Was "Staleness 42%" in a meta ribbon. A proportion has no reading at a+ // glance; the count it is a proportion of does.renderView(<DecisionDetail- decision={makeDecision({ staleness_score: 0.42 })}+ decision={makeDecision({+ staleness_score: 0.42,+ affected_files: ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts", "f.ts"],+ })}adapter={makeAdapter()}/>,);- expect(screen.getByText("Staleness").nextElementSibling).toHaveTextContent(- "42%",+ expect(screen.queryByText("Staleness")).not.toBeInTheDocument();+ expect(screen.queryByText("42%")).not.toBeInTheDocument();+ expect(+ screen.getByText(/3 of its 6 files have changed since it was recorded/),+ ).toBeInTheDocument();+ });++ it("says outright when a record cannot be checked at all", () => {+ // An unscoped record scores 0.0 and used to render exactly like a record+ // whose code had not moved. Two meanings, one encoding.+ renderView(+ <DecisionDetail+ decision={makeDecision({ affected_files: [], staleness_score: 0 })}+ adapter={makeAdapter()}+ />,+ );+ expect(+ screen.getByText(/names no files, so whether the code moved/),+ ).toBeInTheDocument();+ });++ it("states the quiet case rather than leaving it blank", () => {+ renderView(+ <DecisionDetail+ decision={makeDecision({+ affected_files: ["a.ts", "b.ts"],+ staleness_score: 0,+ })}+ adapter={makeAdapter()}+ />,+ );+ expect(+ screen.getByText(+ "All 2 files it names are still tracked and unchanged since it was recorded.",+ ),+ ).toBeInTheDocument();+ });++ it("drops confidence from the ribbon, since it restated the source beside it", () => {+ renderView(+ <DecisionDetail+ decision={makeDecision({ confidence: 0.844 })}+ adapter={makeAdapter()}+ />,);+ expect(screen.queryByText("Confidence")).not.toBeInTheDocument();+ expect(screen.queryByText("84%")).not.toBeInTheDocument();});it("explains what Confirm/Dismiss do next to the buttons", () => {diff --git a/packages/ui/__tests__/decisions/decision-staleness.test.ts b/packages/ui/__tests__/decisions/decision-staleness.test.tsnew file mode 100644index 000000000..362055a4d--- /dev/null+++ b/packages/ui/__tests__/decisions/decision-staleness.test.ts@@ -0,0 +1,120 @@+import { describe, it, expect } from "vitest";+import {+ describeStaleness,+ describeRecordStaleness,+} from "../../src/decisions/decision-staleness.js";++describe("describeStaleness", () => {+ it("separates unscoped from unchanged, which both score zero", () => {+ // The whole reason this helper exists. Both used to render one em dash.+ const unscoped = describeStaleness([], 0);+ const unchanged = describeStaleness(["a.ts", "b.ts"], 0);+ expect(unscoped.kind).toBe("unscoped");+ expect(unchanged.kind).toBe("unchanged");+ expect(unscoped.short).not.toBe(unchanged.short);+ expect(unscoped.sentence).not.toBe(unchanged.sentence);+ });++ it("treats a null scope as unscoped rather than as an empty repository", () => {+ expect(describeStaleness(null, 0).kind).toBe("unscoped");+ expect(describeStaleness(undefined, 0.5).kind).toBe("unscoped");+ });++ it("converts the proportion back into the count it is a proportion of", () => {+ // 0.3 x 7 = 2.1, which round and ceil disagree about, so this pins round.+ const s7 = describeStaleness(["a", "b", "c", "d", "e", "f", "g"], 0.3);+ expect(s7.changedCount).toBe(2);+ const s = describeStaleness(["a", "b", "c", "d", "e", "f", "g", "h"], 0.25);+ expect(s.kind).toBe("moved");+ expect(s.changedCount).toBe(2);+ expect(s.fileCount).toBe(8);+ expect(s.short).toBe("2 of 8");+ });++ it("never reports zero changed under a non-zero score", () => {+ // One file of 300 rounds to zero, and "0 of 300 have changed" printed+ // under a score the server says is non-zero costs the reader their trust+ // in every other number on the page.+ const wide = Array.from({ length: 300 }, (_, i) => `f${i}.ts`);+ const s = describeStaleness(wide, 0.001);+ expect(s.kind).toBe("moved");+ expect(s.changedCount).toBe(1);+ });++ it("never reports more changed than the record names", () => {+ // 1.4 does not exercise the clamp: round(1.4 * 1) is 1 already. A score+ // above 2 is what reaches it.+ const s = describeStaleness(["a.ts"], 2.6);+ expect(s.changedCount).toBe(1);+ expect(s.short).toBe("1 of 1");+ const wide = describeStaleness(["a.ts", "b.ts"], 5);+ expect(wide.changedCount).toBe(2);+ });++ it("gives one file its own sentence instead of a plural with the s removed", () => {+ expect(describeStaleness(["a.ts"], 0).sentence).toBe(+ "The one file it names is still tracked and unchanged since it was recorded.",+ );+ expect(describeStaleness(["a.ts"], 1).sentence).toContain(+ "The one file it names has changed",+ );+ expect(describeStaleness(["a.ts", "b.ts"], 1).sentence).toContain(+ "2 of its 2 files have changed"+ );+ // Sweep the small cases for disagreement. "1 of its 2 files has changed"+ // is correct and must not be flagged: the subject is the count, not the+ // scope, so a bare /files has/ ban is wrong and this test failed on it+ // once already.+ for (const n of [1, 2, 3]) {+ for (const score of [0, 0.5, 1]) {+ const s = describeStaleness(+ Array.from({ length: n }, (_, i) => `f${i}.ts`),+ score,+ ).sentence;+ expect(s).not.toMatch(/\b1 files\b/);+ expect(s).not.toMatch(/\b[2-9]\d* of its \d+ files has\b/);+ expect(s).not.toMatch(/\b1 of its \d+ files have\b/);+ }+ }+ });++ it("survives a non-finite score instead of printing NaN", () => {+ expect(describeStaleness(["a.ts"], Number.NaN).kind).toBe("unchanged");+ expect(describeStaleness(["a.ts"], null).kind).toBe("unchanged");+ expect(describeStaleness(["a.ts"], undefined).short).toBe("0 of 1");+ });++ it("refuses to vouch for a status nobody rescores", () => {+ // `recompute_decision_staleness` only touches active and proposed, and the+ // column defaults to 0.0, so a deprecated record would otherwise report+ // "all 2 files unchanged" from a value never computed.+ const dep = describeRecordStaleness({+ affected_files: ["a.ts", "b.ts"],+ staleness_score: 0,+ status: "deprecated",+ });+ expect(dep.kind).toBe("unscored");+ expect(dep.short).toBe("not scored");+ expect(dep.sentence).not.toMatch(/unchanged/);++ for (const status of ["active", "proposed"] as const) {+ expect(+ describeRecordStaleness({+ affected_files: ["a.ts", "b.ts"],+ staleness_score: 0,+ status,+ }).kind,+ ).toBe("unchanged");+ }+ });++ it("reads the two fields off a whole record", () => {+ expect(+ describeRecordStaleness({+ affected_files: ["a.ts", "b.ts", "c.ts", "d.ts"],+ staleness_score: 0.5,+ status: "active",+ }).short,+ ).toBe("2 of 4");+ });+});diff --git a/packages/ui/__tests__/decisions/decisions-table.test.tsx b/packages/ui/__tests__/decisions/decisions-table.test.tsxindex fc6ee9f67..cff35ad00 100644--- a/packages/ui/__tests__/decisions/decisions-table.test.tsx+++ b/packages/ui/__tests__/decisions/decisions-table.test.tsx@@ -66,43 +66,126 @@ describe("DecisionsTable", () => {});});- it("renders a scope badge when the record carries one", () => {+ it("draws neither a scope nor a confidence column", () => {+ // Both were the same axis as a column already on the row. Scope is+ // `cross-module` on three quarters of a live index, and confidence is+ // source rank times verification, so every record from one source carried+ // one number. Asserted on the headers rather than the cells, because a+ // cell value can coincide with a title.render(<DecisionsTable{...baseProps}decisions={[- makeDecision({ id: "1", scope: "file" }),+ makeDecision({ id: "1", scope: "file", confidence: 0.84 }),makeDecision({ id: "2", title: "Adopt SWR", scope: "cross-module" }),]}/>,);- // The scope <select> options share these labels, so exclude them.- expect(screen.getAllByText("File").some((el) => el.tagName !== "OPTION")).toBe(true);expect(- screen.getAllByText("Cross-module").some((el) => el.tagName !== "OPTION"),- ).toBe(true);+ screen.queryByRole("columnheader", { name: "Scope" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("columnheader", { name: "Confidence" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("84%")).not.toBeInTheDocument();});- it("invokes onFiltersChange when the scope filter changes", () => {- const onFiltersChange = vi.fn();+ it("never draws a trust column, whatever the page happens to hold", () => {+ // Making the column conditional on the loaded window was the first cut and+ // it changed the table's shape between clicks of Next. Both pages here.+ for (const rows of [+ [makeDecision({ id: "1", verification: "exact" })],+ [makeDecision({ id: "2", verification: "fuzzy" })],+ ]) {+ const { unmount } = render(+ <DecisionsTable {...baseProps} decisions={rows} />,+ );+ expect(+ screen.queryByRole("columnheader", { name: "Trust" }),+ ).not.toBeInTheDocument();+ unmount();+ }+ });++ it("marks only the loosely-matched row, beside its own title", () => {+ render(+ <DecisionsTable+ {...baseProps}+ decisions={[+ makeDecision({ id: "1", title: "Exact one", verification: "exact" }),+ makeDecision({ id: "2", title: "Loose one", verification: "fuzzy" }),+ ]}+ />,+ );+ // `iconOnly` puts the tier in an sr-only label, which is also what a+ // screen reader gets. It must sit with the row it qualifies.+ const mark = screen.getByText("Fuzzy match");+ expect(mark.closest("td")?.textContent).toContain("Loose one");+ expect(mark.closest("td")?.textContent).not.toContain("Exact one");+ expect(screen.queryByText("Verified quote")).not.toBeInTheDocument();+ });++ it("offers every live source in the filter and no retired one", () => {+ // The hardcoded list offered `readme_mining` and `cli` while omitting+ // `pr` and `session`, which are 86% of a live index, so the control could+ // not reach the records worth reaching and could only ever empty the+ // table. Options are not read off the loaded page either: page one of+ // fifty need not carry every source.+ render(+ <DecisionsTable+ {...baseProps}+ decisions={[+ makeDecision({ id: "1", source: "git_archaeology" }),+ // A legacy row predating the purge. Without this the second filter+ // is unreachable and deleting it leaves the test green.+ makeDecision({ id: "2", source: "readme_mining" as never }),+ ]}+ />,+ );+ const select = screen.getByLabelText("Filter by source");+ const values = Array.from(+ select.querySelectorAll("option"),+ (o) => (o as HTMLOptionElement).value,+ );+ expect(values).toContain("pr");+ expect(values).toContain("session");+ expect(values).toContain("adr");+ expect(values).not.toContain("readme_mining");+ expect(values).not.toContain("changelog");+ expect(values).not.toContain("code_comment");+ // `comment` is a live source and `code_comment` is the retired one. They+ // are different values, and dropping both would lose five real records.+ expect(values).toContain("comment");+ });++ it("surfaces an unmapped source the engine has started emitting", () => {+ render(+ <DecisionsTable+ {...baseProps}+ decisions={[makeDecision({ id: "1", source: "issue_tracker" as never })]}+ />,+ );+ const values = Array.from(+ screen.getByLabelText("Filter by source").querySelectorAll("option"),+ (o) => (o as HTMLOptionElement).value,+ );+ expect(values).toContain("issue_tracker");+ });++ it("no longer renders a scope filter control", () => {+ // The prop and the filtering below it are kept for hosts that pass one;+ // the control is gone with the column, because a reader using it would+ // watch rows vanish for a reason nothing on screen explains.render(<DecisionsTable{...baseProps}- onFiltersChange={onFiltersChange}decisions={[makeDecision({ id: "1", scope: "file" })]}/>,);- fireEvent.change(screen.getByLabelText("Filter by scope"), {- target: { value: "module" },- });- expect(onFiltersChange).toHaveBeenCalledWith({- status: "all",- source: "all",- scope: "module",- });+ expect(screen.queryByLabelText("Filter by scope")).not.toBeInTheDocument();});- it("hides the scope filter and ignores a scope value when no record carries scope", () => {+ it("ignores a scope value when no record carries scope", () => {render(<DecisionsTable{...baseProps}@@ -113,12 +196,60 @@ describe("DecisionsTable", () => {]}/>,);- expect(screen.queryByLabelText("Filter by scope")).not.toBeInTheDocument();// Rows are NOT filtered out by the stale scope value.expect(screen.getByText("Pick Postgres")).toBeInTheDocument();expect(screen.getByText("Adopt SWR")).toBeInTheDocument();});+ it("tells apart a record with no files from one whose files have not moved", () => {+ // The defect this replaces: both scored 0.0 and both rendered as the same+ // em dash, so a reader who correctly read one had been taught a rule that+ // made them wrong about the other.+ render(+ <DecisionsTable+ {...baseProps}+ decisions={[+ makeDecision({ id: "1", title: "Unscoped", affected_files: [] }),+ makeDecision({+ id: "2",+ title: "Steady",+ affected_files: ["a.ts", "b.ts"],+ staleness_score: 0,+ }),+ makeDecision({+ id: "3",+ title: "Moved",+ affected_files: ["a.ts", "b.ts", "c.ts", "d.ts"],+ staleness_score: 0.5,+ }),+ ]}+ />,+ );+ expect(screen.getByText("no files")).toBeInTheDocument();+ expect(screen.getByText("0 of 2")).toBeInTheDocument();+ expect(screen.getByText("2 of 4")).toBeInTheDocument();+ });++ it("does not paint a moved scope as an error", () => {+ // Red is reserved for health bands. Three confirmed, still-true working+ // rules sat at a red 100% on a live index because the files they cite+ // happened to change.+ render(+ <DecisionsTable+ {...baseProps}+ decisions={[+ makeDecision({+ id: "1",+ affected_files: ["a.ts"],+ staleness_score: 1,+ }),+ ]}+ />,+ );+ const cell = screen.getByText("1 of 1");+ expect(cell.className).not.toContain("--color-error");+ });+it("filters rows client-side by scope", () => {render(<DecisionsTablediff --git a/packages/ui/src/decisions/checkout-facts.tsx b/packages/ui/src/decisions/checkout-facts.tsxnew file mode 100644index 000000000..52caf0e56--- /dev/null+++ b/packages/ui/src/decisions/checkout-facts.tsx@@ -0,0 +1,167 @@+import type { EpisodeSummary } from "@repowise-dev/types/episodes";++/**+ * Facts about the checkout itself, as opposed to claims somebody made about+ * it. These are the structural-tier episodes: things true of the tree right+ * now, derived without an API key, without transcripts, and without any git+ * history at all, which is what makes them the one part of this page that+ * says something on a repository indexed an hour ago.+ *+ * Deliberately not a timeline and deliberately not paged. The store also holds+ * a git tier, and on this repository that tier is 289 rows of one fix commit+ * each, against a Commits page two items up the nav. A list of them here would+ * be that page with a filter on it, so the git tier is not rendered.+ */++/**+ * One heading per kind. A kind with no entry here still renders, under its own+ * raw name: the store does not constrain `kind` and producers add to it, so+ * falling back is the difference between a new detector showing up unlabelled+ * and it not showing up at all.+ */+const KIND_HEADING: Record<string, string> = {+ formatter_drift: "This tree is not formatter-clean",+ editable_shadow: "An editable install shadows an installed command",+ nested_repos: "The walk stops at nested repositories",+ config_override: "Config changes how a command behaves",+};++/**+ * `kind` is an unconstrained string on the wire, so a plain index reaches+ * `Object.prototype`: a row of kind `constructor` would hand React a function+ * as a child and throw.+ */+function heading(kind: string): string {+ return Object.hasOwn(KIND_HEADING, kind)+ ? (KIND_HEADING[kind] as string)+ : kind;+}++export interface CheckoutFactsProps {+ /**+ * Structural-tier episodes. The caller filters by tier; passing git-tier+ * rows here would render commit subjects under checkout headings.+ */+ facts: EpisodeSummary[];+ /**+ * `false` when the server could not read an episode store. Usually a cold+ * start, but *not* only that: the router degrades to the same value when a+ * read fails, and its own docstring names `SQLITE_BUSY` during an index as+ * the realistic case. So the copy behind this flag must not promise a+ * future index will fill the section, because the store may be full right+ * now and merely unreadable this second.+ */+ available: boolean;+ /**+ * Measured total behind the page, when the caller has one. Used only to say+ * so when the page is short of it.+ */+ total?: number;+}++export function CheckoutFacts({ facts, available, total }: CheckoutFactsProps) {+ if (facts.length === 0) {+ return (+ <p className="text-sm text-[var(--color-text-secondary)]">+ {available+ ? "Nothing unusual about this checkout. Facts appear here when the tree drifts from what its own tooling expects, such as an unformatted tree or an editable install shadowing an installed command."+ : "Nothing to show for this checkout right now. Facts land here once an index has looked: an unformatted tree, an editable install shadowing an installed command, or a walk that stops at a nested repository."}+ </p>+ );+ }++ const order: string[] = [];+ const groups = new Map<string, EpisodeSummary[]>();+ for (const fact of facts) {+ const existing = groups.get(fact.kind);+ if (existing) {+ existing.push(fact);+ } else {+ order.push(fact.kind);+ groups.set(fact.kind, [fact]);+ }+ }++ const hidden = Math.max(0, (total ?? facts.length) - facts.length);++ return (+ <>+ <ul className="divide-y divide-[var(--color-border-default)]">+ {order.map((kind) => {+ const rows = groups.get(kind) ?? [];+ // One editable install shadowing three console scripts is three rows+ // carrying one identical verdict, and a note every row repeats says+ // nothing. Hoist it when the whole group agrees; keep it per row when+ // they differ, because then it is telling them apart.+ const shared =+ rows.length > 1 &&+ rows[0]?.still_true &&+ rows.every((r) => r.still_true === rows[0]?.still_true)+ ? (rows[0]?.still_true ?? null)+ : null;+ return (+ <li key={kind} className="py-3 first:pt-0 last:pb-0">+ <p className="text-sm font-medium text-[var(--color-text-primary)]">+ {heading(kind)}+ </p>+ <ul className="mt-1.5 space-y-1.5">+ {rows.map((row) => (+ <FactRow key={row.id} fact={row} hideVerdict={shared !== null} />+ ))}+ </ul>+ {shared && (+ <p className="mt-1.5 text-[11px] text-[var(--color-text-tertiary)]">+ {shared}+ </p>+ )}+ </li>+ );+ })}+ </ul>+ {hidden > 0 && (+ <p className="mt-3 text-xs text-[var(--color-text-tertiary)]">+ Showing {facts.length} of {total} recorded.+ </p>+ )}+ </>+ );+}++function FactRow({+ fact,+ hideVerdict,+}: {+ fact: EpisodeSummary;+ hideVerdict: boolean;+}) {+ // `nodes` is trimmed for the wire and `node_count` is the untrimmed total,+ // so a scope wider than the list has to say so rather than quietly showing+ // the first twelve as if they were all of them.+ const shown = fact.nodes.length;+ const hidden = Math.max(0, fact.node_count - shown);++ return (+ <li className="text-xs">+ <p className="font-mono text-[var(--color-text-secondary)]">+ {fact.evidence}+ </p>+ {shown > 0 && (+ <p className="mt-0.5 font-mono text-[11px] text-[var(--color-text-tertiary)] break-all">+ {fact.nodes.join(", ")}+ {hidden > 0 && (+ <span className="tabular-nums"> and {hidden} more</span>+ )}+ </p>+ )}+ {/* Absent means unchecked, never stale, so nothing is rendered for it.+ Printing "unverified" on the one fact that cannot vouch for itself+ for free would read as a doubt about the fact rather than about the+ check. */}+ {fact.still_true && !hideVerdict && (+ <p className="mt-0.5 text-[11px] text-[var(--color-text-tertiary)]">+ {fact.still_true}+ </p>+ )}+ </li>+ );+}diff --git a/packages/ui/src/decisions/decision-detail.tsx b/packages/ui/src/decisions/decision-detail.tsxindex 26411fa15..c46c766f1 100644--- a/packages/ui/src/decisions/decision-detail.tsx+++ b/packages/ui/src/decisions/decision-detail.tsx@@ -42,6 +42,7 @@ import { VerificationBadge } from "./verification-badge";import { DecisionStatusMark } from "./decision-status-mark";import { DecisionEvidenceDrawer } from "./decision-evidence-drawer";import { DecisionLineage } from "./decision-lineage";+import { describeRecordStaleness } from "./decision-staleness";import type {DecisionDetailAdapter,DecisionLinkComponent,@@ -101,6 +102,16 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {// still true?") or enforcement ("make the code conform to it").const [promptMode, setPromptMode] = React.useState<"verify" | "enforce" | null>(null);+ // Read from `decision.affected_files` and not from `linkedFiles`, which the+ // editor below mutates locally. `staleness_score` is a proportion the server+ // computed against the *stored* scope, so pairing it with an unsaved scope+ // would print a count derived from one file set over a fraction derived from+ // another, and the sentence would drift the moment somebody typed.+ const staleness = React.useMemo(+ () => describeRecordStaleness(decision),+ [decision],+ );+// Lineage: cheap, load eagerly so the Evolution timeline renders when present.const { data: lineage } = useSWR(`decision-lineage:${adapter.cacheKey}`,@@ -272,23 +283,14 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {</div></div>- {/* One mono ribbon, tabular, instead of four sans sentences. Staleness- is a percentage here and a percentage in the table; it used to be- "0.42" on one surface and "42%" on the other. */}+ {/* One mono ribbon, tabular, instead of four sans sentences.+ Staleness left the ribbon: a proportion has no reading at a glance,+ and the thing a reader wants from it is a sentence, which is now+ below. Confidence left with it, being source rank times+ verification, so it restated the Source cell beside it as a+ percentage and every record from one source carried one number. */}<dl className="flex flex-wrap gap-x-8 gap-y-2"><MetaItem label="Source" value={SOURCE_LABEL[decision.source] ?? decision.source} />- <MetaItem label="Confidence" value={`${Math.round(decision.confidence * 100)}%`} />- <MetaItem- label="Staleness"- value={- decision.staleness_score > 0- ? `${Math.round(decision.staleness_score * 100)}%`- : "—"- }- {...(decision.staleness_score > 0.5- ? { valueClassName: "text-[var(--color-error)]" }- : {})}- /><MetaItem label="Recorded" value={formatDateOrDash(decision.created_at)} /></dl>@@ -319,19 +321,39 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {</div></div>- {/* Stale warning. A line, not a filled panel: a tinted ground plus a- border plus coloured text says the same thing three times, and it- outweighed the record it was warning about. Same argument as the- status marks. */}- {decision.staleness_score > 0.5 && (- <p className="flex items-start gap-2 text-sm text-[var(--color-warning)]">+ {/* What has happened to the code underneath this record, as a fact.+ A line, not a filled panel: a tinted ground plus a border plus+ coloured text says the same thing three times, and it outweighed the+ record it was warning about.++ It renders in all three states rather than only above a threshold,+ because the two quiet states are not the same state. A record naming+ no files scored 0.0 and rendered exactly like a record whose code had+ not moved, so the reader who correctly read one was taught a rule+ that made them wrong about the other. Only the moved case is marked,+ and it is marked in warning rather than error: the arithmetic says+ the files changed, which is a reason to re-read a record, not a+ verdict that it expired. Three confirmed working rules on a live+ index sat at a red 100% while being true. */}+ {/* No band colour. The table cell on the list page is deliberately+ uncoloured because a file-change count is not a health reading, and+ amber here is the same category error one hue down. It would also+ make this the third mark on one record drawing from one colour+ vocabulary with no key: the status mark paints `active` green and+ `deprecated` red, and the verification badge paints `fuzzy` amber.+ The icon carries "look at this"; the sentence carries what it is. */}+ <p+ className={`flex items-start gap-2 text-sm ${+ staleness.kind === "moved"+ ? "text-[var(--color-text-secondary)]"+ : "text-[var(--color-text-tertiary)]"+ }`}+ >+ {staleness.kind === "moved" && (<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden />- <span>- Affected files have changed significantly since this was recorded,- so it may no longer describe the code.- </span>- </p>- )}+ )}+ <span>{staleness.sentence}</span>+ </p>{/* Evolution / lineage chain */}{lineage && lineage.length > 1 && (@@ -542,23 +564,14 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {);}-function MetaItem({- label,- value,- valueClassName,-}: {- label: string;- value: string;- valueClassName?: string;-}) {+function MetaItem({ label, value }: { label: string; value: string }) {+ // `valueClassName` went with the Staleness item, its only caller: it existed+ // to paint that percentage red above 0.5, which is the thing this change+ // removed. Module-private, so nothing outside can be relying on it.return (<div><dt className={MICRO_LABEL}>{label}</dt>- <dd- className={`mt-0.5 font-mono text-xs tabular-nums text-[var(--color-text-secondary)] ${- valueClassName ?? ""- }`}- >+ <dd className="mt-0.5 font-mono text-xs tabular-nums text-[var(--color-text-secondary)]">{value}</dd></div>diff --git a/packages/ui/src/decisions/decision-staleness.ts b/packages/ui/src/decisions/decision-staleness.tsnew file mode 100644index 000000000..e9cd902ac--- /dev/null+++ b/packages/ui/src/decisions/decision-staleness.ts@@ -0,0 +1,147 @@+import type { DecisionRecord } from "@repowise-dev/types/decisions";++/**+ * What `staleness_score` is allowed to say about a record, in words.+ *+ * The stored score is a proportion, and its numerator decides the wording.+ * `DecisionExtractor.compute_staleness` counts a file when its last commit+ * postdates the record's birth **and** when the file has no git metadata at+ * all, which that function's own docstring spells out: "the record names+ * something the repository does not track, so it cannot be shown to still+ * hold". The count is therefore files that cannot be shown to be unchanged,+ * not files observed to change, and the sentence has to say both. An earlier+ * cut said only "have changed", which reports a record naming three deleted+ * paths as three files that changed.+ *+ * It is a fact either way, and a fact survives being read out loud. `0.42`+ * does not, which is why both surfaces used to print a percentage nobody+ * could act on.+ *+ * The reason this is a shared helper rather than two render branches is a+ * collision that shipped. A record naming **no** files also scores 0.0,+ * because the question cannot be asked of it at all, and 0.0 rendered as the+ * same dash as a record whose code genuinely had not moved. Two meanings on+ * one encoding, where the reader who correctly infers one has been taught a+ * rule that makes them confidently wrong about the other. `kind` splits them+ * so no caller can accidentally re-merge them.+ *+ * Zero git calls: both inputs are already on the row every list response+ * carries, so this is affordable in a table cell.+ */+export type DecisionStalenessKind =+ | "unscoped"+ | "unscored"+ | "unchanged"+ | "moved";++/**+ * The statuses `recompute_decision_staleness` actually rescores. Everything+ * else keeps whatever was in the column, and the column defaults to 0.0, so a+ * deprecated record or one created since the last index would otherwise have+ * an unset default promoted into the sentence "all N files are unchanged".+ * Asserting a fact nobody measured is the overstatement this file exists to+ * remove, so those records say the question was not asked of them.+ */+const RESCORED_STATUSES = new Set(["active", "proposed"]);++export interface DecisionStaleness {+ kind: DecisionStalenessKind;+ /** Files the record binds to. Zero exactly when `kind` is `unscoped`. */+ fileCount: number;+ /** Files that cannot be shown to be unchanged. Zero unless `moved`. */+ changedCount: number;+ /** The full reading, for a detail surface. */+ sentence: string;+ /** The same fact at table width. Never a bare dash; see above. */+ short: string;+}++/**+ * Describe a record's currency from the fields a list response already holds.+ *+ * Accepts the two fields rather than the whole record so a caller holding a+ * narrower row (the hosted artifact projection carries no `DecisionRecord`)+ * can use it without inventing one.+ */+export function describeStaleness(+ affectedFiles: readonly string[] | null | undefined,+ stalenessScore: number | null | undefined,+ status?: string | null,+): DecisionStaleness {+ const fileCount = affectedFiles?.length ?? 0;+ const score = Number.isFinite(stalenessScore) ? (stalenessScore as number) : 0;++ if (status != null && !RESCORED_STATUSES.has(status)) {+ return {+ kind: "unscored",+ fileCount,+ changedCount: 0,+ sentence: `Staleness is only recomputed for active and proposed records, so it was not measured for this ${status} one.`,+ short: "not scored",+ };+ }++ if (fileCount === 0) {+ return {+ kind: "unscoped",+ fileCount: 0,+ changedCount: 0,+ sentence:+ "This record names no files, so whether the code moved underneath it cannot be checked.",+ short: "no files",+ };+ }++ // "None of its 1 file have changed" is what a template gets you when the+ // singular case is left to a plural suffix. One file is a different+ // sentence, not the same sentence with an `s` removed.+ const one = fileCount === 1;++ if (score <= 0) {+ return {+ kind: "unchanged",+ fileCount,+ changedCount: 0,+ sentence: one+ ? "The one file it names is still tracked and unchanged since it was recorded."+ : `All ${fileCount} files it names are still tracked and unchanged since it was recorded.`,+ short: `0 of ${fileCount}`,+ };+ }++ // A proportion rounds to zero on a wide record that moved by one file, and+ // "0 of 300 have changed" under a non-zero score is the kind of arithmetic+ // that costs a reader their trust in every other number on the page. Floor+ // at one, ceiling at the scope.+ const changedCount = Math.min(+ fileCount,+ Math.max(1, Math.round(score * fileCount)),+ );++ const verb = changedCount === 1 ? "has" : "have";+ const be = changedCount === 1 ? "is" : "are";++ return {+ kind: "moved",+ fileCount,+ changedCount,+ sentence: one+ ? "The one file it names has changed since it was recorded, or is no longer tracked, so it may no longer describe the code."+ : `${changedCount} of its ${fileCount} files ${verb} changed since it was recorded, or ${be} no longer tracked, so parts of it may no longer describe the code.`,+ short: `${changedCount} of ${fileCount}`,+ };+}++/** Convenience for callers holding a whole record. */+export function describeRecordStaleness(+ decision: Pick<+ DecisionRecord,+ "affected_files" | "staleness_score" | "status"+ >,+): DecisionStaleness {+ return describeStaleness(+ decision.affected_files,+ decision.staleness_score,+ decision.status,+ );+}diff --git a/packages/ui/src/decisions/decisions-table.tsx b/packages/ui/src/decisions/decisions-table.tsxindex 7d8c0a799..18ef5c45e 100644--- a/packages/ui/src/decisions/decisions-table.tsx+++ b/packages/ui/src/decisions/decisions-table.tsx@@ -9,6 +9,7 @@ import {} from "../shared/responsive-table";import { VerificationBadge } from "./verification-badge";import { DecisionStatusMark } from "./decision-status-mark";+import { describeRecordStaleness } from "./decision-staleness";import { stripMarkdown } from "../lib/format";import type {DecisionRecord,@@ -17,9 +18,11 @@ import type {DecisionScope,} from "@repowise-dev/types/decisions";-// The engine emits more sources than the four the type union names — a live-// index carries comment / pr / adr / changelog / session as well. Unmapped-// values used to fall through raw, so one column mixed "Docs" with "pr".+// The engine emits more sources than the four the type union names: a live+// index carries comment / pr / adr / session as well. Unmapped values used+// to fall through raw, so one column mixed "Docs" with "pr". The retired+// entries below stay in the map so an old row still renders a label; see+// RETIRED_SOURCES for why they are not offered as filters.const SOURCE_LABEL: Record<string, string> = {inline_marker: "Marker",git_archaeology: "Git history",@@ -32,11 +35,23 @@ const SOURCE_LABEL: Record<string, string> = {session: "Session",};-const SCOPE_LABEL: Record<string, string> = {- file: "File",- module: "Module",- "cross-module": "Cross-module",-};+// Sources the engine no longer emits and whose rows were purged with them.+// Mirrors `RETIRED_SOURCES` in `analysis/decisions/provenance.py`; a record+// carrying one of these cannot exist, so offering it as a filter is a control+// that cannot act. Note `code_comment` is retired and `comment` is not: they+// are different values and a live index still carries the second.+const RETIRED_SOURCES = new Set(["code_comment", "readme_mining", "changelog"]);++/**+ * `source` is an unconstrained string on the wire, so a plain index into the+ * map reaches `Object.prototype`: a row sourced `toString` would hand a+ * function to `localeCompare` and throw inside the sort comparator.+ */+function sourceLabel(source: string): string {+ return Object.hasOwn(SOURCE_LABEL, source)+ ? (SOURCE_LABEL[source] as string)+ : source;+}export type DecisionStatusFilter = DecisionStatus | "all";export type DecisionSourceFilter = DecisionSource | "all";@@ -96,6 +111,25 @@ export function DecisionsTable({(d) => !hasScope || scopeFilter === "all" || d.scope === scopeFilter,);+ // The hardcoded list offered `readme_mining` and `cli` while omitting `pr`+ // and `session`, which between them are 86% of a live index. Filtering is a+ // server round trip on the whole store, so the two live sources could not+ // be reached at all and the retired one could only empty the table.+ //+ // Built from the label map rather than from the loaded rows on purpose: the+ // rows are one page of fifty, so a source that happens not to appear on+ // page one would become unselectable, which is the same defect wearing a+ // dynamic coat. Anything present but unmapped is unioned in so a source the+ // engine adds is reachable before this map learns its name.+ const sourceOptions = [+ ...new Set([+ ...Object.keys(SOURCE_LABEL).filter((s) => !RETIRED_SOURCES.has(s)),+ ...(decisions ?? []).map((d) => d.source).filter(Boolean),+ ]),+ ]+ .filter((s) => !RETIRED_SOURCES.has(s))+ .sort((a, b) => sourceLabel(a).localeCompare(sourceLabel(b)));+const columns: ResponsiveColumn<DecisionRecord>[] = [{key: "title",@@ -104,13 +138,18 @@ export function DecisionsTable({cellClassName: "min-w-[200px] max-w-[520px]",render: (d) => (<div className="min-w-0">- <Link- href={`${prefix}/decisions/${d.id}`}- className="font-medium text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline block truncate"- title={stripMarkdown(d.title)}- >- {stripMarkdown(d.title)}- </Link>+ <span className="flex min-w-0 items-center gap-1.5">+ <Link+ href={`${prefix}/decisions/${d.id}`}+ className="font-medium text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline truncate"+ title={stripMarkdown(d.title)}+ >+ {stripMarkdown(d.title)}+ </Link>+ {d.verification && d.verification !== "exact" && (+ <VerificationBadge verification={d.verification} iconOnly />+ )}+ </span>{d.evidence_preview?.source_quote && (<pclassName="mt-0.5 truncate text-xs italic text-[var(--color-text-tertiary)]"@@ -146,41 +185,22 @@ export function DecisionsTable({header: "Source",priority: 3,cellClassName: "text-[var(--color-text-secondary)]",- render: (d) => SOURCE_LABEL[d.source] ?? d.source,- },- {- key: "scope",- header: "Scope",- priority: 3,- render: (d) =>- d.scope ? (- <span className="text-[var(--color-text-secondary)]">- {SCOPE_LABEL[d.scope] ?? d.scope}- </span>- ) : (- <span className="text-[var(--color-text-tertiary)]">—</span>- ),- },- {- key: "trust",- header: "Trust",- priority: 3,- render: (d) =>- d.verification ? (- <VerificationBadge verification={d.verification} iconOnly />- ) : (- <span className="text-[var(--color-text-tertiary)]">—</span>- ),- },- {- key: "confidence",- header: "Confidence",- mobileLabel: "Conf",- align: "right",- priority: 2,- cellClassName: "tabular-nums text-[var(--color-text-secondary)]",- render: (d) => `${Math.round(d.confidence * 100)}%`,+ render: (d) => sourceLabel(d.source),},+ // Scope, Confidence and Trust all left this row. Scope is `cross-module`+ // on three quarters of a live index and confidence is source rank times+ // verification, so every record from one source carries one number: all+ // twelve session records read 84%. A column whose value you can predict+ // from the column beside it spends width repeating itself.+ //+ // Trust went for a different reason. 91% of a live index verifies+ // `exact`, so the mark belongs on the exception rather than on every row+ // (it is now inline beside the title above). Making the *column* appear+ // only when a loaded row needs it was the first attempt and was worse:+ // `visibleDecisions` is one page of fifty, so the table grew and lost a+ // column between clicks of Next, and a reader who saw a mark on page one+ // had no way to tell page two had even been asked. That is the same+ // defect the source filter avoids ten lines above.{key: "tags",header: "Tags",@@ -208,21 +228,36 @@ export function DecisionsTable({},{key: "staleness",- header: "Staleness",- mobileLabel: "Stale",+ // Not "Files changed since". The score's numerator also counts a file+ // the repository no longer tracks, so a record naming three deleted+ // paths would read as three files that changed. "Scope changed" is the+ // claim the number supports; the tooltip carries the whole sentence.+ header: "Scope changed",+ mobileLabel: "Changed",align: "right",priority: 2,- render: (d) => (- <span className="tabular-nums" title="0 = fresh, 1 = fully stale">- {d.staleness_score > 0.5 ? (- <span className="text-[var(--color-error)]">{Math.round(d.staleness_score * 100)}%</span>- ) : d.staleness_score > 0 ? (- <span className="text-[var(--color-text-tertiary)]">{Math.round(d.staleness_score * 100)}%</span>- ) : (- <span className="text-[var(--color-text-tertiary)]">—</span>- )}- </span>- ),+ // Was a percentage with a "0 = fresh, 1 = fully stale" tooltip, and the+ // percentage was wrong twice over. Its zero was one dash shared by a+ // record whose files had not moved and a record naming no files at all,+ // and its red above 0.5 painted three confirmed working rules as+ // expired because the files they cite happened to change. Red is+ // reserved for health bands; this is a count, so it reads as one, in+ // mono like every other machine-produced figure.+ render: (d) => {+ const s = describeRecordStaleness(d);+ return (+ <span+ className={+ s.kind === "moved"+ ? "font-mono text-xs tabular-nums text-[var(--color-text-secondary)]"+ : "font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]"+ }+ title={s.sentence}+ >+ {s.short}+ </span>+ );+ },},];@@ -267,26 +302,18 @@ export function DecisionsTable({className="w-full sm:w-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)]"><option value="all">All sources</option>- <option value="inline_marker">Inline markers</option>- <option value="git_archaeology">Git archaeology</option>- <option value="readme_mining">Docs mining</option>- <option value="cli">Manual</option>+ {sourceOptions.map((s) => (+ <option key={s} value={s}>+ {sourceLabel(s)}+ </option>+ ))}</select>- {hasScope && (- <select- value={filters.scope ?? "all"}- onChange={(e) =>- onFiltersChange({ ...filters, scope: e.target.value as DecisionScopeFilter })- }- aria-label="Filter by scope"- className="w-full sm:w-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)]"- >- <option value="all">All scopes</option>- <option value="file">File</option>- <option value="module">Module</option>- <option value="cross-module">Cross-module</option>- </select>- )}+ {/* The scope control is gone with the scope column. It steered an axis+ that is `cross-module` on three quarters of a live index, and with+ the column no longer drawn a reader who used it would watch rows+ disappear for a reason nothing on screen explains. The prop and the+ filtering below it are kept, so a host still passing `scope` gets+ the same rows it did before. */}</div><ResponsiveTablediff --git a/packages/ui/src/decisions/index.ts b/packages/ui/src/decisions/index.tsindex 470e32981..df5c8745c 100644--- a/packages/ui/src/decisions/index.ts+++ b/packages/ui/src/decisions/index.ts@@ -7,3 +7,5 @@ export * from "./decision-lineage";export * from "./decision-detail-adapter";export * from "./decision-detail";export * from "./decision-governance";+export * from "./decision-staleness";+export * from "./checkout-facts";diff --git a/packages/web/src/app/repos/[id]/decisions/page.tsx b/packages/web/src/app/repos/[id]/decisions/page.tsxindex 0bd70fdf8..78f675696 100644--- a/packages/web/src/app/repos/[id]/decisions/page.tsx+++ b/packages/web/src/app/repos/[id]/decisions/page.tsx@@ -1,20 +1,11 @@import type { Metadata } from "next";-import Link from "next/link";import { notFound } from "next/navigation";import { PageShell } from "@repowise-dev/ui/shared/page-shell";-import { OverviewSection, SectionLink } from "@repowise-dev/ui/overview";+import { OverviewSection } from "@repowise-dev/ui/overview";import { PageLede } from "@repowise-dev/ui/shared/page-lede";-import {- DecisionConflicts,- GovernedFiles,- summarizeGovernance,-} from "@repowise-dev/ui/decisions";-import {- getDecision,- getDecisionCounts,- getDecisionGraph,- listDecisions,-} from "@/lib/api/decisions";+import { CheckoutFacts } from "@repowise-dev/ui/decisions";+import { getDecisionCounts, listDecisions } from "@/lib/api/decisions";+import { listEpisodes } from "@/lib/api/episodes";import { ApiClientError } from "@/lib/api/client";import { DecisionsTableWrapper } from "@/components/decisions/decisions-table-wrapper";@@ -34,16 +25,37 @@ interface Props {* The page used to open with a title and go straight into a filter bar, then* close with a React Flow canvas of the decision graph. Neither said the thing* the data says loudest: most records here are unconfirmed *proposals* mined by- * the indexer, and only a handful are confirmed. That makes this a triage- * queue, not an archive, and the lede now says so.+ * the indexer, and only a handful are confirmed.** Every figure comes from `/decisions/counts`, a grouped COUNT. An earlier cut* counted the rows it had fetched and printed "97 of 100" on a repository* holding several hundred — a count nobody measured, on the surface whose whole* job is to be trusted.*- * The canvas is gone. See `decision-governance.tsx` for what its payload- * actually contained and why two lists beat it.+ * Two sections and a fetch left in the same pass, and the reason for each is+ * the same distribution argument that deleted the canvas before them.+ *+ * **Conflicts** rendered from `decision_edges`, which holds zero rows, and not just on+ * a fresh repository, on every repository, because the detector that wrote+ * them was disabled for retiring 74 records on loose semantic matches and its+ * structural replacement is not built. A section that cannot render is not a+ * section.+ *+ * **Most governed files** ranked files by how many records name them, under a+ * heading that reads like settled governance. On a live index 81% of those+ * links belong to *proposed* records, so it ranked files by unconfirmed+ * guesses and told the reader they were "worth reading before you change one".+ * Scoping it to confirmed records does not rescue it: the top file falls from+ * 42 links to 4 and the top twelve run 4,3,3,3,3,3,3,2,2,2,2,2, which is a+ * proportion bar over noise. The honest version of that number is per-file,+ * and the file page already carries it.+ *+ * Both components stay exported, because the hosted decisions view mounts them, and+ * both fed on `getDecisionGraph`, whose payload is roughly 261 KB of code+ * edges for twelve rows. Dropping it takes the page's whole graph fetch, the+ * follow-up per-conflict title lookups, and a swallowed failure with it: that+ * call intermittently 500s and the page caught it silently, so two sections+ * disappeared with nothing to say they had.*/export default async function DecisionsPage({ params }: Props) {const { id: repoId } = await params;@@ -71,42 +83,22 @@ export default async function DecisionsPage({ params }: Props) {include_proposed: true,}).catch(() => undefined);- // Aggregated here, not in the browser: the graph payload runs to thousands of- // code edges and only a dozen rows of it survive to the page.- const graph = await getDecisionGraph(repoId).catch(() => undefined);-- // Conflict endpoints routinely sit outside the graph's own node payload — on- // a live index every one of them did — so titles come from the rows we- // already have, and anything still unnamed is fetched by id. Conflicts are- // rare, so this stays a handful of requests.- const titles = new Map(decisions.map((d) => [d.id, d.title]));- const unresolved = [- ...new Set(- summarizeGovernance(graph, { titles })- .conflicts.flatMap((c) => [- ...(c.aTitle ? [] : [c.aId]),- ...(c.bTitle ? [] : [c.bId]),- ]),- ),- ];- if (unresolved.length > 0) {- const fetched = await Promise.all(- unresolved.map((id) =>- getDecision(repoId, id).then(- (d) => [id, d.title] as const,- () => null,- ),- ),- );- for (const row of fetched) if (row) titles.set(row[0], row[1]);- }-- const { conflicts, governedFiles, governedFileTotal } = summarizeGovernance(- graph,- { topFiles: 12, titles },- );- // A pair still missing a title is dropped rather than shown as a hash.- const namedConflicts = conflicts.filter((c) => c.aTitle && c.bTitle);+ // Facts about the checkout, which is the structural tier of the episode+ // store. Five rows on this repository and none of them need history, a key+ // or a transcript, so this is the one section that says something on a+ // repository indexed an hour ago.+ //+ // The git tier is deliberately not fetched. It is 289 rows of one fix commit+ // each against 301 `fix:`-typed commits in the same window, and Commits is+ // two items up the nav, so a list of it here is that page with a filter on+ // it. A failure and a cold start are different: `available: false` is a 200+ // meaning this repository never derived episodes and gets copy saying what+ // will fill the section, whereas a throw means we do not know and the+ // section does not render at all.+ const facts = await listEpisodes(repoId, {+ tier: "structural",+ limit: 50,+ }).catch(() => undefined);// With counts we can state a measured total; without them we report only// what this page actually loaded, and say so. Never a number nobody counted.@@ -115,7 +107,7 @@ export default async function DecisionsPage({ params }: Props) {counts?.proposed ?? decisions.filter((d) => d.status === "proposed").length;const active =counts?.active ?? decisions.filter((d) => d.status === "active").length;- const queue = proposed > 0;+ const empty = total === 0;const denominator =total !== undefined? `of ${total.toLocaleString()} recorded`@@ -123,87 +115,93 @@ export default async function DecisionsPage({ params }: Props) {return (<PageShell- title="Architectural decisions"- description="Why the codebase is built the way it is — constraints, tradeoffs, and the alternatives that were rejected."+ title="Decisions"+ description="What this codebase has settled on and what is true of the checkout you are standing in: the constraints, the tradeoffs, and the facts that catch people out.">+ {/* The headline used to be the size of the review queue, so the largest+ number on the page pointed at the work nobody had done rather than at+ what the repository actually stands behind. The confirmed count leads+ now; the queue keeps its sentence, because 87 unconfirmed proposals+ are worth knowing about, just not worth 52px.++ The count is the measured `active` total and is not de-duplicated. A+ live index carries near-identical pairs, two spellings of one fix+ landing as two confirmed records, and collapsing them here would need+ a title-similarity threshold tuned on one repository sitting in a+ page component, where a wrong merge hides a record a human confirmed.+ That belongs to supersession, which is structural and not yet built.+ Until then the number is honest about what it counts and the pairs+ stay visible in the table, where they can be deprecated. */}<PageLede- label={queue ? "Awaiting review" : "Active decisions"}- value={(queue ? proposed : active).toLocaleString()}+ label="Confirmed"+ value={active.toLocaleString()}unit={denominator}layout="beside">- {queue ? (+ {empty || active === 0 ? (<><p>- {proposed.toLocaleString()}{" "}- {total !== undefined- ? `of ${total.toLocaleString()} records are`- : `of the first ${decisions.length.toLocaleString()} records are`}{" "}- proposals mined from commits, comments and docs that nobody has- confirmed yet, against {active.toLocaleString()} marked active.- Until one is confirmed it is a guess about your codebase, not a- rule for it — so this page is a queue before it is an archive.+ Decisions land here as the indexer mines them from pull requests,+ commit messages, code comments and your own sessions, and as you+ record them with <code>repowise decision add</code>. Each one+ keeps the quote it was drawn from and the files it governs.</p>+ {proposed > 0 && (+ <p>+ {proposed.toLocaleString()} proposal+ {proposed === 1 ? " is" : "s are"} waiting below. Confirming one+ takes a click and changes no code; it marks the record as+ something the team stands behind, which is what makes it worth+ quoting back to an agent later.+ </p>+ )}+ </>+ ) : (+ <><p>- Confirming takes a click and changes no code. It marks the record- as something your team stands behind, which is what makes it worth+ {active.toLocaleString()} record+ {active === 1 ? " is" : "s are"} confirmed: somebody read{" "}+ {active === 1 ? "it" : "them"} and marked{" "}+ {active === 1 ? "it" : "them"} as something the team stands+ behind, which is what makes {active === 1 ? "it" : "them"} worthquoting back to an agent later.</p>+ {proposed > 0 && (+ <p>+ {proposed.toLocaleString()} more are proposals the indexer mined+ and nobody has confirmed yet. Until one is confirmed it is a+ guess about your codebase rather than a rule for it. Filter by+ status below to work through them; confirming or dismissing one+ takes a click and changes no code.+ </p>+ )}</>- ) : (- <p>- {active.toLocaleString()}{" "}- {total !== undefined ? `of ${total.toLocaleString()} ` : ""}- decisions are confirmed as current, with nothing waiting on review.- New proposals appear here as the indexer mines them from commits,- comments and docs.- </p>)}</PageLede>- {namedConflicts.length > 0 && (+ {facts && (<OverviewSection- title="Conflicts"- description={`${namedConflicts.length} pair${- namedConflicts.length === 1 ? "" : "s"- } of decisions appear to contradict each other. Confirming one and deprecating the other resolves the pair.`}+ title="About this checkout"+ description="Facts about the working tree rather than claims anybody made about it, derived at index time with no model call and no history. These are the ones that trip up a newcomer, human or agent.">- <DecisionConflicts- conflicts={namedConflicts}- decisionHref={(id) => `/repos/${repoId}/decisions/${id}`}- LinkComponent={Link}+ <CheckoutFacts+ facts={facts.episodes}+ available={facts.available}+ total={facts.total}/></OverviewSection>)}- <OverviewSection- title="All decisions"- description="Confirmed rules first, then the proposals most likely to be real. Filter by status to work the queue, or by source to see where a record came from."- >- <DecisionsTableWrapper- repoId={repoId}- initialData={decisions}- {...(total !== undefined ? { initialTotal: total } : {})}- pageSize={PAGE_SIZE}- />- </OverviewSection>-- {governedFiles.length > 0 && (+ {!empty && (<OverviewSection- title="Most governed files"- description={`Of ${governedFileTotal.toLocaleString()} files carrying at least one decision, these have the most. Worth reading before you change one.`}- action={- <SectionLink href={`/repos/${repoId}/files`} LinkComponent={Link}>- All files- </SectionLink>- }+ title="All decisions"+ description="Confirmed records first, then the proposals most likely to be real. Filter by status to work the queue, or by source to see where a record came from. The last column is a count, not a score: how many of the files a record names have been committed to since it was recorded, or are no longer tracked.">- <GovernedFiles- files={governedFiles}- fileHref={(path) =>- `/repos/${repoId}/files?path=${encodeURIComponent(path)}`- }- LinkComponent={Link}+ <DecisionsTableWrapper+ repoId={repoId}+ initialData={decisions}+ {...(total !== undefined ? { initialTotal: total } : {})}+ pageSize={PAGE_SIZE}/></OverviewSection>)}